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.

version 3.1.5'

tilakpatel22b2a7b34355c7
diff --git a/fincept-terminal-desktop/package.json b/fincept-terminal-desktop/package.json
index 5f253c344..2274c8dc9 100644
--- a/fincept-terminal-desktop/package.json
+++ b/fincept-terminal-desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "fincept-terminal-desktop",
"private": true,
- "version": "3.1.4",
+ "version": "3.1.5",
"type": "module",
"license": "AGPL-3.0-or-later",
"scripts": {
diff --git a/fincept-terminal-desktop/src-tauri/Cargo.toml b/fincept-terminal-desktop/src-tauri/Cargo.toml
index 4bc17eaa1..48eb3bf79 100644
--- a/fincept-terminal-desktop/src-tauri/Cargo.toml
+++ b/fincept-terminal-desktop/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "fincept-terminal-desktop"
-version = "3.1.4"
+version = "3.1.5"
description = "Professional-grade financial analysis platform with AI-powered insights and real-time market data"
authors = ["Fincept Corporation <[email protected]>"]
edition = "2021"
diff --git a/fincept-terminal-desktop/src-tauri/src/setup.rs b/fincept-terminal-desktop/src-tauri/src/setup.rs
index de7112538..be6f3e885 100644
--- a/fincept-terminal-desktop/src-tauri/src/setup.rs
+++ b/fincept-terminal-desktop/src-tauri/src/setup.rs
@@ -80,9 +80,8 @@ fn get_install_dir(app: &AppHandle) -> Result<PathBuf, String> {
fn check_python(install_dir: &PathBuf) -> (bool, Option<String>) {
let python_exe = if cfg!(target_os = "windows") {
install_dir.join("python/python.exe")
- } else if cfg!(target_os = "macos") {
- install_dir.join("python/Versions/3.12/bin/python3")
} else {
+ // Linux and macOS both use python-build-standalone now
install_dir.join("python/bin/python3")
};
@@ -92,6 +91,7 @@ fn check_python(install_dir: &PathBuf) -> (bool, Option<String>) {
let mut cmd = Command::new(&python_exe);
cmd.arg("--version");
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -199,6 +199,7 @@ fn check_packages(install_dir: &PathBuf) -> bool {
// Check numpy1 venv for key packages
let mut cmd1 = Command::new(&venv1_python);
cmd1.args(&["-c", "import numpy, pandas, vectorbt, backtesting, gluonts"]);
+
#[cfg(target_os = "windows")]
cmd1.creation_flags(CREATE_NO_WINDOW);
let check1 = cmd1.output().map(|o| o.status.success()).unwrap_or(false);
@@ -210,6 +211,7 @@ fn check_packages(install_dir: &PathBuf) -> bool {
// Check numpy2 venv for key packages
let mut cmd2 = Command::new(&venv2_python);
cmd2.args(&["-c", "import numpy, pandas, yfinance, vnpy"]);
+
#[cfg(target_os = "windows")]
cmd2.creation_flags(CREATE_NO_WINDOW);
let check2 = cmd2.output().map(|o| o.status.success()).unwrap_or(false);
@@ -297,12 +299,21 @@ async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Result<(), St
#[cfg(target_os = "macos")]
{
- // Download official Python.org universal2 installer
- let download_url = format!("https://www.python.org/ftp/python/{}/python-{}-macos11.pkg", PYTHON_VERSION, PYTHON_VERSION);
- let pkg_path = python_dir.join("python.pkg");
+ // Use python-build-standalone for macOS (same approach as Linux)
+ // Detect architecture (Apple Silicon M1/M2 or Intel)
+ let arch = std::env::consts::ARCH;
+ let platform = if arch == "aarch64" {
+ "aarch64-apple-darwin-install_only"
+ } else {
+ "x86_64-apple-darwin-install_only"
+ };
+
+ // Use latest python-build-standalone release
+ let download_url = format!("https://github.com/astral-sh/python-build-standalone/releases/download/20241217/cpython-3.12.8+20241217-{}.tar.gz", platform);
+ let tar_path = python_dir.join("python.tar.gz");
let mut cmd = Command::new("curl");
- cmd.args(&["-L", "-o", pkg_path.to_str().unwrap(), &download_url]);
+ cmd.args(&["-L", "-o", tar_path.to_str().unwrap(), &download_url]);
let output = cmd.output().map_err(|e| format!("Download failed: {}", e))?;
if !output.status.success() {
return Err(format!("Download failed: {}", String::from_utf8_lossy(&output.stderr)));
@@ -310,43 +321,23 @@ async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Result<(), St
emit_progress(app, "python", 60, "Extracting Python...", false);
- // Extract pkg using xar (works better than pkgutil)
- let temp_extract = std::env::temp_dir().join(format!("fincept_py_{}", std::process::id()));
- let _ = std::fs::remove_dir_all(&temp_extract);
- std::fs::create_dir_all(&temp_extract)
- .map_err(|e| format!("Failed to create temp dir: {}", e))?;
-
- let mut cmd = Command::new("xar");
- cmd.args(&["-xf", pkg_path.to_str().unwrap(), "-C", temp_extract.to_str().unwrap()]);
+ let mut cmd = Command::new("tar");
+ cmd.args(&["-xzf", tar_path.to_str().unwrap(), "-C", python_dir.to_str().unwrap(), "--strip-components=1"]);
let output = cmd.output().map_err(|e| format!("Extract failed: {}", e))?;
if !output.status.success() {
return Err(format!("Extract failed: {}", String::from_utf8_lossy(&output.stderr)));
}
- // Find and extract Python Framework payload
- let payload_path = temp_extract.join("Python_Framework.pkg/Payload");
- if payload_path.exists() {
- let mut cmd = Command::new("tar");
- cmd.args(&["-xzf", payload_path.to_str().unwrap(), "-C", python_dir.to_str().unwrap(), "--strip-components=0"]);
- let output = cmd.output().map_err(|e| format!("Payload extract failed: {}", e))?;
- if !output.status.success() {
- return Err(format!("Payload extract failed: {}", String::from_utf8_lossy(&output.stderr)));
- }
+ // Cleanup
+ let _ = std::fs::remove_file(&tar_path);
- // Also check what was actually extracted
- eprintln!("[SETUP] Checking extracted files...");
- if let Ok(entries) = std::fs::read_dir(&python_dir) {
- for entry in entries.flatten() {
- eprintln!("[SETUP] - {:?}", entry.path());
- }
+ // Check what was extracted
+ eprintln!("[SETUP] Checking extracted Python files...");
+ if let Ok(entries) = std::fs::read_dir(&python_dir) {
+ for entry in entries.flatten() {
+ eprintln!("[SETUP] - {:?}", entry.path());
}
- } else {
- return Err("Python Framework payload not found in pkg".to_string());
}
-
- // Cleanup
- let _ = std::fs::remove_file(&pkg_path);
- let _ = std::fs::remove_dir_all(&temp_extract);
}
// Enable pip by modifying python312._pth (Windows only)
@@ -393,23 +384,18 @@ async fn install_python(app: &AppHandle, install_dir: &PathBuf) -> Result<(), St
// Install pip
let python_exe = if cfg!(target_os = "windows") {
python_dir.join("python.exe")
- } else if cfg!(target_os = "macos") {
- // macOS: Python extracted from .pkg has Versions/3.12/bin/python3
- let versions_python = python_dir.join(format!("Versions/{}/bin/python3", &PYTHON_VERSION[..4]));
- let bin_python = python_dir.join("bin/python3");
- if versions_python.exists() {
- versions_python
- } else if bin_python.exists() {
- bin_python
- } else {
- return Err(format!("Python executable not found. Checked:\n - {:?}\n - {:?}", versions_python, bin_python));
- }
} else {
+ // Linux and macOS both use python-build-standalone now
python_dir.join("bin/python3")
};
+ if !python_exe.exists() {
+ return Err(format!("Python executable not found at: {:?}", python_exe));
+ }
+
let mut cmd = Command::new(&python_exe);
cmd.arg(get_pip_path.to_str().unwrap());
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -671,14 +657,14 @@ async fn install_uv(app: &AppHandle, install_dir: &PathBuf) -> Result<(), String
// Use python -m pip instead of pip directly (more reliable)
let python_exe = if cfg!(target_os = "windows") {
install_dir.join("python/python.exe")
- } else if cfg!(target_os = "macos") {
- install_dir.join("python/Versions/3.12/bin/python3")
} else {
+ // Linux and macOS both use python-build-standalone now
install_dir.join("python/bin/python3")
};
let mut cmd = Command::new(&python_exe);
cmd.args(&["-m", "pip", "install", "uv"]);
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -702,20 +688,14 @@ async fn create_venv(app: &AppHandle, install_dir: &PathBuf, venv_name: &str) ->
let python_exe = if cfg!(target_os = "windows") {
install_dir.join("python/python.exe")
- } else if cfg!(target_os = "macos") {
- install_dir.join("python/Versions/3.12/bin/python3")
} else {
+ // Linux and macOS both use python-build-standalone now
install_dir.join("python/bin/python3")
};
- // Find UV executable - check multiple possible locations
+ // Find UV executable - check possible locations
let uv_candidates = if cfg!(target_os = "windows") {
vec![install_dir.join("python/Scripts/uv.exe")]
- } else if cfg!(target_os = "macos") {
- vec![
- install_dir.join("python/Versions/3.12/bin/uv"),
- install_dir.join("python/bin/uv"),
- ]
} else {
vec![install_dir.join("python/bin/uv")]
};
@@ -740,6 +720,7 @@ async fn create_venv(app: &AppHandle, install_dir: &PathBuf, venv_name: &str) ->
venv_path.to_str().unwrap(),
"--python", python_exe.to_str().unwrap()
]);
+
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
@@ -769,9 +750,8 @@ async fn install_packages_in_venv(
let python_exe = if cfg!(target_os = "windows") {
install_dir.join("python/python.exe")
- } else if cfg!(target_os = "macos") {
- install_dir.join("python/Versions/3.12/bin/python3")
} else {
+ // Linux and macOS both use python-build-standalone now
install_dir.join("python/bin/python3")
};
@@ -781,14 +761,9 @@ async fn install_packages_in_venv(
install_dir.join(format!("{}/bin/python3", venv_name))
};
- // Find UV executable - check multiple possible locations
+ // Find UV executable - check possible locations
let uv_candidates = if cfg!(target_os = "windows") {
vec![install_dir.join("python/Scripts/uv.exe")]
- } else if cfg!(target_os = "macos") {
- vec![
- install_dir.join("python/Versions/3.12/bin/uv"),
- install_dir.join("python/bin/uv"),
- ]
} else {
vec![install_dir.join("python/bin/uv")]
};
diff --git a/fincept-terminal-desktop/src-tauri/tauri.conf.json b/fincept-terminal-desktop/src-tauri/tauri.conf.json
index 214fbdcc1..64e0d623f 100644
--- a/fincept-terminal-desktop/src-tauri/tauri.conf.json
+++ b/fincept-terminal-desktop/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "FinceptTerminal",
- "version": "3.1.4",
+ "version": "3.1.5",
"identifier": "com.fincept.terminal",
"build": {
"beforeDevCommand": "bun run dev",
diff --git a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
index 6203bbd7e..b3696629b 100644
--- a/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
+++ b/fincept-terminal-desktop/src/components/auth/PricingScreen.tsx
@@ -25,8 +25,6 @@ const PricingScreen: React.FC<PricingScreenProps> = ({
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string>('');
const [hasLoadedPlans, setHasLoadedPlans] = useState(false);
- const [showDowngradeConfirm, setShowDowngradeConfirm] = useState(false);
- const [pendingPlanSelection, setPendingPlanSelection] = useState<string>('');
// Prevent multiple simultaneous requests
const loadingRef = useRef(false);
@@ -121,45 +119,17 @@ const PricingScreen: React.FC<PricingScreenProps> = ({
return iconMap[planId] || <Star className="w-4 h-4" />;
};
- // Check if selecting a plan is a downgrade
- const isDowngrade = (targetPlanId: string): boolean => {
+ // Handle plan selection - Block selection if user has active subscription and trying to select different plan
+ const handlePlanClick = (planId: string) => {
const currentPlanId = session?.user_info?.account_type;
- if (!currentPlanId) return false; // No current plan, can't downgrade
-
- const planTiers: { [key: string]: number } = {
- 'basic': 1,
- 'standard': 2,
- 'pro': 3,
- 'enterprise': 4
- };
- const currentTier = planTiers[currentPlanId] || 0;
- const targetTier = planTiers[targetPlanId] || 0;
-
- return targetTier < currentTier && currentTier > 0;
- };
-
- // Handle plan selection with downgrade confirmation
- const handlePlanClick = (planId: string) => {
- if (isDowngrade(planId)) {
- setPendingPlanSelection(planId);
- setShowDowngradeConfirm(true);
- } else {
- setSelectedPlan(planId);
+ // If user has active subscription and trying to select a different plan, show message
+ if (currentPlanId && currentPlanId !== 'free' && planId !== currentPlanId) {
+ setError('You already have an active subscription. To change plans, cancel your current subscription first. You will keep access until the end of your billing period, then you can select a new plan.');
+ return;
}
- };
- // Confirm downgrade
- const confirmDowngrade = () => {
- setSelectedPlan(pendingPlanSelection);
- setShowDowngradeConfirm(false);
- setPendingPlanSelection('');
- };
-
- // Cancel downgrade
- const cancelDowngrade = () => {
- setShowDowngradeConfirm(false);
- setPendingPlanSelection('');
+ setSelectedPlan(planId);
};
const handleSelectPlan = async () => {
@@ -180,36 +150,45 @@ const handleSelectPlan = async () => {
const result = await createPaymentSession(selectedPlan, 'USD');
if (result.success && result.data) {
- console.log('=== PAYMENT SESSION DEBUG ===');
- console.log('Full response data:', JSON.stringify(result.data, null, 2));
- console.log('checkout_url:', result.data.checkout_url);
- console.log('session_id:', result.data.session_id);
- console.log('order_id:', result.data.payment_uuid);
- console.log('========================');
-
- // Use checkout_url from the new API format
const checkoutUrl = result.data.checkout_url;
- if (checkoutUrl && checkoutUrl !== 'undefined') {
- console.log('Opening payment in external browser:', checkoutUrl);
-
- // Store order_id in localStorage for payment processing screen
- localStorage.setItem('pending_payment_order_id', result.data.payment_uuid);
-
- // Open in external browser using Tauri shell
- const { open } = await import('@tauri-apps/plugin-shell');
- await open(checkoutUrl);
+ if (checkoutUrl && checkoutUrl !== 'undefined' && checkoutUrl !== 'null') {
+ // Store transaction_id in localStorage for payment processing screen
+ if (result.data.payment_uuid) {
+ localStorage.setItem('pending_payment_order_id', result.data.payment_uuid);
+ }
- // Navigate to payment processing screen which will poll for status
- onNavigate('paymentProcessing' as Screen);
+ try {
+ // Import Tauri shell plugin and open in system browser
+ const { open } = await import('@tauri-apps/plugin-shell');
+ await open(checkoutUrl);
+
+ // Navigate to payment processing screen which will poll for status
+ onNavigate('paymentProcessing' as Screen);
+ } catch (shellError) {
+ // Fallback: try to open with window.open
+ const newWindow = window.open(checkoutUrl, '_blank', 'noopener,noreferrer');
+
+ if (!newWindow) {
+ // If window.open was blocked, show the URL to the user
+ setError(`Please open this URL in your browser to complete payment: ${checkoutUrl}`);
+
+ // Try to copy to clipboard
+ try {
+ await navigator.clipboard.writeText(checkoutUrl);
+ setError(`Payment URL copied to clipboard! Please paste it in your browser to complete payment.`);
+ } catch (clipboardError) {
+ console.error('Failed to copy to clipboard:', clipboardError);
+ }
+ } else {
+ // Window opened successfully, proceed to payment processing
+ onNavigate('paymentProcessing' as Screen);
+ }
+ }
} else {
- console.error('[ERROR] No checkout_url found in response!');
- console.error('Available fields:', Object.keys(result.data));
- console.error('Full response:', result.data);
- setError(`No payment session received. Available fields: ${Object.keys(result.data).join(', ')}`);
+ setError(`Payment URL not received from server. Please contact support.`);
}
} else {
- console.error('Failed to create payment session:', result.error);
setError(result.error || 'Failed to create payment session. Please try again.');
}
} catch (err) {
@@ -240,7 +219,8 @@ const handleSelectPlan = async () => {
// Use API's is_popular flag
const isPopular = plan.is_popular;
- const isRecommended = plan.plan_id === 'pro' || plan.plan_id === 'enterprise';
+ // Only show Best Value badge on the $50 plan
+ const isRecommended = plan.price_usd === 50;
// Check if this is the current plan
const currentPlanId = session?.user_info?.account_type || 'free';
@@ -268,14 +248,6 @@ const handleSelectPlan = async () => {
</div>
)}
- {!isCurrentPlan && isPopular && (
- <div className="absolute -top-2 left-1/2 transform -translate-x-1/2">
- <span className="bg-blue-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">
- Popular
- </span>
- </div>
- )}
-
{!isCurrentPlan && isRecommended && (
<div className="absolute -top-2 left-1/2 transform -translate-x-1/2">
<span className="bg-orange-500 text-white text-xs font-medium px-2 py-0.5 rounded-full">
@@ -386,59 +358,11 @@ const handleSelectPlan = async () => {
// Get current plan info (credit-based system)
const currentPlanId = session?.user_info?.account_type;
const currentPlanData = currentPlanId ? availablePlans.find(p => p.plan_id === currentPlanId) : undefined;
- const hasActiveSubscription = !!currentPlanId;
+ const hasActiveSubscription = !!currentPlanId && currentPlanId !== 'free';
const isCurrentPlanSelected = selectedPlan === currentPlanId;
- const pendingPlanData = availablePlans.find(p => p.plan_id === pendingPlanSelection);
return (
<>
- {/* Downgrade Confirmation Modal */}
- {showDowngradeConfirm && pendingPlanData && currentPlanData && (
- <div className="fixed inset-0 bg-black/80 backdrop-blur-sm flex items-center justify-center z-50">
- <div className="bg-zinc-900 border border-zinc-700 rounded-xl p-6 max-w-md mx-4 shadow-2xl">
- <div className="flex items-center mb-4">
- <AlertCircle className="w-6 h-6 text-orange-500 mr-3" />
- <h3 className="text-white text-lg font-semibold">Confirm Plan Downgrade</h3>
- </div>
-
- <div className="space-y-3 mb-6">
- <p className="text-zinc-300 text-sm">
- You are about to downgrade from <span className="font-semibold text-white">{currentPlanData.name}</span> to <span className="font-semibold text-white">{pendingPlanData.name}</span>.
- </p>
-
- <div className="bg-orange-500/10 border border-orange-500/30 rounded-lg p-3">
- <p className="text-orange-200 text-xs font-medium mb-2">What happens when you downgrade:</p>
- <ul className="text-orange-200/80 text-xs space-y-1">
- <li>• Credits: {currentPlanData.credits_amount.toLocaleString()} → {pendingPlanData.credits_amount.toLocaleString()} per month</li>
- <li>• Price: {currentPlanData.price_display} → {pendingPlanData.price_display} per month</li>
- <li>• Your remaining credits from the current plan will be lost</li>
- <li>• The new plan will take effect immediately after payment</li>
- </ul>
- </div>
-
- <p className="text-zinc-400 text-xs">
- Are you sure you want to continue with the downgrade?
- </p>
- </div>
-
- <div className="flex gap-3">
- <Button
- onClick={cancelDowngrade}
- variant="outline"
- className="flex-1 bg-zinc-800 border-zinc-600 text-white hover:bg-zinc-700"
- >
- Cancel
- </Button>
- <Button
- onClick={confirmDowngrade}
- className="flex-1 bg-orange-500 hover:bg-orange-600 text-white"
- >
- Confirm Downgrade
- </Button>
- </div>
- </div>
- </div>
- )}
<div className="bg-zinc-900/95 backdrop-blur-sm border border-zinc-700 rounded-xl p-6 w-full max-w-6xl mx-auto shadow-2xl overflow-y-auto max-h-[90vh]">
<div className="mb-6">
@@ -467,7 +391,7 @@ const handleSelectPlan = async () => {
<p className="text-zinc-400 text-sm">
{hasActiveSubscription && currentPlanData
- ? `Currently on ${currentPlanData.name}. Select a different plan to upgrade or downgrade.`
+ ? `Currently on ${currentPlanData.name}. To change plans, cancel your current subscription first.`
: 'Select a plan that fits your financial analysis needs.'
}
</p>
@@ -491,11 +415,38 @@ const handleSelectPlan = async () => {
</div>
{error && (
- <div className="mb-4 p-3 bg-red-900/20 border border-red-900/50 rounded-lg">
- <div className="flex items-center text-red-400 text-sm">
- <AlertCircle className="w-4 h-4 mr-2 flex-shrink-0" />
- {error}
+ <div className="mb-4 p-4 bg-red-900/20 border border-red-900/50 rounded-lg">
+ <div className="flex items-start text-red-400 text-sm mb-2">
+ <AlertCircle className="w-5 h-5 mr-2 flex-shrink-0 mt-0.5" />
+ <div className="flex-1">
+ <p className="font-medium mb-1">Payment Error</p>
+ <p className="text-red-300 text-xs">{error}</p>
+ </div>
</div>
+ {error.includes('contact support') && (
+ <div className="mt-3 pt-3 border-t border-red-900/30">
+ <p className="text-red-300 text-xs mb-2">Need help? Contact our support team:</p>
+ <div className="flex gap-2 text-xs">
+ <a
+ href="mailto:[email protected]"
+ className="text-blue-400 hover:text-blue-300 underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ </a>
+ <span className="text-zinc-500">•</span>
+ <a
+ href="https://discord.gg/ae87a8ygbN"
+ className="text-blue-400 hover:text-blue-300 underline"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Discord Support
+ </a>
+ </div>
+ </div>
+ )}
</div>
)}
diff --git a/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
index 88a9f75d9..689e44ba1 100644
--- a/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
+++ b/fincept-terminal-desktop/src/components/payment/PaymentProcessingScreen.tsx
@@ -51,29 +51,37 @@ const PaymentProcessingScreen: React.FC<PaymentProcessingScreenProps> = ({
}
try {
- console.log(`Payment status check #${checkCount + 1}`);
+ // Check if we have a transaction_id from localStorage (set by PricingScreen)
+ const pendingTransactionId = localStorage.getItem('pending_payment_order_id');
- // Check if we have an order_id from localStorage (set by PricingScreen)
- const pendingOrderId = localStorage.getItem('pending_payment_order_id');
+ if (pendingTransactionId) {
+ // Use the new transaction status endpoint
+ const statusResponse = await PaymentApiService.getTransactionStatus(
+ session.api_key,
+ pendingTransactionId
+ );
- if (pendingOrderId) {
- // Check the actual order status from backend
- const statusResponse = await PaymentApiService.getPaymentHistory(session.api_key, 1, 10);
+ if (statusResponse.success && statusResponse.data) {
+ const transactionData = statusResponse.data;
+ const transactionStatus = transactionData.status || transactionData.payment_status;
- if (statusResponse.success && statusResponse.data?.payments) {
- const recentPayment = statusResponse.data.payments.find(
- (p: any) => p.payment_uuid === pendingOrderId
- );
-
- if (recentPayment && recentPayment.status === 'completed') {
- console.log('Payment completed!', recentPayment);
+ if (transactionStatus === 'completed' || transactionStatus === 'success' || transactionStatus === 'paid') {
setStatus('completed');
- setPaymentData(recentPayment);
+ setPaymentData(transactionData);
localStorage.removeItem('pending_payment_order_id');
// Refresh user data to get updated credits
await refreshUserData();
+ // Clear intervals
+ if (intervalRef.current) clearInterval(intervalRef.current);
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
+ return;
+ } else if (transactionStatus === 'failed' || transactionStatus === 'cancelled') {
+ setStatus(transactionStatus as PaymentStatus);
+ setPaymentData(transactionData);
+ localStorage.removeItem('pending_payment_order_id');
+
// Clear intervals
if (intervalRef.current) clearInterval(intervalRef.current);
if (timeoutRef.current) clearTimeout(timeoutRef.current);
@@ -84,14 +92,12 @@ const PaymentProcessingScreen: React.FC<PaymentProcessingScreenProps> = ({
// Fallback: Check credit balance increase
await refreshUserData();
- console.log('User credits:', session.user_info?.credit_balance);
setCheckCount(prev => prev + 1);
setLastChecked(new Date());
// If we've checked too many times, timeout
if (checkCount >= maxChecks) {
- console.log('Payment check timeout reached');
setStatus('timeout');
if (intervalRef.current) clearInterval(intervalRef.current);
if (timeoutRef.current) clearTimeout(timeoutRef.current);
@@ -105,7 +111,6 @@ const PaymentProcessingScreen: React.FC<PaymentProcessingScreenProps> = ({
// Start checking payment status
useEffect(() => {
- console.log('Starting payment status monitoring...');
setStatus('waiting');
// Initial delay before first check
diff --git a/fincept-terminal-desktop/src/contexts/AuthContext.tsx b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
index ca4b48601..05c823f59 100644
--- a/fincept-terminal-desktop/src/contexts/AuthContext.tsx
+++ b/fincept-terminal-desktop/src/contexts/AuthContext.tsx
@@ -152,6 +152,7 @@ interface AuthContextType {
fetchPlans: () => Promise<{ success: boolean; error?: string }>;
createPaymentSession: (planId: string, currency?: string) => Promise<{ success: boolean; data?: PaymentSession; error?: string }>;
getUserSubscription: () => Promise<{ success: boolean; data?: UserSubscription; error?: string }>;
+ cancelSubscription: () => Promise<{ success: boolean; error?: string }>;
refreshUserData: () => Promise<void>;
}
@@ -443,22 +444,42 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
});
if (result.success && result.data) {
- // Handle double-wrapped response
+ // Handle potential double-wrapped response
const apiData = (result.data as any)?.data || result.data;
- // Map the new API response to PaymentSession format
+ // Map the API response to PaymentSession format
+ // Try multiple field names for checkout URL
+ const checkoutUrl = apiData.checkout_url || apiData.url || apiData.payment_url;
+
+ if (!checkoutUrl) {
+ return { success: false, error: 'No checkout URL received from server' };
+ }
+
const paymentSession: PaymentSession = {
- checkout_url: apiData.checkout_url,
- session_id: apiData.payment_session_id,
- payment_uuid: apiData.order_id,
+ checkout_url: checkoutUrl,
+ session_id: apiData.payment_session_id || apiData.session_id || apiData.id || '',
+ payment_uuid: apiData.order_id || apiData.payment_uuid || apiData.transaction_id || '',
plan: {
- name: apiData.plan?.name || 'Unknown Plan',
- price: apiData.pricing?.amount || 0
+ name: apiData.plan?.name || planId,
+ price: apiData.pricing?.amount || apiData.price || 0
}
};
+
return { success: true, data: paymentSession };
} else {
- return { success: false, error: result.error || 'Failed to create payment session' };
+ // Parse and provide user-friendly error messages
+ let errorMessage = result.error || 'Failed to create payment session';
+
+ // Check for specific error patterns
+ if (errorMessage.includes('customer with this email address already exists')) {
+ errorMessage = 'Your account is already registered in our payment system. Please contact support to complete your subscription.';
+ } else if (errorMessage.includes('Customer creation failed')) {
+ errorMessage = 'Unable to set up payment account. Please contact support for assistance.';
+ } else if (errorMessage.includes('PolarRequestValidationError')) {
+ errorMessage = 'Payment system error. Please contact support with your email address.';
+ }
+
+ return { success: false, error: errorMessage };
}
} catch (error) {
console.error('Failed to create payment session:', error);
@@ -485,6 +506,29 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
}
};
+ // Cancel subscription
+ // Cancels subscription in Polar, user keeps access until end of billing period
+ // Subscription auto-downgrades to free plan when it expires (via webhook)
+ const cancelSubscription = async (): Promise<{ success: boolean; error?: string }> => {
+ if (!session?.api_key) {
+ return { success: false, error: 'No API key available' };
+ }
+
+ try {
+ const result = await PaymentApiService.cancelSubscription(session.api_key);
+ if (result.success) {
+ // Refresh user data to reflect the cancellation status
+ await refreshUserData();
+ return { success: true };
+ } else {
+ return { success: false, error: result.error || 'Failed to cancel subscription' };
+ }
+ } catch (error) {
+ console.error('Failed to cancel subscription:', error);
+ return { success: false, error: 'Failed to cancel subscription' };
+ }
+ };
+
// Login function
const login = async (email: string, password: string): Promise<{ success: boolean; error?: string; mfa_required?: boolean }> => {
try {
@@ -829,6 +873,7 @@ const fetchUserProfile = async (apiKey: string): Promise<UserProfileResponse['da
fetchPlans,
createPaymentSession,
getUserSubscription,
+ cancelSubscription,
refreshUserData
};
diff --git a/fincept-terminal-desktop/src/services/paymentApi.tsx b/fincept-terminal-desktop/src/services/paymentApi.tsx
index 41be72521..80a8c988e 100644
--- a/fincept-terminal-desktop/src/services/paymentApi.tsx
+++ b/fincept-terminal-desktop/src/services/paymentApi.tsx
@@ -160,9 +160,7 @@ const makePaymentApiRequest = async <T = any>(
};
}
- if (!response.ok) {
- console.error('Payment request failed:', response.status, responseData.message || response.statusText);
- }
+ // Response handling
return {
success: response.ok,
@@ -229,7 +227,7 @@ export class PaymentApiService {
return makePaymentApiRequest<SubscriptionPlan>('GET', `/payment/plans/${planId}`);
}
- // Create checkout session - Updated to use /payment/create-order endpoint
+ // Create checkout session - Updated to use /payment/checkout/create endpoint
static async createCheckoutSession(
apiKey: string,
request: CheckoutRequest
@@ -252,8 +250,12 @@ export class PaymentApiService {
'X-API-Key': apiKey
};
- console.log('Creating payment order:', { plan_id: request.plan_id, currency: request.currency });
- return await makePaymentApiRequest<CheckoutResponse>('POST', '/payment/create-order', request, headers);
+ // Only send plan_id, not currency (based on API spec)
+ const requestBody = {
+ plan_id: request.plan_id
+ };
+
+ return await makePaymentApiRequest<CheckoutResponse>('POST', '/payment/checkout/create', requestBody, headers);
}
// Handle payment success
@@ -274,9 +276,9 @@ export class PaymentApiService {
});
}
- // Get user's current subscription
+ // Get user's current subscription - Updated to use new endpoint
static async getUserSubscription(apiKey: string): Promise<PaymentApiResponse<UserSubscriptionResponse>> {
- return makePaymentApiRequest<UserSubscriptionResponse>('GET', '/user/subscriptions', undefined, {
+ return makePaymentApiRequest<UserSubscriptionResponse>('GET', '/payment/subscription', undefined, {
'X-API-Key': apiKey
});
}
@@ -288,29 +290,24 @@ export class PaymentApiService {
});
}
- // Cancel subscription
+ // Cancel subscription - Updated to use new endpoint
+ // Cancels subscription in Polar, user keeps access until billing period ends
+ // Auto-downgrades to free plan when subscription expires via webhook
static async cancelSubscription(apiKey: string): Promise<PaymentApiResponse<any>> {
- return makePaymentApiRequest('POST', '/payment/cancel', undefined, {
- 'X-API-Key': apiKey
- });
- }
-
- // Reactivate subscription
- static async reactivateSubscription(apiKey: string): Promise<PaymentApiResponse<any>> {
- return makePaymentApiRequest('POST', '/payment/reactivate', undefined, {
+ return makePaymentApiRequest('POST', '/payment/subscription/cancel', undefined, {
'X-API-Key': apiKey
});
}
- // Get payment history (transactions)
+ // Get payment history (transactions) - Updated to use /payment/history endpoint
static async getPaymentHistory(
apiKey: string,
page: number = 1,
- limit: number = 10
+ limit: number = 20
): Promise<PaymentApiResponse<PaymentHistoryResponse>> {
return makePaymentApiRequest<PaymentHistoryResponse>(
'GET',
- `/user/transactions?page=${page}&limit=${limit}`,
+ `/payment/history?limit=${limit}`,
undefined,
{ 'X-API-Key': apiKey }
);
@@ -329,6 +326,19 @@ export class PaymentApiService {
);
}
+ // Get transaction status - New endpoint
+ static async getTransactionStatus(
+ apiKey: string,
+ transactionId: string
+ ): Promise<PaymentApiResponse<any>> {
+ return makePaymentApiRequest(
+ 'GET',
+ `/payment/status/${transactionId}`,
+ undefined,
+ { 'X-API-Key': apiKey }
+ );
+ }
+
// Webhook validation (for future use)
static async validateWebhook(webhookData: any): Promise<PaymentApiResponse<any>> {
return makePaymentApiRequest('POST', '/payment/webhook', webhookData);