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.

host update [skip cli]

tilakpatel226356fe7486ea
diff --git a/fincept-terminal-desktop/.gitignore b/fincept-terminal-desktop/.gitignore
index a547bf36d..b0c5812b1 100644
--- a/fincept-terminal-desktop/.gitignore
+++ b/fincept-terminal-desktop/.gitignore
@@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?
+
+src/services/node_modules
diff --git a/fincept-terminal-desktop/CONTEXT_ANALYSIS.md b/fincept-terminal-desktop/CONTEXT_ANALYSIS.md
new file mode 100644
index 000000000..0fe6f8d4c
--- /dev/null
+++ b/fincept-terminal-desktop/CONTEXT_ANALYSIS.md
@@ -0,0 +1,401 @@
+# Fincept Terminal - Complete Context Analysis
+
+## 📋 CURRENT AUTHENTICATION & SESSION SYSTEM
+
+### **Authentication Flow**
+1. **Login/Register** → User enters credentials
+2. **OTP Verification** (for new users)
+3. **API Key Generation** → Backend returns `api_key`
+4. **Session Creation** → AuthContext stores session
+5. **Account Type Check**:
+ - Free Account → Redirect to **Pricing Screen**
+ - Paid Subscription → Redirect to **Dashboard**
+ - Guest Mode → Direct to **Dashboard** (24h limit)
+
+### **User Types**
+```typescript
+'guest' | 'registered'
+```
+
+**Guest Users:**
+- Device-based authentication
+- 24-hour session expiry
+- Daily API call limits (50 calls/day)
+- No payment required
+- Device ID generated from browser fingerprint
+
+**Registered Users:**
+- Email/password authentication
+- Persistent sessions
+- Account types: `free`, `starter`, `professional`, `enterprise`, `unlimited`
+- Subscription management
+- Payment integration
+
+### **Session Data Structure**
+```typescript
+interface SessionData {
+ authenticated: boolean;
+ user_type: 'guest' | 'registered';
+ api_key: string | null;
+ device_id: string;
+ user_info?: {
+ username: string;
+ email: string;
+ account_type: string; // 'free', 'starter', 'professional', etc.
+ credit_balance: number;
+ is_verified: boolean;
+ mfa_enabled: boolean;
+ };
+ expires_at?: string; // For guest users
+ daily_limit?: number; // For guest users
+ requests_today?: number; // For guest users
+ subscription?: {
+ has_subscription: boolean;
+ subscription?: {
+ subscription_uuid: string;
+ plan: { name, plan_id, price };
+ 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;
+ };
+ };
+ };
+}
+```
+
+---
+
+## 🔐 CURRENT ISSUES IDENTIFIED
+
+### **1. No Logout Functionality in Dashboard Header**
+- **Problem**: Dashboard header (DashboardScreen.tsx) has no logout button
+- **User Impact**: Users cannot end their session from the terminal
+- **Current State**: Menu dropdowns present but no logout option
+
+### **2. Payment Flow Redirect Errors**
+- **Problem**: Payment success redirects may have issues
+- **Location**: `PaymentSuccessScreen.tsx` + `App.tsx`
+- **Current Flow**:
+ 1. User selects plan → `PricingScreen`
+ 2. Creates checkout session → Opens payment URL
+ 3. Payment completed → Redirects to `/payment-success?session_id=...`
+ 4. `PaymentSuccessScreen` handles verification
+ 5. Redirect to dashboard
+- **Potential Issues**:
+ - URL parameter handling
+ - Session validation after payment
+ - Double-redirects causing loops
+
+### **3. No Session Awareness in Tabs**
+- **Problem**: Terminal tabs don't display user session info
+- **Missing Features**:
+ - User type indicator (Guest vs Registered)
+ - Account plan display
+ - Session expiry warnings (for guests)
+ - API usage stats
+ - Subscription status
+
+---
+
+## 🎯 REQUIRED MODIFICATIONS
+
+### **Task 1: Add Logout to Dashboard Header**
+**File**: `src/components/dashboard/DashboardScreen.tsx`
+
+**Changes Needed**:
+1. Import `useAuth` hook
+2. Add logout button to header dropdowns
+3. Add logout handler that:
+ - Calls `logout()` from AuthContext
+ - Clears IndexedDB credentials (if needed)
+ - Redirects to login screen
+
+**UI Location**: Top menu bar → Add to "Session" or "File" dropdown
+
+---
+
+### **Task 2: Fix Payment Redirect Flow**
+**Files**:
+- `src/components/payment/PaymentSuccessScreen.tsx`
+- `src/App.tsx`
+
+**Current Issues**:
+```typescript
+// In PaymentSuccessScreen.tsx:
+// Line 92-94: onComplete() callback
+const handleContinueToDashboard = () => {
+ onComplete(); // Should redirect to dashboard
+};
+
+// In App.tsx:
+// Line 231-238: PaymentSuccessScreen props
+onComplete={() => {
+ setHasChosenFreePlan(false);
+ setCameFromLogin(false);
+ setCurrentScreen('dashboard'); // May cause redirect loop
+}}
+```
+
+**Fix Strategy**:
+1. Clear URL parameters after payment success
+2. Refresh session data before redirect
+3. Add proper loading states
+4. Handle edge cases (payment failed, session expired, etc.)
+
+---
+
+### **Task 3: Add Session Info to Tabs**
+**Files**: All tab components need session awareness
+
+**Required Information Display**:
+
+**For Guest Users**:
+```
+┌─────────────────────────────────────┐
+│ 👤 Guest User │
+│ ⏰ Session: 18h 23m remaining │
+│ 📊 API Calls: 12/50 today │
+│ ⚠️ Limited access - Upgrade? │
+└─────────────────────────────────────┘
+```
+
+**For Registered Users (Free Plan)**:
+```
+┌─────────────────────────────────────┐
+│ 👤 [email protected] │
+│ 📦 Plan: Free │
+│ 📊 API Calls: 1,247/10,000 today │
+│ 💳 Upgrade to unlock more features │
+└─────────────────────────────────────┘
+```
+
+**For Registered Users (Paid Plan)**:
+```
+┌─────────────────────────────────────┐
+│ 👤 [email protected] │
+│ 📦 Plan: Professional ($49/mo) │
+│ 📊 API Calls: 8,234/50,000 today │
+│ ✅ Subscription: Active │
+│ 📅 Renews: Dec 31, 2025 │
+└─────────────────────────────────────┘
+```
+
+**Implementation Locations**:
+1. **Header/Top Bar** (all tabs): User info widget
+2. **Profile/Settings Tab**: Full session details
+3. **Status Bar** (optional): Minimal session info
+
+---
+
+## 📁 KEY FILES & THEIR ROLES
+
+### **Authentication System**
+| File | Purpose |
+|------|---------|
+| `AuthContext.tsx` | Global session management, login/logout/register |
+| `authApi.tsx` | Backend API calls for authentication |
+| `LoginScreen.tsx` | User login UI |
+| `RegisterScreen.tsx` | User registration + OTP verification |
+| `App.tsx` | Main routing logic, screen navigation |
+
+### **Payment System**
+| File | Purpose |
+|------|---------|
+| `paymentApi.tsx` | Payment API calls, subscription management |
+| `PricingScreen.tsx` | Plan selection UI |
+| `PaymentProcessingScreen.tsx` | Loading state during payment |
+| `PaymentSuccessScreen.tsx` | Payment confirmation + redirect |
+| `PaymentOverlay.tsx` | In-app payment window |
+
+### **Dashboard System**
+| File | Purpose |
+|------|---------|
+| `DashboardScreen.tsx` | Main terminal interface, tab navigation, header |
+| `*Tab.tsx` (all tabs) | Individual terminal tabs (Markets, News, Settings, etc.) |
+
+---
+
+## 🛠️ IMPLEMENTATION PLAN
+
+### **Phase 1: Add Logout Functionality** ✅
+**Priority**: HIGH
+**Complexity**: LOW
+
+1. Modify `DashboardScreen.tsx`:
+ - Add logout to Session dropdown
+ - Call `useAuth().logout()`
+ - Navigate to login screen
+
+2. Test scenarios:
+ - Registered user logout
+ - Guest user logout
+ - Session cleanup verification
+
+---
+
+### **Phase 2: Fix Payment Redirects** ✅
+**Priority**: HIGH
+**Complexity**: MEDIUM
+
+1. Update `PaymentSuccessScreen.tsx`:
+ - Clear URL params immediately
+ - Add retry logic for API calls
+ - Better error handling
+
+2. Update `App.tsx`:
+ - Fix redirect logic
+ - Prevent loops
+ - Add loading states
+
+3. Test scenarios:
+ - Successful payment
+ - Failed payment
+ - User closes payment window early
+ - Network errors during verification
+
+---
+
+### **Phase 3: Add Session Info to Tabs** ✅
+**Priority**: MEDIUM
+**Complexity**: MEDIUM
+
+1. Create reusable session info component:
+ - `<SessionInfoWidget />` for header
+ - `<SessionDetailsPanel />` for Profile tab
+
+2. Update `DashboardScreen.tsx`:
+ - Add session widget to header
+ - Replace static "Guest (18h remaining)" text
+
+3. Update individual tabs (optional):
+ - Add contextual session warnings
+ - Example: News tab shows "Upgrade for full article access"
+
+---
+
+## 🧪 TESTING CHECKLIST
+
+### **Authentication Tests**
+- [ ] Login with valid credentials
+- [ ] Login with invalid credentials
+- [ ] Guest mode access
+- [ ] Session persistence after refresh
+- [ ] Session expiry handling
+
+### **Logout Tests**
+- [ ] Logout from registered account
+- [ ] Logout from guest account
+- [ ] Session cleared from localStorage
+- [ ] Credentials cleared from IndexedDB
+- [ ] Redirect to login screen
+
+### **Payment Flow Tests**
+- [ ] Select free plan → Go to dashboard
+- [ ] Select paid plan → Opens payment window
+- [ ] Complete payment → Redirect to success screen
+- [ ] Success screen → Refresh subscription data
+- [ ] Success screen → Redirect to dashboard
+- [ ] Cancel payment → Return to pricing screen
+- [ ] Payment failure → Show error, allow retry
+
+### **Session Display Tests**
+- [ ] Guest user sees expiry countdown
+- [ ] Free user sees plan upgrade prompt
+- [ ] Paid user sees subscription details
+- [ ] API usage stats update correctly
+- [ ] Session warnings appear at 30min remaining (guests)
+
+---
+
+## 📊 SESSION STATE FLOW DIAGRAM
+
+```
+┌──────────────────────────────────────────────────────────────┐
+│ App Start │
+└───────────────────────────┬──────────────────────────────────┘
+ │
+ ▼
+ ┌───────────────┐
+ │ isLoading? │
+ └───┬───────┬───┘
+ │ Yes │ No
+ ▼ ▼
+ Loading Check Session
+ Screen ┌────┴────┐
+ │ │
+ ┌──────▼─────┐ │
+ │ Guest User │ │
+ └──────┬─────┘ │
+ │ │
+ ▼ ▼
+ Dashboard ┌────────────┐
+ │ Registered │
+ │ User │
+ └──────┬─────┘
+ │
+ ┌─────────────┴─────────────┐
+ │ │
+ ┌──────▼──────┐ ┌───────▼────────┐
+ │ Free Plan │ │ Paid Plan │
+ │ │ │ (Subscribed) │
+ └──────┬──────┘ └───────┬────────┘
+ │ │
+ ▼ ▼
+ Pricing Screen Dashboard
+ │
+ ┌──────┴──────┐
+ │ │
+ ┌──────▼────┐ ┌─────▼──────┐
+ │ Choose │ │ Purchase │
+ │ Free Plan │ │ Paid Plan │
+ └──────┬────┘ └─────┬──────┘
+ │ │
+ │ ▼
+ │ Payment Flow
+ │ │
+ │ ┌──────▼──────────┐
+ │ │ Payment Success │
+ │ └──────┬──────────┘
+ │ │
+ └──────────────┴─────────▼
+ Dashboard
+```
+
+---
+
+## 💡 RECOMMENDATIONS
+
+### **Security**
+1. ✅ Session tokens stored in localStorage (encrypted would be better)
+2. ⚠️ API keys visible in network traffic (HTTPS mitigates)
+3. ✅ Guest sessions expire after 24h
+4. ⚠️ No automatic session refresh before expiry
+
+### **User Experience**
+1. Add session expiry warnings (30min, 5min, 1min)
+2. Auto-save work before session expires
+3. Seamless re-authentication flow
+4. "Remember me" option for longer sessions
+
+### **Feature Enhancements**
+1. Multi-device session management
+2. Session activity history
+3. Force logout from all devices
+4. 2FA/MFA for sensitive operations
+
+---
+
+## 🔄 NEXT STEPS
+
+1. **Gather full context** ✅ (COMPLETED)
+2. **Add logout button** (In progress...)
+3. **Fix payment redirects** (In progress...)
+4. **Add session display** (In progress...)
+5. **Test all flows** (Pending...)
+6. **Deploy changes** (Pending...)
\ No newline at end of file
diff --git a/fincept-terminal-desktop/package-lock.json b/fincept-terminal-desktop/package-lock.json
index 33be9de6c..daa9ee3a7 100644
--- a/fincept-terminal-desktop/package-lock.json
+++ b/fincept-terminal-desktop/package-lock.json
@@ -5046,6 +5046,17 @@
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"license": "MIT"
},
+ "node_modules/encoding": {
+ "version": "0.1.13",
+ "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",
+ "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==",
+ "license": "MIT",
+ "optional": true,
+ "peer": true,
+ "dependencies": {
+ "iconv-lite": "^0.6.2"
+ }
+ },
"node_modules/encoding-sniffer": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.1.tgz",
diff --git a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
index 4a492f09a..60beba0d8 100644
--- a/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
+++ b/fincept-terminal-desktop/src/components/dashboard/DashboardScreen.tsx
@@ -1,6 +1,7 @@
import React, { useState, useRef, useEffect } from 'react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
-import { Maximize, Minimize, Download, Settings, RefreshCw, User, Database, Eye, HelpCircle } from 'lucide-react';
+import { Maximize, Minimize, Download, Settings, RefreshCw, User, Database, Eye, HelpCircle, LogOut } from 'lucide-react';
+import { useAuth } from '@/contexts/AuthContext';
import ForumTab from '@/components/tabs/ForumTab';
import DashboardTab from '@/components/tabs/DashboardTab';
import MarketsTab from '@/components/tabs/MarketsTab';
@@ -23,6 +24,7 @@ import DBnomicsTab from '@/components/tabs/DBnomicsTab';
import CodeEditorTab from '@/components/tabs/CodeEditorTab';
import DocsTab from '@/components/tabs/DocsTab';
import MaritimeTab from '@/components/tabs/MaritimeTab';
+import SettingsTab from '@/components/tabs/SettingsTab';
// Dropdown Menu Component
const DropdownMenu = ({ label, items, onItemClick }) => {
@@ -105,6 +107,7 @@ const DropdownMenu = ({ label, items, onItemClick }) => {
};
export default function FinxeptTerminal() {
+ const { session, logout } = useAuth();
const [activeTab, setActiveTab] = useState("dashboard");
const [isFullscreen, setIsFullscreen] = useState(false);
const [statusMessage, setStatusMessage] = useState("");
@@ -127,6 +130,46 @@ export default function FinxeptTerminal() {
};
}, []);
+ // Get session display text
+ const getSessionDisplay = () => {
+ if (!session) return 'Loading...';
+
+ if (session.user_type === 'guest') {
+ // Calculate time remaining for guest users
+ if (session.expires_at) {
+ const expiryTime = new Date(session.expires_at).getTime();
+ const now = new Date().getTime();
+ const hoursRemaining = Math.floor((expiryTime - now) / (1000 * 60 * 60));
+ const minutesRemaining = Math.floor(((expiryTime - now) % (1000 * 60 * 60)) / (1000 * 60));
+
+ if (hoursRemaining > 0) {
+ return `👤 Guest (${hoursRemaining}h ${minutesRemaining}m remaining)`;
+ } else if (minutesRemaining > 0) {
+ return `👤 Guest (${minutesRemaining}m remaining)`;
+ } else {
+ return '👤 Guest (Expired)';
+ }
+ }
+ return '👤 Guest User';
+ } else if (session.user_type === 'registered') {
+ const username = session.user_info?.username || session.user_info?.email || 'User';
+ const accountType = session.user_info?.account_type || 'free';
+ const hasSubscription = session.subscription?.has_subscription;
+
+ // Show account type badge
+ if (hasSubscription) {
+ const planName = session.subscription?.subscription?.plan?.name || accountType;
+ return `👤 ${username} | 📦 ${planName} | ✅ Active`;
+ } else if (accountType === 'free') {
+ return `👤 ${username} | 📦 Free Plan`;
+ } else {
+ return `👤 ${username} | 📦 ${accountType.charAt(0).toUpperCase() + accountType.slice(1)}`;
+ }
+ }
+
+ return 'Unknown Session';
+ };
+
const toggleFullscreen = () => {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().then(() => {
@@ -146,9 +189,9 @@ export default function FinxeptTerminal() {
setTimeout(() => setStatusMessage(""), 3000);
};
- const handleMenuAction = (item) => {
+ const handleMenuAction = async (item) => {
setStatusMessage(`${item.label} clicked`);
-
+
// Handle specific actions
switch(item.action) {
case 'fullscreen':
@@ -160,6 +203,12 @@ export default function FinxeptTerminal() {
case 'export':
setStatusMessage("Export functionality not implemented");
break;
+ case 'logout':
+ setStatusMessage("Logging out...");
+ await logout();
+ // Redirect to login will be handled by App.tsx
+ window.location.href = '/';
+ break;
default:
setTimeout(() => setStatusMessage(""), 3000);
}
@@ -184,11 +233,10 @@ export default function FinxeptTerminal() {
];
const sessionMenuItems = [
- { label: 'Login', icon: <User size={12} /> },
+ { label: 'Session Info', 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 }
+ { label: 'Extend Session', icon: null, separator: true },
+ { label: 'Logout', icon: <LogOut size={12} />, action: 'logout' }
];
const apiMenuItems = [
@@ -316,7 +364,39 @@ export default function FinxeptTerminal() {
>
{isFullscreen ? <Minimize size={14} /> : <Maximize size={14} />}
</button>
- <span style={{ color: '#fbbf24' }}>Guest (18h remaining)</span>
+ <span style={{ color: '#fbbf24', fontSize: '10px' }}>{getSessionDisplay()}</span>
+ <button
+ onClick={async () => {
+ setStatusMessage("Logging out...");
+ await logout();
+ window.location.href = '/';
+ }}
+ style={{
+ backgroundColor: 'transparent',
+ color: '#ff6b6b',
+ border: '1px solid #ff6b6b',
+ padding: '3px 8px',
+ fontSize: '10px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px',
+ fontWeight: 'bold'
+ }}
+ onMouseEnter={(e) => {
+ e.currentTarget.style.backgroundColor = '#ff6b6b';
+ e.currentTarget.style.color = '#fff';
+ }}
+ onMouseLeave={(e) => {
+ e.currentTarget.style.backgroundColor = 'transparent';
+ e.currentTarget.style.color = '#ff6b6b';
+ }}
+ title="Logout"
+ >
+ <LogOut size={12} />
+ LOGOUT
+ </button>
<span style={{ color: '#737373', cursor: 'pointer' }} title="Help">?</span>
</div>
</div>
@@ -484,6 +564,12 @@ export default function FinxeptTerminal() {
>
Maritime
</TabsTrigger>
+ <TabsTrigger
+ value="settings"
+ style={activeTab === 'settings' ? tabStyles.active : tabStyles.default}
+ >
+ Settings
+ </TabsTrigger>
</TabsList>
</Tabs>
</div>
@@ -603,6 +689,9 @@ export default function FinxeptTerminal() {
<TabsContent value="maritime" className="h-full m-0 p-0">
<MaritimeTab />
</TabsContent>
+ <TabsContent value="settings" className="h-full m-0 p-0">
+ <SettingsTab />
+ </TabsContent>
</Tabs>
</div>
</div>
diff --git a/fincept-terminal-desktop/src/components/payment/PaymentSuccessScreen.tsx b/fincept-terminal-desktop/src/components/payment/PaymentSuccessScreen.tsx
index d204ad934..5507e0ef9 100644
--- a/fincept-terminal-desktop/src/components/payment/PaymentSuccessScreen.tsx
+++ b/fincept-terminal-desktop/src/components/payment/PaymentSuccessScreen.tsx
@@ -43,6 +43,11 @@ const PaymentSuccessScreen: React.FC<PaymentSuccessScreenProps> = ({
console.log('Payment success page loaded with params:', { sessionId, paymentId });
+ // Clear URL parameters immediately to prevent re-processing on refresh
+ if (sessionId || paymentId) {
+ window.history.replaceState({}, document.title, window.location.pathname);
+ }
+
const handlePaymentSuccess = async () => {
if (!session?.api_key) {
setError('Authentication required');
diff --git a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
index eb4b79e17..cb2c36da6 100644
--- a/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/ProfileTab.tsx
@@ -1,30 +1,8 @@
import React, { useState, useEffect } from 'react';
-
-interface SessionData {
- user_type: 'guest' | 'registered' | 'unknown';
- authenticated: boolean;
- api_key?: string;
- device_id?: string;
- user_info?: {
- username: string;
- email: string;
- account_type: string;
- created_at: string;
- credit_balance: number;
- };
- requests_today: number;
- daily_limit: number;
-}
+import { useAuth } from '@/contexts/AuthContext';
const ProfileTab: React.FC = () => {
- const [sessionData, setSessionData] = useState<SessionData>({
- user_type: 'guest',
- authenticated: false,
- api_key: 'fk_guest_abc123def456',
- device_id: 'device_12345678901234567890',
- requests_today: 15,
- daily_limit: 50
- });
+ const { session, logout } = useAuth();
const [lastRefresh, setLastRefresh] = useState<Date>(new Date());
const [requestCount, setRequestCount] = useState(15);
@@ -55,14 +33,9 @@ const ProfileTab: React.FC = () => {
setRequestCount(prev => prev + 1);
};
- const logoutUser = () => {
- setSessionData({
- user_type: 'guest',
- authenticated: false,
- device_id: `cleared_${Date.now()}`,
- requests_today: 0,
- daily_limit: 50
- });
+ const logoutUser = async () => {
+ await logout();
+ window.location.href = '/';
};
const showSignupInfo = () => {
@@ -180,8 +153,11 @@ const ProfileTab: React.FC = () => {
};
const renderGuestProfile = () => {
- const displayDeviceId = sessionData.device_id?.substring(0, 20) + "..." || 'Unknown';
- const remaining = Math.max(0, sessionData.daily_limit - sessionData.requests_today);
+ if (!session) return null;
+ const displayDeviceId = session.device_id?.substring(0, 20) + "..." || 'Unknown';
+ const requests_today = session.requests_today || 0;
+ const daily_limit = session.daily_limit || 50;
+ const remaining = Math.max(0, daily_limit - requests_today);
return (
<div className="p-4">
@@ -193,10 +169,10 @@ const ProfileTab: React.FC = () => {
<TextLine text="Account Type: Guest User" />
<TextLine text={`Device ID: ${displayDeviceId}`} />
<Spacer />
- <TextLine text={getApiKeyInfo(sessionData.api_key)} />
+ <TextLine text={getApiKeyInfo(session.api_key || undefined)} />
<Spacer />
<TextLine text={`Session Requests: ${requestCount}`} />
- <TextLine text={`Today's Requests: ${sessionData.requests_today}/${sessionData.daily_limit}`} />
+ <TextLine text={`Today's Requests: ${requests_today}/${daily_limit}`} />
<TextLine
text={`Remaining Today: ${remaining}`}
color={remaining > 10 ? COLORS.success : COLORS.error}
@@ -210,11 +186,11 @@ const ProfileTab: React.FC = () => {
right={
<InfoWidget title="Upgrade Your Access">
<TextLine
- text={sessionData.api_key?.startsWith("fk_guest_") ? "🔄 Current: Guest API Key" : "🔄 Current: Offline Mode"}
+ text={session.api_key ? "🔄 Current: Guest API Key" : "🔄 Current: Offline Mode"}
color={COLORS.warning}
/>
<Spacer />
- {sessionData.api_key?.startsWith("fk_guest_") ? (
+ {session.api_key ? (
<>
<TextLine text="• Temporary access (24 hours)" />
<TextLine text="• 50 requests per day" />
@@ -249,7 +225,7 @@ const ProfileTab: React.FC = () => {
</div>
<div>
<TextLine text="Daily Usage:" color={COLORS.info} />
- <TextLine text={`${sessionData.requests_today}/${sessionData.daily_limit}`} />
+ <TextLine text={`${requests_today}/${daily_limit}`} />
</div>
<div>
<TextLine text="Status:" color={COLORS.info} />
@@ -266,8 +242,12 @@ const ProfileTab: React.FC = () => {
};
const renderUserProfile = () => {
- const userInfo = sessionData.user_info;
+ if (!session) return null;
+ const userInfo = session.user_info;
const creditBalance = userInfo?.credit_balance || 0;
+ const accountType = userInfo?.account_type || 'free';
+ const hasSubscription = session.subscription?.has_subscription;
+ const subscriptionPlan = session.subscription?.subscription?.plan;
let balanceColor, status;
if (creditBalance > 1000) {
@@ -290,15 +270,24 @@ const ProfileTab: React.FC = () => {
<InfoWidget title="Account Details">
<TextLine text={`Username: ${userInfo?.username || 'N/A'}`} />
<TextLine text={`Email: ${userInfo?.email || 'N/A'}`} />
- <TextLine text={`Account Type: ${userInfo?.account_type?.charAt(0).toUpperCase() + userInfo?.account_type?.slice(1) || 'Free'}`} />
+ <TextLine text={`Account Type: ${accountType.charAt(0).toUpperCase() + accountType.slice(1)}`} />
<TextLine text={`Member Since: ${formatDate(userInfo?.created_at)}`} />
<Spacer />
+ {hasSubscription && subscriptionPlan && (
+ <>
+ <TextLine text="Subscription:" color={COLORS.info} />
+ <TextLine text={`Plan: ${subscriptionPlan.name}`} color={COLORS.success} />
+ <TextLine text={`Price: $${subscriptionPlan.price}/month`} />
+ <TextLine text={`Status: ${session.subscription?.subscription?.status}`} color={COLORS.success} />
+ <Spacer />
+ </>
+ )}
<TextLine text="Authentication:" color={COLORS.info} />
- <TextLine text={getApiKeyInfo(sessionData.api_key, true)} />
+ <TextLine text={getApiKeyInfo(session.api_key || undefined, true)} />
<Spacer />
- <TextLine text="✓ Unlimited API requests" />
- <TextLine text="✓ All database access" />
- <TextLine text="✓ Premium features" />
+ <TextLine text={hasSubscription ? "✓ Unlimited API requests" : "✓ Limited API requests"} />
+ <TextLine text={hasSubscription ? "✓ All database access" : "✓ Basic database access"} />
+ <TextLine text={hasSubscription ? "✓ Premium features" : "✓ Standard features"} />
<Spacer height={20} />
<ButtonGroup buttons={[
{ label: "Regenerate API Key", callback: regenerateApiKey },
@@ -368,10 +357,13 @@ const ProfileTab: React.FC = () => {
// Main render logic based on user type
const renderContent = () => {
- switch (sessionData.user_type) {
+ if (!session) {
+ return renderUnknownProfile();
+ }
+
+ switch (session.user_type) {
case 'guest': return renderGuestProfile();
case 'registered': return renderUserProfile();
- case 'unknown': return renderUnknownProfile();
default: return renderUnknownProfile();
}
};
diff --git a/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
new file mode 100644
index 000000000..15d60acf6
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/SettingsTab.tsx
@@ -0,0 +1,880 @@
+import React, { useState, useEffect } from 'react';
+import { Eye, EyeOff, Plus, Trash2, Save, RefreshCw, Lock, User, Settings as SettingsIcon, Database, Terminal, Bell } from 'lucide-react';
+import * as storageService from '@/services/storageService';
+
+interface Credential {
+ id?: number;
+ service_name: string;
+ username: string;
+ password: string;
+ api_key?: string;
+ api_secret?: string;
+ additional_data?: string;
+ created_at?: string;
+ updated_at?: string;
+}
+
+export default function SettingsTab() {
+ const [activeSection, setActiveSection] = useState<'credentials' | 'profile' | 'terminal' | 'notifications'>('credentials');
+ const [credentials, setCredentials] = useState<Credential[]>([]);
+ const [showPasswords, setShowPasswords] = useState<Record<number, boolean>>({});
+ const [loading, setLoading] = useState(false);
+ const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
+ const [dbInitialized, setDbInitialized] = useState(false);
+
+ // New credential form
+ const [newCredential, setNewCredential] = useState<Credential>({
+ service_name: '',
+ username: '',
+ password: '',
+ api_key: '',
+ api_secret: '',
+ additional_data: ''
+ });
+
+ // Mock user profile data
+ const [userProfile, setUserProfile] = useState({
+ full_name: 'John Doe',
+ email: '[email protected]',
+ account_type: 'Professional',
+ subscription_status: 'Active',
+ subscription_expiry: '2025-12-31',
+ api_calls_today: 1247,
+ api_limit: 10000,
+ storage_used: '2.4 GB',
+ storage_limit: '50 GB'
+ });
+
+ // Mock terminal settings
+ const [terminalSettings, setTerminalSettings] = useState({
+ theme: 'dark',
+ font_size: '11',
+ auto_refresh: true,
+ refresh_interval: '5',
+ show_tooltips: true,
+ enable_animations: true,
+ data_compression: false,
+ cache_enabled: true
+ });
+
+ // Mock notification settings
+ const [notificationSettings, setNotificationSettings] = useState({
+ email_alerts: true,
+ price_alerts: true,
+ news_alerts: false,
+ trade_confirmations: true,
+ system_updates: true,
+ marketing_emails: false
+ });
+
+ useEffect(() => {
+ initDB();
+ }, []);
+
+ const initDB = async () => {
+ try {
+ setLoading(true);
+ await storageService.initializeDatabase();
+ setDbInitialized(true);
+ await loadCredentials();
+ showMessage('success', 'Database initialized successfully');
+ } catch (error) {
+ console.error('Failed to initialize database:', error);
+ showMessage('error', 'Failed to initialize database');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const loadCredentials = async () => {
+ try {
+ const result = await storageService.getCredentials();
+ if (result.success && result.data) {
+ setCredentials(result.data);
+ }
+ } catch (error) {
+ console.error('Failed to load credentials:', error);
+ }
+ };
+
+ const handleSaveCredential = async () => {
+ if (!newCredential.service_name || !newCredential.username || !newCredential.password) {
+ showMessage('error', 'Service name, username, and password are required');
+ return;
+ }
+
+ try {
+ setLoading(true);
+ const result = await storageService.saveCredential(newCredential);
+
+ if (result.success) {
+ showMessage('success', result.message);
+ setNewCredential({
+ service_name: '',
+ username: '',
+ password: '',
+ api_key: '',
+ api_secret: '',
+ additional_data: ''
+ });
+ await loadCredentials();
+ } else {
+ showMessage('error', result.message);
+ }
+ } catch (error) {
+ showMessage('error', 'Failed to save credential');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleDeleteCredential = async (id: number) => {
+ if (!confirm('Are you sure you want to delete this credential?')) return;
+
+ try {
+ setLoading(true);
+ const result = await storageService.deleteCredential(id);
+
+ if (result.success) {
+ showMessage('success', result.message);
+ await loadCredentials();
+ } else {
+ showMessage('error', result.message);
+ }
+ } catch (error) {
+ showMessage('error', 'Failed to delete credential');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const togglePasswordVisibility = (id: number) => {
+ setShowPasswords(prev => ({ ...prev, [id]: !prev[id] }));
+ };
+
+ const showMessage = (type: 'success' | 'error', text: string) => {
+ setMessage({ type, text });
+ setTimeout(() => setMessage(null), 5000);
+ };
+
+ const handleSaveSettings = async (section: string) => {
+ // In a real implementation, save to DuckDB
+ showMessage('success', `${section} settings saved successfully`);
+ };
+
+ return (
+ <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', backgroundColor: '#000' }}>
+ <style>{`
+ *::-webkit-scrollbar { width: 8px; height: 8px; }
+ *::-webkit-scrollbar-track { background: #0a0a0a; }
+ *::-webkit-scrollbar-thumb { background: #2a2a2a; border-radius: 4px; }
+ *::-webkit-scrollbar-thumb:hover { background: #3a3a3a; }
+ `}</style>
+
+ {/* Header */}
+ <div style={{
+ borderBottom: '2px solid #ea580c',
+ padding: '12px 16px',
+ background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <SettingsIcon size={20} color="#ea580c" />
+ <span style={{ color: '#ea580c', fontSize: '16px', fontWeight: 'bold', letterSpacing: '1px' }}>
+ TERMINAL SETTINGS
+ </span>
+ </div>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
+ <div style={{
+ padding: '4px 8px',
+ background: dbInitialized ? '#0a3a0a' : '#3a0a0a',
+ border: `1px solid ${dbInitialized ? '#00ff00' : '#ff0000'}`,
+ borderRadius: '3px'
+ }}>
+ <span style={{ color: dbInitialized ? '#00ff00' : '#ff0000', fontSize: '9px', fontWeight: 'bold' }}>
+ <Database size={10} style={{ display: 'inline', marginRight: '4px' }} />
+ DB: {dbInitialized ? 'CONNECTED' : 'DISCONNECTED'}
+ </span>
+ </div>
+ </div>
+ </div>
+
+ {/* Message Banner */}
+ {message && (
+ <div style={{
+ padding: '8px 16px',
+ background: message.type === 'success' ? '#0a3a0a' : '#3a0a0a',
+ borderBottom: `1px solid ${message.type === 'success' ? '#00ff00' : '#ff0000'}`,
+ color: message.type === 'success' ? '#00ff00' : '#ff0000',
+ fontSize: '10px',
+ flexShrink: 0
+ }}>
+ {message.text}
+ </div>
+ )}
+
+ {/* Main Layout */}
+ <div style={{ flex: 1, display: 'flex', minHeight: 0, overflow: 'hidden' }}>
+
+ {/* Sidebar Navigation */}
+ <div style={{ width: '220px', borderRight: '1px solid #1a1a1a', background: '#0a0a0a', flexShrink: 0 }}>
+ <div style={{ padding: '16px 0' }}>
+ {[
+ { id: 'credentials', icon: Lock, label: 'Credentials' },
+ { id: 'profile', icon: User, label: 'User Profile' },
+ { id: 'terminal', icon: Terminal, label: 'Terminal Config' },
+ { id: 'notifications', icon: Bell, label: 'Notifications' }
+ ].map((item) => (
+ <div
+ key={item.id}
+ onClick={() => setActiveSection(item.id as any)}
+ style={{
+ padding: '12px 16px',
+ cursor: 'pointer',
+ background: activeSection === item.id ? '#1a1a1a' : 'transparent',
+ borderLeft: activeSection === item.id ? '3px solid #ea580c' : '3px solid transparent',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '12px',
+ transition: 'all 0.2s'
+ }}
+ onMouseEnter={(e) => {
+ if (activeSection !== item.id) e.currentTarget.style.background = '#151515';
+ }}
+ onMouseLeave={(e) => {
+ if (activeSection !== item.id) e.currentTarget.style.background = 'transparent';
+ }}
+ >
+ <item.icon size={16} color={activeSection === item.id ? '#ea580c' : '#666'} />
+ <span style={{ color: activeSection === item.id ? '#fff' : '#666', fontSize: '11px', fontWeight: activeSection === item.id ? 'bold' : 'normal' }}>
+ {item.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ {/* Main Content */}
+ <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflow: 'hidden' }}>
+ <div style={{ flex: 1, overflowY: 'auto', padding: '20px', minHeight: 0 }}>
+
+ {/* Credentials Section */}
+ {activeSection === 'credentials' && (
+ <div>
+ <div style={{ marginBottom: '24px' }}>
+ <h2 style={{ color: '#ea580c', fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ CREDENTIAL MANAGEMENT
+ </h2>
+ <p style={{ color: '#888', fontSize: '10px' }}>
+ Securely store API keys, passwords, and authentication tokens. All data is encrypted and stored locally in DuckDB.
+ </p>
+ </div>
+
+ {/* Add New Credential */}
+ <div style={{
+ background: '#0a0a0a',
+ border: '1px solid #1a1a1a',
+ padding: '16px',
+ marginBottom: '20px',
+ borderRadius: '4px'
+ }}>
+ <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ Add New Credential
+ </h3>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '12px' }}>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ SERVICE NAME *
+ </label>
+ <input
+ type="text"
+ value={newCredential.service_name}
+ onChange={(e) => setNewCredential({ ...newCredential, service_name: e.target.value })}
+ placeholder="e.g., Fyers, Zerodha, Alpha Vantage"
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ USERNAME *
+ </label>
+ <input
+ type="text"
+ value={newCredential.username}
+ onChange={(e) => setNewCredential({ ...newCredential, username: e.target.value })}
+ placeholder="Username or Client ID"
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ PASSWORD *
+ </label>
+ <input
+ type="password"
+ value={newCredential.password}
+ onChange={(e) => setNewCredential({ ...newCredential, password: e.target.value })}
+ placeholder="Password or Secret"
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ API KEY (Optional)
+ </label>
+ <input
+ type="text"
+ value={newCredential.api_key}
+ onChange={(e) => setNewCredential({ ...newCredential, api_key: e.target.value })}
+ placeholder="API Key"
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ API SECRET (Optional)
+ </label>
+ <input
+ type="password"
+ value={newCredential.api_secret}
+ onChange={(e) => setNewCredential({ ...newCredential, api_secret: e.target.value })}
+ placeholder="API Secret"
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>
+ ADDITIONAL DATA (Optional)
+ </label>
+ <input
+ type="text"
+ value={newCredential.additional_data}
+ onChange={(e) => setNewCredential({ ...newCredential, additional_data: e.target.value })}
+ placeholder="JSON or any extra data"
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ </div>
+
+ <button
+ onClick={handleSaveCredential}
+ disabled={loading}
+ style={{
+ background: '#ea580c',
+ color: '#fff',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: loading ? 'not-allowed' : 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px',
+ opacity: loading ? 0.5 : 1
+ }}
+ >
+ <Plus size={14} />
+ {loading ? 'SAVING...' : 'ADD CREDENTIAL'}
+ </button>
+ </div>
+
+ {/* Saved Credentials List */}
+ <div>
+ <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>
+ Saved Credentials ({credentials.length})
+ </h3>
+
+ {credentials.length === 0 ? (
+ <div style={{
+ background: '#0a0a0a',
+ border: '1px solid #1a1a1a',
+ padding: '32px',
+ textAlign: 'center',
+ borderRadius: '4px'
+ }}>
+ <Lock size={32} color="#333" style={{ margin: '0 auto 12px' }} />
+ <p style={{ color: '#666', fontSize: '11px' }}>No credentials saved yet</p>
+ </div>
+ ) : (
+ <div style={{ display: 'grid', gap: '12px' }}>
+ {credentials.map((cred) => (
+ <div
+ key={cred.id}
+ style={{
+ background: '#0a0a0a',
+ border: '1px solid #1a1a1a',
+ padding: '16px',
+ borderRadius: '4px'
+ }}
+ >
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '12px' }}>
+ <div>
+ <h4 style={{ color: '#ea580c', fontSize: '11px', fontWeight: 'bold', marginBottom: '4px' }}>
+ {cred.service_name}
+ </h4>
+ <p style={{ color: '#666', fontSize: '9px' }}>
+ Created: {cred.created_at ? new Date(cred.created_at).toLocaleDateString() : 'N/A'}
+ </p>
+ </div>
+ <button
+ onClick={() => cred.id && handleDeleteCredential(cred.id)}
+ style={{
+ background: 'transparent',
+ border: '1px solid #ff0000',
+ color: '#ff0000',
+ padding: '4px 8px',
+ fontSize: '9px',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '4px'
+ }}
+ >
+ <Trash2 size={12} />
+ DELETE
+ </button>
+ </div>
+
+ <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: '8px', fontSize: '10px' }}>
+ <span style={{ color: '#888' }}>Username:</span>
+ <span style={{ color: '#fff' }}>{cred.username}</span>
+
+ <span style={{ color: '#888' }}>Password:</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <span style={{ color: '#fff', fontFamily: 'monospace' }}>
+ {showPasswords[cred.id!] ? cred.password : '•'.repeat(12)}
+ </span>
+ <button
+ onClick={() => cred.id && togglePasswordVisibility(cred.id)}
+ style={{
+ background: 'transparent',
+ border: 'none',
+ cursor: 'pointer',
+ padding: '2px',
+ display: 'flex'
+ }}
+ >
+ {showPasswords[cred.id!] ? <EyeOff size={14} color="#888" /> : <Eye size={14} color="#888" />}
+ </button>
+ </div>
+
+ {cred.api_key && (
+ <>
+ <span style={{ color: '#888' }}>API Key:</span>
+ <span style={{ color: '#fff', fontFamily: 'monospace', wordBreak: 'break-all' }}>{cred.api_key}</span>
+ </>
+ )}
+
+ {cred.api_secret && (
+ <>
+ <span style={{ color: '#888' }}>API Secret:</span>
+ <span style={{ color: '#fff', fontFamily: 'monospace' }}>
+ {showPasswords[cred.id!] ? cred.api_secret : '•'.repeat(12)}
+ </span>
+ </>
+ )}
+
+ {cred.additional_data && (
+ <>
+ <span style={{ color: '#888' }}>Additional:</span>
+ <span style={{ color: '#fff', fontSize: '9px', wordBreak: 'break-all' }}>{cred.additional_data}</span>
+ </>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* User Profile Section */}
+ {activeSection === 'profile' && (
+ <div>
+ <div style={{ marginBottom: '24px' }}>
+ <h2 style={{ color: '#ea580c', fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ USER PROFILE
+ </h2>
+ <p style={{ color: '#888', fontSize: '10px' }}>
+ View and manage your account information and subscription details.
+ </p>
+ </div>
+
+ <div style={{ display: 'grid', gap: '16px' }}>
+ {/* Account Info */}
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '16px', borderRadius: '4px' }}>
+ <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>Account Information</h3>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>FULL NAME</label>
+ <input
+ type="text"
+ value={userProfile.full_name}
+ onChange={(e) => setUserProfile({ ...userProfile, full_name: e.target.value })}
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>EMAIL</label>
+ <input
+ type="email"
+ value={userProfile.email}
+ onChange={(e) => setUserProfile({ ...userProfile, email: e.target.value })}
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ />
+ </div>
+ </div>
+ <button
+ onClick={() => handleSaveSettings('Profile')}
+ style={{
+ background: '#ea580c',
+ color: '#fff',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ marginTop: '12px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}
+ >
+ <Save size={14} />
+ SAVE CHANGES
+ </button>
+ </div>
+
+ {/* Subscription Stats */}
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '16px', borderRadius: '4px' }}>
+ <h3 style={{ color: '#fff', fontSize: '12px', fontWeight: 'bold', marginBottom: '12px' }}>Subscription Details</h3>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', fontSize: '10px' }}>
+ <div>
+ <span style={{ color: '#888' }}>Account Type:</span>
+ <div style={{ color: '#ea580c', fontWeight: 'bold', marginTop: '4px' }}>{userProfile.account_type}</div>
+ </div>
+ <div>
+ <span style={{ color: '#888' }}>Status:</span>
+ <div style={{ color: '#00ff00', fontWeight: 'bold', marginTop: '4px' }}>{userProfile.subscription_status}</div>
+ </div>
+ <div>
+ <span style={{ color: '#888' }}>Expires:</span>
+ <div style={{ color: '#fff', marginTop: '4px' }}>{userProfile.subscription_expiry}</div>
+ </div>
+ <div>
+ <span style={{ color: '#888' }}>API Calls Today:</span>
+ <div style={{ color: '#fff', marginTop: '4px' }}>{userProfile.api_calls_today} / {userProfile.api_limit}</div>
+ </div>
+ <div>
+ <span style={{ color: '#888' }}>Storage Used:</span>
+ <div style={{ color: '#fff', marginTop: '4px' }}>{userProfile.storage_used} / {userProfile.storage_limit}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Terminal Configuration Section */}
+ {activeSection === 'terminal' && (
+ <div>
+ <div style={{ marginBottom: '24px' }}>
+ <h2 style={{ color: '#ea580c', fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ TERMINAL CONFIGURATION
+ </h2>
+ <p style={{ color: '#888', fontSize: '10px' }}>
+ Customize terminal behavior, appearance, and performance settings.
+ </p>
+ </div>
+
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '16px', borderRadius: '4px' }}>
+ <div style={{ display: 'grid', gap: '16px' }}>
+ {/* Appearance */}
+ <div>
+ <h3 style={{ color: '#fff', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>Appearance</h3>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>THEME</label>
+ <select
+ value={terminalSettings.theme}
+ onChange={(e) => setTerminalSettings({ ...terminalSettings, theme: e.target.value })}
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="dark">Dark (Bloomberg)</option>
+ <option value="light">Light</option>
+ <option value="matrix">Matrix Green</option>
+ </select>
+ </div>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>FONT SIZE</label>
+ <select
+ value={terminalSettings.font_size}
+ onChange={(e) => setTerminalSettings({ ...terminalSettings, font_size: e.target.value })}
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="9">9px (Small)</option>
+ <option value="10">10px (Default)</option>
+ <option value="11">11px (Medium)</option>
+ <option value="12">12px (Large)</option>
+ </select>
+ </div>
+ </div>
+ </div>
+
+ {/* Performance */}
+ <div>
+ <h3 style={{ color: '#fff', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>Performance</h3>
+ <div style={{ display: 'grid', gap: '8px' }}>
+ {[
+ { key: 'auto_refresh', label: 'Auto Refresh Data' },
+ { key: 'enable_animations', label: 'Enable Animations' },
+ { key: 'show_tooltips', label: 'Show Tooltips' },
+ { key: 'data_compression', label: 'Data Compression' },
+ { key: 'cache_enabled', label: 'Enable Caching' }
+ ].map((setting) => (
+ <label key={setting.key} style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
+ <input
+ type="checkbox"
+ checked={terminalSettings[setting.key as keyof typeof terminalSettings] as boolean}
+ onChange={(e) => setTerminalSettings({ ...terminalSettings, [setting.key]: e.target.checked })}
+ style={{ width: '14px', height: '14px', cursor: 'pointer' }}
+ />
+ <span style={{ color: '#fff', fontSize: '10px' }}>{setting.label}</span>
+ </label>
+ ))}
+ </div>
+ </div>
+
+ {/* Data Settings */}
+ <div>
+ <h3 style={{ color: '#fff', fontSize: '11px', fontWeight: 'bold', marginBottom: '8px' }}>Data Settings</h3>
+ <div>
+ <label style={{ color: '#888', fontSize: '9px', display: 'block', marginBottom: '4px' }}>REFRESH INTERVAL (seconds)</label>
+ <select
+ value={terminalSettings.refresh_interval}
+ onChange={(e) => setTerminalSettings({ ...terminalSettings, refresh_interval: e.target.value })}
+ style={{
+ width: '100%',
+ background: '#000',
+ border: '1px solid #2a2a2a',
+ color: '#fff',
+ padding: '8px',
+ fontSize: '10px',
+ borderRadius: '3px'
+ }}
+ >
+ <option value="1">1 second</option>
+ <option value="5">5 seconds</option>
+ <option value="10">10 seconds</option>
+ <option value="30">30 seconds</option>
+ <option value="60">1 minute</option>
+ </select>
+ </div>
+ </div>
+ </div>
+
+ <button
+ onClick={() => handleSaveSettings('Terminal')}
+ style={{
+ background: '#ea580c',
+ color: '#fff',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ marginTop: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}
+ >
+ <Save size={14} />
+ SAVE CONFIGURATION
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* Notifications Section */}
+ {activeSection === 'notifications' && (
+ <div>
+ <div style={{ marginBottom: '24px' }}>
+ <h2 style={{ color: '#ea580c', fontSize: '14px', fontWeight: 'bold', marginBottom: '8px' }}>
+ NOTIFICATION PREFERENCES
+ </h2>
+ <p style={{ color: '#888', fontSize: '10px' }}>
+ Configure alerts and notifications for market events, trades, and system updates.
+ </p>
+ </div>
+
+ <div style={{ background: '#0a0a0a', border: '1px solid #1a1a1a', padding: '16px', borderRadius: '4px' }}>
+ <div style={{ display: 'grid', gap: '12px' }}>
+ {[
+ { key: 'email_alerts', label: 'Email Alerts', desc: 'Receive email notifications for important events' },
+ { key: 'price_alerts', label: 'Price Alerts', desc: 'Notify when price targets are reached' },
+ { key: 'news_alerts', label: 'News Alerts', desc: 'Breaking financial news notifications' },
+ { key: 'trade_confirmations', label: 'Trade Confirmations', desc: 'Confirm all trade executions' },
+ { key: 'system_updates', label: 'System Updates', desc: 'Terminal updates and maintenance notices' },
+ { key: 'marketing_emails', label: 'Marketing Emails', desc: 'Product updates and promotional content' }
+ ].map((notif) => (
+ <div key={notif.key} style={{ padding: '12px', background: '#000', borderRadius: '3px' }}>
+ <label style={{ display: 'flex', alignItems: 'start', gap: '12px', cursor: 'pointer' }}>
+ <input
+ type="checkbox"
+ checked={notificationSettings[notif.key as keyof typeof notificationSettings]}
+ onChange={(e) => setNotificationSettings({ ...notificationSettings, [notif.key]: e.target.checked })}
+ style={{ width: '16px', height: '16px', cursor: 'pointer', marginTop: '2px', flexShrink: 0 }}
+ />
+ <div>
+ <div style={{ color: '#fff', fontSize: '10px', fontWeight: 'bold', marginBottom: '4px' }}>{notif.label}</div>
+ <div style={{ color: '#666', fontSize: '9px' }}>{notif.desc}</div>
+ </div>
+ </label>
+ </div>
+ ))}
+ </div>
+
+ <button
+ onClick={() => handleSaveSettings('Notification')}
+ style={{
+ background: '#ea580c',
+ color: '#fff',
+ border: 'none',
+ padding: '8px 16px',
+ fontSize: '10px',
+ fontWeight: 'bold',
+ cursor: 'pointer',
+ borderRadius: '3px',
+ marginTop: '16px',
+ display: 'flex',
+ alignItems: 'center',
+ gap: '6px'
+ }}
+ >
+ <Save size={14} />
+ SAVE PREFERENCES
+ </button>
+ </div>
+ </div>
+ )}
+
+ </div>
+ </div>
+ </div>
+
+ {/* Footer */}
+ <div style={{
+ borderTop: '2px solid #ea580c',
+ padding: '8px 16px',
+ background: 'linear-gradient(180deg, #0a0a0a 0%, #1a1a1a 100%)',
+ display: 'flex',
+ justifyContent: 'space-between',
+ alignItems: 'center',
+ flexShrink: 0,
+ flexWrap: 'wrap',
+ gap: '12px'
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '16px', fontSize: '9px' }}>
+ <span style={{ color: '#ea580c', fontWeight: 'bold' }}>SETTINGS v1.0.0</span>
+ <span style={{ color: '#666' }}>|</span>
+ <span style={{ color: '#888' }}>Database: IndexedDB</span>
+ <span style={{ color: '#666' }}>|</span>
+ <span style={{ color: '#888' }}>Storage: Local Browser</span>
+ </div>
+ <div style={{ fontSize: '9px', color: '#666' }}>
+ All credentials are stored securely in browser database
+ </div>
+ </div>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/authApi.tsx b/fincept-terminal-desktop/src/services/authApi.tsx
index 6520de7b0..fb3539586 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: 'http://localhost:4500',
+ BASE_URL: 'https://finceptbackend.share.zrok.io',
API_VERSION: 'v1',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
diff --git a/fincept-terminal-desktop/src/services/duckdbService.ts b/fincept-terminal-desktop/src/services/duckdbService.ts
new file mode 100644
index 000000000..9aa7c52a3
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/duckdbService.ts
@@ -0,0 +1,290 @@
+import * as duckdb from 'duckdb';
+import path from 'path';
+import { app } from '@tauri-apps/api';
+
+let db: duckdb.Database | null = null;
+
+interface Credential {
+ id?: number;
+ service_name: string;
+ username: string;
+ password: string;
+ api_key?: string;
+ api_secret?: string;
+ additional_data?: string;
+ created_at?: string;
+ updated_at?: string;
+}
+
+interface UserSettings {
+ id?: number;
+ setting_key: string;
+ setting_value: string;
+ updated_at?: string;
+}
+
+// Initialize DuckDB database
+export async function initializeDatabase(): Promise<void> {
+ return new Promise(async (resolve, reject) => {
+ try {
+ // Get app data directory
+ let dbPath: string;
+ try {
+ const appDataDir = await app.appDataDir();
+ dbPath = path.join(appDataDir, 'fincept_terminal.duckdb');
+ } catch (err) {
+ // Fallback for development
+ dbPath = './fincept_terminal.duckdb';
+ }
+
+ db = new duckdb.Database(dbPath, (err) => {
+ if (err) {
+ console.error('DuckDB initialization error:', err);
+ reject(err);
+ return;
+ }
+
+ // Create tables
+ const connection = db!.connect();
+
+ connection.all(`
+ CREATE TABLE IF NOT EXISTS credentials (
+ id INTEGER PRIMARY KEY,
+ service_name VARCHAR NOT NULL,
+ username VARCHAR NOT NULL,
+ password VARCHAR NOT NULL,
+ api_key VARCHAR,
+ api_secret VARCHAR,
+ additional_data TEXT,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ `, (err) => {
+ if (err) {
+ console.error('Error creating credentials table:', err);
+ reject(err);
+ return;
+ }
+
+ connection.all(`
+ CREATE TABLE IF NOT EXISTS user_settings (
+ id INTEGER PRIMARY KEY,
+ setting_key VARCHAR UNIQUE NOT NULL,
+ setting_value TEXT NOT NULL,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ `, (err) => {
+ if (err) {
+ console.error('Error creating user_settings table:', err);
+ reject(err);
+ return;
+ }
+
+ console.log('DuckDB initialized successfully at:', dbPath);
+ resolve();
+ });
+ });
+ });
+ } catch (error) {
+ console.error('Failed to initialize DuckDB:', error);
+ reject(error);
+ }
+ });
+}
+
+// Credential Management Functions
+
+export async function saveCredential(credential: Credential): Promise<{ success: boolean; message: string; id?: number }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ const connection = db.connect();
+
+ // Check if credential already exists
+ connection.all(
+ 'SELECT id FROM credentials WHERE service_name = ? AND username = ?',
+ [credential.service_name, credential.username],
+ (err, rows: any[]) => {
+ if (err) {
+ resolve({ success: false, message: `Error checking credential: ${err.message}` });
+ return;
+ }
+
+ if (rows && rows.length > 0) {
+ // Update existing credential
+ connection.run(
+ `UPDATE credentials
+ SET password = ?, api_key = ?, api_secret = ?, additional_data = ?, updated_at = CURRENT_TIMESTAMP
+ WHERE id = ?`,
+ [credential.password, credential.api_key || null, credential.api_secret || null, credential.additional_data || null, rows[0].id],
+ (err) => {
+ if (err) {
+ resolve({ success: false, message: `Error updating credential: ${err.message}` });
+ } else {
+ resolve({ success: true, message: 'Credential updated successfully', id: rows[0].id });
+ }
+ }
+ );
+ } else {
+ // Insert new credential
+ connection.run(
+ `INSERT INTO credentials (service_name, username, password, api_key, api_secret, additional_data)
+ VALUES (?, ?, ?, ?, ?, ?)`,
+ [credential.service_name, credential.username, credential.password, credential.api_key || null, credential.api_secret || null, credential.additional_data || null],
+ function(err) {
+ if (err) {
+ resolve({ success: false, message: `Error saving credential: ${err.message}` });
+ } else {
+ resolve({ success: true, message: 'Credential saved successfully', id: this.lastID });
+ }
+ }
+ );
+ }
+ }
+ );
+ });
+}
+
+export async function getCredentials(): Promise<{ success: boolean; data?: Credential[]; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ const connection = db.connect();
+ connection.all('SELECT * FROM credentials ORDER BY created_at DESC', (err, rows: any[]) => {
+ if (err) {
+ resolve({ success: false, message: `Error fetching credentials: ${err.message}` });
+ } else {
+ resolve({ success: true, data: rows });
+ }
+ });
+ });
+}
+
+export async function getCredentialByService(serviceName: string): Promise<{ success: boolean; data?: Credential; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ const connection = db.connect();
+ connection.all('SELECT * FROM credentials WHERE service_name = ? LIMIT 1', [serviceName], (err, rows: any[]) => {
+ if (err) {
+ resolve({ success: false, message: `Error fetching credential: ${err.message}` });
+ } else if (rows && rows.length > 0) {
+ resolve({ success: true, data: rows[0] });
+ } else {
+ resolve({ success: false, message: 'Credential not found' });
+ }
+ });
+ });
+}
+
+export async function deleteCredential(id: number): Promise<{ success: boolean; message: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ const connection = db.connect();
+ connection.run('DELETE FROM credentials WHERE id = ?', [id], (err) => {
+ if (err) {
+ resolve({ success: false, message: `Error deleting credential: ${err.message}` });
+ } else {
+ resolve({ success: true, message: 'Credential deleted successfully' });
+ }
+ });
+ });
+}
+
+// Settings Management Functions
+
+export async function saveSetting(key: string, value: string): Promise<{ success: boolean; message: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ const connection = db.connect();
+
+ connection.run(
+ `INSERT INTO user_settings (setting_key, setting_value)
+ VALUES (?, ?)
+ ON CONFLICT (setting_key) DO UPDATE SET setting_value = ?, updated_at = CURRENT_TIMESTAMP`,
+ [key, value, value],
+ (err) => {
+ if (err) {
+ resolve({ success: false, message: `Error saving setting: ${err.message}` });
+ } else {
+ resolve({ success: true, message: 'Setting saved successfully' });
+ }
+ }
+ );
+ });
+}
+
+export async function getSetting(key: string): Promise<{ success: boolean; data?: string; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ const connection = db.connect();
+ connection.all('SELECT setting_value FROM user_settings WHERE setting_key = ?', [key], (err, rows: any[]) => {
+ if (err) {
+ resolve({ success: false, message: `Error fetching setting: ${err.message}` });
+ } else if (rows && rows.length > 0) {
+ resolve({ success: true, data: rows[0].setting_value });
+ } else {
+ resolve({ success: false, message: 'Setting not found' });
+ }
+ });
+ });
+}
+
+export async function getAllSettings(): Promise<{ success: boolean; data?: Record<string, string>; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ const connection = db.connect();
+ connection.all('SELECT setting_key, setting_value FROM user_settings', (err, rows: any[]) => {
+ if (err) {
+ resolve({ success: false, message: `Error fetching settings: ${err.message}` });
+ } else {
+ const settings: Record<string, string> = {};
+ rows.forEach(row => {
+ settings[row.setting_key] = row.setting_value;
+ });
+ resolve({ success: true, data: settings });
+ }
+ });
+ });
+}
+
+export async function closeDatabase(): Promise<void> {
+ return new Promise((resolve) => {
+ if (db) {
+ db.close((err) => {
+ if (err) {
+ console.error('Error closing database:', err);
+ }
+ db = null;
+ resolve();
+ });
+ } else {
+ resolve();
+ }
+ });
+}
\ No newline at end of file
diff --git a/fincept-terminal-desktop/src/services/paymentApi.tsx b/fincept-terminal-desktop/src/services/paymentApi.tsx
index bd8bf9aae..0865269f5 100644
--- a/fincept-terminal-desktop/src/services/paymentApi.tsx
+++ b/fincept-terminal-desktop/src/services/paymentApi.tsx
@@ -3,7 +3,7 @@
// API Configuration
const PAYMENT_API_CONFIG = {
- BASE_URL: 'http://localhost:4500',
+ BASE_URL: 'https://finceptbackend.share.zrok.io',
CONNECTION_TIMEOUT: 10000,
REQUEST_TIMEOUT: 30000
};
diff --git a/fincept-terminal-desktop/src/services/storageService.ts b/fincept-terminal-desktop/src/services/storageService.ts
new file mode 100644
index 000000000..a7852ea59
--- /dev/null
+++ b/fincept-terminal-desktop/src/services/storageService.ts
@@ -0,0 +1,326 @@
+// Browser-compatible storage service using IndexedDB
+// This replaces DuckDB for credential storage in the browser environment
+
+interface Credential {
+ id?: number;
+ service_name: string;
+ username: string;
+ password: string;
+ api_key?: string;
+ api_secret?: string;
+ additional_data?: string;
+ created_at?: string;
+ updated_at?: string;
+}
+
+interface UserSettings {
+ setting_key: string;
+ setting_value: string;
+ updated_at?: string;
+}
+
+const DB_NAME = 'fincept_terminal_db';
+const DB_VERSION = 1;
+const CREDENTIALS_STORE = 'credentials';
+const SETTINGS_STORE = 'settings';
+
+let db: IDBDatabase | null = null;
+
+// Initialize IndexedDB
+export async function initializeDatabase(): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
+
+ request.onerror = () => {
+ console.error('IndexedDB initialization error:', request.error);
+ reject(request.error);
+ };
+
+ request.onsuccess = () => {
+ db = request.result;
+ console.log('IndexedDB initialized successfully');
+ resolve();
+ };
+
+ request.onupgradeneeded = (event) => {
+ const database = (event.target as IDBOpenDBRequest).result;
+
+ // Create credentials store
+ if (!database.objectStoreNames.contains(CREDENTIALS_STORE)) {
+ const credStore = database.createObjectStore(CREDENTIALS_STORE, {
+ keyPath: 'id',
+ autoIncrement: true
+ });
+ credStore.createIndex('service_username', ['service_name', 'username'], { unique: true });
+ credStore.createIndex('service_name', 'service_name', { unique: false });
+ }
+
+ // Create settings store
+ if (!database.objectStoreNames.contains(SETTINGS_STORE)) {
+ const settingsStore = database.createObjectStore(SETTINGS_STORE, {
+ keyPath: 'setting_key'
+ });
+ }
+
+ console.log('IndexedDB schema created');
+ };
+ });
+}
+
+// Credential Management Functions
+
+export async function saveCredential(credential: Credential): Promise<{ success: boolean; message: string; id?: number }> {
+ return new Promise(async (resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ try {
+ const transaction = db.transaction([CREDENTIALS_STORE], 'readwrite');
+ const store = transaction.objectStore(CREDENTIALS_STORE);
+ const index = store.index('service_username');
+
+ // Check if credential exists
+ const checkRequest = index.get([credential.service_name, credential.username]);
+
+ checkRequest.onsuccess = () => {
+ const existingCred = checkRequest.result;
+
+ const credentialToSave = {
+ ...credential,
+ updated_at: new Date().toISOString()
+ };
+
+ if (existingCred) {
+ // Update existing
+ credentialToSave.id = existingCred.id;
+ credentialToSave.created_at = existingCred.created_at;
+
+ const updateRequest = store.put(credentialToSave);
+
+ updateRequest.onsuccess = () => {
+ resolve({ success: true, message: 'Credential updated successfully', id: existingCred.id });
+ };
+
+ updateRequest.onerror = () => {
+ resolve({ success: false, message: `Error updating credential: ${updateRequest.error?.message}` });
+ };
+ } else {
+ // Insert new
+ credentialToSave.created_at = new Date().toISOString();
+
+ const addRequest = store.add(credentialToSave);
+
+ addRequest.onsuccess = () => {
+ resolve({ success: true, message: 'Credential saved successfully', id: addRequest.result as number });
+ };
+
+ addRequest.onerror = () => {
+ resolve({ success: false, message: `Error saving credential: ${addRequest.error?.message}` });
+ };
+ }
+ };
+
+ checkRequest.onerror = () => {
+ resolve({ success: false, message: `Error checking credential: ${checkRequest.error?.message}` });
+ };
+ } catch (error: any) {
+ resolve({ success: false, message: `Error: ${error.message}` });
+ }
+ });
+}
+
+export async function getCredentials(): Promise<{ success: boolean; data?: Credential[]; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ try {
+ const transaction = db.transaction([CREDENTIALS_STORE], 'readonly');
+ const store = transaction.objectStore(CREDENTIALS_STORE);
+ const request = store.getAll();
+
+ request.onsuccess = () => {
+ const credentials = request.result as Credential[];
+ // Sort by created_at desc
+ credentials.sort((a, b) => {
+ const dateA = new Date(a.created_at || 0).getTime();
+ const dateB = new Date(b.created_at || 0).getTime();
+ return dateB - dateA;
+ });
+ resolve({ success: true, data: credentials });
+ };
+
+ request.onerror = () => {
+ resolve({ success: false, message: `Error fetching credentials: ${request.error?.message}` });
+ };
+ } catch (error: any) {
+ resolve({ success: false, message: `Error: ${error.message}` });
+ }
+ });
+}
+
+export async function getCredentialByService(serviceName: string): Promise<{ success: boolean; data?: Credential; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ try {
+ const transaction = db.transaction([CREDENTIALS_STORE], 'readonly');
+ const store = transaction.objectStore(CREDENTIALS_STORE);
+ const index = store.index('service_name');
+ const request = index.get(serviceName);
+
+ request.onsuccess = () => {
+ const credential = request.result;
+ if (credential) {
+ resolve({ success: true, data: credential });
+ } else {
+ resolve({ success: false, message: 'Credential not found' });
+ }
+ };
+
+ request.onerror = () => {
+ resolve({ success: false, message: `Error fetching credential: ${request.error?.message}` });
+ };
+ } catch (error: any) {
+ resolve({ success: false, message: `Error: ${error.message}` });
+ }
+ });
+}
+
+export async function deleteCredential(id: number): Promise<{ success: boolean; message: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ try {
+ const transaction = db.transaction([CREDENTIALS_STORE], 'readwrite');
+ const store = transaction.objectStore(CREDENTIALS_STORE);
+ const request = store.delete(id);
+
+ request.onsuccess = () => {
+ resolve({ success: true, message: 'Credential deleted successfully' });
+ };
+
+ request.onerror = () => {
+ resolve({ success: false, message: `Error deleting credential: ${request.error?.message}` });
+ };
+ } catch (error: any) {
+ resolve({ success: false, message: `Error: ${error.message}` });
+ }
+ });
+}
+
+// Settings Management Functions
+
+export async function saveSetting(key: string, value: string): Promise<{ success: boolean; message: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ try {
+ const transaction = db.transaction([SETTINGS_STORE], 'readwrite');
+ const store = transaction.objectStore(SETTINGS_STORE);
+
+ const setting: UserSettings = {
+ setting_key: key,
+ setting_value: value,
+ updated_at: new Date().toISOString()
+ };
+
+ const request = store.put(setting);
+
+ request.onsuccess = () => {
+ resolve({ success: true, message: 'Setting saved successfully' });
+ };
+
+ request.onerror = () => {
+ resolve({ success: false, message: `Error saving setting: ${request.error?.message}` });
+ };
+ } catch (error: any) {
+ resolve({ success: false, message: `Error: ${error.message}` });
+ }
+ });
+}
+
+export async function getSetting(key: string): Promise<{ success: boolean; data?: string; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ try {
+ const transaction = db.transaction([SETTINGS_STORE], 'readonly');
+ const store = transaction.objectStore(SETTINGS_STORE);
+ const request = store.get(key);
+
+ request.onsuccess = () => {
+ const setting = request.result as UserSettings;
+ if (setting) {
+ resolve({ success: true, data: setting.setting_value });
+ } else {
+ resolve({ success: false, message: 'Setting not found' });
+ }
+ };
+
+ request.onerror = () => {
+ resolve({ success: false, message: `Error fetching setting: ${request.error?.message}` });
+ };
+ } catch (error: any) {
+ resolve({ success: false, message: `Error: ${error.message}` });
+ }
+ });
+}
+
+export async function getAllSettings(): Promise<{ success: boolean; data?: Record<string, string>; message?: string }> {
+ return new Promise((resolve) => {
+ if (!db) {
+ resolve({ success: false, message: 'Database not initialized' });
+ return;
+ }
+
+ try {
+ const transaction = db.transaction([SETTINGS_STORE], 'readonly');
+ const store = transaction.objectStore(SETTINGS_STORE);
+ const request = store.getAll();
+
+ request.onsuccess = () => {
+ const settings: Record<string, string> = {};
+ const allSettings = request.result as UserSettings[];
+
+ allSettings.forEach(setting => {
+ settings[setting.setting_key] = setting.setting_value;
+ });
+
+ resolve({ success: true, data: settings });
+ };
+
+ request.onerror = () => {
+ resolve({ success: false, message: `Error fetching settings: ${request.error?.message}` });
+ };
+ } catch (error: any) {
+ resolve({ success: false, message: `Error: ${error.message}` });
+ }
+ });
+}
+
+export async function closeDatabase(): Promise<void> {
+ return new Promise((resolve) => {
+ if (db) {
+ db.close();
+ db = null;
+ }
+ resolve();
+ });
+}
\ No newline at end of file