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
update
tilakpatel22af39ccb60f95
diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.pyindex 714dd0806..e9c9ed256 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/agents/finagent_core/registries/fincept_model.py@@ -37,15 +37,15 @@ class FinceptChat(Model):def _make_request(self, messages: List[Message]) -> Dict[str, Any]:"""Send request to Fincept endpoint and return raw response dict."""- formatted_messages = self._format_messages(messages)+ # Fincept endpoint expects a single 'prompt' field, not 'messages'+ prompt = self._messages_to_prompt(messages)headers = {"Content-Type": "application/json"}if self.api_key:headers["X-API-Key"] = self.api_keypayload: Dict[str, Any] = {- "messages": formatted_messages,- "model": self.id,+ "prompt": prompt,}if self.temperature is not None:payload["temperature"] = self.temperature@@ -108,17 +108,29 @@ class FinceptChat(Model):content = self._extract_content(response) if isinstance(response, dict) else (str(response) if response else "")return ModelResponse(content=content, role="assistant")- def _format_messages(self, messages: List[Message]) -> List[Dict[str, str]]:- """Convert agno Messages to simple dicts for the API."""- formatted = []+ def _messages_to_prompt(self, messages: List[Message]) -> str:+ """Convert agno Messages list into a single prompt string for the Fincept API."""+ parts = []for msg in messages:- role = msg.role or "user"content = msg.content or ""if isinstance(content, list):text_parts = [p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text"]content = "\n".join(text_parts) if text_parts else str(content)- formatted.append({"role": role, "content": str(content)})- return formatted+ content = str(content).strip()+ if not content:+ continue++ role = msg.role or "user"+ if role == "system":+ parts.append(f"[System]: {content}")+ elif role == "user":+ parts.append(content)+ elif role == "assistant":+ parts.append(f"[Assistant]: {content}")+ else:+ parts.append(content)++ return "\n\n".join(parts)def _extract_content(self, data: Any) -> str:"""Extract text content from various response formats."""diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.pyindex 765015ac7..1ec8521ce 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/edgar_tools.py@@ -635,6 +635,806 @@ class EdgarToolsWrapper:except Exception as e:return {"error": EdgarError("get_fund_holdings", str(e), traceback.format_exc()).to_dict()}+ # =========================================================================+ # ENHANCED DATA EXTRACTION FOR RELATIONSHIP MAP+ # =========================================================================++ def get_fund_holdings_detailed(self, ticker: str, quarters: int = 2) -> Dict[str, Any]:+ """+ Get detailed institutional holdings for a company using 13F-HR filings.+ Returns real institutional holders with shares, values, and QoQ changes.++ This queries the company's institutional holders by looking at who files+ 13F-HR forms that include this company's stock.++ Falls back to the company's major_holders from yfinance-style data if available.+ """+ try:+ from decimal import Decimal+ company = Company(ticker)++ # Strategy: Get institutional holders from the company object directly+ # edgartools provides institutional_holders on Company objects+ holders_list = []++ # Try to get institutional holders directly+ if hasattr(company, 'institutional_holders'):+ try:+ inst_holders = company.institutional_holders+ if inst_holders is not None and hasattr(inst_holders, '__iter__'):+ for holder in inst_holders:+ holder_data = {}+ if hasattr(holder, 'name'):+ holder_data['name'] = str(holder.name)+ elif hasattr(holder, 'holder'):+ holder_data['name'] = str(holder.holder)+ else:+ holder_data['name'] = str(holder)++ if hasattr(holder, 'shares'):+ holder_data['shares'] = int(holder.shares) if holder.shares else 0+ if hasattr(holder, 'value'):+ val = holder.value+ holder_data['value'] = float(val) if isinstance(val, Decimal) else (val or 0)+ if hasattr(holder, 'percentage'):+ pct = holder.percentage+ holder_data['percentage'] = float(pct) if isinstance(pct, Decimal) else (pct or 0)+ if hasattr(holder, 'date_reported'):+ holder_data['date_reported'] = str(holder.date_reported)++ if holder_data.get('name'):+ holders_list.append(holder_data)+ except Exception:+ pass++ # Strategy 2: Look for 13F-HR filings that mention this company+ # Get the latest SC 13G/A filings for ownership > 5%+ if not holders_list:+ try:+ filings_sc13 = company.get_filings(form="SC 13G")+ for i, filing in enumerate(filings_sc13):+ if i >= 30:+ break+ try:+ holders_list.append({+ 'name': str(filing.company) if hasattr(filing, 'company') else 'Unknown',+ 'filing_date': str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ 'form': 'SC 13G',+ 'shares': 0,+ 'value': 0,+ 'percentage': 5.0, # SC 13G implies > 5%+ 'source': '13G'+ })+ except:+ continue+ except:+ pass++ # Strategy 3: Look at SC 13D filings (activist investors, >5% with intent)+ if len(holders_list) < 5:+ try:+ filings_sc13d = company.get_filings(form="SC 13D")+ for i, filing in enumerate(filings_sc13d):+ if i >= 15:+ break+ try:+ name = str(filing.company) if hasattr(filing, 'company') else 'Unknown'+ # Avoid duplicates+ if not any(h.get('name') == name for h in holders_list):+ holders_list.append({+ 'name': name,+ 'filing_date': str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ 'form': 'SC 13D',+ 'shares': 0,+ 'value': 0,+ 'percentage': 5.0,+ 'source': '13D_activist'+ })+ except:+ continue+ except:+ pass++ # Strategy 4: Parse from most recent DEF 14A (proxy) for beneficial ownership table+ if len(holders_list) < 10:+ try:+ proxy_filings = company.get_filings(form="DEF 14A")+ if proxy_filings and len(proxy_filings) > 0:+ proxy = proxy_filings[0].obj()+ if proxy and hasattr(proxy, 'security_ownership'):+ ownership = proxy.security_ownership+ if ownership is not None and hasattr(ownership, '__iter__'):+ for owner in ownership:+ name = str(owner.name) if hasattr(owner, 'name') else str(owner)+ if not any(h.get('name') == name for h in holders_list):+ holders_list.append({+ 'name': name,+ 'shares': int(owner.shares) if hasattr(owner, 'shares') and owner.shares else 0,+ 'percentage': float(owner.percent) if hasattr(owner, 'percent') and owner.percent else 0,+ 'value': 0,+ 'source': 'proxy_ownership'+ })+ except:+ pass++ # Deduplicate by name+ seen_names = set()+ unique_holders = []+ for h in holders_list:+ name_key = h.get('name', '').lower().strip()+ if name_key and name_key not in seen_names and name_key != 'unknown':+ seen_names.add(name_key)+ unique_holders.append(h)++ return {+ "success": True,+ "data": {+ "holders": unique_holders[:50],+ "total_count": len(unique_holders),+ "source": "edgar_13f_13g_13d_proxy"+ },+ "count": min(len(unique_holders), 50),+ "parameters": {"ticker": ticker, "quarters": quarters}+ }+ except Exception as e:+ return {"error": EdgarError("get_fund_holdings_detailed", str(e), traceback.format_exc()).to_dict()}++ def get_insider_transactions_detailed(self, ticker: str, limit: int = 25) -> Dict[str, Any]:+ """+ Get detailed insider transactions with transaction types, amounts, prices.+ Parses Form 4 filings more deeply for buy/sell/exercise details.+ """+ try:+ from decimal import Decimal+ company = Company(ticker)+ filings = company.get_filings(form="4")++ transactions = []+ insider_summary = {}++ for i, filing in enumerate(filings):+ if i >= limit:+ break++ try:+ form4 = filing.obj()+ if not form4:+ transactions.append({+ "filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ "insider_name": "Unknown",+ "transaction_type": "unknown",+ "shares": 0,+ "price": 0,+ "value": 0,+ })+ continue++ # Extract insider name+ insider_name = None+ if hasattr(form4, 'reporting_owner'):+ insider_name = str(form4.reporting_owner)+ elif hasattr(form4, 'owner'):+ insider_name = str(form4.owner)++ if not insider_name:+ insider_name = "Unknown Insider"++ # Extract insider title/role+ insider_title = ""+ if hasattr(form4, 'is_officer') and form4.is_officer:+ insider_title = str(form4.officer_title) if hasattr(form4, 'officer_title') else "Officer"+ elif hasattr(form4, 'is_director') and form4.is_director:+ insider_title = "Director"+ elif hasattr(form4, 'is_ten_percent_owner') and form4.is_ten_percent_owner:+ insider_title = "10% Owner"++ # Extract non-derivative transactions+ tx_list = []+ if hasattr(form4, 'non_derivative_transactions'):+ nd_tx = form4.non_derivative_transactions+ if nd_tx is not None and hasattr(nd_tx, '__iter__'):+ for tx in nd_tx:+ tx_data = self._parse_form4_transaction(tx, filing)+ tx_data['insider_name'] = insider_name+ tx_data['insider_title'] = insider_title+ tx_data['security_type'] = 'common_stock'+ tx_list.append(tx_data)++ # Extract derivative transactions (options, warrants)+ if hasattr(form4, 'derivative_transactions'):+ d_tx = form4.derivative_transactions+ if d_tx is not None and hasattr(d_tx, '__iter__'):+ for tx in d_tx:+ tx_data = self._parse_form4_transaction(tx, filing)+ tx_data['insider_name'] = insider_name+ tx_data['insider_title'] = insider_title+ tx_data['security_type'] = 'derivative'+ tx_list.append(tx_data)++ # If no transactions parsed from detailed attributes, create a basic entry+ if not tx_list:+ tx_list.append({+ 'filing_date': str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ 'insider_name': insider_name,+ 'insider_title': insider_title,+ 'transaction_type': 'unknown',+ 'shares': 0,+ 'price': 0,+ 'value': 0,+ 'security_type': 'common_stock',+ 'code': '',+ })++ transactions.extend(tx_list)++ # Build insider summary+ if insider_name not in insider_summary:+ insider_summary[insider_name] = {+ 'name': insider_name,+ 'title': insider_title,+ 'total_buys': 0,+ 'total_sells': 0,+ 'total_buy_value': 0,+ 'total_sell_value': 0,+ 'transaction_count': 0,+ 'last_transaction_date': None,+ }++ summary = insider_summary[insider_name]+ for tx in tx_list:+ summary['transaction_count'] += 1+ if tx.get('transaction_type') == 'purchase':+ summary['total_buys'] += tx.get('shares', 0)+ summary['total_buy_value'] += tx.get('value', 0)+ elif tx.get('transaction_type') == 'sale':+ summary['total_sells'] += tx.get('shares', 0)+ summary['total_sell_value'] += tx.get('value', 0)+ if not summary['last_transaction_date']:+ summary['last_transaction_date'] = tx.get('filing_date')++ except Exception:+ transactions.append({+ "filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ "insider_name": "Parse Error",+ "transaction_type": "unknown",+ "shares": 0,+ "price": 0,+ "value": 0,+ })++ # Calculate net buying signal+ total_buy_value = sum(s.get('total_buy_value', 0) for s in insider_summary.values())+ total_sell_value = sum(s.get('total_sell_value', 0) for s in insider_summary.values())++ return {+ "success": True,+ "data": {+ "transactions": transactions[:50],+ "insider_summary": list(insider_summary.values()),+ "net_buying_signal": total_buy_value > total_sell_value,+ "total_buy_value": total_buy_value,+ "total_sell_value": total_sell_value,+ },+ "count": len(transactions),+ "parameters": {"ticker": ticker, "limit": limit}+ }+ except Exception as e:+ return {"error": EdgarError("get_insider_transactions_detailed", str(e), traceback.format_exc()).to_dict()}++ def _parse_form4_transaction(self, tx: Any, filing: Any) -> Dict[str, Any]:+ """Parse a single Form 4 transaction entry"""+ from decimal import Decimal++ shares = 0+ price = 0.0+ tx_type = 'unknown'+ code = ''++ # Get shares+ if hasattr(tx, 'shares'):+ s = tx.shares+ shares = int(float(s)) if s else 0+ elif hasattr(tx, 'amount'):+ s = tx.amount+ shares = int(float(s)) if s else 0++ # Get price+ if hasattr(tx, 'price_per_share'):+ p = tx.price_per_share+ price = float(p) if isinstance(p, (int, float, Decimal)) and p else 0.0+ elif hasattr(tx, 'price'):+ p = tx.price+ price = float(p) if isinstance(p, (int, float, Decimal)) and p else 0.0++ # Get transaction code (A=acquisition, D=disposition, M=exercise, etc.)+ if hasattr(tx, 'transaction_code'):+ code = str(tx.transaction_code) if tx.transaction_code else ''+ elif hasattr(tx, 'code'):+ code = str(tx.code) if tx.code else ''++ # Determine transaction type from code+ code_upper = code.upper()+ if code_upper in ('P', 'A'):+ tx_type = 'purchase'+ elif code_upper in ('S', 'D', 'F'):+ tx_type = 'sale'+ elif code_upper in ('M', 'C'):+ tx_type = 'option_exercise'+ elif code_upper == 'G':+ tx_type = 'gift'+ elif code_upper in ('J', 'K'):+ tx_type = 'other'++ # Get acquisition/disposition flag as fallback+ if tx_type == 'unknown' and hasattr(tx, 'acquired_disposed'):+ ad = str(tx.acquired_disposed).upper() if tx.acquired_disposed else ''+ if ad == 'A':+ tx_type = 'purchase'+ elif ad == 'D':+ tx_type = 'sale'++ value = abs(shares * price)++ return {+ 'filing_date': str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ 'transaction_type': tx_type,+ 'code': code,+ 'shares': abs(shares),+ 'price': round(price, 2),+ 'value': round(value, 2),+ }++ def get_corporate_events_categorized(self, ticker: str, limit: int = 30) -> Dict[str, Any]:+ """+ Get comprehensive corporate events from 8-K filings, categorized by type.+ Parses item numbers to categorize: M&A, management, earnings, debt, etc.+ Does NOT call filing.obj() to avoid timeouts - uses filing metadata only.+ """+ try:+ company = Company(ticker)+ filings = company.get_filings(form="8-K")++ categorized = {+ 'acquisitions': [],+ 'management_changes': [],+ 'material_agreements': [],+ 'financial_results': [],+ 'debt_events': [],+ 'asset_events': [],+ 'governance': [],+ 'other': [],+ }++ all_events = []++ for i, filing in enumerate(filings):+ if i >= limit:+ break++ try:+ event_data = {+ "filing_date": str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ "form": "8-K",+ "filing_url": filing.filing_url if hasattr(filing, 'filing_url') else None,+ "accession_number": filing.accession_number,+ "description": "",+ "category": "other",+ "items": [],+ }++ # Get items from filing metadata (fast, no obj() call)+ items = []+ if hasattr(filing, 'items') and filing.items:+ items = filing.items if isinstance(filing.items, list) else [filing.items]++ # Get description+ desc = ""+ if hasattr(filing, 'primary_doc_description') and filing.primary_doc_description:+ desc = str(filing.primary_doc_description)+ elif hasattr(filing, 'description') and filing.description:+ desc = str(filing.description)++ event_data["items"] = items+ event_data["description"] = desc if desc else (items[0] if items else "8-K Filing")++ # Categorize by 8-K item number+ items_str = ' '.join(str(it) for it in items).lower()+ desc_lower = desc.lower()+ combined = items_str + ' ' + desc_lower++ if any(x in combined for x in ['2.01', 'acquisition', 'disposition', 'merger', 'acquired']):+ event_data["category"] = "acquisition"+ categorized['acquisitions'].append(event_data)+ elif any(x in combined for x in ['5.02', 'officer', 'director', 'departure', 'appointment']):+ event_data["category"] = "management"+ categorized['management_changes'].append(event_data)+ elif any(x in combined for x in ['1.01', 'material definitive', 'agreement', 'contract']):+ event_data["category"] = "material_agreement"+ categorized['material_agreements'].append(event_data)+ elif any(x in combined for x in ['2.02', 'results of operations', 'financial condition', 'earnings']):+ event_data["category"] = "financial_results"+ categorized['financial_results'].append(event_data)+ elif any(x in combined for x in ['2.03', '2.04', 'obligation', 'off-balance', 'credit', 'debt', 'loan']):+ event_data["category"] = "debt"+ categorized['debt_events'].append(event_data)+ elif any(x in combined for x in ['2.05', '2.06', 'impairment', 'asset', 'exit', 'disposal']):+ event_data["category"] = "asset"+ categorized['asset_events'].append(event_data)+ elif any(x in combined for x in ['5.03', '5.07', 'bylaw', 'amendment', 'governance', 'shareholder']):+ event_data["category"] = "governance"+ categorized['governance'].append(event_data)+ else:+ event_data["category"] = "other"+ categorized['other'].append(event_data)++ all_events.append(event_data)++ except:+ continue++ return {+ "success": True,+ "data": {+ "all_events": all_events,+ "categorized": {k: v[:10] for k, v in categorized.items()}, # Top 10 per category+ "summary": {k: len(v) for k, v in categorized.items()},+ },+ "count": len(all_events),+ "parameters": {"ticker": ticker, "limit": limit}+ }+ except Exception as e:+ return {"error": EdgarError("get_corporate_events_categorized", str(e), traceback.format_exc()).to_dict()}++ def extract_supply_chain(self, ticker: str) -> Dict[str, Any]:+ """+ Extract supply chain relationships from 10-K filings.+ Parses Item 1 (Business) for customer/supplier mentions.+ Uses regex patterns to find revenue concentration disclosures.+ """+ try:+ import re+ company = Company(ticker)+ filings_10k = company.get_filings(form="10-K")++ if not filings_10k or len(filings_10k) == 0:+ return {+ "success": True,+ "data": {"customers": [], "suppliers": [], "partners": []},+ "parameters": {"ticker": ticker}+ }++ # Get the latest 10-K text (with timeout protection)+ import threading+ text_result = [None]++ def fetch_text():+ try:+ filing = filings_10k[0]+ obj = filing.obj()+ if obj:+ # Try to get specific sections+ if hasattr(obj, 'text'):+ text_result[0] = obj.text()[:50000] # Limit to 50K chars+ elif hasattr(obj, 'full_text'):+ text_result[0] = obj.full_text[:50000]+ except:+ pass++ thread = threading.Thread(target=fetch_text)+ thread.daemon = True+ thread.start()+ thread.join(timeout=20) # 20 second timeout++ text = text_result[0]+ if not text:+ return {+ "success": True,+ "data": {"customers": [], "suppliers": [], "partners": [], "note": "Could not extract 10-K text"},+ "parameters": {"ticker": ticker}+ }++ customers = []+ suppliers = []+ partners = []++ # Pattern 1: "X accounted for Y% of (our|total) revenue"+ revenue_pattern = r'([A-Z][A-Za-z\s&.,]+?)(?:\s+(?:Inc\.|Corp\.|Co\.|LLC|Ltd\.?|Corporation|Company))?\s+(?:accounted for|represented|comprised)\s+(?:approximately\s+)?(\d+(?:\.\d+)?)\s*%\s+of\s+(?:our\s+|total\s+)?(?:revenue|net revenue|sales|net sales)'+ for match in re.finditer(revenue_pattern, text[:30000]):+ name = match.group(1).strip()+ pct = float(match.group(2))+ if pct >= 5 and len(name) > 2 and len(name) < 50:+ customers.append({+ 'name': name,+ 'percentage_of_revenue': pct,+ 'relationship': 'customer',+ 'source': 'revenue_disclosure'+ })++ # Pattern 2: "customers include X, Y, and Z"+ customer_list_pattern = r'(?:major|significant|key|primary|largest)\s+customers?\s+(?:include|are|consist of)\s+([^.]{10,200})'+ for match in re.finditer(customer_list_pattern, text[:30000], re.IGNORECASE):+ names_text = match.group(1)+ # Split by commas and "and"+ names = re.split(r',\s*|\s+and\s+', names_text)+ for name in names[:5]:+ clean_name = name.strip().strip('"\'')+ if len(clean_name) > 2 and len(clean_name) < 50 and not clean_name[0].islower():+ if not any(c.get('name') == clean_name for c in customers):+ customers.append({+ 'name': clean_name,+ 'relationship': 'customer',+ 'source': 'customer_list'+ })++ # Pattern 3: Supplier/vendor mentions+ supplier_pattern = r'(?:major|primary|key|significant|sole|single)\s+(?:supplier|vendor|source|manufacturer)s?\s+(?:include|are|is)\s+([^.]{10,200})'+ for match in re.finditer(supplier_pattern, text[:30000], re.IGNORECASE):+ names_text = match.group(1)+ names = re.split(r',\s*|\s+and\s+', names_text)+ for name in names[:5]:+ clean_name = name.strip().strip('"\'')+ if len(clean_name) > 2 and len(clean_name) < 50 and not clean_name[0].islower():+ suppliers.append({+ 'name': clean_name,+ 'relationship': 'supplier',+ 'source': 'supplier_mention'+ })++ # Pattern 4: Strategic partnerships/alliances+ partner_pattern = r'(?:strategic|key|significant)\s+(?:partnership|alliance|collaboration|agreement|joint venture)\s+with\s+([A-Z][A-Za-z\s&.,]+?)(?:\s+(?:Inc\.|Corp\.|Co\.|LLC|Ltd\.?))?\s*[,.]'+ for match in re.finditer(partner_pattern, text[:30000]):+ name = match.group(1).strip()+ if len(name) > 2 and len(name) < 50:+ partners.append({+ 'name': name,+ 'relationship': 'partner',+ 'source': 'partnership_mention'+ })++ # Pattern 5: "we purchase/procure/source X from Y"+ procure_pattern = r'(?:we|the company)\s+(?:purchase|procure|source|obtain|buy)s?\s+[^.]{5,100}?\s+from\s+([A-Z][A-Za-z\s&.,]+?)(?:\s+(?:Inc\.|Corp\.|Co\.|LLC|Ltd\.?))?\s*[,.]'+ for match in re.finditer(procure_pattern, text[:30000], re.IGNORECASE):+ name = match.group(1).strip()+ if len(name) > 2 and len(name) < 50:+ if not any(s.get('name') == name for s in suppliers):+ suppliers.append({+ 'name': name,+ 'relationship': 'supplier',+ 'source': 'procurement_mention'+ })++ return {+ "success": True,+ "data": {+ "customers": customers[:15],+ "suppliers": suppliers[:15],+ "partners": partners[:10],+ "total_relationships": len(customers) + len(suppliers) + len(partners),+ },+ "parameters": {"ticker": ticker}+ }+ except Exception as e:+ return {"error": EdgarError("extract_supply_chain", str(e), traceback.format_exc()).to_dict()}++ def get_segment_financials(self, ticker: str) -> Dict[str, Any]:+ """+ Extract segment-level financials (geographic, product line, business unit).+ Uses XBRL facts/dimensional data when available, falls back to 10-K parsing.+ """+ try:+ company = Company(ticker)+ segments = {+ 'geographic': [],+ 'business_units': [],+ 'products': [],+ }++ # Try to get facts for dimensional data+ if hasattr(company, 'facts'):+ try:+ facts = company.facts+ if facts:+ # Look for segment revenue data in XBRL+ # Common concepts: Revenues, RevenueFromContractWithCustomerExcludingAssessedTax+ for concept_name in ['Revenues', 'RevenueFromContractWithCustomerExcludingAssessedTax', 'SalesRevenueNet']:+ try:+ if hasattr(facts, 'query'):+ # Query with geographic dimension+ geo_data = facts.query(+ concept=f'us-gaap:{concept_name}',+ dimensions={'us-gaap:StatementGeographicalAxis': '*'}+ )+ if geo_data is not None and hasattr(geo_data, '__iter__'):+ for item in geo_data:+ segments['geographic'].append({+ 'name': str(item.member) if hasattr(item, 'member') else str(item),+ 'value': float(item.value) if hasattr(item, 'value') else 0,+ 'period': str(item.period) if hasattr(item, 'period') else None,+ })++ # Query with business segment dimension+ seg_data = facts.query(+ concept=f'us-gaap:{concept_name}',+ dimensions={'us-gaap:StatementBusinessSegmentsAxis': '*'}+ )+ if seg_data is not None and hasattr(seg_data, '__iter__'):+ for item in seg_data:+ segments['business_units'].append({+ 'name': str(item.member) if hasattr(item, 'member') else str(item),+ 'value': float(item.value) if hasattr(item, 'value') else 0,+ 'period': str(item.period) if hasattr(item, 'period') else None,+ })++ if segments['geographic'] or segments['business_units']:+ break+ except:+ continue+ except:+ pass++ # Fallback: Parse segment info from latest 10-K if XBRL didn't work+ if not segments['geographic'] and not segments['business_units']:+ try:+ import re+ import threading++ filings_10k = company.get_filings(form="10-K")+ if filings_10k and len(filings_10k) > 0:+ text_result = [None]++ def fetch():+ try:+ obj = filings_10k[0].obj()+ if obj and hasattr(obj, 'text'):+ text_result[0] = obj.text()[:60000]+ except:+ pass++ thread = threading.Thread(target=fetch)+ thread.daemon = True+ thread.start()+ thread.join(timeout=15)++ text = text_result[0]+ if text:+ # Look for segment revenue tables+ # Pattern: "Region/Segment: $X,XXX million" or "Region: XX%"+ seg_pattern = r'(?:United States|Americas|North America|Europe|Asia|China|Japan|Other|International|Rest of World|EMEA|APAC|Latin America)[^$\d]*[\$]?\s*(\d[\d,.]+)\s*(?:million|billion)?'+ for match in re.finditer(seg_pattern, text[:30000], re.IGNORECASE):+ region = match.group(0).split(':')[0].strip() if ':' in match.group(0) else match.group(0)[:30].strip()+ value_str = match.group(1).replace(',', '')+ try:+ value = float(value_str)+ if value > 0:+ segments['geographic'].append({+ 'name': region,+ 'value': value,+ })+ except:+ pass+ except:+ pass++ # Deduplicate+ for key in segments:+ seen = set()+ unique = []+ for item in segments[key]:+ name = item.get('name', '')+ if name and name not in seen:+ seen.add(name)+ unique.append(item)+ segments[key] = unique[:10]++ return {+ "success": True,+ "data": segments,+ "total_segments": sum(len(v) for v in segments.values()),+ "parameters": {"ticker": ticker}+ }+ except Exception as e:+ return {"error": EdgarError("get_segment_financials", str(e), traceback.format_exc()).to_dict()}++ def extract_debt_holders(self, ticker: str) -> Dict[str, Any]:+ """+ Extract major debt holders and credit facilities from 8-K and 10-K filings.+ Identifies creditors, credit agreements, and major bondholders.+ """+ try:+ import re+ company = Company(ticker)++ creditors = []+ credit_facilities = []++ # Strategy 1: Get 8-K filings related to credit agreements (Item 1.01)+ try:+ filings_8k = company.get_filings(form="8-K")+ for i, filing in enumerate(filings_8k):+ if i >= 30:+ break+ try:+ desc = ""+ if hasattr(filing, 'primary_doc_description') and filing.primary_doc_description:+ desc = str(filing.primary_doc_description).lower()++ items_str = ""+ if hasattr(filing, 'items') and filing.items:+ items_str = str(filing.items).lower()++ combined = desc + ' ' + items_str++ if any(kw in combined for kw in ['credit', 'loan', 'debt', 'indenture', 'note', 'bond', 'facility']):+ credit_facilities.append({+ 'filing_date': str(filing.filing_date) if hasattr(filing, 'filing_date') else None,+ 'description': desc[:200] if desc else 'Credit/Debt Related Filing',+ 'type': 'credit_agreement' if 'credit' in combined else ('bond' if 'bond' in combined or 'note' in combined else 'debt'),+ 'url': filing.filing_url if hasattr(filing, 'filing_url') else None,+ })+ except:+ continue+ except:+ pass++ # Strategy 2: Parse 10-K for major creditors in debt footnotes+ try:+ import threading+ filings_10k = company.get_filings(form="10-K")+ if filings_10k and len(filings_10k) > 0:+ text_result = [None]++ def fetch():+ try:+ obj = filings_10k[0].obj()+ if obj and hasattr(obj, 'text'):+ text_result[0] = obj.text()[:80000]+ except:+ pass++ thread = threading.Thread(target=fetch)+ thread.daemon = True+ thread.start()+ thread.join(timeout=15)++ text = text_result[0]+ if text:+ # Look for credit facility mentions with bank names+ bank_pattern = r'(?:revolving\s+)?(?:credit\s+)?(?:facility|agreement|line)\s+(?:with|from|provided by|led by|arranged by)\s+([A-Z][A-Za-z\s&.,]+?)(?:\s*(?:,|\.|as\s+))'+ for match in re.finditer(bank_pattern, text[:40000]):+ name = match.group(1).strip()+ if len(name) > 3 and len(name) < 60:+ creditors.append({+ 'name': name,+ 'type': 'bank_lender',+ 'source': '10k_footnote'+ })++ # Look for bond trustee mentions+ trustee_pattern = r'(?:trustee|indenture\s+trustee)\s+(?:is|shall be|was)\s+([A-Z][A-Za-z\s&.,]+?)(?:\s*[,.])'+ for match in re.finditer(trustee_pattern, text[:40000]):+ name = match.group(1).strip()+ if len(name) > 3 and len(name) < 60:+ if not any(c.get('name') == name for c in creditors):+ creditors.append({+ 'name': name,+ 'type': 'bond_trustee',+ 'source': '10k_footnote'+ })+ except:+ pass++ return {+ "success": True,+ "data": {+ "creditors": creditors[:10],+ "credit_facilities": credit_facilities[:10],+ "total_debt_relationships": len(creditors) + len(credit_facilities),+ },+ "parameters": {"ticker": ticker}+ }+ except Exception as e:+ return {"error": EdgarError("extract_debt_holders", str(e), traceback.format_exc()).to_dict()}+# =========================================================================# PROXY STATEMENTS & EXECUTIVE COMPENSATION# =========================================================================@@ -1223,12 +2023,43 @@ def main(args=None):limit = int(args[2]) if len(args) > 2 else 20result = wrapper.get_insider_transactions(ticker, limit)+ elif command == "get_insider_transactions_detailed":+ ticker = args[1] if len(args) > 1 else None+ limit = int(args[2]) if len(args) > 2 else 25+ result = wrapper.get_insider_transactions_detailed(ticker, limit)+# Fund holdingselif command == "get_fund_holdings":ticker = args[1] if len(args) > 1 else Nonelimit = int(args[2]) if len(args) > 2 else 5result = wrapper.get_fund_holdings(ticker, limit)+ elif command == "get_fund_holdings_detailed":+ ticker = args[1] if len(args) > 1 else None+ quarters = int(args[2]) if len(args) > 2 else 2+ result = wrapper.get_fund_holdings_detailed(ticker, quarters)++ # Supply chain extraction+ elif command == "extract_supply_chain":+ ticker = args[1] if len(args) > 1 else None+ result = wrapper.extract_supply_chain(ticker)++ # Segment financials+ elif command == "get_segment_financials":+ ticker = args[1] if len(args) > 1 else None+ result = wrapper.get_segment_financials(ticker)++ # Debt holders+ elif command == "extract_debt_holders":+ ticker = args[1] if len(args) > 1 else None+ result = wrapper.extract_debt_holders(ticker)++ # Categorized corporate events+ elif command == "get_corporate_events_categorized":+ ticker = args[1] if len(args) > 1 else None+ limit = int(args[2]) if len(args) > 2 else 30+ result = wrapper.get_corporate_events_categorized(ticker, limit)+# Proxy statementelif command == "get_proxy_statement":if len(args) < 2:@@ -1278,14 +2109,17 @@ def main(args=None):result = {"error": EdgarError(command, f"Unknown command: {command}").to_dict()}# Return JSON for PyO3, print for subprocess- output = json.dumps(result, indent=2)+ # IMPORTANT: Do NOT use indent=2 here. The Rust subprocess fallback parser+ # looks for the last line starting with '{' or '[' to extract JSON.+ # Pretty-printed JSON breaks this parsing logic.+ output = json.dumps(result)print(output)return outputexcept Exception as e:error_output = json.dumps({"error": EdgarError(command, str(e), traceback.format_exc()).to_dict()- }, indent=2)+ })print(error_output)return error_outputdiff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.pyindex fca72eb10..bfb68200c 100644--- a/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/yfinance_data.py@@ -443,7 +443,10 @@ def main(args=None):result = {"error": f"Unknown command: {command}"}# Return JSON for worker pool, print for subprocess/CLI- output = json.dumps(result, indent=2)+ # IMPORTANT: Do NOT use indent=2 here. The Rust subprocess parser+ # looks for the last line starting with '{' or '[' to extract JSON.+ # Pretty-printed JSON puts '{' alone on the first line, breaking parsing.+ output = json.dumps(result)print(output)return outputdiff --git a/fincept-terminal-desktop/src-tauri/src/utils/python.rs b/fincept-terminal-desktop/src-tauri/src/utils/python.rsindex d83cf73ac..83e5f1efe 100644--- a/fincept-terminal-desktop/src-tauri/src/utils/python.rs+++ b/fincept-terminal-desktop/src-tauri/src/utils/python.rs@@ -313,22 +313,35 @@ pub fn execute_python_subprocess(.map_err(|e| format!("Failed to parse output: {}", e))?;// Extract JSON from output - handles case where logging/warnings leak to stdout- // Look for the last line that starts with '{' or '[' (our JSON result)- let json_line = raw_output- .lines()- .rev()- .find(|line| {- let trimmed = line.trim();- trimmed.starts_with('{') || trimmed.starts_with('[')- });-- match json_line {- Some(json) => Ok(json.to_string()),- None => {- // If no JSON found, return raw output (might be plain text result)- Ok(raw_output.trim().to_string())+ // Strategy: Find the last complete JSON object/array in the output.+ // 1. Try the last line first (compact JSON on one line - most common case)+ // 2. If that doesn't start with { or [, search backwards for the JSON start+ // 3. If found on a non-last line, collect from that line to the end (multi-line JSON)+ let lines: Vec<&str> = raw_output.lines().collect();++ // First try: check if last line is compact JSON (single-line output)+ if let Some(last) = lines.last() {+ let trimmed = last.trim();+ if trimmed.starts_with('{') || trimmed.starts_with('[') {+ return Ok(trimmed.to_string());}}++ // Second try: find the first line from the start that begins JSON, then take everything from there+ // This handles multi-line (pretty-printed) JSON output+ if let Some(json_start_idx) = lines.iter().position(|line| {+ let trimmed = line.trim();+ trimmed.starts_with('{') || trimmed.starts_with('[')+ }) {+ let json_text: String = lines[json_start_idx..].join("\n");+ let trimmed = json_text.trim();+ if !trimmed.is_empty() {+ return Ok(trimmed.to_string());+ }+ }++ // Fallback: return raw output+ Ok(raw_output.trim().to_string())} else {let stderr = String::from_utf8_lossy(&output.stderr);let stdout = String::from_utf8_lossy(&output.stdout);diff --git a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs b/fincept-terminal-desktop/src-tauri/src/worker_pool.rsindex d5cf1c040..76331488f 100644--- a/fincept-terminal-desktop/src-tauri/src/worker_pool.rs+++ b/fincept-terminal-desktop/src-tauri/src/worker_pool.rs@@ -466,13 +466,29 @@ async fn execute_python_subprocess(if output.status.success() {let stdout = String::from_utf8_lossy(&output.stdout).to_string();- // Try to extract just the JSON part (last line typically)+ // Extract JSON from output - handles both compact and multi-line JSONlet lines: Vec<&str> = stdout.lines().collect();++ // Try last line first (compact JSON)if let Some(last_line) = lines.last() {- if last_line.starts_with('{') || last_line.starts_with('[') {- return Ok(last_line.to_string());+ let trimmed = last_line.trim();+ if trimmed.starts_with('{') || trimmed.starts_with('[') {+ return Ok(trimmed.to_string());}}++ // Try finding JSON start from beginning (multi-line JSON)+ if let Some(json_start_idx) = lines.iter().position(|line| {+ let trimmed = line.trim();+ trimmed.starts_with('{') || trimmed.starts_with('[')+ }) {+ let json_text: String = lines[json_start_idx..].join("\n");+ let trimmed = json_text.trim();+ if !trimmed.is_empty() {+ return Ok(trimmed.to_string());+ }+ }+Ok(stdout)} else {let stderr = String::from_utf8_lossy(&output.stderr);diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 658deab3f..184d7d7ca 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -33,7 +33,7 @@ import SupportTicketTab from '@/components/tabs/support-ticket';import RecordedContextsManager from '@/components/common/RecordedContextsManager';import { HeaderSupportButtons } from '@/components/common/HeaderSupportButtons';import AgentConfigTab from '@/components/tabs/agent-config';-import RelationshipMapTab from '@/components/tabs/relationship-map-v2/RelationshipMapTabV2';+import RelationshipMapTab from '@/components/tabs/relationship-map/RelationshipMapTab';import MonitoringTab from '@/components/tabs/monitoring';import { useTranslation } from 'react-i18next';import { WorkspaceProvider } from '@/contexts/WorkspaceContext';diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/RelationshipMapTabV2.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/RelationshipMapTabV2.tsxdeleted file mode 100644index 737063952..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/RelationshipMapTabV2.tsx+++ /dev/null@@ -1,511 +0,0 @@-// Relationship Map V2 - Comprehensive Corporate Intelligence Visualization-// Multi-layer graph with valuation signals, ownership, peers, events--import React, { useState, useMemo, useCallback } from 'react';-import ReactFlow, {- Background,- Controls,- MiniMap,- type Node,- type Edge,- type NodeTypes,- type EdgeTypes,-} from 'reactflow';-import 'reactflow/dist/style.css';--import type {- GraphNodeData,- GraphEdgeData,- LayoutMode,- FilterState,- RelationshipMapDataV2,-} from './types';-import { DEFAULT_FILTERS } from './types';-import { useRelationshipData } from './hooks/useRelationshipData';-import { applyLayout, selectOptimalLayout } from './utils/layoutAlgorithms';--// Node components-import CompanyNode from './components/nodes/CompanyNode';-import PeerNode from './components/nodes/PeerNode';-import InstitutionalHolderNode from './components/nodes/InstitutionalHolderNode';-import FundFamilyNode from './components/nodes/FundFamilyNode';-import InsiderNode from './components/nodes/InsiderNode';-import EventNode from './components/nodes/EventNode';-import MetricsClusterNode from './components/nodes/MetricsClusterNode';-import SupplyChainNode from './components/nodes/SupplyChainNode';--// Edge components-import OwnershipEdge from './components/edges/OwnershipEdge';--// Panels & Controls-import HeaderBar from './components/controls/HeaderBar';-import FilterPanel from './components/panels/FilterPanel';-import DetailPanel from './components/panels/DetailPanel';-import LegendPanel from './components/controls/LegendPanel';--// ============================================================================-// NODE & EDGE TYPE REGISTRATIONS-// ============================================================================--const nodeTypes: NodeTypes = {- company: CompanyNode,- peer: PeerNode,- institutional: InstitutionalHolderNode,- fund_family: FundFamilyNode,- insider: InsiderNode,- event: EventNode,- metrics: MetricsClusterNode,- supply_chain: SupplyChainNode,-};--const edgeTypes: EdgeTypes = {- ownership: OwnershipEdge,- peer: OwnershipEdge,- event: OwnershipEdge,- internal: OwnershipEdge,- supply_chain: OwnershipEdge,-};--// ============================================================================-// GRAPH BUILDER-// ============================================================================--function buildGraph(- data: RelationshipMapDataV2,- filters: FilterState-): { nodes: Node<GraphNodeData>[]; edges: Edge<GraphEdgeData>[] } {- const nodes: Node<GraphNodeData>[] = [];- const edges: Edge<GraphEdgeData>[] = [];- const companyId = `company-${data.company.ticker}`;-- // 1. Company Node (always shown)- nodes.push({- id: companyId,- type: 'company',- position: { x: 0, y: 0 },- data: {- id: companyId,- category: 'company',- label: data.company.ticker,- company: data.company,- valuation: data.companyValuation,- executives: data.executives,- },- });-- // 2. Peer Nodes- if (filters.showPeers) {- for (const peer of data.peers) {- // Apply peer filter- const peerVal = data.peerValuations.get(peer.ticker);- if (filters.peerFilter === 'undervalued' && peerVal?.action !== 'BUY') continue;- if (filters.peerFilter === 'overvalued' && peerVal?.action !== 'SELL') continue;-- const peerId = `peer-${peer.ticker}`;- nodes.push({- id: peerId,- type: 'peer',- position: { x: 0, y: 0 },- data: {- id: peerId,- category: 'peer',- label: peer.ticker,- peer,- peerValuation: peerVal,- },- });- edges.push({- id: `edge-${companyId}-${peerId}`,- source: companyId,- target: peerId,- type: 'peer',- data: { category: 'peer', label: 'peer' },- });- }- }-- // 3. Institutional Holders- if (filters.showInstitutional) {- for (const holder of data.institutionalHolders) {- if (holder.percentage < filters.minOwnership) continue;- const holderId = `inst-${holder.name.replace(/\s+/g, '-').slice(0, 20)}`;- nodes.push({- id: holderId,- type: 'institutional',- position: { x: 0, y: 0 },- data: {- id: holderId,- category: 'institutional',- label: holder.name,- holder,- },- });- edges.push({- id: `edge-${holderId}-${companyId}`,- source: holderId,- target: companyId,- type: 'ownership',- data: { category: 'ownership', percentage: holder.percentage, shares: holder.shares, value: holder.value },- });- }- }-- // 4. Fund Families- if (filters.showFundFamilies) {- for (const family of data.fundFamilies) {- if (family.total_percentage < filters.minOwnership) continue;- const familyId = `fund-${family.name.replace(/\s+/g, '-').slice(0, 20)}`;- nodes.push({- id: familyId,- type: 'fund_family',- position: { x: 0, y: 0 },- data: {- id: familyId,- category: 'fund_family',- label: family.name,- fundFamily: family,- },- });- edges.push({- id: `edge-${familyId}-${companyId}`,- source: familyId,- target: companyId,- type: 'ownership',- data: { category: 'ownership', percentage: family.total_percentage, value: family.total_value },- });- }- }-- // 5. Insider Holders- if (filters.showInsiders) {- for (const insider of data.insiderHolders) {- const insiderId = `insider-${insider.name.replace(/\s+/g, '-').slice(0, 20)}`;- nodes.push({- id: insiderId,- type: 'insider',- position: { x: 0, y: 0 },- data: {- id: insiderId,- category: 'insider',- label: insider.name,- insider,- transactions: data.insiderTransactions.filter(t =>- t.name.toLowerCase().includes(insider.name.split(' ')[0].toLowerCase())- ),- },- });- edges.push({- id: `edge-${insiderId}-${companyId}`,- source: insiderId,- target: companyId,- type: 'internal',- data: { category: 'internal' },- });- }- }-- // 6. Corporate Events- if (filters.showEvents) {- for (let i = 0; i < data.corporateEvents.length; i++) {- const event = data.corporateEvents[i];- const eventId = `event-${i}`;- nodes.push({- id: eventId,- type: 'event',- position: { x: 0, y: 0 },- data: {- id: eventId,- category: 'event',- label: event.description || event.form,- event,- },- });- edges.push({- id: `edge-${companyId}-${eventId}`,- source: companyId,- target: eventId,- type: 'event',- data: { category: 'event' },- });- }- }-- // 7. Metrics Clusters- if (filters.showMetrics) {- // Financials cluster- if (data.company.revenue > 0) {- const finId = 'metrics-financials';- nodes.push({- id: finId,- type: 'metrics',- position: { x: 0, y: 0 },- data: {- id: finId,- category: 'metrics',- label: 'Financials',- metricsType: 'financials',- metrics: {- revenue: data.company.revenue,- gross_profit: data.company.gross_profit,- ebitda: data.company.ebitda,- free_cashflow: data.company.free_cashflow,- profit_margins: data.company.profit_margins,- operating_margins: data.company.operating_margins,- },- },- });- edges.push({- id: `edge-${companyId}-${finId}`,- source: companyId,- target: finId,- type: 'internal',- data: { category: 'internal' },- });- }-- // Valuation cluster- if (data.company.pe_ratio > 0 || data.company.price_to_book > 0) {- const valId = 'metrics-valuation';- nodes.push({- id: valId,- type: 'metrics',- position: { x: 0, y: 0 },- data: {- id: valId,- category: 'metrics',- label: 'Valuation',- metricsType: 'valuation',- metrics: {- pe_ratio: data.company.pe_ratio,- forward_pe: data.company.forward_pe,- price_to_book: data.company.price_to_book,- peg_ratio: data.company.peg_ratio,- enterprise_value: data.company.enterprise_value,- ev_to_revenue: data.company.enterprise_to_revenue,- },- },- });- edges.push({- id: `edge-${companyId}-${valId}`,- source: companyId,- target: valId,- type: 'internal',- data: { category: 'internal' },- });- }-- // Balance Sheet cluster- if (data.company.total_cash > 0 || data.company.total_debt > 0) {- const bsId = 'metrics-balance';- nodes.push({- id: bsId,- type: 'metrics',- position: { x: 0, y: 0 },- data: {- id: bsId,- category: 'metrics',- label: 'Balance Sheet',- metricsType: 'balance_sheet',- metrics: {- total_cash: data.company.total_cash,- total_debt: data.company.total_debt,- shares_outstanding: data.company.shares_outstanding,- float_shares: data.company.float_shares,- },- },- });- edges.push({- id: `edge-${companyId}-${bsId}`,- source: companyId,- target: bsId,- type: 'internal',- data: { category: 'internal' },- });- }- }-- return { nodes, edges };-}--// ============================================================================-// MAIN COMPONENT-// ============================================================================--const RelationshipMapTabV2: React.FC = () => {- const { data, loading, error, phase, fetchData } = useRelationshipData();- const [layoutMode, setLayoutMode] = useState<LayoutMode>('layered');- const [filters, setFilters] = useState<FilterState>(DEFAULT_FILTERS);- const [showFilters, setShowFilters] = useState(false);- const [selectedNode, setSelectedNode] = useState<GraphNodeData | null>(null);-- // Build graph from data- const { nodes: rawNodes, edges } = useMemo(() => {- if (!data) return { nodes: [], edges: [] };- return buildGraph(data, filters);- }, [data, filters]);-- // Apply layout- const nodes = useMemo(() => {- if (rawNodes.length === 0) return [];-- const effectiveMode = layoutMode === 'custom'- ? selectOptimalLayout(rawNodes)- : layoutMode;-- return applyLayout(rawNodes, effectiveMode, {- mode: effectiveMode,- centerX: 600,- centerY: 500,- width: 2000,- height: 1600,- padding: 100,- });- }, [rawNodes, layoutMode]);-- // Node counts for filter panel- const nodeCounts: Record<string, number> = useMemo(() => {- if (!data) return { peer: 0, institutional: 0, fund_family: 0, insider: 0, event: 0, metrics: 0 };- return {- peer: data.peers.length,- institutional: data.institutionalHolders.length,- fund_family: data.fundFamilies.length,- insider: data.insiderHolders.length,- event: data.corporateEvents.length,- metrics: 3,- };- }, [data]);-- const handleSearch = useCallback((ticker: string) => {- setSelectedNode(null);- fetchData(ticker);- }, [fetchData]);-- const handleNodeClick = useCallback((_: React.MouseEvent, node: Node<GraphNodeData>) => {- setSelectedNode(node.data);- }, []);-- const handlePaneClick = useCallback(() => {- setSelectedNode(null);- }, []);-- return (- <div style={{ width: '100%', height: '100%', position: 'relative', background: 'var(--ft-color-background)' }}>- {/* Header Bar */}- <HeaderBar- onSearch={handleSearch}- layoutMode={layoutMode}- onLayoutChange={setLayoutMode}- onToggleFilters={() => setShowFilters(!showFilters)}- showFilters={showFilters}- dataQuality={data?.dataQuality}- loading={loading}- progress={phase.progress}- message={phase.message}- />-- {/* Filter Panel */}- {showFilters && (- <FilterPanel- filters={filters}- onChange={setFilters}- nodeCounts={nodeCounts}- />- )}-- {/* Main Graph */}- <div style={{ position: 'absolute', top: '48px', left: 0, right: 0, bottom: 0 }}>- {nodes.length > 0 ? (- <ReactFlow- nodes={nodes}- edges={edges}- nodeTypes={nodeTypes}- edgeTypes={edgeTypes}- onNodeClick={handleNodeClick}- onPaneClick={handlePaneClick}- fitView- fitViewOptions={{ padding: 0.2, maxZoom: 1.5 }}- minZoom={0.1}- maxZoom={3}- defaultEdgeOptions={{ animated: false }}- proOptions={{ hideAttribution: true }}- >- <Background color="rgba(120,120,120,0.1)" gap={40} />- <Controls- position="bottom-right"- style={{ background: 'rgba(10,10,10,0.8)', border: '1px solid rgba(120,120,120,0.3)', borderRadius: '4px' }}- />- <MiniMap- nodeColor={(node: any) => {- const category = node?.data?.category;- if (category === 'company') return '#FFA500';- if (category === 'peer') return '#6496FA';- if (category === 'institutional') return '#00C800';- if (category === 'fund_family') return '#C864FF';- if (category === 'insider') return '#00FFFF';- if (category === 'event') return '#FF0000';- return '#787878';- }}- style={{ background: 'rgba(10,10,10,0.8)', border: '1px solid rgba(120,120,120,0.3)' }}- position="bottom-left"- pannable- zoomable- />- </ReactFlow>- ) : !loading ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '100%',- color: 'var(--ft-color-text-muted)',- gap: '12px',- }}>- <div style={{ fontSize: '40px', opacity: 0.3 }}>🌐</div>- <div style={{ fontSize: '14px', fontWeight: 'bold', color: 'var(--ft-color-text)' }}>- Corporate Intelligence Map- </div>- <div style={{ fontSize: '11px', maxWidth: '400px', textAlign: 'center', lineHeight: 1.6 }}>- Enter a ticker symbol to visualize the complete corporate relationship network:- ownership structure, peer valuations, insider activity, and corporate events.- </div>- <div style={{ fontSize: '10px', color: 'var(--ft-color-primary)', marginTop: '8px' }}>- Try: AAPL, MSFT, TSLA, NVDA, GOOGL- </div>- </div>- ) : null}-- {/* Error Display */}- {error && (- <div style={{- position: 'absolute',- top: '50%',- left: '50%',- transform: 'translate(-50%, -50%)',- background: 'rgba(255,0,0,0.1)',- border: '1px solid var(--ft-color-alert)',- borderRadius: '6px',- padding: '16px 24px',- color: 'var(--ft-color-alert)',- fontSize: '12px',- textAlign: 'center',- }}>- <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>Error Loading Data</div>- <div style={{ fontSize: '10px', color: 'var(--ft-color-text-muted)' }}>{error}</div>- </div>- )}- </div>-- {/* Detail Panel */}- <DetailPanel- nodeData={selectedNode}- onClose={() => setSelectedNode(null)}- />-- {/* Legend */}- <LegendPanel visible={nodes.length > 0 && !selectedNode} />- </div>- );-};--export default RelationshipMapTabV2;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/controls/HeaderBar.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/controls/HeaderBar.tsxdeleted file mode 100644index 2b9383fed..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/controls/HeaderBar.tsx+++ /dev/null@@ -1,168 +0,0 @@-import React, { useState, useCallback } from 'react';-import type { LayoutMode, DataQualityScore } from '../../types';--interface HeaderBarProps {- onSearch: (ticker: string) => void;- layoutMode: LayoutMode;- onLayoutChange: (mode: LayoutMode) => void;- onToggleFilters: () => void;- showFilters: boolean;- dataQuality?: DataQualityScore;- loading: boolean;- progress: number;- message: string;-}--const LAYOUT_OPTIONS: { value: LayoutMode; label: string }[] = [- { value: 'layered', label: 'Layered' },- { value: 'force', label: 'Force' },- { value: 'circular', label: 'Circular' },- { value: 'hierarchical', label: 'Tree' },- { value: 'radial', label: 'Radial' },-];--const HeaderBar: React.FC<HeaderBarProps> = ({- onSearch,- layoutMode,- onLayoutChange,- onToggleFilters,- showFilters,- dataQuality,- loading,- progress,- message,-}) => {- const [searchInput, setSearchInput] = useState('');-- const handleSubmit = useCallback((e: React.FormEvent) => {- e.preventDefault();- if (searchInput.trim()) {- onSearch(searchInput.trim().toUpperCase());- }- }, [searchInput, onSearch]);-- return (- <div style={{- position: 'absolute',- top: 0,- left: 0,- right: 0,- height: '48px',- background: 'rgba(10, 10, 10, 0.9)',- borderBottom: '1px solid var(--ft-color-text-muted)',- display: 'flex',- alignItems: 'center',- padding: '0 12px',- gap: '12px',- zIndex: 60,- backdropFilter: 'blur(4px)',- }}>- {/* Search */}- <form onSubmit={handleSubmit} style={{ display: 'flex', gap: '6px' }}>- <input- type="text"- value={searchInput}- onChange={(e) => setSearchInput(e.target.value.toUpperCase())}- placeholder="Enter Ticker (e.g., AAPL)"- style={{- background: 'rgba(255,255,255,0.05)',- border: '1px solid var(--ft-color-text-muted)',- borderRadius: '4px',- padding: '6px 10px',- color: 'var(--ft-color-text)',- fontSize: '12px',- width: '180px',- outline: 'none',- }}- />- <button- type="submit"- disabled={loading}- style={{- background: 'var(--ft-color-primary)',- border: 'none',- borderRadius: '4px',- padding: '6px 12px',- color: '#000',- fontSize: '11px',- fontWeight: 'bold',- cursor: loading ? 'not-allowed' : 'pointer',- opacity: loading ? 0.6 : 1,- }}- >- {loading ? 'Loading...' : 'Map'}- </button>- </form>-- {/* Loading Progress */}- {loading && (- <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '8px' }}>- <div style={{ flex: 1, height: '4px', background: 'rgba(255,255,255,0.1)', borderRadius: '2px', overflow: 'hidden' }}>- <div style={{- width: `${progress}%`,- height: '100%',- background: 'var(--ft-color-primary)',- borderRadius: '2px',- transition: 'width 0.3s ease',- }} />- </div>- <span style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', whiteSpace: 'nowrap' }}>{message}</span>- </div>- )}-- {/* Data Quality */}- {!loading && dataQuality && (- <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginLeft: 'auto' }}>- <div style={{- width: '8px', height: '8px', borderRadius: '50%',- background: dataQuality.overall >= 70 ? 'var(--ft-color-success)' : dataQuality.overall >= 40 ? 'var(--ft-color-warning)' : 'var(--ft-color-alert)',- }} />- <span style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)' }}>- Quality: {dataQuality.overall}%- </span>- </div>- )}-- {/* Layout Selector */}- {!loading && (- <div style={{ display: 'flex', gap: '2px', marginLeft: loading ? '0' : 'auto' }}>- {LAYOUT_OPTIONS.map(opt => (- <button- key={opt.value}- onClick={() => onLayoutChange(opt.value)}- style={{- fontSize: '9px',- padding: '4px 8px',- borderRadius: '3px',- border: `1px solid ${layoutMode === opt.value ? 'var(--ft-color-primary)' : 'rgba(120,120,120,0.3)'}`,- background: layoutMode === opt.value ? 'rgba(255,165,0,0.15)' : 'transparent',- color: layoutMode === opt.value ? 'var(--ft-color-primary)' : 'var(--ft-color-text-muted)',- cursor: 'pointer',- }}- >- {opt.label}- </button>- ))}- </div>- )}-- {/* Filter Toggle */}- <button- onClick={onToggleFilters}- style={{- fontSize: '10px',- padding: '5px 10px',- borderRadius: '4px',- border: `1px solid ${showFilters ? 'var(--ft-color-primary)' : 'var(--ft-color-text-muted)'}`,- background: showFilters ? 'rgba(255,165,0,0.15)' : 'transparent',- color: showFilters ? 'var(--ft-color-primary)' : 'var(--ft-color-text-muted)',- cursor: 'pointer',- }}- >- Filters- </button>- </div>- );-};--export default HeaderBar;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/controls/LegendPanel.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/controls/LegendPanel.tsxdeleted file mode 100644index fbbeb49ce..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/controls/LegendPanel.tsx+++ /dev/null@@ -1,80 +0,0 @@-import React from 'react';-import { NODE_COLORS, SIGNAL_COLORS } from '../../constants';--interface LegendPanelProps {- visible: boolean;-}--const LegendPanel: React.FC<LegendPanelProps> = ({ visible }) => {- if (!visible) return null;-- return (- <div style={{- position: 'absolute',- left: '12px',- bottom: '12px',- background: 'rgba(10, 10, 10, 0.9)',- border: '1px solid rgba(120,120,120,0.3)',- borderRadius: '6px',- padding: '10px 14px',- zIndex: 50,- maxWidth: '220px',- }}>- <div style={{ fontSize: '10px', fontWeight: 'bold', color: 'var(--ft-color-primary)', marginBottom: '8px' }}>Legend</div>-- {/* Node Types */}- <div style={{ marginBottom: '8px' }}>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)', marginBottom: '4px' }}>Node Types</div>- <LegendItem color={NODE_COLORS.company.border} label="Company (Center)" />- <LegendItem color={NODE_COLORS.peer.border} label="Peer Company" />- <LegendItem color={NODE_COLORS.institutional.border} label="Institutional Holder" />- <LegendItem color={NODE_COLORS.fund_family.border} label="Fund Family" />- <LegendItem color={NODE_COLORS.insider.border} label="Insider" />- <LegendItem color={NODE_COLORS.event.border} label="Corporate Event" />- <LegendItem color={NODE_COLORS.metrics.border} label="Metrics Cluster" />- </div>-- {/* Valuation Signals */}- <div style={{ marginBottom: '8px' }}>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)', marginBottom: '4px' }}>Valuation Signals</div>- <LegendItem color={SIGNAL_COLORS.BUY.text} label="BUY (Undervalued)" />- <LegendItem color={SIGNAL_COLORS.HOLD.text} label="HOLD (Fair Value)" />- <LegendItem color={SIGNAL_COLORS.SELL.text} label="SELL (Overvalued)" />- </div>-- {/* Edge Types */}- <div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)', marginBottom: '4px' }}>Edge Types</div>- <LegendEdge color="var(--ft-color-success)" label="Ownership" dashed={false} />- <LegendEdge color="var(--ft-color-info)" label="Peer Comparison" dashed={true} />- <LegendEdge color="var(--ft-color-alert)" label="Event Link" dashed={true} />- <LegendEdge color="var(--ft-color-text-muted)" label="Internal" dashed={false} />- </div>- </div>- );-};--function LegendItem({ color, label }: { color: string; label: string }) {- return (- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '3px' }}>- <div style={{ width: '10px', height: '10px', borderRadius: '3px', border: `2px solid ${color}`, background: 'rgba(0,0,0,0.3)' }} />- <span style={{ fontSize: '9px', color: 'var(--ft-color-text)' }}>{label}</span>- </div>- );-}--function LegendEdge({ color, label, dashed }: { color: string; label: string; dashed: boolean }) {- return (- <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '3px' }}>- <svg width="16" height="6">- <line x1="0" y1="3" x2="16" y2="3"- stroke={color} strokeWidth="2"- strokeDasharray={dashed ? '3 2' : undefined}- />- </svg>- <span style={{ fontSize: '9px', color: 'var(--ft-color-text)' }}>{label}</span>- </div>- );-}--export default LegendPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/edges/OwnershipEdge.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/edges/OwnershipEdge.tsxdeleted file mode 100644index f4b15e150..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/edges/OwnershipEdge.tsx+++ /dev/null@@ -1,105 +0,0 @@-import React from 'react';-import { BaseEdge, getSmoothStepPath, type EdgeProps } from 'reactflow';-import type { GraphEdgeData } from '../../types';--const OwnershipEdge: React.FC<EdgeProps> = ({- id,- sourceX,- sourceY,- targetX,- targetY,- sourcePosition,- targetPosition,- data,- selected,-}) => {- const edgeData = data as GraphEdgeData | undefined;- const percentage = edgeData?.percentage || 0;- const category = edgeData?.category || 'internal';-- // Scale stroke width based on ownership percentage (1-8px for 0-15%)- const strokeWidth = category === 'ownership'- ? Math.max(1, Math.min(8, (percentage / 15) * 8))- : category === 'peer' ? 1.5- : 1;-- // Color based on category- const strokeColor = category === 'ownership' ? 'var(--ft-color-success)'- : category === 'peer' ? 'var(--ft-color-info)'- : category === 'event' ? 'var(--ft-color-alert)'- : category === 'supply_chain' ? 'var(--ft-color-warning)'- : 'var(--ft-color-text-muted)';-- const strokeDasharray = category === 'peer' ? '5 5'- : category === 'event' ? '3 3'- : undefined;-- const [edgePath, labelX, labelY] = getSmoothStepPath({- sourceX,- sourceY,- sourcePosition,- targetX,- targetY,- targetPosition,- borderRadius: 20,- });-- return (- <>- <BaseEdge- id={id}- path={edgePath}- style={{- stroke: selected ? '#fff' : strokeColor,- strokeWidth: selected ? strokeWidth + 1 : strokeWidth,- strokeDasharray,- opacity: selected ? 1 : 0.7,- }}- />- {/* Edge Label for ownership */}- {category === 'ownership' && percentage > 0 && (- <foreignObject- x={labelX - 25}- y={labelY - 10}- width={50}- height={20}- style={{ pointerEvents: 'none' }}- >- <div style={{- background: 'rgba(0,0,0,0.8)',- border: '1px solid rgba(0,200,0,0.4)',- borderRadius: '3px',- padding: '1px 4px',- fontSize: '8px',- color: 'var(--ft-color-success)',- textAlign: 'center',- whiteSpace: 'nowrap',- }}>- {percentage.toFixed(1)}%- </div>- </foreignObject>- )}- {/* Edge Label for peer */}- {category === 'peer' && edgeData?.label && (- <foreignObject- x={labelX - 20}- y={labelY - 8}- width={40}- height={16}- style={{ pointerEvents: 'none' }}- >- <div style={{- fontSize: '7px',- color: 'var(--ft-color-info)',- textAlign: 'center',- opacity: 0.7,- }}>- {edgeData.label}- </div>- </foreignObject>- )}- </>- );-};--export default OwnershipEdge;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/CompanyNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/CompanyNode.tsxdeleted file mode 100644index 6d5b9b8d3..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/CompanyNode.tsx+++ /dev/null@@ -1,139 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';-import { getSignalColor, getSignalLabel } from '../../utils/valuationSignals';--interface CompanyNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const CompanyNode: React.FC<CompanyNodeProps> = ({ data, selected }) => {- const company = data.company;- const valuation = data.valuation;- if (!company) return null;-- const signalColor = valuation ? getSignalColor(valuation.action) : null;- const colors = NODE_COLORS.company;-- const formatNumber = (num: number): string => {- if (num >= 1e12) return `$${(num / 1e12).toFixed(2)}T`;- if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;- if (num >= 1e6) return `$${(num / 1e6).toFixed(1)}M`;- return `$${num.toLocaleString()}`;- };-- const formatPercent = (val: number): string => {- if (Math.abs(val) < 1) return `${(val * 100).toFixed(1)}%`;- return `${val.toFixed(1)}%`;- };-- return (- <div- style={{- background: colors.bg,- border: `2px solid ${selected ? '#fff' : colors.border}`,- borderRadius: '8px',- padding: '16px',- width: '420px',- minHeight: '240px',- position: 'relative',- boxShadow: selected ? '0 0 20px rgba(255,165,0,0.4)' : '0 4px 12px rgba(0,0,0,0.3)',- }}- >- <Handle type="source" position={Position.Right} style={{ background: colors.border }} />- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />- <Handle type="source" position={Position.Bottom} id="bottom" style={{ background: colors.border }} />- <Handle type="target" position={Position.Top} id="top" style={{ background: colors.border }} />-- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>- <div>- <div style={{ fontSize: '18px', fontWeight: 'bold', color: colors.border }}>{company.ticker}</div>- <div style={{ fontSize: '11px', color: 'var(--ft-color-text-muted)', maxWidth: '240px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>- {company.name}- </div>- <div style={{ fontSize: '10px', color: 'var(--ft-color-text-muted)', marginTop: '2px' }}>- {company.sector} | {company.industry}- </div>- </div>- {/* Valuation Badge */}- {valuation && signalColor && (- <div style={{- background: signalColor.bg,- border: `1px solid ${signalColor.border}`,- borderRadius: '4px',- padding: '4px 8px',- textAlign: 'center',- }}>- <div style={{ fontSize: '9px', fontWeight: 'bold', color: signalColor.text }}>- {getSignalLabel(valuation.status)}- </div>- <div style={{ fontSize: '11px', fontWeight: 'bold', color: signalColor.text }}>- {valuation.action}- </div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>- {valuation.confidence} conf.- </div>- </div>- )}- </div>-- {/* Key Metrics Grid */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', marginBottom: '10px' }}>- <MetricBox label="Market Cap" value={formatNumber(company.market_cap)} />- <MetricBox label="Price" value={`$${company.current_price?.toFixed(2) || '0'}`} />- <MetricBox label="P/E" value={company.pe_ratio ? company.pe_ratio.toFixed(1) : 'N/A'} />- <MetricBox label="Revenue Growth" value={formatPercent(company.revenue_growth)} positive={company.revenue_growth > 0} />- <MetricBox label="Profit Margin" value={formatPercent(company.profit_margins)} positive={company.profit_margins > 0} />- <MetricBox label="ROE" value={formatPercent(company.roe)} positive={company.roe > 0} />- </div>-- {/* Ownership Bar */}- <div style={{ marginTop: '8px' }}>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', marginBottom: '4px' }}>Ownership Distribution</div>- <div style={{ display: 'flex', height: '8px', borderRadius: '4px', overflow: 'hidden', background: 'rgba(255,255,255,0.05)' }}>- <div style={{ width: `${company.insider_percent}%`, background: 'var(--ft-color-accent)', minWidth: company.insider_percent > 0 ? '2px' : '0' }} />- <div style={{ width: `${company.institutional_percent}%`, background: 'var(--ft-color-success)', minWidth: company.institutional_percent > 0 ? '2px' : '0' }} />- <div style={{ flex: 1, background: 'rgba(120,120,120,0.3)' }} />- </div>- <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '3px', fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>- <span>Insiders: {company.insider_percent.toFixed(1)}%</span>- <span>Institutional: {company.institutional_percent.toFixed(1)}%</span>- </div>- </div>-- {/* Analyst Recommendation */}- {company.recommendation && company.recommendation !== 'N/A' && (- <div style={{ marginTop: '8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <span style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)' }}>- Analyst: {company.recommendation.toUpperCase()} ({company.analyst_count})- </span>- {company.target_price > 0 && (- <span style={{ fontSize: '9px', color: 'var(--ft-color-info)' }}>- Target: ${company.target_price.toFixed(0)}- </span>- )}- </div>- )}- </div>- );-};--function MetricBox({ label, value, positive }: { label: string; value: string; positive?: boolean }) {- return (- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)', marginBottom: '2px' }}>{label}</div>- <div style={{- fontSize: '11px',- fontWeight: 'bold',- color: positive !== undefined ? (positive ? 'var(--ft-color-success)' : 'var(--ft-color-alert)') : 'var(--ft-color-text)',- }}>- {value}- </div>- </div>- );-}--export default memo(CompanyNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/EventNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/EventNode.tsxdeleted file mode 100644index ea348aa09..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/EventNode.tsx+++ /dev/null@@ -1,74 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';--interface EventNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const categoryIcons: Record<string, string> = {- earnings: 'E',- management: 'M',- merger: 'A',- restructuring: 'R',- governance: 'G',- other: '8K',-};--const categoryLabels: Record<string, string> = {- earnings: 'Earnings',- management: 'Management',- merger: 'M&A',- restructuring: 'Restructuring',- governance: 'Governance',- other: 'Corporate Event',-};--const EventNode: React.FC<EventNodeProps> = ({ data, selected }) => {- const event = data.event;- if (!event) return null;-- const colors = NODE_COLORS.event;- const icon = categoryIcons[event.category] || '8K';- const categoryLabel = categoryLabels[event.category] || 'Event';-- return (- <div- style={{- background: colors.bg,- border: `1.5px solid ${selected ? '#fff' : colors.border}`,- borderRadius: '6px',- padding: '8px 12px',- width: '240px',- minHeight: '80px',- position: 'relative',- }}- >- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />-- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>- <div style={{ width: '22px', height: '22px', borderRadius: '4px', background: 'rgba(255,0,0,0.2)', border: `1px solid ${colors.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '8px', fontWeight: 'bold', color: colors.border }}>- {icon}- </div>- <div>- <div style={{ fontSize: '10px', fontWeight: 'bold', color: colors.text }}>{categoryLabel}</div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>{event.filing_date}</div>- </div>- </div>-- <div style={{ fontSize: '9px', color: 'var(--ft-color-text)', maxHeight: '28px', overflow: 'hidden', textOverflow: 'ellipsis', lineHeight: '14px' }}>- {event.description || event.items?.[0] || 'Corporate event'}- </div>-- {event.form && (- <div style={{ marginTop: '4px', fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>- Form: {event.form}- </div>- )}- </div>- );-};--export default memo(EventNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/FundFamilyNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/FundFamilyNode.tsxdeleted file mode 100644index 5e15dfe6d..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/FundFamilyNode.tsx+++ /dev/null@@ -1,77 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';--interface FundFamilyNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const FundFamilyNode: React.FC<FundFamilyNodeProps> = ({ data, selected }) => {- const family = data.fundFamily;- if (!family) return null;-- const colors = NODE_COLORS.fund_family;-- const formatValue = (val: number): string => {- if (val >= 1e9) return `$${(val / 1e9).toFixed(1)}B`;- if (val >= 1e6) return `$${(val / 1e6).toFixed(0)}M`;- return `$${val.toLocaleString()}`;- };-- const trendIcon = family.change_trend === 'increasing' ? '\u2191' :- family.change_trend === 'decreasing' ? '\u2193' : '\u2194';- const trendColor = family.change_trend === 'increasing' ? 'var(--ft-color-success)' :- family.change_trend === 'decreasing' ? 'var(--ft-color-alert)' : 'var(--ft-color-text-muted)';-- return (- <div- style={{- background: colors.bg,- border: `1.5px solid ${selected ? '#fff' : colors.border}`,- borderRadius: '8px',- padding: '12px',- width: '280px',- minHeight: '160px',- position: 'relative',- }}- >- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />- <Handle type="source" position={Position.Right} style={{ background: colors.border }} />-- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>- <div style={{ fontSize: '12px', fontWeight: 'bold', color: colors.border, maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>- {family.name}- </div>- <span style={{ fontSize: '14px', color: trendColor }}>{trendIcon}</span>- </div>-- {/* Aggregate Stats */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '10px' }}>- <div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>Total Ownership</div>- <div style={{ fontSize: '14px', fontWeight: 'bold', color: colors.border }}>{family.total_percentage.toFixed(2)}%</div>- </div>- <div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>Total Value</div>- <div style={{ fontSize: '11px', fontWeight: 'bold', color: 'var(--ft-color-text)' }}>{formatValue(family.total_value)}</div>- </div>- </div>-- {/* Top Funds */}- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)', marginBottom: '4px' }}>- Funds ({family.funds.length})- </div>- {family.funds.slice(0, 3).map((fund, i) => (- <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '9px', color: 'var(--ft-color-text)', marginBottom: '2px', padding: '2px 4px', background: 'rgba(255,255,255,0.03)', borderRadius: '2px' }}>- <span style={{ maxWidth: '160px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fund.name}</span>- <span style={{ color: colors.border }}>{fund.percentage.toFixed(2)}%</span>- </div>- ))}- </div>- );-};--export default memo(FundFamilyNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/InsiderNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/InsiderNode.tsxdeleted file mode 100644index ee9854634..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/InsiderNode.tsx+++ /dev/null@@ -1,71 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';--interface InsiderNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const InsiderNode: React.FC<InsiderNodeProps> = ({ data, selected }) => {- const insider = data.insider;- if (!insider) return null;-- const colors = NODE_COLORS.insider;- const activityColor = insider.last_transaction_type === 'buy' ? 'var(--ft-color-success)' :- insider.last_transaction_type === 'sell' ? 'var(--ft-color-alert)' : 'var(--ft-color-text-muted)';-- return (- <div- style={{- background: colors.bg,- border: `1.5px solid ${selected ? '#fff' : colors.border}`,- borderRadius: '6px',- padding: '10px 14px',- width: '240px',- minHeight: '100px',- position: 'relative',- }}- >- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />-- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>- <div style={{ width: '28px', height: '28px', borderRadius: '50%', background: 'rgba(0,255,255,0.15)', border: `1px solid ${colors.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px' }}>- P- </div>- <div>- <div style={{ fontSize: '11px', fontWeight: 'bold', color: colors.text, maxWidth: '160px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>- {insider.name}- </div>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)' }}>{insider.title}</div>- </div>- </div>-- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- {insider.percentage > 0 && (- <div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>Ownership</div>- <div style={{ fontSize: '11px', fontWeight: 'bold', color: colors.border }}>{insider.percentage.toFixed(2)}%</div>- </div>- )}- {insider.last_transaction_type && (- <div style={{ textAlign: 'right' }}>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>Last Activity</div>- <div style={{ fontSize: '10px', fontWeight: 'bold', color: activityColor }}>- {insider.last_transaction_type.toUpperCase()}- </div>- </div>- )}- </div>-- {insider.last_transaction_date && (- <div style={{ marginTop: '4px', fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>- Last: {insider.last_transaction_date}- </div>- )}- </div>- );-};--export default memo(InsiderNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/InstitutionalHolderNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/InstitutionalHolderNode.tsxdeleted file mode 100644index be55db2c9..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/InstitutionalHolderNode.tsx+++ /dev/null@@ -1,70 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';--interface InstitutionalHolderNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const InstitutionalHolderNode: React.FC<InstitutionalHolderNodeProps> = ({ data, selected }) => {- const holder = data.holder;- if (!holder) return null;-- const colors = NODE_COLORS.institutional;-- const formatValue = (val: number): string => {- if (val >= 1e9) return `$${(val / 1e9).toFixed(1)}B`;- if (val >= 1e6) return `$${(val / 1e6).toFixed(0)}M`;- return `$${val.toLocaleString()}`;- };-- return (- <div- style={{- background: colors.bg,- border: `1.5px solid ${selected ? '#fff' : colors.border}`,- borderRadius: '6px',- padding: '10px 14px',- width: '220px',- minHeight: '90px',- position: 'relative',- }}- >- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />-- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>- <div style={{ width: '24px', height: '24px', borderRadius: '50%', background: 'rgba(0,200,0,0.2)', border: `1px solid ${colors.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '10px', color: colors.border }}>- I- </div>- <div>- <div style={{ fontSize: '11px', fontWeight: 'bold', color: colors.text, maxWidth: '150px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>- {holder.name}- </div>- </div>- </div>-- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>Ownership</div>- <div style={{ fontSize: '13px', fontWeight: 'bold', color: colors.border }}>{holder.percentage.toFixed(2)}%</div>- </div>- {holder.value > 0 && (- <div style={{ textAlign: 'right' }}>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>Value</div>- <div style={{ fontSize: '10px', color: 'var(--ft-color-text)' }}>{formatValue(holder.value)}</div>- </div>- )}- </div>-- {holder.change_percent !== undefined && holder.change_percent !== 0 && (- <div style={{ marginTop: '4px', fontSize: '9px', color: holder.change_percent > 0 ? 'var(--ft-color-success)' : 'var(--ft-color-alert)' }}>- {holder.change_percent > 0 ? '+' : ''}{holder.change_percent.toFixed(1)}% QoQ- </div>- )}- </div>- );-};--export default memo(InstitutionalHolderNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/MetricsClusterNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/MetricsClusterNode.tsxdeleted file mode 100644index 62ee816e2..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/MetricsClusterNode.tsx+++ /dev/null@@ -1,80 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';--interface MetricsClusterNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const typeLabels: Record<string, string> = {- financials: 'Financial Metrics',- valuation: 'Valuation Metrics',- ownership: 'Ownership Structure',- balance_sheet: 'Balance Sheet',-};--const MetricsClusterNode: React.FC<MetricsClusterNodeProps> = ({ data, selected }) => {- const metrics = data.metrics;- const metricsType = data.metricsType || 'financials';- if (!metrics) return null;-- const colors = NODE_COLORS.metrics;- const title = typeLabels[metricsType] || 'Metrics';-- const formatValue = (val: number | string): string => {- if (typeof val === 'string') return val;- if (Math.abs(val) >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;- if (Math.abs(val) >= 1e9) return `$${(val / 1e9).toFixed(2)}B`;- if (Math.abs(val) >= 1e6) return `$${(val / 1e6).toFixed(1)}M`;- if (Math.abs(val) < 1 && val !== 0) return `${(val * 100).toFixed(1)}%`;- return val.toFixed(2);- };-- const entries = Object.entries(metrics).filter(([, v]) => v !== 0 && v !== '' && v !== 'N/A');-- return (- <div- style={{- background: colors.bg,- border: `1.5px solid ${selected ? '#fff' : colors.border}`,- borderRadius: '6px',- padding: '10px 14px',- width: '260px',- minHeight: '140px',- position: 'relative',- }}- >- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />-- <div style={{ fontSize: '11px', fontWeight: 'bold', color: colors.border, marginBottom: '8px', borderBottom: '1px solid rgba(120,120,120,0.3)', paddingBottom: '6px' }}>- {title}- </div>-- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>- {entries.slice(0, 8).map(([key, value]) => (- <div key={key} style={{ padding: '2px 0' }}>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)', textTransform: 'capitalize' }}>- {key.replace(/_/g, ' ')}- </div>- <div style={{- fontSize: '10px', fontWeight: 'bold',- color: typeof value === 'number' && value < 0 ? 'var(--ft-color-alert)' : 'var(--ft-color-text)',- }}>- {formatValue(value)}- </div>- </div>- ))}- </div>-- {entries.length > 8 && (- <div style={{ marginTop: '4px', fontSize: '8px', color: 'var(--ft-color-text-muted)', textAlign: 'center' }}>- +{entries.length - 8} more metrics- </div>- )}- </div>- );-};--export default memo(MetricsClusterNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/PeerNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/PeerNode.tsxdeleted file mode 100644index 942e04832..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/PeerNode.tsx+++ /dev/null@@ -1,96 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';-import { getSignalColor, getSignalLabel } from '../../utils/valuationSignals';--interface PeerNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const PeerNode: React.FC<PeerNodeProps> = ({ data, selected }) => {- const peer = data.peer;- const valuation = data.peerValuation;- if (!peer) return null;-- const signalColor = valuation ? getSignalColor(valuation.action) : null;- const colors = NODE_COLORS.peer;-- const formatNumber = (num: number): string => {- if (num >= 1e12) return `$${(num / 1e12).toFixed(1)}T`;- if (num >= 1e9) return `$${(num / 1e9).toFixed(1)}B`;- if (num >= 1e6) return `$${(num / 1e6).toFixed(0)}M`;- return `$${num.toLocaleString()}`;- };-- return (- <div- style={{- background: signalColor ? signalColor.bg : colors.bg,- border: `1.5px solid ${selected ? '#fff' : (signalColor ? signalColor.border : colors.border)}`,- borderRadius: '6px',- padding: '12px',- width: '260px',- minHeight: '140px',- position: 'relative',- }}- >- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />- <Handle type="source" position={Position.Right} style={{ background: colors.border }} />-- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>- <div>- <div style={{ fontSize: '14px', fontWeight: 'bold', color: colors.text }}>{peer.ticker}</div>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', maxWidth: '150px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>- {peer.name}- </div>- </div>- {valuation && signalColor && (- <div style={{- background: 'rgba(0,0,0,0.3)',- border: `1px solid ${signalColor.border}`,- borderRadius: '3px',- padding: '2px 6px',- }}>- <div style={{ fontSize: '8px', fontWeight: 'bold', color: signalColor.text }}>- {valuation.action}- </div>- </div>- )}- </div>-- {/* Metrics */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>- <MiniMetric label="Mkt Cap" value={formatNumber(peer.market_cap)} />- <MiniMetric label="P/E" value={peer.pe_ratio > 0 ? peer.pe_ratio.toFixed(1) : 'N/A'} />- <MiniMetric label="P/B" value={peer.price_to_book > 0 ? peer.price_to_book.toFixed(1) : 'N/A'} />- <MiniMetric label="Growth" value={`${(peer.revenue_growth * 100).toFixed(1)}%`} positive={peer.revenue_growth > 0} />- </div>-- {/* Signal Status */}- {valuation && (- <div style={{ marginTop: '6px', fontSize: '8px', color: 'var(--ft-color-text-muted)', textAlign: 'center' }}>- {getSignalLabel(valuation.status)} | {valuation.confidence}- </div>- )}- </div>- );-};--function MiniMetric({ label, value, positive }: { label: string; value: string; positive?: boolean }) {- return (- <div>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>{label}</div>- <div style={{- fontSize: '10px', fontWeight: 'bold',- color: positive !== undefined ? (positive ? 'var(--ft-color-success)' : 'var(--ft-color-alert)') : 'var(--ft-color-text)',- }}>- {value}- </div>- </div>- );-}--export default memo(PeerNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/SupplyChainNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/SupplyChainNode.tsxdeleted file mode 100644index b61c8e374..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/nodes/SupplyChainNode.tsx+++ /dev/null@@ -1,53 +0,0 @@-import React, { memo } from 'react';-import { Handle, Position } from 'reactflow';-import type { GraphNodeData } from '../../types';-import { NODE_COLORS } from '../../constants';--interface SupplyChainNodeProps {- data: GraphNodeData;- selected?: boolean;-}--const SupplyChainNode: React.FC<SupplyChainNodeProps> = ({ data, selected }) => {- const colors = NODE_COLORS.supply_chain;-- return (- <div- style={{- background: colors.bg,- border: `1.5px solid ${selected ? '#fff' : colors.border}`,- borderRadius: '6px',- padding: '10px 14px',- width: '260px',- minHeight: '100px',- position: 'relative',- }}- >- <Handle type="target" position={Position.Left} style={{ background: colors.border }} />- <Handle type="source" position={Position.Right} style={{ background: colors.border }} />-- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>- <div style={{ width: '22px', height: '22px', borderRadius: '4px', background: 'rgba(255,255,0,0.15)', border: `1px solid ${colors.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '9px', color: colors.border }}>- SC- </div>- <div>- <div style={{ fontSize: '11px', fontWeight: 'bold', color: colors.text }}>{data.label}</div>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)' }}>Supply Chain</div>- </div>- </div>-- {data.metrics && (- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px', marginTop: '4px' }}>- {Object.entries(data.metrics).slice(0, 4).map(([key, val]) => (- <div key={key}>- <div style={{ fontSize: '8px', color: 'var(--ft-color-text-muted)' }}>{key.replace(/_/g, ' ')}</div>- <div style={{ fontSize: '10px', color: colors.text }}>{String(val)}</div>- </div>- ))}- </div>- )}- </div>- );-};--export default memo(SupplyChainNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/panels/DetailPanel.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/panels/DetailPanel.tsxdeleted file mode 100644index bc8fb4535..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/panels/DetailPanel.tsx+++ /dev/null@@ -1,293 +0,0 @@-import React from 'react';-import type { GraphNodeData } from '../../types';-import { getSignalColor, getSignalLabel } from '../../utils/valuationSignals';--interface DetailPanelProps {- nodeData: GraphNodeData | null;- onClose: () => void;-}--const DetailPanel: React.FC<DetailPanelProps> = ({ nodeData, onClose }) => {- if (!nodeData) return null;-- return (- <div style={{- position: 'absolute',- right: 0,- top: 0,- bottom: 0,- width: '380px',- background: 'rgba(10, 10, 10, 0.95)',- borderLeft: '1px solid var(--ft-color-text-muted)',- padding: '16px',- overflowY: 'auto',- zIndex: 100,- backdropFilter: 'blur(8px)',- }}>- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>- <h3 style={{ color: 'var(--ft-color-primary)', fontSize: '14px', margin: 0 }}>{nodeData.label}</h3>- <button- onClick={onClose}- style={{ background: 'none', border: '1px solid var(--ft-color-text-muted)', color: 'var(--ft-color-text)', cursor: 'pointer', padding: '4px 8px', borderRadius: '4px', fontSize: '11px' }}- >- X- </button>- </div>-- {/* Company Details */}- {nodeData.category === 'company' && nodeData.company && (- <CompanyDetails data={nodeData} />- )}-- {/* Peer Details */}- {nodeData.category === 'peer' && nodeData.peer && (- <PeerDetails data={nodeData} />- )}-- {/* Institutional Holder */}- {nodeData.category === 'institutional' && nodeData.holder && (- <HolderDetails data={nodeData} />- )}-- {/* Insider */}- {nodeData.category === 'insider' && nodeData.insider && (- <InsiderDetails data={nodeData} />- )}-- {/* Event */}- {nodeData.category === 'event' && nodeData.event && (- <EventDetails data={nodeData} />- )}-- {/* Metrics */}- {nodeData.category === 'metrics' && nodeData.metrics && (- <MetricsDetails data={nodeData} />- )}- </div>- );-};--function CompanyDetails({ data }: { data: GraphNodeData }) {- const company = data.company!;- const valuation = data.valuation;- const signalColor = valuation ? getSignalColor(valuation.action) : null;-- const fmt = (num: number): string => {- if (num >= 1e12) return `$${(num / 1e12).toFixed(2)}T`;- if (num >= 1e9) return `$${(num / 1e9).toFixed(2)}B`;- if (num >= 1e6) return `$${(num / 1e6).toFixed(1)}M`;- return `$${num.toLocaleString()}`;- };-- return (- <div>- {/* Valuation Signal */}- {valuation && signalColor && (- <div style={{ background: signalColor.bg, border: `1px solid ${signalColor.border}`, borderRadius: '6px', padding: '10px', marginBottom: '12px' }}>- <div style={{ fontSize: '12px', fontWeight: 'bold', color: signalColor.text, marginBottom: '4px' }}>- {getSignalLabel(valuation.status)} - {valuation.action}- </div>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', marginBottom: '6px' }}>- Confidence: {valuation.confidence} | Score: {valuation.score.toFixed(1)}- </div>- {valuation.reasoning.map((r, i) => (- <div key={i} style={{ fontSize: '9px', color: 'var(--ft-color-text)', marginBottom: '2px' }}>- - {r}- </div>- ))}- </div>- )}-- {/* Company Info */}- <SectionTitle title="Company Info" />- <DetailRow label="Sector" value={company.sector} />- <DetailRow label="Industry" value={company.industry} />- <DetailRow label="Exchange" value={company.exchange} />- <DetailRow label="Employees" value={company.employees?.toLocaleString() || 'N/A'} />- {company.website && <DetailRow label="Website" value={company.website} />}-- {/* Valuation */}- <SectionTitle title="Valuation" />- <DetailRow label="Market Cap" value={fmt(company.market_cap)} />- <DetailRow label="P/E Ratio" value={company.pe_ratio ? company.pe_ratio.toFixed(2) : 'N/A'} />- <DetailRow label="Forward P/E" value={company.forward_pe ? company.forward_pe.toFixed(2) : 'N/A'} />- <DetailRow label="P/B" value={company.price_to_book ? company.price_to_book.toFixed(2) : 'N/A'} />- <DetailRow label="PEG" value={company.peg_ratio ? company.peg_ratio.toFixed(2) : 'N/A'} />- <DetailRow label="EV" value={fmt(company.enterprise_value)} />-- {/* Financials */}- <SectionTitle title="Financials" />- <DetailRow label="Revenue" value={fmt(company.revenue)} />- <DetailRow label="Rev Growth" value={`${(company.revenue_growth * 100).toFixed(1)}%`} />- <DetailRow label="Profit Margin" value={`${(company.profit_margins * 100).toFixed(1)}%`} />- <DetailRow label="ROE" value={`${(company.roe * 100).toFixed(1)}%`} />- <DetailRow label="Free Cash Flow" value={fmt(company.free_cashflow)} />-- {/* Ownership */}- <SectionTitle title="Ownership" />- <DetailRow label="Insider %" value={`${company.insider_percent.toFixed(1)}%`} />- <DetailRow label="Institutional %" value={`${company.institutional_percent.toFixed(1)}%`} />- <DetailRow label="Shares Outstanding" value={(company.shares_outstanding / 1e9).toFixed(2) + 'B'} />-- {/* Executives */}- {data.executives && data.executives.length > 0 && (- <>- <SectionTitle title="Executives" />- {data.executives.slice(0, 8).map((exec, i) => (- <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', fontSize: '10px' }}>- <span style={{ color: 'var(--ft-color-text)' }}>{exec.name}</span>- <span style={{ color: 'var(--ft-color-text-muted)' }}>{exec.role}</span>- </div>- ))}- </>- )}-- {/* Description */}- {company.description && company.description !== 'N/A' && (- <>- <SectionTitle title="Description" />- <p style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', lineHeight: 1.4, maxHeight: '80px', overflow: 'hidden' }}>- {company.description.slice(0, 300)}...- </p>- </>- )}- </div>- );-}--function PeerDetails({ data }: { data: GraphNodeData }) {- const peer = data.peer!;- const val = data.peerValuation;- const signalColor = val ? getSignalColor(val.action) : null;-- return (- <div>- {val && signalColor && (- <div style={{ background: signalColor.bg, border: `1px solid ${signalColor.border}`, borderRadius: '4px', padding: '8px', marginBottom: '12px' }}>- <div style={{ fontSize: '11px', fontWeight: 'bold', color: signalColor.text }}>- {getSignalLabel(val.status)} - {val.action}- </div>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', marginTop: '4px' }}>- Confidence: {val.confidence} | Score: {val.score.toFixed(1)}- </div>- </div>- )}- <DetailRow label="Industry" value={peer.industry} />- <DetailRow label="Market Cap" value={`$${(peer.market_cap / 1e9).toFixed(1)}B`} />- <DetailRow label="P/E" value={peer.pe_ratio > 0 ? peer.pe_ratio.toFixed(2) : 'N/A'} />- <DetailRow label="P/B" value={peer.price_to_book > 0 ? peer.price_to_book.toFixed(2) : 'N/A'} />- <DetailRow label="ROE" value={`${(peer.roe * 100).toFixed(1)}%`} />- <DetailRow label="Rev Growth" value={`${(peer.revenue_growth * 100).toFixed(1)}%`} />- <DetailRow label="Margin" value={`${(peer.profit_margins * 100).toFixed(1)}%`} />- </div>- );-}--function HolderDetails({ data }: { data: GraphNodeData }) {- const holder = data.holder!;- return (- <div>- <DetailRow label="Ownership" value={`${holder.percentage.toFixed(2)}%`} />- <DetailRow label="Shares" value={holder.shares.toLocaleString()} />- <DetailRow label="Value" value={`$${(holder.value / 1e6).toFixed(1)}M`} />- {holder.fund_family && <DetailRow label="Fund Family" value={holder.fund_family} />}- </div>- );-}--function InsiderDetails({ data }: { data: GraphNodeData }) {- const insider = data.insider!;- return (- <div>- <DetailRow label="Title" value={insider.title} />- {insider.percentage > 0 && <DetailRow label="Ownership" value={`${insider.percentage.toFixed(2)}%`} />}- {insider.last_transaction_date && <DetailRow label="Last Tx Date" value={insider.last_transaction_date} />}- {insider.last_transaction_type && <DetailRow label="Last Activity" value={insider.last_transaction_type.toUpperCase()} />}-- {data.transactions && data.transactions.length > 0 && (- <>- <SectionTitle title="Recent Transactions" />- {data.transactions.slice(0, 5).map((tx, i) => (- <div key={i} style={{ fontSize: '9px', marginBottom: '4px', padding: '4px', background: 'rgba(255,255,255,0.03)', borderRadius: '3px' }}>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: tx.transaction_type === 'buy' ? 'var(--ft-color-success)' : 'var(--ft-color-alert)' }}>- {tx.transaction_type.toUpperCase()}- </span>- <span style={{ color: 'var(--ft-color-text-muted)' }}>{tx.date}</span>- </div>- </div>- ))}- </>- )}- </div>- );-}--function EventDetails({ data }: { data: GraphNodeData }) {- const event = data.event!;- return (- <div>- <DetailRow label="Form" value={event.form} />- <DetailRow label="Filing Date" value={event.filing_date} />- <DetailRow label="Category" value={event.category} />- {event.description && (- <div style={{ marginTop: '8px', fontSize: '10px', color: 'var(--ft-color-text)', lineHeight: 1.4 }}>- {event.description}- </div>- )}- {event.items.length > 0 && (- <>- <SectionTitle title="Items" />- {event.items.map((item, i) => (- <div key={i} style={{ fontSize: '9px', color: 'var(--ft-color-text)', marginBottom: '3px' }}>- - {item}- </div>- ))}- </>- )}- {event.filing_url && (- <div style={{ marginTop: '8px' }}>- <a- href={event.filing_url}- target="_blank"- rel="noopener noreferrer"- style={{ fontSize: '10px', color: 'var(--ft-color-info)', textDecoration: 'underline' }}- >- View Filing on SEC- </a>- </div>- )}- </div>- );-}--function MetricsDetails({ data }: { data: GraphNodeData }) {- const metrics = data.metrics!;- return (- <div>- {Object.entries(metrics).filter(([, v]) => v !== 0 && v !== '').map(([key, value]) => (- <DetailRow key={key} label={key.replace(/_/g, ' ')} value={String(value)} />- ))}- </div>- );-}--function SectionTitle({ title }: { title: string }) {- return (- <div style={{ fontSize: '10px', fontWeight: 'bold', color: 'var(--ft-color-primary)', marginTop: '12px', marginBottom: '6px', borderBottom: '1px solid rgba(120,120,120,0.2)', paddingBottom: '4px' }}>- {title}- </div>- );-}--function DetailRow({ label, value }: { label: string; value: string }) {- return (- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>- <span style={{ fontSize: '10px', color: 'var(--ft-color-text-muted)' }}>{label}</span>- <span style={{ fontSize: '10px', color: 'var(--ft-color-text)', fontWeight: 500 }}>{value}</span>- </div>- );-}--export default DetailPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/panels/FilterPanel.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/panels/FilterPanel.tsxdeleted file mode 100644index 52e8061c3..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/components/panels/FilterPanel.tsx+++ /dev/null@@ -1,157 +0,0 @@-import React from 'react';-import type { FilterState } from '../../types';--interface FilterPanelProps {- filters: FilterState;- onChange: (filters: FilterState) => void;- nodeCounts: Record<string, number>;-}--const FilterPanel: React.FC<FilterPanelProps> = ({ filters, onChange, nodeCounts }) => {- const toggleFilter = (key: keyof FilterState) => {- onChange({ ...filters, [key]: !filters[key] });- };-- const resetFilters = () => {- onChange({- showInstitutional: true,- showInsiders: true,- showPeers: true,- showEvents: true,- showMetrics: true,- showFundFamilies: true,- minOwnership: 0,- peerFilter: 'all',- eventTypes: [],- });- };-- return (- <div style={{- position: 'absolute',- left: '12px',- top: '60px',- background: 'rgba(10, 10, 10, 0.92)',- border: '1px solid var(--ft-color-text-muted)',- borderRadius: '6px',- padding: '12px',- width: '200px',- zIndex: 50,- backdropFilter: 'blur(4px)',- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' }}>- <span style={{ fontSize: '11px', fontWeight: 'bold', color: 'var(--ft-color-primary)' }}>Filters</span>- <button- onClick={resetFilters}- style={{ fontSize: '9px', color: 'var(--ft-color-info)', background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'underline' }}- >- Reset- </button>- </div>-- {/* Relationship Type Toggles */}- <div style={{ marginBottom: '10px' }}>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', marginBottom: '6px' }}>Relationship Types</div>- <FilterCheckbox- label={`Peers (${nodeCounts.peer || 0})`}- checked={filters.showPeers}- color="var(--ft-color-info)"- onChange={() => toggleFilter('showPeers')}- />- <FilterCheckbox- label={`Institutional (${nodeCounts.institutional || 0})`}- checked={filters.showInstitutional}- color="var(--ft-color-success)"- onChange={() => toggleFilter('showInstitutional')}- />- <FilterCheckbox- label={`Fund Families (${nodeCounts.fund_family || 0})`}- checked={filters.showFundFamilies}- color="var(--ft-color-purple)"- onChange={() => toggleFilter('showFundFamilies')}- />- <FilterCheckbox- label={`Insiders (${nodeCounts.insider || 0})`}- checked={filters.showInsiders}- color="var(--ft-color-accent)"- onChange={() => toggleFilter('showInsiders')}- />- <FilterCheckbox- label={`Events (${nodeCounts.event || 0})`}- checked={filters.showEvents}- color="var(--ft-color-alert)"- onChange={() => toggleFilter('showEvents')}- />- <FilterCheckbox- label={`Metrics (${nodeCounts.metrics || 0})`}- checked={filters.showMetrics}- color="var(--ft-color-text-muted)"- onChange={() => toggleFilter('showMetrics')}- />- </div>-- {/* Min Ownership Slider */}- <div style={{ marginBottom: '10px' }}>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', marginBottom: '4px' }}>- Min Ownership: {filters.minOwnership.toFixed(1)}%- </div>- <input- type="range"- min="0"- max="10"- step="0.5"- value={filters.minOwnership}- onChange={(e) => onChange({ ...filters, minOwnership: parseFloat(e.target.value) })}- style={{ width: '100%', accentColor: 'var(--ft-color-primary)' }}- />- </div>-- {/* Peer Valuation Filter */}- <div>- <div style={{ fontSize: '9px', color: 'var(--ft-color-text-muted)', marginBottom: '4px' }}>Peer Valuation</div>- <div style={{ display: 'flex', gap: '4px' }}>- {(['all', 'undervalued', 'overvalued'] as const).map(opt => (- <button- key={opt}- onClick={() => onChange({ ...filters, peerFilter: opt })}- style={{- fontSize: '8px',- padding: '3px 6px',- borderRadius: '3px',- border: `1px solid ${filters.peerFilter === opt ? 'var(--ft-color-primary)' : 'var(--ft-color-text-muted)'}`,- background: filters.peerFilter === opt ? 'rgba(255,165,0,0.2)' : 'transparent',- color: filters.peerFilter === opt ? 'var(--ft-color-primary)' : 'var(--ft-color-text-muted)',- cursor: 'pointer',- textTransform: 'capitalize',- }}- >- {opt}- </button>- ))}- </div>- </div>- </div>- );-};--function FilterCheckbox({ label, checked, color, onChange }: {- label: string;- checked: boolean;- color: string;- onChange: () => void;-}) {- return (- <label style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px', cursor: 'pointer', fontSize: '10px', color: 'var(--ft-color-text)' }}>- <input- type="checkbox"- checked={checked}- onChange={onChange}- style={{ accentColor: color, width: '12px', height: '12px' }}- />- <span style={{ display: 'inline-block', width: '8px', height: '8px', borderRadius: '2px', background: color, marginRight: '2px' }} />- {label}- </label>- );-}--export default FilterPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/constants.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/constants.tsdeleted file mode 100644index 6c1dd9466..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/constants.ts+++ /dev/null@@ -1,209 +0,0 @@-// Relationship Map V2 - Configuration Constants--// ============================================================================-// TIMEOUT CONFIGURATION-// ============================================================================--export const TIMEOUTS = {- EDGAR_COMPANY: 15000,- EDGAR_FILINGS: 15000,- EDGAR_PROXY: 20000,- EDGAR_EVENTS: 15000,- EDGAR_INSTITUTIONAL: 20000,- EDGAR_INSIDER: 15000,- YFINANCE_INFO: 10000,- YFINANCE_PEERS: 12000,- TOTAL_MAX: 30000,-} as const;--// ============================================================================-// CACHE CONFIGURATION-// ============================================================================--export const CACHE_TTL = {- REALTIME: 5 * 60 * 1000, // 5 minutes - price, quick metrics- DAILY: 24 * 60 * 60 * 1000, // 24 hours - holdings changes- WEEKLY: 7 * 24 * 60 * 60 * 1000, // 7 days - filings, events- QUARTERLY: 30 * 24 * 60 * 60 * 1000, // 30 days - 13F data-} as const;--// ============================================================================-// NODE DIMENSIONS-// ============================================================================--export const NODE_SIZES = {- company: { width: 420, height: 260 },- peer: { width: 260, height: 160 },- institutional: { width: 220, height: 110 },- fund_family: { width: 280, height: 180 },- insider: { width: 240, height: 120 },- event: { width: 240, height: 100 },- supply_chain: { width: 260, height: 130 },- metrics: { width: 260, height: 160 },-} as const;--// ============================================================================-// LAYOUT CONFIGURATION-// ============================================================================--export const LAYOUT_CONFIG = {- // Layered layout ring radii (px from center)- RINGS: {- INSIDERS: 320,- INSTITUTIONAL: 520,- FUND_FAMILIES: 700,- PEERS: 880,- EVENTS: 1050,- METRICS: 400,- },- // Force-directed layout params- FORCE: {- CHARGE_STRENGTH: -800,- LINK_DISTANCE: 250,- CENTER_GRAVITY: 0.05,- ITERATIONS: 300,- COLLISION_RADIUS: 100,- },- // Transition animation- TRANSITION_DURATION: 800,-} as const;--// ============================================================================-// NODE COLORS (using CSS variables for theme compatibility)-// ============================================================================--export const NODE_COLORS = {- company: {- bg: 'rgba(255, 165, 0, 0.15)',- border: 'var(--ft-color-primary)',- text: 'var(--ft-color-text)',- },- peer: {- bg: 'rgba(100, 150, 250, 0.12)',- border: 'var(--ft-color-info)',- text: 'var(--ft-color-text)',- },- institutional: {- bg: 'rgba(0, 200, 0, 0.12)',- border: 'var(--ft-color-success)',- text: 'var(--ft-color-text)',- },- fund_family: {- bg: 'rgba(200, 100, 255, 0.12)',- border: 'var(--ft-color-purple)',- text: 'var(--ft-color-text)',- },- insider: {- bg: 'rgba(0, 255, 255, 0.12)',- border: 'var(--ft-color-accent)',- text: 'var(--ft-color-text)',- },- event: {- bg: 'rgba(255, 0, 0, 0.10)',- border: 'var(--ft-color-alert)',- text: 'var(--ft-color-text)',- },- supply_chain: {- bg: 'rgba(255, 255, 0, 0.10)',- border: 'var(--ft-color-warning)',- text: 'var(--ft-color-text)',- },- metrics: {- bg: 'rgba(120, 120, 120, 0.12)',- border: 'var(--ft-color-text-muted)',- text: 'var(--ft-color-text)',- },-} as const;--// ============================================================================-// VALUATION SIGNAL COLORS-// ============================================================================--export const SIGNAL_COLORS = {- BUY: { bg: 'rgba(0, 200, 0, 0.2)', border: '#00C800', text: '#00FF41' },- HOLD: { bg: 'rgba(255, 255, 0, 0.15)', border: '#FFFF00', text: '#FFFF00' },- SELL: { bg: 'rgba(255, 0, 0, 0.2)', border: '#FF0000', text: '#FF4444' },-} as const;--// ============================================================================-// EDGE STYLES-// ============================================================================--export const EDGE_STYLES = {- ownership: {- stroke: 'var(--ft-color-success)',- strokeWidth: 2,- animated: false,- },- peer: {- stroke: 'var(--ft-color-info)',- strokeWidth: 1.5,- strokeDasharray: '5 5',- animated: false,- },- supply_chain: {- stroke: 'var(--ft-color-warning)',- strokeWidth: 2,- animated: true,- },- event: {- stroke: 'var(--ft-color-alert)',- strokeWidth: 1,- strokeDasharray: '3 3',- animated: false,- },- internal: {- stroke: 'var(--ft-color-text-muted)',- strokeWidth: 1,- animated: false,- },-} as const;--// ============================================================================-// DATA LIMITS-// ============================================================================--export const DATA_LIMITS = {- MAX_INSTITUTIONAL_HOLDERS: 15,- MAX_INSIDER_HOLDERS: 10,- MAX_INSIDER_TRANSACTIONS: 20,- MAX_PEERS: 8,- MAX_EVENTS: 10,- MAX_FILINGS: 15,- MAX_FUND_FAMILIES: 5,-} as const;--// ============================================================================-// FILING FORM DESCRIPTIONS-// ============================================================================--export const FORM_DESCRIPTIONS: Record<string, string> = {- '10-K': 'Annual Report',- '10-Q': 'Quarterly Report',- '8-K': 'Current Event',- '4': 'Insider Trading',- 'DEF 14A': 'Proxy Statement',- '13F-HR': 'Institutional Holdings',- 'S-8': 'Employee Stock Plan',- 'SC 13G': '5%+ Ownership',- 'SC 13G/A': '5%+ Ownership Amendment',- 'DEFA14A': 'Proxy Materials',- '144': 'Insider Sale Notice',- 'S-1': 'IPO Registration',- '424B4': 'Prospectus',-};--// ============================================================================-// EVENT CATEGORIES-// ============================================================================--export const EVENT_CATEGORIES: Record<string, string> = {- '1.01': 'merger',- '1.02': 'restructuring',- '2.01': 'restructuring',- '2.02': 'earnings',- '5.02': 'management',- '5.03': 'governance',- '5.07': 'governance',- '8.01': 'other',-};diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/types.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/types.tsdeleted file mode 100644index a660ae54d..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/types.ts+++ /dev/null@@ -1,314 +0,0 @@-// Relationship Map V2 - Type Definitions-// Multi-layer corporate intelligence visualization--// ============================================================================-// DATA SOURCE TYPES-// ============================================================================--export interface CompanyInfoV2 {- ticker: string;- name: string;- cik: string;- industry: string;- sic: string;- sector: string;- address: string;- exchange: string;- employees: number;- website: string;- description: string;- market_cap: number;- current_price: number;- // Valuation metrics- pe_ratio: number;- forward_pe: number;- price_to_book: number;- price_to_sales: number;- peg_ratio: number;- enterprise_value: number;- enterprise_to_revenue: number;- // Profitability- profit_margins: number;- operating_margins: number;- roe: number;- roa: number;- // Growth- revenue_growth: number;- earnings_growth: number;- // Financials- revenue: number;- gross_profit: number;- ebitda: number;- free_cashflow: number;- total_cash: number;- total_debt: number;- // Ownership- insider_percent: number;- institutional_percent: number;- shares_outstanding: number;- float_shares: number;- // Analyst- recommendation: string;- target_price: number;- analyst_count: number;-}--export interface InstitutionalHolder {- name: string;- shares: number;- value: number;- percentage: number;- change_shares?: number;- change_percent?: number;- filing_date?: string;- fund_family?: string;-}--export interface FundFamily {- name: string;- total_shares: number;- total_value: number;- total_percentage: number;- funds: InstitutionalHolder[];- change_trend: 'increasing' | 'decreasing' | 'stable';-}--export interface InsiderHolder {- name: string;- title: string;- shares: number;- value: number;- percentage: number;- last_transaction_date?: string;- last_transaction_type?: 'buy' | 'sell' | 'option_exercise';-}--export interface InsiderTransaction {- name: string;- title: string;- transaction_type: 'buy' | 'sell' | 'option_exercise';- shares: number;- value: number;- price: number;- date: string;- shares_remaining: number;-}--export interface PeerCompany {- ticker: string;- name: string;- market_cap: number;- pe_ratio: number;- price_to_book: number;- price_to_sales: number;- roe: number;- revenue_growth: number;- profit_margins: number;- current_price: number;- sector: string;- industry: string;-}--export interface ValuationSignal {- status: 'UNDERVALUED' | 'POTENTIALLY_UNDERVALUED' | 'FAIRLY_VALUED' | 'POTENTIALLY_OVERVALUED' | 'OVERVALUED';- action: 'BUY' | 'HOLD' | 'SELL';- confidence: 'HIGH' | 'MEDIUM' | 'LOW';- score: number; // -3 to +3- reasoning: string[];- percentiles: {- pe: number;- pb: number;- ps: number;- roe: number;- growth: number;- };-}--export interface CorporateEventV2 {- filing_date: string;- period_of_report?: string;- form: string;- filing_url?: string;- accession_number: string;- items: string[];- description: string;- category: 'earnings' | 'management' | 'merger' | 'restructuring' | 'governance' | 'other';-}--export interface FilingV2 {- form: string;- filing_date: string;- description: string;- url?: string;- period?: string;-}--export interface Executive {- name: string;- role: string;- compensation?: number;-}--// ============================================================================-// GRAPH NODE TYPES-// ============================================================================--export type NodeCategory =- | 'company'- | 'peer'- | 'institutional'- | 'fund_family'- | 'insider'- | 'event'- | 'supply_chain'- | 'metrics';--export interface GraphNodeData {- id: string;- category: NodeCategory;- label: string;- // Company node data- company?: CompanyInfoV2;- valuation?: ValuationSignal;- executives?: Executive[];- // Peer node data- peer?: PeerCompany;- peerValuation?: ValuationSignal;- // Institutional node data- holder?: InstitutionalHolder;- // Fund family node data- fundFamily?: FundFamily;- // Insider node data- insider?: InsiderHolder;- transactions?: InsiderTransaction[];- // Event node data- event?: CorporateEventV2;- // Metrics cluster data- metrics?: Record<string, number | string>;- metricsType?: 'financials' | 'valuation' | 'ownership' | 'balance_sheet';-}--// ============================================================================-// GRAPH EDGE TYPES-// ============================================================================--export type EdgeCategory =- | 'ownership'- | 'peer'- | 'supply_chain'- | 'event'- | 'internal';--export interface GraphEdgeData {- category: EdgeCategory;- label?: string;- // Ownership edge- percentage?: number;- shares?: number;- value?: number;- change?: number;- // Peer edge- correlation?: number;- // Supply chain edge- relationship?: 'customer' | 'supplier';-}--// ============================================================================-// LAYOUT TYPES-// ============================================================================--export type LayoutMode =- | 'layered'- | 'force'- | 'hierarchical'- | 'circular'- | 'radial'- | 'custom';--export interface LayoutConfig {- mode: LayoutMode;- centerX: number;- centerY: number;- width: number;- height: number;- padding: number;-}--// ============================================================================-// FILTER TYPES-// ============================================================================--export interface FilterState {- showInstitutional: boolean;- showInsiders: boolean;- showPeers: boolean;- showEvents: boolean;- showMetrics: boolean;- showFundFamilies: boolean;- minOwnership: number; // 0-100%- peerFilter: 'all' | 'undervalued' | 'overvalued';- eventTypes: string[];-}--export const DEFAULT_FILTERS: FilterState = {- showInstitutional: true,- showInsiders: true,- showPeers: true,- showEvents: true,- showMetrics: true,- showFundFamilies: true,- minOwnership: 0,- peerFilter: 'all',- eventTypes: [],-};--// ============================================================================-// COMPLETE DATA STRUCTURE-// ============================================================================--export interface RelationshipMapDataV2 {- company: CompanyInfoV2;- executives: Executive[];- institutionalHolders: InstitutionalHolder[];- fundFamilies: FundFamily[];- insiderHolders: InsiderHolder[];- insiderTransactions: InsiderTransaction[];- peers: PeerCompany[];- peerValuations: Map<string, ValuationSignal>;- corporateEvents: CorporateEventV2[];- filings: FilingV2[];- companyValuation: ValuationSignal;- timestamp: string;- dataQuality: DataQualityScore;-}--export interface DataQualityScore {- overall: number; // 0-100- sources: {- edgar_company: boolean;- edgar_filings: boolean;- edgar_proxy: boolean;- edgar_institutional: boolean;- edgar_insider: boolean;- yfinance: boolean;- peers: boolean;- };- completeness: number; // 0-100 based on how many fields have data-}--// ============================================================================-// LOADING STATE-// ============================================================================--export interface LoadingPhase {- phase: 'idle' | 'company' | 'ownership' | 'peers' | 'supplementary' | 'complete' | 'error';- progress: number; // 0-100- message: string;- partialData?: Partial<RelationshipMapDataV2>;-}--// ============================================================================-// EXPORT TYPES-// ============================================================================--export type ExportFormat = 'svg' | 'png' | 'csv' | 'json';diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/RelationshipMapTab.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/RelationshipMapTab.tsxindex f7f10e297..2954ee8bb 100644--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/RelationshipMapTab.tsx+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/RelationshipMapTab.tsx@@ -1,464 +1,477 @@-import React, { useState, useCallback, useMemo, useEffect, useRef, memo } from 'react';-import { useTranslation } from 'react-i18next';+// Relationship Map - Comprehensive Corporate Intelligence Visualization+// FINCEPT Design System compliant++import React, { useState, useMemo, useCallback } from 'react';import ReactFlow, {- Node,- Edge,Background,Controls,MiniMap,- useNodesState,- useEdgesState,- MarkerType,+ type Node,+ type Edge,+ type NodeTypes,+ type EdgeTypes,} from 'reactflow';import 'reactflow/dist/style.css';-import { Search, Globe } from 'lucide-react';-import { useTerminalTheme } from '@/contexts/ThemeContext';-import { TabFooter } from '@/components/common/TabFooter';-import { relationshipMapService } from '@/services/geopolitics/relationshipMapService';--import { CompanyNode, DataNode } from './components';-import { NODE_POSITIONS, EDGE_CONFIG, FLOW_CONFIG, BACKGROUND_CONFIG, DEFAULT_TICKER } from './constants';-import { formatMoney, formatPercent, formatNumber, formatDate } from './utils';-import type { NodeColors, GraphData } from './types';--// Define nodeTypes outside component to prevent recreation-const nodeTypes = {++import type {+ GraphNodeData,+ GraphEdgeData,+ LayoutMode,+ FilterState,+ RelationshipMapDataV2,+} from './types';+import { DEFAULT_FILTERS } from './types';+import { useRelationshipData } from './hooks/useRelationshipData';+import { applyLayout, selectOptimalLayout } from './utils/layoutAlgorithms';+import { FINCEPT, NODE_COLORS } from './constants';++import CompanyNode from './components/nodes/CompanyNode';+import PeerNode from './components/nodes/PeerNode';+import InstitutionalHolderNode from './components/nodes/InstitutionalHolderNode';+import FundFamilyNode from './components/nodes/FundFamilyNode';+import InsiderNode from './components/nodes/InsiderNode';+import EventNode from './components/nodes/EventNode';+import MetricsClusterNode from './components/nodes/MetricsClusterNode';+import SupplyChainNode from './components/nodes/SupplyChainNode';+import OwnershipEdge from './components/edges/OwnershipEdge';+import HeaderBar from './components/controls/HeaderBar';+import FilterPanel from './components/panels/FilterPanel';+import DetailPanel from './components/panels/DetailPanel';+import LegendPanel from './components/controls/LegendPanel';++const nodeTypes: NodeTypes = {company: CompanyNode,- data: DataNode,+ peer: PeerNode,+ institutional: InstitutionalHolderNode,+ fund_family: FundFamilyNode,+ insider: InsiderNode,+ event: EventNode,+ metrics: MetricsClusterNode,+ supply_chain: SupplyChainNode,};-// Build graph nodes and edges from data-const buildGraph = (data: GraphData, colors: NodeColors) => {- const newNodes: Node[] = [];- const newEdges: Edge[] = [];+const edgeTypes: EdgeTypes = {+ ownership: OwnershipEdge,+ peer: OwnershipEdge,+ event: OwnershipEdge,+ internal: OwnershipEdge,+ supply_chain: OwnershipEdge,+ segment: OwnershipEdge,+ debt: OwnershipEdge,+};- // Center: Company node- newNodes.push({- id: 'company',+function buildGraph(+ data: RelationshipMapDataV2,+ filters: FilterState+): { nodes: Node<GraphNodeData>[]; edges: Edge<GraphEdgeData>[] } {+ const nodes: Node<GraphNodeData>[] = [];+ const edges: Edge<GraphEdgeData>[] = [];+ const companyId = `company-${data.company.ticker}`;++ // 1. Company Node (always shown)+ nodes.push({+ id: companyId,type: 'company',- position: NODE_POSITIONS.company,+ position: { x: 0, y: 0 },data: {- ...data.company,- colors,+ id: companyId,+ category: 'company',+ label: data.company.ticker,+ company: data.company,+ valuation: data.companyValuation,+ executives: data.executives,},});- // Helper to add a data node with edge- const addDataNode = (- id: string,- type: string,- title: string,- items: { label: string; value: string; url?: string }[],- edgeColor: string- ) => {- const position = NODE_POSITIONS[id as keyof typeof NODE_POSITIONS];- if (!position) return;-- newNodes.push({- id,- type: 'data',- position,- data: {- type,- title,- items,- colors,- },- });+ // 2. Peer Nodes+ if (filters.showPeers && data.peers.length > 0) {+ for (const peer of data.peers) {+ const peerVal = data.peerValuations.get(peer.ticker);+ if (filters.peerFilter === 'undervalued' && peerVal?.action !== 'BUY') continue;+ if (filters.peerFilter === 'overvalued' && peerVal?.action !== 'SELL') continue;++ const peerId = `peer-${peer.ticker}`;+ nodes.push({+ id: peerId,+ type: 'peer',+ position: { x: 0, y: 0 },+ data: { id: peerId, category: 'peer', label: peer.ticker, peer, peerValuation: peerVal },+ });+ edges.push({+ id: `edge-${companyId}-${peerId}`,+ source: companyId,+ target: peerId,+ type: 'peer',+ data: { category: 'peer', label: 'peer' },+ });+ }+ }- newEdges.push({- id: `e-${id}`,- source: 'company',- target: id,- type: EDGE_CONFIG.type,- animated: EDGE_CONFIG.animated,- style: { stroke: edgeColor, strokeWidth: EDGE_CONFIG.strokeWidth },- markerEnd: { type: MarkerType.ArrowClosed, color: edgeColor },- });- };-- // 1. Corporate Events- if (data.corporate_events && data.corporate_events.length > 0) {- const eventItems = data.corporate_events.slice(0, 8).map((e) => ({- label: formatDate(e.filing_date),- value: e.items?.[0] || e.description || '8-K Filing',- url: e.filing_url,- }));- addDataNode('events', 'events', 'Corporate Events', eventItems, '#ef4444');+ // 3. Institutional Holders+ if (filters.showInstitutional && data.institutionalHolders.length > 0) {+ for (const holder of data.institutionalHolders) {+ if (holder.percentage < filters.minOwnership) continue;+ const holderId = `inst-${holder.name.replace(/\s+/g, '-').slice(0, 20)}`;+ nodes.push({+ id: holderId,+ type: 'institutional',+ position: { x: 0, y: 0 },+ data: { id: holderId, category: 'institutional', label: holder.name, holder },+ });+ edges.push({+ id: `edge-${holderId}-${companyId}`,+ source: holderId,+ target: companyId,+ type: 'ownership',+ data: { category: 'ownership', percentage: holder.percentage, shares: holder.shares, value: holder.value },+ });+ }}- // 2. Recent SEC Filings- if (data.filings && data.filings.length > 0) {- addDataNode(- 'filings',- 'filings',- 'Recent SEC Filings',- data.filings.map((f) => ({- label: `${f.form} (${f.description || ''})`,- value: formatDate(f.filing_date),- })),- '#3b82f6'- );+ // 4. Fund Families+ if (filters.showFundFamilies && data.fundFamilies.length > 0) {+ for (const family of data.fundFamilies) {+ if (family.total_percentage < filters.minOwnership) continue;+ const familyId = `fund-${family.name.replace(/\s+/g, '-').slice(0, 20)}`;+ nodes.push({+ id: familyId,+ type: 'fund_family',+ position: { x: 0, y: 0 },+ data: { id: familyId, category: 'fund_family', label: family.name, fundFamily: family },+ });+ edges.push({+ id: `edge-${familyId}-${companyId}`,+ source: familyId,+ target: companyId,+ type: 'ownership',+ data: { category: 'ownership', percentage: family.total_percentage, value: family.total_value },+ });+ }}- // 3. Financials - only show non-zero metrics- if (data.financials && (data.financials.revenue || data.financials.gross_profit || data.financials.ebitda_margins)) {- const financialItems: { label: string; value: string }[] = [];- if (data.financials.revenue) financialItems.push({ label: 'Revenue', value: formatMoney(data.financials.revenue) });- if (data.financials.gross_profit) financialItems.push({ label: 'Gross Profit', value: formatMoney(data.financials.gross_profit) });- if (data.financials.operating_cashflow) financialItems.push({ label: 'Operating CF', value: formatMoney(data.financials.operating_cashflow) });- if (data.financials.free_cashflow) financialItems.push({ label: 'Free CF', value: formatMoney(data.financials.free_cashflow) });- if (data.financials.ebitda_margins) financialItems.push({ label: 'EBITDA Margin', value: formatPercent(data.financials.ebitda_margins) });- if (data.financials.profit_margins) financialItems.push({ label: 'Profit Margin', value: formatPercent(data.financials.profit_margins) });- if (data.financials.revenue_growth) financialItems.push({ label: 'Revenue Growth', value: formatPercent(data.financials.revenue_growth) });- if (data.financials.earnings_growth) financialItems.push({ label: 'Earnings Growth', value: formatPercent(data.financials.earnings_growth) });-- if (financialItems.length > 0) {- addDataNode('financials', 'financials', 'Financial Metrics', financialItems, '#10b981');+ // 5. Insider Holders+ if (filters.showInsiders && data.insiderHolders.length > 0) {+ for (const insider of data.insiderHolders) {+ const insiderId = `insider-${insider.name.replace(/\s+/g, '-').slice(0, 20)}`;+ nodes.push({+ id: insiderId,+ type: 'insider',+ position: { x: 0, y: 0 },+ data: {+ id: insiderId,+ category: 'insider',+ label: insider.name,+ insider,+ transactions: data.insiderTransactions.filter(t =>+ t.name.toLowerCase().includes(insider.name.split(' ')[0].toLowerCase())+ ),+ },+ });+ edges.push({+ id: `edge-${insiderId}-${companyId}`,+ source: insiderId,+ target: companyId,+ type: 'internal',+ data: { category: 'internal' },+ });}}- // 4. Balance Sheet - only show if we have meaningful data- if (data.balance_sheet && (data.balance_sheet.total_cash || data.balance_sheet.total_debt || data.balance_sheet.total_assets)) {- const balanceItems: { label: string; value: string }[] = [];- if (data.balance_sheet.total_assets) balanceItems.push({ label: 'Total Assets', value: formatMoney(data.balance_sheet.total_assets) });- if (data.balance_sheet.total_liabilities) balanceItems.push({ label: 'Total Liabilities', value: formatMoney(data.balance_sheet.total_liabilities) });- if (data.balance_sheet.stockholders_equity) balanceItems.push({ label: 'Equity', value: formatMoney(data.balance_sheet.stockholders_equity) });- if (data.balance_sheet.total_cash) balanceItems.push({ label: 'Cash', value: formatMoney(data.balance_sheet.total_cash) });- if (data.balance_sheet.total_debt) balanceItems.push({ label: 'Debt', value: formatMoney(data.balance_sheet.total_debt) });- if (data.balance_sheet.shares_outstanding) balanceItems.push({ label: 'Shares Out', value: formatNumber(data.balance_sheet.shares_outstanding) });-- if (balanceItems.length > 0) {- addDataNode('balance', 'balance', 'Balance Sheet', balanceItems, colors.accent);+ // 6. Corporate Events+ if (filters.showEvents && data.corporateEvents.length > 0) {+ for (let i = 0; i < data.corporateEvents.length; i++) {+ const event = data.corporateEvents[i];+ const eventId = `event-${i}`;+ nodes.push({+ id: eventId,+ type: 'event',+ position: { x: 0, y: 0 },+ data: { id: eventId, category: 'event', label: event.description || event.form, event },+ });+ edges.push({+ id: `edge-${companyId}-${eventId}`,+ source: companyId,+ target: eventId,+ type: 'event',+ data: { category: 'event' },+ });}}- // 5. Analysts- if (data.analysts && data.analysts.recommendation !== 'N/A') {- addDataNode(- 'analysts',- 'analysts',- 'Analyst Coverage',- [- { label: 'Recommendation', value: (data.analysts.recommendation || 'N/A').toUpperCase() },- {- label: 'Rating Score',- value: data.analysts.recommendation_mean ? data.analysts.recommendation_mean.toFixed(2) : 'N/A',+ // 7. Metrics Clusters - always show if we have ANY company data+ if (filters.showMetrics) {+ const hasFinancials = data.company.revenue || data.company.gross_profit || data.company.ebitda || data.company.free_cashflow;+ if (hasFinancials) {+ const finId = 'metrics-financials';+ nodes.push({+ id: finId, type: 'metrics', position: { x: 0, y: 0 },+ data: {+ id: finId, category: 'metrics', label: 'Financials', metricsType: 'financials',+ metrics: {+ revenue: data.company.revenue,+ gross_profit: data.company.gross_profit,+ ebitda: data.company.ebitda,+ free_cashflow: data.company.free_cashflow,+ profit_margins: data.company.profit_margins,+ operating_margins: data.company.operating_margins,+ },},- { label: 'Target Price', value: formatMoney(data.analysts.target_price) },- { label: 'Target High', value: formatMoney(data.analysts.target_high) },- { label: 'Target Low', value: formatMoney(data.analysts.target_low) },- { label: 'Analysts', value: String(data.analysts.analyst_count || 0) },- ],- '#8b5cf6'- );- }+ });+ edges.push({ id: `edge-${companyId}-${finId}`, source: companyId, target: finId, type: 'internal', data: { category: 'internal' } });+ }++ const hasValuation = data.company.pe_ratio || data.company.price_to_book || data.company.peg_ratio || data.company.enterprise_value;+ if (hasValuation) {+ const valId = 'metrics-valuation';+ nodes.push({+ id: valId, type: 'metrics', position: { x: 0, y: 0 },+ data: {+ id: valId, category: 'metrics', label: 'Valuation', metricsType: 'valuation',+ metrics: {+ pe_ratio: data.company.pe_ratio,+ forward_pe: data.company.forward_pe,+ price_to_book: data.company.price_to_book,+ peg_ratio: data.company.peg_ratio,+ enterprise_value: data.company.enterprise_value,+ ev_to_revenue: data.company.enterprise_to_revenue,+ },+ },+ });+ edges.push({ id: `edge-${companyId}-${valId}`, source: companyId, target: valId, type: 'internal', data: { category: 'internal' } });+ }- // 6. Ownership- if (data.ownership && (data.ownership.insider_percent || data.ownership.institutional_percent)) {- addDataNode(- 'ownership',- 'ownership',- 'Ownership Structure',- [- { label: 'Insider %', value: `${(data.ownership.insider_percent || 0).toFixed(2)}%` },- { label: 'Institutional %', value: `${(data.ownership.institutional_percent || 0).toFixed(2)}%` },- { label: 'Float Shares', value: formatNumber(data.ownership.float_shares) },- { label: 'Total Shares', value: formatNumber(data.ownership.shares_outstanding) },- ],- '#f59e0b'- );+ const hasBalance = data.company.total_cash || data.company.total_debt || data.company.shares_outstanding;+ if (hasBalance) {+ const bsId = 'metrics-balance';+ nodes.push({+ id: bsId, type: 'metrics', position: { x: 0, y: 0 },+ data: {+ id: bsId, category: 'metrics', label: 'Balance Sheet', metricsType: 'balance_sheet',+ metrics: {+ total_cash: data.company.total_cash,+ total_debt: data.company.total_debt,+ shares_outstanding: data.company.shares_outstanding,+ float_shares: data.company.float_shares,+ },+ },+ });+ edges.push({ id: `edge-${companyId}-${bsId}`, source: companyId, target: bsId, type: 'internal', data: { category: 'internal' } });+ }}- // 7. Valuation- if (data.valuation && (data.valuation.pe_ratio || data.valuation.enterprise_value)) {- addDataNode(- 'valuation',- 'valuation',- 'Valuation Metrics',- [- { label: 'P/E Ratio', value: (data.valuation.pe_ratio || 0).toFixed(2) },- { label: 'Forward P/E', value: (data.valuation.forward_pe || 0).toFixed(2) },- { label: 'Price/Book', value: (data.valuation.price_to_book || 0).toFixed(2) },- { label: 'Enterprise Value', value: formatMoney(data.valuation.enterprise_value) },- { label: 'EV/Revenue', value: (data.valuation.enterprise_to_revenue || 0).toFixed(2) },- { label: 'PEG Ratio', value: (data.valuation.peg_ratio || 0).toFixed(2) },- ],- '#ec4899'- );+ // 8. Supply Chain Nodes+ if (filters.showSupplyChain && data.supplyChain && data.supplyChain.length > 0) {+ for (let i = 0; i < data.supplyChain.length; i++) {+ const entity = data.supplyChain[i];+ const scId = `sc-${entity.name.replace(/\s+/g, '-').slice(0, 20)}-${i}`;+ nodes.push({+ id: scId,+ type: 'supply_chain',+ position: { x: 0, y: 0 },+ data: { id: scId, category: 'supply_chain', label: entity.name, supplyChain: entity },+ });+ // Direction: customer buys FROM company, supplier sells TO company+ if (entity.relationship === 'customer') {+ edges.push({+ id: `edge-${companyId}-${scId}`,+ source: companyId,+ target: scId,+ type: 'supply_chain',+ data: { category: 'supply_chain', relationship: 'customer' },+ });+ } else {+ edges.push({+ id: `edge-${scId}-${companyId}`,+ source: scId,+ target: companyId,+ type: 'supply_chain',+ data: { category: 'supply_chain', relationship: 'supplier' },+ });+ }+ }}- // 8. Company Info- addDataNode(- 'info',- 'info',- 'Company Information',- [- { label: 'Exchange', value: data.company.exchange },- { label: 'Sector', value: data.company.sector },- { label: 'Industry', value: data.company.industry },- { label: 'Employees', value: data.company.employees ? data.company.employees.toLocaleString() : 'N/A' },- { label: 'CIK', value: data.company.cik },- ],- '#14b8a6'- );+ // 9. Segment Nodes+ if (filters.showSegments && data.segments && data.segments.length > 0) {+ for (let i = 0; i < data.segments.length; i++) {+ const segment = data.segments[i];+ const segId = `seg-${segment.name.replace(/\s+/g, '-').slice(0, 20)}-${i}`;+ nodes.push({+ id: segId,+ type: 'metrics', // Reuse metrics node for segments+ position: { x: 0, y: 0 },+ data: {+ id: segId, category: 'segment', label: segment.name, segment,+ metrics: { value: segment.value, type: segment.type },+ },+ });+ edges.push({+ id: `edge-${companyId}-${segId}`,+ source: companyId,+ target: segId,+ type: 'internal',+ data: { category: 'segment' },+ });+ }+ }- // 9. Executives- if (data.executives && data.executives.length > 0) {- addDataNode(- 'executives',- 'executives',- 'Executives',- data.executives.map((exec) => ({- label: exec.name,- value: exec.role,- })),- '#10b981'- );+ // 10. Debt Holder Nodes+ if (filters.showDebtHolders && data.debtHolders && data.debtHolders.length > 0) {+ for (let i = 0; i < data.debtHolders.length; i++) {+ const dh = data.debtHolders[i];+ const dhId = `debt-${dh.name.replace(/\s+/g, '-').slice(0, 20)}-${i}`;+ nodes.push({+ id: dhId,+ type: 'event', // Reuse event node styling for debt holders+ position: { x: 0, y: 0 },+ data: { id: dhId, category: 'debt_holder', label: dh.name, debtHolder: dh },+ });+ edges.push({+ id: `edge-${dhId}-${companyId}`,+ source: dhId,+ target: companyId,+ type: 'internal',+ data: { category: 'debt' },+ });+ }}- return { nodes: newNodes, edges: newEdges };-};+ return { nodes, edges };+}const RelationshipMapTab: React.FC = () => {- const { t } = useTranslation('relationshipMap');- const { colors, fontSize, fontFamily } = useTerminalTheme();- const [searchQuery, setSearchQuery] = useState('');- const [selectedSymbol, setSelectedSymbol] = useState(DEFAULT_TICKER);- const [isLoading, setIsLoading] = useState(false);- const [loadingTime, setLoadingTime] = useState(0);- const [error, setError] = useState<string | null>(null);- const loadingTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);-- const [nodes, setNodes, onNodesChange] = useNodesState([]);- const [edges, setEdges, onEdgesChange] = useEdgesState([]);-- // Memoize node colors to pass to child components- const nodeColors: NodeColors = useMemo(- () => ({- accent: colors.accent,- text: colors.text,- textMuted: colors.textMuted,- success: colors.success,- alert: colors.alert,- panel: colors.panel,- }),- [colors.accent, colors.text, colors.textMuted, colors.success, colors.alert, colors.panel]- );-- const fetchRelationshipData = useCallback(- async (ticker: string) => {- setIsLoading(true);- setError(null);- setLoadingTime(0);-- // Start loading timer- if (loadingTimerRef.current) clearInterval(loadingTimerRef.current);- loadingTimerRef.current = setInterval(() => {- setLoadingTime((prev) => prev + 1);- }, 1000);-- try {- const data = await relationshipMapService.getRelationshipMap(ticker);- const { nodes: newNodes, edges: newEdges } = buildGraph(data as unknown as GraphData, nodeColors);- setNodes(newNodes);- setEdges(newEdges);- } catch (err) {- console.error('[UI] Error:', err);- setError(`Failed to load data for ${ticker}`);- } finally {- if (loadingTimerRef.current) {- clearInterval(loadingTimerRef.current);- loadingTimerRef.current = null;- }- setIsLoading(false);- }- },- [nodeColors, setNodes, setEdges]- );-- useEffect(() => {- fetchRelationshipData(selectedSymbol);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [selectedSymbol]);-- // Cleanup timer on unmount- useEffect(() => {- return () => {- if (loadingTimerRef.current) clearInterval(loadingTimerRef.current);+ const { data, loading, error, phase, fetchData } = useRelationshipData();+ const [layoutMode, setLayoutMode] = useState<LayoutMode>('layered');+ const [filters, setFilters] = useState<FilterState>(DEFAULT_FILTERS);+ const [showFilters, setShowFilters] = useState(false);+ const [selectedNode, setSelectedNode] = useState<GraphNodeData | null>(null);++ const { nodes: rawNodes, edges } = useMemo(() => {+ if (!data) return { nodes: [], edges: [] };+ return buildGraph(data, filters);+ }, [data, filters]);++ const nodes = useMemo(() => {+ if (rawNodes.length === 0) return [];+ const effectiveMode = layoutMode === 'custom' ? selectOptimalLayout(rawNodes) : layoutMode;+ return applyLayout(rawNodes, effectiveMode, {+ mode: effectiveMode, centerX: 600, centerY: 500, width: 2000, height: 1600, padding: 100,+ });+ }, [rawNodes, layoutMode]);++ const nodeCounts: Record<string, number> = useMemo(() => {+ if (!data) return { peer: 0, institutional: 0, fund_family: 0, insider: 0, event: 0, supply_chain: 0, segment: 0, debt_holder: 0, metrics: 0 };+ return {+ peer: data.peers.length,+ institutional: data.institutionalHolders.length,+ fund_family: data.fundFamilies.length,+ insider: data.insiderHolders.length,+ event: data.corporateEvents.length,+ supply_chain: data.supplyChain?.length || 0,+ segment: data.segments?.length || 0,+ debt_holder: data.debtHolders?.length || 0,+ metrics: 3,};- }, []);+ }, [data]);- const handleSearch = useCallback(- (e: React.FormEvent) => {- e.preventDefault();- if (!searchQuery.trim()) return;- const ticker = searchQuery.toUpperCase().trim();- setSelectedSymbol(ticker);- },- [searchQuery]- );+ const handleSearch = useCallback((ticker: string) => {+ setSelectedNode(null);+ fetchData(ticker);+ }, [fetchData]);- // Memoize container style- const containerStyle = useMemo(- () => ({- fontFamily,- fontSize: `${fontSize}px`,- backgroundColor: colors.background,- color: colors.text,- }),- [fontFamily, fontSize, colors.background, colors.text]- );-- // Memoize header border style- const headerStyle = useMemo(- () => ({ borderColor: colors.textMuted }),- [colors.textMuted]- );-- // Memoize ticker badge style- const badgeStyle = useMemo(- () => ({- backgroundColor: colors.panel,- color: colors.accent,- border: `1px solid ${colors.textMuted}`,- }),- [colors.panel, colors.accent, colors.textMuted]- );-- // Memoize input style- const inputStyle = useMemo(- () => ({- backgroundColor: colors.panel,- borderColor: colors.textMuted,- color: colors.text,- }),- [colors.panel, colors.textMuted, colors.text]- );-- // Memoize minimap node color function- const minimapNodeColor = useCallback(- (node: Node) => {- if (node.id === 'company') return colors.accent;- return colors.textMuted;- },- [colors.accent, colors.textMuted]- );-- // Memoize controls style- const controlsStyle = useMemo(- () => ({- background: '#1a1a1a',- border: `1px solid ${colors.textMuted}`,- borderRadius: '4px',- }),- [colors.textMuted]- );+ const handleNodeClick = useCallback((_: React.MouseEvent, node: Node<GraphNodeData>) => {+ setSelectedNode(node.data);+ }, []);- // Memoize minimap style- const minimapStyle = useMemo(- () => ({- background: '#1a1a1a',- border: `1px solid ${colors.textMuted}`,- }),- [colors.textMuted]- );+ const handlePaneClick = useCallback(() => {+ setSelectedNode(null);+ }, []);return (- <div className="h-full flex flex-col" style={containerStyle}>- {/* Header */}- <div className="border-b px-4 py-3 flex items-center justify-between" style={headerStyle}>- <div className="flex items-center gap-3">- <Globe className="w-5 h-5" style={{ color: colors.accent }} />- <h2 className="text-lg font-semibold">{t('title')}</h2>- <span className="text-xs px-2 py-1 rounded font-mono" style={badgeStyle}>- {selectedSymbol}- </span>- </div>-- <form onSubmit={handleSearch} className="relative w-96">- <Search- className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4"- style={{ color: colors.textMuted }}- />- <input- type="text"- value={searchQuery}- onChange={(e) => setSearchQuery(e.target.value)}- placeholder={t('search.placeholder')}- className="w-full pl-10 pr-4 py-2 rounded border focus:outline-none focus:ring-1"- style={inputStyle}- />- </form>- </div>-- {/* Graph */}- <div className="flex-1" style={{ background: '#0a0a0a' }}>- {isLoading ? (- <div className="flex items-center justify-center h-full">- <div className="text-center">- <div- className="animate-spin rounded-full h-16 w-16 border-b-2 mx-auto mb-4"- style={{ borderColor: colors.accent }}- />- <p className="text-lg font-semibold" style={{ color: colors.text }}>- {t('loading.title')} {selectedSymbol}...- </p>- <p className="text-sm mt-2" style={{ color: colors.textMuted }}>- {loadingTime < 5- ? t('loading.subtitle')- : loadingTime < 15- ? 'Fetching SEC filings and market data...'- : 'Almost there, waiting for SEC data...'}- </p>- <p className="text-xs mt-1 font-mono" style={{ color: colors.textMuted }}>- {loadingTime}s- </p>- </div>- </div>- ) : error ? (- <div className="flex items-center justify-center h-full">- <div- className="text-center p-8 rounded border"- style={{- backgroundColor: colors.panel,- borderColor: colors.alert,- }}- >- <p className="text-lg font-semibold mb-2" style={{ color: colors.alert }}>- {t('error.title')}- </p>- <p style={{ color: colors.textMuted }}>{error}</p>- </div>- </div>- ) : (+ <div style={{ width: '100%', height: '100%', position: 'relative', backgroundColor: FINCEPT.DARK_BG, fontFamily: '"IBM Plex Mono", "Consolas", monospace' }}>+ <HeaderBar+ onSearch={handleSearch}+ layoutMode={layoutMode}+ onLayoutChange={setLayoutMode}+ onToggleFilters={() => setShowFilters(!showFilters)}+ showFilters={showFilters}+ dataQuality={data?.dataQuality}+ loading={loading}+ progress={phase.progress}+ message={phase.message}+ />++ {showFilters && (+ <FilterPanel filters={filters} onChange={setFilters} nodeCounts={nodeCounts} />+ )}++ <div style={{ position: 'absolute', top: '48px', left: 0, right: 0, bottom: '28px' }}>+ {nodes.length > 0 ? (<ReactFlownodes={nodes}edges={edges}- onNodesChange={onNodesChange}- onEdgesChange={onEdgesChange}nodeTypes={nodeTypes}- fitView={FLOW_CONFIG.fitView}- minZoom={FLOW_CONFIG.minZoom}- maxZoom={FLOW_CONFIG.maxZoom}- defaultViewport={FLOW_CONFIG.defaultViewport}- style={BACKGROUND_CONFIG.style}+ edgeTypes={edgeTypes}+ onNodeClick={handleNodeClick}+ onPaneClick={handlePaneClick}+ onlyRenderVisibleElements={true}+ fitView+ fitViewOptions={{ padding: 0.2, maxZoom: 1.5 }}+ minZoom={0.05}+ maxZoom={3}+ defaultEdgeOptions={{ animated: false }}+ proOptions={{ hideAttribution: true }}>- <Background- gap={BACKGROUND_CONFIG.gap}- size={BACKGROUND_CONFIG.size}- style={BACKGROUND_CONFIG.style}- color={BACKGROUND_CONFIG.color}+ <Background color={FINCEPT.BORDER} gap={40} />+ <Controls+ position="bottom-right"+ style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px' }}+ />+ <MiniMap+ nodeColor={(node: any) => {+ const cat = node?.data?.category;+ return NODE_COLORS[cat as keyof typeof NODE_COLORS]?.border || FINCEPT.GRAY;+ }}+ style={{ background: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}` }}+ position="bottom-left"+ pannable+ zoomable/>- <Controls style={controlsStyle} />- <MiniMap style={minimapStyle} maskColor="#0a0a0a90" nodeColor={minimapNodeColor} /></ReactFlow>+ ) : !loading ? (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', color: FINCEPT.MUTED, fontSize: '10px', textAlign: 'center' }}>+ <div style={{ fontSize: '32px', opacity: 0.3, marginBottom: '12px' }}>📈</div>+ <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.WHITE, letterSpacing: '0.5px' }}>+ CORPORATE INTELLIGENCE MAP+ </div>+ <div style={{ fontSize: '10px', maxWidth: '360px', marginTop: '8px', lineHeight: 1.6, color: FINCEPT.GRAY }}>+ Enter a ticker symbol to visualize corporate relationships: ownership structure, peer valuations, insider activity, and events.+ </div>+ <div style={{ fontSize: '9px', color: FINCEPT.ORANGE, marginTop: '12px', fontWeight: 700 }}>+ TRY: AAPL, MSFT, TSLA, NVDA, GOOGL+ </div>+ </div>+ ) : null}++ {error && (+ <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', background: `${FINCEPT.RED}15`, border: `1px solid ${FINCEPT.RED}`, borderRadius: '2px', padding: '16px 24px', textAlign: 'center' }}>+ <div style={{ fontWeight: 700, marginBottom: '4px', color: FINCEPT.RED, fontSize: '10px' }}>ERROR LOADING DATA</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>{error}</div>+ </div>)}</div>- <TabFooter tabName="Relationship Map" />+ <DetailPanel nodeData={selectedNode} onClose={() => setSelectedNode(null)} />+ <LegendPanel visible={nodes.length > 0 && !selectedNode} />++ {/* Status Bar */}+ <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: '28px', backgroundColor: FINCEPT.HEADER_BG, borderTop: `1px solid ${FINCEPT.BORDER}`, padding: '4px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: '9px', color: FINCEPT.GRAY }}>+ <span>{data ? `${nodes.length} NODES | ${edges.length} EDGES` : 'READY'}</span>+ <span>{data ? `QUALITY: ${data.dataQuality.overall}%` : ''}</span>+ <span style={{ color: FINCEPT.ORANGE }}>FINCEPT TERMINAL</span>+ </div></div>);};-export default memo(RelationshipMapTab);+export default RelationshipMapTab;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/CompanyNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/CompanyNode.tsxdeleted file mode 100644index 0733a9914..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/CompanyNode.tsx+++ /dev/null@@ -1,61 +0,0 @@-import React, { memo, useMemo } from 'react';-import { Handle, Position } from 'reactflow';-import { Building2 } from 'lucide-react';-import { formatMarketCap } from '../utils';-import type { CompanyNodeProps } from '../types';--const CompanyNode = memo(({ data }: CompanyNodeProps) => {- const { colors } = data;-- // Memoize styles to prevent recreation on each render- const containerStyle = useMemo(- () => ({- background: 'linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%)',- border: `3px solid ${colors.accent}`,- borderRadius: '12px',- padding: '24px',- minWidth: '320px',- maxWidth: '400px',- boxShadow: `0 0 40px ${colors.accent}80, 0 10px 30px rgba(0,0,0,0.7)`,- }),- [colors.accent]- );-- const handleStyle = useMemo(() => ({ opacity: 0 }), []);-- return (- <div style={containerStyle}>- <Handle type="target" position={Position.Top} style={handleStyle} />- <div className="flex flex-col items-center text-center">- <Building2 className="w-12 h-12 mb-3" style={{ color: colors.accent }} />- <h2 className="text-2xl font-bold mb-1" style={{ color: colors.text }}>- {data.name}- </h2>- <div className="text-xl mb-2 font-mono" style={{ color: colors.accent }}>- {data.ticker}- </div>- <div className="text-sm mb-1" style={{ color: colors.textMuted }}>- {data.sector} • {data.industry}- </div>- <div className="text-sm font-semibold mt-2" style={{ color: colors.success }}>- Market Cap: {formatMarketCap(data.market_cap || 0)}- </div>- <div className="text-xs mt-2 opacity-60">- CIK: {data.cik} | {data.exchange}- </div>- {data.employees && (- <div className="text-xs mt-1" style={{ color: colors.textMuted }}>- {data.employees.toLocaleString()} employees- </div>- )}- </div>- <Handle type="source" position={Position.Bottom} style={handleStyle} />- <Handle type="source" position={Position.Left} style={handleStyle} />- <Handle type="source" position={Position.Right} style={handleStyle} />- </div>- );-});--CompanyNode.displayName = 'CompanyNode';--export default CompanyNode;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/DataNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/DataNode.tsxdeleted file mode 100644index b106e9711..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/DataNode.tsx+++ /dev/null@@ -1,202 +0,0 @@-import React, { memo, useMemo, useCallback, useState } from 'react';-import { Handle, Position } from 'reactflow';-import {- Activity,- Calendar,- DollarSign,- BarChart3,- Award,- PieChart,- TrendingUp,- Briefcase,- Users,- FileText,- ExternalLink,-} from 'lucide-react';-import { open } from '@tauri-apps/plugin-shell';-import { NODE_TYPE_COLORS } from '../constants';-import type { DataNodeProps, DataNodeType, DataNodeItem } from '../types';--// Memoized icon getter - returns the icon component-const getIconComponent = (type: DataNodeType) => {- switch (type) {- case 'events':- return Activity;- case 'filings':- return Calendar;- case 'financials':- return DollarSign;- case 'balance':- return BarChart3;- case 'analysts':- return Award;- case 'ownership':- return PieChart;- case 'valuation':- return TrendingUp;- case 'info':- return Briefcase;- case 'executives':- return Users;- default:- return FileText;- }-};--// Get node color based on type-const getNodeColor = (type: DataNodeType, accentColor: string): string => {- if (type === 'balance') return accentColor;- return NODE_TYPE_COLORS[type] || '#6b7280';-};--// Memoized data item row-const DataItemRow = memo(- ({- item,- isClickable,- textMutedColor,- textColor,- onClick,- }: {- item: DataNodeItem;- isClickable: boolean;- textMutedColor: string;- textColor: string;- onClick: (e: React.MouseEvent) => void;- }) => (- <div- className="flex justify-between gap-3 hover:bg-white/5 rounded px-1 py-0.5 transition-colors"- onClick={onClick}- style={{ cursor: isClickable && item.url ? 'pointer' : 'default' }}- >- <span className="truncate" style={{ color: textMutedColor }}>- {item.label}- </span>- <span className="font-medium text-right flex items-center gap-1" style={{ color: textColor }}>- {item.value}- {isClickable && item.url && <ExternalLink className="w-3 h-3 opacity-50" />}- </span>- </div>- )-);--DataItemRow.displayName = 'DataItemRow';--const DataNode = memo(({ data }: DataNodeProps) => {- const { colors, type, title, items } = data;- const [expanded, setExpanded] = useState(false);-- const nodeColor = useMemo(() => getNodeColor(type, colors.accent), [type, colors.accent]);- const IconComponent = useMemo(() => getIconComponent(type), [type]);- const hasClickableItems = type === 'events' || type === 'filings';- const displayItems = expanded ? items : items?.slice(0, 4);- const hasMoreItems = items?.length > 4;-- // Memoize styles- const containerStyle = useMemo(- () => ({- background: '#1a1a1a',- border: `2px solid ${nodeColor}`,- borderRadius: '8px',- padding: '14px 18px',- minWidth: '260px',- maxWidth: '320px',- boxShadow: `0 0 20px ${nodeColor}50, 0 4px 12px rgba(0,0,0,0.5)`,- cursor: hasMoreItems ? 'pointer' : 'default',- transition: 'all 0.2s',- }),- [nodeColor, hasMoreItems]- );-- const handleStyle = useMemo(() => ({ background: nodeColor }), [nodeColor]);- const handleStyleHidden = useMemo(() => ({ background: nodeColor, opacity: 0 }), [nodeColor]);-- const badgeStyle = useMemo(- () => ({- backgroundColor: `${nodeColor}20`,- color: nodeColor,- }),- [nodeColor]- );-- const handleContainerClick = useCallback(() => {- if (hasMoreItems) {- setExpanded((prev) => !prev);- }- }, [hasMoreItems]);-- const handleItemClick = useCallback(- async (e: React.MouseEvent, item: DataNodeItem) => {- e.stopPropagation();- if (hasClickableItems && item.url) {- await open(item.url);- }- },- [hasClickableItems]- );-- const handleMouseEnter = useCallback(- (e: React.MouseEvent<HTMLDivElement>) => {- e.currentTarget.style.transform = 'scale(1.02)';- e.currentTarget.style.boxShadow = `0 0 30px ${nodeColor}70, 0 6px 16px rgba(0,0,0,0.6)`;- },- [nodeColor]- );-- const handleMouseLeave = useCallback(- (e: React.MouseEvent<HTMLDivElement>) => {- e.currentTarget.style.transform = 'scale(1)';- e.currentTarget.style.boxShadow = `0 0 20px ${nodeColor}50, 0 4px 12px rgba(0,0,0,0.5)`;- },- [nodeColor]- );-- return (- <div- style={containerStyle}- onClick={handleContainerClick}- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- >- <Handle type="target" position={Position.Top} style={handleStyle} />-- <div className="flex items-center gap-2 mb-3">- <div style={{ color: nodeColor }}>- <IconComponent className="w-5 h-5" />- </div>- <h4 className="font-semibold text-sm" style={{ color: colors.text }}>- {title}- </h4>- {hasMoreItems && (- <span className="text-xs ml-auto px-1.5 py-0.5 rounded" style={badgeStyle}>- {items.length}- </span>- )}- </div>-- <div className="space-y-1.5 text-xs">- {displayItems?.map((item, idx) => (- <DataItemRow- key={idx}- item={item}- isClickable={hasClickableItems}- textMutedColor={colors.textMuted}- textColor={colors.text}- onClick={(e) => handleItemClick(e, item)}- />- ))}- {!expanded && hasMoreItems && (- <div className="text-center pt-1 text-xs font-semibold" style={{ color: nodeColor }}>- Click to see +{items.length - 4} more- </div>- )}- </div>-- <Handle type="source" position={Position.Bottom} style={handleStyleHidden} />- </div>- );-});--DataNode.displayName = 'DataNode';--export default DataNode;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/controls/HeaderBar.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/controls/HeaderBar.tsxnew file mode 100644index 000000000..1b8d7cf65--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/controls/HeaderBar.tsx@@ -0,0 +1,86 @@+import React, { useState } from 'react';+import type { LayoutMode, DataQualityScore } from '../../types';+import { FINCEPT } from '../../constants';++interface HeaderBarProps {+ onSearch: (ticker: string) => void;+ layoutMode: LayoutMode;+ onLayoutChange: (mode: LayoutMode) => void;+ onToggleFilters: () => void;+ showFilters: boolean;+ dataQuality?: DataQualityScore;+ loading: boolean;+ progress: number;+ message: string;+}++const LAYOUTS: { mode: LayoutMode; label: string }[] = [+ { mode: 'layered', label: 'RING' },+ { mode: 'force', label: 'FORCE' },+ { mode: 'circular', label: 'CIRCLE' },+ { mode: 'hierarchical', label: 'TREE' },+ { mode: 'radial', label: 'RADIAL' },+];++const HeaderBar: React.FC<HeaderBarProps> = ({+ onSearch, layoutMode, onLayoutChange, onToggleFilters, showFilters,+ dataQuality, loading, progress, message,+}) => {+ const [input, setInput] = useState('');++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ if (input.trim()) {+ onSearch(input.trim().toUpperCase());+ setInput('');+ }+ };++ return (+ <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: '48px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `2px solid ${FINCEPT.ORANGE}`, padding: '0 16px', display: 'flex', alignItems: 'center', gap: '12px', zIndex: 100, boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20` }}>+ <form onSubmit={handleSubmit} style={{ display: 'flex', gap: '6px' }}>+ <input+ value={input}+ onChange={(e) => setInput(e.target.value.toUpperCase())}+ placeholder="TICKER"+ style={{ width: '80px', padding: '6px 8px', backgroundColor: FINCEPT.DARK_BG, color: FINCEPT.WHITE, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '10px', fontFamily: '"IBM Plex Mono", monospace', fontWeight: 700 }}+ />+ <button type="submit" disabled={loading} style={{ padding: '6px 12px', backgroundColor: FINCEPT.ORANGE, color: FINCEPT.DARK_BG, border: 'none', borderRadius: '2px', fontSize: '9px', fontWeight: 700, cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.5 : 1 }}>+ MAP+ </button>+ </form>++ {loading && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>+ <div style={{ flex: 1, maxWidth: '200px', height: '4px', backgroundColor: FINCEPT.BORDER, borderRadius: '2px', overflow: 'hidden' }}>+ <div style={{ width: `${progress}%`, height: '100%', backgroundColor: FINCEPT.ORANGE, transition: 'width 0.3s' }} />+ </div>+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>{message}</span>+ </div>+ )}++ {!loading && <div style={{ flex: 1 }} />}++ {dataQuality && (+ <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>+ <div style={{ width: '8px', height: '8px', borderRadius: '50%', backgroundColor: dataQuality.overall >= 70 ? FINCEPT.GREEN : dataQuality.overall >= 40 ? FINCEPT.YELLOW : FINCEPT.RED }} />+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 700 }}>{dataQuality.overall}%</span>+ </div>+ )}++ <div style={{ display: 'flex', gap: '2px' }}>+ {LAYOUTS.map(({ mode, label }) => (+ <button key={mode} onClick={() => onLayoutChange(mode)} style={{ padding: '4px 8px', backgroundColor: layoutMode === mode ? FINCEPT.ORANGE : 'transparent', color: layoutMode === mode ? FINCEPT.DARK_BG : FINCEPT.GRAY, border: 'none', fontSize: '8px', fontWeight: 700, letterSpacing: '0.5px', cursor: 'pointer', borderRadius: '2px', transition: 'all 0.2s' }}>+ {label}+ </button>+ ))}+ </div>++ <button onClick={onToggleFilters} style={{ padding: '4px 10px', backgroundColor: showFilters ? `${FINCEPT.ORANGE}20` : 'transparent', color: showFilters ? FINCEPT.ORANGE : FINCEPT.GRAY, border: `1px solid ${showFilters ? FINCEPT.ORANGE : FINCEPT.BORDER}`, borderRadius: '2px', fontSize: '8px', fontWeight: 700, cursor: 'pointer', letterSpacing: '0.5px' }}>+ FILTER+ </button>+ </div>+ );+};++export default HeaderBar;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/controls/LegendPanel.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/controls/LegendPanel.tsxnew file mode 100644index 000000000..5734f7680--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/controls/LegendPanel.tsx@@ -0,0 +1,41 @@+import React from 'react';+import { FINCEPT, NODE_COLORS } from '../../constants';++interface LegendPanelProps {+ visible: boolean;+}++const ITEMS = [+ { label: 'COMPANY', color: NODE_COLORS.company.border },+ { label: 'PEERS', color: NODE_COLORS.peer.border },+ { label: 'INSTITUTIONAL', color: NODE_COLORS.institutional.border },+ { label: 'FUND FAMILY', color: NODE_COLORS.fund_family.border },+ { label: 'INSIDERS', color: NODE_COLORS.insider.border },+ { label: 'EVENTS', color: NODE_COLORS.event.border },+ { label: 'METRICS', color: NODE_COLORS.metrics.border },+];++const LegendPanel: React.FC<LegendPanelProps> = ({ visible }) => {+ if (!visible) return null;+ return (+ <div style={{ position: 'absolute', bottom: '40px', left: '12px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderRadius: '2px', padding: '8px 12px', zIndex: 50 }}>+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '6px' }}>LEGEND</div>+ {ITEMS.map(item => (+ <div key={item.label} style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '3px' }}>+ <div style={{ width: '8px', height: '8px', borderRadius: '2px', backgroundColor: item.color }} />+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 700 }}>{item.label}</span>+ </div>+ ))}+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, marginTop: '6px', paddingTop: '6px' }}>+ {[{ c: FINCEPT.GREEN, l: 'BUY' }, { c: FINCEPT.YELLOW, l: 'HOLD' }, { c: FINCEPT.RED, l: 'SELL' }].map(s => (+ <div key={s.l} style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '2px' }}>+ <div style={{ width: '8px', height: '4px', backgroundColor: s.c, borderRadius: '1px' }} />+ <span style={{ fontSize: '7px', color: s.c, fontWeight: 700 }}>{s.l}</span>+ </div>+ ))}+ </div>+ </div>+ );+};++export default LegendPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/edges/OwnershipEdge.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/edges/OwnershipEdge.tsxnew file mode 100644index 000000000..d264c2cec--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/edges/OwnershipEdge.tsx@@ -0,0 +1,44 @@+import React from 'react';+import { BaseEdge, getSmoothStepPath, type EdgeProps } from 'reactflow';+import type { GraphEdgeData } from '../../types';+import { FINCEPT } from '../../constants';++const CATEGORY_COLORS: Record<string, string> = {+ ownership: FINCEPT.GREEN,+ peer: FINCEPT.BLUE,+ event: FINCEPT.RED,+ supply_chain: FINCEPT.YELLOW,+ internal: FINCEPT.MUTED,+};++const OwnershipEdge: React.FC<EdgeProps> = ({+ id, sourceX, sourceY, targetX, targetY,+ sourcePosition, targetPosition, data, selected,+}) => {+ const edgeData = data as GraphEdgeData | undefined;+ const category = edgeData?.category || 'internal';+ const percentage = edgeData?.percentage || 0;++ const [edgePath, labelX, labelY] = getSmoothStepPath({+ sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, borderRadius: 8,+ });++ const strokeWidth = category === 'ownership' ? Math.max(1, Math.min(6, percentage / 2)) : category === 'peer' ? 1.5 : 1;+ const stroke = CATEGORY_COLORS[category] || FINCEPT.MUTED;+ const dashArray = (category === 'peer' || category === 'event') ? '5 5' : undefined;++ return (+ <>+ <BaseEdge id={id} path={edgePath} style={{ stroke, strokeWidth, opacity: selected ? 1 : 0.6, strokeDasharray: dashArray }} />+ {category === 'ownership' && percentage > 0 && (+ <foreignObject x={labelX - 20} y={labelY - 8} width={40} height={16} style={{ overflow: 'visible' }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: FINCEPT.GREEN, backgroundColor: FINCEPT.DARK_BG, padding: '1px 4px', borderRadius: '2px', border: `1px solid ${FINCEPT.BORDER}`, textAlign: 'center', fontFamily: '"IBM Plex Mono", monospace' }}>+ {percentage.toFixed(1)}%+ </div>+ </foreignObject>+ )}+ </>+ );+};++export default OwnershipEdge;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/index.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/index.tsdeleted file mode 100644index c3e6a6c95..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export { default as CompanyNode } from './CompanyNode';-export { default as DataNode } from './DataNode';diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/CompanyNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/CompanyNode.tsxnew file mode 100644index 000000000..6fe860818--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/CompanyNode.tsx@@ -0,0 +1,88 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT, SIGNAL_COLORS } from '../../constants';++interface CompanyNodeProps { data: GraphNodeData; selected?: boolean; }++function fmtMoney(val: number): string {+ if (!val) return 'N/A';+ if (val >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;+ if (val >= 1e9) return `$${(val / 1e9).toFixed(1)}B`;+ if (val >= 1e6) return `$${(val / 1e6).toFixed(0)}M`;+ return `$${val.toLocaleString()}`;+}++const CompanyNode: React.FC<CompanyNodeProps> = ({ data, selected }) => {+ const c = data.company;+ const v = data.valuation;+ if (!c) return null;++ const sigColor = v ? SIGNAL_COLORS[v.action] : null;++ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `2px solid ${selected ? FINCEPT.WHITE : FINCEPT.ORANGE}`, borderRadius: '2px', padding: '12px 16px', width: '380px', minHeight: '200px', fontFamily: '"IBM Plex Mono", monospace', boxShadow: `0 0 12px ${FINCEPT.ORANGE}30` }}>+ <Handle type="target" position={Position.Top} style={{ background: FINCEPT.ORANGE }} />+ <Handle type="source" position={Position.Bottom} style={{ background: FINCEPT.ORANGE }} />+ <Handle type="source" position={Position.Left} style={{ background: FINCEPT.ORANGE }} />+ <Handle type="source" position={Position.Right} style={{ background: FINCEPT.ORANGE }} />++ {/* Header */}+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>+ <div>+ <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.ORANGE }}>{c.ticker}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.WHITE }}>{c.name}</div>+ </div>+ {sigColor && (+ <div style={{ padding: '3px 8px', backgroundColor: sigColor.bg, border: `1px solid ${sigColor.border}`, borderRadius: '2px' }}>+ <div style={{ fontSize: '8px', fontWeight: 700, color: sigColor.text }}>{v!.action}</div>+ </div>+ )}+ </div>++ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '10px' }}>{c.sector} | {c.industry}</div>++ {/* Key Metrics Grid */}+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '6px', marginBottom: '10px' }}>+ <Metric label="MKT CAP" value={fmtMoney(c.market_cap)} />+ <Metric label="PRICE" value={c.current_price ? `$${c.current_price.toFixed(2)}` : 'N/A'} />+ <Metric label="P/E" value={c.pe_ratio ? c.pe_ratio.toFixed(1) : 'N/A'} />+ <Metric label="GROWTH" value={c.revenue_growth ? `${(c.revenue_growth * 100).toFixed(1)}%` : 'N/A'} color={c.revenue_growth > 0 ? FINCEPT.GREEN : FINCEPT.RED} />+ <Metric label="MARGIN" value={c.profit_margins ? `${(c.profit_margins * 100).toFixed(1)}%` : 'N/A'} />+ <Metric label="ROE" value={c.roe ? `${(c.roe * 100).toFixed(1)}%` : 'N/A'} />+ </div>++ {/* Ownership Bar */}+ {(c.insider_percent > 0 || c.institutional_percent > 0) && (+ <div style={{ marginBottom: '8px' }}>+ <div style={{ fontSize: '7px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '3px' }}>OWNERSHIP</div>+ <div style={{ display: 'flex', height: '4px', borderRadius: '2px', overflow: 'hidden', backgroundColor: FINCEPT.BORDER }}>+ <div style={{ width: `${c.insider_percent}%`, backgroundColor: FINCEPT.CYAN }} />+ <div style={{ width: `${c.institutional_percent}%`, backgroundColor: FINCEPT.GREEN }} />+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '2px' }}>+ <span style={{ fontSize: '7px', color: FINCEPT.CYAN }}>INS {c.insider_percent.toFixed(1)}%</span>+ <span style={{ fontSize: '7px', color: FINCEPT.GREEN }}>INST {c.institutional_percent.toFixed(1)}%</span>+ </div>+ </div>+ )}++ {/* Analyst */}+ {c.recommendation && c.recommendation !== 'N/A' && (+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY }}>ANALYST: <span style={{ color: FINCEPT.YELLOW, fontWeight: 700 }}>{c.recommendation.toUpperCase()}</span></span>+ {c.target_price > 0 && <span style={{ fontSize: '8px', color: FINCEPT.CYAN }}>TARGET ${c.target_price.toFixed(0)}</span>}+ </div>+ )}+ </div>+ );+};++const Metric: React.FC<{ label: string; value: string; color?: string }> = ({ label, value, color }) => (+ <div>+ <div style={{ fontSize: '7px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.3px' }}>{label}</div>+ <div style={{ fontSize: '10px', fontWeight: 700, color: color || FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace' }}>{value}</div>+ </div>+);++export default memo(CompanyNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/EventNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/EventNode.tsxnew file mode 100644index 000000000..bca385afd--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/EventNode.tsx@@ -0,0 +1,38 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT } from '../../constants';++interface Props { data: GraphNodeData; selected?: boolean; }++const CATEGORY_LABELS: Record<string, string> = {+ earnings: 'EARNINGS',+ management: 'MGMT',+ merger: 'M&A',+ restructuring: 'RESTRUCTURE',+ governance: 'GOVERNANCE',+ other: '8-K',+};++const EventNode: React.FC<Props> = ({ data, selected }) => {+ const ev = data.event;+ if (!ev) return null;++ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1.5px solid ${selected ? FINCEPT.WHITE : FINCEPT.RED}`, borderRadius: '2px', padding: '8px 12px', width: '220px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <Handle type="target" position={Position.Left} style={{ background: FINCEPT.RED }} />++ <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>+ <div style={{ padding: '2px 5px', backgroundColor: `${FINCEPT.RED}20`, borderRadius: '2px' }}>+ <span style={{ fontSize: '7px', fontWeight: 700, color: FINCEPT.RED }}>{CATEGORY_LABELS[ev.category] || ev.form}</span>+ </div>+ <span style={{ fontSize: '7px', color: FINCEPT.MUTED }}>{ev.filing_date}</span>+ </div>+ <div style={{ fontSize: '8px', color: FINCEPT.WHITE, lineHeight: 1.3 }}>+ {ev.description.length > 60 ? ev.description.slice(0, 60) + '...' : ev.description}+ </div>+ </div>+ );+};++export default memo(EventNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/FundFamilyNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/FundFamilyNode.tsxnew file mode 100644index 000000000..9412b4e7e--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/FundFamilyNode.tsx@@ -0,0 +1,41 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT } from '../../constants';++interface Props { data: GraphNodeData; selected?: boolean; }++const FundFamilyNode: React.FC<Props> = ({ data, selected }) => {+ const f = data.fundFamily;+ if (!f) return null;++ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1.5px solid ${selected ? FINCEPT.WHITE : FINCEPT.PURPLE}`, borderRadius: '2px', padding: '10px 12px', width: '240px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <Handle type="source" position={Position.Right} style={{ background: FINCEPT.PURPLE }} />++ <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.PURPLE, marginBottom: '6px' }}>{f.name}</div>++ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>+ <div>+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>TOTAL %</div>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.CYAN }}>{f.total_percentage.toFixed(2)}%</div>+ </div>+ <div style={{ textAlign: 'right' }}>+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>VALUE</div>+ <div style={{ fontSize: '9px', color: FINCEPT.WHITE }}>{f.total_value >= 1e9 ? `$${(f.total_value / 1e9).toFixed(1)}B` : `$${(f.total_value / 1e6).toFixed(0)}M`}</div>+ </div>+ </div>++ {f.funds.length > 1 && (+ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, paddingTop: '6px' }}>+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY, marginBottom: '3px' }}>FUNDS ({f.funds.length})</div>+ {f.funds.slice(0, 3).map((fund, i) => (+ <div key={i} style={{ fontSize: '8px', color: FINCEPT.MUTED, marginBottom: '1px' }}>{fund.name} ({fund.percentage.toFixed(1)}%)</div>+ ))}+ </div>+ )}+ </div>+ );+};++export default memo(FundFamilyNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/InsiderNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/InsiderNode.tsxnew file mode 100644index 000000000..0ce06d8ec--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/InsiderNode.tsx@@ -0,0 +1,33 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT } from '../../constants';++interface Props { data: GraphNodeData; selected?: boolean; }++const InsiderNode: React.FC<Props> = ({ data, selected }) => {+ const ins = data.insider;+ if (!ins) return null;++ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1.5px solid ${selected ? FINCEPT.WHITE : FINCEPT.CYAN}`, borderRadius: '2px', padding: '8px 12px', width: '220px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <Handle type="source" position={Position.Right} style={{ background: FINCEPT.CYAN }} />++ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.CYAN, marginBottom: '2px' }}>{ins.name}</div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '6px' }}>{ins.title}</div>++ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ {ins.last_transaction_type && (+ <div style={{ padding: '2px 6px', backgroundColor: ins.last_transaction_type === 'buy' ? `${FINCEPT.GREEN}20` : `${FINCEPT.RED}20`, borderRadius: '2px' }}>+ <span style={{ fontSize: '7px', fontWeight: 700, color: ins.last_transaction_type === 'buy' ? FINCEPT.GREEN : FINCEPT.RED }}>{ins.last_transaction_type.toUpperCase()}</span>+ </div>+ )}+ {ins.last_transaction_date && (+ <span style={{ fontSize: '7px', color: FINCEPT.MUTED }}>{ins.last_transaction_date}</span>+ )}+ </div>+ </div>+ );+};++export default memo(InsiderNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/InstitutionalHolderNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/InstitutionalHolderNode.tsxnew file mode 100644index 000000000..1eec629ea--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/InstitutionalHolderNode.tsx@@ -0,0 +1,31 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT } from '../../constants';++interface Props { data: GraphNodeData; selected?: boolean; }++const InstitutionalHolderNode: React.FC<Props> = ({ data, selected }) => {+ const h = data.holder;+ if (!h) return null;++ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1.5px solid ${selected ? FINCEPT.WHITE : FINCEPT.GREEN}`, borderRadius: '2px', padding: '8px 12px', width: '200px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <Handle type="source" position={Position.Right} style={{ background: FINCEPT.GREEN }} />++ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GREEN, marginBottom: '4px' }}>{h.name}</div>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>+ <div>+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>OWNERSHIP</div>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.CYAN }}>{h.percentage.toFixed(2)}%</div>+ </div>+ <div style={{ textAlign: 'right' }}>+ <div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>VALUE</div>+ <div style={{ fontSize: '9px', color: FINCEPT.WHITE }}>{h.value >= 1e9 ? `$${(h.value / 1e9).toFixed(1)}B` : h.value >= 1e6 ? `$${(h.value / 1e6).toFixed(0)}M` : 'N/A'}</div>+ </div>+ </div>+ </div>+ );+};++export default memo(InstitutionalHolderNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/MetricsClusterNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/MetricsClusterNode.tsxnew file mode 100644index 000000000..1e4875089--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/MetricsClusterNode.tsx@@ -0,0 +1,62 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT } from '../../constants';++interface Props { data: GraphNodeData; selected?: boolean; }++const TYPE_LABELS: Record<string, string> = {+ financials: 'FINANCIALS',+ valuation: 'VALUATION',+ ownership: 'OWNERSHIP',+ balance_sheet: 'BALANCE SHEET',+};++const formatValue = (val: number | string): string => {+ if (typeof val === 'string') return val;+ if (Math.abs(val) >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;+ if (Math.abs(val) >= 1e9) return `$${(val / 1e9).toFixed(1)}B`;+ if (Math.abs(val) >= 1e6) return `$${(val / 1e6).toFixed(0)}M`;+ if (Math.abs(val) < 1 && val !== 0) return `${(val * 100).toFixed(1)}%`;+ return val.toFixed(2);+};++const MetricsClusterNode: React.FC<Props> = ({ data, selected }) => {+ const metrics = data.metrics;+ const metricsType = data.metricsType || 'financials';+ if (!metrics) return null;++ const title = TYPE_LABELS[metricsType] || 'METRICS';+ const entries = Object.entries(metrics).filter(([, v]) => v !== 0 && v !== '' && v !== 'N/A');++ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1.5px solid ${selected ? FINCEPT.WHITE : FINCEPT.GRAY}`, borderRadius: '2px', padding: '10px 12px', width: '240px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <Handle type="target" position={Position.Left} style={{ background: FINCEPT.GRAY }} />++ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '8px', paddingBottom: '6px', borderBottom: `1px solid ${FINCEPT.BORDER}`, letterSpacing: '0.5px' }}>+ {title}+ </div>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>+ {entries.slice(0, 8).map(([key, value]) => (+ <div key={key} style={{ padding: '2px 0' }}>+ <div style={{ fontSize: '7px', color: FINCEPT.MUTED, textTransform: 'uppercase', letterSpacing: '0.3px' }}>+ {key.replace(/_/g, ' ')}+ </div>+ <div style={{ fontSize: '9px', fontWeight: 700, color: typeof value === 'number' && value < 0 ? FINCEPT.RED : FINCEPT.CYAN }}>+ {formatValue(value)}+ </div>+ </div>+ ))}+ </div>++ {entries.length > 8 && (+ <div style={{ marginTop: '6px', fontSize: '7px', color: FINCEPT.MUTED, textAlign: 'center' }}>+ +{entries.length - 8} MORE+ </div>+ )}+ </div>+ );+};++export default memo(MetricsClusterNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/PeerNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/PeerNode.tsxnew file mode 100644index 000000000..c736301bd--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/PeerNode.tsx@@ -0,0 +1,39 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT, SIGNAL_COLORS } from '../../constants';++interface PeerNodeProps { data: GraphNodeData; selected?: boolean; }++const PeerNode: React.FC<PeerNodeProps> = ({ data, selected }) => {+ const p = data.peer;+ const v = data.peerValuation;+ if (!p) return null;++ const sigColor = v ? SIGNAL_COLORS[v.action] : null;++ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1.5px solid ${selected ? FINCEPT.WHITE : FINCEPT.BLUE}`, borderRadius: '2px', padding: '10px 12px', width: '240px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <Handle type="target" position={Position.Left} style={{ background: FINCEPT.BLUE }} />++ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.BLUE }}>{p.ticker}</div>+ {sigColor && (+ <div style={{ padding: '2px 6px', backgroundColor: sigColor.bg, borderRadius: '2px' }}>+ <span style={{ fontSize: '7px', fontWeight: 700, color: sigColor.text }}>{v!.action}</span>+ </div>+ )}+ </div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginBottom: '8px' }}>{p.name}</div>++ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px' }}>+ <div><div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>MKT CAP</div><div style={{ fontSize: '9px', color: FINCEPT.CYAN }}>{p.market_cap >= 1e9 ? `$${(p.market_cap / 1e9).toFixed(0)}B` : p.market_cap >= 1e6 ? `$${(p.market_cap / 1e6).toFixed(0)}M` : 'N/A'}</div></div>+ <div><div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>P/E</div><div style={{ fontSize: '9px', color: FINCEPT.CYAN }}>{p.pe_ratio ? p.pe_ratio.toFixed(1) : 'N/A'}</div></div>+ <div><div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>P/B</div><div style={{ fontSize: '9px', color: FINCEPT.CYAN }}>{p.price_to_book ? p.price_to_book.toFixed(1) : 'N/A'}</div></div>+ <div><div style={{ fontSize: '7px', color: FINCEPT.GRAY }}>GROWTH</div><div style={{ fontSize: '9px', color: p.revenue_growth > 0 ? FINCEPT.GREEN : FINCEPT.RED }}>{p.revenue_growth ? `${(p.revenue_growth * 100).toFixed(1)}%` : 'N/A'}</div></div>+ </div>+ </div>+ );+};++export default memo(PeerNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/SupplyChainNode.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/SupplyChainNode.tsxnew file mode 100644index 000000000..e04dadb65--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/nodes/SupplyChainNode.tsx@@ -0,0 +1,38 @@+import React, { memo } from 'react';+import { Handle, Position } from 'reactflow';+import type { GraphNodeData } from '../../types';+import { FINCEPT } from '../../constants';++interface Props { data: GraphNodeData; selected?: boolean; }++const SupplyChainNode: React.FC<Props> = ({ data, selected }) => {+ return (+ <div style={{ backgroundColor: FINCEPT.PANEL_BG, border: `1.5px solid ${selected ? FINCEPT.WHITE : FINCEPT.YELLOW}`, borderRadius: '2px', padding: '10px 12px', width: '240px', fontFamily: '"IBM Plex Mono", monospace' }}>+ <Handle type="target" position={Position.Left} style={{ background: FINCEPT.YELLOW }} />+ <Handle type="source" position={Position.Right} style={{ background: FINCEPT.YELLOW }} />++ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>+ <div style={{ padding: '2px 6px', backgroundColor: `${FINCEPT.YELLOW}20`, borderRadius: '2px' }}>+ <span style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.YELLOW }}>SC</span>+ </div>+ <div>+ <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE }}>{data.label}</div>+ <div style={{ fontSize: '7px', color: FINCEPT.MUTED, letterSpacing: '0.5px' }}>SUPPLY CHAIN</div>+ </div>+ </div>++ {data.metrics && (+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px', borderTop: `1px solid ${FINCEPT.BORDER}`, paddingTop: '6px' }}>+ {Object.entries(data.metrics).slice(0, 4).map(([key, val]) => (+ <div key={key}>+ <div style={{ fontSize: '7px', color: FINCEPT.MUTED, textTransform: 'uppercase' }}>{key.replace(/_/g, ' ')}</div>+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.CYAN }}>{String(val)}</div>+ </div>+ ))}+ </div>+ )}+ </div>+ );+};++export default memo(SupplyChainNode);diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/panels/DetailPanel.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/panels/DetailPanel.tsxnew file mode 100644index 000000000..3042bfdea--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/panels/DetailPanel.tsx@@ -0,0 +1,186 @@+import React from 'react';+import type { GraphNodeData } from '../../types';+import { FINCEPT, SIGNAL_COLORS } from '../../constants';++interface DetailPanelProps {+ nodeData: GraphNodeData | null;+ onClose: () => void;+}++function fmt(val: number | undefined, type: 'money' | 'pct' | 'num' = 'num'): string {+ if (val === undefined || val === null) return 'N/A';+ if (type === 'money') {+ if (Math.abs(val) >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;+ if (Math.abs(val) >= 1e9) return `$${(val / 1e9).toFixed(2)}B`;+ if (Math.abs(val) >= 1e6) return `$${(val / 1e6).toFixed(1)}M`;+ return `$${val.toLocaleString()}`;+ }+ if (type === 'pct') return `${(val * 100).toFixed(1)}%`;+ if (Math.abs(val) < 1 && val !== 0) return `${(val * 100).toFixed(1)}%`;+ return val.toFixed(2);+}++const DetailPanel: React.FC<DetailPanelProps> = ({ nodeData, onClose }) => {+ if (!nodeData) return null;++ const renderContent = () => {+ if (nodeData.category === 'company' && nodeData.company) {+ const c = nodeData.company;+ const v = nodeData.valuation;+ return (+ <>+ <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '4px' }}>{c.ticker}</div>+ <div style={{ fontSize: '10px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{c.name}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '12px' }}>{c.sector} | {c.industry}</div>++ {v && (+ <div style={{ padding: '6px 8px', backgroundColor: SIGNAL_COLORS[v.action].bg, border: `1px solid ${SIGNAL_COLORS[v.action].border}`, borderRadius: '2px', marginBottom: '12px' }}>+ <div style={{ fontSize: '9px', fontWeight: 700, color: SIGNAL_COLORS[v.action].text }}>{v.status.replace(/_/g, ' ')} | {v.action}</div>+ <div style={{ fontSize: '8px', color: FINCEPT.GRAY, marginTop: '2px' }}>Confidence: {v.confidence} | Score: {v.score.toFixed(1)}</div>+ </div>+ )}++ <Section title="MARKET DATA">+ <Row label="MARKET CAP" value={fmt(c.market_cap, 'money')} />+ <Row label="PRICE" value={`$${c.current_price.toFixed(2)}`} />+ <Row label="P/E" value={c.pe_ratio ? c.pe_ratio.toFixed(1) : 'N/A'} />+ <Row label="FORWARD P/E" value={c.forward_pe ? c.forward_pe.toFixed(1) : 'N/A'} />+ <Row label="P/B" value={c.price_to_book ? c.price_to_book.toFixed(1) : 'N/A'} />+ <Row label="PEG" value={c.peg_ratio ? c.peg_ratio.toFixed(2) : 'N/A'} />+ </Section>+ <Section title="PROFITABILITY">+ <Row label="PROFIT MARGIN" value={fmt(c.profit_margins, 'pct')} />+ <Row label="OPERATING MARGIN" value={fmt(c.operating_margins, 'pct')} />+ <Row label="ROE" value={fmt(c.roe, 'pct')} />+ <Row label="ROA" value={fmt(c.roa, 'pct')} />+ </Section>+ <Section title="GROWTH">+ <Row label="REVENUE GROWTH" value={fmt(c.revenue_growth, 'pct')} color={c.revenue_growth > 0 ? FINCEPT.GREEN : FINCEPT.RED} />+ <Row label="EARNINGS GROWTH" value={fmt(c.earnings_growth, 'pct')} color={c.earnings_growth > 0 ? FINCEPT.GREEN : FINCEPT.RED} />+ </Section>+ <Section title="OWNERSHIP">+ <Row label="INSIDERS" value={`${c.insider_percent.toFixed(1)}%`} />+ <Row label="INSTITUTIONS" value={`${c.institutional_percent.toFixed(1)}%`} />+ </Section>+ {nodeData.executives && nodeData.executives.length > 0 && (+ <Section title="EXECUTIVES">+ {nodeData.executives.slice(0, 5).map((ex, i) => (+ <Row key={i} label={ex.role} value={ex.name} />+ ))}+ </Section>+ )}+ </>+ );+ }++ if (nodeData.category === 'peer' && nodeData.peer) {+ const p = nodeData.peer;+ const v = nodeData.peerValuation;+ return (+ <>+ <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.BLUE, marginBottom: '4px' }}>{p.ticker}</div>+ <div style={{ fontSize: '10px', color: FINCEPT.WHITE, marginBottom: '12px' }}>{p.name}</div>+ {v && (+ <div style={{ padding: '6px 8px', backgroundColor: SIGNAL_COLORS[v.action].bg, border: `1px solid ${SIGNAL_COLORS[v.action].border}`, borderRadius: '2px', marginBottom: '12px' }}>+ <div style={{ fontSize: '9px', fontWeight: 700, color: SIGNAL_COLORS[v.action].text }}>{v.action} | Score: {v.score.toFixed(1)}</div>+ </div>+ )}+ <Section title="METRICS">+ <Row label="MARKET CAP" value={fmt(p.market_cap, 'money')} />+ <Row label="P/E" value={p.pe_ratio ? p.pe_ratio.toFixed(1) : 'N/A'} />+ <Row label="P/B" value={p.price_to_book ? p.price_to_book.toFixed(1) : 'N/A'} />+ <Row label="ROE" value={fmt(p.roe, 'pct')} />+ <Row label="GROWTH" value={fmt(p.revenue_growth, 'pct')} color={p.revenue_growth > 0 ? FINCEPT.GREEN : FINCEPT.RED} />+ </Section>+ </>+ );+ }++ if (nodeData.category === 'institutional' && nodeData.holder) {+ const h = nodeData.holder;+ return (+ <>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.GREEN, marginBottom: '12px' }}>{h.name}</div>+ <Section title="HOLDINGS">+ <Row label="OWNERSHIP" value={`${h.percentage.toFixed(2)}%`} />+ <Row label="SHARES" value={h.shares.toLocaleString()} />+ <Row label="VALUE" value={fmt(h.value, 'money')} />+ </Section>+ </>+ );+ }++ if (nodeData.category === 'insider' && nodeData.insider) {+ const ins = nodeData.insider;+ return (+ <>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.CYAN, marginBottom: '4px' }}>{ins.name}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '12px' }}>{ins.title}</div>+ <Section title="ACTIVITY">+ <Row label="SHARES" value={ins.shares ? ins.shares.toLocaleString() : 'N/A'} />+ {ins.last_transaction_date && <Row label="LAST TX" value={ins.last_transaction_date} />}+ {ins.last_transaction_type && <Row label="TYPE" value={ins.last_transaction_type.toUpperCase()} color={ins.last_transaction_type === 'buy' ? FINCEPT.GREEN : FINCEPT.RED} />}+ </Section>+ </>+ );+ }++ if (nodeData.category === 'event' && nodeData.event) {+ const ev = nodeData.event;+ return (+ <>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.RED, marginBottom: '4px' }}>{ev.form}</div>+ <div style={{ fontSize: '9px', color: FINCEPT.WHITE, marginBottom: '8px' }}>{ev.description}</div>+ <Section title="DETAILS">+ <Row label="DATE" value={ev.filing_date} />+ <Row label="CATEGORY" value={ev.category.toUpperCase()} />+ {ev.items.length > 0 && ev.items.map((item, i) => <Row key={i} label={`ITEM ${i + 1}`} value={item} />)}+ </Section>+ </>+ );+ }++ if (nodeData.category === 'metrics' && nodeData.metrics) {+ return (+ <>+ <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.CYAN, marginBottom: '12px' }}>{nodeData.label}</div>+ <Section title="DATA">+ {Object.entries(nodeData.metrics).filter(([, v]) => v !== 0 && v !== '').map(([key, val]) => (+ <Row key={key} label={key.replace(/_/g, ' ').toUpperCase()} value={typeof val === 'number' ? fmt(val) : String(val)} />+ ))}+ </Section>+ </>+ );+ }++ return <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>No details available</div>;+ };++ return (+ <div style={{ position: 'absolute', top: '48px', right: 0, bottom: '28px', width: '300px', backgroundColor: FINCEPT.PANEL_BG, borderLeft: `1px solid ${FINCEPT.BORDER}`, zIndex: 80, overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>+ <div style={{ padding: '12px', backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>+ <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>DETAILS</span>+ <button onClick={onClose} style={{ background: 'none', border: 'none', color: FINCEPT.GRAY, cursor: 'pointer', fontSize: '14px', padding: '2px 6px' }}>×</button>+ </div>+ <div style={{ padding: '12px', flex: 1 }}>+ {renderContent()}+ </div>+ </div>+ );+};++const Section: React.FC<{ title: string; children: React.ReactNode }> = ({ title, children }) => (+ <div style={{ marginBottom: '12px' }}>+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '6px', paddingBottom: '4px', borderBottom: `1px solid ${FINCEPT.BORDER}` }}>{title}</div>+ {children}+ </div>+);++const Row: React.FC<{ label: string; value: string; color?: string }> = ({ label, value, color }) => (+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '2px 0' }}>+ <span style={{ fontSize: '8px', color: FINCEPT.GRAY, fontWeight: 700, letterSpacing: '0.3px' }}>{label}</span>+ <span style={{ fontSize: '9px', color: color || FINCEPT.CYAN, fontFamily: '"IBM Plex Mono", monospace' }}>{value}</span>+ </div>+);++export default DetailPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/components/panels/FilterPanel.tsx b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/panels/FilterPanel.tsxnew file mode 100644index 000000000..2e4c5c0e2--- /dev/null+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/components/panels/FilterPanel.tsx@@ -0,0 +1,72 @@+import React from 'react';+import type { FilterState } from '../../types';+import { FINCEPT, NODE_COLORS } from '../../constants';++interface FilterPanelProps {+ filters: FilterState;+ onChange: (filters: FilterState) => void;+ nodeCounts: Record<string, number>;+}++const TOGGLES: { key: keyof FilterState; label: string; colorKey: keyof typeof NODE_COLORS }[] = [+ { key: 'showPeers', label: 'PEERS', colorKey: 'peer' },+ { key: 'showInstitutional', label: 'INSTITUTIONAL', colorKey: 'institutional' },+ { key: 'showFundFamilies', label: 'FUND FAMILIES', colorKey: 'fund_family' },+ { key: 'showInsiders', label: 'INSIDERS', colorKey: 'insider' },+ { key: 'showEvents', label: 'EVENTS', colorKey: 'event' },+ { key: 'showSupplyChain', label: 'SUPPLY CHAIN', colorKey: 'supply_chain' },+ { key: 'showSegments', label: 'SEGMENTS', colorKey: 'segment' },+ { key: 'showDebtHolders', label: 'DEBT/CREDIT', colorKey: 'debt_holder' },+ { key: 'showMetrics', label: 'METRICS', colorKey: 'metrics' },+];++const FilterPanel: React.FC<FilterPanelProps> = ({ filters, onChange, nodeCounts }) => {+ const toggle = (key: keyof FilterState) => {+ onChange({ ...filters, [key]: !filters[key] });+ };++ return (+ <div style={{ position: 'absolute', top: '48px', left: 0, width: '200px', backgroundColor: FINCEPT.PANEL_BG, border: `1px solid ${FINCEPT.BORDER}`, borderTop: 'none', zIndex: 90, padding: '12px' }}>+ <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '8px' }}>LAYERS</div>++ {TOGGLES.map(({ key, label, colorKey }) => {+ const countKey = colorKey;+ return (+ <div key={key} style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px', cursor: 'pointer', padding: '4px 6px', borderRadius: '2px', backgroundColor: filters[key] ? `${NODE_COLORS[colorKey].border}10` : 'transparent', transition: 'all 0.2s' }} onClick={() => toggle(key)}>+ <div style={{ width: '10px', height: '10px', borderRadius: '2px', border: `1.5px solid ${NODE_COLORS[colorKey].border}`, backgroundColor: filters[key] ? NODE_COLORS[colorKey].border : 'transparent' }} />+ <span style={{ fontSize: '9px', fontWeight: 700, color: filters[key] ? FINCEPT.WHITE : FINCEPT.MUTED, flex: 1 }}>{label}</span>+ <span style={{ fontSize: '8px', color: FINCEPT.MUTED }}>{nodeCounts[countKey] || 0}</span>+ </div>+ );+ })}++ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, marginTop: '8px', paddingTop: '8px' }}>+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '6px' }}>MIN OWNERSHIP</div>+ <input+ type="range"+ min={0} max={10} step={0.5}+ value={filters.minOwnership}+ onChange={(e) => onChange({ ...filters, minOwnership: parseFloat(e.target.value) })}+ style={{ width: '100%', accentColor: FINCEPT.ORANGE }}+ />+ <div style={{ fontSize: '8px', color: FINCEPT.CYAN, textAlign: 'center' }}>{filters.minOwnership.toFixed(1)}%</div>+ </div>++ <div style={{ borderTop: `1px solid ${FINCEPT.BORDER}`, marginTop: '8px', paddingTop: '8px' }}>+ <div style={{ fontSize: '8px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px', marginBottom: '6px' }}>PEER FILTER</div>+ {(['all', 'undervalued', 'overvalued'] as const).map(f => (+ <div key={f} style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px', cursor: 'pointer', padding: '2px 4px' }} onClick={() => onChange({ ...filters, peerFilter: f })}>+ <div style={{ width: '8px', height: '8px', borderRadius: '50%', border: `1.5px solid ${FINCEPT.ORANGE}`, backgroundColor: filters.peerFilter === f ? FINCEPT.ORANGE : 'transparent' }} />+ <span style={{ fontSize: '8px', color: filters.peerFilter === f ? FINCEPT.WHITE : FINCEPT.MUTED, fontWeight: 700, textTransform: 'uppercase' }}>{f}</span>+ </div>+ ))}+ </div>++ <button onClick={() => onChange({ showInstitutional: true, showInsiders: true, showPeers: true, showEvents: true, showMetrics: true, showFundFamilies: true, showSupplyChain: true, showSegments: true, showDebtHolders: true, minOwnership: 0, peerFilter: 'all', eventTypes: [] })} style={{ width: '100%', marginTop: '12px', padding: '6px', backgroundColor: 'transparent', border: `1px solid ${FINCEPT.BORDER}`, color: FINCEPT.GRAY, fontSize: '8px', fontWeight: 700, cursor: 'pointer', borderRadius: '2px', letterSpacing: '0.5px' }}>+ RESET+ </button>+ </div>+ );+};++export default FilterPanel;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/constants.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/constants.tsindex 7bbe2d3ce..51ead76d4 100644--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/constants.ts+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/constants.ts@@ -1,60 +1,236 @@-// Constants for RelationshipMapTab-import { MarkerType } from 'reactflow';-import type { DataNodeType } from './types';--// Node type colors-export const NODE_TYPE_COLORS: Record<DataNodeType, string> = {- events: '#ef4444',- filings: '#3b82f6',- financials: '#10b981',- balance: '#f97316', // Will be overridden by theme accent- analysts: '#8b5cf6',- ownership: '#f59e0b',- valuation: '#ec4899',- info: '#14b8a6',- executives: '#10b981',-};--// Node positions for the graph layout-export const NODE_POSITIONS = {- company: { x: 600, y: 350 },- events: { x: 50, y: 50 },- filings: { x: 200, y: 80 },- financials: { x: 500, y: 50 },- balance: { x: 850, y: 80 },- analysts: { x: 1100, y: 350 },- ownership: { x: 850, y: 620 },- valuation: { x: 450, y: 650 },- info: { x: 100, y: 620 },- executives: { x: 50, y: 350 },-} as const;--// Edge configuration-export const EDGE_CONFIG = {- type: 'smoothstep' as const,- animated: true,- strokeWidth: 2,- markerType: MarkerType.ArrowClosed,-};--// Cache duration in milliseconds (5 minutes)-export const CACHE_DURATION = 5 * 60 * 1000;--// Default ticker-export const DEFAULT_TICKER = 'AAPL';--// ReactFlow configuration-export const FLOW_CONFIG = {- minZoom: 0.3,- maxZoom: 2,- defaultViewport: { x: 0, y: 0, zoom: 0.75 },- fitView: true,-};--// Background configuration-export const BACKGROUND_CONFIG = {- gap: 20,- size: 1,- color: '#1a1a1a',- style: { background: '#0a0a0a' },-};+// Relationship Map - Configuration Constants+// Following FINCEPT UI Design System++// ============================================================================+// FINCEPT DESIGN SYSTEM COLORS+// ============================================================================++export const FINCEPT = {+ ORANGE: '#FF8800',+ WHITE: '#FFFFFF',+ RED: '#FF3B3B',+ GREEN: '#00D66F',+ GRAY: '#787878',+ DARK_BG: '#000000',+ PANEL_BG: '#0F0F0F',+ HEADER_BG: '#1A1A1A',+ BORDER: '#2A2A2A',+ HOVER: '#1F1F1F',+ MUTED: '#4A4A4A',+ CYAN: '#00E5FF',+ YELLOW: '#FFD700',+ BLUE: '#0088FF',+ PURPLE: '#9D4EDD',+} as const;++// ============================================================================+// TIMEOUT CONFIGURATION+// ============================================================================++export const TIMEOUTS = {+ EDGAR_COMPANY: 15000,+ EDGAR_FILINGS: 15000,+ EDGAR_PROXY: 20000,+ EDGAR_EVENTS: 15000,+ EDGAR_INSTITUTIONAL: 20000,+ EDGAR_INSIDER: 15000,+ YFINANCE_INFO: 10000,+ YFINANCE_PEERS: 12000,+ TOTAL_MAX: 30000,+} as const;++// ============================================================================+// CACHE CONFIGURATION+// ============================================================================++export const CACHE_TTL = {+ REALTIME: 5 * 60 * 1000,+ DAILY: 24 * 60 * 60 * 1000,+ WEEKLY: 7 * 24 * 60 * 60 * 1000,+ QUARTERLY: 30 * 24 * 60 * 60 * 1000,+} as const;++// ============================================================================+// NODE DIMENSIONS+// ============================================================================++export const NODE_SIZES = {+ company: { width: 380, height: 220 },+ peer: { width: 240, height: 140 },+ institutional: { width: 200, height: 90 },+ fund_family: { width: 240, height: 150 },+ insider: { width: 220, height: 100 },+ event: { width: 220, height: 90 },+ supply_chain: { width: 240, height: 110 },+ segment: { width: 220, height: 100 },+ debt_holder: { width: 220, height: 90 },+ metrics: { width: 240, height: 140 },+} as const;++// ============================================================================+// LAYOUT CONFIGURATION+// ============================================================================++export const LAYOUT_CONFIG = {+ RINGS: {+ INSIDERS: 320,+ INSTITUTIONAL: 520,+ FUND_FAMILIES: 700,+ PEERS: 880,+ EVENTS: 1050,+ SUPPLY_CHAIN: 750,+ SEGMENTS: 400,+ DEBT_HOLDERS: 900,+ METRICS: 400,+ },+ FORCE: {+ CHARGE_STRENGTH: -800,+ LINK_DISTANCE: 250,+ CENTER_GRAVITY: 0.05,+ ITERATIONS: 300,+ COLLISION_RADIUS: 100,+ },+ TRANSITION_DURATION: 800,+} as const;++// ============================================================================+// NODE COLORS - FINCEPT DESIGN SYSTEM+// ============================================================================++export const NODE_COLORS = {+ company: {+ bg: `${FINCEPT.ORANGE}18`,+ border: FINCEPT.ORANGE,+ text: FINCEPT.WHITE,+ accent: FINCEPT.ORANGE,+ },+ peer: {+ bg: `${FINCEPT.BLUE}15`,+ border: FINCEPT.BLUE,+ text: FINCEPT.WHITE,+ accent: FINCEPT.BLUE,+ },+ institutional: {+ bg: `${FINCEPT.GREEN}15`,+ border: FINCEPT.GREEN,+ text: FINCEPT.WHITE,+ accent: FINCEPT.GREEN,+ },+ fund_family: {+ bg: `${FINCEPT.PURPLE}15`,+ border: FINCEPT.PURPLE,+ text: FINCEPT.WHITE,+ accent: FINCEPT.PURPLE,+ },+ insider: {+ bg: `${FINCEPT.CYAN}12`,+ border: FINCEPT.CYAN,+ text: FINCEPT.WHITE,+ accent: FINCEPT.CYAN,+ },+ event: {+ bg: `${FINCEPT.RED}12`,+ border: FINCEPT.RED,+ text: FINCEPT.WHITE,+ accent: FINCEPT.RED,+ },+ supply_chain: {+ bg: `${FINCEPT.YELLOW}12`,+ border: FINCEPT.YELLOW,+ text: FINCEPT.WHITE,+ accent: FINCEPT.YELLOW,+ },+ segment: {+ bg: `${FINCEPT.ORANGE}12`,+ border: FINCEPT.ORANGE,+ text: FINCEPT.WHITE,+ accent: FINCEPT.ORANGE,+ },+ debt_holder: {+ bg: `${FINCEPT.RED}10`,+ border: '#FF6B6B',+ text: FINCEPT.WHITE,+ accent: '#FF6B6B',+ },+ metrics: {+ bg: `${FINCEPT.GRAY}15`,+ border: FINCEPT.GRAY,+ text: FINCEPT.WHITE,+ accent: FINCEPT.CYAN,+ },+} as const;++// ============================================================================+// VALUATION SIGNAL COLORS+// ============================================================================++export const SIGNAL_COLORS = {+ BUY: { bg: `${FINCEPT.GREEN}25`, border: FINCEPT.GREEN, text: FINCEPT.GREEN },+ HOLD: { bg: `${FINCEPT.YELLOW}20`, border: FINCEPT.YELLOW, text: FINCEPT.YELLOW },+ SELL: { bg: `${FINCEPT.RED}25`, border: FINCEPT.RED, text: FINCEPT.RED },+} as const;++// ============================================================================+// EDGE STYLES+// ============================================================================++export const EDGE_STYLES = {+ ownership: { stroke: FINCEPT.GREEN, strokeWidth: 2 },+ peer: { stroke: FINCEPT.BLUE, strokeWidth: 1.5, strokeDasharray: '5 5' },+ supply_chain: { stroke: FINCEPT.YELLOW, strokeWidth: 2 },+ event: { stroke: FINCEPT.RED, strokeWidth: 1, strokeDasharray: '3 3' },+ segment: { stroke: FINCEPT.ORANGE, strokeWidth: 1.5, strokeDasharray: '4 4' },+ debt: { stroke: '#FF6B6B', strokeWidth: 1.5 },+ internal: { stroke: FINCEPT.MUTED, strokeWidth: 1 },+} as const;++// ============================================================================+// DATA LIMITS - TIERED CONFIGURATION+// ============================================================================++export const DATA_LIMITS = {+ MAX_INSTITUTIONAL_HOLDERS: 40,+ MAX_INSIDER_HOLDERS: 25,+ MAX_INSIDER_TRANSACTIONS: 30,+ MAX_PEERS: 15,+ MAX_EVENTS: 30,+ MAX_FILINGS: 20,+ MAX_FUND_FAMILIES: 15,+ MAX_SUPPLY_CHAIN: 20,+ MAX_SEGMENTS: 10,+ MAX_DEBT_HOLDERS: 10,+} as const;++// Preset configurations for user-selectable density levels+export const DENSITY_PRESETS = {+ minimal: {+ INSTITUTIONAL_HOLDERS: 10,+ INSIDER_HOLDERS: 5,+ PEERS: 6,+ EVENTS: 8,+ FUND_FAMILIES: 3,+ SUPPLY_CHAIN: 5,+ SEGMENTS: 3,+ DEBT_HOLDERS: 3,+ },+ standard: {+ INSTITUTIONAL_HOLDERS: 25,+ INSIDER_HOLDERS: 15,+ PEERS: 12,+ EVENTS: 20,+ FUND_FAMILIES: 8,+ SUPPLY_CHAIN: 12,+ SEGMENTS: 6,+ DEBT_HOLDERS: 6,+ },+ professional: {+ INSTITUTIONAL_HOLDERS: 40,+ INSIDER_HOLDERS: 25,+ PEERS: 15,+ EVENTS: 30,+ FUND_FAMILIES: 15,+ SUPPLY_CHAIN: 20,+ SEGMENTS: 10,+ DEBT_HOLDERS: 10,+ },+} as const;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/hooks/useRelationshipData.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/hooks/useRelationshipData.tssimilarity index 89%rename from fincept-terminal-desktop/src/components/tabs/relationship-map-v2/hooks/useRelationshipData.tsrename to fincept-terminal-desktop/src/components/tabs/relationship-map/hooks/useRelationshipData.tsindex 09aa73970..3877e67d9 100644--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/hooks/useRelationshipData.ts+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/hooks/useRelationshipData.ts@@ -1,7 +1,7 @@-// Progressive Data Loading Hook for Relationship Map V2+// Progressive Data Loading Hook for Relationship Mapimport { useState, useCallback, useRef } from 'react';-import { relationshipMapServiceV2 } from '../../../../services/geopolitics/relationshipMapServiceV2';+import { relationshipMapService } from '../../../../services/geopolitics/relationshipMapService';import type { RelationshipMapDataV2, LoadingPhase } from '../types';interface UseRelationshipDataReturn {@@ -34,7 +34,7 @@ export function useRelationshipData(): UseRelationshipDataReturn {setPhase({ phase: 'company', progress: 0, message: 'Starting...' });try {- const result = await relationshipMapServiceV2.getRelationshipMap(+ const result = await relationshipMapService.getRelationshipMap(ticker,(loadingPhase) => {if (abortRef.current) return;diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/index.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/index.tsindex 0cd1e3ef5..1f683182b 100644--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/index.ts+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/index.ts@@ -1,5 +1 @@export { default } from './RelationshipMapTab';-export { default as RelationshipMapTab } from './RelationshipMapTab';-export * from './types';-export * from './constants';-export * from './utils';diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/types.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/types.tsindex 08b811526..f77633af8 100644--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/types.ts+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/types.ts@@ -1,131 +1,355 @@-// Type definitions for RelationshipMapTab+// Relationship Map V2 - Type Definitions+// Multi-layer corporate intelligence visualization-export interface NodeColors {- accent: string;- text: string;- textMuted: string;- success: string;- alert: string;- panel: string;-}+// ============================================================================+// DATA SOURCE TYPES+// ============================================================================-export interface CompanyNodeData {- name: string;+export interface CompanyInfoV2 {ticker: string;+ name: string;+ cik: string;industry: string;+ sic: string;sector: string;- cik: string;+ address: string;exchange: string;- employees?: number;- market_cap?: number;+ employees: number;+ website: string;+ description: string;+ market_cap: number;+ current_price: number;+ // Valuation metrics+ pe_ratio: number;+ forward_pe: number;+ price_to_book: number;+ price_to_sales: number;+ peg_ratio: number;+ enterprise_value: number;+ enterprise_to_revenue: number;+ // Profitability+ profit_margins: number;+ operating_margins: number;+ roe: number;+ roa: number;+ // Growth+ revenue_growth: number;+ earnings_growth: number;+ // Financials+ revenue: number;+ gross_profit: number;+ ebitda: number;+ free_cashflow: number;+ total_cash: number;+ total_debt: number;+ // Ownership+ insider_percent: number;+ institutional_percent: number;+ shares_outstanding: number;+ float_shares: number;+ // Analyst+ recommendation: string;+ target_price: number;+ analyst_count: number;}-export interface DataNodeItem {- label: string;- value: string;- description?: string;- url?: string;- allItems?: string[];+export interface InstitutionalHolder {+ name: string;+ shares: number;+ value: number;+ percentage: number;+ change_shares?: number;+ change_percent?: number;+ filing_date?: string;+ fund_family?: string;}-export type DataNodeType =- | 'events'- | 'filings'- | 'financials'- | 'balance'- | 'analysts'- | 'ownership'- | 'valuation'- | 'info'- | 'executives';+export interface FundFamily {+ name: string;+ total_shares: number;+ total_value: number;+ total_percentage: number;+ funds: InstitutionalHolder[];+ change_trend: 'increasing' | 'decreasing' | 'stable';+}-export interface DataNodeData {- type: DataNodeType;+export interface InsiderHolder {+ name: string;title: string;- items: DataNodeItem[];- colors: NodeColors;+ shares: number;+ value: number;+ percentage: number;+ last_transaction_date?: string;+ last_transaction_type?: 'buy' | 'sell' | 'option_exercise';}-export interface CompanyNodeProps {- data: CompanyNodeData & { colors: NodeColors };+export interface InsiderTransaction {+ name: string;+ title: string;+ transaction_type: 'buy' | 'sell' | 'option_exercise';+ shares: number;+ value: number;+ price: number;+ date: string;+ shares_remaining: number;}-export interface DataNodeProps {- data: DataNodeData;+export interface PeerCompany {+ ticker: string;+ name: string;+ market_cap: number;+ pe_ratio: number;+ price_to_book: number;+ price_to_sales: number;+ roe: number;+ revenue_growth: number;+ profit_margins: number;+ current_price: number;+ sector: string;+ industry: string;}-// Graph builder types-export interface GraphData {- company: CompanyNodeData;- corporate_events?: CorporateEventData[];- filings?: FilingData[];- financials?: FinancialsData;- balance_sheet?: BalanceSheetData;- analysts?: AnalystsData;- ownership?: OwnershipData;- valuation?: ValuationData;- executives?: ExecutiveData[];+export interface ValuationSignal {+ status: 'UNDERVALUED' | 'POTENTIALLY_UNDERVALUED' | 'FAIRLY_VALUED' | 'POTENTIALLY_OVERVALUED' | 'OVERVALUED';+ action: 'BUY' | 'HOLD' | 'SELL';+ confidence: 'HIGH' | 'MEDIUM' | 'LOW';+ score: number; // -3 to +3+ reasoning: string[];+ percentiles: {+ pe: number;+ pb: number;+ ps: number;+ roe: number;+ growth: number;+ };}-export interface CorporateEventData {- filing_date: string;- items?: string[];+export interface SupplyChainEntity {+ name: string;+ relationship: 'customer' | 'supplier' | 'partner';+ percentage_of_revenue?: number;+ source?: string;+}++export interface SegmentData {+ name: string;+ value: number;+ type: 'geographic' | 'business_unit' | 'product';+ period?: string;+}++export interface DebtHolder {+ name: string;+ type: 'bank_lender' | 'bond_trustee' | 'credit_facility';+ filing_date?: string;description?: string;+ source?: string;+}++export interface CorporateEventV2 {+ filing_date: string;+ period_of_report?: string;+ form: string;filing_url?: string;+ accession_number: string;+ items: string[];+ description: string;+ category: 'earnings' | 'management' | 'merger' | 'restructuring' | 'governance' | 'acquisition' | 'material_agreement' | 'financial_results' | 'debt' | 'asset' | 'other';}-export interface FilingData {+export interface FilingV2 {form: string;- description?: string;filing_date: string;+ description: string;+ url?: string;+ period?: string;}-export interface FinancialsData {- revenue: number;- gross_profit: number;- operating_cashflow: number;- free_cashflow: number;- ebitda_margins: number;- profit_margins: number;- revenue_growth: number;- earnings_growth: number;+export interface Executive {+ name: string;+ role: string;+ compensation?: number;}-export interface BalanceSheetData {- total_assets: number;- total_liabilities: number;- stockholders_equity: number;- total_cash: number;- total_debt: number;- shares_outstanding: number;+// ============================================================================+// GRAPH NODE TYPES+// ============================================================================++export type NodeCategory =+ | 'company'+ | 'peer'+ | 'institutional'+ | 'fund_family'+ | 'insider'+ | 'event'+ | 'supply_chain'+ | 'segment'+ | 'debt_holder'+ | 'metrics';++export interface GraphNodeData {+ id: string;+ category: NodeCategory;+ label: string;+ // Company node data+ company?: CompanyInfoV2;+ valuation?: ValuationSignal;+ executives?: Executive[];+ // Peer node data+ peer?: PeerCompany;+ peerValuation?: ValuationSignal;+ // Institutional node data+ holder?: InstitutionalHolder;+ // Fund family node data+ fundFamily?: FundFamily;+ // Insider node data+ insider?: InsiderHolder;+ transactions?: InsiderTransaction[];+ // Event node data+ event?: CorporateEventV2;+ // Supply chain node data+ supplyChain?: SupplyChainEntity;+ // Segment node data+ segment?: SegmentData;+ // Debt holder node data+ debtHolder?: DebtHolder;+ // Metrics cluster data+ metrics?: Record<string, number | string>;+ metricsType?: 'financials' | 'valuation' | 'ownership' | 'balance_sheet';}-export interface AnalystsData {- recommendation: string;- recommendation_mean?: number;- target_price: number;- target_high: number;- target_low: number;- analyst_count: number;+// ============================================================================+// GRAPH EDGE TYPES+// ============================================================================++export type EdgeCategory =+ | 'ownership'+ | 'peer'+ | 'supply_chain'+ | 'event'+ | 'segment'+ | 'debt'+ | 'internal';++export interface GraphEdgeData {+ category: EdgeCategory;+ label?: string;+ // Ownership edge+ percentage?: number;+ shares?: number;+ value?: number;+ change?: number;+ // Peer edge+ correlation?: number;+ // Supply chain edge+ relationship?: 'customer' | 'supplier';}-export interface OwnershipData {- insider_percent: number;- institutional_percent: number;- float_shares: number;- shares_outstanding: number;+// ============================================================================+// LAYOUT TYPES+// ============================================================================++export type LayoutMode =+ | 'layered'+ | 'force'+ | 'hierarchical'+ | 'circular'+ | 'radial'+ | 'custom';++export interface LayoutConfig {+ mode: LayoutMode;+ centerX: number;+ centerY: number;+ width: number;+ height: number;+ padding: number;}-export interface ValuationData {- pe_ratio: number;- forward_pe: number;- price_to_book: number;- enterprise_value: number;- enterprise_to_revenue: number;- peg_ratio: number;+// ============================================================================+// FILTER TYPES+// ============================================================================++export interface FilterState {+ showInstitutional: boolean;+ showInsiders: boolean;+ showPeers: boolean;+ showEvents: boolean;+ showMetrics: boolean;+ showFundFamilies: boolean;+ showSupplyChain: boolean;+ showSegments: boolean;+ showDebtHolders: boolean;+ minOwnership: number; // 0-100%+ peerFilter: 'all' | 'undervalued' | 'overvalued';+ eventTypes: string[];}-export interface ExecutiveData {- name: string;- role: string;+export const DEFAULT_FILTERS: FilterState = {+ showInstitutional: true,+ showInsiders: true,+ showPeers: true,+ showEvents: true,+ showMetrics: true,+ showFundFamilies: true,+ showSupplyChain: true,+ showSegments: true,+ showDebtHolders: true,+ minOwnership: 0,+ peerFilter: 'all',+ eventTypes: [],+};++// ============================================================================+// COMPLETE DATA STRUCTURE+// ============================================================================++export interface RelationshipMapDataV2 {+ company: CompanyInfoV2;+ executives: Executive[];+ institutionalHolders: InstitutionalHolder[];+ fundFamilies: FundFamily[];+ insiderHolders: InsiderHolder[];+ insiderTransactions: InsiderTransaction[];+ peers: PeerCompany[];+ peerValuations: Map<string, ValuationSignal>;+ corporateEvents: CorporateEventV2[];+ filings: FilingV2[];+ supplyChain: SupplyChainEntity[];+ segments: SegmentData[];+ debtHolders: DebtHolder[];+ companyValuation: ValuationSignal;+ timestamp: string;+ dataQuality: DataQualityScore;+}++export interface DataQualityScore {+ overall: number; // 0-100+ sources: {+ edgar_company: boolean;+ edgar_filings: boolean;+ edgar_proxy: boolean;+ edgar_institutional: boolean;+ edgar_insider: boolean;+ yfinance: boolean;+ peers: boolean;+ };+ completeness: number; // 0-100 based on how many fields have data+}++// ============================================================================+// LOADING STATE+// ============================================================================++export interface LoadingPhase {+ phase: 'idle' | 'company' | 'ownership' | 'peers' | 'supplementary' | 'complete' | 'error';+ progress: number; // 0-100+ message: string;+ partialData?: Partial<RelationshipMapDataV2>;}++// ============================================================================+// EXPORT TYPES+// ============================================================================++export type ExportFormat = 'svg' | 'png' | 'csv' | 'json';diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map/utils.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/utils.tsdeleted file mode 100644index 2725091d4..000000000--- a/fincept-terminal-desktop/src/components/tabs/relationship-map/utils.ts+++ /dev/null@@ -1,53 +0,0 @@-// Utility functions for RelationshipMapTab--/**- * Format monetary values with appropriate suffixes- */-export const formatMoney = (val: number): string => {- if (!val || val === 0) return '$0';- if (val >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;- if (val >= 1e9) return `$${(val / 1e9).toFixed(2)}B`;- if (val >= 1e6) return `$${(val / 1e6).toFixed(2)}M`;- if (val >= 1e3) return `$${(val / 1e3).toFixed(2)}K`;- return `$${val.toFixed(2)}`;-};--/**- * Format market cap with appropriate suffixes (same as formatMoney but for display)- */-export const formatMarketCap = (val: number): string => {- if (!val) return 'N/A';- if (val >= 1e12) return `$${(val / 1e12).toFixed(2)}T`;- if (val >= 1e9) return `$${(val / 1e9).toFixed(2)}B`;- if (val >= 1e6) return `$${(val / 1e6).toFixed(2)}M`;- return `$${val}`;-};--/**- * Format percentage values- */-export const formatPercent = (val: number): string => {- if (!val && val !== 0) return 'N/A';- return `${(val * 100).toFixed(2)}%`;-};--/**- * Format large numbers with appropriate suffixes- */-export const formatNumber = (val: number): string => {- if (!val && val !== 0) return 'N/A';- if (val >= 1e9) return `${(val / 1e9).toFixed(2)}B`;- if (val >= 1e6) return `${(val / 1e6).toFixed(2)}M`;- return val.toFixed(2);-};--/**- * Format date for display- */-export const formatDate = (dateStr: string): string => {- return new Date(dateStr).toLocaleDateString('en-US', {- month: 'short',- day: 'numeric',- year: '2-digit',- });-};diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/utils/layoutAlgorithms.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/utils/layoutAlgorithms.tssimilarity index 94%rename from fincept-terminal-desktop/src/components/tabs/relationship-map-v2/utils/layoutAlgorithms.tsrename to fincept-terminal-desktop/src/components/tabs/relationship-map/utils/layoutAlgorithms.tsindex e4d8fc875..4259bff8e 100644--- a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/utils/layoutAlgorithms.ts+++ b/fincept-terminal-desktop/src/components/tabs/relationship-map/utils/layoutAlgorithms.ts@@ -106,8 +106,17 @@ function calculateLayeredLayout(// Peer companiesplaceInRing(groups.peer, LAYOUT_CONFIG.RINGS.PEERS, cx, cy, positions, 0);- // Events and supply chain- placeInRing([...groups.event, ...groups.supply_chain], LAYOUT_CONFIG.RINGS.EVENTS, cx, cy, positions, Math.PI / 4);+ // Supply chain nodes (customers and suppliers)+ placeInRing(groups.supply_chain, LAYOUT_CONFIG.RINGS.SUPPLY_CHAIN, cx, cy, positions, -Math.PI / 3);++ // Segment nodes+ placeInRing(groups.segment, LAYOUT_CONFIG.RINGS.SEGMENTS, cx, cy, positions, Math.PI * 0.75);++ // Events+ placeInRing(groups.event, LAYOUT_CONFIG.RINGS.EVENTS, cx, cy, positions, Math.PI / 4);++ // Debt holders+ placeInRing(groups.debt_holder, LAYOUT_CONFIG.RINGS.DEBT_HOLDERS, cx, cy, positions, Math.PI * 0.6);return positions;}@@ -277,7 +286,7 @@ function calculateRadialLayout(const cy = config.centerY;const groups = groupByCategory(nodes);- const categories: NodeCategory[] = ['insider', 'institutional', 'fund_family', 'peer', 'event', 'metrics', 'supply_chain'];+ const categories: NodeCategory[] = ['insider', 'institutional', 'fund_family', 'peer', 'event', 'metrics', 'supply_chain', 'segment', 'debt_holder'];// Company at centerfor (const node of groups.company) {@@ -322,6 +331,8 @@ function groupByCategory(nodes: Node<GraphNodeData>[]): Record<NodeCategory, Nodinsider: [],event: [],supply_chain: [],+ segment: [],+ debt_holder: [],metrics: [],};diff --git a/fincept-terminal-desktop/src/components/tabs/relationship-map-v2/utils/valuationSignals.ts b/fincept-terminal-desktop/src/components/tabs/relationship-map/utils/valuationSignals.tssimilarity index 100%rename from fincept-terminal-desktop/src/components/tabs/relationship-map-v2/utils/valuationSignals.tsrename to fincept-terminal-desktop/src/components/tabs/relationship-map/utils/valuationSignals.tsdiff --git a/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.ts b/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.tsindex 07a4d6637..1b4c18f17 100644--- a/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.ts+++ b/fincept-terminal-desktop/src/services/geopolitics/relationshipMapService.ts@@ -1,21 +1,37 @@-// Relationship Map Service - Production-Level Implementation-// Combines Edgar (SEC filings) + yfinance (market data) for comprehensive company intelligence+// Relationship Map Service - Production-Level Multi-Source Implementation+// Integrates: Edgar (SEC filings, 13F, insider), YFinance (market data, peers)import { invoke } from '@tauri-apps/api/core';+import { TIMEOUTS, DATA_LIMITS, CACHE_TTL } from '../../components/tabs/relationship-map/constants';+import type {+ CompanyInfoV2,+ InstitutionalHolder,+ FundFamily,+ InsiderHolder,+ InsiderTransaction,+ PeerCompany,+ CorporateEventV2,+ FilingV2,+ Executive,+ RelationshipMapDataV2,+ DataQualityScore,+ LoadingPhase,+ SupplyChainEntity,+ SegmentData,+ DebtHolder,+} from '../../components/tabs/relationship-map/types';+import { calculateValuationSignal, calculatePeerValuations } from '../../components/tabs/relationship-map/utils/valuationSignals';// ============================================================================// TIMEOUT UTILITY// ============================================================================-/**- * Wrap a promise with a timeout. Returns null if the promise doesn't resolve in time.- */function withTimeout<T>(promise: Promise<T>, ms: number, label?: string): Promise<T | null> {return Promise.race([promise,new Promise<null>((resolve) => {setTimeout(() => {- console.warn(`[RelationshipMapService] ${label || 'Request'} timed out after ${ms}ms`);+ console.warn(`[RelMapV2] ${label || 'Request'} timed out after ${ms}ms`);resolve(null);}, ms);}),@@ -23,309 +39,401 @@ function withTimeout<T>(promise: Promise<T>, ms: number, label?: string): Promis}// ============================================================================-// TYPE DEFINITIONS+// CACHE SYSTEM// ============================================================================-export interface CompanyInfo {- ticker: string;- name: string;- cik: string;- industry: string;- sic: string;- sector?: string;- address?: string;- exchange?: string;- employees?: number;- website?: string;- description?: string;- market_cap?: number;-}--export interface Executive {- name: string;- role: string;- compensation?: number;-}--export interface InstitutionalHolder {- name: string;- value: number;- shares?: number;- percentage?: number;-}--export interface Filing {- form: string;- filing_date: string;- description?: string;- url?: string;- period?: string;-}--export interface CorporateEvent {- filing_date: string;- period_of_report?: string;- form: string;- filing_url?: string;- accession_number: string;- items?: string[];- description?: string;+interface CacheEntry<T> {+ data: T;+ timestamp: number;+ ttl: number;}-export interface BalanceSheetMetrics {- total_assets: number;- total_liabilities: number;- stockholders_equity: number;- shares_outstanding: number;- total_cash?: number;- total_debt?: number;-}+class DataCache {+ private cache = new Map<string, CacheEntry<unknown>>();-export interface FinancialMetrics {- revenue: number;- gross_profit: number;- operating_cashflow: number;- free_cashflow: number;- ebitda_margins: number;- profit_margins: number;- revenue_growth: number;- earnings_growth: number;-}+ get<T>(key: string): T | null {+ const entry = this.cache.get(key) as CacheEntry<T> | undefined;+ if (!entry) return null;+ if (Date.now() - entry.timestamp > entry.ttl) {+ this.cache.delete(key);+ return null;+ }+ return entry.data;+ }-export interface AnalystData {- recommendation: string;- recommendation_mean?: number;- target_price: number;- target_high: number;- target_low: number;- analyst_count: number;-}+ set<T>(key: string, data: T, ttl: number): void {+ this.cache.set(key, { data, timestamp: Date.now(), ttl });+ }-export interface OwnershipData {- insider_percent: number;- institutional_percent: number;- float_shares: number;- shares_outstanding: number;+ clear(prefix?: string): void {+ if (prefix) {+ for (const key of this.cache.keys()) {+ if (key.startsWith(prefix)) this.cache.delete(key);+ }+ } else {+ this.cache.clear();+ }+ }}-export interface ValuationMetrics {- pe_ratio: number;- forward_pe: number;- price_to_book: number;- enterprise_value: number;- enterprise_to_revenue: number;- peg_ratio: number;-}+// ============================================================================+// PEER DISCOVERY+// ============================================================================-export interface RelationshipMapData {- company: CompanyInfo;- executives: Executive[];- holders: InstitutionalHolder[];- filings: Filing[];- corporate_events: CorporateEvent[];- balance_sheet: BalanceSheetMetrics;- financials: FinancialMetrics;- analysts: AnalystData;- ownership: OwnershipData;- valuation: ValuationMetrics;- timestamp: string;+// Common industry peers mapping for reliable peer selection+const INDUSTRY_PEERS: Record<string, string[]> = {+ 'Technology': ['AAPL', 'MSFT', 'GOOGL', 'META', 'AMZN', 'NVDA', 'CRM', 'ORCL', 'ADBE', 'INTC'],+ 'Software': ['MSFT', 'CRM', 'ORCL', 'ADBE', 'NOW', 'INTU', 'SNOW', 'PLTR', 'PANW', 'ZS'],+ 'Semiconductors': ['NVDA', 'AMD', 'INTC', 'AVGO', 'QCOM', 'TXN', 'MU', 'LRCX', 'AMAT', 'MRVL'],+ 'Internet Content & Information': ['GOOGL', 'META', 'SNAP', 'PINS', 'TWTR'],+ 'Consumer Electronics': ['AAPL', 'SONY', 'DELL', 'HPQ', 'LOGI'],+ 'E-Commerce': ['AMZN', 'SHOP', 'EBAY', 'ETSY', 'MELI', 'JD', 'BABA'],+ 'Electric Vehicles': ['TSLA', 'RIVN', 'LCID', 'NIO', 'XPEV', 'LI'],+ 'Auto Manufacturers': ['TSLA', 'F', 'GM', 'TM', 'HMC', 'STLA', 'RIVN'],+ 'Banks': ['JPM', 'BAC', 'WFC', 'C', 'GS', 'MS', 'USB', 'PNC', 'TFC', 'COF'],+ 'Insurance': ['BRK-B', 'UNH', 'AIG', 'MET', 'PRU', 'ALL', 'TRV', 'CB', 'PGR', 'AFL'],+ 'Pharmaceuticals': ['JNJ', 'PFE', 'MRK', 'ABBV', 'LLY', 'BMY', 'AMGN', 'GILD', 'BIIB', 'REGN'],+ 'Biotechnology': ['AMGN', 'GILD', 'BIIB', 'REGN', 'VRTX', 'MRNA', 'BNTX'],+ 'Oil & Gas': ['XOM', 'CVX', 'COP', 'EOG', 'SLB', 'MPC', 'VLO', 'PSX', 'OXY', 'DVN'],+ 'Retail': ['WMT', 'COST', 'TGT', 'HD', 'LOW', 'DG', 'DLTR', 'KR'],+ 'Aerospace & Defense': ['LMT', 'RTX', 'BA', 'NOC', 'GD', 'LHX', 'TDG'],+ 'Streaming': ['NFLX', 'DIS', 'PARA', 'WBD', 'ROKU'],+ 'Cloud Computing': ['AMZN', 'MSFT', 'GOOGL', 'CRM', 'NOW', 'SNOW', 'NET', 'DDOG'],+ 'Payments': ['V', 'MA', 'PYPL', 'SQ', 'FIS', 'FISV', 'GPN'],+ 'Real Estate': ['AMT', 'PLD', 'CCI', 'EQIX', 'SPG', 'O', 'DLR', 'PSA'],+ 'Utilities': ['NEE', 'DUK', 'SO', 'D', 'AEP', 'SRE', 'XEL', 'ES', 'WEC', 'ED'],+};++function findPeersByIndustry(ticker: string, industry: string, sector: string): string[] {+ // Try exact industry match first+ for (const [key, peers] of Object.entries(INDUSTRY_PEERS)) {+ if (industry.toLowerCase().includes(key.toLowerCase()) ||+ key.toLowerCase().includes(industry.toLowerCase())) {+ return peers.filter(p => p !== ticker).slice(0, DATA_LIMITS.MAX_PEERS);+ }+ }+ // Try sector match+ for (const [key, peers] of Object.entries(INDUSTRY_PEERS)) {+ if (sector.toLowerCase().includes(key.toLowerCase()) ||+ key.toLowerCase().includes(sector.toLowerCase())) {+ return peers.filter(p => p !== ticker).slice(0, DATA_LIMITS.MAX_PEERS);+ }+ }+ // Fallback to broad tech/general+ return ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'NVDA'].filter(p => p !== ticker).slice(0, 5);}// ============================================================================// SERVICE CLASS// ============================================================================-// Cache configuration-const CACHE_DURATION = 5 * 60 * 1000; // 5 minutes--interface CacheEntry<T> {- data: T;- timestamp: number;-}-class RelationshipMapService {- // In-memory cache for relationship data- private cache: Map<string, CacheEntry<RelationshipMapData>> = new Map();-- /**- * Check if cache entry is still valid- */- private isCacheValid<T>(entry: CacheEntry<T> | undefined): boolean {- if (!entry) return false;- return Date.now() - entry.timestamp < CACHE_DURATION;- }+ private cache = new DataCache();/*** Clear cache for a specific ticker or all*/clearCache(ticker?: string): void {if (ticker) {- this.cache.delete(ticker.toUpperCase());+ this.cache.clear(ticker.toUpperCase());} else {this.cache.clear();}}/**- * Get comprehensive relationship map data for a ticker.- * Uses individual timeouts per data source so slow sources don't block the UI.+ * Get comprehensive relationship map data with progressive loading.+ * Calls the onProgress callback as data becomes available.*/- async getRelationshipMap(ticker: string): Promise<RelationshipMapData> {+ async getRelationshipMap(+ ticker: string,+ onProgress?: (phase: LoadingPhase) => void+ ): Promise<RelationshipMapDataV2> {const upperTicker = ticker.toUpperCase();- // Check cache first- const cached = this.cache.get(upperTicker);- if (this.isCacheValid(cached)) {- console.log(`[RelationshipMapService] Cache hit for ${upperTicker}`);- return cached!.data;+ // Check cache+ const cached = this.cache.get<RelationshipMapDataV2>(`${upperTicker}:full`);+ if (cached) {+ onProgress?.({ phase: 'complete', progress: 100, message: 'Loaded from cache' });+ return cached;}- console.log(`[RelationshipMapService] Cache miss for ${upperTicker}, fetching...`);try {- // Use individual timeouts: yfinance is fast (10s), edgar company/filings (15s),- // proxy and events can be slow so give them 20s max- const [edgarCompany, edgarProxy, edgarFilings, edgarEvents, yfinanceInfo] = await Promise.all([- withTimeout(this.getEdgarCompany(ticker), 15000, 'EdgarCompany'),- withTimeout(this.getEdgarProxy(ticker), 20000, 'EdgarProxy'),- withTimeout(this.getEdgarFilings(ticker), 15000, 'EdgarFilings'),- withTimeout(this.getEdgarCorporateEvents(ticker), 15000, 'EdgarEvents'),- withTimeout(this.getYFinanceInfo(ticker), 10000, 'YFinanceInfo'),+ // ====================================================================+ // PHASE 1: Company Info (0-30%)+ // ====================================================================+ onProgress?.({ phase: 'company', progress: 5, message: 'Fetching company data...' });++ const [edgarCompany, yfinanceInfo, edgarProxy] = await Promise.all([+ withTimeout(this.fetchEdgarCompany(ticker), TIMEOUTS.EDGAR_COMPANY, 'EdgarCompany'),+ withTimeout(this.fetchYFinanceInfo(ticker), TIMEOUTS.YFINANCE_INFO, 'YFinanceInfo'),+ withTimeout(this.fetchEdgarProxy(ticker), TIMEOUTS.EDGAR_PROXY, 'EdgarProxy'),]);- const result = this.combineData(ticker, edgarCompany, edgarProxy, edgarFilings, edgarEvents, yfinanceInfo);+ onProgress?.({ phase: 'company', progress: 30, message: 'Company data loaded' });++ // Build company info+ const company = this.buildCompanyInfo(ticker, edgarCompany, yfinanceInfo);+ const executives = this.extractExecutives(edgarProxy);++ // ====================================================================+ // PHASE 2: Ownership & Deep Data (30-60%)+ // ====================================================================+ onProgress?.({ phase: 'ownership', progress: 35, message: 'Fetching ownership & deep data...' });++ const [insiderData, edgarFilings, edgarEvents, holdingsDetailed, supplyChainData, segmentData, debtData] = await Promise.all([+ withTimeout(this.fetchEdgarInsiderTransactionsDetailed(ticker), TIMEOUTS.EDGAR_INSIDER, 'InsiderTx'),+ withTimeout(this.fetchEdgarFilings(ticker), TIMEOUTS.EDGAR_FILINGS, 'Filings'),+ withTimeout(this.fetchEdgarCorporateEventsCategorized(ticker), TIMEOUTS.EDGAR_EVENTS, 'Events'),+ withTimeout(this.fetchInstitutionalHoldingsDetailed(ticker), TIMEOUTS.EDGAR_INSTITUTIONAL, 'Holdings'),+ withTimeout(this.fetchSupplyChain(ticker), TIMEOUTS.EDGAR_FILINGS, 'SupplyChain'),+ withTimeout(this.fetchSegmentFinancials(ticker), TIMEOUTS.EDGAR_FILINGS, 'Segments'),+ withTimeout(this.fetchDebtHolders(ticker), TIMEOUTS.EDGAR_FILINGS, 'DebtHolders'),+ ]);++ onProgress?.({ phase: 'ownership', progress: 55, message: 'Processing ownership & relationships...' });++ // Build institutional holders from real 13F/13G/13D data+ const institutionalHolders = this.buildInstitutionalHoldersFromEdgar(holdingsDetailed, yfinanceInfo);+ const fundFamilies = this.buildFundFamilies(institutionalHolders);+ const insiderHolders = this.buildInsiderHoldersDetailed(insiderData, edgarProxy);+ const insiderTransactions = this.buildInsiderTransactionsDetailed(insiderData);+ const filings = this.extractFilings(edgarFilings);+ const corporateEvents = this.extractCorporateEventsCategorized(edgarEvents);+ const supplyChain = this.extractSupplyChain(supplyChainData);+ const segments = this.extractSegments(segmentData);+ const debtHolders = this.extractDebtHolders(debtData);++ onProgress?.({ phase: 'ownership', progress: 60, message: 'Deep data processed' });++ // ====================================================================+ // PHASE 3: Peers (60-80%)+ // ====================================================================+ onProgress?.({ phase: 'peers', progress: 65, message: 'Finding peer companies...' });++ const peerTickers = findPeersByIndustry(ticker, company.industry, company.sector);+ const peers = await this.fetchPeerData(peerTickers);++ onProgress?.({ phase: 'peers', progress: 80, message: 'Calculating valuation signals...' });++ // Calculate valuation signals+ const companyValuation = calculateValuationSignal(company, peers);+ const peerValuations = calculatePeerValuations(peers);++ // ====================================================================+ // PHASE 4: Supplementary (80-100%)+ // ====================================================================+ onProgress?.({ phase: 'supplementary', progress: 85, message: 'Finalizing data...' });++ // Calculate data quality score+ const dataQuality = this.calculateDataQuality(+ edgarCompany, yfinanceInfo, edgarProxy, insiderData,+ edgarFilings, edgarEvents, peers+ );++ const result: RelationshipMapDataV2 = {+ company,+ executives,+ institutionalHolders,+ fundFamilies,+ insiderHolders,+ insiderTransactions,+ peers,+ peerValuations,+ corporateEvents,+ filings,+ supplyChain,+ segments,+ debtHolders,+ companyValuation,+ timestamp: new Date().toISOString(),+ dataQuality,+ };// Store in cache- this.cache.set(upperTicker, {- data: result,- timestamp: Date.now(),- });+ this.cache.set(`${upperTicker}:full`, result, CACHE_TTL.REALTIME);+ onProgress?.({ phase: 'complete', progress: 100, message: 'Complete' });return result;} catch (error) {- console.error('[RelationshipMapService] Error:', error);+ console.error('[RelMapV2] Error:', error);+ onProgress?.({ phase: 'error', progress: 0, message: `Error: ${error}` });throw error;}}- /**- * Fetch Edgar company info- */- private async getEdgarCompany(ticker: string) {+ // ==========================================================================+ // DATA FETCHING METHODS+ // ==========================================================================++ private async fetchEdgarCompany(ticker: string): Promise<any> {try {const result = await invoke<string>('execute_edgar_command', {- command: 'get_company',- args: [ticker]+ command: 'get_company', args: [ticker]});const parsed = JSON.parse(result);- if (parsed?.error) {- console.warn('[Edgar] Company returned error:', parsed.error);- return null;- }- return parsed;- } catch (error) {- console.error('[Edgar] Company error:', error);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Edgar company error:', e);return null;}}- /**- * Fetch Edgar proxy statement- */- private async getEdgarProxy(ticker: string) {+ private async fetchEdgarProxy(ticker: string): Promise<any> {try {const result = await invoke<string>('execute_edgar_command', {- command: 'get_proxy_statement',- args: [ticker]+ command: 'get_proxy_statement', args: [ticker]});const parsed = JSON.parse(result);- if (parsed?.error) {- console.warn('[Edgar] Proxy returned error:', parsed.error);- return null;- }- return parsed;- } catch (error) {- console.error('[Edgar] Proxy error:', error);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Edgar proxy error:', e);return null;}}- /**- * Fetch Edgar filings (limited to 10 for faster response)- */- private async getEdgarFilings(ticker: string) {+ private async fetchEdgarFilings(ticker: string): Promise<any> {try {const result = await invoke<string>('execute_edgar_command', {- command: 'get_company_filings',- args: [ticker]+ command: 'get_company_filings', args: [ticker, '', '', '', '15']});const parsed = JSON.parse(result);- if (parsed?.error) {- console.warn('[Edgar] Filings returned error:', parsed.error);- return null;- }- return parsed;- } catch (error) {- console.error('[Edgar] Filings error:', error);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Edgar filings error:', e);return null;}}- /**- * Fetch Edgar corporate events (8-K filings) - limited to 10- */- private async getEdgarCorporateEvents(ticker: string) {+ private async fetchEdgarCorporateEventsCategorized(ticker: string): Promise<any> {try {const result = await invoke<string>('execute_edgar_command', {- command: 'get_corporate_events',- args: [ticker, '10']+ command: 'get_corporate_events_categorized', args: [ticker, '30']});const parsed = JSON.parse(result);- if (parsed?.error) {- console.warn('[Edgar] Corporate Events returned error:', parsed.error);- return null;- }- return parsed;- } catch (error) {- console.error('[Edgar] Corporate Events error:', error);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Edgar events error:', e);return null;}}- /**- * Fetch yfinance data- */- private async getYFinanceInfo(ticker: string) {+ private async fetchEdgarInsiderTransactionsDetailed(ticker: string): Promise<any> {+ try {+ const result = await invoke<string>('execute_edgar_command', {+ command: 'get_insider_transactions_detailed', args: [ticker, '25']+ });+ const parsed = JSON.parse(result);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Edgar insider detailed error:', e);+ return null;+ }+ }++ private async fetchInstitutionalHoldingsDetailed(ticker: string): Promise<any> {+ try {+ const result = await invoke<string>('execute_edgar_command', {+ command: 'get_fund_holdings_detailed', args: [ticker, '2']+ });+ const parsed = JSON.parse(result);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Edgar holdings detailed error:', e);+ return null;+ }+ }++ private async fetchSupplyChain(ticker: string): Promise<any> {+ try {+ const result = await invoke<string>('execute_edgar_command', {+ command: 'extract_supply_chain', args: [ticker]+ });+ const parsed = JSON.parse(result);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Supply chain error:', e);+ return null;+ }+ }++ private async fetchSegmentFinancials(ticker: string): Promise<any> {+ try {+ const result = await invoke<string>('execute_edgar_command', {+ command: 'get_segment_financials', args: [ticker]+ });+ const parsed = JSON.parse(result);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Segment financials error:', e);+ return null;+ }+ }++ private async fetchDebtHolders(ticker: string): Promise<any> {+ try {+ const result = await invoke<string>('execute_edgar_command', {+ command: 'extract_debt_holders', args: [ticker]+ });+ const parsed = JSON.parse(result);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] Debt holders error:', e);+ return null;+ }+ }++ private async fetchYFinanceInfo(ticker: string): Promise<any> {try {const result = await invoke<string>('execute_yfinance_command', {- command: 'info',- args: [ticker]+ command: 'info', args: [ticker]});const parsed = JSON.parse(result);- if (parsed?.error) {- console.warn('[YFinance] Info returned error:', parsed.error);- return null;- }- return parsed;- } catch (error) {- console.error('[YFinance] Info error:', error);+ return parsed?.error ? null : parsed;+ } catch (e) {+ console.error('[RelMapV2] YFinance info error:', e);return null;}}- /**- * Combine all data sources- */- private combineData(- ticker: string,- edgarCompany: any,- edgarProxy: any,- edgarFilings: any,- edgarEvents: any,- yfinanceData: any- ): RelationshipMapData {-- // Extract company info- const company: CompanyInfo = {+ private async fetchPeerData(tickers: string[]): Promise<PeerCompany[]> {+ const peers: PeerCompany[] = [];+ // Fetch peer data in parallel batches of 4+ const batchSize = 4;+ for (let i = 0; i < tickers.length; i += batchSize) {+ const batch = tickers.slice(i, i + batchSize);+ const results = await Promise.all(+ batch.map(t => withTimeout(this.fetchYFinanceInfo(t), TIMEOUTS.YFINANCE_PEERS, `Peer:${t}`))+ );+ for (let j = 0; j < results.length; j++) {+ const data = results[j];+ if (data) {+ peers.push({+ ticker: batch[j],+ name: data.company_name || batch[j],+ market_cap: data.market_cap || 0,+ pe_ratio: data.pe_ratio || 0,+ price_to_book: data.price_to_book || 0,+ price_to_sales: data.enterprise_to_revenue || 0,+ roe: data.return_on_equity || 0,+ revenue_growth: data.revenue_growth || 0,+ profit_margins: data.profit_margins || 0,+ current_price: data.current_price || 0,+ sector: data.sector || 'N/A',+ industry: data.industry || 'N/A',+ });+ }+ }+ }+ return peers;+ }++ // ==========================================================================+ // DATA BUILDING METHODS+ // ==========================================================================++ private buildCompanyInfo(ticker: string, edgarCompany: any, yfinanceData: any): CompanyInfoV2 {+ return {ticker: ticker.toUpperCase(),name: edgarCompany?.data?.name || yfinanceData?.company_name || ticker,cik: edgarCompany?.data?.cik?.toString() || '',@@ -334,123 +442,42 @@ class RelationshipMapService {sector: yfinanceData?.sector || 'N/A',address: edgarCompany?.data?.business_address || '',exchange: yfinanceData?.exchange || 'N/A',- employees: yfinanceData?.employees,- website: yfinanceData?.website,- description: yfinanceData?.description,- market_cap: yfinanceData?.market_cap,- };-- // Extract executives- const executives: Executive[] = this.extractExecutives(edgarProxy);-- // Extract holders (placeholder - will implement when yfinance adds institutional_holders)- const holders: InstitutionalHolder[] = this.extractHolders(yfinanceData);-- // Extract filings- const filings: Filing[] = this.extractFilings(edgarFilings);-- // Extract corporate events- const corporate_events: CorporateEvent[] = this.extractCorporateEvents(edgarEvents);-- // Extract balance sheet - use book_value_total as stockholders_equity proxy- const bookValueTotal = yfinanceData?.book_value_total || 0;- const totalDebt = yfinanceData?.total_debt || 0;- const totalCash = yfinanceData?.total_cash || 0;- // Approximate total assets = equity + debt- const estimatedAssets = yfinanceData?.total_assets || (bookValueTotal + totalDebt) || 0;- const estimatedLiabilities = yfinanceData?.total_liabilities || totalDebt || 0;-- const balance_sheet: BalanceSheetMetrics = {- total_assets: estimatedAssets,- total_liabilities: estimatedLiabilities,- stockholders_equity: bookValueTotal || (estimatedAssets - estimatedLiabilities),- shares_outstanding: yfinanceData?.shares_outstanding || 0,- total_cash: totalCash,- total_debt: totalDebt,- };-- // Extract financial metrics- const financials: FinancialMetrics = {- revenue: yfinanceData?.total_revenue || 0,- gross_profit: yfinanceData?.gross_profits || 0,- operating_cashflow: yfinanceData?.operating_cashflow || 0,- free_cashflow: yfinanceData?.free_cashflow || 0,- ebitda_margins: yfinanceData?.ebitda_margins || 0,+ employees: yfinanceData?.employees || 0,+ website: yfinanceData?.website || '',+ description: yfinanceData?.description || '',+ market_cap: yfinanceData?.market_cap || 0,+ current_price: yfinanceData?.current_price || 0,+ pe_ratio: yfinanceData?.pe_ratio || 0,+ forward_pe: yfinanceData?.forward_pe || 0,+ price_to_book: yfinanceData?.price_to_book || 0,+ price_to_sales: yfinanceData?.enterprise_to_revenue || 0,+ peg_ratio: yfinanceData?.peg_ratio || 0,+ enterprise_value: yfinanceData?.enterprise_value || 0,+ enterprise_to_revenue: yfinanceData?.enterprise_to_revenue || 0,profit_margins: yfinanceData?.profit_margins || 0,+ operating_margins: yfinanceData?.operating_margins || 0,+ roe: yfinanceData?.return_on_equity || 0,+ roa: yfinanceData?.return_on_assets || 0,revenue_growth: yfinanceData?.revenue_growth || 0,earnings_growth: yfinanceData?.earnings_growth || 0,- };-- // Extract analyst data- const analysts: AnalystData = {- recommendation: yfinanceData?.recommendation_key || 'N/A',- recommendation_mean: yfinanceData?.recommendation_mean,- target_price: yfinanceData?.target_mean_price || 0,- target_high: yfinanceData?.target_high_price || 0,- target_low: yfinanceData?.target_low_price || 0,- analyst_count: yfinanceData?.number_of_analyst_opinions || 0,- };-- // Extract ownership- const ownership: OwnershipData = {+ revenue: yfinanceData?.total_revenue || 0,+ gross_profit: yfinanceData?.gross_profits || 0,+ ebitda: (yfinanceData?.total_revenue || 0) * (yfinanceData?.ebitda_margins || 0),+ free_cashflow: yfinanceData?.free_cashflow || 0,+ total_cash: yfinanceData?.total_cash || 0,+ total_debt: yfinanceData?.total_debt || 0,insider_percent: (yfinanceData?.held_percent_insiders || 0) * 100,institutional_percent: (yfinanceData?.held_percent_institutions || 0) * 100,- float_shares: yfinanceData?.float_shares || 0,shares_outstanding: yfinanceData?.shares_outstanding || 0,+ float_shares: yfinanceData?.float_shares || 0,+ recommendation: yfinanceData?.recommendation_key || 'N/A',+ target_price: yfinanceData?.target_mean_price || 0,+ analyst_count: yfinanceData?.number_of_analyst_opinions || 0,};-- // Extract valuation- const valuation: ValuationMetrics = {- pe_ratio: yfinanceData?.pe_ratio || 0,- forward_pe: yfinanceData?.forward_pe || 0,- price_to_book: yfinanceData?.price_to_book || 0,- enterprise_value: yfinanceData?.enterprise_value || 0,- enterprise_to_revenue: yfinanceData?.enterprise_to_revenue || 0,- peg_ratio: yfinanceData?.peg_ratio || 0,- };-- return {- company,- executives,- holders,- filings,- corporate_events,- balance_sheet,- financials,- analysts,- ownership,- valuation,- timestamp: new Date().toISOString()- };- }-- /**- * Extract corporate events from Edgar data- */- private extractCorporateEvents(eventsData: any): CorporateEvent[] {- if (!eventsData?.data) {- return [];- }-- return eventsData.data.slice(0, 15).map((event: any) => ({- filing_date: event.filing_date || '',- period_of_report: event.period_of_report || '',- form: event.form || '8-K',- filing_url: event.filing_url || '',- accession_number: event.accession_number || '',- items: event.items || [],- description: event.description || '',- }));}- /**- * Extract executives from proxy data- */private extractExecutives(proxyData: any): Executive[] {- if (!proxyData?.data?.named_executives || proxyData.data.named_executives.length === 0) {- return [];- }-+ if (!proxyData?.data?.named_executives?.length) return [];const executives: Executive[] = [];const seen = new Set<string>();@@ -461,17 +488,13 @@ class RelationshipMapService {executives.push({name,role: this.parseRole(exec.role),- compensation: exec.total_comp+ compensation: exec.total_comp,});}}-- return executives.slice(0, 20);+ return executives.slice(0, 15);}- /**- * Parse executive role- */private parseRole(role: string): string {if (!role) return 'Executive';if (role.includes('Peo') || role.includes('CEO')) return 'CEO';@@ -482,49 +505,363 @@ class RelationshipMapService {return role;}- /**- * Extract institutional holders (placeholder)- */- private extractHolders(yfinanceData: any): InstitutionalHolder[] {- // TODO: Implement when yfinance_data.py adds institutional_holders method- return [];+ private buildInstitutionalHoldersFromEdgar(holdingsData: any, yfinanceData: any): InstitutionalHolder[] {+ const holders: InstitutionalHolder[] = [];+ const price = yfinanceData?.current_price || 0;+ const sharesOutstanding = yfinanceData?.shares_outstanding || 0;++ // Use real data from Edgar 13F/13G/13D/proxy filings+ if (holdingsData?.data?.holders?.length) {+ for (const h of holdingsData.data.holders) {+ const name = h.name || 'Unknown';+ const shares = h.shares || 0;+ const value = h.value || (shares * price) || 0;+ let percentage = h.percentage || 0;++ // Calculate percentage from shares if not provided+ if (!percentage && shares && sharesOutstanding) {+ percentage = (shares / sharesOutstanding) * 100;+ }++ holders.push({+ name,+ shares,+ value,+ percentage: parseFloat((percentage || 0).toFixed(2)),+ fund_family: this.extractFundFamily(name),+ filing_date: h.filing_date || h.date_reported,+ });+ }+ }++ // If no real data found, generate from yfinance institutional percentage+ if (holders.length === 0) {+ return this.buildFallbackInstitutionalHolders(yfinanceData);+ }++ // Sort by percentage descending+ holders.sort((a, b) => b.percentage - a.percentage);+ return holders.slice(0, DATA_LIMITS.MAX_INSTITUTIONAL_HOLDERS);}- /**- * Extract recent filings- */- private extractFilings(filingsData: any): Filing[] {- if (!filingsData?.data) {- return [];+ private buildFallbackInstitutionalHolders(yfinanceData: any): InstitutionalHolder[] {+ const institutionalPercent = (yfinanceData?.held_percent_institutions || 0) * 100;+ if (institutionalPercent <= 0) return [];++ const knownHolders = [+ { name: 'Vanguard Group', typicalShare: 0.08 },+ { name: 'BlackRock', typicalShare: 0.07 },+ { name: 'State Street', typicalShare: 0.04 },+ { name: 'Fidelity Management', typicalShare: 0.035 },+ { name: 'Capital Research', typicalShare: 0.03 },+ ];++ const sharesOutstanding = yfinanceData?.shares_outstanding || 0;+ const price = yfinanceData?.current_price || 0;+ const holders: InstitutionalHolder[] = [];+ const scaleFactor = institutionalPercent / 100;++ for (const known of knownHolders) {+ const percentage = known.typicalShare * scaleFactor * 100;+ if (percentage < 0.5) continue;+ const shares = Math.round(sharesOutstanding * known.typicalShare * scaleFactor);+ holders.push({+ name: known.name,+ shares,+ value: shares * price,+ percentage: parseFloat(percentage.toFixed(2)),+ fund_family: known.name,+ });+ }++ return holders;+ }++ private extractFundFamily(name: string): string {+ const families: Record<string, string[]> = {+ 'Vanguard': ['vanguard'],+ 'BlackRock': ['blackrock', 'ishares'],+ 'State Street': ['state street', 'spdr', 'ssga'],+ 'Fidelity': ['fidelity', 'fmr'],+ 'Capital Group': ['capital research', 'capital group', 'american funds'],+ 'T. Rowe Price': ['t. rowe', 'trowe'],+ 'JP Morgan': ['jpmorgan', 'jp morgan', 'j.p. morgan'],+ 'Goldman Sachs': ['goldman'],+ 'Morgan Stanley': ['morgan stanley'],+ 'Bank of America': ['bank of america', 'merrill'],+ };++ const lower = name.toLowerCase();+ for (const [family, keywords] of Object.entries(families)) {+ if (keywords.some(kw => lower.includes(kw))) return family;+ }+ return name;+ }++ private buildFundFamilies(holders: InstitutionalHolder[]): FundFamily[] {+ const familyMap = new Map<string, InstitutionalHolder[]>();++ for (const holder of holders) {+ const family = holder.fund_family || holder.name;+ if (!familyMap.has(family)) familyMap.set(family, []);+ familyMap.get(family)!.push(holder);+ }++ const families: FundFamily[] = [];+ for (const [name, funds] of familyMap) {+ if (funds.length === 0) continue;+ families.push({+ name,+ total_shares: funds.reduce((s, f) => s + f.shares, 0),+ total_value: funds.reduce((s, f) => s + f.value, 0),+ total_percentage: funds.reduce((s, f) => s + f.percentage, 0),+ funds,+ change_trend: 'stable',+ });+ }++ return families+ .sort((a, b) => b.total_percentage - a.total_percentage)+ .slice(0, DATA_LIMITS.MAX_FUND_FAMILIES);+ }++ private buildInsiderHoldersDetailed(insiderData: any, proxyData: any): InsiderHolder[] {+ const holders: InsiderHolder[] = [];+ const seen = new Set<string>();++ // Use detailed insider summary from Form 4 parsing+ if (insiderData?.data?.insider_summary) {+ for (const insider of insiderData.data.insider_summary) {+ const name = insider.name || 'Unknown';+ if (seen.has(name.toLowerCase())) continue;+ seen.add(name.toLowerCase());++ holders.push({+ name,+ title: insider.title || 'Insider',+ shares: (insider.total_buys || 0) - (insider.total_sells || 0),+ value: (insider.total_buy_value || 0) - (insider.total_sell_value || 0),+ percentage: 0,+ last_transaction_date: insider.last_transaction_date,+ last_transaction_type: insider.total_buys > insider.total_sells ? 'buy' : 'sell',+ });+ }}- return filingsData.data.slice(0, 20).map((filing: any) => ({- form: filing.form || '',- filing_date: filing.filing_date || '',- description: this.getFilingDescription(filing.form),- url: filing.filing_url || '',- period: filing.period_of_report || ''+ // Supplement from proxy data (executives)+ if (proxyData?.data?.named_executives) {+ for (const exec of proxyData.data.named_executives.slice(0, 10)) {+ if (exec.name && !seen.has(exec.name.toLowerCase())) {+ seen.add(exec.name.toLowerCase());+ holders.push({+ name: exec.name,+ title: this.parseRole(exec.role),+ shares: 0,+ value: exec.total_comp || 0,+ percentage: 0,+ });+ }+ }+ }++ return holders.slice(0, DATA_LIMITS.MAX_INSIDER_HOLDERS);+ }++ private buildInsiderTransactionsDetailed(insiderData: any): InsiderTransaction[] {+ if (!insiderData?.data?.transactions) return [];++ return insiderData.data.transactions+ .filter((tx: any) => tx.transaction_type !== 'unknown')+ .slice(0, DATA_LIMITS.MAX_INSIDER_TRANSACTIONS)+ .map((tx: any) => ({+ name: tx.insider_name || 'Unknown',+ title: tx.insider_title || 'Insider',+ transaction_type: tx.transaction_type === 'purchase' ? 'buy' as const :+ tx.transaction_type === 'sale' ? 'sell' as const :+ 'option_exercise' as const,+ shares: tx.shares || 0,+ value: tx.value || 0,+ price: tx.price || 0,+ date: tx.filing_date || '',+ shares_remaining: 0,+ }));+ }++ private extractFilings(filingsData: any): FilingV2[] {+ if (!filingsData?.data) return [];++ return filingsData.data.slice(0, DATA_LIMITS.MAX_FILINGS).map((f: any) => ({+ form: f.form || '',+ filing_date: f.filing_date || '',+ description: this.getFilingDescription(f.form),+ url: f.filing_url || '',+ period: f.period_of_report || '',}));}- /**- * Get filing description- */+ private extractCorporateEventsCategorized(eventsData: any): CorporateEventV2[] {+ if (!eventsData?.data?.all_events) return [];++ return eventsData.data.all_events.slice(0, DATA_LIMITS.MAX_EVENTS).map((e: any) => ({+ filing_date: e.filing_date || '',+ period_of_report: '',+ form: e.form || '8-K',+ filing_url: e.filing_url || '',+ accession_number: e.accession_number || '',+ items: e.items || [],+ description: e.description || e.items?.[0] || '8-K Filing',+ category: (e.category || 'other') as CorporateEventV2['category'],+ }));+ }++ private extractSupplyChain(data: any): SupplyChainEntity[] {+ if (!data?.data) return [];+ const entities: SupplyChainEntity[] = [];++ // Add customers+ if (data.data.customers) {+ for (const c of data.data.customers.slice(0, DATA_LIMITS.MAX_SUPPLY_CHAIN)) {+ entities.push({+ name: c.name,+ relationship: 'customer',+ percentage_of_revenue: c.percentage_of_revenue,+ source: c.source,+ });+ }+ }++ // Add suppliers+ if (data.data.suppliers) {+ for (const s of data.data.suppliers.slice(0, DATA_LIMITS.MAX_SUPPLY_CHAIN)) {+ entities.push({+ name: s.name,+ relationship: 'supplier',+ source: s.source,+ });+ }+ }++ // Add partners+ if (data.data.partners) {+ for (const p of data.data.partners.slice(0, 5)) {+ entities.push({+ name: p.name,+ relationship: 'partner',+ source: p.source,+ });+ }+ }++ return entities.slice(0, DATA_LIMITS.MAX_SUPPLY_CHAIN);+ }++ private extractSegments(data: any): SegmentData[] {+ if (!data?.data) return [];+ const segments: SegmentData[] = [];++ if (data.data.geographic) {+ for (const g of data.data.geographic.slice(0, 5)) {+ segments.push({+ name: g.name,+ value: g.value || 0,+ type: 'geographic',+ period: g.period,+ });+ }+ }++ if (data.data.business_units) {+ for (const b of data.data.business_units.slice(0, 5)) {+ segments.push({+ name: b.name,+ value: b.value || 0,+ type: 'business_unit',+ period: b.period,+ });+ }+ }++ if (data.data.products) {+ for (const p of data.data.products.slice(0, 5)) {+ segments.push({+ name: p.name,+ value: p.value || 0,+ type: 'product',+ period: p.period,+ });+ }+ }++ return segments.slice(0, DATA_LIMITS.MAX_SEGMENTS);+ }++ private extractDebtHolders(data: any): DebtHolder[] {+ if (!data?.data) return [];+ const holders: DebtHolder[] = [];++ if (data.data.creditors) {+ for (const c of data.data.creditors.slice(0, DATA_LIMITS.MAX_DEBT_HOLDERS)) {+ holders.push({+ name: c.name,+ type: c.type || 'bank_lender',+ source: c.source,+ });+ }+ }++ if (data.data.credit_facilities) {+ for (const cf of data.data.credit_facilities.slice(0, 5)) {+ holders.push({+ name: cf.description?.substring(0, 50) || 'Credit Facility',+ type: 'credit_facility',+ filing_date: cf.filing_date,+ description: cf.description,+ });+ }+ }++ return holders.slice(0, DATA_LIMITS.MAX_DEBT_HOLDERS);+ }+private getFilingDescription(form: string): string {const descriptions: Record<string, string> = {- '10-K': 'Annual Report',- '10-Q': 'Quarterly Report',- '8-K': 'Current Event',- '4': 'Insider Trading',- 'DEF 14A': 'Proxy Statement',- '13F-HR': 'Institutional Holdings',- 'S-8': 'Employee Stock Plan',- 'SCHEDULE 13G/A': '5%+ Ownership Amendment',- 'DEFA14A': 'Proxy Additional Materials',- '144': 'Insider Sale Notice'+ '10-K': 'Annual Report', '10-Q': 'Quarterly Report',+ '8-K': 'Current Event', '4': 'Insider Trading',+ 'DEF 14A': 'Proxy Statement', '13F-HR': 'Institutional Holdings',+ 'S-8': 'Employee Stock Plan', 'SC 13G': '5%+ Ownership',+ 'DEFA14A': 'Proxy Materials', '144': 'Insider Sale Notice',};return descriptions[form] || form;}++ private calculateDataQuality(+ edgarCompany: any, yfinanceInfo: any, edgarProxy: any,+ insiderData: any, edgarFilings: any, edgarEvents: any,+ peers: PeerCompany[]+ ): DataQualityScore {+ const sources = {+ edgar_company: !!edgarCompany,+ edgar_filings: !!edgarFilings?.data?.length,+ edgar_proxy: !!edgarProxy?.data,+ edgar_institutional: !!edgarCompany,+ edgar_insider: !!insiderData?.data?.transactions?.length || !!insiderData?.data?.insider_summary?.length,+ yfinance: !!yfinanceInfo,+ peers: peers.length >= 3,+ };++ const successCount = Object.values(sources).filter(Boolean).length;+ const overall = Math.round((successCount / Object.keys(sources).length) * 100);++ const keyFields = [+ yfinanceInfo?.market_cap, yfinanceInfo?.pe_ratio, yfinanceInfo?.revenue_growth,+ yfinanceInfo?.profit_margins, yfinanceInfo?.return_on_equity,+ edgarCompany?.data?.name, edgarFilings?.data?.length,+ ];+ const filled = keyFields.filter(v => v && v !== 0 && v !== 'N/A').length;+ const completeness = Math.round((filled / keyFields.length) * 100);++ return { overall, sources, completeness };+ }}export const relationshipMapService = new RelationshipMapService();diff --git a/fincept-terminal-desktop/src/services/geopolitics/relationshipMapServiceV2.ts b/fincept-terminal-desktop/src/services/geopolitics/relationshipMapServiceV2.tsdeleted file mode 100644index 8f741a4b1..000000000--- a/fincept-terminal-desktop/src/services/geopolitics/relationshipMapServiceV2.ts+++ /dev/null@@ -1,641 +0,0 @@-// Relationship Map Service V2 - Production-Level Multi-Source Implementation-// Integrates: Edgar (SEC filings, 13F, insider), YFinance (market data, peers)--import { invoke } from '@tauri-apps/api/core';-import { TIMEOUTS, DATA_LIMITS, CACHE_TTL } from '../../components/tabs/relationship-map-v2/constants';-import type {- CompanyInfoV2,- InstitutionalHolder,- FundFamily,- InsiderHolder,- InsiderTransaction,- PeerCompany,- CorporateEventV2,- FilingV2,- Executive,- RelationshipMapDataV2,- DataQualityScore,- LoadingPhase,-} from '../../components/tabs/relationship-map-v2/types';-import { calculateValuationSignal, calculatePeerValuations } from '../../components/tabs/relationship-map-v2/utils/valuationSignals';--// ============================================================================-// TIMEOUT UTILITY-// ============================================================================--function withTimeout<T>(promise: Promise<T>, ms: number, label?: string): Promise<T | null> {- return Promise.race([- promise,- new Promise<null>((resolve) => {- setTimeout(() => {- console.warn(`[RelMapV2] ${label || 'Request'} timed out after ${ms}ms`);- resolve(null);- }, ms);- }),- ]);-}--// ============================================================================-// CACHE SYSTEM-// ============================================================================--interface CacheEntry<T> {- data: T;- timestamp: number;- ttl: number;-}--class DataCache {- private cache = new Map<string, CacheEntry<unknown>>();-- get<T>(key: string): T | null {- const entry = this.cache.get(key) as CacheEntry<T> | undefined;- if (!entry) return null;- if (Date.now() - entry.timestamp > entry.ttl) {- this.cache.delete(key);- return null;- }- return entry.data;- }-- set<T>(key: string, data: T, ttl: number): void {- this.cache.set(key, { data, timestamp: Date.now(), ttl });- }-- clear(prefix?: string): void {- if (prefix) {- for (const key of this.cache.keys()) {- if (key.startsWith(prefix)) this.cache.delete(key);- }- } else {- this.cache.clear();- }- }-}--// ============================================================================-// PEER DISCOVERY-// ============================================================================--// Common industry peers mapping for reliable peer selection-const INDUSTRY_PEERS: Record<string, string[]> = {- 'Technology': ['AAPL', 'MSFT', 'GOOGL', 'META', 'AMZN', 'NVDA', 'CRM', 'ORCL', 'ADBE', 'INTC'],- 'Software': ['MSFT', 'CRM', 'ORCL', 'ADBE', 'NOW', 'INTU', 'SNOW', 'PLTR', 'PANW', 'ZS'],- 'Semiconductors': ['NVDA', 'AMD', 'INTC', 'AVGO', 'QCOM', 'TXN', 'MU', 'LRCX', 'AMAT', 'MRVL'],- 'Internet Content & Information': ['GOOGL', 'META', 'SNAP', 'PINS', 'TWTR'],- 'Consumer Electronics': ['AAPL', 'SONY', 'DELL', 'HPQ', 'LOGI'],- 'E-Commerce': ['AMZN', 'SHOP', 'EBAY', 'ETSY', 'MELI', 'JD', 'BABA'],- 'Electric Vehicles': ['TSLA', 'RIVN', 'LCID', 'NIO', 'XPEV', 'LI'],- 'Auto Manufacturers': ['TSLA', 'F', 'GM', 'TM', 'HMC', 'STLA', 'RIVN'],- 'Banks': ['JPM', 'BAC', 'WFC', 'C', 'GS', 'MS', 'USB', 'PNC', 'TFC', 'COF'],- 'Insurance': ['BRK-B', 'UNH', 'AIG', 'MET', 'PRU', 'ALL', 'TRV', 'CB', 'PGR', 'AFL'],- 'Pharmaceuticals': ['JNJ', 'PFE', 'MRK', 'ABBV', 'LLY', 'BMY', 'AMGN', 'GILD', 'BIIB', 'REGN'],- 'Biotechnology': ['AMGN', 'GILD', 'BIIB', 'REGN', 'VRTX', 'MRNA', 'BNTX'],- 'Oil & Gas': ['XOM', 'CVX', 'COP', 'EOG', 'SLB', 'MPC', 'VLO', 'PSX', 'OXY', 'DVN'],- 'Retail': ['WMT', 'COST', 'TGT', 'HD', 'LOW', 'DG', 'DLTR', 'KR'],- 'Aerospace & Defense': ['LMT', 'RTX', 'BA', 'NOC', 'GD', 'LHX', 'TDG'],- 'Streaming': ['NFLX', 'DIS', 'PARA', 'WBD', 'ROKU'],- 'Cloud Computing': ['AMZN', 'MSFT', 'GOOGL', 'CRM', 'NOW', 'SNOW', 'NET', 'DDOG'],- 'Payments': ['V', 'MA', 'PYPL', 'SQ', 'FIS', 'FISV', 'GPN'],- 'Real Estate': ['AMT', 'PLD', 'CCI', 'EQIX', 'SPG', 'O', 'DLR', 'PSA'],- 'Utilities': ['NEE', 'DUK', 'SO', 'D', 'AEP', 'SRE', 'XEL', 'ES', 'WEC', 'ED'],-};--function findPeersByIndustry(ticker: string, industry: string, sector: string): string[] {- // Try exact industry match first- for (const [key, peers] of Object.entries(INDUSTRY_PEERS)) {- if (industry.toLowerCase().includes(key.toLowerCase()) ||- key.toLowerCase().includes(industry.toLowerCase())) {- return peers.filter(p => p !== ticker).slice(0, DATA_LIMITS.MAX_PEERS);- }- }- // Try sector match- for (const [key, peers] of Object.entries(INDUSTRY_PEERS)) {- if (sector.toLowerCase().includes(key.toLowerCase()) ||- key.toLowerCase().includes(sector.toLowerCase())) {- return peers.filter(p => p !== ticker).slice(0, DATA_LIMITS.MAX_PEERS);- }- }- // Fallback to broad tech/general- return ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'META', 'NVDA'].filter(p => p !== ticker).slice(0, 5);-}--// ============================================================================-// SERVICE CLASS-// ============================================================================--class RelationshipMapServiceV2 {- private cache = new DataCache();-- /**- * Clear cache for a specific ticker or all- */- clearCache(ticker?: string): void {- if (ticker) {- this.cache.clear(ticker.toUpperCase());- } else {- this.cache.clear();- }- }-- /**- * Get comprehensive relationship map data with progressive loading.- * Calls the onProgress callback as data becomes available.- */- async getRelationshipMap(- ticker: string,- onProgress?: (phase: LoadingPhase) => void- ): Promise<RelationshipMapDataV2> {- const upperTicker = ticker.toUpperCase();-- // Check cache- const cached = this.cache.get<RelationshipMapDataV2>(`${upperTicker}:full`);- if (cached) {- onProgress?.({ phase: 'complete', progress: 100, message: 'Loaded from cache' });- return cached;- }-- try {- // ====================================================================- // PHASE 1: Company Info (0-30%)- // ====================================================================- onProgress?.({ phase: 'company', progress: 5, message: 'Fetching company data...' });-- const [edgarCompany, yfinanceInfo, edgarProxy] = await Promise.all([- withTimeout(this.fetchEdgarCompany(ticker), TIMEOUTS.EDGAR_COMPANY, 'EdgarCompany'),- withTimeout(this.fetchYFinanceInfo(ticker), TIMEOUTS.YFINANCE_INFO, 'YFinanceInfo'),- withTimeout(this.fetchEdgarProxy(ticker), TIMEOUTS.EDGAR_PROXY, 'EdgarProxy'),- ]);-- onProgress?.({ phase: 'company', progress: 30, message: 'Company data loaded' });-- // Build company info- const company = this.buildCompanyInfo(ticker, edgarCompany, yfinanceInfo);- const executives = this.extractExecutives(edgarProxy);-- // ====================================================================- // PHASE 2: Ownership (30-60%)- // ====================================================================- onProgress?.({ phase: 'ownership', progress: 35, message: 'Fetching ownership data...' });-- const [insiderData, edgarFilings, edgarEvents] = await Promise.all([- withTimeout(this.fetchEdgarInsiderTransactions(ticker), TIMEOUTS.EDGAR_INSIDER, 'InsiderTx'),- withTimeout(this.fetchEdgarFilings(ticker), TIMEOUTS.EDGAR_FILINGS, 'Filings'),- withTimeout(this.fetchEdgarCorporateEvents(ticker), TIMEOUTS.EDGAR_EVENTS, 'Events'),- ]);-- onProgress?.({ phase: 'ownership', progress: 55, message: 'Ownership data loaded' });-- // Build institutional holders from yfinance ownership percentages- const institutionalHolders = this.buildInstitutionalHolders(yfinanceInfo);- const fundFamilies = this.buildFundFamilies(institutionalHolders);- const insiderHolders = this.buildInsiderHolders(insiderData, edgarProxy);- const insiderTransactions = this.buildInsiderTransactions(insiderData);- const filings = this.extractFilings(edgarFilings);- const corporateEvents = this.extractCorporateEvents(edgarEvents);-- onProgress?.({ phase: 'ownership', progress: 60, message: 'Processing ownership structure...' });-- // ====================================================================- // PHASE 3: Peers (60-80%)- // ====================================================================- onProgress?.({ phase: 'peers', progress: 65, message: 'Finding peer companies...' });-- const peerTickers = findPeersByIndustry(ticker, company.industry, company.sector);- const peers = await this.fetchPeerData(peerTickers);-- onProgress?.({ phase: 'peers', progress: 80, message: 'Calculating valuation signals...' });-- // Calculate valuation signals- const companyValuation = calculateValuationSignal(company, peers);- const peerValuations = calculatePeerValuations(peers);-- // ====================================================================- // PHASE 4: Supplementary (80-100%)- // ====================================================================- onProgress?.({ phase: 'supplementary', progress: 85, message: 'Finalizing data...' });-- // Calculate data quality score- const dataQuality = this.calculateDataQuality(- edgarCompany, yfinanceInfo, edgarProxy, insiderData,- edgarFilings, edgarEvents, peers- );-- const result: RelationshipMapDataV2 = {- company,- executives,- institutionalHolders,- fundFamilies,- insiderHolders,- insiderTransactions,- peers,- peerValuations,- corporateEvents,- filings,- companyValuation,- timestamp: new Date().toISOString(),- dataQuality,- };-- // Store in cache- this.cache.set(`${upperTicker}:full`, result, CACHE_TTL.REALTIME);-- onProgress?.({ phase: 'complete', progress: 100, message: 'Complete' });- return result;- } catch (error) {- console.error('[RelMapV2] Error:', error);- onProgress?.({ phase: 'error', progress: 0, message: `Error: ${error}` });- throw error;- }- }-- // ==========================================================================- // DATA FETCHING METHODS- // ==========================================================================-- private async fetchEdgarCompany(ticker: string): Promise<any> {- try {- const result = await invoke<string>('execute_edgar_command', {- command: 'get_company', args: [ticker]- });- const parsed = JSON.parse(result);- return parsed?.error ? null : parsed;- } catch (e) {- console.error('[RelMapV2] Edgar company error:', e);- return null;- }- }-- private async fetchEdgarProxy(ticker: string): Promise<any> {- try {- const result = await invoke<string>('execute_edgar_command', {- command: 'get_proxy_statement', args: [ticker]- });- const parsed = JSON.parse(result);- return parsed?.error ? null : parsed;- } catch (e) {- console.error('[RelMapV2] Edgar proxy error:', e);- return null;- }- }-- private async fetchEdgarFilings(ticker: string): Promise<any> {- try {- const result = await invoke<string>('execute_edgar_command', {- command: 'get_company_filings', args: [ticker, '', '', '', '15']- });- const parsed = JSON.parse(result);- return parsed?.error ? null : parsed;- } catch (e) {- console.error('[RelMapV2] Edgar filings error:', e);- return null;- }- }-- private async fetchEdgarCorporateEvents(ticker: string): Promise<any> {- try {- const result = await invoke<string>('execute_edgar_command', {- command: 'get_corporate_events', args: [ticker, '10']- });- const parsed = JSON.parse(result);- return parsed?.error ? null : parsed;- } catch (e) {- console.error('[RelMapV2] Edgar events error:', e);- return null;- }- }-- private async fetchEdgarInsiderTransactions(ticker: string): Promise<any> {- try {- const result = await invoke<string>('execute_edgar_command', {- command: 'get_insider_transactions', args: [ticker, '10']- });- const parsed = JSON.parse(result);- return parsed?.error ? null : parsed;- } catch (e) {- console.error('[RelMapV2] Edgar insider error:', e);- return null;- }- }-- private async fetchYFinanceInfo(ticker: string): Promise<any> {- try {- const result = await invoke<string>('execute_yfinance_command', {- command: 'info', args: [ticker]- });- const parsed = JSON.parse(result);- return parsed?.error ? null : parsed;- } catch (e) {- console.error('[RelMapV2] YFinance info error:', e);- return null;- }- }-- private async fetchPeerData(tickers: string[]): Promise<PeerCompany[]> {- const peers: PeerCompany[] = [];- // Fetch peer data in parallel batches of 4- const batchSize = 4;- for (let i = 0; i < tickers.length; i += batchSize) {- const batch = tickers.slice(i, i + batchSize);- const results = await Promise.all(- batch.map(t => withTimeout(this.fetchYFinanceInfo(t), TIMEOUTS.YFINANCE_PEERS, `Peer:${t}`))- );- for (let j = 0; j < results.length; j++) {- const data = results[j];- if (data) {- peers.push({- ticker: batch[j],- name: data.company_name || batch[j],- market_cap: data.market_cap || 0,- pe_ratio: data.pe_ratio || 0,- price_to_book: data.price_to_book || 0,- price_to_sales: data.enterprise_to_revenue || 0,- roe: data.return_on_equity || 0,- revenue_growth: data.revenue_growth || 0,- profit_margins: data.profit_margins || 0,- current_price: data.current_price || 0,- sector: data.sector || 'N/A',- industry: data.industry || 'N/A',- });- }- }- }- return peers;- }-- // ==========================================================================- // DATA BUILDING METHODS- // ==========================================================================-- private buildCompanyInfo(ticker: string, edgarCompany: any, yfinanceData: any): CompanyInfoV2 {- return {- ticker: ticker.toUpperCase(),- name: edgarCompany?.data?.name || yfinanceData?.company_name || ticker,- cik: edgarCompany?.data?.cik?.toString() || '',- industry: edgarCompany?.data?.industry || yfinanceData?.industry || 'N/A',- sic: edgarCompany?.data?.sic || '',- sector: yfinanceData?.sector || 'N/A',- address: edgarCompany?.data?.business_address || '',- exchange: yfinanceData?.exchange || 'N/A',- employees: yfinanceData?.employees || 0,- website: yfinanceData?.website || '',- description: yfinanceData?.description || '',- market_cap: yfinanceData?.market_cap || 0,- current_price: yfinanceData?.current_price || 0,- pe_ratio: yfinanceData?.pe_ratio || 0,- forward_pe: yfinanceData?.forward_pe || 0,- price_to_book: yfinanceData?.price_to_book || 0,- price_to_sales: yfinanceData?.enterprise_to_revenue || 0,- peg_ratio: yfinanceData?.peg_ratio || 0,- enterprise_value: yfinanceData?.enterprise_value || 0,- enterprise_to_revenue: yfinanceData?.enterprise_to_revenue || 0,- profit_margins: yfinanceData?.profit_margins || 0,- operating_margins: yfinanceData?.operating_margins || 0,- roe: yfinanceData?.return_on_equity || 0,- roa: yfinanceData?.return_on_assets || 0,- revenue_growth: yfinanceData?.revenue_growth || 0,- earnings_growth: yfinanceData?.earnings_growth || 0,- revenue: yfinanceData?.total_revenue || 0,- gross_profit: yfinanceData?.gross_profits || 0,- ebitda: (yfinanceData?.total_revenue || 0) * (yfinanceData?.ebitda_margins || 0),- free_cashflow: yfinanceData?.free_cashflow || 0,- total_cash: yfinanceData?.total_cash || 0,- total_debt: yfinanceData?.total_debt || 0,- insider_percent: (yfinanceData?.held_percent_insiders || 0) * 100,- institutional_percent: (yfinanceData?.held_percent_institutions || 0) * 100,- shares_outstanding: yfinanceData?.shares_outstanding || 0,- float_shares: yfinanceData?.float_shares || 0,- recommendation: yfinanceData?.recommendation_key || 'N/A',- target_price: yfinanceData?.target_mean_price || 0,- analyst_count: yfinanceData?.number_of_analyst_opinions || 0,- };- }-- private extractExecutives(proxyData: any): Executive[] {- if (!proxyData?.data?.named_executives?.length) return [];- const executives: Executive[] = [];- const seen = new Set<string>();-- for (const exec of proxyData.data.named_executives) {- const name = exec.name;- if (name && !seen.has(name)) {- seen.add(name);- executives.push({- name,- role: this.parseRole(exec.role),- compensation: exec.total_comp,- });- }- }- return executives.slice(0, 15);- }-- private parseRole(role: string): string {- if (!role) return 'Executive';- if (role.includes('Peo') || role.includes('CEO')) return 'CEO';- if (role.includes('CFO')) return 'CFO';- if (role.includes('Neo')) return 'Executive Officer';- if (role.includes('COO')) return 'COO';- if (role.includes('CTO')) return 'CTO';- return role;- }-- private buildInstitutionalHolders(yfinanceData: any): InstitutionalHolder[] {- // Use yfinance ownership percentage to generate representative institutional holder nodes- const institutionalPercent = (yfinanceData?.held_percent_institutions || 0) * 100;- if (institutionalPercent <= 0) return [];-- // Top known institutional holders for major US stocks (representative data)- const knownHolders = [- { name: 'Vanguard Group', typicalShare: 0.08 },- { name: 'BlackRock', typicalShare: 0.07 },- { name: 'State Street', typicalShare: 0.04 },- { name: 'Fidelity Management', typicalShare: 0.035 },- { name: 'Capital Research', typicalShare: 0.03 },- { name: 'T. Rowe Price', typicalShare: 0.025 },- { name: 'Geode Capital', typicalShare: 0.02 },- { name: 'Morgan Stanley', typicalShare: 0.018 },- { name: 'Northern Trust', typicalShare: 0.015 },- { name: 'Bank of America', typicalShare: 0.012 },- ];-- const sharesOutstanding = yfinanceData?.shares_outstanding || 0;- const price = yfinanceData?.current_price || 0;- const holders: InstitutionalHolder[] = [];-- // Scale to match actual institutional ownership percentage- const scaleFactor = institutionalPercent / 100;-- for (const known of knownHolders) {- const percentage = known.typicalShare * scaleFactor * 100;- if (percentage < 0.5) continue; // Skip if less than 0.5%- const shares = Math.round(sharesOutstanding * known.typicalShare * scaleFactor);- holders.push({- name: known.name,- shares,- value: shares * price,- percentage: parseFloat(percentage.toFixed(2)),- fund_family: known.name,- });- }-- return holders.slice(0, DATA_LIMITS.MAX_INSTITUTIONAL_HOLDERS);- }-- private buildFundFamilies(holders: InstitutionalHolder[]): FundFamily[] {- const familyMap = new Map<string, InstitutionalHolder[]>();-- for (const holder of holders) {- const family = holder.fund_family || holder.name;- if (!familyMap.has(family)) familyMap.set(family, []);- familyMap.get(family)!.push(holder);- }-- const families: FundFamily[] = [];- for (const [name, funds] of familyMap) {- if (funds.length === 0) continue;- families.push({- name,- total_shares: funds.reduce((s, f) => s + f.shares, 0),- total_value: funds.reduce((s, f) => s + f.value, 0),- total_percentage: funds.reduce((s, f) => s + f.percentage, 0),- funds,- change_trend: 'stable',- });- }-- return families- .sort((a, b) => b.total_percentage - a.total_percentage)- .slice(0, DATA_LIMITS.MAX_FUND_FAMILIES);- }-- private buildInsiderHolders(insiderData: any, proxyData: any): InsiderHolder[] {- const holders: InsiderHolder[] = [];-- // Extract from proxy data (executives with compensation = insiders)- if (proxyData?.data?.named_executives) {- for (const exec of proxyData.data.named_executives.slice(0, 5)) {- if (exec.name) {- holders.push({- name: exec.name,- title: this.parseRole(exec.role),- shares: 0, // Not directly available- value: 0,- percentage: 0,- last_transaction_type: undefined,- });- }- }- }-- // Enhance with insider transaction data- if (insiderData?.data) {- for (const tx of insiderData.data.slice(0, 10)) {- const existing = holders.find(h =>- tx.reporting_owner && h.name.toLowerCase().includes(tx.reporting_owner.toLowerCase().split(' ')[0])- );- if (existing && tx.filing_date) {- existing.last_transaction_date = tx.filing_date;- }- }- }-- return holders.slice(0, DATA_LIMITS.MAX_INSIDER_HOLDERS);- }-- private buildInsiderTransactions(insiderData: any): InsiderTransaction[] {- if (!insiderData?.data) return [];-- return insiderData.data.slice(0, DATA_LIMITS.MAX_INSIDER_TRANSACTIONS).map((tx: any) => ({- name: tx.reporting_owner || 'Unknown',- title: 'Insider',- transaction_type: 'buy' as const,- shares: 0,- value: 0,- price: 0,- date: tx.filing_date || '',- shares_remaining: 0,- }));- }-- private extractFilings(filingsData: any): FilingV2[] {- if (!filingsData?.data) return [];-- return filingsData.data.slice(0, DATA_LIMITS.MAX_FILINGS).map((f: any) => ({- form: f.form || '',- filing_date: f.filing_date || '',- description: this.getFilingDescription(f.form),- url: f.filing_url || '',- period: f.period_of_report || '',- }));- }-- private extractCorporateEvents(eventsData: any): CorporateEventV2[] {- if (!eventsData?.data) return [];-- return eventsData.data.slice(0, DATA_LIMITS.MAX_EVENTS).map((e: any) => ({- filing_date: e.filing_date || '',- period_of_report: e.period_of_report || '',- form: e.form || '8-K',- filing_url: e.filing_url || '',- accession_number: e.accession_number || '',- items: e.items || [],- description: e.description || e.items?.[0] || '8-K Filing',- category: this.categorizeEvent(e.items) as CorporateEventV2['category'],- }));- }-- private categorizeEvent(items: string[]): string {- if (!items || items.length === 0) return 'other';- const first = items[0]?.toLowerCase() || '';- if (first.includes('result') || first.includes('earning')) return 'earnings';- if (first.includes('officer') || first.includes('director')) return 'management';- if (first.includes('merger') || first.includes('acqui')) return 'merger';- if (first.includes('restructur') || first.includes('impair')) return 'restructuring';- if (first.includes('bylaw') || first.includes('governance')) return 'governance';- return 'other';- }-- private getFilingDescription(form: string): string {- const descriptions: Record<string, string> = {- '10-K': 'Annual Report', '10-Q': 'Quarterly Report',- '8-K': 'Current Event', '4': 'Insider Trading',- 'DEF 14A': 'Proxy Statement', '13F-HR': 'Institutional Holdings',- 'S-8': 'Employee Stock Plan', 'SC 13G': '5%+ Ownership',- 'DEFA14A': 'Proxy Materials', '144': 'Insider Sale Notice',- };- return descriptions[form] || form;- }-- private calculateDataQuality(- edgarCompany: any, yfinanceInfo: any, edgarProxy: any,- insiderData: any, edgarFilings: any, edgarEvents: any,- peers: PeerCompany[]- ): DataQualityScore {- const sources = {- edgar_company: !!edgarCompany,- edgar_filings: !!edgarFilings?.data?.length,- edgar_proxy: !!edgarProxy?.data,- edgar_institutional: true, // We always have yfinance percent data- edgar_insider: !!insiderData?.data?.length,- yfinance: !!yfinanceInfo,- peers: peers.length >= 3,- };-- const successCount = Object.values(sources).filter(Boolean).length;- const overall = Math.round((successCount / Object.keys(sources).length) * 100);-- // Completeness: how many key fields have non-zero values- const keyFields = [- yfinanceInfo?.market_cap, yfinanceInfo?.pe_ratio, yfinanceInfo?.revenue_growth,- yfinanceInfo?.profit_margins, yfinanceInfo?.return_on_equity,- edgarCompany?.data?.name, edgarFilings?.data?.length,- ];- const filled = keyFields.filter(v => v && v !== 0 && v !== 'N/A').length;- const completeness = Math.round((filled / keyFields.length) * 100);-- return { overall, sources, completeness };- }-}--export const relationshipMapServiceV2 = new RelationshipMapServiceV2();