fixing and creatign mess
This commit is contained in:
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}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
// 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>
|
||||
<Link to="/account/plans">
|
||||
<Button variant="outline" size="sm">
|
||||
View Billing Details
|
||||
</Button>
|
||||
</Link>
|
||||
{/* 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 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 (
|
||||
|
||||
Reference in New Issue
Block a user