feat: API analytics dashboard with i18n and theme support
Next.js full-stack analytics dashboard for new-api. - Direct PostgreSQL readonly queries on logs table - 5 pages: Dashboard, Rankings, Aggregation, Logs, Detail - Dark/Light/System theme with CSS variables - Chinese/English i18n (default Chinese) - Recharts with dual Y-axis for input/output tokens - Lucide icons + Motion animations - Docker + docker-compose with external sinobridge network, port 8019
This commit is contained in:
18
lib/db.ts
Normal file
18
lib/db.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Pool, type QueryResultRow } from "pg";
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.PG_CONNECTION_STRING,
|
||||
max: 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
|
||||
export async function query<T extends QueryResultRow = QueryResultRow>(
|
||||
text: string,
|
||||
params?: (string | number | boolean | null)[]
|
||||
): Promise<T[]> {
|
||||
const { rows } = await pool.query<T>(text, params);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export default pool;
|
||||
190
lib/i18n.tsx
Normal file
190
lib/i18n.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useState, useEffect, type ReactNode } from "react";
|
||||
|
||||
export type Locale = "zh" | "en";
|
||||
|
||||
const translations = {
|
||||
zh: {
|
||||
// nav
|
||||
"nav.overview": "总览",
|
||||
"nav.rankings": "排名",
|
||||
"nav.aggregation": "聚合",
|
||||
"nav.logs": "日志",
|
||||
// common
|
||||
"common.loading": "加载中...",
|
||||
"common.noData": "暂无数据",
|
||||
"common.records": "条记录",
|
||||
"common.systemOnline": "系统在线",
|
||||
"common.back": "返回",
|
||||
"common.backToRankings": "返回排名",
|
||||
"common.prevPage": "上一页",
|
||||
"common.nextPage": "下一页",
|
||||
"common.share": "占比",
|
||||
// time range
|
||||
"time.today": "今日",
|
||||
"time.7d": "7 天",
|
||||
"time.30d": "30 天",
|
||||
"time.all": "全部",
|
||||
// granularity
|
||||
"gran.day": "日",
|
||||
"gran.week": "周",
|
||||
"gran.month": "月",
|
||||
// metrics
|
||||
"metric.token": "Token",
|
||||
"metric.calls": "调用量",
|
||||
// dashboard
|
||||
"dash.title": "仪表盘",
|
||||
"dash.totalCalls": "调用次数",
|
||||
"dash.tokenUsage": "Token 消耗",
|
||||
"dash.activeUsers": "活跃用户",
|
||||
"dash.activeModels": "活跃模型",
|
||||
"dash.trend": "使用趋势",
|
||||
"dash.userTop10": "用户 Top 10 — Token 消耗",
|
||||
"dash.modelTop10": "模型 Top 10 — Token 消耗",
|
||||
// table headers
|
||||
"th.rank": "#",
|
||||
"th.name": "名称",
|
||||
"th.user": "用户",
|
||||
"th.calls": "调用次数",
|
||||
"th.input": "输入",
|
||||
"th.output": "输出",
|
||||
"th.totalToken": "总 Token",
|
||||
"th.time": "时间",
|
||||
"th.realModel": "真实模型",
|
||||
"th.channel": "渠道",
|
||||
"th.latency": "耗时",
|
||||
// rankings
|
||||
"rank.title": "排名",
|
||||
"rank.user": "用户",
|
||||
"rank.model": "模型",
|
||||
"rank.channel": "渠道",
|
||||
// aggregation
|
||||
"agg.title": "用户聚合",
|
||||
"agg.userCount": "用户数",
|
||||
"agg.totalCalls": "总调用",
|
||||
"agg.totalToken": "总 Token",
|
||||
// logs
|
||||
"logs.title": "日志明细",
|
||||
"logs.filterUser": "用户名",
|
||||
"logs.filterModel": "模型",
|
||||
"logs.filterToken": "Token 名称",
|
||||
// detail
|
||||
"detail.user": "用户",
|
||||
"detail.model": "模型",
|
||||
"detail.channel": "渠道",
|
||||
"detail.trend": "使用趋势",
|
||||
"detail.modelDist": "模型分布",
|
||||
"detail.userDist": "用户分布",
|
||||
// theme
|
||||
"theme.light": "浅色",
|
||||
"theme.dark": "深色",
|
||||
"theme.system": "系统",
|
||||
},
|
||||
en: {
|
||||
"nav.overview": "Overview",
|
||||
"nav.rankings": "Rankings",
|
||||
"nav.aggregation": "Aggregation",
|
||||
"nav.logs": "Logs",
|
||||
"common.loading": "Loading...",
|
||||
"common.noData": "No data",
|
||||
"common.records": "records",
|
||||
"common.systemOnline": "System Online",
|
||||
"common.back": "Back",
|
||||
"common.backToRankings": "Back to Rankings",
|
||||
"common.prevPage": "Previous",
|
||||
"common.nextPage": "Next",
|
||||
"common.share": "Share",
|
||||
"time.today": "Today",
|
||||
"time.7d": "7 Days",
|
||||
"time.30d": "30 Days",
|
||||
"time.all": "All",
|
||||
"gran.day": "Day",
|
||||
"gran.week": "Week",
|
||||
"gran.month": "Month",
|
||||
"metric.token": "Token",
|
||||
"metric.calls": "Calls",
|
||||
"dash.title": "Dashboard",
|
||||
"dash.totalCalls": "Total Calls",
|
||||
"dash.tokenUsage": "Token Usage",
|
||||
"dash.activeUsers": "Active Users",
|
||||
"dash.activeModels": "Active Models",
|
||||
"dash.trend": "Usage Trend",
|
||||
"dash.userTop10": "User Top 10 — Token Usage",
|
||||
"dash.modelTop10": "Model Top 10 — Token Usage",
|
||||
"th.rank": "#",
|
||||
"th.name": "Name",
|
||||
"th.user": "User",
|
||||
"th.calls": "Calls",
|
||||
"th.input": "Input",
|
||||
"th.output": "Output",
|
||||
"th.totalToken": "Total Token",
|
||||
"th.time": "Time",
|
||||
"th.realModel": "Real Model",
|
||||
"th.channel": "Channel",
|
||||
"th.latency": "Latency",
|
||||
"rank.title": "Rankings",
|
||||
"rank.user": "User",
|
||||
"rank.model": "Model",
|
||||
"rank.channel": "Channel",
|
||||
"agg.title": "User Aggregation",
|
||||
"agg.userCount": "Users",
|
||||
"agg.totalCalls": "Total Calls",
|
||||
"agg.totalToken": "Total Token",
|
||||
"logs.title": "Log Details",
|
||||
"logs.filterUser": "Username",
|
||||
"logs.filterModel": "Model",
|
||||
"logs.filterToken": "Token Name",
|
||||
"detail.user": "User",
|
||||
"detail.model": "Model",
|
||||
"detail.channel": "Channel",
|
||||
"detail.trend": "Usage Trend",
|
||||
"detail.modelDist": "Model Distribution",
|
||||
"detail.userDist": "User Distribution",
|
||||
"theme.light": "Light",
|
||||
"theme.dark": "Dark",
|
||||
"theme.system": "System",
|
||||
},
|
||||
} as const;
|
||||
|
||||
type TranslationKey = keyof typeof translations.zh;
|
||||
|
||||
interface I18nContextType {
|
||||
locale: Locale;
|
||||
setLocale: (l: Locale) => void;
|
||||
t: (key: TranslationKey) => string;
|
||||
}
|
||||
|
||||
const I18nContext = createContext<I18nContextType>({
|
||||
locale: "zh",
|
||||
setLocale: () => {},
|
||||
t: (key) => key,
|
||||
});
|
||||
|
||||
export function I18nProvider({ children }: { children: ReactNode }) {
|
||||
const [locale, setLocale] = useState<Locale>("zh");
|
||||
|
||||
useEffect(() => {
|
||||
const saved = localStorage.getItem("locale") as Locale | null;
|
||||
if (saved && (saved === "zh" || saved === "en")) setLocale(saved);
|
||||
}, []);
|
||||
|
||||
const handleSetLocale = (l: Locale) => {
|
||||
setLocale(l);
|
||||
localStorage.setItem("locale", l);
|
||||
};
|
||||
|
||||
const t = (key: TranslationKey): string => {
|
||||
return translations[locale][key] || key;
|
||||
};
|
||||
|
||||
return (
|
||||
<I18nContext.Provider value={{ locale, setLocale: handleSetLocale, t }}>
|
||||
{children}
|
||||
</I18nContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useI18n() {
|
||||
return useContext(I18nContext);
|
||||
}
|
||||
524
lib/queries.ts
Normal file
524
lib/queries.ts
Normal file
@@ -0,0 +1,524 @@
|
||||
import { query } from "./db";
|
||||
|
||||
// 真实模型名表达式:优先取 other 里的 upstream_model_name
|
||||
const REAL_MODEL = `COALESCE(
|
||||
CASE WHEN other IS NOT NULL AND other != '' AND other::jsonb ? 'upstream_model_name'
|
||||
THEN other::jsonb->>'upstream_model_name' END,
|
||||
model_name)`;
|
||||
|
||||
// 时间条件构建
|
||||
function timeWhere(
|
||||
params: (string | number | boolean | null)[],
|
||||
startTs?: number,
|
||||
endTs?: number
|
||||
): string {
|
||||
let where = "type = 2";
|
||||
if (startTs) {
|
||||
params.push(startTs);
|
||||
where += ` AND created_at >= $${params.length}`;
|
||||
}
|
||||
if (endTs) {
|
||||
params.push(endTs);
|
||||
where += ` AND created_at < $${params.length}`;
|
||||
}
|
||||
return where;
|
||||
}
|
||||
|
||||
// ── 总览 ──────────────────────────────────────────────────────
|
||||
|
||||
export interface OverviewData {
|
||||
total_calls: number;
|
||||
total_tokens: number;
|
||||
total_prompt: number;
|
||||
total_completion: number;
|
||||
total_quota: number;
|
||||
active_users: number;
|
||||
active_models: number;
|
||||
active_channels: number;
|
||||
}
|
||||
|
||||
export async function getOverview(
|
||||
startTs?: number,
|
||||
endTs?: number
|
||||
): Promise<OverviewData> {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
|
||||
const rows = await query(
|
||||
`SELECT
|
||||
COUNT(*)::int as total_calls,
|
||||
COALESCE(SUM(prompt_tokens + completion_tokens), 0)::bigint as total_tokens,
|
||||
COALESCE(SUM(prompt_tokens), 0)::bigint as total_prompt,
|
||||
COALESCE(SUM(completion_tokens), 0)::bigint as total_completion,
|
||||
COALESCE(SUM(quota), 0)::bigint as total_quota,
|
||||
COUNT(DISTINCT user_id)::int as active_users,
|
||||
COUNT(DISTINCT ${REAL_MODEL})::int as active_models,
|
||||
COUNT(DISTINCT channel_id)::int as active_channels
|
||||
FROM logs WHERE ${where}`,
|
||||
params
|
||||
);
|
||||
const r = rows[0];
|
||||
return {
|
||||
total_calls: Number(r.total_calls),
|
||||
total_tokens: Number(r.total_tokens),
|
||||
total_prompt: Number(r.total_prompt),
|
||||
total_completion: Number(r.total_completion),
|
||||
total_quota: Number(r.total_quota),
|
||||
active_users: Number(r.active_users),
|
||||
active_models: Number(r.active_models),
|
||||
active_channels: Number(r.active_channels),
|
||||
};
|
||||
}
|
||||
|
||||
// ── 趋势 ──────────────────────────────────────────────────────
|
||||
|
||||
export interface TrendPoint {
|
||||
date: string;
|
||||
calls: number;
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
quota: number;
|
||||
}
|
||||
|
||||
export async function getTrends(
|
||||
granularity: "day" | "week" | "month" = "day",
|
||||
startTs?: number,
|
||||
endTs?: number
|
||||
): Promise<TrendPoint[]> {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
|
||||
const truncExpr =
|
||||
granularity === "day"
|
||||
? `(to_timestamp(created_at) AT TIME ZONE 'Asia/Shanghai')::date`
|
||||
: `date_trunc('${granularity}', to_timestamp(created_at) AT TIME ZONE 'Asia/Shanghai')::date`;
|
||||
|
||||
const rows = await query(
|
||||
`SELECT
|
||||
${truncExpr} as date,
|
||||
COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens), 0)::bigint as prompt_tokens,
|
||||
COALESCE(SUM(completion_tokens), 0)::bigint as completion_tokens,
|
||||
COALESCE(SUM(quota), 0)::bigint as quota
|
||||
FROM logs WHERE ${where}
|
||||
GROUP BY date ORDER BY date`,
|
||||
params
|
||||
);
|
||||
|
||||
return rows.map((r) => ({
|
||||
date: String(r.date).slice(0, 10),
|
||||
calls: Number(r.calls),
|
||||
prompt_tokens: Number(r.prompt_tokens),
|
||||
completion_tokens: Number(r.completion_tokens),
|
||||
total_tokens: Number(r.prompt_tokens) + Number(r.completion_tokens),
|
||||
quota: Number(r.quota),
|
||||
}));
|
||||
}
|
||||
|
||||
// ── 排名 ──────────────────────────────────────────────────────
|
||||
|
||||
export interface RankingItem {
|
||||
rank: number;
|
||||
name: string;
|
||||
id?: number;
|
||||
calls: number;
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
quota: number;
|
||||
quota_usd: number;
|
||||
}
|
||||
|
||||
// 用户显示名称映射
|
||||
async function getDisplayNames(): Promise<Record<number, string>> {
|
||||
const rows = await query(
|
||||
"SELECT id, display_name FROM users WHERE display_name IS NOT NULL AND display_name != ''"
|
||||
);
|
||||
return Object.fromEntries(rows.map((r) => [r.id, r.display_name]));
|
||||
}
|
||||
|
||||
// 渠道名称映射
|
||||
async function getChannelNames(): Promise<Record<number, string>> {
|
||||
const rows = await query("SELECT id, name FROM channels");
|
||||
return Object.fromEntries(rows.map((r) => [r.id, r.name]));
|
||||
}
|
||||
|
||||
export async function getUserRanking(
|
||||
startTs?: number,
|
||||
endTs?: number,
|
||||
limit = 50
|
||||
): Promise<RankingItem[]> {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
params.push(limit);
|
||||
|
||||
const displayNames = await getDisplayNames();
|
||||
|
||||
const rows = await query(
|
||||
`SELECT user_id, username,
|
||||
COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens), 0)::bigint as prompt,
|
||||
COALESCE(SUM(completion_tokens), 0)::bigint as completion,
|
||||
COALESCE(SUM(quota), 0)::bigint as quota
|
||||
FROM logs WHERE ${where}
|
||||
GROUP BY user_id, username
|
||||
ORDER BY COALESCE(SUM(prompt_tokens),0) + COALESCE(SUM(completion_tokens),0) DESC
|
||||
LIMIT $${params.length}`,
|
||||
params
|
||||
);
|
||||
|
||||
return rows.map((r, i) => ({
|
||||
rank: i + 1,
|
||||
name: displayNames[r.user_id] || r.username,
|
||||
id: Number(r.user_id),
|
||||
calls: Number(r.calls),
|
||||
prompt_tokens: Number(r.prompt),
|
||||
completion_tokens: Number(r.completion),
|
||||
total_tokens: Number(r.prompt) + Number(r.completion),
|
||||
quota: Number(r.quota),
|
||||
quota_usd: Number(r.quota) / 500000,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getModelRanking(
|
||||
startTs?: number,
|
||||
endTs?: number,
|
||||
limit = 50
|
||||
): Promise<RankingItem[]> {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
params.push(limit);
|
||||
|
||||
const rows = await query(
|
||||
`SELECT ${REAL_MODEL} as model,
|
||||
COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens), 0)::bigint as prompt,
|
||||
COALESCE(SUM(completion_tokens), 0)::bigint as completion,
|
||||
COALESCE(SUM(quota), 0)::bigint as quota
|
||||
FROM logs WHERE ${where}
|
||||
GROUP BY model
|
||||
ORDER BY COALESCE(SUM(prompt_tokens),0) + COALESCE(SUM(completion_tokens),0) DESC
|
||||
LIMIT $${params.length}`,
|
||||
params
|
||||
);
|
||||
|
||||
return rows.map((r, i) => ({
|
||||
rank: i + 1,
|
||||
name: r.model || "(unknown)",
|
||||
calls: Number(r.calls),
|
||||
prompt_tokens: Number(r.prompt),
|
||||
completion_tokens: Number(r.completion),
|
||||
total_tokens: Number(r.prompt) + Number(r.completion),
|
||||
quota: Number(r.quota),
|
||||
quota_usd: Number(r.quota) / 500000,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getChannelRanking(
|
||||
startTs?: number,
|
||||
endTs?: number,
|
||||
limit = 50
|
||||
): Promise<RankingItem[]> {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
params.push(limit);
|
||||
|
||||
const channelNames = await getChannelNames();
|
||||
|
||||
const rows = await query(
|
||||
`SELECT channel_id,
|
||||
COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens), 0)::bigint as prompt,
|
||||
COALESCE(SUM(completion_tokens), 0)::bigint as completion,
|
||||
COALESCE(SUM(quota), 0)::bigint as quota
|
||||
FROM logs WHERE ${where}
|
||||
GROUP BY channel_id
|
||||
ORDER BY COALESCE(SUM(prompt_tokens),0) + COALESCE(SUM(completion_tokens),0) DESC
|
||||
LIMIT $${params.length}`,
|
||||
params
|
||||
);
|
||||
|
||||
return rows.map((r, i) => ({
|
||||
rank: i + 1,
|
||||
name: channelNames[r.channel_id] || `已删除(${r.channel_id})`,
|
||||
id: Number(r.channel_id),
|
||||
calls: Number(r.calls),
|
||||
prompt_tokens: Number(r.prompt),
|
||||
completion_tokens: Number(r.completion),
|
||||
total_tokens: Number(r.prompt) + Number(r.completion),
|
||||
quota: Number(r.quota),
|
||||
quota_usd: Number(r.quota) / 500000,
|
||||
}));
|
||||
}
|
||||
|
||||
// ── 下钻详情 ──────────────────────────────────────────────────
|
||||
|
||||
export interface DetailBreakdown {
|
||||
name: string;
|
||||
calls: number;
|
||||
total_tokens: number;
|
||||
quota: number;
|
||||
}
|
||||
|
||||
export async function getUserDetail(
|
||||
username: string,
|
||||
startTs?: number,
|
||||
endTs?: number
|
||||
) {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
params.push(username);
|
||||
|
||||
// 用户总览
|
||||
const overview = await query(
|
||||
`SELECT COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens),0)::bigint as prompt,
|
||||
COALESCE(SUM(completion_tokens),0)::bigint as completion,
|
||||
COALESCE(SUM(quota),0)::bigint as quota
|
||||
FROM logs WHERE ${where} AND username = $${params.length}`,
|
||||
params
|
||||
);
|
||||
|
||||
// 用户的模型分布
|
||||
const params2: (string | number | boolean | null)[] = [];
|
||||
const where2 = timeWhere(params2, startTs, endTs);
|
||||
params2.push(username);
|
||||
|
||||
const models = await query(
|
||||
`SELECT ${REAL_MODEL} as model,
|
||||
COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens + completion_tokens),0)::bigint as tokens,
|
||||
COALESCE(SUM(quota),0)::bigint as quota
|
||||
FROM logs WHERE ${where2} AND username = $${params2.length}
|
||||
GROUP BY model
|
||||
ORDER BY tokens DESC LIMIT 20`,
|
||||
params2
|
||||
);
|
||||
|
||||
const o = overview[0];
|
||||
return {
|
||||
calls: Number(o.calls),
|
||||
prompt_tokens: Number(o.prompt),
|
||||
completion_tokens: Number(o.completion),
|
||||
total_tokens: Number(o.prompt) + Number(o.completion),
|
||||
quota: Number(o.quota),
|
||||
models: models.map((m) => ({
|
||||
name: m.model,
|
||||
calls: Number(m.calls),
|
||||
total_tokens: Number(m.tokens),
|
||||
quota: Number(m.quota),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getModelDetail(
|
||||
model: string,
|
||||
startTs?: number,
|
||||
endTs?: number
|
||||
) {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
params.push(model);
|
||||
|
||||
const overview = await query(
|
||||
`SELECT COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens),0)::bigint as prompt,
|
||||
COALESCE(SUM(completion_tokens),0)::bigint as completion,
|
||||
COALESCE(SUM(quota),0)::bigint as quota
|
||||
FROM logs WHERE ${where} AND ${REAL_MODEL} = $${params.length}`,
|
||||
params
|
||||
);
|
||||
|
||||
const params2: (string | number | boolean | null)[] = [];
|
||||
const where2 = timeWhere(params2, startTs, endTs);
|
||||
params2.push(model);
|
||||
|
||||
const displayNames = await getDisplayNames();
|
||||
const users = await query(
|
||||
`SELECT user_id, username,
|
||||
COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens + completion_tokens),0)::bigint as tokens,
|
||||
COALESCE(SUM(quota),0)::bigint as quota
|
||||
FROM logs WHERE ${where2} AND ${REAL_MODEL} = $${params2.length}
|
||||
GROUP BY user_id, username
|
||||
ORDER BY tokens DESC LIMIT 20`,
|
||||
params2
|
||||
);
|
||||
|
||||
const o = overview[0];
|
||||
return {
|
||||
calls: Number(o.calls),
|
||||
prompt_tokens: Number(o.prompt),
|
||||
completion_tokens: Number(o.completion),
|
||||
total_tokens: Number(o.prompt) + Number(o.completion),
|
||||
quota: Number(o.quota),
|
||||
users: users.map((u) => ({
|
||||
name: displayNames[u.user_id] || u.username,
|
||||
calls: Number(u.calls),
|
||||
total_tokens: Number(u.tokens),
|
||||
quota: Number(u.quota),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export async function getChannelDetail(
|
||||
channelId: number,
|
||||
startTs?: number,
|
||||
endTs?: number
|
||||
) {
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
const where = timeWhere(params, startTs, endTs);
|
||||
params.push(channelId);
|
||||
|
||||
const channelNames = await getChannelNames();
|
||||
|
||||
const overview = await query(
|
||||
`SELECT COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens),0)::bigint as prompt,
|
||||
COALESCE(SUM(completion_tokens),0)::bigint as completion,
|
||||
COALESCE(SUM(quota),0)::bigint as quota
|
||||
FROM logs WHERE ${where} AND channel_id = $${params.length}`,
|
||||
params
|
||||
);
|
||||
|
||||
const params2: (string | number | boolean | null)[] = [];
|
||||
const where2 = timeWhere(params2, startTs, endTs);
|
||||
params2.push(channelId);
|
||||
|
||||
const models = await query(
|
||||
`SELECT ${REAL_MODEL} as model,
|
||||
COUNT(*)::int as calls,
|
||||
COALESCE(SUM(prompt_tokens + completion_tokens),0)::bigint as tokens,
|
||||
COALESCE(SUM(quota),0)::bigint as quota
|
||||
FROM logs WHERE ${where2} AND channel_id = $${params2.length}
|
||||
GROUP BY model
|
||||
ORDER BY tokens DESC LIMIT 20`,
|
||||
params2
|
||||
);
|
||||
|
||||
const o = overview[0];
|
||||
return {
|
||||
channel_name: channelNames[channelId] || `已删除(${channelId})`,
|
||||
calls: Number(o.calls),
|
||||
prompt_tokens: Number(o.prompt),
|
||||
completion_tokens: Number(o.completion),
|
||||
total_tokens: Number(o.prompt) + Number(o.completion),
|
||||
quota: Number(o.quota),
|
||||
models: models.map((m) => ({
|
||||
name: m.model,
|
||||
calls: Number(m.calls),
|
||||
total_tokens: Number(m.tokens),
|
||||
quota: Number(m.quota),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// ── 明细日志 ──────────────────────────────────────────────────
|
||||
|
||||
export interface LogEntry {
|
||||
id: number;
|
||||
created_at: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
real_model: string;
|
||||
request_model: string;
|
||||
channel_name: string;
|
||||
channel_id: number;
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
quota: number;
|
||||
quota_usd: number;
|
||||
use_time: number;
|
||||
is_stream: boolean;
|
||||
token_name: string;
|
||||
}
|
||||
|
||||
export interface LogsResult {
|
||||
logs: LogEntry[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
export async function getLogs(options: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
startTs?: number;
|
||||
endTs?: number;
|
||||
username?: string;
|
||||
model?: string;
|
||||
channelId?: number;
|
||||
tokenName?: string;
|
||||
}): Promise<LogsResult> {
|
||||
const { page = 1, pageSize = 100 } = options;
|
||||
const params: (string | number | boolean | null)[] = [];
|
||||
let where = timeWhere(params, options.startTs, options.endTs);
|
||||
|
||||
if (options.username) {
|
||||
params.push(options.username);
|
||||
where += ` AND username = $${params.length}`;
|
||||
}
|
||||
if (options.model) {
|
||||
params.push(options.model);
|
||||
where += ` AND ${REAL_MODEL} = $${params.length}`;
|
||||
}
|
||||
if (options.channelId) {
|
||||
params.push(options.channelId);
|
||||
where += ` AND channel_id = $${params.length}`;
|
||||
}
|
||||
if (options.tokenName) {
|
||||
params.push(`%${options.tokenName}%`);
|
||||
where += ` AND token_name ILIKE $${params.length}`;
|
||||
}
|
||||
|
||||
// Count
|
||||
const countRows = await query(
|
||||
`SELECT COUNT(*)::int as total FROM logs WHERE ${where}`,
|
||||
params
|
||||
);
|
||||
const total = Number(countRows[0].total);
|
||||
|
||||
// Data
|
||||
const offset = (page - 1) * pageSize;
|
||||
const dataParams = [...params, pageSize, offset];
|
||||
|
||||
const displayNames = await getDisplayNames();
|
||||
const channelNames = await getChannelNames();
|
||||
|
||||
const rows = await query(
|
||||
`SELECT id, created_at, user_id, username, model_name,
|
||||
${REAL_MODEL} as real_model,
|
||||
channel_id, prompt_tokens, completion_tokens, quota,
|
||||
use_time, is_stream, token_name
|
||||
FROM logs WHERE ${where}
|
||||
ORDER BY id DESC
|
||||
LIMIT $${dataParams.length - 1} OFFSET $${dataParams.length}`,
|
||||
dataParams
|
||||
);
|
||||
|
||||
return {
|
||||
total,
|
||||
page,
|
||||
page_size: pageSize,
|
||||
logs: rows.map((r) => ({
|
||||
id: Number(r.id),
|
||||
created_at: new Date(Number(r.created_at) * 1000).toISOString(),
|
||||
username: r.username,
|
||||
display_name: displayNames[r.user_id] || r.username,
|
||||
real_model: r.real_model || r.model_name,
|
||||
request_model: r.model_name,
|
||||
channel_name: channelNames[r.channel_id] || `已删除(${r.channel_id})`,
|
||||
channel_id: Number(r.channel_id),
|
||||
prompt_tokens: Number(r.prompt_tokens),
|
||||
completion_tokens: Number(r.completion_tokens),
|
||||
total_tokens: Number(r.prompt_tokens) + Number(r.completion_tokens),
|
||||
quota: Number(r.quota),
|
||||
quota_usd: Number(r.quota) / 500000,
|
||||
use_time: Number(r.use_time),
|
||||
is_stream: Boolean(r.is_stream),
|
||||
token_name: r.token_name || "",
|
||||
})),
|
||||
};
|
||||
}
|
||||
74
lib/theme.tsx
Normal file
74
lib/theme.tsx
Normal file
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { createContext, useContext, useState, useEffect, type ReactNode } from "react";
|
||||
|
||||
export type Theme = "light" | "dark" | "system";
|
||||
|
||||
interface ThemeContextType {
|
||||
theme: Theme;
|
||||
setTheme: (t: Theme) => void;
|
||||
resolved: "light" | "dark";
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextType>({
|
||||
theme: "system",
|
||||
setTheme: () => {},
|
||||
resolved: "dark",
|
||||
});
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setThemeState] = useState<Theme>("system");
|
||||
const [resolved, setResolved] = useState<"light" | "dark">("dark");
|
||||
|
||||
useEffect(() => {
|
||||
const saved = localStorage.getItem("theme") as Theme | null;
|
||||
if (saved && ["light", "dark", "system"].includes(saved)) {
|
||||
setThemeState(saved);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const resolve = () => {
|
||||
if (theme === "system") {
|
||||
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||
}
|
||||
return theme;
|
||||
};
|
||||
|
||||
const r = resolve();
|
||||
setResolved(r);
|
||||
|
||||
const root = document.documentElement;
|
||||
root.classList.remove("light", "dark");
|
||||
root.classList.add(r);
|
||||
root.setAttribute("data-theme", r);
|
||||
|
||||
if (theme === "system") {
|
||||
const mq = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const handler = () => {
|
||||
const nr = mq.matches ? "dark" : "light";
|
||||
setResolved(nr);
|
||||
root.classList.remove("light", "dark");
|
||||
root.classList.add(nr);
|
||||
root.setAttribute("data-theme", nr);
|
||||
};
|
||||
mq.addEventListener("change", handler);
|
||||
return () => mq.removeEventListener("change", handler);
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
const setTheme = (t: Theme) => {
|
||||
setThemeState(t);
|
||||
localStorage.setItem("theme", t);
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, setTheme, resolved }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
return useContext(ThemeContext);
|
||||
}
|
||||
54
lib/utils.ts
Normal file
54
lib/utils.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import dayjs from "dayjs";
|
||||
|
||||
export function formatNumber(n: number): string {
|
||||
return n.toLocaleString("en-US");
|
||||
}
|
||||
|
||||
export function formatTokens(n: number): string {
|
||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(1)}B`;
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
|
||||
return String(n);
|
||||
}
|
||||
|
||||
export function formatUSD(n: number): string {
|
||||
if (n >= 1000) return `$${n.toLocaleString("en-US", { maximumFractionDigits: 0 })}`;
|
||||
if (n >= 1) return `$${n.toFixed(2)}`;
|
||||
if (n >= 0.01) return `$${n.toFixed(3)}`;
|
||||
return `$${n.toFixed(4)}`;
|
||||
}
|
||||
|
||||
export function formatDate(iso: string): string {
|
||||
return dayjs(iso).format("YYYY-MM-DD HH:mm:ss");
|
||||
}
|
||||
|
||||
// 预设时间范围
|
||||
export type TimeRange = "today" | "7d" | "30d" | "all" | "custom";
|
||||
|
||||
export function getTimeRange(range: TimeRange): { start?: number; end?: number } {
|
||||
const now = dayjs();
|
||||
switch (range) {
|
||||
case "today":
|
||||
return { start: now.startOf("day").unix(), end: now.unix() };
|
||||
case "7d":
|
||||
return { start: now.subtract(7, "day").startOf("day").unix(), end: now.unix() };
|
||||
case "30d":
|
||||
return { start: now.subtract(30, "day").startOf("day").unix(), end: now.unix() };
|
||||
case "all":
|
||||
return {};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function buildQuery(
|
||||
base: string,
|
||||
params: Record<string, string | number | undefined>
|
||||
): string {
|
||||
const sp = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (v !== undefined && v !== "") sp.set(k, String(v));
|
||||
}
|
||||
const qs = sp.toString();
|
||||
return qs ? `${base}?${qs}` : base;
|
||||
}
|
||||
Reference in New Issue
Block a user