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
marketplace removed
tilakpatel22c065d25a3427
diff --git a/fincept-terminal-desktop/public/locales/ar/marketplace.json b/fincept-terminal-desktop/public/locales/ar/marketplace.jsondeleted file mode 100644index 1dfbc579f..000000000--- a/fincept-terminal-desktop/public/locales/ar/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "السوق",- "header": {- "browse": "تصفح",- "myPurchases": "[AR] MY PURCHASES",- "upload": "[AR] UPLOAD",- "myDatasets": "[AR] MY DATASETS",- "analytics": "[AR] ANALYTICS",- "pricing": "[AR] PRICING",- "datasetsAvailable": "[AR] Datasets Available",- "myUploads": "[AR] My Uploads"- },- "buttons": {- "addToCart": "أضف للسلة",- "inCart": "[AR] ✓ IN CART",- "viewDetails": "[AR] VIEW DETAILS",- "backToMarketplace": "[AR] BACK TO MARKETPLACE",- "loading": "[AR] ⟳ LOADING...",- "refresh": "[AR] 🔄 REFRESH"- },- "product": {- "rating": "التقييم",- "description": "[AR] PRODUCT DESCRIPTION",- "users": "[AR] USERS"- },- "cart": {- "empty": "السلة فارغة",- "title": "[AR] SHOPPING CART",- "items": "[AR] items"- },- "guest": {- "title": "[AR] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[AR] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/bn/marketplace.json b/fincept-terminal-desktop/public/locales/bn/marketplace.jsondeleted file mode 100644index 4120c70a9..000000000--- a/fincept-terminal-desktop/public/locales/bn/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "মার্কেটপ্লেস",- "header": {- "browse": "ব্রাউজ",- "myPurchases": "[BN] MY PURCHASES",- "upload": "[BN] UPLOAD",- "myDatasets": "[BN] MY DATASETS",- "analytics": "[BN] ANALYTICS",- "pricing": "[BN] PRICING",- "datasetsAvailable": "[BN] Datasets Available",- "myUploads": "[BN] My Uploads"- },- "buttons": {- "addToCart": "কার্টে যোগ",- "inCart": "[BN] ✓ IN CART",- "viewDetails": "[BN] VIEW DETAILS",- "backToMarketplace": "[BN] BACK TO MARKETPLACE",- "loading": "[BN] ⟳ LOADING...",- "refresh": "[BN] 🔄 REFRESH"- },- "product": {- "rating": "রেটিং",- "description": "[BN] PRODUCT DESCRIPTION",- "users": "[BN] USERS"- },- "cart": {- "empty": "কার্ট খালি",- "title": "[BN] SHOPPING CART",- "items": "[BN] items"- },- "guest": {- "title": "[BN] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[BN] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/de/marketplace.json b/fincept-terminal-desktop/public/locales/de/marketplace.jsondeleted file mode 100644index 7f015ff3e..000000000--- a/fincept-terminal-desktop/public/locales/de/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Durchsuchen",- "myPurchases": "[DE] MY PURCHASES",- "upload": "[DE] UPLOAD",- "myDatasets": "[DE] MY DATASETS",- "analytics": "[DE] ANALYTICS",- "pricing": "[DE] PRICING",- "datasetsAvailable": "[DE] Datasets Available",- "myUploads": "[DE] My Uploads"- },- "buttons": {- "addToCart": "In den Warenkorb",- "inCart": "[DE] ✓ IN CART",- "viewDetails": "[DE] VIEW DETAILS",- "backToMarketplace": "[DE] BACK TO MARKETPLACE",- "loading": "[DE] ⟳ LOADING...",- "refresh": "[DE] 🔄 REFRESH"- },- "product": {- "rating": "Bewertung",- "description": "[DE] PRODUCT DESCRIPTION",- "users": "[DE] USERS"- },- "cart": {- "empty": "Warenkorb leer",- "title": "[DE] SHOPPING CART",- "items": "[DE] items"- },- "guest": {- "title": "[DE] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[DE] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/en/marketplace.json b/fincept-terminal-desktop/public/locales/en/marketplace.jsondeleted file mode 100644index 433db63f3..000000000--- a/fincept-terminal-desktop/public/locales/en/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "FINCEPT MARKETPLACE",- "header": {- "browse": "BROWSE",- "myPurchases": "MY PURCHASES",- "upload": "UPLOAD",- "myDatasets": "MY DATASETS",- "analytics": "ANALYTICS",- "pricing": "PRICING",- "datasetsAvailable": "Datasets Available",- "myUploads": "My Uploads"- },- "guest": {- "title": "MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- },- "product": {- "description": "PRODUCT DESCRIPTION",- "rating": "RATING",- "users": "USERS"- },- "buttons": {- "addToCart": "ADD TO CART",- "inCart": "✓ IN CART",- "viewDetails": "VIEW DETAILS",- "backToMarketplace": "BACK TO MARKETPLACE",- "loading": "⟳ LOADING...",- "refresh": "🔄 REFRESH"- },- "cart": {- "title": "SHOPPING CART",- "items": "items",- "empty": "Your cart is empty"- }-}diff --git a/fincept-terminal-desktop/public/locales/es/marketplace.json b/fincept-terminal-desktop/public/locales/es/marketplace.jsondeleted file mode 100644index 917f5f49d..000000000--- a/fincept-terminal-desktop/public/locales/es/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Explorar",- "myPurchases": "[ES] MY PURCHASES",- "upload": "[ES] UPLOAD",- "myDatasets": "[ES] MY DATASETS",- "analytics": "[ES] ANALYTICS",- "pricing": "[ES] PRICING",- "datasetsAvailable": "[ES] Datasets Available",- "myUploads": "[ES] My Uploads"- },- "buttons": {- "addToCart": "Añadir al carrito",- "inCart": "[ES] ✓ IN CART",- "viewDetails": "[ES] VIEW DETAILS",- "backToMarketplace": "[ES] BACK TO MARKETPLACE",- "loading": "[ES] ⟳ LOADING...",- "refresh": "[ES] 🔄 REFRESH"- },- "product": {- "rating": "Valoración",- "description": "[ES] PRODUCT DESCRIPTION",- "users": "[ES] USERS"- },- "cart": {- "empty": "Carrito vacío",- "title": "[ES] SHOPPING CART",- "items": "[ES] items"- },- "guest": {- "title": "[ES] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[ES] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/fr/marketplace.json b/fincept-terminal-desktop/public/locales/fr/marketplace.jsondeleted file mode 100644index bd14d8e83..000000000--- a/fincept-terminal-desktop/public/locales/fr/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Parcourir",- "myPurchases": "[FR] MY PURCHASES",- "upload": "[FR] UPLOAD",- "myDatasets": "[FR] MY DATASETS",- "analytics": "[FR] ANALYTICS",- "pricing": "[FR] PRICING",- "datasetsAvailable": "[FR] Datasets Available",- "myUploads": "[FR] My Uploads"- },- "buttons": {- "addToCart": "Ajouter au panier",- "inCart": "[FR] ✓ IN CART",- "viewDetails": "[FR] VIEW DETAILS",- "backToMarketplace": "[FR] BACK TO MARKETPLACE",- "loading": "[FR] ⟳ LOADING...",- "refresh": "[FR] 🔄 REFRESH"- },- "product": {- "rating": "Note",- "description": "[FR] PRODUCT DESCRIPTION",- "users": "[FR] USERS"- },- "cart": {- "empty": "Panier vide",- "title": "[FR] SHOPPING CART",- "items": "[FR] items"- },- "guest": {- "title": "[FR] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[FR] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/hi/marketplace.json b/fincept-terminal-desktop/public/locales/hi/marketplace.jsondeleted file mode 100644index 2af59776d..000000000--- a/fincept-terminal-desktop/public/locales/hi/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "मार्केटप्लेस",- "header": {- "browse": "ब्राउज़ करें",- "myPurchases": "[HI] MY PURCHASES",- "upload": "[HI] UPLOAD",- "myDatasets": "[HI] MY DATASETS",- "analytics": "[HI] ANALYTICS",- "pricing": "[HI] PRICING",- "datasetsAvailable": "[HI] Datasets Available",- "myUploads": "[HI] My Uploads"- },- "buttons": {- "addToCart": "कार्ट में जोड़ें",- "inCart": "[HI] ✓ IN CART",- "viewDetails": "[HI] VIEW DETAILS",- "backToMarketplace": "[HI] BACK TO MARKETPLACE",- "loading": "[HI] ⟳ LOADING...",- "refresh": "[HI] 🔄 REFRESH"- },- "product": {- "rating": "रेटिंग",- "description": "[HI] PRODUCT DESCRIPTION",- "users": "[HI] USERS"- },- "cart": {- "empty": "कार्ट खाली है",- "title": "[HI] SHOPPING CART",- "items": "[HI] items"- },- "guest": {- "title": "[HI] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[HI] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/id/marketplace.json b/fincept-terminal-desktop/public/locales/id/marketplace.jsondeleted file mode 100644index b225e9001..000000000--- a/fincept-terminal-desktop/public/locales/id/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Jelajahi",- "myPurchases": "[ID] MY PURCHASES",- "upload": "[ID] UPLOAD",- "myDatasets": "[ID] MY DATASETS",- "analytics": "[ID] ANALYTICS",- "pricing": "[ID] PRICING",- "datasetsAvailable": "[ID] Datasets Available",- "myUploads": "[ID] My Uploads"- },- "buttons": {- "addToCart": "Tambah ke keranjang",- "inCart": "[ID] ✓ IN CART",- "viewDetails": "[ID] VIEW DETAILS",- "backToMarketplace": "[ID] BACK TO MARKETPLACE",- "loading": "[ID] ⟳ LOADING...",- "refresh": "[ID] 🔄 REFRESH"- },- "product": {- "rating": "Rating",- "description": "[ID] PRODUCT DESCRIPTION",- "users": "[ID] USERS"- },- "cart": {- "empty": "Keranjang kosong",- "title": "[ID] SHOPPING CART",- "items": "[ID] items"- },- "guest": {- "title": "[ID] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[ID] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/it/marketplace.json b/fincept-terminal-desktop/public/locales/it/marketplace.jsondeleted file mode 100644index d8ceda779..000000000--- a/fincept-terminal-desktop/public/locales/it/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Esplora",- "myPurchases": "[IT] MY PURCHASES",- "upload": "[IT] UPLOAD",- "myDatasets": "[IT] MY DATASETS",- "analytics": "[IT] ANALYTICS",- "pricing": "[IT] PRICING",- "datasetsAvailable": "[IT] Datasets Available",- "myUploads": "[IT] My Uploads"- },- "buttons": {- "addToCart": "Aggiungi al carrello",- "inCart": "[IT] ✓ IN CART",- "viewDetails": "[IT] VIEW DETAILS",- "backToMarketplace": "[IT] BACK TO MARKETPLACE",- "loading": "[IT] ⟳ LOADING...",- "refresh": "[IT] 🔄 REFRESH"- },- "product": {- "rating": "Valutazione",- "description": "[IT] PRODUCT DESCRIPTION",- "users": "[IT] USERS"- },- "cart": {- "empty": "Carrello vuoto",- "title": "[IT] SHOPPING CART",- "items": "[IT] items"- },- "guest": {- "title": "[IT] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[IT] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/ja/marketplace.json b/fincept-terminal-desktop/public/locales/ja/marketplace.jsondeleted file mode 100644index 0e492cc9b..000000000--- a/fincept-terminal-desktop/public/locales/ja/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "マーケットプレイス",- "header": {- "browse": "閲覧",- "myPurchases": "[JA] MY PURCHASES",- "upload": "[JA] UPLOAD",- "myDatasets": "[JA] MY DATASETS",- "analytics": "[JA] ANALYTICS",- "pricing": "[JA] PRICING",- "datasetsAvailable": "[JA] Datasets Available",- "myUploads": "[JA] My Uploads"- },- "buttons": {- "addToCart": "カートに追加",- "inCart": "[JA] ✓ IN CART",- "viewDetails": "[JA] VIEW DETAILS",- "backToMarketplace": "[JA] BACK TO MARKETPLACE",- "loading": "[JA] ⟳ LOADING...",- "refresh": "[JA] 🔄 REFRESH"- },- "product": {- "rating": "評価",- "description": "[JA] PRODUCT DESCRIPTION",- "users": "[JA] USERS"- },- "cart": {- "empty": "カートは空です",- "title": "[JA] SHOPPING CART",- "items": "[JA] items"- },- "guest": {- "title": "[JA] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[JA] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/ko/marketplace.json b/fincept-terminal-desktop/public/locales/ko/marketplace.jsondeleted file mode 100644index edc2b185e..000000000--- a/fincept-terminal-desktop/public/locales/ko/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "마켓플레이스",- "header": {- "browse": "둘러보기",- "myPurchases": "[KO] MY PURCHASES",- "upload": "[KO] UPLOAD",- "myDatasets": "[KO] MY DATASETS",- "analytics": "[KO] ANALYTICS",- "pricing": "[KO] PRICING",- "datasetsAvailable": "[KO] Datasets Available",- "myUploads": "[KO] My Uploads"- },- "buttons": {- "addToCart": "장바구니에 추가",- "inCart": "[KO] ✓ IN CART",- "viewDetails": "[KO] VIEW DETAILS",- "backToMarketplace": "[KO] BACK TO MARKETPLACE",- "loading": "[KO] ⟳ LOADING...",- "refresh": "[KO] 🔄 REFRESH"- },- "product": {- "rating": "평점",- "description": "[KO] PRODUCT DESCRIPTION",- "users": "[KO] USERS"- },- "cart": {- "empty": "장바구니가 비어있습니다",- "title": "[KO] SHOPPING CART",- "items": "[KO] items"- },- "guest": {- "title": "[KO] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[KO] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/pl/marketplace.json b/fincept-terminal-desktop/public/locales/pl/marketplace.jsondeleted file mode 100644index 08c531388..000000000--- a/fincept-terminal-desktop/public/locales/pl/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Przeglądaj",- "myPurchases": "[PL] MY PURCHASES",- "upload": "[PL] UPLOAD",- "myDatasets": "[PL] MY DATASETS",- "analytics": "[PL] ANALYTICS",- "pricing": "[PL] PRICING",- "datasetsAvailable": "[PL] Datasets Available",- "myUploads": "[PL] My Uploads"- },- "buttons": {- "addToCart": "Dodaj do koszyka",- "inCart": "[PL] ✓ IN CART",- "viewDetails": "[PL] VIEW DETAILS",- "backToMarketplace": "[PL] BACK TO MARKETPLACE",- "loading": "[PL] ⟳ LOADING...",- "refresh": "[PL] 🔄 REFRESH"- },- "product": {- "rating": "Ocena",- "description": "[PL] PRODUCT DESCRIPTION",- "users": "[PL] USERS"- },- "cart": {- "empty": "Koszyk pusty",- "title": "[PL] SHOPPING CART",- "items": "[PL] items"- },- "guest": {- "title": "[PL] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[PL] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/pt/marketplace.json b/fincept-terminal-desktop/public/locales/pt/marketplace.jsondeleted file mode 100644index 616e2eee8..000000000--- a/fincept-terminal-desktop/public/locales/pt/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Explorar",- "myPurchases": "[PT] MY PURCHASES",- "upload": "[PT] UPLOAD",- "myDatasets": "[PT] MY DATASETS",- "analytics": "[PT] ANALYTICS",- "pricing": "[PT] PRICING",- "datasetsAvailable": "[PT] Datasets Available",- "myUploads": "[PT] My Uploads"- },- "buttons": {- "addToCart": "Adicionar ao carrinho",- "inCart": "[PT] ✓ IN CART",- "viewDetails": "[PT] VIEW DETAILS",- "backToMarketplace": "[PT] BACK TO MARKETPLACE",- "loading": "[PT] ⟳ LOADING...",- "refresh": "[PT] 🔄 REFRESH"- },- "product": {- "rating": "Avaliação",- "description": "[PT] PRODUCT DESCRIPTION",- "users": "[PT] USERS"- },- "cart": {- "empty": "Carrinho vazio",- "title": "[PT] SHOPPING CART",- "items": "[PT] items"- },- "guest": {- "title": "[PT] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[PT] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/ro/marketplace.json b/fincept-terminal-desktop/public/locales/ro/marketplace.jsondeleted file mode 100644index a8b678a47..000000000--- a/fincept-terminal-desktop/public/locales/ro/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Răsfoiește",- "myPurchases": "[RO] MY PURCHASES",- "upload": "[RO] UPLOAD",- "myDatasets": "[RO] MY DATASETS",- "analytics": "[RO] ANALYTICS",- "pricing": "[RO] PRICING",- "datasetsAvailable": "[RO] Datasets Available",- "myUploads": "[RO] My Uploads"- },- "buttons": {- "addToCart": "Adaugă în coș",- "inCart": "[RO] ✓ IN CART",- "viewDetails": "[RO] VIEW DETAILS",- "backToMarketplace": "[RO] BACK TO MARKETPLACE",- "loading": "[RO] ⟳ LOADING...",- "refresh": "[RO] 🔄 REFRESH"- },- "product": {- "rating": "Rating",- "description": "[RO] PRODUCT DESCRIPTION",- "users": "[RO] USERS"- },- "cart": {- "empty": "Coș gol",- "title": "[RO] SHOPPING CART",- "items": "[RO] items"- },- "guest": {- "title": "[RO] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[RO] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/ru/marketplace.json b/fincept-terminal-desktop/public/locales/ru/marketplace.jsondeleted file mode 100644index d576f9bc4..000000000--- a/fincept-terminal-desktop/public/locales/ru/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "МАРКЕТПЛЕЙС",- "header": {- "browse": "Обзор",- "myPurchases": "[RU] MY PURCHASES",- "upload": "[RU] UPLOAD",- "myDatasets": "[RU] MY DATASETS",- "analytics": "[RU] ANALYTICS",- "pricing": "[RU] PRICING",- "datasetsAvailable": "[RU] Datasets Available",- "myUploads": "[RU] My Uploads"- },- "buttons": {- "addToCart": "В корзину",- "inCart": "[RU] ✓ IN CART",- "viewDetails": "[RU] VIEW DETAILS",- "backToMarketplace": "[RU] BACK TO MARKETPLACE",- "loading": "[RU] ⟳ LOADING...",- "refresh": "[RU] 🔄 REFRESH"- },- "product": {- "rating": "Рейтинг",- "description": "[RU] PRODUCT DESCRIPTION",- "users": "[RU] USERS"- },- "cart": {- "empty": "Корзина пуста",- "title": "[RU] SHOPPING CART",- "items": "[RU] items"- },- "guest": {- "title": "[RU] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[RU] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/th/marketplace.json b/fincept-terminal-desktop/public/locales/th/marketplace.jsondeleted file mode 100644index 8dae9d3e8..000000000--- a/fincept-terminal-desktop/public/locales/th/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "ตลาด",- "header": {- "browse": "เรียกดู",- "myPurchases": "[TH] MY PURCHASES",- "upload": "[TH] UPLOAD",- "myDatasets": "[TH] MY DATASETS",- "analytics": "[TH] ANALYTICS",- "pricing": "[TH] PRICING",- "datasetsAvailable": "[TH] Datasets Available",- "myUploads": "[TH] My Uploads"- },- "buttons": {- "addToCart": "เพิ่มในตะกร้า",- "inCart": "[TH] ✓ IN CART",- "viewDetails": "[TH] VIEW DETAILS",- "backToMarketplace": "[TH] BACK TO MARKETPLACE",- "loading": "[TH] ⟳ LOADING...",- "refresh": "[TH] 🔄 REFRESH"- },- "product": {- "rating": "คะแนน",- "description": "[TH] PRODUCT DESCRIPTION",- "users": "[TH] USERS"- },- "cart": {- "empty": "ตะกร้าว่าง",- "title": "[TH] SHOPPING CART",- "items": "[TH] items"- },- "guest": {- "title": "[TH] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[TH] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/tr/marketplace.json b/fincept-terminal-desktop/public/locales/tr/marketplace.jsondeleted file mode 100644index d32150d7c..000000000--- a/fincept-terminal-desktop/public/locales/tr/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "MARKETPLACE",- "header": {- "browse": "Gözat",- "myPurchases": "[TR] MY PURCHASES",- "upload": "[TR] UPLOAD",- "myDatasets": "[TR] MY DATASETS",- "analytics": "[TR] ANALYTICS",- "pricing": "[TR] PRICING",- "datasetsAvailable": "[TR] Datasets Available",- "myUploads": "[TR] My Uploads"- },- "buttons": {- "addToCart": "Sepete ekle",- "inCart": "[TR] ✓ IN CART",- "viewDetails": "[TR] VIEW DETAILS",- "backToMarketplace": "[TR] BACK TO MARKETPLACE",- "loading": "[TR] ⟳ LOADING...",- "refresh": "[TR] 🔄 REFRESH"- },- "product": {- "rating": "Puan",- "description": "[TR] PRODUCT DESCRIPTION",- "users": "[TR] USERS"- },- "cart": {- "empty": "Sepet boş",- "title": "[TR] SHOPPING CART",- "items": "[TR] items"- },- "guest": {- "title": "[TR] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[TR] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/uk/marketplace.json b/fincept-terminal-desktop/public/locales/uk/marketplace.jsondeleted file mode 100644index 1d061d3d4..000000000--- a/fincept-terminal-desktop/public/locales/uk/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "МАРКЕТПЛЕЙС",- "header": {- "browse": "Переглянути",- "myPurchases": "[UK] MY PURCHASES",- "upload": "[UK] UPLOAD",- "myDatasets": "[UK] MY DATASETS",- "analytics": "[UK] ANALYTICS",- "pricing": "[UK] PRICING",- "datasetsAvailable": "[UK] Datasets Available",- "myUploads": "[UK] My Uploads"- },- "buttons": {- "addToCart": "До кошика",- "inCart": "[UK] ✓ IN CART",- "viewDetails": "[UK] VIEW DETAILS",- "backToMarketplace": "[UK] BACK TO MARKETPLACE",- "loading": "[UK] ⟳ LOADING...",- "refresh": "[UK] 🔄 REFRESH"- },- "product": {- "rating": "Рейтинг",- "description": "[UK] PRODUCT DESCRIPTION",- "users": "[UK] USERS"- },- "cart": {- "empty": "Кошик порожній",- "title": "[UK] SHOPPING CART",- "items": "[UK] items"- },- "guest": {- "title": "[UK] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[UK] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/vi/marketplace.json b/fincept-terminal-desktop/public/locales/vi/marketplace.jsondeleted file mode 100644index 4900120b5..000000000--- a/fincept-terminal-desktop/public/locales/vi/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "CHỢ",- "header": {- "browse": "Duyệt",- "myPurchases": "[VI] MY PURCHASES",- "upload": "[VI] UPLOAD",- "myDatasets": "[VI] MY DATASETS",- "analytics": "[VI] ANALYTICS",- "pricing": "[VI] PRICING",- "datasetsAvailable": "[VI] Datasets Available",- "myUploads": "[VI] My Uploads"- },- "buttons": {- "addToCart": "Thêm vào giỏ",- "inCart": "[VI] ✓ IN CART",- "viewDetails": "[VI] VIEW DETAILS",- "backToMarketplace": "[VI] BACK TO MARKETPLACE",- "loading": "[VI] ⟳ LOADING...",- "refresh": "[VI] 🔄 REFRESH"- },- "product": {- "rating": "Đánh giá",- "description": "[VI] PRODUCT DESCRIPTION",- "users": "[VI] USERS"- },- "cart": {- "empty": "Giỏ trống",- "title": "[VI] SHOPPING CART",- "items": "[VI] items"- },- "guest": {- "title": "[VI] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[VI] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/public/locales/zh/marketplace.json b/fincept-terminal-desktop/public/locales/zh/marketplace.jsondeleted file mode 100644index 65c344a43..000000000--- a/fincept-terminal-desktop/public/locales/zh/marketplace.json+++ /dev/null@@ -1,35 +0,0 @@-{- "title": "市场",- "header": {- "browse": "浏览",- "myPurchases": "[ZH] MY PURCHASES",- "upload": "[ZH] UPLOAD",- "myDatasets": "[ZH] MY DATASETS",- "analytics": "[ZH] ANALYTICS",- "pricing": "[ZH] PRICING",- "datasetsAvailable": "[ZH] Datasets Available",- "myUploads": "[ZH] My Uploads"- },- "buttons": {- "addToCart": "加入购物车",- "inCart": "[ZH] ✓ IN CART",- "viewDetails": "[ZH] VIEW DETAILS",- "backToMarketplace": "[ZH] BACK TO MARKETPLACE",- "loading": "[ZH] ⟳ LOADING...",- "refresh": "[ZH] 🔄 REFRESH"- },- "product": {- "rating": "评分",- "description": "[ZH] PRODUCT DESCRIPTION",- "users": "[ZH] USERS"- },- "cart": {- "empty": "购物车为空",- "title": "[ZH] SHOPPING CART",- "items": "[ZH] items"- },- "guest": {- "title": "[ZH] MARKETPLACE REQUIRES REGISTERED ACCOUNT",- "message": "[ZH] Guest users cannot access marketplace features. Please register to upload, purchase, and trade datasets."- }-}diff --git a/fincept-terminal-desktop/src-tauri/resources/scripts/polymarket_quant_bot.py b/fincept-terminal-desktop/src-tauri/resources/scripts/polymarket_quant_bot.pynew file mode 100644index 000000000..187663149--- /dev/null+++ b/fincept-terminal-desktop/src-tauri/resources/scripts/polymarket_quant_bot.py@@ -0,0 +1,827 @@+"""+Polymarket Quant Bot -- Standalone Demo+=======================================+A quantitative trading bot for Polymarket prediction markets.++How it works (4 steps):+1. READ PRICES — Pull live contract prices from Polymarket Gamma API+2. ESTIMATE PROB — Particle filter + Bayesian model estimates "true" probability+3. FIND EDGE — Compare model probability vs market price+4. EXECUTE TRADE — Paper trade if edge > threshold, with full risk controls++Run: python polymarket_quant_bot.py+Deps: pip install numpy scipy requests++Author: Fincept Corporation+License: AGPL-3.0-or-later+"""++import time+import json+import sys+import math+import random+from datetime import datetime, timezone+from dataclasses import dataclass, field+from typing import Optional++try:+ import numpy as np+ from scipy.special import expit, logit+ from scipy.stats import norm+ import requests+except ImportError:+ print("Missing dependencies. Install with:")+ print(" pip install numpy scipy requests")+ sys.exit(1)+++# ==============================================================================+# CONFIGURATION+# ==============================================================================++GAMMA_API = "https://gamma-api.polymarket.com"+CLOB_API = "https://clob.polymarket.com"++# Bot settings+SCAN_LIMIT = 15 # Markets to scan per cycle+EDGE_THRESHOLD = 0.05 # Minimum 5-cent edge to trade+MIN_CONFIDENCE = 65 # Minimum confidence score (0-100)+CYCLE_INTERVAL_SEC = 60 # Seconds between scan cycles+NUM_CYCLES = 10 # Total cycles to run (set 0 for infinite)++# Risk limits+MAX_POSITION_USDC = 50.0 # Max per contract+MAX_EXPOSURE_USDC = 200.0 # Max total portfolio exposure+STOP_LOSS_PCT = 30.0 # Exit if position drops 30%+TAKE_PROFIT_PCT = 50.0 # Exit if position gains 50%+MAX_BRIER_SCORE = 0.25 # Pause trading if calibration drifts+MAX_CORRELATION = 0.70 # Don't stack highly correlated bets++# Particle filter settings+N_PARTICLES = 3000+PROCESS_VOL = 0.03 # Volatility of probability drift per step+OBS_NOISE = 0.04 # Observation noise (market price noise)+++# ==============================================================================+# DATA LAYER — Fetch live prices from Polymarket+# ==============================================================================++def fetch_active_markets(limit: int = 20) -> list[dict]:+ """Fetch top active markets by volume from Gamma API."""+ try:+ url = f"{GAMMA_API}/markets"+ params = {+ "limit": limit,+ "active": "true",+ "closed": "false",+ "order": "volume",+ "ascending": "false",+ }+ resp = requests.get(url, params=params, timeout=15)+ resp.raise_for_status()+ markets = resp.json()++ # Filter to tradeable markets with valid prices+ result = []+ for m in markets:+ if not m.get("active") or m.get("closed") or m.get("archived"):+ continue+ raw_prices = m.get("outcomePrices", [])+ # outcomePrices can be a JSON string or a list+ if isinstance(raw_prices, str):+ try:+ raw_prices = json.loads(raw_prices)+ except (json.JSONDecodeError, TypeError):+ continue+ if not raw_prices or len(raw_prices) < 1:+ continue+ try:+ yes_price = float(raw_prices[0])+ except (ValueError, TypeError):+ continue+ if yes_price <= 0.02 or yes_price >= 0.98:+ continue # Skip near-certain or near-zero contracts++ result.append({+ "id": m.get("id", ""),+ "question": m.get("question", "Unknown"),+ "yes_price": yes_price,+ "no_price": 1.0 - yes_price,+ "volume": float(m.get("volume", 0) or 0),+ "liquidity": float(m.get("liquidity", 0) or 0),+ "end_date": m.get("endDate", ""),+ "category": m.get("category", ""),+ "clob_token_ids": m.get("clobTokenIds", []),+ "condition_id": m.get("conditionId", ""),+ })+ return result+ except Exception as e:+ print(f" [ERROR] Failed to fetch markets: {e}")+ return []+++def fetch_price_history(token_id: str, interval: str = "1w") -> list[dict]:+ """Fetch price history for a token from CLOB API."""+ try:+ url = f"{CLOB_API}/prices-history"+ params = {"market": token_id, "interval": interval, "fidelity": 60}+ resp = requests.get(url, params=params, timeout=10)+ resp.raise_for_status()+ data = resp.json()+ history = data.get("history", [])+ return [+ {"price": float(h.get("p", 0)), "timestamp": int(h.get("t", 0))}+ for h in history+ if float(h.get("p", 0)) > 0+ ]+ except Exception:+ return []+++def fetch_order_book(token_id: str) -> Optional[dict]:+ """Fetch order book for liquidity assessment."""+ try:+ url = f"{CLOB_API}/book"+ params = {"token_id": token_id}+ resp = requests.get(url, params=params, timeout=10)+ resp.raise_for_status()+ data = resp.json()+ bids = data.get("bids", [])+ asks = data.get("asks", [])+ best_bid = float(bids[0]["price"]) if bids else 0.0+ best_ask = float(asks[0]["price"]) if asks else 1.0+ spread = best_ask - best_bid+ bid_depth = sum(float(b.get("size", 0)) for b in bids[:5])+ ask_depth = sum(float(a.get("size", 0)) for a in asks[:5])+ return {+ "best_bid": best_bid,+ "best_ask": best_ask,+ "spread": spread,+ "bid_depth": bid_depth,+ "ask_depth": ask_depth,+ }+ except Exception:+ return None+++# ==============================================================================+# PROBABILITY ENGINE — Particle Filter + Bayesian Estimation+# ==============================================================================++class ParticleFilter:+ """+ Sequential Monte Carlo filter for real-time event probability estimation.++ Maintains N particles (hypotheses about the true probability) in logit space.+ Updates as new market prices arrive, smoothing noise and propagating uncertainty.+ """++ def __init__(+ self,+ prior_prob: float = 0.5,+ n_particles: int = N_PARTICLES,+ process_vol: float = PROCESS_VOL,+ obs_noise: float = OBS_NOISE,+ ):+ self.n = n_particles+ self.process_vol = process_vol+ self.obs_noise = obs_noise++ # Initialize particles around prior in logit space+ logit_prior = logit(np.clip(prior_prob, 0.01, 0.99))+ self.logit_particles = logit_prior + np.random.normal(0, 0.5, n_particles)+ self.weights = np.ones(n_particles) / n_particles+ self.history: list[float] = []+ self.observations: list[float] = []++ def update(self, observed_price: float) -> None:+ """Incorporate a new price observation."""+ observed_price = np.clip(observed_price, 0.01, 0.99)+ self.observations.append(observed_price)++ # 1. Propagate: random walk in logit space+ noise = np.random.normal(0, self.process_vol, self.n)+ self.logit_particles += noise++ # 2. Convert to probability space+ prob_particles = expit(self.logit_particles)++ # 3. Reweight: likelihood of observation given each particle+ log_likelihood = -0.5 * ((observed_price - prob_particles) / self.obs_noise) ** 2+ log_weights = np.log(self.weights + 1e-300) + log_likelihood++ # Normalize in log space for numerical stability+ log_weights -= log_weights.max()+ self.weights = np.exp(log_weights)+ self.weights /= self.weights.sum()++ # 4. Resample if effective sample size too low+ ess = 1.0 / np.sum(self.weights ** 2)+ if ess < self.n / 2:+ self._systematic_resample()++ self.history.append(self.estimate())++ def _systematic_resample(self) -> None:+ """Systematic resampling — lower variance than multinomial."""+ cumsum = np.cumsum(self.weights)+ u = (np.arange(self.n) + np.random.uniform()) / self.n+ indices = np.searchsorted(cumsum, u)+ indices = np.clip(indices, 0, self.n - 1)+ self.logit_particles = self.logit_particles[indices]+ self.weights = np.ones(self.n) / self.n++ def estimate(self) -> float:+ """Weighted mean probability estimate."""+ probs = expit(self.logit_particles)+ return float(np.average(probs, weights=self.weights))++ def credible_interval(self, alpha: float = 0.05) -> tuple[float, float]:+ """Weighted quantile-based credible interval."""+ probs = expit(self.logit_particles)+ sorted_idx = np.argsort(probs)+ sorted_probs = probs[sorted_idx]+ sorted_weights = self.weights[sorted_idx]+ cumw = np.cumsum(sorted_weights)+ lower = float(sorted_probs[np.searchsorted(cumw, alpha / 2)])+ upper = float(sorted_probs[np.searchsorted(cumw, 1 - alpha / 2)])+ return lower, upper++ def uncertainty(self) -> float:+ """Standard deviation of the particle distribution."""+ probs = expit(self.logit_particles)+ return float(np.sqrt(np.average((probs - self.estimate()) ** 2, weights=self.weights)))+++# ==============================================================================+# MONTE CARLO SIMULATION — For contracts with underlying assets+# ==============================================================================++def monte_carlo_binary(+ current_price: float,+ vol_estimate: float,+ time_to_expiry_days: float,+ n_paths: int = 50_000,+) -> dict:+ """+ Monte Carlo simulation for a binary prediction market contract.+ Simulates probability paths in logit space (bounded [0,1]).+ Uses antithetic variates + stratified sampling for variance reduction.++ Returns estimated terminal probability, standard error, and CI.+ """+ if time_to_expiry_days <= 0:+ return {"probability": current_price, "std_error": 0.0, "ci_95": (current_price, current_price)}++ T = time_to_expiry_days / 365.0+ logit_p = logit(np.clip(current_price, 0.02, 0.98))+ # Scale vol for logit space (higher vol for prices near 0 or 1)+ logit_vol = vol_estimate / max(current_price * (1 - current_price), 0.01)+ logit_vol = min(logit_vol, 5.0) # Cap to prevent explosion++ n_strata = 10+ per_stratum = n_paths // (n_strata * 2) # *2 for antithetic++ terminal_probs = []++ for j in range(n_strata):+ # Stratified uniform draws+ U = np.random.uniform(j / n_strata, (j + 1) / n_strata, per_stratum)+ Z = norm.ppf(np.clip(U, 1e-8, 1 - 1e-8))++ # Antithetic variates: use Z and -Z+ for z in [Z, -Z]:+ # Random walk in logit space (drift=0, risk-neutral)+ logit_terminal = logit_p + logit_vol * np.sqrt(T) * z+ # Convert back to probability space+ prob_terminal = expit(logit_terminal)+ terminal_probs.append(prob_terminal.mean())++ p_hat = float(np.mean(terminal_probs))+ se = float(np.std(terminal_probs) / np.sqrt(len(terminal_probs)))++ return {+ "probability": np.clip(p_hat, 0.0, 1.0),+ "std_error": se,+ "ci_95": (max(0, p_hat - 1.96 * se), min(1, p_hat + 1.96 * se)),+ }+++def estimate_volatility(price_history: list[dict]) -> float:+ """Estimate annualized volatility from price history."""+ if len(price_history) < 5:+ return 0.20 # Default 20% vol++ prices = [h["price"] for h in price_history if h["price"] > 0.01]+ if len(prices) < 5:+ return 0.20++ log_returns = np.diff(np.log(np.array(prices)))+ daily_vol = float(np.std(log_returns))++ # Annualize (assume ~hourly data, ~24*365 observations per year)+ timestamps = [h["timestamp"] for h in price_history]+ if len(timestamps) >= 2:+ avg_interval_sec = (timestamps[-1] - timestamps[0]) / max(len(timestamps) - 1, 1)+ periods_per_year = 365.25 * 24 * 3600 / max(avg_interval_sec, 1)+ annual_vol = daily_vol * np.sqrt(periods_per_year)+ else:+ annual_vol = daily_vol * np.sqrt(365)++ return float(np.clip(annual_vol, 0.05, 2.0))+++# ==============================================================================+# EDGE DETECTION — Find mispricings+# ==============================================================================++def kelly_criterion(edge: float, odds: float) -> float:+ """+ Kelly criterion for optimal bet sizing.+ edge: probability advantage (model_prob - market_price)+ odds: payout odds (1/market_price - 1 for binary)+ Returns fraction of bankroll to bet.+ """+ if odds <= 0 or edge <= 0:+ return 0.0+ p = edge + (1.0 / (1.0 + odds)) # Implied win probability+ q = 1.0 - p+ f = (p * odds - q) / odds+ # Half-Kelly for safety+ return max(0.0, min(f * 0.5, 0.25))+++def detect_edge(model_prob: float, market_price: float, threshold: float = EDGE_THRESHOLD) -> dict:+ """+ Compare model probability vs market price to find edge.+ Returns trade signal with direction, edge size, and confidence.+ """+ edge = model_prob - market_price++ if abs(edge) < threshold:+ return {"action": "HOLD", "edge": edge, "confidence": 0, "direction": None}++ # Confidence: scale edge to 0-100 range+ # 5% edge = ~50 confidence, 10% = ~70, 20% = ~90+ confidence = min(100, int(50 + abs(edge) * 200))++ if edge > 0:+ # Model says higher probability than market — BUY YES+ odds = (1.0 / market_price) - 1.0+ kelly_frac = kelly_criterion(edge, odds)+ return {+ "action": "BUY_YES",+ "edge": edge,+ "confidence": confidence,+ "direction": "YES",+ "kelly_fraction": kelly_frac,+ }+ else:+ # Model says lower probability — BUY NO+ no_price = 1.0 - market_price+ odds = (1.0 / no_price) - 1.0+ kelly_frac = kelly_criterion(-edge, odds)+ return {+ "action": "BUY_NO",+ "edge": edge,+ "confidence": confidence,+ "direction": "NO",+ "kelly_fraction": kelly_frac,+ }+++# ==============================================================================+# RISK MANAGER — Position limits, stop loss, correlation, Brier score+# ==============================================================================++@dataclass+class Position:+ market_id: str+ question: str+ direction: str # YES or NO+ entry_price: float+ current_price: float+ size_usdc: float+ opened_at: str+ closed_at: Optional[str] = None+ close_reason: Optional[str] = None+ pnl_usdc: float = 0.0+++@dataclass+class BrierTracker:+ """Track Brier score for calibration monitoring."""+ predictions: list[float] = field(default_factory=list)+ outcomes: list[float] = field(default_factory=list)++ def record(self, predicted_prob: float, outcome: float) -> None:+ self.predictions.append(predicted_prob)+ self.outcomes.append(outcome)++ def score(self) -> float:+ if not self.predictions:+ return 0.0+ preds = np.array(self.predictions)+ outs = np.array(self.outcomes)+ return float(np.mean((preds - outs) ** 2))++ def is_calibrated(self, threshold: float = MAX_BRIER_SCORE) -> bool:+ if len(self.predictions) < 5:+ return True # Not enough data to judge+ return self.score() < threshold+++class RiskManager:+ """Enforces all risk controls before allowing trades."""++ def __init__(self):+ self.positions: list[Position] = []+ self.brier = BrierTracker()+ self.total_pnl: float = 0.0+ self.trades_executed: int = 0+ self.trades_won: int = 0++ @property+ def open_positions(self) -> list[Position]:+ return [p for p in self.positions if p.closed_at is None]++ @property+ def current_exposure(self) -> float:+ return sum(p.size_usdc for p in self.open_positions)++ @property+ def win_rate(self) -> float:+ if self.trades_executed == 0:+ return 0.0+ return self.trades_won / self.trades_executed * 100++ def check_can_trade(self, size_usdc: float, market_id: str) -> tuple[bool, str]:+ """Run all risk checks. Returns (allowed, reason)."""++ # 1. Brier score calibration check+ if not self.brier.is_calibrated():+ return False, f"Brier score {self.brier.score():.3f} > {MAX_BRIER_SCORE} - model uncalibrated"++ # 2. Max exposure check+ if self.current_exposure + size_usdc > MAX_EXPOSURE_USDC:+ return False, f"Exposure {self.current_exposure:.0f}+{size_usdc:.0f} > {MAX_EXPOSURE_USDC:.0f} limit"++ # 3. Per-market size check+ if size_usdc > MAX_POSITION_USDC:+ return False, f"Size {size_usdc:.0f} > {MAX_POSITION_USDC:.0f} per-market limit"++ # 4. Already in this market?+ for p in self.open_positions:+ if p.market_id == market_id:+ return False, "Already have position in this market"++ # 5. Correlation check — simple category-based+ # (In production, use copula. Here we just limit same-category positions)+ return True, "OK"++ def open_position(self, market_id: str, question: str, direction: str,+ entry_price: float, size_usdc: float) -> Position:+ pos = Position(+ market_id=market_id,+ question=question,+ direction=direction,+ entry_price=entry_price,+ current_price=entry_price,+ size_usdc=size_usdc,+ opened_at=datetime.now(timezone.utc).isoformat(),+ )+ self.positions.append(pos)+ self.trades_executed += 1+ return pos++ def update_positions(self, market_prices: dict[str, float]) -> list[str]:+ """Update current prices and check stop-loss / take-profit."""+ events = []+ for pos in self.open_positions:+ if pos.market_id not in market_prices:+ continue++ new_price = market_prices[pos.market_id]+ pos.current_price = new_price++ # Calculate P&L+ if pos.direction == "YES":+ pnl_pct = ((new_price - pos.entry_price) / pos.entry_price) * 100+ else:+ pnl_pct = ((pos.entry_price - new_price) / (1.0 - pos.entry_price)) * 100++ pos.pnl_usdc = pos.size_usdc * (pnl_pct / 100.0)++ # Stop loss+ if pnl_pct <= -STOP_LOSS_PCT:+ pos.closed_at = datetime.now(timezone.utc).isoformat()+ pos.close_reason = "STOP_LOSS"+ self.total_pnl += pos.pnl_usdc+ events.append(f" STOP LOSS: {pos.question[:40]}... PnL: ${pos.pnl_usdc:.2f}")++ # Take profit+ elif pnl_pct >= TAKE_PROFIT_PCT:+ pos.closed_at = datetime.now(timezone.utc).isoformat()+ pos.close_reason = "TAKE_PROFIT"+ self.total_pnl += pos.pnl_usdc+ self.trades_won += 1+ events.append(f" TAKE PROFIT: {pos.question[:40]}... PnL: ${pos.pnl_usdc:.2f}")++ return events+++# ==============================================================================+# CORRELATION CHECK — Simple pairwise correlation from price histories+# ==============================================================================++def check_correlation(+ new_market_prices: list[float],+ existing_position_prices: list[list[float]],+ threshold: float = MAX_CORRELATION,+) -> tuple[bool, float]:+ """+ Check if a new market is too correlated with existing positions.+ Returns (is_safe, max_correlation).+ """+ if not existing_position_prices or len(new_market_prices) < 10:+ return True, 0.0++ max_corr = 0.0+ new_arr = np.array(new_market_prices[-50:]) # Last 50 observations++ for existing in existing_position_prices:+ ex_arr = np.array(existing[-50:])+ min_len = min(len(new_arr), len(ex_arr))+ if min_len < 10:+ continue++ corr = float(np.corrcoef(new_arr[:min_len], ex_arr[:min_len])[0, 1])+ max_corr = max(max_corr, abs(corr))++ return max_corr < threshold, max_corr+++# ==============================================================================+# MAIN BOT LOOP+# ==============================================================================++def print_header():+ print("\n" + "=" * 72)+ print(" POLYMARKET QUANT BOT -- Demo (Paper Trading)")+ print(" Particle Filter + Monte Carlo + Edge Detection + Risk Management")+ print("=" * 72)+ print(f" Edge Threshold: {EDGE_THRESHOLD*100:.0f}% | Max Position: ${MAX_POSITION_USDC:.0f}")+ print(f" Max Exposure: ${MAX_EXPOSURE_USDC:.0f} | Stop Loss: {STOP_LOSS_PCT:.0f}% | Take Profit: {TAKE_PROFIT_PCT:.0f}%")+ print(f" Particles: {N_PARTICLES} | Cycle Interval: {CYCLE_INTERVAL_SEC}s")+ print("=" * 72)+++def print_cycle_header(cycle: int, total: int):+ now = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")+ label = f"{cycle}/{total}" if total > 0 else f"{cycle}"+ print(f"\n{'-' * 72}")+ print(f" CYCLE {label} | {now}")+ print(f"{'-' * 72}")+++def print_market_analysis(market: dict, pf: ParticleFilter, mc: dict, signal: dict, ob: Optional[dict]):+ q = market["question"][:55]+ mp = market["yes_price"]+ model_p = pf.estimate()+ ci = pf.credible_interval()+ unc = pf.uncertainty()++ action = signal["action"]+ edge = signal["edge"]++ # Color-code action+ if action == "BUY_YES":+ action_str = f">>> BUY YES (edge +{edge*100:.1f}%)"+ elif action == "BUY_NO":+ action_str = f">>> BUY NO (edge {edge*100:.1f}%)"+ else:+ action_str = f" HOLD (edge {edge*100:.1f}%)"++ spread_str = f"spread {ob['spread']:.3f}" if ob else "no book"++ print(f"\n {q}")+ print(f" Market: {mp:.3f} | Model: {model_p:.3f} | CI: [{ci[0]:.3f}, {ci[1]:.3f}] | Unc: {unc:.3f}")+ print(f" MC prob: {mc['probability']:.3f} +/- {mc['std_error']:.4f} | {spread_str}")+ print(f" {action_str}")+++def print_portfolio(risk: RiskManager):+ print(f"\n{'-' * 72}")+ print(f" PORTFOLIO SUMMARY")+ print(f"{'-' * 72}")+ print(f" Exposure: ${risk.current_exposure:.2f} / ${MAX_EXPOSURE_USDC:.0f}")+ print(f" Open Positions: {len(risk.open_positions)}")+ print(f" Total P&L: ${risk.total_pnl:.2f}")+ print(f" Trades: {risk.trades_executed} | Win Rate: {risk.win_rate:.0f}%")+ print(f" Brier Score: {risk.brier.score():.4f} | Calibrated: {'YES' if risk.brier.is_calibrated() else 'NO'}")++ if risk.open_positions:+ print(f"\n Open Positions:")+ for p in risk.open_positions:+ pnl_pct = 0.0+ if p.direction == "YES":+ pnl_pct = ((p.current_price - p.entry_price) / max(p.entry_price, 0.001)) * 100+ else:+ pnl_pct = ((p.entry_price - p.current_price) / max(1.0 - p.entry_price, 0.001)) * 100++ indicator = "+" if pnl_pct >= 0 else ""+ print(f" [{p.direction}] {p.question[:45]}...")+ print(f" Entry: {p.entry_price:.3f} Now: {p.current_price:.3f} PnL: {indicator}{pnl_pct:.1f}% (${p.pnl_usdc:.2f})")+++def run_bot():+ """Main bot loop."""+ print_header()++ risk = RiskManager()+ # Particle filters — one per market we're tracking+ filters: dict[str, ParticleFilter] = {}+ # Price histories for correlation checks+ price_histories: dict[str, list[float]] = {}++ cycles = NUM_CYCLES if NUM_CYCLES > 0 else float("inf")+ cycle = 0++ while cycle < cycles:+ cycle += 1+ print_cycle_header(cycle, NUM_CYCLES)++ # ── Step 1: Fetch live market data ─────────────────────────+ print("\n [1/4] Fetching live markets...")+ markets = fetch_active_markets(SCAN_LIMIT)+ if not markets:+ print(" No markets fetched. Retrying next cycle.")+ time.sleep(CYCLE_INTERVAL_SEC)+ continue++ print(f" Found {len(markets)} active markets")++ # ── Update existing positions with new prices ──────────────+ market_prices = {m["id"]: m["yes_price"] for m in markets}+ close_events = risk.update_positions(market_prices)+ for event in close_events:+ print(event)++ # ── Step 2: Run probability engine on each market ──────────+ print(f"\n [2/4] Running particle filter + Monte Carlo on {len(markets)} markets...")++ opportunities = []++ for market in markets:+ mid = market["id"]++ # Initialize or update particle filter+ if mid not in filters:+ filters[mid] = ParticleFilter(prior_prob=market["yes_price"])++ pf = filters[mid]+ pf.update(market["yes_price"])++ # Track price history for correlation+ if mid not in price_histories:+ price_histories[mid] = []+ price_histories[mid].append(market["yes_price"])++ # Fetch historical prices for volatility estimation+ token_ids = market.get("clob_token_ids", [])+ vol = 0.20 # Default+ if token_ids:+ hist = fetch_price_history(token_ids[0], interval="1w")+ if hist:+ vol = estimate_volatility(hist)++ # Days to expiry+ days_to_expiry = 30.0 # Default+ if market["end_date"]:+ try:+ end = datetime.fromisoformat(market["end_date"].replace("Z", "+00:00"))+ days_to_expiry = max(0.1, (end - datetime.now(timezone.utc)).total_seconds() / 86400)+ except Exception:+ pass++ # Monte Carlo simulation+ mc = monte_carlo_binary(market["yes_price"], vol, days_to_expiry)++ # ── Step 3: Edge detection ─────────────────────────────+ # Ensemble: 60% particle filter + 40% Monte Carlo+ model_prob = 0.6 * pf.estimate() + 0.4 * mc["probability"]++ signal = detect_edge(model_prob, market["yes_price"])++ # Record for Brier tracking (use market price as proxy outcome for now)+ risk.brier.record(pf.estimate(), market["yes_price"])++ # Fetch order book for liquidity check+ ob = None+ if signal["action"] != "HOLD" and token_ids:+ ob = fetch_order_book(token_ids[0])++ print_market_analysis(market, pf, mc, signal, ob)++ if signal["action"] != "HOLD" and signal.get("confidence", 0) >= MIN_CONFIDENCE:+ opportunities.append((market, pf, mc, signal, ob))++ # ── Step 4: Execute trades (paper) ─────────────────────────+ print(f"\n [3/4] Edge detection found {len(opportunities)} opportunities")+ print(f"\n [4/4] Executing trades (paper)...")++ trades_this_cycle = 0++ for market, pf, mc, signal, ob in opportunities:+ # Liquidity check+ if ob and ob["spread"] > 0.10:+ print(f" SKIP (spread too wide: {ob['spread']:.3f}): {market['question'][:50]}")+ continue++ # Kelly-based position sizing+ kelly_frac = signal.get("kelly_fraction", 0.05)+ size_usdc = min(+ MAX_POSITION_USDC,+ MAX_EXPOSURE_USDC * kelly_frac,+ MAX_POSITION_USDC * 0.5, # Conservative cap+ )+ size_usdc = max(5.0, size_usdc) # Minimum $5++ # Correlation check+ existing_histories = [+ price_histories.get(p.market_id, [])+ for p in risk.open_positions+ ]+ new_history = price_histories.get(market["id"], [])+ is_safe, max_corr = check_correlation(new_history, existing_histories)++ if not is_safe:+ print(f" SKIP (correlation {max_corr:.2f} > {MAX_CORRELATION}): {market['question'][:50]}")+ continue++ # Risk gate+ can_trade, reason = risk.check_can_trade(size_usdc, market["id"])+ if not can_trade:+ print(f" BLOCKED ({reason}): {market['question'][:50]}")+ continue++ # Paper trade!+ direction = signal["direction"]+ entry = market["yes_price"] if direction == "YES" else (1.0 - market["yes_price"])+ pos = risk.open_position(+ market_id=market["id"],+ question=market["question"],+ direction=direction,+ entry_price=market["yes_price"],+ size_usdc=size_usdc,+ )+ trades_this_cycle += 1+ print(f" TRADE: {direction} ${size_usdc:.2f} on \"{market['question'][:45]}...\"")+ print(f" Entry: {market['yes_price']:.3f} | Model: {pf.estimate():.3f} | Edge: {signal['edge']*100:.1f}%")++ if trades_this_cycle == 0:+ print(" No trades this cycle.")++ # ── Portfolio summary ──────────────────────────────────────+ print_portfolio(risk)++ # ── Wait for next cycle ────────────────────────────────────+ if cycle < cycles:+ print(f"\n Waiting {CYCLE_INTERVAL_SEC}s for next cycle... (Ctrl+C to stop)")+ try:+ time.sleep(CYCLE_INTERVAL_SEC)+ except KeyboardInterrupt:+ print("\n\n Bot stopped by user.")+ break++ # ── Final summary ──────────────────────────────────────────────+ print("\n" + "=" * 72)+ print(" FINAL RESULTS")+ print("=" * 72)+ print(f" Cycles Run: {cycle}")+ print(f" Trades Executed: {risk.trades_executed}")+ print(f" Win Rate: {risk.win_rate:.0f}%")+ print(f" Total P&L: ${risk.total_pnl:.2f}")+ print(f" Final Brier Score: {risk.brier.score():.4f}")+ print(f" Open Positions: {len(risk.open_positions)}")+ print("=" * 72)+++# ==============================================================================+# ENTRY POINT+# ==============================================================================++if __name__ == "__main__":+ import io as _io+ sys.stdout = _io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')+ sys.stderr = _io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')+ try:+ run_bot()+ except KeyboardInterrupt:+ print("\n\n Bot stopped by user.")+ except Exception as e:+ print(f"\n FATAL ERROR: {e}")+ import traceback+ traceback.print_exc()diff --git a/fincept-terminal-desktop/src-tauri/src/commands/database/admin.rs b/fincept-terminal-desktop/src-tauri/src/commands/database/admin.rsindex ed02b9df6..65869f5f3 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/database/admin.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/database/admin.rs@@ -4,6 +4,9 @@ use crate::database::*;use rusqlite::Connection;use serde::{Deserialize, Serialize};use std::collections::HashMap;+use sha2::Sha256;+use hmac::{Hmac, Mac};+use rand::Rng;#[derive(Debug, Serialize, Deserialize)]pub struct DatabaseInfo {@@ -87,30 +90,81 @@ pub async fn db_admin_clear_session() -> Result<String, String> {#[tauri::command]pub async fn db_admin_set_password(password: String) -> Result<String, String> {- use sha2::{Sha256, Digest};- let mut hasher = Sha256::new();- hasher.update(password.as_bytes());- let hashed = format!("{:x}", hasher.finalize());+ // Generate a random 32-byte salt+ let mut salt = [0u8; 32];+ rand::thread_rng().fill(&mut salt);+ let salt_hex = hex::encode(salt);- operations::save_setting("db_admin_password", &hashed, Some("security"))+ // Hash password with HMAC-SHA256 using the salt as key+ let hash_hex = hmac_sha256_hash(&password, &salt);++ // Store as "salt$hash"+ let stored = format!("{}${}", salt_hex, hash_hex);++ operations::save_setting("db_admin_password", &stored, Some("security")).map_err(|e| e.to_string())?;Ok("Password set successfully".to_string())}#[tauri::command]pub async fn db_admin_verify_password(password: String) -> Result<bool, String> {- use sha2::{Sha256, Digest};- let mut hasher = Sha256::new();- hasher.update(password.as_bytes());- let hashed = format!("{:x}", hasher.finalize());-match operations::get_setting("db_admin_password") {- Ok(Some(stored_hash)) => Ok(stored_hash == hashed),+ Ok(Some(stored)) => {+ // Handle both new "salt$hash" format and legacy bare-hash format+ if let Some((salt_hex, stored_hash)) = stored.split_once('$') {+ // New salted format: verify with HMAC-SHA256+ if let Ok(salt) = hex::decode(salt_hex) {+ let computed_hash = hmac_sha256_hash(&password, &salt);+ // Constant-time comparison to prevent timing attacks+ Ok(constant_time_eq(computed_hash.as_bytes(), stored_hash.as_bytes()))+ } else {+ Ok(false)+ }+ } else {+ // Legacy unsalted SHA-256 format: verify then migrate+ use sha2::Digest;+ let mut hasher = Sha256::new();+ hasher.update(password.as_bytes());+ let legacy_hash = format!("{:x}", hasher.finalize());+ let matches = constant_time_eq(legacy_hash.as_bytes(), stored.as_bytes());+ if matches {+ // Auto-migrate to salted format on successful login+ let mut salt = [0u8; 32];+ rand::thread_rng().fill(&mut salt);+ let salt_hex = hex::encode(salt);+ let hash_hex = hmac_sha256_hash(&password, &salt);+ let new_stored = format!("{}${}", salt_hex, hash_hex);+ let _ = operations::save_setting("db_admin_password", &new_stored, Some("security"));+ }+ Ok(matches)+ }+ }Ok(None) => Ok(true), // No password set, allow accessErr(e) => Err(e.to_string()),}}+/// Compute HMAC-SHA256(key=salt, message=password) and return hex string+fn hmac_sha256_hash(password: &str, salt: &[u8]) -> String {+ type HmacSha256 = Hmac<Sha256>;+ let mut mac = HmacSha256::new_from_slice(salt)+ .expect("HMAC can take key of any size");+ mac.update(password.as_bytes());+ hex::encode(mac.finalize().into_bytes())+}++/// Constant-time comparison of two byte slices to prevent timing attacks+fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {+ if a.len() != b.len() {+ return false;+ }+ let mut result = 0u8;+ for (x, y) in a.iter().zip(b.iter()) {+ result |= x ^ y;+ }+ result == 0+}+// Get all databases#[tauri::command]pub async fn db_admin_get_databases() -> Result<Vec<DatabaseInfo>, String> {@@ -200,6 +254,11 @@ pub async fn db_admin_get_tables(db_path: String) -> Result<Vec<TableInfo>, Strilet mut tables = Vec::new();for table_name in table_names {+ // Validate table name to prevent SQL injection via crafted sqlite_master entries+ if let Err(_) = validate_sql_identifier(&table_name, "Table name") {+ continue; // Skip tables with suspicious names+ }+// Get row countlet row_count: i64 = conn.query_row(&format!("SELECT COUNT(*) FROM \"{}\"", table_name), [], |row| {diff --git a/fincept-terminal-desktop/src-tauri/src/commands/monitoring.rs b/fincept-terminal-desktop/src-tauri/src/commands/monitoring.rsindex 985218d2d..6cd94295e 100644--- a/fincept-terminal-desktop/src-tauri/src/commands/monitoring.rs+++ b/fincept-terminal-desktop/src-tauri/src/commands/monitoring.rs@@ -76,12 +76,18 @@ pub async fn monitor_get_conditions(let conditions = stmt.query_map([], |row| {+ let field_str = row.get::<_, String>(3)?;+ let operator_str = row.get::<_, String>(4)?;+ let field = MonitorField::from_str(&field_str)+ .ok_or_else(|| rusqlite::Error::InvalidParameterName(format!("Unknown monitor field: {}", field_str)))?;+ let operator = MonitorOperator::from_str(&operator_str)+ .ok_or_else(|| rusqlite::Error::InvalidParameterName(format!("Unknown monitor operator: {}", operator_str)))?;Ok(MonitorCondition {id: Some(row.get(0)?),provider: row.get(1)?,symbol: row.get(2)?,- field: MonitorField::from_str(&row.get::<_, String>(3)?).unwrap(),- operator: MonitorOperator::from_str(&row.get::<_, String>(4)?).unwrap(),+ field,+ operator,value: row.get(5)?,value2: row.get(6)?,enabled: row.get::<_, i32>(7)? == 1,@@ -137,12 +143,15 @@ pub async fn monitor_get_alerts(let alerts = stmt.query_map(params![limit], |row| {+ let field_str = row.get::<_, String>(4)?;+ let field = MonitorField::from_str(&field_str)+ .ok_or_else(|| rusqlite::Error::InvalidParameterName(format!("Unknown monitor field: {}", field_str)))?;Ok(MonitorAlert {id: Some(row.get(0)?),condition_id: row.get(1)?,provider: row.get(2)?,symbol: row.get(3)?,- field: MonitorField::from_str(&row.get::<_, String>(4)?).unwrap(),+ field,triggered_value: row.get(5)?,triggered_at: row.get::<_, i64>(6)? as u64,})diff --git a/fincept-terminal-desktop/src-tauri/src/database/notes_excel.rs b/fincept-terminal-desktop/src-tauri/src/database/notes_excel.rsindex 5321220d1..782162f4c 100644--- a/fincept-terminal-desktop/src-tauri/src/database/notes_excel.rs+++ b/fincept-terminal-desktop/src-tauri/src/database/notes_excel.rs@@ -14,7 +14,7 @@ static EXCEL_CONN: Lazy<Mutex<Option<Connection>>> = Lazy::new(|| Mutex::new(Non// Notes Database Initialization// ============================================================================-fn get_notes_conn() -> Result<()> {+fn get_notes_conn_guard() -> Result<parking_lot::MutexGuard<'static, Option<Connection>>> {let mut conn_lock = NOTES_CONN.lock();if conn_lock.is_none() {let path = get_notes_db_path()?;@@ -58,7 +58,7 @@ fn get_notes_conn() -> Result<()> {*conn_lock = Some(conn);}- Ok(())+ Ok(conn_lock)}// ============================================================================@@ -66,9 +66,8 @@ fn get_notes_conn() -> Result<()> {// ============================================================================pub fn create_note(note: &Note) -> Result<i64> {- get_notes_conn()?;- let conn_lock = NOTES_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_notes_conn_guard()?;+ let conn = conn_lock.as_ref().context("Notes database connection not initialized")?;conn.execute("INSERT INTO financial_notes@@ -98,9 +97,8 @@ pub fn create_note(note: &Note) -> Result<i64> {}pub fn get_all_notes(include_archived: bool) -> Result<Vec<Note>> {- get_notes_conn()?;- let conn_lock = NOTES_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_notes_conn_guard()?;+ let conn = conn_lock.as_ref().context("Notes database connection not initialized")?;let query = if include_archived {"SELECT * FROM financial_notes ORDER BY updated_at DESC"@@ -136,9 +134,8 @@ pub fn get_all_notes(include_archived: bool) -> Result<Vec<Note>> {}pub fn update_note(id: i64, updates: &Note) -> Result<()> {- get_notes_conn()?;- let conn_lock = NOTES_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_notes_conn_guard()?;+ let conn = conn_lock.as_ref().context("Notes database connection not initialized")?;conn.execute("UPDATE financial_notes SET@@ -169,9 +166,8 @@ pub fn update_note(id: i64, updates: &Note) -> Result<()> {}pub fn delete_note(id: i64) -> Result<()> {- get_notes_conn()?;- let conn_lock = NOTES_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_notes_conn_guard()?;+ let conn = conn_lock.as_ref().context("Notes database connection not initialized")?;conn.execute("DELETE FROM financial_notes WHERE id = ?1", params![id])?;@@ -179,9 +175,8 @@ pub fn delete_note(id: i64) -> Result<()> {}pub fn search_notes(query: &str) -> Result<Vec<Note>> {- get_notes_conn()?;- let conn_lock = NOTES_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_notes_conn_guard()?;+ let conn = conn_lock.as_ref().context("Notes database connection not initialized")?;let search_pattern = format!("%{}%", query);@@ -219,9 +214,8 @@ pub fn search_notes(query: &str) -> Result<Vec<Note>> {}pub fn get_note_templates() -> Result<Vec<NoteTemplate>> {- get_notes_conn()?;- let conn_lock = NOTES_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_notes_conn_guard()?;+ let conn = conn_lock.as_ref().context("Notes database connection not initialized")?;let mut stmt = conn.prepare("SELECT * FROM note_templates ORDER BY name ASC")?;let templates = stmt@@ -244,7 +238,7 @@ pub fn get_note_templates() -> Result<Vec<NoteTemplate>> {// Excel Database Initialization// ============================================================================-fn get_excel_conn() -> Result<()> {+fn get_excel_conn_guard() -> Result<parking_lot::MutexGuard<'static, Option<Connection>>> {let mut conn_lock = EXCEL_CONN.lock();if conn_lock.is_none() {let path = get_excel_db_path()?;@@ -277,7 +271,7 @@ fn get_excel_conn() -> Result<()> {*conn_lock = Some(conn);}- Ok(())+ Ok(conn_lock)}// ============================================================================@@ -285,9 +279,8 @@ fn get_excel_conn() -> Result<()> {// ============================================================================pub fn add_or_update_excel_file(file: &ExcelFile) -> Result<i64> {- get_excel_conn()?;- let conn_lock = EXCEL_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_excel_conn_guard()?;+ let conn = conn_lock.as_ref().context("Excel database connection not initialized")?;// Check if existslet existing: Option<i64> = conn@@ -318,9 +311,8 @@ pub fn add_or_update_excel_file(file: &ExcelFile) -> Result<i64> {}pub fn get_recent_excel_files(limit: i64) -> Result<Vec<ExcelFile>> {- get_excel_conn()?;- let conn_lock = EXCEL_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_excel_conn_guard()?;+ let conn = conn_lock.as_ref().context("Excel database connection not initialized")?;let mut stmt = conn.prepare("SELECT * FROM excel_files ORDER BY last_opened DESC LIMIT ?1"@@ -344,9 +336,8 @@ pub fn get_recent_excel_files(limit: i64) -> Result<Vec<ExcelFile>> {}pub fn create_excel_snapshot(file_id: i64, snapshot_name: &str, sheet_data: &str, created_at: &str) -> Result<i64> {- get_excel_conn()?;- let conn_lock = EXCEL_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_excel_conn_guard()?;+ let conn = conn_lock.as_ref().context("Excel database connection not initialized")?;conn.execute("INSERT INTO excel_snapshots (file_id, snapshot_name, sheet_data, created_at)@@ -358,9 +349,8 @@ pub fn create_excel_snapshot(file_id: i64, snapshot_name: &str, sheet_data: &str}pub fn get_excel_snapshots(file_id: i64) -> Result<Vec<ExcelSnapshot>> {- get_excel_conn()?;- let conn_lock = EXCEL_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_excel_conn_guard()?;+ let conn = conn_lock.as_ref().context("Excel database connection not initialized")?;let mut stmt = conn.prepare("SELECT * FROM excel_snapshots WHERE file_id = ?1 ORDER BY created_at DESC"@@ -382,9 +372,8 @@ pub fn get_excel_snapshots(file_id: i64) -> Result<Vec<ExcelSnapshot>> {}pub fn delete_excel_snapshot(id: i64) -> Result<()> {- get_excel_conn()?;- let conn_lock = EXCEL_CONN.lock();- let conn = conn_lock.as_ref().unwrap();+ let conn_lock = get_excel_conn_guard()?;+ let conn = conn_lock.as_ref().context("Excel database connection not initialized")?;conn.execute("DELETE FROM excel_snapshots WHERE id = ?1", params![id])?;diff --git a/fincept-terminal-desktop/src-tauri/src/setup/install.rs b/fincept-terminal-desktop/src-tauri/src/setup/install.rsindex 2283edd3a..07726c400 100644--- a/fincept-terminal-desktop/src-tauri/src/setup/install.rs+++ b/fincept-terminal-desktop/src-tauri/src/setup/install.rs@@ -70,8 +70,11 @@ pub(super) async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Reemit_progress(app, "python", 40, "Downloading Python...", false);+ let tar_path_str = tar_path.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", tar_path))?;+ let python_dir_str = python_dir.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", python_dir))?;+let mut cmd = Command::new("curl");- cmd.args(&["-L", "-o", tar_path.to_str().unwrap(), &download_url]);+ cmd.args(&["-L", "-o", tar_path_str, &download_url]);let output = cmd.output().map_err(|e| format!("Download failed: {}", e))?;if !output.status.success() {return Err(format!("Download failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -83,7 +86,7 @@ pub(super) async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Reemit_progress(app, "python", 60, "Extracting Python...", false);let mut cmd = Command::new("tar");- cmd.args(&["-xzf", tar_path.to_str().unwrap(), "-C", python_dir.to_str().unwrap(), "--strip-components=1"]);+ cmd.args(&["-xzf", tar_path_str, "-C", python_dir_str, "--strip-components=1"]);let output = cmd.output().map_err(|e| format!("Extract failed: {}", e))?;if !output.status.success() {return Err(format!("Extract failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -108,8 +111,11 @@ pub(super) async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Reemit_progress(app, "python", 40, "Downloading Python...", false);+ let tar_path_str = tar_path.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", tar_path))?;+ let python_dir_str = python_dir.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", python_dir))?;+let mut cmd = Command::new("curl");- cmd.args(&["-L", "-o", tar_path.to_str().unwrap(), &download_url]);+ cmd.args(&["-L", "-o", tar_path_str, &download_url]);let output = cmd.output().map_err(|e| format!("Download failed: {}", e))?;if !output.status.success() {return Err(format!("Download failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -122,7 +128,7 @@ pub(super) async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Re// Use gunzip separately for better BSD tar compatibilitylet mut gunzip_cmd = Command::new("gunzip");- gunzip_cmd.arg(tar_path.to_str().unwrap());+ gunzip_cmd.arg(tar_path_str);let output = gunzip_cmd.output().map_err(|e| format!("Gunzip failed: {}", e))?;if !output.status.success() {return Err(format!("Gunzip failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -132,8 +138,9 @@ pub(super) async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Re// Extract the uncompressed tar filelet tar_uncompressed = python_dir.join("python.tar");+ let tar_uncompressed_str = tar_uncompressed.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", tar_uncompressed))?;let mut cmd = Command::new("tar");- cmd.args(&["-xf", tar_uncompressed.to_str().unwrap(), "-C", python_dir.to_str().unwrap(), "--strip-components=1"]);+ cmd.args(&["-xf", tar_uncompressed_str, "-C", python_dir_str, "--strip-components=1"]);let output = cmd.output().map_err(|e| format!("Extract failed: {}", e))?;if !output.status.success() {return Err(format!("Extract failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -222,8 +229,9 @@ pub(super) async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Re#[cfg(not(target_os = "windows"))]{+ let get_pip_path_str = get_pip_path.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", get_pip_path))?;let mut cmd = Command::new("curl");- cmd.args(&["-L", "-o", get_pip_path.to_str().unwrap(), get_pip_url]);+ cmd.args(&["-L", "-o", get_pip_path_str, get_pip_url]);let output = cmd.output().map_err(|e| format!("Failed to download get-pip.py: {}", e))?;if !output.status.success() {@@ -260,7 +268,8 @@ pub(super) async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Reeprintln!("[SETUP] Running: {:?} {:?}", python_exe, get_pip_path);let mut cmd = Command::new(&python_exe);- cmd.arg(get_pip_path.to_str().unwrap());+ let get_pip_str = get_pip_path.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", get_pip_path))?;+ cmd.arg(get_pip_str);// Add --no-warn-script-location to suppress warningscmd.arg("--no-warn-script-location");@@ -359,8 +368,11 @@ pub(super) async fn install_bun(app: &AppHandle, install_dir: &PathBuf) -> Resullet download_url = format!("https://github.com/oven-sh/bun/releases/download/bun-v{}/bun-linux-x64.zip", BUN_VERSION);let zip_path = bun_dir.join("bun.zip");+ let zip_path_str = zip_path.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", zip_path))?;+ let bun_dir_str = bun_dir.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", bun_dir))?;+let mut cmd = Command::new("curl");- cmd.args(&["-L", "-o", zip_path.to_str().unwrap(), &download_url]);+ cmd.args(&["-L", "-o", zip_path_str, &download_url]);let output = cmd.output().map_err(|e| format!("Download failed: {}", e))?;if !output.status.success() {return Err(format!("Download failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -369,7 +381,7 @@ pub(super) async fn install_bun(app: &AppHandle, install_dir: &PathBuf) -> Resulemit_progress(app, "bun", 70, "Extracting Bun...", false);let mut cmd = Command::new("unzip");- cmd.args(&["-o", zip_path.to_str().unwrap(), "-d", bun_dir.to_str().unwrap()]);+ cmd.args(&["-o", zip_path_str, "-d", bun_dir_str]);let output = cmd.output().map_err(|e| format!("Extract failed: {}", e))?;if !output.status.success() {return Err(format!("Extract failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -414,8 +426,11 @@ pub(super) async fn install_bun(app: &AppHandle, install_dir: &PathBuf) -> Resullet download_url = format!("https://github.com/oven-sh/bun/releases/download/bun-v{}/bun-darwin-{}.zip", BUN_VERSION, bun_arch);let zip_path = bun_dir.join("bun.zip");+ let zip_path_str = zip_path.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", zip_path))?;+ let bun_dir_str = bun_dir.to_str().ok_or_else(|| format!("Invalid path encoding: {:?}", bun_dir))?;+let mut cmd = Command::new("curl");- cmd.args(&["-L", "-o", zip_path.to_str().unwrap(), &download_url]);+ cmd.args(&["-L", "-o", zip_path_str, &download_url]);let output = cmd.output().map_err(|e| format!("Download failed: {}", e))?;if !output.status.success() {return Err(format!("Download failed: {}", String::from_utf8_lossy(&output.stderr)));@@ -424,7 +439,7 @@ pub(super) async fn install_bun(app: &AppHandle, install_dir: &PathBuf) -> Resulemit_progress(app, "bun", 70, "Extracting Bun...", false);let mut cmd = Command::new("unzip");- cmd.args(&["-o", zip_path.to_str().unwrap(), "-d", bun_dir.to_str().unwrap()]);+ cmd.args(&["-o", zip_path_str, "-d", bun_dir_str]);let output = cmd.output().map_err(|e| format!("Extract failed: {}", e))?;if !output.status.success() {return Err(format!("Extract failed: {}", String::from_utf8_lossy(&output.stderr)));diff --git a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.tsindex ec478e852..e81c01bea 100644--- a/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts+++ b/fincept-terminal-desktop/src/components/command-bar/commandRegistry.ts@@ -346,15 +346,6 @@ export const COMMANDS: Command[] = [action: 'forum',keywords: ['forum', 'community', 'discussion', 'posts']},- {- id: 'market',- name: 'Marketplace',- description: 'Extension marketplace',- aliases: ['market', 'marketplace', 'store'],- category: 'navigation',- action: 'marketplace',- keywords: ['marketplace', 'store', 'extensions', 'plugins']- },{id: 'docs',name: 'Documentation',diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsxindex 91f51fd5c..2832fcb99 100644--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx@@ -20,7 +20,7 @@ import WatchlistTab from '@/components/tabs/watchlist';import ChatTab from '@/components/tabs/chat';import ProfileTab from '@/components/tabs/profile';import AboutTab from '@/components/tabs/about';-import MarketplaceTab from '@/components/tabs/marketplace';+import PortfolioTab from '@/components/tabs/portfolio-tab';import DocsTab from '@/components/tabs/docs';import SettingsTab from '@/components/tabs/settings-tab';@@ -433,7 +433,6 @@ function FinxeptTerminalContent() {// Community & Support{ label: 'Community & Support', header: true },{ label: 'Forum', action: () => setActiveTab('forum') },- { label: 'Marketplace', action: () => setActiveTab('marketplace') },{ label: 'Documentation', action: () => setActiveTab('docs') },{ label: 'Support Tickets', action: () => setActiveTab('support') },];@@ -877,9 +876,6 @@ function FinxeptTerminalContent() {<TabsContent value="about" className="h-full m-0 p-0"><AboutTab /></TabsContent>- <TabsContent value="marketplace" className="h-full m-0 p-0">- <MarketplaceTab />- </TabsContent><TabsContent value="portfolio" className="h-full m-0 p-0"><PortfolioTab /></TabsContent>diff --git a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptDocsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptDocsPanel.tsxindex 82a50fd69..fc04beb04 100644--- a/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptDocsPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/code-editor/FinScriptDocsPanel.tsx@@ -92,8 +92,18 @@ export const FinScriptDocsPanel: React.FC<FinScriptDocsPanelProps> = ({ onClose,return elements;};+ const escapeHtml = (text: string): string => {+ return text+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+ };+const formatInlineText = (text: string): string => {- let result = text;+ // Escape HTML entities first to prevent XSS+ let result = escapeHtml(text);// Bold **text**result = result.replace(/\*\*(.+?)\*\*/g, `<span style="color:${F.CYAN};font-weight:bold">$1</span>`);// Code `text`diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/MarketplaceTab.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/MarketplaceTab.tsxdeleted file mode 100644index 7d6adf95e..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/MarketplaceTab.tsx+++ /dev/null@@ -1,445 +0,0 @@-import React, { useState, useEffect, useReducer, useCallback, useRef } from 'react';-import { useAuth } from '@/contexts/AuthContext';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { useTranslation } from 'react-i18next';-import { withTimeout } from '@/services/core/apiUtils';-import { ErrorBoundary } from '@/components/common/ErrorBoundary';-import { showError } from '@/utils/notifications';-import {- Search,- Upload,- ShoppingCart,- Package,- BarChart3,- DollarSign,- Shield,- TrendingUp,- Clock,- AlertCircle,-} from 'lucide-react';-import {- FINCEPT,- API_TIMEOUT_MS,- ScreenType,- initialState,- marketplaceReducer-} from './types';-import { TabButton } from './SharedComponents';-import { BrowseScreen } from './screens/BrowseScreen';-import { UploadScreen } from './screens/UploadScreen';-import { MyPurchasesScreen } from './screens/MyPurchasesScreen';-import { MyDatasetsScreen } from './screens/MyDatasetsScreen';-import { AnalyticsScreen } from './screens/AnalyticsScreen';-import { PricingScreen } from './screens/PricingScreen';-import { AdminStatsScreen, AdminPendingScreen, AdminRevenueScreen } from './screens/AdminScreens';--const MarketplaceTab: React.FC = () => {- const { t } = useTranslation('marketplace');- const { session } = useAuth();-- // State machine- const [state, dispatch] = useReducer(marketplaceReducer, initialState);- const {- status,- currentScreen,- datasets,- myUploadedDatasets,- selectedDataset,- selectedCategory,- searchQuery,- currentPage,- totalPages,- error- } = state;-- // Cleanup refs for race condition prevention- const mountedRef = useRef(true);- const fetchIdRef = useRef(0);-- const isLoading = status === 'loading';-- // Upload state (kept separate as form state)- const [uploadFile, setUploadFile] = useState<File | null>(null);- const [uploadMetadata, setUploadMetadata] = useState({- title: '',- description: '',- category: 'stocks',- price_tier: 'free',- tags: ''- });-- const isGuestUser = session?.user_type === 'guest' || session?.api_key?.startsWith('fk_guest_');- const isAdmin = (session?.user_info as any)?.is_admin;-- // Cleanup on unmount- useEffect(() => {- mountedRef.current = true;- return () => {- mountedRef.current = false;- };- }, []);-- // Fetch datasets with race condition prevention- const fetchDatasets = useCallback(async () => {- if (!session?.api_key) return;-- const currentFetchId = ++fetchIdRef.current;- dispatch({ type: 'SET_LOADING' });-- try {- const response = await withTimeout(- MarketplaceApiService.browseDatasets(session.api_key, {- category: selectedCategory === 'ALL' ? undefined : selectedCategory,- search: searchQuery || undefined,- page: currentPage,- limit: 20,- sort_by: 'uploaded_at',- sort_order: 'desc'- }),- API_TIMEOUT_MS,- 'Browse datasets timeout'- );-- // Prevent stale updates- if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;-- if (response.success && response.data) {- const responseData = response.data as any;- const rawDatasets = responseData.data?.datasets || responseData.datasets || [];- const pagination = responseData.data?.pagination || responseData.pagination || {};-- const transformedDatasets = rawDatasets.map((apiDataset: any) => ({- id: apiDataset.id,- title: apiDataset.title,- description: apiDataset.description,- category: apiDataset.category,- price_tier: apiDataset.pricing?.tier || 'free',- price_credits: apiDataset.pricing?.price_usd || 0,- uploader_id: apiDataset.uploader?.id || 0,- uploader_username: apiDataset.uploader?.username || 'Unknown',- file_name: apiDataset.metadata?.file_name || '',- file_size: (apiDataset.metadata?.file_size_mb || 0) * 1024 * 1024,- downloads_count: apiDataset.statistics?.download_count || 0,- rating: apiDataset.statistics?.rating || 0,- tags: apiDataset.tags || [],- status: apiDataset.status || 'approved',- rejection_reason: apiDataset.rejection_reason,- uploaded_at: apiDataset.uploaded_at,- updated_at: apiDataset.updated_at || apiDataset.uploaded_at- }));-- dispatch({ type: 'SET_DATASETS', datasets: transformedDatasets, totalPages: pagination.total_pages || responseData.total_pages || 1 });- dispatch({ type: 'SET_READY' });- } else {- dispatch({ type: 'SET_READY' });- }- } catch (err) {- if (!mountedRef.current || currentFetchId !== fetchIdRef.current) return;- console.error('Failed to fetch datasets:', err);- dispatch({ type: 'SET_ERROR', error: err instanceof Error ? err.message : 'Failed to fetch datasets' });- }- }, [session?.api_key, selectedCategory, searchQuery, currentPage]);-- const fetchMyDatasets = useCallback(async () => {- if (!session?.api_key) return;-- try {- const response = await withTimeout(- MarketplaceApiService.getMyDatasets(session.api_key, 1, 100),- API_TIMEOUT_MS,- 'Fetch my datasets timeout'- );-- if (!mountedRef.current) return;-- if (response.success && response.data) {- dispatch({ type: 'SET_MY_DATASETS', datasets: response.data.datasets || [] });- }- } catch (err) {- // Non-critical, don't show error- console.error('Failed to fetch my datasets:', err);- }- }, [session?.api_key]);-- useEffect(() => {- fetchDatasets();- fetchMyDatasets();- }, [fetchDatasets, fetchMyDatasets]);-- // Handler functions for state updates- const setCurrentScreen = useCallback((screen: ScreenType) => {- dispatch({ type: 'SET_SCREEN', screen });- }, []);-- const setSelectedDataset = useCallback((dataset: any | null) => {- dispatch({ type: 'SET_SELECTED_DATASET', dataset });- }, []);-- const setSelectedCategory = useCallback((category: string) => {- dispatch({ type: 'SET_CATEGORY', category });- }, []);-- const setSearchQuery = useCallback((query: string) => {- dispatch({ type: 'SET_SEARCH', query });- }, []);-- const setCurrentPage = useCallback((page: number) => {- dispatch({ type: 'SET_PAGE', page });- }, []);-- // Get unique categories- const categories = [- { name: 'ALL', count: datasets.length },- ...Object.entries(- datasets.reduce((acc, d) => {- acc[d.category] = (acc[d.category] || 0) + 1;- return acc;- }, {} as Record<string, number>)- ).map(([name, count]) => ({ name, count: count as number }))- ];-- const filteredDatasets = datasets.filter(d =>- (selectedCategory === 'ALL' || d.category === selectedCategory) &&- (searchQuery === '' || d.title.toLowerCase().includes(searchQuery.toLowerCase()))- );-- return (- <div style={{- width: '100%',- height: '100%',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- fontFamily: '"IBM Plex Mono", "Consolas", monospace',- display: 'flex',- flexDirection: 'column',- overflow: 'hidden'- }}>- {/* Custom Scrollbar */}- <style>{`- .marketplace-scroll::-webkit-scrollbar { width: 6px; height: 6px; }- .marketplace-scroll::-webkit-scrollbar-track { background: ${FINCEPT.DARK_BG}; }- .marketplace-scroll::-webkit-scrollbar-thumb { background: ${FINCEPT.BORDER}; border-radius: 3px; }- .marketplace-scroll::-webkit-scrollbar-thumb:hover { background: ${FINCEPT.MUTED}; }- `}</style>-- {/* Top Navigation Bar */}- <div style={{- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `2px solid ${FINCEPT.ORANGE}`,- padding: '8px 16px',- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`,- flexShrink: 0- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>- <span style={{- fontSize: '12px',- fontWeight: 700,- color: FINCEPT.ORANGE,- letterSpacing: '0.5px'- }}>- MARKETPLACE- </span>- <span style={{ color: FINCEPT.BORDER }}>|</span>- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>- <Package size={12} color={FINCEPT.CYAN} />- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>- {datasets.length} DATASETS- </span>- </div>- {currentScreen === 'BROWSE' && (- <>- <span style={{ color: FINCEPT.BORDER }}>|</span>- <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>- <Upload size={12} color={FINCEPT.YELLOW} />- <span style={{ fontSize: '9px', color: FINCEPT.GRAY }}>- {myUploadedDatasets.length} MY UPLOADS- </span>- </div>- </>- )}- </div>-- {/* Tab Buttons */}- <div style={{ display: 'flex', gap: '4px' }}>- <TabButton- active={currentScreen === 'BROWSE'}- onClick={() => setCurrentScreen('BROWSE')}- icon={<Search size={10} />}- label="BROWSE"- />- <TabButton- active={currentScreen === 'UPLOAD'}- onClick={() => setCurrentScreen('UPLOAD')}- icon={<Upload size={10} />}- label="UPLOAD"- />- <TabButton- active={currentScreen === 'MY_PURCHASES'}- onClick={() => setCurrentScreen('MY_PURCHASES')}- icon={<ShoppingCart size={10} />}- label="PURCHASES"- />- <TabButton- active={currentScreen === 'MY_DATASETS'}- onClick={() => setCurrentScreen('MY_DATASETS')}- icon={<Package size={10} />}- label="MY DATASETS"- />- <TabButton- active={currentScreen === 'ANALYTICS'}- onClick={() => setCurrentScreen('ANALYTICS')}- icon={<BarChart3 size={10} />}- label="ANALYTICS"- />- <TabButton- active={currentScreen === 'PRICING'}- onClick={() => setCurrentScreen('PRICING')}- icon={<DollarSign size={10} />}- label="PRICING"- />- {isAdmin && (- <>- <TabButton- active={currentScreen === 'ADMIN_STATS'}- onClick={() => setCurrentScreen('ADMIN_STATS')}- icon={<BarChart3 size={10} />}- label="ADMIN"- />- <TabButton- active={currentScreen === 'ADMIN_PENDING'}- onClick={() => setCurrentScreen('ADMIN_PENDING')}- icon={<Clock size={10} />}- label="PENDING"- />- <TabButton- active={currentScreen === 'ADMIN_REVENUE'}- onClick={() => setCurrentScreen('ADMIN_REVENUE')}- icon={<TrendingUp size={10} />}- label="REVENUE"- />- </>- )}- </div>- </div>-- {/* Guest Warning Banner */}- {isGuestUser && (- <div style={{- backgroundColor: `${FINCEPT.ORANGE}20`,- borderBottom: `1px solid ${FINCEPT.ORANGE}`,- padding: '8px 16px',- display: 'flex',- alignItems: 'center',- gap: '12px',- flexShrink: 0- }}>- <AlertCircle size={16} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', color: FINCEPT.WHITE, fontWeight: 700 }}>- GUEST MODE: Register to upload datasets and make purchases- </span>- </div>- )}-- {/* Main Content */}- <ErrorBoundary name="MarketplaceContent" variant="minimal">- <div style={{ flex: 1, overflow: 'hidden' }}>- {currentScreen === 'BROWSE' && (- <ErrorBoundary name="BrowseScreen" variant="minimal">- <BrowseScreen- datasets={filteredDatasets}- categories={categories}- selectedCategory={selectedCategory}- onCategorySelect={setSelectedCategory}- searchQuery={searchQuery}- onSearchChange={setSearchQuery}- selectedDataset={selectedDataset}- onDatasetSelect={setSelectedDataset}- isLoading={isLoading}- onRefresh={() => { fetchDatasets(); fetchMyDatasets(); }}- />- </ErrorBoundary>- )}- {currentScreen === 'UPLOAD' && (- <ErrorBoundary name="UploadScreen" variant="minimal">- <UploadScreen- uploadFile={uploadFile}- onFileChange={setUploadFile}- uploadMetadata={uploadMetadata}- onMetadataChange={setUploadMetadata}- isLoading={isLoading}- session={session}- onUploadComplete={() => {- fetchDatasets();- fetchMyDatasets();- setCurrentScreen('BROWSE');- }}- />- </ErrorBoundary>- )}- {currentScreen === 'MY_PURCHASES' && (- <ErrorBoundary name="MyPurchasesScreen" variant="minimal">- <MyPurchasesScreen session={session} />- </ErrorBoundary>- )}- {currentScreen === 'MY_DATASETS' && (- <ErrorBoundary name="MyDatasetsScreen" variant="minimal">- <MyDatasetsScreen session={session} onRefresh={() => { fetchDatasets(); fetchMyDatasets(); }} />- </ErrorBoundary>- )}- {currentScreen === 'ANALYTICS' && (- <ErrorBoundary name="AnalyticsScreen" variant="minimal">- <AnalyticsScreen session={session} />- </ErrorBoundary>- )}- {currentScreen === 'PRICING' && (- <ErrorBoundary name="PricingScreen" variant="minimal">- <PricingScreen session={session} />- </ErrorBoundary>- )}- {currentScreen === 'ADMIN_STATS' && (- <ErrorBoundary name="AdminStatsScreen" variant="minimal">- <AdminStatsScreen session={session} />- </ErrorBoundary>- )}- {currentScreen === 'ADMIN_PENDING' && (- <ErrorBoundary name="AdminPendingScreen" variant="minimal">- <AdminPendingScreen session={session} onRefresh={fetchDatasets} />- </ErrorBoundary>- )}- {currentScreen === 'ADMIN_REVENUE' && (- <ErrorBoundary name="AdminRevenueScreen" variant="minimal">- <AdminRevenueScreen session={session} />- </ErrorBoundary>- )}- </div>- </ErrorBoundary>-- {/* Status Bar */}- <div style={{- backgroundColor: FINCEPT.HEADER_BG,- borderTop: `1px solid ${FINCEPT.BORDER}`,- padding: '4px 16px',- fontSize: '9px',- color: FINCEPT.GRAY,- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center',- flexShrink: 0- }}>- <div style={{ display: 'flex', gap: '16px' }}>- <span>SCREEN: <span style={{ color: FINCEPT.ORANGE }}>{currentScreen}</span></span>- <span>DATASETS: <span style={{ color: FINCEPT.CYAN }}>{filteredDatasets.length}</span></span>- </div>- <div style={{ display: 'flex', gap: '16px', alignItems: 'center' }}>- <span>STATUS: <span style={{ color: FINCEPT.GREEN }}>CONNECTED</span></span>- <Shield size={10} color={FINCEPT.GREEN} />- </div>- </div>- </div>- );-};--export default MarketplaceTab;diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/SharedComponents.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/SharedComponents.tsxdeleted file mode 100644index b1ed4e52d..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/SharedComponents.tsx+++ /dev/null@@ -1,85 +0,0 @@-import React from 'react';-import { FINCEPT, FONT_FAMILY } from './types';--// Tab Button Component-export const TabButton: React.FC<{ active: boolean; onClick: () => void; icon: React.ReactNode; label: string }> = ({ active, onClick, icon, label }) => (- <button- onClick={onClick}- style={{- padding: '6px 12px',- backgroundColor: active ? FINCEPT.ORANGE : 'transparent',- color: active ? FINCEPT.DARK_BG : FINCEPT.GRAY,- border: 'none',- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px',- cursor: 'pointer',- display: 'flex',- alignItems: 'center',- gap: '4px',- borderRadius: '2px',- transition: 'all 0.2s',- fontFamily: FONT_FAMILY- }}- onMouseEnter={(e) => {- if (!active) {- e.currentTarget.style.color = FINCEPT.WHITE;- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;- }- }}- onMouseLeave={(e) => {- if (!active) {- e.currentTarget.style.color = FINCEPT.GRAY;- e.currentTarget.style.backgroundColor = 'transparent';- }- }}- >- {icon}- {label}- </button>-);--// Stat Box Component-export const StatBox: React.FC<{ label: string; value: string; color: string }> = ({ label, value, color }) => (- <div style={{- padding: '8px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- textAlign: 'center'- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px', letterSpacing: '0.5px' }}>- {label}- </div>- <div style={{ fontSize: '11px', fontWeight: 700, color }}>- {value}- </div>- </div>-);--// Stat Card Component-export const StatCard: React.FC<{ label: string; value: number; color: string }> = ({ label, value, color }) => (- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${color}`,- borderRadius: '2px',- padding: '16px',- textAlign: 'center'- }}>- <div style={{- fontSize: '9px',- color: FINCEPT.GRAY,- marginBottom: '6px',- letterSpacing: '0.5px'- }}>- {label}- </div>- <div style={{- fontSize: '28px',- fontWeight: 700,- color- }}>- {value.toLocaleString()}- </div>- </div>-);diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/index.ts b/fincept-terminal-desktop/src/components/tabs/marketplace/index.tsdeleted file mode 100644index e367d6534..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export { default } from "./MarketplaceTab";-export { default as MarketplaceTab } from "./MarketplaceTab";diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/AdminScreens.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/screens/AdminScreens.tsxdeleted file mode 100644index 2f3e8744c..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/AdminScreens.tsx+++ /dev/null@@ -1,641 +0,0 @@-import React, { useState, useEffect, useCallback, useRef } from 'react';-import { Dataset } from '@/services/marketplace/marketplaceApi';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { withTimeout } from '@/services/core/apiUtils';-import { sanitizeInput } from '@/services/core/validators';-import { showConfirm, showWarning, showError, showSuccess } from '@/utils/notifications';-import { FINCEPT, FONT_FAMILY, API_TIMEOUT_MS } from '../types';-import { StatCard } from '../SharedComponents';-import { BarChart3, Shield, Clock, TrendingUp, Check, X } from 'lucide-react';--// Admin Stats Screen-export const AdminStatsScreen: React.FC<{ session: any }> = ({ session }) => {- const [stats, setStats] = useState<any>(null);- const [isLoading, setIsLoading] = useState(true);- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- useEffect(() => {- const fetchStats = async () => {- if (!session?.api_key) return;- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.getMarketplaceStats(session.api_key),- API_TIMEOUT_MS,- 'Fetch stats timeout'- );- if (!mountedRef.current) return;- if (response.success && response.data) {- setStats(response.data);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('Failed to fetch stats:', err);- } finally {- if (mountedRef.current) setIsLoading(false);- }- };- fetchStats();- }, [session?.api_key]);-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <Shield size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- MARKETPLACE STATISTICS- </span>- </div>- </div>-- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- {isLoading ? (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading statistics...- </div>- ) : !stats ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <BarChart3 size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No statistics available</span>- </div>- ) : (- <div style={{ maxWidth: '1200px', margin: '0 auto' }}>- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '16px' }}>- <StatCard label="TOTAL DATASETS" value={stats.total_datasets || 0} color={FINCEPT.BLUE} />- <StatCard label="TOTAL PURCHASES" value={stats.total_purchases || 0} color={FINCEPT.GREEN} />- <StatCard label="TOTAL REVENUE" value={stats.total_revenue || 0} color={FINCEPT.ORANGE} />- </div>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '24px' }}>- <StatCard label="TOTAL UPLOADS" value={stats.total_uploads || 0} color={FINCEPT.CYAN} />- <StatCard label="ACTIVE USERS" value={stats.active_users || 0} color={FINCEPT.PURPLE} />- </div>-- {stats.popular_categories && Object.keys(stats.popular_categories).length > 0 && (- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- padding: '16px'- }}>- <div style={{- fontSize: '10px',- fontWeight: 700,- color: FINCEPT.ORANGE,- marginBottom: '16px',- letterSpacing: '0.5px'- }}>- POPULAR CATEGORIES- </div>- {Object.entries(stats.popular_categories).map(([category, count]: [string, any]) => (- <div key={category} style={{- borderBottom: `1px solid ${FINCEPT.BORDER}`,- padding: '12px 0',- display: 'flex',- justifyContent: 'space-between'- }}>- <div style={{ fontSize: '10px', color: FINCEPT.WHITE }}>- {category.toUpperCase()}- </div>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.CYAN }}>- {count} datasets- </div>- </div>- ))}- </div>- )}- </div>- )}- </div>- </div>- );-};--// Admin Pending Screen-export const AdminPendingScreen: React.FC<{ session: any; onRefresh: () => void }> = ({ session, onRefresh }) => {- const [pendingDatasets, setPendingDatasets] = useState<Dataset[]>([]);- const [isLoading, setIsLoading] = useState(true);- const [rejectingId, setRejectingId] = useState<number | null>(null);- const [rejectionReason, setRejectionReason] = useState('');- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- const loadPending = useCallback(async () => {- if (!session?.api_key) return;- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.getPendingDatasets(session.api_key),- API_TIMEOUT_MS,- 'Fetch pending datasets timeout'- );- if (!mountedRef.current) return;- if (response.success && response.data) {- setPendingDatasets(response.data.datasets || []);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('Failed to fetch pending datasets:', err);- } finally {- if (mountedRef.current) setIsLoading(false);- }- }, [session?.api_key]);-- useEffect(() => {- loadPending();- }, [loadPending]);-- const handleApprove = useCallback(async (datasetId: number, title: string) => {- const confirmed = await showConfirm('', {- title: `Approve dataset "${title}"?`,- type: 'info'- });- if (!confirmed) return;- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.approveDataset(session.api_key, datasetId),- API_TIMEOUT_MS,- 'Approve dataset timeout'- );- if (!mountedRef.current) return;- if (response.success) {- showSuccess('Dataset approved');- loadPending();- onRefresh();- } else {- showError('Approval failed');- }- } catch (err) {- if (mountedRef.current) {- showError('Approval failed', [- { label: 'ERROR', value: err instanceof Error ? err.message : 'Unknown error' }- ]);- }- } finally {- if (mountedRef.current) setIsLoading(false);- }- }, [session?.api_key, loadPending, onRefresh]);-- const handleReject = useCallback(async (datasetId: number) => {- const sanitizedReason = sanitizeInput(rejectionReason);- if (!sanitizedReason.trim()) {- showWarning('Please provide a rejection reason');- return;- }- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.rejectDataset(session.api_key, datasetId, sanitizedReason),- API_TIMEOUT_MS,- 'Reject dataset timeout'- );- if (!mountedRef.current) return;- if (response.success) {- showSuccess('Dataset rejected');- setRejectingId(null);- setRejectionReason('');- loadPending();- onRefresh();- } else {- showError('Rejection failed');- }- } catch (err) {- if (mountedRef.current) {- showError('Rejection failed', [- { label: 'ERROR', value: err instanceof Error ? err.message : 'Unknown error' }- ]);- }- } finally {- if (mountedRef.current) setIsLoading(false);- }- }, [session?.api_key, rejectionReason, loadPending, onRefresh]);-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <Clock size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- PENDING APPROVALS ({pendingDatasets.length})- </span>- </div>- </div>-- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- {isLoading ? (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading pending datasets...- </div>- ) : pendingDatasets.length === 0 ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <Clock size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No pending datasets</span>- </div>- ) : (- <div style={{ maxWidth: '1000px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {pendingDatasets.map((dataset) => (- <div key={dataset.id} style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.YELLOW}`,- borderRadius: '2px',- padding: '16px'- }}>- <div style={{ marginBottom: '12px' }}>- <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '6px' }}>- {dataset.title}- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>- by {dataset.uploader_username} • {dataset.category} • {dataset.price_tier} • {(dataset.file_size / 1024 / 1024).toFixed(2)} MB- </div>- <div style={{ fontSize: '10px', color: FINCEPT.WHITE, lineHeight: '1.5', marginBottom: '12px' }}>- {dataset.description}- </div>- {dataset.tags && dataset.tags.length > 0 && (- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>- {dataset.tags.map((tag, idx) => (- <span key={idx} style={{- padding: '2px 6px',- backgroundColor: `${FINCEPT.CYAN}20`,- color: FINCEPT.CYAN,- fontSize: '8px',- fontWeight: 700,- borderRadius: '2px'- }}>- #{tag}- </span>- ))}- </div>- )}- </div>-- {rejectingId === dataset.id ? (- <div style={{- backgroundColor: `${FINCEPT.RED}10`,- border: `1px solid ${FINCEPT.RED}`,- borderRadius: '2px',- padding: '12px',- marginTop: '12px'- }}>- <div style={{- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.RED,- marginBottom: '8px',- letterSpacing: '0.5px'- }}>- REJECTION REASON- </div>- <textarea- value={rejectionReason}- onChange={(e) => setRejectionReason(e.target.value)}- placeholder="Enter reason for rejection..."- style={{- width: '100%',- padding: '8px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- minHeight: '60px',- marginBottom: '8px',- outline: 'none'- }}- />- <div style={{ display: 'flex', gap: '8px' }}>- <button- onClick={() => handleReject(dataset.id)}- disabled={!rejectionReason.trim()}- style={{- padding: '6px 12px',- backgroundColor: FINCEPT.RED,- color: FINCEPT.WHITE,- border: 'none',- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: rejectionReason.trim() ? 'pointer' : 'not-allowed',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px',- opacity: rejectionReason.trim() ? 1 : 0.5- }}- >- CONFIRM REJECT- </button>- <button- onClick={() => { setRejectingId(null); setRejectionReason(''); }}- style={{- padding: '6px 12px',- backgroundColor: 'transparent',- color: FINCEPT.GRAY,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px'- }}- >- CANCEL- </button>- </div>- </div>- ) : (- <div style={{ display: 'flex', gap: '8px' }}>- <button- onClick={() => handleApprove(dataset.id, dataset.title)}- style={{- padding: '8px 16px',- backgroundColor: 'transparent',- border: `1px solid ${FINCEPT.GREEN}`,- color: FINCEPT.GREEN,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Check size={10} />- APPROVE- </button>- <button- onClick={() => setRejectingId(dataset.id)}- style={{- padding: '8px 16px',- backgroundColor: 'transparent',- border: `1px solid ${FINCEPT.RED}`,- color: FINCEPT.RED,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <X size={10} />- REJECT- </button>- </div>- )}- </div>- ))}- </div>- )}- </div>- </div>- );-};--// Admin Revenue Screen-export const AdminRevenueScreen: React.FC<{ session: any }> = ({ session }) => {- const [revenue, setRevenue] = useState<any>(null);- const [isLoading, setIsLoading] = useState(true);- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- useEffect(() => {- const fetchRevenue = async () => {- if (!session?.api_key) return;- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.getAdminRevenueAnalytics(session.api_key),- API_TIMEOUT_MS,- 'Fetch revenue timeout'- );- if (!mountedRef.current) return;- if (response.success && response.data) {- setRevenue(response.data);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('Failed to fetch revenue:', err);- } finally {- if (mountedRef.current) setIsLoading(false);- }- };- fetchRevenue();- }, [session?.api_key]);-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <TrendingUp size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- REVENUE ANALYTICS- </span>- </div>- </div>-- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- {isLoading ? (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading revenue data...- </div>- ) : !revenue ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <TrendingUp size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No revenue data available</span>- </div>- ) : (- <div style={{ maxWidth: '1200px', margin: '0 auto' }}>- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '24px' }}>- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.GREEN}`,- borderRadius: '2px',- padding: '24px',- textAlign: 'center'- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px', letterSpacing: '0.5px' }}>- TOTAL REVENUE- </div>- <div style={{ fontSize: '36px', fontWeight: 700, color: FINCEPT.GREEN }}>- {revenue.total_revenue || 0}- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginTop: '4px', letterSpacing: '0.5px' }}>- CREDITS- </div>- </div>- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.BLUE}`,- borderRadius: '2px',- padding: '24px',- textAlign: 'center'- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px', letterSpacing: '0.5px' }}>- TOTAL TRANSACTIONS- </div>- <div style={{ fontSize: '36px', fontWeight: 700, color: FINCEPT.BLUE }}>- {revenue.total_transactions || 0}- </div>- </div>- </div>-- {revenue.revenue_by_tier && Object.keys(revenue.revenue_by_tier).length > 0 && (- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- padding: '16px',- marginBottom: '24px'- }}>- <div style={{- fontSize: '10px',- fontWeight: 700,- color: FINCEPT.ORANGE,- marginBottom: '16px',- letterSpacing: '0.5px'- }}>- REVENUE BY TIER- </div>- {Object.entries(revenue.revenue_by_tier).map(([tier, amount]: [string, any]) => (- <div key={tier} style={{- borderBottom: `1px solid ${FINCEPT.BORDER}`,- padding: '12px 0',- display: 'flex',- justifyContent: 'space-between'- }}>- <div style={{ fontSize: '10px', color: FINCEPT.WHITE }}>- {tier.toUpperCase()}- </div>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.GREEN }}>- {amount} credits- </div>- </div>- ))}- </div>- )}-- {revenue.top_datasets && revenue.top_datasets.length > 0 && (- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- padding: '16px'- }}>- <div style={{- fontSize: '10px',- fontWeight: 700,- color: FINCEPT.ORANGE,- marginBottom: '16px',- letterSpacing: '0.5px'- }}>- TOP PERFORMING DATASETS- </div>- {revenue.top_datasets.map((dataset: any, idx: number) => (- <div key={dataset.id} style={{- borderBottom: `1px solid ${FINCEPT.BORDER}`,- padding: '12px 0',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center'- }}>- <div style={{ flex: 1 }}>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '4px' }}>- #{idx + 1} {dataset.title}- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>- {dataset.downloads} downloads- </div>- </div>- <div style={{ fontSize: '14px', fontWeight: 700, color: FINCEPT.GREEN, marginLeft: '16px' }}>- {dataset.revenue} credits- </div>- </div>- ))}- </div>- )}- </div>- )}- </div>- </div>- );-};diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/AnalyticsScreen.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/screens/AnalyticsScreen.tsxdeleted file mode 100644index da6c05a95..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/AnalyticsScreen.tsx+++ /dev/null@@ -1,192 +0,0 @@-import React, { useState, useEffect, useRef } from 'react';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { withTimeout } from '@/services/core/apiUtils';-import { FINCEPT, API_TIMEOUT_MS } from '../types';-import { BarChart3 } from 'lucide-react';--export const AnalyticsScreen: React.FC<{ session: any }> = ({ session }) => {- const [analytics, setAnalytics] = useState<any>(null);- const [isLoading, setIsLoading] = useState(true);- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- useEffect(() => {- const fetchAnalytics = async () => {- if (!session?.api_key) return;- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.getDatasetAnalytics(session.api_key),- API_TIMEOUT_MS,- 'Fetch analytics timeout'- );- if (!mountedRef.current) return;- if (response.success && response.data) {- setAnalytics(response.data);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('Failed to fetch analytics:', err);- } finally {- if (mountedRef.current) setIsLoading(false);- }- };- fetchAnalytics();- }, [session?.api_key]);-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <BarChart3 size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- DATASET ANALYTICS- </span>- </div>- </div>-- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- {isLoading ? (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading analytics...- </div>- ) : !analytics ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <BarChart3 size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No analytics data available</span>- </div>- ) : (- <div style={{ maxWidth: '1200px', margin: '0 auto' }}>- {/* Summary Stats */}- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '24px' }}>- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.BLUE}`,- borderRadius: '2px',- padding: '16px',- textAlign: 'center'- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- TOTAL DATASETS- </div>- <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.BLUE }}>- {analytics.total_datasets || 0}- </div>- </div>- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.GREEN}`,- borderRadius: '2px',- padding: '16px',- textAlign: 'center'- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- TOTAL DOWNLOADS- </div>- <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.GREEN }}>- {analytics.total_downloads || 0}- </div>- </div>- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.ORANGE}`,- borderRadius: '2px',- padding: '16px',- textAlign: 'center'- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- TOTAL REVENUE- </div>- <div style={{ fontSize: '24px', fontWeight: 700, color: FINCEPT.ORANGE }}>- {analytics.total_revenue || 0}- </div>- </div>- </div>-- {/* Dataset Performance */}- {analytics.datasets && analytics.datasets.length > 0 && (- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- padding: '16px'- }}>- <div style={{- fontSize: '10px',- fontWeight: 700,- color: FINCEPT.ORANGE,- marginBottom: '16px',- letterSpacing: '0.5px'- }}>- DATASET PERFORMANCE- </div>- {analytics.datasets.map((dataset: any) => (- <div key={dataset.id} style={{- borderBottom: `1px solid ${FINCEPT.BORDER}`,- padding: '12px 0'- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>- <div style={{ fontSize: '10px', color: FINCEPT.WHITE, flex: 1 }}>- {dataset.title}- </div>- <div style={{ display: 'flex', gap: '24px' }}>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.CYAN }}>- {dataset.downloads}- </div>- <div style={{ fontSize: '8px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- DOWNLOADS- </div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.GREEN }}>- {dataset.revenue}- </div>- <div style={{ fontSize: '8px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- REVENUE- </div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: '12px', fontWeight: 700, color: FINCEPT.YELLOW }}>- ★ {dataset.rating.toFixed(1)}- </div>- <div style={{ fontSize: '8px', color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- RATING- </div>- </div>- </div>- </div>- </div>- ))}- </div>- )}- </div>- )}- </div>- </div>- );-};diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/BrowseScreen.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/screens/BrowseScreen.tsxdeleted file mode 100644index cad2d6109..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/BrowseScreen.tsx+++ /dev/null@@ -1,584 +0,0 @@-import React, { useState } from 'react';-import { Dataset } from '@/services/marketplace/marketplaceApi';-import { useAuth } from '@/contexts/AuthContext';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { FINCEPT, FONT_FAMILY } from '../types';-import { StatBox } from '../SharedComponents';-import { showError, showSuccess } from '@/utils/notifications';-import {- Search,- Filter,- RefreshCw,- Package,- Download,- X-} from 'lucide-react';--// Dataset Card Component-const DatasetCard: React.FC<{ dataset: Dataset; selected: boolean; onClick: () => void }> = ({ dataset, selected, onClick }) => {- const statusColor = dataset.status === 'approved' ? FINCEPT.GREEN : dataset.status === 'pending' ? FINCEPT.YELLOW : FINCEPT.RED;-- return (- <div- onClick={onClick}- style={{- backgroundColor: selected ? `${FINCEPT.ORANGE}10` : FINCEPT.PANEL_BG,- border: selected ? `1px solid ${FINCEPT.ORANGE}` : `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- padding: '12px',- cursor: 'pointer',- transition: 'all 0.2s'- }}- onMouseEnter={(e) => {- if (!selected) {- e.currentTarget.style.borderColor = FINCEPT.ORANGE;- }- }}- onMouseLeave={(e) => {- if (!selected) {- e.currentTarget.style.borderColor = FINCEPT.BORDER;- }- }}- >- {/* Header */}- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>- <div style={{- padding: '2px 6px',- backgroundColor: `${FINCEPT.CYAN}20`,- color: FINCEPT.CYAN,- fontSize: '8px',- fontWeight: 700,- borderRadius: '2px',- letterSpacing: '0.5px'- }}>- {dataset.category.toUpperCase()}- </div>- {dataset.status && dataset.status !== 'approved' && (- <div style={{- padding: '2px 6px',- backgroundColor: `${statusColor}20`,- color: statusColor,- fontSize: '8px',- fontWeight: 700,- borderRadius: '2px',- letterSpacing: '0.5px'- }}>- {dataset.status.toUpperCase()}- </div>- )}- </div>-- {/* Title */}- <div style={{- fontSize: '11px',- fontWeight: 700,- color: FINCEPT.WHITE,- marginBottom: '4px',- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap'- }}>- {dataset.title}- </div>-- {/* Author */}- <div style={{- fontSize: '9px',- color: FINCEPT.GRAY,- marginBottom: '8px'- }}>- by <span style={{ color: FINCEPT.CYAN }}>{dataset.uploader_username}</span>- </div>-- {/* Description */}- <div style={{- fontSize: '10px',- color: FINCEPT.GRAY,- lineHeight: '1.4',- marginBottom: '12px',- overflow: 'hidden',- textOverflow: 'ellipsis',- display: '-webkit-box',- WebkitLineClamp: 2,- WebkitBoxOrient: 'vertical'- }}>- {dataset.description}- </div>-- {/* Stats */}- <div style={{- display: 'grid',- gridTemplateColumns: '1fr 1fr 1fr',- gap: '8px',- padding: '8px',- backgroundColor: FINCEPT.DARK_BG,- borderRadius: '2px'- }}>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '2px' }}>DOWNLOADS</div>- <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.CYAN }}>{dataset.downloads_count}</div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '2px' }}>RATING</div>- <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.YELLOW }}>★ {dataset.rating.toFixed(1)}</div>- </div>- <div style={{ textAlign: 'center' }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '2px' }}>PRICE</div>- <div style={{ fontSize: '11px', fontWeight: 700, color: dataset.price_credits > 0 ? FINCEPT.GREEN : FINCEPT.GRAY }}>- {dataset.price_credits > 0 ? `${dataset.price_credits}c` : 'FREE'}- </div>- </div>- </div>- </div>- );-};--// Dataset Details Component-const DatasetDetails: React.FC<{ dataset: Dataset; onClose: () => void }> = ({ dataset, onClose }) => {- const { session } = useAuth();- const [isDownloading, setIsDownloading] = useState(false);-- const handleDownload = async () => {- if (!session?.api_key) return;- setIsDownloading(true);- try {- const response = await MarketplaceApiService.downloadDataset(session.api_key, dataset.id);- if (response.success && response.data?.download_url) {- window.open(response.data.download_url, '_blank');- } else {- showError('Download failed');- }- } catch (error) {- showError('Download failed');- } finally {- setIsDownloading(false);- }- };-- const handlePurchase = async () => {- if (!session?.api_key) return;- try {- const response = await MarketplaceApiService.purchaseDataset(session.api_key, dataset.id);- if (response.success) {- showSuccess('Purchase successful');- } else {- showError('Purchase failed');- }- } catch (error) {- showError('Purchase failed');- }- };-- return (- <>- {/* Header */}- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center'- }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- DATASET DETAILS- </span>- <button- onClick={onClose}- style={{- padding: '4px',- backgroundColor: 'transparent',- border: 'none',- cursor: 'pointer'- }}- >- <X size={12} color={FINCEPT.GRAY} />- </button>- </div>-- {/* Content */}- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>- {/* Category Badge */}- <div style={{- padding: '2px 6px',- backgroundColor: `${FINCEPT.CYAN}20`,- color: FINCEPT.CYAN,- fontSize: '8px',- fontWeight: 700,- borderRadius: '2px',- display: 'inline-block',- marginBottom: '12px',- letterSpacing: '0.5px'- }}>- {dataset.category.toUpperCase()}- </div>-- {/* Title */}- <h3 style={{- fontSize: '13px',- fontWeight: 700,- color: FINCEPT.WHITE,- marginBottom: '4px',- lineHeight: '1.4'- }}>- {dataset.title}- </h3>-- {/* Author */}- <div style={{- fontSize: '9px',- color: FINCEPT.GRAY,- marginBottom: '16px'- }}>- by <span style={{ color: FINCEPT.CYAN }}>{dataset.uploader_username}</span>- </div>-- {/* Price */}- <div style={{- padding: '12px',- backgroundColor: FINCEPT.DARK_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- marginBottom: '16px',- textAlign: 'center'- }}>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '4px' }}>PRICE</div>- <div style={{- fontSize: '20px',- fontWeight: 700,- color: dataset.price_credits > 0 ? FINCEPT.GREEN : FINCEPT.ORANGE- }}>- {dataset.price_credits > 0 ? `${dataset.price_credits} CREDITS` : 'FREE'}- </div>- </div>-- {/* Stats Grid */}- <div style={{- display: 'grid',- gridTemplateColumns: '1fr 1fr',- gap: '8px',- marginBottom: '16px'- }}>- <StatBox label="DOWNLOADS" value={dataset.downloads_count.toString()} color={FINCEPT.CYAN} />- <StatBox label="RATING" value={`★ ${dataset.rating.toFixed(1)}`} color={FINCEPT.YELLOW} />- <StatBox label="FILE SIZE" value={`${(dataset.file_size / 1024 / 1024).toFixed(2)} MB`} color={FINCEPT.GRAY} />- <StatBox label="UPLOADED" value={new Date(dataset.uploaded_at).toLocaleDateString()} color={FINCEPT.GRAY} />- </div>-- {/* Description */}- <div style={{ marginBottom: '16px' }}>- <div style={{- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '8px',- letterSpacing: '0.5px'- }}>- DESCRIPTION- </div>- <div style={{- fontSize: '10px',- color: FINCEPT.WHITE,- lineHeight: '1.6',- backgroundColor: FINCEPT.DARK_BG,- padding: '12px',- borderRadius: '2px'- }}>- {dataset.description}- </div>- </div>-- {/* Tags */}- {dataset.tags && dataset.tags.length > 0 && (- <div style={{ marginBottom: '16px' }}>- <div style={{- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '8px',- letterSpacing: '0.5px'- }}>- TAGS- </div>- <div style={{ display: 'flex', flexWrap: 'wrap', gap: '6px' }}>- {dataset.tags.map((tag, idx) => (- <span key={idx} style={{- padding: '4px 8px',- backgroundColor: `${FINCEPT.PURPLE}20`,- color: FINCEPT.PURPLE,- fontSize: '9px',- fontWeight: 700,- borderRadius: '2px'- }}>- #{tag}- </span>- ))}- </div>- </div>- )}-- {/* Actions */}- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>- {dataset.price_credits > 0 ? (- <button- onClick={handlePurchase}- style={{- padding: '8px 16px',- backgroundColor: FINCEPT.GREEN,- color: FINCEPT.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px'- }}- >- PURCHASE FOR {dataset.price_credits} CREDITS- </button>- ) : (- <button- onClick={handleDownload}- disabled={isDownloading}- style={{- padding: '8px 16px',- backgroundColor: FINCEPT.ORANGE,- color: FINCEPT.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: isDownloading ? 'not-allowed' : 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px',- opacity: isDownloading ? 0.7 : 1,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '6px'- }}- >- <Download size={10} />- {isDownloading ? 'DOWNLOADING...' : 'DOWNLOAD FREE'}- </button>- )}- </div>- </div>- </>- );-};--// Browse Screen Component-export const BrowseScreen: React.FC<{- datasets: Dataset[];- categories: Array<{ name: string; count: number }>;- selectedCategory: string;- onCategorySelect: (cat: string) => void;- searchQuery: string;- onSearchChange: (q: string) => void;- selectedDataset: Dataset | null;- onDatasetSelect: (d: Dataset | null) => void;- isLoading: boolean;- onRefresh: () => void;-}> = ({ datasets, categories, selectedCategory, onCategorySelect, searchQuery, onSearchChange, selectedDataset, onDatasetSelect, isLoading, onRefresh }) => {- return (- <div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>- {/* Left Panel - Categories & Filters */}- <div style={{- width: '280px',- backgroundColor: FINCEPT.PANEL_BG,- borderRight: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- flexDirection: 'column',- overflow: 'hidden'- }}>- {/* Section Header */}- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>- <Filter size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- CATEGORIES- </span>- </div>- <button- onClick={onRefresh}- style={{- padding: '4px',- backgroundColor: 'transparent',- border: 'none',- cursor: 'pointer',- display: 'flex',- alignItems: 'center'- }}- >- <RefreshCw size={10} color={FINCEPT.GRAY} />- </button>- </div>- </div>-- {/* Categories List */}- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto' }}>- {categories.map((cat) => (- <div- key={cat.name}- onClick={() => onCategorySelect(cat.name)}- style={{- padding: '10px 12px',- backgroundColor: selectedCategory === cat.name ? `${FINCEPT.ORANGE}15` : 'transparent',- borderLeft: selectedCategory === cat.name ? `2px solid ${FINCEPT.ORANGE}` : '2px solid transparent',- cursor: 'pointer',- transition: 'all 0.2s',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center'- }}- onMouseEnter={(e) => {- if (selectedCategory !== cat.name) {- e.currentTarget.style.backgroundColor = FINCEPT.HOVER;- }- }}- onMouseLeave={(e) => {- if (selectedCategory !== cat.name) {- e.currentTarget.style.backgroundColor = 'transparent';- }- }}- >- <span style={{- fontSize: '10px',- color: selectedCategory === cat.name ? FINCEPT.WHITE : FINCEPT.GRAY,- fontWeight: 700,- letterSpacing: '0.5px'- }}>- {cat.name}- </span>- <span style={{- fontSize: '9px',- color: selectedCategory === cat.name ? FINCEPT.CYAN : FINCEPT.MUTED,- fontWeight: 700- }}>- {cat.count}- </span>- </div>- ))}- </div>- </div>-- {/* Center Panel - Dataset Grid */}- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>- {/* Search Bar */}- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ position: 'relative' }}>- <Search size={14} color={FINCEPT.GRAY} style={{ position: 'absolute', left: '10px', top: '50%', transform: 'translateY(-50%)' }} />- <input- type="text"- placeholder="Search datasets..."- value={searchQuery}- onChange={(e) => onSearchChange(e.target.value)}- style={{- width: '100%',- padding: '8px 10px 8px 32px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- outline: 'none'- }}- onFocus={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}- />- </div>- </div>-- {/* Dataset Grid */}- <div className="marketplace-scroll" style={{- flex: 1,- overflowY: 'auto',- padding: '12px',- display: 'grid',- gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',- gap: '12px',- alignContent: 'start'- }}>- {isLoading ? (- <div style={{- gridColumn: '1 / -1',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading datasets...- </div>- ) : datasets.length === 0 ? (- <div style={{- gridColumn: '1 / -1',- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <Package size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No datasets found</span>- </div>- ) : (- datasets.map((dataset) => (- <DatasetCard- key={dataset.id}- dataset={dataset}- selected={selectedDataset?.id === dataset.id}- onClick={() => onDatasetSelect(dataset)}- />- ))- )}- </div>- </div>-- {/* Right Panel - Dataset Details */}- <div style={{- width: '320px',- backgroundColor: FINCEPT.PANEL_BG,- borderLeft: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- flexDirection: 'column',- overflow: 'hidden'- }}>- {selectedDataset ? (- <DatasetDetails dataset={selectedDataset} onClose={() => onDatasetSelect(null)} />- ) : (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '100%',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center',- padding: '16px'- }}>- <Package size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>Select a dataset to view details</span>- </div>- )}- </div>- </div>- );-};diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/MyDatasetsScreen.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/screens/MyDatasetsScreen.tsxdeleted file mode 100644index 3b79397b0..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/MyDatasetsScreen.tsx+++ /dev/null@@ -1,495 +0,0 @@-import React, { useState, useEffect, useCallback, useRef } from 'react';-import { Dataset } from '@/services/marketplace/marketplaceApi';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { withTimeout } from '@/services/core/apiUtils';-import { sanitizeInput } from '@/services/core/validators';-import { showConfirm, showWarning, showError, showSuccess } from '@/utils/notifications';-import { FINCEPT, FONT_FAMILY, API_TIMEOUT_MS } from '../types';-import { Package, Edit, Trash2 } from 'lucide-react';--export const MyDatasetsScreen: React.FC<{ session: any; onRefresh: () => void }> = ({ session, onRefresh }) => {- const [myDatasets, setMyDatasets] = useState<Dataset[]>([]);- const [isLoading, setIsLoading] = useState(true);- const [editingDataset, setEditingDataset] = useState<Dataset | null>(null);- const [editForm, setEditForm] = useState({- title: '',- description: '',- category: '',- price_tier: '',- tags: ''- });- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- const loadMyDatasets = useCallback(async () => {- if (!session?.api_key) return;- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.getMyDatasets(session.api_key, 1, 100),- API_TIMEOUT_MS,- 'Fetch my datasets timeout'- );- if (!mountedRef.current) return;- if (response.success && response.data) {- setMyDatasets(response.data.datasets || []);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('Failed to fetch my datasets:', err);- } finally {- if (mountedRef.current) setIsLoading(false);- }- }, [session?.api_key]);-- useEffect(() => {- loadMyDatasets();- }, [loadMyDatasets]);-- const handleEdit = useCallback((dataset: Dataset) => {- setEditingDataset(dataset);- setEditForm({- title: dataset.title,- description: dataset.description,- category: dataset.category,- price_tier: dataset.price_tier,- tags: dataset.tags.join(', ')- });- }, []);-- const handleUpdate = useCallback(async () => {- if (!session?.api_key || !editingDataset) return;-- // Sanitize inputs- const sanitizedTitle = sanitizeInput(editForm.title);- const sanitizedDescription = sanitizeInput(editForm.description);-- if (!sanitizedTitle || !sanitizedDescription) {- showWarning('Title and description are required');- return;- }-- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.updateDataset(session.api_key, editingDataset.id, {- title: sanitizedTitle,- description: sanitizedDescription,- category: editForm.category,- price_tier: editForm.price_tier,- tags: editForm.tags.split(',').map(t => sanitizeInput(t.trim())).filter(t => t)- }),- API_TIMEOUT_MS,- 'Update dataset timeout'- );- if (!mountedRef.current) return;- if (response.success) {- showSuccess('Dataset updated successfully');- setEditingDataset(null);- loadMyDatasets();- onRefresh();- } else {- showError('Update failed', [- { label: 'ERROR', value: response.error || 'Unknown error' }- ]);- }- } catch (err) {- if (mountedRef.current) {- showError('Update failed', [- { label: 'ERROR', value: err instanceof Error ? err.message : 'Unknown error' }- ]);- }- } finally {- if (mountedRef.current) setIsLoading(false);- }- }, [session?.api_key, editingDataset, editForm, loadMyDatasets, onRefresh]);-- const handleDelete = useCallback(async (datasetId: number, datasetTitle: string) => {- if (!session?.api_key) return;- const confirmed = await showConfirm(`This action cannot be undone.`, {- title: `Delete "${datasetTitle}"?`,- type: 'danger'- });- if (!confirmed) return;-- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.deleteDataset(session.api_key, datasetId),- API_TIMEOUT_MS,- 'Delete dataset timeout'- );- if (!mountedRef.current) return;- if (response.success) {- showSuccess('Dataset deleted successfully');- loadMyDatasets();- onRefresh();- } else {- showError('Delete failed', [- { label: 'ERROR', value: response.error || 'Unknown error' }- ]);- }- } catch (err) {- if (mountedRef.current) {- showError('Delete failed', [- { label: 'ERROR', value: err instanceof Error ? err.message : 'Unknown error' }- ]);- }- } finally {- if (mountedRef.current) setIsLoading(false);- }- }, [session?.api_key, loadMyDatasets, onRefresh]);-- const getStatusColor = (datasetStatus: string) => {- switch (status) {- case 'approved': return FINCEPT.GREEN;- case 'pending': return FINCEPT.YELLOW;- case 'rejected': return FINCEPT.RED;- default: return FINCEPT.GRAY;- }- };-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <Package size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- MY DATASETS ({myDatasets.length})- </span>- </div>- </div>-- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- {editingDataset && (- <div style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.ORANGE}`,- borderRadius: '2px',- padding: '16px',- marginBottom: '16px',- maxWidth: '800px',- margin: '0 auto 16px'- }}>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '16px', letterSpacing: '0.5px' }}>- EDIT DATASET- </div>-- <div style={{ marginBottom: '12px' }}>- <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- TITLE- </label>- <input- type="text"- value={editForm.title}- onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- outline: 'none'- }}- />- </div>-- <div style={{ marginBottom: '12px' }}>- <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- DESCRIPTION- </label>- <textarea- value={editForm.description}- onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- minHeight: '80px',- outline: 'none'- }}- />- </div>-- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '16px' }}>- <div>- <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- CATEGORY- </label>- <select- value={editForm.category}- onChange={(e) => setEditForm({ ...editForm, category: e.target.value })}- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY- }}- >- <option value="stocks">Stocks</option>- <option value="forex">Forex</option>- <option value="crypto">Cryptocurrency</option>- <option value="commodities">Commodities</option>- <option value="bonds">Bonds</option>- <option value="indices">Indices</option>- <option value="economic_data">Economic Data</option>- </select>- </div>- <div>- <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- PRICE TIER- </label>- <select- value={editForm.price_tier}- onChange={(e) => setEditForm({ ...editForm, price_tier: e.target.value })}- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY- }}- >- <option value="free">Free</option>- <option value="basic">Basic</option>- <option value="premium">Premium</option>- <option value="enterprise">Enterprise</option>- </select>- </div>- </div>-- <div style={{ marginBottom: '16px' }}>- <label style={{ display: 'block', fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, marginBottom: '6px', letterSpacing: '0.5px' }}>- TAGS- </label>- <input- type="text"- value={editForm.tags}- onChange={(e) => setEditForm({ ...editForm, tags: e.target.value })}- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- outline: 'none'- }}- />- </div>-- <div style={{ display: 'flex', gap: '8px' }}>- <button- onClick={handleUpdate}- disabled={isLoading}- style={{- padding: '8px 16px',- backgroundColor: isLoading ? FINCEPT.MUTED : FINCEPT.GREEN,- color: FINCEPT.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: isLoading ? 'not-allowed' : 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px'- }}- >- {isLoading ? 'SAVING...' : 'SAVE CHANGES'}- </button>- <button- onClick={() => setEditingDataset(null)}- style={{- padding: '8px 16px',- backgroundColor: 'transparent',- color: FINCEPT.GRAY,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px'- }}- >- CANCEL- </button>- </div>- </div>- )}-- {isLoading && !editingDataset ? (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading datasets...- </div>- ) : myDatasets.length === 0 ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <Package size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No datasets uploaded yet</span>- </div>- ) : (- <div style={{ maxWidth: '1000px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {myDatasets.map((dataset) => {- const statusColor = getStatusColor(dataset.status || 'pending');- return (- <div key={dataset.id} style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderLeft: `4px solid ${statusColor}`,- borderRadius: '2px',- padding: '16px'- }}>- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '12px' }}>- <div style={{ flex: 1 }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '6px' }}>- <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE }}>- {dataset.title}- </div>- <div style={{- padding: '2px 6px',- backgroundColor: `${statusColor}20`,- color: statusColor,- fontSize: '8px',- fontWeight: 700,- borderRadius: '2px',- letterSpacing: '0.5px'- }}>- {(dataset.status || 'pending').toUpperCase()}- </div>- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, marginBottom: '8px' }}>- {dataset.category} • {dataset.price_tier} • {dataset.downloads_count} downloads • {new Date(dataset.uploaded_at).toLocaleDateString()}- </div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: '1.5' }}>- {dataset.description}- </div>- {dataset.rejection_reason && (- <div style={{- marginTop: '12px',- padding: '8px',- backgroundColor: `${FINCEPT.RED}10`,- border: `1px solid ${FINCEPT.RED}`,- borderRadius: '2px'- }}>- <div style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.RED, marginBottom: '4px', letterSpacing: '0.5px' }}>- REJECTION REASON- </div>- <div style={{ fontSize: '9px', color: FINCEPT.RED }}>- {dataset.rejection_reason}- </div>- </div>- )}- </div>- <div style={{ display: 'flex', gap: '8px', marginLeft: '16px' }}>- {(dataset.status === 'pending' || dataset.status === 'rejected') && (- <button- onClick={() => handleEdit(dataset)}- style={{- padding: '6px 12px',- backgroundColor: 'transparent',- border: `1px solid ${FINCEPT.BLUE}`,- color: FINCEPT.BLUE,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Edit size={10} />- EDIT- </button>- )}- <button- onClick={() => handleDelete(dataset.id, dataset.title)}- style={{- padding: '6px 12px',- backgroundColor: 'transparent',- border: `1px solid ${FINCEPT.RED}`,- color: FINCEPT.RED,- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '4px'- }}- >- <Trash2 size={10} />- DELETE- </button>- </div>- </div>- {dataset.tags && dataset.tags.length > 0 && (- <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>- {dataset.tags.map((tag, idx) => (- <span key={idx} style={{- padding: '2px 6px',- backgroundColor: `${FINCEPT.PURPLE}20`,- color: FINCEPT.PURPLE,- fontSize: '8px',- fontWeight: 700,- borderRadius: '2px'- }}>- #{tag}- </span>- ))}- </div>- )}- </div>- );- })}- </div>- )}- </div>- </div>- );-};diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/MyPurchasesScreen.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/screens/MyPurchasesScreen.tsxdeleted file mode 100644index d098795e7..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/MyPurchasesScreen.tsx+++ /dev/null@@ -1,158 +0,0 @@-import React, { useState, useEffect, useCallback, useRef } from 'react';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { withTimeout } from '@/services/core/apiUtils';-import { showError } from '@/utils/notifications';-import { FINCEPT, FONT_FAMILY, API_TIMEOUT_MS } from '../types';-import { ShoppingCart, Download } from 'lucide-react';--export const MyPurchasesScreen: React.FC<{ session: any }> = ({ session }) => {- const [purchases, setPurchases] = useState<any[]>([]);- const [isLoading, setIsLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- useEffect(() => {- const fetchPurchases = async () => {- if (!session?.api_key) return;- setIsLoading(true);- setError(null);- try {- const response = await withTimeout(- MarketplaceApiService.getUserPurchases(session.api_key, 1, 50),- API_TIMEOUT_MS,- 'Fetch purchases timeout'- );- if (!mountedRef.current) return;- if (response.success && response.data) {- setPurchases(response.data.purchases || []);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('Failed to fetch purchases:', err);- setError(err instanceof Error ? err.message : 'Failed to fetch purchases');- } finally {- if (mountedRef.current) setIsLoading(false);- }- };- fetchPurchases();- }, [session?.api_key]);-- const handleDownload = useCallback(async (datasetId: number) => {- if (!session?.api_key) return;- try {- const response = await withTimeout(- MarketplaceApiService.downloadDataset(session.api_key, datasetId),- API_TIMEOUT_MS,- 'Download timeout'- );- if (response.success && response.data?.download_url) {- window.open(response.data.download_url, '_blank');- } else {- showError('Download failed');- }- } catch (err) {- showError('Download failed', [- { label: 'ERROR', value: err instanceof Error ? err.message : 'Unknown error' }- ]);- }- }, [session?.api_key]);-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <ShoppingCart size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- MY PURCHASES ({purchases.length})- </span>- </div>- </div>- </div>-- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- {isLoading ? (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading purchases...- </div>- ) : purchases.length === 0 ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <ShoppingCart size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No purchases yet</span>- </div>- ) : (- <div style={{ maxWidth: '1000px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '12px' }}>- {purchases.map((purchase) => (- <div key={purchase.id} style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `1px solid ${FINCEPT.BORDER}`,- borderLeft: `4px solid ${FINCEPT.GREEN}`,- borderRadius: '2px',- padding: '16px',- display: 'flex',- justifyContent: 'space-between',- alignItems: 'center'- }}>- <div style={{ flex: 1 }}>- <div style={{ fontSize: '11px', fontWeight: 700, color: FINCEPT.WHITE, marginBottom: '6px' }}>- {purchase.dataset_title}- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY, display: 'flex', gap: '16px' }}>- <span>PURCHASED: {new Date(purchase.purchased_at).toLocaleDateString()}</span>- <span>PAID: <span style={{ color: FINCEPT.GREEN }}>{purchase.price_paid} CREDITS</span></span>- </div>- </div>- <button- onClick={() => handleDownload(purchase.dataset_id)}- style={{- padding: '8px 16px',- backgroundColor: FINCEPT.ORANGE,- color: FINCEPT.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- cursor: 'pointer',- fontFamily: FONT_FAMILY,- letterSpacing: '0.5px',- display: 'flex',- alignItems: 'center',- gap: '6px'- }}- >- <Download size={10} />- DOWNLOAD- </button>- </div>- ))}- </div>- )}- </div>- </div>- );-};diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/PricingScreen.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/screens/PricingScreen.tsxdeleted file mode 100644index db6c36866..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/PricingScreen.tsx+++ /dev/null@@ -1,168 +0,0 @@-import React, { useState, useEffect, useRef } from 'react';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { withTimeout } from '@/services/core/apiUtils';-import { FINCEPT, API_TIMEOUT_MS } from '../types';-import { DollarSign, Check } from 'lucide-react';--export const PricingScreen: React.FC<{ session: any }> = ({ session }) => {- const [pricingTiers, setPricingTiers] = useState<any[]>([]);- const [isLoading, setIsLoading] = useState(true);- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- useEffect(() => {- const fetchPricing = async () => {- if (!session?.api_key) return;- setIsLoading(true);- try {- const response = await withTimeout(- MarketplaceApiService.getPricingTiers(session.api_key),- API_TIMEOUT_MS,- 'Fetch pricing timeout'- );- if (!mountedRef.current) return;- if (response.success && response.data) {- setPricingTiers(response.data.tiers || []);- }- } catch (err) {- if (!mountedRef.current) return;- console.error('Failed to fetch pricing tiers:', err);- } finally {- if (mountedRef.current) setIsLoading(false);- }- };- fetchPricing();- }, [session?.api_key]);-- return (- <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- <DollarSign size={12} color={FINCEPT.ORANGE} />- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- PRICING TIERS- </span>- </div>- </div>-- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- {isLoading ? (- <div style={{- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px'- }}>- Loading pricing...- </div>- ) : pricingTiers.length === 0 ? (- <div style={{- display: 'flex',- flexDirection: 'column',- alignItems: 'center',- justifyContent: 'center',- height: '200px',- color: FINCEPT.MUTED,- fontSize: '10px',- textAlign: 'center'- }}>- <DollarSign size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />- <span>No pricing information available</span>- </div>- ) : (- <div style={{- maxWidth: '1200px',- margin: '0 auto',- display: 'grid',- gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',- gap: '16px'- }}>- {pricingTiers.map((tier, idx) => (- <div key={idx} style={{- backgroundColor: FINCEPT.PANEL_BG,- border: `2px solid ${FINCEPT.ORANGE}`,- borderRadius: '2px',- padding: '20px',- textAlign: 'center'- }}>- <div style={{- fontSize: '12px',- fontWeight: 700,- color: FINCEPT.ORANGE,- marginBottom: '12px',- letterSpacing: '0.5px'- }}>- {tier.tier.toUpperCase()}- </div>- <div style={{- fontSize: '32px',- fontWeight: 700,- color: FINCEPT.GREEN,- marginBottom: '4px'- }}>- {tier.price_credits}- </div>- <div style={{- fontSize: '9px',- color: FINCEPT.GRAY,- marginBottom: '16px',- letterSpacing: '0.5px'- }}>- CREDITS- </div>- <div style={{- fontSize: '10px',- color: FINCEPT.WHITE,- lineHeight: '1.6',- marginBottom: '20px'- }}>- {tier.description}- </div>- {tier.features && tier.features.length > 0 && (- <div style={{- textAlign: 'left',- borderTop: `1px solid ${FINCEPT.BORDER}`,- paddingTop: '16px'- }}>- <div style={{- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.CYAN,- marginBottom: '12px',- letterSpacing: '0.5px'- }}>- FEATURES- </div>- {tier.features.map((feature: string, fidx: number) => (- <div key={fidx} style={{- fontSize: '9px',- color: FINCEPT.WHITE,- marginBottom: '6px',- display: 'flex',- alignItems: 'center',- gap: '8px'- }}>- <Check size={10} color={FINCEPT.GREEN} />- <span>{feature}</span>- </div>- ))}- </div>- )}- </div>- ))}- </div>- )}- </div>- </div>- );-};diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/UploadScreen.tsx b/fincept-terminal-desktop/src/components/tabs/marketplace/screens/UploadScreen.tsxdeleted file mode 100644index a5e1498a5..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/screens/UploadScreen.tsx+++ /dev/null@@ -1,418 +0,0 @@-import React, { useState, useEffect, useCallback, useRef } from 'react';-import { MarketplaceApiService } from '@/services/marketplace/marketplaceApi';-import { withTimeout } from '@/services/core/apiUtils';-import { sanitizeInput } from '@/services/core/validators';-import { showWarning, showError, showSuccess } from '@/utils/notifications';-import { FINCEPT, FONT_FAMILY, API_TIMEOUT_MS } from '../types';-import { Upload, Check } from 'lucide-react';--export const UploadScreen: React.FC<{- uploadFile: File | null;- onFileChange: (file: File | null) => void;- uploadMetadata: any;- onMetadataChange: (metadata: any) => void;- isLoading: boolean;- session: any;- onUploadComplete: () => void;-}> = ({ uploadFile, onFileChange, uploadMetadata, onMetadataChange, isLoading, session, onUploadComplete }) => {- const [uploading, setUploading] = useState(false);- const mountedRef = useRef(true);-- useEffect(() => {- mountedRef.current = true;- return () => { mountedRef.current = false; };- }, []);-- const handleUpload = useCallback(async () => {- if (!session?.api_key || !uploadFile) {- showWarning('Please select a file and fill in all required fields');- return;- }-- // Sanitize inputs- const sanitizedTitle = sanitizeInput(uploadMetadata.title);- const sanitizedDescription = sanitizeInput(uploadMetadata.description);-- if (!sanitizedTitle || !sanitizedDescription) {- showWarning('Title and description are required');- return;- }-- setUploading(true);- try {- const response = await withTimeout(- MarketplaceApiService.uploadDataset(- session.api_key,- uploadFile,- {- title: sanitizedTitle,- description: sanitizedDescription,- category: uploadMetadata.category,- price_tier: uploadMetadata.price_tier,- tags: uploadMetadata.tags ? uploadMetadata.tags.split(',').map((t: string) => sanitizeInput(t.trim())).filter((t: string) => t) : []- }- ),- 60000, // 60 second timeout for file uploads- 'Upload timeout'- );-- if (!mountedRef.current) return;-- if (response.success) {- showSuccess('Dataset uploaded successfully');- onFileChange(null);- onMetadataChange({- title: '',- description: '',- category: 'stocks',- price_tier: 'free',- tags: ''- });- setTimeout(() => onUploadComplete(), 1000);- } else {- showError('Upload failed', [- { label: 'ERROR', value: response.error || 'Unknown error' }- ]);- }- } catch (err) {- if (mountedRef.current) {- showError('Upload failed', [- { label: 'ERROR', value: err instanceof Error ? err.message : 'Unknown error' }- ]);- }- } finally {- if (mountedRef.current) setUploading(false);- }- }, [session?.api_key, uploadFile, uploadMetadata, onFileChange, onMetadataChange, onUploadComplete]);-- return (- <div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>- {/* Left Panel - Guidelines */}- <div style={{- width: '320px',- backgroundColor: FINCEPT.PANEL_BG,- borderRight: `1px solid ${FINCEPT.BORDER}`,- display: 'flex',- flexDirection: 'column',- overflow: 'hidden'- }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- UPLOAD GUIDELINES- </span>- </div>- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '12px' }}>- <div style={{ marginBottom: '16px' }}>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '8px' }}>- SUPPORTED FORMATS- </div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: '1.6' }}>- CSV, JSON, XLSX, Parquet, HDF5- </div>- </div>- <div style={{ marginBottom: '16px' }}>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '8px' }}>- FILE SIZE LIMIT- </div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: '1.6' }}>- Maximum 500 MB per file- </div>- </div>- <div style={{ marginBottom: '16px' }}>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '8px' }}>- APPROVAL PROCESS- </div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: '1.6' }}>- All datasets undergo admin review before becoming publicly available. You'll be notified via email once approved.- </div>- </div>- <div style={{ marginBottom: '16px' }}>- <div style={{ fontSize: '10px', fontWeight: 700, color: FINCEPT.ORANGE, marginBottom: '8px' }}>- PRICING TIERS- </div>- <div style={{ fontSize: '10px', color: FINCEPT.GRAY, lineHeight: '1.6' }}>- • FREE: No cost<br />- • BASIC: 10 credits<br />- • PREMIUM: 50 credits<br />- • ENTERPRISE: 100 credits- </div>- </div>- </div>- </div>-- {/* Center Panel - Upload Form */}- <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>- <div style={{- padding: '12px',- backgroundColor: FINCEPT.HEADER_BG,- borderBottom: `1px solid ${FINCEPT.BORDER}`- }}>- <span style={{ fontSize: '9px', fontWeight: 700, color: FINCEPT.GRAY, letterSpacing: '0.5px' }}>- UPLOAD NEW DATASET- </span>- </div>- <div className="marketplace-scroll" style={{ flex: 1, overflowY: 'auto', padding: '16px' }}>- <div style={{ maxWidth: '600px', margin: '0 auto' }}>- {/* Title Input */}- <div style={{ marginBottom: '16px' }}>- <label style={{- display: 'block',- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '6px',- letterSpacing: '0.5px'- }}>- DATASET TITLE *- </label>- <input- type="text"- value={uploadMetadata.title}- onChange={(e) => onMetadataChange({ ...uploadMetadata, title: e.target.value })}- placeholder="Enter descriptive title..."- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- outline: 'none'- }}- onFocus={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}- />- </div>-- {/* Description Textarea */}- <div style={{ marginBottom: '16px' }}>- <label style={{- display: 'block',- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '6px',- letterSpacing: '0.5px'- }}>- DESCRIPTION *- </label>- <textarea- value={uploadMetadata.description}- onChange={(e) => onMetadataChange({ ...uploadMetadata, description: e.target.value })}- placeholder="Describe your dataset, its contents, and use cases..."- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- minHeight: '120px',- outline: 'none',- resize: 'vertical'- }}- onFocus={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}- />- </div>-- {/* Category & Price Tier Row */}- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '16px' }}>- <div>- <label style={{- display: 'block',- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '6px',- letterSpacing: '0.5px'- }}>- CATEGORY *- </label>- <select- value={uploadMetadata.category}- onChange={(e) => onMetadataChange({ ...uploadMetadata, category: e.target.value })}- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- outline: 'none'- }}- onFocus={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}- >- <option value="stocks">Stocks</option>- <option value="forex">Forex</option>- <option value="crypto">Cryptocurrency</option>- <option value="commodities">Commodities</option>- <option value="bonds">Bonds</option>- <option value="indices">Indices</option>- <option value="economic_data">Economic Data</option>- </select>- </div>- <div>- <label style={{- display: 'block',- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '6px',- letterSpacing: '0.5px'- }}>- PRICE TIER *- </label>- <select- value={uploadMetadata.price_tier}- onChange={(e) => onMetadataChange({ ...uploadMetadata, price_tier: e.target.value })}- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- outline: 'none'- }}- onFocus={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}- >- <option value="free">Free (0 credits)</option>- <option value="basic">Basic (10 credits)</option>- <option value="premium">Premium (50 credits)</option>- <option value="enterprise">Enterprise (100 credits)</option>- </select>- </div>- </div>-- {/* Tags Input */}- <div style={{ marginBottom: '16px' }}>- <label style={{- display: 'block',- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '6px',- letterSpacing: '0.5px'- }}>- TAGS (COMMA SEPARATED)- </label>- <input- type="text"- value={uploadMetadata.tags}- onChange={(e) => onMetadataChange({ ...uploadMetadata, tags: e.target.value })}- placeholder="stocks, equity, real-time, historical"- style={{- width: '100%',- padding: '8px 10px',- backgroundColor: FINCEPT.DARK_BG,- color: FINCEPT.WHITE,- border: `1px solid ${FINCEPT.BORDER}`,- borderRadius: '2px',- fontSize: '10px',- fontFamily: FONT_FAMILY,- outline: 'none'- }}- onFocus={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onBlur={(e) => e.currentTarget.style.borderColor = FINCEPT.BORDER}- />- </div>-- {/* File Upload */}- <div style={{ marginBottom: '24px' }}>- <label style={{- display: 'block',- fontSize: '9px',- fontWeight: 700,- color: FINCEPT.GRAY,- marginBottom: '6px',- letterSpacing: '0.5px'- }}>- DATASET FILE *- </label>- <div style={{- border: `2px dashed ${uploadFile ? FINCEPT.GREEN : FINCEPT.BORDER}`,- borderRadius: '2px',- padding: '24px',- textAlign: 'center',- backgroundColor: FINCEPT.DARK_BG,- cursor: 'pointer',- transition: 'all 0.2s'- }}- onMouseEnter={(e) => e.currentTarget.style.borderColor = FINCEPT.ORANGE}- onMouseLeave={(e) => e.currentTarget.style.borderColor = uploadFile ? FINCEPT.GREEN : FINCEPT.BORDER}- >- <input- type="file"- onChange={(e) => onFileChange(e.target.files?.[0] || null)}- style={{ display: 'none' }}- id="file-upload"- />- <label htmlFor="file-upload" style={{ cursor: 'pointer', display: 'block' }}>- {uploadFile ? (- <>- <Check size={24} color={FINCEPT.GREEN} style={{ marginBottom: '8px' }} />- <div style={{ fontSize: '10px', color: FINCEPT.WHITE, marginBottom: '4px' }}>- {uploadFile.name}- </div>- <div style={{ fontSize: '9px', color: FINCEPT.GRAY }}>- {(uploadFile.size / 1024 / 1024).toFixed(2)} MB- </div>- </>- ) : (- <>- <Upload size={24} color={FINCEPT.GRAY} style={{ marginBottom: '8px', opacity: 0.5 }} />- <div style={{ fontSize: '10px', color: FINCEPT.GRAY }}>- Click to select file or drag and drop- </div>- </>- )}- </label>- </div>- </div>-- {/* Upload Button */}- <button- onClick={handleUpload}- disabled={uploading || isLoading || !uploadFile || !uploadMetadata.title || !uploadMetadata.description}- style={{- width: '100%',- padding: '12px',- backgroundColor: uploading || isLoading || !uploadFile || !uploadMetadata.title || !uploadMetadata.description ? FINCEPT.MUTED : FINCEPT.ORANGE,- color: FINCEPT.DARK_BG,- border: 'none',- borderRadius: '2px',- fontSize: '9px',- fontWeight: 700,- letterSpacing: '0.5px',- cursor: uploading || isLoading || !uploadFile || !uploadMetadata.title || !uploadMetadata.description ? 'not-allowed' : 'pointer',- fontFamily: FONT_FAMILY,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- gap: '8px'- }}- >- <Upload size={12} />- {uploading ? 'UPLOADING...' : 'UPLOAD DATASET'}- </button>- </div>- </div>- </div>- </div>- );-};diff --git a/fincept-terminal-desktop/src/components/tabs/marketplace/types.ts b/fincept-terminal-desktop/src/components/tabs/marketplace/types.tsdeleted file mode 100644index 5b201fd3e..000000000--- a/fincept-terminal-desktop/src/components/tabs/marketplace/types.ts+++ /dev/null@@ -1,97 +0,0 @@-// 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',-};--export const FONT_FAMILY = '"IBM Plex Mono", "Consolas", monospace';--export const API_TIMEOUT_MS = 30000;--export type ScreenType = 'BROWSE' | 'UPLOAD' | 'MY_PURCHASES' | 'MY_DATASETS' | 'ANALYTICS' | 'PRICING' | 'ADMIN_STATS' | 'ADMIN_PENDING' | 'ADMIN_REVENUE';--// ══════════════════════════════════════════════════════════════-// STATE MACHINE & TYPES-// ══════════════════════════════════════════════════════════════-export type MarketplaceStatus = 'idle' | 'loading' | 'ready' | 'error';--export interface MarketplaceState {- status: MarketplaceStatus;- currentScreen: ScreenType;- datasets: any[];- myUploadedDatasets: any[];- selectedDataset: any | null;- selectedCategory: string;- searchQuery: string;- currentPage: number;- totalPages: number;- error: string | null;-}--export type MarketplaceAction =- | { type: 'SET_LOADING' }- | { type: 'SET_READY' }- | { type: 'SET_ERROR'; error: string }- | { type: 'SET_SCREEN'; screen: ScreenType }- | { type: 'SET_DATASETS'; datasets: any[]; totalPages: number }- | { type: 'SET_MY_DATASETS'; datasets: any[] }- | { type: 'SET_SELECTED_DATASET'; dataset: any | null }- | { type: 'SET_CATEGORY'; category: string }- | { type: 'SET_SEARCH'; query: string }- | { type: 'SET_PAGE'; page: number }- | { type: 'RESET_ERROR' };--export const initialState: MarketplaceState = {- status: 'idle',- currentScreen: 'BROWSE',- datasets: [],- myUploadedDatasets: [],- selectedDataset: null,- selectedCategory: 'ALL',- searchQuery: '',- currentPage: 1,- totalPages: 1,- error: null-};--export function marketplaceReducer(state: MarketplaceState, action: MarketplaceAction): MarketplaceState {- switch (action.type) {- case 'SET_LOADING':- return { ...state, status: 'loading', error: null };- case 'SET_READY':- return { ...state, status: 'ready', error: null };- case 'SET_ERROR':- return { ...state, status: 'error', error: action.error };- case 'SET_SCREEN':- return { ...state, currentScreen: action.screen };- case 'SET_DATASETS':- return { ...state, datasets: action.datasets, totalPages: action.totalPages };- case 'SET_MY_DATASETS':- return { ...state, myUploadedDatasets: action.datasets };- case 'SET_SELECTED_DATASET':- return { ...state, selectedDataset: action.dataset };- case 'SET_CATEGORY':- return { ...state, selectedCategory: action.category, currentPage: 1 };- case 'SET_SEARCH':- return { ...state, searchQuery: action.query, currentPage: 1 };- case 'SET_PAGE':- return { ...state, currentPage: action.page };- case 'RESET_ERROR':- return { ...state, error: null };- default:- return state;- }-}diff --git a/fincept-terminal-desktop/src/components/tabs/news/LiveNewsPanel.tsx b/fincept-terminal-desktop/src/components/tabs/news/LiveNewsPanel.tsxindex 43dc885f4..07943e91d 100644--- a/fincept-terminal-desktop/src/components/tabs/news/LiveNewsPanel.tsx+++ b/fincept-terminal-desktop/src/components/tabs/news/LiveNewsPanel.tsx@@ -102,7 +102,9 @@ export const LiveNewsPanel: React.FC<Props> = () => {}, []);const postEmbed = useCallback((msg: Record<string, unknown>) => {- iframeRef.current?.contentWindow?.postMessage(msg, embedOriginRef.current);+ if (embedOriginRef.current) {+ iframeRef.current?.contentWindow?.postMessage(msg, embedOriginRef.current);+ }}, []);const toggleMute = () => {@@ -118,7 +120,7 @@ export const LiveNewsPanel: React.FC<Props> = () => {const embedSrc = (ch: LiveChannel): string => {if (!embedPort) return '';- return `http://127.0.0.1:${embedPort}/yt-embed?videoId=${ch.fallbackVideoId}&autoplay=1&mute=${muted ? '1' : '0'}`;+ return `http://127.0.0.1:${embedPort}/yt-embed?videoId=${encodeURIComponent(ch.fallbackVideoId)}&autoplay=1&mute=${muted ? '1' : '0'}`;};const btn = (active = false): React.CSSProperties => ({diff --git a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/TerminalAppearanceSection.tsx b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/TerminalAppearanceSection.tsxindex 88f6e977f..09abdd03a 100644--- a/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/TerminalAppearanceSection.tsx+++ b/fincept-terminal-desktop/src/components/tabs/settings-tab/sections/TerminalAppearanceSection.tsx@@ -833,7 +833,6 @@ export function TerminalAppearanceSection({<option value="profile">Profile</option><option value="settings">Settings</option><option value="forum">Forum</option>- <option value="marketplace">Marketplace</option></select></div>))}diff --git a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx b/fincept-terminal-desktop/src/contexts/BrokerContext.tsxindex 10d7703fb..c200dac27 100644--- a/fincept-terminal-desktop/src/contexts/BrokerContext.tsx+++ b/fincept-terminal-desktop/src/contexts/BrokerContext.tsx@@ -56,11 +56,13 @@ async function safeStorageSet(key: string, value: string): Promise<void> {}}-// Helper to create timeout promise-function createTimeout(ms: number): Promise<never> {- return new Promise((_, reject) =>- setTimeout(() => reject(new Error(`Connection timeout after ${ms}ms`)), ms)- );+// Helper to create timeout promise with cleanup+function createTimeout(ms: number): { promise: Promise<never>; clear: () => void } {+ let timerId: ReturnType<typeof setTimeout>;+ const promise = new Promise<never>((_, reject) => {+ timerId = setTimeout(() => reject(new Error(`Connection timeout after ${ms}ms`)), ms);+ });+ return { promise, clear: () => clearTimeout(timerId) };}// Helper to retry connection with exponential backoff@@ -70,10 +72,13 @@ async function retryConnect(delay: number = CONNECTION_RETRY_DELAY): Promise<void> {for (let i = 0; i < attempts; i++) {+ const timeout = createTimeout(CONNECTION_TIMEOUT);try {- await Promise.race([connectFn(), createTimeout(CONNECTION_TIMEOUT)]);+ await Promise.race([connectFn(), timeout.promise]);+ timeout.clear();return;} catch (error) {+ timeout.clear();if (i === attempts - 1) throw error;await new Promise(resolve => setTimeout(resolve, delay * (i + 1))); // Exponential backoff}diff --git a/fincept-terminal-desktop/src/i18n/config.ts b/fincept-terminal-desktop/src/i18n/config.tsindex c0e1e0c82..bfd8993fd 100644--- a/fincept-terminal-desktop/src/i18n/config.ts+++ b/fincept-terminal-desktop/src/i18n/config.ts@@ -74,7 +74,7 @@ i18next'profile', 'screener', 'trading', 'watchlist', 'dataMapping','dataSources', 'docs', 'notes', 'support', 'nodeEditor','reportBuilder', 'alphaArena', 'codeEditor', 'agentConfig',- 'dbnomics', 'excel', 'marketplace', 'backtesting', 'akshare'+ 'dbnomics', 'excel', 'backtesting', 'akshare'],react: {diff --git a/fincept-terminal-desktop/src/services/marketplace/marketplaceApi.tsx b/fincept-terminal-desktop/src/services/marketplace/marketplaceApi.tsxdeleted file mode 100644index 724d773ff..000000000--- a/fincept-terminal-desktop/src/services/marketplace/marketplaceApi.tsx+++ /dev/null@@ -1,489 +0,0 @@-// File: src/services/marketplaceApi.tsx-// Marketplace API service for handling all marketplace-related API calls--import { fetch } from '@tauri-apps/plugin-http';--// API Configuration-const API_CONFIG = {- BASE_URL: import.meta.env.DEV ? '/api' : 'https://api.fincept.in',- API_VERSION: 'v1',- CONNECTION_TIMEOUT: 10000,- REQUEST_TIMEOUT: 30000-};--const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;--// API Response Types-interface ApiResponse<T = any> {- success: boolean;- data?: T;- message?: string;- error?: string;- status_code?: number;-}--// Request Types-export interface DatasetMetadata {- title: string;- description: string;- category: string;- price_tier: string;- tags?: string[];-}--export interface DatasetPurchaseRequest {- payment_method?: string;-}--export interface DatasetFilters {- category?: string;- search?: string;- price_tier?: string;- page?: number;- limit?: number;- sort_by?: string;- sort_order?: string;-}--// Response Types-export interface Dataset {- id: number;- title: string;- description: string;- category: string;- price_tier: string;- price_credits: number;- uploader_id: number;- uploader_username: string;- file_name: string;- file_size: number;- downloads_count: number;- rating: number;- tags: string[];- status?: string; // pending, approved, rejected- rejection_reason?: string;- uploaded_at: string;- updated_at: string;-}--export interface DatasetPurchase {- id: number;- dataset_id: number;- dataset_title: string;- price_paid: number;- purchased_at: string;- access_expires_at?: string;-}--export interface PricingTier {- tier: string;- price_credits: number;- description: string;- features: string[];-}--export interface DatasetAnalytics {- total_datasets: number;- total_downloads: number;- total_revenue: number;- datasets: Array<{- id: number;- title: string;- downloads: number;- revenue: number;- rating: number;- }>;-}--export interface RevenueAnalytics {- total_revenue: number;- total_transactions: number;- revenue_by_tier: Record<string, number>;- top_datasets: Array<{- id: number;- title: string;- revenue: number;- downloads: number;- }>;-}--export interface MarketplaceStats {- total_datasets: number;- total_purchases: number;- total_revenue: number;- total_uploads: number;- active_users: number;- popular_categories: Record<string, number>;-}--// Generic API request function-const makeApiRequest = async <T = any>(- method: string,- endpoint: string,- data?: any,- headers?: Record<string, string>,- isFormData: boolean = false-): Promise<ApiResponse<T>> => {- try {- const defaultHeaders: Record<string, string> = {- ...(isFormData ? {} : { 'Content-Type': 'application/json' }),- ...headers- };-- const url = getApiEndpoint(endpoint);- console.log('🚀 Making marketplace request:', {- method,- url,- endpoint,- isFormData,- headers: { ...defaultHeaders, 'X-API-Key': (defaultHeaders as any)['X-API-Key'] ? '[REDACTED]' : undefined }- });-- const config: RequestInit = {- method,- headers: defaultHeaders,- mode: 'cors',- };-- if (data) {- if (isFormData) {- config.body = data; // FormData- } else if (method === 'POST' || method === 'PUT') {- config.body = JSON.stringify(data);- }- }-- const response = await fetch(url, config);-- console.log('📡 Marketplace response received:', {- status: response.status,- statusText: response.statusText,- url: response.url- });-- const responseText = await response.text();- console.log('📄 Raw marketplace response text:', responseText.substring(0, 200));-- let responseData;- try {- responseData = JSON.parse(responseText);- console.log('[OK] Parsed marketplace JSON:', responseData);- } catch (parseError) {- console.error('[ERROR] Marketplace JSON parse failed:', parseError);- return {- success: false,- error: `Invalid JSON response: ${responseText.substring(0, 100)}...`,- status_code: response.status- };- }-- return {- success: response.ok,- data: responseData,- status_code: response.status,- error: response.ok ? undefined : responseData.message || `HTTP ${response.status}`- };-- } catch (error) {- console.error('💥 Marketplace request failed:', error);-- if (error instanceof TypeError && error.message.includes('Failed to fetch')) {- return {- success: false,- error: 'Network error: Unable to connect to server. Please check your internet connection.'- };- }-- return {- success: false,- error: error instanceof Error ? error.message : 'Network error'- };- }-};--// Marketplace API Service Class-export class MarketplaceApiService {- /**- * 1. Upload dataset to marketplace- * POST /marketplace/upload- */- static async uploadDataset(- apiKey: string,- file: File,- metadata: DatasetMetadata- ): Promise<ApiResponse<Dataset>> {- try {- const formData = new FormData();- formData.append('file', file);-- // Create proper metadata object without tags if empty- const metadataObj = {- title: metadata.title,- description: metadata.description,- category: metadata.category,- price_tier: metadata.price_tier,- ...(metadata.tags && metadata.tags.length > 0 ? { tags: metadata.tags } : {})- };-- const metadataString = JSON.stringify(metadataObj);- console.log('Upload metadata:', metadataObj);-- // Append as query parameter in the URL- const endpoint = `/marketplace/upload?metadata=${encodeURIComponent(metadataString)}`;-- return makeApiRequest<Dataset>(- 'POST',- endpoint,- formData,- { 'X-API-Key': apiKey },- true // isFormData- );- } catch (error) {- console.error('Upload dataset error:', error);- return {- success: false,- error: error instanceof Error ? error.message : 'Upload failed'- };- }- }-- /**- * 2. Browse datasets in marketplace- * GET /marketplace/datasets- */- static async browseDatasets(- apiKey: string,- filters?: DatasetFilters- ): Promise<ApiResponse<{ datasets: Dataset[]; total: number; page: number; total_pages: number }>> {- const queryParams = new URLSearchParams();-- if (filters?.category) queryParams.append('category', filters.category);- if (filters?.search) queryParams.append('search', filters.search);- if (filters?.price_tier) queryParams.append('price_tier', filters.price_tier);- if (filters?.page) queryParams.append('page', filters.page.toString());- if (filters?.limit) queryParams.append('limit', filters.limit.toString());- if (filters?.sort_by) queryParams.append('sort_by', filters.sort_by);- if (filters?.sort_order) queryParams.append('sort_order', filters.sort_order);-- const endpoint = `/marketplace/datasets${queryParams.toString() ? `?${queryParams.toString()}` : ''}`;-- return makeApiRequest('GET', endpoint, undefined, { 'X-API-Key': apiKey });- }-- /**- * 3. Get dataset details- * GET /marketplace/datasets/{dataset_id}- */- static async getDatasetDetails(- apiKey: string,- datasetId: number- ): Promise<ApiResponse<Dataset>> {- return makeApiRequest<Dataset>(- 'GET',- `/marketplace/datasets/${datasetId}`,- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 4. Purchase dataset access- * POST /marketplace/datasets/{dataset_id}/purchase- */- static async purchaseDataset(- apiKey: string,- datasetId: number,- purchaseData?: DatasetPurchaseRequest- ): Promise<ApiResponse<{ purchase_id: number; access_granted: boolean; credits_remaining: number }>> {- return makeApiRequest(- 'POST',- `/marketplace/datasets/${datasetId}/purchase`,- purchaseData || { payment_method: 'subscription_credit' },- { 'X-API-Key': apiKey }- );- }-- /**- * 5. Download dataset- * POST /marketplace/datasets/{dataset_id}/download- */- static async downloadDataset(- apiKey: string,- datasetId: number- ): Promise<ApiResponse<{ download_url: string; expires_at: string }>> {- return makeApiRequest(- 'POST',- `/marketplace/datasets/${datasetId}/download`,- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 6. Get user's purchases- * GET /marketplace/my-purchases- */- static async getUserPurchases(- apiKey: string,- page: number = 1,- limit: number = 20- ): Promise<ApiResponse<{ purchases: DatasetPurchase[]; total: number; page: number; total_pages: number }>> {- return makeApiRequest(- 'GET',- `/marketplace/my-purchases?page=${page}&limit=${limit}`,- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 7. Get pricing tiers- * GET /marketplace/pricing- */- static async getPricingTiers(apiKey: string): Promise<ApiResponse<{ tiers: PricingTier[] }>> {- return makeApiRequest('GET', '/marketplace/pricing', undefined, { 'X-API-Key': apiKey });- }-- /**- * 8. Get my uploaded datasets- * GET /marketplace/my-datasets- */- static async getMyDatasets(- apiKey: string,- page: number = 1,- limit: number = 20,- status?: string- ): Promise<ApiResponse<{ datasets: Dataset[]; total: number; page: number; total_pages: number }>> {- const queryParams = new URLSearchParams();- queryParams.append('page', page.toString());- queryParams.append('limit', limit.toString());- if (status) queryParams.append('status', status);-- return makeApiRequest(- 'GET',- `/marketplace/my-datasets?${queryParams.toString()}`,- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 9. Update dataset metadata- * PATCH /marketplace/datasets/{dataset_id}- */- static async updateDataset(- apiKey: string,- datasetId: number,- updateData: Partial<DatasetMetadata>- ): Promise<ApiResponse<Dataset>> {- return makeApiRequest<Dataset>(- 'PATCH',- `/marketplace/datasets/${datasetId}`,- updateData,- { 'X-API-Key': apiKey }- );- }-- /**- * 10. Delete dataset- * DELETE /marketplace/datasets/{dataset_id}- */- static async deleteDataset(- apiKey: string,- datasetId: number- ): Promise<ApiResponse<{ message: string }>> {- return makeApiRequest(- 'DELETE',- `/marketplace/datasets/${datasetId}`,- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 11. Get dataset analytics (for uploader)- * GET /marketplace/my-datasets/analytics- */- static async getDatasetAnalytics(apiKey: string): Promise<ApiResponse<DatasetAnalytics>> {- return makeApiRequest<DatasetAnalytics>(- 'GET',- '/marketplace/my-datasets/analytics',- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 12. Get admin revenue analytics- * GET /marketplace/admin/revenue-analytics- */- static async getAdminRevenueAnalytics(apiKey: string): Promise<ApiResponse<RevenueAnalytics>> {- return makeApiRequest<RevenueAnalytics>(- 'GET',- '/marketplace/admin/revenue-analytics',- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 13. Get marketplace statistics- * GET /marketplace/admin/stats- */- static async getMarketplaceStats(apiKey: string): Promise<ApiResponse<MarketplaceStats>> {- return makeApiRequest<MarketplaceStats>(- 'GET',- '/marketplace/admin/stats',- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 14. Get pending datasets (admin)- * GET /marketplace/admin/pending-datasets- */- static async getPendingDatasets(apiKey: string): Promise<ApiResponse<{ datasets: Dataset[] }>> {- return makeApiRequest(- 'GET',- '/marketplace/admin/pending-datasets',- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 15. Approve dataset (admin)- * POST /marketplace/admin/datasets/{dataset_id}/approve- */- static async approveDataset(- apiKey: string,- datasetId: number- ): Promise<ApiResponse<{ message: string; dataset: Dataset }>> {- return makeApiRequest(- 'POST',- `/marketplace/admin/datasets/${datasetId}/approve`,- undefined,- { 'X-API-Key': apiKey }- );- }-- /**- * 16. Reject dataset (admin)- * POST /marketplace/admin/datasets/{dataset_id}/reject- */- static async rejectDataset(- apiKey: string,- datasetId: number,- reason: string- ): Promise<ApiResponse<{ message: string; dataset: Dataset }>> {- return makeApiRequest(- 'POST',- `/marketplace/admin/datasets/${datasetId}/reject`,- { reason },- { 'X-API-Key': apiKey }- );- }-}--export default MarketplaceApiService;diff --git a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.tsindex 569ea2db8..90939e9ca 100644--- a/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts+++ b/fincept-terminal-desktop/src/services/mcp/internal/tools/navigation.ts@@ -3,7 +3,7 @@ import { InternalTool } from '../types';const AVAILABLE_TABS = ['dashboard', 'markets', 'news', 'watchlist', 'portfolio', 'research','economics', 'dbnomics', 'geopolitics', 'maritime', 'screener',- 'chat', 'docs', 'nodes', 'code', 'forum', 'marketplace',+ 'chat', 'docs', 'nodes', 'code', 'forum','profile', 'support', 'settings', 'backtesting', 'mcp', 'trading','reportbuilder', 'equity-trading', 'datasources', 'ai-quant-lab','notes', 'agents', 'monitoring', 'polymarket', 'derivatives', 'asia-markets', 'akshare'@@ -352,21 +352,6 @@ export const navigationTools: InternalTool[] = [return { success: true, message: 'Navigated to Forum tab' };},},- {- name: 'open_marketplace_tab',- description: 'Navigate to the Marketplace tab to browse and install extensions, indicators, strategies, and premium features',- inputSchema: {- type: 'object',- properties: {},- },- handler: async (_args, contexts) => {- if (!contexts.setActiveTab) {- return { success: false, error: 'Navigation context not available' };- }- contexts.setActiveTab('marketplace');- return { success: true, message: 'Navigated to Marketplace tab' };- },- },{name: 'open_profile_tab',description: 'Navigate to the Profile tab for user account settings, subscription management, and personal information',diff --git a/fincept-terminal-desktop/src/types/tabConfig.ts b/fincept-terminal-desktop/src/types/tabConfig.tsindex d735d0b6f..696091472 100644--- a/fincept-terminal-desktop/src/types/tabConfig.ts+++ b/fincept-terminal-desktop/src/types/tabConfig.ts@@ -45,7 +45,6 @@ export const DEFAULT_TABS: TabDefinition[] = [{ id: 'reportbuilder', label: 'Report Builder', value: 'reportbuilder', component: 'ReportBuilderTab' },{ id: 'contexts', label: 'Contexts', value: 'contexts', component: 'RecordedContextsManager' },{ id: 'forum', label: 'Forum', value: 'forum', component: 'ForumTab' },- { id: 'marketplace', label: 'Marketplace', value: 'marketplace', component: 'MarketplaceTab' },{ id: 'docs', label: 'Documentation', value: 'docs', component: 'DocsTab' },{ id: 'support', label: 'Support', value: 'support', component: 'SupportTicketTab' },{ id: 'agents', label: 'Agents', value: 'agents', component: 'AgentConfigTab' },@@ -60,7 +59,7 @@ export const DEFAULT_TAB_CONFIG: TabConfiguration = {{ id: 'research-menu', label: 'Research', tabs: ['geopolitics', 'maritime'] },{ id: 'trading-menu', label: 'Trading', tabs: ['fyers', 'alpha-arena', 'ai-quant-lab'] },{ id: 'tools-menu', label: 'Tools', tabs: ['mcp', 'nodes', 'code', 'datasources', 'reportbuilder', 'contexts'] },- { id: 'community-menu', label: 'Community', tabs: ['forum', 'marketplace', 'docs'] },+ { id: 'community-menu', label: 'Community', tabs: ['forum', 'docs'] },{ id: 'help-menu', label: 'Help', tabs: ['support'] }]};