import { useState, useEffect } from 'react'; import { RankingTable } from './RankingTable'; import { UserDetailCard } from './UserDetailCard'; interface Period { index: number; startSnapshotId: number | null; startAt: string | null; endAt: string | null; isCurrent: boolean; } interface PeriodSummary { period: { index: number; startAt: string | null; endAt: string | null; isCurrent: boolean; }; totals: { totalCost: number; userCount: number; }; ranking: Array<{ id: string; name: string; cost: number; share: number; isMe: boolean; rawStart: any; rawEnd: any; periodTokens: number; periodRequests: number; }>; } interface CurrentPeriodProps { period: Period; apiKey: string; userId: string; } export function CurrentPeriod({ period, apiKey, userId }: CurrentPeriodProps) { const [summary, setSummary] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(''); useEffect(() => { fetchSummary(); }, [period.index]); const fetchSummary = async () => { setIsLoading(true); setError(''); try { const response = await fetch(`/api/periods/${period.index}/summary`, { headers: { 'X-API-Key': apiKey, }, }); if (!response.ok) { throw new Error(`Failed to fetch period summary: ${response.status}`); } const data = await response.json(); setSummary(data); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load period data'); } finally { setIsLoading(false); } }; const formatDate = (dateString: string | null, isEndDate = false) => { if (!dateString && isEndDate) return 'Now'; if (!dateString) return 'Beginning'; const date = new Date(dateString); return date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false, }); }; const formatCurrency = (amount: number) => { return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2, }).format(amount); }; const myUser = summary?.ranking.find(u => u.isMe); if (isLoading) { return (
); } if (error || !summary) { return (

Failed to Load Period Data

{error}

); } return (
{/* Header with period info */}

Current Period: {formatDate(summary.period.startAt)} → {formatDate(summary.period.endAt, true)}

{formatCurrency(summary.totals.totalCost)}
Total Cost
{summary.totals.userCount}
Active Users
{myUser ? formatCurrency(myUser.cost) : '$0.00'}
Your Cost ({myUser ? (myUser.share * 100).toFixed(2) : '0.00'}%)
{/* Ranking Table */} {/* User Detail Card */}
); }