FInal bank, stripe and paypal sandbox completed
This commit is contained in:
@@ -281,7 +281,16 @@ export default function BankTransferForm({
|
||||
<div className="flex justify-between items-center pt-3 border-t border-gray-200 dark:border-gray-700">
|
||||
<span className="font-medium text-gray-900 dark:text-white">Amount to Transfer</span>
|
||||
<span className="text-xl font-bold text-brand-600 dark:text-brand-400">
|
||||
{invoice.currency === 'PKR' ? 'PKR ' : '$'}{invoice.total_amount || invoice.total}
|
||||
{invoice.currency === 'PKR' ? 'PKR ' : '$'}
|
||||
{(() => {
|
||||
const amount = parseFloat(String(invoice.total_amount || invoice.total || 0));
|
||||
// Round PKR to nearest thousand
|
||||
if (invoice.currency === 'PKR') {
|
||||
const rounded = Math.round(amount / 1000) * 1000;
|
||||
return rounded.toLocaleString();
|
||||
}
|
||||
return amount.toFixed(2);
|
||||
})()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* - Pakistan (PK): Stripe (Credit/Debit Card) + Bank Transfer
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
CreditCardIcon,
|
||||
Building2Icon,
|
||||
@@ -20,16 +20,19 @@ import {
|
||||
Loader2Icon,
|
||||
ArrowLeftIcon,
|
||||
LockIcon,
|
||||
RefreshCwIcon,
|
||||
} from '../../icons';
|
||||
import { Card } from '../ui/card';
|
||||
import Badge from '../ui/badge/Badge';
|
||||
import Button from '../ui/button/Button';
|
||||
import { useToast } from '../ui/toast/ToastContainer';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import BankTransferForm from './BankTransferForm';
|
||||
import {
|
||||
Invoice,
|
||||
getAvailablePaymentGateways,
|
||||
subscribeToPlan,
|
||||
getPayments,
|
||||
type PaymentGateway,
|
||||
} from '../../services/billing.api';
|
||||
|
||||
@@ -40,6 +43,18 @@ const PayPalIcon = ({ className }: { className?: string }) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
// Currency symbol helper
|
||||
const getCurrencySymbol = (currency: string): string => {
|
||||
const symbols: Record<string, string> = {
|
||||
USD: '$',
|
||||
PKR: 'Rs.',
|
||||
EUR: '€',
|
||||
GBP: '£',
|
||||
INR: '₹',
|
||||
};
|
||||
return symbols[currency.toUpperCase()] || currency;
|
||||
};
|
||||
|
||||
interface PaymentOption {
|
||||
id: string;
|
||||
type: PaymentGateway;
|
||||
@@ -52,7 +67,10 @@ interface PendingPaymentViewProps {
|
||||
invoice: Invoice | null;
|
||||
userCountry: string;
|
||||
planName: string;
|
||||
planPrice: string;
|
||||
planPrice: string; // USD price (from plan)
|
||||
planPricePKR?: string; // PKR price (from invoice, if available)
|
||||
currency?: string;
|
||||
hasPendingBankTransfer?: boolean; // True if user has submitted bank transfer awaiting approval
|
||||
onPaymentSuccess: () => void;
|
||||
}
|
||||
|
||||
@@ -61,26 +79,79 @@ export default function PendingPaymentView({
|
||||
userCountry,
|
||||
planName,
|
||||
planPrice,
|
||||
planPricePKR,
|
||||
currency = 'USD',
|
||||
hasPendingBankTransfer = false,
|
||||
onPaymentSuccess,
|
||||
}: PendingPaymentViewProps) {
|
||||
const toast = useToast();
|
||||
const refreshUser = useAuthStore((state) => state.refreshUser);
|
||||
const [selectedGateway, setSelectedGateway] = useState<PaymentGateway>('stripe');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [gatewaysLoading, setGatewaysLoading] = useState(true);
|
||||
const [paymentOptions, setPaymentOptions] = useState<PaymentOption[]>([]);
|
||||
const [showBankTransfer, setShowBankTransfer] = useState(false);
|
||||
// Initialize bankTransferSubmitted from prop (persisted state)
|
||||
const [bankTransferSubmitted, setBankTransferSubmitted] = useState(hasPendingBankTransfer);
|
||||
const [checkingStatus, setCheckingStatus] = useState(false);
|
||||
|
||||
const isPakistan = userCountry === 'PK';
|
||||
|
||||
// SIMPLIFIED: Always show USD price, with PKR equivalent for Pakistan bank transfer users
|
||||
const showPKREquivalent = isPakistan && selectedGateway === 'manual';
|
||||
// Round PKR to nearest thousand for cleaner display
|
||||
const pkrRaw = planPricePKR ? parseFloat(planPricePKR) : parseFloat(planPrice) * 278;
|
||||
const pkrEquivalent = Math.round(pkrRaw / 1000) * 1000;
|
||||
|
||||
// Check if bank transfer has been approved
|
||||
const checkPaymentStatus = useCallback(async () => {
|
||||
if (!bankTransferSubmitted) return;
|
||||
|
||||
setCheckingStatus(true);
|
||||
try {
|
||||
// Refresh user data from backend
|
||||
await refreshUser();
|
||||
|
||||
// Also check payments to see if any succeeded
|
||||
const { results: payments } = await getPayments();
|
||||
const hasSucceededPayment = payments.some(
|
||||
(p: any) => p.status === 'succeeded' || p.status === 'completed'
|
||||
);
|
||||
|
||||
if (hasSucceededPayment) {
|
||||
toast?.success?.('Payment approved! Your account is now active.');
|
||||
onPaymentSuccess();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to check payment status:', error);
|
||||
} finally {
|
||||
setCheckingStatus(false);
|
||||
}
|
||||
}, [bankTransferSubmitted, refreshUser, onPaymentSuccess, toast]);
|
||||
|
||||
// Auto-check status every 30 seconds when awaiting approval
|
||||
useEffect(() => {
|
||||
if (!bankTransferSubmitted) return;
|
||||
|
||||
// Check immediately on mount
|
||||
checkPaymentStatus();
|
||||
|
||||
// Then poll every 30 seconds
|
||||
const interval = setInterval(checkPaymentStatus, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, [bankTransferSubmitted, checkPaymentStatus]);
|
||||
|
||||
// Load available payment gateways
|
||||
useEffect(() => {
|
||||
const loadGateways = async () => {
|
||||
const isPK = userCountry === 'PK';
|
||||
|
||||
setGatewaysLoading(true);
|
||||
try {
|
||||
const gateways = await getAvailablePaymentGateways();
|
||||
const gateways = await getAvailablePaymentGateways(userCountry);
|
||||
const options: PaymentOption[] = [];
|
||||
|
||||
// Always show Stripe (Credit Card) if available
|
||||
// Add Stripe if available
|
||||
if (gateways.stripe) {
|
||||
options.push({
|
||||
id: 'stripe',
|
||||
@@ -91,28 +162,26 @@ export default function PendingPaymentView({
|
||||
});
|
||||
}
|
||||
|
||||
// For Pakistan: show Bank Transfer
|
||||
// For Global: show PayPal
|
||||
if (isPakistan) {
|
||||
if (gateways.manual) {
|
||||
options.push({
|
||||
id: 'bank_transfer',
|
||||
type: 'manual',
|
||||
name: 'Bank Transfer',
|
||||
description: 'Pay via local bank transfer (PKR)',
|
||||
icon: <Building2Icon className="w-6 h-6" />,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (gateways.paypal) {
|
||||
options.push({
|
||||
id: 'paypal',
|
||||
type: 'paypal',
|
||||
name: 'PayPal',
|
||||
description: 'Pay with your PayPal account',
|
||||
icon: <PayPalIcon className="w-6 h-6" />,
|
||||
});
|
||||
}
|
||||
// Add PayPal if available (Global users only, not PK)
|
||||
if (gateways.paypal) {
|
||||
options.push({
|
||||
id: 'paypal',
|
||||
type: 'paypal',
|
||||
name: 'PayPal',
|
||||
description: 'Pay with your PayPal account',
|
||||
icon: <PayPalIcon className="w-6 h-6" />,
|
||||
});
|
||||
}
|
||||
|
||||
// Add Bank Transfer if available (Pakistan users only)
|
||||
if (gateways.manual) {
|
||||
options.push({
|
||||
id: 'bank_transfer',
|
||||
type: 'manual',
|
||||
name: 'Bank Transfer',
|
||||
description: 'Pay via local bank transfer (PKR equivalent)',
|
||||
icon: <Building2Icon className="w-6 h-6" />,
|
||||
});
|
||||
}
|
||||
|
||||
setPaymentOptions(options);
|
||||
@@ -135,7 +204,7 @@ export default function PendingPaymentView({
|
||||
};
|
||||
|
||||
loadGateways();
|
||||
}, [isPakistan]);
|
||||
}, [userCountry]);
|
||||
|
||||
const handlePayNow = async () => {
|
||||
if (!invoice) {
|
||||
@@ -187,7 +256,8 @@ export default function PendingPaymentView({
|
||||
invoice={invoice}
|
||||
onSuccess={() => {
|
||||
setShowBankTransfer(false);
|
||||
onPaymentSuccess();
|
||||
setBankTransferSubmitted(true);
|
||||
// Don't call onPaymentSuccess immediately - wait for approval
|
||||
}}
|
||||
onCancel={() => setShowBankTransfer(false)}
|
||||
/>
|
||||
@@ -196,6 +266,132 @@ export default function PendingPaymentView({
|
||||
);
|
||||
}
|
||||
|
||||
// If bank transfer was submitted - show awaiting approval state
|
||||
if (bankTransferSubmitted) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-amber-50 via-white to-orange-50 dark:from-gray-900 dark:via-gray-900 dark:to-amber-950 py-12 px-4">
|
||||
<div className="max-w-xl mx-auto">
|
||||
{/* Header with Awaiting Badge */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-amber-100 dark:bg-amber-900/30 mb-4 animate-pulse">
|
||||
<Loader2Icon className="w-10 h-10 text-amber-600 dark:text-amber-400 animate-spin" />
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-2 mb-3">
|
||||
<Badge variant="soft" tone="warning" size="md">
|
||||
Awaiting Approval
|
||||
</Badge>
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold text-gray-900 dark:text-white mb-2">
|
||||
Payment Submitted!
|
||||
</h1>
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
Your bank transfer for <strong>{planName}</strong> is being verified
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Status Card */}
|
||||
<Card className="p-6 mb-6 border-2 border-amber-200 dark:border-amber-800 bg-amber-50/50 dark:bg-amber-900/10">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-amber-200 dark:bg-amber-800 rounded-full">
|
||||
<Building2Icon className="w-5 h-5 text-amber-700 dark:text-amber-300" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-amber-900 dark:text-amber-100">Bank Transfer</h3>
|
||||
<p className="text-sm text-amber-700 dark:text-amber-400">Manual verification required</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 py-4 border-t border-b border-amber-200 dark:border-amber-800">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-gray-600 dark:text-gray-400">{planName} Plan</span>
|
||||
<span className="text-gray-900 dark:text-white">${planPrice} USD</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-gray-600 dark:text-gray-400">Amount Transferred (PKR)</span>
|
||||
<span className="font-medium text-amber-700 dark:text-amber-300">PKR {pkrEquivalent.toLocaleString()}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Info Pointers */}
|
||||
<Card className="p-6 mb-6 border border-gray-200 dark:border-gray-700">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
|
||||
<CheckCircleIcon className="w-5 h-5 text-brand-500" />
|
||||
What happens next?
|
||||
</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-brand-100 dark:bg-brand-900/30 text-brand-600 dark:text-brand-400 text-sm font-bold shrink-0 mt-0.5">1</div>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-white">Verification in Progress</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Our team is reviewing your payment</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-brand-100 dark:bg-brand-900/30 text-brand-600 dark:text-brand-400 text-sm font-bold shrink-0 mt-0.5">2</div>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-white">Email Confirmation</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">You'll receive an email once approved</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex items-center justify-center w-6 h-6 rounded-full bg-brand-100 dark:bg-brand-900/30 text-brand-600 dark:text-brand-400 text-sm font-bold shrink-0 mt-0.5">3</div>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-white">Account Activated</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Your subscription will be activated automatically</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Time Estimate Badge */}
|
||||
<div className="flex items-center justify-center gap-2 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-xl border border-blue-200 dark:border-blue-800">
|
||||
<AlertCircleIcon className="w-5 h-5 text-blue-600 dark:text-blue-400" />
|
||||
<p className="text-sm text-blue-800 dark:text-blue-200">
|
||||
<strong>Expected approval time:</strong> Within 24 hours (usually faster)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Check Status Button */}
|
||||
<Button
|
||||
variant="outline"
|
||||
tone="brand"
|
||||
size="lg"
|
||||
onClick={checkPaymentStatus}
|
||||
disabled={checkingStatus}
|
||||
className="w-full mt-6"
|
||||
>
|
||||
{checkingStatus ? (
|
||||
<span className="flex items-center justify-center gap-2">
|
||||
<Loader2Icon className="w-5 h-5 animate-spin" />
|
||||
Checking status...
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center justify-center gap-2">
|
||||
<RefreshCwIcon className="w-5 h-5" />
|
||||
Check Payment Status
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<p className="text-xs text-center text-gray-500 dark:text-gray-400 mt-2">
|
||||
Status is checked automatically every 30 seconds
|
||||
</p>
|
||||
|
||||
{/* Disabled Payment Options Notice */}
|
||||
<div className="mt-6 p-4 bg-gray-100 dark:bg-gray-800 rounded-xl opacity-60">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<LockIcon className="w-4 h-4 text-gray-500" />
|
||||
<span className="text-sm font-medium text-gray-600 dark:text-gray-400">Payment options disabled</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-500">
|
||||
Other payment methods are disabled while your bank transfer is being verified.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-brand-50 dark:from-gray-900 dark:via-gray-900 dark:to-brand-950 py-12 px-4">
|
||||
<div className="max-w-xl mx-auto">
|
||||
@@ -222,13 +418,24 @@ export default function PendingPaymentView({
|
||||
<div className="space-y-3 py-4 border-t border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-gray-600 dark:text-gray-400">{planName} Plan (Monthly)</span>
|
||||
<span className="text-gray-900 dark:text-white">${planPrice}</span>
|
||||
<span className="text-gray-900 dark:text-white">${planPrice} USD</span>
|
||||
</div>
|
||||
{showPKREquivalent && (
|
||||
<div className="flex justify-between text-sm text-brand-600 dark:text-brand-400 font-medium">
|
||||
<span>Bank Transfer Amount (PKR)</span>
|
||||
<span>PKR {pkrEquivalent.toLocaleString()}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between mt-4">
|
||||
<span className="text-lg font-semibold text-gray-900 dark:text-white">Total</span>
|
||||
<span className="text-2xl font-bold text-brand-600 dark:text-brand-400">${planPrice}</span>
|
||||
<div className="text-right">
|
||||
<span className="text-2xl font-bold text-brand-600 dark:text-brand-400">${planPrice} USD</span>
|
||||
{showPKREquivalent && (
|
||||
<div className="text-sm font-medium text-brand-500">≈ PKR {pkrEquivalent.toLocaleString()}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -320,16 +527,16 @@ export default function PendingPaymentView({
|
||||
Processing...
|
||||
</span>
|
||||
) : selectedGateway === 'manual' ? (
|
||||
'Continue to Bank Transfer'
|
||||
'Continue to Bank Transfer Details'
|
||||
) : (
|
||||
`Pay $${planPrice} Now`
|
||||
`Pay $${planPrice} USD Now`
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Info text */}
|
||||
<p className="mt-4 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
{selectedGateway === 'manual'
|
||||
? 'You will receive bank details to complete your transfer'
|
||||
? 'View bank account details and submit your transfer proof'
|
||||
: 'You will be redirected to complete payment securely'
|
||||
}
|
||||
</p>
|
||||
|
||||
@@ -166,7 +166,10 @@ const LayoutContent: React.FC = () => {
|
||||
>
|
||||
<AppHeader />
|
||||
{/* Pending Payment Banner - Shows when account status is 'pending_payment' */}
|
||||
<PendingPaymentBanner className="mx-4 mt-2 md:mx-6 md:mt-2" />
|
||||
{/* Hidden on /account/plans since PendingPaymentView handles it there */}
|
||||
{!window.location.pathname.startsWith('/account/plans') && (
|
||||
<PendingPaymentBanner className="mx-4 mt-2 md:mx-6 md:mt-2" />
|
||||
)}
|
||||
<div className="p-3">
|
||||
<PageLoaderWrapper>
|
||||
<Outlet />
|
||||
|
||||
@@ -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 ${
|
||||
|
||||
@@ -340,11 +340,11 @@ export default function UsageDashboardPage() {
|
||||
{/* SECTION 1: Credit Overview - Hero Stats */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Main Credit Card */}
|
||||
<Card className="lg:col-span-2 p-6 bg-gradient-to-br from-brand-50 to-purple-50 dark:from-brand-900/20 dark:to-purple-900/20 border-0">
|
||||
<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>
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-1">Credit Balance</h2>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">Your available credits for AI operations</p>
|
||||
<h2 className="text-lg font-semibold text-brand-900 dark:text-white mb-1">Credit Balance</h2>
|
||||
<p className="text-sm text-brand-700 dark:text-brand-200">Your available credits for AI operations</p>
|
||||
</div>
|
||||
<Link to="/account/plans">
|
||||
<Button size="sm" variant="primary" tone="brand">
|
||||
@@ -355,30 +355,30 @@ export default function UsageDashboardPage() {
|
||||
|
||||
<div className="grid grid-cols-3 gap-6">
|
||||
<div>
|
||||
<div className="text-4xl font-bold text-brand-600 dark:text-brand-400 mb-1">
|
||||
<div className="text-4xl font-bold text-brand-700 dark:text-brand-400 mb-1">
|
||||
{creditBalance?.credits.toLocaleString() || 0}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">Available Now</div>
|
||||
<div className="text-sm text-brand-600 dark:text-brand-300">Available Now</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-4xl font-bold text-purple-600 dark:text-purple-400 mb-1">
|
||||
<div className="text-4xl font-bold text-purple-700 dark:text-purple-400 mb-1">
|
||||
{creditBalance?.credits_used_this_month.toLocaleString() || 0}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">Used This Month</div>
|
||||
<div className="text-sm text-purple-600 dark:text-purple-300">Used This Month</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-4xl font-bold text-gray-900 dark:text-white mb-1">
|
||||
<div className="text-4xl font-bold text-indigo-800 dark:text-white mb-1">
|
||||
{creditBalance?.plan_credits_per_month.toLocaleString() || 0}
|
||||
</div>
|
||||
<div className="text-sm text-gray-600 dark:text-gray-400">Monthly Allowance</div>
|
||||
<div className="text-sm text-indigo-600 dark:text-indigo-300">Monthly Allowance</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Credit Usage Bar */}
|
||||
<div className="mt-6">
|
||||
<div className="flex justify-between text-sm mb-2">
|
||||
<span className="text-gray-600 dark:text-gray-400">Monthly Usage</span>
|
||||
<span className="font-medium text-gray-900 dark:text-white">{creditPercentage}%</span>
|
||||
<span className="text-brand-700 dark:text-brand-300">Monthly Usage</span>
|
||||
<span className="font-medium text-brand-900 dark:text-white">{creditPercentage}%</span>
|
||||
</div>
|
||||
<div className="h-3 bg-white/50 dark:bg-gray-800/50 rounded-full overflow-hidden">
|
||||
<div
|
||||
|
||||
@@ -493,13 +493,29 @@ export async function getInvoiceDetail(invoiceId: number): Promise<Invoice> {
|
||||
}
|
||||
|
||||
export async function downloadInvoicePDF(invoiceId: number): Promise<Blob> {
|
||||
const response = await fetch(`/v1/billing/invoices/${invoiceId}/download_pdf/`, {
|
||||
const token = localStorage.getItem('access_token') ||
|
||||
(() => {
|
||||
try {
|
||||
const authStorage = localStorage.getItem('auth-storage');
|
||||
if (authStorage) {
|
||||
const parsed = JSON.parse(authStorage);
|
||||
return parsed?.state?.token || null;
|
||||
}
|
||||
} catch (e) {}
|
||||
return null;
|
||||
})();
|
||||
|
||||
// Use the full API URL from the api.ts module
|
||||
const apiUrl = (await import('./api')).API_BASE_URL;
|
||||
const response = await fetch(`${apiUrl}/v1/billing/invoices/${invoiceId}/download_pdf/`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
|
||||
'Authorization': `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error('PDF download failed:', response.status, errorText);
|
||||
throw new Error('Failed to download invoice PDF');
|
||||
}
|
||||
|
||||
@@ -1374,9 +1390,11 @@ export async function isPayPalConfigured(): Promise<boolean> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available payment gateways
|
||||
* Get available payment gateways based on user's country
|
||||
* - Pakistan (PK): Stripe + Bank Transfer (manual), NO PayPal
|
||||
* - Global: Stripe + PayPal, NO Bank Transfer
|
||||
*/
|
||||
export async function getAvailablePaymentGateways(): Promise<{
|
||||
export async function getAvailablePaymentGateways(userCountry?: string): Promise<{
|
||||
stripe: boolean;
|
||||
paypal: boolean;
|
||||
manual: boolean;
|
||||
@@ -1386,10 +1404,14 @@ export async function getAvailablePaymentGateways(): Promise<{
|
||||
isPayPalConfigured(),
|
||||
]);
|
||||
|
||||
const isPakistan = userCountry?.toUpperCase() === 'PK';
|
||||
|
||||
return {
|
||||
stripe: stripeAvailable,
|
||||
paypal: paypalAvailable,
|
||||
manual: true, // Manual payment is always available
|
||||
// PayPal: available globally EXCEPT Pakistan
|
||||
paypal: !isPakistan && paypalAvailable,
|
||||
// Manual (Bank Transfer): available for Pakistan only
|
||||
manual: isPakistan,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1404,10 +1426,14 @@ export async function subscribeToPlan(
|
||||
switch (gateway) {
|
||||
case 'stripe': {
|
||||
const session = await createStripeCheckout(planId, options);
|
||||
return { redirect_url: session.checkout_url };
|
||||
// FIX: Return URL should include session_id for verification
|
||||
const redirectUrl = new URL(session.checkout_url);
|
||||
return { redirect_url: redirectUrl.toString() };
|
||||
}
|
||||
case 'paypal': {
|
||||
const order = await createPayPalSubscriptionOrder(planId, options);
|
||||
// FIX: Store order_id in localStorage before redirect
|
||||
localStorage.setItem('paypal_order_id', order.order_id);
|
||||
return { redirect_url: order.approval_url };
|
||||
}
|
||||
case 'manual':
|
||||
@@ -1432,6 +1458,8 @@ export async function purchaseCredits(
|
||||
}
|
||||
case 'paypal': {
|
||||
const order = await createPayPalCreditOrder(packageId, options);
|
||||
// FIX: Store order_id in localStorage before redirect
|
||||
localStorage.setItem('paypal_order_id', order.order_id);
|
||||
return { redirect_url: order.approval_url };
|
||||
}
|
||||
case 'manual':
|
||||
|
||||
Reference in New Issue
Block a user