import { Head } from "zudoku/components"; import { useAuth, useZudoku } from "zudoku/hooks"; import { useEffect, useState } from "react"; interface WalletData { wallets: Array<{ lago_id: string; external_customer_id: string; name: string; credits_ongoing_balance: string; currency: string; }>; hasPaymentMethod: boolean; payment_methods?: PaymentMethod[]; wallet_transactions: WalletTransaction[]; current_usage?: CurrentUsage; portal_url?: string; } interface PaymentMethod { id: string; type: string; card?: { brand: string; last4: string; exp_month: number; exp_year: number; }; } interface WalletTransaction { lago_id: string; status: string; transaction_type: string; amount: string; credit_amount: string; created_at: string; name?: string; source?: string; } interface CurrentUsage { customer_usage: { from_datetime: string; to_datetime: string; issuing_date: string; currency: string; amount_cents: number; total_amount_cents: number; taxes_amount_cents: number; charges_usage: ChargeUsage[]; }; } interface ChargeUsage { units: string; events_count: number; amount_cents: number; amount_currency: string; charge: { lago_id: string; charge_model: string; }; billable_metric: { name: string; code: string; }; filters?: Array<{ units: string; events_count: number; amount_cents: number; pricing_unit_details: string | null; invoice_display_name: string | null; values: Record | null; }>; grouped_usage?: Array; } interface ModelUsage { model: string; inputTokens: number; outputTokens: number; totalTokens: number; inputCost: number; outputCost: number; totalCost: number; } interface ModelPricing { model_name: string; input_cost_per_token: number; output_cost_per_token: number; } export const BillingPage = () => { const auth = useAuth(); const context = useZudoku(); const [balance, setBalance] = useState(null); const [totalCredits, setTotalCredits] = useState(null); const [currentUsage, setCurrentUsage] = useState(0); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [transactions, setTransactions] = useState([]); const [loadingTransactions, setLoadingTransactions] = useState(false); const [processingTopUp, setProcessingTopUp] = useState(false); const [processingPaymentSetup, setProcessingPaymentSetup] = useState(false); const [topUpSuccess, setTopUpSuccess] = useState(false); const [topUpError, setTopUpError] = useState(null); const [hasPaymentMethod, setHasPaymentMethod] = useState(false); const [paymentMethods, setPaymentMethods] = useState([]); const [deletingPaymentMethod, setDeletingPaymentMethod] = useState(null); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); const [paymentMethodToDelete, setPaymentMethodToDelete] = useState(null); const [showTopUpModal, setShowTopUpModal] = useState(false); const [topUpAmount, setTopUpAmount] = useState("10"); const [modelUsage, setModelUsage] = useState([]); const [billingPeriod, setBillingPeriod] = useState<{from: string; to: string} | null>(null); const [modelPricing, setModelPricing] = useState([]); const [loadingPricing, setLoadingPricing] = useState(false); const [pricingError, setPricingError] = useState(null); const [portalUrl, setPortalUrl] = useState(null); const formatRelativeTime = (dateString: string) => { const date = new Date(dateString); const now = new Date(); const diffMs = now.getTime() - date.getTime(); const diffHours = Math.floor(diffMs / (1000 * 60 * 60)); const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); if (diffHours < 1) { const diffMinutes = Math.floor(diffMs / (1000 * 60)); return diffMinutes <= 1 ? "just now" : `${diffMinutes} minutes ago`; } else if (diffHours < 24) { return `${diffHours} ${diffHours === 1 ? 'hour' : 'hours'} ago`; } else if (diffDays <= 3) { return `${diffDays} ${diffDays === 1 ? 'day' : 'days'} ago`; } else { // Format as "8th Dec 2025" const day = date.getDate(); const suffix = day === 1 || day === 21 || day === 31 ? 'st' : day === 2 || day === 22 ? 'nd' : day === 3 || day === 23 ? 'rd' : 'th'; const month = date.toLocaleDateString('en-US', { month: 'short' }); const year = date.getFullYear(); return `${day}${suffix} ${month} ${year}`; } }; const formatBillingPeriodDate = (dateString: string) => { const date = new Date(dateString); const day = date.getDate(); const suffix = day === 1 || day === 21 || day === 31 ? 'st' : day === 2 || day === 22 ? 'nd' : day === 3 || day === 23 ? 'rd' : 'th'; const month = date.toLocaleDateString('en-US', { month: 'short' }); const year = date.getFullYear(); return `${day}${suffix} ${month} ${year}`; }; const fetchWalletBalance = async () => { if (!auth.isAuthenticated) { setLoading(false); setLoadingTransactions(false); return; } setLoadingTransactions(true); try { const serverUrl = import.meta.env.ZUPLO_SERVER_URL || window.location.origin; const walletRequest = new Request( `${serverUrl}/v1/developer/wallet`, { method: "GET", headers: { "Content-Type": "application/json", } } ); const signedRequest = await context.signRequest(walletRequest); const response = await fetch(signedRequest); // Handle API key required error if (!response.ok) { const errorData = await response.json().catch(() => ({})); if (errorData.error?.type === "api_key_required") { // Redirect immediately to API keys page window.location.href = "/settings/api-keys"; return; } throw new Error(errorData.error?.message || "Failed to fetch wallet data"); } const data: WalletData = await response.json(); // Get ongoing wallet balance and total credits let ongoingBalance = 0; let initialCredits = 0; if (data.wallets && data.wallets.length > 0) { const wallet = data.wallets[0]; // Standardize on credits_ongoing_balance which reflects actual real-time deductions in Lago ongoingBalance = parseFloat(wallet.credits_ongoing_balance || wallet.credits_balance || "0"); initialCredits = parseFloat(wallet.credits_balance || wallet.credits_ongoing_balance || "0"); setTotalCredits(initialCredits.toFixed(2)); } else { setTotalCredits("0.00"); } // Get current usage amount from customer_usage let usageAmount = 0; if (data.current_usage?.customer_usage?.amount_cents) { usageAmount = data.current_usage.customer_usage.amount_cents / 100; setCurrentUsage(usageAmount); } else { setCurrentUsage(0); } // Standardized remaining balance matching Gateway evaluation setBalance(ongoingBalance.toFixed(2)); // Set payment method status and methods list setHasPaymentMethod(data.hasPaymentMethod || false); setPaymentMethods(data.payment_methods || []); // Set transactions setTransactions(data.wallet_transactions || []); // Set portal URL setPortalUrl(data.portal_url || null); // Parse usage data if (data.current_usage?.customer_usage?.charges_usage) { const usageMap = new Map(); // Capture billing period if (data.current_usage.customer_usage.from_datetime && data.current_usage.customer_usage.to_datetime) { setBillingPeriod({ from: data.current_usage.customer_usage.from_datetime, to: data.current_usage.customer_usage.to_datetime }); } for (const charge of data.current_usage.customer_usage.charges_usage) { // Process filters directly (they're at the top level now) if (charge.filters) { for (const filter of charge.filters) { // Skip filters without values (null values) if (!filter.values) continue; const modelName = filter.values.model?.[0]; const tokenType = filter.values.type?.[0]; if (modelName && tokenType) { if (!usageMap.has(modelName)) { usageMap.set(modelName, { model: modelName, inputTokens: 0, outputTokens: 0, totalTokens: 0, inputCost: 0, outputCost: 0, totalCost: 0 }); } const usage = usageMap.get(modelName)!; const tokens = parseFloat(filter.units) || 0; const cost = filter.amount_cents / 100; if (tokenType === "input") { usage.inputTokens += tokens; usage.inputCost += cost; } else if (tokenType === "output") { usage.outputTokens += tokens; usage.outputCost += cost; } usage.totalTokens = usage.inputTokens + usage.outputTokens; usage.totalCost = usage.inputCost + usage.outputCost; } } } } setModelUsage(Array.from(usageMap.values())); } else { setModelUsage([]); } } catch (err) { setError(err instanceof Error ? err.message : "An error occurred"); } finally { setLoading(false); setLoadingTransactions(false); } }; const handleAddPaymentMethod = async () => { setProcessingPaymentSetup(true); setTopUpError(null); try { const serverUrl = import.meta.env.ZUPLO_SERVER_URL || window.location.origin; const setupPaymentRequest = new Request( `${serverUrl}/v1/developer/wallet/setup-payment`, { method: "POST", headers: { "Content-Type": "application/json", } } ); const signedRequest = await context.signRequest(setupPaymentRequest); const response = await fetch(signedRequest); if (!response.ok) { throw new Error("Failed to generate payment setup URL"); } const data = await response.json(); if (!data.customer?.checkout_url) { throw new Error("No checkout URL returned from server"); } // Redirect to Stripe payment setup window.location.href = data.customer.checkout_url; } catch (err) { setTopUpError(err instanceof Error ? err.message : "Failed to setup payment method"); } finally { setProcessingPaymentSetup(false); } }; const handleDeletePaymentMethod = async (paymentMethodId: string) => { setPaymentMethodToDelete(paymentMethodId); setShowDeleteConfirm(true); }; const confirmDeletePaymentMethod = async () => { if (!paymentMethodToDelete) return; setDeletingPaymentMethod(paymentMethodToDelete); setShowDeleteConfirm(false); setTopUpError(null); try { const serverUrl = import.meta.env.ZUPLO_SERVER_URL || window.location.origin; const deleteRequest = new Request( `${serverUrl}/v1/developer/wallet/payment-method/${paymentMethodToDelete}`, { method: "DELETE", headers: { "Content-Type": "application/json", } } ); const signedRequest = await context.signRequest(deleteRequest); const response = await fetch(signedRequest); if (!response.ok) { throw new Error("Failed to delete payment method"); } // Refresh wallet data to update payment methods list await fetchWalletBalance(); } catch (err) { setTopUpError(err instanceof Error ? err.message : "Failed to delete payment method"); } finally { setDeletingPaymentMethod(null); setPaymentMethodToDelete(null); } }; const cancelDeletePaymentMethod = () => { setShowDeleteConfirm(false); setPaymentMethodToDelete(null); }; const openTopUpModal = () => { if (!hasPaymentMethod) { setTopUpError("Please add a payment method first"); return; } setTopUpAmount("10"); setTopUpError(null); setTopUpSuccess(false); setShowTopUpModal(true); }; const closeTopUpModal = () => { setShowTopUpModal(false); setTopUpAmount("10"); }; const handleConfirmTopUp = async () => { const amount = parseFloat(topUpAmount); if (isNaN(amount) || amount < 1) { setTopUpError("Minimum top-up amount is $1"); return; } setProcessingTopUp(true); setTopUpError(null); setTopUpSuccess(false); try { const serverUrl = import.meta.env.ZUPLO_SERVER_URL || window.location.origin; const topUpRequest = new Request( `${serverUrl}/v1/developer/wallet/topup`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ amount }) } ); const signedTopUpRequest = await context.signRequest(topUpRequest); const topUpResponse = await fetch(signedTopUpRequest); if (!topUpResponse.ok) { throw new Error("Failed to process top-up"); } const transactionData = await topUpResponse.json(); let transaction = transactionData.wallet_transaction; if (!transaction) { throw new Error("No transaction data returned from server"); } // Poll for transaction status until it's settled or failed // Lago creates the transaction as "pending", then charges Stripe, then updates to "settled" const maxAttempts = 20; // 20 attempts const pollInterval = 1000; // 1 second between attempts let attempts = 0; while (transaction.status === "pending" && attempts < maxAttempts) { await new Promise(resolve => setTimeout(resolve, pollInterval)); attempts++; // Refresh wallet data to get updated transaction status const pollRequest = new Request( `${serverUrl}/v1/developer/wallet`, { method: "GET", headers: { "Content-Type": "application/json", } } ); const signedPollRequest = await context.signRequest(pollRequest); const pollResponse = await fetch(signedPollRequest); if (pollResponse.ok) { const pollData = await pollResponse.json(); // Find our transaction in the list const updatedTransaction = pollData.wallet_transactions?.find( (tx: WalletTransaction) => tx.lago_id === transaction.lago_id ); if (updatedTransaction) { transaction = updatedTransaction; } } } if (transaction.status === "settled") { // Charge succeeded! setTopUpSuccess(true); setShowTopUpModal(false); setTopUpAmount("10"); // Refresh wallet data (balance, payment method, and transactions) await fetchWalletBalance(); } else if (transaction.status === "pending") { // Still pending after max attempts throw new Error("Payment is taking longer than expected. Please refresh the page in a moment to see your updated balance."); } else { // Failed or other status throw new Error(`Payment ${transaction.status}. Please try again or contact support.`); } } catch (err) { setTopUpError(err instanceof Error ? err.message : "Failed to process top-up"); } finally { setProcessingTopUp(false); } }; const fetchModelPricing = async () => { setLoadingPricing(true); setPricingError(null); try { const serverUrl = import.meta.env.ZUPLO_SERVER_URL || window.location.origin; const pricingRequest = new Request( `${serverUrl}/v1/developer/pricing`, { method: "GET", headers: { "Content-Type": "application/json", } } ); // Fetch pricing without authentication const response = await fetch(pricingRequest); if (!response.ok) { throw new Error("Failed to fetch model pricing"); } const data = await response.json(); // Transform the data to our simpler format const pricingData: ModelPricing[] = data.data.map((model: any) => ({ model_name: model.model_name, input_cost_per_token: typeof model.model_info.input_cost_per_token === 'string' ? parseFloat(model.model_info.input_cost_per_token) : model.model_info.input_cost_per_token, output_cost_per_token: typeof model.model_info.output_cost_per_token === 'string' ? parseFloat(model.model_info.output_cost_per_token) : model.model_info.output_cost_per_token, })); setModelPricing(pricingData); } catch (err) { setPricingError(err instanceof Error ? err.message : "Failed to fetch pricing"); } finally { setLoadingPricing(false); } }; useEffect(() => { // Always fetch pricing data, even when not authenticated fetchModelPricing(); // Only fetch wallet balance when authenticated if (auth.isAuthenticated) { fetchWalletBalance(); } }, [auth.isAuthenticated]); if (!auth.isAuthenticated) { return (
Billing - Public AI Gateway

Billing

{/* Login prompt */}

Track Your Usage

Log in to view your wallet balance, usage statistics, and transaction history.

{/* Model Pricing - Public */}

Model Pricing

{loadingPricing ? (

Loading pricing data...

) : pricingError ? (

{pricingError}

) : modelPricing.length === 0 ? (

No pricing data available

) : (
{modelPricing .sort((a, b) => a.model_name.localeCompare(b.model_name)) .map((pricing) => ( ))}
Model Input Cost per 1M Tokens Output Cost per 1M Tokens
{pricing.model_name} ${(pricing.input_cost_per_token * 1000000).toFixed(2)} ${(pricing.output_cost_per_token * 1000000).toFixed(2)}
)}
); } return (
Billing - Public AI Gateway

Billing

{/* Wallet Balance Section */}

Wallet Balance

{portalUrl && ( View billing portal )}
{loading ? (

Loading your balance...

) : error ? (

{error}

) : (
{/* Remaining Balance (Primary Display) */}
${balance} USD
{/* Breakdown */}
Total credits: ${totalCredits}
Current billing period usage: -${currentUsage.toFixed(2)}
Remaining balance: ${balance}
{balance && parseFloat(balance) <= 0.10 && (

Your balance is low. Please add credits to continue using the API.

)} {/* Top Up Button */} {topUpSuccess && (

Credits added successfully!

)} {hasPaymentMethod ? ( ) : ( )}
)}
{/* Payment Method Section - Only show if user has payment methods */} {paymentMethods.length > 0 && (

Payment Method

{(() => { const pm = paymentMethods[0]; return (
{pm.card && ( <>

{pm.card.brand.charAt(0).toUpperCase() + pm.card.brand.slice(1)} •••• {pm.card.last4}

Expires {pm.card.exp_month}/{pm.card.exp_year}

)}
); })()} {topUpError && (

{topUpError}

)}
)} {/* Model Usage Section */}

Current Billing Period Usage

{billingPeriod && (

{formatBillingPeriodDate(billingPeriod.from)} - {formatBillingPeriodDate(billingPeriod.to)}

)}
{loadingTransactions ? (

Loading usage data...

) : (() => { const usedModels = modelUsage.filter(usage => usage.totalTokens > 0); return usedModels.length === 0 ? (

No usage data for this billing period yet

) : (
{usedModels .sort((a, b) => b.totalCost - a.totalCost) .map((usage) => ( ))}
Model Input Tokens Output Tokens Total Tokens Cost
{usage.model} {usage.inputTokens.toLocaleString()} (${usage.inputCost.toFixed(4)}) {usage.outputTokens.toLocaleString()} (${usage.outputCost.toFixed(4)}) {usage.totalTokens.toLocaleString()} ${usage.totalCost.toFixed(4)}
Total {usedModels.reduce((sum, u) => sum + u.inputTokens, 0).toLocaleString()} {usedModels.reduce((sum, u) => sum + u.outputTokens, 0).toLocaleString()} {usedModels.reduce((sum, u) => sum + u.totalTokens, 0).toLocaleString()} ${usedModels.reduce((sum, u) => sum + u.totalCost, 0).toFixed(4)}
); })()}
{/* Transaction History */}

Recent Transactions

{loadingTransactions ? (

Loading transactions...

) : (() => { const settledTransactions = transactions.filter(tx => tx.status === "settled"); return settledTransactions.length === 0 ? (

No transactions yet

) : (
{settledTransactions.slice(0, 10).map((tx) => (
{tx.name && (

{tx.name}

)}

{formatRelativeTime(tx.created_at)}

{(() => { const amount = parseFloat(tx.credit_amount || tx.amount || "0"); const isOutbound = tx.transaction_type === "outbound"; const displayAmount = isOutbound ? -Math.abs(amount) : Math.abs(amount); return (

{isOutbound ? '' : '+'}${displayAmount.toFixed(2)}

); })()}
))}
); })()}
{/* Model Pricing */}

Model Pricing

{loadingPricing ? (

Loading pricing data...

) : pricingError ? (

{pricingError}

) : modelPricing.length === 0 ? (

No pricing data available

) : (
{modelPricing .sort((a, b) => a.model_name.localeCompare(b.model_name)) .map((pricing) => ( ))}
Model Input Cost per 1M Tokens Output Cost per 1M Tokens
{pricing.model_name} ${(pricing.input_cost_per_token * 1000000).toFixed(2)} ${(pricing.output_cost_per_token * 1000000).toFixed(2)}
)}
{/* Delete Confirmation Modal */} {showDeleteConfirm && (

Delete Payment Method

Are you sure you want to delete this payment method? This action cannot be undone.

)} {/* Top Up Modal */} {showTopUpModal && (

Top Up Credits

{topUpError && (

{topUpError}

)}
$ setTopUpAmount(e.target.value)} className="w-full pl-8 pr-3 py-2 border border-border rounded-lg bg-card text-foreground focus:ring-2 focus:ring-ring focus:border-transparent" disabled={processingTopUp} />

Minimum top-up amount is $1. Your payment method will be charged immediately.

{processingTopUp && (

Processing your payment...

)}
)}
); };