feat: Token Limits UI - Phase 2 (Dashboard + User Management)
Token Usage Dashboard (/admin/token-usage): - Add Monthly Limit column with edit functionality - Add % Used column with progress bars - Color-coded alerts (green/yellow/orange/red) - Real-time limit updates via API - Alert banners for users >80% and >100% User Management (/admin/users): - Add Token Limit column - Show percentage used with progress indicator - Color-coded badges for usage levels Admin Dashboard (/admin): - Add AI Token Usage card - Display total tokens, requests, and cost - Link to detailed token usage page All changes are fully responsive and dark-mode compatible. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
@@ -9,15 +9,24 @@ import {
|
|||||||
Zap,
|
Zap,
|
||||||
Server,
|
Server,
|
||||||
Clock,
|
Clock,
|
||||||
ShieldAlert
|
ShieldAlert,
|
||||||
|
Gauge,
|
||||||
|
TrendingUp
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
|
|
||||||
|
interface TokenStats {
|
||||||
|
total_tokens: number;
|
||||||
|
total_requests: number;
|
||||||
|
total_cost_usd: number;
|
||||||
|
}
|
||||||
|
|
||||||
export default function AdminDashboard() {
|
export default function AdminDashboard() {
|
||||||
const [stats, setStats] = useState({
|
const [stats, setStats] = useState({
|
||||||
orgs: 0,
|
orgs: 0,
|
||||||
users: 0,
|
users: 0,
|
||||||
courses: 0
|
courses: 0
|
||||||
});
|
});
|
||||||
|
const [tokenStats, setTokenStats] = useState<TokenStats | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -25,9 +34,14 @@ export default function AdminDashboard() {
|
|||||||
try {
|
try {
|
||||||
// In a real app we'd have a specific stats endpoint,
|
// In a real app we'd have a specific stats endpoint,
|
||||||
// but for now we'll calculate from lists
|
// but for now we'll calculate from lists
|
||||||
const [org, users] = await Promise.all([
|
const [org, users, tokenResp] = await Promise.all([
|
||||||
cmsApi.getOrganization(),
|
cmsApi.getOrganization(),
|
||||||
cmsApi.getAllUsers()
|
cmsApi.getAllUsers(),
|
||||||
|
fetch(`${process.env.NEXT_PUBLIC_CMS_API_URL || 'http://localhost:3001'}/admin/token-usage`, {
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${localStorage.getItem('token')}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
]);
|
]);
|
||||||
|
|
||||||
setStats({
|
setStats({
|
||||||
@@ -35,6 +49,16 @@ export default function AdminDashboard() {
|
|||||||
users: users.length,
|
users: users.length,
|
||||||
courses: 0 // We'd need a global courses count
|
courses: 0 // We'd need a global courses count
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Load token stats
|
||||||
|
if (tokenResp.ok) {
|
||||||
|
const tokenData = await tokenResp.json();
|
||||||
|
setTokenStats({
|
||||||
|
total_tokens: tokenData.stats?.total_tokens || 0,
|
||||||
|
total_requests: tokenData.stats?.total_requests || 0,
|
||||||
|
total_cost_usd: tokenData.stats?.total_cost_usd || 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to load admin stats", err);
|
console.error("Failed to load admin stats", err);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -79,7 +103,7 @@ export default function AdminDashboard() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Stat Grid */}
|
{/* Stat Grid */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||||
{cards.map((card) => (
|
{cards.map((card) => (
|
||||||
<div key={card.label} className="p-8 rounded-3xl bg-white dark:bg-white/[0.02] border border-slate-200 dark:border-white/5 flex flex-col gap-4 shadow-sm dark:shadow-none">
|
<div key={card.label} className="p-8 rounded-3xl bg-white dark:bg-white/[0.02] border border-slate-200 dark:border-white/5 flex flex-col gap-4 shadow-sm dark:shadow-none">
|
||||||
<div className={`w-12 h-12 rounded-xl ${card.bg} flex items-center justify-center ${card.color}`}>
|
<div className={`w-12 h-12 rounded-xl ${card.bg} flex items-center justify-center ${card.color}`}>
|
||||||
@@ -92,6 +116,25 @@ export default function AdminDashboard() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
|
{/* AI Token Usage Card */}
|
||||||
|
<div className="p-8 rounded-3xl bg-white dark:bg-white/[0.02] border border-slate-200 dark:border-white/5 flex flex-col gap-4 shadow-sm dark:shadow-none">
|
||||||
|
<div className="w-12 h-12 rounded-xl bg-indigo-500/10 flex items-center justify-center text-indigo-600 dark:text-indigo-400">
|
||||||
|
<Gauge size={24} />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 dark:text-gray-500 mb-1">AI Token Usage</div>
|
||||||
|
<div className="text-4xl font-black text-slate-900 dark:text-white">
|
||||||
|
{loading ? "..." : tokenStats ? new Intl.NumberFormat('en-US', { notation: 'compact', compactDisplay: 'short' }).format(tokenStats.total_tokens) : 'N/A'}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-slate-500 dark:text-gray-500 mt-2">
|
||||||
|
{tokenStats ? `${new Intl.NumberFormat('en-US').format(tokenStats.total_requests)} requests • $${tokenStats.total_cost_usd.toFixed(2)}` : 'Loading...'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<a href="/admin/token-usage" className="text-xs font-bold text-indigo-600 dark:text-indigo-400 hover:text-indigo-500 flex items-center gap-1 mt-2">
|
||||||
|
View Details <TrendingUp className="w-3 h-3" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* System Health */}
|
{/* System Health */}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { ShieldCheck, TrendingUp, Users, AlertTriangle, DollarSign, Activity } from 'lucide-react';
|
import { ShieldCheck, TrendingUp, Users, AlertTriangle, DollarSign, Activity, Edit2, Save, X, Gauge } from 'lucide-react';
|
||||||
|
import { cmsApi } from '@/lib/api';
|
||||||
|
|
||||||
interface TokenUsage {
|
interface TokenUsage {
|
||||||
user_id: string;
|
user_id: string;
|
||||||
@@ -14,6 +15,8 @@ interface TokenUsage {
|
|||||||
ai_requests: number;
|
ai_requests: number;
|
||||||
last_used: string;
|
last_used: string;
|
||||||
estimated_cost_usd: number;
|
estimated_cost_usd: number;
|
||||||
|
monthly_token_limit?: number;
|
||||||
|
token_limit_reset_day?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TokenStats {
|
interface TokenStats {
|
||||||
@@ -26,12 +29,24 @@ interface TokenStats {
|
|||||||
avg_tokens_per_user: number;
|
avg_tokens_per_user: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface UserLimit {
|
||||||
|
user_id: string;
|
||||||
|
monthly_limit: number;
|
||||||
|
used_tokens: number;
|
||||||
|
remaining_tokens: number;
|
||||||
|
percentage_used: number;
|
||||||
|
reset_day: number;
|
||||||
|
}
|
||||||
|
|
||||||
export default function AdminTokenTracking() {
|
export default function AdminTokenTracking() {
|
||||||
const [usage, setUsage] = useState<TokenUsage[]>([]);
|
const [usage, setUsage] = useState<TokenUsage[]>([]);
|
||||||
const [stats, setStats] = useState<TokenStats | null>(null);
|
const [stats, setStats] = useState<TokenStats | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [filterRole, setFilterRole] = useState<string>('');
|
const [filterRole, setFilterRole] = useState<string>('');
|
||||||
const [sortBy, setSortBy] = useState<'total_tokens' | 'ai_requests' | 'estimated_cost_usd'>('total_tokens');
|
const [sortBy, setSortBy] = useState<'total_tokens' | 'ai_requests' | 'estimated_cost_usd' | 'percentage_used'>('total_tokens');
|
||||||
|
const [editingLimit, setEditingLimit] = useState<string | null>(null);
|
||||||
|
const [editValue, setEditValue] = useState<number>(0);
|
||||||
|
const [userLimits, setUserLimits] = useState<Record<string, UserLimit>>({});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadTokenUsage();
|
loadTokenUsage();
|
||||||
@@ -49,6 +64,37 @@ export default function AdminTokenTracking() {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setUsage(data.usage || []);
|
setUsage(data.usage || []);
|
||||||
setStats(data.stats);
|
setStats(data.stats);
|
||||||
|
|
||||||
|
// Load limits for each user
|
||||||
|
const limits: Record<string, UserLimit> = {};
|
||||||
|
for (const user of data.usage || []) {
|
||||||
|
try {
|
||||||
|
const limitResp = await fetch(
|
||||||
|
`${process.env.NEXT_PUBLIC_CMS_API_URL || 'http://localhost:3001'}/admin/users/${user.user_id}/token-limit/check`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${localStorage.getItem('token')}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (limitResp.ok) {
|
||||||
|
const limitData = await limitResp.json();
|
||||||
|
limits[user.user_id] = {
|
||||||
|
user_id: user.user_id,
|
||||||
|
monthly_limit: limitData.monthly_limit,
|
||||||
|
used_tokens: limitData.used_tokens,
|
||||||
|
remaining_tokens: limitData.remaining_tokens,
|
||||||
|
percentage_used: limitData.monthly_limit > 0
|
||||||
|
? Math.round((limitData.used_tokens / limitData.monthly_limit) * 100)
|
||||||
|
: 0,
|
||||||
|
reset_day: 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to load limit for user ${user.user_id}:`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setUserLimits(limits);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load token usage:', error);
|
console.error('Failed to load token usage:', error);
|
||||||
@@ -57,17 +103,84 @@ export default function AdminTokenTracking() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleUpdateLimit = async (userId: string) => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${process.env.NEXT_PUBLIC_CMS_API_URL || 'http://localhost:3001'}/admin/users/${userId}/token-limit`,
|
||||||
|
{
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${localStorage.getItem('token')}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
monthly_token_limit: editValue,
|
||||||
|
token_limit_reset_day: 1,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
// Reload limits
|
||||||
|
const limitResp = await fetch(
|
||||||
|
`${process.env.NEXT_PUBLIC_CMS_API_URL || 'http://localhost:3001'}/admin/users/${userId}/token-limit/check`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${localStorage.getItem('token')}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (limitResp.ok) {
|
||||||
|
const limitData = await limitResp.json();
|
||||||
|
setUserLimits(prev => ({
|
||||||
|
...prev,
|
||||||
|
[userId]: {
|
||||||
|
user_id: userId,
|
||||||
|
monthly_limit: limitData.monthly_limit,
|
||||||
|
used_tokens: limitData.used_tokens,
|
||||||
|
remaining_tokens: limitData.remaining_tokens,
|
||||||
|
percentage_used: limitData.monthly_limit > 0
|
||||||
|
? Math.round((limitData.used_tokens / limitData.monthly_limit) * 100)
|
||||||
|
: 0,
|
||||||
|
reset_day: 1,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
setEditingLimit(null);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to update limit:', error);
|
||||||
|
alert('Failed to update token limit');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getLimitColor = (percentage: number) => {
|
||||||
|
if (percentage >= 100) return 'text-red-600 bg-red-50 dark:bg-red-900/20';
|
||||||
|
if (percentage >= 90) return 'text-orange-600 bg-orange-50 dark:bg-orange-900/20';
|
||||||
|
if (percentage >= 80) return 'text-yellow-600 bg-yellow-50 dark:bg-yellow-900/20';
|
||||||
|
return 'text-green-600 bg-green-50 dark:bg-green-900/20';
|
||||||
|
};
|
||||||
|
|
||||||
|
const getProgressBarColor = (percentage: number) => {
|
||||||
|
if (percentage >= 100) return 'bg-red-600';
|
||||||
|
if (percentage >= 90) return 'bg-orange-600';
|
||||||
|
if (percentage >= 80) return 'bg-yellow-600';
|
||||||
|
return 'bg-green-600';
|
||||||
|
};
|
||||||
|
|
||||||
const filteredUsage = usage
|
const filteredUsage = usage
|
||||||
.filter(u => !filterRole || u.role === filterRole)
|
.filter(u => !filterRole || u.role === filterRole)
|
||||||
.sort((a, b) => b[sortBy] - a[sortBy]);
|
.sort((a, b) => {
|
||||||
|
if (sortBy === 'percentage_used') {
|
||||||
|
const aPct = userLimits[a.user_id]?.percentage_used || 0;
|
||||||
|
const bPct = userLimits[b.user_id]?.percentage_used || 0;
|
||||||
|
return bPct - aPct;
|
||||||
|
}
|
||||||
|
return b[sortBy] - a[sortBy];
|
||||||
|
});
|
||||||
|
|
||||||
const formatNumber = (num: number) => {
|
const formatNumber = (num: number) => new Intl.NumberFormat('en-US').format(num);
|
||||||
return new Intl.NumberFormat('en-US').format(num);
|
const formatCurrency = (num: number) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(num);
|
||||||
};
|
|
||||||
|
|
||||||
const formatCurrency = (num: number) => {
|
|
||||||
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(num);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
<div className="min-h-screen bg-gray-50 dark:bg-gray-900">
|
||||||
@@ -82,7 +195,7 @@ export default function AdminTokenTracking() {
|
|||||||
Control Global - Token Usage
|
Control Global - Token Usage
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||||
Monitoreo de tokens de IA y costos del sistema
|
Monitoreo de tokens de IA, límites mensuales y costos del sistema
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -157,16 +270,29 @@ export default function AdminTokenTracking() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Alerts */}
|
{/* Alerts */}
|
||||||
{usage.some(u => u.total_tokens > 1000000) && (
|
{Object.values(userLimits).some(ul => ul.percentage_used >= 80) && (
|
||||||
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-6 flex items-start gap-3">
|
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4 mb-6 flex items-start gap-3">
|
||||||
<AlertTriangle className="w-5 h-5 text-yellow-600 shrink-0 mt-0.5" />
|
<AlertTriangle className="w-5 h-5 text-yellow-600 shrink-0 mt-0.5" />
|
||||||
<div>
|
<div>
|
||||||
<h4 className="font-semibold text-yellow-900 dark:text-yellow-100 text-sm">
|
<h4 className="font-semibold text-yellow-900 dark:text-yellow-100 text-sm">
|
||||||
Usuarios con alto consumo detectado
|
Usuarios cerca del límite
|
||||||
</h4>
|
</h4>
|
||||||
<p className="text-xs text-yellow-700 dark:text-yellow-300 mt-1">
|
<p className="text-xs text-yellow-700 dark:text-yellow-300 mt-1">
|
||||||
{usage.filter(u => u.total_tokens > 1000000).length} usuario(s) han superado 1M de tokens.
|
{Object.values(userLimits).filter(ul => ul.percentage_used >= 80 && ul.percentage_used < 100).length} usuario(s) han usado ≥80% de su límite mensual.
|
||||||
Considere implementar límites de uso.
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{Object.values(userLimits).some(ul => ul.percentage_used >= 100) && (
|
||||||
|
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-6 flex items-start gap-3">
|
||||||
|
<AlertTriangle className="w-5 h-5 text-red-600 shrink-0 mt-0.5" />
|
||||||
|
<div>
|
||||||
|
<h4 className="font-semibold text-red-900 dark:text-red-100 text-sm">
|
||||||
|
Límite excedido
|
||||||
|
</h4>
|
||||||
|
<p className="text-xs text-red-700 dark:text-red-300 mt-1">
|
||||||
|
{Object.values(userLimits).filter(ul => ul.percentage_used >= 100).length} usuario(s) han excedido su límite mensual.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -174,7 +300,7 @@ export default function AdminTokenTracking() {
|
|||||||
|
|
||||||
{/* Filters */}
|
{/* Filters */}
|
||||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 mb-6">
|
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 mb-6">
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4 flex-wrap">
|
||||||
<div>
|
<div>
|
||||||
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
<label className="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">
|
||||||
Filtrar por Rol
|
Filtrar por Rol
|
||||||
@@ -203,6 +329,7 @@ export default function AdminTokenTracking() {
|
|||||||
<option value="total_tokens">Total Tokens</option>
|
<option value="total_tokens">Total Tokens</option>
|
||||||
<option value="ai_requests">Requests IA</option>
|
<option value="ai_requests">Requests IA</option>
|
||||||
<option value="estimated_cost_usd">Costo USD</option>
|
<option value="estimated_cost_usd">Costo USD</option>
|
||||||
|
<option value="percentage_used">% Usado</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -210,10 +337,14 @@ export default function AdminTokenTracking() {
|
|||||||
|
|
||||||
{/* Usage Table */}
|
{/* Usage Table */}
|
||||||
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
|
<div className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
|
||||||
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
|
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
|
||||||
<h3 className="font-semibold text-gray-900 dark:text-white">
|
<h3 className="font-semibold text-gray-900 dark:text-white">
|
||||||
Uso por Usuario
|
Uso por Usuario
|
||||||
</h3>
|
</h3>
|
||||||
|
<div className="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
|
||||||
|
<Gauge className="w-4 h-4" />
|
||||||
|
<span>Límites mensuales configurables</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full">
|
<table className="w-full">
|
||||||
@@ -225,11 +356,11 @@ export default function AdminTokenTracking() {
|
|||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||||
Rol
|
Rol
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
<th className="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||||
Input Tokens
|
Límite Mensual
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
<th className="px-6 py-3 text-center text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||||
Output Tokens
|
% Usado
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||||
Total Tokens
|
Total Tokens
|
||||||
@@ -240,13 +371,15 @@ export default function AdminTokenTracking() {
|
|||||||
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||||
Costo USD
|
Costo USD
|
||||||
</th>
|
</th>
|
||||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
|
||||||
Última Actividad
|
|
||||||
</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
|
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
{filteredUsage.map((user) => (
|
{filteredUsage.map((user) => {
|
||||||
|
const limit = userLimits[user.user_id];
|
||||||
|
const percentage = limit?.percentage_used || 0;
|
||||||
|
const isUnlimited = limit?.monthly_limit === 0;
|
||||||
|
|
||||||
|
return (
|
||||||
<tr key={user.user_id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
|
<tr key={user.user_id} className="hover:bg-gray-50 dark:hover:bg-gray-700/50">
|
||||||
<td className="px-6 py-4 whitespace-nowrap">
|
<td className="px-6 py-4 whitespace-nowrap">
|
||||||
<div>
|
<div>
|
||||||
@@ -267,11 +400,71 @@ export default function AdminTokenTracking() {
|
|||||||
{user.role}
|
{user.role}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm text-gray-500 dark:text-gray-400">
|
<td className="px-6 py-4 whitespace-nowrap text-center">
|
||||||
{formatNumber(user.input_tokens)}
|
{editingLimit === user.user_id ? (
|
||||||
|
<div className="flex items-center justify-center gap-2">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={editValue}
|
||||||
|
onChange={(e) => setEditValue(parseInt(e.target.value) || 0)}
|
||||||
|
className="w-24 px-2 py-1 border border-gray-300 dark:border-gray-600 rounded text-sm dark:bg-gray-700 dark:text-white"
|
||||||
|
placeholder="0 = unlimited"
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={() => handleUpdateLimit(user.user_id)}
|
||||||
|
className="p-1 text-green-600 hover:bg-green-50 rounded"
|
||||||
|
>
|
||||||
|
<Save className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setEditingLimit(null)}
|
||||||
|
className="p-1 text-gray-600 hover:bg-gray-100 rounded"
|
||||||
|
>
|
||||||
|
<X className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center justify-center gap-2">
|
||||||
|
<span className={`text-sm font-medium ${
|
||||||
|
isUnlimited ? 'text-gray-400' :
|
||||||
|
percentage >= 100 ? 'text-red-600' :
|
||||||
|
percentage >= 80 ? 'text-yellow-600' :
|
||||||
|
'text-gray-900 dark:text-white'
|
||||||
|
}`}>
|
||||||
|
{isUnlimited ? '∞' : formatNumber(limit?.monthly_limit || 0)}
|
||||||
|
</span>
|
||||||
|
{!isUnlimited && limit && (
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setEditingLimit(user.user_id);
|
||||||
|
setEditValue(limit.monthly_limit);
|
||||||
|
}}
|
||||||
|
className="p-1 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors"
|
||||||
|
title="Edit limit"
|
||||||
|
>
|
||||||
|
<Edit2 className="w-3 h-3" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm text-gray-500 dark:text-gray-400">
|
<td className="px-6 py-4 whitespace-nowrap text-center">
|
||||||
{formatNumber(user.output_tokens)}
|
{isUnlimited ? (
|
||||||
|
<span className="text-xs text-gray-400">Unlimited</span>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col items-center gap-1">
|
||||||
|
<span className={`text-xs font-bold px-2 py-1 rounded ${getLimitColor(percentage)}`}>
|
||||||
|
{percentage}%
|
||||||
|
</span>
|
||||||
|
<div className="w-24 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
className={`h-full ${getProgressBarColor(percentage)} transition-all duration-500`}
|
||||||
|
style={{ width: `${Math.min(percentage, 100)}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-right">
|
<td className="px-6 py-4 whitespace-nowrap text-right">
|
||||||
<span className={`text-sm font-medium ${
|
<span className={`text-sm font-medium ${
|
||||||
@@ -288,11 +481,9 @@ export default function AdminTokenTracking() {
|
|||||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium text-gray-900 dark:text-white">
|
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium text-gray-900 dark:text-white">
|
||||||
{formatCurrency(user.estimated_cost_usd)}
|
{formatCurrency(user.estimated_cost_usd)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
|
|
||||||
{new Date(user.last_used).toLocaleDateString()}
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
);
|
||||||
|
})}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,15 +3,21 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { cmsApi, User, Organization } from '@/lib/api';
|
import { cmsApi, User, Organization } from '@/lib/api';
|
||||||
import { useAuth } from '@/context/AuthContext';
|
import { useAuth } from '@/context/AuthContext';
|
||||||
import { UserCog, Mail, Search, Filter, ShieldCheck, Plus, X, UserPlus, Key, User as UserIcon, Building2 } from 'lucide-react';
|
import { UserCog, Mail, Search, Filter, ShieldCheck, Plus, X, UserPlus, Key, User as UserIcon, Building2, Gauge } from 'lucide-react';
|
||||||
|
|
||||||
|
interface UserWithLimit extends User {
|
||||||
|
monthly_token_limit?: number;
|
||||||
|
token_usage_percentage?: number;
|
||||||
|
}
|
||||||
|
|
||||||
export default function UsersPage() {
|
export default function UsersPage() {
|
||||||
const [users, setUsers] = useState<User[]>([]);
|
const [users, setUsers] = useState<UserWithLimit[]>([]);
|
||||||
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [searchTerm, setSearchTerm] = useState('');
|
const [searchTerm, setSearchTerm] = useState('');
|
||||||
const [roleFilter, setRoleFilter] = useState('');
|
const [roleFilter, setRoleFilter] = useState('');
|
||||||
const { user: currentUser } = useAuth();
|
const { user: currentUser } = useAuth();
|
||||||
|
const [tokenLimits, setTokenLimits] = useState<Record<string, {limit: number, percentage: number}>>({});
|
||||||
|
|
||||||
// Create User States
|
// Create User States
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||||
@@ -34,7 +40,34 @@ export default function UsersPage() {
|
|||||||
cmsApi.getOrganization()
|
cmsApi.getOrganization()
|
||||||
]);
|
]);
|
||||||
setUsers(usersData);
|
setUsers(usersData);
|
||||||
setOrganizations([orgData]); // Single tenant - wrap in array for compatibility
|
setOrganizations([orgData]);
|
||||||
|
|
||||||
|
// Load token limits for each user
|
||||||
|
const limits: Record<string, {limit: number, percentage: number}> = {};
|
||||||
|
for (const user of usersData) {
|
||||||
|
try {
|
||||||
|
const resp = await fetch(
|
||||||
|
`${process.env.NEXT_PUBLIC_CMS_API_URL || 'http://localhost:3001'}/admin/users/${user.id}/token-limit/check`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${localStorage.getItem('token')}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (resp.ok) {
|
||||||
|
const data = await resp.json();
|
||||||
|
limits[user.id] = {
|
||||||
|
limit: data.monthly_limit,
|
||||||
|
percentage: data.monthly_limit > 0
|
||||||
|
? Math.round((data.used_tokens / data.monthly_limit) * 100)
|
||||||
|
: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`Failed to load limit for user ${user.id}:`, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setTokenLimits(limits);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load data', error);
|
console.error('Failed to load data', error);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -71,6 +104,8 @@ export default function UsersPage() {
|
|||||||
return matchesSearch && matchesRole;
|
return matchesSearch && matchesRole;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const formatNumber = (num: number) => new Intl.NumberFormat('en-US').format(num);
|
||||||
|
|
||||||
if (currentUser?.role !== 'admin') {
|
if (currentUser?.role !== 'admin') {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center min-h-[60vh] text-center p-4">
|
<div className="flex flex-col items-center justify-center min-h-[60vh] text-center p-4">
|
||||||
@@ -135,6 +170,7 @@ export default function UsersPage() {
|
|||||||
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400">User</th>
|
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400">User</th>
|
||||||
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400">Role</th>
|
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400">Role</th>
|
||||||
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400">Organization</th>
|
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400">Organization</th>
|
||||||
|
<th className="px-6 py-4 text-center text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400">Token Limit</th>
|
||||||
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400 text-right">Actions</th>
|
<th className="px-6 py-4 text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-gray-400 text-right">Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -188,6 +224,38 @@ export default function UsersPage() {
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
|
<td className="px-6 py-4 text-center">
|
||||||
|
{tokenLimits[u.id] ? (
|
||||||
|
<div className="flex flex-col items-center gap-1">
|
||||||
|
<span className={`text-xs font-bold px-2 py-1 rounded ${
|
||||||
|
tokenLimits[u.id].percentage >= 100 ? 'text-red-600 bg-red-50 dark:bg-red-900/20' :
|
||||||
|
tokenLimits[u.id].percentage >= 80 ? 'text-yellow-600 bg-yellow-50 dark:bg-yellow-900/20' :
|
||||||
|
tokenLimits[u.id].percentage >= 50 ? 'text-blue-600 bg-blue-50 dark:bg-blue-900/20' :
|
||||||
|
'text-green-600 bg-green-50 dark:bg-green-900/20'
|
||||||
|
}`}>
|
||||||
|
{tokenLimits[u.id].limit === 0 ? '∞' : `${tokenLimits[u.id].percentage}%`}
|
||||||
|
</span>
|
||||||
|
{tokenLimits[u.id].limit > 0 && (
|
||||||
|
<div className="w-20 h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
className={`h-full ${
|
||||||
|
tokenLimits[u.id].percentage >= 100 ? 'bg-red-600' :
|
||||||
|
tokenLimits[u.id].percentage >= 80 ? 'bg-yellow-600' :
|
||||||
|
tokenLimits[u.id].percentage >= 50 ? 'bg-blue-600' :
|
||||||
|
'bg-green-600'
|
||||||
|
}`}
|
||||||
|
style={{ width: `${Math.min(tokenLimits[u.id].percentage, 100)}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<span className="text-[9px] text-gray-400">
|
||||||
|
{tokenLimits[u.id].limit === 0 ? 'Unlimited' : formatNumber(tokenLimits[u.id].limit)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-gray-400">-</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
<td className="px-6 py-4 text-right">
|
<td className="px-6 py-4 text-right">
|
||||||
<button className="p-2 hover:bg-slate-200 dark:hover:bg-white/10 rounded-lg transition-all text-slate-400 hover:text-slate-900 dark:hover:text-white opacity-0 group-hover:opacity-100 shadow-sm">
|
<button className="p-2 hover:bg-slate-200 dark:hover:bg-white/10 rounded-lg transition-all text-slate-400 hover:text-slate-900 dark:hover:text-white opacity-0 group-hover:opacity-100 shadow-sm">
|
||||||
<UserCog className="w-4 h-4" />
|
<UserCog className="w-4 h-4" />
|
||||||
|
|||||||
Reference in New Issue
Block a user