Skip to content

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.

Update build.yml [skip ci]

tilakpatel22c703fafb57b5
diff --git a/.gitignore b/.gitignore
index 4b649f28a..93cc63164 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,6 +14,9 @@ fincept_env
python
treeview.py
testing
+fincept-terminal-desktop/.vscode
+fincept-terminal-desktop/.claude
+fincept-terminal-desktop/CLAUDE.md
fincept_terminal/fyers_session_config.json
fincept_terminal/backup_20250730_072611
.pdm-build
@@ -32,7 +35,6 @@ fincept_terminal/watchlist_settings.json
upx.exe
fincept_icon.ico
legacy-python-depreciated/python
-fincept-terminal-desktop/.vscode
fincept-terminal-desktop/node_modules
setup.iss
upx.exe"build/"
diff --git a/fincept-terminal-desktop/package-lock.json b/fincept-terminal-desktop/package-lock.json
index 72afb0175..33be9de6c 100644
--- a/fincept-terminal-desktop/package-lock.json
+++ b/fincept-terminal-desktop/package-lock.json
@@ -10,37 +10,67 @@
"dependencies": {
"@langchain/community": "^0.3.56",
"@langchain/ollama": "^0.2.4",
+ "@radix-ui/react-accordion": "^1.2.12",
+ "@radix-ui/react-alert-dialog": "^1.1.15",
+ "@radix-ui/react-aspect-ratio": "^1.1.7",
"@radix-ui/react-avatar": "^1.1.10",
+ "@radix-ui/react-checkbox": "^1.3.3",
+ "@radix-ui/react-collapsible": "^1.1.12",
+ "@radix-ui/react-context-menu": "^2.2.16",
+ "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
+ "@radix-ui/react-hover-card": "^1.1.15",
"@radix-ui/react-label": "^2.1.7",
+ "@radix-ui/react-menubar": "^1.1.16",
+ "@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-progress": "^1.1.7",
+ "@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-scroll-area": "^1.2.10",
+ "@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.7",
+ "@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.3",
+ "@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
+ "@radix-ui/react-toggle": "^1.1.10",
+ "@radix-ui/react-toggle-group": "^1.1.11",
+ "@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/vite": "^4.1.13",
"@tauri-apps/api": "^2.8.0",
"@tauri-apps/plugin-http": "^2.5.2",
"@tauri-apps/plugin-opener": "^2",
+ "axios": "^1.12.2",
"cheerio": "^1.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "cmdk": "^1.1.1",
+ "date-fns": "^4.1.0",
+ "embla-carousel-react": "^8.6.0",
+ "fyers-web-sdk-v3": "^1.3.1",
"langchain": "^0.3.34",
"lucide-react": "^0.544.0",
"next-themes": "^0.4.6",
"ollama": "^0.6.0",
+ "otplib": "^12.0.1",
"playwright": "^1.55.1",
"react": "^19.1.0",
+ "react-day-picker": "^9.11.0",
"react-dom": "^19.1.0",
+ "recharts": "^2.15.4",
"sonner": "^2.0.7",
"tailwind-merge": "^3.3.1",
- "tailwindcss": "^4.1.13"
+ "tailwindcss": "^4.1.13",
+ "vaul": "^1.1.2",
+ "ws": "^8.18.3"
},
"devDependencies": {
"@tauri-apps/cli": "^2",
+ "@types/node": "^24.5.2",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
+ "@types/ws": "^8.18.1",
"@vitejs/plugin-react": "^4.6.0",
+ "ts-node": "^10.9.2",
"tw-animate-css": "^1.4.0",
"typescript": "~5.8.3",
"vite": "^7.0.4"
@@ -313,6 +343,15 @@
"@babel/core": "^7.0.0-0"
}
},
+ "node_modules/@babel/runtime": {
+ "version": "7.28.4",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",
+ "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
"node_modules/@babel/template": {
"version": "7.27.2",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz",
@@ -421,6 +460,36 @@
"license": "MIT",
"peer": true
},
+ "node_modules/@cspotcode/source-map-support": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
+ "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.9"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.9",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
+ "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.0.3",
+ "@jridgewell/sourcemap-codec": "^1.4.10"
+ }
+ },
+ "node_modules/@date-fns/tz": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/@date-fns/tz/-/tz-1.4.1.tgz",
+ "integrity": "sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==",
+ "license": "MIT"
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.25.10",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.10.tgz",
@@ -1654,6 +1723,53 @@
"@langchain/core": ">=0.2.21 <0.4.0"
}
},
+ "node_modules/@otplib/core": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/@otplib/core/-/core-12.0.1.tgz",
+ "integrity": "sha512-4sGntwbA/AC+SbPhbsziRiD+jNDdIzsZ3JUyfZwjtKyc/wufl1pnSIaG4Uqx8ymPagujub0o92kgBnB89cuAMA==",
+ "license": "MIT"
+ },
+ "node_modules/@otplib/plugin-crypto": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/@otplib/plugin-crypto/-/plugin-crypto-12.0.1.tgz",
+ "integrity": "sha512-qPuhN3QrT7ZZLcLCyKOSNhuijUi9G5guMRVrxq63r9YNOxxQjPm59gVxLM+7xGnHnM6cimY57tuKsjK7y9LM1g==",
+ "license": "MIT",
+ "dependencies": {
+ "@otplib/core": "^12.0.1"
+ }
+ },
+ "node_modules/@otplib/plugin-thirty-two": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/@otplib/plugin-thirty-two/-/plugin-thirty-two-12.0.1.tgz",
+ "integrity": "sha512-MtT+uqRso909UkbrrYpJ6XFjj9D+x2Py7KjTO9JDPhL0bJUYVu5kFP4TFZW4NFAywrAtFRxOVY261u0qwb93gA==",
+ "license": "MIT",
+ "dependencies": {
+ "@otplib/core": "^12.0.1",
+ "thirty-two": "^1.0.2"
+ }
+ },
+ "node_modules/@otplib/preset-default": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/@otplib/preset-default/-/preset-default-12.0.1.tgz",
+ "integrity": "sha512-xf1v9oOJRyXfluBhMdpOkr+bsE+Irt+0D5uHtvg6x1eosfmHCsCC6ej/m7FXiWqdo0+ZUI6xSKDhJwc8yfiOPQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@otplib/core": "^12.0.1",
+ "@otplib/plugin-crypto": "^12.0.1",
+ "@otplib/plugin-thirty-two": "^12.0.1"
+ }
+ },
+ "node_modules/@otplib/preset-v11": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/@otplib/preset-v11/-/preset-v11-12.0.1.tgz",
+ "integrity": "sha512-9hSetMI7ECqbFiKICrNa4w70deTUfArtwXykPUvSHWOdzOlfa9ajglu7mNCntlvxycTiOAXkQGwjQCzzDEMRMg==",
+ "license": "MIT",
+ "dependencies": {
+ "@otplib/core": "^12.0.1",
+ "@otplib/plugin-crypto": "^12.0.1",
+ "@otplib/plugin-thirty-two": "^12.0.1"
+ }
+ },
"node_modules/@playwright/test": {
"version": "1.55.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.55.1.tgz",
@@ -1746,6 +1862,65 @@
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
+ "node_modules/@radix-ui/react-accordion": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.2.12.tgz",
+ "integrity": "sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-collapsible": "1.1.12",
+ "@radix-ui/react-collection": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-alert-dialog": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.1.15.tgz",
+ "integrity": "sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dialog": "1.1.15",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-arrow": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.1.7.tgz",
@@ -1769,6 +1944,29 @@
}
}
},
+ "node_modules/@radix-ui/react-aspect-ratio": {
+ "version": "1.1.7",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-aspect-ratio/-/react-aspect-ratio-1.1.7.tgz",
+ "integrity": "sha512-Yq6lvO9HQyPwev1onK1daHCHqXVLzPhSVjmsNjCa2Zcxy2f7uJD2itDtxknv6FzAKCwD1qQkeVDmX/cev13n/g==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-primitive": "2.1.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-avatar": {
"version": "1.1.10",
"resolved": "https://registry.npmjs.org/@radix-ui/react-avatar/-/react-avatar-1.1.10.tgz",
@@ -1796,6 +1994,66 @@
}
}
},
+ "node_modules/@radix-ui/react-checkbox": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-checkbox/-/react-checkbox-1.3.3.tgz",
+ "integrity": "sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-collapsible": {
+ "version": "1.1.12",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-collapsible/-/react-collapsible-1.1.12.tgz",
+ "integrity": "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-layout-effect": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-collection": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",
@@ -1852,6 +2110,70 @@
}
}
},
+ "node_modules/@radix-ui/react-context-menu": {
+ "version": "2.2.16",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-context-menu/-/react-context-menu-2.2.16.tgz",
+ "integrity": "sha512-O8morBEW+HsVG28gYDZPTrT9UUovQUlJue5YO836tiTJhuIWBm/zQHc7j388sHWtdH/xUZurK9olD2+pcqx5ww==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-menu": "2.1.16",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-dialog": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-dialog/-/react-dialog-1.1.15.tgz",
+ "integrity": "sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-focus-guards": "1.1.3",
+ "@radix-ui/react-focus-scope": "1.1.7",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "aria-hidden": "^1.2.4",
+ "react-remove-scroll": "^2.6.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-direction": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-direction/-/react-direction-1.1.1.tgz",
@@ -1963,6 +2285,37 @@
}
}
},
+ "node_modules/@radix-ui/react-hover-card": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-hover-card/-/react-hover-card-1.1.15.tgz",
+ "integrity": "sha512-qgTkjNT1CfKMoP0rcasmlH2r1DAiYicWsDsufxl940sT2wHNEWWv6FMWIQXWhVdmC1d/HYfbhQx60KYyAtKxjg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-popper": "1.2.8",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-id": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-id/-/react-id-1.1.1.tgz",
@@ -2044,22 +2397,91 @@
}
}
},
- "node_modules/@radix-ui/react-popper": {
- "version": "1.2.8",
- "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.8.tgz",
- "integrity": "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==",
+ "node_modules/@radix-ui/react-menubar": {
+ "version": "1.1.16",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-menubar/-/react-menubar-1.1.16.tgz",
+ "integrity": "sha512-EB1FktTz5xRRi2Er974AUQZWg2yVBb1yjip38/lgwtCVRd3a+maUoGHN/xs9Yv8SY8QwbSEb+YrxGadVWbEutA==",
"license": "MIT",
"dependencies": {
- "@floating-ui/react-dom": "^2.0.0",
- "@radix-ui/react-arrow": "1.1.7",
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-collection": "1.1.7",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-menu": "2.1.16",
"@radix-ui/react-primitive": "2.1.3",
- "@radix-ui/react-use-callback-ref": "1.1.1",
- "@radix-ui/react-use-layout-effect": "1.1.1",
- "@radix-ui/react-use-rect": "1.1.1",
- "@radix-ui/react-use-size": "1.1.1",
- "@radix-ui/rect": "1.1.1"
+ "@radix-ui/react-roving-focus": "1.1.11",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-popover": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popover/-/react-popover-1.1.15.tgz",
+ "integrity": "sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-focus-guards": "1.1.3",
+ "@radix-ui/react-focus-scope": "1.1.7",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.8",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "aria-hidden": "^1.2.4",
+ "react-remove-scroll": "^2.6.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-popper": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-popper/-/react-popper-1.2.8.tgz",
+ "integrity": "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==",
+ "license": "MIT",
+ "dependencies": {
+ "@floating-ui/react-dom": "^2.0.0",
+ "@radix-ui/react-arrow": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-use-rect": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1",
+ "@radix-ui/rect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
@@ -2171,6 +2593,38 @@
}
}
},
+ "node_modules/@radix-ui/react-radio-group": {
+ "version": "1.3.8",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-radio-group/-/react-radio-group-1.3.8.tgz",
+ "integrity": "sha512-VBKYIYImA5zsxACdisNQ3BjCBfmbGH3kQlnFVqlWU4tXwjy7cGX8ta80BcrO+WJXIn5iBylEH3K6ZTlee//lgQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-roving-focus": "1.1.11",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-roving-focus": {
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.11.tgz",
@@ -2233,6 +2687,49 @@
}
}
},
+ "node_modules/@radix-ui/react-select": {
+ "version": "2.2.6",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.2.6.tgz",
+ "integrity": "sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/number": "1.1.1",
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-collection": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-focus-guards": "1.1.3",
+ "@radix-ui/react-focus-scope": "1.1.7",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.8",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3",
+ "@radix-ui/react-use-callback-ref": "1.1.1",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-visually-hidden": "1.2.3",
+ "aria-hidden": "^1.2.4",
+ "react-remove-scroll": "^2.6.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-separator": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.7.tgz",
@@ -2256,6 +2753,39 @@
}
}
},
+ "node_modules/@radix-ui/react-slider": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.3.6.tgz",
+ "integrity": "sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/number": "1.1.1",
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-collection": "1.1.7",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-layout-effect": "1.1.1",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-slot": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
@@ -2274,6 +2804,35 @@
}
}
},
+ "node_modules/@radix-ui/react-switch": {
+ "version": "1.2.6",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-switch/-/react-switch-1.2.6.tgz",
+ "integrity": "sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-use-previous": "1.1.1",
+ "@radix-ui/react-use-size": "1.1.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-tabs": {
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/@radix-ui/react-tabs/-/react-tabs-1.1.13.tgz",
@@ -2304,6 +2863,94 @@
}
}
},
+ "node_modules/@radix-ui/react-toggle": {
+ "version": "1.1.10",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle/-/react-toggle-1.1.10.tgz",
+ "integrity": "sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-toggle-group": {
+ "version": "1.1.11",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-toggle-group/-/react-toggle-group-1.1.11.tgz",
+ "integrity": "sha512-5umnS0T8JQzQT6HbPyO7Hh9dgd82NmS36DQr+X/YJ9ctFNCiiQd6IJAYYZ33LUwm8M+taCz5t2ui29fHZc4Y6Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-direction": "1.1.1",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-roving-focus": "1.1.11",
+ "@radix-ui/react-toggle": "1.1.10",
+ "@radix-ui/react-use-controllable-state": "1.2.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-tooltip": {
+ "version": "1.2.8",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.2.8.tgz",
+ "integrity": "sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/primitive": "1.1.3",
+ "@radix-ui/react-compose-refs": "1.1.2",
+ "@radix-ui/react-context": "1.1.2",
+ "@radix-ui/react-dismissable-layer": "1.1.11",
+ "@radix-ui/react-id": "1.1.1",
+ "@radix-ui/react-popper": "1.2.8",
+ "@radix-ui/react-portal": "1.1.9",
+ "@radix-ui/react-presence": "1.1.5",
+ "@radix-ui/react-primitive": "2.1.3",
+ "@radix-ui/react-slot": "1.2.3",
+ "@radix-ui/react-use-controllable-state": "1.2.2",
+ "@radix-ui/react-visually-hidden": "1.2.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-use-callback-ref": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
@@ -2407,6 +3054,21 @@
}
}
},
+ "node_modules/@radix-ui/react-use-previous": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-use-previous/-/react-use-previous-1.1.1.tgz",
+ "integrity": "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-use-rect": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-rect/-/react-use-rect-1.1.1.tgz",
@@ -2443,6 +3105,29 @@
}
}
},
+ "node_modules/@radix-ui/react-visually-hidden": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-visually-hidden/-/react-visually-hidden-1.2.3.tgz",
+ "integrity": "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-primitive": "2.1.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/rect": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/rect/-/rect-1.1.1.tgz",
@@ -3243,6 +3928,34 @@
"license": "MIT",
"peer": true
},
+ "node_modules/@tsconfig/node10": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
+ "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tsconfig/node12": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
+ "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tsconfig/node14": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
+ "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tsconfig/node16": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
+ "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -3288,6 +4001,69 @@
"@babel/types": "^7.28.2"
}
},
+ "node_modules/@types/d3-array": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
+ "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-color": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
+ "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-ease": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
+ "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-interpolate": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
+ "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-color": "*"
+ }
+ },
+ "node_modules/@types/d3-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
+ "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-scale": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
+ "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-time": "*"
+ }
+ },
+ "node_modules/@types/d3-shape": {
+ "version": "3.1.7",
+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz",
+ "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/d3-path": "*"
+ }
+ },
+ "node_modules/@types/d3-time": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
+ "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
+ "license": "MIT"
+ },
+ "node_modules/@types/d3-timer": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
+ "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
+ "license": "MIT"
+ },
"node_modules/@types/debug": {
"version": "4.1.12",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
@@ -3370,6 +4146,16 @@
"integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==",
"license": "MIT"
},
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@vitejs/plugin-react": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
@@ -3410,6 +4196,32 @@
"integrity": "sha512-VtUwTNU8fpMwvWGn4xE93ywbogTYsuT+AUxAXOeelbXuQVIwNmC5YLeho9sH4vZ4ITW8414TTAOG1nW6uIVHCA==",
"license": "MIT"
},
+ "node_modules/acorn": {
+ "version": "8.15.0",
+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
+ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "acorn": "bin/acorn"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/acorn-walk": {
+ "version": "8.3.4",
+ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",
+ "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "acorn": "^8.11.0"
+ },
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/agentkeepalive": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz",
@@ -3445,6 +4257,13 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
+ "node_modules/arg": {
+ "version": "4.1.3",
+ "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
+ "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
@@ -3467,15 +4286,13 @@
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/axios": {
"version": "1.12.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz",
"integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==",
"license": "MIT",
- "peer": true,
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.4",
@@ -3601,7 +4418,6 @@
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
@@ -3761,6 +4577,22 @@
"node": ">=6"
}
},
+ "node_modules/cmdk": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.1.1.tgz",
+ "integrity": "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-compose-refs": "^1.1.1",
+ "@radix-ui/react-dialog": "^1.1.6",
+ "@radix-ui/react-id": "^1.1.0",
+ "@radix-ui/react-primitive": "^2.0.2"
+ },
+ "peerDependencies": {
+ "react": "^18 || ^19 || ^19.0.0-rc",
+ "react-dom": "^18 || ^19 || ^19.0.0-rc"
+ }
+ },
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -3784,7 +4616,6 @@
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"license": "MIT",
- "peer": true,
"dependencies": {
"delayed-stream": "~1.0.0"
},
@@ -3808,6 +4639,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/create-require": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
+ "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/cross-fetch": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.2.0.tgz",
@@ -3849,7 +4687,143 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",
"integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==",
- "devOptional": true,
+ "license": "MIT"
+ },
+ "node_modules/d3-array": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
+ "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
+ "license": "ISC",
+ "dependencies": {
+ "internmap": "1 - 2"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-color": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-ease": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
+ "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-format": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
+ "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-interpolate": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
+ "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-color": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-path": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
+ "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-scale": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
+ "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2.10.0 - 3",
+ "d3-format": "1 - 3",
+ "d3-interpolate": "1.2.0 - 3",
+ "d3-time": "2.1.1 - 3",
+ "d3-time-format": "2 - 4"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-shape": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
+ "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-path": "^3.1.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
+ "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-array": "2 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-time-format": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
+ "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
+ "license": "ISC",
+ "dependencies": {
+ "d3-time": "1 - 3"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/d3-timer": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
+ "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/date-fns": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
+ "integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/kossnocorp"
+ }
+ },
+ "node_modules/date-fns-jalali": {
+ "version": "4.1.0-0",
+ "resolved": "https://registry.npmjs.org/date-fns-jalali/-/date-fns-jalali-4.1.0-0.tgz",
+ "integrity": "sha512-hTIP/z+t+qKwBDcmmsnmjWTduxCg+5KfdqWQvb2X/8C9+knYY6epN/pfxdDuyVlSVeFz0sM5eEfwIUQ70U4ckg==",
"license": "MIT"
},
"node_modules/debug": {
@@ -3879,6 +4853,12 @@
"node": ">=0.10.0"
}
},
+ "node_modules/decimal.js-light": {
+ "version": "2.5.1",
+ "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz",
+ "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==",
+ "license": "MIT"
+ },
"node_modules/deepmerge": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
@@ -3894,7 +4874,6 @@
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=0.4.0"
}
@@ -3914,6 +4893,26 @@
"integrity": "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==",
"license": "MIT"
},
+ "node_modules/diff": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
+ "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.3.1"
+ }
+ },
+ "node_modules/dom-helpers": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/dom-helpers/-/dom-helpers-5.2.1.tgz",
+ "integrity": "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.8.7",
+ "csstype": "^3.0.2"
+ }
+ },
"node_modules/dom-serializer": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
@@ -3987,7 +4986,6 @@
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
- "peer": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
@@ -4014,6 +5012,34 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/embla-carousel": {
+ "version": "8.6.0",
+ "resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
+ "integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
+ "license": "MIT"
+ },
+ "node_modules/embla-carousel-react": {
+ "version": "8.6.0",
+ "resolved": "https://registry.npmjs.org/embla-carousel-react/-/embla-carousel-react-8.6.0.tgz",
+ "integrity": "sha512-0/PjqU7geVmo6F734pmPqpyHqiM99olvyecY7zdweCw+6tKEXnrE90pBiBbMMU8s5tICemzpQ3hi5EpxzGW+JA==",
+ "license": "MIT",
+ "dependencies": {
+ "embla-carousel": "8.6.0",
+ "embla-carousel-reactive-utils": "8.6.0"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.1 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"
+ }
+ },
+ "node_modules/embla-carousel-reactive-utils": {
+ "version": "8.6.0",
+ "resolved": "https://registry.npmjs.org/embla-carousel-reactive-utils/-/embla-carousel-reactive-utils-8.6.0.tgz",
+ "integrity": "sha512-fMVUDUEx0/uIEDM0Mz3dHznDhfX+znCCDCeIophYb1QGVM7YThSWX+wz11zlYwWFOr74b4QLGg0hrGPJeG2s4A==",
+ "license": "MIT",
+ "peerDependencies": {
+ "embla-carousel": "8.6.0"
+ }
+ },
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
@@ -4063,7 +5089,6 @@
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 0.4"
}
@@ -4073,7 +5098,6 @@
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 0.4"
}
@@ -4083,7 +5107,6 @@
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
- "peer": true,
"dependencies": {
"es-errors": "^1.3.0"
},
@@ -4096,7 +5119,6 @@
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"license": "MIT",
- "peer": true,
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
@@ -4196,6 +5218,15 @@
"license": "MIT",
"peer": true
},
+ "node_modules/fast-equals": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/fast-equals/-/fast-equals-5.3.2.tgz",
+ "integrity": "sha512-6rxyATwPCkaFIL3JLqw8qXqMpIZ942pTX/tbQFkRsDGblS8tNGtlUauA/+mt6RUfqn/4MoEr+WDkYoIQbibWuQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -4251,7 +5282,6 @@
}
],
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=4.0"
},
@@ -4266,7 +5296,6 @@
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
- "peer": true,
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
@@ -4318,11 +5347,19 @@
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
- "peer": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/fyers-web-sdk-v3": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/fyers-web-sdk-v3/-/fyers-web-sdk-v3-1.3.1.tgz",
+ "integrity": "sha512-rnLlJkSIm7Y4fxv8FuHuDgiMFG9rAHlQ/2jMZcV2XqX8faIG4nLwcbjcwNAV9DJB5i7MB7PhU23QtClHd/vWQg==",
+ "license": "ISC",
+ "dependencies": {
+ "axios": "^1.6.8"
+ }
+ },
"node_modules/gensync": {
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
@@ -4347,7 +5384,6 @@
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
@@ -4381,7 +5417,6 @@
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
- "peer": true,
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
@@ -4395,7 +5430,6 @@
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 0.4"
},
@@ -4445,7 +5479,6 @@
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 0.4"
},
@@ -4458,7 +5491,6 @@
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"license": "MIT",
- "peer": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
@@ -4474,7 +5506,6 @@
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"function-bind": "^1.1.2"
},
@@ -4600,6 +5631,15 @@
"license": "BSD-3-Clause",
"peer": true
},
+ "node_modules/internmap": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
+ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
@@ -4638,7 +5678,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
- "dev": true,
"license": "MIT"
},
"node_modules/js-yaml": {
@@ -5117,6 +6156,12 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/lodash": {
+ "version": "4.17.21",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
+ "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
+ "license": "MIT"
+ },
"node_modules/lodash.camelcase": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz",
@@ -5178,6 +6223,18 @@
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"license": "Apache-2.0"
},
+ "node_modules/loose-envify": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "license": "MIT",
+ "dependencies": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ },
+ "bin": {
+ "loose-envify": "cli.js"
+ }
+ },
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -5206,12 +6263,18 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/make-error": {
+ "version": "1.3.6",
+ "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
+ "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 0.4"
}
@@ -5221,7 +6284,6 @@
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">= 0.6"
}
@@ -5231,7 +6293,6 @@
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
- "peer": true,
"dependencies": {
"mime-db": "1.52.0"
},
@@ -5394,6 +6455,15 @@
"url": "https://github.com/fb55/nth-check?sponsor=1"
}
},
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/ollama": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/ollama/-/ollama-0.6.0.tgz",
@@ -5457,6 +6527,17 @@
"integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==",
"license": "MIT"
},
+ "node_modules/otplib": {
+ "version": "12.0.1",
+ "resolved": "https://registry.npmjs.org/otplib/-/otplib-12.0.1.tgz",
+ "integrity": "sha512-xDGvUOQjop7RDgxTQ+o4pOol0/3xSZzawTiPKRrHnQWAy0WjhNs/5HdIDJCrqC4MBynmjXgULc6YfioaxZeFgg==",
+ "license": "MIT",
+ "dependencies": {
+ "@otplib/core": "^12.0.1",
+ "@otplib/preset-default": "^12.0.1",
+ "@otplib/preset-v11": "^12.0.1"
+ }
+ },
"node_modules/p-finally": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz",
@@ -5670,6 +6751,23 @@
"node": ">= 0.6.0"
}
},
+ "node_modules/prop-types": {
+ "version": "15.8.1",
+ "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
+ "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.4.0",
+ "object-assign": "^4.1.1",
+ "react-is": "^16.13.1"
+ }
+ },
+ "node_modules/prop-types/node_modules/react-is": {
+ "version": "16.13.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
+ "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
+ "license": "MIT"
+ },
"node_modules/protobufjs": {
"version": "7.5.4",
"resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.5.4.tgz",
@@ -5698,8 +6796,7 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/psl": {
"version": "1.15.0",
@@ -5740,6 +6837,27 @@
"node": ">=0.10.0"
}
},
+ "node_modules/react-day-picker": {
+ "version": "9.11.0",
+ "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-9.11.0.tgz",
+ "integrity": "sha512-L4FYOaPrr3+AEROeP6IG2mCORZZfxJDkJI2df8mv1jyPrNYeccgmFPZDaHyAuPCBCddQFozkxbikj2NhMEYfDQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@date-fns/tz": "^1.4.1",
+ "date-fns": "^4.1.0",
+ "date-fns-jalali": "^4.1.0-0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "individual",
+ "url": "https://github.com/sponsors/gpbl"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0"
+ }
+ },
"node_modules/react-dom": {
"version": "19.1.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.1.tgz",
@@ -5752,6 +6870,12 @@
"react": "^19.1.1"
}
},
+ "node_modules/react-is": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
+ "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
+ "license": "MIT"
+ },
"node_modules/react-refresh": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
@@ -5809,6 +6933,21 @@
}
}
},
+ "node_modules/react-smooth": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/react-smooth/-/react-smooth-4.0.4.tgz",
+ "integrity": "sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-equals": "^5.0.1",
+ "prop-types": "^15.8.1",
+ "react-transition-group": "^4.4.5"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/react-style-singleton": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",
@@ -5831,6 +6970,22 @@
}
}
},
+ "node_modules/react-transition-group": {
+ "version": "4.4.5",
+ "resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
+ "integrity": "sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@babel/runtime": "^7.5.5",
+ "dom-helpers": "^5.0.1",
+ "loose-envify": "^1.4.0",
+ "prop-types": "^15.6.2"
+ },
+ "peerDependencies": {
+ "react": ">=16.6.0",
+ "react-dom": ">=16.6.0"
+ }
+ },
"node_modules/readable-stream": {
"version": "4.7.0",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-4.7.0.tgz",
@@ -5865,6 +7020,38 @@
"url": "https://github.com/sponsors/Borewit"
}
},
+ "node_modules/recharts": {
+ "version": "2.15.4",
+ "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.15.4.tgz",
+ "integrity": "sha512-UT/q6fwS3c1dHbXv2uFgYJ9BMFHu3fwnd7AYZaEQhXuYQ4hgsxLvsUXzGdKeZrW5xopzDCvuA2N41WJ88I7zIw==",
+ "license": "MIT",
+ "dependencies": {
+ "clsx": "^2.0.0",
+ "eventemitter3": "^4.0.1",
+ "lodash": "^4.17.21",
+ "react-is": "^18.3.1",
+ "react-smooth": "^4.0.4",
+ "recharts-scale": "^0.4.4",
+ "tiny-invariant": "^1.3.1",
+ "victory-vendor": "^36.6.8"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "peerDependencies": {
+ "react": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
+ "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
+ "node_modules/recharts-scale": {
+ "version": "0.4.5",
+ "resolved": "https://registry.npmjs.org/recharts-scale/-/recharts-scale-0.4.5.tgz",
+ "integrity": "sha512-kivNFO+0OcUNu7jQquLXAxz1FIwZj8nrj+YkOKc5694NbjCvcT6aSZiIzNzd2Kul4o4rTto8QVR9lMNtxD4G1w==",
+ "license": "MIT",
+ "dependencies": {
+ "decimal.js-light": "^2.4.1"
+ }
+ },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@@ -6131,6 +7318,20 @@
"node": ">=18"
}
},
+ "node_modules/thirty-two": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/thirty-two/-/thirty-two-1.0.2.tgz",
+ "integrity": "sha512-OEI0IWCe+Dw46019YLl6V10Us5bi574EvlJEOcAkB29IzQ/mYD1A6RyNHLjZPiHCmuodxvgF6U+vZO1L15lxVA==",
+ "engines": {
+ "node": ">=0.2.6"
+ }
+ },
+ "node_modules/tiny-invariant": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz",
+ "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==",
+ "license": "MIT"
+ },
"node_modules/tinyglobby": {
"version": "0.2.15",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
@@ -6193,6 +7394,50 @@
"integrity": "sha512-tLJxacIQUM82IR7JO1UUkKlYuUTmoY9HBJAmNWFzheSlDS5SPMcNIepejHJa4BpPQLAcbRhRf3GDJzyj6rbKvA==",
"license": "MIT"
},
+ "node_modules/ts-node": {
+ "version": "10.9.2",
+ "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
+ "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@cspotcode/source-map-support": "^0.8.0",
+ "@tsconfig/node10": "^1.0.7",
+ "@tsconfig/node12": "^1.0.7",
+ "@tsconfig/node14": "^1.0.0",
+ "@tsconfig/node16": "^1.0.2",
+ "acorn": "^8.4.1",
+ "acorn-walk": "^8.1.1",
+ "arg": "^4.1.0",
+ "create-require": "^1.1.0",
+ "diff": "^4.0.1",
+ "make-error": "^1.1.1",
+ "v8-compile-cache-lib": "^3.0.1",
+ "yn": "3.1.1"
+ },
+ "bin": {
+ "ts-node": "dist/bin.js",
+ "ts-node-cwd": "dist/bin-cwd.js",
+ "ts-node-esm": "dist/bin-esm.js",
+ "ts-node-script": "dist/bin-script.js",
+ "ts-node-transpile-only": "dist/bin-transpile.js",
+ "ts-script": "dist/bin-script-deprecated.js"
+ },
+ "peerDependencies": {
+ "@swc/core": ">=1.2.50",
+ "@swc/wasm": ">=1.2.50",
+ "@types/node": "*",
+ "typescript": ">=2.7"
+ },
+ "peerDependenciesMeta": {
+ "@swc/core": {
+ "optional": true
+ },
+ "@swc/wasm": {
+ "optional": true
+ }
+ }
+ },
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -6355,6 +7600,48 @@
"uuid": "dist/bin/uuid"
}
},
+ "node_modules/v8-compile-cache-lib": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
+ "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vaul": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vaul/-/vaul-1.1.2.tgz",
+ "integrity": "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA==",
+ "license": "MIT",
+ "dependencies": {
+ "@radix-ui/react-dialog": "^1.1.1"
+ },
+ "peerDependencies": {
+ "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc",
+ "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc"
+ }
+ },
+ "node_modules/victory-vendor": {
+ "version": "36.9.2",
+ "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-36.9.2.tgz",
+ "integrity": "sha512-PnpQQMuxlwYdocC8fIJqVXvkeViHYzotI+NJrCuav0ZYFoq912ZHBk3mCeuj+5/VpodOjPe1z0Fk2ihgzlXqjQ==",
+ "license": "MIT AND ISC",
+ "dependencies": {
+ "@types/d3-array": "^3.0.3",
+ "@types/d3-ease": "^3.0.0",
+ "@types/d3-interpolate": "^3.0.1",
+ "@types/d3-scale": "^4.0.2",
+ "@types/d3-shape": "^3.1.0",
+ "@types/d3-time": "^3.0.0",
+ "@types/d3-timer": "^3.0.0",
+ "d3-array": "^3.1.6",
+ "d3-ease": "^3.0.1",
+ "d3-interpolate": "^3.0.1",
+ "d3-scale": "^4.0.2",
+ "d3-shape": "^3.1.0",
+ "d3-time": "^3.0.0",
+ "d3-timer": "^3.0.1"
+ }
+ },
"node_modules/vite": {
"version": "7.1.6",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.6.tgz",
@@ -6551,7 +7838,6 @@
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=10.0.0"
},
@@ -6623,6 +7909,16 @@
"node": ">=12"
}
},
+ "node_modules/yn": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
+ "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/zod": {
"version": "3.25.76",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index f36b77125..78e7a6295 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -12,37 +12,67 @@
"dependencies": {
"@langchain/community": "^0.3.56",
"@langchain/ollama": "^0.2.4",
+ "@radix-ui/react-accordion": "^1.2.12",
+ "@radix-ui/react-alert-dialog": "^1.1.15",
+ "@radix-ui/react-aspect-ratio": "^1.1.7",
"@radix-ui/react-avatar": "^1.1.10",
+ "@radix-ui/react-checkbox": "^1.3.3",
+ "@radix-ui/react-collapsible": "^1.1.12",
+ "@radix-ui/react-context-menu": "^2.2.16",
+ "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
+ "@radix-ui/react-hover-card": "^1.1.15",
"@radix-ui/react-label": "^2.1.7",
+ "@radix-ui/react-menubar": "^1.1.16",
+ "@radix-ui/react-popover": "^1.1.15",
"@radix-ui/react-progress": "^1.1.7",
+ "@radix-ui/react-radio-group": "^1.3.8",
"@radix-ui/react-scroll-area": "^1.2.10",
+ "@radix-ui/react-select": "^2.2.6",
"@radix-ui/react-separator": "^1.1.7",
+ "@radix-ui/react-slider": "^1.3.6",
"@radix-ui/react-slot": "^1.2.3",
+ "@radix-ui/react-switch": "^1.2.6",
"@radix-ui/react-tabs": "^1.1.13",
+ "@radix-ui/react-toggle": "^1.1.10",
+ "@radix-ui/react-toggle-group": "^1.1.11",
+ "@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/vite": "^4.1.13",
"@tauri-apps/api": "^2.8.0",
"@tauri-apps/plugin-http": "^2.5.2",
"@tauri-apps/plugin-opener": "^2",
+ "axios": "^1.12.2",
"cheerio": "^1.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "cmdk": "^1.1.1",
+ "date-fns": "^4.1.0",
+ "embla-carousel-react": "^8.6.0",
+ "fyers-web-sdk-v3": "^1.3.1",
"langchain": "^0.3.34",
"lucide-react": "^0.544.0",
"next-themes": "^0.4.6",
"ollama": "^0.6.0",
+ "otplib": "^12.0.1",
"playwright": "^1.55.1",
"react": "^19.1.0",
+ "react-day-picker": "^9.11.0",
"react-dom": "^19.1.0",
+ "recharts": "^2.15.4",
"sonner": "^2.0.7",
"tailwind-merge": "^3.3.1",
- "tailwindcss": "^4.1.13"
+ "tailwindcss": "^4.1.13",
+ "vaul": "^1.1.2",
+ "ws": "^8.18.3"
},
"devDependencies": {
"@tauri-apps/cli": "^2",
+ "@types/node": "^24.5.2",
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
+ "@types/ws": "^8.18.1",
"@vitejs/plugin-react": "^4.6.0",
+ "ts-node": "^10.9.2",
"tw-animate-css": "^1.4.0",
"typescript": "~5.8.3",
"vite": "^7.0.4"
diff --git a/fincept-terminal-desktop/src/App.tsx b/fincept-terminal-desktop/src/App.tsx
index c57026aff..dab0b3834 100644
--- a/fincept-terminal-desktop/src/App.tsx
+++ b/fincept-terminal-desktop/src/App.tsx
@@ -1,12 +1,19 @@
// File: src/App.tsx
-// Main application file that handles routing between authentication screens and dashboard
+// Main application file that handles routing between authentication screens, payment flow, and dashboard
import React, { useState, useEffect } from 'react';
import { useAuth } from './contexts/AuthContext';
+import { setPaymentWindowManager } from './services/paymentApi';
+
+// Import screens
import LoginScreen from './components/auth/LoginScreen';
import RegisterScreen from './components/auth/RegisterScreen';
import ForgotPasswordScreen from './components/auth/ForgotPasswordScreen';
import HelpScreen from './components/auth/HelpScreen';
+import PricingScreen from './components/auth/PricingScreen';
+import PaymentProcessingScreen from './components/payment/PaymentProcessingScreen';
+import PaymentSuccessScreen from './components/payment/PaymentSuccessScreen';
+import InAppPaymentWindow from './components/payment/InAppPaymentWindow';
import ContactUsScreen from './components/info/ContactUsScreen';
import TermsOfServiceScreen from './components/info/TermsOfServiceScreen';
import TrademarksScreen from './components/info/TrademarksScreen';
@@ -25,11 +32,90 @@ export type Screen =
| 'termsOfService'
| 'trademarks'
| 'privacyPolicy'
+ | 'pricing'
+ | 'paymentProcessing'
+ | 'paymentSuccess'
| 'dashboard';
+interface PaymentWindowState {
+ isOpen: boolean;
+ checkoutUrl: string;
+ planName: string;
+ planPrice: number;
+ onSuccess?: () => void;
+ onCancel?: () => void;
+ onError?: (error: string) => void;
+}
+
const App: React.FC = () => {
const { session, isLoading } = useAuth();
const [currentScreen, setCurrentScreen] = useState<Screen>('login');
+ const [hasChosenFreePlan, setHasChosenFreePlan] = useState(false);
+ const [cameFromLogin, setCameFromLogin] = useState(false);
+ const [paymentWindow, setPaymentWindow] = useState<PaymentWindowState>({
+ isOpen: false,
+ checkoutUrl: '',
+ planName: '',
+ planPrice: 0
+ });
+
+ // Set up payment window manager on app initialization
+ useEffect(() => {
+ const paymentManager = {
+ openPaymentWindow: (
+ url: string,
+ planName: string,
+ planPrice: number
+ ): Promise<boolean> => {
+ return new Promise((resolve) => {
+ console.log('PaymentManager: Opening payment window for:', planName);
+
+ setPaymentWindow({
+ isOpen: true,
+ checkoutUrl: url,
+ planName,
+ planPrice,
+ onSuccess: () => {
+ console.log('PaymentManager: Payment completed successfully');
+ setPaymentWindow(prev => ({ ...prev, isOpen: false }));
+ setCurrentScreen('paymentProcessing');
+ resolve(true);
+ },
+ onCancel: () => {
+ console.log('PaymentManager: Payment cancelled by user');
+ setPaymentWindow(prev => ({ ...prev, isOpen: false }));
+ resolve(false);
+ },
+ onError: (error: string) => {
+ console.error('PaymentManager: Payment error:', error);
+ setPaymentWindow(prev => ({ ...prev, isOpen: false }));
+ alert(`Payment failed: ${error}`);
+ resolve(false);
+ }
+ });
+ });
+ }
+ };
+
+ setPaymentWindowManager(paymentManager);
+ console.log('PaymentManager: Initialized in-app payment window manager');
+ }, []);
+
+ // Handle payment success URL parameters
+ useEffect(() => {
+ const urlParams = new URLSearchParams(window.location.search);
+ const sessionId = urlParams.get('session_id');
+ const paymentId = urlParams.get('payment_id');
+
+ // If we have payment parameters, go directly to success screen
+ if ((sessionId || paymentId) && session?.authenticated) {
+ console.log('Payment success URL detected, redirecting to payment success screen');
+ setCurrentScreen('paymentSuccess');
+ // Clear URL parameters to prevent issues on refresh
+ window.history.replaceState({}, document.title, window.location.pathname);
+ return;
+ }
+ }, [session?.authenticated]);
// Auto-navigation based on authentication state
useEffect(() => {
@@ -37,21 +123,57 @@ const App: React.FC = () => {
session: session?.authenticated,
isLoading,
currentScreen,
- userType: session?.user_type
+ userType: session?.user_type,
+ accountType: session?.user_info?.account_type,
+ hasSubscription: session?.subscription?.has_subscription,
+ cameFromLogin,
+ hasChosenFreePlan
});
if (!isLoading) {
if (session?.authenticated) {
- console.log('Session is authenticated, redirecting to dashboard');
- setCurrentScreen('dashboard');
+ console.log('Session is authenticated');
+
+ // Check if user is on free plan and needs to see pricing
+ const isFreePlan = session.user_info?.account_type === 'free';
+ const hasActiveSubscription = session.subscription?.has_subscription;
+
+ // Show pricing if:
+ // 1. User is registered with free account type AND
+ // 2. No active subscription AND
+ // 3. Either came from fresh login OR hasn't chosen free plan yet
+ if (session.user_type === 'registered' &&
+ isFreePlan &&
+ !hasActiveSubscription &&
+ currentScreen !== 'pricing' &&
+ currentScreen !== 'paymentProcessing' &&
+ currentScreen !== 'paymentSuccess' &&
+ (cameFromLogin || !hasChosenFreePlan)) {
+ console.log('Free user without subscription detected, showing pricing screen');
+ setCurrentScreen('pricing');
+ } else if (hasActiveSubscription ||
+ session.user_type === 'guest' ||
+ (hasChosenFreePlan && !cameFromLogin) ||
+ (isFreePlan && hasChosenFreePlan)) {
+ console.log('User has subscription, is guest, or chose free plan - redirecting to dashboard');
+ if (currentScreen !== 'paymentProcessing' && currentScreen !== 'paymentSuccess') {
+ setCurrentScreen('dashboard');
+ }
+ }
} else {
console.log('Session not authenticated, staying on auth screens');
- if (currentScreen === 'dashboard') {
+ if (currentScreen === 'dashboard' ||
+ currentScreen === 'pricing' ||
+ currentScreen === 'paymentProcessing' ||
+ currentScreen === 'paymentSuccess') {
setCurrentScreen('login');
}
+ // Reset flags when user logs out
+ setHasChosenFreePlan(false);
+ setCameFromLogin(false);
}
}
- }, [session, isLoading, currentScreen]);
+ }, [session, isLoading, currentScreen, cameFromLogin, hasChosenFreePlan]);
// Show loading screen while checking authentication
if (isLoading) {
@@ -66,30 +188,132 @@ const App: React.FC = () => {
);
}
- // If authenticated, show dashboard without header/footer
+ // If authenticated and should show dashboard
if (session?.authenticated && currentScreen === 'dashboard') {
- return <DashboardScreen />;
+ return (
+ <>
+ <DashboardScreen />
+ {/* In-App Payment Window Overlay */}
+ {paymentWindow.isOpen && (
+ <InAppPaymentWindow
+ checkoutUrl={paymentWindow.checkoutUrl}
+ planName={paymentWindow.planName}
+ planPrice={paymentWindow.planPrice}
+ onSuccess={paymentWindow.onSuccess || (() => {})}
+ onCancel={paymentWindow.onCancel || (() => {})}
+ onError={paymentWindow.onError || (() => {})}
+ />
+ )}
+ </>
+ );
+ }
+
+ // Payment processing and success screens (full screen, no header/footer)
+ if (currentScreen === 'paymentProcessing' || currentScreen === 'paymentSuccess') {
+ return (
+ <div className="min-h-screen bg-black relative overflow-hidden flex items-center justify-center" style={{ minHeight: '100vh', height: '100%' }}>
+ <BackgroundPattern />
+ <div className="relative z-10 flex items-center justify-center">
+ {renderPaymentScreen()}
+ </div>
+ {/* In-App Payment Window Overlay */}
+ {paymentWindow.isOpen && (
+ <InAppPaymentWindow
+ checkoutUrl={paymentWindow.checkoutUrl}
+ planName={paymentWindow.planName}
+ planPrice={paymentWindow.planPrice}
+ onSuccess={paymentWindow.onSuccess || (() => {})}
+ onCancel={paymentWindow.onCancel || (() => {})}
+ onError={paymentWindow.onError || (() => {})}
+ />
+ )}
+ </div>
+ );
+ }
+
+ // Payment screen renderer
+ function renderPaymentScreen() {
+ switch (currentScreen) {
+ case 'paymentProcessing':
+ return (
+ <PaymentProcessingScreen
+ onNavigate={setCurrentScreen}
+ onPaymentComplete={() => {
+ setHasChosenFreePlan(false); // Reset since they now have a paid plan
+ setCameFromLogin(false);
+ setCurrentScreen('dashboard');
+ }}
+ />
+ );
+ case 'paymentSuccess':
+ return (
+ <PaymentSuccessScreen
+ onNavigate={setCurrentScreen}
+ onComplete={() => {
+ setHasChosenFreePlan(false); // Reset since they now have a paid plan
+ setCameFromLogin(false);
+ setCurrentScreen('dashboard');
+ }}
+ />
+ );
+ default:
+ return null;
+ }
}
- // Authentication and info screens with header/footer
+ // Authentication, pricing, and info screens with header/footer
const renderCurrentScreen = () => {
switch (currentScreen) {
case 'login':
- return <LoginScreen onNavigate={setCurrentScreen} />;
+ return <LoginScreen onNavigate={(screen) => {
+ if (screen === 'dashboard') {
+ // User successfully logged in via login screen
+ setCameFromLogin(true);
+ }
+ setCurrentScreen(screen);
+ }} />;
+
case 'register':
return <RegisterScreen onNavigate={setCurrentScreen} />;
+
case 'forgotPassword':
return <ForgotPasswordScreen onNavigate={setCurrentScreen} />;
+
case 'help':
return <HelpScreen onNavigate={setCurrentScreen} />;
+
+ case 'pricing':
+ return (
+ <PricingScreen
+ onNavigate={(screen) => {
+ // Handle navigation from pricing screen
+ if (screen === 'paymentProcessing') {
+ setCurrentScreen('paymentProcessing');
+ } else {
+ setCurrentScreen(screen);
+ }
+ }}
+ onProceedToDashboard={() => {
+ setHasChosenFreePlan(true);
+ setCameFromLogin(false); // Reset after choice is made
+ setCurrentScreen('dashboard');
+ }}
+ userType="existing"
+ />
+ );
+
case 'contactUs':
return <ContactUsScreen onNavigate={setCurrentScreen} />;
+
case 'termsOfService':
return <TermsOfServiceScreen onNavigate={setCurrentScreen} />;
+
case 'trademarks':
return <TrademarksScreen onNavigate={setCurrentScreen} />;
+
case 'privacyPolicy':
return <PrivacyPolicyScreen onNavigate={setCurrentScreen} />;
+
default:
return <LoginScreen onNavigate={setCurrentScreen} />;
}
@@ -105,6 +329,18 @@ const App: React.FC = () => {
</div>
<Footer onNavigate={setCurrentScreen} />
+
+ {/* In-App Payment Window Overlay - Available on all screens */}
+ {paymentWindow.isOpen && (
+ <InAppPaymentWindow
+ checkoutUrl={paymentWindow.checkoutUrl}
+ planName={paymentWindow.planName}
+ planPrice={paymentWindow.planPrice}
+ onSuccess={paymentWindow.onSuccess || (() => {})}
+ onCancel={paymentWindow.onCancel || (() => {})}
+ onError={paymentWindow.onError || (() => {})}
+ />
+ )}
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
index 6aaafc642..ee7bea07d 100644
--- a/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/LoginScreen.tsx
@@ -1,47 +1,32 @@
// File: src/components/auth/LoginScreen.tsx
-// Login screen with username/password authentication and guest access
+// User login screen with email/password authentication and guest access
import React, { useState } from 'react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import { Mail, Lock, Eye, EyeOff } from "lucide-react";
import { Screen } from '../../App';
import { useAuth } from '@/contexts/AuthContext';
-import { Mail, Lock } from 'lucide-react';
-
interface LoginScreenProps {
onNavigate: (screen: Screen) => void;
}
const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
- const [formData, setFormData] = useState({
- email: "",
- password: ""
- });
+ const { login, setupGuestAccess } = useAuth();
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
+ const [showPassword, setShowPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [isGuestLoading, setIsGuestLoading] = useState(false);
const [error, setError] = useState("");
- const { login, setupGuestAccess } = useAuth();
-
- const handleChange = (field: string, value: string) => {
- setFormData(prev => ({ ...prev, [field]: value }));
- if (error) setError("");
- };
-
- const handleSubmit = async (e: React.FormEvent) => {
+ const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
- if (!formData.email || !formData.password) {
- setError("Please fill in all fields");
- return;
- }
-
- // Basic email validation
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
- if (!emailRegex.test(formData.email)) {
- setError("Please enter a valid email address");
+ if (!email || !password) {
+ setError("Please enter both email and password");
return;
}
@@ -49,14 +34,13 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
setError("");
try {
- console.log('Login attempt for:', formData.email);
+ console.log('Login attempt for:', email);
- const result = await login(formData.email, formData.password);
+ const result = await login(email, password);
if (result.success) {
- console.log('Login successful');
- // The useAuth hook will handle navigation/state updates
- // You can add any post-login logic here if needed
+ console.log('Login successful - App.tsx will handle routing based on account type');
+ // App.tsx useEffect will handle navigation based on account_type
} else {
console.log('Login failed:', result.error);
setError(result.error || 'Login failed. Please check your credentials.');
@@ -79,15 +63,15 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
const result = await setupGuestAccess();
if (result.success) {
- console.log('Guest access setup successful');
- // The useAuth hook will handle navigation/state updates
+ console.log('Guest access setup successful - App.tsx will handle routing');
+ // App.tsx useEffect will handle navigation to dashboard
} else {
console.log('Guest access setup failed:', result.error);
setError(result.error || 'Failed to setup guest access. Please try again.');
}
} catch (err) {
console.error('Guest access error:', err);
- setError("An unexpected error occurred. Please try again.");
+ setError("Failed to setup guest access. Please try again.");
} finally {
setIsGuestLoading(false);
}
@@ -96,13 +80,13 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
return (
<div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-sm mx-4 shadow-2xl">
<div className="mb-6">
- <h2 className="text-white text-2xl font-light mb-3">Login</h2>
+ <h2 className="text-white text-2xl font-light mb-3">Welcome to Fincept</h2>
<p className="text-zinc-400 text-xs leading-5">
- This is a secure Fincept authentication service that allows you access to Fincept services from wherever you are.
+ Sign in to access your financial terminal and analytics platform.
</p>
</div>
- <form onSubmit={handleSubmit} className="space-y-4">
+ <form onSubmit={handleLogin} className="space-y-4">
<div className="space-y-1">
<Label htmlFor="email" className="text-white text-xs">
Email Address
@@ -113,8 +97,11 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
id="email"
type="email"
placeholder="Enter your email"
- value={formData.email}
- onChange={(e) => handleChange("email", e.target.value)}
+ value={email}
+ onChange={(e) => {
+ setEmail(e.target.value);
+ if (error) setError("");
+ }}
className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
disabled={isLoading || isGuestLoading}
required
@@ -123,47 +110,50 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
</div>
<div className="space-y-1">
- <div className="flex justify-between items-center">
- <Label htmlFor="password" className="text-white text-xs">
- Password
- </Label>
- <button
- type="button"
- onClick={() => onNavigate('forgotPassword')}
- className="text-blue-400 hover:text-blue-300 text-xs transition-colors"
- disabled={isLoading || isGuestLoading}
- >
- Forgot Password?
- </button>
- </div>
+ <Label htmlFor="password" className="text-white text-xs">
+ Password
+ </Label>
<div className="relative">
<Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
<Input
id="password"
- type="password"
+ type={showPassword ? "text" : "password"}
placeholder="Enter your password"
- value={formData.password}
- onChange={(e) => handleChange("password", e.target.value)}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ value={password}
+ onChange={(e) => {
+ setPassword(e.target.value);
+ if (error) setError("");
+ }}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 pr-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
disabled={isLoading || isGuestLoading}
required
/>
+ <button
+ type="button"
+ onClick={() => setShowPassword(!showPassword)}
+ className="absolute right-2.5 top-1/2 transform -translate-y-1/2 text-zinc-400 hover:text-zinc-300"
+ disabled={isLoading || isGuestLoading}
+ >
+ {showPassword ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
+ </button>
</div>
</div>
- <div className="pt-1">
- <p className="text-zinc-500 text-xs">
- Your account credentials are required to access Fincept services.
- </p>
- </div>
-
{error && (
<div className="text-red-400 text-xs bg-red-900/20 border border-red-900/50 rounded p-2">
{error}
</div>
)}
- <div className="flex justify-end pt-2">
+ <div className="flex justify-between items-center text-xs pt-1">
+ <button
+ type="button"
+ onClick={() => onNavigate('forgotPassword')}
+ className="text-blue-400 hover:text-blue-300 transition-colors"
+ disabled={isLoading || isGuestLoading}
+ >
+ Forgot Password?
+ </button>
<Button
type="submit"
className="bg-zinc-700 hover:bg-zinc-600 text-white px-6 py-1.5 text-sm font-normal transition-colors disabled:opacity-50"
@@ -179,32 +169,26 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
</div>
</form>
- <div className="mt-5 pt-4 border-t border-zinc-700">
- <div className="text-center mb-3">
- <p className="text-zinc-400 text-xs mb-3">Want to explore first?</p>
- <Button
- onClick={handleGuestAccess}
- disabled={isLoading || isGuestLoading}
- className="bg-green-600/20 hover:bg-green-600/30 border border-green-600/50 text-green-400 px-4 py-1.5 text-xs font-normal transition-colors disabled:opacity-50 w-full"
- >
- {isGuestLoading ? (
- <div className="flex items-center justify-center">
- <div className="w-3 h-3 border border-green-400/30 border-t-green-400 rounded-full animate-spin mr-1.5"></div>
- Setting up Guest Access...
- </div>
- ) : (
- <div className="flex items-center justify-center">
- <svg className="w-3 h-3 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
- </svg>
- Continue as Guest
- </div>
- )}
- </Button>
- <p className="text-zinc-500 text-xs mt-1.5">
- 50 API requests • 24-hour access • No signup required
- </p>
- </div>
+ <div className="mt-5 pt-4 border-t border-zinc-700 space-y-3">
+ <Button
+ onClick={handleGuestAccess}
+ className="w-full bg-blue-600/20 hover:bg-blue-600/30 border border-blue-600/50 text-blue-400 py-2 text-sm font-normal transition-colors disabled:opacity-50"
+ disabled={isLoading || isGuestLoading}
+ >
+ {isGuestLoading ? (
+ <div className="flex items-center justify-center">
+ <div className="w-3 h-3 border border-blue-400/30 border-t-blue-400 rounded-full animate-spin mr-1.5"></div>
+ Setting up...
+ </div>
+ ) : (
+ <>
+ <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
+ </svg>
+ Continue as Guest
+ </>
+ )}
+ </Button>
<div className="text-center">
<p className="text-zinc-400 text-xs">
@@ -215,13 +199,17 @@ const LoginScreen: React.FC<LoginScreenProps> = ({ onNavigate }) => {
className="text-blue-400 hover:text-blue-300 transition-colors"
disabled={isLoading || isGuestLoading}
>
- Create Account
+ Sign Up
</button>
</p>
</div>
+
+ <div className="text-center text-zinc-500 text-xs">
+ <p>Guest Access: 50 API requests • 24-hour session</p>
+ </div>
</div>
</div>
);
};
-export default LoginScreen;
\ No newline at end of file
+export default LoginScreen
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
index 3d171807f..85e1a220c 100644
--- a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
@@ -1,411 +1,469 @@
// File: src/components/auth/PricingScreen.tsx
-// Pricing screen for plan selection after login/signup
+// Pricing screen for plan selection after login/signup with API integration
-import React, { useState } from 'react';
+import React, { useState, useEffect, useRef } from 'react';
import { Button } from "@/components/ui/button";
-import { ArrowLeft, Check, Star, Zap, Crown, Rocket, Shield } from "lucide-react";
+import { ArrowLeft, Check, Star, Zap, Crown, Rocket, Shield, Loader2, AlertCircle } from "lucide-react";
import { Screen } from '../../App';
+import { useAuth } from '@/contexts/AuthContext';
+import { PaymentUtils } from '@/services/paymentApi';
interface PricingScreenProps {
onNavigate: (screen: Screen) => void;
- onProceedToDashboard: (plan: PricingPlan) => void;
+ onProceedToDashboard: () => void;
userType?: 'new' | 'existing'; // new = after signup, existing = after login
}
-interface PricingPlan {
- id: string;
- name: string;
- price: number;
- period: 'month';
- icon: React.ReactNode;
- description: string;
- features: string[];
- limits: {
- apiRequests: string;
- dataStreams: string;
- portfolios: string;
- alerts: string;
- history: string;
- };
- popular?: boolean;
- recommended?: boolean;
-}
-
const PricingScreen: React.FC<PricingScreenProps> = ({
onNavigate,
onProceedToDashboard,
userType = 'new'
}) => {
- const [selectedPlan, setSelectedPlan] = useState<string>('free');
+ const { availablePlans, isLoadingPlans, fetchPlans, createPaymentSession, session } = useAuth();
+ const [selectedPlan, setSelectedPlan] = useState<string>('');
const [billingPeriod, setBillingPeriod] = useState<'monthly' | 'annually'>('monthly');
const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<string>('');
+ const [hasLoadedPlans, setHasLoadedPlans] = useState(false);
- const plans: PricingPlan[] = [
- {
- id: 'free',
- name: 'Free',
- price: 0,
- period: 'month',
- icon: <Shield className="w-5 h-5" />,
- description: 'Perfect for getting started with basic market data',
- features: [
- 'Basic market data access',
- 'Limited portfolio tracking',
- 'Standard charts and graphs',
- 'Email support',
- 'Basic alerts',
- ],
- limits: {
- apiRequests: '1,000/month',
- dataStreams: '5 concurrent',
- portfolios: '1 portfolio',
- alerts: '10 alerts',
- history: '1 year'
- }
- },
- {
- id: 'starter',
- name: 'Starter',
- price: 20,
- period: 'month',
- icon: <Star className="w-5 h-5" />,
- description: 'Ideal for individual investors and small portfolios',
- features: [
- 'Real-time market data',
- 'Advanced portfolio analytics',
- 'Custom watchlists',
- 'Priority email support',
- 'Advanced charting tools',
- 'Mobile app access',
- 'Basic API access'
- ],
- limits: {
- apiRequests: '10,000/month',
- dataStreams: '25 concurrent',
- portfolios: '5 portfolios',
- alerts: '50 alerts',
- history: '5 years'
+ // Prevent multiple simultaneous requests
+ const loadingRef = useRef(false);
+ const retryTimeoutRef = useRef<NodeJS.Timeout>();
+
+ // Load plans on component mount - with debouncing
+ useEffect(() => {
+ const loadPlans = async () => {
+ // Prevent multiple simultaneous requests
+ if (loadingRef.current || hasLoadedPlans || isLoadingPlans) {
+ console.log('Skipping plan load - already in progress or completed');
+ return;
}
- },
- {
- id: 'professional',
- name: 'Professional',
- price: 49,
- period: 'month',
- icon: <Zap className="w-5 h-5" />,
- description: 'Advanced tools for active traders and analysts',
- popular: true,
- features: [
- 'Premium real-time data',
- 'Advanced risk analytics',
- 'Multiple portfolio management',
- 'Phone & chat support',
- 'Professional charting suite',
- 'Options & derivatives data',
- 'Extended API access',
- 'Custom indicators',
- 'Backtesting tools'
- ],
- limits: {
- apiRequests: '50,000/month',
- dataStreams: '100 concurrent',
- portfolios: '25 portfolios',
- alerts: '250 alerts',
- history: '10 years'
+
+ if (availablePlans.length > 0) {
+ console.log('Plans already available, skipping load');
+ setHasLoadedPlans(true);
+ return;
}
- },
- {
- id: 'enterprise',
- name: 'Enterprise',
- price: 99,
- period: 'month',
- icon: <Crown className="w-5 h-5" />,
- description: 'Comprehensive solution for investment professionals',
- features: [
- 'Level 2 market data',
- 'Institutional-grade analytics',
- 'Unlimited portfolios',
- 'Dedicated support manager',
- 'Advanced trading tools',
- 'Alternative data sources',
- 'Full API access',
- 'Custom integrations',
- 'White-label options',
- 'Team collaboration tools'
- ],
- limits: {
- apiRequests: '200,000/month',
- dataStreams: '500 concurrent',
- portfolios: 'Unlimited',
- alerts: '1,000 alerts',
- history: '20 years'
+
+ loadingRef.current = true;
+ console.log('Loading subscription plans from API...');
+
+ try {
+ const result = await fetchPlans();
+ if (result.success) {
+ setHasLoadedPlans(true);
+ setError('');
+ } else {
+ setError(result.error || 'Failed to load subscription plans');
+
+ // Retry after 3 seconds if it failed
+ retryTimeoutRef.current = setTimeout(() => {
+ console.log('Retrying to load plans...');
+ loadingRef.current = false;
+ setHasLoadedPlans(false);
+ loadPlans();
+ }, 3000);
+ }
+ } catch (err) {
+ console.error('Error loading plans:', err);
+ setError('Failed to load subscription plans');
+ } finally {
+ loadingRef.current = false;
}
- },
- {
- id: 'institutional',
- name: 'Institutional',
- price: 199,
- period: 'month',
- icon: <Rocket className="w-5 h-5" />,
- description: 'Premium solution for large organizations and funds',
- recommended: true,
- features: [
- 'Complete market data coverage',
- 'Advanced risk management',
- 'Unlimited everything',
- '24/7 dedicated support',
- 'Custom development',
- 'On-premise deployment',
- 'Enterprise API',
- 'Advanced compliance tools',
- 'Multi-tenant architecture',
- 'Custom reporting',
- 'SLA guarantees'
- ],
- limits: {
- apiRequests: 'Unlimited',
- dataStreams: 'Unlimited',
- portfolios: 'Unlimited',
- alerts: 'Unlimited',
- history: 'Complete history'
+ };
+
+ // Small delay to ensure component is fully mounted
+ const timer = setTimeout(loadPlans, 100);
+
+ return () => {
+ clearTimeout(timer);
+ if (retryTimeoutRef.current) {
+ clearTimeout(retryTimeoutRef.current);
}
+ };
+ }, []); // Only run once on mount
+
+ // Separate effect to set default selection when plans are loaded
+ useEffect(() => {
+ if (availablePlans.length > 0 && !selectedPlan) {
+ setSelectedPlan('starter_20');
}
- ];
+ }, [availablePlans.length, selectedPlan]);
const getAnnualPrice = (monthlyPrice: number) => {
return monthlyPrice * 10; // 2 months free when billed annually
};
- const handleSelectPlan = async () => {
- if (!selectedPlan) return;
+ const getPlanIcon = (planId: string) => {
+ const iconMap: Record<string, React.ReactNode> = {
+ 'starter_20': <Star className="w-4 h-4" />,
+ 'professional_49': <Zap className="w-4 h-4" />,
+ 'enterprise_99': <Crown className="w-4 h-4" />,
+ 'unlimited_199': <Rocket className="w-4 h-4" />
+ };
+ return iconMap[planId] || <Shield className="w-4 h-4" />;
+ };
- setIsLoading(true);
+const handleSelectPlan = async () => {
+ if (!selectedPlan) {
+ setError('Please select a plan');
+ return;
+ }
- try {
- // TODO: Replace with actual API call to process plan selection
- setTimeout(() => {
- const plan = plans.find(p => p.id === selectedPlan);
- if (plan) {
- console.log('Plan selected:', plan);
- onProceedToDashboard(plan);
- }
- setIsLoading(false);
- }, 2000);
- } catch (err) {
- console.error('Plan selection error:', err);
- setIsLoading(false);
+ if (!session?.api_key) {
+ setError('Authentication required. Please log in again.');
+ return;
+ }
+
+ setIsLoading(true);
+ setError('');
+
+ try {
+ console.log('Creating payment session for plan:', selectedPlan);
+
+ const result = await createPaymentSession(selectedPlan);
+
+ if (result.success && result.data) {
+ console.log('Payment session created:', result.data);
+
+ // DEBUG: Log the exact structure
+ console.log('result.data structure:', JSON.stringify(result.data, null, 2));
+ console.log('checkout_url direct access:', result.data.checkout_url);
+ console.log('checkout_url via data.data:', result.data.data?.checkout_url);
+
+ // Try different data access patterns
+ const checkoutUrl = result.data.checkout_url || result.data.data?.checkout_url;
+
+ if (checkoutUrl) {
+ console.log('Found checkout URL:', checkoutUrl);
+
+
+ PaymentUtils.openPaymentUrl(checkoutUrl);
+ onNavigate('paymentProcessing' as Screen);
+ } else {
+ console.error('No checkout URL found in result data');
+ setError('No payment URL received. Please try again.');
+ }
+ } else {
+ console.error('Failed to create payment session:', result.error);
+ setError(result.error || 'Failed to create payment session. Please try again.');
+ }
+ } catch (err) {
+ console.error('Payment session error:', err);
+ setError('An unexpected error occurred. Please try again.');
+ } finally {
+ setIsLoading(false);
+ }
+};
+
+ const handleContinueWithFree = () => {
+ console.log('Continuing with free plan');
+ onProceedToDashboard();
+ };
+
+ const handleRetryLoadPlans = async () => {
+ setError('');
+ setHasLoadedPlans(false);
+ loadingRef.current = false;
+
+ console.log('Manual retry - loading plans...');
+ const result = await fetchPlans();
+ if (result.success) {
+ setHasLoadedPlans(true);
+ } else {
+ setError(result.error || 'Failed to load subscription plans');
}
};
- const getPlanCard = (plan: PricingPlan) => {
- const isSelected = selectedPlan === plan.id;
- const displayPrice = billingPeriod === 'annually' && plan.price > 0
- ? getAnnualPrice(plan.price)
- : plan.price;
+ const getPlanCard = (plan: any) => {
+ const isSelected = selectedPlan === plan.plan_id;
+ const displayPrice = billingPeriod === 'annually' && plan.price_usd > 0
+ ? getAnnualPrice(plan.price_usd)
+ : plan.price_usd;
const priceUnit = billingPeriod === 'annually' ? 'year' : 'month';
+ // Determine if plan is popular or recommended
+ const isPopular = plan.plan_id === 'starter_20';
+ const isRecommended = plan.plan_id === 'unlimited_199';
+
return (
<div
- key={plan.id}
- onClick={() => setSelectedPlan(plan.id)}
+ key={plan.plan_id}
+ onClick={() => setSelectedPlan(plan.plan_id)}
className={`
- relative cursor-pointer rounded-lg border-2 p-6 transition-all duration-200 hover:scale-105
+ relative cursor-pointer rounded-lg border-2 p-4 transition-all duration-200 hover:scale-[1.02]
${isSelected
? 'border-blue-500 bg-blue-600/10 shadow-lg shadow-blue-500/20'
: 'border-zinc-600 bg-zinc-800/50 hover:border-zinc-500'
}
`}
>
- {plan.popular && (
- <div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
- <span className="bg-blue-500 text-white text-xs font-medium px-3 py-1 rounded-full">
- Most Popular
+ {isPopular && (
+ <div className="absolute -top-2 left-1/2 transform -translate-x-1/2">
+ <span className="bg-blue-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">
+ Popular
</span>
</div>
)}
- {plan.recommended && (
- <div className="absolute -top-3 left-1/2 transform -translate-x-1/2">
- <span className="bg-green-500 text-white text-xs font-medium px-3 py-1 rounded-full">
- Recommended
+ {isRecommended && (
+ <div className="absolute -top-2 left-1/2 transform -translate-x-1/2">
+ <span className="bg-green-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">
+ Best Value
</span>
</div>
)}
- <div className="text-center mb-4">
+ <div className="text-center mb-3">
<div className={`
- inline-flex items-center justify-center w-12 h-12 rounded-full mb-3
+ inline-flex items-center justify-center w-8 h-8 rounded-full mb-2
${isSelected ? 'bg-blue-500 text-white' : 'bg-zinc-700 text-zinc-300'}
`}>
- {plan.icon}
+ {getPlanIcon(plan.plan_id)}
</div>
- <h3 className="text-white text-xl font-semibold mb-2">{plan.name}</h3>
+ <h3 className="text-white text-lg font-semibold mb-1">{plan.name}</h3>
<div className="mb-2">
- {plan.price === 0 ? (
- <span className="text-3xl font-bold text-green-400">Free</span>
- ) : (
- <div className="flex items-baseline justify-center">
- <span className="text-3xl font-bold text-white">${displayPrice}</span>
- <span className="text-zinc-400 text-sm ml-1">/{priceUnit}</span>
- </div>
- )}
+ <div className="flex items-baseline justify-center">
+ <span className="text-2xl font-bold text-white">
+ {PaymentUtils.formatCurrency(displayPrice)}
+ </span>
+ <span className="text-zinc-400 text-xs ml-1">/{priceUnit}</span>
+ </div>
- {billingPeriod === 'annually' && plan.price > 0 && (
- <div className="text-green-400 text-xs mt-1">
- Save ${plan.price * 2}/year
+ {billingPeriod === 'annually' && plan.price_usd > 0 && (
+ <div className="text-green-400 text-xs mt-0.5">
+ Save {PaymentUtils.formatCurrency(PaymentUtils.calculateAnnualSavings(plan.price_usd))}/year
</div>
)}
</div>
- <p className="text-zinc-400 text-xs leading-relaxed">{plan.description}</p>
+ <p className="text-zinc-400 text-xs">{plan.description}</p>
</div>
- <div className="space-y-3 mb-6">
- <div className="text-white text-sm font-medium">Usage Limits:</div>
- <div className="grid grid-cols-2 gap-2 text-xs">
- <div className="bg-zinc-800/50 p-2 rounded">
- <div className="text-zinc-400">API Requests</div>
- <div className="text-white font-medium">{plan.limits.apiRequests}</div>
+ <div className="space-y-2 mb-3">
+ <div className="grid grid-cols-2 gap-1 text-xs">
+ <div className="bg-zinc-800/30 p-1.5 rounded text-center">
+ <div className="text-zinc-400 text-xs">{plan.features.api_calls}</div>
+ <div className="text-white font-medium text-xs">API Calls</div>
+ </div>
+ <div className="bg-zinc-800/30 p-1.5 rounded text-center">
+ <div className="text-zinc-400 text-xs">{plan.features.databases}</div>
+ <div className="text-white font-medium text-xs">Databases</div>
</div>
- <div className="bg-zinc-800/50 p-2 rounded">
- <div className="text-zinc-400">Data Streams</div>
- <div className="text-white font-medium">{plan.limits.dataStreams}</div>
+ </div>
+ </div>
+
+ <div className="space-y-1">
+ <div className="text-xs text-zinc-300 space-y-0.5">
+ <div className="flex items-center">
+ <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
+ <span>{plan.features.support}</span>
</div>
- <div className="bg-zinc-800/50 p-2 rounded">
- <div className="text-zinc-400">Portfolios</div>
- <div className="text-white font-medium">{plan.limits.portfolios}</div>
+ {plan.priority_support && (
+ <div className="flex items-center">
+ <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
+ <span>Priority support</span>
+ </div>
+ )}
+ <div className="flex items-center">
+ <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
+ <span>Real-time data</span>
</div>
- <div className="bg-zinc-800/50 p-2 rounded">
- <div className="text-zinc-400">History</div>
- <div className="text-white font-medium">{plan.limits.history}</div>
+ <div className="flex items-center">
+ <Check className="w-3 h-3 text-green-400 mr-2 flex-shrink-0" />
+ <span>Custom dashboards</span>
</div>
</div>
</div>
+ </div>
+ );
+ };
- <div className="space-y-2">
- <div className="text-white text-sm font-medium">Features:</div>
- <ul className="space-y-1">
- {plan.features.map((feature, index) => (
- <li key={index} className="flex items-start text-xs text-zinc-300">
- <Check className="w-3 h-3 text-green-400 mr-2 mt-0.5 flex-shrink-0" />
- <span>{feature}</span>
- </li>
- ))}
- </ul>
+ if (isLoadingPlans && !hasLoadedPlans) {
+ return (
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-8 w-full max-w-md mx-auto shadow-2xl">
+ <div className="text-center">
+ <Loader2 className="w-8 h-8 animate-spin text-blue-500 mx-auto mb-4" />
+ <h2 className="text-white text-xl font-semibold mb-2">Loading Plans</h2>
+ <p className="text-zinc-400 text-sm">Fetching subscription options...</p>
</div>
</div>
);
- };
+ }
+
+ if (error && availablePlans.length === 0) {
+ return (
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-8 w-full max-w-md mx-auto shadow-2xl">
+ <div className="text-center">
+ <AlertCircle className="w-8 h-8 text-red-500 mx-auto mb-4" />
+ <h2 className="text-white text-xl font-semibold mb-2">Unable to Load Plans</h2>
+ <p className="text-zinc-400 text-sm mb-4">{error}</p>
+ <div className="space-y-2">
+ <Button
+ onClick={handleRetryLoadPlans}
+ className="w-full bg-blue-600 hover:bg-blue-500 text-white"
+ disabled={isLoadingPlans}
+ >
+ {isLoadingPlans ? (
+ <div className="flex items-center">
+ <Loader2 className="w-4 h-4 animate-spin mr-2" />
+ Loading...
+ </div>
+ ) : (
+ 'Retry'
+ )}
+ </Button>
+ {userType === 'existing' && (
+ <Button
+ onClick={handleContinueWithFree}
+ variant="outline"
+ className="w-full border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ >
+ Continue with Free Plan
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const selectedPlanData = availablePlans.find(p => p.plan_id === selectedPlan);
return (
- <div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-7xl mx-4 shadow-2xl max-h-[90vh] overflow-y-auto">
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-6 w-full max-w-5xl mx-auto shadow-2xl">
<div className="mb-6">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center">
- <button
- onClick={() => onNavigate('login')}
- className="text-zinc-400 hover:text-white transition-colors mr-3"
- >
- <ArrowLeft className="h-4 w-4" />
- </button>
- <h2 className="text-white text-2xl font-light">Choose Your Plan</h2>
+ {userType === 'existing' && (
+ <button
+ onClick={() => onProceedToDashboard()}
+ className="text-zinc-400 hover:text-white transition-colors mr-3"
+ disabled={isLoading}
+ >
+ <ArrowLeft className="h-4 w-4" />
+ </button>
+ )}
+ <h2 className="text-white text-xl font-semibold">
+ {userType === 'existing' ? 'Upgrade Your Plan' : 'Choose Your Plan'}
+ </h2>
</div>
- <div className="flex items-center bg-zinc-800 rounded-lg p-1">
+ <div className="flex items-center bg-zinc-800 rounded-lg p-0.5">
<button
onClick={() => setBillingPeriod('monthly')}
- className={`px-3 py-1 text-xs rounded transition-colors ${
+ className={`px-3 py-1.5 text-xs rounded-md transition-colors ${
billingPeriod === 'monthly'
? 'bg-zinc-600 text-white'
: 'text-zinc-400 hover:text-white'
}`}
+ disabled={isLoading}
>
Monthly
</button>
<button
onClick={() => setBillingPeriod('annually')}
- className={`px-3 py-1 text-xs rounded transition-colors ${
+ className={`px-3 py-1.5 text-xs rounded-md transition-colors ${
billingPeriod === 'annually'
? 'bg-zinc-600 text-white'
: 'text-zinc-400 hover:text-white'
}`}
+ disabled={isLoading}
>
- Annual <span className="text-green-400 text-xs">(Save 17%)</span>
+ Annual <span className="text-green-400">(-17%)</span>
</button>
</div>
</div>
- <p className="text-zinc-400 text-sm leading-5">
- {userType === 'new'
- ? 'Welcome to Fincept! Select a plan that fits your needs to get started with professional financial analytics.'
- : 'Upgrade your plan to unlock more features and higher limits for your financial analysis.'
+ <p className="text-zinc-400 text-sm">
+ {userType === 'existing'
+ ? 'Currently on Free plan. Upgrade for advanced features and higher limits.'
+ : 'Select a plan that fits your financial analysis needs. Start with 14-day free trial.'
}
</p>
</div>
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-6 mb-8">
- {plans.map(getPlanCard)}
- </div>
-
- <div className="border-t border-zinc-700 pt-6">
- <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
- <div className="text-center sm:text-left">
- <div className="text-white text-sm font-medium mb-1">
- Selected: {plans.find(p => p.id === selectedPlan)?.name || 'None'}
- </div>
- <div className="text-zinc-400 text-xs">
- {selectedPlan === 'free'
- ? 'Start exploring with our free plan - no credit card required'
- : 'You can change or cancel your plan anytime'
- }
- </div>
+ {availablePlans.length === 0 ? (
+ <div className="text-center py-8">
+ <p className="text-zinc-400">No subscription plans available at the moment.</p>
+ <Button
+ onClick={handleRetryLoadPlans}
+ className="mt-4 bg-blue-600 hover:bg-blue-500 text-white"
+ disabled={isLoadingPlans}
+ >
+ {isLoadingPlans ? 'Loading...' : 'Retry Loading Plans'}
+ </Button>
+ </div>
+ ) : (
+ <>
+ <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
+ {availablePlans.map(getPlanCard)}
</div>
- <div className="flex gap-3">
- {selectedPlan !== 'free' && (
- <Button
- onClick={() => setSelectedPlan('free')}
- className="bg-zinc-700 hover:bg-zinc-600 text-white px-6 py-2 text-sm font-normal transition-colors"
- disabled={isLoading}
- >
- Try Free Plan
- </Button>
- )}
+ {error && (
+ <div className="mb-4 p-3 bg-red-900/20 border border-red-900/50 rounded-lg">
+ <div className="flex items-center text-red-400 text-sm">
+ <AlertCircle className="w-4 h-4 mr-2 flex-shrink-0" />
+ {error}
+ </div>
+ </div>
+ )}
- <Button
- onClick={handleSelectPlan}
- disabled={!selectedPlan || isLoading}
- className={`px-8 py-2 text-sm font-normal transition-colors disabled:opacity-50 ${
- selectedPlan === 'free'
- ? 'bg-green-600 hover:bg-green-500 text-white'
- : 'bg-blue-600 hover:bg-blue-500 text-white'
- }`}
- >
- {isLoading ? (
- <div className="flex items-center">
- <div className="w-4 h-4 border border-white/30 border-t-white rounded-full animate-spin mr-2"></div>
- Processing...
+ <div className="border-t border-zinc-700/50 pt-4">
+ <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
+ <div className="text-center sm:text-left">
+ <div className="text-white text-sm font-medium">
+ Selected: {selectedPlanData?.name || 'None'}
</div>
- ) : (
- selectedPlan === 'free'
- ? 'Start with Free Plan'
- : `Continue with ${plans.find(p => p.id === selectedPlan)?.name || 'Selected'} Plan`
- )}
- </Button>
- </div>
- </div>
+ <div className="text-zinc-400 text-xs">
+ {selectedPlanData ? (
+ <>
+ {PaymentUtils.formatCurrency(
+ billingPeriod === 'annually'
+ ? getAnnualPrice(selectedPlanData.price_usd)
+ : selectedPlanData.price_usd
+ )}
+ /{billingPeriod === 'annually' ? 'year' : 'month'} • 14-day free trial • Cancel anytime
+ </>
+ ) : (
+ 'Select a plan to continue'
+ )}
+ </div>
+ </div>
+
+ <div className="flex gap-3">
+ {userType === 'existing' && (
+ <Button
+ onClick={handleContinueWithFree}
+ variant="outline"
+ className="border-zinc-600 text-zinc-300 hover:bg-zinc-800 px-4 py-2 text-sm transition-colors"
+ disabled={isLoading}
+ >
+ Stay Free
+ </Button>
+ )}
- <div className="mt-4 text-center">
- <div className="text-zinc-500 text-xs space-y-1">
- <p>• All plans include 14-day free trial (except Free plan)</p>
- <p>• No setup fees or long-term contracts</p>
- <p>• Enterprise support available for all paid plans</p>
- <p>• Cancel or upgrade anytime</p>
+ <Button
+ onClick={handleSelectPlan}
+ disabled={!selectedPlan || isLoading}
+ className="bg-blue-600 hover:bg-blue-500 text-white px-6 py-2 text-sm transition-colors disabled:opacity-50"
+ >
+ {isLoading ? (
+ <div className="flex items-center">
+ <Loader2 className="w-3 h-3 animate-spin mr-2" />
+ Processing...
+ </div>
+ ) : (
+ `Start Free Trial - ${selectedPlanData?.name || 'Plan'}`
+ )}
+ </Button>
+ </div>
+ </div>
</div>
- </div>
- </div>
+ </>
+ )}
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx b/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx
index 348d93306..0cce3234d 100644
--- a/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/RegisterScreen.tsx
@@ -1,36 +1,120 @@
// File: src/components/auth/RegisterScreen.tsx
-// User registration screen with complete form validation
+// User registration screen with country code selector and complete form validation
-import React, { useState } from 'react';
+import React, { useState, useEffect } from 'react';
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import { ArrowLeft, User, Mail, Phone, Building, Lock } from "lucide-react";
+import { ArrowLeft, User, Mail, Phone, Building, Lock, Key, ChevronDown } from "lucide-react";
import { Screen } from '../../App';
+import { useAuth } from '@/contexts/AuthContext';
interface RegisterScreenProps {
onNavigate: (screen: Screen) => void;
}
+type RegisterStep = 'form' | 'otp-verification';
+
+interface Country {
+ name: string;
+ code: string;
+ dialCode: string;
+ flag: string;
+}
+
const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {
+ const { signup, verifyOtp, session } = useAuth();
+ const [step, setStep] = useState<RegisterStep>('form');
const [formData, setFormData] = useState({
firstName: "",
lastName: "",
email: "",
phone: "",
+ countryCode: "+1", // Default to US
company: "",
password: "",
confirmPassword: ""
});
+ const [otp, setOtp] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
+ const [isVerificationComplete, setIsVerificationComplete] = useState(false);
+ const [countries, setCountries] = useState<Country[]>([]);
+ const [isCountryDropdownOpen, setIsCountryDropdownOpen] = useState(false);
+ const [countrySearchTerm, setCountrySearchTerm] = useState("");
+
+ // Fetch countries data from REST Countries API
+ useEffect(() => {
+ const fetchCountries = async () => {
+ try {
+ const response = await fetch('https://restcountries.com/v3.1/all?fields=name,cca2,idd,flag');
+ const data = await response.json();
+
+ const formattedCountries: Country[] = data
+ .filter((country: any) => country.idd?.root && country.idd?.suffixes?.length > 0)
+ .map((country: any) => ({
+ name: country.name.common,
+ code: country.cca2,
+ dialCode: country.idd.root + (country.idd.suffixes[0] || ''),
+ flag: country.flag
+ }))
+ .sort((a: Country, b: Country) => a.name.localeCompare(b.name));
+
+ setCountries(formattedCountries);
+ } catch (error) {
+ console.error('Failed to fetch countries:', error);
+ // Fallback to common countries if API fails
+ setCountries([
+ { name: "United States", code: "US", dialCode: "+1", flag: "🇺🇸" },
+ { name: "United Kingdom", code: "GB", dialCode: "+44", flag: "🇬🇧" },
+ { name: "Canada", code: "CA", dialCode: "+1", flag: "🇨🇦" },
+ { name: "India", code: "IN", dialCode: "+91", flag: "🇮🇳" },
+ { name: "Australia", code: "AU", dialCode: "+61", flag: "🇦🇺" },
+ { name: "Germany", code: "DE", dialCode: "+49", flag: "🇩🇪" },
+ { name: "France", code: "FR", dialCode: "+33", flag: "🇫🇷" },
+ { name: "Japan", code: "JP", dialCode: "+81", flag: "🇯🇵" },
+ ]);
+ }
+ };
+
+ fetchCountries();
+ }, []);
+
+ // Handle navigation after successful authentication
+ useEffect(() => {
+ if (session?.authenticated && session?.user_type === 'registered' && isVerificationComplete) {
+ console.log('Registration complete, navigating based on account type:', session.user_info?.account_type);
+
+ // Check if user has subscription
+ if (session.subscription?.has_subscription) {
+ console.log('User has subscription, redirecting to dashboard');
+ onNavigate('dashboard' as Screen);
+ } else {
+ console.log('User is free tier, showing pricing screen');
+ onNavigate('pricing' as Screen);
+ }
+ }
+ }, [session, isVerificationComplete, onNavigate]);
const handleChange = (field: string, value: string) => {
setFormData(prev => ({ ...prev, [field]: value }));
if (error) setError("");
};
- const handleSubmit = async (e: React.FormEvent) => {
+ const handleCountrySelect = (country: Country) => {
+ setFormData(prev => ({ ...prev, countryCode: country.dialCode }));
+ setIsCountryDropdownOpen(false);
+ setCountrySearchTerm("");
+ };
+
+ const filteredCountries = countries.filter(country =>
+ country.name.toLowerCase().includes(countrySearchTerm.toLowerCase()) ||
+ country.dialCode.includes(countrySearchTerm)
+ );
+
+ const selectedCountry = countries.find(country => country.dialCode === formData.countryCode);
+
+ const handleRegister = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.firstName || !formData.lastName || !formData.email || !formData.password || !formData.confirmPassword) {
@@ -43,202 +127,432 @@ const RegisterScreen: React.FC<RegisterScreenProps> = ({ onNavigate }) => {
return;
}
+ if (formData.password.length < 8) {
+ setError("Password must be at least 8 characters long");
+ return;
+ }
+
setIsLoading(true);
setError("");
try {
- // TODO: Replace with actual API call
- setTimeout(() => {
- console.log('Registration attempt:', formData);
- // Handle successful registration here
- setIsLoading(false);
- }, 2000);
+ console.log('Registration attempt for:', formData.email);
+
+ // Create username from first and last name, ensuring no spaces
+ const username = `${formData.firstName.trim()}${formData.lastName.trim()}`.toLowerCase();
+ console.log('Generated username:', username);
+
+ const result = await signup(username, formData.email, formData.password);
+
+ if (result.success) {
+ console.log('Registration successful, OTP sent to:', formData.email);
+ setStep('otp-verification');
+ } else {
+ console.log('Registration failed:', result.error);
+ setError(result.error || 'Registration failed. Please try again.');
+ }
} catch (err) {
- setError("An unexpected error occurred");
+ console.error('Registration error:', err);
+ setError("An unexpected error occurred. Please try again.");
+ } finally {
setIsLoading(false);
}
};
- return (
- <div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-sm mx-4 shadow-2xl">
- <div className="mb-6">
- <div className="flex items-center mb-3">
- <button
- onClick={() => onNavigate('login')}
- className="text-zinc-400 hover:text-white transition-colors mr-3"
- >
- <ArrowLeft className="h-4 w-4" />
- </button>
- <h2 className="text-white text-2xl font-light">Create Account</h2>
+ const handleVerifyOtp = async (e: React.FormEvent) => {
+ e.preventDefault();
+
+ if (!otp) {
+ setError("Please enter the verification code");
+ return;
+ }
+
+ if (isLoading || isVerificationComplete) {
+ console.log('Verification already in progress or complete, skipping');
+ return;
+ }
+
+ setIsLoading(true);
+ setError("");
+
+ try {
+ console.log('OTP verification for:', formData.email);
+
+ const result = await verifyOtp(formData.email, otp);
+
+ if (result.success) {
+ console.log('OTP verification successful');
+ setIsVerificationComplete(true);
+ // Navigation will be handled by useEffect
+ } else {
+ console.log('OTP verification failed:', result.error);
+ setError(result.error || 'Verification failed. Please check your code and try again.');
+ }
+ } catch (err) {
+ console.error('OTP verification error:', err);
+ setError("An unexpected error occurred. Please try again.");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleResendOtp = async () => {
+ setIsLoading(true);
+ setError("");
+
+ try {
+ const username = `${formData.firstName.trim()}${formData.lastName.trim()}`.toLowerCase();
+ const result = await signup(username, formData.email, formData.password);
+
+ if (result.success) {
+ setError(""); // Clear any previous errors
+ console.log('OTP resent successfully');
+ } else {
+ setError(result.error || 'Failed to resend code. Please try again.');
+ }
+ } catch (err) {
+ setError("Failed to resend code. Please try again.");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ // Prevent double submission
+ if (isVerificationComplete) {
+ return (
+ <div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-sm mx-4 shadow-2xl">
+ <div className="text-center">
+ <div className="w-8 h-8 border border-white/30 border-t-white rounded-full animate-spin mx-auto mb-4"></div>
+ <h2 className="text-white text-xl font-semibold mb-2">Verification Complete</h2>
+ <p className="text-zinc-400 text-sm">Setting up your account...</p>
</div>
- <p className="text-zinc-400 text-xs leading-5">
- Join Fincept to access professional financial terminal and analytics platform.
- </p>
</div>
+ );
+ }
+
+ // Step 1: Registration Form
+ if (step === 'form') {
+ return (
+ <div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-sm mx-4 shadow-2xl">
+ <div className="mb-6">
+ <div className="flex items-center mb-3">
+ <button
+ onClick={() => onNavigate('login')}
+ className="text-zinc-400 hover:text-white transition-colors mr-3"
+ >
+ <ArrowLeft className="h-4 w-4" />
+ </button>
+ <h2 className="text-white text-2xl font-light">Create Account</h2>
+ </div>
+ <p className="text-zinc-400 text-xs leading-5">
+ Join Fincept to access professional financial terminal and analytics platform.
+ </p>
+ </div>
+
+ <form onSubmit={handleRegister} className="space-y-4">
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1">
+ <Label htmlFor="firstName" className="text-white text-xs">
+ First Name *
+ </Label>
+ <div className="relative">
+ <User className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
+ <Input
+ id="firstName"
+ type="text"
+ placeholder="First name"
+ value={formData.firstName}
+ onChange={(e) => handleChange("firstName", e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ disabled={isLoading}
+ required
+ />
+ </div>
+ </div>
+
+ <div className="space-y-1">
+ <Label htmlFor="lastName" className="text-white text-xs">
+ Last Name *
+ </Label>
+ <Input
+ id="lastName"
+ type="text"
+ placeholder="Last name"
+ value={formData.lastName}
+ onChange={(e) => handleChange("lastName", e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ disabled={isLoading}
+ required
+ />
+ </div>
+ </div>
- <form onSubmit={handleSubmit} className="space-y-4">
- <div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
- <Label htmlFor="firstName" className="text-white text-xs">
- First Name *
+ <Label htmlFor="email" className="text-white text-xs">
+ Email Address *
</Label>
<div className="relative">
- <User className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
+ <Mail className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
<Input
- id="firstName"
- type="text"
- placeholder="First name"
- value={formData.firstName}
- onChange={(e) => handleChange("firstName", e.target.value)}
+ id="email"
+ type="email"
+ placeholder="Enter your email"
+ value={formData.email}
+ onChange={(e) => handleChange("email", e.target.value)}
className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
disabled={isLoading}
+ required
/>
</div>
</div>
<div className="space-y-1">
- <Label htmlFor="lastName" className="text-white text-xs">
- Last Name *
+ <Label htmlFor="phone" className="text-white text-xs">
+ Phone Number
</Label>
- <Input
- id="lastName"
- type="text"
- placeholder="Last name"
- value={formData.lastName}
- onChange={(e) => handleChange("lastName", e.target.value)}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
- disabled={isLoading}
- />
+ <div className="flex gap-2">
+ {/* Country Code Dropdown */}
+ <div className="relative">
+ <button
+ type="button"
+ onClick={() => setIsCountryDropdownOpen(!isCountryDropdownOpen)}
+ className="bg-zinc-800 border border-zinc-600 text-white h-9 px-2 text-sm rounded flex items-center gap-1 hover:bg-zinc-700 focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500 min-w-[70px]"
+ disabled={isLoading}
+ >
+ <span className="text-base">{selectedCountry?.flag || "🌍"}</span>
+ <span className="text-xs">{formData.countryCode}</span>
+ <ChevronDown className="h-3 w-3" />
+ </button>
+
+ {isCountryDropdownOpen && (
+ <div className="absolute top-full left-0 mt-1 w-80 bg-zinc-800 border border-zinc-600 rounded-lg shadow-lg z-50 max-h-60 overflow-hidden">
+ <div className="p-2">
+ <Input
+ type="text"
+ placeholder="Search countries..."
+ value={countrySearchTerm}
+ onChange={(e) => setCountrySearchTerm(e.target.value)}
+ className="bg-zinc-700 border-zinc-600 text-white placeholder-zinc-500 h-8 text-sm"
+ />
+ </div>
+ <div className="overflow-y-auto max-h-48">
+ {filteredCountries.slice(0, 50).map((country) => (
+ <button
+ key={country.code}
+ type="button"
+ onClick={() => handleCountrySelect(country)}
+ className="w-full px-3 py-2 text-left hover:bg-zinc-700 flex items-center gap-2 text-sm text-white"
+ >
+ <span className="text-base">{country.flag}</span>
+ <span className="flex-1">{country.name}</span>
+ <span className="text-zinc-400">{country.dialCode}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Phone Number Input */}
+ <div className="flex-1 relative">
+ <Phone className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
+ <Input
+ id="phone"
+ type="tel"
+ placeholder="Phone number (optional)"
+ value={formData.phone}
+ onChange={(e) => handleChange("phone", e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ disabled={isLoading}
+ />
+ </div>
+ </div>
</div>
- </div>
- <div className="space-y-1">
- <Label htmlFor="email" className="text-white text-xs">
- Email Address *
- </Label>
- <div className="relative">
- <Mail className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
- <Input
- id="email"
- type="email"
- placeholder="Enter your email"
- value={formData.email}
- onChange={(e) => handleChange("email", e.target.value)}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
- disabled={isLoading}
- />
+ <div className="space-y-1">
+ <Label htmlFor="company" className="text-white text-xs">
+ Company
+ </Label>
+ <div className="relative">
+ <Building className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
+ <Input
+ id="company"
+ type="text"
+ placeholder="Company name (optional)"
+ value={formData.company}
+ onChange={(e) => handleChange("company", e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ disabled={isLoading}
+ />
+ </div>
</div>
- </div>
- <div className="space-y-1">
- <Label htmlFor="phone" className="text-white text-xs">
- Phone Number
- </Label>
- <div className="relative">
- <Phone className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
- <Input
- id="phone"
- type="tel"
- placeholder="Phone number (optional)"
- value={formData.phone}
- onChange={(e) => handleChange("phone", e.target.value)}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
- disabled={isLoading}
- />
+ <div className="space-y-1">
+ <Label htmlFor="password" className="text-white text-xs">
+ Password *
+ </Label>
+ <div className="relative">
+ <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
+ <Input
+ id="password"
+ type="password"
+ placeholder="Create password"
+ value={formData.password}
+ onChange={(e) => handleChange("password", e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ disabled={isLoading}
+ required
+ minLength={8}
+ />
+ </div>
</div>
- </div>
- <div className="space-y-1">
- <Label htmlFor="company" className="text-white text-xs">
- Company
- </Label>
- <div className="relative">
- <Building className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
- <Input
- id="company"
- type="text"
- placeholder="Company name (optional)"
- value={formData.company}
- onChange={(e) => handleChange("company", e.target.value)}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
- disabled={isLoading}
- />
+ <div className="space-y-1">
+ <Label htmlFor="confirmPassword" className="text-white text-xs">
+ Confirm Password *
+ </Label>
+ <div className="relative">
+ <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
+ <Input
+ id="confirmPassword"
+ type="password"
+ placeholder="Confirm password"
+ value={formData.confirmPassword}
+ onChange={(e) => handleChange("confirmPassword", e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ disabled={isLoading}
+ required
+ />
+ </div>
</div>
- </div>
- <div className="space-y-1">
- <Label htmlFor="password" className="text-white text-xs">
- Password *
- </Label>
- <div className="relative">
- <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
- <Input
- id="password"
- type="password"
- placeholder="Create password"
- value={formData.password}
- onChange={(e) => handleChange("password", e.target.value)}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ {error && (
+ <div className="text-red-400 text-xs bg-red-900/20 border border-red-900/50 rounded p-2">
+ {error}
+ </div>
+ )}
+
+ <div className="flex justify-end pt-2">
+ <Button
+ type="submit"
+ className="bg-zinc-700 hover:bg-zinc-600 text-white px-6 py-1.5 text-sm font-normal transition-colors disabled:opacity-50"
disabled={isLoading}
- />
+ >
+ {isLoading ? (
+ <div className="flex items-center">
+ <div className="w-3 h-3 border border-white/30 border-t-white rounded-full animate-spin mr-1.5"></div>
+ Creating...
+ </div>
+ ) : "Create Account"}
+ </Button>
</div>
+ </form>
+
+ <div className="mt-5 pt-4 border-t border-zinc-700 text-center">
+ <p className="text-zinc-400 text-xs">
+ Already have an account?{" "}
+ <button
+ type="button"
+ onClick={() => onNavigate('login')}
+ className="text-blue-400 hover:text-blue-300 transition-colors"
+ disabled={isLoading}
+ >
+ Sign In
+ </button>
+ </p>
</div>
- <div className="space-y-1">
- <Label htmlFor="confirmPassword" className="text-white text-xs">
- Confirm Password *
- </Label>
- <div className="relative">
- <Lock className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
- <Input
- id="confirmPassword"
- type="password"
- placeholder="Confirm password"
- value={formData.confirmPassword}
- onChange={(e) => handleChange("confirmPassword", e.target.value)}
- className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ {/* Close dropdown when clicking outside */}
+ {isCountryDropdownOpen && (
+ <div
+ className="fixed inset-0 z-40"
+ onClick={() => setIsCountryDropdownOpen(false)}
+ />
+ )}
+ </div>
+ );
+ }
+
+ // Step 2: OTP Verification (unchanged)
+ if (step === 'otp-verification') {
+ return (
+ <div className="bg-zinc-900/90 backdrop-blur-sm border border-zinc-700 rounded-lg p-6 w-full max-w-sm mx-4 shadow-2xl">
+ <div className="mb-6">
+ <div className="flex items-center mb-3">
+ <button
+ onClick={() => setStep('form')}
+ className="text-zinc-400 hover:text-white transition-colors mr-3"
disabled={isLoading}
- />
+ >
+ <ArrowLeft className="h-4 w-4" />
+ </button>
+ <h2 className="text-white text-2xl font-light">Verify Email</h2>
</div>
+ <p className="text-zinc-400 text-xs leading-5">
+ We've sent a verification code to <span className="text-white">{formData.email}</span>.
+ Please enter the code below to complete your registration.
+ </p>
</div>
- {error && (
- <div className="text-red-400 text-xs bg-red-900/20 border border-red-900/50 rounded p-2">
- {error}
+ <form onSubmit={handleVerifyOtp} className="space-y-4">
+ <div className="space-y-1">
+ <Label htmlFor="otp" className="text-white text-xs">
+ Verification Code
+ </Label>
+ <div className="relative">
+ <Key className="absolute left-2.5 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-zinc-400" />
+ <Input
+ id="otp"
+ type="text"
+ placeholder="Enter verification code"
+ value={otp}
+ onChange={(e) => {
+ setOtp(e.target.value);
+ if (error) setError("");
+ }}
+ className="bg-zinc-800 border-zinc-600 text-white placeholder-zinc-500 pl-9 py-2 h-9 text-sm focus:border-zinc-500 focus:ring-1 focus:ring-zinc-500"
+ disabled={isLoading}
+ required
+ />
+ </div>
</div>
- )}
- <div className="flex justify-end pt-2">
- <Button
- type="submit"
- className="bg-zinc-700 hover:bg-zinc-600 text-white px-6 py-1.5 text-sm font-normal transition-colors disabled:opacity-50"
- disabled={isLoading}
- >
- {isLoading ? (
- <div className="flex items-center">
- <div className="w-3 h-3 border border-white/30 border-t-white rounded-full animate-spin mr-1.5"></div>
- Creating...
- </div>
- ) : "Create Account"}
- </Button>
- </div>
- </form>
+ {error && (
+ <div className="text-red-400 text-xs bg-red-900/20 border border-red-900/50 rounded p-2">
+ {error}
+ </div>
+ )}
+
+ <div className="flex justify-end pt-2">
+ <Button
+ type="submit"
+ className="bg-zinc-700 hover:bg-zinc-600 text-white px-6 py-1.5 text-sm font-normal transition-colors disabled:opacity-50"
+ disabled={isLoading || isVerificationComplete}
+ >
+ {isLoading ? (
+ <div className="flex items-center">
+ <div className="w-3 h-3 border border-white/30 border-t-white rounded-full animate-spin mr-1.5"></div>
+ Verifying...
+ </div>
+ ) : "Verify & Complete"}
+ </Button>
+ </div>
+ </form>
- <div className="mt-5 pt-4 border-t border-zinc-700 text-center">
- <p className="text-zinc-400 text-xs">
- Already have an account?{" "}
+ <div className="mt-5 pt-4 border-t border-zinc-700 text-center">
<button
- type="button"
- onClick={() => onNavigate('login')}
- className="text-blue-400 hover:text-blue-300 transition-colors"
+ onClick={handleResendOtp}
+ className="text-blue-400 hover:text-blue-300 text-xs transition-colors"
disabled={isLoading}
>
- Sign In
+ {isLoading ? "Sending..." : "Didn't receive the code? Resend"}
</button>
- </p>
+ </div>
</div>
- </div>
- );
+ );
+ }
+
+ return null;
};
export default RegisterScreen;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 77c98173b..ca9bb594d 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -1,366 +1,458 @@
-import { useState, useEffect } from 'react';
-import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
-import { Button } from '@/components/ui/button';
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow
-} from '@/components/ui/table';
+import React, { useState, useRef, useEffect } from 'react';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { Maximize, Minimize, Download, Settings, RefreshCw, User, Database, Eye, HelpCircle } from 'lucide-react';
+import ForumTab from '@/components/tabs/ForumTab';
+import DashboardTab from '@/components/tabs/DashboardTab';
+import MarketsTab from '@/components/tabs/MarketsTab';
+import NewsTab from '@/components/tabs/NewsTab';
+import AdvancedTab from '@/components/tabs/AdvancedTab';
+import WatchlistTab from '@/components/tabs/WatchlistTab';
+import GeopoliticsTab from '@/components/tabs/GeopoliticsTab';
-const DashboardScreen = () => {
- const [currentTime, setCurrentTime] = useState(new Date());
+// Dropdown Menu Component
+const DropdownMenu = ({ label, items, onItemClick }) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const menuRef = useRef(null);
useEffect(() => {
- const timer = setInterval(() => {
- setCurrentTime(new Date());
- }, 1000);
- return () => clearInterval(timer);
+ const handleClickOutside = (event) => {
+ if (menuRef.current && !menuRef.current.contains(event.target)) {
+ setIsOpen(false);
+ }
+ };
+
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
- // Custom Bloomberg Terminal Styling
- const terminalStyles = `
- .terminal-bg {
- background: #000000 !important;
- border: 1px solid #FF6600 !important;
- border-radius: 0 !important;
- }
- .terminal-header {
- background: #FF6600 !important;
- color: #000000 !important;
- border-radius: 0 !important;
- font-family: 'Courier New', monospace !important;
- font-weight: bold !important;
- padding: 2px 4px !important;
- margin: 0 !important;
- }
- .terminal-text {
- font-family: 'Courier New', monospace !important;
- font-size: 11px !important;
- line-height: 1.2 !important;
- color: #FFFFFF !important;
- }
- .terminal-orange { color: #FF6600 !important; }
- .terminal-green { color: #00FF00 !important; }
- .terminal-red { color: #FF0000 !important; }
- .terminal-yellow { color: #FFFF00 !important; }
- .terminal-cyan { color: #00FFFF !important; }
- .terminal-gray { color: #808080 !important; }
- .terminal-table {
- border-collapse: collapse !important;
- width: 100% !important;
- font-family: 'Courier New', monospace !important;
- font-size: 10px !important;
- }
- .terminal-table th {
- background: #333333 !important;
- color: #FFFF00 !important;
- border: 1px solid #808080 !important;
- padding: 2px 4px !important;
- text-align: left !important;
- }
- .terminal-table td {
- border: 1px solid #333333 !important;
- padding: 1px 4px !important;
- color: #FFFFFF !important;
- }
- .terminal-button {
- background: #000000 !important;
- border: 1px solid #FFFF00 !important;
- color: #FFFF00 !important;
- border-radius: 0 !important;
- font-family: 'Courier New', monospace !important;
- font-size: 9px !important;
- padding: 1px 6px !important;
- margin: 1px !important;
- height: auto !important;
- }
- .terminal-button:hover {
- background: #FFFF00 !important;
- color: #000000 !important;
- }
- .india-border {
- border: 2px solid #00FF00 !important;
- background: #000000 !important;
- }
- .india-header {
- background: #00FF00 !important;
- color: #000000 !important;
- text-align: center !important;
+ return (
+ <div ref={menuRef} style={{ position: 'relative', display: 'inline-block' }}>
+ <span
+ style={{ cursor: 'pointer', padding: '2px 4px', borderRadius: '2px', backgroundColor: isOpen ? '#404040' : 'transparent' }}
+ onClick={() => setIsOpen(!isOpen)}
+ >
+ {label}
+ </span>
+ {isOpen && (
+ <div style={{
+ position: 'absolute',
+ top: '100%',
+ left: 0,
+ backgroundColor: '#2d2d2d',
+ border: '1px solid #404040',
+ borderRadius: '2px',
+ minWidth: '150px',
+ zIndex: 1000,
+ boxShadow: '0 2px 8px rgba(0,0,0,0.5)'
+ }}>
+ {items.map((item, index) => (
+ <div
+ key={index}
+ style={{
+ padding: '6px 12px',
+ cursor: item.disabled ? 'not-allowed' : 'pointer',
+ color: item.disabled ? '#666' : '#a3a3a3',
+ fontSize: '11px',
+ borderBottom: item.separator ? '1px solid #404040' : 'none'
+ }}
+ onMouseEnter={(e) => {
+ if (!item.disabled) {
+ e.target.style.backgroundColor = '#404040';
+ e.target.style.color = '#fff';
+ }
+ }}
+ onMouseLeave={(e) => {
+ e.target.style.backgroundColor = 'transparent';
+ e.target.style.color = item.disabled ? '#666' : '#a3a3a3';
+ }}
+ onClick={() => {
+ if (!item.disabled && onItemClick) {
+ onItemClick(item);
+ setIsOpen(false);
+ }
+ }}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ {item.icon}
+ <span>{item.label}</span>
+ {item.shortcut && (
+ <span style={{ marginLeft: 'auto', fontSize: '10px', color: '#666' }}>
+ {item.shortcut}
+ </span>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default function FinxeptTerminal() {
+ const [activeTab, setActiveTab] = useState("dashboard");
+ const [isFullscreen, setIsFullscreen] = useState(false);
+ const [statusMessage, setStatusMessage] = useState("");
+
+ React.useEffect(() => {
+ document.body.style.margin = '0';
+ document.body.style.padding = '0';
+ document.body.style.backgroundColor = '#000000';
+ document.body.style.overflow = 'hidden';
+ document.body.style.overscrollBehavior = 'none';
+ document.documentElement.style.backgroundColor = '#000000';
+ document.documentElement.style.overflow = 'hidden';
+ document.documentElement.style.overscrollBehavior = 'none';
+
+ return () => {
+ document.body.style.overflow = 'auto';
+ document.body.style.overscrollBehavior = 'auto';
+ document.documentElement.style.overflow = 'auto';
+ document.documentElement.style.overscrollBehavior = 'auto';
+ };
+ }, []);
+
+ const toggleFullscreen = () => {
+ if (!document.fullscreenElement) {
+ document.documentElement.requestFullscreen().then(() => {
+ setIsFullscreen(true);
+ setStatusMessage("Entered fullscreen mode");
+ }).catch(err => {
+ setStatusMessage("Failed to enter fullscreen mode");
+ });
+ } else {
+ document.exitFullscreen().then(() => {
+ setIsFullscreen(false);
+ setStatusMessage("Exited fullscreen mode");
+ });
}
- `;
+
+ // Clear status message after 3 seconds
+ setTimeout(() => setStatusMessage(""), 3000);
+ };
- const countries = {
- "India": { gdp_trillion: 3.9, military_budget_billion: 83.6, political_stability: 6.8, current_risk: "Medium", market_influence: 7.8 },
- "United States": { gdp_trillion: 27.4, military_budget_billion: 842, political_stability: 7.0, current_risk: "Low", market_influence: 9.5 },
- "China": { gdp_trillion: 18.2, military_budget_billion: 296, political_stability: 6.5, current_risk: "Medium", market_influence: 8.9 },
- "Russia": { gdp_trillion: 2.0, military_budget_billion: 109, political_stability: 4.0, current_risk: "High", market_influence: 6.2 }
+ const handleMenuAction = (item) => {
+ setStatusMessage(`${item.label} clicked`);
+
+ // Handle specific actions
+ switch(item.action) {
+ case 'fullscreen':
+ toggleFullscreen();
+ break;
+ case 'refresh':
+ window.location.reload();
+ break;
+ case 'export':
+ setStatusMessage("Export functionality not implemented");
+ break;
+ default:
+ setTimeout(() => setStatusMessage(""), 3000);
+ }
};
- const intelligenceFeeds = [
- { time: "16:15", priority: "HIGH", source: "HUMINT", classification: "SECRET", event: "India-China border talks scheduled; infrastructure buildout accelerating" },
- { time: "16:02", priority: "CRITICAL", source: "ECONINT", classification: "TOP SECRET", event: "Significant FDI inflows to India's semiconductor sector detected" },
- { time: "15:48", priority: "MEDIUM", source: "OSINT", classification: "CONFIDENTIAL", event: "India-Middle East-Europe Corridor gaining momentum among traders" }
+ // Menu configurations
+ const fileMenuItems = [
+ { label: 'New Workspace', shortcut: 'Ctrl+N', icon: null },
+ { label: 'Open Workspace', shortcut: 'Ctrl+O', icon: null },
+ { label: 'Save Workspace', shortcut: 'Ctrl+S', icon: null },
+ { label: 'Export Data', shortcut: 'Ctrl+E', icon: <Download size={12} />, action: 'export', separator: true },
+ { label: 'Import Settings', icon: null },
+ { label: 'Exit', shortcut: 'Alt+F4', icon: null, separator: true }
];
- const marketData = [
- { asset: "India Nifty 50", impact: +0.95, reason: "FDI Strong" },
- { asset: "S&P 500", impact: -1.8, reason: "Geopolitical Risk" },
- { asset: "Energy Sector", impact: +3.8, reason: "Supply Risk" },
- { asset: "Tech Stocks", impact: -2.9, reason: "US-China Tension" },
- { asset: "Gold", impact: +2.1, reason: "Safe Haven" }
+ const tabsMenuItems = [
+ { label: 'New Tab', shortcut: 'Ctrl+T', icon: null },
+ { label: 'Close Tab', shortcut: 'Ctrl+W', icon: null },
+ { label: 'Close Other Tabs', icon: null },
+ { label: 'Duplicate Tab', icon: null, separator: true },
+ { label: 'Tab Settings', icon: <Settings size={12} /> }
];
- return (
- <>
- <style>{terminalStyles}</style>
- <div className="min-h-screen bg-black text-white p-2 terminal-text">
+ const sessionMenuItems = [
+ { label: 'Login', icon: <User size={12} /> },
+ { label: 'Switch User', icon: null },
+ { label: 'Session Info', icon: null, separator: true },
+ { label: 'Extend Session', icon: null },
+ { label: 'Logout', icon: null }
+ ];
- {/* Bloomberg Header */}
- <Card className="terminal-bg mb-2">
- <CardHeader className="terminal-header p-2">
- <div className="text-sm font-bold">
- ████████ BLOOMBERG TERMINAL ████████ GEOPOLITICAL INTELLIGENCE SYSTEM ████████
- </div>
- </CardHeader>
- <CardContent className="p-2">
- <div className="terminal-text text-xs">
- <span className="terminal-orange">GLOBAL RISK: </span>
- <span className="terminal-red">7.2/10 </span>
- <span className="terminal-gray">| </span>
- <span className="terminal-orange">CONFLICTS: </span>
- <span className="terminal-red">15 </span>
- <span className="terminal-gray">| </span>
- <span className="terminal-orange">SANCTIONS: </span>
- <span className="terminal-yellow">3124 </span>
- <span className="terminal-gray">| </span>
- <span className="terminal-white">{currentTime.toLocaleString()}</span>
- </div>
- <div className="terminal-text text-xs mt-1">
- <span className="terminal-gray">INDIA NIFTY: </span>
- <span className="terminal-green">24,850 </span>
- <span className="terminal-gray">| INR/USD: </span>
- <span className="terminal-cyan">83.12 </span>
- <span className="terminal-gray">| OIL: </span>
- <span className="terminal-green">$82.30 </span>
- <span className="terminal-gray">| ALERTS: </span>
- <span className="terminal-red">52 ACTIVE</span>
- </div>
- </CardContent>
- </Card>
+ const apiMenuItems = [
+ { label: 'API Status', icon: null },
+ { label: 'Rate Limits', icon: null },
+ { label: 'API Keys', icon: null, separator: true },
+ { label: 'Documentation', icon: null },
+ { label: 'Test Connection', icon: <RefreshCw size={12} />, action: 'refresh' }
+ ];
- {/* Function Keys */}
- <div className="mb-2 flex gap-1 flex-wrap">
- {["F1:INDIA", "F2:CHINA", "F3:PAKISTAN", "F4:USA", "F5:RUSSIA", "F6:LAC", "F7:QUAD", "F8:BRICS"].map(key => (
- <Button key={key} className="terminal-button">
- {key}
- </Button>
- ))}
- </div>
+ const databaseMenuItems = [
+ { label: 'Connect Database', icon: <Database size={12} /> },
+ { label: 'Query Builder', icon: null },
+ { label: 'Schema Browser', icon: null, separator: true },
+ { label: 'Backup Data', icon: null },
+ { label: 'Import Data', icon: null }
+ ];
- {/* Main Dashboard Grid */}
- <div className="grid grid-cols-3 gap-2 mb-4">
+ const viewMenuItems = [
+ { label: 'Fullscreen', shortcut: 'F11', icon: isFullscreen ? <Minimize size={12} /> : <Maximize size={12} />, action: 'fullscreen' },
+ { label: 'Zoom In', shortcut: 'Ctrl++', icon: null },
+ { label: 'Zoom Out', shortcut: 'Ctrl+-', icon: null },
+ { label: 'Reset Zoom', shortcut: 'Ctrl+0', icon: null, separator: true },
+ { label: 'Show Toolbar', icon: <Eye size={12} /> },
+ { label: 'Show Sidebar', icon: null }
+ ];
- {/* Intelligence Alerts */}
- <Card className="terminal-bg">
- <CardHeader className="terminal-header p-1">
- <CardTitle className="text-xs">■ REAL-TIME INTELLIGENCE ALERTS ■</CardTitle>
- </CardHeader>
- <CardContent className="p-2">
- {intelligenceFeeds.map((alert, idx) => (
- <div key={idx} className="mb-3 text-xs terminal-text">
- <div className="flex gap-2">
- <span className="terminal-gray">{alert.time}</span>
- <span className={alert.priority === 'CRITICAL' ? 'terminal-red' : alert.priority === 'HIGH' ? 'terminal-orange' : 'terminal-yellow'}>
- [{alert.priority}]
- </span>
- <span className="terminal-cyan">[{alert.source}]</span>
- </div>
- <div className="mt-1">{alert.event}</div>
- <div className="terminal-yellow text-xs">CLASSIFICATION: {alert.classification}</div>
- <div className="border-b border-gray-600 mt-1"></div>
- </div>
- ))}
- </CardContent>
- </Card>
+ const toolsMenuItems = [
+ { label: 'Calculator', icon: null },
+ { label: 'Screen Capture', icon: null },
+ { label: 'Color Picker', icon: null, separator: true },
+ { label: 'Settings', icon: <Settings size={12} /> },
+ { label: 'Preferences', shortcut: 'Ctrl+,', icon: null }
+ ];
- {/* Country Risk Matrix */}
- <Card className="terminal-bg">
- <CardHeader className="terminal-header p-1">
- <CardTitle className="text-xs">■ COUNTRY RISK MATRIX ■</CardTitle>
- </CardHeader>
- <CardContent className="p-2">
- <Table className="terminal-table">
- <TableHeader>
- <TableRow>
- <TableHead className="text-xs">COUNTRY</TableHead>
- <TableHead className="text-xs">RISK</TableHead>
- <TableHead className="text-xs">STAB</TableHead>
- <TableHead className="text-xs">MIL($B)</TableHead>
- <TableHead className="text-xs">GDP</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {Object.entries(countries).map(([country, data]) => (
- <TableRow key={country}>
- <TableCell className="text-xs">{country.substring(0,8)}</TableCell>
- <TableCell className={`text-xs ${
- data.current_risk === 'Low' ? 'terminal-green' :
- data.current_risk === 'Medium' ? 'terminal-yellow' : 'terminal-red'
- }`}>
- {data.current_risk.substring(0,3).toUpperCase()}
- </TableCell>
- <TableCell className="text-xs terminal-cyan">{data.political_stability}</TableCell>
- <TableCell className="text-xs terminal-red">${data.military_budget_billion}</TableCell>
- <TableCell className="text-xs terminal-green">${data.gdp_trillion}T</TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </CardContent>
- </Card>
+ const helpMenuItems = [
+ { label: 'User Manual', icon: <HelpCircle size={12} /> },
+ { label: 'Keyboard Shortcuts', shortcut: 'Ctrl+?', icon: null },
+ { label: 'Video Tutorials', icon: null, separator: true },
+ { label: 'Contact Support', icon: null },
+ { label: 'Report Bug', icon: null, separator: true },
+ { label: 'About Finxept', icon: null }
+ ];
- {/* Market Impact */}
- <Card className="terminal-bg">
- <CardHeader className="terminal-header p-1">
- <CardTitle className="text-xs">■ MARKET IMPACT SUMMARY ■</CardTitle>
- </CardHeader>
- <CardContent className="p-2">
- <Table className="terminal-table">
- <TableHeader>
- <TableRow>
- <TableHead className="text-xs">ASSET</TableHead>
- <TableHead className="text-xs">IMPACT</TableHead>
- <TableHead className="text-xs">REASON</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {marketData.map((item, idx) => (
- <TableRow key={idx}>
- <TableCell className="text-xs">{item.asset.substring(0,12)}</TableCell>
- <TableCell className={`text-xs ${item.impact > 0 ? 'terminal-green' : 'terminal-red'}`}>
- {item.impact > 0 ? '+' : ''}{item.impact}%
- </TableCell>
- <TableCell className="text-xs terminal-gray">{item.reason}</TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </CardContent>
- </Card>
- </div>
+ const tabStyles = {
+ default: {
+ backgroundColor: 'transparent',
+ color: '#d4d4d4',
+ border: 'none',
+ padding: '3px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '0'
+ },
+ active: {
+ backgroundColor: '#ea580c',
+ color: 'white',
+ border: 'none',
+ padding: '3px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '0'
+ }
+ };
- {/* India-Specific Dashboard */}
- <Card className="india-border mb-4">
- <CardHeader className="india-header p-2">
- <CardTitle className="text-sm font-bold">
- ████ INDIA GEOPOLITICAL DASHBOARD - REAL-TIME ANALYSIS ████
- </CardTitle>
- </CardHeader>
- <CardContent className="p-2">
- <div className="grid grid-cols-4 gap-2">
+ return (
+ <div style={{
+ width: '100vw',
+ height: '100vh',
+ margin: 0,
+ padding: 0,
+ backgroundColor: '#000000',
+ fontFamily: 'Consolas, "Courier New", monospace',
+ overflow: 'hidden',
+ fontSize: '11px',
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ overscrollBehavior: 'none'
+ }}>
+ {/* Top Menu Bar with Functional Dropdowns */}
+ <div style={{
+ backgroundColor: '#2d2d2d',
+ color: '#a3a3a3',
+ fontSize: '11px',
+ borderBottom: '1px solid #404040',
+ padding: '2px 8px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ height: '20px'
+ }}>
+ <div style={{ display: 'flex', gap: '16px' }}>
+ <DropdownMenu label="File" items={fileMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Tabs" items={tabsMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Session" items={sessionMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="API" items={apiMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Database" items={databaseMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="View" items={viewMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Tools" items={toolsMenuItems} onItemClick={handleMenuAction} />
+ <DropdownMenu label="Help" items={helpMenuItems} onItemClick={handleMenuAction} />
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <button
+ onClick={toggleFullscreen}
+ style={{
+ background: 'none',
+ border: 'none',
+ color: '#a3a3a3',
+ cursor: 'pointer',
+ padding: '2px',
+ borderRadius: '2px'
+ }}
+ onMouseEnter={(e) => {
+ e.target.style.backgroundColor = '#404040';
+ e.target.style.color = '#fff';
+ }}
+ onMouseLeave={(e) => {
+ e.target.style.backgroundColor = 'transparent';
+ e.target.style.color = '#a3a3a3';
+ }}
+ title={isFullscreen ? 'Exit Fullscreen (F11)' : 'Enter Fullscreen (F11)'}
+ >
+ {isFullscreen ? <Minimize size={14} /> : <Maximize size={14} />}
+ </button>
+ <span style={{ color: '#fbbf24' }}>Guest (18h remaining)</span>
+ <span style={{ color: '#737373', cursor: 'pointer' }} title="Help">?</span>
+ </div>
+ </div>
- <Card className="terminal-bg">
- <CardHeader className="p-1">
- <CardTitle className="text-xs terminal-yellow">INDIA: KEY METRICS</CardTitle>
- </CardHeader>
- <CardContent className="p-2">
- <Table className="terminal-table">
- <TableBody>
- <TableRow>
- <TableCell className="text-xs">GDP:</TableCell>
- <TableCell className="text-xs terminal-green">$3.9T</TableCell>
- </TableRow>
- <TableRow>
- <TableCell className="text-xs">Population:</TableCell>
- <TableCell className="text-xs terminal-cyan">1428M</TableCell>
- </TableRow>
- <TableRow>
- <TableCell className="text-xs">Military:</TableCell>
- <TableCell className="text-xs terminal-red">$83.6B</TableCell>
- </TableRow>
- <TableRow>
- <TableCell className="text-xs">Risk Level:</TableCell>
- <TableCell className="text-xs terminal-yellow">MEDIUM</TableCell>
- </TableRow>
- </TableBody>
- </Table>
- </CardContent>
- </Card>
+ {/* Status Message Bar */}
+ {statusMessage && (
+ <div style={{
+ backgroundColor: '#ea580c',
+ color: 'white',
+ fontSize: '10px',
+ padding: '2px 8px',
+ borderBottom: '1px solid #404040',
+ height: '16px',
+ display: 'flex',
+ alignItems: 'center'
+ }}>
+ {statusMessage}
+ </div>
+ )}
- <Card className="terminal-bg">
- <CardHeader className="p-1">
- <CardTitle className="text-xs terminal-yellow">STRATEGIC DEVELOPMENTS</CardTitle>
- </CardHeader>
- <CardContent className="p-2 text-xs">
- <div className="terminal-green">✓ G20 Presidency Success</div>
- <div className="terminal-green">✓ Quad Alliance Active</div>
- <div className="terminal-green">✓ Digital India Growth</div>
- <div className="terminal-orange">⚠ LAC Border Tensions</div>
- <div className="terminal-orange">⚠ Pakistan Relations</div>
- <div className="terminal-green">✓ Manufacturing Hub</div>
- </CardContent>
- </Card>
+ {/* Main Navigation Bar with Tabs */}
+ <div style={{
+ backgroundColor: '#3f3f3f',
+ borderBottom: '1px solid #404040',
+ height: '26px'
+ }}>
+ <Tabs value={activeTab} onValueChange={setActiveTab} className="h-full">
+ <TabsList style={{
+ backgroundColor: 'transparent',
+ border: 'none',
+ padding: '2px 4px',
+ height: '100%',
+ justifyContent: 'flex-start',
+ borderRadius: '0'
+ }}>
+ <TabsTrigger
+ value="dashboard"
+ style={activeTab === 'dashboard' ? tabStyles.active : tabStyles.default}
+ >
+ Dashboard
+ </TabsTrigger>
+ <TabsTrigger
+ value="markets"
+ style={activeTab === 'markets' ? tabStyles.active : tabStyles.default}
+ >
+ Markets
+ </TabsTrigger>
+ <TabsTrigger
+ value="news"
+ style={activeTab === 'news' ? tabStyles.active : tabStyles.default}
+ >
+ News
+ </TabsTrigger>
+ <TabsTrigger
+ value="forum"
+ style={activeTab === 'forum' ? tabStyles.active : tabStyles.default}
+ >
+ Forum
+ </TabsTrigger>
+ <TabsTrigger
+ value="advanced"
+ style={activeTab === 'advanced' ? tabStyles.active : tabStyles.default}
+ >
+ Advanced
+ </TabsTrigger>
+ <TabsTrigger
+ value="watchlist"
+ style={activeTab === 'watchlist' ? tabStyles.active : tabStyles.default}
+ >
+ Watchlist
+ </TabsTrigger>
+ <TabsTrigger
+ value="geopolitics"
+ style={activeTab === 'geopolitics' ? tabStyles.active : tabStyles.default}
+ >
+ Geopolitics
+ </TabsTrigger>
+ </TabsList>
+ </Tabs>
+ </div>
- <Card className="terminal-bg">
- <CardHeader className="p-1">
- <CardTitle className="text-xs terminal-yellow">THREAT ASSESSMENT</CardTitle>
- </CardHeader>
- <CardContent className="p-2">
- <Table className="terminal-table">
- <TableBody>
- {[
- {threat: "China Border", level: 7.8, category: "HIGH"},
- {threat: "Pakistan Terror", level: 6.9, category: "MEDIUM"},
- {threat: "Cyber Threats", level: 6.5, category: "MEDIUM"},
- {threat: "Energy Security", level: 5.8, category: "MEDIUM"}
- ].map((item, idx) => (
- <TableRow key={idx}>
- <TableCell className="text-xs">{item.threat.substring(0,10)}:</TableCell>
- <TableCell className={`text-xs ${item.level >= 7.0 ? 'terminal-orange' : 'terminal-yellow'}`}>
- {item.level}
- </TableCell>
- <TableCell className={`text-xs ${item.level >= 7.0 ? 'terminal-orange' : 'terminal-yellow'}`}>
- [{item.category.substring(0,3)}]
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </CardContent>
- </Card>
+ {/* Command Bar */}
+ <div style={{
+ backgroundColor: '#2d2d2d',
+ borderBottom: '1px solid #404040',
+ padding: '4px 8px',
+ height: '24px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px'
+ }}>
+ <span style={{ backgroundColor: '#ea580c', color: 'white', padding: '2px 6px', fontSize: '9px', fontWeight: 'bold' }}>FINXEPT PROFESSIONAL</span>
+ <span style={{ color: '#a3a3a3', fontSize: '10px' }}>Enter Command</span>
+ <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>
+ <span style={{ color: '#a3a3a3', fontSize: '10px' }}>Search</span>
+ <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>
+ <span style={{ color: '#a3a3a3', fontSize: '10px' }}>2025-09-26 14:00:49</span>
+ {isFullscreen && (
+ <>
+ <div style={{ width: '1px', height: '16px', backgroundColor: '#525252' }}></div>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>FULLSCREEN MODE</span>
+ </>
+ )}
+ </div>
- <Card className="terminal-bg">
- <CardHeader className="p-1">
- <CardTitle className="text-xs terminal-yellow">STRATEGIC OPPORTUNITIES</CardTitle>
- </CardHeader>
- <CardContent className="p-2 text-xs terminal-green">
- <div>• Global Manufacturing Hub</div>
- <div>• Semiconductor Production</div>
- <div>• Renewable Energy Leader</div>
- <div>• Defense Exports Growth</div>
- <div>• IMEC Trade Corridor</div>
- <div>• Digital Economy Expansion</div>
- </CardContent>
- </Card>
- </div>
- </CardContent>
- </Card>
+ {/* Function Keys Bar */}
+ <div style={{
+ backgroundColor: '#1a1a1a',
+ borderBottom: '1px solid #404040',
+ padding: '2px 8px',
+ height: '20px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '16px'
+ }}>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>F1:HELP</span>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>F2:MARKETS</span>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>F3:NEWS</span>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>F4:PORT</span>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>F5:MOVERS</span>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>F6:ECON</span>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>F11:FULLSCREEN</span>
+ </div>
- {/* Status Bar */}
- <Card className="terminal-bg">
- <CardContent className="p-2 terminal-header">
- <div className="flex justify-between text-xs font-bold">
- <div>SYSTEM STATUS: OPERATIONAL | DATA FEEDS: ACTIVE | INTEL PROCESSING: REAL-TIME</div>
- <div>Last Update: {currentTime.toLocaleTimeString()} | Classification: CONFIDENTIAL</div>
- </div>
- </CardContent>
- </Card>
+ {/* Main Content Area with Tab Content */}
+ <div style={{
+ height: statusMessage ? 'calc(100vh - 123px)' : 'calc(100vh - 107px)',
+ backgroundColor: '#000000'
+ }}>
+ <Tabs value={activeTab} className="h-full">
+ <TabsContent value="dashboard" className="h-full m-0 p-0">
+ <DashboardTab />
+ </TabsContent>
+ <TabsContent value="markets" className="h-full m-0 p-0">
+ <MarketsTab />
+ </TabsContent>
+ <TabsContent value="news" className="h-full m-0 p-0">
+ <NewsTab />
+ </TabsContent>
+ <TabsContent value="forum" className="h-full m-0 p-0">
+ <ForumTab />
+ </TabsContent>
+ <TabsContent value="advanced" className="h-full m-0 p-0">
+ <AdvancedTab />
+ </TabsContent>
+ <TabsContent value="watchlist" className="h-full m-0 p-0">
+ <WatchlistTab />
+ </TabsContent>
+ <TabsContent value="geopolitics" className="h-full m-0 p-0">
+ <GeopoliticsTab />
+ </TabsContent>
+ </Tabs>
</div>
- </>
+ </div>
);
-};
-
-export default DashboardScreen;
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/payment/InAppPaymentWindow.tsx b/fincept-terminal-desktop/src/components/payment/InAppPaymentWindow.tsx
new file mode 100644
index 000000000..007c969b6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/payment/InAppPaymentWindow.tsx
@@ -0,0 +1,252 @@
+// File: src/components/payment/InAppPaymentWindow.tsx
+// In-app payment window that opens within the Tauri application
+
+import React, { useState, useEffect, useRef } from 'react';
+import { Button } from "@/components/ui/button";
+import { X, ExternalLink, RefreshCw, AlertCircle, Shield, CreditCard } from "lucide-react";
+
+interface InAppPaymentWindowProps {
+ checkoutUrl: string;
+ onSuccess: () => void;
+ onCancel: () => void;
+ onError: (error: string) => void;
+ planName: string;
+ planPrice: number;
+}
+
+const InAppPaymentWindow: React.FC<InAppPaymentWindowProps> = ({
+ checkoutUrl,
+ onSuccess,
+ onCancel,
+ onError,
+ planName,
+ planPrice
+}) => {
+ const [isLoading, setIsLoading] = useState(true);
+ const [hasError, setHasError] = useState(false);
+ const [errorMessage, setErrorMessage] = useState('');
+ const iframeRef = useRef<HTMLIFrameElement>(null);
+
+ useEffect(() => {
+ // Set up message listener for payment completion
+ const handleMessage = (event: MessageEvent) => {
+ // Only accept messages from trusted payment domains
+ const trustedDomains = ['dodopayments.com', 'stripe.com', 'paypal.com'];
+ const origin = new URL(event.origin);
+
+ if (!trustedDomains.some(domain => origin.hostname.includes(domain))) {
+ return;
+ }
+
+ console.log('Payment message received:', event.data);
+
+ if (event.data.type === 'payment_success') {
+ console.log('Payment completed successfully');
+ onSuccess();
+ } else if (event.data.type === 'payment_error') {
+ console.log('Payment failed:', event.data.error);
+ onError(event.data.error || 'Payment failed');
+ } else if (event.data.type === 'payment_cancelled') {
+ console.log('Payment cancelled by user');
+ onCancel();
+ }
+ };
+
+ window.addEventListener('message', handleMessage);
+
+ // Set up URL monitoring for payment completion
+ const checkPaymentStatus = () => {
+ try {
+ if (iframeRef.current?.contentWindow) {
+ const currentUrl = iframeRef.current.contentWindow.location.href;
+
+ // Check for success/failure URLs
+ if (currentUrl.includes('payment-success') || currentUrl.includes('success')) {
+ console.log('Payment success detected via URL');
+ onSuccess();
+ } else if (currentUrl.includes('payment-error') || currentUrl.includes('cancelled')) {
+ console.log('Payment cancelled/failed detected via URL');
+ onCancel();
+ }
+ }
+ } catch (error) {
+ // Cross-origin restrictions prevent URL access - this is normal
+ console.log('URL monitoring blocked by CORS (expected)');
+ }
+ };
+
+ const urlCheckInterval = setInterval(checkPaymentStatus, 2000);
+
+ return () => {
+ window.removeEventListener('message', handleMessage);
+ clearInterval(urlCheckInterval);
+ };
+ }, [onSuccess, onError, onCancel]);
+
+ const handleIframeLoad = () => {
+ setIsLoading(false);
+ setHasError(false);
+ };
+
+ const handleIframeError = () => {
+ setIsLoading(false);
+ setHasError(true);
+ setErrorMessage('Failed to load payment page. Please check your internet connection.');
+ };
+
+ const handleRetry = () => {
+ setIsLoading(true);
+ setHasError(false);
+ setErrorMessage('');
+
+ if (iframeRef.current) {
+ iframeRef.current.src = checkoutUrl;
+ }
+ };
+
+ const handleOpenInBrowser = () => {
+ window.open(checkoutUrl, '_blank');
+ };
+
+ const formatCurrency = (amount: number) => {
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD'
+ }).format(amount);
+ };
+
+ return (
+ <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4">
+ <div className="bg-zinc-900 border border-zinc-700 rounded-xl w-full max-w-4xl h-full max-h-[90vh] flex flex-col shadow-2xl">
+ {/* Header */}
+ <div className="flex items-center justify-between p-4 border-b border-zinc-700">
+ <div className="flex items-center space-x-3">
+ <div className="p-2 bg-blue-600/20 rounded-lg">
+ <CreditCard className="w-5 h-5 text-blue-400" />
+ </div>
+ <div>
+ <h2 className="text-white font-semibold">Complete Your Payment</h2>
+ <p className="text-zinc-400 text-sm">
+ {planName} - {formatCurrency(planPrice)}
+ </p>
+ </div>
+ </div>
+
+ <div className="flex items-center space-x-2">
+ <div className="flex items-center space-x-1 text-xs text-zinc-500">
+ <Shield className="w-3 h-3" />
+ <span>Secure Payment</span>
+ </div>
+
+ <Button
+ onClick={handleRetry}
+ variant="outline"
+ size="sm"
+ className="border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ disabled={isLoading}
+ >
+ <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} />
+ </Button>
+
+ <Button
+ onClick={handleOpenInBrowser}
+ variant="outline"
+ size="sm"
+ className="border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ title="Open in browser"
+ >
+ <ExternalLink className="w-4 h-4" />
+ </Button>
+
+ <Button
+ onClick={onCancel}
+ variant="outline"
+ size="sm"
+ className="border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ >
+ <X className="w-4 h-4" />
+ </Button>
+ </div>
+ </div>
+
+ {/* Content Area */}
+ <div className="flex-1 relative">
+ {/* Loading State */}
+ {isLoading && (
+ <div className="absolute inset-0 flex items-center justify-center bg-zinc-900">
+ <div className="text-center">
+ <div className="w-8 h-8 border border-white/30 border-t-white rounded-full animate-spin mx-auto mb-4"></div>
+ <h3 className="text-white font-medium mb-2">Loading Payment Page</h3>
+ <p className="text-zinc-400 text-sm">Please wait while we prepare your checkout...</p>
+ </div>
+ </div>
+ )}
+
+ {/* Error State */}
+ {hasError && (
+ <div className="absolute inset-0 flex items-center justify-center bg-zinc-900">
+ <div className="text-center max-w-md">
+ <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
+ <h3 className="text-white font-medium mb-2">Payment Page Failed to Load</h3>
+ <p className="text-zinc-400 text-sm mb-6">
+ {errorMessage || 'There was an issue loading the payment page. Please try again or open in your browser.'}
+ </p>
+ <div className="space-y-3">
+ <Button
+ onClick={handleRetry}
+ className="w-full bg-blue-600 hover:bg-blue-500 text-white"
+ >
+ <RefreshCw className="w-4 h-4 mr-2" />
+ Try Again
+ </Button>
+ <Button
+ onClick={handleOpenInBrowser}
+ variant="outline"
+ className="w-full border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ >
+ <ExternalLink className="w-4 h-4 mr-2" />
+ Open in Browser
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Payment Iframe */}
+ <iframe
+ ref={iframeRef}
+ src={checkoutUrl}
+ className="w-full h-full border-0"
+ onLoad={handleIframeLoad}
+ onError={handleIframeError}
+ title="Payment Checkout"
+ sandbox="allow-same-origin allow-scripts allow-forms allow-top-navigation allow-popups"
+ allow="payment; encrypted-media"
+ />
+ </div>
+
+ {/* Footer */}
+ <div className="p-4 border-t border-zinc-700 bg-zinc-900/50">
+ <div className="flex items-center justify-between text-xs text-zinc-500">
+ <div className="flex items-center space-x-4">
+ <div className="flex items-center space-x-1">
+ <Shield className="w-3 h-3" />
+ <span>SSL Encrypted</span>
+ </div>
+ <span>•</span>
+ <span>PCI Compliant</span>
+ <span>•</span>
+ <span>Secure Payment Processing</span>
+ </div>
+
+ <div className="text-right">
+ <div>Need help? Contact support</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default InAppPaymentWindow;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
new file mode 100644
index 000000000..0b4f9de10
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
@@ -0,0 +1,351 @@
+// File: src/components/payment/PaymentProcessingScreen.tsx
+// Payment processing screen that handles the waiting and verification process
+
+import React, { useState, useEffect, useRef } from 'react';
+import { Button } from "@/components/ui/button";
+import {
+ CheckCircle,
+ XCircle,
+ Clock,
+ ExternalLink,
+ RefreshCw,
+ AlertTriangle,
+ CreditCard,
+ Shield,
+ Loader2
+} from "lucide-react";
+import { Screen } from '../../App';
+import { useAuth } from '@/contexts/AuthContext';
+import { PaymentApiService, PaymentUtils } from '@/services/paymentApi';
+
+interface PaymentProcessingScreenProps {
+ onNavigate: (screen: Screen) => void;
+ onPaymentComplete: () => void;
+}
+
+type PaymentStatus = 'processing' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'timeout';
+
+const PaymentProcessingScreen: React.FC<PaymentProcessingScreenProps> = ({
+ onNavigate,
+ onPaymentComplete
+}) => {
+ const { session, refreshUserData } = useAuth();
+ const [status, setStatus] = useState<PaymentStatus>('processing');
+ const [checkCount, setCheckCount] = useState(0);
+ const [timeElapsed, setTimeElapsed] = useState(0);
+ const [lastChecked, setLastChecked] = useState<Date>(new Date());
+ const [paymentData, setPaymentData] = useState<any>(null);
+ const [error, setError] = useState<string>('');
+
+ const intervalRef = useRef<NodeJS.Timeout>();
+ const timeoutRef = useRef<NodeJS.Timeout>();
+ const maxChecks = 60; // Check for 5 minutes (every 5 seconds)
+ const checkInterval = 5000; // 5 seconds
+ const maxWaitTime = 300000; // 5 minutes
+
+ // Check payment status
+ const checkPaymentStatus = async () => {
+ if (!session?.api_key) {
+ setError('Authentication required');
+ setStatus('failed');
+ return;
+ }
+
+ try {
+ console.log(`Payment status check #${checkCount + 1}`);
+
+ // Get updated user subscription to see if payment completed
+ const subscriptionResult = await PaymentApiService.getUserSubscription(session.api_key);
+
+ if (subscriptionResult.success && subscriptionResult.data?.has_subscription) {
+ console.log('Payment completed - user now has active subscription');
+ setStatus('completed');
+ setPaymentData(subscriptionResult.data);
+
+ // Refresh user data in context
+ await refreshUserData();
+
+ // Clear intervals
+ if (intervalRef.current) clearInterval(intervalRef.current);
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
+
+ return;
+ }
+
+ setCheckCount(prev => prev + 1);
+ setLastChecked(new Date());
+
+ // If we've checked too many times, timeout
+ if (checkCount >= maxChecks) {
+ console.log('Payment check timeout reached');
+ setStatus('timeout');
+ if (intervalRef.current) clearInterval(intervalRef.current);
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
+ }
+
+ } catch (error) {
+ console.error('Payment status check failed:', error);
+ setError('Failed to check payment status');
+ }
+ };
+
+ // Start checking payment status
+ useEffect(() => {
+ console.log('Starting payment status monitoring...');
+ setStatus('waiting');
+
+ // Initial delay before first check
+ const initialDelay = setTimeout(() => {
+ checkPaymentStatus();
+
+ // Set up interval for subsequent checks
+ intervalRef.current = setInterval(checkPaymentStatus, checkInterval);
+ }, 3000);
+
+ // Set overall timeout
+ timeoutRef.current = setTimeout(() => {
+ console.log('Payment processing timeout');
+ setStatus('timeout');
+ if (intervalRef.current) clearInterval(intervalRef.current);
+ }, maxWaitTime);
+
+ // Track elapsed time
+ const timeTracker = setInterval(() => {
+ setTimeElapsed(prev => prev + 1);
+ }, 1000);
+
+ return () => {
+ clearTimeout(initialDelay);
+ if (intervalRef.current) clearInterval(intervalRef.current);
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
+ clearInterval(timeTracker);
+ };
+ }, []);
+
+ const handleManualRefresh = async () => {
+ setError('');
+ setStatus('processing');
+ await checkPaymentStatus();
+ };
+
+ const handleContinueToDashboard = () => {
+ onPaymentComplete();
+ };
+
+ const handleBackToPricing = () => {
+ onNavigate('pricing');
+ };
+
+ const formatTimeElapsed = (seconds: number): string => {
+ const mins = Math.floor(seconds / 60);
+ const secs = seconds % 60;
+ return `${mins}:${secs.toString().padStart(2, '0')}`;
+ };
+
+ const getStatusDisplay = () => {
+ switch (status) {
+ case 'processing':
+ return {
+ icon: <Loader2 className="w-8 h-8 animate-spin text-blue-500" />,
+ title: 'Initializing Payment Check',
+ subtitle: 'Setting up payment verification...',
+ color: 'text-blue-500'
+ };
+ case 'waiting':
+ return {
+ icon: <Clock className="w-8 h-8 text-yellow-500 animate-pulse" />,
+ title: 'Waiting for Payment Confirmation',
+ subtitle: 'Please complete your payment in the browser window that opened.',
+ color: 'text-yellow-500'
+ };
+ case 'completed':
+ return {
+ icon: <CheckCircle className="w-8 h-8 text-green-500" />,
+ title: 'Payment Successful!',
+ subtitle: 'Your subscription has been activated successfully.',
+ color: 'text-green-500'
+ };
+ case 'failed':
+ return {
+ icon: <XCircle className="w-8 h-8 text-red-500" />,
+ title: 'Payment Failed',
+ subtitle: 'There was an issue processing your payment.',
+ color: 'text-red-500'
+ };
+ case 'cancelled':
+ return {
+ icon: <XCircle className="w-8 h-8 text-orange-500" />,
+ title: 'Payment Cancelled',
+ subtitle: 'The payment was cancelled or not completed.',
+ color: 'text-orange-500'
+ };
+ case 'timeout':
+ return {
+ icon: <AlertTriangle className="w-8 h-8 text-orange-500" />,
+ title: 'Payment Verification Timeout',
+ subtitle: 'We\'re still waiting for payment confirmation. This may take a few more minutes.',
+ color: 'text-orange-500'
+ };
+ default:
+ return {
+ icon: <Clock className="w-8 h-8 text-gray-500" />,
+ title: 'Processing...',
+ subtitle: 'Please wait...',
+ color: 'text-gray-500'
+ };
+ }
+ };
+
+ const statusDisplay = getStatusDisplay();
+
+ return (
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-8 w-full max-w-md mx-auto shadow-2xl">
+ <div className="text-center">
+ {/* Status Icon */}
+ <div className="mb-6">
+ {statusDisplay.icon}
+ </div>
+
+ {/* Status Title */}
+ <h2 className={`text-xl font-semibold mb-2 ${statusDisplay.color}`}>
+ {statusDisplay.title}
+ </h2>
+
+ {/* Status Subtitle */}
+ <p className="text-zinc-400 text-sm mb-6">
+ {statusDisplay.subtitle}
+ </p>
+
+ {/* Payment Status Details */}
+ {status === 'waiting' && (
+ <div className="bg-zinc-800/50 rounded-lg p-4 mb-6 space-y-3">
+ <div className="flex items-center justify-center space-x-2 text-zinc-300">
+ <CreditCard className="w-4 h-4" />
+ <span className="text-sm">Secure Payment Processing</span>
+ </div>
+
+ <div className="text-xs text-zinc-500 space-y-1">
+ <div>Time elapsed: {formatTimeElapsed(timeElapsed)}</div>
+ <div>Status checks: {checkCount}/{maxChecks}</div>
+ <div>Last checked: {lastChecked.toLocaleTimeString()}</div>
+ </div>
+
+ <div className="flex items-center justify-center space-x-1 text-zinc-400">
+ <Shield className="w-3 h-3" />
+ <span className="text-xs">Encrypted & Secure</span>
+ </div>
+ </div>
+ )}
+
+ {/* Success Details */}
+ {status === 'completed' && paymentData && (
+ <div className="bg-green-900/20 border border-green-900/50 rounded-lg p-4 mb-6">
+ <div className="text-sm text-green-300 space-y-2">
+ <div className="font-medium">
+ {paymentData.subscription?.plan?.name} Plan Activated
+ </div>
+ <div className="text-xs text-green-400">
+ {PaymentUtils.formatCurrency(paymentData.subscription?.plan?.price || 0)}/month
+ </div>
+ <div className="text-xs text-zinc-400">
+ {paymentData.subscription?.days_remaining} days remaining in current period
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Error Display */}
+ {error && (
+ <div className="bg-red-900/20 border border-red-900/50 rounded-lg p-3 mb-6">
+ <div className="flex items-center text-red-400 text-sm">
+ <AlertTriangle className="w-4 h-4 mr-2 flex-shrink-0" />
+ {error}
+ </div>
+ </div>
+ )}
+
+ {/* Action Buttons */}
+ <div className="space-y-3">
+ {status === 'completed' && (
+ <Button
+ onClick={handleContinueToDashboard}
+ className="w-full bg-green-600 hover:bg-green-500 text-white font-medium"
+ >
+ Continue to Dashboard
+ </Button>
+ )}
+
+ {(status === 'waiting' || status === 'processing') && (
+ <Button
+ onClick={handleManualRefresh}
+ variant="outline"
+ className="w-full border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ >
+ <RefreshCw className="w-4 h-4 mr-2" />
+ Check Status Now
+ </Button>
+ )}
+
+ {(status === 'failed' || status === 'cancelled' || status === 'timeout') && (
+ <div className="space-y-2">
+ <Button
+ onClick={handleManualRefresh}
+ className="w-full bg-blue-600 hover:bg-blue-500 text-white"
+ >
+ <RefreshCw className="w-4 h-4 mr-2" />
+ Check Again
+ </Button>
+ <Button
+ onClick={handleBackToPricing}
+ variant="outline"
+ className="w-full border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ >
+ Back to Plans
+ </Button>
+ </div>
+ )}
+ </div>
+
+ {/* Help Text */}
+ <div className="mt-6 pt-4 border-t border-zinc-700/50">
+ <div className="text-xs text-zinc-500 space-y-1">
+ {status === 'waiting' && (
+ <>
+ <p>Complete your payment in the opened browser window.</p>
+ <p>This page will automatically update when payment is confirmed.</p>
+ </>
+ )}
+ {status === 'timeout' && (
+ <>
+ <p>Payment processing may take up to 10 minutes.</p>
+ <p>You can safely close this window and check your account later.</p>
+ </>
+ )}
+ {(status === 'failed' || status === 'cancelled') && (
+ <>
+ <p>If you completed the payment, please wait a few minutes and check again.</p>
+ <p>Contact support if issues persist.</p>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Progress Indicator for waiting status */}
+ {status === 'waiting' && (
+ <div className="mt-4">
+ <div className="w-full bg-zinc-700 rounded-full h-1">
+ <div
+ className="bg-blue-500 h-1 rounded-full transition-all duration-300"
+ style={{
+ width: `${Math.min((checkCount / maxChecks) * 100, 100)}%`
+ }}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default PaymentProcessingScreen;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/payment/PaymentSuccessScreen.tsx b/fincept-terminal-desktop/src/components/payment/PaymentSuccessScreen.tsx
new file mode 100644
index 000000000..d204ad934
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/payment/PaymentSuccessScreen.tsx
@@ -0,0 +1,312 @@
+// File: src/components/payment/PaymentSuccessScreen.tsx
+// Payment success screen that confirms completed payment and activates subscription
+
+import React, { useState, useEffect } from 'react';
+import { Button } from "@/components/ui/button";
+import {
+ CheckCircle,
+ Download,
+ Mail,
+ Calendar,
+ CreditCard,
+ ArrowRight,
+ Star,
+ Shield,
+ Zap,
+ AlertCircle,
+ Loader2
+} from "lucide-react";
+import { Screen } from '../../App';
+import { useAuth } from '@/contexts/AuthContext';
+import { PaymentApiService, PaymentUtils } from '@/services/paymentApi';
+
+interface PaymentSuccessScreenProps {
+ onNavigate: (screen: Screen) => void;
+ onComplete: () => void;
+}
+
+const PaymentSuccessScreen: React.FC<PaymentSuccessScreenProps> = ({
+ onNavigate,
+ onComplete
+}) => {
+ const { session, refreshUserData } = useAuth();
+ const [isLoading, setIsLoading] = useState(true);
+ const [paymentData, setPaymentData] = useState<any>(null);
+ const [subscriptionData, setSubscriptionData] = useState<any>(null);
+ const [error, setError] = useState<string>('');
+
+ // Extract payment parameters from URL
+ useEffect(() => {
+ const urlParams = new URLSearchParams(window.location.search);
+ const sessionId = urlParams.get('session_id');
+ const paymentId = urlParams.get('payment_id');
+
+ console.log('Payment success page loaded with params:', { sessionId, paymentId });
+
+ const handlePaymentSuccess = async () => {
+ if (!session?.api_key) {
+ setError('Authentication required');
+ setIsLoading(false);
+ return;
+ }
+
+ try {
+ // Handle payment success with API
+ const paymentResult = await PaymentApiService.handlePaymentSuccess(
+ session.api_key,
+ sessionId || undefined,
+ paymentId || undefined
+ );
+
+ if (paymentResult.success && paymentResult.data) {
+ console.log('Payment success confirmed:', paymentResult.data);
+ setPaymentData(paymentResult.data);
+ } else {
+ console.log('Payment success API call failed, proceeding with subscription check');
+ }
+
+ // Get updated subscription data
+ const subscriptionResult = await PaymentApiService.getUserSubscription(session.api_key);
+
+ if (subscriptionResult.success && subscriptionResult.data) {
+ console.log('Subscription data retrieved:', subscriptionResult.data);
+ setSubscriptionData(subscriptionResult.data);
+
+ // Refresh user data in context
+ await refreshUserData();
+ } else {
+ throw new Error('Failed to retrieve subscription data');
+ }
+
+ } catch (error) {
+ console.error('Payment success handling failed:', error);
+ setError('Failed to confirm payment. Please contact support if you were charged.');
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ handlePaymentSuccess();
+ }, [session?.api_key, refreshUserData]);
+
+ const handleContinueToDashboard = () => {
+ onComplete();
+ };
+
+ const handleDownloadReceipt = () => {
+ if (paymentData) {
+ const receiptData = PaymentUtils.generateReceiptData(paymentData);
+
+ // Create receipt content
+ const receiptContent = `
+FINCEPT API - PAYMENT RECEIPT
+============================
+
+Receipt ID: ${receiptData.receiptId}
+Date: ${receiptData.date}
+Description: ${receiptData.description}
+Amount: ${receiptData.amount}
+Status: ${receiptData.status}
+
+Thank you for your subscription!
+Visit: https://fincept.in
+ `.trim();
+
+ // Download as text file
+ const blob = new Blob([receiptContent], { type: 'text/plain' });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = `fincept-receipt-${receiptData.receiptId}.txt`;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+ }
+ };
+
+ if (isLoading) {
+ return (
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-8 w-full max-w-md mx-auto shadow-2xl">
+ <div className="text-center">
+ <Loader2 className="w-8 h-8 animate-spin text-blue-500 mx-auto mb-4" />
+ <h2 className="text-white text-xl font-semibold mb-2">Confirming Payment</h2>
+ <p className="text-zinc-400 text-sm">Activating your subscription...</p>
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-8 w-full max-w-md mx-auto shadow-2xl">
+ <div className="text-center">
+ <AlertCircle className="w-8 h-8 text-red-500 mx-auto mb-4" />
+ <h2 className="text-white text-xl font-semibold mb-2">Payment Confirmation Error</h2>
+ <p className="text-zinc-400 text-sm mb-6">{error}</p>
+ <div className="space-y-2">
+ <Button
+ onClick={handleContinueToDashboard}
+ className="w-full bg-blue-600 hover:bg-blue-500 text-white"
+ >
+ Continue to Dashboard
+ </Button>
+ <p className="text-xs text-zinc-500">
+ Check your account dashboard for subscription status
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ const subscription = subscriptionData?.subscription;
+ const planName = subscription?.plan?.name || 'Subscription';
+ const planPrice = subscription?.plan?.price || 0;
+ const daysRemaining = subscription?.days_remaining || 0;
+
+ return (
+ <div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-8 w-full max-w-lg mx-auto shadow-2xl">
+ <div className="text-center">
+ {/* Success Icon */}
+ <div className="mb-6">
+ <CheckCircle className="w-12 h-12 text-green-500 mx-auto" />
+ </div>
+
+ {/* Success Title */}
+ <h2 className="text-2xl font-bold text-white mb-2">
+ Payment Successful!
+ </h2>
+
+ <p className="text-zinc-400 text-sm mb-6">
+ Your subscription has been activated and you now have access to all premium features.
+ </p>
+
+ {/* Subscription Details */}
+ <div className="bg-gradient-to-r from-green-900/20 to-blue-900/20 border border-green-900/50 rounded-lg p-6 mb-6">
+ <div className="text-center space-y-3">
+ <div className="flex items-center justify-center space-x-2">
+ <Star className="w-5 h-5 text-yellow-500" />
+ <h3 className="text-lg font-semibold text-white">{planName} Plan</h3>
+ </div>
+
+ <div className="text-2xl font-bold text-green-400">
+ {PaymentUtils.formatCurrency(planPrice)}/month
+ </div>
+
+ <div className="grid grid-cols-2 gap-4 text-sm">
+ <div className="text-center">
+ <div className="text-zinc-400">API Calls</div>
+ <div className="text-white font-medium">
+ {subscription?.usage?.api_calls_limit === 'unlimited'
+ ? 'Unlimited'
+ : `${subscription?.usage?.api_calls_limit?.toLocaleString()}/month`
+ }
+ </div>
+ </div>
+ <div className="text-center">
+ <div className="text-zinc-400">Billing Period</div>
+ <div className="text-white font-medium">{daysRemaining} days</div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Features Activated */}
+ <div className="bg-zinc-800/50 rounded-lg p-4 mb-6">
+ <h4 className="text-white font-medium mb-3 text-sm">Features Activated</h4>
+ <div className="grid grid-cols-2 gap-3 text-xs">
+ <div className="flex items-center space-x-2">
+ <Zap className="w-3 h-3 text-blue-400" />
+ <span className="text-zinc-300">Real-time Data</span>
+ </div>
+ <div className="flex items-center space-x-2">
+ <Shield className="w-3 h-3 text-green-400" />
+ <span className="text-zinc-300">Priority Support</span>
+ </div>
+ <div className="flex items-center space-x-2">
+ <Calendar className="w-3 h-3 text-purple-400" />
+ <span className="text-zinc-300">Advanced Analytics</span>
+ </div>
+ <div className="flex items-center space-x-2">
+ <CreditCard className="w-3 h-3 text-yellow-400" />
+ <span className="text-zinc-300">Custom Dashboards</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Action Buttons */}
+ <div className="space-y-3">
+ <Button
+ onClick={handleContinueToDashboard}
+ className="w-full bg-green-600 hover:bg-green-500 text-white font-medium"
+ >
+ <ArrowRight className="w-4 h-4 mr-2" />
+ Start Using Fincept API
+ </Button>
+
+ <div className="flex space-x-2">
+ <Button
+ onClick={handleDownloadReceipt}
+ variant="outline"
+ className="flex-1 border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ disabled={!paymentData}
+ >
+ <Download className="w-4 h-4 mr-2" />
+ Receipt
+ </Button>
+
+ <Button
+ onClick={() => {
+ // Email support (could integrate with email service)
+ window.open('mailto:[email protected]?subject=New Subscription - Thank You', '_blank');
+ }}
+ variant="outline"
+ className="flex-1 border-zinc-600 text-zinc-300 hover:bg-zinc-800"
+ >
+ <Mail className="w-4 h-4 mr-2" />
+ Support
+ </Button>
+ </div>
+ </div>
+
+ {/* Next Steps */}
+ <div className="mt-6 pt-4 border-t border-zinc-700/50">
+ <h4 className="text-white font-medium mb-2 text-sm">What's Next?</h4>
+ <div className="text-xs text-zinc-400 space-y-1 text-left">
+ <div className="flex items-start space-x-2">
+ <div className="w-1 h-1 bg-blue-400 rounded-full mt-2 flex-shrink-0" />
+ <span>Explore your new dashboard with real-time market data</span>
+ </div>
+ <div className="flex items-start space-x-2">
+ <div className="w-1 h-1 bg-blue-400 rounded-full mt-2 flex-shrink-0" />
+ <span>Set up custom alerts and watchlists</span>
+ </div>
+ <div className="flex items-start space-x-2">
+ <div className="w-1 h-1 bg-blue-400 rounded-full mt-2 flex-shrink-0" />
+ <span>Access premium API endpoints</span>
+ </div>
+ <div className="flex items-start space-x-2">
+ <div className="w-1 h-1 bg-blue-400 rounded-full mt-2 flex-shrink-0" />
+ <span>Get priority support when you need help</span>
+ </div>
+ </div>
+ </div>
+
+ {/* Payment Details */}
+ {paymentData && (
+ <div className="mt-4 pt-3 border-t border-zinc-700/50">
+ <div className="text-xs text-zinc-500 space-y-1">
+ <div>Payment ID: {paymentData.payment_uuid}</div>
+ <div>Amount: {PaymentUtils.formatCurrency(paymentData.amount || planPrice)}</div>
+ <div>Date: {new Date().toLocaleDateString()}</div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default PaymentSuccessScreen;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/AdvancedTab.tsx b/fincept-terminal-desktop/src/components/tabs/AdvancedTab.tsx
new file mode 100644
index 000000000..009e055ff
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/AdvancedTab.tsx
@@ -0,0 +1,321 @@
+import React, { useState, useEffect } from 'react';
+import { TrendingUp, Calculator, BarChart3, PieChart, Activity, Database, Settings, Filter } from 'lucide-react';
+
+interface AnalyticsData {
+ metric: string;
+ value: string;
+ change: string;
+ trend: 'up' | 'down' | 'neutral';
+}
+
+interface ToolSection {
+ id: string;
+ title: string;
+ icon: React.ReactNode;
+ description: string;
+ status: 'active' | 'inactive' | 'processing';
+}
+
+const AdvancedTab: React.FC = () => {
+ const [activeSection, setActiveSection] = useState('analytics');
+ const [analyticsData, setAnalyticsData] = useState<AnalyticsData[]>([
+ { metric: 'Portfolio Value', value: '$1,234,567.89', change: '+2.34%', trend: 'up' },
+ { metric: 'Daily P&L', value: '+$23,456.78', change: '+1.89%', trend: 'up' },
+ { metric: 'Market Exposure', value: '78.45%', change: '-0.23%', trend: 'down' },
+ { metric: 'Beta Coefficient', value: '1.23', change: '+0.05', trend: 'up' },
+ { metric: 'Sharpe Ratio', value: '1.67', change: '+0.12', trend: 'up' },
+ { metric: 'Max Drawdown', value: '-8.45%', change: '+1.23%', trend: 'up' },
+ { metric: 'Win Rate', value: '67.8%', change: '+2.1%', trend: 'up' },
+ { metric: 'Average Trade', value: '$1,234.56', change: '-$45.23', trend: 'down' }
+ ]);
+
+ const [tools, setTools] = useState<ToolSection[]>([
+ {
+ id: 'risk-analysis',
+ title: 'Risk Analysis Engine',
+ icon: <Activity size={20} />,
+ description: 'Advanced portfolio risk assessment and VaR calculations',
+ status: 'active'
+ },
+ {
+ id: 'backtesting',
+ title: 'Strategy Backtesting',
+ icon: <BarChart3 size={20} />,
+ description: 'Historical strategy performance analysis and optimization',
+ status: 'inactive'
+ },
+ {
+ id: 'correlation',
+ title: 'Correlation Matrix',
+ icon: <PieChart size={20} />,
+ description: 'Asset correlation analysis and diversification metrics',
+ status: 'processing'
+ },
+ {
+ id: 'monte-carlo',
+ title: 'Monte Carlo Simulation',
+ icon: <TrendingUp size={20} />,
+ description: 'Probabilistic portfolio outcome modeling',
+ status: 'inactive'
+ },
+ {
+ id: 'options-pricing',
+ title: 'Options Pricing Models',
+ icon: <Calculator size={20} />,
+ description: 'Black-Scholes and advanced options valuation',
+ status: 'active'
+ },
+ {
+ id: 'data-mining',
+ title: 'Market Data Mining',
+ icon: <Database size={20} />,
+ description: 'Advanced pattern recognition and signal detection',
+ status: 'processing'
+ }
+ ]);
+
+ const sections = [
+ { key: 'analytics', label: 'ANALYTICS', icon: <BarChart3 size={16} /> },
+ { key: 'tools', label: 'TOOLS', icon: <Settings size={16} /> },
+ { key: 'models', label: 'MODELS', icon: <Calculator size={16} /> },
+ { key: 'signals', label: 'SIGNALS', icon: <Activity size={16} /> }
+ ];
+
+ const [lastUpdated, setLastUpdated] = useState(new Date());
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setLastUpdated(new Date());
+ }, 10000);
+
+ return () => clearInterval(timer);
+ }, []);
+
+ const getTrendColor = (trend: string) => {
+ switch (trend) {
+ case 'up': return 'text-green-400';
+ case 'down': return 'text-red-400';
+ default: return 'text-gray-400';
+ }
+ };
+
+ const getTrendIcon = (trend: string) => {
+ switch (trend) {
+ case 'up': return '↗';
+ case 'down': return '↘';
+ default: return '→';
+ }
+ };
+
+ const getStatusColor = (status: string) => {
+ switch (status) {
+ case 'active': return 'text-green-400';
+ case 'processing': return 'text-yellow-400';
+ default: return 'text-gray-400';
+ }
+ };
+
+ const getStatusIndicator = (status: string) => {
+ switch (status) {
+ case 'active': return '●';
+ case 'processing': return '◐';
+ default: return '○';
+ }
+ };
+
+ const renderAnalytics = () => (
+ <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-4 gap-4 p-4">
+ {analyticsData.map((data, index) => (
+ <div key={index} className="bg-gray-900 border border-gray-700 rounded-lg p-4">
+ <div className="flex justify-between items-start mb-2">
+ <h3 className="text-sm font-medium text-gray-300">{data.metric}</h3>
+ <span className={`text-sm ${getTrendColor(data.trend)}`}>
+ {getTrendIcon(data.trend)}
+ </span>
+ </div>
+ <div className="text-xl font-bold text-white mb-1">{data.value}</div>
+ <div className={`text-sm ${getTrendColor(data.trend)}`}>
+ {data.change}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+
+ const renderTools = () => (
+ <div className="p-4">
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ {tools.map((tool) => (
+ <div key={tool.id} className="bg-gray-900 border border-gray-700 rounded-lg p-4 hover:bg-gray-800 transition-colors">
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3">
+ <div className="text-orange-400">{tool.icon}</div>
+ <h3 className="text-lg font-semibold text-white">{tool.title}</h3>
+ </div>
+ <div className="flex items-center gap-1">
+ <span className={`text-sm ${getStatusColor(tool.status)}`}>
+ {getStatusIndicator(tool.status)}
+ </span>
+ <span className={`text-xs uppercase ${getStatusColor(tool.status)}`}>
+ {tool.status}
+ </span>
+ </div>
+ </div>
+ <p className="text-gray-300 text-sm mb-4">{tool.description}</p>
+ <button className="w-full bg-orange-600 hover:bg-orange-700 text-white py-2 px-4 rounded text-sm font-medium transition-colors">
+ {tool.status === 'active' ? 'Open Tool' : tool.status === 'processing' ? 'View Progress' : 'Activate'}
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+
+ const renderModels = () => (
+ <div className="p-4">
+ <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
+ <h3 className="text-lg font-bold text-orange-500 mb-4">FINANCIAL MODELS</h3>
+ <div className="space-y-4">
+ <div className="border border-gray-700 rounded p-4">
+ <h4 className="font-semibold text-white mb-2">Black-Scholes Option Pricing</h4>
+ <div className="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span className="text-gray-400">Spot Price: </span>
+ <span className="text-white">$150.00</span>
+ </div>
+ <div>
+ <span className="text-gray-400">Strike Price: </span>
+ <span className="text-white">$155.00</span>
+ </div>
+ <div>
+ <span className="text-gray-400">Time to Expiry: </span>
+ <span className="text-white">30 days</span>
+ </div>
+ <div>
+ <span className="text-gray-400">Call Option Value: </span>
+ <span className="text-green-400">$3.45</span>
+ </div>
+ </div>
+ </div>
+ <div className="border border-gray-700 rounded p-4">
+ <h4 className="font-semibold text-white mb-2">CAPM Analysis</h4>
+ <div className="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span className="text-gray-400">Risk-Free Rate: </span>
+ <span className="text-white">4.5%</span>
+ </div>
+ <div>
+ <span className="text-gray-400">Market Return: </span>
+ <span className="text-white">12.3%</span>
+ </div>
+ <div>
+ <span className="text-gray-400">Beta: </span>
+ <span className="text-white">1.23</span>
+ </div>
+ <div>
+ <span className="text-gray-400">Expected Return: </span>
+ <span className="text-green-400">14.1%</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+
+ const renderSignals = () => (
+ <div className="p-4">
+ <div className="bg-gray-900 border border-gray-700 rounded-lg p-6">
+ <h3 className="text-lg font-bold text-orange-500 mb-4">TRADING SIGNALS</h3>
+ <div className="space-y-3">
+ {[
+ { asset: 'AAPL', signal: 'BUY', strength: 'Strong', price: '$175.43', target: '$185.00' },
+ { asset: 'TSLA', signal: 'SELL', strength: 'Moderate', price: '$201.78', target: '$190.00' },
+ { asset: 'MSFT', signal: 'HOLD', strength: 'Weak', price: '$334.89', target: '$340.00' },
+ { asset: 'GOOGL', signal: 'BUY', strength: 'Strong', price: '$134.56', target: '$145.00' }
+ ].map((signal, index) => (
+ <div key={index} className="flex justify-between items-center p-3 border border-gray-700 rounded">
+ <div className="flex items-center gap-4">
+ <span className="font-semibold text-white">{signal.asset}</span>
+ <span className={`px-2 py-1 rounded text-xs font-medium ${
+ signal.signal === 'BUY' ? 'bg-green-900 text-green-400' :
+ signal.signal === 'SELL' ? 'bg-red-900 text-red-400' :
+ 'bg-gray-800 text-gray-400'
+ }`}>
+ {signal.signal}
+ </span>
+ <span className="text-sm text-gray-400">{signal.strength}</span>
+ </div>
+ <div className="text-right">
+ <div className="text-sm text-white">{signal.price}</div>
+ <div className="text-xs text-gray-400">Target: {signal.target}</div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+
+ const renderContent = () => {
+ switch (activeSection) {
+ case 'analytics': return renderAnalytics();
+ case 'tools': return renderTools();
+ case 'models': return renderModels();
+ case 'signals': return renderSignals();
+ default: return renderAnalytics();
+ }
+ };
+
+ return (
+ <div className="h-full bg-black text-white flex flex-col">
+ {/* Section Navigation */}
+ <div className="bg-gray-900 border-b border-gray-700 p-2">
+ <div className="flex gap-2">
+ {sections.map((section) => (
+ <button
+ key={section.key}
+ onClick={() => setActiveSection(section.key)}
+ className={`flex items-center gap-2 px-4 py-2 text-sm font-medium rounded transition-colors ${
+ activeSection === section.key
+ ? 'bg-orange-600 text-white'
+ : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
+ }`}
+ >
+ {section.icon}
+ <span>{section.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Header */}
+ <div className="bg-gray-800 border-b border-gray-700 p-4">
+ <div className="flex justify-between items-center">
+ <h1 className="text-xl font-bold text-orange-500">
+ ADVANCED ANALYTICS & TOOLS
+ </h1>
+ <div className="flex items-center gap-4 text-sm text-gray-400">
+ <span>Last Updated: {lastUpdated.toLocaleTimeString()}</span>
+ <div className="text-green-400">● REAL-TIME</div>
+ </div>
+ </div>
+ </div>
+
+ {/* Content */}
+ <div className="flex-1 overflow-y-auto">
+ {renderContent()}
+ </div>
+
+ {/* Footer */}
+ <div className="bg-gray-900 border-t border-gray-700 p-3">
+ <div className="flex justify-between items-center text-sm text-gray-400">
+ <span>Advanced features require Professional subscription</span>
+ <span>CPU Usage: 23% | Memory: 1.2GB</span>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default AdvancedTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx b/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
new file mode 100644
index 000000000..b3d057659
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/DashboardTab.tsx
@@ -0,0 +1,478 @@
+import React, { useState, useEffect } from 'react';
+
+const DashboardTab: React.FC = () => {
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const [stockData, setStockData] = useState({
+ 'AAPL': { price: 175.43, change: 2.34, changePct: 1.35, volume: 45200000, high: 177.89, low: 174.12, open: 175.00 },
+ 'MSFT': { price: 420.67, change: 4.12, changePct: 0.99, volume: 28700000, high: 422.45, low: 418.90, open: 420.00 },
+ 'GOOGL': { price: 140.23, change: -1.23, changePct: -0.87, volume: 32100000, high: 142.45, low: 139.78, open: 141.50 },
+ 'AMZN': { price: 145.32, change: 1.89, changePct: 1.32, volume: 41800000, high: 147.23, low: 144.56, open: 145.00 },
+ 'NVDA': { price: 800.45, change: 12.45, changePct: 1.58, volume: 52300000, high: 805.67, low: 795.23, open: 798.00 },
+ 'META': { price: 345.67, change: -2.34, changePct: -0.67, volume: 31500000, high: 348.90, low: 344.12, open: 347.50 }
+ });
+
+ const [indices, setIndices] = useState({
+ 'S&P 500': { value: 5234.18, change: 0.45 },
+ 'NASDAQ': { value: 16421.67, change: -0.09 },
+ 'DOW JONES': { value: 38567.89, change: 0.41 },
+ 'RUSSELL 2000': { value: 2089.45, change: 0.43 },
+ 'VIX': { value: 18.23, change: -2.41 },
+ 'FTSE 100': { value: 7634.56, change: 0.16 }
+ });
+
+ const [economicIndicators, setEconomicIndicators] = useState({
+ 'USD/EUR': { value: 1.0845, change: 0.21 },
+ 'USD/GBP': { value: 1.2578, change: -0.10 },
+ 'GOLD': { value: 2318.45, change: 0.55 },
+ 'OIL WTI': { value: 78.89, change: -1.53 },
+ '10Y TREASURY': { value: 4.35, change: 0.46 },
+ 'BITCOIN': { value: 67234.56, change: 1.87 }
+ });
+
+ const [newsHeadlines, setNewsHeadlines] = useState([
+ 'Federal Reserve Signals Potential Rate Cut in Q2 2024',
+ 'Tech Stocks Rally on AI Investment Surge',
+ 'Oil Prices Drop on Increased Production Outlook',
+ 'European Markets Open Higher on GDP Data',
+ 'Cryptocurrency Regulation Bill Advances in Senate',
+ 'Banking Sector Shows Strong Q4 Earnings',
+ 'Supply Chain Disruptions Impact Manufacturing',
+ 'Green Energy Investments Reach Record High'
+ ]);
+
+ // Bloomberg color scheme (exact from Python)
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_YELLOW = '#FFFF00';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#1a1a1a';
+ const BLOOMBERG_PANEL_BG = '#000000';
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ }, 1000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Create left panel (Market Monitor)
+ const createLeftPanel = () => (
+ <div style={{
+ width: '350px',
+ height: '600px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ MARKET MONITOR
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Global Indices */}
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ GLOBAL INDICES
+ </div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr',
+ gap: '4px',
+ fontSize: '9px',
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', borderBottom: `1px solid ${BLOOMBERG_GRAY}`, padding: '2px 0' }}>Index</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', borderBottom: `1px solid ${BLOOMBERG_GRAY}`, padding: '2px 0', textAlign: 'right' }}>Value</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', borderBottom: `1px solid ${BLOOMBERG_GRAY}`, padding: '2px 0', textAlign: 'right' }}>Change %</div>
+
+ {Object.entries(indices).map(([index, data]) => (
+ <React.Fragment key={index}>
+ <div style={{ color: BLOOMBERG_WHITE, padding: '2px 0' }}>{index}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right', padding: '2px 0' }}>{data.value.toFixed(2)}</div>
+ <div style={{
+ color: data.change > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right',
+ padding: '2px 0'
+ }}>
+ {data.change > 0 ? '+' : ''}{data.change.toFixed(2)}%
+ </div>
+ </React.Fragment>
+ ))}
+ </div>
+
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Economic Indicators */}
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ ECONOMIC INDICATORS
+ </div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr',
+ gap: '4px',
+ fontSize: '9px',
+ marginBottom: '12px'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', borderBottom: `1px solid ${BLOOMBERG_GRAY}`, padding: '2px 0' }}>Indicator</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', borderBottom: `1px solid ${BLOOMBERG_GRAY}`, padding: '2px 0', textAlign: 'right' }}>Value</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', borderBottom: `1px solid ${BLOOMBERG_GRAY}`, padding: '2px 0', textAlign: 'right' }}>Change</div>
+
+ {Object.entries(economicIndicators).map(([indicator, data]) => (
+ <React.Fragment key={indicator}>
+ <div style={{ color: BLOOMBERG_WHITE, padding: '2px 0' }}>{indicator}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right', padding: '2px 0' }}>{data.value.toFixed(2)}</div>
+ <div style={{
+ color: data.change > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right',
+ padding: '2px 0'
+ }}>
+ {data.change > 0 ? '+' : ''}{data.change.toFixed(2)}
+ </div>
+ </React.Fragment>
+ ))}
+ </div>
+
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Latest News */}
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ LATEST NEWS
+ </div>
+ {newsHeadlines.slice(0, 4).map((headline, index) => (
+ <div key={index} style={{ marginBottom: '8px' }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '9px', lineHeight: '1.3' }}>
+ {currentTime.toTimeString().substring(0, 5)} - {headline.length > 50 ? headline.substring(0, 47) + '...' : headline}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+
+ // Create center panel (Stock Data with Tabs)
+ const createCenterPanel = () => (
+ <div style={{
+ width: '800px',
+ height: '600px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px',
+ overflow: 'auto'
+ }}>
+ {/* Tab Bar */}
+ <div style={{ display: 'flex', marginBottom: '12px', borderBottom: `1px solid ${BLOOMBERG_GRAY}` }}>
+ <div style={{
+ padding: '8px 16px',
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginRight: '2px'
+ }}>
+ Market Data
+ </div>
+ <div style={{
+ padding: '8px 16px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontSize: '11px',
+ fontWeight: 'bold',
+ marginRight: '2px'
+ }}>
+ Charts
+ </div>
+ <div style={{
+ padding: '8px 16px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ News
+ </div>
+ </div>
+
+ {/* Market Data Tab Content */}
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ TOP STOCKS
+ </div>
+
+ {/* Stock Table */}
+ <div style={{ marginBottom: '20px' }}>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr 1fr 1.5fr 1fr 1fr',
+ gap: '4px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 0',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>Ticker</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>Last</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>Chg</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>Chg%</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>Volume</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>High</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>Low</div>
+ </div>
+
+ {Object.entries(stockData).map(([ticker, data]) => (
+ <div key={ticker} style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr 1fr 1fr 1.5fr 1fr 1fr',
+ gap: '4px',
+ fontSize: '9px',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ padding: '2px 0',
+ alignItems: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{ticker}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{data.price.toFixed(2)}</div>
+ <div style={{
+ color: data.change > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>
+ {data.change > 0 ? '+' : ''}{data.change.toFixed(2)}
+ </div>
+ <div style={{
+ color: data.changePct > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>
+ {data.changePct > 0 ? '+' : ''}{data.changePct.toFixed(2)}%
+ </div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{data.volume.toLocaleString()}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{data.high.toFixed(2)}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{data.low.toFixed(2)}</div>
+ </div>
+ ))}
+ </div>
+
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Stock Details */}
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ STOCK DETAILS
+ </div>
+
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px' }}>
+ <input
+ type="text"
+ defaultValue="AAPL"
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '11px',
+ width: '150px'
+ }}
+ />
+ <button style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ fontSize: '11px',
+ fontWeight: 'bold'
+ }}>
+ Load
+ </button>
+ </div>
+
+ {/* AAPL Details */}
+ <div style={{ display: 'flex', gap: '20px' }}>
+ <div>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '12px', fontWeight: 'bold' }}>Apple Inc (AAPL US Equity)</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px', marginBottom: '4px' }}>Technology - Consumer Electronics</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>Last Price: {stockData.AAPL.price.toFixed(2)}</div>
+ <div style={{
+ color: stockData.AAPL.changePct > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ fontSize: '10px'
+ }}>
+ Change: {stockData.AAPL.change > 0 ? '+' : ''}{stockData.AAPL.change.toFixed(2)} ({stockData.AAPL.changePct > 0 ? '+' : ''}{stockData.AAPL.changePct.toFixed(2)}%)
+ </div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>Volume: {stockData.AAPL.volume.toLocaleString()}</div>
+ </div>
+ <div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>High: {stockData.AAPL.high.toFixed(2)}</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>Low: {stockData.AAPL.low.toFixed(2)}</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>Open: {stockData.AAPL.open.toFixed(2)}</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>P/E Ratio: 28.5</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px' }}>Market Cap: $2.8T</div>
+ </div>
+ </div>
+ </div>
+ );
+
+ // Create right panel (Command Line)
+ const createRightPanel = () => (
+ <div style={{
+ width: '350px',
+ height: '600px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ COMMAND LINE
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Command History */}
+ <div style={{
+ height: '200px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '8px',
+ marginBottom: '12px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px', marginBottom: '4px' }}>&gt; AAPL US Equity &lt;GO&gt;</div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', marginBottom: '8px', marginLeft: '8px' }}>Loading AAPL US Equity...</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px', marginBottom: '4px' }}>&gt; TOP &lt;GO&gt;</div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', marginBottom: '8px', marginLeft: '8px' }}>Loading TOP news...</div>
+ <div style={{ color: BLOOMBERG_WHITE, fontSize: '10px', marginBottom: '4px' }}>&gt; WEI &lt;GO&gt;</div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '10px', marginBottom: '8px', marginLeft: '8px' }}>Loading World Equity Indices...</div>
+ </div>
+
+ {/* Command Input */}
+ <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
+ <span style={{ color: BLOOMBERG_WHITE, marginRight: '8px' }}>&gt;</span>
+ <input
+ type="text"
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '11px',
+ flex: 1
+ }}
+ />
+ </div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '9px', marginBottom: '12px' }}>
+ &lt;HELP&gt; for commands. Press &lt;GO&gt; to execute.
+ </div>
+
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Quick Actions */}
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ QUICK ACTIONS
+ </div>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
+ <button style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '10px',
+ textAlign: 'left'
+ }}>
+ WEI - World Equity Indices
+ </button>
+ <button style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '10px',
+ textAlign: 'left'
+ }}>
+ TOP - Top News
+ </button>
+ <button style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '10px',
+ textAlign: 'left'
+ }}>
+ CURY - Currency Rates
+ </button>
+ <button style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '10px',
+ textAlign: 'left'
+ }}>
+ PORT - Portfolio
+ </button>
+ </div>
+
+ {/* Status */}
+ <div style={{ marginTop: '16px' }}>
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '12px', fontWeight: 'bold', marginBottom: '8px' }}>
+ STATUS
+ </div>
+ <div style={{ color: BLOOMBERG_GREEN, fontSize: '10px' }}>● Market Data: LIVE</div>
+ <div style={{ color: BLOOMBERG_GREEN, fontSize: '10px' }}>● News Feed: ACTIVE</div>
+ <div style={{ color: BLOOMBERG_GREEN, fontSize: '10px' }}>● API: CONNECTED</div>
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '10px' }}>● Latency: ~200ms</div>
+ </div>
+ </div>
+ );
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ fontSize: '12px'
+ }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>BLOOMBERG TERMINAL</span>
+ <span style={{ color: BLOOMBERG_WHITE, marginLeft: '16px' }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)}
+ </span>
+ <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: BLOOMBERG_GREEN }}>●</span>
+ <span style={{ color: BLOOMBERG_GREEN, fontSize: '10px' }}>LIVE</span>
+ </div>
+ </div>
+
+ {/* Main Content - 3 Panel Layout */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ <div style={{ display: 'flex', gap: '8px' }}>
+ {createLeftPanel()}
+ {createCenterPanel()}
+ {createRightPanel()}
+ </div>
+ </div>
+
+ {/* Status Bar */}
+ <div style={{
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '4px 12px',
+ fontSize: '10px',
+ color: BLOOMBERG_GRAY
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span>Bloomberg Professional Service | Real-time financial data</span>
+ <span>Session: {currentTime.toTimeString().substring(0, 8)}</span>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default DashboardTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
new file mode 100644
index 000000000..1a0df0f92
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/ForumTab.tsx
@@ -0,0 +1,892 @@
+// File: src/components/tabs/ForumTab.tsx
+// Forum UI component with Bloomberg terminal styling
+
+import React, { useState, useEffect } from 'react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Badge } from '@/components/ui/badge';
+import { Textarea } from '@/components/ui/textarea';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Separator } from '@/components/ui/separator';
+import { ScrollArea } from '@/components/ui/scroll-area';
+import {
+ Search,
+ Plus,
+ TrendingUp,
+ Clock,
+ MessageSquare,
+ Eye,
+ ThumbsUp,
+ ThumbsDown,
+ Pin,
+ RefreshCw,
+ HelpCircle,
+ User
+} from 'lucide-react';
+
+import { useAuth } from '@/contexts/AuthContext';
+import {
+ ForumApiService,
+ ForumCategory,
+ ForumPost,
+ ForumComment,
+ ForumStats,
+ ForumUtils
+} from '@/services/forumApi';
+
+interface ForumTabProps {}
+
+const ForumTab: React.FC<ForumTabProps> = () => {
+ const { session } = useAuth();
+
+ // State management
+ const [categories, setCategories] = useState<ForumCategory[]>([]);
+ const [posts, setPosts] = useState<ForumPost[]>([]);
+ const [stats, setStats] = useState<ForumStats | null>(null);
+ const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
+ const [currentCategoryName, setCurrentCategoryName] = useState<string>('All Categories');
+ const [searchQuery, setSearchQuery] = useState<string>('');
+ const [sortBy, setSortBy] = useState<string>('latest');
+ const [loading, setLoading] = useState<boolean>(false);
+ const [error, setError] = useState<string>('');
+
+ // Post creation state
+ const [showCreatePost, setShowCreatePost] = useState<boolean>(false);
+ const [newPostTitle, setNewPostTitle] = useState<string>('');
+ const [newPostContent, setNewPostContent] = useState<string>('');
+ const [newPostCategory, setNewPostCategory] = useState<string>('');
+ const [createPostLoading, setCreatePostLoading] = useState<boolean>(false);
+
+ // Post details state
+ const [selectedPost, setSelectedPost] = useState<ForumPost | null>(null);
+ const [postComments, setPostComments] = useState<ForumComment[]>([]);
+ const [showPostDetails, setShowPostDetails] = useState<boolean>(false);
+ const [newComment, setNewComment] = useState<string>('');
+ const [commentLoading, setCommentLoading] = useState<boolean>(false);
+
+ // Bloomberg terminal colors
+ const colors = {
+ orange: '#ea580c',
+ white: '#ffffff',
+ red: '#ef4444',
+ green: '#22c55e',
+ yellow: '#eab308',
+ gray: '#64748b',
+ blue: '#3b82f6',
+ purple: '#8b5cf6'
+ };
+
+ // Authentication check
+ const isAuthenticated = session?.authenticated || false;
+ const apiKey = session?.api_key || undefined;
+ const deviceId = session?.device_id || undefined;
+
+ // Load initial data
+ useEffect(() => {
+ if (isAuthenticated || session?.user_type === 'guest') {
+ loadInitialData();
+ }
+ }, [isAuthenticated, session]);
+
+ const loadInitialData = async () => {
+ setLoading(true);
+ setError('');
+
+ try {
+ // Load categories and stats in parallel
+ const [categoriesResult, statsResult] = await Promise.all([
+ ForumApiService.getCategories(apiKey, deviceId),
+ ForumApiService.getForumStats(apiKey, deviceId)
+ ]);
+
+ if (categoriesResult.success && categoriesResult.data?.success) {
+ const categoriesData = categoriesResult.data.data.categories;
+ setCategories(categoriesData);
+
+ // Load posts from first category or all posts
+ if (categoriesData.length > 0) {
+ loadPosts(categoriesData[0].id, categoriesData[0].name);
+ } else {
+ loadAllPosts();
+ }
+ }
+
+ if (statsResult.success && statsResult.data?.success) {
+ setStats(statsResult.data.data);
+ }
+ } catch (err) {
+ setError('Failed to load forum data. Please try again.');
+ console.error('Forum data loading failed:', err);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const loadPosts = async (categoryId?: number, categoryName?: string) => {
+ setLoading(true);
+ setError('');
+
+ try {
+ let result;
+
+ if (categoryId) {
+ result = await ForumApiService.getPostsByCategory(
+ categoryId,
+ sortBy,
+ 20,
+ apiKey,
+ deviceId
+ );
+ setSelectedCategory(categoryId);
+ setCurrentCategoryName(categoryName || 'Unknown Category');
+ } else {
+ result = await ForumApiService.getAllPosts(sortBy, 20, apiKey, deviceId);
+ setSelectedCategory(null);
+ setCurrentCategoryName('All Categories');
+ }
+
+ if (result.success && result.data?.success) {
+ const postsData = result.data.data.posts || [];
+ setPosts(postsData);
+ } else {
+ throw new Error(result.error || 'Failed to load posts');
+ }
+ } catch (err) {
+ setError('Failed to load posts. Please try again.');
+ console.error('Posts loading failed:', err);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const loadAllPosts = () => {
+ loadPosts();
+ };
+
+ const handleSearch = async () => {
+ if (!searchQuery.trim()) return;
+
+ setLoading(true);
+ setError('');
+
+ try {
+ const result = await ForumApiService.searchPosts(
+ searchQuery,
+ 'all',
+ 20,
+ apiKey,
+ deviceId
+ );
+
+ if (result.success && result.data?.success) {
+ const searchResults = result.data.data.results.posts || [];
+ setPosts(searchResults);
+ setCurrentCategoryName(`Search: "${searchQuery}"`);
+ setSelectedCategory(null);
+ } else {
+ throw new Error(result.error || 'Search failed');
+ }
+ } catch (err) {
+ setError('Search failed. Please try again.');
+ console.error('Search failed:', err);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleVote = async (postUuid: string, voteType: 'up' | 'down') => {
+ if (!isAuthenticated) {
+ setError('You must be logged in to vote');
+ return;
+ }
+
+ try {
+ const result = await ForumApiService.voteOnPost(
+ postUuid,
+ voteType,
+ apiKey!,
+ deviceId
+ );
+
+ if (result.success && result.data?.success) {
+ // Refresh posts to show updated vote counts
+ loadPosts(selectedCategory, currentCategoryName);
+ } else {
+ throw new Error(result.error || 'Vote failed');
+ }
+ } catch (err) {
+ console.error('Vote failed:', err);
+ setError('Vote failed. Please try again.');
+ }
+ };
+
+ const handleCreatePost = async () => {
+ if (!isAuthenticated) {
+ setError('You must be logged in to create posts');
+ return;
+ }
+
+ const validation = ForumUtils.validatePost(newPostTitle, newPostContent);
+ if (!validation.valid) {
+ setError(validation.error!);
+ return;
+ }
+
+ if (!newPostCategory) {
+ setError('Please select a category');
+ return;
+ }
+
+ setCreatePostLoading(true);
+ setError('');
+
+ try {
+ const result = await ForumApiService.createPost({
+ title: newPostTitle,
+ content: newPostContent,
+ category_id: parseInt(newPostCategory)
+ }, apiKey!, deviceId);
+
+ if (result.success && result.data?.success) {
+ setShowCreatePost(false);
+ setNewPostTitle('');
+ setNewPostContent('');
+ setNewPostCategory('');
+ // Refresh posts
+ loadPosts(selectedCategory, currentCategoryName);
+ } else {
+ throw new Error(result.error || 'Failed to create post');
+ }
+ } catch (err) {
+ setError('Failed to create post. Please try again.');
+ console.error('Post creation failed:', err);
+ } finally {
+ setCreatePostLoading(false);
+ }
+ };
+
+ const viewPostDetails = async (post: ForumPost) => {
+ setSelectedPost(post);
+ setShowPostDetails(true);
+
+ try {
+ const result = await ForumApiService.getPostDetails(
+ post.post_uuid,
+ apiKey,
+ deviceId
+ );
+
+ if (result.success && result.data?.success) {
+ setPostComments(result.data.data.comments || []);
+ }
+ } catch (err) {
+ console.error('Failed to load post details:', err);
+ }
+ };
+
+ const addComment = async () => {
+ if (!isAuthenticated || !selectedPost) return;
+
+ const validation = ForumUtils.validateComment(newComment);
+ if (!validation.valid) {
+ setError(validation.error!);
+ return;
+ }
+
+ setCommentLoading(true);
+
+ try {
+ const result = await ForumApiService.addComment(
+ selectedPost.post_uuid,
+ { content: newComment },
+ apiKey!,
+ deviceId
+ );
+
+ if (result.success && result.data?.success) {
+ setNewComment('');
+ // Reload post details
+ viewPostDetails(selectedPost);
+ } else {
+ throw new Error(result.error || 'Failed to add comment');
+ }
+ } catch (err) {
+ setError('Failed to add comment. Please try again.');
+ console.error('Comment failed:', err);
+ } finally {
+ setCommentLoading(false);
+ }
+ };
+
+ // Render authentication error
+ if (!session || (!isAuthenticated && session.user_type !== 'guest')) {
+ return (
+ <div className="h-full bg-black text-white p-8 flex items-center justify-center">
+ <Card className="bg-zinc-900 border-zinc-700 max-w-md">
+ <CardHeader>
+ <CardTitle className="text-yellow-500 flex items-center gap-2">
+ <HelpCircle className="h-5 w-5" />
+ Authentication Required
+ </CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <p className="text-zinc-300">
+ Please authenticate to access the Global Forum
+ </p>
+ <ul className="text-zinc-400 text-sm space-y-1">
+ <li>• Access to all forum categories</li>
+ <li>• Create posts and comments</li>
+ <li>• Vote on posts and comments</li>
+ <li>• Real-time forum activity</li>
+ <li>• User profiles and reputation</li>
+ </ul>
+ </CardContent>
+ </Card>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-full bg-black text-white font-mono">
+ {/* Header */}
+ <div className="bg-zinc-900 border-b border-zinc-700 p-4">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-4">
+ <span style={{ color: colors.orange }} className="text-lg font-bold">FINCEPT</span>
+ <span className="text-white">GLOBAL FORUM</span>
+ <span className="text-zinc-500">|</span>
+
+ {/* Search */}
+ <div className="flex items-center gap-2">
+ <Input
+ placeholder="Search posts, topics..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
+ className="bg-zinc-800 border-zinc-600 text-white w-64"
+ />
+ <Button
+ onClick={handleSearch}
+ className="bg-zinc-700 hover:bg-zinc-600"
+ >
+ <Search className="h-4 w-4" />
+ </Button>
+ </div>
+
+ <span className="text-zinc-500">|</span>
+
+ {/* User Status */}
+ <div className="flex items-center gap-2">
+ <User className="h-4 w-4" />
+ {session.user_type === 'registered' ? (
+ <span style={{ color: colors.green }}>
+ USER: {session.user_info?.username?.toUpperCase() || 'REGISTERED'}
+ </span>
+ ) : (
+ <span style={{ color: colors.yellow }}>USER: GUEST</span>
+ )}
+ </div>
+ </div>
+ </div>
+
+ {/* Function Keys */}
+ <div className="flex items-center gap-4">
+ <Button
+ onClick={loadInitialData}
+ className="bg-transparent hover:bg-zinc-700 text-yellow-500 text-xs h-6 px-2"
+ >
+ F1:HELP
+ </Button>
+ <Button
+ onClick={loadInitialData}
+ className="bg-transparent hover:bg-zinc-700 text-yellow-500 text-xs h-6 px-2"
+ >
+ <RefreshCw className="h-3 w-3 mr-1" />
+ F2:REFRESH
+ </Button>
+ {isAuthenticated && (
+ <Button
+ onClick={() => setShowCreatePost(true)}
+ className="bg-transparent hover:bg-zinc-700 text-yellow-500 text-xs h-6 px-2"
+ >
+ <Plus className="h-3 w-3 mr-1" />
+ F3:NEW POST
+ </Button>
+ )}
+ <Button
+ onClick={() => document.querySelector('input')?.focus()}
+ className="bg-transparent hover:bg-zinc-700 text-yellow-500 text-xs h-6 px-2"
+ >
+ F4:SEARCH
+ </Button>
+ <Button
+ onClick={() => setSortBy('popular')}
+ className="bg-transparent hover:bg-zinc-700 text-yellow-500 text-xs h-6 px-2"
+ >
+ <TrendingUp className="h-3 w-3 mr-1" />
+ F5:TRENDING
+ </Button>
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div className="flex h-[calc(100%-120px)]">
+ {/* Left Panel - Categories */}
+ <div className="w-80 bg-zinc-950 border-r border-zinc-700 p-4 overflow-y-auto">
+ <div style={{ color: colors.orange }} className="font-bold mb-4">FORUM CATEGORIES</div>
+
+ <div className="space-y-2 mb-4">
+ <Button
+ onClick={() => loadAllPosts()}
+ variant={selectedCategory === null ? "default" : "ghost"}
+ className="w-full justify-start text-xs h-8"
+ >
+ ALL
+ </Button>
+ <Button
+ onClick={() => setSortBy('popular')}
+ variant="ghost"
+ className="w-full justify-start text-xs h-8"
+ >
+ TRENDING
+ </Button>
+ <Button
+ onClick={() => setSortBy('latest')}
+ variant="ghost"
+ className="w-full justify-start text-xs h-8"
+ >
+ RECENT
+ </Button>
+ </div>
+
+ <Separator className="bg-zinc-700 mb-4" />
+
+ {/* Categories List */}
+ <div className="space-y-2 mb-6">
+ {categories.map((category) => (
+ <Button
+ key={category.id}
+ onClick={() => loadPosts(category.id, category.name)}
+ variant={selectedCategory === category.id ? "default" : "ghost"}
+ className="w-full justify-start text-xs h-auto p-2 flex-col items-start"
+ >
+ <div className="flex justify-between w-full">
+ <span>{category.name}</span>
+ <Badge variant="secondary" className="text-xs">
+ {category.post_count}
+ </Badge>
+ </div>
+ {category.description && (
+ <span className="text-zinc-500 text-xs mt-1">
+ {ForumUtils.truncateText(category.description, 40)}
+ </span>
+ )}
+ </Button>
+ ))}
+ </div>
+
+ <Separator className="bg-zinc-700 mb-4" />
+
+ {/* Statistics */}
+ {stats && (
+ <div>
+ <div style={{ color: colors.yellow }} className="font-bold mb-2">FORUM STATISTICS</div>
+ <div className="text-xs space-y-1">
+ <div>Categories: {stats.total_categories}</div>
+ <div>Total Posts: {ForumUtils.formatNumber(stats.total_posts)}</div>
+ <div>Total Comments: {ForumUtils.formatNumber(stats.total_comments)}</div>
+ <div style={{ color: colors.green }}>Total Votes: {ForumUtils.formatNumber(stats.total_votes)}</div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Center Panel - Posts */}
+ <div className="flex-1 bg-black overflow-y-auto">
+ <div className="p-4">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-4">
+ <span style={{ color: colors.orange }} className="font-bold">FORUM POSTS</span>
+ <span className="text-zinc-500">|</span>
+ <span className="text-white">{currentCategoryName}</span>
+ </div>
+
+ <div className="flex items-center gap-2">
+ <Label className="text-zinc-400 text-xs">SORT:</Label>
+ <Select value={sortBy} onValueChange={setSortBy}>
+ <SelectTrigger className="w-32 bg-zinc-800 border-zinc-600 text-white text-xs h-8">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent className="bg-zinc-800 border-zinc-600">
+ <SelectItem value="latest">Latest</SelectItem>
+ <SelectItem value="popular">Popular</SelectItem>
+ <SelectItem value="views">Most Viewed</SelectItem>
+ <SelectItem value="replies">Most Replies</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ {loading && (
+ <div className="text-yellow-500 mb-4">Loading posts...</div>
+ )}
+
+ {error && (
+ <div className="text-red-400 bg-red-900/20 border border-red-900/50 rounded p-2 mb-4 text-xs">
+ {error}
+ </div>
+ )}
+
+ {/* Posts List */}
+ <div className="space-y-4">
+ {posts.map((post) => (
+ <Card key={post.post_uuid} className="bg-zinc-900 border-zinc-700">
+ <CardContent className="p-4">
+ <div className="flex items-start justify-between mb-2">
+ <div className="flex items-center gap-2">
+ {post.is_pinned && <Pin className="h-4 w-4" style={{ color: colors.orange }} />}
+ <Button
+ onClick={() => viewPostDetails(post)}
+ variant="ghost"
+ className="p-0 h-auto text-left text-white hover:text-blue-400"
+ >
+ <span className="text-sm font-medium">
+ {ForumUtils.truncateText(post.title, 60)}
+ </span>
+ </Button>
+ <Badge
+ variant="outline"
+ className="text-xs"
+ style={{ borderColor: colors.blue, color: colors.blue }}
+ >
+ {post.category_name}
+ </Badge>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-4 text-xs text-zinc-400 mb-2">
+ <div className="flex items-center gap-1">
+ <Eye className="h-3 w-3" />
+ {ForumUtils.formatNumber(post.views)}
+ </div>
+ <div
+ className={`flex items-center gap-1 ${ForumUtils.getVoteColor(ForumUtils.calculateVoteScore(post.likes, post.dislikes))}`}
+ >
+ <ThumbsUp className="h-3 w-3" />
+ {ForumUtils.calculateVoteScore(post.likes, post.dislikes)}
+ </div>
+ <div className="flex items-center gap-1">
+ <MessageSquare className="h-3 w-3" />
+ {post.reply_count}
+ </div>
+ <div>By: {post.author_display_name}</div>
+ <div>{ForumUtils.formatTimestamp(post.created_at)}</div>
+ </div>
+
+ <p className="text-zinc-300 text-xs mb-3">
+ {ForumUtils.truncateText(post.content, 120)}
+ </p>
+
+ <div className="flex items-center gap-2">
+ <Button
+ onClick={() => viewPostDetails(post)}
+ size="sm"
+ className="bg-zinc-700 hover:bg-zinc-600 text-xs h-6"
+ >
+ VIEW
+ </Button>
+
+ {isAuthenticated && (
+ <>
+ <Button
+ onClick={() => handleVote(post.post_uuid, 'up')}
+ size="sm"
+ className="bg-transparent hover:bg-green-900/20 text-green-400 border border-green-600 text-xs h-6"
+ >
+ 👍 UP
+ </Button>
+ <Button
+ onClick={() => handleVote(post.post_uuid, 'down')}
+ size="sm"
+ className="bg-transparent hover:bg-red-900/20 text-red-400 border border-red-600 text-xs h-6"
+ >
+ 👎 DOWN
+ </Button>
+ </>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+
+ {posts.length === 0 && !loading && (
+ <div className="text-center text-zinc-400 mt-8">
+ <MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-50" />
+ <p>No posts found</p>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Right Panel - User Dashboard */}
+ <div className="w-80 bg-zinc-950 border-l border-zinc-700 p-4 overflow-y-auto">
+ <div style={{ color: colors.orange }} className="font-bold mb-4">USER DASHBOARD</div>
+
+ {/* User Info */}
+ <div className="mb-6">
+ <div style={{ color: colors.yellow }} className="font-bold mb-2">CURRENT USER</div>
+ <div className="flex items-center gap-3 mb-2">
+ <div
+ className="w-8 h-8 rounded flex items-center justify-center text-xs font-bold text-white"
+ style={{ backgroundColor: session.user_type === 'registered' ? colors.green : colors.yellow }}
+ >
+ {session.user_type === 'registered'
+ ? session.user_info?.username?.substring(0, 2).toUpperCase() || 'RU'
+ : 'GU'
+ }
+ </div>
+ <div>
+ <div className="text-white text-sm">
+ {session.user_type === 'registered'
+ ? session.user_info?.username || 'Registered User'
+ : 'Guest User'
+ }
+ </div>
+ {session.user_type === 'registered' ? (
+ <div style={{ color: colors.green }} className="text-xs">
+ Credits: {session.user_info?.credit_balance || 0}
+ </div>
+ ) : (
+ <div style={{ color: colors.yellow }} className="text-xs">
+ Limited Access
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <Separator className="bg-zinc-700 mb-4" />
+
+ {/* User Actions */}
+ <div className="mb-6">
+ <div style={{ color: colors.yellow }} className="font-bold mb-2">USER ACTIONS</div>
+ <div className="space-y-2">
+ {isAuthenticated ? (
+ <>
+ <Button
+ onClick={() => setShowCreatePost(true)}
+ className="w-full justify-start text-xs h-8"
+ >
+ CREATE NEW POST
+ </Button>
+ <Button className="w-full justify-start text-xs h-6">
+ MY POSTS
+ </Button>
+ <Button className="w-full justify-start text-xs h-6">
+ MY ACTIVITY
+ </Button>
+ <Button className="w-full justify-start text-xs h-6">
+ SETTINGS
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button
+ onClick={() => loadAllPosts()}
+ className="w-full justify-start text-xs h-6"
+ >
+ VIEW POSTS
+ </Button>
+ <Button
+ onClick={() => document.querySelector('input')?.focus()}
+ className="w-full justify-start text-xs h-6"
+ >
+ SEARCH FORUM
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+
+ <Separator className="bg-zinc-700 mb-4" />
+
+ {/* Recent Activity */}
+ <div>
+ <div style={{ color: colors.yellow }} className="font-bold mb-2">RECENT ACTIVITY</div>
+ <div className="text-xs text-zinc-400 space-y-1">
+ <div>Loading activity...</div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Create Post Dialog */}
+ <Dialog open={showCreatePost} onOpenChange={setShowCreatePost}>
+ <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
+ <DialogHeader>
+ <DialogTitle style={{ color: colors.orange }}>CREATE NEW POST</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div>
+ <Label className="text-white">Category</Label>
+ <Select value={newPostCategory} onValueChange={setNewPostCategory}>
+ <SelectTrigger className="bg-zinc-800 border-zinc-600 text-white">
+ <SelectValue placeholder="Select category" />
+ </SelectTrigger>
+ <SelectContent className="bg-zinc-800 border-zinc-600">
+ {categories.map((category) => (
+ <SelectItem key={category.id} value={category.id.toString()}>
+ {category.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div>
+ <Label className="text-white">Title</Label>
+ <Input
+ value={newPostTitle}
+ onChange={(e) => setNewPostTitle(e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white"
+ placeholder="Enter post title..."
+ />
+ </div>
+ <div>
+ <Label className="text-white">Content</Label>
+ <Textarea
+ value={newPostContent}
+ onChange={(e) => setNewPostContent(e.target.value)}
+ className="bg-zinc-800 border-zinc-600 text-white min-h-32"
+ placeholder="Enter post content..."
+ />
+ </div>
+ {error && (
+ <div className="text-red-400 text-xs">{error}</div>
+ )}
+ <div className="flex justify-end gap-2">
+ <Button
+ onClick={() => setShowCreatePost(false)}
+ variant="ghost"
+ className="text-zinc-400"
+ >
+ CANCEL
+ </Button>
+ <Button
+ onClick={handleCreatePost}
+ disabled={createPostLoading}
+ style={{ backgroundColor: colors.orange }}
+ className="hover:bg-orange-600"
+ >
+ {createPostLoading ? 'CREATING...' : 'CREATE POST'}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {/* Post Details Dialog */}
+ <Dialog open={showPostDetails} onOpenChange={setShowPostDetails}>
+ <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-4xl max-h-[80vh] overflow-y-auto">
+ {selectedPost && (
+ <>
+ <DialogHeader>
+ <DialogTitle style={{ color: colors.orange }}>POST DETAILS</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div>
+ <h3 className="text-lg font-bold text-white mb-2">{selectedPost.title}</h3>
+ <div className="flex items-center gap-4 text-xs text-zinc-400 mb-4">
+ <div>Author: {selectedPost.author_display_name}</div>
+ <div>Category: {selectedPost.category_name}</div>
+ <div>Views: {ForumUtils.formatNumber(selectedPost.views)}</div>
+ <div>Likes: {selectedPost.likes}</div>
+ <div>Comments: {postComments.length}</div>
+ </div>
+ <div className="text-zinc-300 whitespace-pre-wrap mb-4">
+ {selectedPost.content}
+ </div>
+ </div>
+
+ {/* Comments */}
+ <div>
+ <h4 className="font-bold text-yellow-500 mb-2">COMMENTS ({postComments.length})</h4>
+
+ {/* Add Comment */}
+ {isAuthenticated && (
+ <div className="flex gap-2 mb-4">
+ <Textarea
+ value={newComment}
+ onChange={(e) => setNewComment(e.target.value)}
+ placeholder="Add a comment..."
+ className="bg-zinc-800 border-zinc-600 text-white flex-1 min-h-20"
+ />
+ <Button
+ onClick={addComment}
+ disabled={commentLoading}
+ style={{ backgroundColor: colors.orange }}
+ className="hover:bg-orange-600"
+ >
+ {commentLoading ? 'POSTING...' : 'POST'}
+ </Button>
+ </div>
+ )}
+
+ {/* Comments List */}
+ <div className="space-y-3">
+ {postComments.map((comment) => (
+ <div key={comment.comment_uuid} className="bg-zinc-800 p-3 rounded border border-zinc-700">
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ <span className="text-white font-medium text-sm">
+ {comment.author_display_name}
+ </span>
+ <span className="text-zinc-500 text-xs">
+ {ForumUtils.formatTimestamp(comment.created_at)}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <div
+ className={`text-xs ${ForumUtils.getVoteColor(ForumUtils.calculateVoteScore(comment.likes, comment.dislikes))}`}
+ >
+ {ForumUtils.calculateVoteScore(comment.likes, comment.dislikes)}
+ </div>
+ </div>
+ </div>
+ <div className="text-zinc-300 text-sm whitespace-pre-wrap">
+ {comment.content}
+ </div>
+ </div>
+ ))}
+
+ {postComments.length === 0 && (
+ <div className="text-center text-zinc-500 py-8">
+ <MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
+ <p className="text-sm">No comments yet</p>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div className="flex justify-end">
+ <Button
+ onClick={() => setShowPostDetails(false)}
+ className="bg-zinc-700 hover:bg-zinc-600"
+ >
+ CLOSE
+ </Button>
+ </div>
+ </div>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+};
+
+export default ForumTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx b/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx
new file mode 100644
index 000000000..e86efbafa
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/GeopoliticsTab.tsx
@@ -0,0 +1,715 @@
+import React, { useState, useEffect } from 'react';
+import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, AreaChart, Area, ScatterChart, Scatter, RadarChart, PolarGrid, PolarAngleAxis, PolarRadiusAxis, Radar } from 'recharts';
+
+const GeopoliticsTab: React.FC = () => {
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const [activePanel, setActivePanel] = useState('overview');
+ const [alertCount, setAlertCount] = useState(127);
+ const [dataUpdateCount, setDataUpdateCount] = useState(0);
+
+ // Bloomberg color scheme
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_YELLOW = '#FFFF00';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_BLUE = '#64B4FF';
+ const BLOOMBERG_PURPLE = '#C864FF';
+ const BLOOMBERG_CYAN = '#00FFFF';
+ const BLOOMBERG_DARK_BG = '#000000';
+ const BLOOMBERG_PANEL_BG = '#0a0a0a';
+
+ // Risk colors
+ const RISK_CRITICAL = '#FF0000';
+ const RISK_HIGH = '#FF6400';
+ const RISK_MEDIUM = '#FFC800';
+ const RISK_LOW = '#64FF64';
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ setDataUpdateCount(prev => prev + 1);
+ if (Math.random() > 0.7) setAlertCount(prev => prev + 1);
+ }, 2000);
+ return () => clearInterval(timer);
+ }, []);
+
+ // Complex chart data
+ const riskForecastData = Array.from({ length: 90 }, (_, i) => ({
+ day: i + 1,
+ baseRisk: 7.2 + Math.sin(i * 0.1) * 0.8 + Math.random() * 0.4,
+ militaryRisk: 8.1 + Math.cos(i * 0.08) * 0.6 + Math.random() * 0.3,
+ economicRisk: 6.8 + Math.sin(i * 0.12) * 0.9 + Math.random() * 0.5,
+ cyberRisk: 7.5 + Math.cos(i * 0.15) * 0.7 + Math.random() * 0.4,
+ nuclearRisk: 7.0 + Math.sin(i * 0.05) * 0.5 + Math.random() * 0.2,
+ volatility: 2.1 + Math.random() * 1.8
+ }));
+
+ const correlationMatrix = [
+ { asset: 'Energy', military: 0.89, economic: 0.76, cyber: 0.45, nuclear: 0.67, volatility: 3.2 },
+ { asset: 'Tech', military: 0.23, economic: 0.84, cyber: 0.91, nuclear: 0.34, volatility: 2.8 },
+ { asset: 'Defense', military: 0.94, economic: 0.56, cyber: 0.67, nuclear: 0.78, volatility: 2.1 },
+ { asset: 'Finance', military: 0.45, economic: 0.91, cyber: 0.72, nuclear: 0.43, volatility: 2.4 },
+ { asset: 'Materials', military: 0.78, economic: 0.69, cyber: 0.34, nuclear: 0.56, volatility: 3.1 },
+ { asset: 'Crypto', military: 0.12, economic: 0.67, cyber: 0.89, nuclear: 0.23, volatility: 4.8 },
+ { asset: 'Commodities', military: 0.82, economic: 0.74, cyber: 0.28, nuclear: 0.61, volatility: 3.6 }
+ ];
+
+ const threatRadarData = [
+ { threat: 'Military', current: 8.1, max: 10, trend: 'up' },
+ { threat: 'Economic', current: 7.4, max: 10, trend: 'up' },
+ { threat: 'Cyber', current: 7.8, max: 10, trend: 'up' },
+ { threat: 'Nuclear', current: 7.2, max: 10, trend: 'stable' },
+ { threat: 'Climate', current: 6.4, max: 10, trend: 'up' },
+ { threat: 'Terror', current: 5.8, max: 10, trend: 'down' }
+ ];
+
+ const countryRiskData = [
+ { country: 'Russia', military: 9.2, economic: 8.1, political: 4.0, total: 7.1, trend: 'up', sanctions: 1247 },
+ { country: 'China', military: 8.5, economic: 7.8, political: 6.5, total: 7.6, trend: 'up', sanctions: 89 },
+ { country: 'Iran', military: 7.9, economic: 8.3, political: 3.2, total: 6.5, trend: 'stable', sanctions: 891 },
+ { country: 'N. Korea', military: 8.7, economic: 6.2, political: 2.1, total: 5.7, trend: 'up', sanctions: 456 },
+ { country: 'Pakistan', military: 6.8, economic: 8.1, political: 3.8, total: 6.2, trend: 'up', sanctions: 34 },
+ { country: 'India', military: 5.2, economic: 4.1, political: 6.8, total: 5.4, trend: 'stable', sanctions: 0 },
+ { country: 'USA', military: 4.1, economic: 5.2, political: 7.0, total: 5.4, trend: 'stable', sanctions: 0 },
+ { country: 'EU', military: 4.8, economic: 6.1, political: 7.3, total: 6.1, trend: 'down', sanctions: 12 }
+ ];
+
+ const marketImpactData = [
+ { sector: 'Energy', correlation: 0.89, impact: 3.8, volume: '2.3B', change: '+2.4%' },
+ { sector: 'Defense', correlation: 0.94, impact: 4.2, volume: '890M', change: '+3.1%' },
+ { sector: 'Tech', correlation: 0.84, impact: -2.1, volume: '4.7B', change: '-1.8%' },
+ { sector: 'Finance', correlation: 0.71, impact: -1.6, volume: '3.2B', change: '-0.9%' },
+ { sector: 'Materials', correlation: 0.80, impact: 2.8, volume: '1.8B', change: '+2.2%' },
+ { sector: 'Healthcare', correlation: 0.34, impact: 0.2, volume: '1.4B', change: '+0.1%' },
+ { sector: 'Utilities', correlation: 0.45, impact: 1.1, volume: '780M', change: '+0.8%' },
+ { sector: 'Crypto', correlation: 0.67, impact: -4.2, volume: '890M', change: '-3.7%' }
+ ];
+
+ const intelligenceStream = [
+ { time: "16:47:23", priority: "FLASH", source: "SIGINT", classification: "TS/SCI", region: "LAC", event: "PLA forces movement detected near Galwan Valley - 3 battalions repositioning", confidence: 95 },
+ { time: "16:45:12", priority: "URGENT", source: "HUMINT", classification: "SECRET", region: "PAK", event: "ISI-China joint operation planning meeting confirmed in Islamabad", confidence: 88 },
+ { time: "16:43:56", priority: "FLASH", source: "CYBINT", classification: "TS", region: "IND", event: "State-sponsored APT targeting Indian critical infrastructure - Power grid vulnerabilities", confidence: 92 },
+ { time: "16:42:31", priority: "IMMEDIATE", source: "ECONINT", classification: "SECRET", region: "CHN", event: "Major capital outflows from China $2.8B in 24hrs - Real estate sector collapse", confidence: 97 },
+ { time: "16:41:08", priority: "URGENT", source: "OSINT", classification: "CONFIDENTIAL", region: "RUS", event: "Wagner Group remnants regrouping in Belarus - 2000+ personnel", confidence: 78 },
+ { time: "16:39:45", priority: "FLASH", source: "GEOINT", classification: "TS", region: "NK", event: "Satellite imagery confirms new ICBM facility construction - 78% complete", confidence: 94 },
+ { time: "16:38:22", priority: "ROUTINE", source: "HUMINT", classification: "SECRET", region: "IRN", event: "IRGC naval exercises in Strait of Hormuz - 12 vessels deployed", confidence: 85 },
+ { time: "16:37:01", priority: "URGENT", source: "SIGINT", classification: "TS/SCI", region: "UKR", event: "Russian communications indicate winter offensive preparations", confidence: 91 }
+ ];
+
+ const economicIndicators = [
+ { name: "VIX Fear Index", current: 18.45, change: -1.2, trend: "down", impact: "Medium", alert: false },
+ { name: "DXY Dollar Index", current: 104.78, change: 0.3, trend: "up", impact: "High", alert: false },
+ { name: "Gold Spot", current: 2047.80, change: 18.3, trend: "up", impact: "Medium", alert: true },
+ { name: "Oil Brent", current: 82.45, change: 2.1, trend: "up", impact: "Critical", alert: true },
+ { name: "Bitcoin", current: 67234, change: -1234, trend: "down", impact: "Low", alert: false },
+ { name: "India Nifty 50", current: 24867, change: 234, trend: "up", impact: "High", alert: false },
+ { name: "INR/USD", current: 83.14, change: -0.08, trend: "stable", impact: "Medium", alert: false },
+ { name: "Yuan/USD", current: 7.234, change: 0.045, trend: "up", impact: "High", alert: true },
+ { name: "Ruble/USD", current: 92.45, change: -2.34, trend: "down", impact: "Critical", alert: true },
+ { name: "Baltic Dry Index", current: 1567, change: -89, trend: "down", impact: "Medium", alert: false }
+ ];
+
+ const tradeRouteRisk = [
+ { route: "Strait of Hormuz", risk: 8.7, throughput: "21.0mbpd", threat: "Military", status: "Critical", india: "40% oil imports" },
+ { route: "Strait of Malacca", risk: 6.8, throughput: "$3.8B/day", threat: "Piracy", status: "Medium", india: "Major trade route" },
+ { route: "Suez Canal", risk: 7.2, throughput: "$10.2B/day", threat: "Regional", status: "High", india: "Europe trade 25%" },
+ { route: "South China Sea", risk: 8.1, throughput: "$5.8B/day", threat: "Military", status: "Critical", india: "ASEAN trade 18%" },
+ { route: "Bab el-Mandeb", risk: 7.8, throughput: "$2.4B/day", threat: "Terrorism", status: "High", india: "Energy route 15%" },
+ { route: "IMEC Corridor", risk: 4.5, throughput: "$1.2B/day", threat: "Development", status: "Opportunity", india: "Alternative route" }
+ ];
+
+ const getRiskColor = (level: number) => {
+ if (level >= 8.5) return RISK_CRITICAL;
+ if (level >= 7.0) return RISK_HIGH;
+ if (level >= 5.5) return RISK_MEDIUM;
+ return RISK_LOW;
+ };
+
+ const getPriorityColor = (priority: string) => {
+ switch (priority) {
+ case "FLASH": return '#FF0000';
+ case "URGENT": return '#FF6400';
+ case "IMMEDIATE": return '#FFC800';
+ case "ROUTINE": return '#00C800';
+ default: return BLOOMBERG_GRAY;
+ }
+ };
+
+ const createMatrixDisplay = () => (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '6px',
+ height: '220px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '11px', fontWeight: 'bold', marginBottom: '6px' }}>
+ CORRELATION MATRIX - GEOPOLITICAL RISK vs MARKETS
+ </div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '80px repeat(5, 1fr)',
+ gap: '2px',
+ fontSize: '10px',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>Asset</div>
+ <div style={{ color: BLOOMBERG_RED, fontWeight: 'bold' }}>MIL</div>
+ <div style={{ color: BLOOMBERG_YELLOW, fontWeight: 'bold' }}>ECO</div>
+ <div style={{ color: BLOOMBERG_BLUE, fontWeight: 'bold' }}>CYB</div>
+ <div style={{ color: BLOOMBERG_PURPLE, fontWeight: 'bold' }}>NUC</div>
+ <div style={{ color: BLOOMBERG_CYAN, fontWeight: 'bold' }}>VOL</div>
+ </div>
+ {correlationMatrix.map((item, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '80px repeat(5, 1fr)',
+ gap: '2px',
+ fontSize: '10px',
+ marginBottom: '2px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{item.asset}</div>
+ <div style={{ color: item.military > 0.8 ? RISK_CRITICAL : item.military > 0.6 ? RISK_HIGH : RISK_MEDIUM }}>
+ {item.military.toFixed(2)}
+ </div>
+ <div style={{ color: item.economic > 0.8 ? RISK_CRITICAL : item.economic > 0.6 ? RISK_HIGH : RISK_MEDIUM }}>
+ {item.economic.toFixed(2)}
+ </div>
+ <div style={{ color: item.cyber > 0.8 ? RISK_CRITICAL : item.cyber > 0.6 ? RISK_HIGH : RISK_MEDIUM }}>
+ {item.cyber.toFixed(2)}
+ </div>
+ <div style={{ color: item.nuclear > 0.8 ? RISK_CRITICAL : item.nuclear > 0.6 ? RISK_HIGH : RISK_MEDIUM }}>
+ {item.nuclear.toFixed(2)}
+ </div>
+ <div style={{ color: getRiskColor(item.volatility) }}>
+ {item.volatility.toFixed(1)}
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: '12px'
+ }}>
+ {/* Complex Header with Multiple Status Lines */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px 8px',
+ flexShrink: 0
+ }}>
+ {/* Main Status Line */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '13px', marginBottom: '2px' }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>GEOPOLITICAL INTELLIGENCE SYSTEM</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: RISK_HIGH, fontWeight: 'bold' }}>GLOBAL RISK: 7.34/10</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_RED }}>ACTIVE CONFLICTS: 15</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_YELLOW }}>SANCTIONS: 3,127 (+3)</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: alertCount > 125 ? BLOOMBERG_RED : BLOOMBERG_YELLOW }}>ALERTS: {alertCount}</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_GREEN, animation: 'blink 1s infinite' }}>● INTEL: LIVE</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>{currentTime.toISOString().replace('T', ' ').substring(0, 19)} UTC</span>
+ </div>
+
+ {/* Secondary Status Line */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', marginBottom: '2px' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>FEEDS:</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>SIGINT●</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>HUMINT●</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>CYBINT●</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>ECONINT●</span>
+ <span style={{ color: BLOOMBERG_YELLOW }}>GEOINT◐</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>LATENCY:</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>89ms</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>UPDATES:</span>
+ <span style={{ color: BLOOMBERG_BLUE }}>{dataUpdateCount}</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>CLASSIFICATION:</span>
+ <span style={{ color: BLOOMBERG_RED }}>TOP SECRET//SCI</span>
+ </div>
+
+ {/* Market Ticker */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px', fontSize: '11px' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>MARKETS:</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>NIFTY: 24,867 (+234)</span>
+ <span style={{ color: BLOOMBERG_BLUE }}>INR: 83.14 (-0.08)</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>BRENT: $82.45 (+2.1)</span>
+ <span style={{ color: BLOOMBERG_YELLOW }}>GOLD: $2,047 (+18.3)</span>
+ <span style={{ color: BLOOMBERG_RED }}>VIX: 18.45 (-1.2)</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>DXY: 104.78 (+0.3)</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>|</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>ENERGY:</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>+3.8%</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>DEFENSE:</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>+4.2%</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>TECH:</span>
+ <span style={{ color: BLOOMBERG_RED }}>-2.1%</span>
+ </div>
+ </div>
+
+ {/* Function Keys with Sub-categories */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '3px 6px',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: '2px' }}>
+ {[
+ { key: "F1", label: "INDIA", status: "●" },
+ { key: "F2", label: "CHINA", status: "●" },
+ { key: "F3", label: "PAKISTAN", status: "◐" },
+ { key: "F4", label: "USA", status: "●" },
+ { key: "F5", label: "RUSSIA", status: "●" },
+ { key: "F6", label: "LAC", status: "◐" },
+ { key: "F7", label: "QUAD", status: "○" },
+ { key: "F8", label: "BRICS", status: "○" },
+ { key: "F9", label: "TRADE", status: "●" },
+ { key: "F10", label: "DEFENSE", status: "●" },
+ { key: "F11", label: "ENERGY", status: "●" },
+ { key: "F12", label: "CYBER", status: "●" }
+ ].map(item => (
+ <button key={item.key} style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '2px 4px',
+ fontSize: '12px',
+ height: '18px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center'
+ }}>
+ <span style={{ color: BLOOMBERG_YELLOW }}>{item.key}:</span>
+ <span style={{ marginLeft: '2px' }}>{item.label}</span>
+ <span style={{
+ marginLeft: '2px',
+ color: item.status === '●' ? BLOOMBERG_GREEN :
+ item.status === '◐' ? BLOOMBERG_YELLOW : BLOOMBERG_GRAY
+ }}>
+ {item.status}
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Dense Main Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '4px', backgroundColor: '#050505' }}>
+ {/* Top Row - Intelligence Stream & Risk Assessment */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '4px', marginBottom: '4px', height: '180px' }}>
+ {/* Real-time Intelligence Stream */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ REAL-TIME INTELLIGENCE STREAM [CLASSIFICATION: TS//SCI]
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+
+ {intelligenceStream.map((intel, index) => (
+ <div key={index} style={{
+ marginBottom: '4px',
+ fontSize: '12px',
+ borderLeft: `2px solid ${getPriorityColor(intel.priority)}`,
+ paddingLeft: '4px'
+ }}>
+ <div style={{ display: 'flex', gap: '4px', marginBottom: '1px' }}>
+ <span style={{ color: BLOOMBERG_GRAY, minWidth: '50px' }}>{intel.time}</span>
+ <span style={{ color: getPriorityColor(intel.priority), fontWeight: 'bold', minWidth: '60px' }}>
+ [{intel.priority}]
+ </span>
+ <span style={{ color: BLOOMBERG_BLUE, minWidth: '50px' }}>[{intel.source}]</span>
+ <span style={{ color: BLOOMBERG_PURPLE, minWidth: '30px' }}>{intel.region}</span>
+ <span style={{ color: BLOOMBERG_YELLOW, minWidth: '30px' }}>{intel.confidence}%</span>
+ </div>
+ <div style={{ color: BLOOMBERG_WHITE, lineHeight: '1.1', marginBottom: '1px' }}>
+ {intel.event}
+ </div>
+ <div style={{ color: BLOOMBERG_GRAY, fontSize: '7px' }}>
+ Classification: {intel.classification}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Country Risk Matrix */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ COUNTRY RISK ASSESSMENT MATRIX
+ </div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '50px repeat(6, 1fr)',
+ gap: '2px',
+ fontSize: '12px',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>CTRY</div>
+ <div style={{ color: BLOOMBERG_RED, fontWeight: 'bold' }}>MIL</div>
+ <div style={{ color: BLOOMBERG_YELLOW, fontWeight: 'bold' }}>ECO</div>
+ <div style={{ color: BLOOMBERG_BLUE, fontWeight: 'bold' }}>POL</div>
+ <div style={{ color: BLOOMBERG_PURPLE, fontWeight: 'bold' }}>TOT</div>
+ <div style={{ color: BLOOMBERG_CYAN, fontWeight: 'bold' }}>TRD</div>
+ <div style={{ color: BLOOMBERG_GRAY, fontWeight: 'bold' }}>SAN</div>
+ </div>
+ {countryRiskData.map((country, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '50px repeat(6, 1fr)',
+ gap: '2px',
+ fontSize: '11px',
+ marginBottom: '1px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>{country.country}</div>
+ <div style={{ color: getRiskColor(country.military) }}>{country.military.toFixed(1)}</div>
+ <div style={{ color: getRiskColor(country.economic) }}>{country.economic.toFixed(1)}</div>
+ <div style={{ color: getRiskColor(country.political) }}>{country.political.toFixed(1)}</div>
+ <div style={{ color: getRiskColor(country.total) }}>{country.total.toFixed(1)}</div>
+ <div style={{
+ color: country.trend === 'up' ? BLOOMBERG_RED :
+ country.trend === 'down' ? BLOOMBERG_GREEN : BLOOMBERG_YELLOW
+ }}>
+ {country.trend === 'up' ? '↑' : country.trend === 'down' ? '↓' : '→'}
+ </div>
+ <div style={{ color: country.sanctions > 500 ? BLOOMBERG_RED : country.sanctions > 50 ? BLOOMBERG_YELLOW : BLOOMBERG_GREEN }}>
+ {country.sanctions}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Economic Indicators Dashboard */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ ECONOMIC THREAT INDICATORS
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+
+ {economicIndicators.map((indicator, index) => (
+ <div key={index} style={{
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ marginBottom: '2px',
+ fontSize: '12px',
+ backgroundColor: indicator.alert ? 'rgba(255,0,0,0.1)' : 'transparent',
+ padding: '1px 2px'
+ }}>
+ <div style={{ flex: 1 }}>
+ <span style={{ color: BLOOMBERG_WHITE, fontWeight: indicator.alert ? 'bold' : 'normal' }}>
+ {indicator.name}
+ </span>
+ {indicator.alert && <span style={{ color: BLOOMBERG_RED, marginLeft: '2px' }}>⚠</span>}
+ </div>
+ <div style={{
+ color: indicator.change > 0 ? BLOOMBERG_GREEN :
+ indicator.change < 0 ? BLOOMBERG_RED : BLOOMBERG_GRAY,
+ minWidth: '60px',
+ textAlign: 'right'
+ }}>
+ {indicator.current.toLocaleString()}
+ </div>
+ <div style={{
+ color: indicator.change > 0 ? BLOOMBERG_GREEN :
+ indicator.change < 0 ? BLOOMBERG_RED : BLOOMBERG_GRAY,
+ minWidth: '40px',
+ textAlign: 'right'
+ }}>
+ {indicator.change > 0 ? '+' : ''}{indicator.change}
+ </div>
+ <div style={{
+ color: indicator.impact === 'Critical' ? BLOOMBERG_RED :
+ indicator.impact === 'High' ? BLOOMBERG_ORANGE :
+ indicator.impact === 'Medium' ? BLOOMBERG_YELLOW : BLOOMBERG_GREEN,
+ minWidth: '20px',
+ textAlign: 'center',
+ fontSize: '11px'
+ }}>
+ {indicator.impact.charAt(0)}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Middle Row - Charts Section */}
+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: '4px', marginBottom: '4px', height: '240px' }}>
+ {/* Complex Risk Forecast Chart */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ MULTI-VECTOR RISK FORECAST - 90 DAY PREDICTIVE MODEL
+ </div>
+ <ResponsiveContainer width="100%" height={200}>
+ <LineChart data={riskForecastData.slice(0, 30)}>
+ <CartesianGrid strokeDasharray="1 1" stroke={BLOOMBERG_GRAY} opacity={0.3} />
+ <XAxis dataKey="day" stroke={BLOOMBERG_WHITE} fontSize={10} />
+ <YAxis stroke={BLOOMBERG_WHITE} fontSize={10} domain={[5, 10]} />
+ <Tooltip
+ contentStyle={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ fontSize: '10px'
+ }}
+ />
+ <Legend wrapperStyle={{ fontSize: '10px' }} />
+ <Line type="monotone" dataKey="baseRisk" stroke={BLOOMBERG_GREEN} strokeWidth={1} name="Base Risk" dot={false} />
+ <Line type="monotone" dataKey="militaryRisk" stroke={BLOOMBERG_RED} strokeWidth={1} name="Military" dot={false} />
+ <Line type="monotone" dataKey="economicRisk" stroke={BLOOMBERG_YELLOW} strokeWidth={1} name="Economic" dot={false} />
+ <Line type="monotone" dataKey="cyberRisk" stroke={BLOOMBERG_BLUE} strokeWidth={1} name="Cyber" dot={false} />
+ <Line type="monotone" dataKey="nuclearRisk" stroke={BLOOMBERG_PURPLE} strokeWidth={1} name="Nuclear" dot={false} />
+ </LineChart>
+ </ResponsiveContainer>
+ </div>
+
+ {/* Threat Radar Chart */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ THREAT RADAR
+ </div>
+ <ResponsiveContainer width="100%" height={200}>
+ <RadarChart data={threatRadarData}>
+ <PolarGrid stroke={BLOOMBERG_GRAY} />
+ <PolarAngleAxis dataKey="threat" tick={{ fontSize: 10, fill: BLOOMBERG_WHITE }} />
+ <PolarRadiusAxis angle={90} domain={[0, 10]} tick={{ fontSize: 9, fill: BLOOMBERG_GRAY }} />
+ <Radar
+ name="Current Threat"
+ dataKey="current"
+ stroke={BLOOMBERG_RED}
+ fill={BLOOMBERG_RED}
+ fillOpacity={0.3}
+ strokeWidth={2}
+ />
+ </RadarChart>
+ </ResponsiveContainer>
+ </div>
+
+ {/* Correlation Matrix Display */}
+ {createMatrixDisplay()}
+ </div>
+
+ {/* Bottom Row - Market Impact & Trade Routes */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '4px', height: '200px' }}>
+ {/* Market Impact Analysis */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ MARKET IMPACT ANALYSIS
+ </div>
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '60px 40px 40px 50px 40px',
+ gap: '2px',
+ fontSize: '12px',
+ marginBottom: '4px'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold' }}>SECTOR</div>
+ <div style={{ color: BLOOMBERG_BLUE, fontWeight: 'bold' }}>CORR</div>
+ <div style={{ color: BLOOMBERG_GREEN, fontWeight: 'bold' }}>IMPL</div>
+ <div style={{ color: BLOOMBERG_YELLOW, fontWeight: 'bold' }}>VOLUME</div>
+ <div style={{ color: BLOOMBERG_PURPLE, fontWeight: 'bold' }}>CHG</div>
+ </div>
+ {marketImpactData.map((market, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '60px 40px 40px 50px 40px',
+ gap: '2px',
+ fontSize: '11px',
+ marginBottom: '1px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{market.sector}</div>
+ <div style={{ color: market.correlation > 0.8 ? BLOOMBERG_RED : market.correlation > 0.6 ? BLOOMBERG_YELLOW : BLOOMBERG_GREEN }}>
+ {market.correlation.toFixed(2)}
+ </div>
+ <div style={{ color: market.impact > 0 ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
+ {market.impact > 0 ? '+' : ''}{market.impact.toFixed(1)}
+ </div>
+ <div style={{ color: BLOOMBERG_GRAY }}>{market.volume}</div>
+ <div style={{ color: market.change.startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED }}>
+ {market.change}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* Critical Trade Routes */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ CRITICAL TRADE ROUTE RISK
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+
+ {tradeRouteRisk.map((route, index) => (
+ <div key={index} style={{ marginBottom: '6px', fontSize: '8px' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: BLOOMBERG_WHITE, fontWeight: 'bold', fontSize: '9px' }}>
+ {route.route}
+ </span>
+ <span style={{ color: getRiskColor(route.risk) }}>
+ {route.risk.toFixed(1)}
+ </span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>Throughput:</span>
+ <span style={{ color: BLOOMBERG_BLUE }}>{route.throughput}</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>Threat:</span>
+ <span style={{ color: BLOOMBERG_YELLOW }}>{route.threat}</span>
+ </div>
+ <div style={{ color: BLOOMBERG_CYAN, fontSize: '7px', lineHeight: '1.1' }}>
+ India: {route.india}
+ </div>
+ </div>
+ ))}
+ </div>
+
+ {/* India Strategic Dashboard */}
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ padding: '4px',
+ overflow: 'auto'
+ }}>
+ <div style={{ color: BLOOMBERG_ORANGE, fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>
+ INDIA STRATEGIC POSITION ANALYSIS
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '4px' }}></div>
+
+ <div style={{ marginBottom: '6px' }}>
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
+ KEY METRICS
+ </div>
+ <div style={{ fontSize: '8px', lineHeight: '1.2' }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>GDP Growth:</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>6.7% YoY</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>FDI Inflows:</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>$83.6B</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>Defense Budget:</span>
+ <span style={{ color: BLOOMBERG_BLUE }}>$75.6B</span>
+ </div>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span style={{ color: BLOOMBERG_GRAY }}>Border Infra:</span>
+ <span style={{ color: BLOOMBERG_YELLOW }}>67% Complete</span>
+ </div>
+ </div>
+ </div>
+
+ <div style={{ marginBottom: '6px' }}>
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
+ THREAT MATRIX
+ </div>
+ <div style={{ fontSize: '7px' }}>
+ {[
+ { threat: "LAC Tensions", level: 7.8, status: "ACTIVE" },
+ { threat: "Pakistan Terror", level: 6.9, status: "MEDIUM" },
+ { threat: "Cyber Warfare", level: 6.5, status: "HIGH" },
+ { threat: "Energy Security", level: 5.8, status: "WATCH" },
+ { threat: "Trade Disruption", level: 5.2, status: "LOW" }
+ ].map((item, index) => (
+ <div key={index} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '1px' }}>
+ <span style={{ color: BLOOMBERG_WHITE }}>{item.threat}:</span>
+ <span style={{ color: getRiskColor(item.level) }}>{item.level} [{item.status}]</span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div>
+ <div style={{ color: BLOOMBERG_YELLOW, fontSize: '9px', fontWeight: 'bold', marginBottom: '2px' }}>
+ STRATEGIC INITIATIVES
+ </div>
+ <div style={{ fontSize: '7px', color: BLOOMBERG_GREEN }}>
+ <div>✓ Quad Alliance Operationalization</div>
+ <div>✓ IMEC Corridor Development</div>
+ <div>✓ Semiconductor Self-Reliance</div>
+ <div>✓ Digital India 2.0 Rollout</div>
+ <div>✓ Defense Export Push</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Enhanced Status Bar */}
+ <div style={{
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '2px 8px',
+ fontSize: '10px',
+ color: BLOOMBERG_GRAY,
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
+ <div style={{ display: 'flex', gap: '16px' }}>
+ <span>Geopolitical Intelligence System v3.2.1 | Real-time threat analysis</span>
+ <span>Sources: 47 Active | Confidence: 94.2% | Processing: 2.1M events/min</span>
+ </div>
+ <div style={{ display: 'flex', gap: '16px' }}>
+ <span>Classification: TOP SECRET//SCI//NOFORN</span>
+ <span>Session: {currentTime.toTimeString().substring(0, 8)}</span>
+ <span style={{ color: BLOOMBERG_GREEN }}>SCIF: AUTHORIZED</span>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default GeopoliticsTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
new file mode 100644
index 000000000..c529d3c65
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/MarketsTab.tsx
@@ -0,0 +1,485 @@
+import React, { useState, useEffect } from 'react';
+
+const MarketsTab: React.FC = () => {
+ const [currentTime, setCurrentTime] = useState(new Date());
+ const [lastUpdate, setLastUpdate] = useState(new Date());
+ const [isUpdating, setIsUpdating] = useState(false);
+ const [autoUpdate, setAutoUpdate] = useState(true);
+
+ // Bloomberg color scheme (exact from Python)
+ const BLOOMBERG_ORANGE = '#FFA500';
+ const BLOOMBERG_WHITE = '#FFFFFF';
+ const BLOOMBERG_RED = '#FF0000';
+ const BLOOMBERG_GREEN = '#00C800';
+ const BLOOMBERG_GRAY = '#787878';
+ const BLOOMBERG_DARK_BG = '#1a1a1a';
+ const BLOOMBERG_PANEL_BG = '#000000';
+
+ // Market data (exact structure from Python)
+ const marketData = {
+ 'Stock Indices': [
+ ['S&P 500', '5232.35', '+23.45', '+0.45%', '+2.1%', '+5.4%'],
+ ['Nasdaq 100', '16412.87', '-15.23', '-0.09%', '+1.8%', '+7.2%'],
+ ['Dow Jones', '38546.12', '+156.78', '+0.41%', '+1.5%', '+3.9%'],
+ ['Russell 2000', '2087.45', '+8.90', '+0.43%', '+2.3%', '+4.1%'],
+ ['VIX', '18.23', '-0.45', '-2.41%', '-5.2%', '-8.7%'],
+ ['FTSE 100', '7623.98', '+12.34', '+0.16%', '+0.8%', '+2.3%'],
+ ['DAX 40', '18245.67', '+89.23', '+0.49%', '+1.2%', '+4.6%'],
+ ['Nikkei 225', '35897.45', '-123.45', '-0.34%', '-0.5%', '+1.8%'],
+ ['CAC 40', '7890.12', '+45.67', '+0.58%', '+1.8%', '+4.2%'],
+ ['Hang Seng', '18654.23', '-89.45', '-0.48%', '-1.2%', '+2.8%']
+ ],
+ 'Forex': [
+ ['EUR/USD', '1.0840', '+0.0023', '+0.21%', '+0.8%', '+2.1%'],
+ ['GBP/USD', '1.2567', '-0.0012', '-0.10%', '-0.3%', '+1.5%'],
+ ['USD/JPY', '151.45', '+0.35', '+0.23%', '+1.2%', '+3.4%'],
+ ['USD/CHF', '0.8923', '-0.0034', '-0.38%', '-0.7%', '-1.2%'],
+ ['USD/CAD', '1.3578', '+0.0089', '+0.66%', '+0.4%', '+1.8%'],
+ ['AUD/USD', '0.6634', '+0.0067', '+1.02%', '+2.1%', '+4.3%'],
+ ['NZD/USD', '0.6089', '-0.0034', '-0.56%', '-0.8%', '+1.2%'],
+ ['EUR/GBP', '0.8623', '+0.0012', '+0.14%', '+0.3%', '+0.9%'],
+ ['EUR/JPY', '164.23', '+0.89', '+0.54%', '+1.8%', '+5.1%'],
+ ['GBP/JPY', '190.45', '-1.23', '-0.64%', '-0.9%', '+2.3%']
+ ],
+ 'Commodities': [
+ ['Gold', '2312.80', '+12.45', '+0.54%', '+1.8%', '+5.2%'],
+ ['Silver', '28.45', '-0.67', '-2.30%', '-1.2%', '+3.1%'],
+ ['Crude Oil (WTI)', '78.35', '-1.23', '-1.55%', '-2.8%', '-0.5%'],
+ ['Brent Crude', '82.10', '-0.89', '-1.07%', '-2.1%', '+1.2%'],
+ ['Natural Gas', '3.45', '+0.12', '+3.60%', '+8.2%', '+12.4%'],
+ ['Copper', '4.23', '+0.045', '+1.08%', '+2.3%', '+6.7%'],
+ ['Platinum', '987.50', '+8.90', '+0.91%', '+2.1%', '+4.8%'],
+ ['Palladium', '1045.20', '-12.45', '-1.18%', '-2.3%', '-5.1%'],
+ ['Wheat', '567.80', '+5.67', '+1.01%', '+3.2%', '+7.9%'],
+ ['Corn', '478.90', '-3.45', '-0.72%', '-1.8%', '+2.4%']
+ ],
+ 'Bonds': [
+ ['US 10Y Treasury', '4.35%', '+0.02', '+0.46%', '+1.2%', '+3.4%'],
+ ['US 30Y Treasury', '4.52%', '+0.01', '+0.22%', '+0.8%', '+2.1%'],
+ ['US 2Y Treasury', '4.89%', '-0.03', '-0.61%', '-0.5%', '+1.8%'],
+ ['Germany 10Y', '2.45%', '+0.01', '+0.41%', '+0.6%', '+1.9%'],
+ ['UK 10Y', '4.12%', '-0.02', '-0.48%', '-0.3%', '+2.3%'],
+ ['Japan 10Y', '0.78%', '+0.01', '+1.30%', '+2.1%', '+8.7%'],
+ ['France 10Y', '2.98%', '+0.02', '+0.67%', '+0.9%', '+2.8%'],
+ ['Italy 10Y', '4.23%', '-0.01', '-0.24%', '-0.2%', '+1.5%'],
+ ['Spain 10Y', '3.67%', '+0.03', '+0.82%', '+1.1%', '+3.2%'],
+ ['Canada 10Y', '3.89%', '+0.01', '+0.26%', '+0.7%', '+2.1%']
+ ],
+ 'ETFs': [
+ ['SPY (S&P 500)', '523.45', '+2.34', '+0.45%', '+2.1%', '+5.4%'],
+ ['QQQ (Nasdaq)', '412.67', '-1.23', '-0.30%', '+1.8%', '+7.2%'],
+ ['DIA (Dow)', '385.23', '+1.56', '+0.41%', '+1.5%', '+3.9%'],
+ ['EEM (Emerging)', '41.78', '+0.34', '+0.82%', '+3.2%', '+6.8%'],
+ ['GLD (Gold)', '231.45', '+1.23', '+0.53%', '+1.8%', '+5.1%'],
+ ['XLK (Tech)', '198.90', '-0.89', '-0.45%', '+2.3%', '+8.9%'],
+ ['XLE (Energy)', '89.34', '+1.45', '+1.65%', '+3.8%', '+7.2%'],
+ ['XLF (Finance)', '42.56', '-0.67', '-1.55%', '-1.2%', '+2.1%'],
+ ['XLV (Health)', '156.78', '+0.98', '+0.63%', '+1.1%', '+3.7%'],
+ ['VNQ (REIT)', '78.90', '-1.12', '-1.40%', '-2.3%', '+1.8%']
+ ],
+ 'Cryptocurrencies': [
+ ['Bitcoin', '67890.45', '+1234.56', '+1.85%', '+8.2%', '+15.7%'],
+ ['Ethereum', '3789.23', '-67.89', '-1.76%', '+5.4%', '+12.3%'],
+ ['Binance Coin', '567.89', '+12.34', '+2.22%', '+6.8%', '+18.9%'],
+ ['Solana', '234.56', '+8.90', '+3.94%', '+12.1%', '+25.6%'],
+ ['Dogecoin', '0.1234', '-0.0045', '-3.52%', '-2.1%', '+8.7%'],
+ ['Polygon', '1.23', '+0.045', '+3.80%', '+9.8%', '+21.4%'],
+ ['Chainlink', '23.45', '+0.89', '+3.94%', '+7.2%', '+14.8%'],
+ ['Cardano', '0.67', '-0.023', '-3.32%', '-1.8%', '+5.4%'],
+ ['Polkadot', '12.34', '+0.56', '+4.76%', '+8.9%', '+19.2%'],
+ ['Avalanche', '45.67', '-1.23', '-2.62%', '-3.1%', '+11.7%']
+ ]
+ };
+
+ // Regional data (exact from Python)
+ const regionalData = {
+ 'India': [
+ ['RELIANCE.NS', 'Reliance Industries', '2500.45', '+23.45', '+0.95%'],
+ ['TCS.NS', 'Tata Consultancy', '3456.78', '-12.34', '-0.36%'],
+ ['HDFCBANK.NS', 'HDFC Bank', '1678.90', '+8.90', '+0.53%'],
+ ['INFY.NS', 'Infosys', '1234.56', '+15.67', '+1.29%'],
+ ['HINDUNILVR.NS', 'Hindustan Unilever', '2345.67', '-5.43', '-0.23%'],
+ ['ICICIBANK.NS', 'ICICI Bank', '987.65', '+12.34', '+1.27%'],
+ ['SBIN.NS', 'State Bank of India', '678.90', '+3.45', '+0.51%'],
+ ['BHARTIARTL.NS', 'Bharti Airtel', '876.54', '-7.89', '-0.89%']
+ ],
+ 'China': [
+ ['BABA', 'Alibaba Group', '85.67', '+2.34', '+2.81%'],
+ ['PDD', 'PDD Holdings', '123.45', '-1.23', '-0.99%'],
+ ['JD', 'JD.com', '34.56', '+0.89', '+2.64%'],
+ ['BIDU', 'Baidu', '145.67', '+3.45', '+2.43%'],
+ ['TCEHY', 'Tencent Holdings', '45.78', '-0.67', '-1.44%'],
+ ['NIO', 'NIO Inc', '12.34', '+0.45', '+3.78%'],
+ ['LI', 'Li Auto', '23.45', '+1.23', '+5.54%'],
+ ['XPEV', 'XPeng', '15.67', '-0.89', '-5.38%']
+ ],
+ 'United States': [
+ ['AAPL', 'Apple Inc', '175.43', '+2.34', '+1.35%'],
+ ['MSFT', 'Microsoft Corp', '420.67', '+4.12', '+0.99%'],
+ ['GOOGL', 'Alphabet Inc', '140.23', '-1.23', '-0.87%'],
+ ['AMZN', 'Amazon.com', '145.32', '+1.89', '+1.32%'],
+ ['NVDA', 'NVIDIA Corp', '800.45', '+12.45', '+1.58%'],
+ ['META', 'Meta Platforms', '345.67', '-2.34', '-0.67%'],
+ ['TSLA', 'Tesla Inc', '200.78', '-5.67', '-2.75%'],
+ ['JPM', 'JPMorgan Chase', '156.89', '+1.23', '+0.79%']
+ ]
+ };
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setCurrentTime(new Date());
+ if (autoUpdate) {
+ setIsUpdating(true);
+ setLastUpdate(new Date());
+ setTimeout(() => setIsUpdating(false), 1000);
+ }
+ }, 5000);
+ return () => clearInterval(timer);
+ }, [autoUpdate]);
+
+ // Create market panel (exact layout from Python)
+ const createMarketPanel = (title: string, data: string[][]) => (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ width: '500px',
+ height: '250px',
+ margin: '5px',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Panel Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_ORANGE,
+ padding: '8px',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ textAlign: 'center',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ {title.toUpperCase()}
+ </div>
+
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '4px 8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div>SYMBOL</div>
+ <div style={{ textAlign: 'right' }}>PRICE</div>
+ <div style={{ textAlign: 'right' }}>CHANGE</div>
+ <div style={{ textAlign: 'right' }}>%CHG</div>
+ <div style={{ textAlign: 'right' }}>7D</div>
+ <div style={{ textAlign: 'right' }}>30D</div>
+ </div>
+
+ {/* Data Rows */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {data.map((row, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '2px 8px',
+ fontSize: '10px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ minHeight: '18px',
+ alignItems: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[1]}</div>
+ <div style={{
+ color: row[2].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[2]}</div>
+ <div style={{
+ color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[3]}</div>
+ <div style={{
+ color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[4]}</div>
+ <div style={{
+ color: row[5].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[5]}</div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+
+ // Create regional panel (exact layout from Python)
+ const createRegionalPanel = (title: string, data: string[][]) => (
+ <div style={{
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ width: '500px',
+ height: '280px',
+ margin: '5px',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Panel Header */}
+ <div style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_ORANGE,
+ padding: '8px',
+ fontSize: '14px',
+ fontWeight: 'bold',
+ textAlign: 'center',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ {title.toUpperCase()} - LIVE DATA
+ </div>
+
+ {/* Table Header */}
+ <div style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '4px 8px',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontSize: '12px',
+ fontWeight: 'bold',
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`
+ }}>
+ <div>SYMBOL</div>
+ <div>NAME</div>
+ <div style={{ textAlign: 'right' }}>PRICE</div>
+ <div style={{ textAlign: 'right' }}>CHANGE</div>
+ <div style={{ textAlign: 'right' }}>%CHG</div>
+ </div>
+
+ {/* Data Rows */}
+ <div style={{ flex: 1, overflow: 'auto' }}>
+ {data.map((row, index) => (
+ <div key={index} style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 2fr 1fr 1fr 1fr',
+ gap: '4px',
+ padding: '2px 8px',
+ fontSize: '10px',
+ backgroundColor: index % 2 === 0 ? 'rgba(255,255,255,0.05)' : 'transparent',
+ borderBottom: `1px solid rgba(120,120,120,0.3)`,
+ minHeight: '18px',
+ alignItems: 'center'
+ }}>
+ <div style={{ color: BLOOMBERG_WHITE }}>{row[0]}</div>
+ <div style={{ color: BLOOMBERG_WHITE, overflow: 'hidden', textOverflow: 'ellipsis' }}>{row[1]}</div>
+ <div style={{ color: BLOOMBERG_WHITE, textAlign: 'right' }}>{row[2]}</div>
+ <div style={{
+ color: row[3].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[3]}</div>
+ <div style={{
+ color: row[4].startsWith('+') ? BLOOMBERG_GREEN : BLOOMBERG_RED,
+ textAlign: 'right'
+ }}>{row[4]}</div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+
+ const categories = Object.keys(marketData);
+
+ return (
+ <div style={{
+ height: '100%',
+ backgroundColor: BLOOMBERG_DARK_BG,
+ color: BLOOMBERG_WHITE,
+ fontFamily: 'Consolas, monospace',
+ overflow: 'hidden',
+ display: 'flex',
+ flexDirection: 'column'
+ }}>
+ {/* Header Bar (exact from Python) */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ fontSize: '13px'
+ }}>
+ <span style={{ color: BLOOMBERG_ORANGE, fontWeight: 'bold' }}>FINCEPT</span>
+ <span style={{ color: BLOOMBERG_WHITE, marginLeft: '8px' }}>MARKET TERMINAL</span>
+ <span style={{ color: BLOOMBERG_GRAY, margin: '0 8px' }}>|</span>
+ <input
+ type="text"
+ defaultValue="Search Symbol"
+ style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ width: '200px',
+ fontSize: '11px'
+ }}
+ />
+ <button style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ marginLeft: '8px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ width: '80px'
+ }}>
+ SEARCH
+ </button>
+ <span style={{ color: BLOOMBERG_GRAY, margin: '0 8px' }}>|</span>
+ <span style={{ color: BLOOMBERG_WHITE }}>
+ {currentTime.toISOString().replace('T', ' ').substring(0, 19)}
+ </span>
+ </div>
+
+ {/* Control Panel (exact from Python) */}
+ <div style={{
+ display: 'flex',
+ alignItems: 'center',
+ padding: '8px 12px',
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ borderBottom: `1px solid ${BLOOMBERG_GRAY}`,
+ fontSize: '12px'
+ }}>
+ <button
+ onClick={() => { setIsUpdating(true); setLastUpdate(new Date()); setTimeout(() => setIsUpdating(false), 1000); }}
+ style={{
+ backgroundColor: BLOOMBERG_ORANGE,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ marginRight: '8px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ width: '80px'
+ }}
+ >
+ REFRESH
+ </button>
+ <button
+ onClick={() => setAutoUpdate(!autoUpdate)}
+ style={{
+ backgroundColor: autoUpdate ? BLOOMBERG_GREEN : BLOOMBERG_GRAY,
+ color: 'black',
+ border: 'none',
+ padding: '4px 12px',
+ marginRight: '8px',
+ fontSize: '11px',
+ fontWeight: 'bold',
+ width: '80px'
+ }}
+ >
+ AUTO {autoUpdate ? 'ON' : 'OFF'}
+ </button>
+ <select style={{
+ backgroundColor: BLOOMBERG_DARK_BG,
+ border: `1px solid ${BLOOMBERG_GRAY}`,
+ color: BLOOMBERG_WHITE,
+ padding: '4px 8px',
+ fontSize: '11px',
+ width: '80px',
+ marginRight: '8px'
+ }}>
+ <option>1 min</option>
+ <option>5 min</option>
+ <option selected>10 min</option>
+ <option>30 min</option>
+ </select>
+ <span style={{ color: BLOOMBERG_GRAY, margin: '0 8px' }}>|</span>
+ <span style={{ color: BLOOMBERG_GRAY }}>LAST UPDATE:</span>
+ <span style={{ color: BLOOMBERG_WHITE, marginLeft: '8px' }}>
+ {lastUpdate.toTimeString().substring(0, 8)}
+ </span>
+ <span style={{ color: BLOOMBERG_GRAY, margin: '0 8px' }}>|</span>
+ <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN }}>●</span>
+ <span style={{ color: isUpdating ? BLOOMBERG_ORANGE : BLOOMBERG_GREEN, marginLeft: '8px' }}>
+ {isUpdating ? 'UPDATING' : 'LIVE'}
+ </span>
+ </div>
+
+ {/* Main Content */}
+ <div style={{ flex: 1, overflow: 'auto', padding: '8px' }}>
+ {/* Global Markets Section */}
+ <div style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ GLOBAL MARKETS
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* 3x2 Market Grid (exact from Python) */}
+ <div>
+ {/* First row - 3 categories */}
+ <div style={{ display: 'flex' }}>
+ {categories.slice(0, 3).map(category =>
+ createMarketPanel(category, marketData[category])
+ )}
+ </div>
+
+ <div style={{ height: '10px' }}></div>
+
+ {/* Second row - 3 categories */}
+ <div style={{ display: 'flex' }}>
+ {categories.slice(3, 6).map(category =>
+ createMarketPanel(category, marketData[category])
+ )}
+ </div>
+ </div>
+
+ <div style={{ height: '20px' }}></div>
+
+ {/* Regional Markets Section */}
+ <div style={{
+ color: BLOOMBERG_ORANGE,
+ fontSize: '14px',
+ fontWeight: 'bold',
+ marginBottom: '8px'
+ }}>
+ REGIONAL MARKETS - LIVE DATA
+ </div>
+ <div style={{ borderBottom: `1px solid ${BLOOMBERG_GRAY}`, marginBottom: '12px' }}></div>
+
+ {/* Regional Panels (exact from Python) */}
+ <div style={{ display: 'flex' }}>
+ {Object.keys(regionalData).map(region =>
+ createRegionalPanel(region, regionalData[region])
+ )}
+ </div>
+ </div>
+
+ {/* Status Bar */}
+ <div style={{
+ borderTop: `1px solid ${BLOOMBERG_GRAY}`,
+ backgroundColor: BLOOMBERG_PANEL_BG,
+ padding: '4px 12px',
+ fontSize: '10px',
+ color: BLOOMBERG_GRAY
+ }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>
+ <span>Data provided by Bloomberg Terminal API | Updates every 5 seconds</span>
+ <span>Connected: {Object.keys(regionalData).length} regional markets</span>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default MarketsTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
new file mode 100644
index 000000000..ec77e8e88
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/NewsTab.tsx
@@ -0,0 +1,274 @@
+import React, { useState, useEffect } from 'react';
+import { ExternalLink, Clock, TrendingUp, Globe, DollarSign, Building } from 'lucide-react';
+
+interface NewsArticle {
+ id: string;
+ title: string;
+ summary: string;
+ source: string;
+ publishedAt: string;
+ category: string;
+ url: string;
+ sentiment: 'positive' | 'negative' | 'neutral';
+}
+
+interface NewsCategory {
+ key: string;
+ label: string;
+ icon: React.ReactNode;
+ color: string;
+}
+
+const NewsTab: React.FC = () => {
+ const [activeCategory, setActiveCategory] = useState('all');
+ const [articles, setArticles] = useState<NewsArticle[]>([
+ {
+ id: '1',
+ title: 'Federal Reserve Signals Potential Rate Cut in Q2 2024',
+ summary: 'Fed officials hint at possible monetary policy adjustments as inflation shows signs of cooling across major economic indicators.',
+ source: 'Reuters',
+ publishedAt: '2 minutes ago',
+ category: 'economics',
+ url: '#',
+ sentiment: 'positive'
+ },
+ {
+ id: '2',
+ title: 'Tech Stocks Rally on AI Investment Surge',
+ summary: 'Major technology companies see significant gains as artificial intelligence investments continue to drive market optimism.',
+ source: 'Bloomberg',
+ publishedAt: '5 minutes ago',
+ category: 'technology',
+ url: '#',
+ sentiment: 'positive'
+ },
+ {
+ id: '3',
+ title: 'Oil Prices Drop on Increased Production Outlook',
+ summary: 'Crude oil futures decline as OPEC+ members signal potential production increases in response to global demand.',
+ source: 'Wall Street Journal',
+ publishedAt: '8 minutes ago',
+ category: 'commodities',
+ url: '#',
+ sentiment: 'negative'
+ },
+ {
+ id: '4',
+ title: 'European Markets Open Higher on GDP Data',
+ summary: 'European indices gain as stronger-than-expected GDP growth data boosts investor confidence in regional recovery.',
+ source: 'Financial Times',
+ publishedAt: '12 minutes ago',
+ category: 'markets',
+ url: '#',
+ sentiment: 'positive'
+ },
+ {
+ id: '5',
+ title: 'Cryptocurrency Regulation Bill Advances in Senate',
+ summary: 'Bipartisan cryptocurrency regulation framework moves forward, providing clearer guidelines for digital asset trading.',
+ source: 'CNBC',
+ publishedAt: '15 minutes ago',
+ category: 'cryptocurrency',
+ url: '#',
+ sentiment: 'neutral'
+ },
+ {
+ id: '6',
+ title: 'Banking Sector Shows Strong Q4 Earnings',
+ summary: 'Major banks report better-than-expected quarterly results, driven by higher interest margins and loan growth.',
+ source: 'MarketWatch',
+ publishedAt: '18 minutes ago',
+ category: 'banking',
+ url: '#',
+ sentiment: 'positive'
+ },
+ {
+ id: '7',
+ title: 'Supply Chain Disruptions Impact Manufacturing',
+ summary: 'Global manufacturing faces headwinds as supply chain bottlenecks persist in key industrial sectors.',
+ source: 'Associated Press',
+ publishedAt: '22 minutes ago',
+ category: 'economics',
+ url: '#',
+ sentiment: 'negative'
+ },
+ {
+ id: '8',
+ title: 'Green Energy Investments Reach Record High',
+ summary: 'Renewable energy sector attracts unprecedented investment levels as governments accelerate clean energy transitions.',
+ source: 'Reuters',
+ publishedAt: '25 minutes ago',
+ category: 'energy',
+ url: '#',
+ sentiment: 'positive'
+ }
+ ]);
+
+ const categories: NewsCategory[] = [
+ { key: 'all', label: 'ALL NEWS', icon: <Globe size={16} />, color: 'text-blue-400' },
+ { key: 'markets', label: 'MARKETS', icon: <TrendingUp size={16} />, color: 'text-green-400' },
+ { key: 'economics', label: 'ECONOMICS', icon: <DollarSign size={16} />, color: 'text-yellow-400' },
+ { key: 'technology', label: 'TECHNOLOGY', icon: <Building size={16} />, color: 'text-purple-400' },
+ { key: 'banking', label: 'BANKING', icon: <Building size={16} />, color: 'text-orange-400' },
+ { key: 'commodities', label: 'COMMODITIES', icon: <TrendingUp size={16} />, color: 'text-red-400' },
+ { key: 'cryptocurrency', label: 'CRYPTO', icon: <DollarSign size={16} />, color: 'text-cyan-400' },
+ { key: 'energy', label: 'ENERGY', icon: <Globe size={16} />, color: 'text-emerald-400' }
+ ];
+
+ const [lastUpdated, setLastUpdated] = useState(new Date());
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setLastUpdated(new Date());
+ }, 30000);
+
+ return () => clearInterval(timer);
+ }, []);
+
+ const filteredArticles = activeCategory === 'all'
+ ? articles
+ : articles.filter(article => article.category === activeCategory);
+
+ const getSentimentColor = (sentiment: string) => {
+ switch (sentiment) {
+ case 'positive': return 'text-green-400';
+ case 'negative': return 'text-red-400';
+ default: return 'text-gray-400';
+ }
+ };
+
+ const getSentimentIndicator = (sentiment: string) => {
+ switch (sentiment) {
+ case 'positive': return '↗';
+ case 'negative': return '↘';
+ default: return '→';
+ }
+ };
+
+ return (
+ <div className="h-full bg-black text-white flex flex-col">
+ {/* Category Navigation */}
+ <div className="bg-gray-900 border-b border-gray-700 p-2">
+ <div className="flex flex-wrap gap-2">
+ {categories.map((category) => (
+ <button
+ key={category.key}
+ onClick={() => setActiveCategory(category.key)}
+ className={`flex items-center gap-2 px-3 py-2 text-sm font-medium rounded transition-colors ${
+ activeCategory === category.key
+ ? 'bg-orange-600 text-white'
+ : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
+ }`}
+ >
+ <span className={category.color}>{category.icon}</span>
+ <span>{category.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Header */}
+ <div className="bg-gray-800 border-b border-gray-700 p-4">
+ <div className="flex justify-between items-center">
+ <h1 className="text-xl font-bold text-orange-500">
+ FINANCIAL NEWS ANALYSIS
+ </h1>
+ <div className="flex items-center gap-4 text-sm text-gray-400">
+ <div className="flex items-center gap-1">
+ <Clock size={14} />
+ <span>Last Updated: {lastUpdated.toLocaleTimeString()}</span>
+ </div>
+ <div className="text-green-400">● LIVE FEED</div>
+ </div>
+ </div>
+ </div>
+
+ {/* News Counter */}
+ <div className="bg-gray-900 border-b border-gray-700 p-3">
+ <div className="flex justify-between items-center text-sm">
+ <div>
+ <span className="text-gray-400">Showing </span>
+ <span className="text-white font-semibold">{filteredArticles.length}</span>
+ <span className="text-gray-400"> articles</span>
+ {activeCategory !== 'all' && (
+ <>
+ <span className="text-gray-400"> in </span>
+ <span className="text-orange-400">
+ {categories.find(c => c.key === activeCategory)?.label}
+ </span>
+ </>
+ )}
+ </div>
+ <div className="flex gap-4">
+ <span className="text-gray-400">Positive: </span>
+ <span className="text-green-400">{articles.filter(a => a.sentiment === 'positive').length}</span>
+ <span className="text-gray-400">Negative: </span>
+ <span className="text-red-400">{articles.filter(a => a.sentiment === 'negative').length}</span>
+ </div>
+ </div>
+ </div>
+
+ {/* News Articles */}
+ <div className="flex-1 overflow-y-auto">
+ <div className="p-4 space-y-4">
+ {filteredArticles.map((article) => (
+ <div
+ key={article.id}
+ className="bg-gray-900 border border-gray-700 rounded-lg p-4 hover:bg-gray-800 transition-colors"
+ >
+ <div className="flex justify-between items-start mb-2">
+ <div className="flex items-center gap-2">
+ <span className={`font-semibold ${getSentimentColor(article.sentiment)}`}>
+ {getSentimentIndicator(article.sentiment)}
+ </span>
+ <span className="text-sm font-medium text-orange-400 uppercase">
+ {article.category}
+ </span>
+ </div>
+ <div className="flex items-center gap-2 text-sm text-gray-400">
+ <span>{article.source}</span>
+ <span>•</span>
+ <span>{article.publishedAt}</span>
+ </div>
+ </div>
+
+ <h3 className="text-lg font-semibold text-white mb-2 hover:text-orange-400 cursor-pointer">
+ {article.title}
+ </h3>
+
+ <p className="text-gray-300 text-sm mb-3 leading-relaxed">
+ {article.summary}
+ </p>
+
+ <div className="flex justify-between items-center">
+ <div className="flex items-center gap-4">
+ <span className={`text-sm font-medium ${getSentimentColor(article.sentiment)}`}>
+ {article.sentiment.toUpperCase()}
+ </span>
+ </div>
+ <button className="flex items-center gap-1 text-sm text-orange-400 hover:text-orange-300 transition-colors">
+ <span>Read More</span>
+ <ExternalLink size={14} />
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <div className="bg-gray-900 border-t border-gray-700 p-3">
+ <div className="flex justify-between items-center text-sm">
+ <div className="text-gray-400">
+ News sources: Reuters, Bloomberg, WSJ, FT, CNBC, MarketWatch, AP
+ </div>
+ <div className="text-gray-400">
+ Auto-refresh: 30s
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default NewsTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx b/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx
new file mode 100644
index 000000000..51052a121
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/WatchlistTab.tsx
@@ -0,0 +1,393 @@
+import React, { useState, useEffect } from 'react';
+import { Plus, Trash2, Star, TrendingUp, TrendingDown, AlertTriangle, Settings } from 'lucide-react';
+
+interface WatchlistItem {
+ id: string;
+ symbol: string;
+ name: string;
+ price: string;
+ change: string;
+ changePercent: string;
+ volume: string;
+ marketCap: string;
+ pe: string;
+ isPositive: boolean;
+ isFavorite: boolean;
+ alerts: number;
+}
+
+interface Watchlist {
+ id: string;
+ name: string;
+ items: WatchlistItem[];
+ color: string;
+}
+
+const WatchlistTab: React.FC = () => {
+ const [activeWatchlist, setActiveWatchlist] = useState('portfolio');
+ const [watchlists, setWatchlists] = useState<Record<string, Watchlist>>({
+ portfolio: {
+ id: 'portfolio',
+ name: 'My Portfolio',
+ color: 'text-green-400',
+ items: [
+ {
+ id: '1',
+ symbol: 'AAPL',
+ name: 'Apple Inc.',
+ price: '$175.43',
+ change: '+2.34',
+ changePercent: '+1.35%',
+ volume: '45.2M',
+ marketCap: '2.7T',
+ pe: '28.4',
+ isPositive: true,
+ isFavorite: true,
+ alerts: 2
+ },
+ {
+ id: '2',
+ symbol: 'MSFT',
+ name: 'Microsoft Corporation',
+ price: '$334.89',
+ change: '+4.12',
+ changePercent: '+1.24%',
+ volume: '28.7M',
+ marketCap: '2.5T',
+ pe: '32.1',
+ isPositive: true,
+ isFavorite: true,
+ alerts: 0
+ },
+ {
+ id: '3',
+ symbol: 'GOOGL',
+ name: 'Alphabet Inc.',
+ price: '$134.56',
+ change: '-1.23',
+ changePercent: '-0.91%',
+ volume: '32.1M',
+ marketCap: '1.7T',
+ pe: '24.8',
+ isPositive: false,
+ isFavorite: false,
+ alerts: 1
+ }
+ ]
+ },
+ watchlist1: {
+ id: 'watchlist1',
+ name: 'Tech Giants',
+ color: 'text-blue-400',
+ items: [
+ {
+ id: '4',
+ symbol: 'TSLA',
+ name: 'Tesla Inc.',
+ price: '$201.78',
+ change: '-5.67',
+ changePercent: '-2.73%',
+ volume: '67.4M',
+ marketCap: '641B',
+ pe: '45.6',
+ isPositive: false,
+ isFavorite: true,
+ alerts: 3
+ },
+ {
+ id: '5',
+ symbol: 'NVDA',
+ name: 'NVIDIA Corporation',
+ price: '$478.23',
+ change: '+12.45',
+ changePercent: '+2.67%',
+ volume: '52.3M',
+ marketCap: '1.2T',
+ pe: '78.9',
+ isPositive: true,
+ isFavorite: true,
+ alerts: 0
+ },
+ {
+ id: '6',
+ symbol: 'AMZN',
+ name: 'Amazon.com Inc.',
+ price: '$145.32',
+ change: '+1.89',
+ changePercent: '+1.32%',
+ volume: '41.8M',
+ marketCap: '1.5T',
+ pe: '58.3',
+ isPositive: true,
+ isFavorite: false,
+ alerts: 1
+ }
+ ]
+ },
+ watchlist2: {
+ id: 'watchlist2',
+ name: 'Energy Sector',
+ color: 'text-yellow-400',
+ items: [
+ {
+ id: '7',
+ symbol: 'XOM',
+ name: 'Exxon Mobil Corporation',
+ price: '$108.45',
+ change: '+2.34',
+ changePercent: '+2.20%',
+ volume: '18.5M',
+ marketCap: '458B',
+ pe: '14.2',
+ isPositive: true,
+ isFavorite: false,
+ alerts: 0
+ },
+ {
+ id: '8',
+ symbol: 'CVX',
+ name: 'Chevron Corporation',
+ price: '$159.78',
+ change: '+1.23',
+ changePercent: '+0.78%',
+ volume: '12.3M',
+ marketCap: '298B',
+ pe: '13.8',
+ isPositive: true,
+ isFavorite: false,
+ alerts: 1
+ }
+ ]
+ }
+ });
+
+ const [sortBy, setSortBy] = useState('symbol');
+ const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
+ const [lastUpdated, setLastUpdated] = useState(new Date());
+
+ useEffect(() => {
+ const timer = setInterval(() => {
+ setLastUpdated(new Date());
+ }, 5000);
+
+ return () => clearInterval(timer);
+ }, []);
+
+ const currentWatchlist = watchlists[activeWatchlist];
+
+ const toggleFavorite = (itemId: string) => {
+ setWatchlists(prev => ({
+ ...prev,
+ [activeWatchlist]: {
+ ...prev[activeWatchlist],
+ items: prev[activeWatchlist].items.map(item =>
+ item.id === itemId ? { ...item, isFavorite: !item.isFavorite } : item
+ )
+ }
+ }));
+ };
+
+ const removeFromWatchlist = (itemId: string) => {
+ setWatchlists(prev => ({
+ ...prev,
+ [activeWatchlist]: {
+ ...prev[activeWatchlist],
+ items: prev[activeWatchlist].items.filter(item => item.id !== itemId)
+ }
+ }));
+ };
+
+ const sortedItems = [...currentWatchlist.items].sort((a, b) => {
+ let aValue = a[sortBy as keyof WatchlistItem];
+ let bValue = b[sortBy as keyof WatchlistItem];
+
+ if (sortBy === 'price' || sortBy === 'change') {
+ aValue = parseFloat(aValue.toString().replace(/[$+,%]/g, ''));
+ bValue = parseFloat(bValue.toString().replace(/[$+,%]/g, ''));
+ }
+
+ const comparison = aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
+ return sortOrder === 'asc' ? comparison : -comparison;
+ });
+
+ const handleSort = (column: string) => {
+ if (sortBy === column) {
+ setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
+ } else {
+ setSortBy(column);
+ setSortOrder('asc');
+ }
+ };
+
+ return (
+ <div className="h-full bg-black text-white flex flex-col">
+ {/* Watchlist Navigation */}
+ <div className="bg-gray-900 border-b border-gray-700 p-2">
+ <div className="flex items-center justify-between">
+ <div className="flex gap-2">
+ {Object.values(watchlists).map((watchlist) => (
+ <button
+ key={watchlist.id}
+ onClick={() => setActiveWatchlist(watchlist.id)}
+ className={`px-4 py-2 text-sm font-medium rounded transition-colors ${
+ activeWatchlist === watchlist.id
+ ? 'bg-orange-600 text-white'
+ : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
+ }`}
+ >
+ <span className={watchlist.color}>●</span>
+ <span className="ml-2">{watchlist.name}</span>
+ <span className="ml-1 text-xs text-gray-400">({watchlist.items.length})</span>
+ </button>
+ ))}
+ </div>
+ <button className="flex items-center gap-2 px-3 py-2 bg-orange-600 text-white text-sm font-medium rounded hover:bg-orange-700 transition-colors">
+ <Plus size={16} />
+ <span>Add Symbol</span>
+ </button>
+ </div>
+ </div>
+
+ {/* Header */}
+ <div className="bg-gray-800 border-b border-gray-700 p-4">
+ <div className="flex justify-between items-center">
+ <div>
+ <h1 className="text-xl font-bold text-orange-500">
+ {currentWatchlist.name.toUpperCase()}
+ </h1>
+ <div className="text-sm text-gray-400 mt-1">
+ {currentWatchlist.items.length} securities •
+ {currentWatchlist.items.filter(item => item.isPositive).length} gaining •
+ {currentWatchlist.items.filter(item => !item.isPositive).length} declining
+ </div>
+ </div>
+ <div className="flex items-center gap-4 text-sm text-gray-400">
+ <span>Last Updated: {lastUpdated.toLocaleTimeString()}</span>
+ <div className="text-green-400">● LIVE</div>
+ </div>
+ </div>
+ </div>
+
+ {/* Controls */}
+ <div className="bg-gray-900 border-b border-gray-700 p-3">
+ <div className="flex justify-between items-center">
+ <div className="flex items-center gap-4">
+ <span className="text-sm text-gray-400">Sort by:</span>
+ <select
+ value={sortBy}
+ onChange={(e) => setSortBy(e.target.value)}
+ className="bg-gray-800 border border-gray-600 rounded px-2 py-1 text-sm text-white"
+ >
+ <option value="symbol">Symbol</option>
+ <option value="price">Price</option>
+ <option value="change">Change</option>
+ <option value="changePercent">% Change</option>
+ <option value="volume">Volume</option>
+ </select>
+ <button
+ onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}
+ className="text-sm text-orange-400 hover:text-orange-300"
+ >
+ {sortOrder === 'asc' ? '↑' : '↓'}
+ </button>
+ </div>
+ <div className="flex items-center gap-2">
+ <button className="flex items-center gap-1 px-2 py-1 bg-gray-800 text-sm text-gray-300 rounded hover:bg-gray-700">
+ <Settings size={14} />
+ <span>Settings</span>
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Table Header */}
+ <div className="bg-gray-900 border-b border-gray-700 p-3">
+ <div className="grid grid-cols-9 gap-4 text-sm font-semibold text-gray-300">
+ <div className="cursor-pointer hover:text-white" onClick={() => handleSort('symbol')}>
+ SYMBOL
+ </div>
+ <div>NAME</div>
+ <div className="text-right cursor-pointer hover:text-white" onClick={() => handleSort('price')}>
+ PRICE
+ </div>
+ <div className="text-right cursor-pointer hover:text-white" onClick={() => handleSort('change')}>
+ CHANGE
+ </div>
+ <div className="text-right cursor-pointer hover:text-white" onClick={() => handleSort('changePercent')}>
+ % CHANGE
+ </div>
+ <div className="text-right cursor-pointer hover:text-white" onClick={() => handleSort('volume')}>
+ VOLUME
+ </div>
+ <div className="text-right">MKT CAP</div>
+ <div className="text-right">P/E</div>
+ <div className="text-center">ACTIONS</div>
+ </div>
+ </div>
+
+ {/* Watchlist Items */}
+ <div className="flex-1 overflow-y-auto">
+ <div className="p-3 space-y-1">
+ {sortedItems.map((item) => (
+ <div
+ key={item.id}
+ className="grid grid-cols-9 gap-4 py-3 px-2 rounded hover:bg-gray-900 transition-colors border-b border-gray-800"
+ >
+ <div className="flex items-center gap-2">
+ <span className="font-semibold text-white">{item.symbol}</span>
+ {item.alerts > 0 && (
+ <div className="flex items-center gap-1">
+ <AlertTriangle size={14} className="text-yellow-400" />
+ <span className="text-xs text-yellow-400">{item.alerts}</span>
+ </div>
+ )}
+ </div>
+ <div className="text-sm text-gray-300 truncate">{item.name}</div>
+ <div className="text-right font-mono">{item.price}</div>
+ <div className={`text-right font-mono ${item.isPositive ? 'text-green-400' : 'text-red-400'}`}>
+ {item.change}
+ </div>
+ <div className={`text-right font-mono flex items-center justify-end gap-1 ${item.isPositive ? 'text-green-400' : 'text-red-400'}`}>
+ {item.isPositive ? <TrendingUp size={14} /> : <TrendingDown size={14} />}
+ {item.changePercent}
+ </div>
+ <div className="text-right text-gray-400">{item.volume}</div>
+ <div className="text-right text-gray-400">{item.marketCap}</div>
+ <div className="text-right text-gray-400">{item.pe}</div>
+ <div className="flex justify-center items-center gap-2">
+ <button
+ onClick={() => toggleFavorite(item.id)}
+ className={`p-1 rounded transition-colors ${
+ item.isFavorite ? 'text-yellow-400 hover:text-yellow-300' : 'text-gray-400 hover:text-yellow-400'
+ }`}
+ >
+ <Star size={14} fill={item.isFavorite ? 'currentColor' : 'none'} />
+ </button>
+ <button
+ onClick={() => removeFromWatchlist(item.id)}
+ className="p-1 text-gray-400 hover:text-red-400 transition-colors"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <div className="bg-gray-900 border-t border-gray-700 p-3">
+ <div className="flex justify-between items-center text-sm">
+ <div className="text-gray-400">
+ Portfolio Value: $1,234,567.89 | Daily P&L: +$23,456.78 (+1.89%)
+ </div>
+ <div className="text-gray-400">
+ Auto-refresh: 5s
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default WatchlistTab;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/components/ui/accordion.tsx b/fincept-terminal-desktop/src/components/ui/accordion.tsx
new file mode 100644
index 000000000..d21b65f7a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/accordion.tsx
@@ -0,0 +1,64 @@
+import * as React from "react"
+import * as AccordionPrimitive from "@radix-ui/react-accordion"
+import { ChevronDownIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Accordion({
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
+ return <AccordionPrimitive.Root data-slot="accordion" {...props} />
+}
+
+function AccordionItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
+ return (
+ <AccordionPrimitive.Item
+ data-slot="accordion-item"
+ className={cn("border-b last:border-b-0", className)}
+ {...props}
+ />
+ )
+}
+
+function AccordionTrigger({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
+ return (
+ <AccordionPrimitive.Header className="flex">
+ <AccordionPrimitive.Trigger
+ data-slot="accordion-trigger"
+ className={cn(
+ "focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
+ </AccordionPrimitive.Trigger>
+ </AccordionPrimitive.Header>
+ )
+}
+
+function AccordionContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
+ return (
+ <AccordionPrimitive.Content
+ data-slot="accordion-content"
+ className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
+ {...props}
+ >
+ <div className={cn("pt-0 pb-4", className)}>{children}</div>
+ </AccordionPrimitive.Content>
+ )
+}
+
+export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
diff --git a/fincept-terminal-desktop/src/components/ui/alert-dialog.tsx b/fincept-terminal-desktop/src/components/ui/alert-dialog.tsx
new file mode 100644
index 000000000..0863e40d9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/alert-dialog.tsx
@@ -0,0 +1,157 @@
+"use client"
+
+import * as React from "react"
+import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
+
+import { cn } from "@/lib/utils"
+import { buttonVariants } from "@/components/ui/button"
+
+function AlertDialog({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
+ return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
+}
+
+function AlertDialogTrigger({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
+ return (
+ <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
+ )
+}
+
+function AlertDialogPortal({
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
+ return (
+ <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
+ )
+}
+
+function AlertDialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
+ return (
+ <AlertDialogPrimitive.Overlay
+ data-slot="alert-dialog-overlay"
+ className={cn(
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
+ return (
+ <AlertDialogPortal>
+ <AlertDialogOverlay />
+ <AlertDialogPrimitive.Content
+ data-slot="alert-dialog-content"
+ className={cn(
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
+ className
+ )}
+ {...props}
+ />
+ </AlertDialogPortal>
+ )
+}
+
+function AlertDialogHeader({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-header"
+ className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogFooter({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="alert-dialog-footer"
+ className={cn(
+ "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
+ return (
+ <AlertDialogPrimitive.Title
+ data-slot="alert-dialog-title"
+ className={cn("text-lg font-semibold", className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
+ return (
+ <AlertDialogPrimitive.Description
+ data-slot="alert-dialog-description"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogAction({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
+ return (
+ <AlertDialogPrimitive.Action
+ className={cn(buttonVariants(), className)}
+ {...props}
+ />
+ )
+}
+
+function AlertDialogCancel({
+ className,
+ ...props
+}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
+ return (
+ <AlertDialogPrimitive.Cancel
+ className={cn(buttonVariants({ variant: "outline" }), className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ AlertDialog,
+ AlertDialogPortal,
+ AlertDialogOverlay,
+ AlertDialogTrigger,
+ AlertDialogContent,
+ AlertDialogHeader,
+ AlertDialogFooter,
+ AlertDialogTitle,
+ AlertDialogDescription,
+ AlertDialogAction,
+ AlertDialogCancel,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/aspect-ratio.tsx b/fincept-terminal-desktop/src/components/ui/aspect-ratio.tsx
new file mode 100644
index 000000000..3df3fd02a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/aspect-ratio.tsx
@@ -0,0 +1,11 @@
+"use client"
+
+import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"
+
+function AspectRatio({
+ ...props
+}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
+ return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
+}
+
+export { AspectRatio }
diff --git a/fincept-terminal-desktop/src/components/ui/breadcrumb.tsx b/fincept-terminal-desktop/src/components/ui/breadcrumb.tsx
new file mode 100644
index 000000000..eb88f3212
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/breadcrumb.tsx
@@ -0,0 +1,109 @@
+import * as React from "react"
+import { Slot } from "@radix-ui/react-slot"
+import { ChevronRight, MoreHorizontal } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
+ return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />
+}
+
+function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
+ return (
+ <ol
+ data-slot="breadcrumb-list"
+ className={cn(
+ "text-muted-foreground flex flex-wrap items-center gap-1.5 text-sm break-words sm:gap-2.5",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="breadcrumb-item"
+ className={cn("inline-flex items-center gap-1.5", className)}
+ {...props}
+ />
+ )
+}
+
+function BreadcrumbLink({
+ asChild,
+ className,
+ ...props
+}: React.ComponentProps<"a"> & {
+ asChild?: boolean
+}) {
+ const Comp = asChild ? Slot : "a"
+
+ return (
+ <Comp
+ data-slot="breadcrumb-link"
+ className={cn("hover:text-foreground transition-colors", className)}
+ {...props}
+ />
+ )
+}
+
+function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="breadcrumb-page"
+ role="link"
+ aria-disabled="true"
+ aria-current="page"
+ className={cn("text-foreground font-normal", className)}
+ {...props}
+ />
+ )
+}
+
+function BreadcrumbSeparator({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="breadcrumb-separator"
+ role="presentation"
+ aria-hidden="true"
+ className={cn("[&>svg]:size-3.5", className)}
+ {...props}
+ >
+ {children ?? <ChevronRight />}
+ </li>
+ )
+}
+
+function BreadcrumbEllipsis({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="breadcrumb-ellipsis"
+ role="presentation"
+ aria-hidden="true"
+ className={cn("flex size-9 items-center justify-center", className)}
+ {...props}
+ >
+ <MoreHorizontal className="size-4" />
+ <span className="sr-only">More</span>
+ </span>
+ )
+}
+
+export {
+ Breadcrumb,
+ BreadcrumbList,
+ BreadcrumbItem,
+ BreadcrumbLink,
+ BreadcrumbPage,
+ BreadcrumbSeparator,
+ BreadcrumbEllipsis,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/calendar.tsx b/fincept-terminal-desktop/src/components/ui/calendar.tsx
new file mode 100644
index 000000000..5f62ae943
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/calendar.tsx
@@ -0,0 +1,211 @@
+import * as React from "react"
+import {
+ ChevronDownIcon,
+ ChevronLeftIcon,
+ ChevronRightIcon,
+} from "lucide-react"
+import { DayButton, DayPicker, getDefaultClassNames } from "react-day-picker"
+
+import { cn } from "@/lib/utils"
+import { Button, buttonVariants } from "@/components/ui/button"
+
+function Calendar({
+ className,
+ classNames,
+ showOutsideDays = true,
+ captionLayout = "label",
+ buttonVariant = "ghost",
+ formatters,
+ components,
+ ...props
+}: React.ComponentProps<typeof DayPicker> & {
+ buttonVariant?: React.ComponentProps<typeof Button>["variant"]
+}) {
+ const defaultClassNames = getDefaultClassNames()
+
+ return (
+ <DayPicker
+ showOutsideDays={showOutsideDays}
+ className={cn(
+ "bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
+ String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
+ String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
+ className
+ )}
+ captionLayout={captionLayout}
+ formatters={{
+ formatMonthDropdown: (date) =>
+ date.toLocaleString("default", { month: "short" }),
+ ...formatters,
+ }}
+ classNames={{
+ root: cn("w-fit", defaultClassNames.root),
+ months: cn(
+ "flex gap-4 flex-col md:flex-row relative",
+ defaultClassNames.months
+ ),
+ month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
+ nav: cn(
+ "flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
+ defaultClassNames.nav
+ ),
+ button_previous: cn(
+ buttonVariants({ variant: buttonVariant }),
+ "size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
+ defaultClassNames.button_previous
+ ),
+ button_next: cn(
+ buttonVariants({ variant: buttonVariant }),
+ "size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
+ defaultClassNames.button_next
+ ),
+ month_caption: cn(
+ "flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
+ defaultClassNames.month_caption
+ ),
+ dropdowns: cn(
+ "w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
+ defaultClassNames.dropdowns
+ ),
+ dropdown_root: cn(
+ "relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
+ defaultClassNames.dropdown_root
+ ),
+ dropdown: cn(
+ "absolute bg-popover inset-0 opacity-0",
+ defaultClassNames.dropdown
+ ),
+ caption_label: cn(
+ "select-none font-medium",
+ captionLayout === "label"
+ ? "text-sm"
+ : "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
+ defaultClassNames.caption_label
+ ),
+ table: "w-full border-collapse",
+ weekdays: cn("flex", defaultClassNames.weekdays),
+ weekday: cn(
+ "text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
+ defaultClassNames.weekday
+ ),
+ week: cn("flex w-full mt-2", defaultClassNames.week),
+ week_number_header: cn(
+ "select-none w-(--cell-size)",
+ defaultClassNames.week_number_header
+ ),
+ week_number: cn(
+ "text-[0.8rem] select-none text-muted-foreground",
+ defaultClassNames.week_number
+ ),
+ day: cn(
+ "relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
+ defaultClassNames.day
+ ),
+ range_start: cn(
+ "rounded-l-md bg-accent",
+ defaultClassNames.range_start
+ ),
+ range_middle: cn("rounded-none", defaultClassNames.range_middle),
+ range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
+ today: cn(
+ "bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
+ defaultClassNames.today
+ ),
+ outside: cn(
+ "text-muted-foreground aria-selected:text-muted-foreground",
+ defaultClassNames.outside
+ ),
+ disabled: cn(
+ "text-muted-foreground opacity-50",
+ defaultClassNames.disabled
+ ),
+ hidden: cn("invisible", defaultClassNames.hidden),
+ ...classNames,
+ }}
+ components={{
+ Root: ({ className, rootRef, ...props }) => {
+ return (
+ <div
+ data-slot="calendar"
+ ref={rootRef}
+ className={cn(className)}
+ {...props}
+ />
+ )
+ },
+ Chevron: ({ className, orientation, ...props }) => {
+ if (orientation === "left") {
+ return (
+ <ChevronLeftIcon className={cn("size-4", className)} {...props} />
+ )
+ }
+
+ if (orientation === "right") {
+ return (
+ <ChevronRightIcon
+ className={cn("size-4", className)}
+ {...props}
+ />
+ )
+ }
+
+ return (
+ <ChevronDownIcon className={cn("size-4", className)} {...props} />
+ )
+ },
+ DayButton: CalendarDayButton,
+ WeekNumber: ({ children, ...props }) => {
+ return (
+ <td {...props}>
+ <div className="flex size-(--cell-size) items-center justify-center text-center">
+ {children}
+ </div>
+ </td>
+ )
+ },
+ ...components,
+ }}
+ {...props}
+ />
+ )
+}
+
+function CalendarDayButton({
+ className,
+ day,
+ modifiers,
+ ...props
+}: React.ComponentProps<typeof DayButton>) {
+ const defaultClassNames = getDefaultClassNames()
+
+ const ref = React.useRef<HTMLButtonElement>(null)
+ React.useEffect(() => {
+ if (modifiers.focused) ref.current?.focus()
+ }, [modifiers.focused])
+
+ return (
+ <Button
+ ref={ref}
+ variant="ghost"
+ size="icon"
+ data-day={day.date.toLocaleDateString()}
+ data-selected-single={
+ modifiers.selected &&
+ !modifiers.range_start &&
+ !modifiers.range_end &&
+ !modifiers.range_middle
+ }
+ data-range-start={modifiers.range_start}
+ data-range-end={modifiers.range_end}
+ data-range-middle={modifiers.range_middle}
+ className={cn(
+ "data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
+ defaultClassNames.day,
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export { Calendar, CalendarDayButton }
diff --git a/fincept-terminal-desktop/src/components/ui/carousel.tsx b/fincept-terminal-desktop/src/components/ui/carousel.tsx
new file mode 100644
index 000000000..0e05a77ea
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/carousel.tsx
@@ -0,0 +1,241 @@
+"use client"
+
+import * as React from "react"
+import useEmblaCarousel, {
+ type UseEmblaCarouselType,
+} from "embla-carousel-react"
+import { ArrowLeft, ArrowRight } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+
+type CarouselApi = UseEmblaCarouselType[1]
+type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
+type CarouselOptions = UseCarouselParameters[0]
+type CarouselPlugin = UseCarouselParameters[1]
+
+type CarouselProps = {
+ opts?: CarouselOptions
+ plugins?: CarouselPlugin
+ orientation?: "horizontal" | "vertical"
+ setApi?: (api: CarouselApi) => void
+}
+
+type CarouselContextProps = {
+ carouselRef: ReturnType<typeof useEmblaCarousel>[0]
+ api: ReturnType<typeof useEmblaCarousel>[1]
+ scrollPrev: () => void
+ scrollNext: () => void
+ canScrollPrev: boolean
+ canScrollNext: boolean
+} & CarouselProps
+
+const CarouselContext = React.createContext<CarouselContextProps | null>(null)
+
+function useCarousel() {
+ const context = React.useContext(CarouselContext)
+
+ if (!context) {
+ throw new Error("useCarousel must be used within a <Carousel />")
+ }
+
+ return context
+}
+
+function Carousel({
+ orientation = "horizontal",
+ opts,
+ setApi,
+ plugins,
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & CarouselProps) {
+ const [carouselRef, api] = useEmblaCarousel(
+ {
+ ...opts,
+ axis: orientation === "horizontal" ? "x" : "y",
+ },
+ plugins
+ )
+ const [canScrollPrev, setCanScrollPrev] = React.useState(false)
+ const [canScrollNext, setCanScrollNext] = React.useState(false)
+
+ const onSelect = React.useCallback((api: CarouselApi) => {
+ if (!api) return
+ setCanScrollPrev(api.canScrollPrev())
+ setCanScrollNext(api.canScrollNext())
+ }, [])
+
+ const scrollPrev = React.useCallback(() => {
+ api?.scrollPrev()
+ }, [api])
+
+ const scrollNext = React.useCallback(() => {
+ api?.scrollNext()
+ }, [api])
+
+ const handleKeyDown = React.useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (event.key === "ArrowLeft") {
+ event.preventDefault()
+ scrollPrev()
+ } else if (event.key === "ArrowRight") {
+ event.preventDefault()
+ scrollNext()
+ }
+ },
+ [scrollPrev, scrollNext]
+ )
+
+ React.useEffect(() => {
+ if (!api || !setApi) return
+ setApi(api)
+ }, [api, setApi])
+
+ React.useEffect(() => {
+ if (!api) return
+ onSelect(api)
+ api.on("reInit", onSelect)
+ api.on("select", onSelect)
+
+ return () => {
+ api?.off("select", onSelect)
+ }
+ }, [api, onSelect])
+
+ return (
+ <CarouselContext.Provider
+ value={{
+ carouselRef,
+ api: api,
+ opts,
+ orientation:
+ orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
+ scrollPrev,
+ scrollNext,
+ canScrollPrev,
+ canScrollNext,
+ }}
+ >
+ <div
+ onKeyDownCapture={handleKeyDown}
+ className={cn("relative", className)}
+ role="region"
+ aria-roledescription="carousel"
+ data-slot="carousel"
+ {...props}
+ >
+ {children}
+ </div>
+ </CarouselContext.Provider>
+ )
+}
+
+function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
+ const { carouselRef, orientation } = useCarousel()
+
+ return (
+ <div
+ ref={carouselRef}
+ className="overflow-hidden"
+ data-slot="carousel-content"
+ >
+ <div
+ className={cn(
+ "flex",
+ orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
+ className
+ )}
+ {...props}
+ />
+ </div>
+ )
+}
+
+function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
+ const { orientation } = useCarousel()
+
+ return (
+ <div
+ role="group"
+ aria-roledescription="slide"
+ data-slot="carousel-item"
+ className={cn(
+ "min-w-0 shrink-0 grow-0 basis-full",
+ orientation === "horizontal" ? "pl-4" : "pt-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function CarouselPrevious({
+ className,
+ variant = "outline",
+ size = "icon",
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ const { orientation, scrollPrev, canScrollPrev } = useCarousel()
+
+ return (
+ <Button
+ data-slot="carousel-previous"
+ variant={variant}
+ size={size}
+ className={cn(
+ "absolute size-8 rounded-full",
+ orientation === "horizontal"
+ ? "top-1/2 -left-12 -translate-y-1/2"
+ : "-top-12 left-1/2 -translate-x-1/2 rotate-90",
+ className
+ )}
+ disabled={!canScrollPrev}
+ onClick={scrollPrev}
+ {...props}
+ >
+ <ArrowLeft />
+ <span className="sr-only">Previous slide</span>
+ </Button>
+ )
+}
+
+function CarouselNext({
+ className,
+ variant = "outline",
+ size = "icon",
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ const { orientation, scrollNext, canScrollNext } = useCarousel()
+
+ return (
+ <Button
+ data-slot="carousel-next"
+ variant={variant}
+ size={size}
+ className={cn(
+ "absolute size-8 rounded-full",
+ orientation === "horizontal"
+ ? "top-1/2 -right-12 -translate-y-1/2"
+ : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
+ className
+ )}
+ disabled={!canScrollNext}
+ onClick={scrollNext}
+ {...props}
+ >
+ <ArrowRight />
+ <span className="sr-only">Next slide</span>
+ </Button>
+ )
+}
+
+export {
+ type CarouselApi,
+ Carousel,
+ CarouselContent,
+ CarouselItem,
+ CarouselPrevious,
+ CarouselNext,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/chart.tsx b/fincept-terminal-desktop/src/components/ui/chart.tsx
new file mode 100644
index 000000000..48d27244b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/chart.tsx
@@ -0,0 +1,355 @@
+import * as React from "react"
+import * as RechartsPrimitive from "recharts"
+
+import { cn } from "@/lib/utils"
+
+// Format: { THEME_NAME: CSS_SELECTOR }
+const THEMES = { light: "", dark: ".dark" } as const
+
+export type ChartConfig = {
+ [k in string]: {
+ label?: React.ReactNode
+ icon?: React.ComponentType
+ } & (
+ | { color?: string; theme?: never }
+ | { color?: never; theme: Record<keyof typeof THEMES, string> }
+ )
+}
+
+type ChartContextProps = {
+ config: ChartConfig
+}
+
+const ChartContext = React.createContext<ChartContextProps | null>(null)
+
+function useChart() {
+ const context = React.useContext(ChartContext)
+
+ if (!context) {
+ throw new Error("useChart must be used within a <ChartContainer />")
+ }
+
+ return context
+}
+
+function ChartContainer({
+ id,
+ className,
+ children,
+ config,
+ ...props
+}: React.ComponentProps<"div"> & {
+ config: ChartConfig
+ children: React.ComponentProps<
+ typeof RechartsPrimitive.ResponsiveContainer
+ >["children"]
+}) {
+ const uniqueId = React.useId()
+ const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
+
+ return (
+ <ChartContext.Provider value={{ config }}>
+ <div
+ data-slot="chart"
+ data-chart={chartId}
+ className={cn(
+ "[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
+ className
+ )}
+ {...props}
+ >
+ <ChartStyle id={chartId} config={config} />
+ <RechartsPrimitive.ResponsiveContainer>
+ {children}
+ </RechartsPrimitive.ResponsiveContainer>
+ </div>
+ </ChartContext.Provider>
+ )
+}
+
+const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
+ const colorConfig = Object.entries(config).filter(
+ ([, config]) => config.theme || config.color
+ )
+
+ if (!colorConfig.length) {
+ return null
+ }
+
+ return (
+ <style
+ dangerouslySetInnerHTML={{
+ __html: Object.entries(THEMES)
+ .map(
+ ([theme, prefix]) => `
+${prefix} [data-chart=${id}] {
+${colorConfig
+ .map(([key, itemConfig]) => {
+ const color =
+ itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
+ itemConfig.color
+ return color ? ` --color-${key}: ${color};` : null
+ })
+ .join("\n")}
+}
+`
+ )
+ .join("\n"),
+ }}
+ />
+ )
+}
+
+const ChartTooltip = RechartsPrimitive.Tooltip
+
+function ChartTooltipContent({
+ active,
+ payload,
+ className,
+ indicator = "dot",
+ hideLabel = false,
+ hideIndicator = false,
+ label,
+ labelFormatter,
+ labelClassName,
+ formatter,
+ color,
+ nameKey,
+ labelKey,
+}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
+ React.ComponentProps<"div"> & {
+ hideLabel?: boolean
+ hideIndicator?: boolean
+ indicator?: "line" | "dot" | "dashed"
+ nameKey?: string
+ labelKey?: string
+ }) {
+ const { config } = useChart()
+
+ const tooltipLabel = React.useMemo(() => {
+ if (hideLabel || !payload?.length) {
+ return null
+ }
+
+ const [item] = payload
+ const key = `${labelKey || item?.dataKey || item?.name || "value"}`
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
+ const value =
+ !labelKey && typeof label === "string"
+ ? config[label as keyof typeof config]?.label || label
+ : itemConfig?.label
+
+ if (labelFormatter) {
+ return (
+ <div className={cn("font-medium", labelClassName)}>
+ {labelFormatter(value, payload)}
+ </div>
+ )
+ }
+
+ if (!value) {
+ return null
+ }
+
+ return <div className={cn("font-medium", labelClassName)}>{value}</div>
+ }, [
+ label,
+ labelFormatter,
+ payload,
+ hideLabel,
+ labelClassName,
+ config,
+ labelKey,
+ ])
+
+ if (!active || !payload?.length) {
+ return null
+ }
+
+ const nestLabel = payload.length === 1 && indicator !== "dot"
+
+ return (
+ <div
+ className={cn(
+ "border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",
+ className
+ )}
+ >
+ {!nestLabel ? tooltipLabel : null}
+ <div className="grid gap-1.5">
+ {payload
+ .filter((item) => item.type !== "none")
+ .map((item, index) => {
+ const key = `${nameKey || item.name || item.dataKey || "value"}`
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
+ const indicatorColor = color || item.payload.fill || item.color
+
+ return (
+ <div
+ key={item.dataKey}
+ className={cn(
+ "[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
+ indicator === "dot" && "items-center"
+ )}
+ >
+ {formatter && item?.value !== undefined && item.name ? (
+ formatter(item.value, item.name, item, index, item.payload)
+ ) : (
+ <>
+ {itemConfig?.icon ? (
+ <itemConfig.icon />
+ ) : (
+ !hideIndicator && (
+ <div
+ className={cn(
+ "shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
+ {
+ "h-2.5 w-2.5": indicator === "dot",
+ "w-1": indicator === "line",
+ "w-0 border-[1.5px] border-dashed bg-transparent":
+ indicator === "dashed",
+ "my-0.5": nestLabel && indicator === "dashed",
+ }
+ )}
+ style={
+ {
+ "--color-bg": indicatorColor,
+ "--color-border": indicatorColor,
+ } as React.CSSProperties
+ }
+ />
+ )
+ )}
+ <div
+ className={cn(
+ "flex flex-1 justify-between leading-none",
+ nestLabel ? "items-end" : "items-center"
+ )}
+ >
+ <div className="grid gap-1.5">
+ {nestLabel ? tooltipLabel : null}
+ <span className="text-muted-foreground">
+ {itemConfig?.label || item.name}
+ </span>
+ </div>
+ {item.value && (
+ <span className="text-foreground font-mono font-medium tabular-nums">
+ {item.value.toLocaleString()}
+ </span>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
+
+const ChartLegend = RechartsPrimitive.Legend
+
+function ChartLegendContent({
+ className,
+ hideIcon = false,
+ payload,
+ verticalAlign = "bottom",
+ nameKey,
+}: React.ComponentProps<"div"> &
+ Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
+ hideIcon?: boolean
+ nameKey?: string
+ }) {
+ const { config } = useChart()
+
+ if (!payload?.length) {
+ return null
+ }
+
+ return (
+ <div
+ className={cn(
+ "flex items-center justify-center gap-4",
+ verticalAlign === "top" ? "pb-3" : "pt-3",
+ className
+ )}
+ >
+ {payload
+ .filter((item) => item.type !== "none")
+ .map((item) => {
+ const key = `${nameKey || item.dataKey || "value"}`
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
+
+ return (
+ <div
+ key={item.value}
+ className={cn(
+ "[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3"
+ )}
+ >
+ {itemConfig?.icon && !hideIcon ? (
+ <itemConfig.icon />
+ ) : (
+ <div
+ className="h-2 w-2 shrink-0 rounded-[2px]"
+ style={{
+ backgroundColor: item.color,
+ }}
+ />
+ )}
+ {itemConfig?.label}
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+// Helper to extract item config from a payload.
+function getPayloadConfigFromPayload(
+ config: ChartConfig,
+ payload: unknown,
+ key: string
+) {
+ if (typeof payload !== "object" || payload === null) {
+ return undefined
+ }
+
+ const payloadPayload =
+ "payload" in payload &&
+ typeof payload.payload === "object" &&
+ payload.payload !== null
+ ? payload.payload
+ : undefined
+
+ let configLabelKey: string = key
+
+ if (
+ key in payload &&
+ typeof payload[key as keyof typeof payload] === "string"
+ ) {
+ configLabelKey = payload[key as keyof typeof payload] as string
+ } else if (
+ payloadPayload &&
+ key in payloadPayload &&
+ typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
+ ) {
+ configLabelKey = payloadPayload[
+ key as keyof typeof payloadPayload
+ ] as string
+ }
+
+ return configLabelKey in config
+ ? config[configLabelKey]
+ : config[key as keyof typeof config]
+}
+
+export {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ ChartLegend,
+ ChartLegendContent,
+ ChartStyle,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/checkbox.tsx b/fincept-terminal-desktop/src/components/ui/checkbox.tsx
new file mode 100644
index 000000000..fa0e4b59f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/checkbox.tsx
@@ -0,0 +1,32 @@
+"use client"
+
+import * as React from "react"
+import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
+import { CheckIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Checkbox({
+ className,
+ ...props
+}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
+ return (
+ <CheckboxPrimitive.Root
+ data-slot="checkbox"
+ className={cn(
+ "peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <CheckboxPrimitive.Indicator
+ data-slot="checkbox-indicator"
+ className="flex items-center justify-center text-current transition-none"
+ >
+ <CheckIcon className="size-3.5" />
+ </CheckboxPrimitive.Indicator>
+ </CheckboxPrimitive.Root>
+ )
+}
+
+export { Checkbox }
diff --git a/fincept-terminal-desktop/src/components/ui/collapsible.tsx b/fincept-terminal-desktop/src/components/ui/collapsible.tsx
new file mode 100644
index 000000000..77f86beda
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/collapsible.tsx
@@ -0,0 +1,31 @@
+import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
+
+function Collapsible({
+ ...props
+}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
+ return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
+}
+
+function CollapsibleTrigger({
+ ...props
+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
+ return (
+ <CollapsiblePrimitive.CollapsibleTrigger
+ data-slot="collapsible-trigger"
+ {...props}
+ />
+ )
+}
+
+function CollapsibleContent({
+ ...props
+}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
+ return (
+ <CollapsiblePrimitive.CollapsibleContent
+ data-slot="collapsible-content"
+ {...props}
+ />
+ )
+}
+
+export { Collapsible, CollapsibleTrigger, CollapsibleContent }
diff --git a/fincept-terminal-desktop/src/components/ui/command.tsx b/fincept-terminal-desktop/src/components/ui/command.tsx
new file mode 100644
index 000000000..8cb4ca7a5
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/command.tsx
@@ -0,0 +1,184 @@
+"use client"
+
+import * as React from "react"
+import { Command as CommandPrimitive } from "cmdk"
+import { SearchIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog"
+
+function Command({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive>) {
+ return (
+ <CommandPrimitive
+ data-slot="command"
+ className={cn(
+ "bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function CommandDialog({
+ title = "Command Palette",
+ description = "Search for a command to run...",
+ children,
+ className,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps<typeof Dialog> & {
+ title?: string
+ description?: string
+ className?: string
+ showCloseButton?: boolean
+}) {
+ return (
+ <Dialog {...props}>
+ <DialogHeader className="sr-only">
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{description}</DialogDescription>
+ </DialogHeader>
+ <DialogContent
+ className={cn("overflow-hidden p-0", className)}
+ showCloseButton={showCloseButton}
+ >
+ <Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
+ {children}
+ </Command>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function CommandInput({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Input>) {
+ return (
+ <div
+ data-slot="command-input-wrapper"
+ className="flex h-9 items-center gap-2 border-b px-3"
+ >
+ <SearchIcon className="size-4 shrink-0 opacity-50" />
+ <CommandPrimitive.Input
+ data-slot="command-input"
+ className={cn(
+ "placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...props}
+ />
+ </div>
+ )
+}
+
+function CommandList({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.List>) {
+ return (
+ <CommandPrimitive.List
+ data-slot="command-list"
+ className={cn(
+ "max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function CommandEmpty({
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Empty>) {
+ return (
+ <CommandPrimitive.Empty
+ data-slot="command-empty"
+ className="py-6 text-center text-sm"
+ {...props}
+ />
+ )
+}
+
+function CommandGroup({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Group>) {
+ return (
+ <CommandPrimitive.Group
+ data-slot="command-group"
+ className={cn(
+ "text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function CommandSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Separator>) {
+ return (
+ <CommandPrimitive.Separator
+ data-slot="command-separator"
+ className={cn("bg-border -mx-1 h-px", className)}
+ {...props}
+ />
+ )
+}
+
+function CommandItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof CommandPrimitive.Item>) {
+ return (
+ <CommandPrimitive.Item
+ data-slot="command-item"
+ className={cn(
+ "data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function CommandShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="command-shortcut"
+ className={cn(
+ "text-muted-foreground ml-auto text-xs tracking-widest",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ Command,
+ CommandDialog,
+ CommandInput,
+ CommandList,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandShortcut,
+ CommandSeparator,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/context-menu.tsx b/fincept-terminal-desktop/src/components/ui/context-menu.tsx
new file mode 100644
index 000000000..e29ad05f9
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/context-menu.tsx
@@ -0,0 +1,252 @@
+"use client"
+
+import * as React from "react"
+import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
+import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function ContextMenu({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
+ return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
+}
+
+function ContextMenuTrigger({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
+ return (
+ <ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
+ )
+}
+
+function ContextMenuGroup({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
+ return (
+ <ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
+ )
+}
+
+function ContextMenuPortal({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
+ return (
+ <ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
+ )
+}
+
+function ContextMenuSub({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
+ return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
+}
+
+function ContextMenuRadioGroup({
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
+ return (
+ <ContextMenuPrimitive.RadioGroup
+ data-slot="context-menu-radio-group"
+ {...props}
+ />
+ )
+}
+
+function ContextMenuSubTrigger({
+ className,
+ inset,
+ children,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
+ inset?: boolean
+}) {
+ return (
+ <ContextMenuPrimitive.SubTrigger
+ data-slot="context-menu-sub-trigger"
+ data-inset={inset}
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRightIcon className="ml-auto" />
+ </ContextMenuPrimitive.SubTrigger>
+ )
+}
+
+function ContextMenuSubContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
+ return (
+ <ContextMenuPrimitive.SubContent
+ data-slot="context-menu-sub-content"
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
+ return (
+ <ContextMenuPrimitive.Portal>
+ <ContextMenuPrimitive.Content
+ data-slot="context-menu-content"
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
+ className
+ )}
+ {...props}
+ />
+ </ContextMenuPrimitive.Portal>
+ )
+}
+
+function ContextMenuItem({
+ className,
+ inset,
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
+ inset?: boolean
+ variant?: "default" | "destructive"
+}) {
+ return (
+ <ContextMenuPrimitive.Item
+ data-slot="context-menu-item"
+ data-inset={inset}
+ data-variant={variant}
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuCheckboxItem({
+ className,
+ children,
+ checked,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
+ return (
+ <ContextMenuPrimitive.CheckboxItem
+ data-slot="context-menu-checkbox-item"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
+ <ContextMenuPrimitive.ItemIndicator>
+ <CheckIcon className="size-4" />
+ </ContextMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </ContextMenuPrimitive.CheckboxItem>
+ )
+}
+
+function ContextMenuRadioItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
+ return (
+ <ContextMenuPrimitive.RadioItem
+ data-slot="context-menu-radio-item"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
+ <ContextMenuPrimitive.ItemIndicator>
+ <CircleIcon className="size-2 fill-current" />
+ </ContextMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </ContextMenuPrimitive.RadioItem>
+ )
+}
+
+function ContextMenuLabel({
+ className,
+ inset,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
+ inset?: boolean
+}) {
+ return (
+ <ContextMenuPrimitive.Label
+ data-slot="context-menu-label"
+ data-inset={inset}
+ className={cn(
+ "text-foreground px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
+ return (
+ <ContextMenuPrimitive.Separator
+ data-slot="context-menu-separator"
+ className={cn("bg-border -mx-1 my-1 h-px", className)}
+ {...props}
+ />
+ )
+}
+
+function ContextMenuShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="context-menu-shortcut"
+ className={cn(
+ "text-muted-foreground ml-auto text-xs tracking-widest",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ ContextMenu,
+ ContextMenuTrigger,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuCheckboxItem,
+ ContextMenuRadioItem,
+ ContextMenuLabel,
+ ContextMenuSeparator,
+ ContextMenuShortcut,
+ ContextMenuGroup,
+ ContextMenuPortal,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+ ContextMenuRadioGroup,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/dialog.tsx b/fincept-terminal-desktop/src/components/ui/dialog.tsx
new file mode 100644
index 000000000..6cb123b38
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/dialog.tsx
@@ -0,0 +1,141 @@
+import * as React from "react"
+import * as DialogPrimitive from "@radix-ui/react-dialog"
+import { XIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Dialog({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Root>) {
+ return <DialogPrimitive.Root data-slot="dialog" {...props} />
+}
+
+function DialogTrigger({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
+ return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
+}
+
+function DialogPortal({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
+ return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
+}
+
+function DialogClose({
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Close>) {
+ return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
+}
+
+function DialogOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
+ return (
+ <DialogPrimitive.Overlay
+ data-slot="dialog-overlay"
+ className={cn(
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function DialogContent({
+ className,
+ children,
+ showCloseButton = true,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Content> & {
+ showCloseButton?: boolean
+}) {
+ return (
+ <DialogPortal data-slot="dialog-portal">
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ data-slot="dialog-content"
+ className={cn(
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <DialogPrimitive.Close
+ data-slot="dialog-close"
+ className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
+ >
+ <XIcon />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ )}
+ </DialogPrimitive.Content>
+ </DialogPortal>
+ )
+}
+
+function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="dialog-header"
+ className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
+ {...props}
+ />
+ )
+}
+
+function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="dialog-footer"
+ className={cn(
+ "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function DialogTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Title>) {
+ return (
+ <DialogPrimitive.Title
+ data-slot="dialog-title"
+ className={cn("text-lg leading-none font-semibold", className)}
+ {...props}
+ />
+ )
+}
+
+function DialogDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof DialogPrimitive.Description>) {
+ return (
+ <DialogPrimitive.Description
+ data-slot="dialog-description"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogOverlay,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/drawer.tsx b/fincept-terminal-desktop/src/components/ui/drawer.tsx
new file mode 100644
index 000000000..8aa69230a
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/drawer.tsx
@@ -0,0 +1,135 @@
+"use client"
+
+import * as React from "react"
+import { Drawer as DrawerPrimitive } from "vaul"
+
+import { cn } from "@/lib/utils"
+
+function Drawer({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
+ return <DrawerPrimitive.Root data-slot="drawer" {...props} />
+}
+
+function DrawerTrigger({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
+ return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
+}
+
+function DrawerPortal({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
+ return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
+}
+
+function DrawerClose({
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
+ return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
+}
+
+function DrawerOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
+ return (
+ <DrawerPrimitive.Overlay
+ data-slot="drawer-overlay"
+ className={cn(
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function DrawerContent({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
+ return (
+ <DrawerPortal data-slot="drawer-portal">
+ <DrawerOverlay />
+ <DrawerPrimitive.Content
+ data-slot="drawer-content"
+ className={cn(
+ "group/drawer-content bg-background fixed z-50 flex h-auto flex-col",
+ "data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
+ "data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
+ "data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
+ "data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
+ className
+ )}
+ {...props}
+ >
+ <div className="bg-muted mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
+ {children}
+ </DrawerPrimitive.Content>
+ </DrawerPortal>
+ )
+}
+
+function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="drawer-header"
+ className={cn(
+ "flex flex-col gap-0.5 p-4 group-data-[vaul-drawer-direction=bottom]/drawer-content:text-center group-data-[vaul-drawer-direction=top]/drawer-content:text-center md:gap-1.5 md:text-left",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="drawer-footer"
+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...props}
+ />
+ )
+}
+
+function DrawerTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
+ return (
+ <DrawerPrimitive.Title
+ data-slot="drawer-title"
+ className={cn("text-foreground font-semibold", className)}
+ {...props}
+ />
+ )
+}
+
+function DrawerDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
+ return (
+ <DrawerPrimitive.Description
+ data-slot="drawer-description"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ Drawer,
+ DrawerPortal,
+ DrawerOverlay,
+ DrawerTrigger,
+ DrawerClose,
+ DrawerContent,
+ DrawerHeader,
+ DrawerFooter,
+ DrawerTitle,
+ DrawerDescription,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/hover-card.tsx b/fincept-terminal-desktop/src/components/ui/hover-card.tsx
new file mode 100644
index 000000000..e7541864c
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/hover-card.tsx
@@ -0,0 +1,44 @@
+"use client"
+
+import * as React from "react"
+import * as HoverCardPrimitive from "@radix-ui/react-hover-card"
+
+import { cn } from "@/lib/utils"
+
+function HoverCard({
+ ...props
+}: React.ComponentProps<typeof HoverCardPrimitive.Root>) {
+ return <HoverCardPrimitive.Root data-slot="hover-card" {...props} />
+}
+
+function HoverCardTrigger({
+ ...props
+}: React.ComponentProps<typeof HoverCardPrimitive.Trigger>) {
+ return (
+ <HoverCardPrimitive.Trigger data-slot="hover-card-trigger" {...props} />
+ )
+}
+
+function HoverCardContent({
+ className,
+ align = "center",
+ sideOffset = 4,
+ ...props
+}: React.ComponentProps<typeof HoverCardPrimitive.Content>) {
+ return (
+ <HoverCardPrimitive.Portal data-slot="hover-card-portal">
+ <HoverCardPrimitive.Content
+ data-slot="hover-card-content"
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-64 origin-(--radix-hover-card-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
+ className
+ )}
+ {...props}
+ />
+ </HoverCardPrimitive.Portal>
+ )
+}
+
+export { HoverCard, HoverCardTrigger, HoverCardContent }
diff --git a/fincept-terminal-desktop/src/components/ui/menubar.tsx b/fincept-terminal-desktop/src/components/ui/menubar.tsx
new file mode 100644
index 000000000..8480f0aac
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/menubar.tsx
@@ -0,0 +1,276 @@
+"use client"
+
+import * as React from "react"
+import * as MenubarPrimitive from "@radix-ui/react-menubar"
+import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Menubar({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
+ return (
+ <MenubarPrimitive.Root
+ data-slot="menubar"
+ className={cn(
+ "bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function MenubarMenu({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
+ return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />
+}
+
+function MenubarGroup({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
+ return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />
+}
+
+function MenubarPortal({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
+ return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />
+}
+
+function MenubarRadioGroup({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
+ return (
+ <MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
+ )
+}
+
+function MenubarTrigger({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
+ return (
+ <MenubarPrimitive.Trigger
+ data-slot="menubar-trigger"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function MenubarContent({
+ className,
+ align = "start",
+ alignOffset = -4,
+ sideOffset = 8,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
+ return (
+ <MenubarPortal>
+ <MenubarPrimitive.Content
+ data-slot="menubar-content"
+ align={align}
+ alignOffset={alignOffset}
+ sideOffset={sideOffset}
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md",
+ className
+ )}
+ {...props}
+ />
+ </MenubarPortal>
+ )
+}
+
+function MenubarItem({
+ className,
+ inset,
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
+ inset?: boolean
+ variant?: "default" | "destructive"
+}) {
+ return (
+ <MenubarPrimitive.Item
+ data-slot="menubar-item"
+ data-inset={inset}
+ data-variant={variant}
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function MenubarCheckboxItem({
+ className,
+ children,
+ checked,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
+ return (
+ <MenubarPrimitive.CheckboxItem
+ data-slot="menubar-checkbox-item"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
+ <MenubarPrimitive.ItemIndicator>
+ <CheckIcon className="size-4" />
+ </MenubarPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </MenubarPrimitive.CheckboxItem>
+ )
+}
+
+function MenubarRadioItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
+ return (
+ <MenubarPrimitive.RadioItem
+ data-slot="menubar-radio-item"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
+ <MenubarPrimitive.ItemIndicator>
+ <CircleIcon className="size-2 fill-current" />
+ </MenubarPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </MenubarPrimitive.RadioItem>
+ )
+}
+
+function MenubarLabel({
+ className,
+ inset,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
+ inset?: boolean
+}) {
+ return (
+ <MenubarPrimitive.Label
+ data-slot="menubar-label"
+ data-inset={inset}
+ className={cn(
+ "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function MenubarSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
+ return (
+ <MenubarPrimitive.Separator
+ data-slot="menubar-separator"
+ className={cn("bg-border -mx-1 my-1 h-px", className)}
+ {...props}
+ />
+ )
+}
+
+function MenubarShortcut({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="menubar-shortcut"
+ className={cn(
+ "text-muted-foreground ml-auto text-xs tracking-widest",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function MenubarSub({
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
+ return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />
+}
+
+function MenubarSubTrigger({
+ className,
+ inset,
+ children,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
+ inset?: boolean
+}) {
+ return (
+ <MenubarPrimitive.SubTrigger
+ data-slot="menubar-sub-trigger"
+ data-inset={inset}
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRightIcon className="ml-auto h-4 w-4" />
+ </MenubarPrimitive.SubTrigger>
+ )
+}
+
+function MenubarSubContent({
+ className,
+ ...props
+}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
+ return (
+ <MenubarPrimitive.SubContent
+ data-slot="menubar-sub-content"
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ Menubar,
+ MenubarPortal,
+ MenubarMenu,
+ MenubarTrigger,
+ MenubarContent,
+ MenubarGroup,
+ MenubarSeparator,
+ MenubarLabel,
+ MenubarItem,
+ MenubarShortcut,
+ MenubarCheckboxItem,
+ MenubarRadioGroup,
+ MenubarRadioItem,
+ MenubarSub,
+ MenubarSubTrigger,
+ MenubarSubContent,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/popover.tsx b/fincept-terminal-desktop/src/components/ui/popover.tsx
new file mode 100644
index 000000000..6d51b6ced
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/popover.tsx
@@ -0,0 +1,46 @@
+import * as React from "react"
+import * as PopoverPrimitive from "@radix-ui/react-popover"
+
+import { cn } from "@/lib/utils"
+
+function Popover({
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
+ return <PopoverPrimitive.Root data-slot="popover" {...props} />
+}
+
+function PopoverTrigger({
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
+ return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
+}
+
+function PopoverContent({
+ className,
+ align = "center",
+ sideOffset = 4,
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
+ return (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ data-slot="popover-content"
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
+ className
+ )}
+ {...props}
+ />
+ </PopoverPrimitive.Portal>
+ )
+}
+
+function PopoverAnchor({
+ ...props
+}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
+ return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
+}
+
+export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
diff --git a/fincept-terminal-desktop/src/components/ui/radio-group.tsx b/fincept-terminal-desktop/src/components/ui/radio-group.tsx
new file mode 100644
index 000000000..dc682eb90
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/radio-group.tsx
@@ -0,0 +1,43 @@
+import * as React from "react"
+import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
+import { CircleIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function RadioGroup({
+ className,
+ ...props
+}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
+ return (
+ <RadioGroupPrimitive.Root
+ data-slot="radio-group"
+ className={cn("grid gap-3", className)}
+ {...props}
+ />
+ )
+}
+
+function RadioGroupItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
+ return (
+ <RadioGroupPrimitive.Item
+ data-slot="radio-group-item"
+ className={cn(
+ "border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <RadioGroupPrimitive.Indicator
+ data-slot="radio-group-indicator"
+ className="relative flex items-center justify-center"
+ >
+ <CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
+ </RadioGroupPrimitive.Indicator>
+ </RadioGroupPrimitive.Item>
+ )
+}
+
+export { RadioGroup, RadioGroupItem }
diff --git a/fincept-terminal-desktop/src/components/ui/select.tsx b/fincept-terminal-desktop/src/components/ui/select.tsx
new file mode 100644
index 000000000..51f466ecc
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/select.tsx
@@ -0,0 +1,183 @@
+import * as React from "react"
+import * as SelectPrimitive from "@radix-ui/react-select"
+import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Select({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Root>) {
+ return <SelectPrimitive.Root data-slot="select" {...props} />
+}
+
+function SelectGroup({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Group>) {
+ return <SelectPrimitive.Group data-slot="select-group" {...props} />
+}
+
+function SelectValue({
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Value>) {
+ return <SelectPrimitive.Value data-slot="select-value" {...props} />
+}
+
+function SelectTrigger({
+ className,
+ size = "default",
+ children,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
+ size?: "sm" | "default"
+}) {
+ return (
+ <SelectPrimitive.Trigger
+ data-slot="select-trigger"
+ data-size={size}
+ className={cn(
+ "border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <SelectPrimitive.Icon asChild>
+ <ChevronDownIcon className="size-4 opacity-50" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+ )
+}
+
+function SelectContent({
+ className,
+ children,
+ position = "popper",
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Content>) {
+ return (
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ data-slot="select-content"
+ className={cn(
+ "bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ className
+ )}
+ position={position}
+ {...props}
+ >
+ <SelectScrollUpButton />
+ <SelectPrimitive.Viewport
+ className={cn(
+ "p-1",
+ position === "popper" &&
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ <SelectScrollDownButton />
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+ )
+}
+
+function SelectLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Label>) {
+ return (
+ <SelectPrimitive.Label
+ data-slot="select-label"
+ className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
+ {...props}
+ />
+ )
+}
+
+function SelectItem({
+ className,
+ children,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Item>) {
+ return (
+ <SelectPrimitive.Item
+ data-slot="select-item"
+ className={cn(
+ "focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
+ className
+ )}
+ {...props}
+ >
+ <span className="absolute right-2 flex size-3.5 items-center justify-center">
+ <SelectPrimitive.ItemIndicator>
+ <CheckIcon className="size-4" />
+ </SelectPrimitive.ItemIndicator>
+ </span>
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ </SelectPrimitive.Item>
+ )
+}
+
+function SelectSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
+ return (
+ <SelectPrimitive.Separator
+ data-slot="select-separator"
+ className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
+ {...props}
+ />
+ )
+}
+
+function SelectScrollUpButton({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
+ return (
+ <SelectPrimitive.ScrollUpButton
+ data-slot="select-scroll-up-button"
+ className={cn(
+ "flex cursor-default items-center justify-center py-1",
+ className
+ )}
+ {...props}
+ >
+ <ChevronUpIcon className="size-4" />
+ </SelectPrimitive.ScrollUpButton>
+ )
+}
+
+function SelectScrollDownButton({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
+ return (
+ <SelectPrimitive.ScrollDownButton
+ data-slot="select-scroll-down-button"
+ className={cn(
+ "flex cursor-default items-center justify-center py-1",
+ className
+ )}
+ {...props}
+ >
+ <ChevronDownIcon className="size-4" />
+ </SelectPrimitive.ScrollDownButton>
+ )
+}
+
+export {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectScrollDownButton,
+ SelectScrollUpButton,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/sheet.tsx b/fincept-terminal-desktop/src/components/ui/sheet.tsx
new file mode 100644
index 000000000..6906f5b2b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/sheet.tsx
@@ -0,0 +1,137 @@
+import * as React from "react"
+import * as SheetPrimitive from "@radix-ui/react-dialog"
+import { XIcon } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
+ return <SheetPrimitive.Root data-slot="sheet" {...props} />
+}
+
+function SheetTrigger({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
+ return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
+}
+
+function SheetClose({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Close>) {
+ return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
+}
+
+function SheetPortal({
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
+ return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
+}
+
+function SheetOverlay({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
+ return (
+ <SheetPrimitive.Overlay
+ data-slot="sheet-overlay"
+ className={cn(
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SheetContent({
+ className,
+ children,
+ side = "right",
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Content> & {
+ side?: "top" | "right" | "bottom" | "left"
+}) {
+ return (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Content
+ data-slot="sheet-content"
+ className={cn(
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
+ side === "right" &&
+ "data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
+ side === "left" &&
+ "data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
+ side === "top" &&
+ "data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
+ side === "bottom" &&
+ "data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
+ <XIcon className="size-4" />
+ <span className="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ </SheetPrimitive.Content>
+ </SheetPortal>
+ )
+}
+
+function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-header"
+ className={cn("flex flex-col gap-1.5 p-4", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-footer"
+ className={cn("mt-auto flex flex-col gap-2 p-4", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Title>) {
+ return (
+ <SheetPrimitive.Title
+ data-slot="sheet-title"
+ className={cn("text-foreground font-semibold", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof SheetPrimitive.Description>) {
+ return (
+ <SheetPrimitive.Description
+ data-slot="sheet-description"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ Sheet,
+ SheetTrigger,
+ SheetClose,
+ SheetContent,
+ SheetHeader,
+ SheetFooter,
+ SheetTitle,
+ SheetDescription,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/sidebar.tsx b/fincept-terminal-desktop/src/components/ui/sidebar.tsx
new file mode 100644
index 000000000..5d8d3cad6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/sidebar.tsx
@@ -0,0 +1,724 @@
+import * as React from "react"
+import { Slot } from "@radix-ui/react-slot"
+import { cva, VariantProps } from "class-variance-authority"
+import { PanelLeftIcon } from "lucide-react"
+
+import { useIsMobile } from "@/hooks/use-mobile"
+import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+import { Input } from "@/components/ui/input"
+import { Separator } from "@/components/ui/separator"
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet"
+import { Skeleton } from "@/components/ui/skeleton"
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip"
+
+const SIDEBAR_COOKIE_NAME = "sidebar_state"
+const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
+const SIDEBAR_WIDTH = "16rem"
+const SIDEBAR_WIDTH_MOBILE = "18rem"
+const SIDEBAR_WIDTH_ICON = "3rem"
+const SIDEBAR_KEYBOARD_SHORTCUT = "b"
+
+type SidebarContextProps = {
+ state: "expanded" | "collapsed"
+ open: boolean
+ setOpen: (open: boolean) => void
+ openMobile: boolean
+ setOpenMobile: (open: boolean) => void
+ isMobile: boolean
+ toggleSidebar: () => void
+}
+
+const SidebarContext = React.createContext<SidebarContextProps | null>(null)
+
+function useSidebar() {
+ const context = React.useContext(SidebarContext)
+ if (!context) {
+ throw new Error("useSidebar must be used within a SidebarProvider.")
+ }
+
+ return context
+}
+
+function SidebarProvider({
+ defaultOpen = true,
+ open: openProp,
+ onOpenChange: setOpenProp,
+ className,
+ style,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ defaultOpen?: boolean
+ open?: boolean
+ onOpenChange?: (open: boolean) => void
+}) {
+ const isMobile = useIsMobile()
+ const [openMobile, setOpenMobile] = React.useState(false)
+
+ // This is the internal state of the sidebar.
+ // We use openProp and setOpenProp for control from outside the component.
+ const [_open, _setOpen] = React.useState(defaultOpen)
+ const open = openProp ?? _open
+ const setOpen = React.useCallback(
+ (value: boolean | ((value: boolean) => boolean)) => {
+ const openState = typeof value === "function" ? value(open) : value
+ if (setOpenProp) {
+ setOpenProp(openState)
+ } else {
+ _setOpen(openState)
+ }
+
+ // This sets the cookie to keep the sidebar state.
+ document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
+ },
+ [setOpenProp, open]
+ )
+
+ // Helper to toggle the sidebar.
+ const toggleSidebar = React.useCallback(() => {
+ return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
+ }, [isMobile, setOpen, setOpenMobile])
+
+ // Adds a keyboard shortcut to toggle the sidebar.
+ React.useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (
+ event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
+ (event.metaKey || event.ctrlKey)
+ ) {
+ event.preventDefault()
+ toggleSidebar()
+ }
+ }
+
+ window.addEventListener("keydown", handleKeyDown)
+ return () => window.removeEventListener("keydown", handleKeyDown)
+ }, [toggleSidebar])
+
+ // We add a state so that we can do data-state="expanded" or "collapsed".
+ // This makes it easier to style the sidebar with Tailwind classes.
+ const state = open ? "expanded" : "collapsed"
+
+ const contextValue = React.useMemo<SidebarContextProps>(
+ () => ({
+ state,
+ open,
+ setOpen,
+ isMobile,
+ openMobile,
+ setOpenMobile,
+ toggleSidebar,
+ }),
+ [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
+ )
+
+ return (
+ <SidebarContext.Provider value={contextValue}>
+ <TooltipProvider delayDuration={0}>
+ <div
+ data-slot="sidebar-wrapper"
+ style={
+ {
+ "--sidebar-width": SIDEBAR_WIDTH,
+ "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
+ ...style,
+ } as React.CSSProperties
+ }
+ className={cn(
+ "group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ </TooltipProvider>
+ </SidebarContext.Provider>
+ )
+}
+
+function Sidebar({
+ side = "left",
+ variant = "sidebar",
+ collapsible = "offcanvas",
+ className,
+ children,
+ ...props
+}: React.ComponentProps<"div"> & {
+ side?: "left" | "right"
+ variant?: "sidebar" | "floating" | "inset"
+ collapsible?: "offcanvas" | "icon" | "none"
+}) {
+ const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
+
+ if (collapsible === "none") {
+ return (
+ <div
+ data-slot="sidebar"
+ className={cn(
+ "bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ )
+ }
+
+ if (isMobile) {
+ return (
+ <Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
+ <SheetContent
+ data-sidebar="sidebar"
+ data-slot="sidebar"
+ data-mobile="true"
+ className="bg-sidebar text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
+ style={
+ {
+ "--sidebar-width": SIDEBAR_WIDTH_MOBILE,
+ } as React.CSSProperties
+ }
+ side={side}
+ >
+ <SheetHeader className="sr-only">
+ <SheetTitle>Sidebar</SheetTitle>
+ <SheetDescription>Displays the mobile sidebar.</SheetDescription>
+ </SheetHeader>
+ <div className="flex h-full w-full flex-col">{children}</div>
+ </SheetContent>
+ </Sheet>
+ )
+ }
+
+ return (
+ <div
+ className="group peer text-sidebar-foreground hidden md:block"
+ data-state={state}
+ data-collapsible={state === "collapsed" ? collapsible : ""}
+ data-variant={variant}
+ data-side={side}
+ data-slot="sidebar"
+ >
+ {/* This is what handles the sidebar gap on desktop */}
+ <div
+ data-slot="sidebar-gap"
+ className={cn(
+ "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
+ "group-data-[collapsible=offcanvas]:w-0",
+ "group-data-[side=right]:rotate-180",
+ variant === "floating" || variant === "inset"
+ ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
+ )}
+ />
+ <div
+ data-slot="sidebar-container"
+ className={cn(
+ "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
+ side === "left"
+ ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
+ : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
+ // Adjust the padding for floating and inset variants.
+ variant === "floating" || variant === "inset"
+ ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
+ : "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
+ className
+ )}
+ {...props}
+ >
+ <div
+ data-sidebar="sidebar"
+ data-slot="sidebar-inner"
+ className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow-sm"
+ >
+ {children}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+function SidebarTrigger({
+ className,
+ onClick,
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ const { toggleSidebar } = useSidebar()
+
+ return (
+ <Button
+ data-sidebar="trigger"
+ data-slot="sidebar-trigger"
+ variant="ghost"
+ size="icon"
+ className={cn("size-7", className)}
+ onClick={(event) => {
+ onClick?.(event)
+ toggleSidebar()
+ }}
+ {...props}
+ >
+ <PanelLeftIcon />
+ <span className="sr-only">Toggle Sidebar</span>
+ </Button>
+ )
+}
+
+function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
+ const { toggleSidebar } = useSidebar()
+
+ return (
+ <button
+ data-sidebar="rail"
+ data-slot="sidebar-rail"
+ aria-label="Toggle Sidebar"
+ tabIndex={-1}
+ onClick={toggleSidebar}
+ title="Toggle Sidebar"
+ className={cn(
+ "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
+ "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
+ "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
+ "hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
+ "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
+ "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
+ return (
+ <main
+ data-slot="sidebar-inset"
+ className={cn(
+ "bg-background relative flex w-full flex-1 flex-col",
+ "md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarInput({
+ className,
+ ...props
+}: React.ComponentProps<typeof Input>) {
+ return (
+ <Input
+ data-slot="sidebar-input"
+ data-sidebar="input"
+ className={cn("bg-background h-8 w-full shadow-none", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-header"
+ data-sidebar="header"
+ className={cn("flex flex-col gap-2 p-2", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-footer"
+ data-sidebar="footer"
+ className={cn("flex flex-col gap-2 p-2", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarSeparator({
+ className,
+ ...props
+}: React.ComponentProps<typeof Separator>) {
+ return (
+ <Separator
+ data-slot="sidebar-separator"
+ data-sidebar="separator"
+ className={cn("bg-sidebar-border mx-2 w-auto", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-content"
+ data-sidebar="content"
+ className={cn(
+ "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-group"
+ data-sidebar="group"
+ className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarGroupLabel({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"div"> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot : "div"
+
+ return (
+ <Comp
+ data-slot="sidebar-group-label"
+ data-sidebar="group-label"
+ className={cn(
+ "text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarGroupAction({
+ className,
+ asChild = false,
+ ...props
+}: React.ComponentProps<"button"> & { asChild?: boolean }) {
+ const Comp = asChild ? Slot : "button"
+
+ return (
+ <Comp
+ data-slot="sidebar-group-action"
+ data-sidebar="group-action"
+ className={cn(
+ "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ // Increases the hit area of the button on mobile.
+ "after:absolute after:-inset-2 md:after:hidden",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarGroupContent({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-group-content"
+ data-sidebar="group-content"
+ className={cn("w-full text-sm", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
+ return (
+ <ul
+ data-slot="sidebar-menu"
+ data-sidebar="menu"
+ className={cn("flex w-full min-w-0 flex-col gap-1", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="sidebar-menu-item"
+ data-sidebar="menu-item"
+ className={cn("group/menu-item relative", className)}
+ {...props}
+ />
+ )
+}
+
+const sidebarMenuButtonVariants = cva(
+ "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ {
+ variants: {
+ variant: {
+ default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
+ outline:
+ "bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
+ },
+ size: {
+ default: "h-8 text-sm",
+ sm: "h-7 text-xs",
+ lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ }
+)
+
+function SidebarMenuButton({
+ asChild = false,
+ isActive = false,
+ variant = "default",
+ size = "default",
+ tooltip,
+ className,
+ ...props
+}: React.ComponentProps<"button"> & {
+ asChild?: boolean
+ isActive?: boolean
+ tooltip?: string | React.ComponentProps<typeof TooltipContent>
+} & VariantProps<typeof sidebarMenuButtonVariants>) {
+ const Comp = asChild ? Slot : "button"
+ const { isMobile, state } = useSidebar()
+
+ const button = (
+ <Comp
+ data-slot="sidebar-menu-button"
+ data-sidebar="menu-button"
+ data-size={size}
+ data-active={isActive}
+ className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
+ {...props}
+ />
+ )
+
+ if (!tooltip) {
+ return button
+ }
+
+ if (typeof tooltip === "string") {
+ tooltip = {
+ children: tooltip,
+ }
+ }
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>{button}</TooltipTrigger>
+ <TooltipContent
+ side="right"
+ align="center"
+ hidden={state !== "collapsed" || isMobile}
+ {...tooltip}
+ />
+ </Tooltip>
+ )
+}
+
+function SidebarMenuAction({
+ className,
+ asChild = false,
+ showOnHover = false,
+ ...props
+}: React.ComponentProps<"button"> & {
+ asChild?: boolean
+ showOnHover?: boolean
+}) {
+ const Comp = asChild ? Slot : "button"
+
+ return (
+ <Comp
+ data-slot="sidebar-menu-action"
+ data-sidebar="menu-action"
+ className={cn(
+ "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ // Increases the hit area of the button on mobile.
+ "after:absolute after:-inset-2 md:after:hidden",
+ "peer-data-[size=sm]/menu-button:top-1",
+ "peer-data-[size=default]/menu-button:top-1.5",
+ "peer-data-[size=lg]/menu-button:top-2.5",
+ "group-data-[collapsible=icon]:hidden",
+ showOnHover &&
+ "peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarMenuBadge({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sidebar-menu-badge"
+ data-sidebar="menu-badge"
+ className={cn(
+ "text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
+ "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
+ "peer-data-[size=sm]/menu-button:top-1",
+ "peer-data-[size=default]/menu-button:top-1.5",
+ "peer-data-[size=lg]/menu-button:top-2.5",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarMenuSkeleton({
+ className,
+ showIcon = false,
+ ...props
+}: React.ComponentProps<"div"> & {
+ showIcon?: boolean
+}) {
+ // Random width between 50 to 90%.
+ const width = React.useMemo(() => {
+ return `${Math.floor(Math.random() * 40) + 50}%`
+ }, [])
+
+ return (
+ <div
+ data-slot="sidebar-menu-skeleton"
+ data-sidebar="menu-skeleton"
+ className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
+ {...props}
+ >
+ {showIcon && (
+ <Skeleton
+ className="size-4 rounded-md"
+ data-sidebar="menu-skeleton-icon"
+ />
+ )}
+ <Skeleton
+ className="h-4 max-w-(--skeleton-width) flex-1"
+ data-sidebar="menu-skeleton-text"
+ style={
+ {
+ "--skeleton-width": width,
+ } as React.CSSProperties
+ }
+ />
+ </div>
+ )
+}
+
+function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
+ return (
+ <ul
+ data-slot="sidebar-menu-sub"
+ data-sidebar="menu-sub"
+ className={cn(
+ "border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SidebarMenuSubItem({
+ className,
+ ...props
+}: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="sidebar-menu-sub-item"
+ data-sidebar="menu-sub-item"
+ className={cn("group/menu-sub-item relative", className)}
+ {...props}
+ />
+ )
+}
+
+function SidebarMenuSubButton({
+ asChild = false,
+ size = "md",
+ isActive = false,
+ className,
+ ...props
+}: React.ComponentProps<"a"> & {
+ asChild?: boolean
+ size?: "sm" | "md"
+ isActive?: boolean
+}) {
+ const Comp = asChild ? Slot : "a"
+
+ return (
+ <Comp
+ data-slot="sidebar-menu-sub-button"
+ data-sidebar="menu-sub-button"
+ data-size={size}
+ data-active={isActive}
+ className={cn(
+ "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
+ size === "sm" && "text-xs",
+ size === "md" && "text-sm",
+ "group-data-[collapsible=icon]:hidden",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ Sidebar,
+ SidebarContent,
+ SidebarFooter,
+ SidebarGroup,
+ SidebarGroupAction,
+ SidebarGroupContent,
+ SidebarGroupLabel,
+ SidebarHeader,
+ SidebarInput,
+ SidebarInset,
+ SidebarMenu,
+ SidebarMenuAction,
+ SidebarMenuBadge,
+ SidebarMenuButton,
+ SidebarMenuItem,
+ SidebarMenuSkeleton,
+ SidebarMenuSub,
+ SidebarMenuSubButton,
+ SidebarMenuSubItem,
+ SidebarProvider,
+ SidebarRail,
+ SidebarSeparator,
+ SidebarTrigger,
+ useSidebar,
+}
diff --git a/fincept-terminal-desktop/src/components/ui/skeleton.tsx b/fincept-terminal-desktop/src/components/ui/skeleton.tsx
new file mode 100644
index 000000000..32ea0ef7f
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/skeleton.tsx
@@ -0,0 +1,13 @@
+import { cn } from "@/lib/utils"
+
+function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="skeleton"
+ className={cn("bg-accent animate-pulse rounded-md", className)}
+ {...props}
+ />
+ )
+}
+
+export { Skeleton }
diff --git a/fincept-terminal-desktop/src/components/ui/slider.tsx b/fincept-terminal-desktop/src/components/ui/slider.tsx
new file mode 100644
index 000000000..09391e86b
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/slider.tsx
@@ -0,0 +1,63 @@
+"use client"
+
+import * as React from "react"
+import * as SliderPrimitive from "@radix-ui/react-slider"
+
+import { cn } from "@/lib/utils"
+
+function Slider({
+ className,
+ defaultValue,
+ value,
+ min = 0,
+ max = 100,
+ ...props
+}: React.ComponentProps<typeof SliderPrimitive.Root>) {
+ const _values = React.useMemo(
+ () =>
+ Array.isArray(value)
+ ? value
+ : Array.isArray(defaultValue)
+ ? defaultValue
+ : [min, max],
+ [value, defaultValue, min, max]
+ )
+
+ return (
+ <SliderPrimitive.Root
+ data-slot="slider"
+ defaultValue={defaultValue}
+ value={value}
+ min={min}
+ max={max}
+ className={cn(
+ "relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
+ className
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track
+ data-slot="slider-track"
+ className={cn(
+ "bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
+ )}
+ >
+ <SliderPrimitive.Range
+ data-slot="slider-range"
+ className={cn(
+ "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
+ )}
+ />
+ </SliderPrimitive.Track>
+ {Array.from({ length: _values.length }, (_, index) => (
+ <SliderPrimitive.Thumb
+ data-slot="slider-thumb"
+ key={index}
+ className="border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
+ />
+ ))}
+ </SliderPrimitive.Root>
+ )
+}
+
+export { Slider }
diff --git a/fincept-terminal-desktop/src/components/ui/switch.tsx b/fincept-terminal-desktop/src/components/ui/switch.tsx
new file mode 100644
index 000000000..b0363e3f8
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/switch.tsx
@@ -0,0 +1,29 @@
+import * as React from "react"
+import * as SwitchPrimitive from "@radix-ui/react-switch"
+
+import { cn } from "@/lib/utils"
+
+function Switch({
+ className,
+ ...props
+}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
+ return (
+ <SwitchPrimitive.Root
+ data-slot="switch"
+ className={cn(
+ "peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <SwitchPrimitive.Thumb
+ data-slot="switch-thumb"
+ className={cn(
+ "bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
+ )}
+ />
+ </SwitchPrimitive.Root>
+ )
+}
+
+export { Switch }
diff --git a/fincept-terminal-desktop/src/components/ui/toggle-group.tsx b/fincept-terminal-desktop/src/components/ui/toggle-group.tsx
new file mode 100644
index 000000000..5eed401b6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/toggle-group.tsx
@@ -0,0 +1,73 @@
+"use client"
+
+import * as React from "react"
+import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
+import { type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+import { toggleVariants } from "@/components/ui/toggle"
+
+const ToggleGroupContext = React.createContext<
+ VariantProps<typeof toggleVariants>
+>({
+ size: "default",
+ variant: "default",
+})
+
+function ToggleGroup({
+ className,
+ variant,
+ size,
+ children,
+ ...props
+}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
+ VariantProps<typeof toggleVariants>) {
+ return (
+ <ToggleGroupPrimitive.Root
+ data-slot="toggle-group"
+ data-variant={variant}
+ data-size={size}
+ className={cn(
+ "group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
+ className
+ )}
+ {...props}
+ >
+ <ToggleGroupContext.Provider value={{ variant, size }}>
+ {children}
+ </ToggleGroupContext.Provider>
+ </ToggleGroupPrimitive.Root>
+ )
+}
+
+function ToggleGroupItem({
+ className,
+ children,
+ variant,
+ size,
+ ...props
+}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
+ VariantProps<typeof toggleVariants>) {
+ const context = React.useContext(ToggleGroupContext)
+
+ return (
+ <ToggleGroupPrimitive.Item
+ data-slot="toggle-group-item"
+ data-variant={context.variant || variant}
+ data-size={context.size || size}
+ className={cn(
+ toggleVariants({
+ variant: context.variant || variant,
+ size: context.size || size,
+ }),
+ "min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </ToggleGroupPrimitive.Item>
+ )
+}
+
+export { ToggleGroup, ToggleGroupItem }
diff --git a/fincept-terminal-desktop/src/components/ui/toggle.tsx b/fincept-terminal-desktop/src/components/ui/toggle.tsx
new file mode 100644
index 000000000..94ec8f589
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/toggle.tsx
@@ -0,0 +1,47 @@
+"use client"
+
+import * as React from "react"
+import * as TogglePrimitive from "@radix-ui/react-toggle"
+import { cva, type VariantProps } from "class-variance-authority"
+
+import { cn } from "@/lib/utils"
+
+const toggleVariants = cva(
+ "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ outline:
+ "border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
+ },
+ size: {
+ default: "h-9 px-2 min-w-9",
+ sm: "h-8 px-1.5 min-w-8",
+ lg: "h-10 px-2.5 min-w-10",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ }
+)
+
+function Toggle({
+ className,
+ variant,
+ size,
+ ...props
+}: React.ComponentProps<typeof TogglePrimitive.Root> &
+ VariantProps<typeof toggleVariants>) {
+ return (
+ <TogglePrimitive.Root
+ data-slot="toggle"
+ className={cn(toggleVariants({ variant, size, className }))}
+ {...props}
+ />
+ )
+}
+
+export { Toggle, toggleVariants }
diff --git a/fincept-terminal-desktop/src/components/ui/tooltip.tsx b/fincept-terminal-desktop/src/components/ui/tooltip.tsx
new file mode 100644
index 000000000..715bf76d6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/ui/tooltip.tsx
@@ -0,0 +1,59 @@
+import * as React from "react"
+import * as TooltipPrimitive from "@radix-ui/react-tooltip"
+
+import { cn } from "@/lib/utils"
+
+function TooltipProvider({
+ delayDuration = 0,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
+ return (
+ <TooltipPrimitive.Provider
+ data-slot="tooltip-provider"
+ delayDuration={delayDuration}
+ {...props}
+ />
+ )
+}
+
+function Tooltip({
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
+ return (
+ <TooltipProvider>
+ <TooltipPrimitive.Root data-slot="tooltip" {...props} />
+ </TooltipProvider>
+ )
+}
+
+function TooltipTrigger({
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
+ return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
+}
+
+function TooltipContent({
+ className,
+ sideOffset = 0,
+ children,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
+ return (
+ <TooltipPrimitive.Portal>
+ <TooltipPrimitive.Content
+ data-slot="tooltip-content"
+ sideOffset={sideOffset}
+ className={cn(
+ "bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
+ </TooltipPrimitive.Content>
+ </TooltipPrimitive.Portal>
+ )
+}
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
index 2a8ccd88f..fab155311 100644
--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
@@ -1,8 +1,9 @@
// File: src/contexts/AuthContext.tsx
-// Authentication context for managing user state and backend API integration
+// Authentication context for managing user state and backend API integration with payment support
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { AuthApiService } from '@/services/authApi';
+import { PaymentApiService } from '@/services/paymentApi';
// Response types to match your API
export interface LoginResponse {
@@ -17,6 +18,23 @@ export interface LoginResponse {
error?: string;
}
+export interface UserProfileResponse {
+ success: boolean;
+ data?: {
+ id: number;
+ username: string;
+ email: string;
+ account_type: string;
+ credit_balance: number;
+ is_verified: boolean;
+ mfa_enabled: boolean;
+ created_at: string;
+ last_login_at: string;
+ };
+ message?: string;
+ error?: string;
+}
+
export interface DeviceRegisterResponse {
success: boolean;
data?: {
@@ -39,6 +57,55 @@ export interface ApiResponse {
status_code?: number;
}
+// Payment related types
+export interface SubscriptionPlan {
+ plan_id: string;
+ name: string;
+ description: string;
+ price_usd: number;
+ billing_interval: string;
+ api_calls_limit: number | string;
+ databases_access: string[];
+ priority_support: boolean;
+ features: {
+ api_calls: string;
+ databases: string;
+ support: string;
+ };
+}
+
+export interface PaymentSession {
+ checkout_url: string;
+ session_id: string;
+ payment_uuid: string;
+ plan: {
+ name: string;
+ price: number;
+ };
+}
+
+export interface UserSubscription {
+ has_subscription: boolean;
+ subscription?: {
+ subscription_uuid: string;
+ plan: {
+ name: string;
+ plan_id: string;
+ price: number;
+ };
+ status: string;
+ current_period_start: string;
+ current_period_end: string;
+ days_remaining: number;
+ cancel_at_period_end: boolean;
+ usage: {
+ api_calls_used: number;
+ api_calls_limit: number | string;
+ usage_percentage: number;
+ };
+ };
+}
+
// Types based on your Python API client
export interface SessionData {
authenticated: boolean;
@@ -48,17 +115,23 @@ export interface SessionData {
user_info?: {
username?: string;
email?: string;
+ account_type?: string;
credit_balance?: number;
+ is_verified?: boolean;
+ mfa_enabled?: boolean;
};
expires_at?: string;
daily_limit?: number;
requests_today?: number;
+ subscription?: UserSubscription;
}
interface AuthContextType {
session: SessionData | null;
isLoading: boolean;
isFirstTimeUser: boolean;
+ availablePlans: SubscriptionPlan[];
+ isLoadingPlans: boolean;
login: (email: string, password: string) => Promise<{ success: boolean; error?: string }>;
signup: (username: string, email: string, password: string) => Promise<{ success: boolean; error?: string }>;
verifyOtp: (email: string, otp: string) => Promise<{ success: boolean; error?: string }>;
@@ -67,6 +140,11 @@ interface AuthContextType {
checkApiConnectivity: () => Promise<boolean>;
forgotPassword: (email: string) => Promise<{ success: boolean; error?: string }>;
resetPassword: (email: string, otp: string, newPassword: string) => Promise<{ success: boolean; error?: string }>;
+ // Payment methods
+ fetchPlans: () => Promise<{ success: boolean; error?: string }>;
+ createPaymentSession: (planId: string) => Promise<{ success: boolean; data?: PaymentSession; error?: string }>;
+ getUserSubscription: () => Promise<{ success: boolean; data?: UserSubscription; error?: string }>;
+ refreshUserData: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
@@ -151,6 +229,74 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const [session, setSession] = useState<SessionData | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isFirstTimeUser, setIsFirstTimeUser] = useState(false);
+ const [availablePlans, setAvailablePlans] = useState<SubscriptionPlan[]>([]);
+ const [isLoadingPlans, setIsLoadingPlans] = useState(false);
+
+ // Fetch user profile after login
+ // Find this function in AuthContext.tsx and update it:
+const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['data'] | null> => {
+ try {
+ const result = await AuthApiService.getUserProfile(apiKey);
+ console.log('AuthContext: Raw profile result:', result); // Add this debug line
+
+ if (result.success && result.data) {
+ // Fix: Extract the nested data properly
+ const profileData = result.data.data || result.data;
+ console.log('AuthContext: Extracted profile data:', profileData); // Add this debug line
+ return profileData;
+ }
+ return null;
+ } catch (error) {
+ console.error('Failed to fetch user profile:', error);
+ return null;
+ }
+};
+
+ // Fetch user subscription data
+ const fetchUserSubscription = async (apiKey: string): Promise<UserSubscription | null> => {
+ try {
+ const result = await PaymentApiService.getUserSubscription(apiKey);
+ if (result.success && result.data) {
+ return result.data;
+ }
+ return null;
+ } catch (error) {
+ console.error('Failed to fetch user subscription:', error);
+ return null;
+ }
+ };
+
+ // Refresh user data including subscription
+ const refreshUserData = async (): Promise<void> => {
+ if (!session?.api_key || session.user_type !== 'registered') return;
+
+ try {
+ const [userProfile, userSubscription] = await Promise.all([
+ fetchUserProfile(session.api_key),
+ fetchUserSubscription(session.api_key)
+ ]);
+
+ if (userProfile) {
+ const updatedSession: SessionData = {
+ ...session,
+ user_info: {
+ username: userProfile.username,
+ email: userProfile.email,
+ account_type: userProfile.account_type,
+ credit_balance: userProfile.credit_balance,
+ is_verified: userProfile.is_verified,
+ mfa_enabled: userProfile.mfa_enabled
+ },
+ subscription: userSubscription || undefined
+ };
+
+ setSession(updatedSession);
+ saveSession(updatedSession);
+ }
+ } catch (error) {
+ console.error('Failed to refresh user data:', error);
+ }
+ };
// Validate session with API
const validateSession = async (sessionData: SessionData): Promise<SessionData | null> => {
@@ -160,15 +306,33 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
if (result.success && result.data?.authenticated) {
const apiData = result.data;
+
+ // For registered users, fetch detailed profile and subscription
+ let userProfile = null;
+ let userSubscription = null;
+
+ if (apiData.user_type === 'registered') {
+ userProfile = await fetchUserProfile(sessionData.api_key);
+ userSubscription = await fetchUserSubscription(sessionData.api_key);
+ }
+
return {
authenticated: true,
user_type: apiData.user_type,
api_key: sessionData.api_key,
device_id: sessionData.device_id,
- user_info: apiData.user_type === 'registered' ? apiData.user : undefined,
+ user_info: apiData.user_type === 'registered' && userProfile ? {
+ username: userProfile.username,
+ email: userProfile.email,
+ account_type: userProfile.account_type,
+ credit_balance: userProfile.credit_balance,
+ is_verified: userProfile.is_verified,
+ mfa_enabled: userProfile.mfa_enabled
+ } : apiData.user,
expires_at: apiData.user_type === 'guest' ? apiData.guest?.expires_at : undefined,
daily_limit: apiData.user_type === 'guest' ? apiData.guest?.daily_limit : undefined,
- requests_today: apiData.user_type === 'guest' ? apiData.guest?.requests_today : undefined
+ requests_today: apiData.user_type === 'guest' ? apiData.guest?.requests_today : undefined,
+ subscription: userSubscription || undefined
};
}
@@ -186,22 +350,21 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const savedSession = loadSession();
console.log('AuthContext: Saved session:', savedSession ? 'Found' : 'Not found');
+ // In your AuthContext useEffect:
if (savedSession) {
- console.log('AuthContext: Validating session with API...');
- // For development, skip API validation to avoid CORS issues
- if (import.meta.env.DEV) {
- console.log('AuthContext: Development mode - using saved session without validation');
- setSession(savedSession);
- } else {
+ if (savedSession.user_type === 'registered') {
+ // Always validate registered users, even in dev mode
const validatedSession = await validateSession(savedSession);
if (validatedSession) {
- console.log('AuthContext: Session validated successfully');
setSession(validatedSession);
saveSession(validatedSession);
} else {
- console.log('AuthContext: Session validation failed, clearing...');
+ console.log('Session validation failed, clearing...');
clearSession();
}
+ } else {
+ // Only skip validation for guest users in dev mode
+ setSession(savedSession);
}
}
@@ -219,11 +382,7 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// Check API connectivity
const checkApiConnectivity = async (): Promise<boolean> => {
try {
- console.log('Checking API connectivity...');
-
const isConnected = await AuthApiService.checkHealth();
-
- console.log('API connectivity result:', isConnected);
return isConnected;
} catch (error) {
console.error('API connectivity check failed:', error);
@@ -231,6 +390,86 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
}
};
+ // Fetch subscription plans
+ // Fetch subscription plans
+ const fetchPlans = async (): Promise<{ success: boolean; error?: string }> => {
+ setIsLoadingPlans(true);
+ try {
+ console.log('AuthContext: Fetching plans from API...');
+ const result = await PaymentApiService.getSubscriptionPlans();
+
+ console.log('AuthContext: Plans API result:', result);
+
+ if (result.success && result.data) {
+ // Handle the nested response structure: result.data.data.plans
+ const plansData = result.data.data || result.data;
+ const plans = plansData.plans || [];
+
+ console.log('AuthContext: Extracted plans:', plans);
+ console.log('AuthContext: Number of plans:', plans.length);
+
+ if (plans.length > 0) {
+ setAvailablePlans(plans);
+ console.log('AuthContext: Plans set successfully');
+ return { success: true };
+ } else {
+ console.log('AuthContext: No plans found in response');
+ return { success: false, error: 'No plans available' };
+ }
+ } else {
+ console.log('AuthContext: API request failed:', result.error);
+ return { success: false, error: result.error || 'Failed to fetch plans' };
+ }
+ } catch (error) {
+ console.error('AuthContext: Failed to fetch plans:', error);
+ return { success: false, error: 'Failed to fetch plans' };
+ } finally {
+ setIsLoadingPlans(false);
+ }
+ };
+
+ // Create payment session
+ const createPaymentSession = async (planId: string): Promise<{ success: boolean; data?: PaymentSession; error?: string }> => {
+ if (!session?.api_key) {
+ return { success: false, error: 'No API key available' };
+ }
+
+ try {
+ const result = await PaymentApiService.createCheckoutSession(session.api_key, {
+ plan_id: planId,
+ return_url: `${window.location.origin}/payment-success`
+ });
+
+ if (result.success && result.data) {
+ return { success: true, data: result.data };
+ } else {
+ return { success: false, error: result.error || 'Failed to create payment session' };
+ }
+ } catch (error) {
+ console.error('Failed to create payment session:', error);
+ return { success: false, error: 'Failed to create payment session' };
+ }
+ };
+
+ // Get user subscription
+ const getUserSubscription = async (): Promise<{ success: boolean; data?: UserSubscription; error?: string }> => {
+ if (!session?.api_key) {
+ return { success: false, error: 'No API key available' };
+ }
+
+ try {
+ const result = await PaymentApiService.getUserSubscription(session.api_key);
+ if (result.success) {
+ return { success: true, data: result.data };
+ } else {
+ return { success: false, error: result.error || 'Failed to get subscription' };
+ }
+ } catch (error) {
+ console.error('Failed to get subscription:', error);
+ return { success: false, error: 'Failed to get subscription' };
+ }
+ };
+
// Login function
const login = async (email: string, password: string): Promise<{ success: boolean; error?: string }> => {
try {
@@ -238,28 +477,52 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const result = await AuthApiService.login({ email, password }) as ApiResponse;
- if (result.success && result.data) {
- const apiData = result.data;
- const newSession: SessionData = {
- authenticated: true,
- user_type: 'registered',
- api_key: apiData.api_key,
- device_id: generateDeviceId(),
- user_info: {
- username: apiData.username,
- email: apiData.email,
- credit_balance: apiData.credit_balance
- }
- };
+ console.log('AuthContext: Full login result:', result);
+ console.log('AuthContext: result.success:', result.success);
+ console.log('AuthContext: result.data:', result.data);
+
+ // In AuthContext.tsx, update the login function around line 480-515:
+
+if (result.success && result.data && result.data.data && result.data.data.api_key) {
+ const apiKey = result.data.data.api_key;
+ console.log('AuthContext: Login successful, API key received:', apiKey.substring(0, 20) + '...');
+
+ // Fetch user profile and subscription to get account_type and other details
+ const [userProfile, userSubscription] = await Promise.all([
+ fetchUserProfile(apiKey),
+ fetchUserSubscription(apiKey)
+ ]);
+
+ const newSession: SessionData = {
+ authenticated: true,
+ user_type: 'registered',
+ api_key: apiKey,
+ device_id: generateDeviceId(),
+ user_info: userProfile ? {
+ username: userProfile.username,
+ email: userProfile.email,
+ account_type: userProfile.account_type, // ← This should be working
+ credit_balance: userProfile.credit_balance,
+ is_verified: userProfile.is_verified,
+ mfa_enabled: userProfile.mfa_enabled
+ } : {
+ // Fallback if profile fetch fails - assume free account
+ email: email,
+ account_type: 'free', // ← Make sure this fallback is 'free', not undefined
+ credit_balance: 0
+ },
+ subscription: userSubscription || undefined
+ };
- setSession(newSession);
- saveSession(newSession);
- setIsFirstTimeUser(checkIsFirstTimeUser());
+ setSession(newSession);
+ saveSession(newSession);
+ setIsFirstTimeUser(checkIsFirstTimeUser());
- console.log('AuthContext: Login successful');
- return { success: true };
- } else {
- console.log('AuthContext: Login failed:', result.message || result.error);
+ console.log('AuthContext: Login successful, account_type:', newSession.user_info?.account_type);
+ console.log('AuthContext: Has subscription:', !!newSession.subscription?.has_subscription);
+ return { success: true };
+} else {
+ console.log('AuthContext: Login failed - success:', result.success, 'data:', result.data, 'api_key:', result.data?.api_key);
return {
success: false,
error: result.message || result.error || 'Login failed'
@@ -277,8 +540,6 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// Signup function
const signup = async (username: string, email: string, password: string): Promise<{ success: boolean; error?: string }> => {
try {
- console.log('AuthContext: Attempting signup for:', username, email);
-
const result = await AuthApiService.register({
username,
email,
@@ -286,17 +547,14 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
}) as ApiResponse;
if (result.success) {
- console.log('AuthContext: Signup successful, OTP sent');
return { success: true };
} else {
- console.log('AuthContext: Signup failed:', result.message || result.error);
return {
success: false,
error: result.message || result.error || 'Registration failed'
};
}
} catch (error) {
- console.error('AuthContext: Signup error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Registration failed'
@@ -307,39 +565,48 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// OTP verification
const verifyOtp = async (email: string, otp: string): Promise<{ success: boolean; error?: string }> => {
try {
- console.log('AuthContext: Verifying OTP for:', email);
-
const result = await AuthApiService.verifyOtp({ email, otp }) as ApiResponse;
- if (result.success && result.data) {
- const apiData = result.data;
+ if (result.success && result.data && result.data.data && result.data.data.api_key) {
+ const apiKey = result.data.data.api_key;
+ console.log('AuthContext: OTP verification successful, API key received');
+
+ // Fetch user profile for new registered user (no subscription yet)
+ const userProfile = await fetchUserProfile(apiKey);
+
const newSession: SessionData = {
authenticated: true,
user_type: 'registered',
- api_key: apiData.api_key,
+ api_key: apiKey,
device_id: generateDeviceId(),
- user_info: {
- username: apiData.username,
- email: apiData.email,
- credit_balance: apiData.credit_balance
- }
+ user_info: userProfile ? {
+ username: userProfile.username,
+ email: userProfile.email,
+ account_type: userProfile.account_type,
+ credit_balance: userProfile.credit_balance,
+ is_verified: userProfile.is_verified,
+ mfa_enabled: userProfile.mfa_enabled
+ } : {
+ // Fallback if profile fetch fails - assume free account
+ email: email,
+ account_type: 'free',
+ credit_balance: 0
+ },
+ subscription: undefined // New user won't have subscription yet
};
setSession(newSession);
saveSession(newSession);
setIsFirstTimeUser(checkIsFirstTimeUser());
- console.log('AuthContext: OTP verification successful');
return { success: true };
} else {
- console.log('AuthContext: OTP verification failed:', result.message || result.error);
return {
success: false,
error: result.message || result.error || 'Verification failed'
};
}
} catch (error) {
- console.error('AuthContext: OTP verification error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Verification failed'
@@ -350,22 +617,11 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// Forgot password function
const forgotPassword = async (email: string): Promise<{ success: boolean; error?: string }> => {
try {
- console.log('AuthContext: Requesting password reset for:', email);
-
const result = await AuthApiService.forgotPassword({ email }) as ApiResponse;
-
- if (result.success) {
- console.log('AuthContext: Password reset OTP sent successfully');
- return { success: true };
- } else {
- console.log('AuthContext: Password reset request failed:', result.message || result.error);
- return {
- success: false,
- error: result.message || result.error || 'Failed to send reset email'
- };
- }
+ return result.success
+ ? { success: true }
+ : { success: false, error: result.message || result.error || 'Failed to send reset email' };
} catch (error) {
- console.error('AuthContext: Forgot password error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to send reset email'
@@ -376,26 +632,16 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// Reset password function
const resetPassword = async (email: string, otp: string, newPassword: string): Promise<{ success: boolean; error?: string }> => {
try {
- console.log('AuthContext: Attempting password reset for:', email);
-
const result = await AuthApiService.resetPassword({
email,
otp,
new_password: newPassword
}) as ApiResponse;
- if (result.success) {
- console.log('AuthContext: Password reset successful');
- return { success: true };
- } else {
- console.log('AuthContext: Password reset failed:', result.message || result.error);
- return {
- success: false,
- error: result.message || result.error || 'Password reset failed'
- };
- }
+ return result.success
+ ? { success: true }
+ : { success: false, error: result.message || result.error || 'Password reset failed' };
} catch (error) {
- console.error('AuthContext: Reset password error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Password reset failed'
@@ -406,18 +652,13 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
// Guest access setup
const setupGuestAccess = async (): Promise<{ success: boolean; error?: string }> => {
try {
- console.log('AuthContext: Setting up guest access...');
-
- // For development, create a mock guest session
if (import.meta.env.DEV) {
- console.log('AuthContext: Development mode - creating mock guest session');
-
const mockGuestSession: SessionData = {
authenticated: true,
user_type: 'guest',
api_key: 'mock_guest_api_key_' + Date.now(),
device_id: generateDeviceId(),
- expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24 hours
+ expires_at: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
daily_limit: 50,
requests_today: 0
};
@@ -426,7 +667,6 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
saveSession(mockGuestSession);
setIsFirstTimeUser(checkIsFirstTimeUser());
- console.log('AuthContext: Mock guest session created');
return { success: true };
}
@@ -459,41 +699,14 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
saveSession(guestSession);
setIsFirstTimeUser(checkIsFirstTimeUser());
- console.log('AuthContext: Guest access setup successful');
return { success: true };
- } else if (result.status_code === 409) {
- console.log('AuthContext: Device exists, getting existing session...');
-
- const statusResult = await AuthApiService.getGuestStatus(deviceId) as ApiResponse;
-
- if (statusResult.success && statusResult.data) {
- const statusData = statusResult.data;
- const existingSession: SessionData = {
- authenticated: true,
- user_type: 'guest',
- api_key: statusData.api_key,
- device_id: deviceId,
- expires_at: statusData.expires_at,
- daily_limit: statusData.daily_limit || 50,
- requests_today: statusData.requests_today || 0
- };
-
- setSession(existingSession);
- saveSession(existingSession);
- setIsFirstTimeUser(checkIsFirstTimeUser());
-
- console.log('AuthContext: Existing guest session retrieved');
- return { success: true };
- }
}
- console.log('AuthContext: Guest setup failed:', result.message || result.error);
return {
success: false,
error: result.message || result.error || 'Failed to setup guest access'
};
} catch (error) {
- console.error('AuthContext: Guest setup error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Failed to setup guest access'
@@ -505,14 +718,6 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
const logout = async (): Promise<void> => {
console.log('AuthContext: Logging out...');
- if (session?.api_key) {
- try {
- await AuthApiService.logout(session.api_key);
- } catch (error) {
- console.error('Logout API call failed:', error);
- }
- }
-
setSession(null);
clearSession();
setIsFirstTimeUser(checkIsFirstTimeUser());
@@ -524,6 +729,8 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
session,
isLoading,
isFirstTimeUser,
+ availablePlans,
+ isLoadingPlans,
login,
signup,
verifyOtp,
@@ -531,7 +738,11 @@ export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
logout,
checkApiConnectivity,
forgotPassword,
- resetPassword
+ resetPassword,
+ fetchPlans,
+ createPaymentSession,
+ getUserSubscription,
+ refreshUserData
};
return (
diff --git a/fincept-terminal-desktop/src/hooks/use-mobile.ts b/fincept-terminal-desktop/src/hooks/use-mobile.ts
new file mode 100644
index 000000000..2b0fe1dfe
--- /dev/null
+++ b/fincept-terminal-desktop/src/hooks/use-mobile.ts
@@ -0,0 +1,19 @@
+import * as React from "react"
+
+const MOBILE_BREAKPOINT = 768
+
+export function useIsMobile() {
+ const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
+
+ React.useEffect(() => {
+ const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
+ const onChange = () => {
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
+ }
+ mql.addEventListener("change", onChange)
+ setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
+ return () => mql.removeEventListener("change", onChange)
+ }, [])
+
+ return !!isMobile
+}
diff --git a/fincept-terminal-desktop/src/services/authApi.tsx b/fincept-terminal-desktop/src/services/authApi.tsx
index 3d33b69f0..6520de7b0 100644
--- a/fincept-terminal-desktop/src/services/authApi.tsx
+++ b/fincept-terminal-desktop/src/services/authApi.tsx
@@ -3,7 +3,7 @@
// API Configuration
const API_CONFIG = {
- BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ BASE_URL: 'http://localhost:4500',
API_VERSION: 'v1',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
@@ -66,18 +66,36 @@ interface LoginResponse {
credit_balance: number;
}
+interface UserProfileResponse {
+ id: number;
+ username: string;
+ email: string;
+ account_type: string;
+ credit_balance: number;
+ is_verified: boolean;
+ mfa_enabled: boolean;
+ created_at: string;
+ last_login_at: string;
+}
+
interface AuthStatusResponse {
authenticated: boolean;
user_type: 'guest' | 'registered';
user?: {
+ id: number;
username: string;
email: string;
+ account_type: string;
credit_balance: number;
+ created_at: string;
};
guest?: {
- expires_at: string;
- daily_limit: number;
+ id: number;
+ device_id: string;
+ platform: string;
requests_today: number;
+ expires_at: string;
+ daily_limit?: number;
};
}
@@ -99,17 +117,16 @@ const makeApiRequest = async <T = any>(
try {
const defaultHeaders = {
'Content-Type': 'application/json',
- 'skip_zrok_interstitial': '1',
...headers
};
const url = getApiEndpoint(endpoint);
- console.log('🚀 Making request:', {
+ console.log('🚀 Making auth request:', {
method,
url,
endpoint,
data,
- headers: defaultHeaders
+ headers: { ...defaultHeaders, 'X-API-Key': defaultHeaders['X-API-Key'] ? '[REDACTED]' : undefined }
});
const config: RequestInit = {
@@ -124,7 +141,7 @@ const makeApiRequest = async <T = any>(
const response = await fetch(url, config);
- console.log('📡 Response received:', {
+ console.log('📡 Auth response received:', {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries(response.headers.entries()),
@@ -132,15 +149,15 @@ const makeApiRequest = async <T = any>(
});
const responseText = await response.text();
- console.log('📝 Raw response text:', responseText.substring(0, 200));
+ console.log('📄 Raw auth response text:', responseText.substring(0, 200));
let responseData;
try {
responseData = JSON.parse(responseText);
- console.log('✅ Parsed JSON:', responseData);
+ console.log('✅ Parsed auth JSON:', responseData);
} catch (parseError) {
- console.error('❌ JSON parse failed:', parseError);
- console.log('📄 Full response text:', responseText);
+ console.error('❌ Auth JSON parse failed:', parseError);
+ console.log('📄 Full auth response text:', responseText);
return {
success: false,
@@ -157,7 +174,7 @@ const makeApiRequest = async <T = any>(
};
} catch (error) {
- console.error('💥 Request failed completely:', error);
+ console.error('💥 Auth request failed completely:', error);
if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
return {
@@ -188,32 +205,32 @@ export class AuthApiService {
// Login user
static async login(request: LoginRequest): Promise<ApiResponse<LoginResponse>> {
- return makeApiRequest<LoginResponse>('POST', '/auth/login', request);
+ return makeApiRequest<LoginResponse>('POST', '/user/login', request);
}
// Register user
static async register(request: RegisterRequest): Promise<ApiResponse> {
- return makeApiRequest('POST', '/auth/register', request);
+ return makeApiRequest('POST', '/user/register', request);
}
// Verify OTP
static async verifyOtp(request: VerifyOtpRequest): Promise<ApiResponse<LoginResponse>> {
- return makeApiRequest<LoginResponse>('POST', '/auth/verify-otp', request);
+ return makeApiRequest<LoginResponse>('POST', '/user/verify-otp', request);
}
// Forgot password
static async forgotPassword(request: ForgotPasswordRequest): Promise<ApiResponse> {
- return makeApiRequest('POST', '/auth/forgot-password', request);
+ return makeApiRequest('POST', '/user/forgot-password', request);
}
// Reset password
static async resetPassword(request: ResetPasswordRequest): Promise<ApiResponse> {
- return makeApiRequest('POST', '/auth/reset-password', request);
+ return makeApiRequest('POST', '/user/reset-password', request);
}
- // Logout user
- static async logout(apiKey: string): Promise<ApiResponse> {
- return makeApiRequest('POST', '/auth/logout', undefined, {
+ // Get user profile
+ static async getUserProfile(apiKey: string): Promise<ApiResponse<UserProfileResponse>> {
+ return makeApiRequest<UserProfileResponse>('GET', '/user/profile', undefined, {
'X-API-Key': apiKey
});
}
@@ -233,15 +250,171 @@ export class AuthApiService {
// Register device for guest access
static async registerDevice(request: DeviceRegisterRequest): Promise<ApiResponse<DeviceRegisterResponse>> {
- return makeApiRequest<DeviceRegisterResponse>('POST', '/device/register', request);
+ return makeApiRequest<DeviceRegisterResponse>('POST', '/guest/register', request);
}
// Get guest status
- static async getGuestStatus(deviceId: string): Promise<ApiResponse<DeviceRegisterResponse>> {
- return makeApiRequest<DeviceRegisterResponse>('GET', '/guest/status', undefined, {
- 'X-Device-ID': deviceId
+ static async getGuestStatus(apiKey: string): Promise<ApiResponse<any>> {
+ return makeApiRequest('GET', '/guest/status', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Update user profile
+ static async updateUserProfile(apiKey: string, profileData: Partial<UserProfileResponse>): Promise<ApiResponse> {
+ return makeApiRequest('PUT', '/user/profile', profileData, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Regenerate API key
+ static async regenerateApiKey(apiKey: string): Promise<ApiResponse<{ api_key: string }>> {
+ return makeApiRequest('POST', '/user/regenerate-api-key', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get user usage statistics
+ static async getUserUsage(apiKey: string): Promise<ApiResponse<any>> {
+ return makeApiRequest('GET', '/user/usage', undefined, {
+ 'X-API-Key': apiKey
});
}
+
+ // Get user subscriptions (database subscriptions, not payment subscriptions)
+ static async getUserSubscriptions(apiKey: string): Promise<ApiResponse<any>> {
+ return makeApiRequest('GET', '/user/subscriptions', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Subscribe to database
+ static async subscribeToDatabase(apiKey: string, databaseName: string): Promise<ApiResponse> {
+ return makeApiRequest('POST', '/user/subscribe', { database_name: databaseName }, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get user transactions
+ static async getUserTransactions(apiKey: string): Promise<ApiResponse<any>> {
+ return makeApiRequest('GET', '/user/transactions', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Delete user account
+ static async deleteAccount(apiKey: string, password: string): Promise<ApiResponse> {
+ return makeApiRequest('DELETE', '/user/account', { password }, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Test API connectivity with authentication
+ static async testApiConnectivity(apiKey?: string): Promise<{
+ success: boolean;
+ response?: any;
+ error?: string;
+ authenticated?: boolean;
+ }> {
+ try {
+ // Test basic connectivity
+ const healthResult = await this.checkHealth();
+ if (!healthResult) {
+ return { success: false, error: 'API server is not responding' };
+ }
+
+ // Test authentication if API key provided
+ if (apiKey) {
+ const authResult = await this.getAuthStatus(apiKey, 'test_device');
+ return {
+ success: authResult.success,
+ response: authResult.data,
+ authenticated: authResult.data?.authenticated || false,
+ error: authResult.error
+ };
+ }
+
+ // Test unauthenticated endpoint
+ const testResult = await makeApiRequest('GET', '/test');
+ return {
+ success: testResult.success,
+ response: testResult.data,
+ error: testResult.error
+ };
+
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Connectivity test failed'
+ };
+ }
+ }
+
+ // Validate session
+ static async validateSession(apiKey: string, deviceId: string): Promise<{
+ valid: boolean;
+ userType?: 'guest' | 'registered';
+ userData?: any;
+ error?: string;
+ }> {
+ try {
+ const result = await this.getAuthStatus(apiKey, deviceId);
+
+ if (result.success && result.data?.authenticated) {
+ return {
+ valid: true,
+ userType: result.data.user_type,
+ userData: result.data.user || result.data.guest
+ };
+ } else {
+ return {
+ valid: false,
+ error: result.error || 'Session invalid'
+ };
+ }
+ } catch (error) {
+ return {
+ valid: false,
+ error: error instanceof Error ? error.message : 'Session validation failed'
+ };
+ }
+ }
+
+ // Refresh user session data
+ static async refreshSession(apiKey: string): Promise<ApiResponse<{
+ profile: UserProfileResponse;
+ usage: any;
+ subscriptions: any;
+ }>> {
+ try {
+ const [profileResult, usageResult, subscriptionsResult] = await Promise.all([
+ this.getUserProfile(apiKey),
+ this.getUserUsage(apiKey),
+ this.getUserSubscriptions(apiKey)
+ ]);
+
+ if (profileResult.success) {
+ return {
+ success: true,
+ data: {
+ profile: profileResult.data!,
+ usage: usageResult.data,
+ subscriptions: subscriptionsResult.data
+ }
+ };
+ } else {
+ return {
+ success: false,
+ error: profileResult.error || 'Failed to refresh session'
+ };
+ }
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Session refresh failed'
+ };
+ }
+ }
}
// Utility function to generate device ID
@@ -269,4 +442,138 @@ export const generateDeviceId = (): string => {
return `desktop_${Math.abs(hash).toString(16)}`;
};
+// Auth utility functions
+export class AuthUtils {
+ // Check if user is authenticated
+ static isAuthenticated(session: any): boolean {
+ return !!(session?.authenticated && session?.api_key);
+ }
+
+ // Check if user is admin
+ static isAdmin(session: any): boolean {
+ return this.isAuthenticated(session) && session?.user_info?.is_admin === true;
+ }
+
+ // Check if user has verified email
+ static isVerified(session: any): boolean {
+ return this.isAuthenticated(session) && session?.user_info?.is_verified === true;
+ }
+
+ // Check if user is on free plan
+ static isFreePlan(session: any): boolean {
+ return session?.user_info?.account_type === 'free';
+ }
+
+ // Check if user has active subscription
+ static hasActiveSubscription(session: any): boolean {
+ return session?.subscription?.has_subscription === true;
+ }
+
+ // Get user display name
+ static getDisplayName(session: any): string {
+ if (session?.user_type === 'guest') {
+ return 'Guest User';
+ }
+ return session?.user_info?.username || session?.user_info?.email || 'User';
+ }
+
+ // Get account type display name
+ static getAccountTypeDisplay(accountType: string): string {
+ const typeMap: Record<string, string> = {
+ 'free': 'Free',
+ 'starter': 'Starter',
+ 'professional': 'Professional',
+ 'enterprise': 'Enterprise',
+ 'unlimited': 'Unlimited'
+ };
+ return typeMap[accountType] || accountType;
+ }
+
+ // Check if session is expiring soon (for guest users)
+ static isSessionExpiringSoon(session: any, minutesThreshold: number = 30): boolean {
+ if (session?.user_type !== 'guest' || !session?.expires_at) {
+ return false;
+ }
+
+ const expiryTime = new Date(session.expires_at).getTime();
+ const currentTime = new Date().getTime();
+ const timeDiff = expiryTime - currentTime;
+ const minutesRemaining = timeDiff / (1000 * 60);
+
+ return minutesRemaining <= minutesThreshold && minutesRemaining > 0;
+ }
+
+ // Format time remaining for guest sessions
+ static formatTimeRemaining(expiresAt: string): string {
+ const expiryTime = new Date(expiresAt).getTime();
+ const currentTime = new Date().getTime();
+ const timeDiff = expiryTime - currentTime;
+
+ if (timeDiff <= 0) {
+ return 'Expired';
+ }
+
+ const hours = Math.floor(timeDiff / (1000 * 60 * 60));
+ const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
+
+ if (hours > 0) {
+ return `${hours}h ${minutes}m`;
+ } else {
+ return `${minutes}m`;
+ }
+ }
+
+ // Validate email format
+ static isValidEmail(email: string): boolean {
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ return emailRegex.test(email);
+ }
+
+ // Validate password strength
+ static validatePassword(password: string): {
+ isValid: boolean;
+ errors: string[];
+ score: number;
+ } {
+ const errors: string[] = [];
+ let score = 0;
+
+ if (password.length < 8) {
+ errors.push('Password must be at least 8 characters long');
+ } else {
+ score += 1;
+ }
+
+ if (!/[A-Z]/.test(password)) {
+ errors.push('Password must contain at least one uppercase letter');
+ } else {
+ score += 1;
+ }
+
+ if (!/[a-z]/.test(password)) {
+ errors.push('Password must contain at least one lowercase letter');
+ } else {
+ score += 1;
+ }
+
+ if (!/\d/.test(password)) {
+ errors.push('Password must contain at least one number');
+ } else {
+ score += 1;
+ }
+
+ if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
+ errors.push('Password should contain at least one special character');
+ } else {
+ score += 1;
+ }
+
+ return {
+ isValid: errors.length === 0,
+ errors,
+ score: Math.min(score, 5)
+ };
+ }
+}
+
export default AuthApiService;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/forumApi.tsx b/fincept-terminal-desktop/src/services/forumApi.tsx
new file mode 100644
index 000000000..c82f13eca
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/forumApi.tsx
@@ -0,0 +1,471 @@
+// File: src/services/forumApi.ts
+// Forum API service for handling all forum-related API calls
+
+// API Configuration - matches your existing auth setup
+const API_CONFIG = {
+ BASE_URL: import.meta.env.DEV ? '/api' : 'https://finceptbackend.share.zrok.io',
+ API_VERSION: 'v1',
+ CONNECTION_TIMEOUT: 10000,
+ REQUEST_TIMEOUT: 30000
+};
+
+const getApiEndpoint = (path: string) => `${API_CONFIG.BASE_URL}${path}`;
+
+// Forum Types
+export interface ForumCategory {
+ id: number;
+ name: string;
+ description: string;
+ post_count: number;
+ created_at: string;
+}
+
+export interface ForumPost {
+ post_uuid: string;
+ title: string;
+ content: string;
+ author_display_name: string;
+ category_id: number;
+ category_name: string;
+ likes: number;
+ dislikes: number;
+ reply_count: number;
+ views: number;
+ is_pinned: boolean;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ForumComment {
+ comment_uuid: string;
+ post_uuid: string;
+ content: string;
+ author_display_name: string;
+ likes: number;
+ dislikes: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ForumStats {
+ total_categories: number;
+ total_posts: number;
+ total_comments: number;
+ total_votes: number;
+ active_users: number;
+}
+
+export interface PostDetails {
+ post: ForumPost;
+ comments: ForumComment[];
+}
+
+export interface SearchResults {
+ posts: ForumPost[];
+ total_results: number;
+}
+
+// API Response Types
+interface ApiResponse<T = any> {
+ success: boolean;
+ data?: {
+ success: boolean;
+ data: T;
+ message?: string;
+ };
+ message?: string;
+ error?: string;
+ status_code?: number;
+}
+
+// Request Types
+interface CreatePostRequest {
+ title: string;
+ content: string;
+ category_id: number;
+}
+
+interface CreateCommentRequest {
+ content: string;
+}
+
+interface VoteRequest {
+ vote_type: 'up' | 'down';
+}
+
+interface SearchRequest {
+ q: string;
+ post_type?: 'all' | 'posts' | 'comments';
+ limit?: number;
+}
+
+// Generic API request function with auth headers
+const makeForumRequest = async <T = any>(
+ method: string,
+ endpoint: string,
+ apiKey?: string,
+ deviceId?: string,
+ data?: any
+): Promise<ApiResponse<T>> => {
+ try {
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ 'skip_zrok_interstitial': '1'
+ };
+
+ // Add authentication headers if available
+ if (apiKey) {
+ headers['X-API-Key'] = apiKey;
+ }
+ if (deviceId) {
+ headers['X-Device-ID'] = deviceId;
+ }
+
+ const url = getApiEndpoint(endpoint);
+ console.log('🔥 Forum API Request:', {
+ method,
+ url,
+ endpoint,
+ hasApiKey: !!apiKey,
+ hasDeviceId: !!deviceId,
+ data
+ });
+
+ const config: RequestInit = {
+ method,
+ headers,
+ mode: 'cors',
+ };
+
+ if (data && (method === 'POST' || method === 'PUT')) {
+ config.body = JSON.stringify(data);
+ }
+
+ const response = await fetch(url, config);
+
+ console.log('📡 Forum Response:', {
+ status: response.status,
+ statusText: response.statusText,
+ url: response.url
+ });
+
+ const responseText = await response.text();
+ console.log('📄 Forum Response Text:', responseText.substring(0, 200));
+
+ let responseData;
+ try {
+ responseData = JSON.parse(responseText);
+ console.log('✅ Forum Parsed JSON:', responseData);
+ } catch (parseError) {
+ console.error('❌ Forum 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('💥 Forum 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 or try again later.'
+ };
+ }
+
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Network error'
+ };
+ }
+};
+
+// Forum API Service Class
+export class ForumApiService {
+
+ // Get all forum categories
+ static async getCategories(apiKey?: string, deviceId?: string): Promise<ApiResponse<{ categories: ForumCategory[] }>> {
+ return makeForumRequest<{ categories: ForumCategory[] }>('GET', '/forum/categories', apiKey, deviceId);
+ }
+
+ // Get posts by category
+ static async getPostsByCategory(
+ categoryId: number,
+ sortBy: string = 'latest',
+ limit: number = 20,
+ apiKey?: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ posts: ForumPost[]; category: ForumCategory }>> {
+ return makeForumRequest<{ posts: ForumPost[]; category: ForumCategory }>(
+ 'GET',
+ `/forum/categories/${categoryId}/posts?sort_by=${sortBy}&limit=${limit}`,
+ apiKey,
+ deviceId
+ );
+ }
+
+ // Get all posts (recent/trending)
+ static async getAllPosts(
+ sortBy: string = 'latest',
+ limit: number = 20,
+ apiKey?: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ posts: ForumPost[] }>> {
+ return makeForumRequest<{ posts: ForumPost[] }>(
+ 'GET',
+ `/forum/posts?sort_by=${sortBy}&limit=${limit}`,
+ apiKey,
+ deviceId
+ );
+ }
+
+ // Get post details with comments
+ static async getPostDetails(
+ postUuid: string,
+ apiKey?: string,
+ deviceId?: string
+ ): Promise<ApiResponse<PostDetails>> {
+ return makeForumRequest<PostDetails>('GET', `/forum/posts/${postUuid}`, apiKey, deviceId);
+ }
+
+ // Create new post
+ static async createPost(
+ request: CreatePostRequest,
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ post: ForumPost }>> {
+ return makeForumRequest<{ post: ForumPost }>('POST', '/forum/posts', apiKey, deviceId, request);
+ }
+
+ // Add comment to post
+ static async addComment(
+ postUuid: string,
+ request: CreateCommentRequest,
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ comment: ForumComment }>> {
+ return makeForumRequest<{ comment: ForumComment }>(
+ 'POST',
+ `/forum/posts/${postUuid}/comments`,
+ apiKey,
+ deviceId,
+ request
+ );
+ }
+
+ // Vote on post
+ static async voteOnPost(
+ postUuid: string,
+ voteType: 'up' | 'down',
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ action: string; vote_score: number }>> {
+ return makeForumRequest<{ action: string; vote_score: number }>(
+ 'POST',
+ `/forum/posts/${postUuid}/vote`,
+ apiKey,
+ deviceId,
+ { vote_type: voteType }
+ );
+ }
+
+ // Vote on comment
+ static async voteOnComment(
+ commentUuid: string,
+ voteType: 'up' | 'down',
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ action: string; vote_score: number }>> {
+ return makeForumRequest<{ action: string; vote_score: number }>(
+ 'POST',
+ `/forum/comments/${commentUuid}/vote`,
+ apiKey,
+ deviceId,
+ { vote_type: voteType }
+ );
+ }
+
+ // Search forum posts
+ static async searchPosts(
+ query: string,
+ postType: string = 'all',
+ limit: number = 20,
+ apiKey?: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ results: { posts: ForumPost[] } }>> {
+ return makeForumRequest<{ results: { posts: ForumPost[] } }>(
+ 'GET',
+ `/forum/search?q=${encodeURIComponent(query)}&post_type=${postType}&limit=${limit}`,
+ apiKey,
+ deviceId
+ );
+ }
+
+ // Get forum statistics
+ static async getForumStats(apiKey?: string, deviceId?: string): Promise<ApiResponse<ForumStats>> {
+ return makeForumRequest<ForumStats>('GET', '/forum/stats', apiKey, deviceId);
+ }
+
+ // Get user's posts
+ static async getUserPosts(apiKey: string, deviceId?: string): Promise<ApiResponse<{ posts: ForumPost[] }>> {
+ return makeForumRequest<{ posts: ForumPost[] }>('GET', '/forum/user/posts', apiKey, deviceId);
+ }
+
+ // Get user's activity (posts and comments)
+ static async getUserActivity(apiKey: string, deviceId?: string): Promise<ApiResponse<{
+ posts: ForumPost[];
+ comments: ForumComment[];
+ total_votes_received: number;
+ }>> {
+ return makeForumRequest<{
+ posts: ForumPost[];
+ comments: ForumComment[];
+ total_votes_received: number;
+ }>('GET', '/forum/user/activity', apiKey, deviceId);
+ }
+
+ // Delete post (if user is author)
+ static async deletePost(
+ postUuid: string,
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ message: string }>> {
+ return makeForumRequest<{ message: string }>('DELETE', `/forum/posts/${postUuid}`, apiKey, deviceId);
+ }
+
+ // Delete comment (if user is author)
+ static async deleteComment(
+ commentUuid: string,
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ message: string }>> {
+ return makeForumRequest<{ message: string }>('DELETE', `/forum/comments/${commentUuid}`, apiKey, deviceId);
+ }
+
+ // Edit post (if user is author)
+ static async editPost(
+ postUuid: string,
+ updates: { title?: string; content?: string },
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ post: ForumPost }>> {
+ return makeForumRequest<{ post: ForumPost }>('PUT', `/forum/posts/${postUuid}`, apiKey, deviceId, updates);
+ }
+
+ // Edit comment (if user is author)
+ static async editComment(
+ commentUuid: string,
+ content: string,
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ comment: ForumComment }>> {
+ return makeForumRequest<{ comment: ForumComment }>(
+ 'PUT',
+ `/forum/comments/${commentUuid}`,
+ apiKey,
+ deviceId,
+ { content }
+ );
+ }
+
+ // Pin/Unpin post (admin only)
+ static async togglePostPin(
+ postUuid: string,
+ apiKey: string,
+ deviceId?: string
+ ): Promise<ApiResponse<{ post: ForumPost }>> {
+ return makeForumRequest<{ post: ForumPost }>('POST', `/forum/posts/${postUuid}/toggle-pin`, apiKey, deviceId);
+ }
+}
+
+// Utility functions for forum operations
+export const ForumUtils = {
+
+ // Format timestamp for display
+ formatTimestamp: (timestamp: string): string => {
+ try {
+ if (!timestamp) return 'Recent';
+
+ const date = timestamp.endsWith('Z')
+ ? new Date(timestamp.replace('Z', '+00:00'))
+ : new Date(timestamp);
+
+ return date.toLocaleString('en-US', {
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false
+ });
+ } catch (error) {
+ return 'Recent';
+ }
+ },
+
+ // Calculate vote score
+ calculateVoteScore: (likes: number, dislikes: number): number => {
+ return likes - dislikes;
+ },
+
+ // Get vote color based on score
+ getVoteColor: (score: number): string => {
+ if (score > 0) return 'text-green-400';
+ if (score < 0) return 'text-red-400';
+ return 'text-zinc-400';
+ },
+
+ // Truncate text for preview
+ truncateText: (text: string, maxLength: number): string => {
+ if (text.length <= maxLength) return text;
+ return text.substring(0, maxLength) + '...';
+ },
+
+ // Format large numbers
+ formatNumber: (num: number): string => {
+ if (num >= 1000000) {
+ return (num / 1000000).toFixed(1) + 'M';
+ } else if (num >= 1000) {
+ return (num / 1000).toFixed(1) + 'K';
+ }
+ return num.toString();
+ },
+
+ // Validate post content
+ validatePost: (title: string, content: string): { valid: boolean; error?: string } => {
+ if (!title.trim()) {
+ return { valid: false, error: 'Post title is required' };
+ }
+ if (title.length > 200) {
+ return { valid: false, error: 'Post title must be less than 200 characters' };
+ }
+ if (!content.trim()) {
+ return { valid: false, error: 'Post content is required' };
+ }
+ if (content.length > 10000) {
+ return { valid: false, error: 'Post content must be less than 10,000 characters' };
+ }
+ return { valid: true };
+ },
+
+ // Validate comment content
+ validateComment: (content: string): { valid: boolean; error?: string } => {
+ if (!content.trim()) {
+ return { valid: false, error: 'Comment content is required' };
+ }
+ if (content.length > 2000) {
+ return { valid: false, error: 'Comment must be less than 2,000 characters' };
+ }
+ return { valid: true };
+ }
+};
+
+export default ForumApiService;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/fyers-auth.js b/fincept-terminal-desktop/src/services/fyers-auth.js
new file mode 100644
index 000000000..dbb2508e3
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/fyers-auth.js
@@ -0,0 +1,163 @@
+const axios = require("axios");
+const { authenticator } = require("otplib");
+const crypto = require("crypto");
+const { JSDOM } = require("jsdom");
+
+// Mock browser environment
+const dom = new JSDOM("", { url: "http://localhost", pretendToBeVisual: true });
+global.window = dom.window;
+global.document = window.document;
+global.navigator = window.navigator;
+global.WebSocket = require("ws");
+
+const { fyersDataSocket, fyersOrderSocket } = require("fyers-web-sdk-v3");
+
+// Configuration
+const CONFIG = {
+ CLIENT_ID: "XB02507",
+ PIN: "1590",
+ APP_ID: "NDM5TDN9DB",
+ APP_TYPE: "100",
+ APP_SECRET: "UR9IJU1U0E",
+ TOTP_KEY: "XOYMD3QRDV6QPNSWK3WSKMD642KGODJQ",
+};
+
+async function authenticate() {
+ let res = await axios.post("https://api-t2.fyers.in/vagator/v2/send_login_otp", {
+ fy_id: CONFIG.CLIENT_ID,
+ app_id: "2",
+ });
+ let key = res.data.request_key;
+
+ const totp = authenticator.generate(CONFIG.TOTP_KEY);
+ res = await axios.post("https://api-t2.fyers.in/vagator/v2/verify_otp", {
+ request_key: key,
+ otp: totp,
+ });
+ key = res.data.request_key;
+
+ res = await axios.post("https://api-t2.fyers.in/vagator/v2/verify_pin", {
+ request_key: key,
+ identity_type: "pin",
+ identifier: CONFIG.PIN,
+ });
+ const token1 = res.data.data.access_token;
+
+ try {
+ res = await axios.post(
+ "https://api-t1.fyers.in/api/v3/token",
+ {
+ fyers_id: CONFIG.CLIENT_ID,
+ app_id: CONFIG.APP_ID,
+ redirect_uri: "https://trade.fyers.in/api-login/redirect-uri/index.html",
+ appType: CONFIG.APP_TYPE,
+ code_challenge: "",
+ state: "sample_state",
+ scope: "",
+ nonce: "",
+ response_type: "code",
+ create_cookie: true,
+ },
+ { headers: { Authorization: `Bearer ${token1}` }, validateStatus: () => true }
+ );
+ } catch (error) {
+ res = error.response;
+ }
+
+ const authCode = new URL(res.data.Url).searchParams.get("auth_code");
+ const hash = crypto.createHash("sha256").update(`${CONFIG.APP_ID}-${CONFIG.APP_TYPE}:${CONFIG.APP_SECRET}`).digest("hex");
+
+ res = await axios.post("https://api-t1.fyers.in/api/v3/validate-authcode", {
+ grant_type: "authorization_code",
+ appIdHash: hash,
+ code: authCode,
+ });
+
+ return `${CONFIG.APP_ID}-${CONFIG.APP_TYPE}:${res.data.access_token}`;
+}
+
+async function main() {
+ const accessToken = await authenticate();
+ console.log("Authenticated successfully\n");
+
+ // === MARKET DATA WebSocket ===
+ const fyersData = new fyersDataSocket(accessToken);
+
+ fyersData.on("connect", () => {
+ console.log("Market Data WebSocket CONNECTED\n");
+ fyersData.subscribe(["NSE:PCJEWELLER-EQ"]);
+ });
+
+ fyersData.on("message", (msg) => {
+ console.log("\n=== MARKET DATA ===");
+ console.log(JSON.stringify(msg, null, 2));
+ console.log("===================\n");
+ });
+
+ fyersData.on("error", (err) => {
+ console.log("\n=== MARKET DATA ERROR ===");
+ console.log(JSON.stringify(err, null, 2));
+ console.log("=========================\n");
+ });
+
+ fyersData.autoreconnect();
+ fyersData.connect();
+
+ // === ORDER WebSocket ===
+ const fyersOrderdata = new fyersOrderSocket(accessToken);
+
+ fyersOrderdata.on("error", (errmsg) => {
+ console.log("\n=== ORDER ERROR ===");
+ console.log(JSON.stringify(errmsg, null, 2));
+ console.log("===================\n");
+ });
+
+ fyersOrderdata.on("general", (msg) => {
+ console.log("\n=== ORDER GENERAL ===");
+ console.log(JSON.stringify(msg, null, 2));
+ console.log("=====================\n");
+ });
+
+ fyersOrderdata.on("connect", () => {
+ console.log("Order WebSocket CONNECTED\n");
+ fyersOrderdata.subscribe([
+ fyersOrderdata.orderUpdates,
+ fyersOrderdata.tradeUpdates,
+ fyersOrderdata.positionUpdates,
+ fyersOrderdata.edis,
+ fyersOrderdata.pricealerts
+ ]);
+ });
+
+ fyersOrderdata.on("close", () => {
+ console.log("\n=== ORDER WEBSOCKET CLOSED ===\n");
+ });
+
+ fyersOrderdata.on("orders", (msg) => {
+ console.log("\n=== ORDER UPDATE ===");
+ console.log(JSON.stringify(msg, null, 2));
+ console.log("====================\n");
+ });
+
+ fyersOrderdata.on("trades", (msg) => {
+ console.log("\n=== TRADE UPDATE ===");
+ console.log(JSON.stringify(msg, null, 2));
+ console.log("====================\n");
+ });
+
+ fyersOrderdata.on("positions", (msg) => {
+ console.log("\n=== POSITION UPDATE ===");
+ console.log(JSON.stringify(msg, null, 2));
+ console.log("=======================\n");
+ });
+
+ fyersOrderdata.autoreconnect();
+ fyersOrderdata.connect();
+
+ process.on("SIGINT", () => {
+ console.log("\nDisconnecting...");
+ process.exit(0);
+ });
+}
+
+main().catch(console.error);
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/paymentApi.tsx b/fincept-terminal-desktop/src/services/paymentApi.tsx
new file mode 100644
index 000000000..bd8bf9aae
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/paymentApi.tsx
@@ -0,0 +1,698 @@
+// File: src/services/paymentApi.ts
+// Payment API service for handling all payment-related API calls with in-app payment window support
+
+// API Configuration
+const PAYMENT_API_CONFIG = {
+ BASE_URL: 'http://localhost:4500',
+ CONNECTION_TIMEOUT: 10000,
+ REQUEST_TIMEOUT: 30000
+};
+
+const getPaymentApiEndpoint = (path: string) => `${PAYMENT_API_CONFIG.BASE_URL}${path}`;
+
+// API Response Types
+interface PaymentApiResponse<T = any> {
+ success: boolean;
+ data?: T;
+ message?: string;
+ error?: string;
+ status_code?: number;
+}
+
+// Request Types
+interface CheckoutRequest {
+ plan_id: string;
+ return_url?: string;
+}
+
+// Response Types
+interface SubscriptionPlan {
+ plan_id: string;
+ name: string;
+ description: string;
+ price_usd: number;
+ billing_interval: string;
+ api_calls_limit: number | string;
+ databases_access: string[];
+ priority_support: boolean;
+ features: {
+ api_calls: string;
+ databases: string;
+ support: string;
+ };
+}
+
+interface PlansResponse {
+ plans: SubscriptionPlan[];
+ total_plans: number;
+}
+
+interface CheckoutResponse {
+ checkout_url: string;
+ session_id: string;
+ payment_uuid: string;
+ plan: {
+ name: string;
+ price: number;
+ };
+}
+
+interface UserSubscriptionResponse {
+ has_subscription: boolean;
+ subscription?: {
+ subscription_uuid: string;
+ plan: {
+ name: string;
+ plan_id: string;
+ price: number;
+ };
+ status: string;
+ current_period_start: string;
+ current_period_end: string;
+ days_remaining: number;
+ cancel_at_period_end: boolean;
+ usage: {
+ api_calls_used: number;
+ api_calls_limit: number | string;
+ usage_percentage: number;
+ };
+ };
+}
+
+interface PaymentSuccessResponse {
+ message: string;
+ payment_uuid: string;
+ status: string;
+ amount: number;
+}
+
+interface PaymentHistoryItem {
+ payment_uuid: string;
+ amount: number;
+ currency: string;
+ status: string;
+ payment_method: string;
+ created_at: string;
+ completed_at: string | null;
+ subscription_plan: string;
+}
+
+interface PaymentHistoryResponse {
+ payments: PaymentHistoryItem[];
+ pagination: {
+ current_page: number;
+ per_page: number;
+ total_payments: number;
+ total_pages: number;
+ };
+}
+
+// Payment Window Manager Interface
+interface PaymentWindowManager {
+ openPaymentWindow: (url: string, planName: string, planPrice: number) => Promise<boolean>;
+}
+
+// Global payment window manager - will be set by the main app
+let paymentWindowManager: PaymentWindowManager | null = null;
+
+export const setPaymentWindowManager = (manager: PaymentWindowManager) => {
+ paymentWindowManager = manager;
+};
+
+// Generic Payment API request function with enhanced debugging
+const makePaymentApiRequest = async <T = any>(
+ method: string,
+ endpoint: string,
+ data?: any,
+ headers?: Record<string, string>
+): Promise<PaymentApiResponse<T>> => {
+ try {
+ const defaultHeaders = {
+ 'Content-Type': 'application/json',
+ ...headers
+ };
+
+ const url = getPaymentApiEndpoint(endpoint);
+
+ // Enhanced debug logging
+ console.log('💳 Making payment request:', {
+ method,
+ url,
+ endpoint,
+ data,
+ timestamp: new Date().toISOString()
+ });
+
+ // Debug headers (with API key redacted)
+ const debugHeaders = { ...defaultHeaders };
+ if (debugHeaders['X-API-Key']) {
+ debugHeaders['X-API-Key'] = '[REDACTED - Length: ' + debugHeaders['X-API-Key'].length + ']';
+ }
+ console.log('💳 Request headers:', debugHeaders);
+
+ // Check if API key is actually present
+ const hasApiKey = !!headers?.['X-API-Key'];
+ const apiKeyLength = headers?.['X-API-Key']?.length || 0;
+ console.log('💳 API Key debug:', {
+ hasApiKey,
+ apiKeyLength,
+ headerKeys: Object.keys(defaultHeaders),
+ originalHeaderKeys: headers ? Object.keys(headers) : 'none'
+ });
+
+ const config: RequestInit = {
+ method,
+ headers: defaultHeaders,
+ mode: 'cors',
+ };
+
+ if (data && (method === 'POST' || method === 'PUT')) {
+ config.body = JSON.stringify(data);
+ console.log('💳 Request body:', JSON.stringify(data, null, 2));
+ }
+
+ console.log('💳 Final fetch config:', {
+ url,
+ method: config.method,
+ mode: config.mode,
+ hasBody: !!config.body,
+ bodyLength: config.body ? config.body.length : 0
+ });
+
+ const response = await fetch(url, config);
+
+ console.log('💰 Payment response received:', {
+ status: response.status,
+ statusText: response.statusText,
+ url: response.url,
+ ok: response.ok,
+ headers: Object.fromEntries(response.headers.entries())
+ });
+
+ const responseText = await response.text();
+ console.log('📄 Payment response text (first 500 chars):', responseText.substring(0, 500));
+ console.log('📄 Payment response full length:', responseText.length);
+
+ let responseData;
+ try {
+ responseData = JSON.parse(responseText);
+ console.log('✅ Payment JSON parsed successfully:', {
+ success: responseData.success,
+ hasData: !!responseData.data,
+ message: responseData.message,
+ error: responseData.error,
+ errorCode: responseData.error_code
+ });
+ } catch (parseError) {
+ console.error('❌ Payment JSON parse failed:', parseError);
+ console.log('📄 Raw response that failed to parse:', responseText);
+ return {
+ success: false,
+ error: `Invalid JSON response: ${responseText.substring(0, 100)}...`,
+ status_code: response.status
+ };
+ }
+
+ // Enhanced response logging for failures
+ if (!response.ok) {
+ console.error('❌ Payment request failed:', {
+ status: response.status,
+ statusText: response.statusText,
+ responseData,
+ requestHeaders: debugHeaders,
+ requestUrl: url,
+ requestMethod: method
+ });
+ }
+
+ return {
+ success: response.ok,
+ data: responseData,
+ status_code: response.status,
+ error: response.ok ? undefined : responseData.message || `HTTP ${response.status}`
+ };
+
+ } catch (error) {
+ console.error('💥 Payment request failed completely:', error);
+ console.error('💥 Error details:', {
+ name: error instanceof Error ? error.name : 'Unknown',
+ message: error instanceof Error ? error.message : 'Unknown error',
+ stack: error instanceof Error ? error.stack : 'No stack trace'
+ });
+
+ if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
+ return {
+ success: false,
+ error: 'Network error: Unable to connect to payment server. Please check your connection.'
+ };
+ }
+
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : 'Payment network error'
+ };
+ }
+};
+
+// Payment API Service Class with enhanced debugging
+export class PaymentApiService {
+ // Get all subscription plans
+ static async getSubscriptionPlans(): Promise<PaymentApiResponse<PlansResponse>> {
+ console.log('📋 PaymentApiService: Starting getSubscriptionPlans request');
+
+ const result = await makePaymentApiRequest<PlansResponse>('GET', '/payment/plans');
+
+ console.log('📋 PaymentApiService: getSubscriptionPlans result:', {
+ success: result.success,
+ hasData: !!result.data,
+ statusCode: result.status_code,
+ error: result.error
+ });
+
+ if (result.success && result.data) {
+ console.log('📋 PaymentApiService: Raw API response structure:', {
+ dataKeys: Object.keys(result.data),
+ hasPlans: !!(result.data as any).plans,
+ hasDataProperty: !!(result.data as any).data,
+ plansCount: (result.data as any).plans?.length || 'no plans array'
+ });
+
+ // Check if the data has the expected structure
+ if ((result.data as any).plans) {
+ console.log('📋 PaymentApiService: Found plans directly in result.data');
+ console.log('📋 PaymentApiService: Number of plans:', (result.data as any).plans.length);
+ } else if ((result.data as any).data && (result.data as any).data.plans) {
+ console.log('📋 PaymentApiService: Found plans in result.data.data');
+ console.log('📋 PaymentApiService: Number of plans:', (result.data as any).data.plans.length);
+ } else {
+ console.log('📋 PaymentApiService: Plans not found in expected location');
+ console.log('📋 PaymentApiService: Available properties:', Object.keys(result.data));
+ }
+ }
+
+ return result;
+ }
+
+ // Get specific plan details
+ static async getPlanDetails(planId: string): Promise<PaymentApiResponse<SubscriptionPlan>> {
+ console.log('📋 PaymentApiService: Getting plan details for:', planId);
+ return makePaymentApiRequest<SubscriptionPlan>('GET', `/payment/plans/${planId}`);
+ }
+
+ // Create checkout session with enhanced debugging
+ static async createCheckoutSession(
+ apiKey: string,
+ request: CheckoutRequest
+ ): Promise<PaymentApiResponse<CheckoutResponse>> {
+ console.log('🔑 PaymentApiService: createCheckoutSession called');
+ console.log('🔑 PaymentApiService: API Key debug:', {
+ hasApiKey: !!apiKey,
+ apiKeyType: typeof apiKey,
+ apiKeyLength: apiKey?.length || 0,
+ apiKeyPrefix: apiKey ? apiKey.substring(0, 10) + '...' : 'null',
+ apiKeyValid: apiKey && apiKey.length > 10
+ });
+ console.log('🔑 PaymentApiService: Request data:', request);
+
+ // Verify API key format
+ if (!apiKey) {
+ console.error('🔑 PaymentApiService: No API key provided!');
+ return {
+ success: false,
+ error: 'No API key provided'
+ };
+ }
+
+ if (typeof apiKey !== 'string') {
+ console.error('🔑 PaymentApiService: API key is not a string:', typeof apiKey);
+ return {
+ success: false,
+ error: 'Invalid API key format'
+ };
+ }
+
+ // Test different header variations to debug the issue
+ const headers = {
+ 'X-API-Key': apiKey
+ };
+
+ console.log('🔑 PaymentApiService: Headers being passed:', {
+ 'X-API-Key': '[REDACTED - Length: ' + apiKey.length + ']',
+ headerCount: Object.keys(headers).length
+ });
+
+ const result = await makePaymentApiRequest<CheckoutResponse>('POST', '/payment/checkout', request, headers);
+
+ console.log('🔑 PaymentApiService: createCheckoutSession result:', {
+ success: result.success,
+ statusCode: result.status_code,
+ error: result.error,
+ hasData: !!result.data
+ });
+
+ return result;
+ }
+
+ // Handle payment success
+ static async handlePaymentSuccess(
+ apiKey: string,
+ sessionId?: string,
+ paymentId?: string
+ ): Promise<PaymentApiResponse<PaymentSuccessResponse>> {
+ console.log('✅ PaymentApiService: handlePaymentSuccess called:', {
+ hasApiKey: !!apiKey,
+ sessionId,
+ paymentId
+ });
+
+ const params = new URLSearchParams();
+ if (sessionId) params.append('session_id', sessionId);
+ if (paymentId) params.append('payment_id', paymentId);
+
+ const queryString = params.toString();
+ const endpoint = `/payment/success${queryString ? `?${queryString}` : ''}`;
+
+ return makePaymentApiRequest<PaymentSuccessResponse>('GET', endpoint, undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get user's current subscription
+ static async getUserSubscription(apiKey: string): Promise<PaymentApiResponse<UserSubscriptionResponse>> {
+ console.log('👤 PaymentApiService: getUserSubscription called:', {
+ hasApiKey: !!apiKey,
+ apiKeyLength: apiKey?.length || 0
+ });
+
+ return makePaymentApiRequest<UserSubscriptionResponse>('GET', '/payment/subscription', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get user's usage details
+ static async getUserUsage(apiKey: string): Promise<PaymentApiResponse<any>> {
+ console.log('📊 PaymentApiService: getUserUsage called');
+ return makePaymentApiRequest('GET', '/payment/usage', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Cancel subscription
+ static async cancelSubscription(apiKey: string): Promise<PaymentApiResponse<any>> {
+ console.log('❌ PaymentApiService: cancelSubscription called');
+ return makePaymentApiRequest('POST', '/payment/cancel', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Reactivate subscription
+ static async reactivateSubscription(apiKey: string): Promise<PaymentApiResponse<any>> {
+ console.log('🔄 PaymentApiService: reactivateSubscription called');
+ return makePaymentApiRequest('POST', '/payment/reactivate', undefined, {
+ 'X-API-Key': apiKey
+ });
+ }
+
+ // Get payment history
+ static async getPaymentHistory(
+ apiKey: string,
+ page: number = 1,
+ limit: number = 10
+ ): Promise<PaymentApiResponse<PaymentHistoryResponse>> {
+ console.log('📜 PaymentApiService: getPaymentHistory called:', { page, limit });
+ return makePaymentApiRequest<PaymentHistoryResponse>(
+ 'GET',
+ `/payment/payments?page=${page}&limit=${limit}`,
+ undefined,
+ { 'X-API-Key': apiKey }
+ );
+ }
+
+ // Get specific payment details
+ static async getPaymentDetails(
+ apiKey: string,
+ paymentUuid: string
+ ): Promise<PaymentApiResponse<any>> {
+ console.log('💳 PaymentApiService: getPaymentDetails called:', paymentUuid);
+ return makePaymentApiRequest(
+ 'GET',
+ `/payment/payments/${paymentUuid}`,
+ undefined,
+ { 'X-API-Key': apiKey }
+ );
+ }
+
+ // Webhook validation (for future use)
+ static async validateWebhook(webhookData: any): Promise<PaymentApiResponse<any>> {
+ console.log('🔗 PaymentApiService: validateWebhook called');
+ return makePaymentApiRequest('POST', '/payment/webhook', webhookData);
+ }
+
+ // Debug function to test API key validity
+ static async testApiKey(apiKey: string): Promise<PaymentApiResponse<any>> {
+ console.log('🧪 PaymentApiService: Testing API key validity');
+ console.log('🧪 API Key test details:', {
+ hasApiKey: !!apiKey,
+ apiKeyLength: apiKey?.length || 0,
+ apiKeyPrefix: apiKey ? apiKey.substring(0, 15) + '...' : 'null'
+ });
+
+ // Try a simple GET request first
+ const testResult = await makePaymentApiRequest('GET', '/payment/subscription', undefined, {
+ 'X-API-Key': apiKey
+ });
+
+ console.log('🧪 API Key test result:', {
+ success: testResult.success,
+ statusCode: testResult.status_code,
+ error: testResult.error
+ });
+
+ return testResult;
+ }
+}
+
+// Updated PaymentUtils class with in-app window support
+export class PaymentUtils {
+ // Format currency
+ static formatCurrency(amount: number, currency: string = 'USD'): string {
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: currency,
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ }).format(amount);
+ }
+
+ // Calculate annual savings
+ static calculateAnnualSavings(monthlyPrice: number): number {
+ const annualPrice = monthlyPrice * 10; // 2 months free
+ const fullYearPrice = monthlyPrice * 12;
+ return fullYearPrice - annualPrice;
+ }
+
+ // Get plan recommendation based on usage
+ static getRecommendedPlan(apiCallsPerMonth: number): string {
+ if (apiCallsPerMonth <= 10000) return 'starter_20';
+ if (apiCallsPerMonth <= 50000) return 'professional_49';
+ if (apiCallsPerMonth <= 200000) return 'enterprise_99';
+ return 'unlimited_199';
+ }
+
+ // Validate plan selection
+ static validatePlanSelection(planId: string, availablePlans: SubscriptionPlan[]): boolean {
+ return availablePlans.some(plan => plan.plan_id === planId);
+ }
+
+ // Parse URL parameters for payment success page
+ static parsePaymentParams(url: string): { sessionId?: string; paymentId?: string } {
+ const urlParams = new URLSearchParams(url.split('?')[1]);
+ return {
+ sessionId: urlParams.get('session_id') || undefined,
+ paymentId: urlParams.get('payment_id') || undefined
+ };
+ }
+
+ // Check if subscription is expiring soon (within 7 days)
+ static isSubscriptionExpiringSoon(endDate: string): boolean {
+ const end = new Date(endDate);
+ const now = new Date();
+ const daysUntilExpiry = Math.ceil((end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));
+ return daysUntilExpiry <= 7 && daysUntilExpiry > 0;
+ }
+
+ // Get usage percentage with color coding
+ static getUsageStatus(used: number, limit: number | string): {
+ percentage: number;
+ status: 'low' | 'medium' | 'high' | 'critical';
+ color: string;
+ } {
+ if (limit === 'unlimited' || limit === -1) {
+ return { percentage: 0, status: 'low', color: 'green' };
+ }
+
+ const limitNum = typeof limit === 'string' ? parseInt(limit) : limit;
+ const percentage = Math.min((used / limitNum) * 100, 100);
+
+ let status: 'low' | 'medium' | 'high' | 'critical';
+ let color: string;
+
+ if (percentage >= 95) {
+ status = 'critical';
+ color = 'red';
+ } else if (percentage >= 80) {
+ status = 'high';
+ color = 'orange';
+ } else if (percentage >= 50) {
+ status = 'medium';
+ color = 'yellow';
+ } else {
+ status = 'low';
+ color = 'green';
+ }
+
+ return { percentage: Math.round(percentage), status, color };
+ }
+
+ // Validate payment URL before opening
+ // Validate payment URL before opening
+static validatePaymentUrl(url: string): boolean {
+ if (!url || url === 'undefined' || url === 'null') {
+ return false;
+ }
+
+ try {
+ const urlObj = new URL(url);
+
+ // Check for valid protocols
+ if (!['http:', 'https:'].includes(urlObj.protocol)) {
+ return false;
+ }
+
+ // Updated: Remove overly restrictive validation
+ // Only block obviously dangerous patterns
+ const dangerousPatterns = [
+ 'javascript:',
+ 'data:',
+ 'file:',
+ ];
+
+ for (const pattern of dangerousPatterns) {
+ if (url.toLowerCase().includes(pattern)) {
+ console.warn('PaymentUtils: Dangerous URL pattern detected:', pattern);
+ return false;
+ }
+ }
+
+ // Allow all HTTPS URLs from legitimate payment providers
+ if (urlObj.protocol === 'https:') {
+ return true;
+ }
+
+ return true;
+ } catch (error) {
+ console.error('PaymentUtils: Invalid URL format:', error);
+ return false;
+ }
+}
+
+ // Updated: Open payment URL using in-app window
+ static async openPaymentUrl(
+ checkoutUrl: string,
+ planName: string = 'Subscription',
+ planPrice: number = 0
+ ): Promise<boolean> {
+ console.log('PaymentUtils: Opening payment URL:', checkoutUrl);
+
+ // Validate the checkout URL
+ if (!this.validatePaymentUrl(checkoutUrl)) {
+ console.error('PaymentUtils: Invalid checkout URL provided');
+ alert('Payment URL is invalid. Please try again or contact support.');
+ return false;
+ }
+
+ try {
+ // Try to use in-app payment window first
+ if (paymentWindowManager) {
+ console.log('PaymentUtils: Using in-app payment window');
+ return await paymentWindowManager.openPaymentWindow(checkoutUrl, planName, planPrice);
+ }
+
+ // Fallback to external browser if in-app window is not available
+ console.log('PaymentUtils: Falling back to external browser');
+ return this.openPaymentUrlExternal(checkoutUrl);
+
+ } catch (error) {
+ console.error('PaymentUtils: Failed to open payment window:', error);
+
+ // Final fallback to external browser
+ return this.openPaymentUrlExternal(checkoutUrl);
+ }
+ }
+
+ // Enhanced payment URL opener with validation
+ static async openValidatedPaymentUrl(
+ checkoutUrl: string,
+ planName: string = 'Subscription',
+ planPrice: number = 0
+ ): Promise<boolean> {
+ // Validate URL first
+ if (!this.validatePaymentUrl(checkoutUrl)) {
+ console.error('PaymentUtils: Invalid or suspicious payment URL');
+ alert('Invalid payment URL. Please contact support.');
+ return false;
+ }
+
+ return this.openPaymentUrl(checkoutUrl, planName, planPrice);
+ }
+
+ // Fallback method: Open external payment URL
+ private static openPaymentUrlExternal(checkoutUrl: string): boolean {
+ try {
+ const newWindow = window.open(checkoutUrl, '_blank', 'noopener,noreferrer');
+
+ if (!newWindow) {
+ console.warn('PaymentUtils: Popup blocked, trying clipboard fallback');
+
+ // Try to copy URL to clipboard as fallback
+ if (navigator.clipboard && checkoutUrl !== 'undefined') {
+ navigator.clipboard.writeText(checkoutUrl).then(() => {
+ alert(`Popup blocked. Payment URL copied to clipboard: ${checkoutUrl}`);
+ }).catch(() => {
+ alert(`Please visit this URL to complete payment: ${checkoutUrl}`);
+ });
+ } else {
+ alert(`Please visit this URL to complete payment: ${checkoutUrl}`);
+ }
+
+ return false;
+ }
+
+ return true;
+
+ } catch (error) {
+ console.error('PaymentUtils: Failed to open external payment URL:', error);
+ alert(`Please visit this URL to complete payment: ${checkoutUrl}`);
+ return false;
+ }
+ }
+
+ // Generate receipt data for successful payment
+ static generateReceiptData(paymentData: any): {
+ receiptId: string;
+ date: string;
+ description: string;
+ amount: string;
+ status: string;
+ } {
+ return {
+ receiptId: paymentData.payment_uuid || 'N/A',
+ date: new Date().toLocaleDateString(),
+ description: `Fincept API Subscription - ${paymentData.plan?.name || 'Plan'}`,
+ amount: this.formatCurrency(paymentData.plan?.price || 0),
+ status: paymentData.status || 'Completed'
+ };
+ }
+}
+
+export default PaymentApiService;
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/stockBrokers/india/zerodhaKite/kiteAdapter.tsx b/fincept-terminal-desktop/src/stockBrokers/india/zerodhaKite/kiteAdapter.tsx
new file mode 100644
index 000000000..3871ef622
--- /dev/null
+++ b/fincept-terminal-desktop/src/stockBrokers/india/zerodhaKite/kiteAdapter.tsx
@@ -0,0 +1,1445 @@
+// kite-connect-adapter.ts
+// Comprehensive TypeScript adapter for Zerodha Kite Connect API v3
+// Modular design for plug-and-play integration
+
+import axios, { AxiosInstance, AxiosResponse } from 'axios';
+import crypto from 'crypto';
+
+// ================================
+// TYPE DEFINITIONS
+// ================================
+
+export interface KiteConfig {
+ apiKey: string;
+ apiSecret: string;
+ accessToken?: string;
+ baseUrl?: string;
+ timeout?: number;
+}
+
+export interface SessionData {
+ user_type: string;
+ email: string;
+ user_name: string;
+ user_shortname: string;
+ broker: string;
+ exchanges: string[];
+ products: string[];
+ order_types: string[];
+ avatar_url: string;
+ user_id: string;
+ api_key: string;
+ access_token: string;
+ public_token: string;
+ refresh_token: string;
+ silo: string;
+ login_time: string;
+}
+
+export interface OrderParams {
+ tradingsymbol: string;
+ exchange: string;
+ transaction_type: 'BUY' | 'SELL';
+ order_type: 'MARKET' | 'LIMIT' | 'SL' | 'SL-M';
+ quantity: number;
+ product: 'CNC' | 'MIS' | 'NRML' | 'MTF';
+ validity?: 'DAY' | 'IOC' | 'TTL';
+ validity_ttl?: number;
+ price?: number;
+ trigger_price?: number;
+ disclosed_quantity?: number;
+ variety?: 'regular' | 'amo' | 'co' | 'iceberg' | 'auction';
+ tag?: string;
+ iceberg_legs?: number;
+ iceberg_quantity?: number;
+ auction_number?: string;
+ market_protection?: number;
+ autoslice?: boolean;
+}
+
+export interface OrderResponse {
+ order_id: string;
+}
+
+export interface Order {
+ order_id: string;
+ parent_order_id?: string;
+ exchange_order_id?: string;
+ placed_by: string;
+ variety: string;
+ status: string;
+ status_message?: string;
+ order_timestamp: string;
+ exchange_timestamp?: string;
+ exchange_update_timestamp?: string;
+ tradingsymbol: string;
+ exchange: string;
+ instrument_token: number;
+ transaction_type: string;
+ order_type: string;
+ product: string;
+ validity: string;
+ price: number;
+ quantity: number;
+ trigger_price: number;
+ average_price: number;
+ pending_quantity: number;
+ filled_quantity: number;
+ disclosed_quantity: number;
+ cancelled_quantity: number;
+ market_protection: number;
+ meta: Record<string, any>;
+ tag?: string;
+ guid: string;
+ modified: boolean;
+}
+
+export interface Trade {
+ trade_id: string;
+ order_id: string;
+ exchange_order_id?: string;
+ tradingsymbol: string;
+ exchange: string;
+ instrument_token: number;
+ transaction_type: string;
+ product: string;
+ average_price: number;
+ quantity: number;
+ fill_timestamp: string;
+ exchange_timestamp: string;
+ order_timestamp: string;
+}
+
+export interface Quote {
+ instrument_token: number;
+ timestamp?: string;
+ last_trade_time?: string;
+ last_price: number;
+ last_quantity?: number;
+ buy_quantity?: number;
+ sell_quantity?: number;
+ volume?: number;
+ average_price?: number;
+ oi?: number;
+ oi_day_high?: number;
+ oi_day_low?: number;
+ net_change?: number;
+ lower_circuit_limit?: number;
+ upper_circuit_limit?: number;
+ ohlc?: {
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ };
+ depth?: {
+ buy: Array<{
+ price: number;
+ quantity: number;
+ orders: number;
+ }>;
+ sell: Array<{
+ price: number;
+ quantity: number;
+ orders: number;
+ }>;
+ };
+}
+
+export interface Holding {
+ tradingsymbol: string;
+ exchange: string;
+ instrument_token: number;
+ isin: string;
+ product: string;
+ price: number;
+ quantity: number;
+ used_quantity: number;
+ t1_quantity: number;
+ realised_quantity: number;
+ authorised_quantity: number;
+ authorised_date: string;
+ opening_quantity: number;
+ collateral_quantity: number;
+ collateral_type: string;
+ discrepancy: boolean;
+ average_price: number;
+ last_price: number;
+ close_price: number;
+ pnl: number;
+ day_change: number;
+ day_change_percentage: number;
+}
+
+export interface Position {
+ tradingsymbol: string;
+ exchange: string;
+ instrument_token: number;
+ product: string;
+ quantity: number;
+ overnight_quantity: number;
+ multiplier: number;
+ average_price: number;
+ close_price: number;
+ last_price: number;
+ value: number;
+ pnl: number;
+ m2m: number;
+ unrealised: number;
+ realised: number;
+ buy_quantity: number;
+ buy_price: number;
+ buy_value: number;
+ buy_m2m: number;
+ sell_quantity: number;
+ sell_price: number;
+ sell_value: number;
+ sell_m2m: number;
+ day_buy_quantity: number;
+ day_buy_price: number;
+ day_buy_value: number;
+ day_sell_quantity: number;
+ day_sell_price: number;
+ day_sell_value: number;
+}
+
+export interface HistoricalParams {
+ instrument_token: string;
+ interval: 'minute' | 'day' | '3minute' | '5minute' | '10minute' | '15minute' | '30minute' | '60minute';
+ from: string; // 'yyyy-mm-dd hh:mm:ss'
+ to: string; // 'yyyy-mm-dd hh:mm:ss'
+ continuous?: boolean;
+ oi?: boolean;
+}
+
+export interface CandleData {
+ timestamp: string;
+ open: number;
+ high: number;
+ low: number;
+ close: number;
+ volume: number;
+ oi?: number;
+}
+
+export interface GTTParams {
+ type: 'single' | 'two-leg';
+ condition: {
+ exchange: string;
+ tradingsymbol: string;
+ trigger_values: number[];
+ last_price: number;
+ instrument_token?: number;
+ };
+ orders: Array<{
+ exchange: string;
+ tradingsymbol: string;
+ transaction_type: 'BUY' | 'SELL';
+ quantity: number;
+ order_type: 'LIMIT' | 'MARKET';
+ product: string;
+ price?: number;
+ }>;
+}
+
+export interface GTTResponse {
+ trigger_id: number;
+}
+
+export interface GTT {
+ id: number;
+ user_id: string;
+ parent_trigger?: number;
+ type: string;
+ created_at: string;
+ updated_at: string;
+ expires_at: string;
+ status: string;
+ condition: Record<string, any>;
+ orders: Array<Record<string, any>>;
+ meta: Record<string, any>;
+}
+
+export interface AlertParams {
+ name: string;
+ type: 'simple' | 'ato';
+ lhs_exchange: string;
+ lhs_tradingsymbol: string;
+ lhs_attribute: 'LastTradedPrice';
+ operator: '<=' | '>=' | '<' | '>' | '==';
+ rhs_type: 'constant' | 'instrument';
+ rhs_constant?: number;
+ rhs_exchange?: string;
+ rhs_tradingsymbol?: string;
+ rhs_attribute?: string;
+ basket?: string; // JSON string for ATO alerts
+}
+
+export interface Alert {
+ type: string;
+ user_id: string;
+ uuid: string;
+ name: string;
+ status: string;
+ disabled_reason: string;
+ lhs_attribute: string;
+ lhs_exchange: string;
+ lhs_tradingsymbol: string;
+ operator: string;
+ rhs_type: string;
+ rhs_attribute: string;
+ rhs_exchange: string;
+ rhs_tradingsymbol: string;
+ rhs_constant: number;
+ alert_count: number;
+ created_at: string;
+ updated_at: string;
+ basket?: Record<string, any>;
+}
+
+export interface MarginOrder {
+ exchange: string;
+ tradingsymbol: string;
+ transaction_type: 'BUY' | 'SELL';
+ variety: string;
+ product: string;
+ order_type: string;
+ quantity: number;
+ price: number;
+ trigger_price: number;
+}
+
+export interface MarginResponse {
+ type: string;
+ tradingsymbol: string;
+ exchange: string;
+ span: number;
+ exposure: number;
+ option_premium: number;
+ additional: number;
+ bo: number;
+ cash: number;
+ var: number;
+ pnl: {
+ realised: number;
+ unrealised: number;
+ };
+ leverage: number;
+ charges: {
+ transaction_tax: number;
+ transaction_tax_type: string;
+ exchange_turnover_charge: number;
+ sebi_turnover_charge: number;
+ brokerage: number;
+ stamp_duty: number;
+ gst: {
+ igst: number;
+ cgst: number;
+ sgst: number;
+ total: number;
+ };
+ total: number;
+ };
+ total: number;
+}
+
+export interface MFOrder {
+ order_id: string;
+ exchange_order_id?: string;
+ tradingsymbol: string;
+ status: string;
+ status_message?: string;
+ folio?: string;
+ fund: string;
+ order_timestamp: string;
+ exchange_timestamp?: string;
+ settlement_id?: string;
+ transaction_type: 'BUY' | 'SELL';
+ amount: number;
+ variety: string;
+ purchase_type?: string;
+ quantity: number;
+ price: number;
+ last_price: number;
+ average_price: number;
+ placed_by: string;
+ last_price_date: string;
+ tag?: string;
+}
+
+export interface MFHolding {
+ folio?: string;
+ fund: string;
+ tradingsymbol: string;
+ average_price: number;
+ last_price: number;
+ pnl: number;
+ last_price_date: string;
+ quantity: number;
+ pledged_quantity: number;
+}
+
+export interface MFSip {
+ sip_id: string;
+ tradingsymbol: string;
+ fund: string;
+ dividend_type: string;
+ transaction_type: 'BUY' | 'SELL';
+ status: string;
+ created: string;
+ frequency: string;
+ next_instalment: string;
+ instalment_amount: number;
+ instalments: number;
+ last_instalment: string;
+ pending_instalments: number;
+ instalment_day: number;
+ completed_instalments: number;
+ tag?: string;
+ sip_reg_num?: string;
+ step_up?: Record<string, number>;
+}
+
+// ================================
+// MAIN ADAPTER CLASS
+// ================================
+
+export class KiteConnectAdapter {
+ private config: KiteConfig;
+ private client: AxiosInstance;
+ private readonly baseUrl: string;
+
+ constructor(config: KiteConfig) {
+ this.config = config;
+ this.baseUrl = config.baseUrl || 'https://api.kite.trade';
+
+ this.client = axios.create({
+ baseURL: this.baseUrl,
+ timeout: config.timeout || 10000,
+ headers: {
+ 'X-Kite-Version': '3',
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ });
+
+ this.setupInterceptors();
+ }
+
+ private setupInterceptors(): void {
+ // Request interceptor to add auth token
+ this.client.interceptors.request.use(
+ (config) => {
+ if (this.config.accessToken) {
+ config.headers.Authorization = `token ${this.config.apiKey}:${this.config.accessToken}`;
+ }
+ return config;
+ },
+ (error) => Promise.reject(error)
+ );
+
+ // Response interceptor for error handling
+ this.client.interceptors.response.use(
+ (response: AxiosResponse) => response,
+ (error) => {
+ if (error.response?.status === 403) {
+ throw new Error('Token expired or invalid. Please re-authenticate.');
+ }
+ throw error;
+ }
+ );
+ }
+
+ // ================================
+ // AUTHENTICATION METHODS
+ // ================================
+
+ /**
+ * Generate login URL for manual authentication
+ * User must complete this step manually
+ */
+ generateLoginUrl(redirectUrl?: string): string {
+ const url = new URL('https://kite.zerodha.com/connect/login');
+ url.searchParams.set('api_key', this.config.apiKey);
+ if (redirectUrl) {
+ url.searchParams.set('redirect_url', redirectUrl);
+ }
+ return url.toString();
+ }
+
+ /**
+ * Generate session after manual login
+ * Call this with the request_token received from redirect
+ */
+ async generateSession(requestToken: string): Promise<SessionData> {
+ const checksum = crypto
+ .createHash('sha256')
+ .update(this.config.apiKey + requestToken + this.config.apiSecret)
+ .digest('hex');
+
+ const data = new URLSearchParams({
+ api_key: this.config.apiKey,
+ request_token: requestToken,
+ checksum: checksum,
+ });
+
+ const response = await this.client.post('/session/token', data);
+ const sessionData = response.data.data;
+
+ // Store access token for future requests
+ this.config.accessToken = sessionData.access_token;
+
+ return sessionData;
+ }
+
+ /**
+ * Invalidate session
+ */
+ async invalidateSession(): Promise<void> {
+ await this.client.delete('/session/token');
+ this.config.accessToken = undefined;
+ }
+
+ /**
+ * Get user profile
+ */
+ async getProfile(): Promise<any> {
+ const response = await this.client.get('/user/profile');
+ return response.data.data;
+ }
+
+ /**
+ * Get user margins
+ */
+ async getMargins(segment?: string): Promise<any> {
+ const url = segment ? `/user/margins/${segment}` : '/user/margins';
+ const response = await this.client.get(url);
+ return response.data.data;
+ }
+
+ // ================================
+ // ORDER MANAGEMENT
+ // ================================
+
+ /**
+ * Place a new order
+ */
+ async placeOrder(params: OrderParams): Promise<OrderResponse> {
+ const variety = params.variety || 'regular';
+ const data = new URLSearchParams();
+
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined && key !== 'variety') {
+ data.append(key, value.toString());
+ }
+ });
+
+ const response = await this.client.post(`/orders/${variety}`, data);
+ return response.data.data;
+ }
+
+ /**
+ * Modify an existing order
+ */
+ async modifyOrder(
+ orderId: string,
+ params: Partial<OrderParams>,
+ variety: string = 'regular'
+ ): Promise<OrderResponse> {
+ const data = new URLSearchParams();
+
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined) {
+ data.append(key, value.toString());
+ }
+ });
+
+ const response = await this.client.put(`/orders/${variety}/${orderId}`, data);
+ return response.data.data;
+ }
+
+ /**
+ * Cancel an order
+ */
+ async cancelOrder(orderId: string, variety: string = 'regular'): Promise<OrderResponse> {
+ const response = await this.client.delete(`/orders/${variety}/${orderId}`);
+ return response.data.data;
+ }
+
+ /**
+ * Get all orders for the day
+ */
+ async getOrders(): Promise<Order[]> {
+ const response = await this.client.get('/orders');
+ return response.data.data;
+ }
+
+ /**
+ * Get order history for a specific order
+ */
+ async getOrderHistory(orderId: string): Promise<Order[]> {
+ const response = await this.client.get(`/orders/${orderId}`);
+ return response.data.data;
+ }
+
+ /**
+ * Get all trades for the day
+ */
+ async getTrades(): Promise<Trade[]> {
+ const response = await this.client.get('/trades');
+ return response.data.data;
+ }
+
+ /**
+ * Get trades for a specific order
+ */
+ async getOrderTrades(orderId: string): Promise<Trade[]> {
+ const response = await this.client.get(`/orders/${orderId}/trades`);
+ return response.data.data;
+ }
+
+ // ================================
+ // MARKET DATA
+ // ================================
+
+ /**
+ * Get full market quotes for instruments
+ * Max 500 instruments per request
+ */
+ async getQuotes(instruments: string[]): Promise<Record<string, Quote>> {
+ if (instruments.length > 500) {
+ throw new Error('Maximum 500 instruments allowed per request');
+ }
+
+ const params = new URLSearchParams();
+ instruments.forEach(instrument => params.append('i', instrument));
+
+ const response = await this.client.get(`/quote?${params.toString()}`);
+ return response.data.data;
+ }
+
+ /**
+ * Get OHLC quotes for instruments
+ * Max 1000 instruments per request
+ */
+ async getOHLC(instruments: string[]): Promise<Record<string, any>> {
+ if (instruments.length > 1000) {
+ throw new Error('Maximum 1000 instruments allowed per request');
+ }
+
+ const params = new URLSearchParams();
+ instruments.forEach(instrument => params.append('i', instrument));
+
+ const response = await this.client.get(`/quote/ohlc?${params.toString()}`);
+ return response.data.data;
+ }
+
+ /**
+ * Get LTP for instruments
+ * Max 1000 instruments per request
+ */
+ async getLTP(instruments: string[]): Promise<Record<string, any>> {
+ if (instruments.length > 1000) {
+ throw new Error('Maximum 1000 instruments allowed per request');
+ }
+
+ const params = new URLSearchParams();
+ instruments.forEach(instrument => params.append('i', instrument));
+
+ const response = await this.client.get(`/quote/ltp?${params.toString()}`);
+ return response.data.data;
+ }
+
+ /**
+ * Get historical data
+ */
+ async getHistoricalData(params: HistoricalParams): Promise<CandleData[]> {
+ const queryParams = new URLSearchParams({
+ from: params.from,
+ to: params.to,
+ });
+
+ if (params.continuous) queryParams.append('continuous', '1');
+ if (params.oi) queryParams.append('oi', '1');
+
+ const response = await this.client.get(
+ `/instruments/historical/${params.instrument_token}/${params.interval}?${queryParams.toString()}`
+ );
+
+ // Transform array format to object format
+ return response.data.data.candles.map((candle: any[]) => ({
+ timestamp: candle[0],
+ open: candle[1],
+ high: candle[2],
+ low: candle[3],
+ close: candle[4],
+ volume: candle[5],
+ oi: candle[6] || undefined,
+ }));
+ }
+
+ /**
+ * Get instruments list for exchange
+ */
+ async getInstruments(exchange?: string): Promise<string> {
+ const url = exchange ? `/instruments/${exchange}` : '/instruments';
+ const response = await this.client.get(url);
+ return response.data; // Returns CSV data
+ }
+
+ // ================================
+ // PORTFOLIO
+ // ================================
+
+ /**
+ * Get holdings
+ */
+ async getHoldings(): Promise<Holding[]> {
+ const response = await this.client.get('/portfolio/holdings');
+ return response.data.data;
+ }
+
+ /**
+ * Get positions
+ */
+ async getPositions(): Promise<{ net: Position[]; day: Position[] }> {
+ const response = await this.client.get('/portfolio/positions');
+ return response.data.data;
+ }
+
+ /**
+ * Convert position
+ */
+ async convertPosition(params: {
+ tradingsymbol: string;
+ exchange: string;
+ transaction_type: 'BUY' | 'SELL';
+ position_type: 'overnight' | 'day';
+ quantity: number;
+ old_product: string;
+ new_product: string;
+ }): Promise<boolean> {
+ const data = new URLSearchParams();
+ Object.entries(params).forEach(([key, value]) => {
+ data.append(key, value.toString());
+ });
+
+ const response = await this.client.put('/portfolio/positions', data);
+ return response.data.data;
+ }
+
+ /**
+ * Get holdings auction list
+ */
+ async getHoldingsAuctions(): Promise<any[]> {
+ const response = await this.client.get('/portfolio/holdings/auctions');
+ return response.data.data;
+ }
+
+ /**
+ * Initiate holdings authorisation
+ */
+ async initiateHoldingsAuth(holdings?: Array<{ isin: string; quantity: number }>): Promise<{ request_id: string }> {
+ const data = new URLSearchParams();
+
+ if (holdings) {
+ holdings.forEach(holding => {
+ data.append('isin', holding.isin);
+ data.append('quantity', holding.quantity.toString());
+ });
+ }
+
+ const response = await this.client.post('/portfolio/holdings/authorise', data);
+ return response.data.data;
+ }
+
+ // ================================
+ // GTT (Good Till Triggered)
+ // ================================
+
+ /**
+ * Place GTT order
+ */
+ async placeGTT(params: GTTParams): Promise<GTTResponse> {
+ const data = new URLSearchParams({
+ type: params.type,
+ condition: JSON.stringify(params.condition),
+ orders: JSON.stringify(params.orders),
+ });
+
+ const response = await this.client.post('/gtt/triggers', data);
+ return response.data.data;
+ }
+
+ /**
+ * Get all GTT orders
+ */
+ async getGTTs(): Promise<GTT[]> {
+ const response = await this.client.get('/gtt/triggers');
+ return response.data.data;
+ }
+
+ /**
+ * Get specific GTT order
+ */
+ async getGTT(triggerId: number): Promise<GTT> {
+ const response = await this.client.get(`/gtt/triggers/${triggerId}`);
+ return response.data.data;
+ }
+
+ /**
+ * Modify GTT order
+ */
+ async modifyGTT(triggerId: number, params: GTTParams): Promise<GTTResponse> {
+ const data = new URLSearchParams({
+ type: params.type,
+ condition: JSON.stringify(params.condition),
+ orders: JSON.stringify(params.orders),
+ });
+
+ const response = await this.client.put(`/gtt/triggers/${triggerId}`, data);
+ return response.data.data;
+ }
+
+ /**
+ * Cancel GTT order
+ */
+ async cancelGTT(triggerId: number): Promise<GTTResponse> {
+ const response = await this.client.delete(`/gtt/triggers/${triggerId}`);
+ return response.data.data;
+ }
+
+ // ================================
+ // ALERTS
+ // ================================
+
+ /**
+ * Create alert
+ */
+ async createAlert(params: AlertParams): Promise<Alert> {
+ const data = new URLSearchParams();
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined) {
+ data.append(key, value.toString());
+ }
+ });
+
+ const response = await this.client.post('/alerts', data);
+ return response.data.data;
+ }
+
+ /**
+ * Get all alerts
+ */
+ async getAlerts(): Promise<Alert[]> {
+ const response = await this.client.get('/alerts');
+ return response.data.data;
+ }
+
+ /**
+ * Get specific alert
+ */
+ async getAlert(alertUuid: string): Promise<Alert> {
+ const response = await this.client.get(`/alerts/${alertUuid}`);
+ return response.data.data;
+ }
+
+ /**
+ * Modify alert
+ */
+ async modifyAlert(alertUuid: string, params: Partial<AlertParams>): Promise<Alert> {
+ const data = new URLSearchParams();
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined) {
+ data.append(key, value.toString());
+ }
+ });
+
+ const response = await this.client.put(`/alerts/${alertUuid}`, data);
+ return response.data.data;
+ }
+
+ /**
+ * Delete alerts
+ */
+ async deleteAlerts(alertUuids: string[]): Promise<void> {
+ const params = new URLSearchParams();
+ alertUuids.forEach(uuid => params.append('uuid', uuid));
+
+ await this.client.delete(`/alerts?${params.toString()}`);
+ }
+
+ /**
+ * Get alert history
+ */
+ async getAlertHistory(alertUuid: string): Promise<any[]> {
+ const response = await this.client.get(`/alerts/${alertUuid}/history`);
+ return response.data.data;
+ }
+
+ // ================================
+ // MARGINS
+ // ================================
+
+ /**
+ * Calculate order margins
+ */
+ async calculateOrderMargins(orders: MarginOrder[], mode?: 'compact'): Promise<MarginResponse[]> {
+ const params = new URLSearchParams();
+ if (mode) params.append('mode', mode);
+
+ const response = await this.client.post(
+ `/margins/orders?${params.toString()}`,
+ JSON.stringify(orders),
+ {
+ headers: { 'Content-Type': 'application/json' }
+ }
+ );
+ return response.data.data;
+ }
+
+ /**
+ * Calculate basket margins
+ */
+ async calculateBasketMargins(orders: MarginOrder[]): Promise<any> {
+ const response = await this.client.post(
+ '/margins/basket',
+ JSON.stringify(orders),
+ {
+ headers: { 'Content-Type': 'application/json' }
+ }
+ );
+ return response.data.data;
+ }
+
+ /**
+ * Calculate order charges
+ */
+ async calculateOrderCharges(orders: MarginOrder[]): Promise<any> {
+ const response = await this.client.post(
+ '/charges/orders',
+ JSON.stringify(orders),
+ {
+ headers: { 'Content-Type': 'application/json' }
+ }
+ );
+ return response.data.data;
+ }
+
+ // ================================
+ // MUTUAL FUNDS
+ // ================================
+
+ /**
+ * Get mutual fund orders
+ */
+ async getMFOrders(): Promise<MFOrder[]> {
+ const response = await this.client.get('/mf/orders');
+ return response.data.data;
+ }
+
+ /**
+ * Get specific mutual fund order
+ */
+ async getMFOrder(orderId: string): Promise<MFOrder> {
+ const response = await this.client.get(`/mf/orders/${orderId}`);
+ return response.data.data;
+ }
+
+ /**
+ * Get mutual fund holdings
+ */
+ async getMFHoldings(): Promise<MFHolding[]> {
+ const response = await this.client.get('/mf/holdings');
+ return response.data.data;
+ }
+
+ /**
+ * Get all SIPs
+ */
+ async getMFSips(): Promise<MFSip[]> {
+ const response = await this.client.get('/mf/sips');
+ return response.data.data;
+ }
+
+ /**
+ * Get mutual fund instruments
+ */
+ async getMFInstruments(): Promise<string> {
+ const response = await this.client.get('/mf/instruments');
+ return response.data; // Returns CSV data
+ }
+
+ // ================================
+ // UTILITY METHODS
+ // ================================
+
+ /**
+ * Validate postback checksum
+ */
+ validatePostbackChecksum(orderId: string, orderTimestamp: string, receivedChecksum: string): boolean {
+ const expectedChecksum = crypto
+ .createHash('sha256')
+ .update(orderId + orderTimestamp + this.config.apiSecret)
+ .digest('hex');
+
+ return expectedChecksum === receivedChecksum;
+ }
+
+ /**
+ * Set access token (for session persistence)
+ */
+ setAccessToken(accessToken: string): void {
+ this.config.accessToken = accessToken;
+ }
+
+ /**
+ * Get current access token
+ */
+ getAccessToken(): string | undefined {
+ return this.config.accessToken;
+ }
+
+ /**
+ * Check if authenticated
+ */
+ isAuthenticated(): boolean {
+ return !!this.config.accessToken;
+ }
+}
+
+// ================================
+// FACTORY FUNCTION
+// ================================
+
+export function createKiteAdapter(config: KiteConfig): KiteConnectAdapter {
+ return new KiteConnectAdapter(config);
+}
+
+// ================================
+// RATE LIMITER UTILITY
+// ================================
+
+export class RateLimiter {
+ private requests: number[] = [];
+ private readonly limit: number;
+ private readonly window: number;
+
+ constructor(limit: number = 100, windowMs: number = 60000) {
+ this.limit = limit;
+ this.window = windowMs;
+ }
+
+ async checkLimit(): Promise<void> {
+ const now = Date.now();
+ this.requests = this.requests.filter(time => now - time < this.window);
+
+ if (this.requests.length >= this.limit) {
+ const oldestRequest = Math.min(...this.requests);
+ const waitTime = this.window - (now - oldestRequest);
+ await new Promise(resolve => setTimeout(resolve, waitTime));
+ return this.checkLimit();
+ }
+
+ this.requests.push(now);
+ }
+}
+
+// ================================
+// WEBHOOK HANDLER UTILITY
+// ================================
+
+export interface PostbackPayload {
+ user_id: string;
+ unfilled_quantity: number;
+ app_id: number;
+ checksum: string;
+ placed_by: string;
+ order_id: string;
+ exchange_order_id?: string;
+ parent_order_id?: string;
+ status: string;
+ status_message?: string;
+ status_message_raw?: string;
+ order_timestamp: string;
+ exchange_update_timestamp?: string;
+ exchange_timestamp?: string;
+ variety: string;
+ exchange: string;
+ tradingsymbol: string;
+ instrument_token: number;
+ order_type: string;
+ transaction_type: string;
+ validity: string;
+ product: string;
+ quantity: number;
+ disclosed_quantity: number;
+ price: number;
+ trigger_price: number;
+ average_price: number;
+ filled_quantity: number;
+ pending_quantity: number;
+ cancelled_quantity: number;
+ market_protection: number;
+ meta: Record<string, any>;
+ tag?: string;
+ guid: string;
+}
+
+export class WebhookHandler {
+ constructor(private apiSecret: string) {}
+
+ /**
+ * Process postback webhook payload
+ */
+ processPostback(payload: PostbackPayload): {
+ isValid: boolean;
+ order: PostbackPayload | null;
+ } {
+ // Validate checksum
+ const expectedChecksum = crypto
+ .createHash('sha256')
+ .update(payload.order_id + payload.order_timestamp + this.apiSecret)
+ .digest('hex');
+
+ const isValid = expectedChecksum === payload.checksum;
+
+ return {
+ isValid,
+ order: isValid ? payload : null
+ };
+ }
+
+ /**
+ * Express.js middleware for handling postbacks
+ */
+ expressMiddleware() {
+ return (req: any, res: any, next: any) => {
+ try {
+ const result = this.processPostback(req.body);
+ req.kitePostback = result;
+ next();
+ } catch (error) {
+ res.status(400).json({ error: 'Invalid postback payload' });
+ }
+ };
+ }
+}
+
+// ================================
+// BATCH OPERATIONS UTILITY
+// ================================
+
+export class BatchOperations {
+ constructor(private adapter: KiteConnectAdapter, private rateLimiter?: RateLimiter) {}
+
+ /**
+ * Get quotes for large number of instruments (handles rate limits)
+ */
+ async getBatchQuotes(instruments: string[]): Promise<Record<string, Quote>> {
+ const batches: string[][] = [];
+ const batchSize = 500; // API limit
+
+ for (let i = 0; i < instruments.length; i += batchSize) {
+ batches.push(instruments.slice(i, i + batchSize));
+ }
+
+ const results: Record<string, Quote> = {};
+
+ for (const batch of batches) {
+ if (this.rateLimiter) {
+ await this.rateLimiter.checkLimit();
+ }
+
+ const batchResult = await this.adapter.getQuotes(batch);
+ Object.assign(results, batchResult);
+
+ // Small delay between batches to be respectful to the API
+ if (batches.length > 1) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ }
+
+ return results;
+ }
+
+ /**
+ * Get OHLC for large number of instruments
+ */
+ async getBatchOHLC(instruments: string[]): Promise<Record<string, any>> {
+ const batches: string[][] = [];
+ const batchSize = 1000; // API limit
+
+ for (let i = 0; i < instruments.length; i += batchSize) {
+ batches.push(instruments.slice(i, i + batchSize));
+ }
+
+ const results: Record<string, any> = {};
+
+ for (const batch of batches) {
+ if (this.rateLimiter) {
+ await this.rateLimiter.checkLimit();
+ }
+
+ const batchResult = await this.adapter.getOHLC(batch);
+ Object.assign(results, batchResult);
+
+ if (batches.length > 1) {
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ }
+
+ return results;
+ }
+
+ /**
+ * Place multiple orders with rate limiting
+ */
+ async placeMultipleOrders(orders: OrderParams[]): Promise<OrderResponse[]> {
+ const results: OrderResponse[] = [];
+
+ for (const order of orders) {
+ if (this.rateLimiter) {
+ await this.rateLimiter.checkLimit();
+ }
+
+ try {
+ const result = await this.adapter.placeOrder(order);
+ results.push(result);
+ } catch (error) {
+ // You might want to handle errors differently based on your use case
+ console.error(`Failed to place order for ${order.tradingsymbol}:`, error);
+ throw error;
+ }
+
+ // Small delay between orders
+ await new Promise(resolve => setTimeout(resolve, 50));
+ }
+
+ return results;
+ }
+}
+
+// ================================
+// SESSION MANAGER UTILITY
+// ================================
+
+export interface SessionStorage {
+ save(key: string, data: any): Promise<void>;
+ load(key: string): Promise<any>;
+ remove(key: string): Promise<void>;
+}
+
+export class FileSessionStorage implements SessionStorage {
+ constructor(private basePath: string = './sessions') {
+ const fs = require('fs');
+ if (!fs.existsSync(this.basePath)) {
+ fs.mkdirSync(this.basePath, { recursive: true });
+ }
+ }
+
+ async save(key: string, data: any): Promise<void> {
+ const fs = require('fs').promises;
+ const path = require('path');
+ const filePath = path.join(this.basePath, `${key}.json`);
+ await fs.writeFile(filePath, JSON.stringify(data, null, 2));
+ }
+
+ async load(key: string): Promise<any> {
+ const fs = require('fs').promises;
+ const path = require('path');
+ const filePath = path.join(this.basePath, `${key}.json`);
+
+ try {
+ const data = await fs.readFile(filePath, 'utf8');
+ return JSON.parse(data);
+ } catch (error) {
+ return null;
+ }
+ }
+
+ async remove(key: string): Promise<void> {
+ const fs = require('fs').promises;
+ const path = require('path');
+ const filePath = path.join(this.basePath, `${key}.json`);
+
+ try {
+ await fs.unlink(filePath);
+ } catch (error) {
+ // File doesn't exist, ignore
+ }
+ }
+}
+
+export class SessionManager {
+ constructor(
+ private adapter: KiteConnectAdapter,
+ private storage: SessionStorage,
+ private sessionKey: string = 'kite_session'
+ ) {}
+
+ /**
+ * Save current session
+ */
+ async saveSession(): Promise<void> {
+ const sessionData = {
+ accessToken: this.adapter.getAccessToken(),
+ timestamp: Date.now()
+ };
+ await this.storage.save(this.sessionKey, sessionData);
+ }
+
+ /**
+ * Load saved session
+ */
+ async loadSession(): Promise<boolean> {
+ const sessionData = await this.storage.load(this.sessionKey);
+
+ if (!sessionData || !sessionData.accessToken) {
+ return false;
+ }
+
+ // Check if session is less than 24 hours old (Kite tokens expire daily)
+ const sessionAge = Date.now() - sessionData.timestamp;
+ const maxAge = 24 * 60 * 60 * 1000; // 24 hours
+
+ if (sessionAge > maxAge) {
+ await this.clearSession();
+ return false;
+ }
+
+ this.adapter.setAccessToken(sessionData.accessToken);
+ return true;
+ }
+
+ /**
+ * Clear saved session
+ */
+ async clearSession(): Promise<void> {
+ await this.storage.remove(this.sessionKey);
+ }
+
+ /**
+ * Generate login URL and handle the full auth flow
+ */
+ async initiateAuth(redirectUrl?: string): Promise<string> {
+ await this.clearSession();
+ return this.adapter.generateLoginUrl(redirectUrl);
+ }
+
+ /**
+ * Complete authentication with request token
+ */
+ async completeAuth(requestToken: string): Promise<SessionData> {
+ const sessionData = await this.adapter.generateSession(requestToken);
+ await this.saveSession();
+ return sessionData;
+ }
+}
+
+// ================================
+// PORTFOLIO TRACKER UTILITY
+// ================================
+
+export class PortfolioTracker {
+ constructor(private adapter: KiteConnectAdapter) {}
+
+ /**
+ * Get complete portfolio summary
+ */
+ async getPortfolioSummary(): Promise<{
+ holdings: Holding[];
+ positions: { net: Position[]; day: Position[] };
+ totalPnL: number;
+ totalValue: number;
+ dayChange: number;
+ }> {
+ const [holdings, positions] = await Promise.all([
+ this.adapter.getHoldings(),
+ this.adapter.getPositions()
+ ]);
+
+ const totalPnL = holdings.reduce((sum, holding) => sum + holding.pnl, 0) +
+ positions.net.reduce((sum, pos) => sum + pos.pnl, 0);
+
+ const totalValue = holdings.reduce((sum, holding) =>
+ sum + (holding.last_price * holding.quantity), 0
+ );
+
+ const dayChange = holdings.reduce((sum, holding) => sum + holding.day_change, 0);
+
+ return {
+ holdings,
+ positions,
+ totalPnL,
+ totalValue,
+ dayChange
+ };
+ }
+
+ /**
+ * Calculate portfolio risk metrics
+ */
+ async getRiskMetrics(): Promise<{
+ concentration: Array<{ symbol: string; percentage: number }>;
+ sectorExposure: Record<string, number>;
+ largestPosition: number;
+ }> {
+ const holdings = await this.adapter.getHoldings();
+ const totalValue = holdings.reduce((sum, holding) =>
+ sum + (holding.last_price * holding.quantity), 0
+ );
+
+ const concentration = holdings
+ .map(holding => ({
+ symbol: holding.tradingsymbol,
+ percentage: ((holding.last_price * holding.quantity) / totalValue) * 100
+ }))
+ .sort((a, b) => b.percentage - a.percentage);
+
+ const largestPosition = Math.max(...concentration.map(c => c.percentage));
+
+ // Note: Sector classification would require additional data mapping
+ const sectorExposure: Record<string, number> = {};
+
+ return {
+ concentration,
+ sectorExposure,
+ largestPosition
+ };
+ }
+}
+
+// ================================
+// ERROR CLASSES
+// ================================
+
+export class KiteError extends Error {
+ constructor(
+ message: string,
+ public code?: string,
+ public statusCode?: number
+ ) {
+ super(message);
+ this.name = 'KiteError';
+ }
+}
+
+export class KiteAuthError extends KiteError {
+ constructor(message: string = 'Authentication required') {
+ super(message, 'AUTH_ERROR', 403);
+ this.name = 'KiteAuthError';
+ }
+}
+
+export class KiteRateLimitError extends KiteError {
+ constructor(message: string = 'Rate limit exceeded') {
+ super(message, 'RATE_LIMIT', 429);
+ this.name = 'KiteRateLimitError';
+ }
+}
+
+// ================================
+// EXPORT ALL
+// ================================
+
+export default KiteConnectAdapter;
\ No newline at end of file