fixing and creatign mess
This commit is contained in:
@@ -606,7 +606,7 @@ class BillingViewSet(viewsets.GenericViewSet):
|
||||
|
||||
class InvoiceViewSet(AccountModelViewSet):
|
||||
"""ViewSet for user-facing invoices"""
|
||||
queryset = Invoice.objects.all().select_related('account')
|
||||
queryset = Invoice.objects.all().select_related('account', 'subscription', 'subscription__plan')
|
||||
permission_classes = [IsAuthenticatedAndActive, HasTenantAccess]
|
||||
pagination_class = CustomPageNumberPagination
|
||||
|
||||
@@ -617,6 +617,43 @@ class InvoiceViewSet(AccountModelViewSet):
|
||||
queryset = queryset.filter(account=self.request.account)
|
||||
return queryset.order_by('-invoice_date', '-created_at')
|
||||
|
||||
def _serialize_invoice(self, invoice):
|
||||
"""Serialize an invoice with all needed fields"""
|
||||
# Build subscription data if exists
|
||||
subscription_data = None
|
||||
if invoice.subscription:
|
||||
plan_data = None
|
||||
if invoice.subscription.plan:
|
||||
plan_data = {
|
||||
'id': invoice.subscription.plan.id,
|
||||
'name': invoice.subscription.plan.name,
|
||||
'slug': invoice.subscription.plan.slug,
|
||||
}
|
||||
subscription_data = {
|
||||
'id': invoice.subscription.id,
|
||||
'plan': plan_data,
|
||||
}
|
||||
|
||||
return {
|
||||
'id': invoice.id,
|
||||
'invoice_number': invoice.invoice_number,
|
||||
'status': invoice.status,
|
||||
'total': str(invoice.total), # Alias for compatibility
|
||||
'total_amount': str(invoice.total),
|
||||
'subtotal': str(invoice.subtotal),
|
||||
'tax_amount': str(invoice.tax),
|
||||
'currency': invoice.currency,
|
||||
'invoice_date': invoice.invoice_date.isoformat(),
|
||||
'due_date': invoice.due_date.isoformat(),
|
||||
'paid_at': invoice.paid_at.isoformat() if invoice.paid_at else None,
|
||||
'line_items': invoice.line_items,
|
||||
'billing_email': invoice.billing_email,
|
||||
'notes': invoice.notes,
|
||||
'payment_method': invoice.payment_method,
|
||||
'subscription': subscription_data,
|
||||
'created_at': invoice.created_at.isoformat(),
|
||||
}
|
||||
|
||||
def list(self, request):
|
||||
"""List invoices for current account"""
|
||||
queryset = self.get_queryset()
|
||||
@@ -630,25 +667,7 @@ class InvoiceViewSet(AccountModelViewSet):
|
||||
page = paginator.paginate_queryset(queryset, request)
|
||||
|
||||
# Serialize invoice data
|
||||
results = []
|
||||
for invoice in (page if page is not None else []):
|
||||
results.append({
|
||||
'id': invoice.id,
|
||||
'invoice_number': invoice.invoice_number,
|
||||
'status': invoice.status,
|
||||
'total': str(invoice.total), # Alias for compatibility
|
||||
'total_amount': str(invoice.total),
|
||||
'subtotal': str(invoice.subtotal),
|
||||
'tax_amount': str(invoice.tax),
|
||||
'currency': invoice.currency,
|
||||
'invoice_date': invoice.invoice_date.isoformat(),
|
||||
'due_date': invoice.due_date.isoformat(),
|
||||
'paid_at': invoice.paid_at.isoformat() if invoice.paid_at else None,
|
||||
'line_items': invoice.line_items,
|
||||
'billing_email': invoice.billing_email,
|
||||
'notes': invoice.notes,
|
||||
'created_at': invoice.created_at.isoformat(),
|
||||
})
|
||||
results = [self._serialize_invoice(invoice) for invoice in (page if page is not None else [])]
|
||||
|
||||
return paginated_response(
|
||||
{'count': paginator.page.paginator.count, 'next': paginator.get_next_link(), 'previous': paginator.get_previous_link(), 'results': results},
|
||||
@@ -659,24 +678,7 @@ class InvoiceViewSet(AccountModelViewSet):
|
||||
"""Get invoice detail"""
|
||||
try:
|
||||
invoice = self.get_queryset().get(pk=pk)
|
||||
data = {
|
||||
'id': invoice.id,
|
||||
'invoice_number': invoice.invoice_number,
|
||||
'status': invoice.status,
|
||||
'total': str(invoice.total), # Alias for compatibility
|
||||
'total_amount': str(invoice.total),
|
||||
'subtotal': str(invoice.subtotal),
|
||||
'tax_amount': str(invoice.tax),
|
||||
'currency': invoice.currency,
|
||||
'invoice_date': invoice.invoice_date.isoformat(),
|
||||
'due_date': invoice.due_date.isoformat(),
|
||||
'paid_at': invoice.paid_at.isoformat() if invoice.paid_at else None,
|
||||
'line_items': invoice.line_items,
|
||||
'billing_email': invoice.billing_email,
|
||||
'notes': invoice.notes,
|
||||
'created_at': invoice.created_at.isoformat(),
|
||||
}
|
||||
return success_response(data=data, request=request)
|
||||
return success_response(data=self._serialize_invoice(invoice), request=request)
|
||||
except Invoice.DoesNotExist:
|
||||
return error_response(error='Invoice not found', status_code=404, request=request)
|
||||
|
||||
|
||||
@@ -274,10 +274,21 @@ class InvoiceService:
|
||||
transaction_id: Optional[str] = None
|
||||
) -> Invoice:
|
||||
"""
|
||||
Mark invoice as paid
|
||||
Mark invoice as paid and record payment details
|
||||
|
||||
Args:
|
||||
invoice: Invoice to mark as paid
|
||||
payment_method: Payment method used ('stripe', 'paypal', 'bank_transfer', etc.)
|
||||
transaction_id: External transaction ID (Stripe payment intent, PayPal capture ID, etc.)
|
||||
"""
|
||||
invoice.status = 'paid'
|
||||
invoice.paid_at = timezone.now()
|
||||
invoice.payment_method = payment_method
|
||||
|
||||
# For Stripe payments, store the transaction ID in stripe_invoice_id field
|
||||
if payment_method == 'stripe' and transaction_id:
|
||||
invoice.stripe_invoice_id = transaction_id
|
||||
|
||||
invoice.save()
|
||||
|
||||
return invoice
|
||||
|
||||
@@ -105,11 +105,15 @@ class PaymentService:
|
||||
) -> Payment:
|
||||
"""
|
||||
Mark payment as completed and update invoice
|
||||
For automatic payments (Stripe/PayPal), sets approved_at but leaves approved_by as None
|
||||
"""
|
||||
from .invoice_service import InvoiceService
|
||||
|
||||
payment.status = 'succeeded'
|
||||
payment.processed_at = timezone.now()
|
||||
# For automatic payments, set approved_at to indicate when payment was verified
|
||||
# approved_by stays None to indicate it was automated, not manual approval
|
||||
payment.approved_at = timezone.now()
|
||||
|
||||
if transaction_id:
|
||||
payment.transaction_reference = transaction_id
|
||||
|
||||
@@ -172,7 +172,7 @@ def _attempt_stripe_renewal(subscription: Subscription, invoice: Invoice) -> boo
|
||||
payment_method='stripe',
|
||||
status='processing',
|
||||
stripe_payment_intent_id=intent.id,
|
||||
metadata={'renewal': True}
|
||||
metadata={'renewal': True, 'auto_approved': True}
|
||||
)
|
||||
|
||||
return True
|
||||
@@ -210,7 +210,7 @@ def _attempt_paypal_renewal(subscription: Subscription, invoice: Invoice) -> boo
|
||||
payment_method='paypal',
|
||||
status='processing',
|
||||
paypal_order_id=subscription.metadata['paypal_subscription_id'],
|
||||
metadata={'renewal': True}
|
||||
metadata={'renewal': True, 'auto_approved': True}
|
||||
)
|
||||
return True
|
||||
else:
|
||||
|
||||
@@ -183,9 +183,14 @@ class PayPalCreateSubscriptionOrderView(APIView):
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get plan
|
||||
# Get plan - support both ID (integer) and slug (string) lookup
|
||||
try:
|
||||
plan = Plan.objects.get(id=plan_id, is_active=True)
|
||||
# Try integer ID first
|
||||
try:
|
||||
plan = Plan.objects.get(id=int(plan_id), is_active=True)
|
||||
except (ValueError, Plan.DoesNotExist):
|
||||
# Fall back to slug lookup
|
||||
plan = Plan.objects.get(slug=plan_id, is_active=True)
|
||||
except Plan.DoesNotExist:
|
||||
return error_response(
|
||||
error='Plan not found',
|
||||
@@ -560,6 +565,7 @@ def _process_credit_purchase(account, package_id: str, capture_result: dict) ->
|
||||
)
|
||||
|
||||
# Create payment record
|
||||
# For automatic payments, approved_at is set but approved_by is None (automated)
|
||||
amount = float(capture_result.get('amount', package.price))
|
||||
currency = capture_result.get('currency', 'USD')
|
||||
|
||||
@@ -573,9 +579,11 @@ def _process_credit_purchase(account, package_id: str, capture_result: dict) ->
|
||||
paypal_order_id=capture_result.get('order_id'),
|
||||
paypal_capture_id=capture_result.get('capture_id'),
|
||||
processed_at=timezone.now(),
|
||||
approved_at=timezone.now(), # Set approved_at for automatic payments
|
||||
metadata={
|
||||
'credit_package_id': str(package_id),
|
||||
'credits_added': package.credits,
|
||||
'auto_approved': True, # Indicates automated approval
|
||||
}
|
||||
)
|
||||
|
||||
@@ -642,6 +650,7 @@ def _process_subscription_payment(account, plan_id: str, capture_result: dict) -
|
||||
)
|
||||
|
||||
# Create payment record
|
||||
# For automatic payments, approved_at is set but approved_by is None (automated)
|
||||
amount = float(capture_result.get('amount', plan.price))
|
||||
currency = capture_result.get('currency', 'USD')
|
||||
|
||||
@@ -655,12 +664,36 @@ def _process_subscription_payment(account, plan_id: str, capture_result: dict) -
|
||||
paypal_order_id=capture_result.get('order_id'),
|
||||
paypal_capture_id=capture_result.get('capture_id'),
|
||||
processed_at=timezone.now(),
|
||||
approved_at=timezone.now(), # Set approved_at for automatic payments
|
||||
metadata={
|
||||
'plan_id': str(plan_id),
|
||||
'subscription_type': 'paypal_order',
|
||||
'auto_approved': True, # Indicates automated approval
|
||||
}
|
||||
)
|
||||
|
||||
# Update/create AccountPaymentMethod and mark as verified
|
||||
from ..models import AccountPaymentMethod
|
||||
# Get country code from account billing info
|
||||
country_code = account.billing_country if account.billing_country else ''
|
||||
AccountPaymentMethod.objects.update_or_create(
|
||||
account=account,
|
||||
type='paypal',
|
||||
defaults={
|
||||
'display_name': 'PayPal',
|
||||
'is_default': True,
|
||||
'is_enabled': True,
|
||||
'is_verified': True, # Mark verified after successful payment
|
||||
'country_code': country_code, # Set country from account billing info
|
||||
'metadata': {
|
||||
'last_payment_at': timezone.now().isoformat(),
|
||||
'paypal_order_id': capture_result.get('order_id'),
|
||||
}
|
||||
}
|
||||
)
|
||||
# Set other payment methods as non-default
|
||||
AccountPaymentMethod.objects.filter(account=account).exclude(type='paypal').update(is_default=False)
|
||||
|
||||
# Add subscription credits
|
||||
if plan.included_credits and plan.included_credits > 0:
|
||||
CreditService.add_credits(
|
||||
@@ -674,10 +707,15 @@ def _process_subscription_payment(account, plan_id: str, capture_result: dict) -
|
||||
}
|
||||
)
|
||||
|
||||
# Update account status
|
||||
# Update account status AND plan (like Stripe flow)
|
||||
update_fields = ['updated_at']
|
||||
if account.status != 'active':
|
||||
account.status = 'active'
|
||||
account.save(update_fields=['status', 'updated_at'])
|
||||
update_fields.append('status')
|
||||
if account.plan_id != plan.id:
|
||||
account.plan = plan
|
||||
update_fields.append('plan')
|
||||
account.save(update_fields=update_fields)
|
||||
|
||||
logger.info(
|
||||
f"PayPal subscription payment completed for account {account.id}: "
|
||||
@@ -706,6 +744,10 @@ def _process_generic_payment(account, capture_result: dict) -> dict:
|
||||
paypal_order_id=capture_result.get('order_id'),
|
||||
paypal_capture_id=capture_result.get('capture_id'),
|
||||
processed_at=timezone.now(),
|
||||
approved_at=timezone.now(), # Set approved_at for automatic payments
|
||||
metadata={
|
||||
'auto_approved': True, # Indicates automated approval
|
||||
}
|
||||
)
|
||||
|
||||
logger.info(f"PayPal generic payment recorded for account {account.id}")
|
||||
|
||||
@@ -82,9 +82,14 @@ class StripeCheckoutView(APIView):
|
||||
request=request
|
||||
)
|
||||
|
||||
# Get plan
|
||||
# Get plan - support both ID (integer) and slug (string) lookup
|
||||
try:
|
||||
plan = Plan.objects.get(id=plan_id, is_active=True)
|
||||
# Try integer ID first
|
||||
try:
|
||||
plan = Plan.objects.get(id=int(plan_id), is_active=True)
|
||||
except (ValueError, Plan.DoesNotExist):
|
||||
# Fall back to slug lookup
|
||||
plan = Plan.objects.get(slug=plan_id, is_active=True)
|
||||
except Plan.DoesNotExist:
|
||||
return error_response(
|
||||
error='Plan not found',
|
||||
@@ -488,7 +493,13 @@ def _activate_subscription(account, stripe_subscription_id: str, plan_id: str, s
|
||||
transaction_id=stripe_subscription_id
|
||||
)
|
||||
|
||||
# Create payment record
|
||||
# Extract payment details from session
|
||||
# For subscription checkouts, payment_intent may be in session or we need to use subscription invoice
|
||||
payment_intent_id = session.get('payment_intent')
|
||||
checkout_session_id = session.get('id')
|
||||
|
||||
# Create payment record with proper Stripe identifiers
|
||||
# For automatic payments, approved_at is set but approved_by is None (automated)
|
||||
Payment.objects.create(
|
||||
account=account,
|
||||
invoice=invoice,
|
||||
@@ -496,15 +507,41 @@ def _activate_subscription(account, stripe_subscription_id: str, plan_id: str, s
|
||||
currency=currency,
|
||||
payment_method='stripe',
|
||||
status='succeeded',
|
||||
stripe_payment_intent_id=session.get('payment_intent'),
|
||||
stripe_payment_intent_id=payment_intent_id or f'sub_{stripe_subscription_id}', # Use subscription ID if no PI
|
||||
stripe_charge_id=checkout_session_id, # Store checkout session as reference
|
||||
processed_at=timezone.now(),
|
||||
approved_at=timezone.now(), # Set approved_at for automatic payments
|
||||
metadata={
|
||||
'checkout_session_id': session.get('id'),
|
||||
'checkout_session_id': checkout_session_id,
|
||||
'subscription_id': stripe_subscription_id,
|
||||
'plan_id': str(plan_id),
|
||||
'payment_intent': payment_intent_id,
|
||||
'auto_approved': True, # Indicates automated approval
|
||||
}
|
||||
)
|
||||
|
||||
# Update/create AccountPaymentMethod and mark as verified
|
||||
from ..models import AccountPaymentMethod
|
||||
# Get country code from account billing info
|
||||
country_code = account.billing_country if account.billing_country else ''
|
||||
AccountPaymentMethod.objects.update_or_create(
|
||||
account=account,
|
||||
type='stripe',
|
||||
defaults={
|
||||
'display_name': 'Credit/Debit Card (Stripe)',
|
||||
'is_default': True,
|
||||
'is_enabled': True,
|
||||
'is_verified': True, # Mark verified after successful payment
|
||||
'country_code': country_code, # Set country from account billing info
|
||||
'metadata': {
|
||||
'last_payment_at': timezone.now().isoformat(),
|
||||
'stripe_subscription_id': stripe_subscription_id,
|
||||
}
|
||||
}
|
||||
)
|
||||
# Set other payment methods as non-default
|
||||
AccountPaymentMethod.objects.filter(account=account).exclude(type='stripe').update(is_default=False)
|
||||
|
||||
# Add initial credits from plan
|
||||
if plan.included_credits and plan.included_credits > 0:
|
||||
CreditService.add_credits(
|
||||
@@ -571,6 +608,7 @@ def _add_purchased_credits(account, credit_package_id: str, credit_amount: str,
|
||||
)
|
||||
|
||||
# Create payment record
|
||||
# For automatic payments, approved_at is set but approved_by is None (automated)
|
||||
amount = session.get('amount_total', 0) / 100
|
||||
currency = session.get('currency', 'usd').upper()
|
||||
|
||||
@@ -583,10 +621,12 @@ def _add_purchased_credits(account, credit_package_id: str, credit_amount: str,
|
||||
status='succeeded',
|
||||
stripe_payment_intent_id=session.get('payment_intent'),
|
||||
processed_at=timezone.now(),
|
||||
approved_at=timezone.now(), # Set approved_at for automatic payments
|
||||
metadata={
|
||||
'checkout_session_id': session.get('id'),
|
||||
'credit_package_id': str(credit_package_id),
|
||||
'credits_added': credits_to_add,
|
||||
'auto_approved': True, # Indicates automated approval
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
543
frontend/src/components/billing/PayInvoiceModal.tsx
Normal file
543
frontend/src/components/billing/PayInvoiceModal.tsx
Normal file
@@ -0,0 +1,543 @@
|
||||
/**
|
||||
* Pay Invoice Modal
|
||||
* Allows users to pay pending invoices using Stripe, PayPal, or submit bank transfer confirmation
|
||||
*
|
||||
* Payment Method Logic (Following SignUpFormUnified pattern):
|
||||
* - Pakistan (PK): Bank Transfer + Credit Card (Stripe) - NO PayPal
|
||||
* - Other countries: Credit Card (Stripe) + PayPal only
|
||||
* - Default selection: User's configured default payment method from AccountPaymentMethod
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Modal } from '../ui/modal';
|
||||
import Button from '../ui/button/Button';
|
||||
import Label from '../form/Label';
|
||||
import Input from '../form/input/InputField';
|
||||
import TextArea from '../form/input/TextArea';
|
||||
import {
|
||||
Loader2Icon,
|
||||
UploadIcon,
|
||||
XIcon,
|
||||
CheckCircleIcon,
|
||||
CreditCardIcon,
|
||||
Building2Icon,
|
||||
WalletIcon
|
||||
} from '../../icons';
|
||||
import { API_BASE_URL } from '../../services/api';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { subscribeToPlan } from '../../services/billing.api';
|
||||
|
||||
interface Invoice {
|
||||
id: number;
|
||||
invoice_number: string;
|
||||
total?: string;
|
||||
total_amount?: string;
|
||||
currency?: string;
|
||||
status?: string;
|
||||
payment_method?: string;
|
||||
subscription?: {
|
||||
id?: number;
|
||||
plan?: {
|
||||
id: number;
|
||||
name: string;
|
||||
slug?: string;
|
||||
};
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface PayInvoiceModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess?: () => void;
|
||||
invoice: Invoice;
|
||||
/** User's billing country code (e.g., 'US', 'PK') */
|
||||
userCountry?: string;
|
||||
/** User's default payment method type */
|
||||
defaultPaymentMethod?: string;
|
||||
}
|
||||
|
||||
type PaymentOption = 'stripe' | 'paypal' | 'bank_transfer';
|
||||
|
||||
export default function PayInvoiceModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSuccess,
|
||||
invoice,
|
||||
userCountry = 'US',
|
||||
defaultPaymentMethod,
|
||||
}: PayInvoiceModalProps) {
|
||||
const isPakistan = userCountry?.toUpperCase() === 'PK';
|
||||
|
||||
// Determine available payment options based on country
|
||||
// PK users: Stripe (Card) + Bank Transfer - NO PayPal
|
||||
// Other users: Stripe (Card) + PayPal only
|
||||
const availableOptions: PaymentOption[] = isPakistan
|
||||
? ['stripe', 'bank_transfer']
|
||||
: ['stripe', 'paypal'];
|
||||
|
||||
// Determine initial selection based on:
|
||||
// 1. User's default payment method (if available for this country)
|
||||
// 2. Invoice's stored payment_method
|
||||
// 3. First available option (stripe)
|
||||
const getInitialOption = (): PaymentOption => {
|
||||
// Check user's default payment method first
|
||||
if (defaultPaymentMethod) {
|
||||
if (defaultPaymentMethod === 'stripe' || defaultPaymentMethod === 'card') return 'stripe';
|
||||
if (defaultPaymentMethod === 'bank_transfer' && isPakistan) return 'bank_transfer';
|
||||
if (defaultPaymentMethod === 'paypal' && !isPakistan) return 'paypal';
|
||||
}
|
||||
// Then check invoice's stored payment method
|
||||
if (invoice.payment_method) {
|
||||
if (invoice.payment_method === 'stripe' || invoice.payment_method === 'card') return 'stripe';
|
||||
if (invoice.payment_method === 'bank_transfer' && isPakistan) return 'bank_transfer';
|
||||
if (invoice.payment_method === 'paypal' && !isPakistan) return 'paypal';
|
||||
}
|
||||
// Fall back to first available (always stripe)
|
||||
return 'stripe';
|
||||
};
|
||||
|
||||
const [selectedOption, setSelectedOption] = useState<PaymentOption>(getInitialOption());
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
// Bank transfer form state
|
||||
const [bankFormData, setBankFormData] = useState({
|
||||
manual_reference: '',
|
||||
manual_notes: '',
|
||||
proof_url: '',
|
||||
});
|
||||
const [uploadedFileName, setUploadedFileName] = useState('');
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
const amount = parseFloat(invoice.total_amount || invoice.total || '0');
|
||||
const currency = invoice.currency?.toUpperCase() || 'USD';
|
||||
const planId = invoice.subscription?.plan?.id;
|
||||
const planSlug = invoice.subscription?.plan?.slug;
|
||||
|
||||
// Check if user's default method is selected (for showing badge)
|
||||
const isDefaultMethod = (option: PaymentOption): boolean => {
|
||||
if (!defaultPaymentMethod) return false;
|
||||
if (option === 'stripe' && (defaultPaymentMethod === 'stripe' || defaultPaymentMethod === 'card')) return true;
|
||||
if (option === 'bank_transfer' && defaultPaymentMethod === 'bank_transfer') return true;
|
||||
if (option === 'paypal' && defaultPaymentMethod === 'paypal') return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
// Reset state when modal opens
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setSelectedOption(getInitialOption());
|
||||
setError('');
|
||||
setSuccess(false);
|
||||
setBankFormData({ manual_reference: '', manual_notes: '', proof_url: '' });
|
||||
setUploadedFileName('');
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleStripePayment = async () => {
|
||||
// Use plan slug if available, otherwise fall back to id
|
||||
const planIdentifier = planSlug || (planId ? String(planId) : null);
|
||||
|
||||
if (!planIdentifier) {
|
||||
setError('Unable to process card payment. Invoice has no associated plan. Please contact support.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
|
||||
// Use the subscribeToPlan function which properly handles Stripe checkout
|
||||
const result = await subscribeToPlan(planIdentifier, 'stripe', {
|
||||
return_url: `${window.location.origin}/account/plans?success=true`,
|
||||
cancel_url: `${window.location.origin}/account/plans?canceled=true`,
|
||||
});
|
||||
|
||||
// Redirect to Stripe Checkout
|
||||
window.location.href = result.redirect_url;
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to initiate card payment');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePayPalPayment = async () => {
|
||||
// Use plan slug if available, otherwise fall back to id
|
||||
const planIdentifier = planSlug || (planId ? String(planId) : null);
|
||||
|
||||
if (!planIdentifier) {
|
||||
setError('Unable to process PayPal payment. Invoice has no associated plan. Please contact support.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
|
||||
// Use the subscribeToPlan function which properly handles PayPal
|
||||
const result = await subscribeToPlan(planIdentifier, 'paypal', {
|
||||
return_url: `${window.location.origin}/account/plans?paypal=success&plan_id=${planIdentifier}`,
|
||||
cancel_url: `${window.location.origin}/account/plans?paypal=cancel`,
|
||||
});
|
||||
|
||||
// Redirect to PayPal
|
||||
window.location.href = result.redirect_url;
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to initiate PayPal payment');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
setError('File size must be less than 5MB');
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
setError('Only JPEG, PNG, and PDF files are allowed');
|
||||
return;
|
||||
}
|
||||
|
||||
setUploadedFileName(file.name);
|
||||
setError('');
|
||||
setUploading(true);
|
||||
|
||||
try {
|
||||
// Placeholder URL - actual S3 upload would go here
|
||||
const placeholderUrl = `https://s3.amazonaws.com/igny8-payments/${Date.now()}-${file.name}`;
|
||||
setBankFormData({ ...bankFormData, proof_url: placeholderUrl });
|
||||
} catch (err) {
|
||||
setError('Failed to upload file');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBankSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
|
||||
if (!bankFormData.manual_reference.trim()) {
|
||||
setError('Transaction reference is required');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const token = useAuthStore.getState().token;
|
||||
const response = await fetch(`${API_BASE_URL}/v1/billing/admin/payments/confirm/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
invoice_id: invoice.id,
|
||||
payment_method: 'bank_transfer',
|
||||
amount: invoice.total_amount || invoice.total || '0',
|
||||
manual_reference: bankFormData.manual_reference.trim(),
|
||||
manual_notes: bankFormData.manual_notes.trim() || undefined,
|
||||
proof_url: bankFormData.proof_url || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || data.message || 'Failed to submit payment confirmation');
|
||||
}
|
||||
|
||||
setSuccess(true);
|
||||
setTimeout(() => {
|
||||
onClose();
|
||||
onSuccess?.();
|
||||
}, 2500);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to submit payment');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePayNow = () => {
|
||||
if (selectedOption === 'stripe') {
|
||||
handleStripePayment();
|
||||
} else if (selectedOption === 'paypal') {
|
||||
handlePayPalPayment();
|
||||
}
|
||||
// Bank transfer uses form submit
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={onClose} className="max-w-xl p-0">
|
||||
<div className="p-6">
|
||||
{success ? (
|
||||
<div className="text-center py-8">
|
||||
<CheckCircleIcon className="w-16 h-16 text-success-500 mx-auto mb-4" />
|
||||
<h3 className="text-2xl font-semibold text-gray-900 dark:text-white mb-2">
|
||||
{selectedOption === 'bank_transfer' ? 'Payment Submitted!' : 'Redirecting...'}
|
||||
</h3>
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
{selectedOption === 'bank_transfer'
|
||||
? 'Your payment confirmation has been submitted for review.'
|
||||
: 'You will be redirected to complete your payment.'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">Pay Invoice</h2>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">#{invoice.invoice_number}</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{currency} {amount.toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mb-4 p-3 text-sm text-error-600 bg-error-50 border border-error-200 rounded-lg dark:bg-error-900/20 dark:text-error-400 dark:border-error-800">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Payment Method Selection */}
|
||||
{availableOptions.length > 1 && (
|
||||
<div className="mb-5">
|
||||
<Label className="text-sm text-gray-600 dark:text-gray-400 mb-2 block">Payment Method</Label>
|
||||
<div className="flex gap-2">
|
||||
{/* Stripe (Card) - Always available */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedOption('stripe')}
|
||||
disabled={loading}
|
||||
className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg border-2 transition-all ${
|
||||
selectedOption === 'stripe'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-300'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<CreditCardIcon className={`w-5 h-5 ${selectedOption === 'stripe' ? 'text-brand-600' : 'text-gray-500'}`} />
|
||||
<span className="font-medium">Credit/Debit Card</span>
|
||||
{isDefaultMethod('stripe') && (
|
||||
<span className="ml-1 px-1.5 py-0.5 text-xs font-medium rounded bg-brand-100 dark:bg-brand-800 text-brand-700 dark:text-brand-200">
|
||||
Default
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* PayPal - Only for non-Pakistan */}
|
||||
{!isPakistan && availableOptions.includes('paypal') && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedOption('paypal')}
|
||||
disabled={loading}
|
||||
className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg border-2 transition-all ${
|
||||
selectedOption === 'paypal'
|
||||
? 'border-[#0070ba] bg-blue-50 dark:bg-blue-900/20 text-[#0070ba] dark:text-blue-300'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<WalletIcon className={`w-5 h-5 ${selectedOption === 'paypal' ? 'text-[#0070ba]' : 'text-gray-500'}`} />
|
||||
<span className="font-medium">PayPal</span>
|
||||
{isDefaultMethod('paypal') && (
|
||||
<span className="ml-1 px-1.5 py-0.5 text-xs font-medium rounded bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-200">
|
||||
Default
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Bank Transfer - Only for Pakistan */}
|
||||
{isPakistan && availableOptions.includes('bank_transfer') && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedOption('bank_transfer')}
|
||||
disabled={loading}
|
||||
className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg border-2 transition-all ${
|
||||
selectedOption === 'bank_transfer'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-300'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600 text-gray-700 dark:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<Building2Icon className={`w-5 h-5 ${selectedOption === 'bank_transfer' ? 'text-brand-600' : 'text-gray-500'}`} />
|
||||
<span className="font-medium">Bank Transfer</span>
|
||||
{isDefaultMethod('bank_transfer') && (
|
||||
<span className="ml-1 px-1.5 py-0.5 text-xs font-medium rounded bg-brand-100 dark:bg-brand-800 text-brand-700 dark:text-brand-200">
|
||||
Default
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stripe Payment */}
|
||||
{selectedOption === 'stripe' && (
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg text-center">
|
||||
<CreditCardIcon className="w-12 h-12 mx-auto text-brand-500 mb-3" />
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
|
||||
Pay securely with your credit or debit card via Stripe.
|
||||
</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handlePayNow}
|
||||
disabled={loading}
|
||||
startIcon={loading ? <Loader2Icon className="w-4 h-4 animate-spin" /> : <CreditCardIcon className="w-4 h-4" />}
|
||||
>
|
||||
{loading ? 'Processing...' : `Pay ${currency} ${amount.toFixed(2)} with Card`}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* PayPal Payment - Only for non-Pakistan */}
|
||||
{selectedOption === 'paypal' && !isPakistan && (
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-lg text-center">
|
||||
<WalletIcon className="w-12 h-12 mx-auto text-[#0070ba] mb-3" />
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
|
||||
Pay securely using your PayPal account.
|
||||
</p>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handlePayNow}
|
||||
disabled={loading}
|
||||
className="bg-[#0070ba] hover:bg-[#005ea6]"
|
||||
startIcon={loading ? <Loader2Icon className="w-4 h-4 animate-spin" /> : <WalletIcon className="w-4 h-4" />}
|
||||
>
|
||||
{loading ? 'Processing...' : `Pay ${currency} ${amount.toFixed(2)} with PayPal`}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Bank Transfer - Only for Pakistan */}
|
||||
{selectedOption === 'bank_transfer' && isPakistan && (
|
||||
<form onSubmit={handleBankSubmit} className="space-y-4">
|
||||
{/* Bank Details */}
|
||||
<div className="p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
|
||||
<h4 className="font-medium text-blue-900 dark:text-blue-100 mb-2 flex items-center gap-2">
|
||||
<Building2Icon className="w-5 h-5" />
|
||||
Bank Transfer Details
|
||||
</h4>
|
||||
<div className="text-sm text-blue-800 dark:text-blue-200 space-y-1">
|
||||
<p><span className="font-medium">Bank:</span> Standard Chartered Bank Pakistan</p>
|
||||
<p><span className="font-medium">Account Title:</span> IGNY8 Technologies</p>
|
||||
<p><span className="font-medium">Account #:</span> 01-2345678-01</p>
|
||||
<p><span className="font-medium">IBAN:</span> PK36SCBL0000001234567890</p>
|
||||
<p><span className="font-medium">Reference:</span> {invoice.invoice_number}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Transaction Reference */}
|
||||
<div>
|
||||
<Label>Transaction Reference / ID<span className="text-error-500">*</span></Label>
|
||||
<Input
|
||||
type="text"
|
||||
value={bankFormData.manual_reference}
|
||||
onChange={(e) => setBankFormData({ ...bankFormData, manual_reference: e.target.value })}
|
||||
placeholder="Enter your bank transaction reference"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Notes */}
|
||||
<div>
|
||||
<Label>Notes (Optional)</Label>
|
||||
<TextArea
|
||||
placeholder="Any additional notes about your payment..."
|
||||
rows={2}
|
||||
value={bankFormData.manual_notes}
|
||||
onChange={(val) => setBankFormData({ ...bankFormData, manual_notes: val })}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Proof Upload */}
|
||||
<div>
|
||||
<Label>Upload Payment Proof (Optional)</Label>
|
||||
{!uploadedFileName ? (
|
||||
<label className="flex items-center justify-center w-full h-20 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer hover:border-brand-500 dark:border-gray-700 transition-colors">
|
||||
<div className="text-center">
|
||||
<UploadIcon className="w-6 h-6 mx-auto text-gray-400 mb-1" />
|
||||
<p className="text-xs text-gray-500">Click to upload receipt screenshot</p>
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
accept=".jpg,.jpeg,.png,.pdf"
|
||||
disabled={loading || uploading}
|
||||
/>
|
||||
</label>
|
||||
) : (
|
||||
<div className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircleIcon className="w-5 h-5 text-success-500" />
|
||||
<span className="text-sm truncate max-w-[200px]">{uploadedFileName}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setUploadedFileName('');
|
||||
setBankFormData({ ...bankFormData, proof_url: '' });
|
||||
}}
|
||||
disabled={loading}
|
||||
className="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded"
|
||||
>
|
||||
<XIcon className="w-4 h-4 text-gray-500" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="text-center">
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={loading || uploading}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2Icon className="w-4 h-4 mr-2 animate-spin" />
|
||||
Submitting...
|
||||
</>
|
||||
) : (
|
||||
'Submit Payment Confirmation'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{/* Cancel Button */}
|
||||
<div className="mt-4 text-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
tone="neutral"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { Link } from 'react-router-dom';
|
||||
import Button from '../ui/button/Button';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { API_BASE_URL } from '../../services/api';
|
||||
import PaymentConfirmationModal from './PaymentConfirmationModal';
|
||||
import PayInvoiceModal from './PayInvoiceModal';
|
||||
|
||||
interface Invoice {
|
||||
id: number;
|
||||
@@ -21,6 +21,15 @@ interface Invoice {
|
||||
status: string;
|
||||
due_date?: string;
|
||||
created_at: string;
|
||||
payment_method?: string; // For checking bank_transfer
|
||||
subscription?: {
|
||||
id?: number;
|
||||
plan?: {
|
||||
id: number;
|
||||
name: string;
|
||||
slug?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
interface PendingPaymentBannerProps {
|
||||
@@ -30,6 +39,11 @@ interface PendingPaymentBannerProps {
|
||||
export default function PendingPaymentBanner({ className = '' }: PendingPaymentBannerProps) {
|
||||
const [invoice, setInvoice] = useState<Invoice | null>(null);
|
||||
const [paymentMethod, setPaymentMethod] = useState<any>(null);
|
||||
const [availableGateways, setAvailableGateways] = useState<{ stripe: boolean; paypal: boolean; manual: boolean }>({
|
||||
stripe: false,
|
||||
paypal: false,
|
||||
manual: true,
|
||||
});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
const [showPaymentModal, setShowPaymentModal] = useState(false);
|
||||
@@ -74,21 +88,58 @@ export default function PendingPaymentBanner({ className = '' }: PendingPaymentB
|
||||
if (response.ok && data.success && data.results?.length > 0) {
|
||||
setInvoice(data.results[0]);
|
||||
|
||||
// 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/payment-configs/payment-methods/?country=${country}`, {
|
||||
// Load user's account payment methods
|
||||
try {
|
||||
const apmResponse = await fetch(`${API_BASE_URL}/v1/billing/payment-methods/`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
const apmData = await apmResponse.json();
|
||||
if (apmResponse.ok && apmData.success && apmData.results?.length > 0) {
|
||||
const defaultMethod = apmData.results.find((m: any) => m.is_default && m.is_verified) ||
|
||||
apmData.results.find((m: any) => m.is_verified) ||
|
||||
apmData.results[0];
|
||||
if (defaultMethod) {
|
||||
setPaymentMethod(defaultMethod);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load account payment methods:', err);
|
||||
}
|
||||
|
||||
const pmData = await pmResponse.json();
|
||||
// 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]);
|
||||
// Load available payment gateways by checking their config endpoints
|
||||
try {
|
||||
const [stripeRes, paypalRes] = await Promise.all([
|
||||
fetch(`${API_BASE_URL}/v1/billing/stripe/config/`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
}),
|
||||
fetch(`${API_BASE_URL}/v1/billing/paypal/config/`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
},
|
||||
credentials: 'include',
|
||||
}),
|
||||
]);
|
||||
const stripeData = await stripeRes.json().catch(() => ({}));
|
||||
const paypalData = await paypalRes.json().catch(() => ({}));
|
||||
setAvailableGateways({
|
||||
stripe: stripeRes.ok && stripeData.success && !!stripeData.publishable_key,
|
||||
paypal: paypalRes.ok && paypalData.success && !!paypalData.client_id,
|
||||
manual: true,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Failed to load payment gateways:', err);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -241,13 +292,17 @@ export default function PendingPaymentBanner({ className = '' }: PendingPaymentB
|
||||
startIcon={<CreditCardIcon className="w-4 h-4" />}
|
||||
onClick={() => setShowPaymentModal(true)}
|
||||
>
|
||||
Confirm Payment
|
||||
Pay Now
|
||||
</Button>
|
||||
{/* Only show Bank Transfer Details for PK users with bank_transfer payment method */}
|
||||
{(user?.account as any)?.billing_country?.toUpperCase() === 'PK' &&
|
||||
(paymentMethod?.type === 'bank_transfer' || invoice.payment_method === 'bank_transfer') && (
|
||||
<Link to="/account/plans">
|
||||
<Button variant="outline" size="sm">
|
||||
View Billing Details
|
||||
View Bank Transfer Details
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -266,18 +321,15 @@ export default function PendingPaymentBanner({ className = '' }: PendingPaymentB
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payment Confirmation Modal */}
|
||||
{/* Payment Modal with All Options */}
|
||||
{showPaymentModal && invoice && (
|
||||
<PaymentConfirmationModal
|
||||
<PayInvoiceModal
|
||||
isOpen={showPaymentModal}
|
||||
onClose={() => setShowPaymentModal(false)}
|
||||
onSuccess={handlePaymentSuccess}
|
||||
invoice={invoice}
|
||||
paymentMethod={paymentMethod || {
|
||||
payment_method: 'bank_transfer',
|
||||
display_name: 'Bank Transfer',
|
||||
country_code: 'US'
|
||||
}}
|
||||
userCountry={(user?.account as any)?.billing_country || 'US'}
|
||||
defaultPaymentMethod={paymentMethod?.type}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -52,7 +52,7 @@ export const Modal: React.FC<ModalProps> = ({
|
||||
const contentClasses = isFullscreen
|
||||
? "w-full h-full"
|
||||
: className
|
||||
? `relative mx-4 rounded-3xl bg-white dark:bg-gray-900 shadow-xl ${className}`
|
||||
? `relative w-full mx-4 rounded-3xl bg-white dark:bg-gray-900 shadow-xl ${className}`
|
||||
: "relative w-full max-w-lg mx-4 rounded-3xl bg-white dark:bg-gray-900 shadow-xl";
|
||||
|
||||
return (
|
||||
|
||||
@@ -28,10 +28,12 @@ import {
|
||||
TagIcon,
|
||||
LockIcon,
|
||||
ShootingStarIcon,
|
||||
DollarLineIcon,
|
||||
} from '../../icons';
|
||||
import { Card } from '../../components/ui/card';
|
||||
import Badge from '../../components/ui/badge/Badge';
|
||||
import Button from '../../components/ui/button/Button';
|
||||
import Label from '../../components/form/Label';
|
||||
import PageMeta from '../../components/common/PageMeta';
|
||||
import PageHeader from '../../components/common/PageHeader';
|
||||
import { useToast } from '../../components/ui/toast/ToastContainer';
|
||||
@@ -41,7 +43,7 @@ import {
|
||||
getCreditBalance,
|
||||
getCreditPackages,
|
||||
getInvoices,
|
||||
getAvailablePaymentMethods,
|
||||
getAccountPaymentMethods,
|
||||
purchaseCreditPackage,
|
||||
downloadInvoicePDF,
|
||||
getPayments,
|
||||
@@ -64,6 +66,7 @@ import {
|
||||
type PaymentGateway,
|
||||
} from '../../services/billing.api';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import PayInvoiceModal from '../../components/billing/PayInvoiceModal';
|
||||
|
||||
export default function PlansAndBillingPage() {
|
||||
const { startLoading, stopLoading } = usePageLoading();
|
||||
@@ -80,13 +83,15 @@ export default function PlansAndBillingPage() {
|
||||
const [showUpgradeModal, setShowUpgradeModal] = useState(false);
|
||||
const [selectedBillingCycle, setSelectedBillingCycle] = useState<'monthly' | 'annual'>('monthly');
|
||||
const [selectedGateway, setSelectedGateway] = useState<PaymentGateway>('stripe');
|
||||
const [showPayInvoiceModal, setShowPayInvoiceModal] = useState(false);
|
||||
const [selectedInvoice, setSelectedInvoice] = useState<Invoice | null>(null);
|
||||
|
||||
// Data States
|
||||
const [creditBalance, setCreditBalance] = useState<CreditBalance | null>(null);
|
||||
const [packages, setPackages] = useState<CreditPackage[]>([]);
|
||||
const [invoices, setInvoices] = useState<Invoice[]>([]);
|
||||
const [payments, setPayments] = useState<Payment[]>([]);
|
||||
const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>([]);
|
||||
const [userPaymentMethods, setUserPaymentMethods] = useState<PaymentMethod[]>([]);
|
||||
const [plans, setPlans] = useState<Plan[]>([]);
|
||||
const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
|
||||
const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string | undefined>(undefined);
|
||||
@@ -99,16 +104,51 @@ export default function PlansAndBillingPage() {
|
||||
useEffect(() => {
|
||||
if (hasLoaded.current) return;
|
||||
hasLoaded.current = true;
|
||||
loadData();
|
||||
|
||||
// Handle payment gateway return URLs
|
||||
// Handle payment gateway return URLs BEFORE loadData
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const success = params.get('success');
|
||||
const canceled = params.get('canceled');
|
||||
const purchase = params.get('purchase');
|
||||
const paypalStatus = params.get('paypal');
|
||||
const paypalToken = params.get('token'); // PayPal order ID
|
||||
const planIdParam = params.get('plan_id');
|
||||
const packageIdParam = params.get('package_id');
|
||||
const { refreshUser } = useAuthStore.getState();
|
||||
|
||||
if (success === 'true') {
|
||||
// Handle PayPal return - MUST capture the order to complete payment
|
||||
// Do this BEFORE loadData to ensure payment is processed first
|
||||
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);
|
||||
});
|
||||
});
|
||||
return; // Don't load data yet, wait for capture to complete
|
||||
} else if (paypalStatus === 'cancel') {
|
||||
toast?.info?.('PayPal payment was cancelled');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
}
|
||||
// Handle Stripe success
|
||||
else if (success === 'true') {
|
||||
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') {
|
||||
@@ -116,11 +156,16 @@ export default function PlansAndBillingPage() {
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
} else if (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') {
|
||||
toast?.info?.('Credit purchase was cancelled');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
}
|
||||
|
||||
// Load data after handling return URLs
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
const handleError = (err: any, fallback: string) => {
|
||||
@@ -138,7 +183,7 @@ export default function PlansAndBillingPage() {
|
||||
const packagesPromise = getCreditPackages();
|
||||
const invoicesPromise = getInvoices({});
|
||||
const paymentsPromise = getPayments({});
|
||||
const methodsPromise = getAvailablePaymentMethods();
|
||||
const userMethodsPromise = getAccountPaymentMethods();
|
||||
const plansData = await getPlans();
|
||||
await wait(400);
|
||||
|
||||
@@ -152,8 +197,8 @@ export default function PlansAndBillingPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const [packagesData, invoicesData, paymentsData, methodsData] = await Promise.all([
|
||||
packagesPromise, invoicesPromise, paymentsPromise, methodsPromise
|
||||
const [packagesData, invoicesData, paymentsData, userMethodsData] = await Promise.all([
|
||||
packagesPromise, invoicesPromise, paymentsPromise, userMethodsPromise
|
||||
]);
|
||||
|
||||
setCreditBalance(balanceData);
|
||||
@@ -161,13 +206,19 @@ export default function PlansAndBillingPage() {
|
||||
setInvoices(invoicesData.results || []);
|
||||
setPayments(paymentsData.results || []);
|
||||
|
||||
const methods = (methodsData.results || []).filter((m) => m.is_enabled !== false);
|
||||
setPaymentMethods(methods);
|
||||
if (methods.length > 0) {
|
||||
const bank = methods.find((m) => m.type === 'bank_transfer');
|
||||
const manual = methods.find((m) => m.type === 'manual');
|
||||
const selected = bank || manual || methods.find((m) => m.is_default) || methods[0];
|
||||
setSelectedPaymentMethod((prev) => prev || selected.type || selected.id);
|
||||
// Load user's verified payment methods (AccountPaymentMethod)
|
||||
const userMethods = (userMethodsData.results || []).filter((m: any) => m.is_enabled !== false);
|
||||
setUserPaymentMethods(userMethods);
|
||||
|
||||
// Select the user's default/verified payment method
|
||||
if (userMethods.length > 0) {
|
||||
const defaultMethod = userMethods.find((m: any) => m.is_default && m.is_verified) ||
|
||||
userMethods.find((m: any) => m.is_verified) ||
|
||||
userMethods.find((m: any) => m.is_default) ||
|
||||
userMethods[0];
|
||||
if (defaultMethod) {
|
||||
setSelectedPaymentMethod(defaultMethod.type);
|
||||
}
|
||||
}
|
||||
|
||||
// Filter plans
|
||||
@@ -191,12 +242,32 @@ export default function PlansAndBillingPage() {
|
||||
}
|
||||
setSubscriptions(subs);
|
||||
|
||||
// Load available payment gateways
|
||||
// Load available payment gateways and sync with user's payment method
|
||||
try {
|
||||
const gateways = await getAvailablePaymentGateways();
|
||||
setAvailableGateways(gateways);
|
||||
// Auto-select first available gateway
|
||||
if (gateways.stripe) {
|
||||
|
||||
// Use user's verified payment method to set gateway
|
||||
// userMethods was already loaded above
|
||||
const verifiedMethod = userMethods.find(
|
||||
(m: any) => m.is_verified && m.is_default
|
||||
) || userMethods.find((m: any) => m.is_verified) || userMethods[0];
|
||||
|
||||
let userPreferredGateway: PaymentGateway | null = null;
|
||||
if (verifiedMethod) {
|
||||
if (verifiedMethod.type === 'stripe' && gateways.stripe) {
|
||||
userPreferredGateway = 'stripe';
|
||||
} else if (verifiedMethod.type === 'paypal' && gateways.paypal) {
|
||||
userPreferredGateway = 'paypal';
|
||||
} else if (['bank_transfer', 'local_wallet', 'manual'].includes(verifiedMethod.type)) {
|
||||
userPreferredGateway = 'manual';
|
||||
}
|
||||
}
|
||||
|
||||
// Set selected gateway based on user preference or available gateways
|
||||
if (userPreferredGateway) {
|
||||
setSelectedGateway(userPreferredGateway);
|
||||
} else if (gateways.stripe) {
|
||||
setSelectedGateway('stripe');
|
||||
} else if (gateways.paypal) {
|
||||
setSelectedGateway('paypal');
|
||||
@@ -312,6 +383,10 @@ export default function PlansAndBillingPage() {
|
||||
const currentPlan = plans.find((p) => p.id === effectivePlanId) || user?.account?.plan;
|
||||
const hasActivePlan = Boolean(effectivePlanId);
|
||||
const hasPendingPayment = payments.some((p) => p.status === 'pending_approval');
|
||||
const hasPendingInvoice = invoices.some((inv) => inv.status === 'pending');
|
||||
|
||||
// Combined check: disable Buy Credits if no active plan OR has pending invoice
|
||||
const canBuyCredits = hasActivePlan && !hasPendingInvoice;
|
||||
|
||||
// Credit usage percentage
|
||||
const creditUsage = creditBalance && creditBalance.plan_credits_per_month > 0
|
||||
@@ -374,14 +449,14 @@ 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-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-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">
|
||||
<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">
|
||||
{currentPlan?.name || 'No Plan'}
|
||||
</h2>
|
||||
<Badge variant="soft" tone={hasActivePlan ? 'success' : 'warning'}>
|
||||
<Badge variant="solid" tone={hasActivePlan ? 'success' : 'warning'}>
|
||||
{hasActivePlan ? 'Active' : 'Inactive'}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -546,8 +621,7 @@ export default function PlansAndBillingPage() {
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Buy Additional Credits */}
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="p-2 bg-success-100 dark:bg-success-900/30 rounded-lg">
|
||||
<PlusIcon className="w-5 h-5 text-success-600 dark:text-success-400" />
|
||||
</div>
|
||||
@@ -556,38 +630,62 @@ export default function PlansAndBillingPage() {
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">Top up your credit balance</p>
|
||||
</div>
|
||||
</div>
|
||||
{/* Compact Payment Gateway Selector for Credits */}
|
||||
|
||||
{/* Show message if no active plan */}
|
||||
{!hasActivePlan ? (
|
||||
<div className="text-center py-8 border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-xl">
|
||||
<LockIcon className="w-8 h-8 mx-auto text-gray-400 mb-2" />
|
||||
<p className="text-gray-500 dark:text-gray-400 text-sm">
|
||||
Subscribe to a plan first to purchase additional credits
|
||||
</p>
|
||||
</div>
|
||||
) : hasPendingInvoice ? (
|
||||
<div className="text-center py-8 border-2 border-dashed border-warning-200 dark:border-warning-700 bg-warning-50 dark:bg-warning-900/20 rounded-xl">
|
||||
<AlertCircleIcon className="w-8 h-8 mx-auto text-warning-500 mb-2" />
|
||||
<p className="text-warning-700 dark:text-warning-300 text-sm font-medium">
|
||||
Please pay your pending invoice first
|
||||
</p>
|
||||
<p className="text-warning-600 dark:text-warning-400 text-xs mt-1">
|
||||
Credit purchases are disabled until your outstanding balance is settled
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Payment Method Selector - Clear buttons */}
|
||||
{(availableGateways.stripe || availableGateways.paypal) && (
|
||||
<div className="flex items-center gap-1 bg-gray-100 dark:bg-gray-800 p-1 rounded-lg">
|
||||
<div className="mb-4">
|
||||
<Label className="text-xs text-gray-500 dark:text-gray-400 mb-2 block">Payment Method</Label>
|
||||
<div className="flex gap-2">
|
||||
{availableGateways.stripe && (
|
||||
<button
|
||||
onClick={() => setSelectedGateway('stripe')}
|
||||
className={`p-1.5 rounded-md transition-colors ${
|
||||
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
|
||||
selectedGateway === 'stripe'
|
||||
? 'bg-white dark:bg-gray-700 shadow-sm'
|
||||
: 'hover:bg-white/50 dark:hover:bg-gray-700/50'
|
||||
? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-300'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
|
||||
}`}
|
||||
title="Pay with Card"
|
||||
>
|
||||
<CreditCardIcon className={`w-4 h-4 ${selectedGateway === 'stripe' ? 'text-brand-600' : 'text-gray-500'}`} />
|
||||
<CreditCardIcon className={`w-5 h-5 ${selectedGateway === 'stripe' ? 'text-brand-600' : 'text-gray-500'}`} />
|
||||
<span className="text-sm font-medium">Credit/Debit Card</span>
|
||||
</button>
|
||||
)}
|
||||
{availableGateways.paypal && (
|
||||
<button
|
||||
onClick={() => setSelectedGateway('paypal')}
|
||||
className={`p-1.5 rounded-md transition-colors ${
|
||||
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2 rounded-lg border-2 transition-all ${
|
||||
selectedGateway === 'paypal'
|
||||
? 'bg-white dark:bg-gray-700 shadow-sm'
|
||||
: 'hover:bg-white/50 dark:hover:bg-gray-700/50'
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300'
|
||||
: 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
|
||||
}`}
|
||||
title="Pay with PayPal"
|
||||
>
|
||||
<WalletIcon className={`w-4 h-4 ${selectedGateway === 'paypal' ? 'text-blue-600' : 'text-gray-500'}`} />
|
||||
<WalletIcon className={`w-5 h-5 ${selectedGateway === 'paypal' ? 'text-blue-600' : 'text-gray-500'}`} />
|
||||
<span className="text-sm font-medium">PayPal</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{packages.slice(0, 4).map((pkg) => (
|
||||
<button
|
||||
@@ -611,6 +709,8 @@ export default function PlansAndBillingPage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Quick Upgrade Options */}
|
||||
@@ -719,6 +819,21 @@ export default function PlansAndBillingPage() {
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-6 py-3 text-end">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
{invoice.status === 'pending' && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
tone="brand"
|
||||
startIcon={<DollarLineIcon className="w-4 h-4" />}
|
||||
onClick={() => {
|
||||
setSelectedInvoice(invoice);
|
||||
setShowPayInvoiceModal(true);
|
||||
}}
|
||||
>
|
||||
Pay Now
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
@@ -728,6 +843,7 @@ export default function PlansAndBillingPage() {
|
||||
>
|
||||
PDF
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
@@ -737,7 +853,7 @@ export default function PlansAndBillingPage() {
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* SECTION 4: Payment Methods */}
|
||||
{/* SECTION 4: Payment Methods - User's verified payment methods */}
|
||||
<Card className="p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -746,12 +862,12 @@ export default function PlansAndBillingPage() {
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white">Payment Methods</h3>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">Manage how you pay</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">Your saved payment methods</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{paymentMethods.map((method) => (
|
||||
{userPaymentMethods.map((method: any) => (
|
||||
<div
|
||||
key={method.id}
|
||||
className={`p-4 border rounded-xl transition-all ${
|
||||
@@ -762,32 +878,48 @@ export default function PlansAndBillingPage() {
|
||||
>
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex items-center gap-3">
|
||||
{method.type === 'bank_transfer' ? (
|
||||
{method.type === 'bank_transfer' || method.type === 'local_wallet' ? (
|
||||
<Building2Icon className="w-6 h-6 text-gray-500" />
|
||||
) : method.type === 'paypal' ? (
|
||||
<WalletIcon className="w-6 h-6 text-blue-500" />
|
||||
) : (
|
||||
<CreditCardIcon className="w-6 h-6 text-gray-500" />
|
||||
<CreditCardIcon className="w-6 h-6 text-brand-500" />
|
||||
)}
|
||||
<div>
|
||||
<div className="font-medium text-gray-900 dark:text-white">{method.display_name}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{method.type?.replace('_', ' ')}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 items-end">
|
||||
{method.is_verified && (
|
||||
<Badge variant="soft" tone="success" size="sm">Verified</Badge>
|
||||
)}
|
||||
{method.is_default && (
|
||||
<Badge variant="soft" tone="success" size="sm">Default</Badge>
|
||||
<Badge variant="soft" tone="brand" size="sm">Default</Badge>
|
||||
)}
|
||||
</div>
|
||||
{selectedPaymentMethod !== method.type && (
|
||||
</div>
|
||||
{selectedPaymentMethod !== method.type ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
tone="neutral"
|
||||
className="w-full"
|
||||
onClick={() => setSelectedPaymentMethod(method.type)}
|
||||
onClick={() => {
|
||||
setSelectedPaymentMethod(method.type);
|
||||
// Sync gateway selection
|
||||
if (method.type === 'stripe' && availableGateways.stripe) {
|
||||
setSelectedGateway('stripe');
|
||||
} else if (method.type === 'paypal' && availableGateways.paypal) {
|
||||
setSelectedGateway('paypal');
|
||||
} else {
|
||||
setSelectedGateway('manual');
|
||||
}
|
||||
}}
|
||||
>
|
||||
Select
|
||||
</Button>
|
||||
)}
|
||||
{selectedPaymentMethod === method.type && (
|
||||
) : (
|
||||
<div className="flex items-center gap-2 text-sm text-brand-600 dark:text-brand-400">
|
||||
<CheckCircleIcon className="w-4 h-4" />
|
||||
Selected for payment
|
||||
@@ -795,9 +927,11 @@ export default function PlansAndBillingPage() {
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{paymentMethods.length === 0 && (
|
||||
{userPaymentMethods.length === 0 && (
|
||||
<div className="col-span-full text-center py-8 text-gray-500 dark:text-gray-400">
|
||||
No payment methods available
|
||||
<CreditCardIcon className="w-8 h-8 mx-auto mb-2 opacity-50" />
|
||||
<p>No payment methods saved yet.</p>
|
||||
<p className="text-xs mt-1">Complete a payment to save your method.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -1034,6 +1168,29 @@ export default function PlansAndBillingPage() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pay Invoice Modal */}
|
||||
{showPayInvoiceModal && selectedInvoice && (
|
||||
<PayInvoiceModal
|
||||
isOpen={showPayInvoiceModal}
|
||||
onClose={() => {
|
||||
setShowPayInvoiceModal(false);
|
||||
setSelectedInvoice(null);
|
||||
}}
|
||||
onSuccess={async () => {
|
||||
setShowPayInvoiceModal(false);
|
||||
setSelectedInvoice(null);
|
||||
// Refresh user and billing data
|
||||
const { refreshUser } = useAuthStore.getState();
|
||||
await refreshUser();
|
||||
await loadData();
|
||||
toast?.success?.('Payment processed successfully!');
|
||||
}}
|
||||
invoice={selectedInvoice}
|
||||
userCountry={(user?.account as any)?.billing_country || 'US'}
|
||||
defaultPaymentMethod={selectedPaymentMethod}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -98,12 +98,14 @@ export interface Invoice {
|
||||
invoice_number: string;
|
||||
status: 'draft' | 'pending' | 'paid' | 'void' | 'uncollectible';
|
||||
total_amount: string;
|
||||
total?: string; // Alias
|
||||
subtotal: string;
|
||||
tax_amount: string;
|
||||
currency: string;
|
||||
created_at: string;
|
||||
paid_at?: string;
|
||||
due_date?: string;
|
||||
invoice_date?: string;
|
||||
line_items: Array<{
|
||||
description: string;
|
||||
amount: string;
|
||||
@@ -115,6 +117,16 @@ export interface Invoice {
|
||||
billing_period_start?: string;
|
||||
billing_period_end?: string;
|
||||
account_name?: string;
|
||||
// New fields for payment flow
|
||||
payment_method?: string;
|
||||
subscription?: {
|
||||
id: number;
|
||||
plan?: {
|
||||
id: number;
|
||||
name: string;
|
||||
slug?: string;
|
||||
};
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface Payment {
|
||||
@@ -170,6 +182,7 @@ export interface PaymentMethod {
|
||||
name?: string;
|
||||
is_enabled: boolean;
|
||||
is_default?: boolean;
|
||||
is_verified?: boolean;
|
||||
instructions?: string;
|
||||
country_code?: string;
|
||||
bank_details?: {
|
||||
@@ -651,17 +664,32 @@ export async function removeTeamMember(memberId: number): Promise<{
|
||||
// PAYMENT METHODS
|
||||
// ============================================================================
|
||||
|
||||
// Account payment methods (CRUD)
|
||||
// Get GLOBAL payment method configs (system-wide available payment options like stripe, paypal, bank_transfer)
|
||||
// This is used on Plans page to show what payment methods are available to choose
|
||||
export async function getAvailablePaymentMethods(): Promise<{
|
||||
results: PaymentMethod[];
|
||||
count: number;
|
||||
}> {
|
||||
const response = await fetchAPI('/v1/billing/payment-methods/');
|
||||
// Frontend guard: only allow the simplified set we currently support
|
||||
const allowed = new Set(['bank_transfer', 'manual']);
|
||||
// Call the payment-configs endpoint which returns global PaymentMethodConfig records
|
||||
const response = await fetchAPI('/v1/billing/payment-configs/payment-methods/');
|
||||
// Return all payment methods - stripe, paypal, bank_transfer, manual, local_wallet
|
||||
const results = Array.isArray(response.results) ? response.results : [];
|
||||
const filtered = results.filter((m: PaymentMethod) => allowed.has(m.type));
|
||||
return { results: filtered, count: filtered.length };
|
||||
// Map payment_method to type for consistent API
|
||||
const mapped = results.map((m: any) => ({
|
||||
...m,
|
||||
type: m.payment_method || m.type, // PaymentMethodConfig uses payment_method field
|
||||
}));
|
||||
return { results: mapped, count: mapped.length };
|
||||
}
|
||||
|
||||
// Get account-specific payment methods (user's saved/verified payment methods)
|
||||
export async function getAccountPaymentMethods(): Promise<{
|
||||
results: PaymentMethod[];
|
||||
count: number;
|
||||
}> {
|
||||
const response = await fetchAPI('/v1/billing/payment-methods/');
|
||||
const results = Array.isArray(response.results) ? response.results : [];
|
||||
return { results, count: results.length };
|
||||
}
|
||||
|
||||
export async function createPaymentMethod(data: {
|
||||
|
||||
Reference in New Issue
Block a user