Merge remote-tracking branch 'origin/main' into electron

This commit is contained in:
Alex Gleason committed 2025-10-27 13:05:08 -05:00
commit 8e296f2eb8
28 files changed
+5982 -649

No files matched your search

+49 -16
View File
@@ -1,7 +1,8 @@
import { useEffect, useRef } from 'react';
import { Check, Sparkles, ArrowRight, AlertCircle } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Check, Sparkles, ArrowRight, AlertCircle, ExternalLink } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useAISettings } from '@/hooks/useAISettings';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import type { AIProvider } from '@/contexts/AISettingsContext';
@@ -14,6 +15,7 @@ interface AddProviderDialogProps {
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
const scrollableContentRef = useRef<HTMLDivElement>(null);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const { settings, setProvider } = useAISettings();
@@ -25,27 +27,26 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
existingProvider.nostr === provider.nostr &&
existingProvider.proxy === provider.proxy;
// Get provider name from presets or fallback to id
const getProviderName = () => {
const preset = AI_PROVIDER_PRESETS.find(
p => p.id === provider.id && p.baseURL === provider.baseURL
);
return preset?.name || provider.id;
};
const providerName = getProviderName();
// Get provider preset if available
const preset = AI_PROVIDER_PRESETS.find(
p => p.id === provider.id && p.baseURL === provider.baseURL
);
const providerName = preset?.name || provider.id;
const handleAddProvider = () => {
setProvider(provider);
onOpenChange(false);
};
// Scroll to top when dialog opens
// Reset agreed to terms when dialog opens or provider changes
useEffect(() => {
if (open && scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
if (open) {
setAgreedToTerms(false);
if (scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
}
}
}, [open]);
}, [open, provider.id]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -164,8 +165,40 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
</p>
</div>
{/* Terms of Service Agreement */}
{preset?.tosURL && (
<div className="space-y-3 max-w-md mx-auto">
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-provider-terms"
checked={agreedToTerms}
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
/>
<label
htmlFor="agree-provider-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree to {providerName}'s{' '}
<a
href={preset.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:no-underline inline-flex items-center gap-1"
onClick={(e) => e.stopPropagation()}
>
Terms of Service
<ExternalLink className="h-3 w-3" />
</a>
</label>
</div>
</div>
)}
<div className="flex justify-center">
<Button onClick={handleAddProvider}>
<Button
onClick={handleAddProvider}
disabled={preset?.tosURL ? !agreedToTerms : false}
>
Add Provider
</Button>
</div>
+761 -144
View File
@@ -1,15 +1,15 @@
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft } from 'lucide-react';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } 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 { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -50,6 +50,35 @@ interface AddCreditsRequest {
redirect_url?: string;
}
interface Giftcard {
object: 'giftcard';
id: string;
code: string;
amount: number;
redeemed: boolean;
created_at?: number;
}
interface GiftcardsResponse {
object: 'list';
data: Giftcard[];
has_more: boolean;
}
interface CreateGiftcardRequest {
amount: number;
quantity: number;
}
interface RedeemGiftcardRequest {
code: string;
}
interface GiftcardRedemption {
object: 'giftcard_redemption';
amount: number;
}
const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
@@ -192,6 +221,11 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
const [giftcardAmount, setGiftcardAmount] = useState<number>(10);
const [giftcardQuantity, setGiftcardQuantity] = useState<number>(1);
const [redeemCode, setRedeemCode] = useState<string>('');
const [copiedCode, setCopiedCode] = useState<string | null>(null);
const [isPrintingQRCodes, setIsPrintingQRCodes] = useState(false);
// Query for payment history
const { data: payments, isLoading: isLoadingPayments } = useQuery({
@@ -206,6 +240,19 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
refetchOnWindowFocus: false,
});
// Query for gift cards
const { data: giftcards, isLoading: isLoadingGiftcards } = useQuery({
queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
queryFn: async (): Promise<Giftcard[]> => {
const ai = createAIClient(provider, user, config.corsProxy);
const data = await ai.get('/credits/giftcards?limit=50') as GiftcardsResponse;
return data.data;
},
enabled: open,
retry: false,
refetchOnWindowFocus: false,
});
// Mutation for adding credits
const addCreditsMutation = useMutation({
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
@@ -316,6 +363,77 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
},
});
// Mutation for creating gift cards
const createGiftcardMutation = useMutation({
mutationFn: async (request: CreateGiftcardRequest): Promise<Giftcard[]> => {
const ai = createAIClient(provider, user, config.corsProxy);
const response = await ai.post('/credits/giftcards', {
body: request,
}) as GiftcardsResponse;
return response.data;
},
onSuccess: (giftcards) => {
toast({
title: 'Gift Cards created!',
description: `Successfully created ${giftcards.length} gift card${giftcards.length > 1 ? 's' : ''}.`,
});
// Refresh gift cards list
queryClient.invalidateQueries({
queryKey: ['ai-giftcards', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Refresh credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Reset form
setGiftcardAmount(10);
setGiftcardQuantity(1);
},
onError: (error: Error) => {
const errorMessage = error?.message || 'Failed to create gift cards';
toast({
title: 'Creation failed',
description: errorMessage,
variant: 'destructive',
});
},
});
// Mutation for redeeming gift cards
const redeemGiftcardMutation = useMutation({
mutationFn: async (request: RedeemGiftcardRequest): Promise<GiftcardRedemption> => {
const ai = createAIClient(provider, user, config.corsProxy);
return await ai.post('/credits/giftcards/redeem', {
body: request,
}) as GiftcardRedemption;
},
onSuccess: (redemption) => {
toast({
title: 'Gift Card redeemed!',
description: `${formatCurrency(redemption.amount)} has been added to your account.`,
});
// Refresh credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Reset redeem code
setRedeemCode('');
},
onError: (error: Error) => {
const errorMessage = error?.message || 'Failed to redeem gift card';
toast({
title: 'Redemption failed',
description: errorMessage,
variant: 'destructive',
});
},
});
const handleAddCredits = () => {
if (amount <= 0) {
toast({
@@ -338,6 +456,292 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
addCreditsMutation.mutate(request);
};
const handleCreateGiftcard = () => {
if (giftcardAmount <= 0) {
toast({
title: 'Invalid amount',
description: 'Please enter a valid amount.',
variant: 'destructive',
});
return;
}
if (giftcardQuantity <= 0 || giftcardQuantity > 100) {
toast({
title: 'Invalid quantity',
description: 'Quantity must be between 1 and 100.',
variant: 'destructive',
});
return;
}
createGiftcardMutation.mutate({
amount: giftcardAmount,
quantity: giftcardQuantity,
});
};
const handleRedeemGiftcard = () => {
const trimmedCode = redeemCode.trim();
if (!trimmedCode) {
toast({
title: 'Invalid code',
description: 'Please enter a gift card code.',
variant: 'destructive',
});
return;
}
redeemGiftcardMutation.mutate({ code: trimmedCode });
};
const handleCopyCode = (code: string) => {
navigator.clipboard.writeText(code);
setCopiedCode(code);
setTimeout(() => setCopiedCode(null), 2000);
};
const handlePrintGiftcards = async () => {
if (!giftcards || giftcards.length === 0) return;
// Filter only active (non-redeemed) gift cards
const activeGiftcards = giftcards.filter(gc => !gc.redeemed);
if (activeGiftcards.length === 0) {
toast({
title: 'No active gift cards',
description: 'You have no active gift cards to print.',
variant: 'destructive',
});
return;
}
setIsPrintingQRCodes(true);
try {
// Generate QR codes for all active gift cards
const qrCodePromises = activeGiftcards.map(async (giftcard) => {
const url = `${window.location.origin}/giftcard#baseURL=${encodeURIComponent(provider.baseURL)}&code=${encodeURIComponent(giftcard.code)}`;
const qrDataUrl = await QRCode.toDataURL(url, {
width: 256,
margin: 2,
color: {
dark: '#000000',
light: '#ffffff',
},
});
return {
...giftcard,
qrDataUrl,
};
});
const giftcardsWithQR = await Promise.all(qrCodePromises);
// Create a new window for printing
const printWindow = window.open('', '_blank');
if (!printWindow) {
throw new Error('Failed to open print window. Please allow popups for this site.');
}
// Generate the print HTML
const printHTML = `
<!DOCTYPE html>
<html>
<head>
<title>Shakespeare AI Gift Cards</title>
<style>
* {
margin: 0;
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);
gap: 20px;
max-width: 8.5in;
margin: 0 auto;
}
.card {
border: 2px solid #000;
border-radius: 8px;
padding: 20px;
text-align: center;
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;
background: #f5f5f5;
padding: 8px 12px;
border-radius: 4px;
word-break: break-all;
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;
}
}
</style>
</head>
<body>
<div class="grid">
${giftcardsWithQR.map(gc => `
<div class="card">
<div class="card-title">Shakespeare AI Gift Card</div>
<img src="${gc.qrDataUrl}" alt="QR Code" class="qr-code" />
<div class="amount">${formatCurrency(gc.amount)}</div>
<div class="code">${gc.code}</div>
<div class="footer">Scan to redeem</div>
</div>
`).join('')}
</div>
</body>
</html>
`;
printWindow.document.write(printHTML);
printWindow.document.close();
// Wait for images to load before printing
printWindow.onload = () => {
setTimeout(() => {
printWindow.print();
}, 250);
};
} catch (error) {
console.error('Failed to generate QR codes:', error);
toast({
title: 'Print failed',
description: error instanceof Error ? error.message : 'Failed to generate QR codes for printing',
variant: 'destructive',
});
} finally {
setIsPrintingQRCodes(false);
}
};
const handleDownloadCSV = () => {
if (!giftcards || giftcards.length === 0) return;
// Filter only active (non-redeemed) gift cards
const activeGiftcards = giftcards.filter(gc => !gc.redeemed);
if (activeGiftcards.length === 0) {
toast({
title: 'No active gift cards',
description: 'You have no active gift cards to download.',
variant: 'destructive',
});
return;
}
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'
})
: 'N/A';
return [
gc.code,
Number(gc.amount).toFixed(2),
gc.redeemed ? 'Redeemed' : 'Active',
createdDate,
url
];
});
// Combine headers and rows
const csvContent = [
headers.join(','),
...rows.map(row => row.map(cell => `"${cell}"`).join(','))
].join('\n');
// Create blob and download
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({
title: 'CSV downloaded',
description: `Downloaded ${activeGiftcards.length} gift card${activeGiftcards.length > 1 ? 's' : ''}.`,
});
} catch (error) {
console.error('Failed to generate CSV:', error);
toast({
title: 'Download failed',
description: error instanceof Error ? error.message : 'Failed to generate CSV file',
variant: 'destructive',
});
}
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
@@ -433,160 +837,373 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
/>
</div>
) : (
<div className="flex-1 flex flex-col min-h-0">
{/* Add Credits Form - Fixed size section */}
<div className="flex-shrink-0 space-y-4 px-1 -mx-1">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
<div className="space-y-3">
<Input
id="amount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
placeholder="Enter amount"
className="text-center text-lg font-medium"
/>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={amount === preset ? "default" : "outline"}
size="sm"
onClick={() => setAmount(preset)}
className="text-xs"
>
${preset}
</Button>
))}
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<Accordion type="multiple" defaultValue={["add"]} className="w-full">
{/* Buy Credits Accordion */}
<AccordionItem value="add">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<DollarSign className="h-4 w-4" />
Buy Credits
</div>
</div>
</div>
<div className="space-y-3">
<Label className="text-sm font-medium">Payment Method</Label>
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="stripe" className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
Credit Card
</TabsTrigger>
<TabsTrigger value="lightning" className="flex items-center gap-2">
<Zap className="h-4 w-4" />
Lightning
</TabsTrigger>
</TabsList>
</Tabs>
</div>
<Button
onClick={handleAddCredits}
disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
</div>
<div className="flex-shrink-0 px-1 -mx-1 py-4">
<Separator />
</div>
{/* Transaction History - Flexible section */}
<div className="flex-1 min-h-0 flex flex-col px-1 -mx-1">
<div className="flex-shrink-0 mb-4">
<h3 className="text-base font-semibold">Recent Transactions</h3>
</div>
<div className="flex-1 min-h-0 overflow-y-auto">
{isLoadingPayments ? (
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
) : !payments || payments.length === 0 ? (
<div className="flex-1 flex items-center justify-center">
<div className="text-center text-muted-foreground">
<CreditCard className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="text-sm">No transactions yet</p>
<p className="text-xs">Your payment history will appear here</p>
</div>
</div>
) : (
<div className="space-y-2 pb-2">
{payments.map((payment) => (
<div
key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && (
<p className="text-xs text-muted-foreground">
+{formatCurrency(payment.fee)}
</p>
)}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">Amount (USD)</Label>
<div className="space-y-3">
<Input
id="amount"
type="number"
step="0.01"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
placeholder="Enter amount"
className="text-center text-lg font-medium"
/>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={amount === preset ? "default" : "outline"}
size="sm"
onClick={() => setAmount(preset)}
className="text-xs"
>
${preset}
</Button>
))}
</div>
</div>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs"
title="Refresh payment status"
>
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button>
{payment.url && (
<div className="space-y-3">
<Label className="text-sm font-medium">Payment Method</Label>
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="stripe" className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
Credit Card
</TabsTrigger>
<TabsTrigger value="lightning" className="flex items-center gap-2">
<Zap className="h-4 w-4" />
Lightning
</TabsTrigger>
</TabsList>
</Tabs>
</div>
<Button
onClick={handleAddCredits}
disabled={amount <= 0 || addCreditsMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{addCreditsMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
{paymentMethod === 'stripe' ? 'Pay with Card' : 'Generate Invoice'}
{amount > 0 && ` - ${formatCurrency(amount)}`}
</Button>
</div>
</AccordionContent>
</AccordionItem>
{/* Transaction History Accordion */}
<AccordionItem value="history">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<History className="h-4 w-4" />
Recent Transactions
</div>
</AccordionTrigger>
<AccordionContent>
<div className="pt-2">
{isLoadingPayments ? (
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-32" />
</div>
) : !payments || payments.length === 0 ? (
<div className="py-8 text-center text-muted-foreground">
<CreditCard className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="text-sm">No transactions yet</p>
<p className="text-xs">Your payment history will appear here</p>
</div>
) : (
<div className="space-y-2">
{payments.map((payment) => (
<div
key={payment.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
{getStatusIcon(payment.status)}
<span className="text-sm font-medium truncate">
{payment.method === 'stripe' ? 'Credit Card' : 'Lightning'}
</span>
<Badge variant={getStatusVariant(payment.status)} className="text-xs flex-shrink-0">
{payment.status}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(payment.amount)}</p>
{payment.fee > 0 && (
<p className="text-xs text-muted-foreground">
+{formatCurrency(payment.fee)}
</p>
)}
</div>
</div>
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>{formatDate(payment.created_at)}</span>
{payment.status === 'pending' && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => checkPaymentMutation.mutate(payment.id)}
disabled={refreshingPayments.has(payment.id)}
className="h-6 px-2 text-xs"
title="Refresh payment status"
>
<RotateCcw className={`h-3 w-3 ${refreshingPayments.has(payment.id) ? 'animate-spin' : ''}`} />
</Button>
{payment.url && (
<Button
variant="ghost"
size="sm"
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
} else {
window.open(payment.url, '_blank');
}
}}
className="h-6 px-2 text-xs"
>
<ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
</Button>
)}
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</AccordionContent>
</AccordionItem>
{/* Redeem Gift Card Accordion */}
<AccordionItem value="redeem">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Redeem Gift Card
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<div className="flex gap-2">
<Input
id="redeem-code"
type="text"
value={redeemCode}
onChange={(e) => setRedeemCode(e.target.value)}
placeholder="Enter gift card code"
className="flex-1"
/>
<Button
onClick={handleRedeemGiftcard}
disabled={!redeemCode.trim() || redeemGiftcardMutation.isPending}
size="lg"
>
{redeemGiftcardMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
Redeem
</Button>
</div>
</div>
</AccordionContent>
</AccordionItem>
{/* Create Gift Card Accordion */}
<AccordionItem value="create">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<Gift className="h-4 w-4" />
Create Gift Card
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-2">
<Label htmlFor="giftcard-amount" className="text-xs text-muted-foreground">Amount (USD)</Label>
<Input
id="giftcard-amount"
type="number"
step="0.01"
value={giftcardAmount}
onChange={(e) => setGiftcardAmount(Number(e.target.value))}
placeholder="Amount"
className="text-center"
/>
</div>
<div className="space-y-2">
<Label htmlFor="giftcard-quantity" className="text-xs text-muted-foreground">Quantity</Label>
<Input
id="giftcard-quantity"
type="number"
min="1"
max="100"
value={giftcardQuantity}
onChange={(e) => setGiftcardQuantity(Number(e.target.value))}
placeholder="Qty"
className="text-center"
/>
</div>
</div>
<div className="grid grid-cols-5 gap-2">
{PRESET_AMOUNTS.map((preset) => (
<Button
key={preset}
variant={giftcardAmount === preset ? "default" : "outline"}
size="sm"
onClick={() => setGiftcardAmount(preset)}
className="text-xs"
>
${preset}
</Button>
))}
</div>
<Button
onClick={handleCreateGiftcard}
disabled={giftcardAmount <= 0 || giftcardQuantity <= 0 || createGiftcardMutation.isPending}
className="w-full h-12 text-base font-medium"
size="lg"
>
{createGiftcardMutation.isPending && <RefreshCw className="h-4 w-4 mr-2 animate-spin" />}
Create {giftcardQuantity > 1 ? `${giftcardQuantity} ` : ''}Gift Card{giftcardQuantity > 1 ? 's' : ''}
{giftcardAmount > 0 && giftcardQuantity > 0 && ` - ${formatCurrency(giftcardAmount * giftcardQuantity)}`}
</Button>
</div>
</AccordionContent>
</AccordionItem>
{/* Your Gift Cards Accordion */}
<AccordionItem value="list" className="border-b-0">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
Your Gift Cards
</div>
</AccordionTrigger>
<AccordionContent className="pb-0">
<div className="pt-2 space-y-3">
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
<div className="grid grid-cols-2 gap-2">
<Button
onClick={handlePrintGiftcards}
disabled={isPrintingQRCodes}
variant="outline"
size="sm"
>
{isPrintingQRCodes ? (
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
) : (
<Printer className="h-4 w-4 mr-2" />
)}
Print QR Codes
</Button>
<Button
onClick={handleDownloadCSV}
variant="outline"
size="sm"
>
<Download className="h-4 w-4 mr-2" />
Download CSV
</Button>
</div>
)}
{isLoadingGiftcards ? (
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
<Skeleton className="h-4 w-4 rounded" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-16 ml-auto" />
</div>
<Skeleton className="h-3 w-48" />
</div>
) : !giftcards || giftcards.length === 0 ? (
<div className="py-8 text-center text-muted-foreground">
<Gift className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="text-sm">No gift cards yet</p>
<p className="text-xs">Create gift cards to share with others</p>
</div>
) : (
<div className="space-y-2">
{giftcards.map((giftcard) => (
<div
key={giftcard.id}
className="p-3 border rounded-lg space-y-2 hover:bg-muted/30 transition-colors"
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2 min-w-0 flex-1">
<Gift className="h-4 w-4 flex-shrink-0" />
<span className="text-sm font-medium truncate">
Gift Card
</span>
<Badge variant={giftcard.redeemed ? "secondary" : "default"} className="text-xs flex-shrink-0">
{giftcard.redeemed ? 'Redeemed' : 'Active'}
</Badge>
</div>
<div className="text-right flex-shrink-0">
<p className="text-sm font-medium">{formatCurrency(giftcard.amount)}</p>
</div>
</div>
<div className="flex items-center justify-between">
<code className="text-xs bg-muted px-2 py-1 rounded font-mono">
{giftcard.code}
</code>
<div className="relative">
<Button
variant="ghost"
size="sm"
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
} else {
window.open(payment.url, '_blank');
}
}}
onClick={() => handleCopyCode(giftcard.code)}
className="h-6 px-2 text-xs"
>
<ExternalLink className="h-3 w-3 mr-1" />
{payment.method === 'lightning' ? 'Pay' : 'Pay'}
<Copy className="h-3 w-3 mr-1" />
Copy
</Button>
)}
{copiedCode === giftcard.code && (
<div className="absolute -top-8 right-0 bg-foreground text-background text-xs px-2 py-1 rounded shadow-lg z-10 animate-in fade-in-0 duration-200 whitespace-nowrap">
Copied!
</div>
)}
</div>
</div>
)}
</div>
{giftcard.created_at && (
<div className="text-xs text-muted-foreground">
Created {formatDate(giftcard.created_at)}
</div>
)}
</div>
))}
</div>
))}
)}
</div>
)}
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
)}
</DialogContent>
@@ -0,0 +1,155 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GiftCardRedeemDialog } from './GiftCardRedeemDialog';
// Mock fetch
global.fetch = vi.fn();
describe('GiftCardRedeemDialog', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders loading state initially', async () => {
// Mock the gift card check endpoint
(global.fetch as ReturnType<typeof vi.fn>).mockImplementation(() =>
new Promise(() => {}) // Never resolves to keep it loading
);
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Should show loading skeleton
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
it('shows error for invalid gift card', async () => {
// Mock the gift card check endpoint to return an error
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: false,
json: async () => ({
error: {
message: 'No giftcard found with code "INVALID-CODE"',
},
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="INVALID-CODE"
/>
</TestApp>
);
// Wait for error message to appear
await waitFor(() => {
expect(screen.getByText('Invalid Gift Card')).toBeInTheDocument();
});
});
it('shows already redeemed message for redeemed gift card', async () => {
// Mock the gift card check endpoint to return a redeemed gift card
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => ({
object: 'giftcard',
id: 'gc_123',
code: 'TEST-CODE-1234-5678',
amount: 25.0,
redeemed: true,
created_at: 1640995200,
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Wait for redeemed message to appear
await waitFor(() => {
expect(screen.getByText('Already Redeemed')).toBeInTheDocument();
});
});
it('shows gift card amount for valid unredeemed gift card', async () => {
// Mock the gift card check endpoint to return a valid gift card
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => ({
object: 'giftcard',
id: 'gc_123',
code: 'TEST-CODE-1234-5678',
amount: 25.0,
redeemed: false,
created_at: 1640995200,
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Wait for gift card amount to appear
await waitFor(() => {
expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
});
});
it('shows provider name when matching preset is found', async () => {
// Mock the gift card check endpoint
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => ({
object: 'giftcard',
id: 'gc_123',
code: 'TEST-CODE-1234-5678',
amount: 10.0,
redeemed: false,
created_at: 1640995200,
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Wait for provider name to appear
await waitFor(() => {
expect(screen.getByText('Shakespeare AI')).toBeInTheDocument();
});
});
});
+410
View File
@@ -0,0 +1,410 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMutation, useQuery } from '@tanstack/react-query';
import { Gift, Check, LogIn, Settings as SettingsIcon } from 'lucide-react';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useToast } from '@/hooks/useToast';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAISettings } from '@/hooks/useAISettings';
import { createAIClient } from '@/lib/ai-client';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import { AccountSwitcher } from '@/components/auth/AccountSwitcher';
import SimpleLoginDialog from '@/components/auth/SimpleLoginDialog';
import SimpleSignupDialog from '@/components/auth/SimpleSignupDialog';
import { AddProviderDialog } from '@/components/AddProviderDialog';
import { useAppContext } from '@/hooks/useAppContext';
interface GiftCardRedeemDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
baseURL: string;
code: string;
}
interface Giftcard {
object: 'giftcard';
id: string;
code: string;
amount: number;
redeemed: boolean;
created_at?: number;
}
interface GiftcardRedemption {
object: 'giftcard_redemption';
amount: number;
}
type Step = 'preview' | 'login' | 'provider';
/**
* Gift Card Redemption Dialog
*
* This component handles the complete gift card redemption flow, including:
* - Fetching gift card details from the provider API
* - Multi-step wizard for login and provider setup
* - Account switching before redemption
* - Automatic provider matching against presets
*
* Flow:
* 1. Check if gift card is valid (unauthenticated API call)
* 2. Determine required steps based on user state:
* - Not logged in? → Show login step
* - Provider not configured? → Show provider setup step
* - Ready to redeem? → Show preview with account switcher
* 3. Redeem gift card and add credits to user's account
* 4. Navigate to AI Settings to show new balance
*
* @param open - Whether the dialog is open
* @param onOpenChange - Callback when dialog open state changes
* @param baseURL - Provider base URL (e.g., https://ai.shakespeare.diy/v1)
* @param code - Gift card code to redeem (e.g., XXXX-XXXX-XXXX-XXXX)
*/
export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: GiftCardRedeemDialogProps) {
const { user } = useCurrentUser();
const { settings } = useAISettings();
const { config } = useAppContext();
const { toast } = useToast();
const navigate = useNavigate();
const [currentStep, setCurrentStep] = useState<Step>('preview');
const [showLoginDialog, setShowLoginDialog] = useState(false);
const [showSignupDialog, setShowSignupDialog] = useState(false);
const [showAddProviderDialog, setShowAddProviderDialog] = useState(false);
// Find matching provider by baseURL
const matchingProvider = settings.providers.find(p => p.baseURL === baseURL);
const matchingPreset = AI_PROVIDER_PRESETS.find(p => p.baseURL === baseURL);
// Query gift card details without authentication
const { data: giftcard, isLoading: isLoadingGiftcard, error: giftcardError } = useQuery({
queryKey: ['giftcard-check', baseURL, code],
queryFn: async (): Promise<Giftcard> => {
const response = await fetch(`${baseURL}/credits/giftcards/check/${code}`);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || 'Failed to fetch gift card details');
}
return response.json();
},
enabled: open && !!baseURL && !!code,
retry: false,
});
// Mutation for redeeming gift card
const redeemMutation = useMutation({
mutationFn: async (): Promise<GiftcardRedemption> => {
if (!matchingProvider) {
throw new Error('Provider not configured');
}
const ai = createAIClient(matchingProvider, user, config.corsProxy);
return await ai.post('/credits/giftcards/redeem', {
body: { code },
}) as GiftcardRedemption;
},
onSuccess: (redemption) => {
toast({
title: '🎉 Gift card redeemed!',
description: `${formatCurrency(redemption.amount)} has been added to your account.`,
});
onOpenChange(false);
// Navigate to AI settings to show the new credits
navigate('/settings/ai');
},
onError: (error: Error) => {
toast({
title: 'Redemption failed',
description: error.message || 'Failed to redeem gift card',
variant: 'destructive',
});
},
});
// Determine current step based on conditions
useEffect(() => {
if (!open) return;
// Check if user is logged in and provider is configured
const hasUser = !!user;
const hasProvider = !!matchingProvider;
if (hasUser && hasProvider) {
setCurrentStep('preview');
} else if (!hasUser) {
setCurrentStep('login');
} else if (!hasProvider) {
setCurrentStep('provider');
}
}, [open, user, matchingProvider]);
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
const handleRedeem = () => {
// Check prerequisites
if (!user) {
setCurrentStep('login');
return;
}
if (!matchingProvider) {
setCurrentStep('provider');
return;
}
// All good, redeem the gift card
redeemMutation.mutate();
};
const handleLoginSuccess = () => {
setShowLoginDialog(false);
setShowSignupDialog(false);
// After login, check if provider is configured
if (matchingProvider) {
setCurrentStep('preview');
} else {
setCurrentStep('provider');
}
};
const handleProviderAdded = () => {
setShowAddProviderDialog(false);
setCurrentStep('preview');
};
const handleNext = () => {
if (currentStep === 'login') {
// User needs to log in
setShowSignupDialog(true);
} else if (currentStep === 'provider') {
// User needs to add provider
setShowAddProviderDialog(true);
}
};
const handleAddAccountClick = () => {
setShowLoginDialog(true);
};
// Error state
if (giftcardError) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8">
<div className="mb-4">
<Gift className="h-16 w-16 mx-auto text-muted-foreground opacity-50" />
</div>
<h2 className="text-2xl font-bold mb-2">Invalid Gift Card</h2>
<p className="text-muted-foreground">
{giftcardError instanceof Error ? giftcardError.message : 'This gift card could not be found.'}
</p>
<Button onClick={() => onOpenChange(false)} className="mt-6">
Close
</Button>
</div>
</DialogContent>
</Dialog>
);
}
// Loading state
if (isLoadingGiftcard) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8 space-y-4">
<Skeleton className="h-16 w-16 rounded-full mx-auto" />
<Skeleton className="h-8 w-48 mx-auto" />
<Skeleton className="h-4 w-64 mx-auto" />
<Skeleton className="h-12 w-full" />
</div>
</DialogContent>
</Dialog>
);
}
// Already redeemed
if (giftcard?.redeemed) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8">
<div className="mb-4">
<Check className="h-16 w-16 mx-auto text-green-500" />
</div>
<h2 className="text-2xl font-bold mb-2">Already Redeemed</h2>
<p className="text-muted-foreground">
This gift card has already been redeemed.
</p>
<Button onClick={() => onOpenChange(false)} className="mt-6">
Close
</Button>
</div>
</DialogContent>
</Dialog>
);
}
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8 space-y-6">
{/* Animated gift icon */}
<div className="relative">
<div className="absolute inset-0 flex items-center justify-center">
<div className="h-24 w-24 rounded-full bg-primary/10 animate-pulse" />
</div>
<div className="relative flex items-center justify-center">
<Gift className="h-16 w-16 text-primary animate-bounce" style={{ animationDuration: '2s' }} />
</div>
</div>
{/* Title and amount */}
<div>
<h2 className="text-3xl font-bold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
You've got {giftcard && formatCurrency(giftcard.amount)}!
</h2>
<p className="text-muted-foreground">
{currentStep === 'preview' && 'Ready to add these credits to your account?'}
{currentStep === 'login' && 'First, let\'s get you logged in to redeem your credits'}
{currentStep === 'provider' && `Add ${matchingPreset?.name || 'the provider'} to redeem your credits`}
</p>
</div>
{/* Provider info */}
{matchingPreset && (
<div className="bg-muted/50 rounded-lg p-4 text-sm">
<div className="flex items-center justify-center gap-2">
<span className="text-muted-foreground">Provider:</span>
<span className="font-medium">{matchingPreset.name}</span>
</div>
</div>
)}
{/* Account preview (only show on preview step) */}
{currentStep === 'preview' && user && (
<div className="border rounded-lg p-4">
<p className="text-xs text-muted-foreground mb-3 text-left">Redeeming to account:</p>
<AccountSwitcher onAddAccountClick={handleAddAccountClick} />
</div>
)}
{/* Action buttons */}
<div className="space-y-3">
{currentStep === 'preview' ? (
<Button
onClick={handleRedeem}
disabled={redeemMutation.isPending}
size="lg"
className="w-full text-lg h-14 font-semibold"
>
{redeemMutation.isPending ? (
<>
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2" />
Redeeming...
</>
) : (
<>
<Gift className="h-5 w-5 mr-2" />
Redeem Now
</>
)}
</Button>
) : (
<Button
onClick={handleNext}
size="lg"
className="w-full text-lg h-14 font-semibold"
>
{currentStep === 'login' ? (
<>
<LogIn className="h-5 w-5 mr-2" />
Log In to Continue
</>
) : (
<>
<SettingsIcon className="h-5 w-5 mr-2" />
Add Provider
</>
)}
</Button>
)}
<Button
variant="ghost"
onClick={() => onOpenChange(false)}
className="w-full"
>
Cancel
</Button>
</div>
{/* Progress indicator */}
{currentStep !== 'preview' && (
<div className="flex items-center justify-center gap-2 pt-2">
<div className={`h-2 w-2 rounded-full ${currentStep === 'login' ? 'bg-primary' : 'bg-muted'}`} />
<div className={`h-2 w-2 rounded-full ${currentStep === 'provider' ? 'bg-primary' : 'bg-muted'}`} />
<div className={`h-2 w-2 rounded-full bg-muted`} />
</div>
)}
</div>
</DialogContent>
</Dialog>
{/* Login/Signup Dialogs */}
<SimpleLoginDialog
isOpen={showLoginDialog}
onClose={() => setShowLoginDialog(false)}
onLogin={handleLoginSuccess}
onSignup={() => {
setShowLoginDialog(false);
setShowSignupDialog(true);
}}
/>
<SimpleSignupDialog
isOpen={showSignupDialog}
onClose={() => setShowSignupDialog(false)}
onComplete={handleLoginSuccess}
onLogin={() => {
setShowSignupDialog(false);
setShowLoginDialog(true);
}}
/>
{/* Add Provider Dialog */}
{matchingPreset && (
<AddProviderDialog
open={showAddProviderDialog}
onOpenChange={(open) => {
setShowAddProviderDialog(open);
if (!open) {
// Check if provider was added when dialog closes
const wasAdded = settings.providers.some(p => p.baseURL === baseURL);
if (wasAdded) {
handleProviderAdded();
}
}
}}
provider={{
id: matchingPreset.id,
baseURL: matchingPreset.baseURL,
nostr: matchingPreset.nostr,
proxy: matchingPreset.proxy,
}}
/>
)}
</>
);
}
+55
View File
@@ -0,0 +1,55 @@
import { WifiOff, Wifi } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useOffline } from '@/hooks/useOffline';
/**
* Component that displays an indicator when the app is offline
*/
export function OfflineIndicator() {
const { isOffline, isOnline } = useOffline();
const [showOnlineNotification, setShowOnlineNotification] = useState(false);
const [wasOffline, setWasOffline] = useState(false);
useEffect(() => {
if (isOffline) {
setWasOffline(true);
}
if (isOnline && wasOffline) {
// Show "back online" notification briefly
setShowOnlineNotification(true);
const timer = setTimeout(() => {
setShowOnlineNotification(false);
setWasOffline(false);
}, 3000);
return () => clearTimeout(timer);
}
}, [isOffline, isOnline, wasOffline]);
if (!isOffline && !showOnlineNotification) {
return null;
}
return (
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 z-50 animate-in slide-in-from-bottom-4">
{isOffline ? (
<Alert variant="destructive" className="shadow-lg border-2">
<WifiOff className="h-4 w-4" />
<AlertDescription className="font-medium">
You're offline. Some features may be limited.
</AlertDescription>
</Alert>
) : (
<Alert className="shadow-lg border-2 border-green-500 bg-green-50 dark:bg-green-950">
<Wifi className="h-4 w-4 text-green-600 dark:text-green-400" />
<AlertDescription className="font-medium text-green-600 dark:text-green-400">
You're back online!
</AlertDescription>
</Alert>
)}
</div>
);
}
+67
View File
@@ -0,0 +1,67 @@
import { useEffect, useState } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import { Sparkles } from 'lucide-react';
/**
* Component that prompts users to update when a new service worker is available
*/
export function PWAUpdatePrompt() {
const [showPrompt, setShowPrompt] = useState(false);
const [isUpdating, setIsUpdating] = useState(false);
const {
offlineReady: [offlineReady],
needRefresh: [needRefresh],
updateServiceWorker,
} = useRegisterSW({
onRegisteredSW(swUrl, registration) {
console.log('[PWA] Service worker registered:', swUrl);
// Check for updates periodically (every hour)
if (registration) {
setInterval(() => {
registration.update();
}, 60 * 60 * 1000);
}
},
onRegisterError(error) {
console.error('[PWA] Service worker registration error:', error);
},
});
useEffect(() => {
if (offlineReady) {
console.log('[PWA] App ready to work offline');
}
}, [offlineReady]);
useEffect(() => {
if (needRefresh) {
setShowPrompt(true);
}
}, [needRefresh]);
const handleUpdate = () => {
setIsUpdating(true);
updateServiceWorker(true);
};
if (!showPrompt) {
return null;
}
return (
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full truncate">
<button
onClick={handleUpdate}
disabled={isUpdating}
className="group relative flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate"
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
</div>
);
}
+1 -1
View File
@@ -31,7 +31,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-muted/50 transition-all w-full text-foreground'>
<Avatar className='w-10 h-10'>
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>