From c10b507cf69345df3dcd66c0c8a5673c7da9e307 Mon Sep 17 00:00:00 2001 From: peng Date: Wed, 5 Nov 2025 09:11:29 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=9F=E4=BA=A7=E7=AE=A1=E7=90=86=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=20-=20=E5=88=A0=E9=99=A4api-example?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../(app)/api-example/openapi-examples.tsx | 420 ---- crop-x/src/app/(app)/api-example/page.tsx | 1706 ----------------- crop-x/src/app/layout.tsx | 8 +- 3 files changed, 1 insertion(+), 2133 deletions(-) delete mode 100644 crop-x/src/app/(app)/api-example/openapi-examples.tsx delete mode 100644 crop-x/src/app/(app)/api-example/page.tsx diff --git a/crop-x/src/app/(app)/api-example/openapi-examples.tsx b/crop-x/src/app/(app)/api-example/openapi-examples.tsx deleted file mode 100644 index f579a18..0000000 --- a/crop-x/src/app/(app)/api-example/openapi-examples.tsx +++ /dev/null @@ -1,420 +0,0 @@ -'use client'; - -import { useState } from 'react'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Button } from '@/components/ui/button'; -import { Badge } from '@/components/ui/badge'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Copy, Eye, EyeOff, Code, FileJson } from 'lucide-react'; - -interface OpenApiExample { - path: string; - method: string; - summary?: string; - description?: string; - parameters?: any[]; - requestBody?: any; - responses?: any; - examples?: any; -} - -interface OpenApiExamplesProps { - className?: string; -} - -// 示例数据 - 这些通常从 OpenAPI 规范中提取 -const openApiExamples: OpenApiExample[] = [ - { - path: '/api/v1/auth/login', - method: 'POST', - summary: '用户登录', - description: '用户登录(需要验证码)', - requestBody: { - 'application/json': { - example: { - identifier: 'admin', - password: 'admin123', - captcha_id: 'test-captcha-id', - captcha_text: '1234' - } - } - }, - responses: { - 200: { - description: 'Successful Response', - content: { - 'application/json': { - example: { - access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', - token_type: 'bearer', - expires_in: 3600 - } - } - } - } - } - }, - { - path: '/api/v1/auth/register', - method: 'POST', - summary: '用户注册', - description: '用户注册', - requestBody: { - 'application/json': { - example: { - username: 'newuser', - password: 'password123', - email: 'user@example.com', - full_name: '新用户', - phone: '13800138000', - tenant_id: 'tenant-uuid', - scope: 'user', - department_id: 'dept-uuid' - } - } - }, - responses: { - 200: { - description: 'Successful Response', - content: { - 'application/json': { - example: { - id: 'uuid-12345', - username: 'newuser', - email: 'user@example.com', - phone: '13800138000', - is_active: true, - created_at: '2024-01-01T00:00:00Z' - } - } - } - } - } - }, - { - path: '/api/v1/users', - method: 'POST', - summary: '创建用户', - description: '创建用户(需要管理员权限)', - requestBody: { - 'application/json': { - example: { - username: 'testuser', - password: 'password123', - email: 'test@example.com', - full_name: '测试用户', - phone: '13900139000', - tenant_id: 'tenant-uuid', - scope: 'user', - department_id: 'dept-uuid' - } - } - }, - responses: { - 200: { - description: 'Successful Response', - content: { - 'application/json': { - example: { - id: 'uuid-67890', - username: 'testuser', - email: 'test@example.com', - phone: '13900139000', - is_active: true, - created_at: '2024-01-01T00:00:00Z' - } - } - } - } - } - }, - { - path: '/api/v1/tenants', - method: 'POST', - summary: '创建租户', - description: '创建新租户', - requestBody: { - 'application/json': { - example: { - company_name: '新企业有限责任公司', - tenant_code: 'NEW001', - company_type: '有限责任公司' - } - } - }, - responses: { - 201: { - description: 'Successful Response', - content: { - 'application/json': { - example: { - id: 'tenant-uuid', - company_name: '新企业有限责任公司', - tenant_code: 'NEW001', - company_type: '有限责任公司', - audit_status: 'pending', - created_at: '2024-01-01T00:00:00Z' - } - } - } - } - } - } -]; - -export default function OpenApiExamples({ className }: OpenApiExamplesProps) { - const [copiedCode, setCopiedCode] = useState(null); - const [visibleExamples, setVisibleExamples] = useState>(new Set()); - - const copyToClipboard = async (text: string, id: string) => { - try { - await navigator.clipboard.writeText(text); - setCopiedCode(id); - setTimeout(() => setCopiedCode(null), 2000); - } catch (err) { - console.error('Failed to copy:', err); - } - }; - - const toggleExampleVisibility = (id: string) => { - setVisibleExamples(prev => { - const newSet = new Set(prev); - if (newSet.has(id)) { - newSet.delete(id); - } else { - newSet.add(id); - } - return newSet; - }); - }; - - const getMethodColor = (method: string) => { - switch (method.toUpperCase()) { - case 'GET': return 'bg-green-100 text-green-800 border-green-200'; - case 'POST': return 'bg-blue-100 text-blue-800 border-blue-200'; - case 'PUT': return 'bg-yellow-100 text-yellow-800 border-yellow-200'; - case 'DELETE': return 'bg-red-100 text-red-800 border-red-200'; - default: return 'bg-gray-100 text-gray-800 border-gray-200'; - } - }; - - const formatJson = (obj: any) => { - return JSON.stringify(obj, null, 2); - }; - - return ( - - - - - OpenAPI 示例文档 - - - 基于 OpenAPI 规范的接口示例,展示了请求参数和响应格式 - - - - - - 全部示例 - 认证 - 用户管理 - 租户管理 - - - - {openApiExamples.map((example) => ( - - ))} - - - - {openApiExamples - .filter(e => e.path.includes('/auth/')) - .map((example) => ( - - ))} - - - - {openApiExamples - .filter(e => e.path.includes('/users')) - .map((example) => ( - - ))} - - - - {openApiExamples - .filter(e => e.path.includes('/tenants')) - .map((example) => ( - - ))} - - - - - ); -} - -interface OpenApiExampleCardProps { - example: OpenApiExample; - getMethodColor: (method: string) => string; - formatJson: (obj: any) => string; - copyToClipboard: (text: string, id: string) => void; - copiedCode: string | null; - visibleExamples: Set; - toggleExampleVisibility: (id: string) => void; -} - -function OpenApiExampleCard({ - example, - getMethodColor, - formatJson, - copyToClipboard, - copiedCode, - visibleExamples, - toggleExampleVisibility -}: OpenApiExampleCardProps) { - const exampleId = `${example.method}-${example.path}`; - const isVisible = visibleExamples.has(exampleId); - - return ( -
-
-
- - {example.method} - -
-

{example.summary}

-

- {example.path} -

-
-
- -
- - {example.description && ( -

{example.description}

- )} - - {isVisible && ( -
- {/* Request Body Examples */} - {example.requestBody && ( -
-

- - 请求示例 -

- {Object.entries(example.requestBody).map(([contentType, content]: [string, any]) => ( -
-
- {contentType} - -
-
-                    {formatJson(content.example)}
-                  
-
- ))} -
- )} - - {/* Response Examples */} - {example.responses && ( -
-

- - 响应示例 -

- {Object.entries(example.responses).map(([statusCode, response]: [string, any]) => ( -
-
- - {statusCode} - - - {response.description} - -
- {response.content && Object.entries(response.content).map(([contentType, content]: [string, any]) => ( -
-
- {contentType} - {content.example && ( - - )} -
- {content.example && ( -
-                          {formatJson(content.example)}
-                        
- )} -
- ))} -
- ))} -
- )} -
- )} -
- ); -} \ No newline at end of file diff --git a/crop-x/src/app/(app)/api-example/page.tsx b/crop-x/src/app/(app)/api-example/page.tsx deleted file mode 100644 index 72ffc31..0000000 --- a/crop-x/src/app/(app)/api-example/page.tsx +++ /dev/null @@ -1,1706 +0,0 @@ -'use client'; - -import { useState } from 'react'; -import { - // 认证相关 - loginApiV1AuthLoginPost, - registerApiV1AuthRegisterPost, - registerWithCompanyApiV1AuthRegisterWithCompanyPost, - getCaptchaApiV1AuthCaptchaGet, - refreshTokenApiV1AuthRefreshPost, - logoutApiV1AuthLogoutPost, - getCurrentUserInfoApiV1AuthMeGet, - updateCurrentUserApiV1AuthMePut, - changePasswordApiV1AuthChangePasswordPost, - verifyUserTokenApiV1AuthVerifyTokenPost, - - // 用户管理 - getUsersApiV1UsersGet, - createUserApiV1UsersPost, - getUserApiV1UsersUserIdGet, - updateUserApiV1UsersUserIdPut, - deleteUserApiV1UsersUserIdDelete, - activateUserApiV1UsersUserIdActivatePost, - deactivateUserApiV1UsersUserIdDeactivatePost, - getUserStatsApiV1UsersStatsSummaryGet, - getDepartmentOptionsApiV1UsersDepartmentsOptionsGet, - - // 系统用户管理 - listSystemUsersApiV1UsersSystemUsersGet, - createSystemUserApiV1UsersSystemUsersPost, - getSystemUserApiV1UsersSystemUsersUserIdGet, - updateSystemUserApiV1UsersSystemUsersUserIdPut, - deleteSystemUserApiV1UsersSystemUsersUserIdDelete, - activateSystemUserApiV1UsersSystemUsersUserIdActivatePost, - deactivateSystemUserApiV1UsersSystemUsersUserIdDeactivatePost, - getSystemUserStatsApiV1UsersSystemUsersStatsSummaryGet, - - // 租户管理 - listTenantsApiV1TenantsGet, - createTenantApiV1TenantsPost, - getTenantApiV1TenantsTenantIdGet, - deleteTenantApiV1TenantsTenantIdDelete, - auditTenantApiV1TenantsTenantIdAuditPost, - disableTenantApiV1TenantsTenantIdDisablePatch, - enableTenantApiV1TenantsTenantIdEnablePatch, - getCurrentTenantApiV1TenantsMeGet, - submitTenantAuditApiV1TenantsSubmitPost, - getTenantAuditLogsApiV1TenantsAuditLogsGet, - listAnonymousTenantsApiV1TenantsAnonymousListGet, - - // 部门管理 - getDepartmentsApiV1DepartmentsDepartmentsGet, - createDepartmentApiV1DepartmentsDepartmentsPost, - getDepartmentApiV1DepartmentsDepartmentsDepartmentIdGet, - updateDepartmentApiV1DepartmentsDepartmentsDepartmentIdPut, - deleteDepartmentApiV1DepartmentsDepartmentsDepartmentIdDelete, - updateDepartmentOrderApiV1DepartmentsDepartmentsDepartmentIdOrderPatch, - updateDepartmentStatusApiV1DepartmentsDepartmentsDepartmentIdStatusPatch, - getDepartmentTreeApiV1DepartmentsDepartmentsTreeGet, - - // 系统相关 - getSystemInfoApiV1SystemInfoGet, - getSystemConfigApiV1SystemConfigGet, - getSystemStatsApiV1SystemStatsGet, - getSystemMetricsApiV1SystemMetricsGet, - getPerformanceSummaryApiV1SystemMetricsSummaryGet, - - // 健康检查 - healthCheckApiV1HealthGet, - detailedHealthCheckApiV1HealthDetailedGet, - - // 类型导入 - type UserCreate, - type UserCreateWithCompany, - type UserLoginWithCaptcha, - type UserUpdate, - type UserUpdatePassword, - type TenantCreateRequest, - type TenantUpdateRequest, - type TenantAuditRequest, - type DepartmentCreate, - type DepartmentUpdate, - type CaptchaResponse, - type Token -} from '@/lib/api'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; -import { Badge } from '@/components/ui/badge'; -import { Alert, AlertDescription } from '@/components/ui/alert'; -import { ScrollArea } from '@/components/ui/scroll-area'; -import { Separator } from '@/components/ui/separator'; -import { Label } from '@/components/ui/label'; -import OpenApiExamples from './openapi-examples'; - -export default function ApiExamplePage() { - const [loading, setLoading] = useState(false); - const [results, setResults] = useState([]); - const [errors, setErrors] = useState([]); - - // 登录表单状态 - const [loginData, setLoginData] = useState({ - identifier: '', - password: '', - captcha_id: '', - captcha_text: '' - }); - - // 验证码状态 - const [captchaData, setCaptchaData] = useState(null); - - // 注册表单状态 - const [registerData, setRegisterData] = useState({ - username: '', - password: '', - email: '', - full_name: '', - phone: '', - tenant_id: '', - scope: '', - department_id: '' - }); - - // 带企业注册表单状态 - const [registerWithCompanyData, setRegisterWithCompanyData] = useState({ - user: { - username: '', - password: '', - email: '', - full_name: '' - }, - company: { - name: '', - code: '', - description: '' - } - }); - - // 用户创建表单状态 - const [createUserData, setCreateUserData] = useState({ - username: '', - password: '', - email: '', - full_name: '', - phone: '', - tenant_id: '', - scope: '', - department_id: '' - }); - - // 租户创建表单状态 - const [createTenantData, setCreateTenantData] = useState({ - company_name: '', - tenant_code: '', - company_type: '有限责任公司' - }); - - // 部门创建表单状态 - const [createDepartmentData, setCreateDepartmentData] = useState({ - name: '', - code: '', - description: '', - parent_id: '' - }); - - // 通用ID输入状态 - const [userId, setUserId] = useState(''); - const [tenantId, setTenantId] = useState(''); - const [departmentId, setDepartmentId] = useState(''); - - // 添加结果到显示列表 - const addResult = (type: string, input: any, output: any, error?: string) => { - const result = { - id: Date.now(), - type, - input, - output, - error, - timestamp: new Date().toLocaleTimeString() - }; - setResults(prev => [result, ...prev]); - if (error) { - setErrors(prev => [error, ...prev]); - } - }; - - // 清空结果 - const clearResults = () => { - setResults([]); - setErrors([]); - }; - - // 用户登录 - const handleLogin = async () => { - setLoading(true); - try { - addResult('用户登录', '登录请求', '发送中...'); - - const response = await loginApiV1AuthLoginPost({ - body: loginData - }); - - if (response.data) { - addResult('用户登录', loginData, response.data); - } else if (response.error) { - addResult('用户登录', loginData, null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('用户登录', loginData, null, error.message); - } finally { - setLoading(false); - } - }; - - // 用户注册 - const handleRegister = async () => { - setLoading(true); - try { - addResult('用户注册', '注册请求', '发送中...'); - - const response = await registerApiV1AuthRegisterPost({ - body: registerData - }); - - if (response.data) { - addResult('用户注册', registerData, response.data); - } else if (response.error) { - addResult('用户注册', registerData, null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('用户注册', registerData, null, error.message); - } finally { - setLoading(false); - } - }; - - // 带企业用户注册 - const handleRegisterWithCompany = async () => { - setLoading(true); - try { - addResult('用户注册并创建企业', '注册请求', '发送中...'); - - const response = await registerWithCompanyApiV1AuthRegisterWithCompanyPost({ - body: registerWithCompanyData - }); - - if (response.data) { - addResult('用户注册并创建企业', registerWithCompanyData, response.data); - } else if (response.error) { - addResult('用户注册并创建企业', registerWithCompanyData, null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('用户注册并创建企业', registerWithCompanyData, null, error.message); - } finally { - setLoading(false); - } - }; - - // 获取验证码 - const handleGetCaptcha = async () => { - setLoading(true); - try { - addResult('获取验证码', 'GET /api/v1/auth/captcha', '发送中...'); - - const response = await getCaptchaApiV1AuthCaptchaGet({}); - - if (response.data) { - setCaptchaData(response.data); - setLoginData(prev => ({ ...prev, captcha_id: response.data.captcha_id })); - addResult('获取验证码', '无参数', response.data); - } else if (response.error) { - addResult('获取验证码', '无参数', null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('获取验证码', '无参数', null, error.message); - } finally { - setLoading(false); - } - }; - - // 刷新令牌 - const handleRefreshToken = async () => { - setLoading(true); - try { - addResult('刷新令牌', 'POST /api/v1/auth/refresh', '发送中...'); - - const response = await refreshTokenApiV1AuthRefreshPost({}); - - if (response.data) { - addResult('刷新令牌', '无参数', response.data); - } else if (response.error) { - addResult('刷新令牌', '无参数', null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('刷新令牌', '无参数', null, error.message); - } finally { - setLoading(false); - } - }; - - // 获取当前用户信息 - const handleGetCurrentUser = async () => { - setLoading(true); - try { - addResult('获取当前用户', 'GET /api/v1/auth/me', '发送中...'); - - const response = await getCurrentUserInfoApiV1AuthMeGet({}); - - if (response.data) { - addResult('获取当前用户', '无参数', response.data); - } else if (response.error) { - addResult('获取当前用户', '无参数', null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('获取当前用户', '无参数', null, error.message); - } finally { - setLoading(false); - } - }; - - // 获取用户列表 - const handleGetUsers = async () => { - setLoading(true); - try { - addResult('获取用户列表', 'GET /api/v1/users', '发送中...'); - - const response = await getUsersApiV1UsersGet({}); - - if (response.data) { - addResult('获取用户列表', '无参数', response.data); - } else if (response.error) { - addResult('获取用户列表', '无参数', null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('获取用户列表', '无参数', null, error.message); - } finally { - setLoading(false); - } - }; - - // 创建用户 - const handleCreateUser = async () => { - setLoading(true); - try { - addResult('创建用户', 'POST /api/v1/users', '发送中...'); - - const response = await createUserApiV1UsersPost({ - body: createUserData - }); - - if (response.data) { - addResult('创建用户', createUserData, response.data); - } else if (response.error) { - addResult('创建用户', createUserData, null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('创建用户', createUserData, null, error.message); - } finally { - setLoading(false); - } - }; - - // 获取用户详情 - const handleGetUser = async () => { - if (!userId) { - addResult('获取用户详情', '缺少用户ID', null, '请输入用户ID'); - return; - } - - setLoading(true); - try { - addResult('获取用户详情', `GET /api/v1/users/${userId}`, '发送中...'); - - const response = await getUserApiV1UsersUserIdGet({ - path: { user_id: userId } - }); - - if (response.data) { - addResult('获取用户详情', { user_id: userId }, response.data); - } else if (response.error) { - addResult('获取用户详情', { user_id: userId }, null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('获取用户详情', { user_id: userId }, null, error.message); - } finally { - setLoading(false); - } - }; - - // 用户登出 - const handleLogout = async () => { - setLoading(true); - try { - addResult('用户登出', 'POST /api/v1/auth/logout', '发送中...'); - - const response = await logoutApiV1AuthLogoutPost({}); - - if (response.data) { - addResult('用户登出', '无参数', response.data); - } else if (response.error) { - addResult('用户登出', '无参数', null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('用户登出', '无参数', null, error.message); - } finally { - setLoading(false); - } - }; - - // 健康检查 - const handleHealthCheck = async () => { - setLoading(true); - try { - addResult('健康检查', 'GET /api/v1/health', '发送中...'); - - const response = await healthCheckApiV1HealthGet({}); - - if (response.data) { - addResult('健康检查', '无参数', response.data); - } else if (response.error) { - addResult('健康检查', '无参数', null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('健康检查', '无参数', null, error.message); - } finally { - setLoading(false); - } - }; - - // 系统信息 - const handleGetSystemInfo = async () => { - setLoading(true); - try { - addResult('系统信息', 'GET /api/v1/system/info', '发送中...'); - - const response = await getSystemInfoApiV1SystemInfoGet({}); - - if (response.data) { - addResult('系统信息', '无参数', response.data); - } else if (response.error) { - addResult('系统信息', '无参数', null, JSON.stringify(response.error)); - } - } catch (error: any) { - addResult('系统信息', '无参数', null, error.message); - } finally { - setLoading(false); - } - }; - - return ( -
-
-
-

OpenAPI 接口测试

- -
- - - - 交互式测试 - 接口示例 - OpenAPI 文档 - - - -
- {/* 左侧:API 操作面板 */} - - - API 操作 - - 使用 @hey-api/openapi-ts 生成的接口函数 - - - - - - 认证操作 - 用户管理 - 租户管理 - 部门管理 - 系统管理 - - - - {/* 登录表单 */} -
-

用户登录(需要验证码)

-
- - setLoginData(prev => ({ ...prev, identifier: e.target.value }))} - /> -
-
- - setLoginData(prev => ({ ...prev, password: e.target.value }))} - /> -
-
- -
- setLoginData(prev => ({ ...prev, captcha_text: e.target.value }))} - className="flex-1" - /> - -
- {captchaData && ( -
- 验证码 -

- 验证码ID: {captchaData.captcha_id} -

-
- )} -
- -
- - {/* 注册表单 */} -
-

用户注册

- setRegisterData(prev => ({ ...prev, username: e.target.value }))} - /> - setRegisterData(prev => ({ ...prev, password: e.target.value }))} - /> - setRegisterData(prev => ({ ...prev, email: e.target.value }))} - /> - setRegisterData(prev => ({ ...prev, full_name: e.target.value }))} - /> - setRegisterData(prev => ({ ...prev, phone: e.target.value }))} - /> - setRegisterData(prev => ({ ...prev, tenant_id: e.target.value || undefined }))} - /> - setRegisterData(prev => ({ ...prev, scope: e.target.value || undefined }))} - /> - setRegisterData(prev => ({ ...prev, department_id: e.target.value || undefined }))} - /> - -
- - {/* 其他认证操作 */} -
- - - - -
-
- - - {/* 创建用户表单 */} -
-

创建用户

- setCreateUserData(prev => ({ ...prev, username: e.target.value }))} - /> - setCreateUserData(prev => ({ ...prev, password: e.target.value }))} - /> - setCreateUserData(prev => ({ ...prev, email: e.target.value }))} - /> - setCreateUserData(prev => ({ ...prev, full_name: e.target.value }))} - /> - setCreateUserData(prev => ({ ...prev, phone: e.target.value }))} - /> - setCreateUserData(prev => ({ ...prev, tenant_id: e.target.value || undefined }))} - /> - setCreateUserData(prev => ({ ...prev, scope: e.target.value || undefined }))} - /> - setCreateUserData(prev => ({ ...prev, department_id: e.target.value || undefined }))} - /> - -
- - {/* 获取用户详情 */} -
-

获取用户详情

- setUserId(e.target.value)} - /> - -
- - {/* 其他用户操作 */} -
- -
-
- - - {/* 创建租户表单 */} -
-

创建租户

- setCreateTenantData(prev => ({ ...prev, company_name: e.target.value }))} - /> - setCreateTenantData(prev => ({ ...prev, tenant_code: e.target.value }))} - /> - - -
- - {/* 其他租户操作 */} -
- - - -
-
- - - {/* 创建部门表单 */} -
-

创建部门

- setCreateDepartmentData(prev => ({ ...prev, code: e.target.value }))} - /> - setCreateDepartmentData(prev => ({ ...prev, name: e.target.value }))} - /> - setCreateDepartmentData(prev => ({ ...prev, description: e.target.value }))} - /> - -
- - {/* 其他部门操作 */} -
- - - -
-
- - - {/* 系统操作 */} -
- - -
-
-
-
-
- - {/* 右侧:结果显示面板 */} - - - 请求 & 响应结果 - - 显示 API 调用的输入和输出结果 - - - -
- {results.length === 0 ? ( -
-

暂无 API 调用记录

-

请在左侧面板中操作 API 接口

-
- ) : ( - results.map((result) => ( -
-
-

{result.type}

-
- {result.timestamp} - {result.error ? ( - 错误 - ) : ( - 成功 - )} -
-
- - {/* 输入数据 */} -
-

输入数据:

-
-                              {JSON.stringify(result.input, null, 2)}
-                            
-
- - {/* 输出数据 */} -
-

- {result.error ? '错误信息:' : '响应数据:'} -

-
-                              {result.error || JSON.stringify(result.output, null, 2)}
-                            
-
-
- )) - )} -
-
-
-
- - {/* 错误提示 */} - {errors.length > 0 && ( -
- - - 最近发生了 {errors.length} 个错误,请查看右侧结果面板中的详细信息。 - - -
- )} -
- - - - - - - - -
-
-
- ); -} - -// API示例页面组件 -function ApiExamplesPage() { - const [examplesLoading, setExamplesLoading] = useState>({}); - const [examplesResults, setExamplesResults] = useState>({}); - - // API示例配置 - 基于新生成的SDK - const apiExamples = [ - // 认证相关 - { - id: 'getCaptcha', - method: 'GET', - path: '/api/v1/auth/captcha', - title: '获取验证码', - description: '获取登录验证码', - exampleParams: null, - category: '认证', - expectedOutput: { captcha_id: 'xyz789', image: 'base64_image_data' } - }, - { - id: 'login', - method: 'POST', - path: '/api/v1/auth/login', - title: '用户登录', - description: '用户登录(需要验证码)', - exampleParams: { - identifier: 'admin', - password: 'admin123', - captcha_id: 'test_captcha_id', - captcha_text: 'test' - }, - category: '认证', - expectedOutput: { access_token: 'jwt_token', token_type: 'bearer', expires_in: 3600 } - }, - { - id: 'register', - method: 'POST', - path: '/api/v1/auth/register', - title: '用户注册', - description: '用户注册接口', - exampleParams: { - username: 'newuser', - password: 'password123', - email: 'user@example.com', - full_name: '新用户', - phone: '13800138000', - tenant_id: 'tenant-uuid', - scope: 'user', - department_id: 'dept-uuid' - }, - category: '认证', - expectedOutput: { id: 'uuid', username: 'newuser', email: 'user@example.com', phone: '13800138000' } - }, - { - id: 'getCurrentUser', - method: 'GET', - path: '/api/v1/auth/me', - title: '获取当前用户', - description: '获取当前登录用户信息', - exampleParams: null, - category: '认证', - expectedOutput: { id: 'uuid', username: 'admin', is_active: true } - }, - { - id: 'refreshToken', - method: 'POST', - path: '/api/v1/auth/refresh', - title: '刷新令牌', - description: '刷新访问令牌', - exampleParams: null, - category: '认证', - expectedOutput: { access_token: 'new_jwt_token' } - }, - { - id: 'logout', - method: 'POST', - path: '/api/v1/auth/logout', - title: '用户登出', - description: '用户登出接口', - exampleParams: null, - category: '认证', - expectedOutput: { message: '登出成功' } - }, - - // 用户管理 - { - id: 'getUsers', - method: 'GET', - path: '/api/v1/users', - title: '获取用户列表', - description: '获取用户列表(需要管理员权限)', - exampleParams: { page: 1, size: 20 }, - category: '用户管理', - expectedOutput: { data: [{ id: 'uuid', username: 'admin' }], total: 1 } - }, - { - id: 'createUser', - method: 'POST', - path: '/api/v1/users', - title: '创建用户', - description: '创建用户(需要管理员权限)', - exampleParams: { - username: 'testuser', - password: 'password123', - email: 'test@example.com', - full_name: '测试用户', - phone: '13900139000', - tenant_id: 'tenant-uuid', - scope: 'user', - department_id: 'dept-uuid' - }, - category: '用户管理', - expectedOutput: { id: 'uuid', username: 'testuser', email: 'test@example.com', phone: '13900139000' } - }, - { - id: 'getUserStats', - method: 'GET', - path: '/api/v1/users/stats/summary', - title: '用户统计', - description: '获取用户统计信息', - exampleParams: null, - category: '用户管理', - expectedOutput: { total_users: 10, active_users: 8, inactive_users: 2 } - }, - { - id: 'getDepartmentOptions', - method: 'GET', - path: '/api/v1/users/departments/options', - title: '获取部门选项', - description: '获取部门选择列表(用于用户管理中的部门选择)', - exampleParams: null, - category: '用户管理', - expectedOutput: [{ id: 'uuid', code: 'TECH001', name: '技术开发部' }] - }, - { - id: 'listSystemUsers', - method: 'GET', - path: '/api/v1/users/system/users', - title: '获取系统用户列表', - description: '获取系统用户列表(需要系统权限)', - exampleParams: { page: 1, size: 20, search: '', is_active: true }, - category: '用户管理', - expectedOutput: { data: [{ id: 'uuid', username: 'admin', is_active: true }], total: 1 } - }, - { - id: 'createSystemUser', - method: 'POST', - path: '/api/v1/users/system/users', - title: '创建系统用户', - description: '创建系统级用户(需要系统权限)', - exampleParams: { - username: 'system_admin', - password: 'admin123', - email: 'admin@system.com', - full_name: '系统管理员', - phone: '13700137000', - tenant_id: null, - scope: 'system', - department_id: null - }, - category: '用户管理', - expectedOutput: { id: 'uuid', username: 'system_admin', scope: 'system' } - }, - - // 租户管理 - { - id: 'listTenants', - method: 'GET', - path: '/api/v1/tenants', - title: '获取租户列表', - description: '获取租户列表', - exampleParams: { page: 1, size: 20, search: '', audit_status: 'approved' }, - category: '租户管理', - expectedOutput: { data: [{ id: 'uuid', name: '测试企业' }], total: 1, page: 1, size: 20 } - }, - { - id: 'getCurrentTenant', - method: 'GET', - path: '/api/v1/tenants/me', - title: '获取当前租户', - description: '获取当前登录租户信息', - exampleParams: null, - category: '租户管理', - expectedOutput: { id: 'uuid', name: '测试企业', code: 'TEST001', audit_status: 'approved' } - }, - { - id: 'createTenant', - method: 'POST', - path: '/api/v1/tenants', - title: '创建租户', - description: '创建新租户', - exampleParams: { - company_name: '新企业有限责任公司', - tenant_code: 'NEW001', - company_type: '有限责任公司' - }, - category: '租户管理', - expectedOutput: { id: 'uuid', company_name: '新企业有限责任公司', tenant_code: 'NEW001', company_type: '有限责任公司' } - }, - { - id: 'getTenantAuditLogs', - method: 'GET', - path: '/api/v1/tenants/audit-logs', - title: '获取租户审计日志', - description: '获取租户审计日志', - exampleParams: { page: 1, size: 20, tenant_id: 'uuid' }, - category: '租户管理', - expectedOutput: { data: [{ id: 'uuid', action: 'create', timestamp: '2024-01-01T00:00:00Z' }], total: 1 } - }, - - // 部门管理 - { - id: 'getDepartments', - method: 'GET', - path: '/api/v1/departments/departments', - title: '获取部门列表', - description: '获取部门列表', - exampleParams: { page: 1, size: 20 }, - category: '部门管理', - expectedOutput: { data: [{ id: 'uuid', name: '技术部', code: 'TECH' }], total: 1, page: 1, size: 20 } - }, - { - id: 'createDepartment', - method: 'POST', - path: '/api/v1/departments/departments', - title: '创建部门', - description: '创建新部门', - exampleParams: { - code: 'TECH001', - name: '技术开发部', - description: '负责技术研发工作' - }, - category: '部门管理', - expectedOutput: { id: 'uuid', code: 'TECH001', name: '技术开发部', description: '负责技术研发工作' } - }, - { - id: 'getDepartmentTree', - method: 'GET', - path: '/api/v1/departments/departments/tree', - title: '获取部门树', - description: '获取部门树形结构', - exampleParams: null, - category: '部门管理', - expectedOutput: [{ id: 'uuid', code: 'TECH001', name: '技术开发部', description: '负责技术研发工作', children: [] }] - }, - - // 系统管理 - { - id: 'healthCheck', - method: 'GET', - path: '/api/v1/health', - title: '健康检查', - description: 'API健康检查', - exampleParams: null, - category: '系统管理', - expectedOutput: { status: 'healthy', timestamp: '2024-01-01T00:00:00Z' } - }, - { - id: 'detailedHealthCheck', - method: 'GET', - path: '/api/v1/health/detailed', - title: '详细健康检查', - description: '详细的系统健康检查', - exampleParams: null, - category: '系统管理', - expectedOutput: { status: 'healthy', database: 'connected', redis: 'connected' } - }, - { - id: 'getSystemInfo', - method: 'GET', - path: '/api/v1/system/info', - title: '系统信息', - description: '获取系统信息', - exampleParams: null, - category: '系统管理', - expectedOutput: { version: '1.0.0', environment: 'development' } - }, - { - id: 'getSystemStats', - method: 'GET', - path: '/api/v1/system/stats', - title: '系统统计', - description: '获取系统统计信息', - exampleParams: null, - category: '系统管理', - expectedOutput: { uptime: 3600, memory_usage: '50MB' } - } - ]; - - // 调用示例API - const callExampleApi = async (example: typeof apiExamples[0]) => { - setExamplesLoading(prev => ({ ...prev, [example.id]: true })); - - try { - let response; - - switch (example.id) { - // 认证相关 - case 'getCaptcha': - response = await getCaptchaApiV1AuthCaptchaGet({}); - break; - case 'login': - response = await loginApiV1AuthLoginPost({ - body: example.exampleParams - }); - break; - case 'register': - response = await registerApiV1AuthRegisterPost({ - body: example.exampleParams - }); - break; - case 'getCurrentUser': - response = await getCurrentUserInfoApiV1AuthMeGet({}); - break; - case 'refreshToken': - response = await refreshTokenApiV1AuthRefreshPost({}); - break; - case 'logout': - response = await logoutApiV1AuthLogoutPost({}); - break; - - // 用户管理 - case 'getUsers': - response = await getUsersApiV1UsersGet({ - query: example.exampleParams - }); - break; - case 'createUser': - response = await createUserApiV1UsersPost({ - body: example.exampleParams - }); - break; - case 'getUserStats': - response = await getUserStatsApiV1UsersStatsSummaryGet({}); - break; - case 'getDepartmentOptions': - response = await getDepartmentOptionsApiV1UsersDepartmentsOptionsGet({}); - break; - case 'listSystemUsers': - response = await listSystemUsersApiV1UsersSystemUsersGet({ - query: example.exampleParams - }); - break; - case 'createSystemUser': - response = await createSystemUserApiV1UsersSystemUsersPost({ - body: example.exampleParams - }); - break; - - // 租户管理 - case 'listTenants': - response = await listTenantsApiV1TenantsGet({ - query: example.exampleParams - }); - break; - case 'getCurrentTenant': - response = await getCurrentTenantApiV1TenantsMeGet({}); - break; - case 'createTenant': - response = await createTenantApiV1TenantsPost({ - body: example.exampleParams - }); - break; - case 'getTenantAuditLogs': - response = await getTenantAuditLogsApiV1TenantsAuditLogsGet({ - query: example.exampleParams - }); - break; - - // 部门管理 - case 'getDepartments': - response = await getDepartmentsApiV1DepartmentsDepartmentsGet({ - query: example.exampleParams - }); - break; - case 'createDepartment': - response = await createDepartmentApiV1DepartmentsDepartmentsPost({ - body: example.exampleParams - }); - break; - case 'getDepartmentTree': - response = await getDepartmentTreeApiV1DepartmentsDepartmentsTreeGet({}); - break; - - // 系统管理 - case 'healthCheck': - response = await healthCheckApiV1HealthGet({}); - break; - case 'detailedHealthCheck': - response = await detailedHealthCheckApiV1HealthDetailedGet({}); - break; - case 'getSystemInfo': - response = await getSystemInfoApiV1SystemInfoGet({}); - break; - case 'getSystemStats': - response = await getSystemStatsApiV1SystemStatsGet({}); - break; - - default: - throw new Error(`Unknown API example: ${example.id}`); - } - - setExamplesResults(prev => ({ - ...prev, - [example.id]: { - success: !response.error, - data: response.data, - error: response.error, - input: example.exampleParams, - timestamp: new Date().toLocaleTimeString() - } - })); - } catch (error: any) { - setExamplesResults(prev => ({ - ...prev, - [example.id]: { - success: false, - error: error.message, - input: example.exampleParams, - timestamp: new Date().toLocaleTimeString() - } - })); - } finally { - setExamplesLoading(prev => ({ ...prev, [example.id]: false })); - } - }; - - // 批量调用所有示例 - const callAllExamples = async () => { - // 按类别调用,先调用认证相关的 - const authExamples = apiExamples.filter(ex => ex.category === '认证'); - for (const example of authExamples) { - await callExampleApi(example); - await new Promise(resolve => setTimeout(resolve, 200)); // 间隔200ms - } - - // 然后调用其他类别的接口 - const otherExamples = apiExamples.filter(ex => ex.category !== '认证'); - for (const example of otherExamples) { - await callExampleApi(example); - await new Promise(resolve => setTimeout(resolve, 100)); // 间隔100ms - } - }; - - // 按类别调用 - const callCategoryExamples = async (category: string) => { - const categoryExamples = apiExamples.filter(ex => ex.category === category); - for (const example of categoryExamples) { - await callExampleApi(example); - await new Promise(resolve => setTimeout(resolve, 150)); // 间隔150ms - } - }; - - // 获取所有类别 - const categories = Array.from(new Set(apiExamples.map(ex => ex.category))); - - return ( -
-
-
-

接口示例集合

-

- 基于OpenAPI规范自动生成的所有接口示例,支持分类测试和批量调用 -

-
-
- -
-
- - {/* 按类别展示 */} - {categories.map((category) => { - const categoryExamples = apiExamples.filter(ex => ex.category === category); - const categorySuccessCount = categoryExamples.filter(ex => examplesResults[ex.id]?.success).length; - const categoryFailureCount = categoryExamples.filter(ex => examplesResults[ex.id]?.success === false).length; - const categoryTotalCount = categoryExamples.length; - - return ( - - -
-
- {category} - - 共 {categoryTotalCount} 个接口,成功 {categorySuccessCount} 个,失败 {categoryFailureCount} 个 - -
-
- -
- {categorySuccessCount} - / - {categoryFailureCount} - / - {categoryTotalCount} -
-
-
-
- -
- {categoryExamples.map((example) => ( - - -
-
- {example.title} - - {example.method} {example.path} - -
- - {example.method} - -
-
- -

{example.description}

- - {/* 示例参数 */} - {example.exampleParams && ( -
-

参数:

-
-                            {JSON.stringify(example.exampleParams, null, 2)}
-                          
-
- )} - - {/* 实际结果 */} - {examplesResults[example.id] && ( -
-
-

- 结果 - - ({examplesResults[example.id].timestamp}) - -

- - {examplesResults[example.id].success ? '成功' : '失败'} - -
-
-                            {examplesResults[example.id].error
-                              ? JSON.stringify(examplesResults[example.id].error, null, 2)
-                              : JSON.stringify(examplesResults[example.id].data, null, 2)
-                            }
-                          
-
- )} - - -
-
- ))} -
-
-
- ); - })} - - {/* 总体统计信息 */} - - - 测试统计总览 - - -
-
-

- {Object.values(examplesResults).filter(r => r?.success).length} -

-

成功

-
-
-

- {Object.values(examplesResults).filter(r => r?.success === false).length} -

-

失败

-
-
-

- {Object.values(examplesResults).filter(r => r !== undefined).length} -

-

已测试

-
-
-

- {apiExamples.length} -

-

总计

-
-
- - {/* 进度条 */} -
-
-
0 ? (Object.values(examplesResults).filter(r => r?.success).length / apiExamples.length) * 100 : 0}%` - }} - >
-
-

- 成功率: {apiExamples.length > 0 ? Math.round((Object.values(examplesResults).filter(r => r?.success).length / apiExamples.length) * 100) : 0}% -

-
-
-
-
- ); -} \ No newline at end of file diff --git a/crop-x/src/app/layout.tsx b/crop-x/src/app/layout.tsx index 008cd58..9144bc3 100644 --- a/crop-x/src/app/layout.tsx +++ b/crop-x/src/app/layout.tsx @@ -61,13 +61,7 @@ const navbarData = { url: "/central-config", description: "租户管理、用户管理、系统监控", icon: , - }, - { - title: "API 测试示例", - url: "/api-example", - description: "测试和展示 OpenAPI 客户端调用", - icon: , - }, + } ], auth: { login: { title: "登录", url: "/login" },