feat: 完成前端重构,采用 Ant Design 5 和完整测试体系
- 采用 Ant Design 5 作为 UI 组件库,替换自定义组件 - 集成 React Router v7 提供路由导航 - 使用 TanStack Query v5 管理数据获取和缓存 - 建立 Vitest + React Testing Library 测试体系 - 添加 Playwright E2E 测试覆盖 - 使用 MSW mock API 响应 - 配置 TypeScript strict 模式 - 采用 SCSS Modules 组织样式 - 更新 OpenSpec 规格以反映前端架构变更 - 归档 frontend-refactor 变更记录
This commit is contained in:
22
README.md
22
README.md
@@ -19,12 +19,14 @@ nex/
|
||||
│
|
||||
├── frontend/ # React 前端界面
|
||||
│ ├── src/
|
||||
│ │ ├── main.tsx
|
||||
│ │ ├── App.tsx
|
||||
│ │ ├── pages/
|
||||
│ │ ├── components/
|
||||
│ │ ├── api/
|
||||
│ │ └── styles/
|
||||
│ │ ├── api/ # API 层(统一请求封装 + 字段转换)
|
||||
│ │ ├── hooks/ # TanStack Query hooks
|
||||
│ │ ├── components/ # 通用组件(AppLayout)
|
||||
│ │ ├── pages/ # 页面(Providers, Stats, NotFound)
|
||||
│ │ ├── routes/ # React Router 路由配置
|
||||
│ │ ├── types/ # TypeScript 类型定义
|
||||
│ │ └── __tests__/ # 测试(API、Hooks、组件)
|
||||
│ ├── e2e/ # Playwright E2E 测试
|
||||
│ └── package.json
|
||||
│
|
||||
└── README.md # 本文件
|
||||
@@ -51,9 +53,13 @@ nex/
|
||||
### 前端
|
||||
- **Bun** - 运行时
|
||||
- **Vite** - 构建工具
|
||||
- **TypeScript** - 类型系统
|
||||
- **TypeScript** (strict mode) - 类型系统
|
||||
- **React** - UI 框架
|
||||
- **SCSS** - 样式预处理
|
||||
- **Ant Design 5** - UI 组件库
|
||||
- **React Router v7** - 路由
|
||||
- **TanStack Query v5** - 数据获取
|
||||
- **SCSS Modules** - 样式方案
|
||||
- **Vitest + Playwright** - 测试
|
||||
|
||||
## 快速开始
|
||||
|
||||
|
||||
1
frontend/.env.development
Normal file
1
frontend/.env.development
Normal file
@@ -0,0 +1 @@
|
||||
VITE_API_BASE=
|
||||
1
frontend/.env.production
Normal file
1
frontend/.env.production
Normal file
@@ -0,0 +1 @@
|
||||
VITE_API_BASE=/api
|
||||
@@ -6,25 +6,52 @@ AI 网关管理前端,提供供应商配置和用量统计界面。
|
||||
|
||||
- **运行时**: Bun
|
||||
- **构建工具**: Vite
|
||||
- **语言**: TypeScript
|
||||
- **语言**: TypeScript (strict mode)
|
||||
- **框架**: React
|
||||
- **样式**: SCSS
|
||||
- **UI 组件库**: Ant Design 5
|
||||
- **路由**: React Router v7
|
||||
- **数据获取**: TanStack Query v5
|
||||
- **样式**: SCSS Modules(禁止使用纯 CSS)
|
||||
- **测试**: Vitest + React Testing Library + Playwright
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
frontend/
|
||||
├── src/
|
||||
│ ├── api/
|
||||
│ │ └── client.ts # API 客户端封装
|
||||
│ ├── api/ # API 层
|
||||
│ │ ├── client.ts # 统一 request<T>() + 字段转换
|
||||
│ │ ├── providers.ts # Provider CRUD
|
||||
│ │ ├── models.ts # Model CRUD
|
||||
│ │ └── stats.ts # Stats 查询
|
||||
│ ├── components/
|
||||
│ │ └── AppLayout/ # 顶部导航布局
|
||||
│ ├── hooks/ # TanStack Query hooks
|
||||
│ │ ├── useProviders.ts
|
||||
│ │ ├── useModels.ts
|
||||
│ │ └── useStats.ts
|
||||
│ ├── pages/
|
||||
│ │ ├── ProvidersPage.tsx # 供应商管理页面
|
||||
│ │ └── StatsPage.tsx # 统计查看页面
|
||||
│ ├── App.tsx # 主应用组件
|
||||
│ ├── App.css # 样式
|
||||
│ └── main.tsx # 入口文件
|
||||
├── package.json
|
||||
└── README.md
|
||||
│ │ ├── Providers/ # 供应商管理(含内嵌模型管理)
|
||||
│ │ ├── Stats/ # 用量统计
|
||||
│ │ └── NotFound.tsx
|
||||
│ ├── routes/
|
||||
│ │ └── index.tsx # 路由配置
|
||||
│ ├── types/
|
||||
│ │ └── index.ts # 类型定义
|
||||
│ ├── __tests__/ # 测试
|
||||
│ │ ├── setup.ts
|
||||
│ │ ├── api/
|
||||
│ │ ├── hooks/
|
||||
│ │ └── components/
|
||||
│ ├── App.tsx
|
||||
│ ├── main.tsx
|
||||
│ └── index.scss
|
||||
├── e2e/ # Playwright E2E 测试
|
||||
├── vitest.config.ts
|
||||
├── playwright.config.ts
|
||||
├── tsconfig.json
|
||||
├── vite.config.ts
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## 运行方式
|
||||
@@ -41,7 +68,7 @@ bun install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
前端将在端口 5173 启动。
|
||||
前端将在端口 5173 启动,API 请求通过 Vite proxy 转发到后端(localhost:9826)。
|
||||
|
||||
### 构建生产版本
|
||||
|
||||
@@ -49,37 +76,60 @@ bun run dev
|
||||
bun run build
|
||||
```
|
||||
|
||||
### 代码检查
|
||||
|
||||
```bash
|
||||
bun run lint
|
||||
```
|
||||
|
||||
## 测试
|
||||
|
||||
### 单元测试 + 组件测试
|
||||
|
||||
```bash
|
||||
bun run test # 运行所有测试
|
||||
bun run test:watch # 监听模式
|
||||
bun run test:coverage # 生成覆盖率报告
|
||||
```
|
||||
|
||||
### E2E 测试
|
||||
|
||||
```bash
|
||||
bun run test:e2e
|
||||
```
|
||||
|
||||
## 功能
|
||||
|
||||
### 供应商管理
|
||||
|
||||
- 查看供应商列表
|
||||
- 添加新供应商
|
||||
- 查看供应商列表(Ant Design Table)
|
||||
- 添加新供应商(Modal Form)
|
||||
- 编辑供应商配置
|
||||
- 删除供应商
|
||||
- 启用/禁用供应商
|
||||
- 删除供应商(Popconfirm 确认)
|
||||
- API Key 脱敏显示
|
||||
- 启用/禁用状态标签
|
||||
|
||||
### 模型管理
|
||||
|
||||
- 查看模型列表
|
||||
- 添加新模型
|
||||
- 编辑模型配置
|
||||
- 删除模型
|
||||
- 按供应商过滤模型
|
||||
- 展开供应商行查看关联模型
|
||||
- 添加/编辑/删除模型
|
||||
- 按供应商筛选模型
|
||||
|
||||
### 用量统计
|
||||
|
||||
- 查看统计数据
|
||||
- 按供应商过滤
|
||||
- 按模型过滤
|
||||
- 按日期范围过滤
|
||||
- 查看聚合统计
|
||||
- 按供应商筛选
|
||||
- 按模型筛选
|
||||
- 按日期范围筛选(DatePicker.RangePicker)
|
||||
|
||||
## API 配置
|
||||
## 开发规范
|
||||
|
||||
API 基础地址默认为 `http://localhost:9826/api`,可在 `src/api/client.ts` 中修改。
|
||||
|
||||
## 开发
|
||||
- 所有样式使用 SCSS,禁止使用纯 CSS 文件
|
||||
- 组件级样式使用 SCSS Modules(*.module.scss)
|
||||
- 图标优先使用 @ant-design/icons
|
||||
- TypeScript strict 模式,禁止 any 类型
|
||||
- API 层自动处理 snake_case ↔ camelCase 字段转换
|
||||
- 使用路径别名 `@/` 引用 src 目录
|
||||
|
||||
### 环境要求
|
||||
|
||||
@@ -87,6 +137,7 @@ API 基础地址默认为 `http://localhost:9826/api`,可在 `src/api/client.t
|
||||
|
||||
### 添加新页面
|
||||
|
||||
1. 在 `src/pages/` 创建页面组件
|
||||
2. 在 `src/App.tsx` 添加路由
|
||||
3. 在导航栏添加链接
|
||||
1. 在 `src/pages/` 创建页面目录和组件
|
||||
2. 在 `src/hooks/` 创建对应的 TanStack Query hook
|
||||
3. 在 `src/routes/index.tsx` 添加路由
|
||||
4. 在 `src/components/AppLayout/index.tsx` 的 menuItems 添加导航项
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
24
frontend/e2e/providers.spec.ts
Normal file
24
frontend/e2e/providers.spec.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('供应商管理', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/providers');
|
||||
});
|
||||
|
||||
test('应显示供应商管理页面', async ({ page }) => {
|
||||
await expect(page.getByRole('heading', { name: '供应商管理' })).toBeVisible();
|
||||
await expect(page.getByText('供应商列表')).toBeVisible();
|
||||
});
|
||||
|
||||
test('应显示添加供应商按钮', async ({ page }) => {
|
||||
await expect(page.getByRole('button', { name: '添加供应商' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('应通过顶部导航切换页面', async ({ page }) => {
|
||||
await page.getByText('用量统计').click();
|
||||
await expect(page.getByRole('heading', { name: '用量统计' })).toBeVisible();
|
||||
|
||||
await page.getByText('供应商管理').click();
|
||||
await expect(page.getByRole('heading', { name: '供应商管理' })).toBeVisible();
|
||||
});
|
||||
});
|
||||
20
frontend/e2e/stats.spec.ts
Normal file
20
frontend/e2e/stats.spec.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('用量统计', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/stats');
|
||||
});
|
||||
|
||||
test('应显示用量统计页面', async ({ page }) => {
|
||||
await expect(page.getByRole('heading', { name: '用量统计' })).toBeVisible();
|
||||
});
|
||||
|
||||
test('应显示筛选控件', async ({ page }) => {
|
||||
await expect(page.getByText('所有供应商')).toBeVisible();
|
||||
});
|
||||
|
||||
test('应通过导航返回供应商页面', async ({ page }) => {
|
||||
await page.getByText('供应商管理').click();
|
||||
await expect(page.getByRole('heading', { name: '供应商管理' })).toBeVisible();
|
||||
});
|
||||
});
|
||||
51
frontend/eslint.config.js
Normal file
51
frontend/eslint.config.js
Normal file
@@ -0,0 +1,51 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
import importPlugin from 'eslint-plugin-import'
|
||||
import tanstackQuery from '@tanstack/eslint-plugin-query'
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2023,
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
import: importPlugin,
|
||||
'@tanstack/query': tanstackQuery,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
'import/order': [
|
||||
'warn',
|
||||
{
|
||||
groups: [
|
||||
'builtin',
|
||||
'external',
|
||||
'internal',
|
||||
'parent',
|
||||
'sibling',
|
||||
'index',
|
||||
'type',
|
||||
],
|
||||
'newlines-between': 'never',
|
||||
alphabetize: { order: 'asc', caseInsensitive: true },
|
||||
pathGroups: [
|
||||
{ pattern: '@/**', group: 'internal', position: 'before' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -7,25 +7,43 @@
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"test:e2e": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/icons": "^5.6.1",
|
||||
"@tanstack/react-query": "^5.80.2",
|
||||
"antd": "^5.24.9",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"sass": "^1.99.0"
|
||||
"react-router": "^7.6.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@playwright/test": "^1.52.0",
|
||||
"@tanstack/eslint-plugin-query": "^5.78.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"@vitest/coverage-v8": "^3.2.1",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.4.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"msw": "^2.8.2",
|
||||
"sass": "^1.99.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.58.0",
|
||||
"vite": "^8.0.4"
|
||||
"vite": "^8.0.4",
|
||||
"vitest": "^3.2.1"
|
||||
}
|
||||
}
|
||||
|
||||
25
frontend/playwright.config.ts
Normal file
25
frontend/playwright.config.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: 'html',
|
||||
use: {
|
||||
baseURL: 'http://localhost:5173',
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
],
|
||||
webServer: {
|
||||
command: 'bun run dev',
|
||||
url: 'http://localhost:5173',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
},
|
||||
})
|
||||
@@ -1,221 +0,0 @@
|
||||
.app {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
background: #1a1a2e;
|
||||
color: #fff;
|
||||
padding: 1rem 2rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.navbar h1 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.nav-links button {
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: #aaa;
|
||||
font-size: 1rem;
|
||||
padding: 0.5rem 1rem;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.nav-links button:hover {
|
||||
color: #fff;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.nav-links button.active {
|
||||
color: #fff;
|
||||
background: #4361ee;
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 2rem;
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.75rem;
|
||||
margin-bottom: 1.5rem;
|
||||
color: #1a1a2e;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.25rem;
|
||||
margin-bottom: 1rem;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.section {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
th, td {
|
||||
text-align: left;
|
||||
padding: 0.75rem 1rem;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
th {
|
||||
background: #fafafa;
|
||||
font-weight: 600;
|
||||
color: #555;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
button {
|
||||
background: #4361ee;
|
||||
color: #fff;
|
||||
border: none;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #3a56d4;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.modal {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 2rem;
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
max-height: 90vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.modal-content h2 {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 0.5rem;
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.form-group input[type="text"],
|
||||
.form-group input[type="password"],
|
||||
.form-group input[type="url"],
|
||||
.form-group input[type="date"],
|
||||
.form-group select {
|
||||
width: 100%;
|
||||
padding: 0.625rem;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.form-group input:focus,
|
||||
.form-group select:focus {
|
||||
outline: none;
|
||||
border-color: #4361ee;
|
||||
}
|
||||
|
||||
.form-actions {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.form-actions button:first-child {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.error {
|
||||
background: #fee2e2;
|
||||
color: #dc2626;
|
||||
padding: 0.75rem;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 2rem;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.filter-form {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 1.5rem;
|
||||
background: #fff;
|
||||
padding: 1.5rem;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.filter-form select,
|
||||
.filter-form input {
|
||||
padding: 0.625rem;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.filter-form button {
|
||||
padding: 0.625rem 1.5rem;
|
||||
}
|
||||
@@ -1,36 +1,24 @@
|
||||
import { useState } from 'react';
|
||||
import { ProvidersPage } from './pages/ProvidersPage';
|
||||
import { StatsPage } from './pages/StatsPage';
|
||||
import './App.css';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { AppRoutes } from '@/routes';
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function App() {
|
||||
const [currentPage, setCurrentPage] = useState<'providers' | 'stats'>('providers');
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
<nav className="navbar">
|
||||
<h1>AI Gateway</h1>
|
||||
<div className="nav-links">
|
||||
<button
|
||||
className={currentPage === 'providers' ? 'active' : ''}
|
||||
onClick={() => setCurrentPage('providers')}
|
||||
>
|
||||
供应商管理
|
||||
</button>
|
||||
<button
|
||||
className={currentPage === 'stats' ? 'active' : ''}
|
||||
onClick={() => setCurrentPage('stats')}
|
||||
>
|
||||
用量统计
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main className="content">
|
||||
{currentPage === 'providers' && <ProvidersPage />}
|
||||
{currentPage === 'stats' && <StatsPage />}
|
||||
</main>
|
||||
</div>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AppRoutes />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
208
frontend/src/__tests__/api/client.test.ts
Normal file
208
frontend/src/__tests__/api/client.test.ts
Normal file
@@ -0,0 +1,208 @@
|
||||
import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { request, fromApi, toApi } from '@/api/client';
|
||||
import { ApiError } from '@/types';
|
||||
|
||||
describe('fromApi', () => {
|
||||
it('converts snake_case keys to camelCase', () => {
|
||||
const input = { first_name: 'John', last_name: 'Doe' };
|
||||
const result = fromApi<{ firstName: string; lastName: string }>(input);
|
||||
expect(result).toEqual({ firstName: 'John', lastName: 'Doe' });
|
||||
});
|
||||
|
||||
it('converts nested objects recursively', () => {
|
||||
const input = {
|
||||
user_name: 'alice',
|
||||
contact_info: { email_address: 'alice@example.com' },
|
||||
};
|
||||
const result = fromApi<{
|
||||
userName: string;
|
||||
contactInfo: { emailAddress: string };
|
||||
}>(input);
|
||||
expect(result).toEqual({
|
||||
userName: 'alice',
|
||||
contactInfo: { emailAddress: 'alice@example.com' },
|
||||
});
|
||||
});
|
||||
|
||||
it('converts arrays recursively', () => {
|
||||
const input = [
|
||||
{ item_name: 'a' },
|
||||
{ item_name: 'b' },
|
||||
];
|
||||
const result = fromApi<Array<{ itemName: string }>>(input);
|
||||
expect(result).toEqual([{ itemName: 'a' }, { itemName: 'b' }]);
|
||||
});
|
||||
|
||||
it('returns primitives unchanged', () => {
|
||||
expect(fromApi<string>('hello')).toBe('hello');
|
||||
expect(fromApi<number>(42)).toBe(42);
|
||||
expect(fromApi<null>(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('toApi', () => {
|
||||
it('converts camelCase keys to snake_case', () => {
|
||||
const input = { firstName: 'John', lastName: 'Doe' };
|
||||
const result = toApi<{ first_name: string; last_name: string }>(input);
|
||||
expect(result).toEqual({ first_name: 'John', last_name: 'Doe' });
|
||||
});
|
||||
|
||||
it('converts nested objects recursively', () => {
|
||||
const input = {
|
||||
userName: 'alice',
|
||||
contactInfo: { emailAddress: 'alice@example.com' },
|
||||
};
|
||||
const result = toApi<{
|
||||
user_name: string;
|
||||
contact_info: { email_address: string };
|
||||
}>(input);
|
||||
expect(result).toEqual({
|
||||
user_name: 'alice',
|
||||
contact_info: { email_address: 'alice@example.com' },
|
||||
});
|
||||
});
|
||||
|
||||
it('converts arrays recursively', () => {
|
||||
const input = [{ itemName: 'a' }, { itemName: 'b' }];
|
||||
const result = toApi<Array<{ item_name: string }>>(input);
|
||||
expect(result).toEqual([{ item_name: 'a' }, { item_name: 'b' }]);
|
||||
});
|
||||
|
||||
it('returns primitives unchanged', () => {
|
||||
expect(toApi<string>('hello')).toBe('hello');
|
||||
expect(toApi<number>(42)).toBe(42);
|
||||
expect(toApi<null>(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('request', () => {
|
||||
const mswServer = setupServer();
|
||||
|
||||
beforeAll(() => mswServer.listen({ onUnhandledRequest: 'bypass' }));
|
||||
afterEach(() => mswServer.resetHandlers());
|
||||
afterAll(() => mswServer.close());
|
||||
|
||||
it('parses JSON and converts snake_case keys to camelCase on success', async () => {
|
||||
mswServer.use(
|
||||
http.get('/api/test', () => {
|
||||
return HttpResponse.json({
|
||||
id: '1',
|
||||
created_at: '2025-01-01',
|
||||
nested_obj: { inner_key: 'value' },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await request<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
nestedObj: { innerKey: string };
|
||||
}>('GET', '/api/test');
|
||||
|
||||
expect(result).toEqual({
|
||||
id: '1',
|
||||
createdAt: '2025-01-01',
|
||||
nestedObj: { innerKey: 'value' },
|
||||
});
|
||||
});
|
||||
|
||||
it('throws ApiError with status and message on HTTP error', async () => {
|
||||
mswServer.use(
|
||||
http.get('/api/test', () => {
|
||||
return HttpResponse.json(
|
||||
{ message: 'Not found' },
|
||||
{ status: 404 },
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(request('GET', '/api/test')).rejects.toThrow(ApiError);
|
||||
try {
|
||||
await request('GET', '/api/test');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ApiError);
|
||||
const apiError = error as ApiError;
|
||||
expect(apiError.status).toBe(404);
|
||||
expect(apiError.message).toBe('Not found');
|
||||
}
|
||||
});
|
||||
|
||||
it('throws ApiError with default message when error body has no message', async () => {
|
||||
mswServer.use(
|
||||
http.get('/api/test', () => {
|
||||
return HttpResponse.json(
|
||||
{ error: 'something' },
|
||||
{ status: 500 },
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
try {
|
||||
await request('GET', '/api/test');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ApiError);
|
||||
const apiError = error as ApiError;
|
||||
expect(apiError.status).toBe(500);
|
||||
expect(apiError.message).toContain('500');
|
||||
}
|
||||
});
|
||||
|
||||
it('throws Error on network failure', async () => {
|
||||
mswServer.use(
|
||||
http.get('/api/test', () => {
|
||||
return HttpResponse.error();
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(request('GET', '/api/test')).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('returns undefined for 204 No Content', async () => {
|
||||
mswServer.use(
|
||||
http.delete('/api/test/1', () => {
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await request('DELETE', '/api/test/1');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends body with camelCase keys converted to snake_case', async () => {
|
||||
let receivedBody: Record<string, unknown> | null = null;
|
||||
|
||||
mswServer.use(
|
||||
http.post('/api/test', async ({ request }) => {
|
||||
receivedBody = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({ id: '1' });
|
||||
}),
|
||||
);
|
||||
|
||||
await request('POST', '/api/test', {
|
||||
providerId: 'prov-1',
|
||||
modelName: 'gpt-4',
|
||||
});
|
||||
|
||||
expect(receivedBody).toEqual({
|
||||
provider_id: 'prov-1',
|
||||
model_name: 'gpt-4',
|
||||
});
|
||||
});
|
||||
|
||||
it('sends Content-Type header as application/json', async () => {
|
||||
let contentType: string | null = null;
|
||||
|
||||
mswServer.use(
|
||||
http.post('/api/test', async ({ request }) => {
|
||||
contentType = request.headers.get('Content-Type');
|
||||
return HttpResponse.json({ id: '1' });
|
||||
}),
|
||||
);
|
||||
|
||||
await request('POST', '/api/test', { name: 'test' });
|
||||
|
||||
expect(contentType).toBe('application/json');
|
||||
});
|
||||
});
|
||||
166
frontend/src/__tests__/api/models.test.ts
Normal file
166
frontend/src/__tests__/api/models.test.ts
Normal file
@@ -0,0 +1,166 @@
|
||||
import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { listModels, createModel, updateModel, deleteModel } from '@/api/models';
|
||||
|
||||
const mockModels = [
|
||||
{
|
||||
id: 'gpt-4',
|
||||
provider_id: 'prov-1',
|
||||
model_name: 'gpt-4',
|
||||
enabled: true,
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'claude-3',
|
||||
provider_id: 'prov-2',
|
||||
model_name: 'claude-3',
|
||||
enabled: false,
|
||||
created_at: '2025-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
describe('models API', () => {
|
||||
const server = setupServer();
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: 'bypass' }));
|
||||
afterEach(() => server.resetHandlers());
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('listModels', () => {
|
||||
it('returns array of Model objects with camelCase keys', async () => {
|
||||
server.use(
|
||||
http.get('/api/models', () => {
|
||||
return HttpResponse.json(mockModels);
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await listModels();
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
id: 'gpt-4',
|
||||
providerId: 'prov-1',
|
||||
modelName: 'gpt-4',
|
||||
enabled: true,
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'claude-3',
|
||||
providerId: 'prov-2',
|
||||
modelName: 'claude-3',
|
||||
enabled: false,
|
||||
createdAt: '2025-01-02T00:00:00Z',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('appends provider_id query parameter when providerId is given', async () => {
|
||||
let receivedUrl: string | null = null;
|
||||
|
||||
server.use(
|
||||
http.get('/api/models', ({ request }) => {
|
||||
receivedUrl = request.url;
|
||||
return HttpResponse.json([mockModels[0]]);
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await listModels('prov-1');
|
||||
|
||||
expect(receivedUrl).toContain('provider_id=prov-1');
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].providerId).toBe('prov-1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createModel', () => {
|
||||
it('sends POST with correct body and returns model', async () => {
|
||||
let receivedMethod: string | null = null;
|
||||
let receivedBody: Record<string, unknown> | null = null;
|
||||
|
||||
server.use(
|
||||
http.post('/api/models', async ({ request }) => {
|
||||
receivedMethod = request.method;
|
||||
receivedBody = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json(mockModels[0]);
|
||||
}),
|
||||
);
|
||||
|
||||
const input = {
|
||||
id: 'gpt-4',
|
||||
providerId: 'prov-1',
|
||||
modelName: 'gpt-4',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = await createModel(input);
|
||||
|
||||
expect(receivedMethod).toBe('POST');
|
||||
expect(receivedBody).toEqual({
|
||||
id: 'gpt-4',
|
||||
provider_id: 'prov-1',
|
||||
model_name: 'gpt-4',
|
||||
enabled: true,
|
||||
});
|
||||
expect(result.id).toBe('gpt-4');
|
||||
expect(result.providerId).toBe('prov-1');
|
||||
expect(result.modelName).toBe('gpt-4');
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateModel', () => {
|
||||
it('sends PUT with correct body and returns model', async () => {
|
||||
let receivedMethod: string | null = null;
|
||||
let receivedUrl: string | null = null;
|
||||
let receivedBody: Record<string, unknown> | null = null;
|
||||
|
||||
server.use(
|
||||
http.put('/api/models/:id', async ({ request }) => {
|
||||
receivedMethod = request.method;
|
||||
receivedUrl = new URL(request.url).pathname;
|
||||
receivedBody = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({
|
||||
...mockModels[0],
|
||||
model_name: 'gpt-4-turbo',
|
||||
enabled: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await updateModel('gpt-4', {
|
||||
modelName: 'gpt-4-turbo',
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
expect(receivedMethod).toBe('PUT');
|
||||
expect(receivedUrl).toBe('/api/models/gpt-4');
|
||||
expect(receivedBody).toEqual({
|
||||
model_name: 'gpt-4-turbo',
|
||||
enabled: false,
|
||||
});
|
||||
expect(result.modelName).toBe('gpt-4-turbo');
|
||||
expect(result.enabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteModel', () => {
|
||||
it('sends DELETE and returns void', async () => {
|
||||
let receivedMethod: string | null = null;
|
||||
let receivedUrl: string | null = null;
|
||||
|
||||
server.use(
|
||||
http.delete('/api/models/:id', ({ request }) => {
|
||||
receivedMethod = request.method;
|
||||
receivedUrl = new URL(request.url).pathname;
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await deleteModel('gpt-4');
|
||||
|
||||
expect(receivedMethod).toBe('DELETE');
|
||||
expect(receivedUrl).toBe('/api/models/gpt-4');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
165
frontend/src/__tests__/api/providers.test.ts
Normal file
165
frontend/src/__tests__/api/providers.test.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { listProviders, createProvider, updateProvider, deleteProvider } from '@/api/providers';
|
||||
|
||||
const mockProviders = [
|
||||
{
|
||||
id: 'prov-1',
|
||||
name: 'OpenAI',
|
||||
api_key: 'sk-xxx',
|
||||
base_url: 'https://api.openai.com',
|
||||
enabled: true,
|
||||
created_at: '2025-01-01T00:00:00Z',
|
||||
updated_at: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'prov-2',
|
||||
name: 'Anthropic',
|
||||
api_key: 'sk-yyy',
|
||||
base_url: 'https://api.anthropic.com',
|
||||
enabled: false,
|
||||
created_at: '2025-01-02T00:00:00Z',
|
||||
updated_at: '2025-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
describe('providers API', () => {
|
||||
const server = setupServer();
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: 'bypass' }));
|
||||
afterEach(() => server.resetHandlers());
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('listProviders', () => {
|
||||
it('returns array of Provider objects with camelCase keys', async () => {
|
||||
server.use(
|
||||
http.get('/api/providers', () => {
|
||||
return HttpResponse.json(mockProviders);
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await listProviders();
|
||||
|
||||
expect(result).toEqual([
|
||||
{
|
||||
id: 'prov-1',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-xxx',
|
||||
baseUrl: 'https://api.openai.com',
|
||||
enabled: true,
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
updatedAt: '2025-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'prov-2',
|
||||
name: 'Anthropic',
|
||||
apiKey: 'sk-yyy',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
enabled: false,
|
||||
createdAt: '2025-01-02T00:00:00Z',
|
||||
updatedAt: '2025-01-02T00:00:00Z',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createProvider', () => {
|
||||
it('sends POST with correct body and returns provider', async () => {
|
||||
let receivedMethod: string | null = null;
|
||||
let receivedBody: Record<string, unknown> | null = null;
|
||||
|
||||
server.use(
|
||||
http.post('/api/providers', async ({ request }) => {
|
||||
receivedMethod = request.method;
|
||||
receivedBody = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json(mockProviders[0]);
|
||||
}),
|
||||
);
|
||||
|
||||
const input = {
|
||||
id: 'prov-1',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-xxx',
|
||||
baseUrl: 'https://api.openai.com',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
const result = await createProvider(input);
|
||||
|
||||
expect(receivedMethod).toBe('POST');
|
||||
expect(receivedBody).toEqual({
|
||||
id: 'prov-1',
|
||||
name: 'OpenAI',
|
||||
api_key: 'sk-xxx',
|
||||
base_url: 'https://api.openai.com',
|
||||
enabled: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
id: 'prov-1',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-xxx',
|
||||
baseUrl: 'https://api.openai.com',
|
||||
enabled: true,
|
||||
createdAt: '2025-01-01T00:00:00Z',
|
||||
updatedAt: '2025-01-01T00:00:00Z',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateProvider', () => {
|
||||
it('sends PUT with correct body and returns provider', async () => {
|
||||
let receivedMethod: string | null = null;
|
||||
let receivedUrl: string | null = null;
|
||||
let receivedBody: Record<string, unknown> | null = null;
|
||||
|
||||
server.use(
|
||||
http.put('/api/providers/:id', async ({ request, params }) => {
|
||||
receivedMethod = request.method;
|
||||
receivedUrl = new URL(request.url).pathname;
|
||||
receivedBody = (await request.json()) as Record<string, unknown>;
|
||||
return HttpResponse.json({
|
||||
...mockProviders[0],
|
||||
name: 'Updated',
|
||||
api_key: 'sk-updated',
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await updateProvider('prov-1', {
|
||||
name: 'Updated',
|
||||
apiKey: 'sk-updated',
|
||||
});
|
||||
|
||||
expect(receivedMethod).toBe('PUT');
|
||||
expect(receivedUrl).toBe('/api/providers/prov-1');
|
||||
expect(receivedBody).toEqual({
|
||||
name: 'Updated',
|
||||
api_key: 'sk-updated',
|
||||
});
|
||||
expect(result.name).toBe('Updated');
|
||||
expect(result.apiKey).toBe('sk-updated');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteProvider', () => {
|
||||
it('sends DELETE and returns void', async () => {
|
||||
let receivedMethod: string | null = null;
|
||||
let receivedUrl: string | null = null;
|
||||
|
||||
server.use(
|
||||
http.delete('/api/providers/:id', ({ request, params }) => {
|
||||
receivedMethod = request.method;
|
||||
receivedUrl = new URL(request.url).pathname;
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await deleteProvider('prov-1');
|
||||
|
||||
expect(receivedMethod).toBe('DELETE');
|
||||
expect(receivedUrl).toBe('/api/providers/prov-1');
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
131
frontend/src/__tests__/api/stats.test.ts
Normal file
131
frontend/src/__tests__/api/stats.test.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import { describe, it, expect, beforeAll, afterEach, afterAll } from 'vitest';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { getStats } from '@/api/stats';
|
||||
|
||||
const mockStats = [
|
||||
{
|
||||
id: 1,
|
||||
provider_id: 'prov-1',
|
||||
model_name: 'gpt-4',
|
||||
request_count: 100,
|
||||
date: '2025-01-15',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
provider_id: 'prov-2',
|
||||
model_name: 'claude-3',
|
||||
request_count: 50,
|
||||
date: '2025-01-16',
|
||||
},
|
||||
];
|
||||
|
||||
describe('stats API', () => {
|
||||
const server = setupServer();
|
||||
|
||||
beforeAll(() => server.listen({ onUnhandledRequest: 'bypass' }));
|
||||
afterEach(() => server.resetHandlers());
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('getStats', () => {
|
||||
it('calls /api/stats without params', async () => {
|
||||
let receivedUrl: string | null = null;
|
||||
|
||||
server.use(
|
||||
http.get('/api/stats', ({ request }) => {
|
||||
receivedUrl = request.url;
|
||||
return HttpResponse.json(mockStats);
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await getStats();
|
||||
|
||||
expect(receivedUrl).toMatch(/\/api\/stats$/);
|
||||
expect(result).toEqual([
|
||||
{
|
||||
id: 1,
|
||||
providerId: 'prov-1',
|
||||
modelName: 'gpt-4',
|
||||
requestCount: 100,
|
||||
date: '2025-01-15',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
providerId: 'prov-2',
|
||||
modelName: 'claude-3',
|
||||
requestCount: 50,
|
||||
date: '2025-01-16',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('builds correct query string with snake_case keys when params are provided', async () => {
|
||||
let receivedUrl: string | null = null;
|
||||
|
||||
server.use(
|
||||
http.get('/api/stats', ({ request }) => {
|
||||
receivedUrl = request.url;
|
||||
return HttpResponse.json([]);
|
||||
}),
|
||||
);
|
||||
|
||||
await getStats({
|
||||
providerId: 'prov-1',
|
||||
modelName: 'gpt-4',
|
||||
startDate: '2025-01-01',
|
||||
endDate: '2025-01-31',
|
||||
});
|
||||
|
||||
expect(receivedUrl).toContain('provider_id=prov-1');
|
||||
expect(receivedUrl).toContain('model_name=gpt-4');
|
||||
expect(receivedUrl).toContain('start_date=2025-01-01');
|
||||
expect(receivedUrl).toContain('end_date=2025-01-31');
|
||||
});
|
||||
|
||||
it('omits undefined params from query string', async () => {
|
||||
let receivedUrl: string | null = null;
|
||||
|
||||
server.use(
|
||||
http.get('/api/stats', ({ request }) => {
|
||||
receivedUrl = request.url;
|
||||
return HttpResponse.json([]);
|
||||
}),
|
||||
);
|
||||
|
||||
await getStats({
|
||||
providerId: 'prov-1',
|
||||
});
|
||||
|
||||
expect(receivedUrl).toContain('provider_id=prov-1');
|
||||
expect(receivedUrl).not.toContain('model_name');
|
||||
expect(receivedUrl).not.toContain('start_date');
|
||||
expect(receivedUrl).not.toContain('end_date');
|
||||
});
|
||||
|
||||
it('returns UsageStats array with camelCase keys', async () => {
|
||||
server.use(
|
||||
http.get('/api/stats', () => {
|
||||
return HttpResponse.json(mockStats);
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await getStats();
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]).toEqual({
|
||||
id: 1,
|
||||
providerId: 'prov-1',
|
||||
modelName: 'gpt-4',
|
||||
requestCount: 100,
|
||||
date: '2025-01-15',
|
||||
});
|
||||
expect(result[1]).toEqual({
|
||||
id: 2,
|
||||
providerId: 'prov-2',
|
||||
modelName: 'claude-3',
|
||||
requestCount: 50,
|
||||
date: '2025-01-16',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
144
frontend/src/__tests__/components/ModelForm.test.tsx
Normal file
144
frontend/src/__tests__/components/ModelForm.test.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import { render, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { ModelForm } from '@/pages/Providers/ModelForm';
|
||||
import type { Provider, Model } from '@/types';
|
||||
|
||||
const mockProviders: Provider[] = [
|
||||
{
|
||||
id: 'openai',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-test',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
enabled: true,
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
updatedAt: '2024-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
apiKey: 'sk-ant-test',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
enabled: true,
|
||||
createdAt: '2024-01-02T00:00:00Z',
|
||||
updatedAt: '2024-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
const mockModel: Model = {
|
||||
id: 'gpt-4o',
|
||||
providerId: 'openai',
|
||||
modelName: 'gpt-4o',
|
||||
enabled: true,
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
const defaultProps = {
|
||||
open: true,
|
||||
providerId: 'openai',
|
||||
providers: mockProviders,
|
||||
onSave: vi.fn(),
|
||||
onCancel: vi.fn(),
|
||||
loading: false,
|
||||
};
|
||||
|
||||
function getDialog() {
|
||||
return screen.getByRole('dialog');
|
||||
}
|
||||
|
||||
describe('ModelForm', () => {
|
||||
it('renders form with provider select', () => {
|
||||
render(<ModelForm {...defaultProps} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
expect(within(dialog).getByText('添加模型')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('ID')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('供应商')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('模型名称')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('启用')).toBeInTheDocument();
|
||||
|
||||
// The selected provider (OpenAI) is shown; Anthropic is not rendered until dropdown opens
|
||||
expect(within(dialog).getByText('OpenAI')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('defaults providerId to the passed providerId in create mode', () => {
|
||||
render(<ModelForm {...defaultProps} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
const selectionItem = dialog.querySelector('.ant-select-selection-item');
|
||||
expect(selectionItem).toBeInTheDocument();
|
||||
expect(selectionItem?.textContent).toBe('OpenAI');
|
||||
});
|
||||
|
||||
it('shows validation error messages for required fields', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(
|
||||
<ModelForm
|
||||
{...defaultProps}
|
||||
providerId={undefined as unknown as string}
|
||||
providers={[]}
|
||||
/>,
|
||||
);
|
||||
|
||||
const dialog = getDialog();
|
||||
const okButton = within(dialog).getByRole('button', { name: /保/ });
|
||||
await user.click(okButton);
|
||||
|
||||
expect(await screen.findByText('请输入模型 ID')).toBeInTheDocument();
|
||||
expect(screen.getByText('请选择供应商')).toBeInTheDocument();
|
||||
expect(screen.getByText('请输入模型名称')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onSave with form values on successful submission', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn();
|
||||
render(<ModelForm {...defaultProps} onSave={onSave} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
// There are two inputs with placeholder "例如: gpt-4o": ID field (index 0) and model name (index 1)
|
||||
const inputs = within(dialog).getAllByPlaceholderText('例如: gpt-4o');
|
||||
|
||||
// Type into the ID field
|
||||
await user.type(inputs[0], 'gpt-4o-mini');
|
||||
// Type into the model name field
|
||||
await user.type(inputs[1], 'gpt-4o-mini');
|
||||
|
||||
const okButton = within(dialog).getByRole('button', { name: /保/ });
|
||||
await user.click(okButton);
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'gpt-4o-mini',
|
||||
providerId: 'openai',
|
||||
modelName: 'gpt-4o-mini',
|
||||
enabled: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('renders pre-filled fields in edit mode', () => {
|
||||
render(<ModelForm {...defaultProps} model={mockModel} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
expect(within(dialog).getByText('编辑模型')).toBeInTheDocument();
|
||||
|
||||
const inputs = within(dialog).getAllByPlaceholderText('例如: gpt-4o');
|
||||
const idInput = inputs[0] as HTMLInputElement;
|
||||
expect(idInput.value).toBe('gpt-4o');
|
||||
expect(idInput).toBeDisabled();
|
||||
|
||||
const modelNameInput = inputs[1] as HTMLInputElement;
|
||||
expect(modelNameInput.value).toBe('gpt-4o');
|
||||
});
|
||||
|
||||
it('calls onCancel when clicking cancel button', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onCancel = vi.fn();
|
||||
render(<ModelForm {...defaultProps} onCancel={onCancel} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
const cancelButton = within(dialog).getByRole('button', { name: /取/ });
|
||||
await user.click(cancelButton);
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
147
frontend/src/__tests__/components/ProviderForm.test.tsx
Normal file
147
frontend/src/__tests__/components/ProviderForm.test.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
import { render, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { ProviderForm } from '@/pages/Providers/ProviderForm';
|
||||
import type { Provider } from '@/types';
|
||||
|
||||
const mockProvider: Provider = {
|
||||
id: 'openai',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-old-key',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
enabled: true,
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
updatedAt: '2024-01-01T00:00:00Z',
|
||||
};
|
||||
|
||||
const defaultProps = {
|
||||
open: true,
|
||||
onSave: vi.fn(),
|
||||
onCancel: vi.fn(),
|
||||
loading: false,
|
||||
};
|
||||
|
||||
function getDialog() {
|
||||
return screen.getByRole('dialog');
|
||||
}
|
||||
|
||||
describe('ProviderForm', () => {
|
||||
it('renders form fields in create mode', () => {
|
||||
render(<ProviderForm {...defaultProps} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
expect(within(dialog).getByText('添加供应商')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('ID')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('名称')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('API Key')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Base URL')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('启用')).toBeInTheDocument();
|
||||
expect(within(dialog).getByPlaceholderText('例如: openai')).toBeInTheDocument();
|
||||
expect(within(dialog).getByPlaceholderText('例如: OpenAI')).toBeInTheDocument();
|
||||
expect(within(dialog).getByPlaceholderText('例如: https://api.openai.com/v1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders pre-filled fields in edit mode', () => {
|
||||
render(<ProviderForm {...defaultProps} provider={mockProvider} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
expect(within(dialog).getByText('编辑供应商')).toBeInTheDocument();
|
||||
|
||||
const idInput = within(dialog).getByPlaceholderText('例如: openai') as HTMLInputElement;
|
||||
expect(idInput.value).toBe('openai');
|
||||
expect(idInput).toBeDisabled();
|
||||
|
||||
const nameInput = within(dialog).getByPlaceholderText('例如: OpenAI') as HTMLInputElement;
|
||||
expect(nameInput.value).toBe('OpenAI');
|
||||
|
||||
const baseUrlInput = within(dialog).getByPlaceholderText('例如: https://api.openai.com/v1') as HTMLInputElement;
|
||||
expect(baseUrlInput.value).toBe('https://api.openai.com/v1');
|
||||
});
|
||||
|
||||
it('shows API Key label variant in edit mode', () => {
|
||||
render(<ProviderForm {...defaultProps} provider={mockProvider} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
expect(within(dialog).getByText('API Key(留空则不修改)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows validation error messages for required fields', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ProviderForm {...defaultProps} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
const okButton = within(dialog).getByRole('button', { name: /保/ });
|
||||
await user.click(okButton);
|
||||
|
||||
// Wait for validation messages to appear
|
||||
expect(await screen.findByText('请输入供应商 ID')).toBeInTheDocument();
|
||||
expect(screen.getByText('请输入名称')).toBeInTheDocument();
|
||||
expect(screen.getByText('请输入 API Key')).toBeInTheDocument();
|
||||
expect(screen.getByText('请输入 Base URL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onSave with form values on successful submission', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onSave = vi.fn();
|
||||
render(<ProviderForm {...defaultProps} onSave={onSave} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
await user.type(within(dialog).getByPlaceholderText('例如: openai'), 'test-provider');
|
||||
await user.type(within(dialog).getByPlaceholderText('例如: OpenAI'), 'Test Provider');
|
||||
await user.type(within(dialog).getByPlaceholderText('sk-...'), 'sk-test-key');
|
||||
await user.type(within(dialog).getByPlaceholderText('例如: https://api.openai.com/v1'), 'https://api.test.com/v1');
|
||||
|
||||
const okButton = within(dialog).getByRole('button', { name: /保/ });
|
||||
await user.click(okButton);
|
||||
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'test-provider',
|
||||
name: 'Test Provider',
|
||||
apiKey: 'sk-test-key',
|
||||
baseUrl: 'https://api.test.com/v1',
|
||||
enabled: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('calls onCancel when clicking cancel button', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onCancel = vi.fn();
|
||||
render(<ProviderForm {...defaultProps} onCancel={onCancel} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
const cancelButton = within(dialog).getByRole('button', { name: /取/ });
|
||||
await user.click(cancelButton);
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('shows confirm loading state', () => {
|
||||
render(<ProviderForm {...defaultProps} loading={true} />);
|
||||
const dialog = getDialog();
|
||||
const okButton = within(dialog).getByRole('button', { name: /保/ });
|
||||
expect(okButton).toHaveClass('ant-btn-loading');
|
||||
});
|
||||
|
||||
it('shows validation error for invalid URL format', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ProviderForm {...defaultProps} />);
|
||||
|
||||
const dialog = getDialog();
|
||||
|
||||
// Fill in required fields
|
||||
await user.type(within(dialog).getByPlaceholderText('例如: openai'), 'test-provider');
|
||||
await user.type(within(dialog).getByPlaceholderText('例如: OpenAI'), 'Test Provider');
|
||||
await user.type(within(dialog).getByPlaceholderText('sk-...'), 'sk-test-key');
|
||||
|
||||
// Enter an invalid URL in the Base URL field
|
||||
await user.type(within(dialog).getByPlaceholderText('例如: https://api.openai.com/v1'), 'not-a-url');
|
||||
|
||||
// Submit the form
|
||||
const okButton = within(dialog).getByRole('button', { name: /保/ });
|
||||
await user.click(okButton);
|
||||
|
||||
// Verify that a URL validation error message appears
|
||||
expect(await screen.findByText('请输入有效的 URL')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
140
frontend/src/__tests__/components/ProviderTable.test.tsx
Normal file
140
frontend/src/__tests__/components/ProviderTable.test.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { ProviderTable } from '@/pages/Providers/ProviderTable';
|
||||
import type { Provider } from '@/types';
|
||||
|
||||
const mockModelsData = [
|
||||
{ id: 'model-1', providerId: 'openai', modelName: 'gpt-4o', enabled: true },
|
||||
{ id: 'model-2', providerId: 'openai', modelName: 'gpt-3.5-turbo', enabled: false },
|
||||
];
|
||||
|
||||
vi.mock('@/hooks/useModels', () => ({
|
||||
useModels: vi.fn(() => ({ data: mockModelsData, isLoading: false })),
|
||||
useDeleteModel: vi.fn(() => ({ mutate: vi.fn() })),
|
||||
}));
|
||||
|
||||
const mockProviders: Provider[] = [
|
||||
{
|
||||
id: 'openai',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-abcdefgh12345678',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
enabled: true,
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
updatedAt: '2024-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
apiKey: 'sk-ant-test',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
enabled: false,
|
||||
createdAt: '2024-01-02T00:00:00Z',
|
||||
updatedAt: '2024-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
const defaultProps = {
|
||||
providers: mockProviders,
|
||||
loading: false,
|
||||
onAdd: vi.fn(),
|
||||
onEdit: vi.fn(),
|
||||
onDelete: vi.fn(),
|
||||
onAddModel: vi.fn(),
|
||||
onEditModel: vi.fn(),
|
||||
};
|
||||
|
||||
describe('ProviderTable', () => {
|
||||
it('renders provider list with name, baseUrl, masked apiKey, and status tags', () => {
|
||||
render(<ProviderTable {...defaultProps} />);
|
||||
|
||||
expect(screen.getByText('供应商列表')).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText('OpenAI')).toBeInTheDocument();
|
||||
expect(screen.getByText('https://api.openai.com/v1')).toBeInTheDocument();
|
||||
expect(screen.getByText('****5678')).toBeInTheDocument();
|
||||
|
||||
expect(screen.getByText('Anthropic')).toBeInTheDocument();
|
||||
expect(screen.getByText('https://api.anthropic.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('****test')).toBeInTheDocument();
|
||||
|
||||
const enabledTags = screen.getAllByText('启用');
|
||||
const disabledTags = screen.getAllByText('禁用');
|
||||
expect(enabledTags.length).toBeGreaterThanOrEqual(1);
|
||||
expect(disabledTags.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('renders short api keys fully masked', () => {
|
||||
const shortKeyProvider: Provider[] = [
|
||||
{
|
||||
...mockProviders[0],
|
||||
id: 'short',
|
||||
name: 'ShortKey',
|
||||
apiKey: 'ab',
|
||||
},
|
||||
];
|
||||
render(<ProviderTable {...defaultProps} providers={shortKeyProvider} />);
|
||||
|
||||
expect(screen.getByText('****')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onAdd when clicking "添加供应商" button', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onAdd = vi.fn();
|
||||
render(<ProviderTable {...defaultProps} onAdd={onAdd} />);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: '添加供应商' }));
|
||||
expect(onAdd).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('calls onEdit with correct provider when clicking "编辑"', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onEdit = vi.fn();
|
||||
render(<ProviderTable {...defaultProps} onEdit={onEdit} />);
|
||||
|
||||
const editButtons = screen.getAllByRole('button', { name: '编辑' });
|
||||
await user.click(editButtons[0]);
|
||||
|
||||
expect(onEdit).toHaveBeenCalledTimes(1);
|
||||
expect(onEdit).toHaveBeenCalledWith(mockProviders[0]);
|
||||
});
|
||||
|
||||
it('calls onDelete with correct provider ID when delete is confirmed', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onDelete = vi.fn();
|
||||
render(<ProviderTable {...defaultProps} onDelete={onDelete} />);
|
||||
|
||||
// Find and click the delete button for the first row
|
||||
const deleteButtons = screen.getAllByRole('button', { name: '删除' });
|
||||
await user.click(deleteButtons[0]);
|
||||
|
||||
// Find and click the "确 定" confirm button in the Popconfirm popup
|
||||
// antd renders the text with spaces between Chinese characters
|
||||
const confirmButtons = await screen.findAllByText('确 定');
|
||||
await user.click(confirmButtons[0]);
|
||||
|
||||
// Assert that onDelete was called with the correct provider ID
|
||||
expect(onDelete).toHaveBeenCalledTimes(1);
|
||||
expect(onDelete).toHaveBeenCalledWith('openai');
|
||||
});
|
||||
|
||||
it('shows loading state', () => {
|
||||
render(<ProviderTable {...defaultProps} loading={true} />);
|
||||
expect(document.querySelector('.ant-spin')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders expandable ModelTable when row is expanded', async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<ProviderTable {...defaultProps} />);
|
||||
|
||||
// Find and click the expand button for the first row
|
||||
const expandButtons = screen.getAllByRole('button', { name: /expand/i });
|
||||
expect(expandButtons.length).toBeGreaterThanOrEqual(1);
|
||||
await user.click(expandButtons[0]);
|
||||
|
||||
// Verify that ModelTable content is rendered with data from mocked useModels
|
||||
expect(await screen.findByText('gpt-4o')).toBeInTheDocument();
|
||||
expect(screen.getByText('gpt-3.5-turbo')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
159
frontend/src/__tests__/components/StatsTable.test.tsx
Normal file
159
frontend/src/__tests__/components/StatsTable.test.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
import { render, screen, within, fireEvent } from '@testing-library/react';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { StatsTable } from '@/pages/Stats/StatsTable';
|
||||
import type { Provider, UsageStats } from '@/types';
|
||||
|
||||
const mockProviders: Provider[] = [
|
||||
{
|
||||
id: 'openai',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-test',
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
enabled: true,
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
updatedAt: '2024-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
apiKey: 'sk-ant-test',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
enabled: true,
|
||||
createdAt: '2024-01-02T00:00:00Z',
|
||||
updatedAt: '2024-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
const mockStats: UsageStats[] = [
|
||||
{
|
||||
id: 1,
|
||||
providerId: 'openai',
|
||||
modelName: 'gpt-4o',
|
||||
requestCount: 100,
|
||||
date: '2024-01-15',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
providerId: 'anthropic',
|
||||
modelName: 'claude-3-opus',
|
||||
requestCount: 50,
|
||||
date: '2024-01-15',
|
||||
},
|
||||
];
|
||||
|
||||
const mockUseStats = vi.fn(() => ({
|
||||
data: mockStats,
|
||||
isLoading: false,
|
||||
}));
|
||||
|
||||
vi.mock('@/hooks/useStats', () => ({
|
||||
useStats: (...args: unknown[]) => mockUseStats(...args),
|
||||
}));
|
||||
|
||||
describe('StatsTable', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders stats table with data', () => {
|
||||
render(<StatsTable providers={mockProviders} />);
|
||||
|
||||
expect(screen.getByText('gpt-4o')).toBeInTheDocument();
|
||||
expect(screen.getByText('claude-3-opus')).toBeInTheDocument();
|
||||
// Both rows share the same date
|
||||
const dateCells = screen.getAllByText('2024-01-15');
|
||||
expect(dateCells.length).toBe(2);
|
||||
expect(screen.getByText('100')).toBeInTheDocument();
|
||||
expect(screen.getByText('50')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows provider name from providers prop instead of providerId', () => {
|
||||
render(<StatsTable providers={mockProviders} />);
|
||||
|
||||
expect(screen.getByText('OpenAI')).toBeInTheDocument();
|
||||
// "Anthropic" appears in both the provider column and the filter select options
|
||||
const allAnthropic = screen.getAllByText('Anthropic');
|
||||
expect(allAnthropic.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('renders filter controls with Select, Input, and DatePicker', () => {
|
||||
render(<StatsTable providers={mockProviders} />);
|
||||
|
||||
// Check that the select element exists for provider filter
|
||||
const selects = document.querySelectorAll('.ant-select');
|
||||
expect(selects.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Check that the Input element exists for model name filter
|
||||
const modelInput = screen.getByPlaceholderText('模型名称');
|
||||
expect(modelInput).toBeInTheDocument();
|
||||
|
||||
// Verify placeholder text is rendered
|
||||
expect(screen.getByText('所有供应商')).toBeInTheDocument();
|
||||
|
||||
const rangePicker = document.querySelector('.ant-picker-range');
|
||||
expect(rangePicker).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders table headers correctly', () => {
|
||||
render(<StatsTable providers={mockProviders} />);
|
||||
|
||||
expect(screen.getByText('供应商')).toBeInTheDocument();
|
||||
expect(screen.getByText('模型')).toBeInTheDocument();
|
||||
expect(screen.getByText('日期')).toBeInTheDocument();
|
||||
expect(screen.getByText('请求数')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back to providerId when provider not found in providers prop', () => {
|
||||
const limitedProviders = [mockProviders[0]]; // only OpenAI
|
||||
render(<StatsTable providers={limitedProviders} />);
|
||||
|
||||
// OpenAI should show name
|
||||
expect(screen.getByText('OpenAI')).toBeInTheDocument();
|
||||
// Anthropic is not in providers list, so providerId "anthropic" should show
|
||||
expect(screen.getByText('anthropic')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders with empty stats data', () => {
|
||||
mockUseStats.mockReturnValueOnce({
|
||||
data: [],
|
||||
isLoading: false,
|
||||
});
|
||||
|
||||
render(<StatsTable providers={mockProviders} />);
|
||||
|
||||
// Table should still be rendered, just empty
|
||||
expect(screen.getByText('供应商')).toBeInTheDocument();
|
||||
expect(screen.getByText('模型')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('updates provider filter when selecting a provider', () => {
|
||||
render(<StatsTable providers={mockProviders} />);
|
||||
|
||||
// Initially useStats should be called with no providerId filter
|
||||
expect(mockUseStats).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
providerId: undefined,
|
||||
}),
|
||||
);
|
||||
|
||||
// Find the provider Select and change its value
|
||||
const selectElement = document.querySelector('.ant-select');
|
||||
expect(selectElement).toBeInTheDocument();
|
||||
|
||||
// Open the select dropdown
|
||||
fireEvent.mouseDown(selectElement!.querySelector('.ant-select-selector')!);
|
||||
|
||||
// Click on the "OpenAI" option from the dropdown
|
||||
const dropdown = document.querySelector('.ant-select-dropdown');
|
||||
expect(dropdown).toBeInTheDocument();
|
||||
const openaiOption = within(dropdown as HTMLElement).getByText('OpenAI');
|
||||
fireEvent.click(openaiOption);
|
||||
|
||||
// After selecting, useStats should be called with providerId set to 'openai'
|
||||
expect(mockUseStats).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
providerId: 'openai',
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
287
frontend/src/__tests__/hooks/useModels.test.tsx
Normal file
287
frontend/src/__tests__/hooks/useModels.test.tsx
Normal file
@@ -0,0 +1,287 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { useModels, useCreateModel, useUpdateModel, useDeleteModel } from '@/hooks/useModels';
|
||||
import type { Model, CreateModelInput, UpdateModelInput } from '@/types';
|
||||
|
||||
// Mock antd message since it uses DOM APIs not available in jsdom
|
||||
vi.mock('antd', () => ({
|
||||
message: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { message } from 'antd';
|
||||
|
||||
// Test data
|
||||
const mockModels: Model[] = [
|
||||
{
|
||||
id: 'model-1',
|
||||
providerId: 'provider-1',
|
||||
modelName: 'gpt-4o',
|
||||
enabled: true,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'model-2',
|
||||
providerId: 'provider-1',
|
||||
modelName: 'gpt-4o-mini',
|
||||
enabled: true,
|
||||
createdAt: '2026-01-02T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
const mockFilteredModels: Model[] = [
|
||||
{
|
||||
id: 'model-3',
|
||||
providerId: 'provider-2',
|
||||
modelName: 'claude-sonnet-4-5',
|
||||
enabled: true,
|
||||
createdAt: '2026-02-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
const mockCreatedModel: Model = {
|
||||
id: 'model-4',
|
||||
providerId: 'provider-1',
|
||||
modelName: 'gpt-4.1',
|
||||
enabled: true,
|
||||
createdAt: '2026-03-01T00:00:00Z',
|
||||
};
|
||||
|
||||
// MSW handlers
|
||||
const handlers = [
|
||||
http.get('/api/models', ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const providerId = url.searchParams.get('provider_id');
|
||||
if (providerId === 'provider-2') {
|
||||
return HttpResponse.json(mockFilteredModels);
|
||||
}
|
||||
return HttpResponse.json(mockModels);
|
||||
}),
|
||||
http.post('/api/models', async ({ request }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({
|
||||
...mockCreatedModel,
|
||||
...body,
|
||||
});
|
||||
}),
|
||||
http.put('/api/models/:id', async ({ request, params }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
const existing = mockModels.find((m) => m.id === params['id']);
|
||||
return HttpResponse.json({ ...existing, ...body });
|
||||
}),
|
||||
http.delete('/api/models/:id', () => {
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
];
|
||||
|
||||
const server = setupServer(...handlers);
|
||||
|
||||
function createTestQueryClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const testQueryClient = createTestQueryClient();
|
||||
return function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={testQueryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('useModels', () => {
|
||||
it('fetches model list', async () => {
|
||||
const { result } = renderHook(() => useModels(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toEqual(mockModels);
|
||||
expect(result.current.data).toHaveLength(2);
|
||||
expect(result.current.data![0]!.modelName).toBe('gpt-4o');
|
||||
});
|
||||
|
||||
it('with providerId passes it to API and returns filtered models', async () => {
|
||||
const { result } = renderHook(() => useModels('provider-2'), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toEqual(mockFilteredModels);
|
||||
expect(result.current.data).toHaveLength(1);
|
||||
expect(result.current.data![0]!.modelName).toBe('claude-sonnet-4-5');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCreateModel', () => {
|
||||
it('calls API and invalidates model queries', async () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useCreateModel(), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
|
||||
const input: CreateModelInput = {
|
||||
id: 'model-4',
|
||||
providerId: 'provider-1',
|
||||
modelName: 'gpt-4.1',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
result.current.mutate(input);
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
id: 'model-4',
|
||||
modelName: 'gpt-4.1',
|
||||
});
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['models'] });
|
||||
expect(message.success).toHaveBeenCalledWith('模型创建成功');
|
||||
});
|
||||
|
||||
it('calls message.error on failure', async () => {
|
||||
server.use(
|
||||
http.post('/api/models', () => {
|
||||
return HttpResponse.json({ message: '创建失败' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useCreateModel(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const input: CreateModelInput = {
|
||||
id: 'model-4',
|
||||
providerId: 'provider-1',
|
||||
modelName: 'gpt-4.1',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
result.current.mutate(input);
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(message.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useUpdateModel', () => {
|
||||
it('calls API and invalidates model queries', async () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useUpdateModel(), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
|
||||
const input: UpdateModelInput = { modelName: 'gpt-4o-updated' };
|
||||
|
||||
result.current.mutate({ id: 'model-1', input });
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
modelName: 'gpt-4o-updated',
|
||||
});
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['models'] });
|
||||
expect(message.success).toHaveBeenCalledWith('模型更新成功');
|
||||
});
|
||||
|
||||
it('calls message.error on failure', async () => {
|
||||
server.use(
|
||||
http.put('/api/models/:id', () => {
|
||||
return HttpResponse.json({ message: '更新失败' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUpdateModel(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
result.current.mutate({ id: 'model-1', input: { modelName: 'Updated' } });
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(message.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useDeleteModel', () => {
|
||||
it('calls API and invalidates model queries', async () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useDeleteModel(), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
|
||||
result.current.mutate('model-1');
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['models'] });
|
||||
expect(message.success).toHaveBeenCalledWith('模型删除成功');
|
||||
});
|
||||
|
||||
it('calls message.error on failure', async () => {
|
||||
server.use(
|
||||
http.delete('/api/models/:id', () => {
|
||||
return HttpResponse.json({ message: '删除失败' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useDeleteModel(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
result.current.mutate('model-1');
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(message.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
270
frontend/src/__tests__/hooks/useProviders.test.tsx
Normal file
270
frontend/src/__tests__/hooks/useProviders.test.tsx
Normal file
@@ -0,0 +1,270 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { useProviders, useCreateProvider, useUpdateProvider, useDeleteProvider } from '@/hooks/useProviders';
|
||||
import type { Provider, CreateProviderInput, UpdateProviderInput } from '@/types';
|
||||
|
||||
// Mock antd message since it uses DOM APIs not available in jsdom
|
||||
vi.mock('antd', () => ({
|
||||
message: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Import the mocked message for assertions
|
||||
import { message } from 'antd';
|
||||
|
||||
// Test data
|
||||
const mockProviders: Provider[] = [
|
||||
{
|
||||
id: 'provider-1',
|
||||
name: 'OpenAI',
|
||||
apiKey: 'sk-xxx',
|
||||
baseUrl: 'https://api.openai.com',
|
||||
enabled: true,
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
{
|
||||
id: 'provider-2',
|
||||
name: 'Anthropic',
|
||||
apiKey: 'sk-yyy',
|
||||
baseUrl: 'https://api.anthropic.com',
|
||||
enabled: false,
|
||||
createdAt: '2026-02-01T00:00:00Z',
|
||||
updatedAt: '2026-02-01T00:00:00Z',
|
||||
},
|
||||
];
|
||||
|
||||
const mockCreatedProvider: Provider = {
|
||||
id: 'provider-3',
|
||||
name: 'NewProvider',
|
||||
apiKey: 'sk-zzz',
|
||||
baseUrl: 'https://api.newprovider.com',
|
||||
enabled: true,
|
||||
createdAt: '2026-03-01T00:00:00Z',
|
||||
updatedAt: '2026-03-01T00:00:00Z',
|
||||
};
|
||||
|
||||
// MSW handlers
|
||||
const handlers = [
|
||||
http.get('/api/providers', () => {
|
||||
return HttpResponse.json(mockProviders);
|
||||
}),
|
||||
http.post('/api/providers', async ({ request }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
return HttpResponse.json({
|
||||
...mockCreatedProvider,
|
||||
...body,
|
||||
});
|
||||
}),
|
||||
http.put('/api/providers/:id', async ({ request, params }) => {
|
||||
const body = await request.json() as Record<string, unknown>;
|
||||
const existing = mockProviders.find((p) => p.id === params['id']);
|
||||
return HttpResponse.json({ ...existing, ...body });
|
||||
}),
|
||||
http.delete('/api/providers/:id', () => {
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
];
|
||||
|
||||
const server = setupServer(...handlers);
|
||||
|
||||
function createTestQueryClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const testQueryClient = createTestQueryClient();
|
||||
return function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={testQueryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('useProviders', () => {
|
||||
it('fetches and returns provider list', async () => {
|
||||
const { result } = renderHook(() => useProviders(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toEqual(mockProviders);
|
||||
expect(result.current.data).toHaveLength(2);
|
||||
expect(result.current.data![0]!.name).toBe('OpenAI');
|
||||
expect(result.current.data![1]!.name).toBe('Anthropic');
|
||||
});
|
||||
});
|
||||
|
||||
describe('useCreateProvider', () => {
|
||||
it('calls API and invalidates provider queries', async () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useCreateProvider(), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
|
||||
const input: CreateProviderInput = {
|
||||
id: 'provider-3',
|
||||
name: 'NewProvider',
|
||||
apiKey: 'sk-zzz',
|
||||
baseUrl: 'https://api.newprovider.com',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
result.current.mutate(input);
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
id: 'provider-3',
|
||||
name: 'NewProvider',
|
||||
});
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['providers'] });
|
||||
expect(message.success).toHaveBeenCalledWith('供应商创建成功');
|
||||
});
|
||||
|
||||
it('calls message.error on failure', async () => {
|
||||
server.use(
|
||||
http.post('/api/providers', () => {
|
||||
return HttpResponse.json({ message: '创建失败' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useCreateProvider(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
const input: CreateProviderInput = {
|
||||
id: 'provider-3',
|
||||
name: 'NewProvider',
|
||||
apiKey: 'sk-zzz',
|
||||
baseUrl: 'https://api.newprovider.com',
|
||||
enabled: true,
|
||||
};
|
||||
|
||||
result.current.mutate(input);
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(message.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useUpdateProvider', () => {
|
||||
it('calls API and invalidates provider queries', async () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useUpdateProvider(), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
|
||||
const input: UpdateProviderInput = { name: 'UpdatedProvider' };
|
||||
|
||||
result.current.mutate({ id: 'provider-1', input });
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
name: 'UpdatedProvider',
|
||||
});
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['providers'] });
|
||||
expect(message.success).toHaveBeenCalledWith('供应商更新成功');
|
||||
});
|
||||
|
||||
it('calls message.error on failure', async () => {
|
||||
server.use(
|
||||
http.put('/api/providers/:id', () => {
|
||||
return HttpResponse.json({ message: '更新失败' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useUpdateProvider(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
result.current.mutate({ id: 'provider-1', input: { name: 'Updated' } });
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(message.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('useDeleteProvider', () => {
|
||||
it('calls API and invalidates provider queries', async () => {
|
||||
const queryClient = createTestQueryClient();
|
||||
const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries');
|
||||
|
||||
function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const { result } = renderHook(() => useDeleteProvider(), {
|
||||
wrapper: Wrapper,
|
||||
});
|
||||
|
||||
result.current.mutate('provider-1');
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['providers'] });
|
||||
expect(message.success).toHaveBeenCalledWith('供应商删除成功');
|
||||
});
|
||||
|
||||
it('calls message.error on failure', async () => {
|
||||
server.use(
|
||||
http.delete('/api/providers/:id', () => {
|
||||
return HttpResponse.json({ message: '删除失败' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useDeleteProvider(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
result.current.mutate('provider-1');
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true));
|
||||
expect(message.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
140
frontend/src/__tests__/hooks/useStats.test.tsx
Normal file
140
frontend/src/__tests__/hooks/useStats.test.tsx
Normal file
@@ -0,0 +1,140 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import React from 'react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { setupServer } from 'msw/node';
|
||||
import { useStats } from '@/hooks/useStats';
|
||||
import type { UsageStats, StatsQueryParams } from '@/types';
|
||||
|
||||
// Test data
|
||||
const mockStats: UsageStats[] = [
|
||||
{
|
||||
id: 1,
|
||||
providerId: 'provider-1',
|
||||
modelName: 'gpt-4o',
|
||||
requestCount: 100,
|
||||
date: '2026-04-01',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
providerId: 'provider-1',
|
||||
modelName: 'gpt-4o-mini',
|
||||
requestCount: 50,
|
||||
date: '2026-04-01',
|
||||
},
|
||||
];
|
||||
|
||||
const mockFilteredStats: UsageStats[] = [
|
||||
{
|
||||
id: 3,
|
||||
providerId: 'provider-2',
|
||||
modelName: 'claude-sonnet-4-5',
|
||||
requestCount: 200,
|
||||
date: '2026-04-01',
|
||||
},
|
||||
];
|
||||
|
||||
// Track the request URL for assertions
|
||||
let capturedUrl: URL | null = null;
|
||||
|
||||
// MSW handlers
|
||||
const handlers = [
|
||||
http.get('/api/stats', ({ request }) => {
|
||||
capturedUrl = new URL(request.url);
|
||||
const providerId = capturedUrl.searchParams.get('provider_id');
|
||||
if (providerId === 'provider-2') {
|
||||
return HttpResponse.json(mockFilteredStats);
|
||||
}
|
||||
return HttpResponse.json(mockStats);
|
||||
}),
|
||||
];
|
||||
|
||||
const server = setupServer(...handlers);
|
||||
|
||||
function createTestQueryClient() {
|
||||
return new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const testQueryClient = createTestQueryClient();
|
||||
return function Wrapper({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<QueryClientProvider client={testQueryClient}>
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
capturedUrl = null;
|
||||
});
|
||||
afterAll(() => server.close());
|
||||
|
||||
describe('useStats', () => {
|
||||
it('fetches stats without params', async () => {
|
||||
const { result } = renderHook(() => useStats(), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toEqual(mockStats);
|
||||
expect(result.current.data).toHaveLength(2);
|
||||
expect(result.current.data![0]!.modelName).toBe('gpt-4o');
|
||||
expect(result.current.data![1]!.requestCount).toBe(50);
|
||||
|
||||
// Verify no query params were sent
|
||||
expect(capturedUrl!.search).toBe('');
|
||||
});
|
||||
|
||||
it('with filter params passes them correctly', async () => {
|
||||
const params: StatsQueryParams = {
|
||||
providerId: 'provider-2',
|
||||
modelName: 'claude-sonnet-4-5',
|
||||
startDate: '2026-04-01',
|
||||
endDate: '2026-04-15',
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useStats(params), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
expect(result.current.data).toEqual(mockFilteredStats);
|
||||
expect(result.current.data).toHaveLength(1);
|
||||
expect(result.current.data![0]!.modelName).toBe('claude-sonnet-4-5');
|
||||
|
||||
// Verify query params were passed correctly (snake_case)
|
||||
expect(capturedUrl!.searchParams.get('provider_id')).toBe('provider-2');
|
||||
expect(capturedUrl!.searchParams.get('model_name')).toBe('claude-sonnet-4-5');
|
||||
expect(capturedUrl!.searchParams.get('start_date')).toBe('2026-04-01');
|
||||
expect(capturedUrl!.searchParams.get('end_date')).toBe('2026-04-15');
|
||||
});
|
||||
|
||||
it('with partial filter params only sends provided params', async () => {
|
||||
const params: StatsQueryParams = {
|
||||
providerId: 'provider-1',
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useStats(params), {
|
||||
wrapper: createWrapper(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
|
||||
// Verify only provider_id was sent
|
||||
expect(capturedUrl!.searchParams.get('provider_id')).toBe('provider-1');
|
||||
expect(capturedUrl!.searchParams.get('model_name')).toBeNull();
|
||||
expect(capturedUrl!.searchParams.get('start_date')).toBeNull();
|
||||
expect(capturedUrl!.searchParams.get('end_date')).toBeNull();
|
||||
});
|
||||
});
|
||||
26
frontend/src/__tests__/setup.ts
Normal file
26
frontend/src/__tests__/setup.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
|
||||
// Polyfill window.matchMedia for jsdom (required by antd)
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: (query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: () => {},
|
||||
removeListener: () => {},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
dispatchEvent: () => false,
|
||||
}),
|
||||
});
|
||||
|
||||
// Polyfill window.getComputedStyle to suppress jsdom warnings
|
||||
const originalGetComputedStyle = window.getComputedStyle;
|
||||
window.getComputedStyle = (elt: Element, pseudoElt?: string | null) => {
|
||||
try {
|
||||
return originalGetComputedStyle(elt, pseudoElt);
|
||||
} catch {
|
||||
return {} as CSSStyleDeclaration;
|
||||
}
|
||||
};
|
||||
@@ -1,129 +1,71 @@
|
||||
const API_BASE = 'http://localhost:9826/api';
|
||||
import { ApiError } from '@/types';
|
||||
|
||||
export interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
api_key: string;
|
||||
base_url: string;
|
||||
enabled: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
const API_BASE = import.meta.env.VITE_API_BASE || '';
|
||||
|
||||
function toCamelCase(str: string): string {
|
||||
return str.replace(/_([a-z])/g, (_, letter: string) => letter.toUpperCase());
|
||||
}
|
||||
|
||||
export interface Model {
|
||||
id: string;
|
||||
provider_id: string;
|
||||
model_name: string;
|
||||
enabled: boolean;
|
||||
created_at: string;
|
||||
function toSnakeCase(str: string): string {
|
||||
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
|
||||
}
|
||||
|
||||
export interface UsageStats {
|
||||
id: number;
|
||||
provider_id: string;
|
||||
model_name: string;
|
||||
request_count: number;
|
||||
date: string;
|
||||
function transformKeys<T>(obj: unknown, transformer: (key: string) => string): T {
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map((item) => transformKeys(item, transformer)) as T;
|
||||
}
|
||||
if (obj !== null && typeof obj === 'object') {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {
|
||||
result[transformer(key)] = transformKeys(value, transformer);
|
||||
}
|
||||
return result as T;
|
||||
}
|
||||
return obj as T;
|
||||
}
|
||||
|
||||
// Provider API
|
||||
export async function listProviders(): Promise<Provider[]> {
|
||||
const response = await fetch(`${API_BASE}/providers`);
|
||||
if (!response.ok) throw new Error('Failed to fetch providers');
|
||||
return response.json();
|
||||
export function fromApi<T>(data: unknown): T {
|
||||
return transformKeys<T>(data, toCamelCase);
|
||||
}
|
||||
|
||||
export async function createProvider(provider: Omit<Provider, 'created_at' | 'updated_at'>): Promise<Provider> {
|
||||
const response = await fetch(`${API_BASE}/providers`, {
|
||||
method: 'POST',
|
||||
export function toApi<T>(data: unknown): T {
|
||||
return transformKeys<T>(data, toSnakeCase);
|
||||
}
|
||||
|
||||
export async function request<T>(
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
): Promise<T> {
|
||||
const url = `${API_BASE}${path}`;
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(provider),
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to create provider');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function updateProvider(id: string, updates: Partial<Provider>): Promise<Provider> {
|
||||
const response = await fetch(`${API_BASE}/providers/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(updates),
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to update provider');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function deleteProvider(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE}/providers/${id}`, { method: 'DELETE' });
|
||||
if (!response.ok) throw new Error('Failed to delete provider');
|
||||
}
|
||||
|
||||
// Model API
|
||||
export async function listModels(providerId?: string): Promise<Model[]> {
|
||||
const url = providerId ? `${API_BASE}/models?provider_id=${providerId}` : `${API_BASE}/models`;
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error('Failed to fetch models');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function createModel(model: Omit<Model, 'created_at'>): Promise<Model> {
|
||||
const response = await fetch(`${API_BASE}/models`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(model),
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to create model');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function updateModel(id: string, updates: Partial<Model>): Promise<Model> {
|
||||
const response = await fetch(`${API_BASE}/models/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(updates),
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to update model');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function deleteModel(id: string): Promise<void> {
|
||||
const response = await fetch(`${API_BASE}/models/${id}`, { method: 'DELETE' });
|
||||
if (!response.ok) throw new Error('Failed to delete model');
|
||||
}
|
||||
|
||||
// Stats API
|
||||
export async function getStats(params?: {
|
||||
provider_id?: string;
|
||||
model_name?: string;
|
||||
start_date?: string;
|
||||
end_date?: string;
|
||||
}): Promise<UsageStats[]> {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.provider_id) query.set('provider_id', params.provider_id);
|
||||
if (params?.model_name) query.set('model_name', params.model_name);
|
||||
if (params?.start_date) query.set('start_date', params.start_date);
|
||||
if (params?.end_date) query.set('end_date', params.end_date);
|
||||
|
||||
const response = await fetch(`${API_BASE}/stats?${query}`);
|
||||
if (!response.ok) throw new Error('Failed to fetch stats');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getAggregatedStats(params?: {
|
||||
provider_id?: string;
|
||||
model_name?: string;
|
||||
start_date?: string;
|
||||
end_date?: string;
|
||||
group_by?: 'provider' | 'model' | 'date';
|
||||
}): Promise<any[]> {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.provider_id) query.set('provider_id', params.provider_id);
|
||||
if (params?.model_name) query.set('model_name', params.model_name);
|
||||
if (params?.start_date) query.set('start_date', params.start_date);
|
||||
if (params?.end_date) query.set('end_date', params.end_date);
|
||||
if (params?.group_by) query.set('group_by', params.group_by);
|
||||
|
||||
const response = await fetch(`${API_BASE}/stats/aggregate?${query}`);
|
||||
if (!response.ok) throw new Error('Failed to fetch aggregated stats');
|
||||
return response.json();
|
||||
};
|
||||
|
||||
if (body !== undefined) {
|
||||
options.body = JSON.stringify(toApi(body));
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
let message = `请求失败 (${response.status})`;
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
if (typeof errorData === 'object' && errorData !== null && 'message' in errorData) {
|
||||
message = (errorData as { message: string }).message;
|
||||
}
|
||||
} catch {
|
||||
// ignore JSON parse error
|
||||
}
|
||||
throw new ApiError(response.status, message);
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return fromApi<T>(data);
|
||||
}
|
||||
|
||||
24
frontend/src/api/models.ts
Normal file
24
frontend/src/api/models.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import type { Model, CreateModelInput, UpdateModelInput } from '@/types';
|
||||
import { request } from './client';
|
||||
|
||||
export async function listModels(providerId?: string): Promise<Model[]> {
|
||||
const path = providerId
|
||||
? `/api/models?provider_id=${encodeURIComponent(providerId)}`
|
||||
: '/api/models';
|
||||
return request<Model[]>('GET', path);
|
||||
}
|
||||
|
||||
export async function createModel(input: CreateModelInput): Promise<Model> {
|
||||
return request<Model>('POST', '/api/models', input);
|
||||
}
|
||||
|
||||
export async function updateModel(
|
||||
id: string,
|
||||
input: UpdateModelInput,
|
||||
): Promise<Model> {
|
||||
return request<Model>('PUT', `/api/models/${id}`, input);
|
||||
}
|
||||
|
||||
export async function deleteModel(id: string): Promise<void> {
|
||||
return request<void>('DELETE', `/api/models/${id}`);
|
||||
}
|
||||
21
frontend/src/api/providers.ts
Normal file
21
frontend/src/api/providers.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { Provider, CreateProviderInput, UpdateProviderInput } from '@/types';
|
||||
import { request } from './client';
|
||||
|
||||
export async function listProviders(): Promise<Provider[]> {
|
||||
return request<Provider[]>('GET', '/api/providers');
|
||||
}
|
||||
|
||||
export async function createProvider(input: CreateProviderInput): Promise<Provider> {
|
||||
return request<Provider>('POST', '/api/providers', input);
|
||||
}
|
||||
|
||||
export async function updateProvider(
|
||||
id: string,
|
||||
input: UpdateProviderInput,
|
||||
): Promise<Provider> {
|
||||
return request<Provider>('PUT', `/api/providers/${id}`, input);
|
||||
}
|
||||
|
||||
export async function deleteProvider(id: string): Promise<void> {
|
||||
return request<void>('DELETE', `/api/providers/${id}`);
|
||||
}
|
||||
26
frontend/src/api/stats.ts
Normal file
26
frontend/src/api/stats.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { UsageStats, StatsQueryParams } from '@/types';
|
||||
import { request } from './client';
|
||||
|
||||
export async function getStats(params?: StatsQueryParams): Promise<UsageStats[]> {
|
||||
if (!params) {
|
||||
return request<UsageStats[]>('GET', '/api/stats');
|
||||
}
|
||||
|
||||
const query = new URLSearchParams();
|
||||
const snakeParams: Record<string, string | undefined> = {
|
||||
provider_id: params.providerId,
|
||||
model_name: params.modelName,
|
||||
start_date: params.startDate,
|
||||
end_date: params.endDate,
|
||||
};
|
||||
|
||||
for (const [key, value] of Object.entries(snakeParams)) {
|
||||
if (value) {
|
||||
query.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
const queryString = query.toString();
|
||||
const path = queryString ? `/api/stats?${queryString}` : '/api/stats';
|
||||
return request<UsageStats[]>('GET', path);
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 44 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 8.5 KiB |
30
frontend/src/components/AppLayout/AppLayout.module.scss
Normal file
30
frontend/src/components/AppLayout/AppLayout.module.scss
Normal file
@@ -0,0 +1,30 @@
|
||||
.layout {
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 2rem;
|
||||
}
|
||||
|
||||
.logo {
|
||||
color: #fff;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
margin-right: 2rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.menu {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: 2rem;
|
||||
max-width: 1400px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
36
frontend/src/components/AppLayout/index.tsx
Normal file
36
frontend/src/components/AppLayout/index.tsx
Normal file
@@ -0,0 +1,36 @@
|
||||
import { Layout, Menu } from 'antd';
|
||||
import {
|
||||
CloudServerOutlined,
|
||||
BarChartOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { Outlet, useLocation, useNavigate } from 'react-router';
|
||||
import styles from './AppLayout.module.scss';
|
||||
|
||||
const menuItems = [
|
||||
{ key: '/providers', label: '供应商管理', icon: <CloudServerOutlined /> },
|
||||
{ key: '/stats', label: '用量统计', icon: <BarChartOutlined /> },
|
||||
];
|
||||
|
||||
export function AppLayout() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<Layout className={styles.layout}>
|
||||
<Layout.Header className={styles.header}>
|
||||
<div className={styles.logo}>AI Gateway</div>
|
||||
<Menu
|
||||
theme="dark"
|
||||
mode="horizontal"
|
||||
selectedKeys={[location.pathname]}
|
||||
items={menuItems}
|
||||
onClick={({ key }) => navigate(key)}
|
||||
className={styles.menu}
|
||||
/>
|
||||
</Layout.Header>
|
||||
<Layout.Content className={styles.content}>
|
||||
<Outlet />
|
||||
</Layout.Content>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import * as api from '../api/client';
|
||||
|
||||
interface ModelFormProps {
|
||||
model?: api.Model;
|
||||
providers: api.Provider[];
|
||||
onSave: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function ModelForm({ model, providers, onSave, onCancel }: ModelFormProps) {
|
||||
const [id, setId] = useState(model?.id || '');
|
||||
const [providerId, setProviderId] = useState(model?.provider_id || (providers[0]?.id || ''));
|
||||
const [modelName, setModelName] = useState(model?.model_name || '');
|
||||
const [enabled, setEnabled] = useState(model?.enabled ?? true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isEdit = !!model;
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (isEdit) {
|
||||
const updates: any = {};
|
||||
if (providerId !== model.provider_id) updates.provider_id = providerId;
|
||||
if (modelName !== model.model_name) updates.model_name = modelName;
|
||||
if (enabled !== model.enabled) updates.enabled = enabled;
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await api.updateModel(model.id, updates);
|
||||
}
|
||||
} else {
|
||||
await api.createModel({
|
||||
id,
|
||||
provider_id: providerId,
|
||||
model_name: modelName,
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
onSave();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal">
|
||||
<div className="modal-content">
|
||||
<h2>{isEdit ? '编辑模型' : '添加模型'}</h2>
|
||||
|
||||
{error && <div className="error">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>ID</label>
|
||||
<input
|
||||
type="text"
|
||||
value={id}
|
||||
onChange={e => setId(e.target.value)}
|
||||
disabled={isEdit}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>供应商</label>
|
||||
<select
|
||||
value={providerId}
|
||||
onChange={e => setProviderId(e.target.value)}
|
||||
required
|
||||
>
|
||||
{providers.map(p => (
|
||||
<option key={p.id} value={p.id}>{p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>模型名称</label>
|
||||
<input
|
||||
type="text"
|
||||
value={modelName}
|
||||
onChange={e => setModelName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enabled}
|
||||
onChange={e => setEnabled(e.target.checked)}
|
||||
/>
|
||||
启用
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={loading}>
|
||||
{loading ? '保存中...' : '保存'}
|
||||
</button>
|
||||
<button type="button" onClick={onCancel} disabled={loading}>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import * as api from '../api/client';
|
||||
|
||||
interface ProviderFormProps {
|
||||
provider?: api.Provider;
|
||||
onSave: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function ProviderForm({ provider, onSave, onCancel }: ProviderFormProps) {
|
||||
const [id, setId] = useState(provider?.id || '');
|
||||
const [name, setName] = useState(provider?.name || '');
|
||||
const [apiKey, setApiKey] = useState('');
|
||||
const [baseUrl, setBaseUrl] = useState(provider?.base_url || '');
|
||||
const [enabled, setEnabled] = useState(provider?.enabled ?? true);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isEdit = !!provider;
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (isEdit) {
|
||||
const updates: any = {};
|
||||
if (name !== provider.name) updates.name = name;
|
||||
if (apiKey) updates.api_key = apiKey;
|
||||
if (baseUrl !== provider.base_url) updates.base_url = baseUrl;
|
||||
if (enabled !== provider.enabled) updates.enabled = enabled;
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await api.updateProvider(provider.id, updates);
|
||||
}
|
||||
} else {
|
||||
await api.createProvider({
|
||||
id,
|
||||
name,
|
||||
api_key: apiKey,
|
||||
base_url: baseUrl,
|
||||
enabled,
|
||||
});
|
||||
}
|
||||
onSave();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="modal">
|
||||
<div className="modal-content">
|
||||
<h2>{isEdit ? '编辑供应商' : '添加供应商'}</h2>
|
||||
|
||||
{error && <div className="error">{error}</div>}
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>ID</label>
|
||||
<input
|
||||
type="text"
|
||||
value={id}
|
||||
onChange={e => setId(e.target.value)}
|
||||
disabled={isEdit}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>名称</label>
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>API Key {isEdit && '(留空则不修改)'}</label>
|
||||
<input
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={e => setApiKey(e.target.value)}
|
||||
required={!isEdit}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Base URL</label>
|
||||
<input
|
||||
type="url"
|
||||
value={baseUrl}
|
||||
onChange={e => setBaseUrl(e.target.value)}
|
||||
placeholder="例如: https://api.openai.com/v1 或 https://open.bigmodel.cn/api/paas/v4"
|
||||
required
|
||||
/>
|
||||
<small style={{color: '#666', fontSize: '0.85rem'}}>
|
||||
配置到 API 版本路径,不包含 /chat/completions
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enabled}
|
||||
onChange={e => setEnabled(e.target.checked)}
|
||||
/>
|
||||
启用
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={loading}>
|
||||
{loading ? '保存中...' : '保存'}
|
||||
</button>
|
||||
<button type="button" onClick={onCancel} disabled={loading}>
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
62
frontend/src/hooks/useModels.ts
Normal file
62
frontend/src/hooks/useModels.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { message } from 'antd';
|
||||
import type { CreateModelInput, UpdateModelInput } from '@/types';
|
||||
import * as api from '@/api/models';
|
||||
|
||||
export const modelKeys = {
|
||||
all: ['models'] as const,
|
||||
filtered: (providerId?: string) => ['models', providerId] as const,
|
||||
};
|
||||
|
||||
export function useModels(providerId?: string) {
|
||||
return useQuery({
|
||||
queryKey: modelKeys.filtered(providerId),
|
||||
queryFn: () => api.listModels(providerId),
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateModel() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (input: CreateModelInput) => api.createModel(input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: modelKeys.all });
|
||||
message.success('模型创建成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
message.error(error.message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateModel() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, input }: { id: string; input: UpdateModelInput }) =>
|
||||
api.updateModel(id, input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: modelKeys.all });
|
||||
message.success('模型更新成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
message.error(error.message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteModel() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.deleteModel(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: modelKeys.all });
|
||||
message.success('模型删除成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
message.error(error.message);
|
||||
},
|
||||
});
|
||||
}
|
||||
61
frontend/src/hooks/useProviders.ts
Normal file
61
frontend/src/hooks/useProviders.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { message } from 'antd';
|
||||
import type { CreateProviderInput, UpdateProviderInput } from '@/types';
|
||||
import * as api from '@/api/providers';
|
||||
|
||||
export const providerKeys = {
|
||||
all: ['providers'] as const,
|
||||
};
|
||||
|
||||
export function useProviders() {
|
||||
return useQuery({
|
||||
queryKey: providerKeys.all,
|
||||
queryFn: api.listProviders,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCreateProvider() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (input: CreateProviderInput) => api.createProvider(input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: providerKeys.all });
|
||||
message.success('供应商创建成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
message.error(error.message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateProvider() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({ id, input }: { id: string; input: UpdateProviderInput }) =>
|
||||
api.updateProvider(id, input),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: providerKeys.all });
|
||||
message.success('供应商更新成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
message.error(error.message);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteProvider() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: string) => api.deleteProvider(id),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: providerKeys.all });
|
||||
message.success('供应商删除成功');
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
message.error(error.message);
|
||||
},
|
||||
});
|
||||
}
|
||||
14
frontend/src/hooks/useStats.ts
Normal file
14
frontend/src/hooks/useStats.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { StatsQueryParams } from '@/types';
|
||||
import * as api from '@/api/stats';
|
||||
|
||||
export const statsKeys = {
|
||||
filtered: (params?: StatsQueryParams) => ['stats', params] as const,
|
||||
};
|
||||
|
||||
export function useStats(params?: StatsQueryParams) {
|
||||
return useQuery({
|
||||
queryKey: statsKeys.filtered(params),
|
||||
queryFn: () => api.getStats(params),
|
||||
});
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
|
||||
background: #f5f5f5;
|
||||
color: #333;
|
||||
line-height: 1.6;
|
||||
}
|
||||
20
frontend/src/index.scss
Normal file
20
frontend/src/index.scss
Normal file
@@ -0,0 +1,20 @@
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family:
|
||||
-apple-system,
|
||||
BlinkMacSystemFont,
|
||||
'Segoe UI',
|
||||
Roboto,
|
||||
'Helvetica Neue',
|
||||
Arial,
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import './index.scss'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
|
||||
19
frontend/src/pages/NotFound.tsx
Normal file
19
frontend/src/pages/NotFound.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import { Button, Result } from 'antd';
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
export function NotFound() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
return (
|
||||
<Result
|
||||
status="404"
|
||||
title="404"
|
||||
subTitle="抱歉,您访问的页面不存在。"
|
||||
extra={
|
||||
<Button type="primary" onClick={() => navigate('/providers')}>
|
||||
返回首页
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
94
frontend/src/pages/Providers/ModelForm.tsx
Normal file
94
frontend/src/pages/Providers/ModelForm.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Modal, Form, Input, Select, Switch } from 'antd';
|
||||
import type { Provider, Model } from '@/types';
|
||||
|
||||
interface ModelFormValues {
|
||||
id: string;
|
||||
providerId: string;
|
||||
modelName: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
interface ModelFormProps {
|
||||
open: boolean;
|
||||
model?: Model;
|
||||
providerId: string;
|
||||
providers: Provider[];
|
||||
onSave: (values: ModelFormValues) => void;
|
||||
onCancel: () => void;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export function ModelForm({
|
||||
open,
|
||||
model,
|
||||
providerId,
|
||||
providers,
|
||||
onSave,
|
||||
onCancel,
|
||||
loading,
|
||||
}: ModelFormProps) {
|
||||
const [form] = Form.useForm<ModelFormValues>();
|
||||
const isEdit = !!model;
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (model) {
|
||||
form.setFieldsValue({
|
||||
id: model.id,
|
||||
providerId: model.providerId,
|
||||
modelName: model.modelName,
|
||||
enabled: model.enabled,
|
||||
});
|
||||
} else {
|
||||
form.resetFields();
|
||||
form.setFieldsValue({ providerId });
|
||||
}
|
||||
}
|
||||
}, [open, model, providerId, form]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={isEdit ? '编辑模型' : '添加模型'}
|
||||
open={open}
|
||||
onOk={() => form.submit()}
|
||||
onCancel={onCancel}
|
||||
confirmLoading={loading}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={form} layout="vertical" onFinish={onSave} initialValues={{ enabled: true }}>
|
||||
<Form.Item label="ID" name="id" rules={[{ required: true, message: '请输入模型 ID' }]}>
|
||||
<Input disabled={isEdit} placeholder="例如: gpt-4o" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="供应商"
|
||||
name="providerId"
|
||||
rules={[{ required: true, message: '请选择供应商' }]}
|
||||
>
|
||||
<Select>
|
||||
{providers.map((p) => (
|
||||
<Select.Option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="模型名称"
|
||||
name="modelName"
|
||||
rules={[{ required: true, message: '请输入模型名称' }]}
|
||||
>
|
||||
<Input placeholder="例如: gpt-4o" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="启用" name="enabled" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
76
frontend/src/pages/Providers/ModelTable.tsx
Normal file
76
frontend/src/pages/Providers/ModelTable.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { Button, Table, Tag, Popconfirm, Space } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { Model } from '@/types';
|
||||
import { useModels, useDeleteModel } from '@/hooks/useModels';
|
||||
|
||||
interface ModelTableProps {
|
||||
providerId: string;
|
||||
onAdd?: () => void;
|
||||
onEdit?: (model: Model) => void;
|
||||
}
|
||||
|
||||
export function ModelTable({ providerId, onAdd, onEdit }: ModelTableProps) {
|
||||
const { data: models = [], isLoading } = useModels(providerId);
|
||||
const deleteModel = useDeleteModel();
|
||||
|
||||
const columns: ColumnsType<Model> = [
|
||||
{
|
||||
title: '模型名称',
|
||||
dataIndex: 'modelName',
|
||||
key: 'modelName',
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'enabled',
|
||||
key: 'enabled',
|
||||
render: (enabled: boolean) =>
|
||||
enabled ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>,
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 120,
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
{onEdit && (
|
||||
<Button type="link" size="small" onClick={() => onEdit(record)}>
|
||||
编辑
|
||||
</Button>
|
||||
)}
|
||||
<Popconfirm
|
||||
title="确定要删除这个模型吗?"
|
||||
onConfirm={() => deleteModel.mutate(record.id)}
|
||||
okText="确定"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button type="link" danger size="small">
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div style={{ padding: '8px 16px' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
|
||||
<span style={{ fontWeight: 500 }}>关联模型 ({models.length})</span>
|
||||
{onAdd && (
|
||||
<Button type="link" size="small" onClick={onAdd}>
|
||||
添加模型
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Table<Model>
|
||||
columns={columns}
|
||||
dataSource={models}
|
||||
rowKey="id"
|
||||
loading={isLoading}
|
||||
pagination={false}
|
||||
size="small"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
92
frontend/src/pages/Providers/ProviderForm.tsx
Normal file
92
frontend/src/pages/Providers/ProviderForm.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Modal, Form, Input, Switch } from 'antd';
|
||||
import type { Provider } from '@/types';
|
||||
|
||||
interface ProviderFormValues {
|
||||
id: string;
|
||||
name: string;
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
interface ProviderFormProps {
|
||||
open: boolean;
|
||||
provider?: Provider;
|
||||
onSave: (values: ProviderFormValues) => void;
|
||||
onCancel: () => void;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
export function ProviderForm({
|
||||
open,
|
||||
provider,
|
||||
onSave,
|
||||
onCancel,
|
||||
loading,
|
||||
}: ProviderFormProps) {
|
||||
const [form] = Form.useForm<ProviderFormValues>();
|
||||
const isEdit = !!provider;
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
if (provider) {
|
||||
form.setFieldsValue({
|
||||
id: provider.id,
|
||||
name: provider.name,
|
||||
apiKey: '',
|
||||
baseUrl: provider.baseUrl,
|
||||
enabled: provider.enabled,
|
||||
});
|
||||
} else {
|
||||
form.resetFields();
|
||||
}
|
||||
}
|
||||
}, [open, provider, form]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={isEdit ? '编辑供应商' : '添加供应商'}
|
||||
open={open}
|
||||
onOk={() => form.submit()}
|
||||
onCancel={onCancel}
|
||||
confirmLoading={loading}
|
||||
okText="保存"
|
||||
cancelText="取消"
|
||||
destroyOnClose
|
||||
>
|
||||
<Form form={form} layout="vertical" onFinish={onSave} initialValues={{ enabled: true }}>
|
||||
<Form.Item label="ID" name="id" rules={[{ required: true, message: '请输入供应商 ID' }]}>
|
||||
<Input disabled={isEdit} placeholder="例如: openai" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
|
||||
<Input placeholder="例如: OpenAI" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label={isEdit ? 'API Key(留空则不修改)' : 'API Key'}
|
||||
name="apiKey"
|
||||
rules={isEdit ? [] : [{ required: true, message: '请输入 API Key' }]}
|
||||
>
|
||||
<Input.Password placeholder="sk-..." />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item
|
||||
label="Base URL"
|
||||
name="baseUrl"
|
||||
rules={[
|
||||
{ required: true, message: '请输入 Base URL' },
|
||||
{ type: 'url', message: '请输入有效的 URL' },
|
||||
]}
|
||||
>
|
||||
<Input placeholder="例如: https://api.openai.com/v1" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="启用" name="enabled" valuePropName="checked">
|
||||
<Switch />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
106
frontend/src/pages/Providers/ProviderTable.tsx
Normal file
106
frontend/src/pages/Providers/ProviderTable.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { Button, Table, Tag, Popconfirm, Space } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { Provider, Model } from '@/types';
|
||||
import { ModelTable } from './ModelTable';
|
||||
|
||||
interface ProviderTableProps {
|
||||
providers: Provider[];
|
||||
loading: boolean;
|
||||
onAdd: () => void;
|
||||
onEdit: (provider: Provider) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onAddModel: (providerId: string) => void;
|
||||
onEditModel: (model: Model) => void;
|
||||
}
|
||||
|
||||
function maskApiKey(key: string | null | undefined): string {
|
||||
if (!key) return '****';
|
||||
if (key.length <= 4) return '****';
|
||||
return `****${key.slice(-4)}`;
|
||||
}
|
||||
|
||||
export function ProviderTable({
|
||||
providers,
|
||||
loading,
|
||||
onAdd,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAddModel,
|
||||
onEditModel,
|
||||
}: ProviderTableProps) {
|
||||
const columns: ColumnsType<Provider> = [
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
},
|
||||
{
|
||||
title: 'Base URL',
|
||||
dataIndex: 'baseUrl',
|
||||
key: 'baseUrl',
|
||||
},
|
||||
{
|
||||
title: 'API Key',
|
||||
dataIndex: 'apiKey',
|
||||
key: 'apiKey',
|
||||
render: (key: string | null | undefined) => maskApiKey(key),
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'enabled',
|
||||
key: 'enabled',
|
||||
render: (enabled: boolean) =>
|
||||
enabled ? <Tag color="green">启用</Tag> : <Tag color="red">禁用</Tag>,
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 160,
|
||||
render: (_, record) => (
|
||||
<Space>
|
||||
<Button type="link" size="small" onClick={() => onEdit(record)}>
|
||||
编辑
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title="确定要删除这个供应商吗?关联的模型也会被删除。"
|
||||
onConfirm={() => onDelete(record.id)}
|
||||
okText="确定"
|
||||
cancelText="取消"
|
||||
>
|
||||
<Button type="link" danger size="small">
|
||||
删除
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</Space>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
|
||||
<h2 style={{ margin: 0 }}>供应商列表</h2>
|
||||
<Button type="primary" onClick={onAdd}>
|
||||
添加供应商
|
||||
</Button>
|
||||
</div>
|
||||
<Table<Provider>
|
||||
columns={columns}
|
||||
dataSource={providers}
|
||||
rowKey="id"
|
||||
loading={loading}
|
||||
expandable={{
|
||||
expandedRowRender: (record) => (
|
||||
<ModelTable
|
||||
providerId={record.id}
|
||||
onAdd={() => onAddModel(record.id)}
|
||||
onEdit={onEditModel}
|
||||
/>
|
||||
),
|
||||
}}
|
||||
pagination={false}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
101
frontend/src/pages/Providers/index.tsx
Normal file
101
frontend/src/pages/Providers/index.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
import { useState } from 'react';
|
||||
import type { Provider, Model, UpdateProviderInput, UpdateModelInput } from '@/types';
|
||||
import { useProviders, useCreateProvider, useUpdateProvider, useDeleteProvider } from '@/hooks/useProviders';
|
||||
import { useCreateModel, useUpdateModel } from '@/hooks/useModels';
|
||||
import { ProviderTable } from './ProviderTable';
|
||||
import { ProviderForm } from './ProviderForm';
|
||||
import { ModelForm } from './ModelForm';
|
||||
|
||||
export function ProvidersPage() {
|
||||
const { data: providers = [], isLoading } = useProviders();
|
||||
const createProvider = useCreateProvider();
|
||||
const updateProvider = useUpdateProvider();
|
||||
const deleteProvider = useDeleteProvider();
|
||||
const createModel = useCreateModel();
|
||||
const updateModel = useUpdateModel();
|
||||
|
||||
const [providerFormOpen, setProviderFormOpen] = useState(false);
|
||||
const [editingProvider, setEditingProvider] = useState<Provider | undefined>();
|
||||
const [modelFormOpen, setModelFormOpen] = useState(false);
|
||||
const [editingModel, setEditingModel] = useState<Model | undefined>();
|
||||
const [modelFormProviderId, setModelFormProviderId] = useState('');
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>供应商管理</h1>
|
||||
|
||||
<ProviderTable
|
||||
providers={providers}
|
||||
loading={isLoading}
|
||||
onAdd={() => {
|
||||
setEditingProvider(undefined);
|
||||
setProviderFormOpen(true);
|
||||
}}
|
||||
onEdit={(provider) => {
|
||||
setEditingProvider(provider);
|
||||
setProviderFormOpen(true);
|
||||
}}
|
||||
onDelete={(id) => deleteProvider.mutate(id)}
|
||||
onAddModel={(providerId) => {
|
||||
setEditingModel(undefined);
|
||||
setModelFormProviderId(providerId);
|
||||
setModelFormOpen(true);
|
||||
}}
|
||||
onEditModel={(model) => {
|
||||
setEditingModel(model);
|
||||
setModelFormProviderId(model.providerId);
|
||||
setModelFormOpen(true);
|
||||
}}
|
||||
/>
|
||||
|
||||
<ProviderForm
|
||||
open={providerFormOpen}
|
||||
provider={editingProvider}
|
||||
loading={createProvider.isPending || updateProvider.isPending}
|
||||
onSave={(values) => {
|
||||
if (editingProvider) {
|
||||
const input: Partial<UpdateProviderInput> = {};
|
||||
if (values.name !== editingProvider.name) input.name = values.name;
|
||||
if (values.apiKey) input.apiKey = values.apiKey;
|
||||
if (values.baseUrl !== editingProvider.baseUrl) input.baseUrl = values.baseUrl;
|
||||
if (values.enabled !== editingProvider.enabled) input.enabled = values.enabled;
|
||||
updateProvider.mutate(
|
||||
{ id: editingProvider.id, input },
|
||||
{ onSuccess: () => setProviderFormOpen(false) },
|
||||
);
|
||||
} else {
|
||||
createProvider.mutate(values, {
|
||||
onSuccess: () => setProviderFormOpen(false),
|
||||
});
|
||||
}
|
||||
}}
|
||||
onCancel={() => setProviderFormOpen(false)}
|
||||
/>
|
||||
|
||||
<ModelForm
|
||||
open={modelFormOpen}
|
||||
model={editingModel}
|
||||
providerId={modelFormProviderId}
|
||||
providers={providers}
|
||||
loading={createModel.isPending || updateModel.isPending}
|
||||
onSave={(values) => {
|
||||
if (editingModel) {
|
||||
const input: Partial<UpdateModelInput> = {};
|
||||
if (values.providerId !== editingModel.providerId) input.providerId = values.providerId;
|
||||
if (values.modelName !== editingModel.modelName) input.modelName = values.modelName;
|
||||
if (values.enabled !== editingModel.enabled) input.enabled = values.enabled;
|
||||
updateModel.mutate(
|
||||
{ id: editingModel.id, input },
|
||||
{ onSuccess: () => setModelFormOpen(false) },
|
||||
);
|
||||
} else {
|
||||
createModel.mutate(values, {
|
||||
onSuccess: () => setModelFormOpen(false),
|
||||
});
|
||||
}
|
||||
}}
|
||||
onCancel={() => setModelFormOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import * as api from '../api/client';
|
||||
import { ProviderForm } from '../components/ProviderForm';
|
||||
import { ModelForm } from '../components/ModelForm';
|
||||
|
||||
export function ProvidersPage() {
|
||||
const [providers, setProviders] = useState<api.Provider[]>([]);
|
||||
const [models, setModels] = useState<api.Model[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 表单状态
|
||||
const [showProviderForm, setShowProviderForm] = useState(false);
|
||||
const [editingProvider, setEditingProvider] = useState<api.Provider | null>(null);
|
||||
const [showModelForm, setShowModelForm] = useState(false);
|
||||
const [editingModel, setEditingModel] = useState<api.Model | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [providersData, modelsData] = await Promise.all([
|
||||
api.listProviders(),
|
||||
api.listModels(),
|
||||
]);
|
||||
setProviders(providersData);
|
||||
setModels(modelsData);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteProvider(id: string) {
|
||||
if (!confirm('确定要删除这个供应商吗?关联的模型也会被删除。')) return;
|
||||
try {
|
||||
await api.deleteProvider(id);
|
||||
loadData();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDeleteModel(id: string) {
|
||||
if (!confirm('确定要删除这个模型吗?')) return;
|
||||
try {
|
||||
await api.deleteModel(id);
|
||||
loadData();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="loading">加载中...</div>;
|
||||
if (error) return <div className="error">{error}</div>;
|
||||
|
||||
return (
|
||||
<div className="providers-page">
|
||||
<h1>供应商管理</h1>
|
||||
|
||||
<div className="section">
|
||||
<h2>供应商列表</h2>
|
||||
<button onClick={() => {
|
||||
setEditingProvider(null);
|
||||
setShowProviderForm(true);
|
||||
}}>
|
||||
添加供应商
|
||||
</button>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>名称</th>
|
||||
<th>API Key</th>
|
||||
<th>Base URL</th>
|
||||
<th>状态</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{providers.map(p => (
|
||||
<tr key={p.id}>
|
||||
<td>{p.id}</td>
|
||||
<td>{p.name}</td>
|
||||
<td>{p.api_key}</td>
|
||||
<td>{p.base_url}</td>
|
||||
<td>{p.enabled ? '启用' : '禁用'}</td>
|
||||
<td>
|
||||
<button onClick={() => {
|
||||
setEditingProvider(p);
|
||||
setShowProviderForm(true);
|
||||
}}>编辑</button>
|
||||
<button onClick={() => handleDeleteProvider(p.id)}>删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div className="section">
|
||||
<h2>模型列表</h2>
|
||||
<button onClick={() => {
|
||||
setEditingModel(null);
|
||||
setShowModelForm(true);
|
||||
}}>
|
||||
添加模型
|
||||
</button>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>供应商</th>
|
||||
<th>模型名称</th>
|
||||
<th>状态</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{models.map(m => {
|
||||
const provider = providers.find(p => p.id === m.provider_id);
|
||||
return (
|
||||
<tr key={m.id}>
|
||||
<td>{m.id}</td>
|
||||
<td>{provider?.name || m.provider_id}</td>
|
||||
<td>{m.model_name}</td>
|
||||
<td>{m.enabled ? '启用' : '禁用'}</td>
|
||||
<td>
|
||||
<button onClick={() => {
|
||||
setEditingModel(m);
|
||||
setShowModelForm(true);
|
||||
}}>编辑</button>
|
||||
<button onClick={() => handleDeleteModel(m.id)}>删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* 供应商表单 */}
|
||||
{showProviderForm && (
|
||||
<ProviderForm
|
||||
provider={editingProvider || undefined}
|
||||
onSave={() => {
|
||||
setShowProviderForm(false);
|
||||
setEditingProvider(null);
|
||||
loadData();
|
||||
}}
|
||||
onCancel={() => {
|
||||
setShowProviderForm(false);
|
||||
setEditingProvider(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 模型表单 */}
|
||||
{showModelForm && (
|
||||
<ModelForm
|
||||
model={editingModel || undefined}
|
||||
providers={providers}
|
||||
onSave={() => {
|
||||
setShowModelForm(false);
|
||||
setEditingModel(null);
|
||||
loadData();
|
||||
}}
|
||||
onCancel={() => {
|
||||
setShowModelForm(false);
|
||||
setEditingModel(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
96
frontend/src/pages/Stats/StatsTable.tsx
Normal file
96
frontend/src/pages/Stats/StatsTable.tsx
Normal file
@@ -0,0 +1,96 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { Table, Select, Input, DatePicker, Space, Card } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import type { Dayjs } from 'dayjs';
|
||||
import type { UsageStats, Provider } from '@/types';
|
||||
import { useStats } from '@/hooks/useStats';
|
||||
|
||||
interface StatsTableProps {
|
||||
providers: Provider[];
|
||||
}
|
||||
|
||||
export function StatsTable({ providers }: StatsTableProps) {
|
||||
const [providerId, setProviderId] = useState<string | undefined>();
|
||||
const [modelName, setModelName] = useState<string | undefined>();
|
||||
const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);
|
||||
|
||||
const params = useMemo(
|
||||
() => ({
|
||||
providerId,
|
||||
modelName,
|
||||
startDate: dateRange?.[0]?.format('YYYY-MM-DD'),
|
||||
endDate: dateRange?.[1]?.format('YYYY-MM-DD'),
|
||||
}),
|
||||
[providerId, modelName, dateRange],
|
||||
);
|
||||
|
||||
const { data: stats = [], isLoading } = useStats(params);
|
||||
|
||||
const providerMap = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
for (const p of providers) {
|
||||
map.set(p.id, p.name);
|
||||
}
|
||||
return map;
|
||||
}, [providers]);
|
||||
|
||||
const columns: ColumnsType<UsageStats> = [
|
||||
{
|
||||
title: '供应商',
|
||||
dataIndex: 'providerId',
|
||||
key: 'providerId',
|
||||
render: (id: string) => providerMap.get(id) ?? id,
|
||||
},
|
||||
{
|
||||
title: '模型',
|
||||
dataIndex: 'modelName',
|
||||
key: 'modelName',
|
||||
},
|
||||
{
|
||||
title: '日期',
|
||||
dataIndex: 'date',
|
||||
key: 'date',
|
||||
},
|
||||
{
|
||||
title: '请求数',
|
||||
dataIndex: 'requestCount',
|
||||
key: 'requestCount',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card style={{ marginBottom: 16 }}>
|
||||
<Space wrap>
|
||||
<Select
|
||||
allowClear
|
||||
placeholder="所有供应商"
|
||||
style={{ width: 200 }}
|
||||
value={providerId}
|
||||
onChange={(value) => setProviderId(value)}
|
||||
options={providers.map((p) => ({ label: p.name, value: p.id }))}
|
||||
/>
|
||||
<Input
|
||||
allowClear
|
||||
placeholder="模型名称"
|
||||
style={{ width: 200 }}
|
||||
value={modelName ?? ''}
|
||||
onChange={(e) => setModelName(e.target.value || undefined)}
|
||||
/>
|
||||
<DatePicker.RangePicker
|
||||
value={dateRange}
|
||||
onChange={(dates) => setDateRange(dates)}
|
||||
/>
|
||||
</Space>
|
||||
</Card>
|
||||
|
||||
<Table<UsageStats>
|
||||
columns={columns}
|
||||
dataSource={stats}
|
||||
rowKey="id"
|
||||
loading={isLoading}
|
||||
pagination={{ pageSize: 20 }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
13
frontend/src/pages/Stats/index.tsx
Normal file
13
frontend/src/pages/Stats/index.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { useProviders } from '@/hooks/useProviders';
|
||||
import { StatsTable } from './StatsTable';
|
||||
|
||||
export function StatsPage() {
|
||||
const { data: providers = [] } = useProviders();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>用量统计</h1>
|
||||
<StatsTable providers={providers} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import * as api from '../api/client';
|
||||
|
||||
export function StatsPage() {
|
||||
const [stats, setStats] = useState<api.UsageStats[]>([]);
|
||||
const [providers, setProviders] = useState<api.Provider[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 过滤条件
|
||||
const [providerId, setProviderId] = useState('');
|
||||
const [modelName, setModelName] = useState('');
|
||||
const [startDate, setStartDate] = useState('');
|
||||
const [endDate, setEndDate] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
setLoading(true);
|
||||
const [statsData, providersData] = await Promise.all([
|
||||
api.getStats({
|
||||
provider_id: providerId || undefined,
|
||||
model_name: modelName || undefined,
|
||||
start_date: startDate || undefined,
|
||||
end_date: endDate || undefined,
|
||||
}),
|
||||
api.listProviders(),
|
||||
]);
|
||||
setStats(statsData);
|
||||
setProviders(providersData);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function handleFilter(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
loadData();
|
||||
}
|
||||
|
||||
if (loading) return <div className="loading">加载中...</div>;
|
||||
if (error) return <div className="error">{error}</div>;
|
||||
|
||||
return (
|
||||
<div className="stats-page">
|
||||
<h1>用量统计</h1>
|
||||
|
||||
<form onSubmit={handleFilter} className="filter-form">
|
||||
<select value={providerId} onChange={e => setProviderId(e.target.value)}>
|
||||
<option value="">所有供应商</option>
|
||||
{providers.map(p => (
|
||||
<option key={p.id} value={p.id}>{p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
placeholder="模型名称"
|
||||
value={modelName}
|
||||
onChange={e => setModelName(e.target.value)}
|
||||
/>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
placeholder="开始日期"
|
||||
value={startDate}
|
||||
onChange={e => setStartDate(e.target.value)}
|
||||
/>
|
||||
|
||||
<input
|
||||
type="date"
|
||||
placeholder="结束日期"
|
||||
value={endDate}
|
||||
onChange={e => setEndDate(e.target.value)}
|
||||
/>
|
||||
|
||||
<button type="submit">查询</button>
|
||||
</form>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>供应商</th>
|
||||
<th>模型</th>
|
||||
<th>日期</th>
|
||||
<th>请求数</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{stats.map(s => {
|
||||
const provider = providers.find(p => p.id === s.provider_id);
|
||||
return (
|
||||
<tr key={s.id}>
|
||||
<td>{provider?.name || s.provider_id}</td>
|
||||
<td>{s.model_name}</td>
|
||||
<td>{s.date}</td>
|
||||
<td>{s.request_count}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
frontend/src/routes/index.tsx
Normal file
18
frontend/src/routes/index.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import { Routes, Route, Navigate } from 'react-router';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { ProvidersPage } from '@/pages/Providers';
|
||||
import { StatsPage } from '@/pages/Stats';
|
||||
import { NotFound } from '@/pages/NotFound';
|
||||
|
||||
export function AppRoutes() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route element={<AppLayout />}>
|
||||
<Route index element={<Navigate to="/providers" replace />} />
|
||||
<Route path="providers" element={<ProvidersPage />} />
|
||||
<Route path="stats" element={<StatsPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
73
frontend/src/types/index.ts
Normal file
73
frontend/src/types/index.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
export interface Provider {
|
||||
id: string;
|
||||
name: string;
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface Model {
|
||||
id: string;
|
||||
providerId: string;
|
||||
modelName: string;
|
||||
enabled: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface UsageStats {
|
||||
id: number;
|
||||
providerId: string;
|
||||
modelName: string;
|
||||
requestCount: number;
|
||||
date: string;
|
||||
}
|
||||
|
||||
export interface CreateProviderInput {
|
||||
id: string;
|
||||
name: string;
|
||||
apiKey: string;
|
||||
baseUrl: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateProviderInput {
|
||||
name?: string;
|
||||
apiKey?: string;
|
||||
baseUrl?: string;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface CreateModelInput {
|
||||
id: string;
|
||||
providerId: string;
|
||||
modelName: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateModelInput {
|
||||
providerId?: string;
|
||||
modelName?: string;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export interface StatsQueryParams {
|
||||
providerId?: string;
|
||||
modelName?: string;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(
|
||||
status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -1,7 +1,26 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"moduleDetection": "force",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"paths": { "@/*": ["./src/*"] },
|
||||
"types": ["vite/client"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts"],
|
||||
"exclude": ["src/__tests__", "e2e"]
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "esnext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -1,7 +1,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import path from 'node:path'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:9826',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
28
frontend/vitest.config.ts
Normal file
28
frontend/vitest.config.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import path from 'node:path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
setupFiles: ['./src/__tests__/setup.ts'],
|
||||
include: ['src/**/*.{test,spec}.{ts,tsx}'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
include: ['src/**/*.{ts,tsx}'],
|
||||
exclude: [
|
||||
'src/__tests__/**',
|
||||
'src/main.tsx',
|
||||
'src/**/*.module.scss',
|
||||
'src/types/**',
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -8,98 +8,96 @@ TBD - 提供供应商、模型配置和用量统计的前端管理界面
|
||||
|
||||
### Requirement: 提供供应商管理页面
|
||||
|
||||
前端 SHALL 提供用于管理供应商配置的网页。
|
||||
前端 SHALL 使用 Ant Design 组件提供供应商管理页面。
|
||||
|
||||
#### Scenario: 显示供应商列表
|
||||
|
||||
- **WHEN** 加载供应商管理页面
|
||||
- **THEN** 前端 SHALL 显示所有已配置供应商的列表
|
||||
- **THEN** 每个供应商 SHALL 显示 id, name, base_url 和 enabled 状态
|
||||
- **THEN** API Key SHALL 被掩码
|
||||
- **THEN** 前端 SHALL 使用 Ant Design Table 显示所有已配置供应商
|
||||
- **THEN** 每个供应商 SHALL 显示 name、base_url 和 enabled 状态(使用 Tag 组件)
|
||||
- **THEN** API Key SHALL 被脱敏显示(掩码处理)
|
||||
- **THEN** 表格 SHALL 支持展开行以显示关联模型
|
||||
|
||||
#### Scenario: 添加新供应商
|
||||
|
||||
- **WHEN** 用户点击"添加供应商"按钮
|
||||
- **THEN** 前端 SHALL 显示输入供应商详情的表单
|
||||
- **THEN** 表单 SHALL 包含 id, name, api_key, base_url 字段
|
||||
- **THEN** 前端 SHALL 使用 Ant Design Modal + Form 显示输入表单
|
||||
- **THEN** 表单 SHALL 包含 id、name、api_key、base_url 字段,带校验规则
|
||||
- **WHEN** 用户提交包含有效数据的表单
|
||||
- **THEN** 前端 SHALL 向 `/api/providers` 发送 POST 请求
|
||||
- **THEN** 前端 SHALL 刷新供应商列表
|
||||
- **THEN** 前端 SHALL 通过 useMutation 调用创建 API
|
||||
- **THEN** 成功后 SHALL 关闭 Modal 并刷新供应商列表
|
||||
- **THEN** 失败 SHALL 使用 message.error() 提示
|
||||
|
||||
#### Scenario: 编辑现有供应商
|
||||
|
||||
- **WHEN** 用户点击供应商的"编辑"按钮
|
||||
- **THEN** 前端 SHALL 显示预填充供应商当前数据的表单
|
||||
- **THEN** 前端 SHALL 使用 Ant Design Modal + Form 显示预填充数据的表单
|
||||
- **WHEN** 用户提交包含更新数据的表单
|
||||
- **THEN** 前端 SHALL 向 `/api/providers/:id` 发送 PUT 请求
|
||||
- **THEN** 前端 SHALL 刷新供应商列表
|
||||
- **THEN** 前端 SHALL 通过 useMutation 调用更新 API
|
||||
- **THEN** 成功后 SHALL 关闭 Modal 并刷新供应商列表
|
||||
|
||||
#### Scenario: 删除供应商
|
||||
|
||||
- **WHEN** 用户点击供应商的"删除"按钮
|
||||
- **THEN** 前端 SHALL 提示确认
|
||||
- **THEN** 前端 SHALL 使用 Ant Design Popconfirm 弹出确认
|
||||
- **WHEN** 用户确认删除
|
||||
- **THEN** 前端 SHALL 向 `/api/providers/:id` 发送 DELETE 请求
|
||||
- **THEN** 前端 SHALL 刷新供应商列表
|
||||
- **THEN** 前端 SHALL 通过 useMutation 调用删除 API
|
||||
- **THEN** 成功后 SHALL 刷新供应商列表
|
||||
|
||||
### Requirement: 提供模型管理界面
|
||||
|
||||
前端 SHALL 在供应商页面中提供管理模型配置的界面。
|
||||
前端 SHALL 在供应商页面展开行中提供模型管理。
|
||||
|
||||
#### Scenario: 显示供应商的模型
|
||||
|
||||
- **WHEN** 选择或展开供应商
|
||||
- **WHEN** 展开供应商行
|
||||
- **THEN** 前端 SHALL 显示该供应商的模型列表
|
||||
- **THEN** 每个模型 SHALL 显示 model_name 和 enabled 状态
|
||||
|
||||
#### Scenario: 为供应商添加模型
|
||||
|
||||
- **WHEN** 用户点击供应商的"添加模型"
|
||||
- **THEN** 前端 SHALL 显示输入 model_name 的表单
|
||||
- **WHEN** 用户在展开行中点击"添加模型"
|
||||
- **THEN** 前端 SHALL 显示 Ant Design Modal + Form
|
||||
- **THEN** provider_id SHALL 自动关联当前供应商
|
||||
- **WHEN** 用户提交表单
|
||||
- **THEN** 前端 SHALL 向 `/api/models` 发送 POST 请求,携带 provider_id
|
||||
- **THEN** 前端 SHALL 刷新模型列表
|
||||
- **THEN** 前端 SHALL 通过 useMutation 调用创建 API
|
||||
- **THEN** 成功后 SHALL 刷新模型列表
|
||||
|
||||
#### Scenario: 编辑模型
|
||||
|
||||
- **WHEN** 用户点击模型的"编辑"
|
||||
- **THEN** 前端 SHALL 显示编辑 model_name 的表单
|
||||
- **THEN** 前端 SHALL 显示编辑表单
|
||||
- **WHEN** 用户提交表单
|
||||
- **THEN** 前端 SHALL 向 `/api/models/:id` 发送 PUT 请求
|
||||
- **THEN** 前端 SHALL 刷新模型列表
|
||||
- **THEN** 前端 SHALL 通过 useMutation 调用更新 API
|
||||
- **THEN** 成功后 SHALL 刷新模型列表
|
||||
|
||||
#### Scenario: 删除模型
|
||||
|
||||
- **WHEN** 用户点击模型的"删除"
|
||||
- **THEN** 前端 SHALL 提示确认
|
||||
- **THEN** 前端 SHALL 使用 Popconfirm 弹出确认
|
||||
- **WHEN** 用户确认删除
|
||||
- **THEN** 前端 SHALL 向 `/api/models/:id` 发送 DELETE 请求
|
||||
- **THEN** 前端 SHALL 刷新模型列表
|
||||
- **THEN** 前端 SHALL 通过 useMutation 调用删除 API
|
||||
- **THEN** 成功后 SHALL 刷新模型列表
|
||||
|
||||
### Requirement: 提供统计查看页面
|
||||
|
||||
前端 SHALL 提供查看用量统计的页面。
|
||||
前端 SHALL 使用 Ant Design 组件提供统计查看页面。
|
||||
|
||||
#### Scenario: 显示统计概览
|
||||
|
||||
- **WHEN** 加载统计页面
|
||||
- **THEN** 前端 SHALL 显示所有供应商和模型的统计
|
||||
- **THEN** 前端 SHALL 按供应商和模型分组显示请求计数
|
||||
- **THEN** 前端 SHALL 使用 Ant Design Table 显示统计数据
|
||||
- **THEN** 统计数据 SHALL 按供应商和模型显示请求计数
|
||||
|
||||
#### Scenario: 按供应商过滤统计
|
||||
|
||||
- **WHEN** 用户从下拉菜单选择供应商
|
||||
- **THEN** 前端 SHALL 过滤统计,仅显示该供应商的数据
|
||||
|
||||
#### Scenario: 按模型过滤统计
|
||||
|
||||
- **WHEN** 用户从下拉菜单选择模型
|
||||
- **THEN** 前端 SHALL 过滤统计,仅显示该模型的数据
|
||||
- **WHEN** 用户从 Ant Design Select 选择供应商
|
||||
- **THEN** 前端 SHALL 自动查询并过滤统计
|
||||
|
||||
#### Scenario: 按日期范围过滤统计
|
||||
|
||||
- **WHEN** 用户选择开始和结束日期
|
||||
- **THEN** 前端 SHALL 过滤统计,仅显示该范围内的数据
|
||||
- **WHEN** 用户使用 Ant Design DatePicker.RangePicker 选择日期范围
|
||||
- **THEN** 前端 SHALL 自动查询并过滤统计
|
||||
|
||||
### Requirement: 优雅处理 API 错误
|
||||
|
||||
@@ -108,8 +106,8 @@ TBD - 提供供应商、模型配置和用量统计的前端管理界面
|
||||
#### Scenario: API 请求失败
|
||||
|
||||
- **WHEN** API 请求失败(网络错误、4xx、5xx)
|
||||
- **THEN** 前端 SHALL 向用户显示错误消息
|
||||
- **THEN** 错误消息 SHALL 具有描述性和可操作性
|
||||
- **THEN** 前端 SHALL 使用 Ant Design 的 message.error() 显示全局错误提示
|
||||
- **THEN** 错误消息 SHALL 具有描述性
|
||||
|
||||
#### Scenario: 验证错误
|
||||
|
||||
@@ -119,64 +117,98 @@ TBD - 提供供应商、模型配置和用量统计的前端管理界面
|
||||
|
||||
### Requirement: 提供响应式布局
|
||||
|
||||
前端 SHALL 提供适应不同屏幕尺寸的响应式布局。
|
||||
前端 SHALL 使用 Ant Design Layout 提供顶部导航布局。
|
||||
|
||||
#### Scenario: 桌面布局
|
||||
|
||||
- **WHEN** 在桌面屏幕上查看前端
|
||||
- **THEN** 布局 SHALL 使用多列设计以高效利用空间
|
||||
- **THEN** 布局 SHALL 使用 Ant Design Layout.Header + Menu(horizontal 模式)
|
||||
- **THEN** 导航菜单 SHALL 在顶部水平排列
|
||||
|
||||
#### Scenario: 移动布局
|
||||
#### Scenario: 页面内容区域
|
||||
|
||||
- **WHEN** 在移动屏幕上查看前端
|
||||
- **THEN** 布局 SHALL 适应为单列设计
|
||||
- **THEN** 所有功能 SHALL 保持可访问
|
||||
- **WHEN** 显示页面内容
|
||||
- **THEN** 内容区域 SHALL 有合理的最大宽度和内边距
|
||||
- **THEN** 页面之间 SHALL 通过 React Router Outlet 渲染
|
||||
|
||||
### Requirement: 使用无组件库的最小 UI
|
||||
|
||||
前端 SHALL 使用自定义组件,不使用外部 UI 库。
|
||||
前端 SHALL 使用 Ant Design 5 作为 UI 组件库。
|
||||
|
||||
#### Scenario: 自定义组件
|
||||
#### Scenario: Ant Design 组件使用
|
||||
|
||||
- **WHEN** 实现前端
|
||||
- **THEN** 它 SHALL 使用自定义 HTML/CSS 组件
|
||||
- **THEN** 它 SHALL NOT 使用外部 UI 库,如 Ant Design、Material-UI 或 shadcn/ui
|
||||
- **THEN** 它 SHALL 使用 Ant Design 5 组件(Table、Form、Modal、Menu、Tag、Popconfirm、DatePicker、Button、Select 等)
|
||||
- **THEN** 它 SHALL 使用 @ant-design/icons 提供图标
|
||||
- **THEN** 图标 SHALL 优先使用图标库中已有的图标
|
||||
|
||||
#### Scenario: SCSS 样式
|
||||
#### Scenario: Ant Design 默认主题
|
||||
|
||||
- **WHEN** 配置 Ant Design 主题
|
||||
- **THEN** 前端 SHALL 使用 Ant Design 默认主题,不进行自定义主题色配置
|
||||
- **THEN** 前端 SHALL NOT 支持暗色模式切换
|
||||
|
||||
### Requirement: SCSS 样式
|
||||
|
||||
前端样式 SHALL 全部使用 SCSS,禁止使用纯 CSS 文件。
|
||||
|
||||
#### Scenario: 样式文件规范
|
||||
|
||||
- **WHEN** 编写样式
|
||||
- **THEN** 前端 SHALL 使用 SCSS 进行样式设计
|
||||
- **THEN** 样式 SHALL 有组织且可维护
|
||||
- **THEN** 前端 SHALL 使用 SCSS(*.scss 文件)
|
||||
- **THEN** 前端 SHALL NOT 使用纯 CSS 文件(*.css)
|
||||
- **THEN** 前端 SHALL NOT 使用 CSS-in-JS 方案
|
||||
|
||||
#### Scenario: SCSS Modules 使用
|
||||
|
||||
- **WHEN** 编写组件级样式
|
||||
- **THEN** 前端 SHALL 使用 SCSS Modules(*.module.scss)
|
||||
- **THEN** 全局样式仅保留 index.scss 做 reset 和 CSS variables
|
||||
|
||||
### Requirement: 提供导航
|
||||
|
||||
前端 SHALL 在不同页面间提供导航。
|
||||
前端 SHALL 使用 React Router v7 提供导航。
|
||||
|
||||
#### Scenario: 导航到供应商页面
|
||||
#### Scenario: 路由配置
|
||||
|
||||
- **WHEN** 用户点击导航中的"供应商"
|
||||
- **THEN** 前端 SHALL 导航到供应商管理页面
|
||||
- **WHEN** 应用启动
|
||||
- **THEN** 前端 SHALL 使用 React Router v7 Library 模式(BrowserRouter)
|
||||
- **THEN** `/providers` 路径 SHALL 显示供应商管理页面
|
||||
- **THEN** `/stats` 路径 SHALL 显示用量统计页面
|
||||
- **THEN** `/` 路径 SHALL 重定向到 `/providers`
|
||||
- **THEN** 不存在的路径 SHALL 显示 404 页面
|
||||
|
||||
#### Scenario: 导航到统计页面
|
||||
#### Scenario: 导航菜单
|
||||
|
||||
- **WHEN** 用户点击导航中的"统计"
|
||||
- **THEN** 前端 SHALL 导航到统计查看页面
|
||||
- **WHEN** 用户点击导航中的"供应商管理"
|
||||
- **THEN** 前端 SHALL 导航到 `/providers` 并高亮当前菜单项
|
||||
- **WHEN** 用户点击导航中的"用量统计"
|
||||
- **THEN** 前端 SHALL 导航到 `/stats` 并高亮当前菜单项
|
||||
|
||||
#### Scenario: URL 同步
|
||||
|
||||
- **WHEN** 用户在供应商页面刷新浏览器
|
||||
- **THEN** 前端 SHALL 保持在供应商页面(URL 持久化)
|
||||
- **WHEN** 用户使用浏览器后退按钮
|
||||
- **THEN** 前端 SHALL 正确导航到上一个页面
|
||||
|
||||
### Requirement: 使用 React 和 TypeScript
|
||||
|
||||
前端 SHALL 使用 React 和 TypeScript 实现。
|
||||
前端 SHALL 使用 React 和 TypeScript 实现,遵循 strict 模式。
|
||||
|
||||
#### Scenario: TypeScript 使用
|
||||
#### Scenario: TypeScript strict 模式
|
||||
|
||||
- **WHEN** 编写前端代码
|
||||
- **THEN** 它 SHALL 使用 TypeScript 提供类型安全
|
||||
- **THEN** 所有组件和函数 SHALL 具有适当的类型定义
|
||||
- **THEN** TypeScript 配置 SHALL 开启 strict: true
|
||||
- **THEN** TypeScript 配置 SHALL 开启 noUncheckedIndexedAccess
|
||||
- **THEN** 所有代码 SHALL NOT 使用 any 类型
|
||||
- **THEN** tsconfig SHALL 合并为单文件(不使用 project references)
|
||||
|
||||
#### Scenario: React 组件
|
||||
#### Scenario: React 函数组件
|
||||
|
||||
- **WHEN** 实现 UI
|
||||
- **THEN** 它 SHALL 使用 React 函数组件
|
||||
- **THEN** 它 SHALL 使用 React hooks 进行状态管理
|
||||
- **THEN** 它 SHALL 使用自定义 Hooks 封装业务逻辑
|
||||
|
||||
### Requirement: 使用 Vite 构建
|
||||
|
||||
@@ -194,15 +226,46 @@ TBD - 提供供应商、模型配置和用量统计的前端管理界面
|
||||
|
||||
### Requirement: 与后端 API 通信
|
||||
|
||||
前端 SHALL 使用 fetch 或类似方法与后端 API 通信。
|
||||
前端 SHALL 使用 TanStack Query v5 和统一 API 客户端与后端通信。
|
||||
|
||||
#### Scenario: API 基础 URL 配置
|
||||
|
||||
- **WHEN** 前端发起 API 请求
|
||||
- **THEN** 它 SHALL 使用配置的后端 API 基础 URL(默认:http://localhost:9826)
|
||||
- **THEN** 开发环境 SHALL 通过 Vite proxy 转发 /api 请求到后端
|
||||
- **THEN** 生产环境 SHALL 使用环境变量 VITE_API_BASE 配置基础 URL
|
||||
- **THEN** 前端 SHALL NOT 硬编码 API 基础 URL
|
||||
|
||||
#### Scenario: API 客户端封装
|
||||
#### Scenario: 统一 API 客户端
|
||||
|
||||
- **WHEN** 进行 API 调用
|
||||
- **THEN** 它们 SHALL 封装在专用的 API 客户端模块中
|
||||
- **THEN** 错误处理 SHALL 集中化
|
||||
- **THEN** 所有调用 SHALL 通过 api/client.ts 的 request<T>() 方法
|
||||
- **THEN** 错误处理 SHALL 统一抛出 ApiError(包含 status 和 message)
|
||||
- **THEN** 开发环境 SHALL 使用 Vite proxy 转发 API 请求
|
||||
|
||||
#### Scenario: 字段名转换
|
||||
|
||||
- **WHEN** 接收后端 API 响应
|
||||
- **THEN** API 层 SHALL 将 snake_case 字段转换为 camelCase
|
||||
- **WHEN** 发送请求到后端 API
|
||||
- **THEN** API 层 SHALL 将 camelCase 字段转换为 snake_case
|
||||
- **THEN** hooks 和组件 SHALL 仅使用 camelCase 字段
|
||||
|
||||
#### Scenario: TanStack Query 数据管理
|
||||
|
||||
- **WHEN** 页面加载数据
|
||||
- **THEN** 前端 SHALL 使用 TanStack Query 的 useQuery hook
|
||||
- **THEN** 前端 SHALL 自动缓存请求结果
|
||||
- **THEN** 前端 SHALL 自动处理加载和错误状态
|
||||
|
||||
#### Scenario: TanStack Query 写操作
|
||||
|
||||
- **WHEN** 用户执行创建、更新或删除操作
|
||||
- **THEN** 前端 SHALL 使用 TanStack Query 的 useMutation hook
|
||||
- **THEN** 操作成功后 SHALL 自动失效相关查询缓存
|
||||
- **THEN** 操作失败 SHALL 使用 Ant Design message.error() 显示错误提示
|
||||
|
||||
#### Scenario: 错误提示
|
||||
|
||||
- **WHEN** API 请求失败(网络错误、4xx、5xx)
|
||||
- **THEN** 前端 SHALL 使用 Ant Design 的 message.error() 显示全局错误提示
|
||||
- **THEN** 错误消息 SHALL 具有描述性
|
||||
|
||||
188
openspec/specs/frontend-testing/spec.md
Normal file
188
openspec/specs/frontend-testing/spec.md
Normal file
@@ -0,0 +1,188 @@
|
||||
# 前端测试体系
|
||||
|
||||
## Purpose
|
||||
|
||||
建立前端测试体系,覆盖单元测试、组件测试和 E2E 测试,确保前端代码质量和功能正确性。
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: 建立前端单元测试体系
|
||||
|
||||
前端 SHALL 使用 Vitest 建立单元测试体系,覆盖 API 层和自定义 Hooks。
|
||||
|
||||
#### Scenario: API 客户端单测
|
||||
|
||||
- **WHEN** 运行 api/client.ts 的单元测试
|
||||
- **THEN** SHALL 覆盖 request<T>() 的正常响应解析
|
||||
- **THEN** SHALL 覆盖 HTTP 错误状态码(4xx、5xx)的 ApiError 抛出
|
||||
- **THEN** SHALL 覆盖网络错误的错误处理
|
||||
- **THEN** SHALL 覆盖 snake_case → camelCase 响应字段转换
|
||||
- **THEN** SHALL 覆盖 camelCase → snake_case 请求字段转换
|
||||
|
||||
#### Scenario: API 模块单测
|
||||
|
||||
- **WHEN** 运行 api/providers.ts、api/models.ts、api/stats.ts 的单元测试
|
||||
- **THEN** SHALL 覆盖所有 CRUD 函数的正确调用
|
||||
- **THEN** SHALL 覆盖参数传递和返回值类型
|
||||
|
||||
#### Scenario: 自定义 Hooks 单测
|
||||
|
||||
- **WHEN** 运行 hooks/ 目录下的单元测试
|
||||
- **THEN** SHALL 使用 @tanstack/react-query 的 renderHook 测试工具
|
||||
- **THEN** SHALL 覆盖 useQuery 数据获取(成功和失败)
|
||||
- **THEN** SHALL 覆盖 useMutation 写操作后的缓存失效
|
||||
- **THEN** SHALL 使用独立的测试 QueryClient(关闭 retry 和缓存)
|
||||
|
||||
### Requirement: 建立前端组件测试体系
|
||||
|
||||
前端 SHALL 使用 React Testing Library 建立组件测试体系。
|
||||
|
||||
#### Scenario: ProviderTable 组件测试
|
||||
|
||||
- **WHEN** 运行 ProviderTable 组件测试
|
||||
- **THEN** SHALL 验证供应商列表正确渲染
|
||||
- **THEN** SHALL 验证点击"添加"按钮弹出 Modal
|
||||
- **THEN** SHALL 验证点击"编辑"按钮弹出预填充的 Modal
|
||||
- **THEN** SHALL 验证删除操作触发 Popconfirm 确认
|
||||
|
||||
#### Scenario: ProviderForm 组件测试
|
||||
|
||||
- **WHEN** 运行 ProviderForm 组件测试
|
||||
- **THEN** SHALL 验证表单校验规则(必填字段、URL 格式)
|
||||
- **THEN** SHALL 验证提交成功后调用 onSave 回调
|
||||
- **THEN** SHALL 验证编辑模式下字段预填充
|
||||
|
||||
#### Scenario: StatsTable 组件测试
|
||||
|
||||
- **WHEN** 运行 StatsTable 组件测试
|
||||
- **THEN** SHALL 验证筛选条件交互(供应商选择、日期范围)
|
||||
- **THEN** SHALL 验证统计数据正确展示
|
||||
|
||||
### Requirement: 建立 E2E 测试体系
|
||||
|
||||
前端 SHALL 使用 Playwright 建立端到端测试体系。
|
||||
|
||||
#### Scenario: 供应商管理 E2E 测试
|
||||
|
||||
- **WHEN** 运行供应商管理的 E2E 测试
|
||||
- **THEN** SHALL 测试完整的供应商创建流程
|
||||
- **THEN** SHALL 测试供应商编辑流程
|
||||
- **THEN** SHALL 测试供应商删除流程(含确认弹窗)
|
||||
- **THEN** SHALL 测试供应商展开后的模型管理
|
||||
|
||||
#### Scenario: 统计查询 E2E 测试
|
||||
|
||||
- **WHEN** 运行统计查询的 E2E 测试
|
||||
- **THEN** SHALL 测试页面加载和默认数据展示
|
||||
- **THEN** SHALL 测试按供应商筛选
|
||||
- **THEN** SHALL 测试按日期范围筛选
|
||||
|
||||
### Requirement: 使用 MSW 进行 API Mock
|
||||
|
||||
前端测试 SHALL 使用 MSW (Mock Service Worker) 模拟后端 API 响应。
|
||||
|
||||
#### Scenario: 测试环境 MSW 配置
|
||||
|
||||
- **WHEN** 初始化测试环境
|
||||
- **THEN** SHALL 配置 MSW server 处理所有 /api/* 请求
|
||||
- **THEN** SHALL 在 setup.ts 中全局启动和清理 MSW server
|
||||
|
||||
#### Scenario: Mock 响应定义
|
||||
|
||||
- **WHEN** 编写需要 API 交互的测试
|
||||
- **THEN** SHALL 使用 MSW handler 定义期望的 API 响应
|
||||
- **THEN** SHALL 支持成功和失败两种响应场景
|
||||
- **THEN** SHALL 在每个测试用例后重置 handler
|
||||
|
||||
### Requirement: 测试文件组织
|
||||
|
||||
前端测试文件 SHALL 按层级组织在 src/__tests__/ 目录下。
|
||||
|
||||
#### Scenario: 目录结构
|
||||
|
||||
- **WHEN** 组织测试文件
|
||||
- **THEN** src/__tests__/setup.ts SHALL 包含全局测试配置
|
||||
- **THEN** src/__tests__/api/ SHALL 包含 API 层单测
|
||||
- **THEN** src/__tests__/hooks/ SHALL 包含 Hooks 单测
|
||||
- **THEN** src/__tests__/components/ SHALL 包含组件测试
|
||||
- **THEN** e2e/ 目录(项目根目录下)SHALL 包含 Playwright E2E 测试
|
||||
|
||||
### Requirement: Vitest 配置
|
||||
|
||||
前端 SHALL 配置 Vitest 作为测试运行器。
|
||||
|
||||
#### Scenario: 测试环境配置
|
||||
|
||||
- **WHEN** 运行 vitest
|
||||
- **THEN** SHALL 使用 jsdom 作为测试环境
|
||||
- **THEN** SHALL 配置 setupFiles 指向 src/__tests__/setup.ts
|
||||
- **THEN** SHALL 配置路径别名 @/ 与 tsconfig 一致
|
||||
- **THEN** SHALL 配置 @testing-library/jest-dom 匹配器
|
||||
|
||||
#### Scenario: 覆盖率配置
|
||||
|
||||
- **WHEN** 运行覆盖率报告
|
||||
- **THEN** SHALL 使用 @vitest/coverage-v8 提供者
|
||||
- **THEN** SHALL 覆盖 src/ 下的所有源文件
|
||||
|
||||
### Requirement: 建立前端单元测试覆盖
|
||||
|
||||
前端代码 SHALL 建立单元测试覆盖,纳入整体测试覆盖率统计。
|
||||
|
||||
#### Scenario: API 层测试覆盖
|
||||
|
||||
- **WHEN** 运行前端 API 层的单元测试
|
||||
- **THEN** SHALL 覆盖 api/client.ts 的请求封装和字段转换逻辑
|
||||
- **THEN** SHALL 覆盖 api/providers.ts、api/models.ts、api/stats.ts 的所有函数
|
||||
- **THEN** SHALL 使用 MSW mock API 响应
|
||||
|
||||
#### Scenario: Hooks 测试覆盖
|
||||
|
||||
- **WHEN** 运行前端 Hooks 的单元测试
|
||||
- **THEN** SHALL 覆盖 useProviders、useModels、useStats 的查询和变更逻辑
|
||||
- **THEN** SHALL 验证缓存失效和自动刷新行为
|
||||
|
||||
### Requirement: 建立前端组件测试覆盖
|
||||
|
||||
前端 SHALL 使用 React Testing Library 建立组件测试覆盖。
|
||||
|
||||
#### Scenario: 页面组件测试覆盖
|
||||
|
||||
- **WHEN** 运行前端组件测试
|
||||
- **THEN** SHALL 覆盖 ProviderTable 的列表渲染和交互操作
|
||||
- **THEN** SHALL 覆盖 ProviderForm 的表单校验和提交
|
||||
- **THEN** SHALL 覆盖 ModelForm 的表单校验和提交
|
||||
- **THEN** SHALL 覆盖 StatsTable 的筛选和数据展示
|
||||
|
||||
### Requirement: 建立前端 E2E 测试覆盖
|
||||
|
||||
前端 SHALL 使用 Playwright 建立 E2E 测试覆盖。
|
||||
|
||||
#### Scenario: 供应商管理 E2E 覆盖
|
||||
|
||||
- **WHEN** 运行 E2E 测试
|
||||
- **THEN** SHALL 覆盖供应商创建、编辑、删除的完整用户流程
|
||||
- **THEN** SHALL 覆盖模型创建、编辑、删除的完整用户流程
|
||||
|
||||
#### Scenario: 统计查询 E2E 覆盖
|
||||
|
||||
- **WHEN** 运行 E2E 测试
|
||||
- **THEN** SHALL 覆盖统计页面的加载和筛选查询流程
|
||||
- **THEN** SHALL 覆盖页面间的导航切换
|
||||
|
||||
### Requirement: 前端测试集成到构建流程
|
||||
|
||||
前端测试 SHALL 集成到项目的构建和验证流程中。
|
||||
|
||||
#### Scenario: 运行前端测试命令
|
||||
|
||||
- **WHEN** 在 frontend/ 目录执行测试命令
|
||||
- **THEN** SHALL 运行所有 Vitest 单元测试和组件测试
|
||||
- **THEN** SHALL 显示测试结果
|
||||
- **THEN** SHALL 在测试失败时返回非零退出码
|
||||
|
||||
#### Scenario: 运行前端 E2E 测试命令
|
||||
|
||||
- **WHEN** 在 frontend/ 目录执行 E2E 测试命令
|
||||
- **THEN** SHALL 启动 Playwright 运行 E2E 测试
|
||||
- **THEN** SHALL 在测试失败时返回非零退出码
|
||||
@@ -104,3 +104,65 @@
|
||||
- **THEN** SHALL 运行测试并生成覆盖率报告
|
||||
- **THEN** SHALL 检查覆盖率是否达标
|
||||
- **THEN** SHALL 在覆盖率不足时返回非零退出码
|
||||
|
||||
### Requirement: 建立前端单元测试覆盖
|
||||
|
||||
前端代码 SHALL 建立单元测试覆盖,纳入整体测试覆盖率统计。
|
||||
|
||||
#### Scenario: API 层测试覆盖
|
||||
|
||||
- **WHEN** 运行前端 API 层的单元测试
|
||||
- **THEN** SHALL 覆盖 api/client.ts 的请求封装和字段转换逻辑
|
||||
- **THEN** SHALL 覆盖 api/providers.ts、api/models.ts、api/stats.ts 的所有函数
|
||||
- **THEN** SHALL 使用 MSW mock API 响应
|
||||
|
||||
#### Scenario: Hooks 测试覆盖
|
||||
|
||||
- **WHEN** 运行前端 Hooks 的单元测试
|
||||
- **THEN** SHALL 覆盖 useProviders、useModels、useStats 的查询和变更逻辑
|
||||
- **THEN** SHALL 验证缓存失效和自动刷新行为
|
||||
|
||||
### Requirement: 建立前端组件测试覆盖
|
||||
|
||||
前端 SHALL 使用 React Testing Library 建立组件测试覆盖。
|
||||
|
||||
#### Scenario: 页面组件测试覆盖
|
||||
|
||||
- **WHEN** 运行前端组件测试
|
||||
- **THEN** SHALL 覆盖 ProviderTable 的列表渲染和交互操作
|
||||
- **THEN** SHALL 覆盖 ProviderForm 的表单校验和提交
|
||||
- **THEN** SHALL 覆盖 ModelForm 的表单校验和提交
|
||||
- **THEN** SHALL 覆盖 StatsTable 的筛选和数据展示
|
||||
|
||||
### Requirement: 建立前端 E2E 测试覆盖
|
||||
|
||||
前端 SHALL 使用 Playwright 建立 E2E 测试覆盖。
|
||||
|
||||
#### Scenario: 供应商管理 E2E 覆盖
|
||||
|
||||
- **WHEN** 运行 E2E 测试
|
||||
- **THEN** SHALL 覆盖供应商创建、编辑、删除的完整用户流程
|
||||
- **THEN** SHALL 覆盖模型创建、编辑、删除的完整用户流程
|
||||
|
||||
#### Scenario: 统计查询 E2E 覆盖
|
||||
|
||||
- **WHEN** 运行 E2E 测试
|
||||
- **THEN** SHALL 覆盖统计页面的加载和筛选查询流程
|
||||
- **THEN** SHALL 覆盖页面间的导航切换
|
||||
|
||||
### Requirement: 前端测试集成到构建流程
|
||||
|
||||
前端测试 SHALL 集成到项目的构建和验证流程中。
|
||||
|
||||
#### Scenario: 运行前端测试命令
|
||||
|
||||
- **WHEN** 在 frontend/ 目录执行测试命令
|
||||
- **THEN** SHALL 运行所有 Vitest 单元测试和组件测试
|
||||
- **THEN** SHALL 显示测试结果
|
||||
- **THEN** SHALL 在测试失败时返回非零退出码
|
||||
|
||||
#### Scenario: 运行前端 E2E 测试命令
|
||||
|
||||
- **WHEN** 在 frontend/ 目录执行 E2E 测试命令
|
||||
- **THEN** SHALL 启动 Playwright 运行 E2E 测试
|
||||
- **THEN** SHALL 在测试失败时返回非零退出码
|
||||
|
||||
Reference in New Issue
Block a user