diff --git a/src/components/CreditsBadge.tsx b/src/components/CreditsBadge.tsx index 850c955a..83d5724e 100644 --- a/src/components/CreditsBadge.tsx +++ b/src/components/CreditsBadge.tsx @@ -1,5 +1,7 @@ +import { useState } from 'react'; import { Badge } from '@/components/ui/badge'; import { useAICredits } from '@/hooks/useAICredits'; +import { CreditsDialog } from '@/components/CreditsDialog'; import type { AIConnection } from '@/contexts/AISettingsContext'; interface CreditsBadgeProps { @@ -9,10 +11,11 @@ interface CreditsBadgeProps { } /** - * Displays a credits badge showing the remaining credits for an AI provider + * Displays a clickable credits badge showing the remaining credits for an AI provider */ export function CreditsBadge({ providerId, connection, className }: CreditsBadgeProps) { const { data: credits, isLoading, error } = useAICredits(providerId, connection); + const [dialogOpen, setDialogOpen] = useState(false); // Don't render anything if there's an error (provider doesn't support credits endpoint) if (error || isLoading) { @@ -33,8 +36,24 @@ export function CreditsBadge({ providerId, connection, className }: CreditsBadge }).format(credits.amount); return ( - - {formattedAmount} - + <> + { + e.stopPropagation(); + setDialogOpen(true); + }} + > + {formattedAmount} + + + + ); } \ No newline at end of file diff --git a/src/components/CreditsDialog.test.tsx b/src/components/CreditsDialog.test.tsx new file mode 100644 index 00000000..8f659846 --- /dev/null +++ b/src/components/CreditsDialog.test.tsx @@ -0,0 +1,97 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { TestApp } from '@/test/TestApp'; +import { CreditsDialog } from './CreditsDialog'; +import type { AIConnection } from '@/contexts/AISettingsContext'; + +// Mock the fetch function +global.fetch = vi.fn(); + +const mockConnection: AIConnection = { + baseURL: 'https://api.test.com/v1', + apiKey: 'test-key', +}; + +describe('CreditsDialog', () => { + it('renders dialog when open', () => { + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + expect(screen.getByText('Credits - test-provider')).toBeInTheDocument(); + expect(screen.getByText('Add Credits')).toBeInTheDocument(); + expect(screen.getByText('Transaction History')).toBeInTheDocument(); + }); + + it('does not render when closed', () => { + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + expect(screen.queryByText('Credits - test-provider')).not.toBeInTheDocument(); + }); + + it('shows payment method options', () => { + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + expect(screen.getByText('Payment Method')).toBeInTheDocument(); + expect(screen.getByText('Amount (USD)')).toBeInTheDocument(); + }); + + it('shows preset amount buttons', () => { + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + expect(screen.getByText('$5')).toBeInTheDocument(); + expect(screen.getByText('$10')).toBeInTheDocument(); + expect(screen.getByText('$25')).toBeInTheDocument(); + expect(screen.getByText('$50')).toBeInTheDocument(); + expect(screen.getByText('$100')).toBeInTheDocument(); + }); + + it('shows login requirement when user is not logged in', () => { + render( + + {}} + providerId="test-provider" + connection={mockConnection} + /> + + ); + + expect(screen.getByText('Please log in to purchase credits')).toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx new file mode 100644 index 00000000..2eedbff5 --- /dev/null +++ b/src/components/CreditsDialog.tsx @@ -0,0 +1,379 @@ +import { useState } from 'react'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle } from 'lucide-react'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Badge } from '@/components/ui/badge'; +import { Separator } from '@/components/ui/separator'; +import { Skeleton } from '@/components/ui/skeleton'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { useToast } from '@/hooks/useToast'; +import { createAIClient } from '@/lib/ai-client'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import type { AIConnection } from '@/contexts/AISettingsContext'; + +interface CreditsDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + providerId: string; + connection: AIConnection; +} + +interface Payment { + object: 'payment'; + id: string; + status: 'pending' | 'completed' | 'failed' | 'expired'; + amount: number; + fee: number; + total: number; + method: 'stripe' | 'lightning'; + description: string; + url: string; + created_at: number; + completed_at?: number; + expires_at: number; +} + +interface PaymentsResponse { + object: 'list'; + data: Payment[]; + has_more: boolean; + url: string; +} + +interface AddCreditsRequest { + amount: number; + method: 'stripe' | 'lightning'; + redirect_url?: string; +} + +const PRESET_AMOUNTS = [5, 10, 25, 50, 100]; + +export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) { + const { user } = useCurrentUser(); + const { toast } = useToast(); + const queryClient = useQueryClient(); + + const [amount, setAmount] = useState(10); + const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe'); + + // Query for payment history + const { data: payments, isLoading: isLoadingPayments } = useQuery({ + queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryFn: async (): Promise => { + const ai = createAIClient(connection, user); + const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse; + return data.data; + }, + enabled: open && !!user, + retry: false, + refetchOnWindowFocus: false, + }); + + // Mutation for adding credits + const addCreditsMutation = useMutation({ + mutationFn: async (request: AddCreditsRequest): Promise => { + const ai = createAIClient(connection, user); + return await ai.post('/credits/add', { + body: request, + }) as Payment; + }, + onSuccess: (payment) => { + if (payment.method === 'stripe') { + // Open Stripe checkout in new window + window.open(payment.url, '_blank'); + toast({ + title: 'Payment initiated', + description: 'Stripe checkout opened in a new window.', + }); + } else if (payment.method === 'lightning') { + // Copy Lightning invoice to clipboard + navigator.clipboard.writeText(payment.url); + toast({ + title: 'Lightning invoice copied', + description: 'The Lightning invoice has been copied to your clipboard.', + }); + } + + // Refresh payments list + queryClient.invalidateQueries({ + queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + }); + + // Refresh credits balance + queryClient.invalidateQueries({ + queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + }); + }, + onError: (error: Error) => { + const errorMessage = error?.message || 'Failed to initiate payment'; + toast({ + title: 'Payment failed', + description: errorMessage, + variant: 'destructive', + }); + }, + }); + + const handleAddCredits = () => { + if (!user) { + toast({ + title: 'Authentication required', + description: 'Please log in to purchase credits.', + variant: 'destructive', + }); + return; + } + + if (amount < 5) { + toast({ + title: 'Minimum amount', + description: 'Minimum credit amount is $5.00', + variant: 'destructive', + }); + return; + } + + const request: AddCreditsRequest = { + amount, + method: paymentMethod, + }; + + if (paymentMethod === 'stripe') { + request.redirect_url = window.location.origin + '/settings/ai'; + } + + addCreditsMutation.mutate(request); + }; + + const formatCurrency = (amount: number) => { + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD', + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }).format(amount); + }; + + const formatDate = (timestamp: number) => { + return new Intl.DateTimeFormat('en-US', { + year: 'numeric', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(timestamp * 1000)); + }; + + const getStatusIcon = (status: Payment['status']) => { + switch (status) { + case 'completed': + return ; + case 'failed': + return ; + case 'expired': + return ; + case 'pending': + default: + return ; + } + }; + + 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 ( + + + + + + Credits - {providerId} + + + +
+ {/* Add Credits Form */} +
+

Add Credits

+ +
+
+ +
+ setAmount(Number(e.target.value))} + placeholder="Enter amount" + className="flex-1" + /> +
+ {PRESET_AMOUNTS.map((preset) => ( + + ))} +
+
+ {amount > 0 && amount < 5 && ( +

Minimum amount is $5.00

+ )} +
+ +
+ + +
+ + + + {!user && ( +

+ Please log in to purchase credits +

+ )} +
+
+ + + + {/* Transaction History */} +
+

Transaction History

+ + {isLoadingPayments ? ( +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+
+ +
+ + +
+
+
+ + +
+
+ ))} +
+ ) : !payments || payments.length === 0 ? ( +
+ +

No transactions yet

+

Your payment history will appear here

+
+ ) : ( +
+ {payments.map((payment) => ( +
+
+ {getStatusIcon(payment.status)} +
+
+ {payment.description} + + {payment.status} + +
+

+ {formatDate(payment.created_at)} + {payment.completed_at && payment.completed_at !== payment.created_at && ( + • Completed {formatDate(payment.completed_at)} + )} +

+
+
+
+

{formatCurrency(payment.amount)}

+ {payment.fee > 0 && ( +

+ +{formatCurrency(payment.fee)} fee +

+ )} + {payment.status === 'pending' && payment.url && ( + + )} +
+
+ ))} +
+ )} +
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/hooks/useAICredits.ts b/src/hooks/useAICredits.ts index b0be9785..1bc8e9f8 100644 --- a/src/hooks/useAICredits.ts +++ b/src/hooks/useAICredits.ts @@ -56,7 +56,9 @@ export function useAICredits(providerId: string, connection: AIConnection) { // Already in V1 format return parsed; } catch (error) { - console.error('Error fetching AI credits:', error); + if (error instanceof Error && !error.message.includes('Connection error')) { + console.error('Error fetching AI credits:', error); + } throw error; } },