feat(billing): add missing payment methods and configurations
- Added migration to include global payment method configurations for Stripe and PayPal (both disabled). - Ensured existing payment methods like bank transfer and manual payment are correctly configured. - Added database constraints and indexes for improved data integrity in billing models. - Introduced foreign key relationship between CreditTransaction and Payment models. - Added webhook configuration fields to PaymentMethodConfig for future payment gateway integrations. - Updated SignUpFormUnified component to handle payment method selection based on user country and plan. - Implemented PaymentHistory component to display user's payment history with status indicators.
This commit is contained in:
@@ -18,6 +18,8 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
const { addError } = useErrorHandler('ProtectedRoute');
|
||||
const [showError, setShowError] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string>('');
|
||||
const [isInitializing, setIsInitializing] = useState(true);
|
||||
|
||||
const PLAN_ALLOWED_PATHS = [
|
||||
'/account/plans',
|
||||
'/account/purchase-credits',
|
||||
@@ -32,6 +34,15 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
location.pathname.startsWith(prefix)
|
||||
);
|
||||
|
||||
// Give the auth store a moment to initialize on mount
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setIsInitializing(false);
|
||||
}, 100); // Short delay to let Zustand hydrate
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
// Track loading state
|
||||
useEffect(() => {
|
||||
trackLoading('auth-loading', loading);
|
||||
@@ -82,13 +93,15 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
}
|
||||
}, [loading, addError]);
|
||||
|
||||
// Show loading state while checking authentication
|
||||
if (loading) {
|
||||
// Show loading state while checking authentication or initializing
|
||||
if (loading || isInitializing) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen bg-gray-50 dark:bg-gray-900">
|
||||
<div className="text-center max-w-md px-4">
|
||||
<div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-brand-500 mb-4"></div>
|
||||
<p className="text-lg font-medium text-gray-800 dark:text-white mb-2">Loading...</p>
|
||||
<p className="text-lg font-medium text-gray-800 dark:text-white mb-2">
|
||||
{isInitializing ? 'Initializing...' : 'Loading...'}
|
||||
</p>
|
||||
|
||||
{showError && (
|
||||
<div className="mt-4 p-4 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
|
||||
@@ -112,8 +125,9 @@ export default function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
);
|
||||
}
|
||||
|
||||
// Redirect to signin if not authenticated
|
||||
// Redirect to signin if not authenticated (after initialization period)
|
||||
if (!isAuthenticated) {
|
||||
console.log('ProtectedRoute: Not authenticated, redirecting to signin');
|
||||
return <Navigate to="/signin" state={{ from: location }} replace />;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ export default function SignUpFormSimplified({ planDetails: planDetailsProp, pla
|
||||
email: '',
|
||||
password: '',
|
||||
accountName: '',
|
||||
billingCountry: 'US', // Default to US for payment method filtering
|
||||
});
|
||||
|
||||
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('');
|
||||
@@ -91,7 +92,8 @@ export default function SignUpFormSimplified({ planDetails: planDetailsProp, pla
|
||||
setPaymentMethodsLoading(true);
|
||||
try {
|
||||
const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || 'https://api.igny8.com/api';
|
||||
const response = await fetch(`${API_BASE_URL}/v1/billing/admin/payment-methods/`);
|
||||
const country = formData.billingCountry || 'US';
|
||||
const response = await fetch(`${API_BASE_URL}/v1/billing/admin/payment-methods/?country=${country}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load payment methods');
|
||||
@@ -125,7 +127,7 @@ export default function SignUpFormSimplified({ planDetails: planDetailsProp, pla
|
||||
};
|
||||
|
||||
loadPaymentMethods();
|
||||
}, [isPaidPlan]);
|
||||
}, [isPaidPlan, formData.billingCountry]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
@@ -171,6 +173,7 @@ export default function SignUpFormSimplified({ planDetails: planDetailsProp, pla
|
||||
registerPayload.payment_method = selectedPaymentMethod;
|
||||
// Use email as billing email by default
|
||||
registerPayload.billing_email = formData.email;
|
||||
registerPayload.billing_country = formData.billingCountry;
|
||||
}
|
||||
|
||||
const user = await register(registerPayload) as any;
|
||||
@@ -314,6 +317,31 @@ export default function SignUpFormSimplified({ planDetails: planDetailsProp, pla
|
||||
{/* Payment Method Selection for Paid Plans */}
|
||||
{isPaidPlan && (
|
||||
<div className="pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
{/* Country Selection */}
|
||||
<div className="mb-5">
|
||||
<Label>
|
||||
Country<span className="text-error-500">*</span>
|
||||
</Label>
|
||||
<select
|
||||
name="billingCountry"
|
||||
value={formData.billingCountry}
|
||||
onChange={handleChange}
|
||||
className="w-full px-4 py-2.5 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:ring-2 focus:ring-brand-500 focus:border-transparent"
|
||||
>
|
||||
<option value="US">United States</option>
|
||||
<option value="GB">United Kingdom</option>
|
||||
<option value="IN">India</option>
|
||||
<option value="PK">Pakistan</option>
|
||||
<option value="CA">Canada</option>
|
||||
<option value="AU">Australia</option>
|
||||
<option value="DE">Germany</option>
|
||||
<option value="FR">France</option>
|
||||
</select>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
Payment methods will be filtered by your country
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mb-3">
|
||||
<Label>
|
||||
Payment Method<span className="text-error-500">*</span>
|
||||
|
||||
645
frontend/src/components/auth/SignUpFormUnified.tsx
Normal file
645
frontend/src/components/auth/SignUpFormUnified.tsx
Normal file
@@ -0,0 +1,645 @@
|
||||
/**
|
||||
* Unified Signup Form with Integrated Pricing Selection
|
||||
* Combines free and paid signup flows in one modern interface
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from '../../icons';
|
||||
import { CreditCard, Building2, Wallet, Check, Loader2, CheckCircle } from 'lucide-react';
|
||||
import Label from '../form/Label';
|
||||
import Input from '../form/input/InputField';
|
||||
import Checkbox from '../form/input/Checkbox';
|
||||
import Button from '../ui/button/Button';
|
||||
import SelectDropdown from '../form/SelectDropdown';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
|
||||
interface Plan {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
price: string | number;
|
||||
billing_cycle: string;
|
||||
is_active: boolean;
|
||||
max_users: number;
|
||||
max_sites: number;
|
||||
max_keywords: number;
|
||||
monthly_word_count_limit: number;
|
||||
included_credits: number;
|
||||
features: string[];
|
||||
}
|
||||
|
||||
interface PaymentMethodConfig {
|
||||
id: number;
|
||||
payment_method: string;
|
||||
display_name: string;
|
||||
instructions: string | null;
|
||||
country_code: string;
|
||||
is_enabled: boolean;
|
||||
}
|
||||
|
||||
interface SignUpFormUnifiedProps {
|
||||
plans: Plan[];
|
||||
selectedPlan: Plan | null;
|
||||
onPlanSelect: (plan: Plan) => void;
|
||||
plansLoading: boolean;
|
||||
}
|
||||
|
||||
export default function SignUpFormUnified({
|
||||
plans,
|
||||
selectedPlan,
|
||||
onPlanSelect,
|
||||
plansLoading,
|
||||
}: SignUpFormUnifiedProps) {
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [isChecked, setIsChecked] = useState(false);
|
||||
const [billingPeriod, setBillingPeriod] = useState<'monthly' | 'annually'>('monthly');
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
password: '',
|
||||
accountName: '',
|
||||
billingCountry: 'US',
|
||||
});
|
||||
|
||||
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('');
|
||||
const [paymentMethods, setPaymentMethods] = useState<PaymentMethodConfig[]>([]);
|
||||
const [paymentMethodsLoading, setPaymentMethodsLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const navigate = useNavigate();
|
||||
const { register, loading } = useAuthStore();
|
||||
|
||||
const isPaidPlan = selectedPlan && parseFloat(String(selectedPlan.price || 0)) > 0;
|
||||
|
||||
// Update URL when plan changes
|
||||
useEffect(() => {
|
||||
if (selectedPlan) {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('plan', selectedPlan.slug);
|
||||
window.history.replaceState({}, '', url.toString());
|
||||
}
|
||||
}, [selectedPlan]);
|
||||
|
||||
// Load payment methods for paid plans
|
||||
useEffect(() => {
|
||||
if (!isPaidPlan) {
|
||||
setPaymentMethods([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const loadPaymentMethods = async () => {
|
||||
setPaymentMethodsLoading(true);
|
||||
try {
|
||||
const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || 'https://api.igny8.com/api';
|
||||
const country = formData.billingCountry || 'US';
|
||||
const response = await fetch(`${API_BASE_URL}/v1/billing/payment-configs/payment-methods/?country=${country}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to load payment methods');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
let methodsList: PaymentMethodConfig[] = [];
|
||||
if (Array.isArray(data)) {
|
||||
methodsList = data;
|
||||
} else if (data.success && data.data) {
|
||||
methodsList = Array.isArray(data.data) ? data.data : data.data.results || [];
|
||||
} else if (data.results) {
|
||||
methodsList = data.results;
|
||||
}
|
||||
|
||||
const enabledMethods = methodsList.filter((m: PaymentMethodConfig) => m.is_enabled);
|
||||
setPaymentMethods(enabledMethods);
|
||||
|
||||
if (enabledMethods.length > 0 && !selectedPaymentMethod) {
|
||||
setSelectedPaymentMethod(enabledMethods[0].payment_method);
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error('Failed to load payment methods:', err);
|
||||
// Don't set error for free plans or if payment methods fail to load
|
||||
// Just log it and continue
|
||||
} finally {
|
||||
setPaymentMethodsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadPaymentMethods();
|
||||
}, [isPaidPlan, formData.billingCountry]);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
if (!formData.email || !formData.password || !formData.firstName || !formData.lastName) {
|
||||
setError('Please fill in all required fields');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isChecked) {
|
||||
setError('Please agree to the Terms and Conditions');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selectedPlan) {
|
||||
setError('Please select a plan');
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPaidPlan && !selectedPaymentMethod) {
|
||||
setError('Please select a payment method');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const username = formData.email.split('@')[0];
|
||||
|
||||
const registerPayload: any = {
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
username: username,
|
||||
first_name: formData.firstName,
|
||||
last_name: formData.lastName,
|
||||
account_name: formData.accountName,
|
||||
plan_slug: selectedPlan.slug,
|
||||
};
|
||||
|
||||
if (isPaidPlan) {
|
||||
registerPayload.payment_method = selectedPaymentMethod;
|
||||
registerPayload.billing_email = formData.email;
|
||||
registerPayload.billing_country = formData.billingCountry;
|
||||
}
|
||||
|
||||
const user = (await register(registerPayload)) as any;
|
||||
|
||||
// CRITICAL: Verify auth state is actually set in Zustand store
|
||||
// The register function should have already set isAuthenticated=true
|
||||
const currentAuthState = useAuthStore.getState();
|
||||
|
||||
console.log('Post-registration auth state check:', {
|
||||
isAuthenticated: currentAuthState.isAuthenticated,
|
||||
hasUser: !!currentAuthState.user,
|
||||
hasToken: !!currentAuthState.token,
|
||||
userData: user
|
||||
});
|
||||
|
||||
// If for some reason state wasn't set, force set it again
|
||||
if (!currentAuthState.isAuthenticated || !currentAuthState.user || !currentAuthState.token) {
|
||||
console.error('Auth state not properly set after registration, forcing update...');
|
||||
|
||||
// Extract tokens from user data if available
|
||||
const tokenData = user?.tokens || {};
|
||||
const accessToken = user?.access || tokenData.access || localStorage.getItem('access_token');
|
||||
const refreshToken = user?.refresh || tokenData.refresh || localStorage.getItem('refresh_token');
|
||||
|
||||
// Force set the state
|
||||
useAuthStore.setState({
|
||||
user: user,
|
||||
token: accessToken,
|
||||
refreshToken: refreshToken,
|
||||
isAuthenticated: true,
|
||||
loading: false
|
||||
});
|
||||
|
||||
// Wait a bit for state to propagate
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
|
||||
// Final verification before navigation
|
||||
const finalState = useAuthStore.getState();
|
||||
if (!finalState.isAuthenticated) {
|
||||
throw new Error('Failed to authenticate after registration. Please try logging in manually.');
|
||||
}
|
||||
|
||||
const status = user?.account?.status;
|
||||
if (status === 'pending_payment') {
|
||||
navigate('/account/plans', { replace: true });
|
||||
} else {
|
||||
navigate('/sites', { replace: true });
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Registration failed. Please try again.');
|
||||
}
|
||||
};
|
||||
|
||||
const getPaymentIcon = (method: string) => {
|
||||
switch (method) {
|
||||
case 'stripe':
|
||||
return <CreditCard className="w-5 h-5" />;
|
||||
case 'bank_transfer':
|
||||
return <Building2 className="w-5 h-5" />;
|
||||
case 'local_wallet':
|
||||
return <Wallet className="w-5 h-5" />;
|
||||
default:
|
||||
return <CreditCard className="w-5 h-5" />;
|
||||
}
|
||||
};
|
||||
|
||||
const formatNumber = (num: number): string => {
|
||||
if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;
|
||||
if (num >= 1000) return `${(num / 1000).toFixed(0)}K`;
|
||||
return num.toString();
|
||||
};
|
||||
|
||||
const extractFeatures = (plan: Plan): string[] => {
|
||||
const features: string[] = [];
|
||||
features.push(`${plan.max_sites} ${plan.max_sites === 1 ? 'Site' : 'Sites'}`);
|
||||
features.push(`${plan.max_users} ${plan.max_users === 1 ? 'User' : 'Users'}`);
|
||||
features.push(`${formatNumber(plan.max_keywords || 0)} Keywords`);
|
||||
features.push(`${formatNumber(plan.monthly_word_count_limit || 0)} Words/Month`);
|
||||
features.push(`${formatNumber(plan.included_credits || 0)} AI Credits`);
|
||||
return features;
|
||||
};
|
||||
|
||||
const getDisplayPrice = (plan: Plan): number => {
|
||||
const monthlyPrice = typeof plan.price === 'number' ? plan.price : parseFloat(String(plan.price || 0));
|
||||
if (billingPeriod === 'annually') {
|
||||
return monthlyPrice * 12 * 0.85; // 15% discount
|
||||
}
|
||||
return monthlyPrice;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col lg:w-1/2 w-full">
|
||||
{/* Mobile Pricing Toggle */}
|
||||
<div className="lg:hidden bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="relative inline-flex p-1 bg-gray-100 dark:bg-gray-800 rounded-lg shadow-sm">
|
||||
<span
|
||||
className={`absolute top-1/2 left-1 flex h-9 w-28 -translate-y-1/2 rounded-md bg-gradient-to-br from-brand-500 to-brand-600 shadow-md transition-all duration-300 ease-out ${
|
||||
billingPeriod === 'monthly' ? 'translate-x-0' : 'translate-x-28'
|
||||
}`}
|
||||
></span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBillingPeriod('monthly')}
|
||||
className={`relative flex h-9 w-28 items-center justify-center text-sm font-semibold transition-all duration-200 rounded-md ${
|
||||
billingPeriod === 'monthly' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
Monthly
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBillingPeriod('annually')}
|
||||
className={`relative flex h-9 w-28 items-center justify-center text-sm font-semibold transition-all duration-200 rounded-md ${
|
||||
billingPeriod === 'annually' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
Annually
|
||||
</button>
|
||||
</div>
|
||||
<div className="h-6 flex items-center justify-center">
|
||||
<span className={`inline-flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400 font-semibold bg-green-50 dark:bg-green-900/20 px-2 py-1 rounded-full transition-opacity duration-200 ${
|
||||
billingPeriod === 'annually' ? 'opacity-100' : 'opacity-0'
|
||||
}`}>
|
||||
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
Save 15%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto no-scrollbar flex items-center">
|
||||
<div className="w-full max-w-md mx-auto p-6 sm:p-8">
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-flex items-center text-sm text-gray-500 transition-colors hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 mb-6"
|
||||
>
|
||||
<ChevronLeftIcon className="size-5" />
|
||||
Back to dashboard
|
||||
</Link>
|
||||
|
||||
<div className="mb-6">
|
||||
<h1 className="mb-2 font-semibold text-gray-800 dark:text-white text-2xl">Sign Up for {selectedPlan?.name || 'IGNY8'}</h1>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Complete your registration and select a payment method.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Plan Selection - Mobile */}
|
||||
<div className="lg:hidden mb-6">
|
||||
<Label>Select Plan</Label>
|
||||
<div className="grid grid-cols-2 gap-2 mt-2">
|
||||
{plans.map((plan) => {
|
||||
const displayPrice = getDisplayPrice(plan);
|
||||
const isSelected = selectedPlan?.id === plan.id;
|
||||
const isFree = parseFloat(String(plan.price || 0)) === 0;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={plan.id}
|
||||
onClick={() => onPlanSelect(plan)}
|
||||
className={`p-3 rounded-lg border-2 text-left transition-all ${
|
||||
isSelected
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className={`font-semibold text-sm ${isSelected ? 'text-brand-600 dark:text-brand-400' : 'text-gray-900 dark:text-white'}`}>
|
||||
{plan.name}
|
||||
</span>
|
||||
{isSelected && <CheckCircle className="w-4 h-4 text-brand-500" />}
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-900 dark:text-white">
|
||||
{isFree ? 'Free' : `$${displayPrice.toFixed(2)}`}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{billingPeriod === 'annually' && !isFree ? '/year' : '/month'}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg dark:bg-red-900/20 dark:text-red-400 dark:border-red-800">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<Label>
|
||||
First Name<span className="text-error-500">*</span>
|
||||
</Label>
|
||||
<Input type="text" name="firstName" value={formData.firstName} onChange={handleChange} placeholder="Enter your first name" />
|
||||
</div>
|
||||
<div>
|
||||
<Label>
|
||||
Last Name<span className="text-error-500">*</span>
|
||||
</Label>
|
||||
<Input type="text" name="lastName" value={formData.lastName} onChange={handleChange} placeholder="Enter your last name" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>
|
||||
Email<span className="text-error-500">*</span>
|
||||
</Label>
|
||||
<Input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="Enter your email" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Account Name (optional)</Label>
|
||||
<Input type="text" name="accountName" value={formData.accountName} onChange={handleChange} placeholder="Workspace / Company name" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>
|
||||
Password<span className="text-error-500">*</span>
|
||||
</Label>
|
||||
<div className="relative">
|
||||
<Input placeholder="Enter your password" type={showPassword ? 'text' : 'password'} name="password" value={formData.password} onChange={handleChange} />
|
||||
<span onClick={() => setShowPassword(!showPassword)} className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2">
|
||||
{showPassword ? <EyeIcon className="fill-gray-500 dark:fill-gray-400 size-5" /> : <EyeCloseIcon className="fill-gray-500 dark:fill-gray-400 size-5" />}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isPaidPlan && (
|
||||
<div className="pt-4 border-t border-gray-200 dark:border-gray-700 space-y-4">
|
||||
<div>
|
||||
<Label>
|
||||
Country<span className="text-error-500">*</span>
|
||||
</Label>
|
||||
<SelectDropdown
|
||||
options={[
|
||||
{ value: 'US', label: '🇺🇸 United States' },
|
||||
{ value: 'GB', label: '🇬🇧 United Kingdom' },
|
||||
{ value: 'IN', label: '🇮🇳 India' },
|
||||
{ value: 'PK', label: '🇵🇰 Pakistan' },
|
||||
{ value: 'CA', label: '🇨🇦 Canada' },
|
||||
{ value: 'AU', label: '🇦🇺 Australia' },
|
||||
{ value: 'DE', label: '🇩🇪 Germany' },
|
||||
{ value: 'FR', label: '🇫🇷 France' },
|
||||
]}
|
||||
value={formData.billingCountry}
|
||||
onChange={(value) => setFormData((prev) => ({ ...prev, billingCountry: value }))}
|
||||
className="text-base"
|
||||
/>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Payment methods will be filtered by your country</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>
|
||||
Payment Method<span className="text-error-500">*</span>
|
||||
</Label>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1 mb-2">Select how you'd like to pay for your subscription</p>
|
||||
|
||||
{paymentMethodsLoading ? (
|
||||
<div className="flex items-center justify-center p-6 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-brand-500 mr-2" />
|
||||
<span className="text-sm text-gray-600 dark:text-gray-400">Loading payment options...</span>
|
||||
</div>
|
||||
) : paymentMethods.length === 0 ? (
|
||||
<div className="p-4 bg-amber-50 border border-amber-200 rounded-lg text-amber-800 dark:bg-amber-900/20 dark:border-amber-800 dark:text-amber-200">
|
||||
<p className="text-sm">No payment methods available. Please contact support.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{paymentMethods.map((method) => (
|
||||
<div
|
||||
key={method.id}
|
||||
onClick={() => setSelectedPaymentMethod(method.payment_method)}
|
||||
className={`relative p-4 rounded-lg border-2 cursor-pointer transition-all ${
|
||||
selectedPaymentMethod === method.payment_method
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20'
|
||||
: 'border-gray-200 hover:border-gray-300 dark:border-gray-700 dark:hover:border-gray-600'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div
|
||||
className={`flex items-center justify-center w-10 h-10 rounded-lg ${
|
||||
selectedPaymentMethod === method.payment_method ? 'bg-brand-500 text-white' : 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{getPaymentIcon(method.payment_method)}
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center justify-between">
|
||||
<h4 className="font-semibold text-gray-900 dark:text-white">{method.display_name}</h4>
|
||||
{selectedPaymentMethod === method.payment_method && <Check className="w-5 h-5 text-brand-500" />}
|
||||
</div>
|
||||
{method.instructions && <p className="text-xs text-gray-500 dark:text-gray-400 mt-1 whitespace-pre-line">{method.instructions}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-start gap-3 pt-2">
|
||||
<Checkbox className="w-5 h-5 mt-0.5" checked={isChecked} onChange={setIsChecked} />
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
By creating an account means you agree to the <span className="text-gray-800 dark:text-white/90">Terms and Conditions</span>, and our{' '}
|
||||
<span className="text-gray-800 dark:text-white">Privacy Policy</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button type="submit" variant="primary" disabled={loading} className="w-full">
|
||||
{loading ? (
|
||||
<span className="flex items-center justify-center">
|
||||
<Loader2 className="w-4 h-4 animate-spin mr-2" />
|
||||
Creating your account...
|
||||
</span>
|
||||
) : isPaidPlan ? (
|
||||
'Create Account & Continue to Payment'
|
||||
) : (
|
||||
'Start Free Trial'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-5 text-center">
|
||||
<p className="text-sm text-gray-700 dark:text-gray-400">
|
||||
Already have an account?{' '}
|
||||
<Link to="/signin" className="text-brand-500 hover:text-brand-600 dark:text-brand-400 font-medium">
|
||||
Sign In
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Desktop Pricing Panel - Renders in right side */}
|
||||
<div className="hidden lg:block">
|
||||
{/* This will be portaled to the right side */}
|
||||
{typeof document !== 'undefined' &&
|
||||
document.getElementById('signup-pricing-plans') &&
|
||||
ReactDOM.createPortal(
|
||||
<div className="space-y-8">
|
||||
{/* Billing Toggle - Improved UI */}
|
||||
<div className="text-center space-y-3">
|
||||
<div className="relative inline-flex p-1 bg-gray-100 dark:bg-gray-800 rounded-xl shadow-sm">
|
||||
<span
|
||||
className={`absolute top-1/2 left-1 flex h-11 w-32 -translate-y-1/2 rounded-lg bg-gradient-to-br from-brand-500 to-brand-600 shadow-md transition-all duration-300 ease-out ${
|
||||
billingPeriod === 'monthly' ? 'translate-x-0' : 'translate-x-32'
|
||||
}`}
|
||||
></span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBillingPeriod('monthly')}
|
||||
className={`relative flex h-11 w-32 items-center justify-center text-base font-semibold transition-all duration-200 rounded-lg ${
|
||||
billingPeriod === 'monthly' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
Monthly
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBillingPeriod('annually')}
|
||||
className={`relative flex h-11 w-32 items-center justify-center text-base font-semibold transition-all duration-200 rounded-lg ${
|
||||
billingPeriod === 'annually' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
Annually
|
||||
</button>
|
||||
</div>
|
||||
<div className="h-7 flex items-center justify-center">
|
||||
<p className={`inline-flex items-center gap-1.5 text-green-600 dark:text-green-400 text-sm font-semibold bg-green-50 dark:bg-green-900/20 px-3 py-1.5 rounded-full transition-opacity duration-200 ${
|
||||
billingPeriod === 'annually' ? 'opacity-100' : 'opacity-0'
|
||||
}`}>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
Save 15% with annual billing
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Plan Cards - 2 columns, wider cards, no buttons */}
|
||||
<div className="grid gap-5 grid-cols-1 xl:grid-cols-2">
|
||||
{plans.map((plan) => {
|
||||
const displayPrice = getDisplayPrice(plan);
|
||||
const features = extractFeatures(plan);
|
||||
const isSelected = selectedPlan?.id === plan.id;
|
||||
const isFree = parseFloat(String(plan.price || 0)) === 0;
|
||||
const isPopular = plan.slug.toLowerCase().includes('growth');
|
||||
|
||||
return (
|
||||
<div
|
||||
key={plan.id}
|
||||
onClick={() => onPlanSelect(plan)}
|
||||
className={`relative rounded-2xl p-6 cursor-pointer transition-all duration-300 border-2 ${
|
||||
isSelected
|
||||
? 'border-brand-500 bg-white dark:bg-gray-800 shadow-2xl ring-4 ring-brand-500/20'
|
||||
: isPopular
|
||||
? 'border-brand-200 dark:border-brand-800 bg-white dark:bg-gray-800/50 hover:shadow-xl'
|
||||
: 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/50 hover:shadow-lg'
|
||||
}`}
|
||||
>
|
||||
{isPopular && !isSelected && (
|
||||
<div className="absolute -top-3 left-1/2 -translate-x-1/2">
|
||||
<span className="bg-gradient-to-r from-green-500 to-emerald-500 text-white text-xs font-bold px-3 py-1 rounded-full shadow-lg">
|
||||
⭐ POPULAR
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{isSelected && (
|
||||
<div className="absolute -top-4 -right-4">
|
||||
<div className="bg-brand-500 rounded-full p-2 shadow-lg">
|
||||
<CheckCircle className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-5">
|
||||
<h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">{plan.name}</h3>
|
||||
<div className="flex items-baseline gap-1">
|
||||
<span className="text-4xl font-bold text-gray-900 dark:text-white">
|
||||
{isFree ? 'Free' : `$${displayPrice.toFixed(2)}`}
|
||||
</span>
|
||||
<div className="h-5 flex items-center">
|
||||
{!isFree && (
|
||||
<span className="text-gray-500 dark:text-gray-400 text-sm">
|
||||
{billingPeriod === 'annually' ? '/year' : '/month'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-5">
|
||||
{billingPeriod === 'annually' && !isFree && (
|
||||
<p className="text-gray-500 dark:text-gray-400 text-xs">
|
||||
${(displayPrice / 12).toFixed(2)}/month billed annually
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Features - 3 rows x 2 columns = 6 features */}
|
||||
<div className="grid grid-cols-2 gap-x-3 gap-y-2.5">
|
||||
{features.slice(0, 6).map((feature, idx) => (
|
||||
<div key={idx} className="flex items-start gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-green-500 dark:text-green-400 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300 leading-tight">{feature}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>,
|
||||
document.getElementById('signup-pricing-plans')!
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -29,7 +29,8 @@ interface PaymentConfirmationModalProps {
|
||||
invoice: {
|
||||
id: number;
|
||||
invoice_number: string;
|
||||
total_amount: string; // Backend returns 'total_amount' in API response
|
||||
total?: string; // For backward compatibility
|
||||
total_amount?: string; // Backend returns 'total_amount'
|
||||
currency?: string;
|
||||
};
|
||||
paymentMethod: {
|
||||
@@ -110,6 +111,10 @@ export default function PaymentConfirmationModal({
|
||||
return;
|
||||
}
|
||||
|
||||
// Create AbortController for timeout handling
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 30000); // 30 second timeout
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
@@ -121,16 +126,19 @@ export default function PaymentConfirmationModal({
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
invoice_id: invoice.id,
|
||||
payment_method: paymentMethod.payment_method,
|
||||
amount: invoice.total_amount,
|
||||
amount: invoice.total_amount || invoice.total || '0', // Handle both field names
|
||||
manual_reference: formData.manual_reference.trim(),
|
||||
manual_notes: formData.manual_notes.trim() || undefined,
|
||||
proof_url: formData.proof_url || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
@@ -139,7 +147,7 @@ export default function PaymentConfirmationModal({
|
||||
|
||||
setSuccess(true);
|
||||
|
||||
// Show success message for 2 seconds, then close and call onSuccess
|
||||
// Show success message for 5 seconds (increased from 2s), then close and call onSuccess
|
||||
setTimeout(() => {
|
||||
onClose();
|
||||
onSuccess?.();
|
||||
@@ -148,9 +156,14 @@ export default function PaymentConfirmationModal({
|
||||
setUploadedFile(null);
|
||||
setUploadedFileName('');
|
||||
setSuccess(false);
|
||||
}, 2000);
|
||||
}, 5000);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to submit payment confirmation');
|
||||
clearTimeout(timeoutId);
|
||||
if (err.name === 'AbortError') {
|
||||
setError('Request timeout. Please check your connection and try again.');
|
||||
} else {
|
||||
setError(err.message || 'Failed to submit payment confirmation');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -197,7 +210,7 @@ export default function PaymentConfirmationModal({
|
||||
<div>
|
||||
<span className="text-gray-600 dark:text-gray-400">Amount:</span>
|
||||
<p className="font-semibold text-gray-900 dark:text-white">
|
||||
{invoice.currency || 'USD'} {invoice.total_amount}
|
||||
{invoice.currency?.toUpperCase() || 'USD'} {parseFloat(invoice.total_amount || invoice.total || '0').toFixed(2)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
|
||||
175
frontend/src/components/billing/PaymentHistory.tsx
Normal file
175
frontend/src/components/billing/PaymentHistory.tsx
Normal file
@@ -0,0 +1,175 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { API_BASE_URL } from '../../services/api';
|
||||
import Button from '../ui/button/Button';
|
||||
import { CheckCircle, XCircle, Clock, RefreshCw } from 'lucide-react';
|
||||
|
||||
interface Payment {
|
||||
id: number;
|
||||
invoice_id: number;
|
||||
invoice_number: string;
|
||||
amount: string;
|
||||
currency: string;
|
||||
status: string;
|
||||
payment_method: string;
|
||||
created_at: string;
|
||||
processed_at?: string;
|
||||
manual_reference?: string;
|
||||
manual_notes?: string;
|
||||
}
|
||||
|
||||
export default function PaymentHistory() {
|
||||
const [payments, setPayments] = useState<Payment[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const { token } = useAuthStore();
|
||||
|
||||
useEffect(() => {
|
||||
loadPayments();
|
||||
}, []);
|
||||
|
||||
const loadPayments = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(`${API_BASE_URL}/v1/billing/payments/`, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
setPayments(data.results || []);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('Failed to load payment history');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'succeeded':
|
||||
return <CheckCircle className="w-5 h-5 text-green-500" />;
|
||||
case 'failed':
|
||||
return <XCircle className="w-5 h-5 text-red-500" />;
|
||||
case 'pending_approval':
|
||||
return <Clock className="w-5 h-5 text-yellow-500" />;
|
||||
default:
|
||||
return <Clock className="w-5 h-5 text-gray-500" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
const badges = {
|
||||
succeeded: 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400',
|
||||
failed: 'bg-red-100 text-red-800 dark:bg-red-900/20 dark:text-red-400',
|
||||
pending_approval: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/20 dark:text-yellow-400',
|
||||
refunded: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-400',
|
||||
};
|
||||
return badges[status as keyof typeof badges] || badges.pending_approval;
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
});
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center p-12">
|
||||
<RefreshCw className="w-8 h-8 animate-spin text-gray-400" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h2 className="text-2xl font-semibold text-gray-900 dark:text-white">
|
||||
Payment History
|
||||
</h2>
|
||||
<Button onClick={loadPayments} variant="outline" size="sm">
|
||||
<RefreshCw className="w-4 h-4 mr-2" />
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-600 dark:bg-red-900/20 dark:border-red-800">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{payments.length === 0 ? (
|
||||
<div className="text-center py-12 text-gray-500 dark:text-gray-400">
|
||||
<p>No payment history yet</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-800">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Invoice
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Amount
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Method
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Status
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Date
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Reference
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{payments.map((payment) => (
|
||||
<tr key={payment.id} className="hover:bg-gray-50 dark:hover:bg-gray-800">
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
|
||||
#{payment.invoice_number}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
|
||||
{payment.currency} {payment.amount}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
|
||||
{payment.payment_method.replace('_', ' ')}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="flex items-center gap-2">
|
||||
{getStatusIcon(payment.status)}
|
||||
<span className={`px-2 py-1 text-xs font-medium rounded-full ${getStatusBadge(payment.status)}`}>
|
||||
{payment.status.replace('_', ' ')}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
|
||||
{formatDate(payment.created_at)}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-600 dark:text-gray-400">
|
||||
{payment.manual_reference || '-'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,8 @@ import PaymentConfirmationModal from './PaymentConfirmationModal';
|
||||
interface Invoice {
|
||||
id: number;
|
||||
invoice_number: string;
|
||||
total_amount: string; // Backend returns 'total_amount' in serialized response
|
||||
total?: string; // For backward compatibility
|
||||
total_amount?: string; // Backend returns 'total_amount'
|
||||
currency: string;
|
||||
status: string;
|
||||
due_date?: string;
|
||||
@@ -65,9 +66,9 @@ export default function PendingPaymentBanner({ className = '' }: PendingPaymentB
|
||||
if (response.ok && data.success && data.results?.length > 0) {
|
||||
setInvoice(data.results[0]);
|
||||
|
||||
// Load payment method if available
|
||||
// Load payment method if available - use public endpoint
|
||||
const country = (user?.account as any)?.billing_country || 'US';
|
||||
const pmResponse = await fetch(`${API_BASE_URL}/v1/billing/admin/payment-methods/?country=${country}`, {
|
||||
const pmResponse = await fetch(`${API_BASE_URL}/v1/billing/payment-configs/payment-methods/?country=${country}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -75,8 +76,10 @@ export default function PendingPaymentBanner({ className = '' }: PendingPaymentB
|
||||
});
|
||||
|
||||
const pmData = await pmResponse.json();
|
||||
// API returns array directly from DRF Response
|
||||
if (pmResponse.ok && Array.isArray(pmData) && pmData.length > 0) {
|
||||
// Use public endpoint response format
|
||||
if (pmResponse.ok && pmData.success && pmData.results?.length > 0) {
|
||||
setPaymentMethod(pmData.results[0]);
|
||||
} else if (pmResponse.ok && Array.isArray(pmData) && pmData.length > 0) {
|
||||
setPaymentMethod(pmData[0]);
|
||||
}
|
||||
}
|
||||
@@ -123,10 +126,15 @@ export default function PendingPaymentBanner({ className = '' }: PendingPaymentB
|
||||
<p className="mt-1 text-sm text-amber-800 dark:text-amber-200">
|
||||
Your account is pending payment. Please complete your payment to activate your subscription.
|
||||
</p>
|
||||
<div className="mt-3">
|
||||
<div className="mt-3 flex gap-2">
|
||||
<Link to="/account/plans">
|
||||
<Button variant="primary" size="sm">
|
||||
View Billing Details
|
||||
Complete Payment
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to="/dashboard">
|
||||
<Button variant="outline" size="sm">
|
||||
Go to Dashboard
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
@@ -251,13 +259,17 @@ export default function PendingPaymentBanner({ className = '' }: PendingPaymentB
|
||||
</div>
|
||||
|
||||
{/* Payment Confirmation Modal */}
|
||||
{showPaymentModal && invoice && paymentMethod && (
|
||||
{showPaymentModal && invoice && (
|
||||
<PaymentConfirmationModal
|
||||
isOpen={showPaymentModal}
|
||||
onClose={() => setShowPaymentModal(false)}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
invoice={invoice}
|
||||
paymentMethod={paymentMethod}
|
||||
paymentMethod={paymentMethod || {
|
||||
payment_method: 'bank_transfer',
|
||||
display_name: 'Bank Transfer',
|
||||
country_code: 'US'
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -1,7 +1,30 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import PageMeta from "../../components/common/PageMeta";
|
||||
import AuthLayout from "./AuthPageLayout";
|
||||
import SignUpFormSimplified from "../../components/auth/SignUpFormSimplified";
|
||||
import SignUpFormUnified from "../../components/auth/SignUpFormUnified";
|
||||
|
||||
interface Plan {
|
||||
id: number;
|
||||
name: string;
|
||||
slug: string;
|
||||
price: string | number;
|
||||
billing_cycle: string;
|
||||
is_active: boolean;
|
||||
max_users: number;
|
||||
max_sites: number;
|
||||
max_keywords: number;
|
||||
max_clusters: number;
|
||||
max_content_ideas: number;
|
||||
monthly_word_count_limit: number;
|
||||
monthly_ai_credit_limit: number;
|
||||
monthly_image_count: number;
|
||||
daily_content_tasks: number;
|
||||
daily_ai_request_limit: number;
|
||||
daily_image_generation_limit: number;
|
||||
included_credits: number;
|
||||
image_model_choices: string[];
|
||||
features: string[];
|
||||
}
|
||||
|
||||
export default function SignUp() {
|
||||
const planSlug = useMemo(() => {
|
||||
@@ -9,29 +32,45 @@ export default function SignUp() {
|
||||
return params.get("plan") || "";
|
||||
}, []);
|
||||
|
||||
const [planDetails, setPlanDetails] = useState<any | null>(null);
|
||||
const [planLoading, setPlanLoading] = useState(false);
|
||||
const [plans, setPlans] = useState<Plan[]>([]);
|
||||
const [plansLoading, setPlansLoading] = useState(true);
|
||||
const [selectedPlan, setSelectedPlan] = useState<Plan | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPlans = async () => {
|
||||
if (!planSlug) return;
|
||||
setPlanLoading(true);
|
||||
setPlansLoading(true);
|
||||
try {
|
||||
const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || "https://api.igny8.com/api";
|
||||
const res = await fetch(`${API_BASE_URL}/v1/auth/plans/`);
|
||||
const data = await res.json();
|
||||
const plans = data?.results || [];
|
||||
const plan = plans.find((p: any) => p.slug === planSlug);
|
||||
if (plan) {
|
||||
const features = Array.isArray(plan.features)
|
||||
? plan.features.map((f: string) => f.charAt(0).toUpperCase() + f.slice(1))
|
||||
: [];
|
||||
setPlanDetails({ ...plan, features });
|
||||
const allPlans = data?.results || [];
|
||||
|
||||
// Show all active plans (including free plan)
|
||||
const publicPlans = allPlans
|
||||
.filter((p: Plan) => p.is_active)
|
||||
.sort((a: Plan, b: Plan) => {
|
||||
const priceA = typeof a.price === 'number' ? a.price : parseFloat(String(a.price || 0));
|
||||
const priceB = typeof b.price === 'number' ? b.price : parseFloat(String(b.price || 0));
|
||||
return priceA - priceB;
|
||||
});
|
||||
|
||||
setPlans(publicPlans);
|
||||
|
||||
// Auto-select plan from URL or default to first plan
|
||||
if (planSlug) {
|
||||
const plan = publicPlans.find((p: Plan) => p.slug === planSlug);
|
||||
if (plan) {
|
||||
setSelectedPlan(plan);
|
||||
} else {
|
||||
setSelectedPlan(publicPlans[0] || null);
|
||||
}
|
||||
} else {
|
||||
setSelectedPlan(publicPlans[0] || null);
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore; SignUpForm will handle lack of plan data gracefully
|
||||
console.error('Failed to load plans:', e);
|
||||
} finally {
|
||||
setPlanLoading(false);
|
||||
setPlansLoading(false);
|
||||
}
|
||||
};
|
||||
fetchPlans();
|
||||
@@ -43,9 +82,36 @@ export default function SignUp() {
|
||||
title="Sign Up - IGNY8"
|
||||
description="Create your IGNY8 account and start building topical authority with AI-powered content"
|
||||
/>
|
||||
<AuthLayout plan={planDetails}>
|
||||
<SignUpFormSimplified planDetails={planDetails} planLoading={planLoading} />
|
||||
</AuthLayout>
|
||||
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
|
||||
<div className="flex min-h-screen">
|
||||
{/* Left Side - Signup Form */}
|
||||
<SignUpFormUnified
|
||||
plans={plans}
|
||||
selectedPlan={selectedPlan}
|
||||
onPlanSelect={setSelectedPlan}
|
||||
plansLoading={plansLoading}
|
||||
/>
|
||||
|
||||
{/* Right Side - Pricing Plans */}
|
||||
<div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-gray-900 dark:to-gray-800 p-8 xl:p-12 items-start justify-center relative">
|
||||
{/* Logo - Top Right */}
|
||||
<Link to="/" className="absolute top-6 right-6 flex items-center gap-3">
|
||||
<div className="flex items-center justify-center w-10 h-10 bg-brand-600 dark:bg-brand-500 rounded-xl">
|
||||
<span className="text-xl font-bold text-white">I</span>
|
||||
</div>
|
||||
<span className="text-xl font-bold text-gray-900 dark:text-white">TailAdmin</span>
|
||||
</Link>
|
||||
|
||||
<div className="w-full max-w-2xl mt-20">
|
||||
|
||||
{/* Pricing Plans Component Will Load Here */}
|
||||
<div id="signup-pricing-plans" className="w-full">
|
||||
{/* Plans will be rendered by SignUpFormUnified */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -233,8 +233,45 @@ export const useAuthStore = create<AuthState>()(
|
||||
const tokens = responseData.tokens || {};
|
||||
const userData = responseData.user || data.user;
|
||||
|
||||
const newToken = tokens.access || responseData.access || data.access || null;
|
||||
const newRefreshToken = tokens.refresh || responseData.refresh || data.refresh || null;
|
||||
// Extract tokens with multiple fallbacks
|
||||
// Response format: { success: true, data: { user: {...}, tokens: { access, refresh } } }
|
||||
const newToken =
|
||||
tokens.access ||
|
||||
responseData.access ||
|
||||
data.access ||
|
||||
data.data?.tokens?.access ||
|
||||
data.tokens?.access ||
|
||||
null;
|
||||
|
||||
const newRefreshToken =
|
||||
tokens.refresh ||
|
||||
responseData.refresh ||
|
||||
data.refresh ||
|
||||
data.data?.tokens?.refresh ||
|
||||
data.tokens?.refresh ||
|
||||
null;
|
||||
|
||||
console.log('Registration response parsed:', {
|
||||
hasUserData: !!userData,
|
||||
hasAccessToken: !!newToken,
|
||||
hasRefreshToken: !!newRefreshToken,
|
||||
userEmail: userData?.email,
|
||||
accountId: userData?.account?.id,
|
||||
tokensLocation: tokens.access ? 'tokens.access' :
|
||||
responseData.access ? 'responseData.access' :
|
||||
data.data?.tokens?.access ? 'data.data.tokens.access' : 'not found'
|
||||
});
|
||||
|
||||
if (!newToken || !userData) {
|
||||
console.error('Registration succeeded but missing critical data:', {
|
||||
token: newToken,
|
||||
user: userData,
|
||||
fullResponse: data,
|
||||
parsedTokens: tokens,
|
||||
parsedResponseData: responseData
|
||||
});
|
||||
throw new Error('Registration completed but authentication failed. Please try logging in.');
|
||||
}
|
||||
|
||||
// CRITICAL: Set auth state AND immediately persist to localStorage
|
||||
// This prevents race conditions where navigation happens before persist
|
||||
@@ -268,8 +305,11 @@ export const useAuthStore = create<AuthState>()(
|
||||
if (newRefreshToken) {
|
||||
localStorage.setItem('refresh_token', newRefreshToken);
|
||||
}
|
||||
|
||||
console.log('Auth state persisted to localStorage successfully');
|
||||
} catch (e) {
|
||||
console.warn('Failed to persist auth state to localStorage:', e);
|
||||
console.error('CRITICAL: Failed to persist auth state to localStorage:', e);
|
||||
throw new Error('Failed to save login session. Please try again.');
|
||||
}
|
||||
|
||||
// Return user data for success handling
|
||||
|
||||
Reference in New Issue
Block a user