FInal bank, stripe and paypal sandbox completed
This commit is contained in:
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
CreditCardIcon,
|
||||
@@ -39,6 +40,7 @@ import PageHeader from '../../components/common/PageHeader';
|
||||
import { useToast } from '../../components/ui/toast/ToastContainer';
|
||||
import { usePageLoading } from '../../context/PageLoadingContext';
|
||||
import { formatCurrency } from '../../utils';
|
||||
import { fetchAPI } from '../../services/api';
|
||||
import {
|
||||
getCreditBalance,
|
||||
getCreditPackages,
|
||||
@@ -69,12 +71,49 @@ import { useAuthStore } from '../../store/authStore';
|
||||
import PayInvoiceModal from '../../components/billing/PayInvoiceModal';
|
||||
import PendingPaymentView from '../../components/billing/PendingPaymentView';
|
||||
|
||||
/**
|
||||
* Helper function to determine the effective currency based on billing country and payment method
|
||||
* - PKR for Pakistan users using bank_transfer
|
||||
* - USD for all other cases (Stripe, PayPal, or non-PK countries)
|
||||
*/
|
||||
const getCurrencyForDisplay = (billingCountry: string, paymentMethod?: string): string => {
|
||||
if (billingCountry === 'PK' && paymentMethod === 'bank_transfer') {
|
||||
return 'PKR';
|
||||
}
|
||||
return 'USD';
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert USD price to PKR using approximate exchange rate
|
||||
* Backend uses 278 PKR per USD
|
||||
* Rounds to nearest thousand for cleaner display
|
||||
*/
|
||||
const convertUSDToPKR = (usdAmount: string | number): number => {
|
||||
const amount = typeof usdAmount === 'string' ? parseFloat(usdAmount) : usdAmount;
|
||||
const pkr = amount * 278;
|
||||
return Math.round(pkr / 1000) * 1000; // Round to nearest thousand
|
||||
};
|
||||
|
||||
export default function PlansAndBillingPage() {
|
||||
const { startLoading, stopLoading } = usePageLoading();
|
||||
const toast = useToast();
|
||||
const hasLoaded = useRef(false);
|
||||
const { user } = useAuthStore.getState();
|
||||
|
||||
// FIX: Subscribe to user changes from Zustand store (reactive)
|
||||
const user = useAuthStore((state) => state.user);
|
||||
const refreshUser = useAuthStore((state) => state.refreshUser);
|
||||
|
||||
const isAwsAdmin = user?.account?.slug === 'aws-admin';
|
||||
|
||||
// Track if initial data has been loaded to prevent flash
|
||||
const [initialDataLoaded, setInitialDataLoaded] = useState(false);
|
||||
|
||||
// Payment processing state - shows beautiful loading UI
|
||||
const [paymentProcessing, setPaymentProcessing] = useState<{
|
||||
active: boolean;
|
||||
stage: 'verifying' | 'processing' | 'finalizing' | 'activating';
|
||||
message: string;
|
||||
} | null>(null);
|
||||
|
||||
// UI States
|
||||
const [error, setError] = useState<string>('');
|
||||
@@ -99,7 +138,7 @@ export default function PlansAndBillingPage() {
|
||||
const [availableGateways, setAvailableGateways] = useState<{ stripe: boolean; paypal: boolean; manual: boolean }>({
|
||||
stripe: false,
|
||||
paypal: false,
|
||||
manual: true,
|
||||
manual: false, // FIX: Initialize as false, will be set based on country
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -109,65 +148,280 @@ export default function PlansAndBillingPage() {
|
||||
// Handle payment gateway return URLs BEFORE loadData
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const success = params.get('success');
|
||||
const sessionId = params.get('session_id'); // Stripe session ID
|
||||
const canceled = params.get('canceled');
|
||||
const purchase = params.get('purchase');
|
||||
const paypalStatus = params.get('paypal');
|
||||
const paypalToken = params.get('token'); // PayPal order ID
|
||||
const paypalToken = params.get('token'); // PayPal token from URL
|
||||
const planIdParam = params.get('plan_id');
|
||||
const packageIdParam = params.get('package_id');
|
||||
const { refreshUser } = useAuthStore.getState();
|
||||
|
||||
// Don't destructure from getState - use hooks above instead
|
||||
|
||||
// Handle PayPal return - MUST capture the order to complete payment
|
||||
// Do this BEFORE loadData to ensure payment is processed first
|
||||
// ============================================================================
|
||||
// PAYMENT RETURN LOGGING - Comprehensive debug output
|
||||
// ============================================================================
|
||||
const LOG_PREFIX = '[PAYMENT-RETURN]';
|
||||
|
||||
console.group(`${LOG_PREFIX} Payment Return Flow Started`);
|
||||
console.log(`${LOG_PREFIX} Full URL:`, window.location.href);
|
||||
console.log(`${LOG_PREFIX} Session ID:`, sessionId);
|
||||
|
||||
// Detect which payment flow we're in
|
||||
const paymentFlow =
|
||||
(paypalStatus === 'success' && paypalToken) ? 'PAYPAL_SUCCESS' :
|
||||
paypalStatus === 'cancel' ? 'PAYPAL_CANCEL' :
|
||||
(success === 'true' && sessionId) ? 'STRIPE_SUCCESS_WITH_SESSION' :
|
||||
success === 'true' ? 'STRIPE_SUCCESS_NO_SESSION' :
|
||||
canceled === 'true' ? 'STRIPE_CANCELED' :
|
||||
purchase === 'success' ? 'CREDIT_PURCHASE_SUCCESS' :
|
||||
purchase === 'canceled' ? 'CREDIT_PURCHASE_CANCELED' :
|
||||
'NO_PAYMENT_RETURN';
|
||||
|
||||
console.log(`${LOG_PREFIX} ===== DETECTED PAYMENT FLOW =====`);
|
||||
console.log(`${LOG_PREFIX} Flow type:`, paymentFlow);
|
||||
console.groupEnd();
|
||||
|
||||
// Handle PayPal return - Get order_id from localStorage and capture
|
||||
if (paypalStatus === 'success' && paypalToken) {
|
||||
// Import and capture PayPal order
|
||||
import('../../services/billing.api').then(({ capturePayPalOrder }) => {
|
||||
toast?.info?.('Completing PayPal payment...');
|
||||
capturePayPalOrder(paypalToken, {
|
||||
plan_id: planIdParam || undefined,
|
||||
package_id: packageIdParam || undefined,
|
||||
})
|
||||
.then(() => {
|
||||
toast?.success?.('Payment completed successfully!');
|
||||
refreshUser().catch(() => {});
|
||||
// Reload the page to get fresh data
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
window.location.reload();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('PayPal capture error:', err);
|
||||
toast?.error?.(err?.message || 'Failed to complete PayPal payment');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
});
|
||||
console.group(`${LOG_PREFIX} PayPal Success Flow`);
|
||||
|
||||
// FIX: Retrieve order_id from localStorage (stored before redirect)
|
||||
const storedOrderId = localStorage.getItem('paypal_order_id');
|
||||
|
||||
console.log(`${LOG_PREFIX} PayPal token from URL:`, paypalToken);
|
||||
console.log(`${LOG_PREFIX} Stored order_id from localStorage:`, storedOrderId);
|
||||
console.log(`${LOG_PREFIX} plan_id:`, planIdParam);
|
||||
console.log(`${LOG_PREFIX} package_id:`, packageIdParam);
|
||||
|
||||
if (!storedOrderId) {
|
||||
console.error(`${LOG_PREFIX} ❌ CRITICAL: No order_id in localStorage!`);
|
||||
console.log(`${LOG_PREFIX} This means order_id was not saved before redirect to PayPal`);
|
||||
console.groupEnd();
|
||||
toast?.error?.('Payment not captured - order ID missing. Please try again.');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
loadData(); // Still load data to show current state
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`${LOG_PREFIX} ✓ Order ID found, proceeding to capture...`);
|
||||
|
||||
// Show payment processing UI for PayPal
|
||||
setPaymentProcessing({
|
||||
active: true,
|
||||
stage: 'processing',
|
||||
message: 'Completing PayPal payment...'
|
||||
});
|
||||
|
||||
// Clean URL immediately
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
|
||||
// Import and capture PayPal order
|
||||
import('../../services/billing.api').then(async ({ capturePayPalOrder }) => {
|
||||
try {
|
||||
const captureResponse = await capturePayPalOrder(storedOrderId, {
|
||||
plan_id: planIdParam || undefined,
|
||||
package_id: packageIdParam || undefined,
|
||||
});
|
||||
|
||||
console.log(`${LOG_PREFIX} ✓ PayPal capture SUCCESS!`, captureResponse);
|
||||
localStorage.removeItem('paypal_order_id');
|
||||
|
||||
// Update stage
|
||||
setPaymentProcessing({
|
||||
active: true,
|
||||
stage: 'activating',
|
||||
message: 'Activating your subscription...'
|
||||
});
|
||||
|
||||
// Refresh user data - IMPORTANT: wait for this!
|
||||
try {
|
||||
await refreshUser();
|
||||
console.log(`${LOG_PREFIX} ✓ User refreshed`);
|
||||
} catch (refreshErr) {
|
||||
console.error(`${LOG_PREFIX} User refresh failed:`, refreshErr);
|
||||
}
|
||||
|
||||
// Short delay then complete
|
||||
setTimeout(() => {
|
||||
setPaymentProcessing(null);
|
||||
toast?.success?.('Payment completed successfully!');
|
||||
loadData();
|
||||
}, 500);
|
||||
|
||||
} catch (err: any) {
|
||||
console.error(`${LOG_PREFIX} ❌ PayPal capture FAILED:`, err);
|
||||
localStorage.removeItem('paypal_order_id');
|
||||
setPaymentProcessing(null);
|
||||
toast?.error?.(err?.message || 'Failed to complete PayPal payment');
|
||||
loadData();
|
||||
}
|
||||
});
|
||||
|
||||
console.groupEnd();
|
||||
return; // Don't load data yet, wait for capture to complete
|
||||
} else if (paypalStatus === 'cancel') {
|
||||
console.log(`${LOG_PREFIX} PayPal payment was cancelled by user`);
|
||||
localStorage.removeItem('paypal_order_id'); // Clear on cancellation
|
||||
toast?.info?.('PayPal payment was cancelled');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
}
|
||||
// Handle Stripe success
|
||||
else if (success === 'true') {
|
||||
// Handle Stripe return - Verify payment with backend
|
||||
else if (success === 'true' && sessionId) {
|
||||
console.log(`${LOG_PREFIX} Stripe Success Flow - Session:`, sessionId);
|
||||
|
||||
// Show beautiful processing UI
|
||||
setPaymentProcessing({
|
||||
active: true,
|
||||
stage: 'verifying',
|
||||
message: 'Verifying your payment...'
|
||||
});
|
||||
|
||||
// Clean URL immediately
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
|
||||
fetchAPI(`/v1/billing/stripe/verify-return/?session_id=${sessionId}`)
|
||||
.then(async (data) => {
|
||||
console.log(`${LOG_PREFIX} Verification response:`, data);
|
||||
|
||||
if (data.payment_processed) {
|
||||
// Payment already processed by webhook!
|
||||
setPaymentProcessing({
|
||||
active: true,
|
||||
stage: 'activating',
|
||||
message: 'Activating your subscription...'
|
||||
});
|
||||
|
||||
// Refresh user to get updated account status
|
||||
try {
|
||||
await refreshUser();
|
||||
console.log(`${LOG_PREFIX} User refreshed successfully`);
|
||||
} catch (err) {
|
||||
console.error(`${LOG_PREFIX} User refresh failed:`, err);
|
||||
}
|
||||
|
||||
// Short delay for UX, then show success
|
||||
setTimeout(() => {
|
||||
setPaymentProcessing(null);
|
||||
toast?.success?.('Payment successful! Your account is now active.');
|
||||
loadData();
|
||||
}, 500);
|
||||
} else if (data.should_poll) {
|
||||
// Webhook hasn't fired yet, poll for status
|
||||
setPaymentProcessing({
|
||||
active: true,
|
||||
stage: 'processing',
|
||||
message: 'Processing your payment...'
|
||||
});
|
||||
pollPaymentStatus(sessionId);
|
||||
} else {
|
||||
setPaymentProcessing(null);
|
||||
toast?.warning?.(data.message || 'Payment verification pending');
|
||||
loadData();
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.error(`${LOG_PREFIX} Verification failed:`, err);
|
||||
setPaymentProcessing(null);
|
||||
toast?.warning?.('Payment verification pending. Please refresh the page.');
|
||||
loadData();
|
||||
});
|
||||
|
||||
console.groupEnd();
|
||||
return;
|
||||
} else if (success === 'true') {
|
||||
// Stripe return without session_id (old flow fallback)
|
||||
console.log(`${LOG_PREFIX} Stripe success without session_id (legacy flow)`);
|
||||
toast?.success?.('Subscription activated successfully!');
|
||||
// Refresh user to get updated account status (removes pending_payment banner)
|
||||
refreshUser().catch(() => {});
|
||||
// Clean up URL
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
} else if (canceled === 'true') {
|
||||
console.log(`${LOG_PREFIX} Stripe payment was cancelled`);
|
||||
toast?.info?.('Payment was cancelled');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
} else if (purchase === 'success') {
|
||||
console.log(`${LOG_PREFIX} Credit purchase success`);
|
||||
toast?.success?.('Credits purchased successfully!');
|
||||
// Refresh user to get updated credit balance and account status
|
||||
refreshUser().catch(() => {});
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
} else if (purchase === 'canceled') {
|
||||
console.log(`${LOG_PREFIX} Credit purchase cancelled`);
|
||||
toast?.info?.('Credit purchase was cancelled');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
} else {
|
||||
console.log(`${LOG_PREFIX} No payment return parameters detected, loading page normally`);
|
||||
}
|
||||
|
||||
// Helper function to poll payment status with beautiful UI updates
|
||||
async function pollPaymentStatus(sessionId: string, attempts = 0) {
|
||||
const maxAttempts = 15; // Increased to 15 attempts
|
||||
console.log(`${LOG_PREFIX} [POLL] Attempt ${attempts + 1}/${maxAttempts}`);
|
||||
|
||||
// Update processing stage based on attempt count
|
||||
if (attempts === 3) {
|
||||
setPaymentProcessing({
|
||||
active: true,
|
||||
stage: 'finalizing',
|
||||
message: 'Finalizing your payment...'
|
||||
});
|
||||
}
|
||||
|
||||
if (attempts >= maxAttempts) {
|
||||
console.warn(`${LOG_PREFIX} [POLL] Max attempts reached`);
|
||||
setPaymentProcessing(null);
|
||||
toast?.warning?.('Payment is being processed. Please refresh the page in a moment.');
|
||||
loadData();
|
||||
return;
|
||||
}
|
||||
|
||||
// Faster initial polls (800ms), slower later (1.5s)
|
||||
const pollDelay = attempts < 5 ? 800 : 1500;
|
||||
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
const data = await fetchAPI(`/v1/billing/stripe/verify-return/?session_id=${sessionId}`);
|
||||
|
||||
if (data.payment_processed) {
|
||||
console.log(`${LOG_PREFIX} [POLL] Payment processed!`);
|
||||
|
||||
// Show activating stage
|
||||
setPaymentProcessing({
|
||||
active: true,
|
||||
stage: 'activating',
|
||||
message: 'Activating your subscription...'
|
||||
});
|
||||
|
||||
// Refresh user data
|
||||
try {
|
||||
await refreshUser();
|
||||
console.log(`${LOG_PREFIX} [POLL] User refreshed`);
|
||||
} catch (err) {
|
||||
console.error(`${LOG_PREFIX} [POLL] User refresh failed:`, err);
|
||||
}
|
||||
|
||||
// Short delay then complete
|
||||
setTimeout(() => {
|
||||
setPaymentProcessing(null);
|
||||
toast?.success?.('Payment successful! Your account is now active.');
|
||||
loadData();
|
||||
}, 500);
|
||||
} else {
|
||||
// Continue polling
|
||||
pollPaymentStatus(sessionId, attempts + 1);
|
||||
}
|
||||
} catch (pollErr) {
|
||||
console.error(`${LOG_PREFIX} [POLL] Error:`, pollErr);
|
||||
setPaymentProcessing(null);
|
||||
toast?.warning?.('Please refresh page to see updated status.');
|
||||
loadData();
|
||||
}
|
||||
}, pollDelay);
|
||||
}
|
||||
|
||||
// Load data after handling return URLs
|
||||
loadData();
|
||||
}, []);
|
||||
console.groupEnd();
|
||||
}, [refreshUser]);
|
||||
|
||||
const handleError = (err: any, fallback: string) => {
|
||||
const message = err?.message || fallback;
|
||||
@@ -245,7 +499,9 @@ export default function PlansAndBillingPage() {
|
||||
|
||||
// Load available payment gateways and sync with user's payment method
|
||||
try {
|
||||
const gateways = await getAvailablePaymentGateways();
|
||||
// FIX: Pass billing country to filter payment gateways correctly
|
||||
const billingCountry = user?.account?.billing_country || 'US';
|
||||
const gateways = await getAvailablePaymentGateways(billingCountry);
|
||||
setAvailableGateways(gateways);
|
||||
|
||||
// Use user's verified payment method to set gateway
|
||||
@@ -288,6 +544,7 @@ export default function PlansAndBillingPage() {
|
||||
}
|
||||
} finally {
|
||||
stopLoading();
|
||||
setInitialDataLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -382,19 +639,33 @@ export default function PlansAndBillingPage() {
|
||||
const accountPlanId = user?.account?.plan?.id;
|
||||
const effectivePlanId = currentPlanId || accountPlanId;
|
||||
const currentPlan = plans.find((p) => p.id === effectivePlanId) || user?.account?.plan;
|
||||
const hasActivePlan = Boolean(effectivePlanId);
|
||||
const hasPendingPayment = payments.some((p) => p.status === 'pending_approval');
|
||||
|
||||
// FIX: hasActivePlan should check account status, not just plan existence
|
||||
const accountStatus = user?.account?.status || '';
|
||||
const hasPendingInvoice = invoices.some((inv) => inv.status === 'pending');
|
||||
const hasActivePlan = accountStatus === 'active'
|
||||
&& effectivePlanId
|
||||
&& currentPlan?.slug !== 'free'
|
||||
&& !hasPendingInvoice;
|
||||
|
||||
const hasPendingPayment = payments.some((p) => p.status === 'pending_approval');
|
||||
|
||||
// Detect new user pending payment scenario:
|
||||
// - account status is 'pending_payment'
|
||||
// - user has never made a successful payment
|
||||
const accountStatus = user?.account?.status || '';
|
||||
const hasEverPaid = payments.some((p) => p.status === 'succeeded' || p.status === 'completed');
|
||||
const isNewUserPendingPayment = accountStatus === 'pending_payment' && !hasEverPaid;
|
||||
const pendingInvoice = invoices.find((inv) => inv.status === 'pending');
|
||||
const billingCountry = (user?.account as any)?.billing_country || 'US';
|
||||
|
||||
// FIX: canManageBilling should check if user actually paid via Stripe
|
||||
const userPaymentMethod = (user?.account as any)?.payment_method || '';
|
||||
const hasStripeCustomerId = !!(user?.account as any)?.stripe_customer_id;
|
||||
const canManageBilling = userPaymentMethod === 'stripe' && hasStripeCustomerId && hasActivePlan;
|
||||
|
||||
// Determine effective currency for display based on country and payment method
|
||||
const effectiveCurrency = getCurrencyForDisplay(billingCountry, userPaymentMethod);
|
||||
|
||||
// Combined check: disable Buy Credits if no active plan OR has pending invoice
|
||||
const canBuyCredits = hasActivePlan && !hasPendingInvoice;
|
||||
|
||||
@@ -409,18 +680,99 @@ export default function PlansAndBillingPage() {
|
||||
return price > 0 && p.id !== effectivePlanId;
|
||||
}).sort((a, b) => (Number(a.price) || 0) - (Number(b.price) || 0));
|
||||
|
||||
// PAYMENT PROCESSING OVERLAY - Beautiful full-page loading with breathing badge
|
||||
if (paymentProcessing?.active) {
|
||||
const stageConfig = {
|
||||
verifying: { color: 'bg-blue-600', label: 'Verifying Payment' },
|
||||
processing: { color: 'bg-amber-600', label: 'Processing Payment' },
|
||||
finalizing: { color: 'bg-purple-600', label: 'Finalizing' },
|
||||
activating: { color: 'bg-green-600', label: 'Activating Subscription' },
|
||||
};
|
||||
const config = stageConfig[paymentProcessing.stage];
|
||||
|
||||
// Use Modal-style overlay (matches app's default modal design)
|
||||
return createPortal(
|
||||
<div className="fixed inset-0 flex items-center justify-center overflow-y-auto modal z-99999">
|
||||
{/* Glass-like backdrop - same as Modal component */}
|
||||
<div className="fixed inset-0 h-full w-full bg-gray-400/50 backdrop-blur-[32px] dark:bg-gray-900/70"></div>
|
||||
|
||||
{/* Content card - Modal style */}
|
||||
<div className="relative w-full max-w-md mx-4 rounded-3xl bg-white dark:bg-gray-900 shadow-xl p-8">
|
||||
{/* Main Loading Spinner */}
|
||||
<div className="relative w-20 h-20 mx-auto mb-6">
|
||||
<div className="absolute inset-0 rounded-full border-4 border-gray-200 dark:border-gray-700"></div>
|
||||
<div className="absolute inset-0 rounded-full border-4 border-transparent border-t-brand-500 animate-spin"></div>
|
||||
<div className="absolute inset-2 rounded-full border-4 border-transparent border-t-brand-400 animate-spin" style={{ animationDirection: 'reverse', animationDuration: '1.5s' }}></div>
|
||||
</div>
|
||||
|
||||
{/* Message */}
|
||||
<h2 className="text-xl text-gray-900 dark:text-white font-bold text-center mb-2">
|
||||
{paymentProcessing.message}
|
||||
</h2>
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm text-center mb-6">
|
||||
Please don't close this page
|
||||
</p>
|
||||
|
||||
{/* Stage Badge */}
|
||||
<div className="flex justify-center">
|
||||
<span className={`inline-flex items-center gap-2 px-4 py-2 rounded-full text-white text-sm font-medium ${config.color} shadow-md`}>
|
||||
<Loader2Icon className="w-4 h-4 animate-spin" />
|
||||
{config.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
);
|
||||
}
|
||||
|
||||
// Show loading spinner until initial data is loaded
|
||||
// This prevents the flash of billing dashboard before PendingPaymentView
|
||||
if (!initialDataLoaded) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-500 mx-auto mb-4"></div>
|
||||
<p className="text-gray-500 dark:text-gray-400">Loading billing information...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// NEW USER PENDING PAYMENT - Show full-page payment view
|
||||
// This is the simplified flow for users who just signed up with a paid plan
|
||||
if (isNewUserPendingPayment && pendingInvoice) {
|
||||
const planName = currentPlan?.name || pendingInvoice.subscription?.plan?.name || 'Selected Plan';
|
||||
const planPrice = pendingInvoice.total_amount || pendingInvoice.total || '0';
|
||||
const invoiceCurrency = pendingInvoice.currency || 'USD';
|
||||
|
||||
// Get USD price from plan, PKR price from invoice
|
||||
const planUSDPrice = currentPlan?.price || pendingInvoice.subscription?.plan?.price || '0';
|
||||
const invoicePKRPrice = invoiceCurrency === 'PKR' ? (pendingInvoice.total_amount || pendingInvoice.total || '0') : undefined;
|
||||
|
||||
// Check if user has a pending bank transfer (status = pending_approval with payment_method = bank_transfer)
|
||||
const hasPendingBankTransfer = payments.some(
|
||||
(p) => p.status === 'pending_approval' && (p.payment_method === 'bank_transfer' || p.payment_method === 'manual')
|
||||
);
|
||||
|
||||
// Debug log for payment view
|
||||
console.log('[PlansAndBillingPage] Rendering PendingPaymentView:', {
|
||||
billingCountry,
|
||||
invoiceCurrency,
|
||||
planUSDPrice,
|
||||
invoicePKRPrice,
|
||||
planName,
|
||||
hasPendingBankTransfer
|
||||
});
|
||||
|
||||
return (
|
||||
<PendingPaymentView
|
||||
invoice={pendingInvoice}
|
||||
userCountry={billingCountry}
|
||||
planName={planName}
|
||||
planPrice={planPrice}
|
||||
planPrice={planUSDPrice}
|
||||
planPricePKR={invoicePKRPrice}
|
||||
currency={invoiceCurrency}
|
||||
hasPendingBankTransfer={hasPendingBankTransfer}
|
||||
onPaymentSuccess={() => {
|
||||
// Refresh user and billing data
|
||||
const { refreshUser } = useAuthStore.getState();
|
||||
@@ -482,23 +834,23 @@ export default function PlansAndBillingPage() {
|
||||
{/* SECTION 1: Current Plan Hero */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Main Plan Card */}
|
||||
<Card className="lg:col-span-2 p-6 bg-gradient-to-br from-brand-500/10 via-purple-500/10 to-indigo-500/10 dark:from-brand-600/20 dark:via-purple-600/20 dark:to-indigo-600/20 border border-brand-200/50 dark:border-brand-700/50">
|
||||
<Card className="lg:col-span-2 p-6 bg-gradient-to-br from-brand-200 via-brand-100 to-indigo-200 dark:from-brand-900/50 dark:via-brand-800/40 dark:to-indigo-900/40 border border-brand-300 dark:border-brand-600">
|
||||
<div className="flex items-start justify-between mb-6">
|
||||
<div>
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<h2 className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
<h2 className="text-2xl font-bold text-brand-900 dark:text-white">
|
||||
{currentPlan?.name || 'No Plan'}
|
||||
</h2>
|
||||
<Badge variant="solid" tone={hasActivePlan ? 'success' : 'warning'}>
|
||||
{hasActivePlan ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
<p className="text-brand-700 dark:text-brand-200">
|
||||
{currentPlan?.description || 'Select a plan to unlock features'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{availableGateways.stripe && hasActivePlan && (
|
||||
{canManageBilling && (
|
||||
<Button
|
||||
variant="outline"
|
||||
tone="neutral"
|
||||
@@ -521,55 +873,61 @@ export default function PlansAndBillingPage() {
|
||||
|
||||
{/* Quick Stats */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
|
||||
<ZapIcon className="w-4 h-4 text-brand-500" />
|
||||
<div className="p-4 bg-white/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-brand-700 dark:text-brand-300 mb-1">
|
||||
<ZapIcon className="w-4 h-4 text-brand-600" />
|
||||
Credits
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
<div className="text-2xl font-bold text-brand-900 dark:text-white">
|
||||
{creditBalance?.credits?.toLocaleString() || 0}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Available now</div>
|
||||
<div className="text-xs text-brand-600 dark:text-brand-400 mt-1">Available now</div>
|
||||
</div>
|
||||
<div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
|
||||
<TrendingUpIcon className="w-4 h-4 text-purple-500" />
|
||||
<div className="p-4 bg-white/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-purple-700 dark:text-purple-300 mb-1">
|
||||
<TrendingUpIcon className="w-4 h-4 text-purple-600" />
|
||||
Used
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
<div className="text-2xl font-bold text-purple-900 dark:text-white">
|
||||
{creditBalance?.credits_used_this_month?.toLocaleString() || 0}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">This month ({creditUsage}%)</div>
|
||||
<div className="text-xs text-purple-600 dark:text-purple-400 mt-1">This month ({creditUsage}%)</div>
|
||||
</div>
|
||||
<div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
|
||||
<CalendarIcon className="w-4 h-4 text-success-500" />
|
||||
<div className="p-4 bg-white/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-success-700 dark:text-success-300 mb-1">
|
||||
<CalendarIcon className="w-4 h-4 text-success-600" />
|
||||
Renews
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
<div className="text-2xl font-bold text-success-900 dark:text-white">
|
||||
{currentSubscription?.current_period_end
|
||||
? new Date(currentSubscription.current_period_end).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
|
||||
: '—'}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Next billing</div>
|
||||
<div className="text-xs text-success-600 dark:text-success-400 mt-1">Next billing</div>
|
||||
</div>
|
||||
<div className="p-4 bg-white/60 dark:bg-gray-800/40 rounded-xl">
|
||||
<div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 mb-1">
|
||||
<WalletIcon className="w-4 h-4 text-warning-500" />
|
||||
<div className="p-4 bg-white/80 dark:bg-gray-800/60 rounded-xl shadow-sm">
|
||||
<div className="flex items-center gap-2 text-sm text-amber-700 dark:text-amber-300 mb-1">
|
||||
<WalletIcon className="w-4 h-4 text-amber-600" />
|
||||
Monthly
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
${Number(currentPlan?.price || 0).toFixed(0)}
|
||||
<div className="text-2xl font-bold text-amber-900 dark:text-white">
|
||||
{formatCurrency(Number(currentPlan?.price || 0), 'USD')}
|
||||
</div>
|
||||
<div className="text-xs text-amber-600 dark:text-amber-400 mt-1">
|
||||
{billingCountry === 'PK' ? (
|
||||
<>≈ PKR {convertUSDToPKR(Number(currentPlan?.price || 0)).toLocaleString()}/mo</>
|
||||
) : (
|
||||
'Per month'
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-1">Per month</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Credit Usage Bar */}
|
||||
<div className="mt-6 pt-6 border-t border-white/30 dark:border-gray-700/30">
|
||||
<div className="mt-6 pt-6 border-t border-brand-200/50 dark:border-brand-700/30">
|
||||
<div className="flex justify-between text-sm mb-2">
|
||||
<span className="text-gray-600 dark:text-gray-400">Credit Usage</span>
|
||||
<span className="font-medium text-gray-900 dark:text-white">
|
||||
<span className="text-brand-700 dark:text-brand-300">Credit Usage</span>
|
||||
<span className="font-medium text-brand-900 dark:text-white">
|
||||
{creditBalance?.credits_used_this_month?.toLocaleString() || 0} / {creditBalance?.plan_credits_per_month?.toLocaleString() || 0}
|
||||
</span>
|
||||
</div>
|
||||
@@ -734,8 +1092,13 @@ export default function PlansAndBillingPage() {
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400 mb-1">credits</div>
|
||||
<div className="font-semibold text-brand-600 dark:text-brand-400 group-hover:text-brand-700 dark:group-hover:text-brand-300">
|
||||
${pkg.price}
|
||||
{formatCurrency(pkg.price, 'USD')}
|
||||
</div>
|
||||
{billingCountry === 'PK' && (
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
|
||||
≈ PKR {convertUSDToPKR(pkg.price).toLocaleString()}
|
||||
</div>
|
||||
)}
|
||||
{purchaseLoadingId === pkg.id && (
|
||||
<Loader2Icon className="w-4 h-4 animate-spin mt-2" />
|
||||
)}
|
||||
@@ -780,7 +1143,14 @@ export default function PlansAndBillingPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="font-bold text-gray-900 dark:text-white">${plan.price}/mo</div>
|
||||
<div className="font-bold text-gray-900 dark:text-white">
|
||||
{formatCurrency(plan.price, 'USD')}/mo
|
||||
</div>
|
||||
{billingCountry === 'PK' && (
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
≈ PKR {convertUSDToPKR(plan.price).toLocaleString()}/mo
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
@@ -845,7 +1215,16 @@ export default function PlansAndBillingPage() {
|
||||
<td className="px-6 py-3 text-gray-600 dark:text-gray-400">
|
||||
{new Date(invoice.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
|
||||
</td>
|
||||
<td className="px-6 py-3 text-center font-semibold text-gray-900 dark:text-white">{formatCurrency(invoice.total_amount, invoice.currency)}</td>
|
||||
<td className="px-6 py-3 text-center">
|
||||
<div className="font-semibold text-gray-900 dark:text-white">
|
||||
{formatCurrency(invoice.total_amount, 'USD')}
|
||||
</div>
|
||||
{billingCountry === 'PK' && invoice.currency === 'USD' && (
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
≈ PKR {convertUSDToPKR(invoice.total_amount).toLocaleString()}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-3 text-center">
|
||||
<Badge variant="soft" tone={invoice.status === 'paid' ? 'success' : 'warning'}>
|
||||
{invoice.status}
|
||||
@@ -900,7 +1279,15 @@ export default function PlansAndBillingPage() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{userPaymentMethods.map((method: any) => (
|
||||
{userPaymentMethods
|
||||
.filter((method: any) => {
|
||||
// Bank transfer is only available for Pakistani users
|
||||
if (method.type === 'bank_transfer' && billingCountry !== 'PK') {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((method: any) => (
|
||||
<div
|
||||
key={method.id}
|
||||
className={`p-4 border rounded-xl transition-all ${
|
||||
|
||||
Reference in New Issue
Block a user