From 05bdd275d1e3cd6783b497ae24c658faaa3162e6 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 29 Oct 2025 01:22:46 -0500 Subject: [PATCH] Support service fee in Credits Dialog --- src/components/CreditsDialog.tsx | 166 +++++++++++++++++++++---------- 1 file changed, 115 insertions(+), 51 deletions(-) diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 2979f798..b8cb506b 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -227,12 +227,38 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro const [copiedCode, setCopiedCode] = useState(null); const [isPrintingQRCodes, setIsPrintingQRCodes] = useState(false); + // Query for payment preview (to get fee information) + // This creates a payment invoice in advance so we can show the fee + const { data: paymentPreview, isLoading: isLoadingPreview } = useQuery({ + queryKey: ['ai-payment-preview', provider.nostr ? user?.pubkey ?? '' : '', provider.id, amount, paymentMethod], + queryFn: async (): Promise => { + const ai = createAIClient(provider, user, config.corsProxy); + const request: AddCreditsRequest = { + amount, + method: paymentMethod, + }; + + if (paymentMethod === 'stripe') { + request.redirect_url = window.location.origin + '/settings/ai'; + } + + return await ai.post('/credits/add', { + body: request, + }) as Payment; + }, + enabled: open && amount > 0, + retry: false, + refetchOnWindowFocus: false, + staleTime: Infinity, // Don't auto-refetch, we'll manually refetch when needed + gcTime: 1000 * 60 * 10, // Keep in cache for 10 minutes + }); + // Query for payment history const { data: payments, isLoading: isLoadingPayments } = useQuery({ queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { const ai = createAIClient(provider, user, config.corsProxy); - const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse; + const data = await ai.get('/credits/payments?status=completed&limit=50') as PaymentsResponse; return data.data; }, enabled: open, @@ -444,16 +470,48 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro return; } - const request: AddCreditsRequest = { - amount, - method: paymentMethod, - }; + // If we have a preview payment, use it directly + if (paymentPreview) { + // Manually trigger the onSuccess callback with the cached payment + if (paymentPreview.method === 'stripe') { + // Open Stripe checkout in new window + window.open(paymentPreview.url, '_blank'); + toast({ + title: 'Payment initiated', + description: 'Stripe checkout opened in a new window.', + }); + } else if (paymentPreview.method === 'lightning') { + // Show Lightning payment interface + setLightningInvoice(paymentPreview.url); + } - if (paymentMethod === 'stripe') { - request.redirect_url = window.location.origin + '/settings/ai'; + // Refresh payments list + queryClient.invalidateQueries({ + queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], + }); + + // Refresh credits balance + queryClient.invalidateQueries({ + queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], + }); + + // Invalidate the preview so a new one will be fetched for the next payment + queryClient.invalidateQueries({ + queryKey: ['ai-payment-preview', provider.nostr ? user?.pubkey ?? '' : '', provider.id, amount, paymentMethod], + }); + } else { + // Fallback: create a new payment if preview isn't available + const request: AddCreditsRequest = { + amount, + method: paymentMethod, + }; + + if (paymentMethod === 'stripe') { + request.redirect_url = window.location.origin + '/settings/ai'; + } + + addCreditsMutation.mutate(request); } - - addCreditsMutation.mutate(request); }; const handleCreateGiftcard = () => { @@ -555,13 +613,13 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro padding: 0; box-sizing: border-box; } - + body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; padding: 20px; background: white; } - + .grid { display: grid; grid-template-columns: repeat(2, 1fr); @@ -569,7 +627,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro max-width: 8.5in; margin: 0 auto; } - + .card { border: 2px solid #000; border-radius: 8px; @@ -578,28 +636,28 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro page-break-inside: avoid; background: white; } - + .card-title { font-size: 18px; font-weight: 600; margin-bottom: 15px; color: #000; } - + .qr-code { width: 200px; height: 200px; margin: 0 auto 15px; display: block; } - + .amount { font-size: 24px; font-weight: 700; color: #000; margin-bottom: 10px; } - + .code { font-family: 'Courier New', monospace; font-size: 14px; @@ -610,22 +668,22 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro color: #000; border: 1px solid #ddd; } - + .footer { margin-top: 10px; font-size: 12px; color: #666; } - + @media print { body { padding: 0; } - + .grid { gap: 15px; } - + .card { page-break-inside: avoid; } @@ -686,18 +744,18 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro try { // Create CSV header const headers = ['Code', 'Amount', 'Status', 'Created Date', 'Redemption URL']; - + // Create CSV rows const rows = activeGiftcards.map(gc => { const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(gc.code)}`; - const createdDate = gc.created_at - ? new Date(gc.created_at * 1000).toLocaleDateString('en-US', { - year: 'numeric', - month: 'short', - day: 'numeric' - }) + const createdDate = gc.created_at + ? new Date(gc.created_at * 1000).toLocaleDateString('en-US', { + year: 'numeric', + month: 'short', + day: 'numeric' + }) : 'N/A'; - + return [ gc.code, Number(gc.amount).toFixed(2), @@ -717,15 +775,15 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); const link = document.createElement('a'); const url = URL.createObjectURL(blob); - + link.setAttribute('href', url); link.setAttribute('download', `shakespeare-giftcards-${new Date().toISOString().split('T')[0]}.csv`); link.style.visibility = 'hidden'; - + document.body.appendChild(link); link.click(); document.body.removeChild(link); - + URL.revokeObjectURL(url); toast({ @@ -789,20 +847,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro } }; - const getStatusVariant = (status: Payment['status']): "default" | "secondary" | "destructive" | "outline" => { - switch (status) { - case 'completed': - return 'default'; - case 'failed': - return 'destructive'; - case 'expired': - return 'secondary'; - case 'pending': - default: - return 'outline'; - } - }; - return ( e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-dvh-safe max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> @@ -893,15 +937,38 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro + {/* Fee display */} + {paymentPreview && paymentPreview.fee > 0 && ( +
+
+ Credits + {formatCurrency(paymentPreview.amount)} +
+
+ Processing Fee + {formatCurrency(paymentPreview.fee)} +
+
+ Total + {formatCurrency(paymentPreview.total)} +
+
+ )} + @@ -945,9 +1012,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro {payment.method === 'stripe' ? 'Credit Card' : 'Lightning'} - - {payment.status} -

{formatCurrency(payment.amount)}