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.

watchlist update

tilakpatel222bccd8c98fcf
diff --git a/fincept-terminal-desktop/src-tauri/icons/128x128.png b/fincept-terminal-desktop/src-tauri/icons/128x128.png
index 120e7ae0d..6f5902d17 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/128x128.png and b/fincept-terminal-desktop/src-tauri/icons/128x128.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/[email protected] b/fincept-terminal-desktop/src-tauri/icons/[email protected]
index d56d0a46c..491ed7835 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/32x32.png b/fincept-terminal-desktop/src-tauri/icons/32x32.png
index 7b4d4d846..6605fe3c5 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/32x32.png and b/fincept-terminal-desktop/src-tauri/icons/32x32.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/64x64.png b/fincept-terminal-desktop/src-tauri/icons/64x64.png
index 609f205f2..87e328596 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/64x64.png and b/fincept-terminal-desktop/src-tauri/icons/64x64.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square107x107Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square107x107Logo.png
index a82c06246..97f0e6d62 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square107x107Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square107x107Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square142x142Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square142x142Logo.png
index 03bfccea6..8c1552775 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square142x142Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square142x142Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square150x150Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square150x150Logo.png
index 838f67510..8fa72f650 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square150x150Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square150x150Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square284x284Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square284x284Logo.png
index c93567dc5..a91c5cd0b 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square284x284Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square284x284Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square30x30Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square30x30Logo.png
index 59e0211e5..8c820a153 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square30x30Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square30x30Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square310x310Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square310x310Logo.png
index c9b51eda1..7ba32cc9e 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square310x310Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square310x310Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square44x44Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square44x44Logo.png
index b253c12c7..d2d67886a 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square44x44Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square44x44Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square71x71Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square71x71Logo.png
index d903f74af..0478f7d09 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square71x71Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square71x71Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/Square89x89Logo.png b/fincept-terminal-desktop/src-tauri/icons/Square89x89Logo.png
index ca31c3272..0c1b2dea7 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/Square89x89Logo.png and b/fincept-terminal-desktop/src-tauri/icons/Square89x89Logo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/StoreLogo.png b/fincept-terminal-desktop/src-tauri/icons/StoreLogo.png
index 6e2664472..a346bc454 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/StoreLogo.png and b/fincept-terminal-desktop/src-tauri/icons/StoreLogo.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png
index 2c8895811..0128704e2 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png
index 32b41f38d..0128704e2 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png
index 2c8895811..0128704e2 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png
index fa095b9ac..88468025a 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png
index 0cbbc5b7b..88468025a 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png
index fa095b9ac..88468025a 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png
index f339ec448..7f036404b 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png
index 4eac1f317..7f036404b 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png
index f339ec448..7f036404b 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png
index d76b8d990..cb2e60d28 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png
index 935699b2f..cb2e60d28 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png
index d76b8d990..cb2e60d28 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png
index 74f97c92a..042280362 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png
index f41f304cb..042280362 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png
index 74f97c92a..042280362 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png and b/fincept-terminal-desktop/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/icon.ico b/fincept-terminal-desktop/src-tauri/icons/icon.ico
index ccc5ae9b2..d1dac964f 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/icon.ico and b/fincept-terminal-desktop/src-tauri/icons/icon.ico differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index 3f6954b1d..0fe9256c5 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index f81da7cfd..20ef74dfe 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index f81da7cfd..20ef74dfe 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index 73e04d870..a8d82d263 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index 4a50d706f..6cd15c8c7 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index d16330cb6..25e58ba6e 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index d16330cb6..25e58ba6e 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index a8c651ee0..46750d5da 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index f81da7cfd..20ef74dfe 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index 224f43672..ae08335a5 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index 224f43672..ae08335a5 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index b11b14818..b89298667 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index cc9156522..5e370ace0 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index b11b14818..b89298667 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index 803b60695..ce099c0d5 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index 46daf10cf..3bcf80619 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index daded0238..6197ae842 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected]
index db3438636..57192dd58 100644
Binary files a/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] and b/fincept-terminal-desktop/src-tauri/icons/ios/[email protected] differ
diff --git a/fincept-terminal-desktop/src-tauri/src/commands/database.rs b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
index 3e6d8b118..aeb3c3e4d 100644
--- a/fincept-terminal-desktop/src-tauri/src/commands/database.rs
+++ b/fincept-terminal-desktop/src-tauri/src/commands/database.rs
@@ -300,8 +300,8 @@ pub async fn db_remove_watchlist_stock(watchlist_id: String, symbol: String) ->
}
#[tauri::command]
-pub async fn db_delete_watchlist(id: String) -> Result<String, String> {
- queries::delete_watchlist(&id).map_err(|e| e.to_string())?;
+pub async fn db_delete_watchlist(watchlist_id: String) -> Result<String, String> {
+ queries::delete_watchlist(&watchlist_id).map_err(|e| e.to_string())?;
Ok("Watchlist deleted successfully".to_string())
}
diff --git a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
index b634f9354..7d6fe73b6 100644
--- a/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/profile/ProfileTab.tsx
@@ -153,6 +153,22 @@ function profileReducer(state: ProfileState, action: ProfileAction): ProfileStat
}
}
+// ─── Profile completeness helper ─────────────────────────────────────────────
+function getProfileCompleteness(session: any): { missing: string[]; percent: number } {
+ if (session?.user_type !== 'registered') return { missing: [], percent: 100 };
+ const info = session?.user_info || {};
+ const checks: { key: string; label: string }[] = [
+ { key: 'username', label: 'Username' },
+ { key: 'email', label: 'Email' },
+ { key: 'phone', label: 'Phone number' },
+ { key: 'country', label: 'Country' },
+ { key: 'country_code', label: 'Country code' },
+ ];
+ const missing = checks.filter(c => !info[c.key]).map(c => c.label);
+ const percent = Math.round(((checks.length - missing.length) / checks.length) * 100);
+ return { missing, percent };
+}
+
// ─── Main Component ───────────────────────────────────────────────────────────
const ProfileTab: React.FC = () => {
const { session, logout, refreshUserData, updateApiKey, isLoggingOut } = useAuth();
@@ -447,51 +463,184 @@ const ProfileTab: React.FC = () => {
// ─── Overview Section ─────────────────────────────────────────────────────────
const OverviewSection: React.FC<{ session: any; onLogout: () => void; isLoggingOut?: boolean }> = ({ session, onLogout, isLoggingOut }) => {
+ const { refreshUserData } = useAuth();
const accountType = session?.user_info?.account_type || 'free';
- return (
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
- <Panel title="ACCOUNT INFORMATION" icon={<User size={14} />}>
- <DataRow label="USERNAME" value={session?.user_info?.username || 'N/A'} />
- <DataRow label="EMAIL" value={session?.user_info?.email || 'N/A'} />
- <DataRow label="USER TYPE" value={session?.user_type?.toUpperCase() || 'N/A'} />
- <DataRow label="ACCOUNT TYPE" value={accountType.toUpperCase()} valueColor={F.ORANGE} />
- <DataRow
- label="EMAIL VERIFIED"
- value={session?.user_info?.is_verified ? 'YES' : 'NO'}
- valueColor={session?.user_info?.is_verified ? F.GREEN : F.RED}
- />
- <DataRow
- label="2FA ENABLED"
- value={session?.user_info?.mfa_enabled ? 'YES' : 'NO'}
- valueColor={session?.user_info?.mfa_enabled ? F.GREEN : F.RED}
- />
- </Panel>
+ const { missing, percent } = getProfileCompleteness(session);
+
+ // Edit profile state
+ const [editing, setEditing] = useState(false);
+ const [editUsername, setEditUsername] = useState(session?.user_info?.username || '');
+ const [editPhone, setEditPhone] = useState(session?.user_info?.phone || '');
+ const [editCountry, setEditCountry] = useState(session?.user_info?.country || '');
+ const [editCountryCode, setEditCountryCode] = useState(session?.user_info?.country_code || '');
+ const [saveLoading, setSaveLoading] = useState(false);
+ const [saveStatus, setSaveStatus] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
+
+ const handleSaveProfile = async () => {
+ if (!session?.api_key) return;
+ setSaveLoading(true);
+ setSaveStatus(null);
+ try {
+ const result = await withTimeout(
+ UserApiService.updateUserProfile(session.api_key, {
+ username: editUsername.trim() || undefined,
+ phone: editPhone.trim() || null,
+ country: editCountry.trim() || null,
+ country_code: editCountryCode.trim() || null,
+ }),
+ API_TIMEOUT_MS,
+ 'Profile update timeout'
+ );
+ setSaveLoading(false);
+ if (result.success) {
+ setSaveStatus({ type: 'success', text: 'Profile updated successfully!' });
+ await refreshUserData();
+ setTimeout(() => { setSaveStatus(null); setEditing(false); }, 2000);
+ } else {
+ setSaveStatus({ type: 'error', text: result.error || 'Failed to update profile' });
+ }
+ } catch (err) {
+ setSaveLoading(false);
+ setSaveStatus({ type: 'error', text: err instanceof Error ? err.message : 'Network error' });
+ }
+ };
- <Panel title="CREDITS & BALANCE" icon={<Zap size={14} />}>
- <div style={{ padding: '20px 0', textAlign: 'center', borderBottom: `1px solid ${F.BORDER}` }}>
- <div style={{ fontSize: '36px', color: F.CYAN, fontWeight: 700, marginBottom: '8px', fontFamily: FONT }}>
- {(session?.user_info?.credit_balance || 0).toLocaleString()}
+ return (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
+ {/* Profile Completeness Banner */}
+ {session?.user_type === 'registered' && missing.length > 0 && (
+ <div style={{
+ padding: '12px 16px',
+ backgroundColor: `${F.YELLOW}15`,
+ border: `1px solid ${F.YELLOW}`,
+ borderRadius: '2px',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: '12px',
+ }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '10px', flex: 1 }}>
+ <AlertCircle size={14} color={F.YELLOW} />
+ <div>
+ <div style={{ fontSize: '9px', fontWeight: 700, color: F.YELLOW, letterSpacing: '0.5px', marginBottom: '2px' }}>
+ PROFILE INCOMPLETE ({percent}%) — Required for payment processing
+ </div>
+ <div style={{ fontSize: '9px', color: F.GRAY }}>
+ Missing: {missing.join(', ')}
+ </div>
+ </div>
+ </div>
+ {/* Completeness bar */}
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <div style={{ width: '80px', height: '4px', backgroundColor: F.BORDER, borderRadius: '2px' }}>
+ <div style={{ width: `${percent}%`, height: '100%', backgroundColor: percent === 100 ? F.GREEN : F.YELLOW, borderRadius: '2px', transition: 'width 0.3s' }} />
+ </div>
+ <SecondaryBtn label="COMPLETE NOW" onClick={() => setEditing(true)} />
</div>
- <div style={{ fontSize: '9px', color: F.GRAY, letterSpacing: '0.5px', fontWeight: 700 }}>AVAILABLE CREDITS</div>
- </div>
- <div style={{ padding: '12px 0' }}>
- <DataRow label="PLAN" value={accountType.toUpperCase()} valueColor={F.ORANGE} />
- {session?.user_type === 'guest' && (
- <>
- <DataRow label="CREDITS" value={session?.credit_balance?.toString() || '0'} />
- <DataRow label="REQUESTS TODAY" value={session?.requests_today?.toString() || '0'} />
- </>
- )}
</div>
- </Panel>
+ )}
- <div style={{ gridColumn: '1 / -1' }}>
- <Panel title="QUICK ACTIONS" icon={<Activity size={14} />}>
- <div style={{ display: 'flex', gap: '12px', padding: '8px 0' }}>
- <ActionBtn label={isLoggingOut ? "LOGGING OUT..." : "LOGOUT"} onClick={onLogout} danger disabled={isLoggingOut} />
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
+ <Panel title="ACCOUNT INFORMATION" icon={<User size={14} />}>
+ <DataRow label="USERNAME" value={session?.user_info?.username || 'N/A'} />
+ <DataRow label="EMAIL" value={session?.user_info?.email || 'N/A'} />
+ <DataRow label="USER TYPE" value={session?.user_type?.toUpperCase() || 'N/A'} />
+ <DataRow label="ACCOUNT TYPE" value={accountType.toUpperCase()} valueColor={F.ORANGE} />
+ <DataRow label="PHONE" value={session?.user_info?.phone || '—'} valueColor={session?.user_info?.phone ? F.WHITE : F.MUTED} />
+ <DataRow label="COUNTRY" value={session?.user_info?.country || '—'} valueColor={session?.user_info?.country ? F.WHITE : F.MUTED} />
+ <DataRow label="COUNTRY CODE" value={session?.user_info?.country_code || '—'} valueColor={session?.user_info?.country_code ? F.WHITE : F.MUTED} />
+ <DataRow
+ label="EMAIL VERIFIED"
+ value={session?.user_info?.is_verified ? 'YES' : 'NO'}
+ valueColor={session?.user_info?.is_verified ? F.GREEN : F.RED}
+ />
+ <DataRow
+ label="2FA ENABLED"
+ value={session?.user_info?.mfa_enabled ? 'YES' : 'NO'}
+ valueColor={session?.user_info?.mfa_enabled ? F.GREEN : F.RED}
+ />
+ <div style={{ paddingTop: '10px' }}>
+ <SecondaryBtn icon={<User size={10} />} label="EDIT PROFILE" onClick={() => setEditing(true)} />
</div>
</Panel>
+
+ <Panel title="CREDITS & BALANCE" icon={<Zap size={14} />}>
+ <div style={{ padding: '20px 0', textAlign: 'center', borderBottom: `1px solid ${F.BORDER}` }}>
+ <div style={{ fontSize: '36px', color: F.CYAN, fontWeight: 700, marginBottom: '8px', fontFamily: FONT }}>
+ {(session?.user_info?.credit_balance || 0).toLocaleString()}
+ </div>
+ <div style={{ fontSize: '9px', color: F.GRAY, letterSpacing: '0.5px', fontWeight: 700 }}>AVAILABLE CREDITS</div>
+ </div>
+ <div style={{ padding: '12px 0' }}>
+ <DataRow label="PLAN" value={accountType.toUpperCase()} valueColor={F.ORANGE} />
+ {session?.user_type === 'guest' && (
+ <>
+ <DataRow label="CREDITS" value={session?.credit_balance?.toString() || '0'} />
+ <DataRow label="REQUESTS TODAY" value={session?.requests_today?.toString() || '0'} />
+ </>
+ )}
+ </div>
+ </Panel>
+
+ <div style={{ gridColumn: '1 / -1' }}>
+ <Panel title="QUICK ACTIONS" icon={<Activity size={14} />}>
+ <div style={{ display: 'flex', gap: '12px', padding: '8px 0' }}>
+ <SecondaryBtn icon={<User size={10} />} label="EDIT PROFILE" onClick={() => setEditing(true)} />
+ <ActionBtn label={isLoggingOut ? "LOGGING OUT..." : "LOGOUT"} onClick={onLogout} danger disabled={isLoggingOut} />
+ </div>
+ </Panel>
+ </div>
</div>
+
+ {/* Edit Profile Modal */}
+ {editing && (
+ <div style={{
+ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
+ backgroundColor: 'rgba(0,0,0,0.85)', display: 'flex',
+ alignItems: 'center', justifyContent: 'center', zIndex: 1000,
+ }}>
+ <div style={{
+ backgroundColor: F.PANEL_BG, border: `1px solid ${F.ORANGE}`,
+ borderRadius: '2px', padding: '24px', width: '480px', maxWidth: '95vw',
+ }}>
+ <div style={{ fontSize: '11px', fontWeight: 700, color: F.ORANGE, marginBottom: '20px', display: 'flex', alignItems: 'center', gap: '8px', fontFamily: FONT, letterSpacing: '0.5px' }}>
+ <User size={14} />
+ EDIT PROFILE
+ </div>
+
+ {saveStatus && <StatusBadge type={saveStatus.type} text={saveStatus.text} />}
+
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
+ <div style={{ gridColumn: '1 / -1' }}>
+ <InputField label="USERNAME" value={editUsername} onChange={setEditUsername} placeholder="Your username" />
+ </div>
+ <div style={{ gridColumn: '1 / -1' }}>
+ <InputField
+ label="PHONE NUMBER (with country dial code, e.g. +91 9876543210)"
+ value={editPhone}
+ onChange={setEditPhone}
+ placeholder="+1 5551234567"
+ type="tel"
+ />
+ <div style={{ fontSize: '9px', color: F.MUTED, marginTop: '-8px', marginBottom: '12px' }}>
+ Required for payment processing (Cashfree). Include country dial code.
+ </div>
+ </div>
+ <InputField label="COUNTRY (e.g. India)" value={editCountry} onChange={setEditCountry} placeholder="India" />
+ <InputField label="COUNTRY CODE (e.g. IN)" value={editCountryCode} onChange={setEditCountryCode} placeholder="IN" />
+ </div>
+
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '8px' }}>
+ <SecondaryBtn label="CANCEL" onClick={() => { setEditing(false); setSaveStatus(null); }} />
+ <PrimaryBtn
+ label={saveLoading ? 'SAVING...' : 'SAVE CHANGES'}
+ onClick={handleSaveProfile}
+ disabled={saveLoading}
+ />
+ </div>
+ </div>
+ </div>
+ )}
</div>
);
};
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx
index 590a3bcca..b60e123f2 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/AddStockModal.tsx
@@ -28,7 +28,6 @@ const AddStockModal: React.FC<AddStockModalProps> = ({ onClose, onAdd, existingS
await onAdd(trimmedSymbol, notes.trim());
onClose();
} catch (error) {
- console.error('Error adding stock:', error);
showError(error instanceof Error ? error.message : 'Failed to add stock');
} finally {
setLoading(false);
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/ImportWatchlistModal.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/ImportWatchlistModal.tsx
new file mode 100644
index 000000000..ddb6000ec
--- /dev/null
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/ImportWatchlistModal.tsx
@@ -0,0 +1,619 @@
+import React, { useState, useCallback } from 'react';
+import { Upload, Download, CheckCircle, AlertCircle, X } from 'lucide-react';
+import { FINCEPT, FONT_FAMILY } from './utils';
+
+// ─── Types ────────────────────────────────────────────────────────────────────
+
+export interface WatchlistImportEntry {
+ symbol: string;
+ notes?: string;
+}
+
+export interface WatchlistImportJSON {
+ format_version: string;
+ watchlist_name: string;
+ description?: string;
+ color?: string;
+ exported_at?: string;
+ stocks: WatchlistImportEntry[];
+}
+
+export interface WatchlistImportResult {
+ watchlistId: string;
+ watchlistName: string;
+ added: number;
+ skipped: string[]; // already-existing symbols
+ errors: string[];
+}
+
+export type ImportWatchlistMode = 'new' | 'append';
+
+type Step = 'select-file' | 'configure' | 'importing' | 'done';
+
+// ─── JSON parser ─────────────────────────────────────────────────────────────
+
+export function parseWatchlistJSON(content: string): WatchlistImportJSON {
+ let raw: any;
+ try {
+ raw = JSON.parse(content);
+ } catch {
+ throw new Error('Invalid JSON — could not parse file.');
+ }
+
+ // Accept both formats:
+ // 1. { stocks: [{symbol, notes?}, ...], ... } — Fincept export
+ // 2. ["AAPL","MSFT",...] — simple symbol array
+ // 3. [{symbol:"AAPL",...},...] — array of objects
+
+ if (Array.isArray(raw)) {
+ const stocks: WatchlistImportEntry[] = raw.map((item: any, i: number) => {
+ if (typeof item === 'string') return { symbol: item.trim().toUpperCase() };
+ if (item && typeof item.symbol === 'string') return { symbol: item.symbol.trim().toUpperCase(), notes: item.notes };
+ if (item && typeof item.ticker === 'string') return { symbol: item.ticker.trim().toUpperCase(), notes: item.notes };
+ throw new Error(`Item at index ${i} is not a valid symbol or stock object.`);
+ });
+ return {
+ format_version: '1.0',
+ watchlist_name: 'Imported Watchlist',
+ stocks,
+ };
+ }
+
+ if (raw && typeof raw === 'object') {
+ // Must have a stocks array
+ const stocksRaw = raw.stocks ?? raw.symbols ?? raw.tickers;
+ if (!Array.isArray(stocksRaw)) {
+ throw new Error('JSON must have a "stocks", "symbols", or "tickers" array, or be a plain array.');
+ }
+ if (stocksRaw.length === 0) throw new Error('No stocks found in file.');
+
+ const stocks: WatchlistImportEntry[] = stocksRaw.map((item: any, i: number) => {
+ if (typeof item === 'string') return { symbol: item.trim().toUpperCase() };
+ if (item && typeof item.symbol === 'string') return { symbol: item.symbol.trim().toUpperCase(), notes: item.notes };
+ if (item && typeof item.ticker === 'string') return { symbol: item.ticker.trim().toUpperCase(), notes: item.notes };
+ throw new Error(`Stock at index ${i} is missing a "symbol" or "ticker" field.`);
+ });
+
+ return {
+ format_version: raw.format_version ?? '1.0',
+ watchlist_name: raw.watchlist_name ?? raw.name ?? 'Imported Watchlist',
+ description: raw.description,
+ color: raw.color,
+ exported_at: raw.exported_at ?? raw.export_date,
+ stocks,
+ };
+ }
+
+ throw new Error('Unrecognized JSON format.');
+}
+
+// ─── Props ────────────────────────────────────────────────────────────────────
+
+interface ImportWatchlistModalProps {
+ show: boolean;
+ existingWatchlists: Array<{ id: string; name: string }>;
+ selectedWatchlistId: string | null;
+ onClose: () => void;
+ onImport: (
+ data: WatchlistImportJSON,
+ mode: ImportWatchlistMode,
+ targetWatchlistId?: string,
+ nameOverride?: string,
+ colorOverride?: string,
+ ) => Promise<WatchlistImportResult>;
+ onImportComplete: (result: WatchlistImportResult) => void;
+}
+
+// ─── Style constants (match FINCEPT palette) ──────────────────────────────────
+
+const { CYAN, ORANGE, GREEN, RED, BORDER, DARK_BG: BG, PANEL_BG: PANEL, GRAY, WHITE, HOVER } = FINCEPT;
+const FF = FONT_FAMILY;
+
+const labelStyle: React.CSSProperties = {
+ color: GRAY, fontSize: '9px', fontWeight: 700,
+ letterSpacing: '0.5px', textTransform: 'uppercase',
+ display: 'block', marginBottom: '4px',
+};
+
+const inputStyle: React.CSSProperties = {
+ width: '100%', padding: '7px 10px', backgroundColor: BG,
+ color: WHITE, border: `1px solid ${BORDER}`, fontSize: '11px',
+ fontFamily: FF, outline: 'none', boxSizing: 'border-box',
+};
+
+// ─── Component ────────────────────────────────────────────────────────────────
+
+const ImportWatchlistModal: React.FC<ImportWatchlistModalProps> = ({
+ show, existingWatchlists, selectedWatchlistId, onClose, onImport, onImportComplete,
+}) => {
+ const [step, setStep] = useState<Step>('select-file');
+ const [fileName, setFileName] = useState('');
+ const [parsedData, setParsedData] = useState<WatchlistImportJSON | null>(null);
+ const [parseError, setParseError] = useState<string | null>(null);
+ const [mode, setMode] = useState<ImportWatchlistMode>('new');
+ const [targetId, setTargetId] = useState(selectedWatchlistId ?? existingWatchlists[0]?.id ?? '');
+ const [nameOverride, setNameOverride] = useState('');
+ const [colorOverride, setColorOverride] = useState('#FF8800');
+ const [isDragging, setIsDragging] = useState(false);
+ const [importing, setImporting] = useState(false);
+ const [result, setResult] = useState<WatchlistImportResult | null>(null);
+
+ const reset = useCallback(() => {
+ setStep('select-file');
+ setFileName('');
+ setParsedData(null);
+ setParseError(null);
+ setMode('new');
+ setTargetId(selectedWatchlistId ?? existingWatchlists[0]?.id ?? '');
+ setNameOverride('');
+ setColorOverride('#FF8800');
+ setIsDragging(false);
+ setImporting(false);
+ setResult(null);
+ }, [selectedWatchlistId, existingWatchlists]);
+
+ const handleClose = useCallback(() => { reset(); onClose(); }, [reset, onClose]);
+
+ const processFile = useCallback((content: string, name: string) => {
+ setParseError(null);
+ try {
+ const data = parseWatchlistJSON(content);
+ setParsedData(data);
+ setFileName(name);
+ setNameOverride(data.watchlist_name);
+ if (data.color) setColorOverride(data.color);
+ if (existingWatchlists.length > 0) {
+ setTargetId(selectedWatchlistId ?? existingWatchlists[0].id);
+ }
+ setStep('configure');
+ } catch (err: any) {
+ setParseError(err?.message || 'Failed to parse file');
+ }
+ }, [selectedWatchlistId, existingWatchlists]);
+
+ const handleFile = useCallback((file: File) => {
+ if (!file.name.toLowerCase().endsWith('.json')) {
+ setParseError('Only JSON files are supported for watchlist import.');
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = (e) => processFile(e.target?.result as string, file.name);
+ reader.readAsText(file);
+ }, [processFile]);
+
+ const handleDrop = useCallback((e: React.DragEvent) => {
+ e.preventDefault();
+ setIsDragging(false);
+ const file = e.dataTransfer.files?.[0];
+ if (file) handleFile(file);
+ }, [handleFile]);
+
+ const handleExecuteImport = useCallback(async () => {
+ if (!parsedData) return;
+ setStep('importing');
+ setImporting(true);
+ try {
+ const importResult = await onImport(
+ parsedData,
+ mode,
+ mode === 'append' ? targetId : undefined,
+ mode === 'new' ? (nameOverride.trim() || parsedData.watchlist_name) : undefined,
+ mode === 'new' ? colorOverride : undefined,
+ );
+ setResult(importResult);
+ setStep('done');
+ } catch (err: any) {
+ setResult({
+ watchlistId: '',
+ watchlistName: '',
+ added: 0,
+ skipped: [],
+ errors: [err?.message || 'Import failed'],
+ });
+ setStep('done');
+ } finally {
+ setImporting(false);
+ }
+ }, [parsedData, mode, targetId, nameOverride, colorOverride, onImport]);
+
+ const downloadTemplate = useCallback(() => {
+ const template: WatchlistImportJSON = {
+ format_version: '1.0',
+ watchlist_name: 'My Tech Watchlist',
+ description: 'US tech sector watchlist',
+ color: '#00E5FF',
+ exported_at: new Date().toISOString(),
+ stocks: [
+ { symbol: 'AAPL', notes: 'Apple Inc' },
+ { symbol: 'MSFT', notes: 'Microsoft' },
+ { symbol: 'GOOGL', notes: 'Alphabet' },
+ { symbol: 'NVDA', notes: 'Nvidia' },
+ { symbol: 'TSLA' },
+ ],
+ };
+ const blob = new Blob([JSON.stringify(template, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = 'watchlist_template.json';
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ }, []);
+
+ if (!show) return null;
+
+ const steps: Step[] = ['select-file', 'configure', 'importing', 'done'];
+
+ return (
+ <div style={{
+ position: 'fixed', inset: 0, backgroundColor: 'rgba(0,0,0,0.88)',
+ display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999,
+ }}>
+ <div style={{
+ backgroundColor: PANEL, border: `2px solid ${CYAN}`,
+ padding: '24px', width: '500px', maxWidth: '95vw',
+ boxShadow: `0 8px 32px ${CYAN}20`, fontFamily: FF,
+ maxHeight: '90vh', overflowY: 'auto',
+ }}>
+
+ {/* Header */}
+ <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '20px' }}>
+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
+ <Upload size={14} color={CYAN} />
+ <span style={{ fontSize: '13px', fontWeight: 800, color: CYAN, letterSpacing: '1px' }}>
+ IMPORT WATCHLIST
+ </span>
+ </div>
+ <button onClick={handleClose} style={{ background: 'none', border: 'none', color: GRAY, cursor: 'pointer', display: 'flex' }}>
+ <X size={14} />
+ </button>
+ </div>
+
+ {/* Step indicator */}
+ <div style={{ display: 'flex', gap: '6px', marginBottom: '20px' }}>
+ {steps.map((s, i) => (
+ <div key={s} style={{
+ flex: 1, height: '2px',
+ backgroundColor: step === s ? CYAN : (steps.indexOf(step) > i ? `${CYAN}60` : BORDER),
+ }} />
+ ))}
+ </div>
+
+ {/* ─── STEP: select-file ─── */}
+ {step === 'select-file' && (
+ <div>
+ <div
+ onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
+ onDragLeave={() => setIsDragging(false)}
+ onDrop={handleDrop}
+ onClick={() => document.getElementById('watchlist-file-input')?.click()}
+ style={{
+ border: `2px dashed ${isDragging ? CYAN : BORDER}`,
+ backgroundColor: isDragging ? `${CYAN}08` : BG,
+ padding: '32px', textAlign: 'center', cursor: 'pointer',
+ transition: 'all 0.2s',
+ }}
+ >
+ <Upload size={28} color={isDragging ? CYAN : GRAY} style={{ marginBottom: '12px' }} />
+ <div style={{ color: WHITE, fontSize: '12px', fontWeight: 600, marginBottom: '4px' }}>
+ Drop JSON file here or click to browse
+ </div>
+ <div style={{ color: GRAY, fontSize: '10px' }}>
+ Accepts Fincept watchlist JSON or a simple symbol array
+ </div>
+ <input
+ id="watchlist-file-input"
+ type="file"
+ accept=".json"
+ style={{ display: 'none' }}
+ onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFile(f); e.target.value = ''; }}
+ />
+ </div>
+
+ {parseError && (
+ <div style={{
+ marginTop: '12px', padding: '10px 12px',
+ backgroundColor: `${RED}12`, border: `1px solid ${RED}40`,
+ display: 'flex', alignItems: 'center', gap: '8px',
+ }}>
+ <AlertCircle size={12} color={RED} />
+ <span style={{ color: RED, fontSize: '10px' }}>{parseError}</span>
+ </div>
+ )}
+
+ {/* Supported formats */}
+ <div style={{ marginTop: '16px', color: GRAY, fontSize: '9px', lineHeight: '1.8' }}>
+ <div style={{ fontWeight: 700, color: WHITE, marginBottom: '4px' }}>SUPPORTED FORMATS</div>
+ <div>• <span style={{ color: CYAN }}>Fincept export</span> — {"{ watchlist_name, stocks: [{symbol, notes}] }"}</div>
+ <div>• <span style={{ color: CYAN }}>Symbol array</span> — {"[\"AAPL\", \"MSFT\", \"GOOGL\"]"}</div>
+ <div>• <span style={{ color: CYAN }}>Object array</span> — {"[{symbol: \"AAPL\", notes: \"...\"}, ...]"}</div>
+ </div>
+
+ {/* Template download */}
+ <div style={{
+ marginTop: '14px', padding: '10px 12px',
+ backgroundColor: `${CYAN}08`, border: `1px solid ${BORDER}`,
+ }}>
+ <div style={{ fontSize: '9px', color: GRAY, fontWeight: 700, marginBottom: '6px' }}>
+ DOWNLOAD TEMPLATE
+ </div>
+ <div style={{ fontSize: '9px', color: GRAY, marginBottom: '8px' }}>
+ Download a sample JSON to see the exact format expected.
+ </div>
+ <button
+ onClick={(e) => { e.stopPropagation(); downloadTemplate(); }}
+ style={{
+ padding: '5px 12px', backgroundColor: 'transparent',
+ border: `1px solid ${CYAN}60`, color: CYAN,
+ fontSize: '9px', fontWeight: 700, cursor: 'pointer',
+ display: 'inline-flex', alignItems: 'center', gap: '4px',
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = `${CYAN}15`; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}
+ >
+ <Download size={9} /> TEMPLATE.JSON
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* ─── STEP: configure ─── */}
+ {step === 'configure' && parsedData && (
+ <div>
+ {/* File preview */}
+ <div style={{
+ padding: '10px 12px', backgroundColor: BG,
+ border: `1px solid ${BORDER}`, marginBottom: '16px',
+ }}>
+ <div style={{ fontSize: '9px', color: GRAY, fontWeight: 700, marginBottom: '6px' }}>FILE DETECTED</div>
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '6px' }}>
+ {[
+ { l: 'FILE', v: fileName },
+ { l: 'WATCHLIST', v: parsedData.watchlist_name },
+ { l: 'SYMBOLS', v: String(parsedData.stocks.length) },
+ { l: 'EXPORTED', v: parsedData.exported_at ? new Date(parsedData.exported_at).toLocaleDateString() : '—' },
+ ].map(({ l, v }) => (
+ <div key={l}>
+ <span style={{ fontSize: '8px', color: GRAY }}>{l}: </span>
+ <span style={{ fontSize: '9px', color: WHITE, fontWeight: 600 }}>{v}</span>
+ </div>
+ ))}
+ </div>
+
+ {/* Symbol preview pills */}
+ <div style={{ marginTop: '8px', display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
+ {parsedData.stocks.slice(0, 12).map(s => (
+ <span key={s.symbol} style={{
+ padding: '2px 6px', fontSize: '8px', fontWeight: 700,
+ backgroundColor: `${CYAN}15`, color: CYAN,
+ border: `1px solid ${CYAN}30`,
+ }}>
+ {s.symbol}
+ </span>
+ ))}
+ {parsedData.stocks.length > 12 && (
+ <span style={{ fontSize: '8px', color: GRAY, padding: '2px 4px' }}>
+ +{parsedData.stocks.length - 12} more
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Import mode */}
+ <div style={{ marginBottom: '14px' }}>
+ <label style={labelStyle}>IMPORT MODE</label>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
+ {([
+ { value: 'new' as ImportWatchlistMode, label: 'Create new watchlist', desc: 'Import as a brand new watchlist' },
+ { value: 'append' as ImportWatchlistMode, label: 'Append to existing watchlist', desc: 'Add symbols to an existing watchlist (duplicates skipped)' },
+ ]).map(opt => (
+ <label key={opt.value} style={{
+ display: 'flex', alignItems: 'flex-start', gap: '8px',
+ padding: '8px 10px', cursor: 'pointer',
+ backgroundColor: mode === opt.value ? `${CYAN}10` : 'transparent',
+ border: `1px solid ${mode === opt.value ? CYAN : BORDER}`,
+ }}>
+ <input
+ type="radio"
+ name="wl-import-mode"
+ value={opt.value}
+ checked={mode === opt.value}
+ onChange={() => setMode(opt.value)}
+ style={{ marginTop: '2px', accentColor: CYAN }}
+ />
+ <div>
+ <div style={{ fontSize: '10px', fontWeight: 700, color: mode === opt.value ? CYAN : WHITE }}>
+ {opt.label}
+ </div>
+ <div style={{ fontSize: '9px', color: GRAY }}>{opt.desc}</div>
+ </div>
+ </label>
+ ))}
+ </div>
+ </div>
+
+ {/* New watchlist fields */}
+ {mode === 'new' && (
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '10px', marginBottom: '14px', alignItems: 'end' }}>
+ <div>
+ <label style={labelStyle}>WATCHLIST NAME</label>
+ <input
+ type="text"
+ value={nameOverride}
+ onChange={(e) => setNameOverride(e.target.value)}
+ style={inputStyle}
+ onFocus={(e) => { e.currentTarget.style.borderColor = CYAN; }}
+ onBlur={(e) => { e.currentTarget.style.borderColor = BORDER; }}
+ />
+ </div>
+ <div>
+ <label style={labelStyle}>COLOR</label>
+ <input
+ type="color"
+ value={colorOverride}
+ onChange={(e) => setColorOverride(e.target.value)}
+ style={{
+ width: '48px', height: '34px', padding: '2px',
+ backgroundColor: BG, border: `1px solid ${BORDER}`,
+ cursor: 'pointer', borderRadius: 0,
+ }}
+ />
+ </div>
+ </div>
+ )}
+
+ {/* Append target */}
+ {mode === 'append' && (
+ <div style={{ marginBottom: '14px' }}>
+ <label style={labelStyle}>TARGET WATCHLIST</label>
+ {existingWatchlists.length === 0 ? (
+ <div style={{ color: GRAY, fontSize: '10px', padding: '8px', backgroundColor: BG, border: `1px solid ${BORDER}` }}>
+ No watchlists available. Switch to "Create new" mode.
+ </div>
+ ) : (
+ <select
+ value={targetId}
+ onChange={(e) => setTargetId(e.target.value)}
+ style={{ ...inputStyle, cursor: 'pointer' }}
+ >
+ {existingWatchlists.map(w => (
+ <option key={w.id} value={w.id}>{w.name}</option>
+ ))}
+ </select>
+ )}
+ </div>
+ )}
+
+ {/* Actions */}
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end', marginTop: '4px' }}>
+ <button onClick={handleClose} style={{
+ padding: '6px 12px', backgroundColor: 'transparent',
+ border: `1px solid ${BORDER}`, color: GRAY,
+ fontSize: '10px', fontWeight: 700, cursor: 'pointer',
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = HOVER; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}
+ >
+ CANCEL
+ </button>
+ <button
+ onClick={handleExecuteImport}
+ disabled={mode === 'append' && !targetId}
+ style={{
+ padding: '6px 16px', backgroundColor: CYAN, color: '#000',
+ border: 'none', fontSize: '10px', fontWeight: 800, cursor: 'pointer',
+ opacity: (mode === 'append' && !targetId) ? 0.5 : 1,
+ }}
+ >
+ IMPORT {parsedData.stocks.length} SYMBOL{parsedData.stocks.length !== 1 ? 'S' : ''}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {/* ─── STEP: importing ─── */}
+ {step === 'importing' && (
+ <div style={{ textAlign: 'center', padding: '32px 0' }}>
+ <style>{`@keyframes wl-spin { to { transform: rotate(360deg); } }`}</style>
+ <div style={{
+ width: '40px', height: '40px', border: `3px solid ${BORDER}`,
+ borderTopColor: CYAN, borderRadius: '50%', margin: '0 auto 16px',
+ animation: 'wl-spin 0.8s linear infinite',
+ }} />
+ <div style={{ color: WHITE, fontSize: '12px', fontWeight: 700, marginBottom: '4px' }}>
+ IMPORTING SYMBOLS...
+ </div>
+ <div style={{ color: CYAN, fontSize: '10px' }}>
+ Adding stocks to watchlist
+ </div>
+ </div>
+ )}
+
+ {/* ─── STEP: done ─── */}
+ {step === 'done' && result && (
+ <div>
+ {result.watchlistId ? (
+ <div style={{ textAlign: 'center', marginBottom: '20px' }}>
+ <CheckCircle size={40} color={GREEN} style={{ marginBottom: '12px' }} />
+ <div style={{ color: GREEN, fontSize: '13px', fontWeight: 800, marginBottom: '4px' }}>
+ IMPORT COMPLETE
+ </div>
+ <div style={{ color: WHITE, fontSize: '11px' }}>
+ <span style={{ color: CYAN, fontWeight: 700 }}>{result.added}</span> symbols added
+ {result.skipped.length > 0 && (
+ <span style={{ color: ORANGE }}> · {result.skipped.length} skipped (already exist)</span>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div style={{ textAlign: 'center', marginBottom: '20px' }}>
+ <AlertCircle size={40} color={RED} style={{ marginBottom: '12px' }} />
+ <div style={{ color: RED, fontSize: '13px', fontWeight: 800 }}>IMPORT FAILED</div>
+ </div>
+ )}
+
+ {/* Skipped symbols */}
+ {result.skipped.length > 0 && (
+ <div style={{ marginBottom: '12px' }}>
+ <div style={{ fontSize: '9px', color: ORANGE, fontWeight: 700, marginBottom: '4px' }}>
+ SKIPPED (ALREADY IN WATCHLIST)
+ </div>
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
+ {result.skipped.map(s => (
+ <span key={s} style={{
+ padding: '2px 6px', fontSize: '8px', fontWeight: 700,
+ backgroundColor: `${ORANGE}15`, color: ORANGE,
+ border: `1px solid ${ORANGE}30`,
+ }}>{s}</span>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Errors */}
+ {result.errors.length > 0 && (
+ <div style={{
+ marginBottom: '12px', padding: '8px',
+ backgroundColor: `${RED}10`, border: `1px solid ${RED}30`,
+ maxHeight: '120px', overflowY: 'auto',
+ }}>
+ <div style={{ fontSize: '9px', color: RED, fontWeight: 700, marginBottom: '4px' }}>ERRORS</div>
+ {result.errors.map((e, i) => (
+ <div key={i} style={{ fontSize: '9px', color: RED, lineHeight: '1.6', fontFamily: 'monospace' }}>{e}</div>
+ ))}
+ </div>
+ )}
+
+ <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
+ <button onClick={handleClose} style={{
+ padding: '6px 12px', backgroundColor: 'transparent',
+ border: `1px solid ${BORDER}`, color: GRAY,
+ fontSize: '10px', fontWeight: 700, cursor: 'pointer',
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.backgroundColor = HOVER; }}
+ onMouseLeave={(e) => { e.currentTarget.style.backgroundColor = 'transparent'; }}
+ >
+ CLOSE
+ </button>
+ {result.watchlistId && (
+ <button
+ onClick={() => { onImportComplete(result); reset(); }}
+ style={{
+ padding: '6px 16px', backgroundColor: CYAN, color: '#000',
+ border: 'none', fontSize: '10px', fontWeight: 800, cursor: 'pointer',
+ }}
+ >
+ VIEW WATCHLIST
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default ImportWatchlistModal;
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
index 0fb12c8f4..3c6b99746 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/WatchlistTab.tsx
@@ -1,6 +1,6 @@
-import React, { useState, useEffect, useCallback } from 'react';
+import React, { useReducer, useEffect, useCallback, useRef } from 'react';
import { useWorkspaceTabState } from '@/hooks/useWorkspaceTabState';
-import { RefreshCw, Download, WifiOff, Plus, BarChart3 } from 'lucide-react';
+import { RefreshCw, Download, Upload, WifiOff, Plus, BarChart3 } from 'lucide-react';
import { useTimezone } from '@/contexts/TimezoneContext';
import {
watchlistService,
@@ -9,30 +9,119 @@ import {
} from '@/services/core/watchlistService';
import { contextRecorderService } from '@/services/data-sources/contextRecorderService';
import { useWatchlistStocks, useMarketMovers, useVolumeLeaders } from '@/hooks/useWatchlist';
+import { withTimeout } from '@/services/core/apiUtils';
+import { validateSymbol } from '@/services/core/validators';
+import { ErrorBoundary } from '@/components/common/ErrorBoundary';
import WatchlistSidebar from './WatchlistSidebar';
import StockListView from './StockListView';
import StockDetailPanel from './StockDetailPanel';
import CreateWatchlistModal from './CreateWatchlistModal';
import AddStockModal from './AddStockModal';
+import ImportWatchlistModal, { WatchlistImportJSON, WatchlistImportResult, ImportWatchlistMode } from './ImportWatchlistModal';
import RecordingControlPanel from '@/components/common/RecordingControlPanel';
import { FINCEPT, FONT_FAMILY, SortCriteria, sortStocks, getNextWatchlistColor } from './utils';
import { useTranslation } from 'react-i18next';
import { showConfirm, showSuccess, showError } from '@/utils/notifications';
-const WatchlistTab: React.FC = () => {
+// ─── State machine (Point 1 + 2) ─────────────────────────────────────────────
+
+type WatchlistWithCount = Watchlist & { stock_count: number };
+
+interface WatchlistState {
+ status: 'idle' | 'loading' | 'ready' | 'error';
+ watchlists: WatchlistWithCount[];
+ selectedWatchlist: WatchlistWithCount | null;
+ selectedStock: WatchlistStockWithQuote | null;
+ sortBy: SortCriteria;
+ currentTime: Date;
+ showCreateWatchlist: boolean;
+ showAddStock: boolean;
+ showImport: boolean;
+ isRecording: boolean;
+ error: string | null;
+}
+
+type WatchlistAction =
+ | { type: 'INIT_START' }
+ | { type: 'INIT_SUCCESS'; watchlists: WatchlistWithCount[] }
+ | { type: 'INIT_ERROR'; error: string }
+ | { type: 'SET_WATCHLISTS'; watchlists: WatchlistWithCount[] }
+ | { type: 'SELECT_WATCHLIST'; watchlist: WatchlistWithCount | null }
+ | { type: 'SELECT_STOCK'; stock: WatchlistStockWithQuote | null }
+ | { type: 'SET_SORT'; sortBy: SortCriteria }
+ | { type: 'TICK' }
+ | { type: 'SHOW_CREATE'; value: boolean }
+ | { type: 'SHOW_ADD_STOCK'; value: boolean }
+ | { type: 'SHOW_IMPORT'; value: boolean }
+ | { type: 'SET_RECORDING'; value: boolean };
+
+const initialState: WatchlistState = {
+ status: 'idle',
+ watchlists: [],
+ selectedWatchlist: null,
+ selectedStock: null,
+ sortBy: 'CHANGE',
+ currentTime: new Date(),
+ showCreateWatchlist: false,
+ showAddStock: false,
+ showImport: false,
+ isRecording: false,
+ error: null,
+};
+
+function reducer(state: WatchlistState, action: WatchlistAction): WatchlistState {
+ switch (action.type) {
+ case 'INIT_START':
+ return { ...state, status: 'loading', error: null };
+ case 'INIT_SUCCESS':
+ return {
+ ...state,
+ status: 'ready',
+ watchlists: action.watchlists,
+ selectedWatchlist: state.selectedWatchlist ?? (action.watchlists[0] ?? null),
+ };
+ case 'INIT_ERROR':
+ return { ...state, status: 'error', error: action.error };
+ case 'SET_WATCHLISTS':
+ return { ...state, watchlists: action.watchlists };
+ case 'SELECT_WATCHLIST':
+ return { ...state, selectedWatchlist: action.watchlist, selectedStock: null };
+ case 'SELECT_STOCK':
+ return { ...state, selectedStock: action.stock };
+ case 'SET_SORT':
+ return { ...state, sortBy: action.sortBy };
+ case 'TICK':
+ return { ...state, currentTime: new Date() };
+ case 'SHOW_CREATE':
+ return { ...state, showCreateWatchlist: action.value };
+ case 'SHOW_ADD_STOCK':
+ return { ...state, showAddStock: action.value };
+ case 'SHOW_IMPORT':
+ return { ...state, showImport: action.value };
+ case 'SET_RECORDING':
+ return { ...state, isRecording: action.value };
+ default:
+ return state;
+ }
+}
+
+const INVOKE_TIMEOUT = 15_000;
+
+// ─── Inner component (wrapped by ErrorBoundary below) ────────────────────────
+
+const WatchlistTabInner: React.FC = () => {
const { t } = useTranslation('watchlist');
const { timezone, formatTime } = useTimezone();
- const [currentTime, setCurrentTime] = useState(new Date());
- const [watchlists, setWatchlists] = useState<Array<Watchlist & { stock_count: number }>>([]);
- const [selectedWatchlist, setSelectedWatchlist] = useState<(Watchlist & { stock_count: number }) | null>(null);
- const [selectedStock, setSelectedStock] = useState<WatchlistStockWithQuote | null>(null);
- const [loading, setLoading] = useState(false);
- const [sortBy, setSortBy] = useState<SortCriteria>('CHANGE');
- const [showCreateWatchlist, setShowCreateWatchlist] = useState(false);
- const [showAddStock, setShowAddStock] = useState(false);
- const [isRecording, setIsRecording] = useState(false);
-
- // Cached data fetching
+ const [state, dispatch] = useReducer(reducer, initialState);
+ const mountedRef = useRef(true); // Point 3
+
+ const {
+ status, watchlists, selectedWatchlist, selectedStock,
+ sortBy, currentTime, showCreateWatchlist, showAddStock, showImport, isRecording,
+ } = state;
+
+ // ── Cached data fetching (Points 1, 4, 7 via useCache) ───────────────────
+
const {
data: stocks,
isLoading: stocksLoading,
@@ -40,207 +129,286 @@ const WatchlistTab: React.FC = () => {
isOffline,
isStale,
refresh: refreshStocks,
- invalidate: invalidateStocks
+ invalidate: invalidateStocks,
} = useWatchlistStocks(selectedWatchlist?.id || null, {
enabled: !!selectedWatchlist,
- refetchInterval: 10 * 60 * 1000
+ refetchInterval: 10 * 60 * 1000,
});
- const {
- data: marketMovers,
- refresh: refreshMovers
- } = useMarketMovers(5, {
+ const { data: marketMovers, refresh: refreshMovers } = useMarketMovers(5, {
enabled: !!selectedWatchlist,
- refetchInterval: 10 * 60 * 1000
+ refetchInterval: 10 * 60 * 1000,
});
- const {
- data: volumeLeaders,
- refresh: refreshVolume
- } = useVolumeLeaders(5, {
+ const { data: volumeLeaders, refresh: refreshVolume } = useVolumeLeaders(5, {
enabled: !!selectedWatchlist,
- refetchInterval: 10 * 60 * 1000
+ refetchInterval: 10 * 60 * 1000,
});
- // Workspace tab state
- const getWorkspaceState = useCallback(() => ({
- sortBy: sortBy || 'CHANGE',
- }), [sortBy]);
+ // ── Workspace state persistence ───────────────────────────────────────────
- const setWorkspaceState = useCallback((state: Record<string, unknown>) => {
- if (typeof state.sortBy === 'string') setSortBy(state.sortBy as SortCriteria);
+ const getWorkspaceState = useCallback(() => ({ sortBy: sortBy || 'CHANGE' }), [sortBy]);
+ const setWorkspaceState = useCallback((s: Record<string, unknown>) => {
+ if (typeof s.sortBy === 'string') dispatch({ type: 'SET_SORT', sortBy: s.sortBy as SortCriteria });
}, []);
-
useWorkspaceTabState('watchlist', getWorkspaceState, setWorkspaceState);
- const refreshWatchlistData = useCallback(async () => {
- await Promise.all([refreshStocks(), refreshMovers(), refreshVolume()]);
- }, [refreshStocks, refreshMovers, refreshVolume]);
+ // ── Init + cleanup (Point 3) ──────────────────────────────────────────────
- const stocksList = stocks || [];
+ useEffect(() => {
+ mountedRef.current = true;
+ const controller = new AbortController();
- const recordCurrentData = async () => {
- if (selectedWatchlist && stocksList.length > 0) {
+ const init = async () => {
+ dispatch({ type: 'INIT_START' });
try {
- const recordData = {
- watchlistId: selectedWatchlist.id,
- watchlistName: selectedWatchlist.name,
- stocks: stocksList.map(s => ({
- symbol: s.symbol,
- quote: s.quote,
- notes: s.notes
- })),
- timestamp: new Date().toISOString()
- };
- await contextRecorderService.recordApiResponse(
- 'Watchlist',
- 'watchlist-stocks',
- recordData,
- `Watchlist (Snapshot): ${selectedWatchlist.name} - ${new Date().toLocaleString()}`,
- ['watchlist', 'stocks', 'snapshot']
+ await withTimeout(watchlistService.initialize(), INVOKE_TIMEOUT, 'Watchlist init timeout');
+ if (controller.signal.aborted || !mountedRef.current) return;
+ const result = await withTimeout(
+ watchlistService.getWatchlistsWithCounts(),
+ INVOKE_TIMEOUT,
+ 'Load watchlists timeout'
);
- } catch (error) {
- console.error('[WatchlistTab] Failed to record current data:', error);
+ if (!controller.signal.aborted && mountedRef.current) {
+ dispatch({ type: 'INIT_SUCCESS', watchlists: result });
+ }
+ } catch (err) {
+ if (!controller.signal.aborted && mountedRef.current) {
+ dispatch({ type: 'INIT_ERROR', error: err instanceof Error ? err.message : 'Initialization failed' });
+ }
}
- }
- };
+ };
- // Initialize service and load watchlists
- useEffect(() => {
- const initService = async () => {
- setLoading(true);
- try {
- await watchlistService.initialize();
- await loadWatchlists();
- } catch (error) {
- console.error('[WatchlistTab] Initialization error:', error);
- } finally {
- setLoading(false);
- }
+ init();
+
+ return () => {
+ mountedRef.current = false;
+ controller.abort();
};
- initService();
}, []);
+ // ── Clock tick (Point 3 — cleanup) ───────────────────────────────────────
+
useEffect(() => {
- const timer = setInterval(() => setCurrentTime(new Date()), 1000);
+ const timer = setInterval(() => {
+ if (mountedRef.current) dispatch({ type: 'TICK' });
+ }, 1000);
return () => clearInterval(timer);
}, []);
- const loadWatchlists = async () => {
- try {
- const result = await watchlistService.getWatchlistsWithCounts();
- setWatchlists(result);
- if (result.length > 0 && !selectedWatchlist) {
- setSelectedWatchlist(result[0]);
- }
- } catch (error) {
- console.error('[WatchlistTab] Error loading watchlists:', error);
- }
- };
+ // ── Sync selectedStock with refreshed quotes ──────────────────────────────
+
+ const stocksList = stocks || [];
useEffect(() => {
if (selectedStock && stocksList.length > 0) {
const updated = stocksList.find(s => s.symbol === selectedStock.symbol);
- if (updated) setSelectedStock(updated);
+ if (updated) dispatch({ type: 'SELECT_STOCK', stock: updated });
}
- }, [stocksList]);
+ }, [stocksList]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // ── Recording effect (Point 3 — no leak) ─────────────────────────────────
useEffect(() => {
- if (isRecording && selectedWatchlist && stocksList.length > 0) {
- const recordData = {
- watchlistId: selectedWatchlist.id,
- watchlistName: selectedWatchlist.name,
- stocks: stocksList.map(s => ({
- symbol: s.symbol,
- quote: s.quote,
- notes: s.notes
- })),
- timestamp: new Date().toISOString()
- };
- contextRecorderService.recordApiResponse(
- 'Watchlist',
- 'watchlist-stocks',
- recordData,
- `Watchlist: ${selectedWatchlist.name} - ${new Date().toLocaleString()}`,
- ['watchlist', 'stocks', 'quotes']
- ).catch(error => {
- console.error('[WatchlistTab] Failed to record data:', error);
- });
- }
+ if (!isRecording || !selectedWatchlist || stocksList.length === 0) return;
+ const recordData = {
+ watchlistId: selectedWatchlist.id,
+ watchlistName: selectedWatchlist.name,
+ stocks: stocksList.map(s => ({ symbol: s.symbol, quote: s.quote, notes: s.notes })),
+ timestamp: new Date().toISOString(),
+ };
+ contextRecorderService.recordApiResponse(
+ 'Watchlist', 'watchlist-stocks', recordData,
+ `Watchlist: ${selectedWatchlist.name} - ${new Date().toLocaleString()}`,
+ ['watchlist', 'stocks', 'quotes']
+ ).catch(() => { /* silent — recording is non-critical */ });
}, [stocksList, isRecording, selectedWatchlist]);
- const handleCreateWatchlist = async (name: string, description: string, color: string) => {
+ // ── Helpers ───────────────────────────────────────────────────────────────
+
+ const loadWatchlists = useCallback(async () => {
+ const result = await withTimeout(
+ watchlistService.getWatchlistsWithCounts(),
+ INVOKE_TIMEOUT,
+ 'Load watchlists timeout'
+ );
+ if (mountedRef.current) dispatch({ type: 'SET_WATCHLISTS', watchlists: result });
+ return result;
+ }, []);
+
+ const refreshWatchlistData = useCallback(async () => {
+ await Promise.all([refreshStocks(), refreshMovers(), refreshVolume()]);
+ }, [refreshStocks, refreshMovers, refreshVolume]);
+
+ const recordCurrentData = useCallback(async () => {
+ if (!selectedWatchlist || stocksList.length === 0) return;
try {
- const newWatchlist = await watchlistService.createWatchlist(name, description, color);
- await loadWatchlists();
- const updated = await watchlistService.getWatchlistsWithCounts();
- const created = updated.find(w => w.id === newWatchlist.id);
- if (created) setSelectedWatchlist(created);
- } catch (error) {
- console.error('[WatchlistTab] Error creating watchlist:', error);
- throw error;
- }
+ await contextRecorderService.recordApiResponse(
+ 'Watchlist', 'watchlist-stocks',
+ {
+ watchlistId: selectedWatchlist.id,
+ watchlistName: selectedWatchlist.name,
+ stocks: stocksList.map(s => ({ symbol: s.symbol, quote: s.quote, notes: s.notes })),
+ timestamp: new Date().toISOString(),
+ },
+ `Watchlist (Snapshot): ${selectedWatchlist.name} - ${new Date().toLocaleString()}`,
+ ['watchlist', 'stocks', 'snapshot']
+ );
+ } catch { /* non-critical */ }
+ }, [selectedWatchlist, stocksList]);
+
+ // ── Handlers ──────────────────────────────────────────────────────────────
+
+ const handleCreateWatchlist = async (name: string, description: string, color: string) => {
+ const newWatchlist = await withTimeout(
+ watchlistService.createWatchlist(name, description, color),
+ INVOKE_TIMEOUT, 'Create watchlist timeout'
+ );
+ const updated = await loadWatchlists();
+ const created = updated.find(w => w.id === newWatchlist.id);
+ if (created && mountedRef.current) dispatch({ type: 'SELECT_WATCHLIST', watchlist: created });
};
const handleDeleteWatchlist = async (watchlistId: string) => {
- const confirmed = await showConfirm(
- 'This action cannot be undone.',
- {
- title: 'Delete this watchlist?',
- type: 'danger'
- }
- );
+ const confirmed = await showConfirm('This action cannot be undone.', {
+ title: 'Delete this watchlist?', type: 'danger',
+ });
if (!confirmed) return;
-
try {
- await watchlistService.deleteWatchlist(watchlistId);
- await loadWatchlists();
- if (selectedWatchlist?.id === watchlistId) {
- setSelectedWatchlist(watchlists.length > 1 ? watchlists[0] : null);
- setSelectedStock(null);
+ await withTimeout(
+ watchlistService.deleteWatchlist(watchlistId),
+ INVOKE_TIMEOUT, 'Delete watchlist timeout'
+ );
+ const updated = await loadWatchlists();
+ if (selectedWatchlist?.id === watchlistId && mountedRef.current) {
+ const next = updated.find(w => w.id !== watchlistId) ?? null;
+ dispatch({ type: 'SELECT_WATCHLIST', watchlist: next });
await invalidateStocks();
}
showSuccess('Watchlist deleted successfully');
- } catch (error) {
- console.error('[WatchlistTab] Error deleting watchlist:', error);
- showError('Failed to delete watchlist');
+ } catch (err) {
+ showError(err instanceof Error ? err.message : 'Failed to delete watchlist');
}
};
const handleAddStock = async (symbol: string, notes: string) => {
if (!selectedWatchlist) return;
- try {
- await watchlistService.addStock(selectedWatchlist.id, symbol, notes);
- await invalidateStocks();
- await refreshStocks();
- await loadWatchlists();
- } catch (error) {
- console.error('[WatchlistTab] Error adding stock:', error);
- throw error;
- }
+ // Point 10: validate input
+ const validation = validateSymbol(symbol);
+ if (!validation.valid) throw new Error(validation.error);
+ await withTimeout(
+ watchlistService.addStock(selectedWatchlist.id, validation.sanitized!, notes),
+ INVOKE_TIMEOUT, 'Add stock timeout'
+ );
+ await invalidateStocks();
+ await refreshStocks();
+ await loadWatchlists();
};
const handleRemoveStock = async (symbol: string) => {
if (!selectedWatchlist) return;
try {
- await watchlistService.removeStock(selectedWatchlist.id, symbol);
+ await withTimeout(
+ watchlistService.removeStock(selectedWatchlist.id, symbol),
+ INVOKE_TIMEOUT, 'Remove stock timeout'
+ );
await invalidateStocks();
await refreshStocks();
await loadWatchlists();
- if (selectedStock?.symbol === symbol) setSelectedStock(null);
- showSuccess('Stock removed from watchlist', [
- { label: 'Symbol', value: symbol },
- ]);
- } catch (error) {
- console.error('[WatchlistTab] Error removing stock:', error);
- showError('Failed to remove stock');
+ if (selectedStock?.symbol === symbol && mountedRef.current) {
+ dispatch({ type: 'SELECT_STOCK', stock: null });
+ }
+ showSuccess('Stock removed from watchlist', [{ label: 'Symbol', value: symbol }]);
+ } catch (err) {
+ showError(err instanceof Error ? err.message : 'Failed to remove stock');
}
};
+ const handleImportWatchlist = async (
+ data: WatchlistImportJSON,
+ mode: ImportWatchlistMode,
+ targetWatchlistId?: string,
+ nameOverride?: string,
+ colorOverride?: string,
+ ): Promise<WatchlistImportResult> => {
+ const existingSymbols = new Set<string>();
+ let watchlistId = '';
+ let watchlistName = '';
+
+ if (mode === 'new') {
+ const name = nameOverride || data.watchlist_name;
+ const color = colorOverride || getNextWatchlistColor(watchlists.map(w => w.color));
+ const created = await withTimeout(
+ watchlistService.createWatchlist(name, data.description, color),
+ INVOKE_TIMEOUT, 'Create watchlist timeout'
+ );
+ watchlistId = created.id;
+ watchlistName = created.name;
+ } else {
+ if (!targetWatchlistId) throw new Error('No target watchlist selected');
+ const target = watchlists.find(w => w.id === targetWatchlistId);
+ if (!target) throw new Error('Target watchlist not found');
+ watchlistId = target.id;
+ watchlistName = target.name;
+ const currentStocks = await withTimeout(
+ watchlistService.getWatchlistStocks(watchlistId),
+ INVOKE_TIMEOUT, 'Get stocks timeout'
+ );
+ currentStocks.forEach(s => existingSymbols.add(s.symbol.toUpperCase()));
+ }
+
+ const skipped: string[] = [];
+ const errors: string[] = [];
+ let added = 0;
+
+ for (const entry of data.stocks) {
+ // Point 10: validate each symbol
+ const validation = validateSymbol(entry.symbol);
+ if (!validation.valid) {
+ errors.push(`${entry.symbol}: ${validation.error}`);
+ continue;
+ }
+ const sym = validation.sanitized!;
+ if (existingSymbols.has(sym)) { skipped.push(sym); continue; }
+ try {
+ await withTimeout(
+ watchlistService.addStock(watchlistId, sym, entry.notes),
+ INVOKE_TIMEOUT, `Add ${sym} timeout`
+ );
+ existingSymbols.add(sym);
+ added++;
+ } catch (err: any) {
+ errors.push(`${sym}: ${err?.message || 'Failed to add'}`);
+ }
+ }
+
+ const updated = await loadWatchlists();
+ await invalidateStocks();
+ await refreshStocks();
+
+ if (mode === 'new') {
+ const created = updated.find(w => w.id === watchlistId);
+ if (created && mountedRef.current) dispatch({ type: 'SELECT_WATCHLIST', watchlist: created });
+ }
+
+ return { watchlistId, watchlistName, added, skipped, errors };
+ };
+
+ const handleImportComplete = (result: WatchlistImportResult) => {
+ dispatch({ type: 'SHOW_IMPORT', value: false });
+ showSuccess(`Imported ${result.added} symbol${result.added !== 1 ? 's' : ''} to "${result.watchlistName}"`, [
+ { label: 'Added', value: String(result.added) },
+ ...(result.skipped.length > 0 ? [{ label: 'Skipped', value: String(result.skipped.length) }] : []),
+ ]);
+ };
+
const handleExportCSV = async () => {
if (!selectedWatchlist) return;
try {
- const csv = await watchlistService.exportWatchlistCSV(selectedWatchlist.id);
+ const csv = await withTimeout(
+ watchlistService.exportWatchlistCSV(selectedWatchlist.id),
+ INVOKE_TIMEOUT, 'Export timeout'
+ );
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -251,16 +419,18 @@ const WatchlistTab: React.FC = () => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
showSuccess('Watchlist exported successfully', [
- { label: 'File', value: `${selectedWatchlist?.name || 'watchlist'}.csv` },
+ { label: 'File', value: `${selectedWatchlist.name}.csv` },
]);
- } catch (error) {
- console.error('[WatchlistTab] Error exporting CSV:', error);
- showError('Failed to export CSV');
+ } catch (err) {
+ showError(err instanceof Error ? err.message : 'Failed to export CSV');
}
};
+ // ── Render ────────────────────────────────────────────────────────────────
+
const sortedStocks = sortStocks(stocksList, sortBy);
const refreshing = stocksRefreshing;
+ const loading = status === 'loading';
return (
<div style={{
@@ -270,7 +440,7 @@ const WatchlistTab: React.FC = () => {
fontFamily: FONT_FAMILY,
overflow: 'hidden',
display: 'flex',
- flexDirection: 'column'
+ flexDirection: 'column',
}}>
<style>{`
*::-webkit-scrollbar { width: 6px; height: 6px; }
@@ -290,7 +460,7 @@ const WatchlistTab: React.FC = () => {
alignItems: 'center',
justifyContent: 'space-between',
boxShadow: `0 2px 8px ${FINCEPT.ORANGE}20`,
- flexShrink: 0
+ flexShrink: 0,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<BarChart3 size={16} style={{ color: FINCEPT.ORANGE }} />
@@ -299,19 +469,14 @@ const WatchlistTab: React.FC = () => {
</span>
<span style={{ color: FINCEPT.BORDER }}>|</span>
<span style={{
- fontSize: '9px',
- fontWeight: 700,
+ fontSize: '9px', fontWeight: 700,
color: refreshing ? FINCEPT.ORANGE : FINCEPT.GREEN,
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
+ display: 'flex', alignItems: 'center', gap: '4px',
}}>
<span style={{
- width: '6px',
- height: '6px',
- borderRadius: '50%',
+ width: '6px', height: '6px', borderRadius: '50%',
backgroundColor: refreshing ? FINCEPT.ORANGE : FINCEPT.GREEN,
- display: 'inline-block'
+ display: 'inline-block',
}} />
{refreshing ? 'UPDATING' : 'LIVE'}
</span>
@@ -319,22 +484,16 @@ const WatchlistTab: React.FC = () => {
<span style={{ color: FINCEPT.CYAN, fontSize: '10px' }}>
{formatTime(currentTime, {
year: 'numeric', month: '2-digit', day: '2-digit',
- hour: '2-digit', minute: '2-digit', second: '2-digit'
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
})} {timezone.shortLabel}
</span>
{isOffline && (
<>
<span style={{ color: FINCEPT.BORDER }}>|</span>
<span style={{
- padding: '2px 6px',
- backgroundColor: `${FINCEPT.ORANGE}20`,
- color: FINCEPT.ORANGE,
- fontSize: '8px',
- fontWeight: 700,
- borderRadius: '2px',
- display: 'flex',
- alignItems: 'center',
- gap: '4px'
+ padding: '2px 6px', backgroundColor: `${FINCEPT.ORANGE}20`,
+ color: FINCEPT.ORANGE, fontSize: '8px', fontWeight: 700,
+ borderRadius: '2px', display: 'flex', alignItems: 'center', gap: '4px',
}}>
<WifiOff size={10} /> OFFLINE
</span>
@@ -344,12 +503,8 @@ const WatchlistTab: React.FC = () => {
<>
<span style={{ color: FINCEPT.BORDER }}>|</span>
<span style={{
- padding: '2px 6px',
- backgroundColor: `${FINCEPT.YELLOW}20`,
- color: FINCEPT.YELLOW,
- fontSize: '8px',
- fontWeight: 700,
- borderRadius: '2px'
+ padding: '2px 6px', backgroundColor: `${FINCEPT.YELLOW}20`,
+ color: FINCEPT.YELLOW, fontSize: '8px', fontWeight: 700, borderRadius: '2px',
}}>
STALE
</span>
@@ -360,34 +515,33 @@ const WatchlistTab: React.FC = () => {
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<RecordingControlPanel
tabName="Watchlist"
- onRecordingChange={setIsRecording}
+ onRecordingChange={(v) => dispatch({ type: 'SET_RECORDING', value: v })}
onRecordingStart={recordCurrentData}
/>
+ <button
+ onClick={() => dispatch({ type: 'SHOW_IMPORT', value: true })}
+ style={{
+ padding: '6px 10px', backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`, color: FINCEPT.GRAY,
+ fontSize: '9px', fontWeight: 700, borderRadius: '2px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px', transition: 'all 0.2s',
+ }}
+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = FINCEPT.CYAN; e.currentTarget.style.color = FINCEPT.CYAN; }}
+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; e.currentTarget.style.color = FINCEPT.GRAY; }}
+ >
+ <Upload size={10} /> IMPORT
+ </button>
{selectedWatchlist && (
<button
- onClick={() => setShowAddStock(true)}
+ onClick={() => dispatch({ type: 'SHOW_ADD_STOCK', value: true })}
style={{
- padding: '6px 10px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- fontSize: '9px',
- fontWeight: 700,
- borderRadius: '2px',
- cursor: 'pointer',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.WHITE;
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
+ padding: '6px 10px', backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`, color: FINCEPT.GRAY,
+ fontSize: '9px', fontWeight: 700, borderRadius: '2px',
+ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '4px', transition: 'all 0.2s',
}}
+ onMouseEnter={(e) => { e.currentTarget.style.borderColor = FINCEPT.ORANGE; e.currentTarget.style.color = FINCEPT.WHITE; }}
+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; e.currentTarget.style.color = FINCEPT.GRAY; }}
>
<Plus size={10} /> ADD STOCK
</button>
@@ -396,30 +550,15 @@ const WatchlistTab: React.FC = () => {
onClick={refreshWatchlistData}
disabled={!selectedWatchlist || refreshing}
style={{
- padding: '6px 10px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- fontSize: '9px',
- fontWeight: 700,
- borderRadius: '2px',
+ padding: '6px 10px', backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`, color: FINCEPT.GRAY,
+ fontSize: '9px', fontWeight: 700, borderRadius: '2px',
cursor: selectedWatchlist && !refreshing ? 'pointer' : 'not-allowed',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- opacity: selectedWatchlist && !refreshing ? 1 : 0.5,
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (selectedWatchlist && !refreshing) {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.WHITE;
- }
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
+ display: 'flex', alignItems: 'center', gap: '4px',
+ opacity: selectedWatchlist && !refreshing ? 1 : 0.5, transition: 'all 0.2s',
}}
+ onMouseEnter={(e) => { if (selectedWatchlist && !refreshing) { e.currentTarget.style.borderColor = FINCEPT.ORANGE; e.currentTarget.style.color = FINCEPT.WHITE; } }}
+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; e.currentTarget.style.color = FINCEPT.GRAY; }}
>
<RefreshCw size={10} className={refreshing ? 'wl-spin' : ''} /> REFRESH
</button>
@@ -427,30 +566,15 @@ const WatchlistTab: React.FC = () => {
onClick={handleExportCSV}
disabled={!selectedWatchlist}
style={{
- padding: '6px 10px',
- backgroundColor: 'transparent',
- border: `1px solid ${FINCEPT.BORDER}`,
- color: FINCEPT.GRAY,
- fontSize: '9px',
- fontWeight: 700,
- borderRadius: '2px',
+ padding: '6px 10px', backgroundColor: 'transparent',
+ border: `1px solid ${FINCEPT.BORDER}`, color: FINCEPT.GRAY,
+ fontSize: '9px', fontWeight: 700, borderRadius: '2px',
cursor: selectedWatchlist ? 'pointer' : 'not-allowed',
- display: 'flex',
- alignItems: 'center',
- gap: '4px',
- opacity: selectedWatchlist ? 1 : 0.5,
- transition: 'all 0.2s'
- }}
- onMouseEnter={(e) => {
- if (selectedWatchlist) {
- e.currentTarget.style.borderColor = FINCEPT.ORANGE;
- e.currentTarget.style.color = FINCEPT.WHITE;
- }
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.borderColor = FINCEPT.BORDER;
- e.currentTarget.style.color = FINCEPT.GRAY;
+ display: 'flex', alignItems: 'center', gap: '4px',
+ opacity: selectedWatchlist ? 1 : 0.5, transition: 'all 0.2s',
}}
+ onMouseEnter={(e) => { if (selectedWatchlist) { e.currentTarget.style.borderColor = FINCEPT.ORANGE; e.currentTarget.style.color = FINCEPT.WHITE; } }}
+ onMouseLeave={(e) => { e.currentTarget.style.borderColor = FINCEPT.BORDER; e.currentTarget.style.color = FINCEPT.GRAY; }}
>
<Download size={10} /> EXPORT
</button>
@@ -460,14 +584,9 @@ const WatchlistTab: React.FC = () => {
{/* Summary Info Bar */}
{selectedWatchlist && (
<div style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderBottom: `1px solid ${FINCEPT.BORDER}`,
- padding: '6px 16px',
- display: 'flex',
- alignItems: 'center',
- gap: '16px',
- fontSize: '9px',
- flexShrink: 0
+ backgroundColor: FINCEPT.HEADER_BG, borderBottom: `1px solid ${FINCEPT.BORDER}`,
+ padding: '6px 16px', display: 'flex', alignItems: 'center',
+ gap: '16px', fontSize: '9px', flexShrink: 0,
}}>
<span style={{ color: FINCEPT.GRAY, fontWeight: 700, letterSpacing: '0.5px' }}>ACTIVE LIST</span>
<span style={{ color: FINCEPT.YELLOW, fontWeight: 700 }}>{selectedWatchlist.name.toUpperCase()}</span>
@@ -482,31 +601,24 @@ const WatchlistTab: React.FC = () => {
{/* Main Three-Panel Content */}
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
- {/* Left Panel - Sidebar */}
<WatchlistSidebar
watchlists={watchlists}
selectedWatchlistId={selectedWatchlist?.id || null}
onSelectWatchlist={(id) => {
const wl = watchlists.find(w => w.id === id);
- if (wl) setSelectedWatchlist(wl);
+ if (wl) dispatch({ type: 'SELECT_WATCHLIST', watchlist: wl });
}}
- onCreateWatchlist={() => setShowCreateWatchlist(true)}
+ onCreateWatchlist={() => dispatch({ type: 'SHOW_CREATE', value: true })}
onDeleteWatchlist={handleDeleteWatchlist}
marketMovers={marketMovers || undefined}
volumeLeaders={volumeLeaders || []}
/>
- {/* Center Panel - Stock List */}
{!selectedWatchlist ? (
<div style={{
- flex: 1,
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- justifyContent: 'center',
- color: FINCEPT.MUTED,
- fontSize: '10px',
- textAlign: 'center'
+ flex: 1, display: 'flex', flexDirection: 'column',
+ alignItems: 'center', justifyContent: 'center',
+ color: FINCEPT.MUTED, fontSize: '10px', textAlign: 'center',
}}>
<BarChart3 size={24} style={{ marginBottom: '8px', opacity: 0.5 }} />
<span>SELECT A WATCHLIST TO VIEW</span>
@@ -516,29 +628,22 @@ const WatchlistTab: React.FC = () => {
stocks={sortedStocks}
watchlistName={selectedWatchlist.name}
sortBy={sortBy}
- onSortChange={setSortBy}
- onStockClick={setSelectedStock}
+ onSortChange={(s) => dispatch({ type: 'SET_SORT', sortBy: s })}
+ onStockClick={(stock) => dispatch({ type: 'SELECT_STOCK', stock })}
onRemoveStock={handleRemoveStock}
selectedSymbol={selectedStock?.symbol}
isLoading={stocksLoading}
/>
)}
- {/* Right Panel - Stock Details */}
<StockDetailPanel stock={selectedStock} />
</div>
{/* Status Bar */}
<div style={{
- backgroundColor: FINCEPT.HEADER_BG,
- borderTop: `1px solid ${FINCEPT.BORDER}`,
- padding: '4px 16px',
- fontSize: '9px',
- color: FINCEPT.GRAY,
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- flexShrink: 0
+ backgroundColor: FINCEPT.HEADER_BG, borderTop: `1px solid ${FINCEPT.BORDER}`,
+ padding: '4px 16px', fontSize: '9px', color: FINCEPT.GRAY,
+ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0,
}}>
<span>FINCEPT WATCHLIST v2.0 | REAL-TIME TRACKING | UNIFIED CACHE</span>
<div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
@@ -553,20 +658,36 @@ const WatchlistTab: React.FC = () => {
{/* Modals */}
{showCreateWatchlist && (
<CreateWatchlistModal
- onClose={() => setShowCreateWatchlist(false)}
+ onClose={() => dispatch({ type: 'SHOW_CREATE', value: false })}
onCreate={handleCreateWatchlist}
existingColors={watchlists.map(w => w.color)}
/>
)}
{showAddStock && selectedWatchlist && (
<AddStockModal
- onClose={() => setShowAddStock(false)}
+ onClose={() => dispatch({ type: 'SHOW_ADD_STOCK', value: false })}
onAdd={handleAddStock}
existingSymbols={stocksList.map(s => s.symbol)}
/>
)}
+ <ImportWatchlistModal
+ show={showImport}
+ existingWatchlists={watchlists.map(w => ({ id: w.id, name: w.name }))}
+ selectedWatchlistId={selectedWatchlist?.id ?? null}
+ onClose={() => dispatch({ type: 'SHOW_IMPORT', value: false })}
+ onImport={handleImportWatchlist}
+ onImportComplete={handleImportComplete}
+ />
</div>
);
};
+// ─── Exported component — wrapped with ErrorBoundary (Point 5) ───────────────
+
+const WatchlistTab: React.FC = () => (
+ <ErrorBoundary name="WatchlistTab">
+ <WatchlistTabInner />
+ </ErrorBoundary>
+);
+
export default WatchlistTab;
diff --git a/fincept-terminal-desktop/src/components/tabs/watchlist/index.ts b/fincept-terminal-desktop/src/components/tabs/watchlist/index.ts
index 279a6f507..9b549f60b 100644
--- a/fincept-terminal-desktop/src/components/tabs/watchlist/index.ts
+++ b/fincept-terminal-desktop/src/components/tabs/watchlist/index.ts
@@ -1,2 +1,4 @@
export { default } from "./WatchlistTab";
export { default as WatchlistTab } from "./WatchlistTab";
+export { default as ImportWatchlistModal } from "./ImportWatchlistModal";
+export type { WatchlistImportJSON, WatchlistImportResult, ImportWatchlistMode } from "./ImportWatchlistModal";
diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
index 3a8fce95c..c5bec5eb4 100644
--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
@@ -126,6 +126,9 @@ export interface SessionData {
credit_balance?: number;
is_verified?: boolean;
mfa_enabled?: boolean;
+ phone?: string | null;
+ country?: string | null;
+ country_code?: string | null;
};
expires_at?: string;
credit_balance?: number;
@@ -158,7 +161,7 @@ interface AuthContextType {
resetPassword: (email: string, otp: string, newPassword: string) => Promise<{ success: boolean; error?: string }>;
// Payment methods
fetchPlans: () => Promise<{ success: boolean; error?: string }>;
- createPaymentSession: (planId: string, currency?: string) => Promise<{ success: boolean; data?: PaymentSession; error?: string }>;
+ createPaymentSession: (planId: string, currency?: string, customerPhone?: string) => Promise<{ success: boolean; data?: PaymentSession; error?: string }>;
getUserSubscription: () => Promise<{ success: boolean; data?: UserSubscription; error?: string }>;
refreshUserData: () => Promise<void>;
// API key management - centralized for all components
@@ -313,7 +316,10 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
account_type: userProfile.account_type,
credit_balance: userProfile.credit_balance,
is_verified: userProfile.is_verified,
- mfa_enabled: userProfile.mfa_enabled
+ mfa_enabled: userProfile.mfa_enabled,
+ phone: (userProfile as any).phone ?? null,
+ country: (userProfile as any).country ?? null,
+ country_code: (userProfile as any).country_code ?? null,
},
subscription: userSubscription || undefined
};
@@ -358,7 +364,10 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
account_type: userProfile.account_type,
credit_balance: userProfile.credit_balance,
is_verified: userProfile.is_verified,
- mfa_enabled: userProfile.mfa_enabled
+ mfa_enabled: userProfile.mfa_enabled,
+ phone: (userProfile as any).phone ?? null,
+ country: (userProfile as any).country ?? null,
+ country_code: (userProfile as any).country_code ?? null,
} : apiData.user,
expires_at: apiData.user_type === 'guest' ? apiData.guest?.expires_at : undefined,
requests_today: apiData.user_type === 'guest' ? apiData.guest?.requests_today : undefined,
@@ -449,15 +458,19 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
};
// Create payment session - Updated for new API format
- const createPaymentSession = async (planId: string, currency: string = 'USD'): Promise<{ success: boolean; data?: PaymentSession; error?: string }> => {
+ const createPaymentSession = async (planId: string, currency: string = 'USD', customerPhone?: string): Promise<{ success: boolean; data?: PaymentSession; error?: string }> => {
if (!session?.api_key) {
return { success: false, error: 'No API key available' };
}
+ // Use provided phone or fall back to profile phone
+ const phoneToUse = customerPhone || session?.user_info?.phone || undefined;
+
try {
const result = await PaymentApiService.createCheckoutSession(session.api_key, {
plan_id: planId,
- currency: currency
+ currency: currency,
+ ...(phoneToUse ? { customer_phone: phoneToUse } : {}),
});
if (result.success && result.data) {
@@ -568,7 +581,10 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
account_type: userProfile.account_type,
credit_balance: userProfile.credit_balance,
is_verified: userProfile.is_verified,
- mfa_enabled: userProfile.mfa_enabled
+ mfa_enabled: userProfile.mfa_enabled,
+ phone: (userProfile as any).phone ?? null,
+ country: (userProfile as any).country ?? null,
+ country_code: (userProfile as any).country_code ?? null,
} : {
email: email,
account_type: 'free',
@@ -662,7 +678,10 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
account_type: userProfile.account_type,
credit_balance: userProfile.credit_balance,
is_verified: userProfile.is_verified,
- mfa_enabled: userProfile.mfa_enabled
+ mfa_enabled: userProfile.mfa_enabled,
+ phone: (userProfile as any).phone ?? null,
+ country: (userProfile as any).country ?? null,
+ country_code: (userProfile as any).country_code ?? null,
} : {
email: email,
account_type: 'free',
@@ -718,7 +737,10 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
account_type: userProfile.account_type,
credit_balance: userProfile.credit_balance,
is_verified: userProfile.is_verified,
- mfa_enabled: userProfile.mfa_enabled
+ mfa_enabled: userProfile.mfa_enabled,
+ phone: (userProfile as any).phone ?? null,
+ country: (userProfile as any).country ?? null,
+ country_code: (userProfile as any).country_code ?? null,
} : {
email: email,
account_type: 'free',
diff --git a/fincept-terminal-desktop/src/services/auth/userApi.tsx b/fincept-terminal-desktop/src/services/auth/userApi.tsx
index 6c57f54d5..4f9a86e4e 100644
--- a/fincept-terminal-desktop/src/services/auth/userApi.tsx
+++ b/fincept-terminal-desktop/src/services/auth/userApi.tsx
@@ -78,7 +78,12 @@ export class UserApiService {
return makeApiRequest('/user/profile', 'GET', apiKey);
}
- static async updateUserProfile(apiKey: string, profileData: any): Promise<ApiResponse> {
+ static async updateUserProfile(apiKey: string, profileData: {
+ username?: string;
+ phone?: string | null;
+ country?: string | null;
+ country_code?: string | null;
+ }): Promise<ApiResponse> {
return makeApiRequest('/user/profile', 'PUT', apiKey, profileData);
}
diff --git a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
index 6d09aee30..b765443ef 100644
--- a/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
+++ b/fincept-terminal-desktop/src/services/payment/paymentApi.tsx
@@ -25,6 +25,7 @@ interface PaymentApiResponse<T = any> {
interface CheckoutRequest {
plan_id: string; // Valid values: free, basic, standard, pro, enterprise
currency: string; // USD, EUR, INR, etc.
+ customer_phone?: string; // Required by Cashfree for some payment methods
}
// Response Types - Matches backend exactly
@@ -245,10 +246,13 @@ export class PaymentApiService {
'X-API-Key': apiKey
};
- const requestBody = {
+ const requestBody: Record<string, string> = {
plan_id: request.plan_id,
currency: request.currency || 'USD'
};
+ if (request.customer_phone) {
+ requestBody.customer_phone = request.customer_phone;
+ }
const response = await makePaymentApiRequest<{ data: CheckoutResponse }>('POST', '/cashfree/create-order', requestBody, headers);
diff --git a/fincept-terminal-desktop/src/services/support/supportApi.ts b/fincept-terminal-desktop/src/services/support/supportApi.ts
index 87d601b48..489b0635c 100644
--- a/fincept-terminal-desktop/src/services/support/supportApi.ts
+++ b/fincept-terminal-desktop/src/services/support/supportApi.ts
@@ -1,7 +1,14 @@
// Support API Service - Feedback, Contact, Newsletter endpoints
+import { fetch as tauriFetch } from '@tauri-apps/plugin-http';
+
const API_BASE_URL = 'https://api.fincept.in';
+// Use native fetch in dev (for Vite proxy), Tauri fetch in production
+const safeFetch: typeof fetch = import.meta.env.DEV
+ ? window.fetch.bind(window)
+ : (tauriFetch as unknown as typeof fetch);
+
// Types
export interface ContactFormData {
name: string;
@@ -35,7 +42,7 @@ export interface ApiResponse<T = any> {
*/
export async function submitContactForm(data: ContactFormData): Promise<ApiResponse> {
try {
- const response = await fetch(`${API_BASE_URL}/support/contact`, {
+ const response = await safeFetch(`${API_BASE_URL}/support/contact`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -58,7 +65,6 @@ export async function submitContactForm(data: ContactFormData): Promise<ApiRespo
message: 'Contact form submitted successfully',
};
} catch (error) {
- console.error('Contact form submission error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Network error',
@@ -71,7 +77,7 @@ export async function submitContactForm(data: ContactFormData): Promise<ApiRespo
*/
export async function submitFeedback(data: FeedbackFormData, apiKey: string): Promise<ApiResponse> {
try {
- const response = await fetch(`${API_BASE_URL}/support/feedback`, {
+ const response = await safeFetch(`${API_BASE_URL}/support/feedback`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -99,7 +105,6 @@ export async function submitFeedback(data: FeedbackFormData, apiKey: string): Pr
message: 'Feedback submitted successfully',
};
} catch (error) {
- console.error('Feedback submission error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Network error',
@@ -112,7 +117,7 @@ export async function submitFeedback(data: FeedbackFormData, apiKey: string): Pr
*/
export async function subscribeToNewsletter(data: NewsletterSubscribeData): Promise<ApiResponse> {
try {
- const response = await fetch(`${API_BASE_URL}/support/newsletter/subscribe`, {
+ const response = await safeFetch(`${API_BASE_URL}/support/newsletter/subscribe`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -135,7 +140,6 @@ export async function subscribeToNewsletter(data: NewsletterSubscribeData): Prom
message: 'Successfully subscribed to newsletter',
};
} catch (error) {
- console.error('Newsletter subscription error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Network error',
@@ -148,7 +152,7 @@ export async function subscribeToNewsletter(data: NewsletterSubscribeData): Prom
*/
export async function getSupportCategories(): Promise<ApiResponse<string[]>> {
try {
- const response = await fetch(`${API_BASE_URL}/support/categories`, {
+ const response = await safeFetch(`${API_BASE_URL}/support/categories`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@@ -169,7 +173,6 @@ export async function getSupportCategories(): Promise<ApiResponse<string[]>> {
data: result,
};
} catch (error) {
- console.error('Get categories error:', error);
return {
success: false,
error: error instanceof Error ? error.message : 'Network error',