initial commit

This commit is contained in:
Kar k1
2025-08-30 18:18:57 +05:30
commit 7219108342
270 changed files with 70221 additions and 0 deletions

View File

@@ -0,0 +1,261 @@
'use client'
import React, { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Wallet, Plus, RefreshCw, CreditCard } from 'lucide-react'
import { useToast } from '@/hooks/use-toast'
interface BalanceCardProps {
showAddBalance?: boolean
className?: string
}
export function BalanceCard({ showAddBalance = true, className = '' }: BalanceCardProps) {
const { user, getBalance, addBalance, refreshBalance } = useAuth()
const { toast } = useToast()
const [balance, setBalance] = useState<number>(user?.balance || 0)
const [loading, setLoading] = useState(false)
const [refreshing, setRefreshing] = useState(false)
const [showAddForm, setShowAddForm] = useState(false)
const [amount, setAmount] = useState('')
const [currency, setCurrency] = useState<'INR' | 'USD'>('INR')
const [error, setError] = useState<string | null>(null)
// Update balance when user changes
useEffect(() => {
if (user?.balance !== undefined) {
setBalance(user.balance)
}
}, [user?.balance])
const handleRefreshBalance = async () => {
if (!user) return
setRefreshing(true)
setError(null)
try {
const newBalance = await getBalance()
setBalance(newBalance)
await refreshBalance() // Update user context
toast({
title: 'Balance Updated',
description: 'Your balance has been refreshed successfully.',
})
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to refresh balance'
setError(errorMessage)
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
})
} finally {
setRefreshing(false)
}
}
const handleAddBalance = async (e: React.FormEvent) => {
e.preventDefault()
const numAmount = parseFloat(amount)
if (!numAmount || numAmount <= 0) {
setError('Please enter a valid amount')
return
}
const minAmount = currency === 'INR' ? 100 : 2
const maxAmount = currency === 'INR' ? 100000 : 1500
if (numAmount < minAmount || numAmount > maxAmount) {
setError(
`Amount must be between ${currency === 'INR' ? '₹' : '$'}${minAmount} and ${currency === 'INR' ? '₹' : '$'}${maxAmount}`
)
return
}
setLoading(true)
setError(null)
try {
const result = await addBalance(numAmount, currency)
if (result.success && result.paymentUrl && result.formData) {
// Create and submit payment form
const form = document.createElement('form')
form.method = 'POST'
form.action = result.paymentUrl
form.style.display = 'none'
// Add form data
Object.entries(result.formData).forEach(([key, value]) => {
const input = document.createElement('input')
input.type = 'hidden'
input.name = key
input.value = String(value)
form.appendChild(input)
})
document.body.appendChild(form)
form.submit()
toast({
title: 'Redirecting to Payment',
description: 'You will be redirected to the payment gateway.',
})
} else {
setError(result.error || 'Failed to initiate payment')
toast({
title: 'Payment Error',
description: result.error || 'Failed to initiate payment',
variant: 'destructive',
})
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to add balance'
setError(errorMessage)
toast({
title: 'Error',
description: errorMessage,
variant: 'destructive',
})
} finally {
setLoading(false)
}
}
const formatBalance = (amount: number) => {
return new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR',
minimumFractionDigits: 0,
maximumFractionDigits: 2,
}).format(amount)
}
if (!user) {
return null
}
return (
<Card className={`w-full max-w-md ${className}`}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<div className="flex items-center space-x-2">
<Wallet className="h-5 w-5 text-muted-foreground" />
<CardTitle className="text-lg font-medium">Balance</CardTitle>
</div>
<Button
variant="ghost"
size="sm"
onClick={handleRefreshBalance}
disabled={refreshing}
className="h-8 w-8 p-0"
>
<RefreshCw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />
</Button>
</CardHeader>
<CardContent className="space-y-4">
<div className="text-center">
<div className="text-3xl font-bold text-primary">{formatBalance(balance)}</div>
<CardDescription>Available Balance</CardDescription>
</div>
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{showAddBalance && (
<div className="space-y-3">
{!showAddForm ? (
<Button onClick={() => setShowAddForm(true)} className="w-full" variant="outline">
<Plus className="h-4 w-4 mr-2" />
Add Balance
</Button>
) : (
<form onSubmit={handleAddBalance} className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<div>
<Label htmlFor="amount">Amount</Label>
<Input
id="amount"
type="number"
placeholder="Enter amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
min={currency === 'INR' ? 100 : 2}
max={currency === 'INR' ? 100000 : 1500}
step={currency === 'INR' ? 1 : 0.01}
required
/>
</div>
<div>
<Label htmlFor="currency">Currency</Label>
<Select
value={currency}
onValueChange={(value: 'INR' | 'USD') => setCurrency(value)}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="INR">INR ()</SelectItem>
<SelectItem value="USD">USD ($)</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<div className="text-xs text-muted-foreground">
Min: {currency === 'INR' ? '₹100' : '$2'} | Max:{' '}
{currency === 'INR' ? '₹1,00,000' : '$1,500'}
</div>
<div className="flex gap-2">
<Button type="submit" disabled={loading} className="flex-1">
{loading ? (
<>
<RefreshCw className="h-4 w-4 mr-2 animate-spin" />
Processing...
</>
) : (
<>
<CreditCard className="h-4 w-4 mr-2" />
Pay Now
</>
)}
</Button>
<Button
type="button"
variant="outline"
onClick={() => {
setShowAddForm(false)
setAmount('')
setError(null)
}}
>
Cancel
</Button>
</div>
</form>
)}
</div>
)}
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,61 @@
'use client'
import React from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { Badge } from '@/components/ui/badge'
import { Wallet } from 'lucide-react'
interface BalanceDisplayProps {
variant?: 'default' | 'compact' | 'badge'
showIcon?: boolean
className?: string
}
export function BalanceDisplay({
variant = 'default',
showIcon = true,
className = '',
}: BalanceDisplayProps) {
const { user } = useAuth()
if (!user) return null
const balance = user.balance || 0
const formatBalance = (amount: number) => {
return new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR',
minimumFractionDigits: 0,
maximumFractionDigits: 2,
}).format(amount)
}
if (variant === 'badge') {
return (
<Badge variant="secondary" className={`${className}`}>
{showIcon && <Wallet className="h-3 w-3 mr-1" />}
{formatBalance(balance)}
</Badge>
)
}
if (variant === 'compact') {
return (
<div className={`flex items-center space-x-1 text-sm ${className}`}>
{showIcon && <Wallet className="h-4 w-4 text-muted-foreground" />}
<span className="font-medium">{formatBalance(balance)}</span>
</div>
)
}
return (
<div className={`flex items-center space-x-2 ${className}`}>
{showIcon && <Wallet className="h-5 w-5 text-muted-foreground" />}
<div>
<div className="text-lg font-semibold">{formatBalance(balance)}</div>
{/* <div className="text-xs text-muted-foreground">Balance</div> */}
</div>
</div>
)
}

View File

@@ -0,0 +1,278 @@
'use client'
import React, { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Alert, AlertDescription } from '@/components/ui/alert'
import {
History,
RefreshCw,
ArrowUpCircle,
ArrowDownCircle,
ChevronLeft,
ChevronRight,
Filter,
} from 'lucide-react'
import { formatCurrency } from '@/lib/balance-service'
interface Transaction {
_id: string
transactionId: string
type: 'debit' | 'credit'
amount: number
service: string
serviceId?: string
description?: string
status: 'pending' | 'completed' | 'failed'
previousBalance: number
newBalance: number
createdAt: string
updatedAt: string
}
interface TransactionHistoryProps {
className?: string
showFilters?: boolean
maxHeight?: string
}
export function TransactionHistory({
className = '',
showFilters = true,
maxHeight = '400px',
}: TransactionHistoryProps) {
const { user } = useAuth()
const [transactions, setTransactions] = useState<Transaction[]>([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [page, setPage] = useState(1)
const [totalPages, setTotalPages] = useState(1)
const [typeFilter, setTypeFilter] = useState<'all' | 'debit' | 'credit'>('all')
const [serviceFilter, setServiceFilter] = useState('all')
const fetchTransactions = async (pageNum: number = 1, reset: boolean = false) => {
if (!user) return
setLoading(true)
setError(null)
try {
const params = new URLSearchParams({
page: pageNum.toString(),
limit: '10',
type: typeFilter,
})
if (serviceFilter && serviceFilter !== 'all') {
params.append('service', serviceFilter)
}
const response = await fetch(`/api/transactions?${params}`, {
credentials: 'include',
})
const data = await response.json()
if (!response.ok) {
throw new Error(data.error?.message || 'Failed to fetch transactions')
}
if (data.success) {
if (reset) {
setTransactions(data.data.transactions)
} else {
setTransactions((prev) => [...prev, ...data.data.transactions])
}
setTotalPages(data.data.pagination.totalPages)
setPage(pageNum)
} else {
throw new Error(data.error?.message || 'Failed to fetch transactions')
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to fetch transactions'
setError(errorMessage)
} finally {
setLoading(false)
}
}
useEffect(() => {
fetchTransactions(1, true)
}, [user, typeFilter, serviceFilter])
const handleRefresh = () => {
setPage(1)
fetchTransactions(1, true)
}
const handleLoadMore = () => {
if (page < totalPages) {
fetchTransactions(page + 1, false)
}
}
const getTransactionIcon = (type: string) => {
return type === 'credit' ? (
<ArrowUpCircle className="h-4 w-4 text-green-600" />
) : (
<ArrowDownCircle className="h-4 w-4 text-red-600" />
)
}
const getStatusBadge = (status: string) => {
const variants = {
completed: 'default',
pending: 'secondary',
failed: 'destructive',
} as const
return (
<Badge variant={variants[status as keyof typeof variants] || 'secondary'}>{status}</Badge>
)
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('en-IN', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
})
}
if (!user) {
return null
}
return (
<Card className={className}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
<div className="flex items-center space-x-2">
<History className="h-5 w-5 text-muted-foreground" />
<CardTitle className="text-lg">Transaction History</CardTitle>
</div>
<Button
variant="ghost"
size="sm"
onClick={handleRefresh}
disabled={loading}
className="h-8 w-8 p-0"
>
<RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
</Button>
</CardHeader>
{showFilters && (
<CardContent className="pb-4">
<div className="flex gap-2">
<Select
value={typeFilter}
onValueChange={(value: 'all' | 'debit' | 'credit') => setTypeFilter(value)}
>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Types</SelectItem>
<SelectItem value="debit">Debits</SelectItem>
<SelectItem value="credit">Credits</SelectItem>
</SelectContent>
</Select>
<Select value={serviceFilter} onValueChange={setServiceFilter}>
<SelectTrigger className="w-40">
<SelectValue placeholder="All Services" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Services</SelectItem>
<SelectItem value="VPS">VPS Server</SelectItem>
<SelectItem value="Kubernetes">Kubernetes</SelectItem>
<SelectItem value="Balance">Balance Top-up</SelectItem>
</SelectContent>
</Select>
</div>
</CardContent>
)}
<CardContent className="pt-0">
{error && (
<Alert variant="destructive" className="mb-4">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-3 overflow-y-auto" style={{ maxHeight }}>
{transactions.length === 0 && !loading ? (
<div className="text-center py-8 text-muted-foreground">
<History className="h-12 w-12 mx-auto mb-4 opacity-50" />
<p>No transactions found</p>
<p className="text-sm">Your transaction history will appear here</p>
</div>
) : (
transactions.map((transaction) => (
<div
key={transaction._id}
className="flex items-center justify-between p-3 border rounded-lg hover:bg-muted/50 transition-colors"
>
<div className="flex items-center space-x-3">
{getTransactionIcon(transaction.type)}
<div>
<div className="font-medium text-sm">
{transaction.description || transaction.service}
</div>
<div className="text-xs text-muted-foreground">
{formatDate(transaction.createdAt)}
</div>
{transaction.serviceId && (
<div className="text-xs text-muted-foreground">
ID: {transaction.serviceId}
</div>
)}
</div>
</div>
<div className="text-right">
<div
className={`font-medium ${
transaction.type === 'credit' ? 'text-green-600' : 'text-red-600'
}`}
>
{transaction.type === 'credit' ? '+' : '-'}
{formatCurrency(transaction.amount)}
</div>
{/* <div className="text-xs text-muted-foreground">Balance: {formatCurrency(transaction.newBalance)}</div> */}
<div className="mt-1">{getStatusBadge(transaction.status)}</div>
</div>
</div>
))
)}
{loading && (
<div className="text-center py-4">
<RefreshCw className="h-6 w-6 animate-spin mx-auto mb-2" />
<p className="text-sm text-muted-foreground">Loading transactions...</p>
</div>
)}
{page < totalPages && !loading && (
<div className="text-center pt-4">
<Button variant="outline" onClick={handleLoadMore} disabled={loading}>
Load More
</Button>
</div>
)}
</div>
</CardContent>
</Card>
)
}

View File

@@ -0,0 +1,3 @@
export { BalanceCard } from './BalanceCard'
export { BalanceDisplay } from './BalanceDisplay'
export { TransactionHistory } from './TransactionHistory'