授权应用添加详情,编辑,删除操作

This commit is contained in:
Lrd
2026-06-11 16:54:41 +08:00
parent bec4f6b419
commit 2a37adea0a
8 changed files with 602 additions and 145 deletions
File diff suppressed because one or more lines are too long
+13 -14
View File
@@ -1,14 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>VideoGen.AI 管理后台</title>
<script type="module" crossorigin src="/assets/index-BBz1j0L-.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>VideoGen.AI 管理后台</title>
<script type="module" crossorigin src="/assets/index-BH90EezD.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
+2
View File
@@ -18,6 +18,7 @@ import AdminCreditRatios from './pages/AdminCreditRatios';
import AdminMenuConfig from './pages/AdminMenuConfig';
import AdminRechargePackages from './pages/AdminRechargePackages';
import AdminOperationLogs from './pages/AdminOperationLogs';
import AdminOauthAppList from './pages/AdminOauthAppList';
import AdminGenerationRecords from './pages/AdminGenerationRecords';
import AdminGenerationAiRecords from './pages/AdminGenerationAiRecords';
import { useAdminStore } from './store';
@@ -77,6 +78,7 @@ const App = () => {
<Route path="payment" element={<AdminPaymentConfig />} />
<Route path="settings" element={<AdminSettings />} />
<Route path="notifications" element={<AdminNotificationManager />} />
<Route path="oauthapp-list" element={<AdminOauthAppList />} />
<Route path="operation-logs" element={<AdminOperationLogs />} />
<Route path="generation-records" element={<AdminGenerationRecords />} />
<Route path="generation-ai" element={<AdminGenerationAiRecords />} />
+37
View File
@@ -278,6 +278,43 @@ export async function getOperationLogs(page?: number): Promise<{ total: number;
return api.get(`/admin/operation-logs${q}`);
}
// ── oauthapp List ──────────────────────────────────────
export async function getOauthAppList(page?: number): Promise<{ total: number; items: any[] }> {
const q = page ? `?page=${page}` : '';
return api.get(`/admin/user-oauth-apps/list${q}`);
}
export async function createOauthApp(data: {
app_id: string;
secret: string;
open_type: number;
count?: number;
auth_url?: string;
company?: string;
}): Promise<any> {
return api.post('/admin/user-oauth-apps/create', data);
}
export async function getOauthApp(id: string): Promise<any> {
return api.get(`/admin/user-oauth-apps/read/${id}`);
}
export async function updateOauthApp(id: string, data: {
app_id?: string;
secret?: string;
open_type?: number;
count?: number;
auth_url?: string;
company?: string;
}): Promise<any> {
return api.post(`/admin/user-oauth-apps/update/${id}`, data);
}
export async function deleteOauthApp(id: string): Promise<void> {
await api.get(`/admin/user-oauth-apps/delete/${id}`);
}
// ── Generation Records (Admin) ─────────────────────────────
export async function getAdminGenerationRecords(params?: {
@@ -0,0 +1,406 @@
import React, { useEffect, useState } from 'react';
import {
Button, Card, Space, Table, Tag, Typography, message, Modal, Form, Input, Select, InputNumber,
} from 'antd';
import {
HistoryOutlined, ReloadOutlined, PlusOutlined, EyeOutlined, EditOutlined, DeleteOutlined,
} from '@ant-design/icons';
import { getOauthAppList, createOauthApp, getOauthApp, updateOauthApp, deleteOauthApp } from '../api';
import { formatDate } from '../utils/formatDate';
interface OAuthApp {
id: string;
appId: string;
secret: string;
status: number;
count: number;
openType: number;
authUrl?: string;
company?: string;
createBy: string;
createdAt: string;
updatedAt: string;
}
const AdminOauthAppList: React.FC = () => {
const [apps, setApps] = useState<OAuthApp[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [page, setPage] = useState(1);
const [createModalVisible, setCreateModalVisible] = useState(false);
const [detailModalVisible, setDetailModalVisible] = useState(false);
const [updateModalVisible, setUpdateModalVisible] = useState(false);
const [currentApp, setCurrentApp] = useState<OAuthApp | null>(null);
const [form] = Form.useForm();
const [updateForm] = Form.useForm();
const load = async (p?: number) => {
setLoading(true);
try {
const res = await getOauthAppList(p || page);
setApps(res.items || []);
setTotal(res.total || 0);
} catch {
message.error('加载授权应用列表失败');
} finally {
setLoading(false);
}
};
const handleCreate = async () => {
try {
const values = await form.validateFields();
await createOauthApp({
app_id: values.app_id,
secret: values.secret,
open_type: values.open_type,
count: values.count,
auth_url: values.auth_url,
company: values.company,
});
message.success('创建成功');
setCreateModalVisible(false);
form.resetFields();
load();
} catch (e: any) {
message.error(e?.message || '创建失败');
}
};
const handleDetail = async (id: string) => {
try {
const app = await getOauthApp(id);
setCurrentApp(app);
setDetailModalVisible(true);
} catch (e: any) {
message.error(e?.message || '获取详情失败');
}
};
const handleUpdate = async (id: string) => {
try {
const app = await getOauthApp(id);
setCurrentApp(app);
updateForm.setFieldsValue({
app_id: app.appId,
secret: app.secret,
open_type: app.openType,
count: app.count,
auth_url: app.authUrl,
company: app.company,
});
setUpdateModalVisible(true);
} catch (e: any) {
message.error(e?.message || '获取详情失败');
}
};
const handleSaveUpdate = async () => {
if (!currentApp) return;
try {
const values = await updateForm.validateFields();
await updateOauthApp(currentApp.id, {
app_id: values.app_id,
secret: values.secret,
open_type: values.open_type,
count: values.count,
auth_url: values.auth_url,
company: values.company,
});
message.success('更新成功');
setUpdateModalVisible(false);
updateForm.resetFields();
load();
} catch (e: any) {
message.error(e?.message || '更新失败');
}
};
const handleDelete = (id: string) => {
Modal.confirm({
title: '确认删除',
content: '确定要删除这个授权应用吗?',
okText: '删除',
okType: 'danger',
cancelText: '取消',
onOk: async () => {
try {
await deleteOauthApp(id);
message.success('删除成功');
load();
} catch (e: any) {
message.error(e?.message || '删除失败');
}
},
});
};
useEffect(() => { load(); }, []);
const columns = [
{ title: 'ID', dataIndex: 'id',
render: (v: string) => <Typography.Text>{v}</Typography.Text>,
},
{ title: '应用ID', dataIndex: 'appId',
render: (v: string) => <Typography.Text>{v}</Typography.Text>,
},
{ title: '应用密钥', dataIndex: 'secret',
render: (v: string) => <Typography.Text>{v}</Typography.Text>,
},
{ title: '开户方式', dataIndex: 'openType',
render: (v: number) => {
const typeMap: Record<number, string> = {
1: '千川', 2: '广告', 3: '本地推', 4: '星图', 5: '快手代理商',
6: '巨量星图', 7: '巨量服务单', 8: '腾讯服务单', 9: '腾讯营销K2', 10: '腾讯营销K3'
};
return <Typography.Text>{typeMap[v] || v}</Typography.Text>;
},
},
{ title: '归属公司', dataIndex: 'company',
render: (v: string) => <Typography.Text>{v}</Typography.Text>,
},
{ title: '授权次数', dataIndex: 'count',
render: (v: number) => <Typography.Text>{v}</Typography.Text>,
},
{ title: '状态', dataIndex: 'status',
render: (v: number) => <Tag color={v === 1 ? 'green' : 'red'}>{v === 1 ? '正常' : '禁用'}</Tag>,
},
{ title: '授权URL', dataIndex: 'authUrl',
render: (v: string) => <Typography.Text>{v}</Typography.Text>,
},
{ title: '创建人', dataIndex: 'createBy',
render: (v: string) => <Typography.Text>{v}</Typography.Text>,
},
{ title: '创建时间', dataIndex: 'createdAt',
render: (v: string) => <Typography.Text>{formatDate(v)}</Typography.Text>,
},
{ title: '更新时间', dataIndex: 'updatedAt',
render: (v: string) => <Typography.Text>{formatDate(v)}</Typography.Text>,
},
{ title: '操作',
render: (_: any, record: OAuthApp) => (
<Space>
<Button
icon={<EyeOutlined />}
size="small"
onClick={() => handleDetail(record.id)}
></Button>
<Button
icon={<EditOutlined />}
size="small"
onClick={() => handleUpdate(record.id)}
></Button>
<Button
icon={<DeleteOutlined />}
size="small"
danger
onClick={() => handleDelete(record.id)}
></Button>
</Space>
),
},
];
return (
<div>
<Card variant="outlined" style={{ borderRadius: 12, border: '1px solid #f0f0f5' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
<Space>
<HistoryOutlined style={{ fontSize: 18, color: '#6366f1' }} />
<Typography.Text strong style={{ fontSize: 16 }}></Typography.Text>
</Space>
<Space>
<Button icon={<ReloadOutlined />} onClick={() => load()}></Button>
<Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}></Button>
</Space>
</div>
<Table
columns={columns}
dataSource={apps}
rowKey="id"
loading={loading}
pagination={{
current: page,
pageSize: 20,
total,
showTotal: (t) => `${t} 条记录`,
onChange: (p) => { setPage(p); load(p); },
}}
scroll={{ x: 800 }}
/>
</Card>
<Modal
title="创建授权应用"
open={createModalVisible}
onOk={handleCreate}
onCancel={() => {
setCreateModalVisible(false);
form.resetFields();
}}
okText="创建"
cancelText="取消"
width={600}
>
<Form form={form} layout="vertical">
<Form.Item
name="app_id"
label="应用ID"
rules={[{ required: true, message: '请输入应用ID' }, { max: 64, message: '应用ID不能超过64个字符' }]}
>
<Input placeholder="请输入应用ID" />
</Form.Item>
<Form.Item
name="secret"
label="应用密钥"
rules={[{ required: true, message: '请输入应用密钥' }, { max: 256, message: '应用密钥不能超过256个字符' }]}
>
<Input placeholder="请输入应用密钥" />
</Form.Item>
<Form.Item
name="open_type"
label="开户方式"
rules={[{ required: true, message: '请选择开户方式' }]}
>
<Select placeholder="请选择开户方式">
<Select.Option value={1}></Select.Option>
<Select.Option value={2}>广</Select.Option>
<Select.Option value={3}></Select.Option>
<Select.Option value={4}></Select.Option>
<Select.Option value={5}></Select.Option>
<Select.Option value={6}></Select.Option>
<Select.Option value={7}></Select.Option>
<Select.Option value={8}></Select.Option>
<Select.Option value={9}>K2</Select.Option>
<Select.Option value={10}>K3</Select.Option>
</Select>
</Form.Item>
<Form.Item
name="count"
label="最大授权用户数"
initialValue={100}
>
<InputNumber min={1} placeholder="应用最大可以授权多少个用户" />
</Form.Item>
<Form.Item
name="auth_url"
label="应用授权链接"
>
<Input placeholder="请输入应用授权链接" />
</Form.Item>
<Form.Item
name="company"
label="应用归属公司名称"
rules={[{ max: 256, message: '公司名称不能超过256个字符' }]}
>
<Input placeholder="请输入应用归属公司名称" />
</Form.Item>
</Form>
</Modal>
<Modal
title="授权应用详情"
open={detailModalVisible}
onCancel={() => {
setDetailModalVisible(false);
setCurrentApp(null);
}}
okText="关闭"
cancelText="取消"
width={600}
>
{currentApp && (
<div style={{ lineHeight: '2' }}>
<p><strong>ID:</strong> {currentApp.id}</p>
<p><strong>ID:</strong> {currentApp.appId}</p>
<p><strong>:</strong> {currentApp.secret}</p>
<p><strong>:</strong> {(() => {
const typeMap: Record<number, string> = {
1: '千川', 2: '广告', 3: '本地推', 4: '星图', 5: '快手代理商',
6: '巨量星图', 7: '巨量服务单', 8: '腾讯服务单', 9: '腾讯营销K2', 10: '腾讯营销K3'
};
return typeMap[currentApp.openType] || currentApp.openType;
})()}</p>
<p><strong>:</strong> {currentApp.company || '-'}</p>
<p><strong>:</strong> {currentApp.count}</p>
<p><strong>:</strong> {currentApp.status === 1 ? '正常' : '禁用'}</p>
<p><strong>URL:</strong> {currentApp.authUrl || '-'}</p>
<p><strong>:</strong> {currentApp.createBy}</p>
<p><strong>:</strong> {formatDate(currentApp.createdAt)}</p>
<p><strong>:</strong> {formatDate(currentApp.updatedAt)}</p>
</div>
)}
</Modal>
<Modal
title="更新授权应用"
open={updateModalVisible}
onOk={handleSaveUpdate}
onCancel={() => {
setUpdateModalVisible(false);
updateForm.resetFields();
setCurrentApp(null);
}}
okText="更新"
cancelText="取消"
width={600}
>
<Form form={updateForm} layout="vertical">
<Form.Item
name="app_id"
label="应用ID"
rules={[{ required: true, message: '请输入应用ID' }, { max: 64, message: '应用ID不能超过64个字符' }]}
>
<Input placeholder="请输入应用ID" />
</Form.Item>
<Form.Item
name="secret"
label="应用密钥"
rules={[{ required: true, message: '请输入应用密钥' }, { max: 256, message: '应用密钥不能超过256个字符' }]}
>
<Input placeholder="请输入应用密钥" />
</Form.Item>
<Form.Item
name="open_type"
label="开户方式"
rules={[{ required: true, message: '请选择开户方式' }]}
>
<Select placeholder="请选择开户方式">
<Select.Option value={1}></Select.Option>
<Select.Option value={2}>广</Select.Option>
<Select.Option value={3}></Select.Option>
<Select.Option value={4}></Select.Option>
<Select.Option value={5}></Select.Option>
<Select.Option value={6}></Select.Option>
<Select.Option value={7}></Select.Option>
<Select.Option value={8}></Select.Option>
<Select.Option value={9}>K2</Select.Option>
<Select.Option value={10}>K3</Select.Option>
</Select>
</Form.Item>
<Form.Item
name="count"
label="最大授权用户数"
>
<InputNumber min={1} placeholder="应用最大可以授权多少个用户" />
</Form.Item>
<Form.Item
name="auth_url"
label="应用授权链接"
>
<Input placeholder="请输入应用授权链接" />
</Form.Item>
<Form.Item
name="company"
label="应用归属公司名称"
rules={[{ max: 256, message: '公司名称不能超过256个字符' }]}
>
<Input placeholder="请输入应用归属公司名称" />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default AdminOauthAppList;
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/app.tsx","./src/env.d.ts","./src/main.tsx","./src/api/client.ts","./src/api/crypto.ts","./src/api/index.ts","./src/pages/admincreditratios.tsx","./src/pages/admincreditrecords.tsx","./src/pages/admindashboard.tsx","./src/pages/admingenerationrecords.tsx","./src/pages/adminimageengines.tsx","./src/pages/adminindustries.tsx","./src/pages/adminlayout.tsx","./src/pages/adminloginpage.tsx","./src/pages/adminmenuconfig.tsx","./src/pages/adminmodels.tsx","./src/pages/adminnotificationmanager.tsx","./src/pages/adminoperationlogs.tsx","./src/pages/adminpaymentconfig.tsx","./src/pages/adminrechargepackages.tsx","./src/pages/adminsettings.tsx","./src/pages/adminusers.tsx","./src/pages/adminvideoengines.tsx","./src/store/index.ts","./src/types/index.ts","./src/utils/formatdate.ts"],"version":"6.0.3"}
{"root":["./src/app.tsx","./src/env.d.ts","./src/main.tsx","./src/api/client.ts","./src/api/crypto.ts","./src/api/index.ts","./src/pages/admincreditratios.tsx","./src/pages/admincreditrecords.tsx","./src/pages/admindashboard.tsx","./src/pages/admingenerationairecords.tsx","./src/pages/admingenerationrecords.tsx","./src/pages/adminimageengines.tsx","./src/pages/adminindustries.tsx","./src/pages/adminlayout.tsx","./src/pages/adminloginpage.tsx","./src/pages/adminmenuconfig.tsx","./src/pages/adminmodels.tsx","./src/pages/adminnotificationmanager.tsx","./src/pages/adminoauthapplist.tsx","./src/pages/adminoperationlogs.tsx","./src/pages/adminpaymentconfig.tsx","./src/pages/adminrechargepackages.tsx","./src/pages/adminsettings.tsx","./src/pages/adminusers.tsx","./src/pages/adminvideoengines.tsx","./src/store/index.ts","./src/types/index.ts","./src/utils/formatdate.ts"],"version":"6.0.3"}
+24 -67
View File
@@ -2,18 +2,14 @@
* API abstraction layer.
* Switches between mock data and real backend based on VITE_USE_MOCK env var.
*/
import { api, setToken, clearToken } from './client';
import * as mock from './mock';
import type {
User, CreditRecord, Project, GenerationRecord, OptimizeParams, GenerateParams, OptimizeResult,
Industry, IndustryConfig, AdminUser, AdminStats, ModelConfig, SystemConfig, AdminNotification,
} from '../types';
const USE_MOCK = import.meta.env.VITE_USE_MOCK === 'true';
// ── Auth ──────────────────────────────────────────────────
export async function login(username: string, password: string, captchaToken?: string, rememberMe?: boolean): Promise<User> {
if (USE_MOCK) return mock.mockLogin({ username, password });
const res = await api.post<{ accessToken: string; user: User }>('/auth/login', { username, password, captcha_token: captchaToken, remember_me: rememberMe || false }, false);
@@ -26,19 +22,16 @@ export async function phonelogin(phone: string, code: string): Promise<User> {
setToken(res.accessToken);
return res.user;
}
export async function register(phone: string, code: string, password: string): Promise<User> {
const res = await api.post<{ accessToken: string; user: User }>('/auth/register', { phone, code, password }, false);
setToken(res.accessToken);
return res.user;
}
export async function logout(): Promise<void> {
if (USE_MOCK) return mock.mockLogout();
await api.post('/auth/logout');
clearToken();
}
export async function getUser(): Promise<User | null> {
if (USE_MOCK) return mock.mockGetUser();
try {
@@ -47,38 +40,30 @@ export async function getUser(): Promise<User | null> {
return null;
}
}
export async function changePassword(oldPwd: string, newPwd: string): Promise<void> {
if (USE_MOCK) return;
await api.post('/auth/change-password', { old_password: oldPwd, new_password: newPwd });
}
// ── Projects ──────────────────────────────────────────────
export async function getProjects(): Promise<Project[]> {
if (USE_MOCK) return mock.mockGetProjects();
return api.get<Project[]>('/projects');
}
export async function createProject(name: string, industry: Industry): Promise<Project> {
if (USE_MOCK) return mock.mockCreateProject(name, industry);
return api.post<Project>('/projects', { name, industry });
}
export async function deleteProject(id: string): Promise<void> {
if (USE_MOCK) return mock.mockDeleteProject(id);
await api.delete(`/projects/${id}`);
}
// ── Generation ────────────────────────────────────────────
export interface GenerationRecordPageListOut {
page: number;
pageSize: number;
total: number;
items: GenerationRecord[];
}
export interface GetRecordsPageParams {
projectId?: string;
status?: string;
@@ -86,7 +71,6 @@ export interface GetRecordsPageParams {
pageSize?: number;
signal?: AbortSignal;
}
export async function getRecordsPage(params: GetRecordsPageParams = {}): Promise<GenerationRecordPageListOut> {
const page = params.page && params.page > 0 ? params.page : 1;
const pageSize = params.pageSize && params.pageSize > 0 ? params.pageSize : 10;
@@ -105,7 +89,6 @@ export async function getRecordsPage(params: GetRecordsPageParams = {}): Promise
items: filtered.slice(start, start + pageSize),
};
}
const query = new URLSearchParams();
if (params.projectId) query.set('project_id', params.projectId);
if (params.status) query.set('status', params.status);
@@ -114,7 +97,6 @@ export async function getRecordsPage(params: GetRecordsPageParams = {}): Promise
return api.get<GenerationRecordPageListOut>(`/generation-records?${query.toString()}`, { signal: params.signal });
}
export async function optimizePrompt(
projectId: string, params: OptimizeParams
): Promise<OptimizeResult> {
@@ -131,7 +113,6 @@ export async function optimizePrompt(
image_px: params.image_px || null,
});
}
export async function uploadImage(file: File): Promise<{ url: string; filename: string }> {
const form = new FormData();
form.append('file', file);
@@ -145,7 +126,6 @@ export async function uploadImage(file: File): Promise<{ url: string; filename:
const data = await res.json();
return { url: data.url, filename: data.filename };
}
export async function uploadVideo(file: File): Promise<{ url: string; filename: string }> {
const form = new FormData();
form.append('file', file);
@@ -159,15 +139,12 @@ export async function uploadVideo(file: File): Promise<{ url: string; filename:
const data = await res.json();
return { url: data.url, filename: data.filename };
}
export async function deleteUpload(url: string): Promise<void> {
await api.post(`/generation-records/delete-file?url=${encodeURIComponent(url)}`);
}
export async function updateRecordPrompt(recordId: string, optimizedPrompt: string): Promise<void> {
await api.put(`/generation-records/${recordId}/prompt`, { optimized_prompt: optimizedPrompt });
}
export async function generateVideo(recordId: string, params: GenerateParams): Promise<GenerationRecord> {
if (USE_MOCK) return mock.mockGenerateVideo(recordId);
return api.post<GenerationRecord>(`/generation-records/${recordId}/generate`, {
@@ -175,36 +152,27 @@ export async function generateVideo(recordId: string, params: GenerateParams): P
resolution: params.resolution,
});
}
// ── Credits ───────────────────────────────────────────────
export async function getCredits(): Promise<{ credits: number; records: CreditRecord[] }> {
if (USE_MOCK) return mock.mockGetCredits();
return api.get('/credits');
}
// ── Captcha ───────────────────────────────────────────────
export async function getSliderCaptcha(): Promise<{ captcha_id: string; bg_image: string; slider_image: string }> {
if (USE_MOCK) return { captcha_id: 'mock', bg_image: '', slider_image: '' };
return api.get('/captcha/slider', false);
}
export async function verifyCaptcha(captchaId: string, x: number): Promise<string> {
if (USE_MOCK) return 'mock-token';
const res = await api.post<{ token: string }>('/captcha/verify', { captcha_id: captchaId, x_offset: x }, false);
return res.token;
}
// ── Site Info ─────────────────────────────────────────────
export async function getSiteInfo(): Promise<{ siteName: string; siteLogo: string; userAgreementUrl: string; privacyPolicyUrl: string }> {
if (USE_MOCK) return { siteName: 'VideoGen.AI', siteLogo: '', userAgreementUrl: '', privacyPolicyUrl: '' };
return api.get('/auth/site-info', false);
}
// ── Video Engines ─────────────────────────────────────────
export async function getVideoEngines(): Promise<{ items: { id: string; name: string; provider: string; supportedRatios: string[]; supportedResolutions: string[]; supportedDurations: number[] }[] }> {
if (USE_MOCK) return { items: [{ id: 'mock', name: 'Seedance', provider: 'seedance', supportedRatios: ['16:9', '9:16', '1:1', '4:3', '3:4', '21:9'], supportedResolutions: ['480p', '720p', '1080p'], supportedDurations: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] }] };
return api.get('/video-engines');
@@ -213,89 +181,69 @@ export async function getVideoEngines(): Promise<{ items: { id: string; name: st
export async function getParameters(): Promise<any[]> {
return api.get('/image-engines');
}
// ── SMS ───────────────────────────────────────────────────
export async function sendSms(phone: string, scene: string): Promise<void> {
if (USE_MOCK) return;
await api.post('/sms/send', { phone, scene: scene }, false);
}
export async function verifySms(phone: string, code: string): Promise<{ token: string }> {
if (USE_MOCK) return { token: 'mock-sms-token' };
return api.post('/sms/verify', { phone, code }, false);
}
// ── Notifications ─────────────────────────────────────────
export async function getNotifications(): Promise<AdminNotification[]> {
if (USE_MOCK) return mock.mockGetAdminNotifications();
return api.get('/notifications');
}
export async function getUnreadCount(): Promise<number> {
if (USE_MOCK) return mock.mockGetAdminNotifications().then(n => n.filter(x => !x.isRead).length);
const res = await api.get<{ count: number }>('/notifications/unread-count');
return res.count;
}
export async function markNotificationRead(id: string): Promise<void> {
if (USE_MOCK) return;
await api.put(`/notifications/${id}/read`);
}
// ── Admin ─────────────────────────────────────────────────
export async function getAdminStats(): Promise<AdminStats> {
if (USE_MOCK) return mock.mockGetAdminStats();
return api.get('/admin/stats');
}
export async function getAdminUsers(search?: string): Promise<AdminUser[]> {
if (USE_MOCK) return mock.mockGetAdminUsers(search);
const q = search ? `?search=${encodeURIComponent(search)}` : '';
return api.get(`/admin/users${q}`);
}
export async function adjustCredits(userId: string, amount: number, description: string): Promise<void> {
if (USE_MOCK) return mock.mockAdjustCredits(userId, amount, description);
await api.post(`/admin/users/${userId}/credits`, { amount, description });
}
export async function toggleUserStatus(userId: string, isActive: boolean): Promise<void> {
if (USE_MOCK) return mock.mockToggleUserStatus(userId, isActive);
await api.put(`/admin/users/${userId}/status`, { is_active: isActive });
}
export async function getModelConfigs(): Promise<ModelConfig[]> {
if (USE_MOCK) return mock.mockGetModelConfigs();
return api.get('/admin/model-configs');
}
export async function saveModelConfig(config: Partial<ModelConfig> & { id?: string }): Promise<ModelConfig> {
if (USE_MOCK) return mock.mockSaveModelConfig(config as any);
if (config.id) return api.put(`/admin/model-configs/${config.id}`, config);
return api.post('/admin/model-configs', config);
}
export async function deleteModelConfig(id: string): Promise<void> {
if (USE_MOCK) return mock.mockDeleteModelConfig(id);
await api.delete(`/admin/model-configs/${id}`);
}
export async function getSystemConfigs(): Promise<SystemConfig[]> {
if (USE_MOCK) return mock.mockGetSystemConfigs();
return api.get('/admin/system-configs');
}
export async function updateSystemConfig(id: string, value: string): Promise<void> {
if (USE_MOCK) return mock.mockUpdateSystemConfig(id, value);
await api.put(`/admin/system-configs/${id}`, { value });
}
// ── Industries ─────────────────────────────────────────────
export async function getIndustries(): Promise<IndustryConfig[]> {
const data = await api.get<any[]>('/industries');
return data.map((item: any) => {
@@ -306,20 +254,14 @@ export async function getIndustries(): Promise<IndustryConfig[]> {
return { ...item, optionGroups };
});
}
// ── Menu Config ────────────────────────────────────────────
export async function getMenuConfigs(): Promise<any[]> {
return api.get('/menu-configs');
}
// ── Recharge Packages ──────────────────────────────────────
export async function getRechargePackages(): Promise<any[]> {
return api.get('/recharge-packages');
}
export async function getCreditRatios(): Promise<any[]> {
return api.get('/credits/ratios');
}
@@ -327,10 +269,7 @@ export async function getCreditRatios(): Promise<any[]> {
export async function getEngine(): Promise<any[]> {
return api.get('/generation-ai/engines');
}
// ── Generation AI Tasks ────────────────────────────────────
// 创建ai生成任务
export async function createGenerationTask(params: any): Promise<any> {
return api.post('/generation-ai/tasks', params);
@@ -347,20 +286,38 @@ export async function gethistory(Pagebreak: any): Promise<any[]> {
export async function gethistoryItems(Pagebreak: any): Promise<any[]> {
return api.get('/generation-ai/history/'+Pagebreak);
}
// 删除ai对话历史记录
export async function deleteHistory(id: string): Promise<void> {
await api.delete(`/generation-ai/tasks/${id}`);
}
export async function calculateCredits(): Promise<any[]> {
return api.get('/credits/credit-ratios');
}
// 获取验证码
export async function getSendcode(phone: string): Promise<any> {
return api.post('/sms/send', { phone });
}
export interface OAuthAppParam {
page: number;
pageSize: number;
open_type?: string;
status?: string;
app_id?: string;
}
export interface OAuthAppList {
page: number;
pageSize: number;
total: number;
data: any[];
}
// 获取用户列表
export async function getAuthorizationList(params: OAuthAppParam): Promise<OAuthAppList> {
const query = new URLSearchParams();
query.set('page', String(params.page));
query.set('page_size', String(params.pageSize));
if (params.open_type) query.set('open_type', params.open_type);
if (params.status) query.set('status', params.status);
if (params.app_id) query.set('app_id', params.app_id);
return api.get<OAuthAppList>(`/admin/user-oauth-apps/list?${query.toString()}`);
}
+118 -62
View File
@@ -1,12 +1,16 @@
import React, { useEffect, useState, useLayoutEffect, useRef, useCallback } from 'react';
import { Button, Table, Checkbox, Tag, Space, message, Modal } from 'antd';
import { PlusOutlined, CheckCircleOutlined, ClockCircleOutlined, CiCircleOutlined, EyeOutlined, XOutlined } from '@ant-design/icons';
// 模拟授权数据
const mockAuthorizations = [
{ id: '1867060028363785', status: 'active', description: '用户张三的API授权' },
{ id: '1867059757929740', status: 'pending', description: '用户李四的API授权' },
{ id: '1867059808785418', status: 'active', description: '用户王五的API授权' },
];
import type { OAuthAppParam } from '../api/index';
import { getAuthorizationList } from '../api/index';
// 授权数据类型
interface AuthorizationData {
id: string;
status: string;
description: string;
}
// 状态配置
const statusConfig = {
active: { label: '已授权', color: 'green', icon: CheckCircleOutlined },
@@ -30,12 +34,60 @@ const consumptionTypeConfig = {
audio: { label: '音频转换', color: 'purple' },
image: { label: '图片处理', color: 'green' },
};
// 模拟表头接口返回数据
const mockTableHeaderResponse = {
code: 200,
message: 'success',
data: [
{ title: '序号', dataIndex: 'index', key: 'index', width: 80, fixed: 'left' },
{ title: '消耗ID', dataIndex: 'id', key: 'id', ellipsis: true },
{ title: '授权ID', dataIndex: 'authorizationId', key: 'authorizationId', ellipsis: true },
{ title: '消耗类型', dataIndex: 'type', key: 'type', width: 120 },
{ title: '消耗金额', dataIndex: 'amount', key: 'amount', width: 120 },
{ title: '消耗描述', dataIndex: 'description', key: 'description', ellipsis: true },
{ title: '消耗时间', dataIndex: 'createdAt', key: 'createdAt', width: 160, fixed: 'right' },
],
};
// 模拟获取表头接口
const fetchTableHeader = () => {
return new Promise<typeof mockTableHeaderResponse>((resolve) => {
setTimeout(() => {
resolve(mockTableHeaderResponse);
}, 500);
});
};
const AuthorizationPage: React.FC = () => {
const [authorizations, setAuthorizations] = useState(mockAuthorizations);
const [authorizations, setAuthorizations] = useState<AuthorizationData[]>([]);
const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
const [loading, setLoading] = useState(false);
const [listLoading, setListLoading] = useState(false);
const [showConsumptionModal, setShowConsumptionModal] = useState(false);
const [consumptionRecords, setConsumptionRecords] = useState(mockConsumptionRecords);
const [consumptionColumns, setConsumptionColumns] = useState<typeof mockTableHeaderResponse['data']>([]);
const [headerLoading, setHeaderLoading] = useState(false);
// 页面初始化时获取授权列表
useEffect(() => {
const loadData = async () => {
setListLoading(true);
try {
const params: OAuthAppParam = {
page: 1,
pageSize: 10,
};
const response = await getAuthorizationList(params);
setAuthorizations(response.data || []);
} catch (error) {
message.error('获取授权列表失败');
} finally {
setListLoading(false);
}
};
loadData();
}, []);
// 状态标签渲染
const renderStatus = (status: string) => {
@@ -97,7 +149,7 @@ const AuthorizationPage: React.FC = () => {
dataIndex: 'operation',
key: 'operation',
width: 120,
render: (_: any, record: typeof mockAuthorizations[0]) => (
render: (_: any, record: AuthorizationData) => (
<Button
type="primary"
size="small"
@@ -106,7 +158,7 @@ const AuthorizationPage: React.FC = () => {
// background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
border: 'none',
}}
onClick={() => setShowConsumptionModal(true)}
onClick={handleOpenConsumptionModal}
>
</Button>
@@ -114,6 +166,60 @@ const AuthorizationPage: React.FC = () => {
}
];
// 获取表头数据
const handleFetchHeader = async () => {
setHeaderLoading(true);
try {
const response = await fetchTableHeader();
if (response.code === 200) {
// 对特定列添加render函数
const columnsWithRender = response.data.map(col => {
if (col.dataIndex === 'index') {
return {
...col,
render: (text: number) => <span style={{ color: '#94a3b8' }}>{text}</span>,
};
}
if (col.dataIndex === 'id') {
return {
...col,
render: (text: string) => <span style={{ fontWeight: 500, color: '#1e293b' }}>{text}</span>,
};
}
if (col.dataIndex === 'type') {
return {
...col,
render: (text: string) => {
const config = consumptionTypeConfig[text as keyof typeof consumptionTypeConfig];
return <Tag color={config?.color}>{config?.label}</Tag>;
},
};
}
if (col.dataIndex === 'amount') {
return {
...col,
render: (text: number) => <span style={{ color: '#ef4444', fontWeight: 500 }}>{text} </span>,
};
}
return col;
});
setConsumptionColumns(columnsWithRender);
} else {
message.error(response.message);
}
} catch (error) {
message.error('获取表头失败');
} finally {
setHeaderLoading(false);
}
};
// 打开消耗弹窗
const handleOpenConsumptionModal = () => {
setShowConsumptionModal(true);
handleFetchHeader();
};
// 处理点击授权按钮
const handleAuthorize = () => {
if (selectedRowKeys.length === 0) {
@@ -134,14 +240,12 @@ const AuthorizationPage: React.FC = () => {
}, 800);
};
// 准备表格数据(添加序号)
const tableData = authorizations.map((item, index) => ({
...item,
index: index + 1,
key: item.id,
}));
// 准备消耗记录表格数据(添加序号)
const consumptionTableData = consumptionRecords.map((item, index) => ({
...item,
index: index + 1,
@@ -184,6 +288,7 @@ const AuthorizationPage: React.FC = () => {
<Table
dataSource={tableData}
columns={columns}
loading={listLoading}
pagination={{
pageSize: 10,
showSizeChanger: true,
@@ -213,57 +318,8 @@ const AuthorizationPage: React.FC = () => {
<div style={{ padding: 16 }}>
<Table
dataSource={consumptionTableData}
columns={[
{
title: '序号',
dataIndex: 'index',
key: 'index',
width: 80,
render: (text: number) => <span style={{ color: '#94a3b8' }}>{text}</span>,
},
{
title: '消耗ID',
dataIndex: 'id',
key: 'id',
ellipsis: true,
render: (text: string) => <span style={{ fontWeight: 500, color: '#1e293b' }}>{text}</span>,
},
{
title: '授权ID',
dataIndex: 'authorizationId',
key: 'authorizationId',
ellipsis: true,
},
{
title: '消耗类型',
dataIndex: 'type',
key: 'type',
width: 120,
render: (text: string) => {
const config = consumptionTypeConfig[text as keyof typeof consumptionTypeConfig];
return <Tag color={config?.color}>{config?.label}</Tag>;
},
},
{
title: '消耗金额',
dataIndex: 'amount',
key: 'amount',
width: 120,
render: (text: number) => <span style={{ color: '#ef4444', fontWeight: 500 }}>{text} </span>,
},
{
title: '消耗描述',
dataIndex: 'description',
key: 'description',
ellipsis: true,
},
{
title: '消耗时间',
dataIndex: 'createdAt',
key: 'createdAt',
width: 160,
},
]}
columns={consumptionColumns}
loading={headerLoading}
pagination={{
pageSize: 10,
showSizeChanger: true,