Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useContext, useEffect, useState } from 'react';
|
||||
import { API, getSystemName, showError } from '../../helpers';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { marked } from 'marked';
|
||||
import { Empty } from '@douyinfe/semi-ui';
|
||||
import {
|
||||
IllustrationConstruction,
|
||||
IllustrationConstructionDark,
|
||||
} from '../../components/common/illustrations';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const About = () => {
|
||||
const { t } = useTranslation();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const [about, setAbout] = useState('');
|
||||
const [aboutLoaded, setAboutLoaded] = useState(false);
|
||||
const currentYear = new Date().getFullYear();
|
||||
const officialWebsite = (statusState?.status?.official_website || '').trim();
|
||||
const systemName = getSystemName();
|
||||
|
||||
const displayAbout = async () => {
|
||||
setAbout(localStorage.getItem('about') || '');
|
||||
const res = await API.get('/api/about');
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
let aboutContent = data;
|
||||
if (!data.startsWith('https://')) {
|
||||
aboutContent = marked.parse(data);
|
||||
}
|
||||
setAbout(aboutContent);
|
||||
localStorage.setItem('about', aboutContent);
|
||||
} else {
|
||||
showError(message);
|
||||
setAbout(t('加载关于内容失败...'));
|
||||
}
|
||||
setAboutLoaded(true);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
displayAbout().then();
|
||||
}, []);
|
||||
|
||||
const emptyStyle = {
|
||||
padding: '24px',
|
||||
};
|
||||
|
||||
const customDescription = (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<p>{t('可在设置页面设置关于内容,支持 HTML & Markdown')}</p>
|
||||
{officialWebsite && (
|
||||
<>
|
||||
{t('官网:')}
|
||||
<a
|
||||
href={officialWebsite}
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='!text-semi-color-primary'
|
||||
>
|
||||
{officialWebsite}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
<p>
|
||||
{officialWebsite ? (
|
||||
<a
|
||||
href={officialWebsite}
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='!text-semi-color-primary'
|
||||
>
|
||||
{systemName}
|
||||
</a>
|
||||
) : (
|
||||
systemName
|
||||
)}{' '}
|
||||
{t('© {{currentYear}}', { currentYear })}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className='mt-[60px] px-2'>
|
||||
{aboutLoaded && about === '' ? (
|
||||
<div className='flex justify-center items-center h-screen p-8'>
|
||||
<Empty
|
||||
image={
|
||||
<IllustrationConstruction style={{ width: 150, height: 150 }} />
|
||||
}
|
||||
darkModeImage={
|
||||
<IllustrationConstructionDark
|
||||
style={{ width: 150, height: 150 }}
|
||||
/>
|
||||
}
|
||||
description={t('管理员暂时未设置任何关于内容')}
|
||||
style={emptyStyle}
|
||||
>
|
||||
{customDescription}
|
||||
</Empty>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{about.startsWith('https://') ? (
|
||||
<iframe
|
||||
src={about}
|
||||
style={{ width: '100%', height: '100vh', border: 'none' }}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
style={{ fontSize: 'larger' }}
|
||||
dangerouslySetInnerHTML={{ __html: about }}
|
||||
></div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default About;
|
||||
@@ -0,0 +1,604 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Input,
|
||||
Tag,
|
||||
Select,
|
||||
Modal,
|
||||
TextArea,
|
||||
Spin,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { Receipt, Search, Eye, Check, X, RotateCw, Ban } from 'lucide-react';
|
||||
import { API, showError, showSuccess } from '../../helpers';
|
||||
import {
|
||||
INVOICE_STATUS,
|
||||
INVOICE_STATUS_TEXT,
|
||||
INVOICE_STATUS_COLOR,
|
||||
} from '../../constants';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const paymentMethodMap = {
|
||||
wechat: '微信',
|
||||
alipay: '支付宝',
|
||||
stripe: 'Stripe',
|
||||
creem: 'Creem',
|
||||
epay: '易支付',
|
||||
};
|
||||
|
||||
const AdminInvoice = () => {
|
||||
const { t } = useTranslation();
|
||||
const [invoices, setInvoices] = useState([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [searchKeyword, setSearchKeyword] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
|
||||
// 详情弹窗
|
||||
const [detailVisible, setDetailVisible] = useState(false);
|
||||
const [detailData, setDetailData] = useState(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
|
||||
// 拒绝弹窗
|
||||
const [rejectVisible, setRejectVisible] = useState(false);
|
||||
const [rejectId, setRejectId] = useState(null);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [rejectLoading, setRejectLoading] = useState(false);
|
||||
|
||||
// 审核通过弹窗
|
||||
const [approveVisible, setApproveVisible] = useState(false);
|
||||
const [approveId, setApproveId] = useState(null);
|
||||
const [adminRemark, setAdminRemark] = useState('');
|
||||
const [approveLoading, setApproveLoading] = useState(false);
|
||||
|
||||
const fetchInvoices = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = { p: page, page_size: 20 };
|
||||
if (searchKeyword) params.keyword = searchKeyword;
|
||||
if (statusFilter) params.status = statusFilter;
|
||||
const res = await API.get('/api/invoice/list', { params });
|
||||
if (res.data.success) {
|
||||
setInvoices(res.data.data?.items || []);
|
||||
setTotal(res.data.data?.total || 0);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [page, searchKeyword, statusFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchInvoices();
|
||||
}, [fetchInvoices]);
|
||||
|
||||
const handleSearch = () => {
|
||||
setPage(1);
|
||||
setSearchKeyword(keyword);
|
||||
};
|
||||
|
||||
const handleStatusFilterChange = (value) => {
|
||||
setPage(1);
|
||||
setStatusFilter(value || '');
|
||||
};
|
||||
|
||||
// 查看详情
|
||||
const handleViewDetail = async (id) => {
|
||||
setDetailData(null);
|
||||
setDetailVisible(true);
|
||||
setDetailLoading(true);
|
||||
try {
|
||||
const res = await API.get(`/api/invoice/detail/${id}`);
|
||||
if (res.data.success) {
|
||||
setDetailData(res.data.data);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
setDetailVisible(false);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
setDetailVisible(false);
|
||||
} finally {
|
||||
setDetailLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 审核通过
|
||||
const handleApprove = async () => {
|
||||
setApproveLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/invoice/approve', {
|
||||
id: approveId,
|
||||
admin_remark: adminRemark,
|
||||
});
|
||||
if (res.data.success) {
|
||||
showSuccess(t('审核通过'));
|
||||
setApproveVisible(false);
|
||||
setApproveId(null);
|
||||
setAdminRemark('');
|
||||
fetchInvoices();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setApproveLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 拒绝
|
||||
const handleReject = async () => {
|
||||
if (!rejectReason.trim()) {
|
||||
showError(t('请填写拒绝理由'));
|
||||
return;
|
||||
}
|
||||
setRejectLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/invoice/reject', {
|
||||
id: rejectId,
|
||||
reject_reason: rejectReason.trim(),
|
||||
});
|
||||
if (res.data.success) {
|
||||
showSuccess(t('已拒绝'));
|
||||
setRejectVisible(false);
|
||||
setRejectId(null);
|
||||
setRejectReason('');
|
||||
fetchInvoices();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setRejectLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 重试开票
|
||||
const handleRetry = async (id) => {
|
||||
try {
|
||||
const res = await API.post('/api/invoice/retry', { id });
|
||||
if (res.data.success) {
|
||||
showSuccess(t('已重新发起开票'));
|
||||
fetchInvoices();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
// 取消失败订单
|
||||
const handleFailCancel = async (id) => {
|
||||
Modal.confirm({
|
||||
title: t('确认取消'),
|
||||
content: t('取消后关联的充值记录将被释放,用户可重新申请开票。'),
|
||||
onOk: async () => {
|
||||
try {
|
||||
const res = await API.post('/api/invoice/fail-cancel', { id });
|
||||
if (res.data.success) {
|
||||
showSuccess(t('已取消'));
|
||||
fetchInvoices();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const formatTime = (timestamp) => {
|
||||
if (!timestamp) return '-';
|
||||
return new Date(timestamp * 1000).toLocaleString();
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{
|
||||
title: t('用户'),
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
render: (_, record) => {
|
||||
const displayName = record.display_name || '';
|
||||
const username = record.username || '';
|
||||
if (displayName && username) {
|
||||
return (
|
||||
<span title={`${displayName} (${username})`}>
|
||||
{displayName}{' '}
|
||||
<span className='text-xs text-gray-400'>({username})</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
displayName ||
|
||||
username || (
|
||||
<span className='text-gray-400'>User#{record.user_id}</span>
|
||||
)
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('发票抬头'),
|
||||
dataIndex: 'invoice_title',
|
||||
width: 160,
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: t('税号'),
|
||||
dataIndex: 'tax_id',
|
||||
width: 140,
|
||||
ellipsis: true,
|
||||
render: (text) => <span className='font-mono text-xs'>{text}</span>,
|
||||
},
|
||||
{
|
||||
title: t('金额'),
|
||||
dataIndex: 'amount',
|
||||
width: 90,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (status) => (
|
||||
<Tag color={INVOICE_STATUS_COLOR[status] || 'grey'}>
|
||||
{t(INVOICE_STATUS_TEXT[status] || '未知')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('申请时间'),
|
||||
dataIndex: 'create_time',
|
||||
width: 150,
|
||||
render: (v) => formatTime(v),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 200,
|
||||
fixed: 'right',
|
||||
render: (_, record) => (
|
||||
<div className='flex items-center gap-1 flex-wrap'>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
icon={<Eye size={14} />}
|
||||
onClick={() => handleViewDetail(record.id)}
|
||||
/>
|
||||
{record.status === INVOICE_STATUS.PENDING && (
|
||||
<>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
type='primary'
|
||||
icon={<Check size={14} />}
|
||||
onClick={() => {
|
||||
setApproveId(record.id);
|
||||
setApproveVisible(true);
|
||||
}}
|
||||
>
|
||||
{t('通过')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
type='danger'
|
||||
icon={<X size={14} />}
|
||||
onClick={() => {
|
||||
setRejectId(record.id);
|
||||
setRejectVisible(true);
|
||||
}}
|
||||
>
|
||||
{t('拒绝')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{(record.status === INVOICE_STATUS.APPROVED ||
|
||||
record.status === INVOICE_STATUS.INVOICING) && (
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
type='danger'
|
||||
icon={<Ban size={14} />}
|
||||
onClick={() => handleFailCancel(record.id)}
|
||||
>
|
||||
{t('取消')}
|
||||
</Button>
|
||||
)}
|
||||
{record.status === INVOICE_STATUS.FAILED && (
|
||||
<>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
icon={<RotateCw size={14} />}
|
||||
onClick={() => handleRetry(record.id)}
|
||||
>
|
||||
{t('重试')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
type='danger'
|
||||
icon={<Ban size={14} />}
|
||||
onClick={() => handleFailCancel(record.id)}
|
||||
>
|
||||
{t('取消')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='mt-[60px] p-4 sm:p-6'>
|
||||
{/* 筛选区:标题与筛选项同行 */}
|
||||
<div className='flex flex-wrap items-center gap-2 mb-4'>
|
||||
<div className='flex items-center gap-1.5 mr-2 flex-shrink-0'>
|
||||
<Receipt size={18} className='text-amber-500' />
|
||||
<span className='text-base font-bold text-gray-900 dark:text-white'>
|
||||
{t('发票管理')}
|
||||
</span>
|
||||
</div>
|
||||
<Input
|
||||
prefix={<Search size={14} />}
|
||||
placeholder={t('搜索抬头/税号/订单号/用户')}
|
||||
value={keyword}
|
||||
onChange={setKeyword}
|
||||
onEnterPress={handleSearch}
|
||||
style={{ width: 240 }}
|
||||
/>
|
||||
<Select
|
||||
placeholder={t('状态')}
|
||||
value={statusFilter || undefined}
|
||||
onChange={handleStatusFilterChange}
|
||||
style={{ width: 120 }}
|
||||
allowClear
|
||||
optionList={[
|
||||
{ label: t('待审核'), value: '1' },
|
||||
{ label: t('审核通过'), value: '2' },
|
||||
{ label: t('已拒绝'), value: '3' },
|
||||
{ label: t('开票中'), value: '4' },
|
||||
{ label: t('已开票'), value: '5' },
|
||||
{ label: t('已取消'), value: '6' },
|
||||
{ label: t('开票失败'), value: '7' },
|
||||
]}
|
||||
/>
|
||||
<Button theme='solid' type='primary' onClick={handleSearch}>
|
||||
{t('搜索')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 表格 */}
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={invoices}
|
||||
loading={loading}
|
||||
rowKey='id'
|
||||
pagination={{
|
||||
currentPage: page,
|
||||
total,
|
||||
pageSize: 20,
|
||||
onPageChange: setPage,
|
||||
showTotal: true,
|
||||
}}
|
||||
scroll={{ x: 1100 }}
|
||||
size='small'
|
||||
empty={t('暂无发票数据')}
|
||||
/>
|
||||
|
||||
{/* 审核通过弹窗 */}
|
||||
<Modal
|
||||
title={t('审核通过')}
|
||||
visible={approveVisible}
|
||||
onCancel={() => {
|
||||
setApproveVisible(false);
|
||||
setApproveId(null);
|
||||
setAdminRemark('');
|
||||
}}
|
||||
onOk={handleApprove}
|
||||
okText={t('确认通过')}
|
||||
confirmLoading={approveLoading}
|
||||
>
|
||||
<div className='space-y-3'>
|
||||
<Text>{t('确认审核通过此发票申请?')}</Text>
|
||||
<TextArea
|
||||
placeholder={t('管理员备注(选填)')}
|
||||
value={adminRemark}
|
||||
onChange={setAdminRemark}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* 拒绝弹窗 */}
|
||||
<Modal
|
||||
title={t('拒绝发票申请')}
|
||||
visible={rejectVisible}
|
||||
onCancel={() => {
|
||||
setRejectVisible(false);
|
||||
setRejectId(null);
|
||||
setRejectReason('');
|
||||
}}
|
||||
onOk={handleReject}
|
||||
okText={t('确认拒绝')}
|
||||
okButtonProps={{ type: 'danger' }}
|
||||
confirmLoading={rejectLoading}
|
||||
>
|
||||
<TextArea
|
||||
placeholder={t('请填写拒绝理由(必填)')}
|
||||
value={rejectReason}
|
||||
onChange={setRejectReason}
|
||||
rows={3}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
{/* 详情弹窗 */}
|
||||
<Modal
|
||||
title={t('发票详情')}
|
||||
visible={detailVisible}
|
||||
onCancel={() => setDetailVisible(false)}
|
||||
footer={null}
|
||||
width={600}
|
||||
>
|
||||
{detailLoading ? (
|
||||
<div className='flex justify-center py-8'>
|
||||
<Spin />
|
||||
</div>
|
||||
) : detailData ? (
|
||||
<div className='space-y-3'>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('状态')}</Text>
|
||||
<div>
|
||||
<Tag
|
||||
color={INVOICE_STATUS_COLOR[detailData.status] || 'grey'}
|
||||
>
|
||||
{t(INVOICE_STATUS_TEXT[detailData.status] || '未知')}
|
||||
</Tag>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('申请人')}</Text>
|
||||
<div>
|
||||
{detailData.display_name ||
|
||||
detailData.username ||
|
||||
`User#${detailData.user_id}`}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('发票抬头')}</Text>
|
||||
<div className='font-medium'>{detailData.invoice_title}</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('税号')}</Text>
|
||||
<div className='font-mono text-sm'>{detailData.tax_id}</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('开票金额')}</Text>
|
||||
<div className='font-bold text-amber-600'>
|
||||
¥{Number(detailData.amount).toFixed(2)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('收件邮箱')}</Text>
|
||||
<div>{detailData.email}</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('订单号')}</Text>
|
||||
<div className='font-mono text-xs'>{detailData.order_no}</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text className='text-gray-400 text-sm'>{t('申请时间')}</Text>
|
||||
<div>{formatTime(detailData.create_time)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{detailData.invoice_number && (
|
||||
<div className='p-3 bg-green-50 dark:bg-green-900/20 rounded-lg'>
|
||||
<Text className='text-sm text-green-600'>
|
||||
{t('发票号码')}: {detailData.invoice_number}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detailData.reject_reason && (
|
||||
<div className='p-3 bg-red-50 dark:bg-red-900/20 rounded-lg'>
|
||||
<Text className='text-sm text-red-600'>
|
||||
{t('拒绝原因')}: {detailData.reject_reason}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detailData.fail_reason && (
|
||||
<div className='p-3 bg-red-50 dark:bg-red-900/20 rounded-lg'>
|
||||
<Text className='text-sm text-red-600'>
|
||||
{t('失败原因')}: {detailData.fail_reason}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detailData.admin_remark && (
|
||||
<div className='p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg'>
|
||||
<Text className='text-sm text-blue-600'>
|
||||
{t('管理员备注')}: {detailData.admin_remark}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 关联充值记录 */}
|
||||
{detailData.topup_list && detailData.topup_list.length > 0 && (
|
||||
<div>
|
||||
<Text className='text-sm text-gray-500 mb-2 block'>
|
||||
{t('关联充值记录')} ({detailData.topup_list.length} {t('笔')}
|
||||
,{t('合计')} ¥
|
||||
{detailData.topup_list
|
||||
.reduce((s, item) => s + (item.money || 0), 0)
|
||||
.toFixed(2)}
|
||||
)
|
||||
</Text>
|
||||
<Table
|
||||
dataSource={detailData.topup_list}
|
||||
rowKey='id'
|
||||
pagination={false}
|
||||
size='small'
|
||||
columns={[
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{
|
||||
title: t('时间'),
|
||||
dataIndex: 'complete_time',
|
||||
width: 150,
|
||||
render: (v) => formatTime(v),
|
||||
},
|
||||
{
|
||||
title: t('方式'),
|
||||
dataIndex: 'payment_method',
|
||||
width: 80,
|
||||
render: (v) => paymentMethodMap[v] || v,
|
||||
},
|
||||
{
|
||||
title: t('金额'),
|
||||
dataIndex: 'money',
|
||||
width: 90,
|
||||
render: (v) => `¥${Number(v).toFixed(2)}`,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminInvoice;
|
||||
@@ -0,0 +1,457 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useEffect, useState, useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ShoppingCart, Search, Copy, Check } from 'lucide-react';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Input,
|
||||
Tag,
|
||||
Select,
|
||||
Toast,
|
||||
DatePicker,
|
||||
InputNumber,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import { renderQuota } from '../../helpers/render';
|
||||
|
||||
const paymentMethodMap = {
|
||||
wechat: '微信',
|
||||
alipay: '支付宝',
|
||||
stripe: 'Stripe',
|
||||
paypal: 'PayPal',
|
||||
creem: 'Creem',
|
||||
epay: '易支付',
|
||||
};
|
||||
|
||||
const statusColorMap = {
|
||||
pending: 'orange',
|
||||
success: 'green',
|
||||
expired: 'red',
|
||||
};
|
||||
|
||||
const statusTextMap = {
|
||||
pending: '待支付',
|
||||
success: '已完成',
|
||||
expired: '已过期',
|
||||
};
|
||||
|
||||
const payPalSettlementStateMap = {
|
||||
pending: '待回填',
|
||||
complete: '已完整',
|
||||
unavailable: '不可获取',
|
||||
};
|
||||
|
||||
const formatUSDMinor = (value) => {
|
||||
if (value === null || value === undefined) return '-';
|
||||
return `$${(Number(value) / 100).toFixed(2)}`;
|
||||
};
|
||||
|
||||
const AdminOrder = () => {
|
||||
const { t } = useTranslation();
|
||||
const [orders, setOrders] = useState([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [searchKeyword, setSearchKeyword] = useState('');
|
||||
const [orderId, setOrderId] = useState(undefined);
|
||||
const [appliedOrderId, setAppliedOrderId] = useState(undefined);
|
||||
const [userId, setUserId] = useState(undefined);
|
||||
const [appliedUserId, setAppliedUserId] = useState(undefined);
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [copiedId, setCopiedId] = useState(null);
|
||||
const [paymentMethodFilter, setPaymentMethodFilter] = useState('');
|
||||
const [dateRange, setDateRange] = useState(null);
|
||||
const [minMoney, setMinMoney] = useState(undefined);
|
||||
const [maxMoney, setMaxMoney] = useState(undefined);
|
||||
const [appliedMinMoney, setAppliedMinMoney] = useState(undefined);
|
||||
const [appliedMaxMoney, setAppliedMaxMoney] = useState(undefined);
|
||||
|
||||
const fetchOrders = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = { p: page, page_size: 20 };
|
||||
if (searchKeyword) params.keyword = searchKeyword;
|
||||
if (appliedOrderId) params.order_id = appliedOrderId;
|
||||
if (appliedUserId) params.user_id = appliedUserId;
|
||||
if (statusFilter) params.status = statusFilter;
|
||||
if (paymentMethodFilter) params.payment_method = paymentMethodFilter;
|
||||
if (dateRange && dateRange[0])
|
||||
params.start_time = Math.floor(dateRange[0].getTime() / 1000);
|
||||
if (dateRange && dateRange[1])
|
||||
params.end_time = Math.floor(dateRange[1].getTime() / 1000);
|
||||
if (appliedMinMoney !== undefined && appliedMinMoney !== null)
|
||||
params.min_money = appliedMinMoney;
|
||||
if (appliedMaxMoney !== undefined && appliedMaxMoney !== null)
|
||||
params.max_money = appliedMaxMoney;
|
||||
const res = await API.get('/api/order/search', { params });
|
||||
if (res.data.success) {
|
||||
setOrders(res.data.data?.items || []);
|
||||
setTotal(res.data.data?.total || 0);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [
|
||||
page,
|
||||
searchKeyword,
|
||||
appliedOrderId,
|
||||
appliedUserId,
|
||||
statusFilter,
|
||||
paymentMethodFilter,
|
||||
dateRange,
|
||||
appliedMinMoney,
|
||||
appliedMaxMoney,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchOrders();
|
||||
}, [fetchOrders]);
|
||||
|
||||
const handleSearch = () => {
|
||||
const trimmedKeyword = keyword.trim();
|
||||
const normalizedOrderId =
|
||||
orderId && Number(orderId) > 0 ? Math.floor(Number(orderId)) : undefined;
|
||||
const normalizedUserId =
|
||||
userId && Number(userId) > 0 ? Math.floor(Number(userId)) : undefined;
|
||||
const numericKeywordAsOrderId =
|
||||
!normalizedOrderId && /^\d+$/.test(trimmedKeyword)
|
||||
? Number(trimmedKeyword)
|
||||
: undefined;
|
||||
const ignoreNumericKeyword =
|
||||
normalizedOrderId && /^\d+$/.test(trimmedKeyword);
|
||||
setPage(1);
|
||||
setSearchKeyword(
|
||||
numericKeywordAsOrderId || ignoreNumericKeyword ? '' : trimmedKeyword,
|
||||
);
|
||||
setAppliedOrderId(normalizedOrderId || numericKeywordAsOrderId);
|
||||
setAppliedUserId(normalizedUserId);
|
||||
setAppliedMinMoney(minMoney);
|
||||
setAppliedMaxMoney(maxMoney);
|
||||
};
|
||||
|
||||
const handleStatusFilterChange = (value) => {
|
||||
setPage(1);
|
||||
setStatusFilter(value || '');
|
||||
};
|
||||
|
||||
const handlePaymentMethodChange = (value) => {
|
||||
setPage(1);
|
||||
setPaymentMethodFilter(value || '');
|
||||
};
|
||||
|
||||
const handleDateRangeChange = (dates) => {
|
||||
setPage(1);
|
||||
setDateRange(dates || null);
|
||||
};
|
||||
|
||||
const handleMinMoneyChange = (value) => {
|
||||
setMinMoney(value);
|
||||
};
|
||||
|
||||
const handleMaxMoneyChange = (value) => {
|
||||
setMaxMoney(value);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setPage(1);
|
||||
setKeyword('');
|
||||
setSearchKeyword('');
|
||||
setOrderId(undefined);
|
||||
setAppliedOrderId(undefined);
|
||||
setUserId(undefined);
|
||||
setAppliedUserId(undefined);
|
||||
setStatusFilter('');
|
||||
setPaymentMethodFilter('');
|
||||
setDateRange(null);
|
||||
setMinMoney(undefined);
|
||||
setMaxMoney(undefined);
|
||||
setAppliedMinMoney(undefined);
|
||||
setAppliedMaxMoney(undefined);
|
||||
};
|
||||
|
||||
const copyText = (text, id) => {
|
||||
navigator.clipboard
|
||||
.writeText(text)
|
||||
.then(() => {
|
||||
setCopiedId(id);
|
||||
Toast.success(t('已复制'));
|
||||
setTimeout(() => setCopiedId(null), 2000);
|
||||
})
|
||||
.catch(() => {
|
||||
showError(t('复制失败'));
|
||||
});
|
||||
};
|
||||
|
||||
const formatTime = (timestamp) => {
|
||||
if (!timestamp) return '-';
|
||||
return new Date(timestamp * 1000).toLocaleString();
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{
|
||||
title: t('订单号'),
|
||||
dataIndex: 'trade_no',
|
||||
width: 180,
|
||||
ellipsis: true,
|
||||
render: (text, record) => (
|
||||
<div className='flex items-center gap-1'>
|
||||
<span className='truncate text-xs font-mono' title={text}>
|
||||
{text}
|
||||
</span>
|
||||
<button
|
||||
className='flex-shrink-0 p-0.5 rounded hover:bg-gray-100 dark:hover:bg-neutral-700 cursor-pointer bg-transparent border-none'
|
||||
onClick={() => copyText(text, `trade-${record.id}`)}
|
||||
title={t('复制订单号')}
|
||||
>
|
||||
{copiedId === `trade-${record.id}` ? (
|
||||
<Check size={12} className='text-green-500' />
|
||||
) : (
|
||||
<Copy size={12} className='text-gray-400' />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('用户'),
|
||||
width: 140,
|
||||
ellipsis: true,
|
||||
render: (_, record) => {
|
||||
const displayName = record.display_name || '';
|
||||
const username = record.username || '';
|
||||
if (displayName && username) {
|
||||
return (
|
||||
<span title={`${displayName} (${username})`}>
|
||||
{displayName}{' '}
|
||||
<span className='text-xs text-gray-400'>({username})</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (displayName || username) {
|
||||
return displayName || username;
|
||||
}
|
||||
return <span className='text-gray-400'>User#{record.user_id}</span>;
|
||||
},
|
||||
},
|
||||
{ title: t('用户ID'), dataIndex: 'user_id', width: 70 },
|
||||
{
|
||||
title: t('充值额度'),
|
||||
dataIndex: 'amount',
|
||||
width: 100,
|
||||
render: (v) => renderQuota(v, 2),
|
||||
},
|
||||
{
|
||||
title: t('支付金额'),
|
||||
dataIndex: 'money',
|
||||
width: 90,
|
||||
render: (v) => (v ? `¥${Number(v).toFixed(2)}` : '-'),
|
||||
},
|
||||
{
|
||||
title: t('支付方式'),
|
||||
dataIndex: 'payment_method',
|
||||
width: 80,
|
||||
render: (v) => (v ? paymentMethodMap[v] || v : '-'),
|
||||
},
|
||||
{
|
||||
title: t('PayPal 结算'),
|
||||
width: 210,
|
||||
render: (_, record) => {
|
||||
if (record.payment_method !== 'paypal') return '-';
|
||||
return (
|
||||
<div className='text-xs leading-5'>
|
||||
<div>
|
||||
{t('基础金额')}:{' '}
|
||||
{formatUSDMinor(record.provider_base_amount_minor)}
|
||||
</div>
|
||||
<div>
|
||||
{t('支付服务费')}:{' '}
|
||||
{formatUSDMinor(record.payment_service_fee_minor)}
|
||||
</div>
|
||||
<div>
|
||||
{t('PayPal 实际手续费')}:{' '}
|
||||
{formatUSDMinor(record.provider_fee_minor)}
|
||||
</div>
|
||||
<div>
|
||||
{t('PayPal 净收金额')}:{' '}
|
||||
{formatUSDMinor(record.provider_net_amount_minor)}
|
||||
</div>
|
||||
<div>
|
||||
{t('结算状态')}:{' '}
|
||||
{t(
|
||||
payPalSettlementStateMap[record.paypal_settlement_state] ||
|
||||
record.paypal_settlement_state ||
|
||||
'未知',
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (status) => (
|
||||
<Tag color={statusColorMap[status] || 'grey'}>
|
||||
{t(statusTextMap[status] || status || '未知')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('创建时间'),
|
||||
dataIndex: 'create_time',
|
||||
width: 150,
|
||||
render: (v) => formatTime(v),
|
||||
},
|
||||
{
|
||||
title: t('完成时间'),
|
||||
dataIndex: 'complete_time',
|
||||
width: 150,
|
||||
render: (v) => formatTime(v),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='mt-[60px] p-4 sm:p-6'>
|
||||
{/* 筛选区:标题与筛选项同行,紧凑布局 */}
|
||||
<div className='flex flex-wrap items-center gap-2 mb-4'>
|
||||
<div className='flex items-center gap-1.5 mr-2 flex-shrink-0'>
|
||||
<ShoppingCart size={18} className='text-blue-500' />
|
||||
<span className='text-base font-bold text-gray-900 dark:text-white'>
|
||||
{t('订单管理')}
|
||||
</span>
|
||||
</div>
|
||||
<Input
|
||||
prefix={<Search size={14} />}
|
||||
placeholder={t('搜索昵称/订单号')}
|
||||
value={keyword}
|
||||
onChange={setKeyword}
|
||||
onEnterPress={handleSearch}
|
||||
style={{ width: 220 }}
|
||||
/>
|
||||
<InputNumber
|
||||
placeholder={t('订单ID')}
|
||||
value={orderId}
|
||||
onChange={setOrderId}
|
||||
min={1}
|
||||
style={{ width: 110 }}
|
||||
hideButtons
|
||||
/>
|
||||
<InputNumber
|
||||
placeholder={t('用户ID')}
|
||||
value={userId}
|
||||
onChange={setUserId}
|
||||
min={1}
|
||||
style={{ width: 110 }}
|
||||
hideButtons
|
||||
/>
|
||||
<Select
|
||||
placeholder={t('状态')}
|
||||
value={statusFilter || undefined}
|
||||
onChange={handleStatusFilterChange}
|
||||
style={{ width: 110 }}
|
||||
allowClear
|
||||
optionList={[
|
||||
{ label: t('待支付'), value: 'pending' },
|
||||
{ label: t('已完成'), value: 'success' },
|
||||
{ label: t('已过期'), value: 'expired' },
|
||||
]}
|
||||
/>
|
||||
<Select
|
||||
placeholder={t('支付方式')}
|
||||
value={paymentMethodFilter || undefined}
|
||||
onChange={handlePaymentMethodChange}
|
||||
style={{ width: 120 }}
|
||||
allowClear
|
||||
optionList={Object.entries(paymentMethodMap).map(
|
||||
([value, label]) => ({ label, value }),
|
||||
)}
|
||||
/>
|
||||
<DatePicker
|
||||
type='dateTimeRange'
|
||||
value={dateRange}
|
||||
onChange={handleDateRangeChange}
|
||||
placeholder={[t('开始时间'), t('结束时间')]}
|
||||
style={{ width: 340 }}
|
||||
density='compact'
|
||||
/>
|
||||
<div className='flex items-center gap-1'>
|
||||
<InputNumber
|
||||
placeholder={t('最小金额')}
|
||||
value={minMoney}
|
||||
onChange={handleMinMoneyChange}
|
||||
min={0}
|
||||
precision={2}
|
||||
style={{ width: 100 }}
|
||||
prefix='¥'
|
||||
/>
|
||||
<span className='text-gray-400'>-</span>
|
||||
<InputNumber
|
||||
placeholder={t('最大金额')}
|
||||
value={maxMoney}
|
||||
onChange={handleMaxMoneyChange}
|
||||
min={0}
|
||||
precision={2}
|
||||
style={{ width: 100 }}
|
||||
prefix='¥'
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
theme='solid'
|
||||
type='primary'
|
||||
size='default'
|
||||
onClick={handleSearch}
|
||||
>
|
||||
{t('搜索')}
|
||||
</Button>
|
||||
<Button type='tertiary' size='default' onClick={handleReset}>
|
||||
{t('重置')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 表格 */}
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={orders}
|
||||
loading={loading}
|
||||
rowKey='id'
|
||||
pagination={{
|
||||
currentPage: page,
|
||||
total,
|
||||
pageSize: 20,
|
||||
onPageChange: setPage,
|
||||
showTotal: true,
|
||||
showSizeChanger: false,
|
||||
}}
|
||||
scroll={{ x: 1100 }}
|
||||
size='small'
|
||||
empty={t('暂无订单数据')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminOrder;
|
||||
@@ -0,0 +1,578 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
// 企业通知预警 · 通知设置弹窗(方案 11 号文档 §8-2 / §8.1)
|
||||
// 配置存储为 org_alert_setting.* 的 option 行(root-only,未登记下放白名单即天然 root-only)。
|
||||
// 密钥回读为 ***ALREADY_SET*** 时置空展示、未改动不提交,防掩码覆盖真值。
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Modal,
|
||||
Input,
|
||||
InputNumber,
|
||||
Select,
|
||||
Switch,
|
||||
Spin,
|
||||
Button,
|
||||
Tag,
|
||||
TimePicker,
|
||||
Collapse,
|
||||
Toast,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
|
||||
const OPTION_PREFIX = 'org_alert_setting.';
|
||||
|
||||
// 字段默认值与后端 setting/operation_setting/org_alert_setting.go 保持一致
|
||||
const DEFAULTS = {
|
||||
enabled: false,
|
||||
scan_interval_minutes: 30,
|
||||
title_prefix: '',
|
||||
excluded_org_ids: '',
|
||||
test_stage_threshold: 1000,
|
||||
webhook_url: '',
|
||||
WebhookSecret: '',
|
||||
webhook_format: 'generic',
|
||||
market_webhook_url: '',
|
||||
MarketWebhookSecret: '',
|
||||
market_webhook_format: '',
|
||||
daily_report_enabled: true,
|
||||
daily_report_time: '09:00',
|
||||
daily_report_max_rows: 50,
|
||||
daily_report_include_inactive: false,
|
||||
no_consumption_enabled: true,
|
||||
no_consumption_days: 3,
|
||||
no_consumption_min_amount: 0,
|
||||
exhausted_prod_enabled: true,
|
||||
exhausted_test_enabled: true,
|
||||
exhausted_threshold: 1,
|
||||
};
|
||||
|
||||
const BOOL_KEYS = new Set([
|
||||
'enabled',
|
||||
'daily_report_enabled',
|
||||
'daily_report_include_inactive',
|
||||
'no_consumption_enabled',
|
||||
'exhausted_prod_enabled',
|
||||
'exhausted_test_enabled',
|
||||
]);
|
||||
const NUMBER_KEYS = new Set([
|
||||
'scan_interval_minutes',
|
||||
'test_stage_threshold',
|
||||
'daily_report_max_rows',
|
||||
'no_consumption_days',
|
||||
'no_consumption_min_amount',
|
||||
'exhausted_threshold',
|
||||
]);
|
||||
const SECRET_KEYS = new Set(['WebhookSecret', 'MarketWebhookSecret']);
|
||||
|
||||
// V1 仅放出三种格式,dingtalk 枚举预留 V2(方案 §6.1)。
|
||||
// 标签走 t():模块级常量里写死中文会在英文界面直显中文。
|
||||
const formatOptions = (t) => [
|
||||
{ value: 'generic', label: t('通用 JSON') },
|
||||
{ value: 'feishu', label: t('飞书机器人') },
|
||||
{ value: 'wecom', label: t('企业微信机器人') },
|
||||
];
|
||||
|
||||
const parseOptionValue = (key, raw) => {
|
||||
if (BOOL_KEYS.has(key)) return raw === 'true';
|
||||
if (NUMBER_KEYS.has(key)) {
|
||||
const n = parseFloat(raw);
|
||||
return Number.isFinite(n) ? n : DEFAULTS[key];
|
||||
}
|
||||
return raw ?? '';
|
||||
};
|
||||
|
||||
// 后端这几个字段是 Go int:存进小数或空串会让 ParseInt 失败而"静默保持旧值"——
|
||||
// 界面显示已保存、实际未生效,重启后还会退回编译期默认值。这里取整兜底,
|
||||
// 配合 InputNumber 的 precision={0}。
|
||||
const INT_KEYS = new Set([
|
||||
'scan_interval_minutes',
|
||||
'daily_report_max_rows',
|
||||
'no_consumption_days',
|
||||
]);
|
||||
|
||||
const serializeValue = (key, value) => {
|
||||
if (BOOL_KEYS.has(key)) return value ? 'true' : 'false';
|
||||
if (NUMBER_KEYS.has(key)) {
|
||||
// 清空输入框给的是 '',Number('') === 0 会把配置存成字面 0:
|
||||
// 后端各自钳制成 5 分钟/1 天/最小阈值,于是"界面显示 0、引擎按别的值跑"。
|
||||
// 空值一律回落该字段的默认值。
|
||||
if (value === '' || value === null || value === undefined) {
|
||||
return String(DEFAULTS[key]);
|
||||
}
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return String(DEFAULTS[key]);
|
||||
return String(INT_KEYS.has(key) ? Math.round(n) : n);
|
||||
}
|
||||
return String(value ?? '');
|
||||
};
|
||||
|
||||
const OrgAlertSettingsModal = ({ visible, onClose, onSaved }) => {
|
||||
const { t } = useTranslation();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState('');
|
||||
const [form, setForm] = useState({ ...DEFAULTS });
|
||||
// 已加载的原始值(序列化后),保存时只提交变更过的字段
|
||||
const [loaded, setLoaded] = useState({});
|
||||
// 密钥是否已设置(回读为掩码):置空展示 placeholder,未改动不提交
|
||||
const [secretSet, setSecretSet] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.get('/api/option/');
|
||||
if (cancelled) return;
|
||||
if (!res.data?.success) {
|
||||
showError(res.data?.message || t('配置加载失败'));
|
||||
return;
|
||||
}
|
||||
const next = { ...DEFAULTS };
|
||||
const raw = {};
|
||||
const secrets = {};
|
||||
(res.data.data || []).forEach(({ key, value }) => {
|
||||
if (!key.startsWith(OPTION_PREFIX)) return;
|
||||
const field = key.slice(OPTION_PREFIX.length);
|
||||
if (!(field in DEFAULTS)) return;
|
||||
if (SECRET_KEYS.has(field)) {
|
||||
// 后端对空密钥根本不返回该 key,所以行存在即已设置(掩码值同理非空)
|
||||
secrets[field] = value !== '';
|
||||
next[field] = '';
|
||||
raw[field] = '';
|
||||
return;
|
||||
}
|
||||
next[field] = parseOptionValue(field, value);
|
||||
raw[field] = value;
|
||||
});
|
||||
setForm(next);
|
||||
setLoaded(raw);
|
||||
setSecretSet(secrets);
|
||||
} catch (err) {
|
||||
// 传 error 对象而非 err.message:showError 只有拿到 AxiosError 对象才会把
|
||||
// 401/429/500/网络错误翻成中文,传字符串会直显 "Request failed with status code 500"
|
||||
if (!cancelled) showError(err);
|
||||
} finally {
|
||||
if (!cancelled) setLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [visible, t]);
|
||||
|
||||
const setField = (key) => (value) => setForm((f) => ({ ...f, [key]: value }));
|
||||
|
||||
const excludedIdList = (form.excluded_org_ids || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const puts = [];
|
||||
Object.keys(DEFAULTS).forEach((key) => {
|
||||
if (SECRET_KEYS.has(key)) {
|
||||
// 密钥留空 = 不修改(防把掩码/空值覆盖回真值)
|
||||
if ((form[key] || '').trim() !== '') {
|
||||
puts.push({ key: OPTION_PREFIX + key, value: form[key].trim() });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const serialized = serializeValue(key, form[key]);
|
||||
const before =
|
||||
key in loaded ? loaded[key] : serializeValue(key, DEFAULTS[key]);
|
||||
if (serialized !== before) {
|
||||
puts.push({ key: OPTION_PREFIX + key, value: serialized });
|
||||
}
|
||||
});
|
||||
for (const item of puts) {
|
||||
const res = await API.put('/api/option/', item);
|
||||
if (!res.data?.success) {
|
||||
showError(res.data?.message || t('保存失败'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
Toast.success(
|
||||
puts.length ? t('通知设置已保存') : t('没有需要保存的变更'),
|
||||
);
|
||||
onSaved?.();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = async (channel) => {
|
||||
setTesting(channel);
|
||||
try {
|
||||
const res = await API.post('/api/org_alert/test', { channel });
|
||||
if (res.data?.success) {
|
||||
// 市场通道未配地址时后端会回落默认通道,必须如实告知,否则会误以为市场通道已配好
|
||||
if (res.data?.data?.fell_back) {
|
||||
Toast.warning(res.data.data.message);
|
||||
} else {
|
||||
Toast.success(t('测试消息已发送,请到目标群确认'));
|
||||
}
|
||||
} else {
|
||||
// 透传后端具体失败原因(SSRF 拒绝 / 对端错误码),便于排障
|
||||
showError(res.data?.message || t('测试发送失败'));
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
} finally {
|
||||
setTesting('');
|
||||
}
|
||||
};
|
||||
|
||||
const timeToDate = (str) => {
|
||||
const m = /^(\d{1,2}):(\d{2})$/.exec(str || '');
|
||||
const d = new Date();
|
||||
d.setHours(m ? parseInt(m[1], 10) : 9, m ? parseInt(m[2], 10) : 0, 0, 0);
|
||||
return d;
|
||||
};
|
||||
|
||||
const labelCls =
|
||||
'block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5';
|
||||
const sectionCls =
|
||||
'text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500 pt-2';
|
||||
const rowCls = 'flex items-center justify-between gap-3';
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('企业预警通知设置')}
|
||||
visible={visible}
|
||||
onOk={handleSave}
|
||||
onCancel={onClose}
|
||||
okText={t('保存')}
|
||||
cancelText={t('取消')}
|
||||
confirmLoading={saving}
|
||||
width={640}
|
||||
style={{ maxWidth: 'calc(100vw - 32px)' }}
|
||||
bodyStyle={{
|
||||
maxHeight: 'calc(100vh - 220px)',
|
||||
overflowY: 'auto',
|
||||
overscrollBehavior: 'contain',
|
||||
scrollbarGutter: 'stable',
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<div className='flex justify-center py-10'>
|
||||
<Spin size='large' />
|
||||
</div>
|
||||
) : (
|
||||
<div className='space-y-4'>
|
||||
{/* —— 通用 —— */}
|
||||
<div className={sectionCls}>{t('通用')}</div>
|
||||
<div className={rowCls}>
|
||||
<span className='text-sm text-gray-700 dark:text-gray-300'>
|
||||
{t('启用企业预警通知')}
|
||||
</span>
|
||||
<Switch checked={form.enabled} onChange={setField('enabled')} />
|
||||
</div>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
<div>
|
||||
<label className={labelCls}>{t('扫描周期(分钟)')}</label>
|
||||
<InputNumber
|
||||
value={form.scan_interval_minutes}
|
||||
onChange={setField('scan_interval_minutes')}
|
||||
min={5}
|
||||
max={1440}
|
||||
precision={0}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('生产/测试分界')}</label>
|
||||
<InputNumber
|
||||
value={form.test_stage_threshold}
|
||||
onChange={setField('test_stage_threshold')}
|
||||
min={0}
|
||||
suffix={t('元')}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('消息标题前缀')}</label>
|
||||
<Input
|
||||
value={form.title_prefix}
|
||||
onChange={setField('title_prefix')}
|
||||
placeholder={t('如 [生产],多环境共用群时区分来源')}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('已屏蔽预警的企业')}</label>
|
||||
{/* 只读展示:编辑入口唯一收敛到企业列表的行内铃铛按钮(走 CAS 接口)。
|
||||
若这里也做整串编辑,弹窗持有的是打开那一刻的快照,保存会把期间
|
||||
别人用行内开关加入的企业静默抹掉。 */}
|
||||
<div className='flex flex-wrap items-center gap-1.5'>
|
||||
{excludedIdList.length ? (
|
||||
excludedIdList.map((id) => (
|
||||
<Tag key={id} size='small' color='grey'>
|
||||
#{id}
|
||||
</Tag>
|
||||
))
|
||||
) : (
|
||||
<span className='text-sm text-gray-400 dark:text-gray-500'>
|
||||
{t('暂无')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1'>
|
||||
{t('在企业列表中用铃铛按钮屏蔽/恢复单个企业')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* —— 投递通道 —— */}
|
||||
<div className={sectionCls}>{t('投递通道')}</div>
|
||||
<div>
|
||||
<label className={labelCls}>
|
||||
{t('默认通道 Webhook 地址')}
|
||||
<span className='text-gray-400 font-normal ml-1'>
|
||||
{t('(日报走此通道)')}
|
||||
</span>
|
||||
</label>
|
||||
<Input
|
||||
value={form.webhook_url}
|
||||
onChange={setField('webhook_url')}
|
||||
placeholder='https://...'
|
||||
className='break-all'
|
||||
/>
|
||||
</div>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
<div>
|
||||
<label className={labelCls}>{t('消息格式')}</label>
|
||||
<Select
|
||||
value={form.webhook_format}
|
||||
onChange={setField('webhook_format')}
|
||||
optionList={formatOptions(t)}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('签名密钥')}</label>
|
||||
<Input
|
||||
mode='password'
|
||||
value={form.WebhookSecret}
|
||||
onChange={setField('WebhookSecret')}
|
||||
placeholder={
|
||||
secretSet.WebhookSecret
|
||||
? t('已设置,留空则不修改')
|
||||
: t('可选')
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<Collapse>
|
||||
<Collapse.Panel
|
||||
header={t('市场通道(可选,预警走此通道,留空回落默认通道)')}
|
||||
itemKey='market'
|
||||
>
|
||||
<div className='space-y-3'>
|
||||
<div>
|
||||
<label className={labelCls}>
|
||||
{t('市场通道 Webhook 地址')}
|
||||
</label>
|
||||
<Input
|
||||
value={form.market_webhook_url}
|
||||
onChange={setField('market_webhook_url')}
|
||||
placeholder='https://...'
|
||||
className='break-all'
|
||||
/>
|
||||
</div>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
<div>
|
||||
<label className={labelCls}>{t('消息格式')}</label>
|
||||
<Select
|
||||
value={form.market_webhook_format || ''}
|
||||
onChange={setField('market_webhook_format')}
|
||||
optionList={[
|
||||
{ value: '', label: t('跟随默认通道') },
|
||||
...formatOptions(t),
|
||||
]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('签名密钥')}</label>
|
||||
<Input
|
||||
mode='password'
|
||||
value={form.MarketWebhookSecret}
|
||||
onChange={setField('MarketWebhookSecret')}
|
||||
placeholder={
|
||||
secretSet.MarketWebhookSecret
|
||||
? t('已设置,留空则不修改')
|
||||
: t('可选')
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
|
||||
{/* —— 日报 —— */}
|
||||
<div className={sectionCls}>{t('每日使用报表')}</div>
|
||||
<div className={rowCls}>
|
||||
<span className='text-sm text-gray-700 dark:text-gray-300'>
|
||||
{t('启用每日报表')}
|
||||
</span>
|
||||
<Switch
|
||||
checked={form.daily_report_enabled}
|
||||
onChange={setField('daily_report_enabled')}
|
||||
/>
|
||||
</div>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
<div>
|
||||
<label className={labelCls}>{t('发送时刻')}</label>
|
||||
<TimePicker
|
||||
format='HH:mm'
|
||||
value={timeToDate(form.daily_report_time)}
|
||||
onChange={(_, timeString) => {
|
||||
if (typeof timeString === 'string' && timeString) {
|
||||
setField('daily_report_time')(timeString.slice(0, 5));
|
||||
}
|
||||
}}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('正文行数上限')}</label>
|
||||
<InputNumber
|
||||
value={form.daily_report_max_rows}
|
||||
onChange={setField('daily_report_max_rows')}
|
||||
min={1}
|
||||
max={200}
|
||||
precision={0}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className={rowCls}>
|
||||
<span className='text-sm text-gray-700 dark:text-gray-300'>
|
||||
{t('包含零消耗零余额企业')}
|
||||
</span>
|
||||
<Switch
|
||||
checked={form.daily_report_include_inactive}
|
||||
onChange={setField('daily_report_include_inactive')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* —— 预警 —— */}
|
||||
<div className={sectionCls}>{t('预警规则')}</div>
|
||||
<div className={rowCls}>
|
||||
<span className='text-sm text-gray-700 dark:text-gray-300'>
|
||||
{t('加额未消耗提醒')}
|
||||
</span>
|
||||
<Switch
|
||||
checked={form.no_consumption_enabled}
|
||||
onChange={setField('no_consumption_enabled')}
|
||||
/>
|
||||
</div>
|
||||
<div className='grid grid-cols-2 gap-3'>
|
||||
<div>
|
||||
<label className={labelCls}>{t('未消耗观察天数')}</label>
|
||||
<InputNumber
|
||||
value={form.no_consumption_days}
|
||||
onChange={setField('no_consumption_days')}
|
||||
min={1}
|
||||
max={30}
|
||||
precision={0}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('加额金额门槛')}</label>
|
||||
<InputNumber
|
||||
value={form.no_consumption_min_amount}
|
||||
onChange={setField('no_consumption_min_amount')}
|
||||
min={0}
|
||||
suffix={t('元')}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className={rowCls}>
|
||||
<span className='text-sm text-gray-700 dark:text-gray-300'>
|
||||
{t('生产企业额度用尽提醒')}
|
||||
</span>
|
||||
<Switch
|
||||
checked={form.exhausted_prod_enabled}
|
||||
onChange={setField('exhausted_prod_enabled')}
|
||||
/>
|
||||
</div>
|
||||
<div className={rowCls}>
|
||||
<span className='text-sm text-gray-700 dark:text-gray-300'>
|
||||
{t('测试企业额度用尽提醒')}
|
||||
</span>
|
||||
<Switch
|
||||
checked={form.exhausted_test_enabled}
|
||||
onChange={setField('exhausted_test_enabled')}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className={labelCls}>{t('用尽阈值')}</label>
|
||||
<InputNumber
|
||||
value={form.exhausted_threshold}
|
||||
onChange={setField('exhausted_threshold')}
|
||||
min={0}
|
||||
suffix={t('元')}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1'>
|
||||
{t(
|
||||
'余额低于此值视为用尽;应不低于客户典型单次请求成本,调大可当低余额提醒用',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* —— 发送测试 —— */}
|
||||
<div className='flex flex-wrap items-center gap-2 pt-2 border-t border-gray-100 dark:border-neutral-800'>
|
||||
<Button
|
||||
loading={testing === 'default'}
|
||||
disabled={!!testing}
|
||||
onClick={() => handleTest('default')}
|
||||
>
|
||||
{t('测试默认通道')}
|
||||
</Button>
|
||||
<Button
|
||||
loading={testing === 'market'}
|
||||
disabled={!!testing}
|
||||
onClick={() => handleTest('market')}
|
||||
>
|
||||
{t('测试市场通道')}
|
||||
</Button>
|
||||
<span className='text-xs text-gray-400 dark:text-gray-500 self-center'>
|
||||
{t('测试使用已保存的配置,改动请先保存')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgAlertSettingsModal;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,592 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, {
|
||||
useState,
|
||||
useEffect,
|
||||
Suspense,
|
||||
lazy,
|
||||
useContext,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
|
||||
import {
|
||||
Button,
|
||||
Spin,
|
||||
Radio,
|
||||
DatePicker,
|
||||
Collapsible,
|
||||
Tabs,
|
||||
TabPane,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { IconRefresh } from '@douyinfe/semi-icons';
|
||||
import {
|
||||
BarChart2,
|
||||
Users,
|
||||
TrendingUp,
|
||||
Server,
|
||||
Trophy,
|
||||
CreditCard,
|
||||
FileText,
|
||||
UserCheck,
|
||||
Wallet,
|
||||
ChevronDown,
|
||||
ShieldAlert,
|
||||
History,
|
||||
Upload,
|
||||
Building2,
|
||||
Activity,
|
||||
} from 'lucide-react';
|
||||
import useAnalyticsData from '../../hooks/analytics/useAnalyticsData';
|
||||
import useOrgConsumptionData from '../../hooks/analytics/useOrgConsumptionData';
|
||||
import useRiskControlData from '../../hooks/analytics/useRiskControlData';
|
||||
import OverviewCards from '../../components/analytics/OverviewCards';
|
||||
import TrendCharts from '../../components/analytics/TrendCharts';
|
||||
import ChannelConsumption from '../../components/analytics/ChannelConsumption';
|
||||
import UserRanking from '../../components/analytics/UserRanking';
|
||||
import TopupChannelChart from '../../components/analytics/TopupChannelChart';
|
||||
import DailyStatsTable from '../../components/analytics/DailyStatsTable';
|
||||
import UserSurveyStats from '../../components/analytics/UserSurveyStats';
|
||||
import UserTopupRanking from '../../components/analytics/UserTopupRanking';
|
||||
import HighFreqLowCostUsers from '../../components/analytics/HighFreqLowCostUsers';
|
||||
import RiskControlRulesModal from '../../components/analytics/RiskControlRulesModal';
|
||||
import RiskControlBanLogs from '../../components/analytics/RiskControlBanLogs';
|
||||
import OrgReportPanel from '../../components/analytics/orgReport';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
|
||||
|
||||
// audit 面板单独切 chunk:仅用户切到审计 Tab 时按需加载
|
||||
const ExperienceCenterAuditPanel = lazy(
|
||||
() => import('../ExperienceCenterAudit'),
|
||||
);
|
||||
|
||||
// 调用质量看板单独切 chunk(含多张图表),仅切到该 Tab 时加载
|
||||
const QualityDashboard = lazy(
|
||||
() => import('../../components/quality/QualityDashboard'),
|
||||
);
|
||||
|
||||
// 内嵌的 chunk 加载占位:不能用全屏的 <Loading />,否则会撑出 100vh 的开机闪屏
|
||||
const TabChunkFallback = () => (
|
||||
<div className='flex justify-center items-center py-16'>
|
||||
<Spin size='large' />
|
||||
</div>
|
||||
);
|
||||
|
||||
// 可折叠区块头部
|
||||
const CollapsibleHeader = ({ icon, title, isOpen, onToggle, t, extra }) => (
|
||||
<div
|
||||
className='flex items-center justify-between cursor-pointer select-none px-5 py-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm hover:shadow-md transition-all border border-gray-100 dark:border-gray-700'
|
||||
onClick={onToggle}
|
||||
>
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-brand'>{icon}</span>
|
||||
<span className='font-semibold text-gray-800 dark:text-gray-100'>
|
||||
{title}
|
||||
</span>
|
||||
{extra}
|
||||
</div>
|
||||
<ChevronDown
|
||||
className={`w-5 h-5 text-gray-400 transition-transform duration-300 ${isOpen ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
// 从 URL ?tab= 派生 activeTab,未知值落回 operations
|
||||
const readTabFromURL = () => {
|
||||
try {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const tab = params.get('tab');
|
||||
if (tab === 'risk' || tab === 'audit' || tab === 'org' || tab === 'quality')
|
||||
return tab;
|
||||
return 'operations';
|
||||
} catch (_e) {
|
||||
return 'operations';
|
||||
}
|
||||
};
|
||||
|
||||
const Analytics = () => {
|
||||
const { t } = useTranslation();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const analyticsConfig = useMemo(
|
||||
() =>
|
||||
normalizeSidebarModulesAdmin(statusState?.status?.SidebarModulesAdmin)
|
||||
.analytics,
|
||||
[statusState?.status?.SidebarModulesAdmin],
|
||||
);
|
||||
const isAnalyticsTabVisible = (key) =>
|
||||
analyticsConfig?.enabled !== false && analyticsConfig?.[key] !== false;
|
||||
const firstVisibleTab = [
|
||||
'operations',
|
||||
'quality',
|
||||
'risk',
|
||||
'org',
|
||||
'audit',
|
||||
].find(isAnalyticsTabVisible);
|
||||
|
||||
// 初始化 VChart Semi 主题(深色模式适配)
|
||||
useEffect(() => {
|
||||
initVChartSemiTheme({
|
||||
isWatchingThemeSwitch: true,
|
||||
});
|
||||
}, []);
|
||||
|
||||
const [channelOpen, setChannelOpen] = useState(false);
|
||||
const [topupRankOpen, setTopupRankOpen] = useState(false);
|
||||
const [dailyStatsOpen, setDailyStatsOpen] = useState(false);
|
||||
const [banLogsOpen, setBanLogsOpen] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState(readTabFromURL);
|
||||
|
||||
useEffect(() => {
|
||||
if (!firstVisibleTab) return;
|
||||
if (!isAnalyticsTabVisible(activeTab)) {
|
||||
setActiveTab(firstVisibleTab);
|
||||
const url = new URL(window.location.href);
|
||||
if (firstVisibleTab === 'operations') url.searchParams.delete('tab');
|
||||
else url.searchParams.set('tab', firstVisibleTab);
|
||||
window.history.replaceState(null, '', url.toString());
|
||||
}
|
||||
}, [activeTab, firstVisibleTab, analyticsConfig]);
|
||||
|
||||
// 浏览器前进/后退切到不同 ?tab= 时同步 UI(我们用 replaceState 改 URL,所以正常切换不会
|
||||
// 产生 history 条目;这里主要兜底浏览器返回到带 ?tab= 的旧条目、或扩展直接改 URL 的情况)
|
||||
useEffect(() => {
|
||||
const onPopState = () => setActiveTab(readTabFromURL());
|
||||
window.addEventListener('popstate', onPopState);
|
||||
return () => window.removeEventListener('popstate', onPopState);
|
||||
}, []);
|
||||
const [riskRuleModalVisible, setRiskRuleModalVisible] = useState(false);
|
||||
const {
|
||||
loading,
|
||||
overview,
|
||||
userTrend,
|
||||
financeTrend,
|
||||
channelConsumption,
|
||||
userRanking,
|
||||
topupChannel,
|
||||
dailyStats,
|
||||
userTopupRanking,
|
||||
period,
|
||||
dateRange,
|
||||
setPeriod,
|
||||
setDateRange,
|
||||
refreshAll,
|
||||
} = useAnalyticsData(
|
||||
activeTab === 'operations' && isAnalyticsTabVisible('operations'),
|
||||
);
|
||||
|
||||
// 懒加载:仅当用户切到风控 Tab 时才发起风控 API 请求
|
||||
const risk = useRiskControlData(
|
||||
activeTab === 'risk' && isAnalyticsTabVisible('risk'),
|
||||
);
|
||||
|
||||
// 懒加载:仅当用户切到「个人/企业消耗」Tab 时才发起请求
|
||||
const org = useOrgConsumptionData(
|
||||
activeTab === 'org' && isAnalyticsTabVisible('org'),
|
||||
);
|
||||
|
||||
// 运营看板与个人/企业消耗看板共用顶部时间筛选器,按当前 Tab 取对应控制器
|
||||
const isOperationsTab =
|
||||
activeTab === 'operations' && isAnalyticsTabVisible('operations');
|
||||
const isOrgTab = activeTab === 'org' && isAnalyticsTabVisible('org');
|
||||
const showPeriodControls = isOperationsTab || isOrgTab;
|
||||
const curPeriod = isOrgTab ? org.period : period;
|
||||
const curDateRange = isOrgTab ? org.dateRange : dateRange;
|
||||
const curSetPeriod = isOrgTab ? org.setPeriod : setPeriod;
|
||||
const curSetDateRange = isOrgTab ? org.setDateRange : setDateRange;
|
||||
const curRefresh = isOrgTab ? org.refreshAll : refreshAll;
|
||||
const curLoading = isOrgTab ? org.loading : loading;
|
||||
|
||||
const handleTabChange = (key) => {
|
||||
setActiveTab(key);
|
||||
const url = new URL(window.location.href);
|
||||
if (key === 'operations') url.searchParams.delete('tab');
|
||||
else url.searchParams.set('tab', key);
|
||||
// 调用质量的筛选条件(q_ 前缀)只属于该 Tab,切走时清理,避免分享链接带上无关参数
|
||||
if (key !== 'quality') {
|
||||
Array.from(url.searchParams.keys())
|
||||
.filter((k) => k.startsWith('q_'))
|
||||
.forEach((k) => url.searchParams.delete(k));
|
||||
}
|
||||
window.history.replaceState(null, '', url.toString());
|
||||
};
|
||||
|
||||
const periodOptions = [
|
||||
{ value: 'today', label: t('今日') },
|
||||
{ value: 'week', label: t('本周') },
|
||||
{ value: 'month', label: t('本月') },
|
||||
{ value: 'quarter', label: t('季度') },
|
||||
{ value: 'custom', label: t('自定义') },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='min-h-screen mt-[60px]'>
|
||||
<Spin spinning={curLoading && showPeriodControls}>
|
||||
<div className='px-4 py-6 max-w-[1600px] mx-auto'>
|
||||
{/* Header */}
|
||||
<div className='mb-6 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='p-2.5 bg-gradient-to-br from-brand-from to-brand-to rounded-xl shadow-lg'>
|
||||
<BarChart2 className='w-6 h-6 text-white' />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className='text-2xl font-bold text-gray-800 dark:text-gray-100'>
|
||||
{t('运营数据看板')}
|
||||
</h1>
|
||||
<p className='text-sm text-gray-500 dark:text-gray-400 mt-0.5'>
|
||||
{t('实时监控平台运营状况')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex flex-wrap items-center gap-3'>
|
||||
{showPeriodControls && (
|
||||
<>
|
||||
<Radio.Group
|
||||
type='button'
|
||||
value={curPeriod}
|
||||
onChange={(e) => curSetPeriod(e.target.value)}
|
||||
buttonSize='middle'
|
||||
>
|
||||
{periodOptions.map((opt) => (
|
||||
<Radio key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</Radio>
|
||||
))}
|
||||
</Radio.Group>
|
||||
{curPeriod === 'custom' && (
|
||||
<DatePicker
|
||||
type='dateRange'
|
||||
value={curDateRange}
|
||||
onChange={curSetDateRange}
|
||||
placeholder={[t('开始日期'), t('结束日期')]}
|
||||
format='yyyy-MM-dd'
|
||||
style={{ width: 260 }}
|
||||
presets={[
|
||||
{
|
||||
text: t('最近7天'),
|
||||
start: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
|
||||
end: new Date(),
|
||||
},
|
||||
{
|
||||
text: t('最近30天'),
|
||||
start: new Date(
|
||||
Date.now() - 30 * 24 * 60 * 60 * 1000,
|
||||
),
|
||||
end: new Date(),
|
||||
},
|
||||
{
|
||||
text: t('最近90天'),
|
||||
start: new Date(
|
||||
Date.now() - 90 * 24 * 60 * 60 * 1000,
|
||||
),
|
||||
end: new Date(),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
icon={<IconRefresh />}
|
||||
onClick={() => curRefresh(curPeriod, curDateRange, true)}
|
||||
loading={curLoading}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!firstVisibleTab && (
|
||||
<div className='rounded-2xl border border-dashed border-gray-200 dark:border-gray-700 bg-white/70 dark:bg-gray-800/60 p-10 text-center shadow-sm'>
|
||||
<div className='mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-indigo-50 text-indigo-500 dark:bg-indigo-900/30 dark:text-indigo-300'>
|
||||
<BarChart2 className='h-6 w-6' />
|
||||
</div>
|
||||
<div className='text-base font-semibold text-gray-800 dark:text-gray-100'>
|
||||
{t('暂无可用的运营看板模块')}
|
||||
</div>
|
||||
<div className='mt-2 text-sm text-gray-500 dark:text-gray-400'>
|
||||
{t('请在系统设置中启用至少一个运营看板 Tab')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{firstVisibleTab && (
|
||||
<Tabs
|
||||
type='line'
|
||||
activeKey={activeTab}
|
||||
onChange={handleTabChange}
|
||||
className='mb-4'
|
||||
>
|
||||
{isAnalyticsTabVisible('operations') && (
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='flex items-center gap-2'>
|
||||
<BarChart2 className='w-4 h-4' />
|
||||
{t('运营看板')}
|
||||
</span>
|
||||
}
|
||||
itemKey='operations'
|
||||
/>
|
||||
)}
|
||||
{isAnalyticsTabVisible('quality') && (
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='flex items-center gap-2'>
|
||||
<Activity className='w-4 h-4' />
|
||||
{t('调用质量')}
|
||||
</span>
|
||||
}
|
||||
itemKey='quality'
|
||||
/>
|
||||
)}
|
||||
{isAnalyticsTabVisible('risk') && (
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='flex items-center gap-2'>
|
||||
<ShieldAlert className='w-4 h-4' />
|
||||
{t('风控看板')}
|
||||
</span>
|
||||
}
|
||||
itemKey='risk'
|
||||
/>
|
||||
)}
|
||||
{isAnalyticsTabVisible('org') && (
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='flex items-center gap-2'>
|
||||
<Building2 className='w-4 h-4' />
|
||||
{t('个人/企业消耗')}
|
||||
</span>
|
||||
}
|
||||
itemKey='org'
|
||||
/>
|
||||
)}
|
||||
{isAnalyticsTabVisible('audit') && (
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='flex items-center gap-2'>
|
||||
<Upload className='w-4 h-4' />
|
||||
{t('体验中心上传审计')}
|
||||
</span>
|
||||
}
|
||||
itemKey='audit'
|
||||
/>
|
||||
)}
|
||||
</Tabs>
|
||||
)}
|
||||
|
||||
{activeTab === 'operations' &&
|
||||
isAnalyticsTabVisible('operations') && (
|
||||
<>
|
||||
{/* Overview Cards */}
|
||||
<OverviewCards overview={overview} t={t} />
|
||||
|
||||
{/* Trend Charts */}
|
||||
<div className='grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6'>
|
||||
<TrendCharts
|
||||
title={t('用户趋势')}
|
||||
icon={<Users className='w-5 h-5' />}
|
||||
data={userTrend}
|
||||
type='user'
|
||||
t={t}
|
||||
/>
|
||||
<TrendCharts
|
||||
title={t('收支趋势')}
|
||||
icon={<TrendingUp className='w-5 h-5' />}
|
||||
data={financeTrend}
|
||||
type='finance'
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Distribution Charts */}
|
||||
<div className='grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6'>
|
||||
<TopupChannelChart
|
||||
data={topupChannel}
|
||||
title={t('充值渠道分布')}
|
||||
icon={<CreditCard className='w-5 h-5' />}
|
||||
t={t}
|
||||
/>
|
||||
<UserRanking
|
||||
data={userRanking}
|
||||
title={t('用户消耗 TOP100')}
|
||||
icon={<Trophy className='w-5 h-5' />}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Channel Consumption Ranking */}
|
||||
<div className='mb-6'>
|
||||
<CollapsibleHeader
|
||||
icon={<Server className='w-5 h-5' />}
|
||||
title={t('渠道消耗排行')}
|
||||
isOpen={channelOpen}
|
||||
onToggle={() => setChannelOpen(!channelOpen)}
|
||||
t={t}
|
||||
/>
|
||||
<Collapsible isOpen={channelOpen} keepDOM>
|
||||
<div className='mt-2'>
|
||||
<ChannelConsumption
|
||||
data={channelConsumption}
|
||||
title={t('渠道消耗排行')}
|
||||
icon={<Server className='w-5 h-5' />}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
|
||||
{/* User Survey Stats */}
|
||||
<div className='mb-6'>
|
||||
<UserSurveyStats
|
||||
title={t('用户身份问卷统计')}
|
||||
icon={<UserCheck className='w-5 h-5' />}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* User Topup Ranking */}
|
||||
<div className='mb-6'>
|
||||
<CollapsibleHeader
|
||||
icon={<Wallet className='w-5 h-5' />}
|
||||
title={t('用户充值排行')}
|
||||
isOpen={topupRankOpen}
|
||||
onToggle={() => setTopupRankOpen(!topupRankOpen)}
|
||||
t={t}
|
||||
/>
|
||||
<Collapsible isOpen={topupRankOpen} keepDOM>
|
||||
<div className='mt-2'>
|
||||
<UserTopupRanking
|
||||
data={userTopupRanking}
|
||||
title={t('用户充值排行')}
|
||||
icon={<Wallet className='w-5 h-5' />}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
|
||||
{/* Daily Stats Table */}
|
||||
<div className='mb-6'>
|
||||
<CollapsibleHeader
|
||||
icon={<FileText className='w-5 h-5' />}
|
||||
title={t('每日统计明细')}
|
||||
isOpen={dailyStatsOpen}
|
||||
onToggle={() => setDailyStatsOpen(!dailyStatsOpen)}
|
||||
t={t}
|
||||
/>
|
||||
<Collapsible isOpen={dailyStatsOpen} keepDOM>
|
||||
<div className='mt-2'>
|
||||
<DailyStatsTable
|
||||
data={dailyStats}
|
||||
title={t('每日统计明细')}
|
||||
icon={<FileText className='w-5 h-5' />}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === 'org' && isAnalyticsTabVisible('org') && (
|
||||
<OrgReportPanel
|
||||
report={org.report}
|
||||
loading={org.loading}
|
||||
error={org.error}
|
||||
onRetry={() => org.refreshAll(org.period, org.dateRange)}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'risk' && isAnalyticsTabVisible('risk') && (
|
||||
<>
|
||||
<HighFreqLowCostUsers
|
||||
loading={risk.loading}
|
||||
items={risk.items}
|
||||
windowRange={risk.windowRange}
|
||||
filters={risk.filters}
|
||||
setFilters={risk.setFilters}
|
||||
fetchSuspects={risk.fetchSuspects}
|
||||
rules={risk.rules}
|
||||
unbanUser={risk.unbanUser}
|
||||
onOpenRuleModal={() => setRiskRuleModalVisible(true)}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
{/* 自动封号历史 */}
|
||||
<div className='mt-6 mb-6'>
|
||||
<CollapsibleHeader
|
||||
icon={<History className='w-5 h-5' />}
|
||||
title={t('自动封号历史')}
|
||||
isOpen={banLogsOpen}
|
||||
onToggle={() => setBanLogsOpen(!banLogsOpen)}
|
||||
t={t}
|
||||
extra={
|
||||
<span className='text-xs text-gray-400 ml-2'>
|
||||
{t('被自动封号的用户列表 + 解封操作入口')}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<Collapsible isOpen={banLogsOpen} keepDOM>
|
||||
<div className='mt-2 px-5 py-4 bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-100 dark:border-gray-700'>
|
||||
<RiskControlBanLogs
|
||||
loading={risk.banLogLoading}
|
||||
banLogs={risk.banLogs}
|
||||
banLogTotal={risk.banLogTotal}
|
||||
banLogStatus={risk.banLogStatus}
|
||||
setBanLogStatus={risk.setBanLogStatus}
|
||||
banLogPage={risk.banLogPage}
|
||||
fetchBanLogs={risk.fetchBanLogs}
|
||||
unbanUser={risk.unbanUser}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
|
||||
<RiskControlRulesModal
|
||||
visible={riskRuleModalVisible}
|
||||
onClose={() => setRiskRuleModalVisible(false)}
|
||||
rules={risk.rules}
|
||||
saveRule={risk.saveRule}
|
||||
triggerScanNow={risk.triggerScanNow}
|
||||
t={t}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{activeTab === 'quality' && isAnalyticsTabVisible('quality') && (
|
||||
<Suspense fallback={<TabChunkFallback />}>
|
||||
<QualityDashboard scope='platform' />
|
||||
</Suspense>
|
||||
)}
|
||||
|
||||
{activeTab === 'audit' && isAnalyticsTabVisible('audit') && (
|
||||
<Suspense fallback={<TabChunkFallback />}>
|
||||
<ExperienceCenterAuditPanel />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Analytics;
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import ChannelsTable from '../../components/table/channels';
|
||||
|
||||
const File = () => {
|
||||
return (
|
||||
<div className='mt-[60px] px-2'>
|
||||
<ChannelsTable />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default File;
|
||||
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { useTokenKeys } from '../../hooks/chat/useTokenKeys';
|
||||
import { Spin } from '@douyinfe/semi-ui';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const ChatPage = () => {
|
||||
const { t } = useTranslation();
|
||||
const { id } = useParams();
|
||||
const { keys, serverAddress, isLoading } = useTokenKeys(id);
|
||||
|
||||
const comLink = (key) => {
|
||||
// console.log('chatLink:', chatLink);
|
||||
if (!serverAddress || !key) return '';
|
||||
let link = '';
|
||||
if (id) {
|
||||
let chats = localStorage.getItem('chats');
|
||||
if (chats) {
|
||||
chats = JSON.parse(chats);
|
||||
if (Array.isArray(chats) && chats.length > 0) {
|
||||
for (let k in chats[id]) {
|
||||
link = chats[id][k];
|
||||
link = link.replaceAll(
|
||||
'{address}',
|
||||
encodeURIComponent(serverAddress),
|
||||
);
|
||||
link = link.replaceAll('{key}', 'sk-' + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return link;
|
||||
};
|
||||
|
||||
const iframeSrc = keys.length > 0 ? comLink(keys[0]) : '';
|
||||
|
||||
return !isLoading && iframeSrc ? (
|
||||
<iframe
|
||||
src={iframeSrc}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: 'calc(100vh - 64px)',
|
||||
border: 'none',
|
||||
marginTop: '64px',
|
||||
}}
|
||||
title='Token Frame'
|
||||
allow='camera;microphone'
|
||||
/>
|
||||
) : (
|
||||
<div className='fixed inset-0 w-screen h-screen flex items-center justify-center bg-white/80 z-[1000] mt-[60px]'>
|
||||
<div className='flex flex-col items-center'>
|
||||
<Spin size='large' spinning={true} tip={null} />
|
||||
<span
|
||||
className='whitespace-nowrap mt-2 text-center'
|
||||
style={{ color: 'var(--semi-color-primary)' }}
|
||||
>
|
||||
{t('正在跳转...')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChatPage;
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useTokenKeys } from '../../hooks/chat/useTokenKeys';
|
||||
|
||||
const Chat2Page = () => {
|
||||
const { t } = useTranslation();
|
||||
const { keys, chatLink, serverAddress } = useTokenKeys();
|
||||
|
||||
const comLink = (key) => {
|
||||
if (!chatLink || !serverAddress || !key) return '';
|
||||
return `${chatLink}/#/?settings={"key":"sk-${key}","url":"${encodeURIComponent(serverAddress)}"}`;
|
||||
};
|
||||
|
||||
if (keys.length > 0) {
|
||||
const redirectLink = comLink(keys[0]);
|
||||
if (redirectLink) {
|
||||
window.location.href = redirectLink;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='mt-[60px] px-2'>
|
||||
<h3>{t('正在加载,请稍候...')}</h3>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Chat2Page;
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Avatar, Radio, RadioGroup, Typography } from '@douyinfe/semi-ui';
|
||||
import { Building2, User } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { optionKey } from './authorizeParams';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
/**
|
||||
* 授权范围选择:「个人」或所属的某个企业。选项由 oauth/context 返回。
|
||||
*/
|
||||
const ScopeOptionList = ({ options, value, onChange, disabled }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<RadioGroup
|
||||
type='pureCard'
|
||||
direction='vertical'
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
aria-label={t('选择使用范围')}
|
||||
className='w-full'
|
||||
>
|
||||
{options.map((option) => {
|
||||
const isOrg = option.scope === 'organization';
|
||||
const key = optionKey(option);
|
||||
return (
|
||||
<Radio
|
||||
key={key}
|
||||
value={key}
|
||||
className='w-full'
|
||||
extra={
|
||||
<Text type='tertiary' size='small'>
|
||||
{isOrg ? t('企业范围') : t('个人范围')}
|
||||
</Text>
|
||||
}
|
||||
>
|
||||
<div className='flex items-center gap-2 min-w-0'>
|
||||
{option.logo ? (
|
||||
<Avatar src={option.logo} size='extra-small' shape='square' />
|
||||
) : (
|
||||
<Avatar size='extra-small' shape='square' color='light-blue'>
|
||||
{isOrg ? <Building2 size={14} /> : <User size={14} />}
|
||||
</Avatar>
|
||||
)}
|
||||
<Text strong ellipsis={{ showTooltip: true }}>
|
||||
{isOrg ? option.name : option.name || t('个人')}
|
||||
</Text>
|
||||
</div>
|
||||
</Radio>
|
||||
);
|
||||
})}
|
||||
</RadioGroup>
|
||||
);
|
||||
};
|
||||
|
||||
export default ScopeOptionList;
|
||||
@@ -0,0 +1,428 @@
|
||||
/* 进入 WeyAi 的过渡画面。配色全部由主题 token 派生(品牌色换预设、亮暗切换
|
||||
都自动跟随),整页背景交给 PageBackground 单层渲染,这里只画徽标、进度与
|
||||
一个聚焦用的居中光晕。动效在 prefers-reduced-motion 下全部关闭。 */
|
||||
.weyai-handoff {
|
||||
--ho-ink: var(--text-primary);
|
||||
--ho-muted: var(--text-secondary);
|
||||
--ho-line: var(--border-subtle);
|
||||
--ho-card: var(--surface-card);
|
||||
/* 主色只取品牌 token:--semi-color-primary 要等 /api/status 回来由
|
||||
helpers/theme.js 注入,首次访问(OAuth 从 WeyAi 拉起的新会话正是这种)
|
||||
在那之前是 Semi 默认蓝,与 --brand-primary-rgb 派生的环/光晕会是两种蓝。
|
||||
两个变量同批注入、同源,注入前后都一致 */
|
||||
--ho-accent: rgb(var(--brand-primary-rgb));
|
||||
--ho-accent-rgb: var(--brand-primary-rgb);
|
||||
--ho-tint: color-mix(in srgb, var(--ho-accent) 12%, transparent);
|
||||
--ho-tint-strong: color-mix(in srgb, var(--ho-accent) 28%, transparent);
|
||||
color: var(--ho-ink);
|
||||
}
|
||||
|
||||
/* ───── 居中光晕 ───── */
|
||||
.weyai-handoff__halo {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: min(70vw, 560px);
|
||||
height: min(70vw, 560px);
|
||||
transform: translate(-50%, -56%);
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(
|
||||
circle at center,
|
||||
rgb(var(--ho-accent-rgb) / 0.22) 0%,
|
||||
rgb(var(--ho-accent-rgb) / 0.08) 38%,
|
||||
transparent 70%
|
||||
);
|
||||
/* 不加 filter: blur —— 径向渐变到 70% 已是透明,模糊看不出差别,却让
|
||||
低端机每帧多做一次几百像素的 GPU 模糊 */
|
||||
pointer-events: none;
|
||||
animation: weyai-handoff-breathe 5s ease-in-out infinite;
|
||||
}
|
||||
.dark .weyai-handoff__halo {
|
||||
background: radial-gradient(
|
||||
circle at center,
|
||||
rgb(var(--ho-accent-rgb) / 0.3) 0%,
|
||||
rgb(var(--ho-accent-rgb) / 0.1) 38%,
|
||||
transparent 70%
|
||||
);
|
||||
}
|
||||
|
||||
/* ───── 内容面板 ───── */
|
||||
.weyai-handoff__panel {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
padding: 8px 0 24px;
|
||||
animation: weyai-handoff-rise 0.3s cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
/* ───── 徽标:脉动光环 + 旋转弧 + 环绕光点 + 品牌 tile ───── */
|
||||
.weyai-handoff__emblem {
|
||||
position: relative;
|
||||
width: 128px;
|
||||
height: 128px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.weyai-handoff__pulse {
|
||||
position: absolute;
|
||||
inset: -18px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(
|
||||
circle,
|
||||
rgb(var(--ho-accent-rgb) / 0.28) 0%,
|
||||
rgb(var(--ho-accent-rgb) / 0.06) 55%,
|
||||
transparent 72%
|
||||
);
|
||||
animation: weyai-handoff-pulse 2.4s ease-out infinite;
|
||||
}
|
||||
.weyai-handoff__ring {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: 50%;
|
||||
background: conic-gradient(
|
||||
from 0deg,
|
||||
transparent 0deg,
|
||||
transparent 200deg,
|
||||
rgb(var(--ho-accent-rgb) / 0.15) 260deg,
|
||||
rgb(var(--ho-accent-rgb) / 0.95) 360deg
|
||||
);
|
||||
/* mask 只取 alpha:把实心圆盘挖成 3px 圆环。颜色值本身不参与显示 */
|
||||
-webkit-mask: radial-gradient(
|
||||
farthest-side,
|
||||
transparent calc(100% - 3.5px),
|
||||
#000 calc(100% - 2.5px)
|
||||
);
|
||||
mask: radial-gradient(
|
||||
farthest-side,
|
||||
transparent calc(100% - 3.5px),
|
||||
#000 calc(100% - 2.5px)
|
||||
);
|
||||
animation: weyai-handoff-spin 1.3s linear infinite;
|
||||
}
|
||||
.weyai-handoff__orbit {
|
||||
position: absolute;
|
||||
inset: 12px;
|
||||
border-radius: 50%;
|
||||
border: 1px dashed var(--ho-tint-strong);
|
||||
animation: weyai-handoff-spin 6s linear infinite reverse;
|
||||
}
|
||||
.weyai-handoff__orbit i {
|
||||
position: absolute;
|
||||
top: -5px;
|
||||
left: calc(50% - 5px);
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background: var(--ho-accent);
|
||||
box-shadow: 0 0 0 4px rgb(var(--ho-accent-rgb) / 0.18);
|
||||
}
|
||||
.weyai-handoff__tile {
|
||||
position: absolute;
|
||||
inset: 30px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 18px;
|
||||
background: var(--ho-card);
|
||||
border: 1px solid color-mix(in srgb, var(--ho-accent) 18%, var(--ho-line));
|
||||
box-shadow:
|
||||
0 18px 40px -16px rgb(var(--ho-accent-rgb) / 0.45),
|
||||
0 2px 6px rgb(var(--ho-accent-rgb) / 0.08);
|
||||
}
|
||||
.weyai-handoff__logo {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 10px;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
/* ───── 文案 ───── */
|
||||
.weyai-handoff__title {
|
||||
margin: 0 0 6px;
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
line-height: 1.3;
|
||||
color: var(--ho-ink);
|
||||
}
|
||||
.weyai-handoff__dots {
|
||||
display: inline-flex;
|
||||
gap: 3px;
|
||||
margin-left: 4px;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
.weyai-handoff__dots i {
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 50%;
|
||||
background: var(--ho-accent);
|
||||
opacity: 0.25;
|
||||
animation: weyai-handoff-blink 1.2s ease-in-out infinite;
|
||||
}
|
||||
.weyai-handoff__dots i:nth-child(2) {
|
||||
animation-delay: 0.2s;
|
||||
}
|
||||
.weyai-handoff__dots i:nth-child(3) {
|
||||
animation-delay: 0.4s;
|
||||
}
|
||||
.weyai-handoff__subtitle {
|
||||
margin: 0 0 28px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--ho-muted);
|
||||
}
|
||||
|
||||
/* ───── 三步进度 ───── */
|
||||
.weyai-handoff__steps {
|
||||
list-style: none;
|
||||
margin: 0 0 14px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
.weyai-handoff__step {
|
||||
position: relative;
|
||||
flex: 1 1 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
.weyai-handoff__step-dot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--ho-line);
|
||||
background: var(--ho-card);
|
||||
color: var(--ho-card);
|
||||
transition:
|
||||
border-color 0.2s,
|
||||
background-color 0.2s,
|
||||
box-shadow 0.2s;
|
||||
}
|
||||
/* 标签允许折两行:390px 下每步只有约 110px,英/日/泰/越的"建立安全会话"
|
||||
单行放不下,nowrap + 省略号会把它切成 "Establish secure se…" */
|
||||
.weyai-handoff__step-label {
|
||||
max-width: 100%;
|
||||
padding: 0 4px;
|
||||
font-size: 12px;
|
||||
line-height: 1.3;
|
||||
color: var(--ho-muted);
|
||||
overflow-wrap: anywhere;
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
overflow: hidden;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
/* 连接线:从本步圆点右缘到下一步圆点左缘 */
|
||||
.weyai-handoff__step-line {
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: calc(50% + 13px);
|
||||
right: calc(-50% + 13px);
|
||||
height: 2px;
|
||||
border-radius: 2px;
|
||||
background: var(--ho-line);
|
||||
}
|
||||
.weyai-handoff__step--done .weyai-handoff__step-dot {
|
||||
border-color: var(--ho-accent);
|
||||
background: var(--ho-accent);
|
||||
color: var(--ho-card);
|
||||
}
|
||||
.weyai-handoff__step--done .weyai-handoff__step-line {
|
||||
background: var(--ho-accent);
|
||||
}
|
||||
.weyai-handoff__step--done .weyai-handoff__step-label {
|
||||
color: var(--ho-ink);
|
||||
}
|
||||
.weyai-handoff__step--active .weyai-handoff__step-dot {
|
||||
border-color: var(--ho-accent);
|
||||
box-shadow: 0 0 0 5px var(--ho-tint);
|
||||
animation: weyai-handoff-dot 1.6s ease-in-out infinite;
|
||||
}
|
||||
.weyai-handoff__step--active .weyai-handoff__step-label {
|
||||
color: var(--ho-accent);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ───── 进度条:宽度跟真实阶段走,高光只是让它"活着" ───── */
|
||||
.weyai-handoff__bar {
|
||||
position: relative;
|
||||
width: min(100%, 280px);
|
||||
height: 4px;
|
||||
border-radius: 999px;
|
||||
background: var(--ho-tint);
|
||||
overflow: hidden;
|
||||
}
|
||||
.weyai-handoff__bar-fill {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
border-radius: inherit;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
color-mix(in srgb, var(--ho-accent) 70%, var(--ho-card)),
|
||||
var(--ho-accent)
|
||||
);
|
||||
transition: width 0.2s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
/* 镜面高光:白色是"反光"本身而非配色,属固定色例外;只在已填充段内扫动 */
|
||||
.weyai-handoff__bar-shine {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
width: 40%;
|
||||
border-radius: inherit;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
rgb(255 255 255 / 0.55),
|
||||
transparent
|
||||
);
|
||||
animation: weyai-handoff-shine 1.8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* ───── 跳转卡住时的手动入口 ───── */
|
||||
.weyai-handoff__manual {
|
||||
margin-top: 22px;
|
||||
padding: 8px 16px;
|
||||
border-radius: 999px;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
/* 主色直接放在淡色底上约 4.1:1,不到 AA;往墨色压两成,亮色压深、暗色提亮 */
|
||||
color: color-mix(in srgb, var(--ho-accent) 80%, var(--ho-ink));
|
||||
background: var(--ho-tint);
|
||||
border: 1px solid var(--ho-tint-strong);
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
transition:
|
||||
background-color 0.2s,
|
||||
box-shadow 0.2s;
|
||||
animation: weyai-handoff-rise 0.3s ease-out both;
|
||||
}
|
||||
.weyai-handoff__manual:hover {
|
||||
background: var(--ho-tint-strong);
|
||||
}
|
||||
.weyai-handoff__manual:focus-visible {
|
||||
outline: 2px solid color-mix(in srgb, var(--ho-accent) 55%, transparent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ───── 动画 ───── */
|
||||
@keyframes weyai-handoff-spin {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@keyframes weyai-handoff-pulse {
|
||||
0% {
|
||||
transform: scale(0.85);
|
||||
opacity: 0.9;
|
||||
}
|
||||
70% {
|
||||
transform: scale(1.15);
|
||||
opacity: 0;
|
||||
}
|
||||
100% {
|
||||
transform: scale(1.15);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@keyframes weyai-handoff-breathe {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.75;
|
||||
transform: translate(-50%, -56%) scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
transform: translate(-50%, -56%) scale(1.06);
|
||||
}
|
||||
}
|
||||
@keyframes weyai-handoff-rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
@keyframes weyai-handoff-blink {
|
||||
0%,
|
||||
80%,
|
||||
100% {
|
||||
opacity: 0.25;
|
||||
}
|
||||
40% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes weyai-handoff-dot {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow: 0 0 0 4px var(--ho-tint);
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 0 0 7px var(--ho-tint);
|
||||
}
|
||||
}
|
||||
@keyframes weyai-handoff-shine {
|
||||
from {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
to {
|
||||
transform: translateX(250%);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.weyai-handoff__halo,
|
||||
.weyai-handoff__panel,
|
||||
.weyai-handoff__pulse,
|
||||
.weyai-handoff__ring,
|
||||
.weyai-handoff__orbit,
|
||||
.weyai-handoff__dots i,
|
||||
.weyai-handoff__step--active .weyai-handoff__step-dot,
|
||||
.weyai-handoff__bar-shine,
|
||||
.weyai-handoff__manual,
|
||||
.weyai-handoff .animate-pulse {
|
||||
animation: none;
|
||||
}
|
||||
.weyai-handoff__dots i {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.weyai-handoff__bar-shine {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.weyai-handoff__emblem {
|
||||
width: 108px;
|
||||
height: 108px;
|
||||
}
|
||||
.weyai-handoff__tile {
|
||||
inset: 26px;
|
||||
}
|
||||
.weyai-handoff__title {
|
||||
font-size: 19px;
|
||||
}
|
||||
.weyai-handoff__step-label {
|
||||
font-size: 11px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 进入 WeyAi 的过渡画面。授权页在三个瞬态里没有任何可操作内容:拉授权信息、
|
||||
// 静默签发、授权完成等浏览器跳走。原来这三态套在登录卡片里只放一个 Spin,
|
||||
// 而登录页背景主题是按需懒加载的 chunk,这个页面通常在 chunk 到达前就跳走了,
|
||||
// 用户看到的是"空白底 + 小转圈"。这里改为:同步渲染的 token 派生背景
|
||||
// (PageBackground,随主题预设与亮暗自动变化)+ 品牌环形加载动画 + 三步
|
||||
// 真实进度(按 phase 推进,不是假进度条)。
|
||||
//
|
||||
// 跳转卡住的兜底:授权完成后浏览器应当立刻跳走,若数秒后还停在这里(弹窗
|
||||
// 拦截、location.replace 被扩展拦下),显示手动入口,用户不至于干等。手动
|
||||
// 入口是**重新走一遍授权**(整页刷新),不是再打一次回跳地址:回跳地址里的
|
||||
// code 只能核销一次,若第一次跳转其实已经到达网关只是慢,再打一次会让网关
|
||||
// 拿着已核销的 code 报错,反而把本来会成功的登录弄坏。刷新会重新拉上下文、
|
||||
// 静默签发新 code,无论第一次是没发出去还是发出去了都能收敛。
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import PageBackground from '../../components/common/PageBackground';
|
||||
import './WeyAiHandoff.css';
|
||||
|
||||
// 授权完成后等多久还没跳走就露出手动入口。网关换 token 正常在 1 秒内,
|
||||
// 8 秒仍未离开这一页基本可以断定跳转没发出去
|
||||
const MANUAL_RETRY_DELAY_MS = 8000;
|
||||
|
||||
export const HANDOFF_STAGE_LOADING = 0;
|
||||
export const HANDOFF_STAGE_ISSUING = 1;
|
||||
export const HANDOFF_STAGE_REDIRECT = 2;
|
||||
|
||||
export default function WeyAiHandoff({
|
||||
logo,
|
||||
stage,
|
||||
title,
|
||||
subtitle,
|
||||
clientName = 'WeyAi',
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [showManual, setShowManual] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (stage !== HANDOFF_STAGE_REDIRECT) {
|
||||
setShowManual(false);
|
||||
return undefined;
|
||||
}
|
||||
const timer = setTimeout(() => setShowManual(true), MANUAL_RETRY_DELAY_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [stage]);
|
||||
|
||||
const steps = [
|
||||
t('验证账号'),
|
||||
t('建立安全会话'),
|
||||
t('打开 {{name}}', { name: clientName }),
|
||||
];
|
||||
|
||||
return (
|
||||
<div
|
||||
className='weyai-handoff relative overflow-hidden flex items-center justify-center px-4 sm:px-6 lg:px-8'
|
||||
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||||
>
|
||||
<PageBackground variant='rich' grid animate />
|
||||
{/* 居中光晕:把视线聚到徽标上,颜色随品牌色 */}
|
||||
<div className='weyai-handoff__halo' aria-hidden='true' />
|
||||
|
||||
<div className='weyai-handoff__panel relative z-10'>
|
||||
<div className='weyai-handoff__emblem' aria-hidden='true'>
|
||||
<span className='weyai-handoff__pulse' />
|
||||
<span className='weyai-handoff__ring' />
|
||||
<span className='weyai-handoff__orbit'>
|
||||
<i />
|
||||
</span>
|
||||
<span className='weyai-handoff__tile'>
|
||||
<img src={logo} alt='' className='weyai-handoff__logo' />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 播报区只包住标题与副标题:整块面板做 live region 会把三个步骤名
|
||||
和链接一并复读,而步骤推进本身又不改文本、读屏听不到 */}
|
||||
<div role='status' aria-live='polite'>
|
||||
<h1 className='weyai-handoff__title'>
|
||||
{title}
|
||||
<span className='weyai-handoff__dots' aria-hidden='true'>
|
||||
<i />
|
||||
<i />
|
||||
<i />
|
||||
</span>
|
||||
</h1>
|
||||
<p className='weyai-handoff__subtitle'>{subtitle}</p>
|
||||
</div>
|
||||
|
||||
<ol className='weyai-handoff__steps' aria-label={t('进度')}>
|
||||
{steps.map((label, index) => {
|
||||
const state =
|
||||
index < stage ? 'done' : index === stage ? 'active' : 'todo';
|
||||
return (
|
||||
<li
|
||||
key={label}
|
||||
className={`weyai-handoff__step weyai-handoff__step--${state}`}
|
||||
aria-current={state === 'active' ? 'step' : undefined}
|
||||
>
|
||||
<span className='weyai-handoff__step-dot'>
|
||||
{state === 'done' ? (
|
||||
<Check size={11} strokeWidth={3} />
|
||||
) : null}
|
||||
</span>
|
||||
<span className='weyai-handoff__step-label'>{label}</span>
|
||||
{index < steps.length - 1 && (
|
||||
<span
|
||||
className='weyai-handoff__step-line'
|
||||
aria-hidden='true'
|
||||
/>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
|
||||
<div className='weyai-handoff__bar' aria-hidden='true'>
|
||||
{/* 高光放在已填充段内部:放在轨道上会扫过未填充的那截,暗色下像
|
||||
多了一根乱动的亮条 */}
|
||||
<span
|
||||
className='weyai-handoff__bar-fill'
|
||||
style={{ width: `${((stage + 1) / steps.length) * 100}%` }}
|
||||
>
|
||||
<span className='weyai-handoff__bar-shine' />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{showManual && (
|
||||
<button
|
||||
type='button'
|
||||
className='weyai-handoff__manual'
|
||||
onClick={() => window.location.reload()}
|
||||
>
|
||||
{t('没有自动跳转?点此重试')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// 授权页的纯函数(不依赖 React 和请求封装,便于单测)。
|
||||
|
||||
export const DESKTOP_CLIENT_ID = 'weyai-desktop';
|
||||
|
||||
// 页面从地址栏读取、原样透传给服务端的参数(页面自己不拼 redirect_uri)
|
||||
export const AUTHORIZE_PARAM_KEYS = [
|
||||
'client_id',
|
||||
'redirect_uri',
|
||||
'state',
|
||||
'code_challenge',
|
||||
'code_challenge_method',
|
||||
'scope_hint',
|
||||
'device_name',
|
||||
'prompt',
|
||||
];
|
||||
|
||||
export function readAuthorizeParams(searchParams) {
|
||||
const params = {};
|
||||
AUTHORIZE_PARAM_KEYS.forEach((key) => {
|
||||
params[key] = searchParams.get(key) || '';
|
||||
});
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 axios 错误或 success:false 响应统一成 { status, code, message, data }。
|
||||
*/
|
||||
export function parseClientApiError(error) {
|
||||
const response = error?.response;
|
||||
const body = response?.data;
|
||||
const isObject = body && typeof body === 'object';
|
||||
return {
|
||||
status: response?.status || 0,
|
||||
code: (isObject && body.code) || '',
|
||||
message: (isObject && body.message) || '',
|
||||
data: (isObject && body.data) || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 只放行服务端返回的 http(s) 或 weyai: 跳转地址,挡住 javascript:/data: 之类的伪协议。
|
||||
* 地址本身由服务端按登记的 redirect_uri 生成,页面不做任何拼接。
|
||||
*/
|
||||
export function isAllowedRedirect(redirect) {
|
||||
if (!redirect || typeof redirect !== 'string') return false;
|
||||
let url;
|
||||
try {
|
||||
url = new URL(redirect);
|
||||
} catch (_e) {
|
||||
return false;
|
||||
}
|
||||
return ['https:', 'http:', 'weyai:'].includes(url.protocol);
|
||||
}
|
||||
|
||||
/**
|
||||
* 未登录时的登录页地址:按 scope_hint 去个人登录或企业登录,登录后回到当前授权页。
|
||||
* 没有 scope_hint(网页端网关发起)时与 PrivateRoute 一致,默认去企业登录页,
|
||||
* 页内可切换到个人登录,回跳地址已由登录页写入本地存储。
|
||||
*/
|
||||
export function buildLoginTarget(scopeHint, currentPath) {
|
||||
const base = scopeHint === 'personal' ? '/login' : '/org/login';
|
||||
return `${base}?redirect=${encodeURIComponent(currentPath)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET oauth/context 的查询参数:client_id、redirect_uri 决定合法性,prompt 决定是否
|
||||
* 静默,scope_hint(personal / organization,桌面端登录入口带)决定默认选中个人还是企业。
|
||||
* 空值不传,避免服务端把空串当成显式的 hint。
|
||||
*/
|
||||
export function buildContextQuery(params) {
|
||||
const query = {};
|
||||
['client_id', 'redirect_uri', 'prompt', 'scope_hint'].forEach((key) => {
|
||||
const value = params?.[key];
|
||||
if (value) query[key] = value;
|
||||
});
|
||||
return query;
|
||||
}
|
||||
|
||||
export function optionKey(option) {
|
||||
if (!option) return '';
|
||||
return `${option.scope}:${Number(option.org_id) || 0}`;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
buildContextQuery,
|
||||
buildLoginTarget,
|
||||
isAllowedRedirect,
|
||||
optionKey,
|
||||
parseClientApiError,
|
||||
readAuthorizeParams,
|
||||
} from './authorizeParams.js';
|
||||
|
||||
test('isAllowedRedirect only accepts http(s) and weyai schemes', () => {
|
||||
assert.equal(isAllowedRedirect('weyai://auth/callback?code=a&state=b'), true);
|
||||
assert.equal(isAllowedRedirect('https://ai.example.com/sso/callback'), true);
|
||||
assert.equal(isAllowedRedirect('javascript:alert(1)'), false);
|
||||
assert.equal(isAllowedRedirect('data:text/html,hi'), false);
|
||||
assert.equal(isAllowedRedirect('/relative'), false);
|
||||
assert.equal(isAllowedRedirect(''), false);
|
||||
assert.equal(isAllowedRedirect(undefined), false);
|
||||
});
|
||||
|
||||
test('buildLoginTarget follows scope_hint and keeps the return path', () => {
|
||||
const path = '/client/authorize?client_id=weyai-desktop&state=x';
|
||||
assert.equal(
|
||||
buildLoginTarget('personal', path),
|
||||
`/login?redirect=${encodeURIComponent(path)}`,
|
||||
);
|
||||
assert.equal(
|
||||
buildLoginTarget('organization', path),
|
||||
`/org/login?redirect=${encodeURIComponent(path)}`,
|
||||
);
|
||||
assert.equal(
|
||||
buildLoginTarget('', path),
|
||||
`/org/login?redirect=${encodeURIComponent(path)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('readAuthorizeParams reads every known param with empty defaults', () => {
|
||||
const params = readAuthorizeParams(
|
||||
new URLSearchParams('client_id=weyai-web&prompt=select&extra=1'),
|
||||
);
|
||||
assert.equal(params.client_id, 'weyai-web');
|
||||
assert.equal(params.prompt, 'select');
|
||||
assert.equal(params.redirect_uri, '');
|
||||
assert.equal('extra' in params, false);
|
||||
});
|
||||
|
||||
test('optionKey distinguishes personal and organization scopes', () => {
|
||||
assert.equal(optionKey({ scope: 'personal', org_id: 0 }), 'personal:0');
|
||||
assert.equal(
|
||||
optionKey({ scope: 'organization', org_id: '12' }),
|
||||
'organization:12',
|
||||
);
|
||||
assert.equal(optionKey(null), '');
|
||||
});
|
||||
|
||||
test('parseClientApiError extracts code, message and data', () => {
|
||||
const err = parseClientApiError({
|
||||
response: {
|
||||
status: 403,
|
||||
data: {
|
||||
success: false,
|
||||
code: 'SCOPE_NOT_ALLOWED',
|
||||
message: 'no',
|
||||
data: { reason: 'org_only' },
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(err, {
|
||||
status: 403,
|
||||
code: 'SCOPE_NOT_ALLOWED',
|
||||
message: 'no',
|
||||
data: { reason: 'org_only' },
|
||||
});
|
||||
assert.equal(parseClientApiError(new Error('network')).status, 0);
|
||||
});
|
||||
|
||||
test('buildContextQuery forwards scope_hint and drops empty values', () => {
|
||||
assert.deepEqual(
|
||||
buildContextQuery({
|
||||
client_id: 'weyai-desktop',
|
||||
redirect_uri: 'weyai://auth/callback',
|
||||
state: 'xyz',
|
||||
scope_hint: 'organization',
|
||||
prompt: '',
|
||||
}),
|
||||
{
|
||||
client_id: 'weyai-desktop',
|
||||
redirect_uri: 'weyai://auth/callback',
|
||||
scope_hint: 'organization',
|
||||
},
|
||||
);
|
||||
assert.deepEqual(buildContextQuery(undefined), {});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// WeyAi 客户端授权页(/client/authorize)的接口封装。
|
||||
// 接口约定见 WeyAi 仓库 docs/fork/账号登录接入方案.md 4.2、4.4:
|
||||
// 成功 { success: true, data };失败 { success: false, code, message, data },
|
||||
// 客户端只按 code 分支。
|
||||
|
||||
import { API } from '../../helpers/api';
|
||||
import { buildContextQuery } from './authorizeParams';
|
||||
|
||||
function unwrap(res) {
|
||||
const body = res?.data;
|
||||
if (body && body.success === false) {
|
||||
const err = new Error(body.message || 'request failed');
|
||||
err.response = res;
|
||||
throw err;
|
||||
}
|
||||
// 兼容 { success, data } 与直接返回数据两种形态
|
||||
if (body && typeof body === 'object' && 'data' in body) {
|
||||
return body.data;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function fetchOAuthContext(params) {
|
||||
const res = await API.get('/api/client/v1/oauth/context', {
|
||||
params: buildContextQuery(params),
|
||||
skipErrorHandler: true,
|
||||
disableDuplicate: true,
|
||||
});
|
||||
return unwrap(res);
|
||||
}
|
||||
|
||||
export async function submitAuthorize(payload) {
|
||||
const res = await API.post('/api/client/v1/oauth/authorize', payload, {
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
return unwrap(res);
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
// WeyAi 客户端授权页 /client/authorize(方案 4.4)。
|
||||
// - 自带登录判断,不套 PrivateRoute(PrivateRoute 总是去企业登录页)。
|
||||
// - client_id / redirect_uri 不合法时只报错、不做任何跳转。
|
||||
// - 所有跳转地址都用服务端返回的 redirect,页面绝不自己拼 redirect_uri。
|
||||
// - 页面禁止被嵌入:服务端应下发 X-Frame-Options / frame-ancestors,这里再做前端兜底。
|
||||
|
||||
import React, {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Banner, Button, Typography } from '@douyinfe/semi-ui';
|
||||
import { Monitor } from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { clearUserData, getLogo } from '../../helpers';
|
||||
import { UserContext } from '../../context/User';
|
||||
import GlassCard from '../../components/auth/GlassCard';
|
||||
import AuthCardHeader from '../../components/auth/AuthCardHeader';
|
||||
import AuthBackground from '../../components/common/AuthBackground';
|
||||
import ScopeOptionList from './ScopeOptionList';
|
||||
import WeyAiHandoff, {
|
||||
HANDOFF_STAGE_ISSUING,
|
||||
HANDOFF_STAGE_LOADING,
|
||||
HANDOFF_STAGE_REDIRECT,
|
||||
} from './WeyAiHandoff';
|
||||
import { fetchOAuthContext, submitAuthorize } from './clientAuthorizeApi';
|
||||
import {
|
||||
DESKTOP_CLIENT_ID,
|
||||
buildLoginTarget,
|
||||
isAllowedRedirect,
|
||||
optionKey,
|
||||
parseClientApiError,
|
||||
readAuthorizeParams,
|
||||
} from './authorizeParams';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
// 被 iframe 嵌入时(点击劫持)不渲染任何可操作内容,并尝试跳出框架。
|
||||
function detectFramed() {
|
||||
try {
|
||||
return window.self !== window.top;
|
||||
} catch (_e) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
const ClientAuthorize = () => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const [, userDispatch] = useContext(UserContext);
|
||||
const logo = getLogo();
|
||||
|
||||
const params = useMemo(
|
||||
() => readAuthorizeParams(searchParams),
|
||||
[searchParams],
|
||||
);
|
||||
const isDesktop = params.client_id === DESKTOP_CLIENT_ID;
|
||||
const currentPath = `${location.pathname}${location.search}`;
|
||||
|
||||
const [framed] = useState(detectFramed);
|
||||
// phase: loading | fatal | ready | submitting | done
|
||||
const [phase, setPhase] = useState('loading');
|
||||
const [fatalMessage, setFatalMessage] = useState('');
|
||||
const [context, setContext] = useState(null);
|
||||
const [selected, setSelected] = useState('');
|
||||
const [inlineError, setInlineError] = useState('');
|
||||
const [doneInfo, setDoneInfo] = useState(null);
|
||||
const autoSubmittedRef = useRef(false);
|
||||
|
||||
const reasonText = useCallback(
|
||||
(reason) => {
|
||||
switch (reason) {
|
||||
case 'org_only_no_org':
|
||||
case 'org_only':
|
||||
return t('当前账号仅能使用企业资源,但没有可用的企业');
|
||||
case 'web_access_denied':
|
||||
return t('你的账号暂未开通 WeyAi 网页端,请联系管理员');
|
||||
case 'super_admin':
|
||||
return t('超级管理员只能使用个人范围');
|
||||
case 'not_member':
|
||||
return t('你已不是该企业的成员');
|
||||
case 'org_unusable':
|
||||
return t('该企业当前不可用(已冻结、欠费或待审核)');
|
||||
default:
|
||||
return t('当前账号没有可用的使用范围');
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const goLogin = useCallback(() => {
|
||||
// 服务端判定未登录时,本地缓存的登录态已失效:清掉,否则 /login 的
|
||||
// AuthRedirect 会把「看起来已登录」的用户弹到体验中心,回不到授权页。
|
||||
clearUserData();
|
||||
userDispatch({ type: 'logout' });
|
||||
navigate(buildLoginTarget(params.scope_hint, currentPath), {
|
||||
replace: true,
|
||||
});
|
||||
}, [currentPath, navigate, params.scope_hint, userDispatch]);
|
||||
|
||||
const loadContext = useCallback(async () => {
|
||||
setPhase('loading');
|
||||
setInlineError('');
|
||||
if (!params.client_id || !params.redirect_uri) {
|
||||
setFatalMessage(t('授权请求无效:缺少客户端或回调地址'));
|
||||
setPhase('fatal');
|
||||
return;
|
||||
}
|
||||
// 与后端 Authorize 的必填项对齐。缺这几个参数时后端一定拒绝,不先拦住
|
||||
// 就会让用户选完范围、点了"允许"才看到报错,而且无从补救
|
||||
if (
|
||||
!params.state ||
|
||||
!params.code_challenge ||
|
||||
params.code_challenge_method !== 'S256'
|
||||
) {
|
||||
setFatalMessage(t('授权请求无效:缺少必要的安全参数'));
|
||||
setPhase('fatal');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data = await fetchOAuthContext(params);
|
||||
const options = Array.isArray(data?.options) ? data.options : [];
|
||||
setContext({ ...data, options });
|
||||
const preferred = data?.default_option
|
||||
? optionKey(data.default_option)
|
||||
: '';
|
||||
const hasPreferred = options.some(
|
||||
(option) => optionKey(option) === preferred,
|
||||
);
|
||||
setSelected(
|
||||
hasPreferred ? preferred : options[0] ? optionKey(options[0]) : '',
|
||||
);
|
||||
setPhase('ready');
|
||||
} catch (error) {
|
||||
const err = parseClientApiError(error);
|
||||
if (err.code === 'INVALID_CLIENT') {
|
||||
setFatalMessage(t('授权请求无效:客户端或回调地址不合法'));
|
||||
setPhase('fatal');
|
||||
return;
|
||||
}
|
||||
// weyai-remote(公网访问):后台总开关关闭
|
||||
if (err.code === 'REMOTE_DISABLED') {
|
||||
setFatalMessage(t('WeyAi 公网访问暂未开放,请联系管理员'));
|
||||
setPhase('fatal');
|
||||
return;
|
||||
}
|
||||
if (err.code === 'UNAUTHENTICATED' || err.status === 401) {
|
||||
goLogin();
|
||||
return;
|
||||
}
|
||||
if (err.code === 'INVALID_REQUEST') {
|
||||
setFatalMessage(t('授权请求参数有误'));
|
||||
} else if (err.code === 'RATE_LIMITED') {
|
||||
setFatalMessage(t('请求过于频繁,请稍后再试'));
|
||||
} else {
|
||||
setFatalMessage(err.message || t('加载授权信息失败,请稍后重试'));
|
||||
}
|
||||
setPhase('fatal');
|
||||
}
|
||||
}, [goLogin, params, t]);
|
||||
|
||||
// 只在进入页面(或地址参数变化)时加载一次;切换语言等导致的回调重建不重复拉取
|
||||
const loadedForRef = useRef('');
|
||||
useEffect(() => {
|
||||
if (framed) {
|
||||
try {
|
||||
window.top.location.replace(window.location.href);
|
||||
} catch (_e) {
|
||||
// 跨域父页面不允许改写 location,保持不渲染操作按钮即可
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (loadedForRef.current === location.search) return;
|
||||
loadedForRef.current = location.search;
|
||||
loadContext();
|
||||
}, [framed, loadContext, location.search]);
|
||||
|
||||
const followRedirect = useCallback(
|
||||
(redirect, denied) => {
|
||||
if (!isAllowedRedirect(redirect)) {
|
||||
setFatalMessage(t('服务端返回的跳转地址无效'));
|
||||
setPhase('fatal');
|
||||
return;
|
||||
}
|
||||
// 拒绝授权与"没有网页端权限"都是 200 + redirect,只有回跳地址里的
|
||||
// error= 能区分。不看它就会在被拒时显示"授权完成,正在跳转"
|
||||
let refused = denied;
|
||||
if (!refused) {
|
||||
try {
|
||||
refused = !!new URL(
|
||||
redirect,
|
||||
window.location.origin,
|
||||
).searchParams.get('error');
|
||||
} catch {
|
||||
refused = false;
|
||||
}
|
||||
}
|
||||
setDoneInfo({ redirect, denied: refused });
|
||||
setPhase('done');
|
||||
window.location.replace(redirect);
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const submit = useCallback(
|
||||
async ({ deny = false, optionKeyValue } = {}) => {
|
||||
const option = context?.options?.find(
|
||||
(item) => optionKey(item) === (optionKeyValue || selected),
|
||||
);
|
||||
if (!deny && !option) {
|
||||
setInlineError(t('请选择使用范围'));
|
||||
return;
|
||||
}
|
||||
setPhase('submitting');
|
||||
setInlineError('');
|
||||
const payload = {
|
||||
client_id: params.client_id,
|
||||
redirect_uri: params.redirect_uri,
|
||||
state: params.state,
|
||||
code_challenge: params.code_challenge,
|
||||
code_challenge_method: params.code_challenge_method,
|
||||
scope: option ? option.scope : 'personal',
|
||||
org_id: option ? Number(option.org_id) || 0 : 0,
|
||||
};
|
||||
if (params.device_name) payload.device_name = params.device_name;
|
||||
if (deny) payload.deny = true;
|
||||
try {
|
||||
const data = await submitAuthorize(payload);
|
||||
followRedirect(data?.redirect, deny);
|
||||
} catch (error) {
|
||||
const err = parseClientApiError(error);
|
||||
if (err.code === 'UNAUTHENTICATED') {
|
||||
goLogin();
|
||||
return;
|
||||
}
|
||||
if (err.code === 'INVALID_CLIENT') {
|
||||
setFatalMessage(t('授权请求无效:客户端或回调地址不合法'));
|
||||
setPhase('fatal');
|
||||
return;
|
||||
}
|
||||
if (err.code === 'REMOTE_DISABLED') {
|
||||
setFatalMessage(t('WeyAi 公网访问暂未开放,请联系管理员'));
|
||||
setPhase('fatal');
|
||||
return;
|
||||
}
|
||||
if (err.code === 'SCOPE_NOT_ALLOWED') {
|
||||
// 可选范围可能已变化(例如刚被移出企业),重新拉取后再让用户选
|
||||
await loadContext();
|
||||
setInlineError(reasonText(err.data?.reason));
|
||||
return;
|
||||
}
|
||||
if (err.code === 'WEB_ACCESS_DENIED') {
|
||||
setInlineError(reasonText('web_access_denied'));
|
||||
} else if (err.code === 'RATE_LIMITED') {
|
||||
setInlineError(t('请求过于频繁,请稍后再试'));
|
||||
} else if (err.code === 'INVALID_REQUEST') {
|
||||
setInlineError(t('授权请求参数有误'));
|
||||
} else {
|
||||
setInlineError(err.message || t('授权失败,请稍后重试'));
|
||||
}
|
||||
setPhase('ready');
|
||||
}
|
||||
},
|
||||
[
|
||||
context,
|
||||
followRedirect,
|
||||
goLogin,
|
||||
loadContext,
|
||||
params,
|
||||
reasonText,
|
||||
selected,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
// 网页端可以静默签发的条件:服务端要求静默、有默认范围、且默认范围确实在
|
||||
// 可选范围里。最后一条与自动提交 effect 共用:只在 effect 里判会让"默认项
|
||||
// 不在可选范围"时自动提交被跳过、而过渡画面仍以为在签发,页面永久停在
|
||||
// "正在进入"且没有任何可操作项。不满足就回卡片让用户手选。
|
||||
const silentKey =
|
||||
!isDesktop && context?.silent && context?.default_option
|
||||
? optionKey(context.default_option)
|
||||
: '';
|
||||
const canAutoSubmit =
|
||||
!!silentKey &&
|
||||
(context?.options || []).some((option) => optionKey(option) === silentKey);
|
||||
|
||||
// 网页端:默认范围可用且未要求强制选择时直接签发,不显示页面
|
||||
useEffect(() => {
|
||||
if (phase !== 'ready' || !canAutoSubmit || autoSubmittedRef.current) {
|
||||
return;
|
||||
}
|
||||
autoSubmittedRef.current = true;
|
||||
submit({ optionKeyValue: silentKey });
|
||||
}, [canAutoSubmit, phase, silentKey, submit]);
|
||||
|
||||
const switchAccount = useCallback(async () => {
|
||||
setPhase('submitting');
|
||||
try {
|
||||
await API.get('/api/user/logout', { skipErrorHandler: true });
|
||||
} catch (_e) {
|
||||
// 退出失败也回登录页,由登录页重新建立会话
|
||||
}
|
||||
goLogin();
|
||||
}, [goLogin]);
|
||||
|
||||
const clientName =
|
||||
context?.client_name || (isDesktop ? t('WeyAi 桌面端') : 'WeyAi');
|
||||
const busy = phase === 'submitting';
|
||||
const silentPending =
|
||||
canAutoSubmit &&
|
||||
(phase === 'ready' || phase === 'submitting') &&
|
||||
!inlineError;
|
||||
|
||||
// 三个没有任何可操作内容的瞬态走整页过渡画面(WeyAiHandoff),不再套登录
|
||||
// 卡片:拉授权信息 → 静默签发 → 授权完成等浏览器跳走。桌面端授权完成后
|
||||
// 要停在页面上给"没有自动打开"的按钮,被拒也要停下来告知,都不算瞬态。
|
||||
let handoffStage = null;
|
||||
if (!framed) {
|
||||
if (phase === 'loading') handoffStage = HANDOFF_STAGE_LOADING;
|
||||
else if (silentPending) handoffStage = HANDOFF_STAGE_ISSUING;
|
||||
else if (phase === 'done' && !isDesktop && !doneInfo?.denied) {
|
||||
handoffStage = HANDOFF_STAGE_REDIRECT;
|
||||
}
|
||||
}
|
||||
|
||||
const renderBody = () => {
|
||||
if (framed) {
|
||||
return (
|
||||
<Banner
|
||||
type='danger'
|
||||
closeIcon={null}
|
||||
description={t('出于安全原因,授权页不能在其他页面中打开')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (phase === 'fatal') {
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
<Banner type='danger' closeIcon={null} description={fatalMessage} />
|
||||
<Button block onClick={() => navigate('/', { replace: true })}>
|
||||
{t('返回首页')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (phase === 'done') {
|
||||
return (
|
||||
<div className='flex flex-col gap-4 items-center text-center'>
|
||||
<Text>
|
||||
{doneInfo?.denied
|
||||
? t('已拒绝授权,可以关闭此页面')
|
||||
: isDesktop
|
||||
? t('授权完成,请回到 WeyAi 桌面端继续')
|
||||
: t('授权完成,正在跳转…')}
|
||||
</Text>
|
||||
{isDesktop && !doneInfo?.denied && (
|
||||
<Button
|
||||
theme='light'
|
||||
block
|
||||
onClick={() => window.location.replace(doneInfo.redirect)}
|
||||
>
|
||||
{t('没有自动打开?点此打开 WeyAi')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const options = context?.options || [];
|
||||
const displayName = context?.user?.display_name || '';
|
||||
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
{displayName && (
|
||||
<div className='flex items-center justify-between gap-2 text-sm'>
|
||||
<Text type='tertiary'>{t('当前账号')}</Text>
|
||||
<Text strong ellipsis={{ showTooltip: true }}>
|
||||
{displayName}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{options.length === 0 ? (
|
||||
<Banner
|
||||
type='warning'
|
||||
closeIcon={null}
|
||||
description={reasonText(context?.no_option_reason)}
|
||||
/>
|
||||
) : (
|
||||
<div className='flex flex-col gap-2'>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('选择使用范围')}
|
||||
</Text>
|
||||
<ScopeOptionList
|
||||
options={options}
|
||||
value={selected}
|
||||
onChange={setSelected}
|
||||
disabled={busy}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isDesktop && params.device_name && (
|
||||
<div className='flex items-center justify-between gap-2 text-sm'>
|
||||
<span className='flex items-center gap-1.5'>
|
||||
<Monitor size={14} className='text-gray-400' />
|
||||
<Text type='tertiary'>{t('设备')}</Text>
|
||||
</span>
|
||||
<Text ellipsis={{ showTooltip: true }}>{params.device_name}</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{inlineError && (
|
||||
<Banner type='danger' closeIcon={null} description={inlineError} />
|
||||
)}
|
||||
|
||||
{isDesktop ? (
|
||||
<div className='flex flex-col gap-2'>
|
||||
<div className='flex gap-2'>
|
||||
<Button
|
||||
block
|
||||
disabled={busy}
|
||||
onClick={() => submit({ deny: true })}
|
||||
>
|
||||
{t('拒绝')}
|
||||
</Button>
|
||||
<Button
|
||||
block
|
||||
theme='solid'
|
||||
type='primary'
|
||||
loading={busy}
|
||||
disabled={options.length === 0}
|
||||
onClick={() => submit()}
|
||||
>
|
||||
{t('允许')}
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
block
|
||||
theme='borderless'
|
||||
disabled={busy}
|
||||
onClick={switchAccount}
|
||||
>
|
||||
{t('切换账号')}
|
||||
</Button>
|
||||
<Text type='tertiary' size='small' className='text-center'>
|
||||
{t('切换账号会退出当前登录,并将同时退出 WeyAi 网页端')}
|
||||
</Text>
|
||||
</div>
|
||||
) : (
|
||||
<div className='flex gap-2'>
|
||||
<Button
|
||||
block
|
||||
disabled={busy}
|
||||
onClick={() => submit({ deny: true })}
|
||||
>
|
||||
{t('取消')}
|
||||
</Button>
|
||||
<Button
|
||||
block
|
||||
theme='solid'
|
||||
type='primary'
|
||||
loading={busy}
|
||||
disabled={options.length === 0}
|
||||
onClick={() => submit()}
|
||||
>
|
||||
{t('继续')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (handoffStage !== null) {
|
||||
const handoffTitle =
|
||||
handoffStage === HANDOFF_STAGE_LOADING
|
||||
? t('正在加载授权信息')
|
||||
: t('正在进入 {{name}}', { name: clientName });
|
||||
return (
|
||||
<WeyAiHandoff
|
||||
logo={logo}
|
||||
stage={handoffStage}
|
||||
title={handoffTitle}
|
||||
// 加载阶段还不知道是静默进入还是要选范围,副标题只说"在确认";
|
||||
// 进入签发/跳转阶段才承诺"正在打开工作台"
|
||||
subtitle={
|
||||
handoffStage === HANDOFF_STAGE_LOADING
|
||||
? t('正在确认授权信息,通常只需几秒')
|
||||
: t('正在为你打开 {{name}} 工作台,通常只需几秒', {
|
||||
name: clientName,
|
||||
})
|
||||
}
|
||||
clientName={clientName}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className='relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
||||
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||||
>
|
||||
<AuthBackground />
|
||||
<div className='w-full max-w-md z-10 flex flex-col items-center'>
|
||||
<GlassCard>
|
||||
<AuthCardHeader
|
||||
wrapperClassName='mb-6'
|
||||
logo={logo}
|
||||
title={t('登录 {{name}}', { name: clientName })}
|
||||
subtitle={
|
||||
isDesktop
|
||||
? t('确认后将使用此账号登录 WeyAi 桌面端')
|
||||
: t('选择进入 WeyAi 时使用的范围')
|
||||
}
|
||||
/>
|
||||
{renderBody()}
|
||||
</GlassCard>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ClientAuthorize;
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import Dashboard from '../../components/dashboard';
|
||||
|
||||
const Detail = () => (
|
||||
<div className='mt-[60px] px-2'>
|
||||
<Dashboard />
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Detail;
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,86 @@
|
||||
# 体验中心 - 开发说明
|
||||
|
||||
## 已完成功能
|
||||
|
||||
### 1. 布局结构
|
||||
|
||||
- ✅ 左侧固定导航栏(宽度200px)
|
||||
- ✅ 右侧主内容区
|
||||
- ✅ 顶部导航栏已添加"体验中心"入口(位于"控制台"左侧)
|
||||
|
||||
### 2. 左侧导航栏
|
||||
|
||||
主功能区(顶部):
|
||||
|
||||
- ✅ 大模型体验(复用操练场)
|
||||
- ✅ 语音合成(占位页面)
|
||||
- ✅ 视频生成(占位页面)
|
||||
|
||||
底部功能区:
|
||||
|
||||
- ✅ 秘钥管理(复用令牌管理)
|
||||
|
||||
### 3. 功能组件
|
||||
|
||||
#### TextModel.jsx
|
||||
|
||||
- 完全复用现有的Playground组件
|
||||
- 无需额外开发
|
||||
|
||||
#### ImageGeneration.jsx
|
||||
|
||||
- 当前显示"此功能正在开发中"占位页面
|
||||
- 使用IllustrationConstruction插画组件
|
||||
|
||||
#### VideoGeneration.jsx
|
||||
|
||||
- 当前显示"此功能正在开发中"占位页面
|
||||
- 使用IllustrationConstruction插画组件
|
||||
|
||||
#### KeyManagement.jsx
|
||||
|
||||
- 完全复用现有的Token组件
|
||||
- 无需额外开发
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
web/src/pages/ExperienceCenter/
|
||||
├── index.jsx # 主入口,包含左侧导航+内容区布局
|
||||
└── components/
|
||||
├── TextModel.jsx # 大模型体验(复用Playground)
|
||||
├── ImageGeneration.jsx # 语音合成(占位)
|
||||
├── VideoGeneration.jsx # 视频生成(占位)
|
||||
└── KeyManagement.jsx # 秘钥管理(复用Token)
|
||||
```
|
||||
|
||||
## 访问方式
|
||||
|
||||
1. 通过顶部导航栏点击"体验中心"
|
||||
2. 直接访问路由:`/experience-center`
|
||||
|
||||
## 后续开发建议
|
||||
|
||||
1. **语音合成功能**:
|
||||
- 集成TTS API
|
||||
- 提供文本输入框和语音试听功能
|
||||
- 支持多种语音选择
|
||||
|
||||
2. **视频生成功能**:
|
||||
- 集成Suno等视频生成API
|
||||
- 提供提示词输入
|
||||
- 视频预览和下载功能
|
||||
|
||||
## 技术栈
|
||||
|
||||
- React 18+
|
||||
- Semi Design UI 组件库
|
||||
- React Router v6
|
||||
- i18next(国际化)
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 左侧导航栏固定定位,不随内容滚动
|
||||
- 主内容区自适应高度,包含滚动条
|
||||
- 响应式设计,适配不同屏幕尺寸
|
||||
- 暗色模式支持
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Tabs, TabPane } from '@douyinfe/semi-ui';
|
||||
import { IconImage, IconVideo, IconBolt } from '@douyinfe/semi-icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import ImageGenerationTab from './AICreation/ImageGenerationTab';
|
||||
import VideoGenerationTab from './AICreation/VideoGenerationTab';
|
||||
import VideoRemixTab from './AICreation/VideoRemixTab';
|
||||
|
||||
const AICreation = () => {
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const [activeTab, setActiveTab] = useState('image');
|
||||
|
||||
// 从URL中解析当前选中的标签页
|
||||
useEffect(() => {
|
||||
const pathSegments = location.pathname.split('/');
|
||||
let tabKey = pathSegments[pathSegments.length - 1] || 'image';
|
||||
if (tabKey === 'ai-creation') {
|
||||
tabKey = 'image';
|
||||
}
|
||||
setActiveTab(tabKey);
|
||||
}, [location.pathname]);
|
||||
|
||||
// 当标签页变化时,更新URL
|
||||
const handleTabChange = (tabKey) => {
|
||||
setActiveTab(tabKey);
|
||||
navigate(`/experience-center/ai-creation/${tabKey}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: '20px' }}>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={handleTabChange}
|
||||
type='button'
|
||||
size='large'
|
||||
style={{ marginBottom: '24px' }}
|
||||
>
|
||||
<TabPane
|
||||
tab={
|
||||
<span>
|
||||
<IconImage style={{ marginRight: '8px' }} />
|
||||
{t('图片生成')}
|
||||
</span>
|
||||
}
|
||||
itemKey='image'
|
||||
>
|
||||
<ImageGenerationTab />
|
||||
</TabPane>
|
||||
|
||||
<TabPane
|
||||
tab={
|
||||
<span>
|
||||
<IconVideo style={{ marginRight: '8px' }} />
|
||||
{t('视频生成')}
|
||||
</span>
|
||||
}
|
||||
itemKey='video'
|
||||
>
|
||||
<VideoGenerationTab />
|
||||
</TabPane>
|
||||
|
||||
<TabPane
|
||||
tab={
|
||||
<span>
|
||||
<IconBolt style={{ marginRight: '8px' }} />
|
||||
{t('视频 Remix')}
|
||||
</span>
|
||||
}
|
||||
itemKey='remix'
|
||||
>
|
||||
<VideoRemixTab />
|
||||
</TabPane>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AICreation;
|
||||
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Modal, Typography, Tag } from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const ImageCompareModal = ({ visible, tasks, onClose }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 跟随窗口尺寸变化,保证 Modal 不会溢出视口
|
||||
const [viewportWidth, setViewportWidth] = useState(
|
||||
typeof window !== 'undefined' ? window.innerWidth : 1280,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const onResize = () => setViewportWidth(window.innerWidth);
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => window.removeEventListener('resize', onResize);
|
||||
}, []);
|
||||
|
||||
if (!visible || !tasks || tasks.length === 0) return null;
|
||||
|
||||
// 自适应列数:2 张并排,3 张 3 列,4 张 2×2
|
||||
const cols = tasks.length === 4 ? 2 : tasks.length;
|
||||
// 宽度 = 内容理想宽度,但不超过视口(留 48px 边距)和 1280 上限
|
||||
const ideal = 360 * cols + 64;
|
||||
const modalWidth = Math.min(1280, ideal, Math.max(320, viewportWidth - 48));
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('对比 {{n}} 张图片', { n: tasks.length })}
|
||||
visible={visible}
|
||||
onCancel={onClose}
|
||||
footer={null}
|
||||
width={modalWidth}
|
||||
bodyStyle={{ maxHeight: '80vh', overflow: 'auto', padding: 16 }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'grid',
|
||||
gridTemplateColumns: `repeat(${cols}, 1fr)`,
|
||||
gap: '16px',
|
||||
}}
|
||||
>
|
||||
{tasks.map((task) => (
|
||||
<div
|
||||
key={task.id}
|
||||
className='rounded-lg overflow-hidden border border-gray-200 dark:border-neutral-700 bg-white dark:bg-neutral-900'
|
||||
>
|
||||
<div className='aspect-square bg-gray-50 dark:bg-neutral-800 flex items-center justify-center overflow-hidden'>
|
||||
{task.imageUrl ? (
|
||||
<img
|
||||
src={task.imageUrl}
|
||||
alt=''
|
||||
className='w-full h-full object-contain'
|
||||
/>
|
||||
) : (
|
||||
<Text type='tertiary'>{t('无图片')}</Text>
|
||||
)}
|
||||
</div>
|
||||
<div className='p-3 space-y-2'>
|
||||
<div className='flex items-center gap-2 flex-wrap'>
|
||||
<Tag
|
||||
size='small'
|
||||
color='grey'
|
||||
className='!rounded !border-brand/25 !bg-brand/10 !text-brand-deep dark:!border-brand/25 dark:!bg-brand/15 dark:!text-brand-from'
|
||||
>
|
||||
{task.model || t('未知模型')}
|
||||
</Tag>
|
||||
<Tag size='small' color='grey' className='!rounded'>
|
||||
{task.width}×{task.height}
|
||||
</Tag>
|
||||
{task.quality && (
|
||||
<Tag size='small' color='grey' className='!rounded'>
|
||||
{task.quality}
|
||||
</Tag>
|
||||
)}
|
||||
</div>
|
||||
<Text
|
||||
size='small'
|
||||
className='block text-gray-600 dark:text-gray-300'
|
||||
style={{
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: 4,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
overflow: 'hidden',
|
||||
wordBreak: 'break-word',
|
||||
}}
|
||||
title={task.prompt}
|
||||
>
|
||||
{task.prompt || t('(无提示词)')}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ImageCompareModal;
|
||||
@@ -0,0 +1,335 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
Image,
|
||||
Button,
|
||||
Space,
|
||||
Typography,
|
||||
Tag,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { Download, Copy, ImagePlus, Sparkles } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { showSuccess, showError } from '../../../../helpers';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const ImageDetailModal = ({
|
||||
visible,
|
||||
task,
|
||||
onClose,
|
||||
onReuseParams,
|
||||
onUseAsReference,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 跟随视口宽度,避免 900px 固定值在窄笔记本/平板上溢出
|
||||
const [viewportWidth, setViewportWidth] = useState(
|
||||
typeof window !== 'undefined' ? window.innerWidth : 900,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const onResize = () => setViewportWidth(window.innerWidth);
|
||||
window.addEventListener('resize', onResize);
|
||||
return () => window.removeEventListener('resize', onResize);
|
||||
}, []);
|
||||
const modalWidth = Math.min(900, Math.max(320, viewportWidth - 48));
|
||||
|
||||
if (!task) return null;
|
||||
|
||||
const handleDownload = async () => {
|
||||
if (!task.imageUrl) {
|
||||
showError(t('图片不存在'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch(task.imageUrl);
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `image_${task.id}.png`;
|
||||
link.style.display = 'none';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
requestAnimationFrame(() => {
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(url);
|
||||
});
|
||||
showSuccess(t('下载成功'));
|
||||
} catch (error) {
|
||||
console.error('下载失败:', error);
|
||||
window.open(task.imageUrl, '_blank');
|
||||
showSuccess(t('已在新窗口打开图片'));
|
||||
}
|
||||
};
|
||||
|
||||
// 复制(带 execCommand 兜底,兼容 http / 老浏览器)
|
||||
const copyToClipboard = async (text) => {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.warn('Clipboard API failed:', err);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = text;
|
||||
textArea.style.position = 'fixed';
|
||||
textArea.style.left = '-9999px';
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
const ok = document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
return ok;
|
||||
} catch (err) {
|
||||
console.error('execCommand copy failed:', err);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleCopyPrompt = async () => {
|
||||
if (!task.prompt) return;
|
||||
const ok = await copyToClipboard(task.prompt);
|
||||
ok ? showSuccess(t('已复制到剪贴板')) : showError(t('复制失败'));
|
||||
};
|
||||
|
||||
const formatDateTime = (isoString) => {
|
||||
if (!isoString) return '-';
|
||||
const date = new Date(isoString);
|
||||
return date.toLocaleString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
};
|
||||
|
||||
const isImageToImage = task.mode === 'image-to-image';
|
||||
|
||||
// 参数行:值为空就不显示
|
||||
const params = [
|
||||
{ label: t('模型'), value: task.model, color: 'grey', brand: true },
|
||||
{
|
||||
label: t('尺寸'),
|
||||
value: task.width && task.height ? `${task.width}×${task.height}` : null,
|
||||
color: 'grey',
|
||||
},
|
||||
{
|
||||
label: t('模式'),
|
||||
value: isImageToImage ? t('图生图') : t('文生图'),
|
||||
color: 'grey',
|
||||
},
|
||||
{ label: t('质量'), value: task.quality, color: 'grey' },
|
||||
{
|
||||
label: t('数量'),
|
||||
value: task.n && task.n > 1 ? `${task.n} ${t('张')}` : null,
|
||||
color: 'grey',
|
||||
},
|
||||
].filter((p) => p.value);
|
||||
|
||||
const handleReuseParamsClick = () => {
|
||||
if (onReuseParams) {
|
||||
onReuseParams(task);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
const handleUseAsReferenceClick = () => {
|
||||
if (onUseAsReference) {
|
||||
onUseAsReference(task);
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('图片详情')}
|
||||
visible={visible}
|
||||
onCancel={onClose}
|
||||
footer={
|
||||
// wrap 必须开:三个中文按钮(用作参考图/在此基础上微调/下载图片)合计 ~370px,
|
||||
// 而 modalWidth 是 viewportWidth-48,390px 屏上扣掉 content 的 padding 只剩 ~294px。
|
||||
// Space 默认 wrap:false + .semi-modal-content{overflow:hidden},
|
||||
// 溢出部分向左溢出并被裁掉 —— 「用作参考图」整个点不到。
|
||||
<Space wrap style={{ justifyContent: 'flex-end', width: '100%' }}>
|
||||
{onUseAsReference && task.imageUrl && (
|
||||
<Button
|
||||
icon={<ImagePlus size={16} />}
|
||||
onClick={handleUseAsReferenceClick}
|
||||
>
|
||||
{t('用作参考图')}
|
||||
</Button>
|
||||
)}
|
||||
{onReuseParams && (
|
||||
<Button
|
||||
icon={<Sparkles size={16} />}
|
||||
theme='light'
|
||||
type='primary'
|
||||
onClick={handleReuseParamsClick}
|
||||
>
|
||||
{t('在此基础上微调')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type='primary'
|
||||
icon={<Download size={16} />}
|
||||
onClick={handleDownload}
|
||||
disabled={!task.imageUrl}
|
||||
>
|
||||
{t('下载图片')}
|
||||
</Button>
|
||||
</Space>
|
||||
}
|
||||
width={modalWidth}
|
||||
bodyStyle={{
|
||||
maxHeight: '75vh',
|
||||
overflowX: 'hidden',
|
||||
overflowY: 'auto',
|
||||
padding: '20px 24px',
|
||||
}}
|
||||
>
|
||||
{/* 图片展示 */}
|
||||
<div className='text-center mb-5'>
|
||||
{isImageToImage && task.sourceImageUrl ? (
|
||||
<div className='flex gap-4 items-start justify-center'>
|
||||
<div className='flex-1' style={{ maxWidth: '48%' }}>
|
||||
<Text type='secondary' size='small' className='block mb-2'>
|
||||
{t('原图')}
|
||||
</Text>
|
||||
<Image
|
||||
src={task.sourceImageUrl}
|
||||
alt='Source'
|
||||
className='rounded-lg border border-gray-200 dark:border-neutral-700'
|
||||
style={{ maxWidth: '100%', maxHeight: 360 }}
|
||||
preview={{ src: task.sourceImageUrl }}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex-1' style={{ maxWidth: '48%' }}>
|
||||
<Text type='secondary' size='small' className='block mb-2'>
|
||||
{t('生成图')}
|
||||
</Text>
|
||||
<Image
|
||||
src={task.imageUrl}
|
||||
alt='Generated'
|
||||
className='rounded-lg border border-gray-200 dark:border-neutral-700'
|
||||
style={{ maxWidth: '100%', maxHeight: 360 }}
|
||||
preview={{ src: task.imageUrl }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : task.imageUrl ? (
|
||||
<Image
|
||||
src={task.imageUrl}
|
||||
alt='Generated'
|
||||
className='rounded-lg border border-gray-200 dark:border-neutral-700'
|
||||
style={{ maxWidth: '100%', maxHeight: 520 }}
|
||||
preview={{ src: task.imageUrl }}
|
||||
/>
|
||||
) : (
|
||||
<div className='py-10 text-gray-400'>
|
||||
<Text type='tertiary'>{t('暂无图片')}</Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 参数 Tag 行 */}
|
||||
{params.length > 0 && (
|
||||
<div className='flex items-center gap-1.5 flex-wrap mb-4'>
|
||||
{params.map((p) => (
|
||||
<Tag
|
||||
key={p.label}
|
||||
color={p.color}
|
||||
size='small'
|
||||
className={`!rounded ${
|
||||
p.brand
|
||||
? '!border-brand/25 !bg-brand/10 !text-brand-deep dark:!border-brand/25 dark:!bg-brand/15 dark:!text-brand-from'
|
||||
: ''
|
||||
}`}
|
||||
>
|
||||
<span className='text-gray-500 mr-1'>{p.label}:</span>
|
||||
<strong>{p.value}</strong>
|
||||
</Tag>
|
||||
))}
|
||||
<Tag size='small' color='grey' className='!rounded'>
|
||||
<span className='text-gray-500 mr-1'>{t('创建')}:</span>
|
||||
<strong>{formatDateTime(task.createdAt)}</strong>
|
||||
</Tag>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 提示词 */}
|
||||
<div className='mb-3'>
|
||||
<div className='flex items-center justify-between mb-1.5'>
|
||||
<Text strong>{t('提示词')}</Text>
|
||||
<Button
|
||||
size='small'
|
||||
theme='borderless'
|
||||
icon={<Copy size={14} />}
|
||||
onClick={handleCopyPrompt}
|
||||
className='!text-gray-500 hover:!text-brand-deep dark:hover:!text-brand-from'
|
||||
>
|
||||
{t('复制')}
|
||||
</Button>
|
||||
</div>
|
||||
<div
|
||||
className='p-3 rounded-lg bg-gray-50 dark:bg-neutral-800/60 text-sm leading-relaxed whitespace-pre-wrap break-words'
|
||||
style={{ minHeight: 60 }}
|
||||
>
|
||||
{task.prompt || <Text type='tertiary'>{t('(无提示词)')}</Text>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 负向提示词(如果有) */}
|
||||
{task.negativePrompt && (
|
||||
<div className='mb-3'>
|
||||
<Text strong className='block mb-1.5'>
|
||||
{t('负向提示词')}
|
||||
</Text>
|
||||
<div className='p-3 rounded-lg bg-rose-50 dark:bg-rose-900/10 text-sm leading-relaxed whitespace-pre-wrap break-words'>
|
||||
{task.negativePrompt}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 失败信息 */}
|
||||
{task.status === 'failed' && task.errorMessage && (
|
||||
<div className='mb-3'>
|
||||
<Text
|
||||
strong
|
||||
className='block mb-1.5 text-rose-600 dark:text-rose-400'
|
||||
>
|
||||
{t('失败原因')}
|
||||
</Text>
|
||||
<div className='p-3 rounded-lg bg-rose-50 dark:bg-rose-900/10 text-xs text-rose-700 dark:text-rose-300 whitespace-pre-wrap break-words'>
|
||||
{task.errorMessage}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default ImageDetailModal;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,148 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { useImageTaskManagement } from '../../../../hooks/image/useImageTaskManagement';
|
||||
import ImageGenerationForm from './ImageGenerationForm';
|
||||
import ImageTaskList from './ImageTaskList';
|
||||
import ImageDetailModal from './ImageDetailModal';
|
||||
|
||||
const ImageGenerationTab = () => {
|
||||
const {
|
||||
tasks,
|
||||
loading,
|
||||
addTask,
|
||||
deleteTask,
|
||||
retryTask,
|
||||
refreshTasks,
|
||||
refreshTaskUrl,
|
||||
} = useImageTaskManagement();
|
||||
|
||||
const [selectedTask, setSelectedTask] = useState(null);
|
||||
const [detailModalVisible, setDetailModalVisible] = useState(false);
|
||||
|
||||
// 历史卡片"复用参数":把任务参数回填到表单,但不立刻生成
|
||||
// 用对象引用变化触发 form 的 useEffect
|
||||
const [prefillSignal, setPrefillSignal] = useState(null);
|
||||
|
||||
// 处理生成提交
|
||||
const handleSubmit = (formData) => {
|
||||
addTask(formData);
|
||||
};
|
||||
|
||||
// 处理重新生成(直接再跑一次)
|
||||
const handleRegenerate = (taskData) => {
|
||||
addTask(taskData);
|
||||
};
|
||||
|
||||
// 处理"复用参数"(仅回填,等用户确认后再生成)
|
||||
const handleReuseParams = (task) => {
|
||||
setPrefillSignal({
|
||||
mode: task.mode,
|
||||
prompt: task.prompt,
|
||||
width: task.width,
|
||||
height: task.height,
|
||||
model: task.model,
|
||||
quality: task.quality,
|
||||
n: task.n,
|
||||
negativePrompt: task.negativePrompt,
|
||||
_ts: Date.now(),
|
||||
});
|
||||
};
|
||||
|
||||
// 处理"用作参考图"(生成结果 -> 切到图生图模式 + 自动回填参考图)
|
||||
// 不带 prompt:保留用户当前已输入的提示词,避免被空串覆盖。
|
||||
// 想要旧 prompt 一并回填的,请走"复用参数"。
|
||||
const handleUseAsReference = (task) => {
|
||||
if (!task?.imageUrl) return;
|
||||
setPrefillSignal({
|
||||
mode: 'image-to-image',
|
||||
referenceImageUrl: task.imageUrl,
|
||||
_ts: Date.now(),
|
||||
});
|
||||
};
|
||||
|
||||
// 空状态:用户点示例 prompt 卡片,直接填回 form
|
||||
const handleSamplePrompt = (samplePrompt) => {
|
||||
if (!samplePrompt) return;
|
||||
setPrefillSignal({
|
||||
mode: 'text-to-image',
|
||||
prompt: samplePrompt,
|
||||
_ts: Date.now(),
|
||||
});
|
||||
};
|
||||
|
||||
// 查看详情
|
||||
const handleViewDetail = (task) => {
|
||||
setSelectedTask(task);
|
||||
setDetailModalVisible(true);
|
||||
};
|
||||
|
||||
// 关闭详情
|
||||
const handleCloseDetail = () => {
|
||||
setDetailModalVisible(false);
|
||||
setSelectedTask(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/*
|
||||
移动端(< md):Tab 整体允许竖向滚动 —— 表单和任务列表按自然高度堆叠,用户上下滚浏览。
|
||||
桌面端(>= md):保持 overflow-hidden,左右两栏各自内部滚动。
|
||||
*/}
|
||||
<div className='h-full min-h-0 flex flex-col md:flex-row gap-4 p-3 sm:p-4 overflow-y-auto md:overflow-hidden'>
|
||||
{/* 左侧:生成参数表单 */}
|
||||
<div className='w-full md:w-[22rem] xl:w-[24rem] md:flex-shrink-0 md:h-full'>
|
||||
<ImageGenerationForm
|
||||
onSubmit={handleSubmit}
|
||||
loading={loading}
|
||||
prefillSignal={prefillSignal}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 右侧:任务列表 —— flex-1 只在桌面端生效,移动端按内容高度展开 */}
|
||||
<div className='md:flex-1 md:min-h-0 flex flex-col'>
|
||||
<ImageTaskList
|
||||
tasks={tasks}
|
||||
onRefresh={refreshTasks}
|
||||
onRefreshUrl={refreshTaskUrl}
|
||||
onViewDetail={handleViewDetail}
|
||||
onDelete={deleteTask}
|
||||
onRetry={retryTask}
|
||||
onRegenerate={handleRegenerate}
|
||||
onReuseParams={handleReuseParams}
|
||||
onUseAsReference={handleUseAsReference}
|
||||
onSamplePrompt={handleSamplePrompt}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 图片详情模态框 */}
|
||||
<ImageDetailModal
|
||||
visible={detailModalVisible}
|
||||
task={selectedTask}
|
||||
onClose={handleCloseDetail}
|
||||
onReuseParams={handleReuseParams}
|
||||
onUseAsReference={handleUseAsReference}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ImageGenerationTab;
|
||||
@@ -0,0 +1,290 @@
|
||||
# 图片生成任务列表界面优化说明
|
||||
|
||||
## 优化概览
|
||||
|
||||
本次优化重新设计了图片生成任务列表的界面,提升了用户体验和视觉美观度。
|
||||
|
||||
## 主要改进
|
||||
|
||||
### 1. 顶部操作栏设计
|
||||
|
||||
#### 统计卡片
|
||||
|
||||
- **三个统计卡片**:生成中、已完成、失败
|
||||
- **可点击筛选**:点击卡片可快速筛选对应状态的任务
|
||||
- **实时统计**:自动计算各状态任务数量
|
||||
- **高亮显示**:选中状态的卡片带蓝色边框
|
||||
|
||||
#### 搜索功能
|
||||
|
||||
- **实时搜索**:支持按提示词或模型搜索
|
||||
- **清除按钮**:可快速清空搜索关键词
|
||||
- **智能匹配**:不区分大小写的模糊搜索
|
||||
|
||||
#### 快捷操作
|
||||
|
||||
- **刷新按钮**:一键刷新所有任务
|
||||
- **清除筛选**:快速清除所有筛选条件
|
||||
|
||||
### 2. 任务卡片重新设计
|
||||
|
||||
#### 左侧图片预览区
|
||||
|
||||
**成功状态**:
|
||||
|
||||
- 显示生成的图片缩略图
|
||||
- 支持点击放大预览
|
||||
- 右上角显示图片尺寸标签
|
||||
- 半透明黑色背景,更有层次感
|
||||
|
||||
**进行中状态**:
|
||||
|
||||
- 显示加载动画(Spin)
|
||||
- 显示当前进度百分比
|
||||
- 渐变背景更美观
|
||||
|
||||
**失败状态**:
|
||||
|
||||
- 显示错误图标
|
||||
- 红色提示文字
|
||||
|
||||
#### 右侧内容区
|
||||
|
||||
- **状态标签**:带图标的彩色标签,更直观
|
||||
- **时间显示**:相对时间(刚刚、X分钟前等)
|
||||
- **提示词**:支持展开查看完整内容
|
||||
- **参数信息**:图片尺寸、使用模型
|
||||
- **进度条**:进行中任务显示实时进度
|
||||
- **错误提示**:失败任务显示错误原因
|
||||
|
||||
#### 操作按钮
|
||||
|
||||
**成功任务**:
|
||||
|
||||
- 查看:查看大图
|
||||
- 下载:直接下载图片(主要操作按钮)
|
||||
- 更多菜单:
|
||||
- 复制提示词
|
||||
- 复制图片链接
|
||||
- 删除任务
|
||||
|
||||
**失败任务**:
|
||||
|
||||
- 重试:重新生成
|
||||
- 删除:移除任务
|
||||
|
||||
**进行中任务**:
|
||||
|
||||
- 取消:停止生成
|
||||
|
||||
### 3. 视觉增强
|
||||
|
||||
#### 卡片效果
|
||||
|
||||
- **圆角设计**:12px圆角,更现代
|
||||
- **阴影效果**:轻微阴影增加层次感
|
||||
- **悬停动画**:鼠标悬停时卡片轻微上浮
|
||||
- **过渡效果**:所有交互都有流畅的过渡动画
|
||||
|
||||
#### 颜色系统
|
||||
|
||||
- **状态颜色**:
|
||||
- 生成中:蓝色 (blue)
|
||||
- 已完成:绿色 (green)
|
||||
- 失败:红色 (red)
|
||||
- **渐变背景**:顶部操作栏使用微妙的渐变
|
||||
- **统一风格**:遵循 Semi Design 设计规范
|
||||
|
||||
#### 响应式设计
|
||||
|
||||
- **移动端适配**:小屏幕下自动调整布局
|
||||
- **网格布局**:统计卡片自动适应屏幕宽度
|
||||
- **滚动优化**:自定义滚动条样式
|
||||
|
||||
### 4. 交互优化
|
||||
|
||||
#### 一键操作
|
||||
|
||||
- **下载图片**:点击下载按钮即可下载,无需右键
|
||||
- **复制功能**:一键复制提示词或图片链接
|
||||
- **快速筛选**:点击统计卡片快速切换筛选
|
||||
|
||||
#### 提示反馈
|
||||
|
||||
- **成功提示**:下载、复制成功后显示提示
|
||||
- **确认对话框**:删除操作需要确认
|
||||
- **错误处理**:操作失败时显示友好提示
|
||||
|
||||
#### 图片预览
|
||||
|
||||
- **点击预览**:点击缩略图查看大图
|
||||
- **原图显示**:支持查看原始尺寸
|
||||
- **缩放功能**:支持放大缩小
|
||||
|
||||
### 5. 性能优化
|
||||
|
||||
#### 计算优化
|
||||
|
||||
- **useMemo**:统计数据和筛选结果使用 memo 缓存
|
||||
- **按需渲染**:只渲染可见区域的任务
|
||||
- **虚拟滚动**:支持大量任务列表
|
||||
|
||||
#### 加载优化
|
||||
|
||||
- **懒加载**:图片懒加载减少初始加载时间
|
||||
- **增量更新**:只更新变化的任务
|
||||
- **缓存策略**:合理使用浏览器缓存
|
||||
|
||||
## 新增功能
|
||||
|
||||
### 1. 搜索和筛选
|
||||
|
||||
```javascript
|
||||
// 按状态筛选
|
||||
filterStatus: 'all' | 'processing' | 'success' | 'failed';
|
||||
|
||||
// 按关键词搜索
|
||||
searchKeyword: 提示词或模型名称;
|
||||
```
|
||||
|
||||
### 2. 批量操作
|
||||
|
||||
- 下载图片
|
||||
- 复制提示词
|
||||
- 复制图片链接
|
||||
- 删除任务
|
||||
|
||||
### 3. 统计功能
|
||||
|
||||
```javascript
|
||||
statistics: {
|
||||
total: 总任务数,
|
||||
processing: 生成中数量,
|
||||
success: 成功数量,
|
||||
failed: 失败数量
|
||||
}
|
||||
```
|
||||
|
||||
## 使用示例
|
||||
|
||||
### 基本用法
|
||||
|
||||
```jsx
|
||||
<ImageTaskList
|
||||
tasks={tasks} // 任务列表
|
||||
onRefresh={handleRefresh} // 刷新回调
|
||||
onViewDetail={handleViewDetail} // 查看详情回调
|
||||
onDelete={handleDelete} // 删除回调
|
||||
onRetry={handleRetry} // 重试回调
|
||||
/>
|
||||
```
|
||||
|
||||
### 任务数据结构
|
||||
|
||||
```javascript
|
||||
{
|
||||
id: '123', // 任务ID
|
||||
prompt: 'a beautiful sunset', // 提示词
|
||||
width: 1024, // 图片宽度
|
||||
height: 1024, // 图片高度
|
||||
model: 'sora_image', // 使用模型
|
||||
status: 'success', // 状态
|
||||
createdAt: '2025-11-29T...', // 创建时间
|
||||
imageUrl: 'https://...', // 图片URL
|
||||
progress: '100%', // 进度
|
||||
errorMessage: null // 错误信息
|
||||
}
|
||||
```
|
||||
|
||||
## 技术实现
|
||||
|
||||
### 组件结构
|
||||
|
||||
```
|
||||
ImageTaskList/
|
||||
├── ImageTaskList.jsx # 主组件
|
||||
├── ImageTaskList.css # 样式文件
|
||||
└── README.md # 说明文档
|
||||
```
|
||||
|
||||
### 依赖库
|
||||
|
||||
- **@douyinfe/semi-ui**:UI 组件库
|
||||
- **@douyinfe/semi-icons**:图标库
|
||||
- **react-i18next**:国际化
|
||||
- **React Hooks**:状态管理
|
||||
|
||||
### 核心 Hooks
|
||||
|
||||
```javascript
|
||||
useState; // 筛选和搜索状态
|
||||
useMemo; // 统计数据和筛选结果缓存
|
||||
useCallback; // 事件处理函数优化
|
||||
```
|
||||
|
||||
## 样式定制
|
||||
|
||||
### CSS 变量
|
||||
|
||||
```css
|
||||
--semi-color-primary // 主色
|
||||
--semi-color-success // 成功色
|
||||
--semi-color-warning // 警告色
|
||||
--semi-color-danger // 危险色
|
||||
--semi-color-bg-2 // 背景色
|
||||
--semi-color-border // 边框色
|
||||
```
|
||||
|
||||
### 自定义类
|
||||
|
||||
```css
|
||||
.task-card-hover // 卡片悬停效果
|
||||
.task-list-scroll // 滚动条样式
|
||||
.stat-card // 统计卡片样式
|
||||
.image-preview-container // 图片预览容器
|
||||
.progress-pulse // 进度条动画
|
||||
```
|
||||
|
||||
## 浏览器兼容性
|
||||
|
||||
- ✅ Chrome 90+
|
||||
- ✅ Firefox 88+
|
||||
- ✅ Safari 14+
|
||||
- ✅ Edge 90+
|
||||
- ✅ 移动端浏览器
|
||||
|
||||
## 已知问题
|
||||
|
||||
暂无
|
||||
|
||||
## 未来计划
|
||||
|
||||
### 短期
|
||||
|
||||
- [ ] 添加批量下载功能
|
||||
- [ ] 支持拖拽排序
|
||||
- [ ] 添加收藏功能
|
||||
|
||||
### 长期
|
||||
|
||||
- [ ] 添加标签分类
|
||||
- [ ] 支持导出历史记录
|
||||
- [ ] 添加分享功能
|
||||
- [ ] AI 推荐相似提示词
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v2.0.0 (2025-11-29)
|
||||
|
||||
- ✨ 全新的界面设计
|
||||
- ✨ 添加搜索和筛选功能
|
||||
- ✨ 优化卡片布局和样式
|
||||
- ✨ 添加统计功能
|
||||
- ✨ 改进操作按钮
|
||||
- ✨ 添加图片预览
|
||||
- ✨ 优化移动端体验
|
||||
- 🐛 修复若干已知问题
|
||||
|
||||
## 反馈和建议
|
||||
|
||||
如有问题或建议,请联系开发团队。
|
||||
@@ -0,0 +1,220 @@
|
||||
/* 任务卡片悬停效果 */
|
||||
.task-card-hover {
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.task-card-hover:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12) !important;
|
||||
}
|
||||
|
||||
/* 滚动条样式已统一到 index.css 的 .app-scrollbar */
|
||||
|
||||
/* 统计卡片悬停效果 */
|
||||
.stat-card {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.stat-card:hover {
|
||||
transform: scale(1.02);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
/* 图片预览悬停效果 */
|
||||
.image-preview-container {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.image-preview-container::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0, 0, 0, 0);
|
||||
transition: background 0.3s;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.image-preview-container:hover::after {
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
/* 进度条动画 */
|
||||
@keyframes pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
/* 处理中状态左侧彩条流光 */
|
||||
@keyframes brandShimmer {
|
||||
0% {
|
||||
background-position: 0% 0%;
|
||||
}
|
||||
100% {
|
||||
background-position: 0% 200%;
|
||||
}
|
||||
}
|
||||
|
||||
/* drop target highlight */
|
||||
.image-ref-drop-active {
|
||||
outline: 2px dashed var(--brand-primary) !important;
|
||||
outline-offset: -4px;
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--brand-primary) 8%,
|
||||
transparent
|
||||
) !important;
|
||||
}
|
||||
|
||||
.progress-pulse {
|
||||
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
|
||||
}
|
||||
|
||||
/* 按钮组动画 */
|
||||
.action-buttons {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.action-buttons > * {
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.action-buttons > *:hover {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
/* 空状态样式 */
|
||||
.empty-state {
|
||||
padding: 60px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 搜索框样式增强 */
|
||||
.search-input-enhanced {
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.search-input-enhanced:focus-within {
|
||||
box-shadow: 0 0 0 2px rgba(var(--semi-color-primary-rgb), 0.2);
|
||||
}
|
||||
|
||||
/* 标签组样式 */
|
||||
.tag-group {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* 响应式设计 */
|
||||
@media (max-width: 768px) {
|
||||
.task-card-content {
|
||||
flex-direction: column !important;
|
||||
}
|
||||
|
||||
.image-preview-container {
|
||||
width: 100% !important;
|
||||
min-height: 200px !important;
|
||||
}
|
||||
|
||||
.stat-cards-grid {
|
||||
grid-template-columns: 1fr !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Badge 样式覆盖 - 修复默认蓝色圆形背景 */
|
||||
.image-task-list .semi-badge-primary.semi-badge-solid .semi-badge-count,
|
||||
.image-task-list
|
||||
.semi-badge-primary.semi-badge-solid.semi-badge-block
|
||||
.semi-badge-count {
|
||||
background: transparent !important;
|
||||
background-image: none !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
/* 历史标题区域的 Badge 特定样式 */
|
||||
.image-task-list .semi-badge.semi-badge-primary .semi-badge-count {
|
||||
background: linear-gradient(
|
||||
to right,
|
||||
var(--brand-gradient-from),
|
||||
var(--brand-gradient-to)
|
||||
) !important;
|
||||
border: none !important;
|
||||
box-shadow: 0 2px 8px
|
||||
color-mix(in srgb, var(--brand-primary) 30%, transparent) !important;
|
||||
}
|
||||
|
||||
/* 图片生成页局部控件留白:避免搜索/筛选内容贴住玻璃卡片边框 */
|
||||
.image-task-list .image-task-search.semi-input-wrapper {
|
||||
padding-left: 10px !important;
|
||||
padding-right: 8px !important;
|
||||
border: 1px solid rgb(255 255 255 / 0.5) !important;
|
||||
background: rgb(255 255 255 / 0.48) !important;
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.dark .image-task-list .image-task-search.semi-input-wrapper {
|
||||
border-color: rgb(255 255 255 / 0.1) !important;
|
||||
background: rgb(255 255 255 / 0.06) !important;
|
||||
}
|
||||
|
||||
.image-task-list .image-task-search .semi-input-prefix {
|
||||
margin-right: 6px !important;
|
||||
}
|
||||
|
||||
.image-task-list .image-task-search .semi-input {
|
||||
padding-left: 2px !important;
|
||||
}
|
||||
|
||||
.image-task-list .image-task-filter-select.semi-select {
|
||||
padding-left: 8px !important;
|
||||
border: 1px solid rgb(255 255 255 / 0.5) !important;
|
||||
background: rgb(255 255 255 / 0.48) !important;
|
||||
backdrop-filter: blur(14px);
|
||||
}
|
||||
|
||||
.dark .image-task-list .image-task-filter-select.semi-select {
|
||||
border-color: rgb(255 255 255 / 0.1) !important;
|
||||
background: rgb(255 255 255 / 0.06) !important;
|
||||
}
|
||||
|
||||
.image-task-list .image-task-filter-select .semi-select-selection {
|
||||
padding-left: 2px !important;
|
||||
}
|
||||
|
||||
.image-task-list .image-task-group-header {
|
||||
margin-left: -4px;
|
||||
margin-right: -4px;
|
||||
border: 1px solid rgb(255 255 255 / 0.45);
|
||||
border-radius: 14px;
|
||||
box-shadow: 0 10px 26px rgb(15 23 42 / 0.06);
|
||||
}
|
||||
|
||||
.dark .image-task-list .image-task-group-header {
|
||||
border-color: rgb(255 255 255 / 0.1);
|
||||
box-shadow: 0 10px 26px rgb(0 0 0 / 0.24);
|
||||
}
|
||||
|
||||
/* ===== 触屏命中区兜底 ===== */
|
||||
/* 卡片操作按钮统一 height:24px(Semi size='small'),在触屏上低于 32px 的下限,
|
||||
且十几个按钮彼此相邻、又叠在图片上,误触率很高。
|
||||
这里不改视觉高度(改了会撑破密集网格),只用伪元素把可点区域向外扩到 32px。 */
|
||||
@media (hover: none) {
|
||||
.image-task-card .semi-button {
|
||||
position: relative;
|
||||
}
|
||||
.image-task-card .semi-button::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: -5px -3px;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,389 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Empty,
|
||||
Input,
|
||||
Modal,
|
||||
Progress,
|
||||
Radio,
|
||||
Spin,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Upload,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
Check,
|
||||
ExternalLink,
|
||||
Image as ImageIcon,
|
||||
Plus,
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
UserRound,
|
||||
} from 'lucide-react';
|
||||
import { QRCodeSVG } from 'qrcode.react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { showError, showSuccess } from '../../../../../helpers';
|
||||
import { usePortraitAssets } from '../../../../../hooks/video/usePortraitAssets';
|
||||
|
||||
const statusColor = {
|
||||
active: 'green',
|
||||
draft: 'grey',
|
||||
processing: 'blue',
|
||||
failed: 'red',
|
||||
};
|
||||
|
||||
const PortraitAssetPicker = ({
|
||||
onSelect,
|
||||
selectedAssetId,
|
||||
onClearSelection,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [consent, setConsent] = useState(false);
|
||||
const [selectedPortraitId, setSelectedPortraitId] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [secondsLeft, setSecondsLeft] = useState(0);
|
||||
const portrait = usePortraitAssets(visible);
|
||||
|
||||
const selectedPortrait = useMemo(
|
||||
() =>
|
||||
portrait.portraits.find((item) => item.id === selectedPortraitId) || null,
|
||||
[portrait.portraits, selectedPortraitId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedPortraitId && portrait.portraits.length > 0) {
|
||||
setSelectedPortraitId(portrait.portraits[0].id);
|
||||
}
|
||||
}, [portrait.portraits, selectedPortraitId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!portrait.session?.expires_at) {
|
||||
setSecondsLeft(0);
|
||||
return undefined;
|
||||
}
|
||||
const tick = () => {
|
||||
setSecondsLeft(
|
||||
Math.max(
|
||||
0,
|
||||
portrait.session.expires_at - Math.floor(Date.now() / 1000),
|
||||
),
|
||||
);
|
||||
};
|
||||
tick();
|
||||
const timer = setInterval(tick, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [portrait.session?.expires_at]);
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!name.trim() || !consent) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const created = await portrait.createPortrait(name.trim());
|
||||
setSelectedPortraitId(created.id);
|
||||
setName('');
|
||||
setConsent(false);
|
||||
} catch (error) {
|
||||
showError(portrait.errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerify = async () => {
|
||||
if (!selectedPortraitId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await portrait.startVerification(selectedPortraitId);
|
||||
} catch (error) {
|
||||
showError(portrait.errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpload = async ({ fileList }) => {
|
||||
const file = fileList?.[fileList.length - 1]?.fileInstance;
|
||||
if (!file || !selectedPortraitId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const asset = await portrait.uploadPortraitAsset(
|
||||
selectedPortraitId,
|
||||
file,
|
||||
);
|
||||
showSuccess(t('素材已提交审核'));
|
||||
portrait.refreshAssetUntilTerminal(asset.id).catch(() => {});
|
||||
} catch (error) {
|
||||
showError(portrait.errorMessage(error));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const assets = portrait.assets.filter(
|
||||
(asset) => asset.portrait_id === selectedPortraitId,
|
||||
);
|
||||
|
||||
const confirmDeleteAsset = (asset) => {
|
||||
Modal.confirm({
|
||||
title: t('删除素材'),
|
||||
content: t('删除后将无法继续用于视频生成。'),
|
||||
okType: 'danger',
|
||||
onOk: async () => {
|
||||
try {
|
||||
await portrait.deleteAsset(asset.id);
|
||||
if (asset.id === selectedAssetId) onClearSelection?.();
|
||||
} catch (error) {
|
||||
showError(portrait.errorMessage(error));
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const confirmDeletePortrait = (item) => {
|
||||
Modal.confirm({
|
||||
title: t('删除人像'),
|
||||
content: t('该人像及其全部关联素材将被删除。'),
|
||||
okType: 'danger',
|
||||
onOk: async () => {
|
||||
try {
|
||||
const clearsSelection = portrait.assets.some(
|
||||
(asset) =>
|
||||
asset.id === selectedAssetId && asset.portrait_id === item.id,
|
||||
);
|
||||
await portrait.deletePortrait(item.id);
|
||||
if (clearsSelection) onClearSelection?.();
|
||||
if (selectedPortraitId === item.id) setSelectedPortraitId('');
|
||||
showSuccess(t('人像已删除'));
|
||||
} catch (error) {
|
||||
showError(portrait.errorMessage(error));
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
icon={<UserRound size={16} />}
|
||||
theme='light'
|
||||
onClick={() => setVisible(true)}
|
||||
>
|
||||
{t('真人人像素材')}
|
||||
</Button>
|
||||
<Modal
|
||||
title={t('真人人像素材')}
|
||||
visible={visible}
|
||||
onCancel={() => setVisible(false)}
|
||||
footer={null}
|
||||
width={720}
|
||||
bodyStyle={{ maxHeight: '72vh', overflow: 'auto' }}
|
||||
>
|
||||
{portrait.loading ? (
|
||||
<div className='flex justify-center py-12'>
|
||||
<Spin />
|
||||
</div>
|
||||
) : portrait.enabled === false ? (
|
||||
<Empty title={t('真人人像素材未启用')} />
|
||||
) : (
|
||||
<div className='flex flex-col gap-5'>
|
||||
<div className='flex flex-col gap-3 border-b border-solid border-semi-color-border pb-5'>
|
||||
<div className='flex gap-2'>
|
||||
<Input
|
||||
value={name}
|
||||
onChange={setName}
|
||||
maxLength={128}
|
||||
placeholder={t('人像名称')}
|
||||
/>
|
||||
<Tooltip content={t('创建人像')}>
|
||||
<Button
|
||||
icon={<Plus size={16} />}
|
||||
onClick={handleCreate}
|
||||
loading={busy}
|
||||
disabled={!name.trim() || !consent}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<Checkbox
|
||||
checked={consent}
|
||||
onChange={(event) => setConsent(event.target.checked)}
|
||||
>
|
||||
{t('我已获得本人授权并拥有该人像素材的合法使用权')}
|
||||
</Checkbox>
|
||||
</div>
|
||||
|
||||
{portrait.portraits.length > 0 && (
|
||||
<Radio.Group
|
||||
value={selectedPortraitId}
|
||||
onChange={(event) => {
|
||||
setSelectedPortraitId(event.target.value);
|
||||
portrait.setSession(null);
|
||||
}}
|
||||
direction='vertical'
|
||||
className='w-full'
|
||||
>
|
||||
{portrait.portraits.map((item) => (
|
||||
<div key={item.id} className='flex items-center gap-2'>
|
||||
<Radio value={item.id} className='min-w-0 flex-1'>
|
||||
<span className='inline-flex min-w-0 items-center gap-2 py-1'>
|
||||
<span className='truncate'>{item.name}</span>
|
||||
<Tag
|
||||
color={statusColor[item.status] || 'grey'}
|
||||
size='small'
|
||||
>
|
||||
{item.status}
|
||||
</Tag>
|
||||
<span className='text-xs text-semi-color-text-2'>
|
||||
{item.id.slice(-6)}
|
||||
</span>
|
||||
</span>
|
||||
</Radio>
|
||||
<Tooltip content={t('删除人像')}>
|
||||
<Button
|
||||
type='danger'
|
||||
theme='borderless'
|
||||
icon={<Trash2 size={16} />}
|
||||
onClick={() => confirmDeletePortrait(item)}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
</Radio.Group>
|
||||
)}
|
||||
|
||||
{selectedPortrait &&
|
||||
selectedPortrait.status !== 'active' &&
|
||||
!portrait.session && (
|
||||
<Button
|
||||
icon={<ShieldCheck size={16} />}
|
||||
onClick={handleVerify}
|
||||
loading={busy}
|
||||
>
|
||||
{t('开始活体认证')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{portrait.session &&
|
||||
['pending', 'confirming'].includes(portrait.session.status) && (
|
||||
<div className='flex flex-col items-center gap-3 border-y border-solid border-semi-color-border py-5'>
|
||||
<QRCodeSVG value={portrait.session.h5_url} size={184} />
|
||||
<Progress
|
||||
percent={Math.round((secondsLeft / 120) * 100)}
|
||||
showInfo
|
||||
format={() => `${secondsLeft}s`}
|
||||
style={{ width: 240 }}
|
||||
/>
|
||||
<Button
|
||||
icon={<ExternalLink size={16} />}
|
||||
onClick={() =>
|
||||
window.open(
|
||||
portrait.session.h5_url,
|
||||
'_blank',
|
||||
'noopener,noreferrer',
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('打开认证页面')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{portrait.session?.status === 'succeeded' && (
|
||||
<Tag color='green' prefixIcon={<Check size={14} />}>
|
||||
{t('认证通过')}
|
||||
</Tag>
|
||||
)}
|
||||
|
||||
{selectedPortrait?.status === 'active' && (
|
||||
<Upload
|
||||
accept='image/*'
|
||||
limit={1}
|
||||
uploadTrigger='custom'
|
||||
showUploadList={false}
|
||||
onChange={handleUpload}
|
||||
>
|
||||
<Button icon={<ImageIcon size={16} />} loading={busy}>
|
||||
{t('上传真人素材')}
|
||||
</Button>
|
||||
</Upload>
|
||||
)}
|
||||
|
||||
<div className='flex flex-col divide-y divide-semi-color-border'>
|
||||
{assets.map((asset) => (
|
||||
<div
|
||||
key={asset.id}
|
||||
className='flex min-h-[64px] items-center gap-3 py-3'
|
||||
>
|
||||
<div className='h-12 w-12 shrink-0 overflow-hidden rounded-[6px] bg-semi-color-fill-0'>
|
||||
{asset.preview_url && (
|
||||
<img
|
||||
src={asset.preview_url}
|
||||
alt={asset.name}
|
||||
className='h-full w-full object-cover'
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className='min-w-0 flex-1'>
|
||||
<div className='truncate text-sm font-medium'>
|
||||
{asset.name}
|
||||
</div>
|
||||
<Tag
|
||||
color={statusColor[asset.status] || 'grey'}
|
||||
size='small'
|
||||
>
|
||||
{asset.status}
|
||||
</Tag>
|
||||
</div>
|
||||
{asset.status === 'active' && (
|
||||
<Tooltip content={t('选择素材')}>
|
||||
<Button
|
||||
icon={<Check size={16} />}
|
||||
onClick={() => {
|
||||
onSelect(asset);
|
||||
setVisible(false);
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip content={t('删除素材')}>
|
||||
<Button
|
||||
type='danger'
|
||||
theme='borderless'
|
||||
icon={<Trash2 size={16} />}
|
||||
onClick={() => confirmDeleteAsset(asset)}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PortraitAssetPicker;
|
||||
@@ -0,0 +1,944 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import {
|
||||
Card,
|
||||
TextArea,
|
||||
Upload,
|
||||
Collapse,
|
||||
Select,
|
||||
InputNumber,
|
||||
Switch,
|
||||
Button,
|
||||
Tag,
|
||||
Typography,
|
||||
Tooltip,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Image as ImageIcon,
|
||||
Video,
|
||||
Info,
|
||||
CreditCard,
|
||||
X,
|
||||
Film,
|
||||
Wand2,
|
||||
Layers,
|
||||
Settings2,
|
||||
Clock,
|
||||
Maximize,
|
||||
Mic,
|
||||
Sparkles,
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { PROMPT_TEMPLATES } from '../../../../../constants/video-generation.constant';
|
||||
import ModelSelector from '../../../../../components/common/ModelSelector';
|
||||
import { MODEL_CATEGORY } from '../../../../../constants';
|
||||
import { convertUSDToCurrency } from '../../../../../helpers';
|
||||
import PortraitAssetPicker from './PortraitAssetPicker';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
// 判断是否是阿里云模型(支持高级参数)
|
||||
const isAlibabaModel = (model) => {
|
||||
if (!model) return false;
|
||||
|
||||
// 检查 vendor 字段
|
||||
const vendor =
|
||||
typeof model === 'object' ? model.vendor || model.provider || '' : '';
|
||||
|
||||
// 检查模型名称
|
||||
const modelName =
|
||||
typeof model === 'object' ? model.model_name || model.id || '' : model;
|
||||
|
||||
// 阿里云厂商名称匹配
|
||||
const aliVendors = ['阿里云', '阿里', 'alibaba', 'aliyun', 'dashscope'];
|
||||
const isAliVendor = aliVendors.some((v) =>
|
||||
vendor.toLowerCase().includes(v.toLowerCase()),
|
||||
);
|
||||
|
||||
// 阿里云模型名称特征
|
||||
const aliModelPrefixes = ['wan', 'wanx', 'qwen'];
|
||||
const isAliModel = aliModelPrefixes.some((prefix) =>
|
||||
modelName.toLowerCase().startsWith(prefix),
|
||||
);
|
||||
|
||||
return isAliVendor || isAliModel;
|
||||
};
|
||||
|
||||
const VideoInputPanel = ({
|
||||
formData,
|
||||
setFormData,
|
||||
onCollapse,
|
||||
collapsed,
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
modelInfo,
|
||||
collapsible = true,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 检查当前模型是否支持高级参数
|
||||
const showAdvancedParams = isAlibabaModel(selectedModel);
|
||||
|
||||
const hoverScale = (e) => {
|
||||
e.currentTarget.style.transform = 'scale(1.1)';
|
||||
};
|
||||
|
||||
const resetScale = (e) => {
|
||||
e.currentTarget.style.transform = 'scale(1)';
|
||||
};
|
||||
|
||||
// 根据模式动态获取模型分类
|
||||
const getModelCategory = () => {
|
||||
return formData.mode === 'text2video'
|
||||
? MODEL_CATEGORY.TEXT_TO_VIDEO
|
||||
: MODEL_CATEGORY.IMAGE_TO_VIDEO;
|
||||
};
|
||||
|
||||
// 更新表单字段
|
||||
const updateField = (field, value) => {
|
||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
};
|
||||
|
||||
// 选择模板
|
||||
const handleTemplateSelect = (value) => {
|
||||
updateField('selectedTemplate', value);
|
||||
};
|
||||
|
||||
// 图片上传处理
|
||||
const handleImageUpload = (info) => {
|
||||
const { fileList } = info;
|
||||
if (fileList && fileList.length > 0) {
|
||||
const file = fileList[fileList.length - 1];
|
||||
const fileInstance = file.fileInstance;
|
||||
if (fileInstance) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
image: e.target.result,
|
||||
imagePreview: e.target.result,
|
||||
imageFile: fileInstance,
|
||||
imageName: fileInstance.name,
|
||||
imageIdentityType: 'aigc',
|
||||
}));
|
||||
};
|
||||
reader.readAsDataURL(fileInstance);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 移除图片
|
||||
const handleImageRemove = () => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
image: null,
|
||||
imagePreview: null,
|
||||
imageFile: null,
|
||||
imageName: null,
|
||||
imageIdentityType: null,
|
||||
}));
|
||||
};
|
||||
|
||||
const handlePortraitAssetSelect = (asset) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
image: `asset://${asset.id}`,
|
||||
imagePreview: asset.preview_url || null,
|
||||
imageFile: null,
|
||||
imageName: asset.name,
|
||||
imageIdentityType: 'real_person',
|
||||
}));
|
||||
};
|
||||
|
||||
// 单列(手机)布局不提供折叠:没有相邻面板可以让位,收起只会留下一片空白,
|
||||
// 而唯一的恢复入口是一个浮在屏幕左侧垂直中央的裸箭头。
|
||||
if (collapsed && collapsible) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: 0,
|
||||
top: '50%',
|
||||
transform: 'translateY(-50%)',
|
||||
zIndex: 100,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
icon={<ChevronRight size={20} />}
|
||||
onClick={onCollapse}
|
||||
style={{
|
||||
borderTopLeftRadius: 0,
|
||||
borderBottomLeftRadius: 0,
|
||||
color: '#1890ff',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='relative h-full overflow-auto' style={{ padding: '16px' }}>
|
||||
{/* 背景装饰 —— 走 bg-glow-* 两 stop(from/to) */}
|
||||
<div className='absolute inset-0 pointer-events-none opacity-30'>
|
||||
<div className='absolute top-10 right-0 w-32 h-32 bg-gradient-to-br from-bg-glow-from/20 to-bg-glow-to/20 rounded-full blur-3xl' />
|
||||
<div className='absolute bottom-20 left-0 w-40 h-40 bg-gradient-to-br from-bg-glow-from/20 to-bg-glow-to/20 rounded-full blur-3xl' />
|
||||
</div>
|
||||
|
||||
{/* 收起按钮 —— 仅在左右分栏布局下提供 */}
|
||||
{collapsible && (
|
||||
<div style={{ marginBottom: '16px', textAlign: 'right' }}>
|
||||
<Button
|
||||
icon={<ChevronLeft size={18} />}
|
||||
onClick={onCollapse}
|
||||
size='small'
|
||||
type='tertiary'
|
||||
className='hover:bg-cyan-50 dark:hover:bg-cyan-900/30 transition-colors'
|
||||
style={{ color: '#06b6d4' }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 生成方式 */}
|
||||
<div className='relative mb-4'>
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-400/20 to-blue-400/20 rounded-[14px] blur-sm' />
|
||||
<Card
|
||||
title={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<div className='p-1.5 bg-gradient-to-br from-cyan-500 to-blue-600 rounded-lg'>
|
||||
<Layers size={14} className='text-white' />
|
||||
</div>
|
||||
<span className='font-semibold bg-clip-text text-transparent bg-gradient-to-r from-cyan-600 to-blue-600 dark:from-cyan-400 dark:to-blue-400'>
|
||||
{t('生成方式')}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
className='relative bg-white/90 dark:bg-neutral-900/90 backdrop-blur-sm'
|
||||
style={{
|
||||
borderRadius: '12px',
|
||||
boxShadow: '0 4px 16px rgba(6, 182, 212, 0.08)',
|
||||
border: 'none',
|
||||
}}
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
headerStyle={{ padding: '12px 16px' }}
|
||||
>
|
||||
<div style={{ display: 'flex', gap: '12px' }}>
|
||||
<div
|
||||
onClick={() => updateField('mode', 'text2video')}
|
||||
onMouseEnter={hoverScale}
|
||||
onMouseLeave={resetScale}
|
||||
className={`group relative overflow-hidden ${formData.mode === 'text2video' ? 'ring-2 ring-cyan-500 shadow-lg shadow-cyan-500/20' : 'border border-gray-200 dark:border-neutral-700'}`}
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '16px',
|
||||
borderRadius: '12px',
|
||||
cursor: 'pointer',
|
||||
backgroundColor:
|
||||
formData.mode === 'text2video'
|
||||
? 'rgba(6, 182, 212, 0.05)'
|
||||
: 'transparent',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: '8px',
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
>
|
||||
{formData.mode === 'text2video' && (
|
||||
<div className='absolute inset-0 bg-gradient-to-br from-cyan-500/10 to-blue-500/10' />
|
||||
)}
|
||||
<div
|
||||
className={`relative p-2.5 rounded-xl transition-all ${formData.mode === 'text2video' ? 'bg-gradient-to-br from-cyan-500 to-blue-600 shadow-lg' : 'bg-gray-100 dark:bg-neutral-800'}`}
|
||||
>
|
||||
<Film
|
||||
size={24}
|
||||
className={
|
||||
formData.mode === 'text2video'
|
||||
? 'text-white'
|
||||
: 'text-gray-500 dark:text-gray-400'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className={`relative text-sm font-medium ${formData.mode === 'text2video' ? 'text-cyan-600 dark:text-cyan-400' : 'text-gray-600 dark:text-gray-400'}`}
|
||||
>
|
||||
{t('文生视频')}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
onClick={() => updateField('mode', 'image2video')}
|
||||
onMouseEnter={hoverScale}
|
||||
onMouseLeave={resetScale}
|
||||
className={`group relative overflow-hidden ${formData.mode === 'image2video' ? 'ring-2 ring-blue-500 shadow-lg shadow-blue-500/20' : 'border border-gray-200 dark:border-neutral-700'}`}
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '16px',
|
||||
borderRadius: '12px',
|
||||
cursor: 'pointer',
|
||||
backgroundColor:
|
||||
formData.mode === 'image2video'
|
||||
? 'rgba(59, 130, 246, 0.05)'
|
||||
: 'transparent',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: '8px',
|
||||
transition: 'all 0.3s ease',
|
||||
}}
|
||||
>
|
||||
{formData.mode === 'image2video' && (
|
||||
<div className='absolute inset-0 bg-gradient-to-br from-blue-500/10 to-brand-to/10' />
|
||||
)}
|
||||
<div
|
||||
className={`relative p-2.5 rounded-xl transition-all ${formData.mode === 'image2video' ? 'bg-gradient-to-br from-blue-500 to-brand-to shadow-lg' : 'bg-gray-100 dark:bg-neutral-800'}`}
|
||||
>
|
||||
<ImageIcon
|
||||
size={24}
|
||||
className={
|
||||
formData.mode === 'image2video'
|
||||
? 'text-white'
|
||||
: 'text-gray-500 dark:text-gray-400'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className={`relative text-sm font-medium ${formData.mode === 'image2video' ? 'text-blue-600 dark:text-blue-400' : 'text-gray-600 dark:text-gray-400'}`}
|
||||
>
|
||||
{t('图生视频')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 模型选择 */}
|
||||
<div className='relative mb-4'>
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-brand-from/20 to-brand-to/20 rounded-[14px] blur-sm' />
|
||||
<Card
|
||||
title={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<div className='p-1.5 bg-gradient-to-br from-brand-from to-brand-to rounded-lg'>
|
||||
<Wand2 size={14} className='text-white' />
|
||||
</div>
|
||||
<span className='font-semibold bg-clip-text text-transparent bg-gradient-to-r from-brand-from to-brand-to dark:from-brand-from dark:to-brand-to'>
|
||||
{t('选择模型')}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
className='relative bg-white/90 dark:bg-neutral-900/90 backdrop-blur-sm'
|
||||
style={{
|
||||
borderRadius: '12px',
|
||||
boxShadow:
|
||||
'0 4px 16px color-mix(in srgb, var(--brand-gradient-via) 8%, transparent)',
|
||||
border: 'none',
|
||||
}}
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
headerStyle={{ padding: '12px 16px' }}
|
||||
>
|
||||
<ModelSelector
|
||||
key={formData.mode}
|
||||
category={getModelCategory()}
|
||||
value={
|
||||
selectedModel?.id || selectedModel?.model_name || selectedModel
|
||||
}
|
||||
onChange={(model) => {
|
||||
setSelectedModel(model);
|
||||
}}
|
||||
placeholder={t('请选择模型')}
|
||||
/>
|
||||
{/* 模型信息简要展示 */}
|
||||
{modelInfo && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: '12px',
|
||||
padding: '12px',
|
||||
backgroundColor: 'var(--semi-color-fill-0)',
|
||||
borderRadius: '8px',
|
||||
fontSize: '13px',
|
||||
border: '1px solid var(--semi-color-border)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Text type='tertiary'>{t('厂商')}</Text>
|
||||
<Tag size='small' color='blue'>
|
||||
{modelInfo.provider}
|
||||
</Tag>
|
||||
</div>
|
||||
{Number(modelInfo.price) > 0 && (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginTop: '8px',
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
type='tertiary'
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '4px',
|
||||
}}
|
||||
>
|
||||
<CreditCard size={14} />
|
||||
{t('单价')}
|
||||
</Text>
|
||||
<Text strong style={{ color: 'var(--semi-color-danger)' }}>
|
||||
{convertUSDToCurrency(Number(modelInfo.price || 0), 6)}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 场景模板 */}
|
||||
<div className='relative mb-4'>
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-amber-400/20 to-orange-400/20 rounded-[14px] blur-sm' />
|
||||
<Card
|
||||
title={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<div className='p-1.5 bg-gradient-to-br from-amber-500 to-orange-500 rounded-lg'>
|
||||
<Sparkles size={14} className='text-white' />
|
||||
</div>
|
||||
<span className='font-semibold bg-clip-text text-transparent bg-gradient-to-r from-amber-600 to-orange-600 dark:from-amber-400 dark:to-orange-400'>
|
||||
{t('场景模板')}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
className='relative bg-white/90 dark:bg-neutral-900/90 backdrop-blur-sm'
|
||||
style={{
|
||||
borderRadius: '12px',
|
||||
boxShadow: '0 4px 16px rgba(251, 146, 60, 0.08)',
|
||||
border: 'none',
|
||||
}}
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
headerStyle={{ padding: '12px 16px' }}
|
||||
>
|
||||
<Select
|
||||
placeholder={t('选择场景模板(可选)')}
|
||||
value={formData.selectedTemplate}
|
||||
onChange={handleTemplateSelect}
|
||||
style={{ width: '100%' }}
|
||||
showClear
|
||||
>
|
||||
{PROMPT_TEMPLATES.map((template, index) => (
|
||||
<Select.Option key={index} value={template.prompt}>
|
||||
{template.label}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
{formData.selectedTemplate && (
|
||||
<div
|
||||
style={{
|
||||
marginTop: '12px',
|
||||
padding: '12px',
|
||||
backgroundColor: 'var(--semi-color-fill-0)',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--semi-color-border)',
|
||||
}}
|
||||
>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('模板内容')}: {formData.selectedTemplate}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 提示词 */}
|
||||
<div className='relative mb-4'>
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-emerald-400/20 to-teal-400/20 rounded-[14px] blur-sm' />
|
||||
<Card
|
||||
title={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<div className='p-1.5 bg-gradient-to-br from-emerald-500 to-teal-500 rounded-lg'>
|
||||
<Video size={14} className='text-white' />
|
||||
</div>
|
||||
<span className='font-semibold bg-clip-text text-transparent bg-gradient-to-r from-emerald-600 to-teal-600 dark:from-emerald-400 dark:to-teal-400'>
|
||||
{t('提示词')}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
className='relative bg-white/90 dark:bg-neutral-900/90 backdrop-blur-sm'
|
||||
style={{
|
||||
borderRadius: '12px',
|
||||
boxShadow: '0 4px 16px rgba(20, 184, 166, 0.08)',
|
||||
border: 'none',
|
||||
}}
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
headerStyle={{ padding: '12px 16px' }}
|
||||
>
|
||||
<TextArea
|
||||
placeholder={t(
|
||||
'描述你想要生成的视频内容,例如:一只可爱的猫咪在草地上玩耍',
|
||||
)}
|
||||
value={formData.prompt}
|
||||
onChange={(value) => updateField('prompt', value)}
|
||||
autosize={{ minRows: 4, maxRows: 8 }}
|
||||
maxLength={2000}
|
||||
showClear
|
||||
/>
|
||||
<Text
|
||||
type='tertiary'
|
||||
size='small'
|
||||
style={{ marginTop: '8px', display: 'block' }}
|
||||
>
|
||||
{formData.prompt?.length || 0} / 2000
|
||||
</Text>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 反向提示词 */}
|
||||
<div className='relative mb-4'>
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-rose-400/20 to-pink-400/20 rounded-[14px] blur-sm' />
|
||||
<Card
|
||||
title={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<div className='p-1.5 bg-gradient-to-br from-rose-500 to-pink-500 rounded-lg'>
|
||||
<X size={14} className='text-white' />
|
||||
</div>
|
||||
<span className='font-semibold bg-clip-text text-transparent bg-gradient-to-r from-rose-600 to-pink-600 dark:from-rose-400 dark:to-pink-400'>
|
||||
{t('反向提示词')}
|
||||
</span>
|
||||
<Tooltip content={t('描述不希望出现的内容')}>
|
||||
<Info size={14} className='text-rose-400' />
|
||||
</Tooltip>
|
||||
</div>
|
||||
}
|
||||
className='relative bg-white/90 dark:bg-neutral-900/90 backdrop-blur-sm'
|
||||
style={{
|
||||
borderRadius: '12px',
|
||||
boxShadow: '0 4px 16px rgba(244, 63, 94, 0.08)',
|
||||
border: 'none',
|
||||
}}
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
headerStyle={{ padding: '12px 16px' }}
|
||||
>
|
||||
<TextArea
|
||||
placeholder={t('例如:模糊、扭曲、低质量')}
|
||||
value={formData.negative_prompt}
|
||||
onChange={(value) => updateField('negative_prompt', value)}
|
||||
autosize={{ minRows: 2, maxRows: 4 }}
|
||||
maxLength={500}
|
||||
showClear
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 图片上传(图生视频时显示) */}
|
||||
{formData.mode === 'image2video' && (
|
||||
<div className='relative mb-4'>
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-blue-400/20 to-brand-to/20 rounded-[14px] blur-sm' />
|
||||
<Card
|
||||
title={
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<div className='p-1.5 bg-gradient-to-br from-blue-500 to-brand-to rounded-lg'>
|
||||
<ImageIcon size={14} className='text-white' />
|
||||
</div>
|
||||
<span className='font-semibold bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-brand-to dark:from-blue-400 dark:to-brand-to'>
|
||||
{t('首帧图片')}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
className='relative bg-white/90 dark:bg-neutral-900/90 backdrop-blur-sm'
|
||||
style={{
|
||||
borderRadius: '12px',
|
||||
boxShadow:
|
||||
'0 4px 16px color-mix(in srgb, var(--brand-primary) 8%, transparent)',
|
||||
border: 'none',
|
||||
}}
|
||||
bodyStyle={{ padding: '16px' }}
|
||||
headerStyle={{ padding: '12px 16px' }}
|
||||
>
|
||||
{formData.image ? (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: '12px',
|
||||
padding: '12px',
|
||||
backgroundColor: 'var(--semi-color-fill-0)',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--semi-color-border)',
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={formData.imagePreview || formData.image}
|
||||
alt='Preview'
|
||||
style={{
|
||||
width: '64px',
|
||||
height: '64px',
|
||||
objectFit: 'cover',
|
||||
borderRadius: '6px',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<Text
|
||||
ellipsis
|
||||
style={{
|
||||
display: 'block',
|
||||
fontSize: '13px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{formData.imageName ||
|
||||
formData.imageFile?.name ||
|
||||
t('已上传图片')}
|
||||
</Text>
|
||||
{formData.imageIdentityType === 'real_person' ? (
|
||||
<Tag color='green' size='small'>
|
||||
{t('真人人像')}
|
||||
</Tag>
|
||||
) : (
|
||||
<Text type='tertiary' size='small'>
|
||||
{formData.imageFile?.size
|
||||
? `${(formData.imageFile.size / 1024).toFixed(1)} KB`
|
||||
: ''}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
<Tooltip content={t('删除图片')}>
|
||||
<Button
|
||||
size='small'
|
||||
type='danger'
|
||||
theme='borderless'
|
||||
icon={<X size={16} />}
|
||||
onClick={handleImageRemove}
|
||||
style={{ marginLeft: 'auto' }}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<Upload
|
||||
accept='image/*'
|
||||
limit={1}
|
||||
onChange={handleImageUpload}
|
||||
uploadTrigger='custom'
|
||||
draggable
|
||||
dragMainText={
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
}}
|
||||
>
|
||||
<ImageIcon
|
||||
size={32}
|
||||
style={{ color: '#1890ff', opacity: 0.6 }}
|
||||
/>
|
||||
<span>{t('点击上传或拖拽图片到此处')}</span>
|
||||
</div>
|
||||
}
|
||||
dragSubText={t('支持 JPG、PNG 格式')}
|
||||
showUploadList={false}
|
||||
style={{
|
||||
border: '1px dashed var(--semi-color-border)',
|
||||
borderRadius: '8px',
|
||||
padding: '24px',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div style={{ marginTop: '12px', display: 'flex' }}>
|
||||
<PortraitAssetPicker
|
||||
onSelect={handlePortraitAssetSelect}
|
||||
selectedAssetId={
|
||||
formData.image?.startsWith('asset://')
|
||||
? formData.image.slice('asset://'.length)
|
||||
: ''
|
||||
}
|
||||
onClearSelection={handleImageRemove}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 高级参数 - 仅对阿里云模型显示 */}
|
||||
{showAdvancedParams && (
|
||||
<div className='relative'>
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-slate-400/20 to-gray-400/20 rounded-[14px] blur-sm' />
|
||||
<div
|
||||
className='relative bg-white/90 dark:bg-neutral-900/90 backdrop-blur-sm rounded-xl overflow-hidden'
|
||||
style={{ boxShadow: '0 4px 16px rgba(100, 116, 139, 0.08)' }}
|
||||
>
|
||||
<Collapse defaultActiveKey={[]} className='border-0'>
|
||||
<Collapse.Panel
|
||||
header={
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
}}
|
||||
>
|
||||
<div className='p-1.5 bg-gradient-to-br from-slate-500 to-gray-600 rounded-lg'>
|
||||
<Settings2 size={14} className='text-white' />
|
||||
</div>
|
||||
<span className='font-semibold text-slate-700 dark:text-slate-300'>
|
||||
{t('高级参数')}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
itemKey='advanced'
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '20px',
|
||||
}}
|
||||
>
|
||||
{/* 分辨率 */}
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '6px',
|
||||
marginBottom: '8px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
<Maximize size={16} style={{ color: '#1890ff' }} />
|
||||
{t('分辨率')}
|
||||
</label>
|
||||
<Select
|
||||
value={formData.resolution}
|
||||
onChange={(value) => updateField('resolution', value)}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Select.Option value='480P'>480P (832x480)</Select.Option>
|
||||
<Select.Option value='720P'>
|
||||
720P (1280x720)
|
||||
</Select.Option>
|
||||
<Select.Option value='1080P'>
|
||||
1080P (1920x1080)
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 时长 */}
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '6px',
|
||||
marginBottom: '8px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
<Clock size={16} style={{ color: '#1890ff' }} />
|
||||
{t('时长(秒)')}
|
||||
</label>
|
||||
<InputNumber
|
||||
value={formData.duration}
|
||||
onChange={(value) => updateField('duration', value)}
|
||||
min={3}
|
||||
max={10}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 帧率 */}
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
display: 'block',
|
||||
marginBottom: '8px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{t('帧率')}
|
||||
</label>
|
||||
<Select
|
||||
value={formData.fps}
|
||||
onChange={(value) => updateField('fps', value)}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Select.Option value={24}>24 FPS</Select.Option>
|
||||
<Select.Option value={30}>30 FPS</Select.Option>
|
||||
<Select.Option value={60}>60 FPS</Select.Option>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 比例 */}
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
display: 'block',
|
||||
marginBottom: '8px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{t('画面比例')}
|
||||
</label>
|
||||
<Select
|
||||
value={formData.ratio}
|
||||
onChange={(value) => updateField('ratio', value)}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Select.Option value='16:9'>
|
||||
{t('16:9 (横屏)')}
|
||||
</Select.Option>
|
||||
<Select.Option value='9:16'>
|
||||
{t('9:16 (竖屏)')}
|
||||
</Select.Option>
|
||||
<Select.Option value='1:1'>
|
||||
{t('1:1 (方形)')}
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* 音频 */}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<label
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '6px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
<Mic size={16} style={{ color: '#1890ff' }} />
|
||||
{t('自动生成音频')}
|
||||
</label>
|
||||
<Switch
|
||||
checked={formData.audio}
|
||||
onChange={(checked) => updateField('audio', checked)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Seed */}
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
display: 'block',
|
||||
marginBottom: '8px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{t('随机种子')}
|
||||
</label>
|
||||
<InputNumber
|
||||
value={formData.seed}
|
||||
onChange={(value) => updateField('seed', value)}
|
||||
min={-1}
|
||||
max={999999999}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('-1 表示随机')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 提示词优化 */}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<label
|
||||
style={{
|
||||
display: 'block',
|
||||
marginBottom: '4px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{t('智能改写提示词')}
|
||||
</label>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('AI 自动优化提示词')}
|
||||
</Text>
|
||||
</div>
|
||||
<Switch
|
||||
checked={formData.prompt_extend}
|
||||
onChange={(checked) =>
|
||||
updateField('prompt_extend', checked)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 水印 */}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<label
|
||||
style={{
|
||||
display: 'block',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
}}
|
||||
>
|
||||
{t('添加水印')}
|
||||
</label>
|
||||
<Switch
|
||||
checked={formData.watermark}
|
||||
onChange={(checked) => updateField('watermark', checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoInputPanel;
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useEffect } from 'react';
|
||||
import { Card, Typography, Space, Tag } from '@douyinfe/semi-ui';
|
||||
import { IconCreditCard, IconTickCircle } from '@douyinfe/semi-icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ModelSelector from '../../../../../components/common/ModelSelector';
|
||||
import { MODEL_CATEGORY } from '../../../../../constants';
|
||||
import { convertUSDToCurrency } from '../../../../../helpers';
|
||||
|
||||
const { Text, Paragraph } = Typography;
|
||||
|
||||
const VideoModelPanel = ({
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
modelInfo,
|
||||
mode,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 根据模式动态获取模型分类
|
||||
const getModelCategory = () => {
|
||||
return mode === 'text2video'
|
||||
? MODEL_CATEGORY.TEXT_TO_VIDEO
|
||||
: MODEL_CATEGORY.IMAGE_TO_VIDEO;
|
||||
};
|
||||
|
||||
// 当模式切换时,清空选中的模型
|
||||
useEffect(() => {
|
||||
setSelectedModel(null);
|
||||
}, [mode, setSelectedModel]);
|
||||
|
||||
return (
|
||||
<div style={{ padding: '16px', height: '100%', overflow: 'auto' }}>
|
||||
{/* 模型选择 */}
|
||||
<Card
|
||||
title={t('选择模型')}
|
||||
style={{ marginBottom: '16px' }}
|
||||
bodyStyle={{ padding: '12px' }}
|
||||
>
|
||||
<ModelSelector
|
||||
key={mode}
|
||||
category={getModelCategory()}
|
||||
value={
|
||||
selectedModel?.id || selectedModel?.model_name || selectedModel
|
||||
}
|
||||
onChange={(model) => {
|
||||
// 传递完整的模型对象,而不仅仅是名称
|
||||
setSelectedModel(model);
|
||||
}}
|
||||
placeholder={t('请选择模型')}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
{/* 模型信息 */}
|
||||
{modelInfo && (
|
||||
<Card
|
||||
title={t('模型信息')}
|
||||
style={{ marginBottom: '16px' }}
|
||||
bodyStyle={{ padding: '12px' }}
|
||||
>
|
||||
<Space vertical spacing='medium' style={{ width: '100%' }}>
|
||||
{/* 厂商 */}
|
||||
<div>
|
||||
<Text type='tertiary'>{t('厂商')}</Text>
|
||||
<div style={{ marginTop: '4px' }}>
|
||||
<Tag>{modelInfo.provider}</Tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 模型描述 */}
|
||||
{modelInfo.description && (
|
||||
<div>
|
||||
<Text type='tertiary'>{t('描述')}</Text>
|
||||
<Paragraph style={{ marginTop: '4px', marginBottom: 0 }}>
|
||||
{modelInfo.description}
|
||||
</Paragraph>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 能力特点 */}
|
||||
{modelInfo.features && modelInfo.features.length > 0 && (
|
||||
<div>
|
||||
<Text type='tertiary'>{t('能力特点')}</Text>
|
||||
<Space wrap style={{ marginTop: '4px' }}>
|
||||
{modelInfo.features.map((feature, index) => (
|
||||
<Tag key={index} color='blue'>
|
||||
<IconTickCircle
|
||||
size='small'
|
||||
style={{ marginRight: '4px' }}
|
||||
/>
|
||||
{feature}
|
||||
</Tag>
|
||||
))}
|
||||
</Space>
|
||||
</div>
|
||||
)}
|
||||
</Space>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* 模型价格 —— 单价为 0(含管理员隐藏价格场景)时不展示,避免误导性的 0.00 */}
|
||||
{Number(modelInfo?.price) > 0 && (
|
||||
<Card
|
||||
title={
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<IconCreditCard />
|
||||
<span>{t('模型价格')}</span>
|
||||
</div>
|
||||
}
|
||||
bodyStyle={{ padding: '12px' }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<Text type='tertiary'>{t('单价')}</Text>
|
||||
<Text
|
||||
strong
|
||||
style={{ fontSize: '18px', color: 'var(--semi-color-primary)' }}
|
||||
>
|
||||
{convertUSDToCurrency(Number(modelInfo?.price || 0), 6)}
|
||||
</Text>
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoModelPanel;
|
||||
@@ -0,0 +1,66 @@
|
||||
/* 视频预览面板 - 电影感动画背景(增强版) */
|
||||
|
||||
/* 动态光晕1 - 缓慢飘动 */
|
||||
@keyframes videoPreviewFloat1 {
|
||||
0%,
|
||||
100% {
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
25% {
|
||||
transform: translate3d(50px, -30px, 0);
|
||||
}
|
||||
50% {
|
||||
transform: translate3d(80px, 20px, 0);
|
||||
}
|
||||
75% {
|
||||
transform: translate3d(30px, 50px, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* 动态光晕2 - 反向飘动 */
|
||||
@keyframes videoPreviewFloat2 {
|
||||
0%,
|
||||
100% {
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
25% {
|
||||
transform: translate3d(-60px, 40px, 0);
|
||||
}
|
||||
50% {
|
||||
transform: translate3d(-30px, -50px, 0);
|
||||
}
|
||||
75% {
|
||||
transform: translate3d(-70px, -20px, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* 脉动效果 */
|
||||
@keyframes videoPreviewPulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.4;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
/* 动画类 - GPU 加速 */
|
||||
.video-preview-glow1 {
|
||||
animation: videoPreviewFloat1 12s ease-in-out infinite;
|
||||
will-change: transform;
|
||||
backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.video-preview-glow2 {
|
||||
animation: videoPreviewFloat2 15s ease-in-out infinite;
|
||||
will-change: transform;
|
||||
backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.video-preview-glow3 {
|
||||
animation: videoPreviewPulse 6s ease-in-out infinite;
|
||||
will-change: opacity, transform;
|
||||
}
|
||||
@@ -0,0 +1,855 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
Card,
|
||||
Button,
|
||||
Progress,
|
||||
Empty,
|
||||
Space,
|
||||
Typography,
|
||||
Spin,
|
||||
Tooltip,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
Play,
|
||||
Square,
|
||||
Download,
|
||||
RotateCcw,
|
||||
Share2,
|
||||
Film,
|
||||
HelpCircle,
|
||||
X,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
canCancelVideoTask,
|
||||
canRegenerateVideoTask,
|
||||
getVideoURLFromDetail,
|
||||
normalizeVideoTaskStatus,
|
||||
} from '../../../../../helpers/videoTask';
|
||||
import './VideoPreviewPanel.css';
|
||||
|
||||
const { Title, Text, Paragraph } = Typography;
|
||||
|
||||
const VideoPreviewPanel = ({
|
||||
formData,
|
||||
generating,
|
||||
currentTask,
|
||||
onGenerate,
|
||||
onCancel,
|
||||
selectedModel,
|
||||
selectedTaskForPlay, // 新增:从任务列表选择的任务
|
||||
onRegenerate, // 新增:再生成回调
|
||||
onClearSelectedTask, // 新增:清除选中任务的回调(关闭视频播放)
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
|
||||
|
||||
// 监听窗口大小变化
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
setWindowWidth(window.innerWidth);
|
||||
};
|
||||
|
||||
window.addEventListener('resize', handleResize);
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
}, []);
|
||||
|
||||
// 根据屏幕宽度获取响应式配置
|
||||
const getResponsiveConfig = () => {
|
||||
if (windowWidth > 1600) {
|
||||
return {
|
||||
minHeight: '400px',
|
||||
padding: '40px',
|
||||
videoMaxHeight: '600px',
|
||||
buttonSize: 'large',
|
||||
titleSize: 4,
|
||||
iconSize: 64,
|
||||
progressWidth: 120,
|
||||
};
|
||||
}
|
||||
if (windowWidth > 1280) {
|
||||
return {
|
||||
minHeight: '350px',
|
||||
padding: '32px',
|
||||
videoMaxHeight: '500px',
|
||||
buttonSize: 'default',
|
||||
titleSize: 5,
|
||||
iconSize: 56,
|
||||
progressWidth: 100,
|
||||
};
|
||||
}
|
||||
if (windowWidth > 1024) {
|
||||
return {
|
||||
minHeight: '300px',
|
||||
padding: '24px',
|
||||
videoMaxHeight: '400px',
|
||||
buttonSize: 'default',
|
||||
titleSize: 5,
|
||||
iconSize: 48,
|
||||
progressWidth: 90,
|
||||
};
|
||||
}
|
||||
// 小屏幕
|
||||
return {
|
||||
minHeight: '250px',
|
||||
padding: '16px',
|
||||
videoMaxHeight: '350px',
|
||||
buttonSize: 'small',
|
||||
titleSize: 6,
|
||||
iconSize: 40,
|
||||
progressWidth: 80,
|
||||
};
|
||||
};
|
||||
|
||||
const config = getResponsiveConfig();
|
||||
|
||||
// 处理下载
|
||||
const handleDownload = () => {
|
||||
const task = selectedTaskForPlay || currentTask;
|
||||
const videoUrl = getVideoURLFromDetail(task);
|
||||
|
||||
if (videoUrl) {
|
||||
const link = document.createElement('a');
|
||||
link.href = videoUrl;
|
||||
link.download = `video_${task.task_id || 'download'}.mp4`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理分享
|
||||
const handleShare = async () => {
|
||||
const task = selectedTaskForPlay || currentTask;
|
||||
const videoUrl = getVideoURLFromDetail(task);
|
||||
|
||||
if (videoUrl) {
|
||||
if (navigator.share) {
|
||||
try {
|
||||
await navigator.share({
|
||||
title: t('视频分享'),
|
||||
text: task.prompt || t('AI生成的视频'),
|
||||
url: videoUrl,
|
||||
});
|
||||
} catch (err) {
|
||||
// 用户取消分享或分享失败
|
||||
copyToClipboard(videoUrl);
|
||||
}
|
||||
} else {
|
||||
// 不支持分享API,复制链接
|
||||
copyToClipboard(videoUrl);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 复制到剪贴板
|
||||
const copyToClipboard = (text) => {
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
// 可以添加提示
|
||||
console.log('链接已复制到剪贴板');
|
||||
});
|
||||
} else {
|
||||
// 兼容旧浏览器
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = text;
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textArea);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理生成视频(同时关闭当前播放的视频)
|
||||
const handleGenerate = () => {
|
||||
// 先清除选中的任务,关闭视频播放窗口
|
||||
if (onClearSelectedTask) {
|
||||
onClearSelectedTask();
|
||||
}
|
||||
// 然后开始生成
|
||||
if (onGenerate) {
|
||||
onGenerate();
|
||||
}
|
||||
};
|
||||
|
||||
// 处理关闭视频播放窗口
|
||||
const handleCloseVideo = () => {
|
||||
if (onClearSelectedTask) {
|
||||
onClearSelectedTask();
|
||||
}
|
||||
};
|
||||
|
||||
// 处理重新生成
|
||||
const handleRegenerate = () => {
|
||||
const task = selectedTaskForPlay || currentTask;
|
||||
if (onRegenerate && task) {
|
||||
onRegenerate(task);
|
||||
} else {
|
||||
// 如果没有提供 onRegenerate 回调,则直接调用 onGenerate
|
||||
onGenerate();
|
||||
}
|
||||
};
|
||||
|
||||
// 判断按钮是否禁用
|
||||
const isButtonDisabled =
|
||||
(!formData.prompt && !formData.selectedTemplate) ||
|
||||
!selectedModel ||
|
||||
(typeof selectedModel === 'object' && selectedModel.level_locked) ||
|
||||
(formData.mode === 'image2video' && !formData.image);
|
||||
|
||||
// 渲染顶部操作栏(始终显示)
|
||||
const renderTopBar = () => {
|
||||
// 优先显示从任务列表选择的任务
|
||||
const displayTask = selectedTaskForPlay || currentTask;
|
||||
const normalizedStatus = normalizeVideoTaskStatus(displayTask?.status);
|
||||
const isCompleted = normalizedStatus === 'success';
|
||||
|
||||
// 检查是否有视频URL
|
||||
let _hasVideo = false;
|
||||
if (displayTask) {
|
||||
const videoUrl = getVideoURLFromDetail(displayTask);
|
||||
_hasVideo = isCompleted && !!videoUrl;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
padding: windowWidth > 768 ? '16px 20px' : '12px 16px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '12px',
|
||||
backgroundColor: 'var(--semi-color-bg-1)',
|
||||
borderBottom: '1px solid var(--semi-color-border)',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
type='primary'
|
||||
theme='solid'
|
||||
size={windowWidth > 768 ? 'default' : 'small'}
|
||||
icon={<Play size={16} fill='currentColor' />}
|
||||
onClick={isButtonDisabled ? undefined : handleGenerate}
|
||||
disabled={isButtonDisabled || generating}
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
background:
|
||||
isButtonDisabled || generating
|
||||
? undefined
|
||||
: 'linear-gradient(135deg, #1890ff 0%, #0050b3 100%)',
|
||||
border: 'none',
|
||||
}}
|
||||
>
|
||||
{generating
|
||||
? t('生成中...')
|
||||
: windowWidth > 768
|
||||
? t('开始生成')
|
||||
: t('生成')}
|
||||
</Button>
|
||||
|
||||
{/* 禁用提示 */}
|
||||
{isButtonDisabled && !generating && (
|
||||
<Text type='tertiary' style={{ fontSize: '12px' }}>
|
||||
{!selectedModel && t('请选择模型')}
|
||||
{selectedModel &&
|
||||
typeof selectedModel === 'object' &&
|
||||
selectedModel.level_locked &&
|
||||
t('当前等级无权调用此模型')}
|
||||
{selectedModel &&
|
||||
!(
|
||||
typeof selectedModel === 'object' && selectedModel.level_locked
|
||||
) &&
|
||||
!formData.prompt &&
|
||||
!formData.selectedTemplate &&
|
||||
t('请输入提示词或选择模板')}
|
||||
{selectedModel &&
|
||||
!(
|
||||
typeof selectedModel === 'object' && selectedModel.level_locked
|
||||
) &&
|
||||
(formData.prompt || formData.selectedTemplate) &&
|
||||
formData.mode === 'image2video' &&
|
||||
!formData.image &&
|
||||
t('请上传图片')}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
{/* 生成中状态提示 */}
|
||||
{generating && displayTask && (
|
||||
<Text
|
||||
type='tertiary'
|
||||
style={{
|
||||
fontSize: '12px',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '4px',
|
||||
}}
|
||||
>
|
||||
<Loader2 size={12} className='animate-spin' />
|
||||
{displayTask.progress || '0%'}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<div style={{ flex: 1 }} />
|
||||
|
||||
<Tooltip
|
||||
content={
|
||||
<div style={{ padding: '12px', maxWidth: '300px' }}>
|
||||
<div
|
||||
style={{
|
||||
fontWeight: 600,
|
||||
marginBottom: '8px',
|
||||
fontSize: '14px',
|
||||
}}
|
||||
>
|
||||
{t('使用提示')}
|
||||
</div>
|
||||
<div style={{ fontSize: '13px', lineHeight: '1.8' }}>
|
||||
• {t('详细的提示词能获得更好的效果')}
|
||||
<br />• {t('建议使用高质量的首帧图片')}
|
||||
<br />• {t('视频生成可能需要 1-3 分钟')}
|
||||
<br />• {t('可在任务队列中查看历史记录')}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
position='bottomRight'
|
||||
trigger='hover'
|
||||
showArrow={true}
|
||||
>
|
||||
<Button
|
||||
icon={<HelpCircle size={18} />}
|
||||
type='tertiary'
|
||||
size={windowWidth > 768 ? 'default' : 'small'}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 渲染预览区域
|
||||
const renderPreview = () => {
|
||||
// 优先显示从任务列表选择的任务
|
||||
const displayTask = selectedTaskForPlay || currentTask;
|
||||
|
||||
// 统一转换状态为小写进行比较
|
||||
const normalizedStatus = normalizeVideoTaskStatus(displayTask?.status);
|
||||
|
||||
// 生成完成 - 优先检查,包括从任务列表点击播放的情况
|
||||
const isCompleted = normalizedStatus === 'success';
|
||||
const videoUrl = getVideoURLFromDetail(displayTask);
|
||||
const taskData = displayTask?.request || {};
|
||||
|
||||
// 如果是已完成的任务且有视频URL,直接显示(无论是从任务列表还是当前生成)
|
||||
if (isCompleted && videoUrl) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: config.padding }}>
|
||||
{/* 视频播放器容器 */}
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
marginBottom: windowWidth > 768 ? '24px' : '16px',
|
||||
}}
|
||||
>
|
||||
{/* 关闭按钮 */}
|
||||
<Button
|
||||
icon={<X size={16} />}
|
||||
type='tertiary'
|
||||
theme='borderless'
|
||||
size='small'
|
||||
onClick={handleCloseVideo}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '8px',
|
||||
right: '8px',
|
||||
zIndex: 10,
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.5)',
|
||||
color: 'white',
|
||||
borderRadius: '50%',
|
||||
}}
|
||||
/>
|
||||
{/* 视频播放器 */}
|
||||
<video
|
||||
controls
|
||||
style={{
|
||||
width: '100%',
|
||||
maxHeight: config.videoMaxHeight,
|
||||
borderRadius: '8px',
|
||||
}}
|
||||
src={videoUrl}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 操作按钮 */}
|
||||
<Space wrap={windowWidth <= 768}>
|
||||
<Button
|
||||
type='primary'
|
||||
size={config.buttonSize}
|
||||
icon={<Download size={16} />}
|
||||
onClick={handleDownload}
|
||||
>
|
||||
{windowWidth > 768 ? t('下载视频') : t('下载')}
|
||||
</Button>
|
||||
<Button
|
||||
size={config.buttonSize}
|
||||
icon={<Share2 size={16} />}
|
||||
onClick={handleShare}
|
||||
>
|
||||
{t('分享')}
|
||||
</Button>
|
||||
{canRegenerateVideoTask(displayTask) && (
|
||||
<Button
|
||||
size={config.buttonSize}
|
||||
icon={<RotateCcw size={16} />}
|
||||
onClick={handleRegenerate}
|
||||
>
|
||||
{windowWidth > 768 ? t('再生成') : t('重新')}
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
|
||||
{/* 视频信息 */}
|
||||
<div
|
||||
style={{
|
||||
marginTop: windowWidth > 768 ? '24px' : '16px',
|
||||
padding: windowWidth > 768 ? '16px' : '12px',
|
||||
backgroundColor: 'var(--semi-color-fill-0)',
|
||||
borderRadius: '8px',
|
||||
textAlign: 'left',
|
||||
}}
|
||||
>
|
||||
<Space vertical spacing='small' style={{ width: '100%' }}>
|
||||
{(taskData.prompt || displayTask.prompt) && (
|
||||
<div>
|
||||
<Text
|
||||
strong
|
||||
style={{ fontSize: windowWidth > 768 ? '14px' : '12px' }}
|
||||
>
|
||||
{t('提示词')}:
|
||||
</Text>
|
||||
<Paragraph
|
||||
copyable
|
||||
style={{
|
||||
fontSize: windowWidth > 768 ? '13px' : '11px',
|
||||
marginTop: '4px',
|
||||
}}
|
||||
>
|
||||
{taskData.prompt || displayTask.prompt}
|
||||
</Paragraph>
|
||||
</div>
|
||||
)}
|
||||
{taskData.negative_prompt && (
|
||||
<div>
|
||||
<Text
|
||||
strong
|
||||
style={{ fontSize: windowWidth > 768 ? '14px' : '12px' }}
|
||||
>
|
||||
{t('反向提示词')}:
|
||||
</Text>
|
||||
<Paragraph
|
||||
copyable
|
||||
style={{
|
||||
fontSize: windowWidth > 768 ? '13px' : '11px',
|
||||
marginTop: '4px',
|
||||
}}
|
||||
>
|
||||
{taskData.negative_prompt}
|
||||
</Paragraph>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<Text
|
||||
type='tertiary'
|
||||
style={{ fontSize: windowWidth > 768 ? '12px' : '10px' }}
|
||||
>
|
||||
{t('模型')}:{' '}
|
||||
{taskData.model ||
|
||||
displayTask.properties?.upstream_model_name ||
|
||||
displayTask.properties?.origin_model_name ||
|
||||
(typeof selectedModel === 'object'
|
||||
? selectedModel?.model_name
|
||||
: selectedModel)}{' '}
|
||||
| {t('时长')}:{' '}
|
||||
{taskData.duration || displayTask.properties?.duration || '-'}
|
||||
s | {t('分辨率')}:{' '}
|
||||
{taskData.resolution ||
|
||||
displayTask.properties?.resolution ||
|
||||
'-'}
|
||||
</Text>
|
||||
</div>
|
||||
</Space>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 生成中(只在没有 selectedTaskForPlay 时显示)
|
||||
if (generating && displayTask && !selectedTaskForPlay) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minHeight: config.minHeight,
|
||||
padding: config.padding,
|
||||
}}
|
||||
>
|
||||
<Spin
|
||||
size={windowWidth > 768 ? 'large' : 'default'}
|
||||
indicator={<Loader2 className='animate-spin' size={32} />}
|
||||
/>
|
||||
<Title
|
||||
heading={config.titleSize}
|
||||
style={{ marginTop: '24px', marginBottom: '8px' }}
|
||||
>
|
||||
{t('视频生成中...')}
|
||||
</Title>
|
||||
<Text
|
||||
type='tertiary'
|
||||
style={{ fontSize: windowWidth > 768 ? '14px' : '12px' }}
|
||||
>
|
||||
{normalizedStatus === 'queued' && t('等待处理')}
|
||||
{normalizedStatus === 'in_progress' && t('正在生成')}
|
||||
</Text>
|
||||
|
||||
{/* 进度条 */}
|
||||
{displayTask.progress !== undefined &&
|
||||
(() => {
|
||||
// 解析进度值,处理字符串格式(如 "50%")
|
||||
let percentValue = 0;
|
||||
if (typeof displayTask.progress === 'string') {
|
||||
percentValue =
|
||||
parseInt(displayTask.progress.replace('%', '')) || 0;
|
||||
} else if (typeof displayTask.progress === 'number') {
|
||||
percentValue = displayTask.progress;
|
||||
}
|
||||
|
||||
return (
|
||||
<Progress
|
||||
percent={percentValue}
|
||||
showInfo
|
||||
type='circle'
|
||||
style={{ marginTop: '24px' }}
|
||||
width={config.progressWidth}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* 任务信息 */}
|
||||
<div style={{ marginTop: '24px', textAlign: 'center' }}>
|
||||
<Space vertical spacing='small'>
|
||||
<Text
|
||||
type='tertiary'
|
||||
style={{ fontSize: windowWidth > 768 ? '13px' : '11px' }}
|
||||
>
|
||||
{t('任务ID')}: {displayTask.task_id}
|
||||
</Text>
|
||||
<Text
|
||||
type='tertiary'
|
||||
style={{ fontSize: windowWidth > 768 ? '13px' : '11px' }}
|
||||
>
|
||||
{t('模型')}:{' '}
|
||||
{typeof selectedModel === 'object'
|
||||
? selectedModel?.model_name
|
||||
: selectedModel}
|
||||
</Text>
|
||||
{displayTask.estimated_time && (
|
||||
<Text
|
||||
type='tertiary'
|
||||
style={{ fontSize: windowWidth > 768 ? '13px' : '11px' }}
|
||||
>
|
||||
{t('预计时间')}: {displayTask.estimated_time}s
|
||||
</Text>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{canCancelVideoTask(displayTask) && (
|
||||
<Button
|
||||
type='danger'
|
||||
size={config.buttonSize}
|
||||
icon={<Square size={16} fill='currentColor' />}
|
||||
onClick={onCancel}
|
||||
style={{ marginTop: '32px' }}
|
||||
>
|
||||
{t('取消生成')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 生成失败 - 检查 'failed' 或 'failure' 状态
|
||||
const isFailed =
|
||||
normalizedStatus === 'failed' || normalizedStatus === 'failure';
|
||||
if (isFailed) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
minHeight: config.minHeight,
|
||||
padding: config.padding,
|
||||
}}
|
||||
>
|
||||
<Empty
|
||||
title={t('生成失败')}
|
||||
description={
|
||||
displayTask.fail_reason || displayTask.error || t('未知错误')
|
||||
}
|
||||
/>
|
||||
{canRegenerateVideoTask(displayTask) && (
|
||||
<Button
|
||||
type='primary'
|
||||
size={config.buttonSize}
|
||||
icon={<RotateCcw size={16} />}
|
||||
onClick={handleRegenerate}
|
||||
style={{ marginTop: '24px' }}
|
||||
>
|
||||
{t('重新生成')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 初始状态或图生视频预览
|
||||
if (formData.mode === 'image2video' && formData.image) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: config.padding }}>
|
||||
<Title
|
||||
heading={config.titleSize + 1}
|
||||
style={{ marginBottom: '16px' }}
|
||||
>
|
||||
{t('首帧预览')}
|
||||
</Title>
|
||||
<img
|
||||
src={formData.imagePreview || formData.image}
|
||||
alt='Preview'
|
||||
style={{
|
||||
maxWidth: '100%',
|
||||
maxHeight: windowWidth > 1024 ? '500px' : '350px',
|
||||
borderRadius: '8px',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 默认空状态 - 纯CSS电影感动画背景(无网络资源消耗)
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
minHeight: config.minHeight,
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
borderRadius: '12px',
|
||||
overflow: 'hidden',
|
||||
margin: '16px',
|
||||
background:
|
||||
'linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 50%, #16213e 100%)',
|
||||
}}
|
||||
>
|
||||
{/* CSS动画背景 - 流动光效(增强版) */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
overflow: 'hidden',
|
||||
pointerEvents: 'none',
|
||||
}}
|
||||
>
|
||||
{/* 动态光晕1 - 紫色 */}
|
||||
<div
|
||||
className='video-preview-glow1'
|
||||
style={{
|
||||
position: 'absolute',
|
||||
width: '60%',
|
||||
height: '60%',
|
||||
top: '10%',
|
||||
left: '5%',
|
||||
background:
|
||||
'radial-gradient(ellipse at center, color-mix(in srgb, var(--brand-gradient-via) 35%, transparent) 0%, color-mix(in srgb, var(--brand-gradient-via) 10%, transparent) 40%, transparent 70%)',
|
||||
borderRadius: '50%',
|
||||
filter: 'blur(40px)',
|
||||
}}
|
||||
/>
|
||||
{/* 动态光晕2 - 橙红色 */}
|
||||
<div
|
||||
className='video-preview-glow2'
|
||||
style={{
|
||||
position: 'absolute',
|
||||
width: '50%',
|
||||
height: '50%',
|
||||
bottom: '10%',
|
||||
right: '5%',
|
||||
background:
|
||||
'radial-gradient(ellipse at center, rgba(251, 146, 60, 0.3) 0%, rgba(251, 146, 60, 0.1) 40%, transparent 70%)',
|
||||
borderRadius: '50%',
|
||||
filter: 'blur(40px)',
|
||||
}}
|
||||
/>
|
||||
{/* 动态光晕3 - 金色中心 */}
|
||||
<div
|
||||
className='video-preview-glow3'
|
||||
style={{
|
||||
position: 'absolute',
|
||||
width: '40%',
|
||||
height: '40%',
|
||||
top: '30%',
|
||||
left: '30%',
|
||||
background:
|
||||
'radial-gradient(ellipse at center, rgba(251, 191, 36, 0.25) 0%, transparent 60%)',
|
||||
borderRadius: '50%',
|
||||
filter: 'blur(30px)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 电影宽银幕效果 - 上下黑边 */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: '6%',
|
||||
background:
|
||||
'linear-gradient(180deg, rgba(0,0,0,0.95) 0%, transparent 100%)',
|
||||
zIndex: 2,
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: '6%',
|
||||
background:
|
||||
'linear-gradient(0deg, rgba(0,0,0,0.95) 0%, transparent 100%)',
|
||||
zIndex: 2,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 中央内容区域 */}
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
padding: config.padding,
|
||||
color: 'white',
|
||||
position: 'relative',
|
||||
zIndex: 3,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.1)',
|
||||
borderRadius: '50%',
|
||||
padding: windowWidth > 1024 ? '32px' : '24px',
|
||||
marginBottom: windowWidth > 768 ? '32px' : '24px',
|
||||
border: '1px solid rgba(255, 255, 255, 0.2)',
|
||||
boxShadow: '0 8px 32px rgba(0, 0, 0, 0.3)',
|
||||
transition: 'transform 0.3s ease',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
e.currentTarget.style.transform = 'scale(1.05)';
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.transform = 'scale(1)';
|
||||
}}
|
||||
>
|
||||
<Film
|
||||
size={config.iconSize}
|
||||
style={{
|
||||
color: 'rgba(255, 220, 180, 0.9)',
|
||||
filter: 'drop-shadow(0 2px 12px rgba(255,200,150,0.4))',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Title
|
||||
heading={config.titleSize}
|
||||
style={{
|
||||
marginBottom: '12px',
|
||||
color: 'rgba(255, 250, 245, 0.95)',
|
||||
fontWeight: 700,
|
||||
textShadow: '0 4px 20px rgba(0, 0, 0, 0.6)',
|
||||
letterSpacing: '3px',
|
||||
}}
|
||||
>
|
||||
{t('AI 视频生成')}
|
||||
</Title>
|
||||
|
||||
<Text
|
||||
style={{
|
||||
marginBottom: windowWidth > 768 ? '24px' : '16px',
|
||||
textAlign: 'center',
|
||||
fontSize: windowWidth > 768 ? '16px' : '14px',
|
||||
padding: '0 16px',
|
||||
color: 'rgba(255, 255, 255, 0.7)',
|
||||
maxWidth: '500px',
|
||||
lineHeight: '1.8',
|
||||
textShadow: '0 2px 8px rgba(0, 0, 0, 0.5)',
|
||||
}}
|
||||
>
|
||||
{formData.mode === 'text2video'
|
||||
? t('输入提示词,让 AI 为你创造精彩视频')
|
||||
: t('上传图片并输入提示词,生成动态视频')}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card
|
||||
style={{ height: '100%', display: 'flex', flexDirection: 'column' }}
|
||||
bodyStyle={{
|
||||
flex: 1,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'hidden',
|
||||
padding: 0,
|
||||
}}
|
||||
>
|
||||
{/* 始终显示的顶部操作栏 */}
|
||||
{renderTopBar()}
|
||||
|
||||
{/* 内容区域 */}
|
||||
<div style={{ flex: 1, overflow: 'auto' }}>{renderPreview()}</div>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoPreviewPanel;
|
||||
@@ -0,0 +1,296 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
Modal,
|
||||
Form,
|
||||
Select,
|
||||
Input,
|
||||
InputNumber,
|
||||
Switch,
|
||||
Space,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useIsMobile } from '../../../../../hooks/common/useIsMobile';
|
||||
import ModelSelector from '../../../../../components/common/ModelSelector';
|
||||
import { MODEL_CATEGORY } from '../../../../../constants';
|
||||
import { buildVideoRegenerateRequest } from '../../../../../helpers/videoTask';
|
||||
|
||||
const { TextArea } = Input;
|
||||
const { Text } = Typography;
|
||||
|
||||
const VideoRegenerateModal = ({ visible, onCancel, onConfirm, task }) => {
|
||||
const isNarrow = useIsMobile();
|
||||
const { t } = useTranslation();
|
||||
const [formData, setFormData] = useState({
|
||||
mode: 'text2video',
|
||||
prompt: '',
|
||||
negative_prompt: '',
|
||||
resolution: '1080P',
|
||||
duration: 5,
|
||||
fps: 30,
|
||||
ratio: '16:9',
|
||||
audio: false,
|
||||
seed: -1,
|
||||
prompt_extend: false,
|
||||
watermark: false,
|
||||
image: '',
|
||||
});
|
||||
const [selectedModel, setSelectedModel] = useState('');
|
||||
|
||||
// 从任务数据中提取参数
|
||||
useEffect(() => {
|
||||
if (task && visible) {
|
||||
const taskData = task.request || {};
|
||||
const mode = taskData.mode || 'text2video';
|
||||
const prompt = taskData.prompt || '';
|
||||
const negativePrompt = taskData.negative_prompt || '';
|
||||
const resolution = taskData.resolution || '1080P';
|
||||
const duration = taskData.duration || 5;
|
||||
const fps = taskData.fps || 30;
|
||||
const ratio = taskData.ratio || '16:9';
|
||||
const audio = taskData.audio === true;
|
||||
const seed = taskData.seed ?? -1;
|
||||
const promptExtend = taskData.prompt_extend === true;
|
||||
const watermark = taskData.watermark === true;
|
||||
const image = taskData.image || '';
|
||||
const model = taskData.model || '';
|
||||
|
||||
setFormData({
|
||||
mode,
|
||||
prompt,
|
||||
negative_prompt: negativePrompt,
|
||||
resolution,
|
||||
duration,
|
||||
fps,
|
||||
ratio,
|
||||
audio,
|
||||
seed,
|
||||
prompt_extend: promptExtend,
|
||||
watermark,
|
||||
image,
|
||||
});
|
||||
|
||||
setSelectedModel(model);
|
||||
}
|
||||
}, [task, visible]);
|
||||
|
||||
// 处理表单提交
|
||||
const handleSubmit = () => {
|
||||
if (!selectedModel || typeof selectedModel !== 'object') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建请求数据
|
||||
onConfirm(buildVideoRegenerateRequest(formData, selectedModel));
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
title={t('再生成视频')}
|
||||
visible={visible}
|
||||
onCancel={onCancel}
|
||||
onOk={handleSubmit}
|
||||
okText={t('确认生成')}
|
||||
cancelText={t('取消')}
|
||||
width={700}
|
||||
bodyStyle={{
|
||||
maxHeight: '70vh',
|
||||
overflowX: 'hidden',
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
>
|
||||
<Form
|
||||
// 窄屏改为标签在上:labelWidth=120 在 ~294px 的弹窗体里要吃掉 41%,
|
||||
// 剩给控件的宽度放不下 seed 输入框和它的说明文案
|
||||
labelPosition={isNarrow ? 'top' : 'left'}
|
||||
labelAlign='right'
|
||||
labelWidth={isNarrow ? undefined : 120}
|
||||
>
|
||||
{/* 生成模式 */}
|
||||
<Form.Label>
|
||||
<Text strong>{t('生成模式')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<Select
|
||||
value={formData.mode}
|
||||
onChange={(value) => {
|
||||
setFormData({ ...formData, mode: value });
|
||||
setSelectedModel('');
|
||||
}}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Select.Option value='text2video'>{t('文生视频')}</Select.Option>
|
||||
<Select.Option value='image2video'>{t('图生视频')}</Select.Option>
|
||||
</Select>
|
||||
</Form.Input>
|
||||
|
||||
{/* 模型选择 */}
|
||||
<Form.Label required>
|
||||
<Text strong>{t('选择模型')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<ModelSelector
|
||||
key={formData.mode}
|
||||
category={
|
||||
formData.mode === 'text2video'
|
||||
? MODEL_CATEGORY.TEXT_TO_VIDEO
|
||||
: MODEL_CATEGORY.IMAGE_TO_VIDEO
|
||||
}
|
||||
value={
|
||||
selectedModel?.id || selectedModel?.model_name || selectedModel
|
||||
}
|
||||
onChange={setSelectedModel}
|
||||
placeholder={t('请选择模型')}
|
||||
autoSelectFirst={false}
|
||||
onModelsLoaded={(models) => {
|
||||
if (typeof selectedModel !== 'string' || !selectedModel) return;
|
||||
const match = models.find(
|
||||
(model) => model.model_name === selectedModel,
|
||||
);
|
||||
setSelectedModel(match || '');
|
||||
}}
|
||||
/>
|
||||
</Form.Input>
|
||||
|
||||
{/* 提示词 */}
|
||||
<Form.Label required>
|
||||
<Text strong>{t('提示词')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<TextArea
|
||||
value={formData.prompt}
|
||||
onChange={(value) => setFormData({ ...formData, prompt: value })}
|
||||
placeholder={t('描述你想生成的视频内容')}
|
||||
rows={3}
|
||||
maxLength={2000}
|
||||
showClear
|
||||
/>
|
||||
</Form.Input>
|
||||
|
||||
{/* 反向提示词 */}
|
||||
<Form.Label>
|
||||
<Text strong>{t('反向提示词')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<TextArea
|
||||
value={formData.negative_prompt}
|
||||
onChange={(value) =>
|
||||
setFormData({ ...formData, negative_prompt: value })
|
||||
}
|
||||
placeholder={t('描述不想出现的内容')}
|
||||
rows={2}
|
||||
maxLength={1000}
|
||||
showClear
|
||||
/>
|
||||
</Form.Input>
|
||||
|
||||
{/* 分辨率 */}
|
||||
<Form.Label>
|
||||
<Text strong>{t('分辨率')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<Select
|
||||
value={formData.resolution}
|
||||
onChange={(value) =>
|
||||
setFormData({ ...formData, resolution: value })
|
||||
}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Select.Option value='480P'>480P (832*480)</Select.Option>
|
||||
<Select.Option value='720P'>720P (1280*720)</Select.Option>
|
||||
<Select.Option value='1080P'>1080P (1920*1080)</Select.Option>
|
||||
</Select>
|
||||
</Form.Input>
|
||||
|
||||
{/* 时长 */}
|
||||
<Form.Label>
|
||||
<Text strong>{t('视频时长')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<InputNumber
|
||||
value={formData.duration}
|
||||
onChange={(value) => setFormData({ ...formData, duration: value })}
|
||||
min={3}
|
||||
max={10}
|
||||
suffix={t('秒')}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</Form.Input>
|
||||
|
||||
{/* 宽高比 */}
|
||||
<Form.Label>
|
||||
<Text strong>{t('宽高比')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<Select
|
||||
value={formData.ratio}
|
||||
onChange={(value) => setFormData({ ...formData, ratio: value })}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
<Select.Option value='16:9'>{t('16:9 (横屏)')}</Select.Option>
|
||||
<Select.Option value='9:16'>{t('9:16 (竖屏)')}</Select.Option>
|
||||
<Select.Option value='1:1'>{t('1:1 (方形)')}</Select.Option>
|
||||
</Select>
|
||||
</Form.Input>
|
||||
|
||||
{/* 高级选项 */}
|
||||
<Form.Label>
|
||||
<Text strong>{t('高级选项')}</Text>
|
||||
</Form.Label>
|
||||
<Form.Input>
|
||||
<Space vertical align='start' style={{ width: '100%' }}>
|
||||
<Space>
|
||||
<Switch
|
||||
checked={formData.audio}
|
||||
onChange={(checked) =>
|
||||
setFormData({ ...formData, audio: checked })
|
||||
}
|
||||
/>
|
||||
<Text>{t('生成音频')}</Text>
|
||||
</Space>
|
||||
<Space>
|
||||
<Switch
|
||||
checked={formData.prompt_extend}
|
||||
onChange={(checked) =>
|
||||
setFormData({ ...formData, prompt_extend: checked })
|
||||
}
|
||||
/>
|
||||
<Text>{t('提示词扩展')}</Text>
|
||||
</Space>
|
||||
<Space>
|
||||
<InputNumber
|
||||
value={formData.seed}
|
||||
onChange={(value) => setFormData({ ...formData, seed: value })}
|
||||
placeholder={t('随机种子(可选)')}
|
||||
min={0}
|
||||
style={{ width: '100%', maxWidth: 200 }}
|
||||
/>
|
||||
<Text type='tertiary'>{t('固定种子可复现结果')}</Text>
|
||||
</Space>
|
||||
</Space>
|
||||
</Form.Input>
|
||||
</Form>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoRegenerateModal;
|
||||
@@ -0,0 +1,483 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Space,
|
||||
Tag,
|
||||
Progress,
|
||||
Tooltip,
|
||||
Modal,
|
||||
Badge,
|
||||
Select,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
ChevronUp,
|
||||
ChevronDown,
|
||||
RefreshCw,
|
||||
Download,
|
||||
Trash2,
|
||||
Play,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Clock,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useIsMobile } from '../../../../../hooks/common/useIsMobile';
|
||||
import {
|
||||
canRegenerateVideoTask,
|
||||
normalizeVideoTaskStatus,
|
||||
} from '../../../../../helpers/videoTask';
|
||||
|
||||
const VideoTaskQueue = ({
|
||||
visible,
|
||||
setVisible,
|
||||
tasks,
|
||||
onRefresh,
|
||||
onDelete,
|
||||
onDownload,
|
||||
onPlay, // 新增:播放回调
|
||||
onRegenerate, // 新增:再生成回调
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
// 断点判定必须按「宽度」。本组件此前 20 多处响应式判断写的是 !isCompact,
|
||||
// 判的是窗口高度——390x844 的手机上 844 > 768 成立,于是整个队列走桌面分支:
|
||||
// 8 列合计 1190px 塞进 ~340px 容器、按钮全带文字,实际完全用不了。
|
||||
const isCompact = useIsMobile();
|
||||
const [selectedTasks, setSelectedTasks] = useState([]);
|
||||
const [windowHeight, setWindowHeight] = useState(window.innerHeight);
|
||||
const [pageSize, setPageSize] = useState(5); // 新增:分页大小状态
|
||||
|
||||
// 监听窗口高度变化
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
setWindowHeight(window.innerHeight);
|
||||
};
|
||||
|
||||
window.addEventListener('resize', handleResize);
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
}, []);
|
||||
|
||||
// 计算任务队列高度:不超过屏幕高度的20%(五分之一)
|
||||
// 同时设置最小高度150px,最大高度300px
|
||||
const getQueueHeight = () => {
|
||||
const maxHeightPercent = windowHeight * 0.2; // 屏幕高度的20%
|
||||
// 手机端工具栏本身会换行占掉 ~100px,再按 20%(844px 屏上仅 169px)会让表格只剩
|
||||
// 不到 70px,连表头带分页都放不下。窄屏改用更宽松的下限。
|
||||
const minHeight = isCompact ? 300 : 150;
|
||||
const maxHeight = isCompact ? 420 : 300;
|
||||
|
||||
// 在最小和最大值之间取适当的高度
|
||||
return Math.max(minHeight, Math.min(maxHeightPercent, maxHeight));
|
||||
};
|
||||
|
||||
const queueHeight = getQueueHeight();
|
||||
|
||||
// 状态标签映射
|
||||
const getStatusTag = (status) => {
|
||||
// 统一转换为小写进行比较
|
||||
const normalizedStatus = normalizeVideoTaskStatus(status);
|
||||
const statusMap = {
|
||||
queued: { color: 'blue', text: t('排队中'), icon: <Clock size={12} /> },
|
||||
in_progress: {
|
||||
color: 'cyan',
|
||||
text: t('生成中'),
|
||||
icon: <Loader2 size={12} className='animate-spin' />,
|
||||
},
|
||||
success: {
|
||||
color: 'green',
|
||||
text: t('已完成'),
|
||||
icon: <CheckCircle2 size={12} />,
|
||||
},
|
||||
completed: {
|
||||
color: 'green',
|
||||
text: t('已完成'),
|
||||
icon: <CheckCircle2 size={12} />,
|
||||
},
|
||||
failure: {
|
||||
color: 'red',
|
||||
text: t('失败'),
|
||||
icon: <AlertCircle size={12} />,
|
||||
},
|
||||
failed: {
|
||||
color: 'red',
|
||||
text: t('失败'),
|
||||
icon: <AlertCircle size={12} />,
|
||||
},
|
||||
canceled: {
|
||||
color: 'grey',
|
||||
text: t('已取消'),
|
||||
icon: <AlertCircle size={12} />,
|
||||
},
|
||||
};
|
||||
const config = statusMap[normalizedStatus] || {
|
||||
color: 'grey',
|
||||
text: status,
|
||||
};
|
||||
return (
|
||||
<Tag
|
||||
color={config.color}
|
||||
style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}
|
||||
>
|
||||
{config.icon}
|
||||
{config.text}
|
||||
</Tag>
|
||||
);
|
||||
};
|
||||
|
||||
// 批量下载 - 只下载已完成的任务
|
||||
const handleBatchDownload = () => {
|
||||
selectedTasks.forEach((taskId) => {
|
||||
const task = tasks.find((t) => t.task_id === taskId);
|
||||
if (task) {
|
||||
const normalizedStatus = normalizeVideoTaskStatus(task.status);
|
||||
// 只下载已完成的任务,视频URL会在 onDownload 中获取
|
||||
if (normalizedStatus === 'success') {
|
||||
onDownload(task);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// 批量删除
|
||||
const handleBatchDelete = () => {
|
||||
selectedTasks.forEach((taskId) => {
|
||||
onDelete(taskId);
|
||||
});
|
||||
setSelectedTasks([]);
|
||||
};
|
||||
|
||||
// 表格列定义
|
||||
const columns = [
|
||||
{
|
||||
title: t('任务ID'),
|
||||
dataIndex: 'task_id',
|
||||
width: !isCompact ? 120 : 100,
|
||||
render: (text) => (
|
||||
<Tooltip content={text}>
|
||||
<span style={{ cursor: 'pointer' }}>{text?.substring(0, 8)}...</span>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('模式'),
|
||||
dataIndex: 'action',
|
||||
width: !isCompact ? 100 : 80,
|
||||
render: (text) => {
|
||||
// action 字段存储的是 text2video 或 image2video
|
||||
const isText2Video = text === 'text2video' || text === 'TEXT2VIDEO';
|
||||
return (
|
||||
<Tag size={!isCompact ? 'default' : 'small'}>
|
||||
{isText2Video ? t('文生视频') : t('图生视频')}
|
||||
</Tag>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('模型'),
|
||||
dataIndex: 'model',
|
||||
width: !isCompact ? 150 : 120,
|
||||
render: (model) => model || '-',
|
||||
},
|
||||
{
|
||||
title: t('提示词'),
|
||||
dataIndex: 'prompt',
|
||||
width: !isCompact ? 200 : 150,
|
||||
ellipsis: { showTitle: true },
|
||||
render: (prompt) => prompt || '-',
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: !isCompact ? 120 : 100,
|
||||
render: (status) => getStatusTag(status),
|
||||
},
|
||||
{
|
||||
title: t('进度'),
|
||||
dataIndex: 'progress',
|
||||
width: !isCompact ? 120 : 100,
|
||||
render: (progress, record) => {
|
||||
const normalizedStatus = normalizeVideoTaskStatus(record.status);
|
||||
if (normalizedStatus === 'success') return '100%';
|
||||
if (normalizedStatus === 'failure') return '-';
|
||||
// 去除百分号并转换为数字
|
||||
const percentValue =
|
||||
typeof progress === 'string'
|
||||
? parseInt(progress.replace('%', ''))
|
||||
: progress || 0;
|
||||
return <Progress percent={percentValue} showInfo size='small' />;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('创建时间'),
|
||||
dataIndex: 'created_at',
|
||||
width: !isCompact ? 160 : 140,
|
||||
render: (timestamp) => new Date(timestamp * 1000).toLocaleString('zh-CN'),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
dataIndex: 'operate',
|
||||
width: !isCompact ? 220 : 180,
|
||||
fixed: 'right',
|
||||
render: (text, record) => {
|
||||
const normalizedStatus = normalizeVideoTaskStatus(record.status);
|
||||
|
||||
return (
|
||||
<Space>
|
||||
{/* 播放和下载按钮:仅根据状态显示,视频URL在点击时才获取 */}
|
||||
{normalizedStatus === 'success' && (
|
||||
<>
|
||||
<Button
|
||||
size='small'
|
||||
type='tertiary'
|
||||
icon={<Play size={14} />}
|
||||
onClick={() => onPlay && onPlay(record)}
|
||||
>
|
||||
{!isCompact ? t('播放') : ''}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
type='tertiary'
|
||||
icon={<Download size={14} />}
|
||||
onClick={() => onDownload(record)}
|
||||
>
|
||||
{!isCompact ? t('下载') : ''}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{/* 再生成按钮 - 对所有已完成或失败的任务显示 */}
|
||||
{(normalizedStatus === 'success' ||
|
||||
normalizedStatus === 'failure') &&
|
||||
canRegenerateVideoTask(record) && (
|
||||
<Button
|
||||
size='small'
|
||||
type='primary'
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={() => onRegenerate && onRegenerate(record)}
|
||||
>
|
||||
{!isCompact ? t('再生成') : ''}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size='small'
|
||||
type='danger'
|
||||
icon={<Trash2 size={14} />}
|
||||
onClick={() => {
|
||||
Modal.warning({
|
||||
title: t('确定删除此任务?'),
|
||||
content: t('删除后将无法恢复'),
|
||||
icon: <AlertCircle size={24} style={{ color: '#f59e0b' }} />,
|
||||
okText: t('确定'),
|
||||
cancelText: t('取消'),
|
||||
onOk: () => onDelete(record.task_id),
|
||||
centered: true,
|
||||
okButtonProps: { type: 'danger' },
|
||||
});
|
||||
}}
|
||||
>
|
||||
{!isCompact ? t('删除') : ''}
|
||||
</Button>
|
||||
</Space>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// 统计信息
|
||||
const taskStats = {
|
||||
total: tasks.length,
|
||||
queued: tasks.filter((t) => normalizeVideoTaskStatus(t.status) === 'queued')
|
||||
.length,
|
||||
in_progress: tasks.filter(
|
||||
(t) => normalizeVideoTaskStatus(t.status) === 'in_progress',
|
||||
).length,
|
||||
completed: tasks.filter((t) => {
|
||||
return normalizeVideoTaskStatus(t.status) === 'success';
|
||||
}).length,
|
||||
failed: tasks.filter((t) => {
|
||||
return normalizeVideoTaskStatus(t.status) === 'failure';
|
||||
}).length,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 折叠触发器 */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: visible ? `${queueHeight}px` : '0',
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: '40px',
|
||||
backgroundColor: 'var(--semi-color-bg-1)',
|
||||
borderTop: '1px solid var(--semi-color-border)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
cursor: 'pointer',
|
||||
transition: 'bottom 0.3s',
|
||||
zIndex: 10,
|
||||
}}
|
||||
onClick={() => setVisible(!visible)}
|
||||
>
|
||||
<Space>
|
||||
{visible ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
|
||||
<span style={{ fontSize: !isCompact ? '14px' : '12px' }}>
|
||||
{t('任务队列')} ({taskStats.total})
|
||||
</span>
|
||||
{taskStats.in_progress > 0 && (
|
||||
<Badge count={taskStats.in_progress} type='danger' />
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{/* 任务队列抽屉 */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: visible ? '0' : `-${queueHeight}px`,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: `${queueHeight}px`,
|
||||
backgroundColor: 'var(--semi-color-bg-0)',
|
||||
borderTop: '1px solid var(--semi-color-border)',
|
||||
transition: 'bottom 0.3s',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
zIndex: 9,
|
||||
}}
|
||||
>
|
||||
{/* 工具栏 */}
|
||||
<div
|
||||
style={{
|
||||
padding: !isCompact ? '12px 16px' : '8px 12px',
|
||||
borderBottom: '1px solid var(--semi-color-border)',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
flexWrap: 'wrap',
|
||||
gap: '8px',
|
||||
}}
|
||||
>
|
||||
<Space wrap>
|
||||
<Button
|
||||
size={!isCompact ? 'default' : 'small'}
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={onRefresh}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
{selectedTasks.length > 0 && (
|
||||
<>
|
||||
<Button
|
||||
size={!isCompact ? 'default' : 'small'}
|
||||
icon={<Download size={14} />}
|
||||
onClick={handleBatchDownload}
|
||||
>
|
||||
{t('批量下载')} ({selectedTasks.length})
|
||||
</Button>
|
||||
<Button
|
||||
size={!isCompact ? 'default' : 'small'}
|
||||
type='danger'
|
||||
icon={<Trash2 size={14} />}
|
||||
onClick={() => {
|
||||
Modal.warning({
|
||||
title: t('确定删除选中的任务?'),
|
||||
content: t('将删除 {{count}} 个任务,删除后将无法恢复', {
|
||||
count: selectedTasks.length,
|
||||
}),
|
||||
icon: (
|
||||
<AlertCircle size={24} style={{ color: '#f59e0b' }} />
|
||||
),
|
||||
okText: t('确定删除'),
|
||||
cancelText: t('取消'),
|
||||
onOk: handleBatchDelete,
|
||||
centered: true,
|
||||
okButtonProps: { type: 'danger' },
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t('批量删除')} ({selectedTasks.length})
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Space>
|
||||
|
||||
{/* 统计信息 */}
|
||||
<Space wrap>
|
||||
<Tag size={!isCompact ? 'default' : 'small'} color='blue'>
|
||||
{t('排队')}: {taskStats.queued}
|
||||
</Tag>
|
||||
<Tag size={!isCompact ? 'default' : 'small'} color='cyan'>
|
||||
{t('生成中')}: {taskStats.in_progress}
|
||||
</Tag>
|
||||
<Tag size={!isCompact ? 'default' : 'small'} color='green'>
|
||||
{t('完成')}: {taskStats.completed}
|
||||
</Tag>
|
||||
<Tag size={!isCompact ? 'default' : 'small'} color='red'>
|
||||
{t('失败')}: {taskStats.failed}
|
||||
</Tag>
|
||||
{/* 分页大小选择器 */}
|
||||
<Select
|
||||
size={!isCompact ? 'default' : 'small'}
|
||||
value={pageSize}
|
||||
onChange={setPageSize}
|
||||
style={{ width: !isCompact ? '120px' : '100px' }}
|
||||
>
|
||||
<Select.Option value={3}>3 {t('条/页')}</Select.Option>
|
||||
<Select.Option value={5}>5 {t('条/页')}</Select.Option>
|
||||
<Select.Option value={10}>10 {t('条/页')}</Select.Option>
|
||||
<Select.Option value={20}>20 {t('条/页')}</Select.Option>
|
||||
<Select.Option value={50}>50 {t('条/页')}</Select.Option>
|
||||
</Select>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
{/* 任务表格 */}
|
||||
<div style={{ flex: 1, overflow: 'auto' }}>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={tasks}
|
||||
rowKey='task_id'
|
||||
scroll={{ x: 'max-content' }}
|
||||
pagination={{
|
||||
pageSize: pageSize,
|
||||
showSizeChanger: false,
|
||||
size: !isCompact ? 'default' : 'small',
|
||||
}}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedTasks,
|
||||
onChange: setSelectedTasks,
|
||||
getCheckboxProps: (record) => ({
|
||||
disabled: record.status === 'in_progress',
|
||||
}),
|
||||
}}
|
||||
size='small'
|
||||
empty={t('暂无任务')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoTaskQueue;
|
||||
@@ -0,0 +1,308 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import VideoInputPanel from './Video/VideoInputPanel';
|
||||
import VideoPreviewPanel from './Video/VideoPreviewPanel';
|
||||
import VideoTaskQueue from './Video/VideoTaskQueue';
|
||||
import VideoRegenerateModal from './Video/VideoRegenerateModal';
|
||||
import { useVideoGeneration } from '../../../../hooks/video/useVideoGeneration';
|
||||
|
||||
const VideoGenerationTab = () => {
|
||||
const [leftPanelCollapsed, setLeftPanelCollapsed] = useState(false);
|
||||
const [taskQueueVisible, setTaskQueueVisible] = useState(false);
|
||||
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
|
||||
const [selectedTaskForPlay, setSelectedTaskForPlay] = useState(null);
|
||||
const [regenerateModalVisible, setRegenerateModalVisible] = useState(false);
|
||||
const [taskToRegenerate, setTaskToRegenerate] = useState(null);
|
||||
|
||||
// 监听窗口大小变化
|
||||
useEffect(() => {
|
||||
const handleResize = () => {
|
||||
setWindowWidth(window.innerWidth);
|
||||
};
|
||||
|
||||
window.addEventListener('resize', handleResize);
|
||||
return () => window.removeEventListener('resize', handleResize);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
// 表单数据
|
||||
formData,
|
||||
setFormData,
|
||||
// 模型相关
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
modelInfo,
|
||||
// 生成相关
|
||||
generating,
|
||||
currentTask,
|
||||
handleGenerate,
|
||||
submitVideo,
|
||||
handleCancel,
|
||||
// 任务列表
|
||||
tasks,
|
||||
refreshTasks,
|
||||
deleteTask,
|
||||
getRegenerationTask,
|
||||
downloadTask,
|
||||
getTaskVideoUrl,
|
||||
} = useVideoGeneration();
|
||||
|
||||
// 处理任务列表的播放按钮
|
||||
const handlePlayTask = async (task) => {
|
||||
// 获取最新的预签名URL
|
||||
const videoUrl = await getTaskVideoUrl(task.task_id);
|
||||
if (videoUrl) {
|
||||
// 更新 task 对象中的 video_url
|
||||
const updatedTask = { ...task };
|
||||
// 解析或初始化 data 对象
|
||||
let data = {};
|
||||
if (updatedTask.data) {
|
||||
try {
|
||||
data =
|
||||
typeof updatedTask.data === 'string'
|
||||
? JSON.parse(updatedTask.data)
|
||||
: { ...updatedTask.data };
|
||||
} catch (e) {
|
||||
console.error('Failed to parse task data:', e);
|
||||
}
|
||||
}
|
||||
// 设置 video_url
|
||||
data.video_url = videoUrl;
|
||||
updatedTask.data = data;
|
||||
setSelectedTaskForPlay(updatedTask);
|
||||
} else {
|
||||
setSelectedTaskForPlay(task);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理关闭视频播放(清除选中的任务)
|
||||
const handleClearSelectedTask = () => {
|
||||
setSelectedTaskForPlay(null);
|
||||
};
|
||||
|
||||
// 处理再生成按钮
|
||||
const handleRegenerate = async (task) => {
|
||||
const detail = await getRegenerationTask(task.task_id);
|
||||
if (!detail) return;
|
||||
setTaskToRegenerate(detail);
|
||||
setRegenerateModalVisible(true);
|
||||
};
|
||||
|
||||
// 确认再生成
|
||||
const handleRegenerateConfirm = async (requestData) => {
|
||||
const submitted = await submitVideo(requestData, requestData.model);
|
||||
if (submitted) {
|
||||
setRegenerateModalVisible(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 响应式布局配置 - 两列布局(左侧配置区 + 右侧预览区)
|
||||
const getLayoutConfig = () => {
|
||||
// 超大屏幕 (>1920px): 25% - 75%
|
||||
if (windowWidth > 1920) {
|
||||
return {
|
||||
leftWidth: '25%',
|
||||
centerWidth: '75%',
|
||||
minLeftWidth: '350px',
|
||||
minCenterWidth: '800px',
|
||||
direction: 'row',
|
||||
};
|
||||
}
|
||||
// 大屏幕 (1600-1920px): 28% - 72%
|
||||
if (windowWidth > 1600) {
|
||||
return {
|
||||
leftWidth: '28%',
|
||||
centerWidth: '72%',
|
||||
minLeftWidth: '320px',
|
||||
minCenterWidth: '700px',
|
||||
direction: 'row',
|
||||
};
|
||||
}
|
||||
// 中等屏幕 (1280-1600px): 32% - 68%
|
||||
if (windowWidth > 1280) {
|
||||
return {
|
||||
leftWidth: '32%',
|
||||
centerWidth: '68%',
|
||||
minLeftWidth: '300px',
|
||||
minCenterWidth: '600px',
|
||||
direction: 'row',
|
||||
};
|
||||
}
|
||||
// 小屏幕 (1024-1280px): 35% - 65%
|
||||
if (windowWidth > 1024) {
|
||||
return {
|
||||
leftWidth: '35%',
|
||||
centerWidth: '65%',
|
||||
minLeftWidth: '280px',
|
||||
minCenterWidth: '500px',
|
||||
direction: 'row',
|
||||
};
|
||||
}
|
||||
// 超小屏幕 (<1024px): 单列布局
|
||||
return {
|
||||
leftWidth: '100%',
|
||||
centerWidth: '100%',
|
||||
minLeftWidth: '100%',
|
||||
minCenterWidth: '100%',
|
||||
direction: 'column',
|
||||
};
|
||||
};
|
||||
|
||||
const layoutConfig = getLayoutConfig();
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
position: 'relative',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
overflow: layoutConfig.direction === 'row' ? 'hidden' : 'auto',
|
||||
display: 'flex',
|
||||
flexDirection: layoutConfig.direction === 'row' ? 'row' : 'column',
|
||||
gap: layoutConfig.direction === 'column' ? '16px' : '0',
|
||||
position: 'relative',
|
||||
paddingBottom: '40px', // 为任务队列触发器留出空间
|
||||
}}
|
||||
>
|
||||
{/* 左侧:输入区域(区域1) */}
|
||||
<div
|
||||
style={{
|
||||
width:
|
||||
layoutConfig.direction === 'row'
|
||||
? layoutConfig.leftWidth
|
||||
: '100%',
|
||||
minWidth: layoutConfig.minLeftWidth,
|
||||
height: layoutConfig.direction === 'row' ? '100%' : 'auto',
|
||||
// 折叠态不能再预留 500px:面板收起后只剩一个 fixed 定位的浮动箭头,
|
||||
// 这 500px 会变成页面顶部一整块空白
|
||||
minHeight:
|
||||
layoutConfig.direction === 'column' && !leftPanelCollapsed
|
||||
? '500px'
|
||||
: 'auto',
|
||||
flexShrink: layoutConfig.direction === 'row' ? 0 : 1,
|
||||
backgroundColor: 'var(--semi-color-bg-1)',
|
||||
borderRight:
|
||||
layoutConfig.direction === 'row'
|
||||
? '1px solid var(--semi-color-border)'
|
||||
: 'none',
|
||||
borderBottom:
|
||||
layoutConfig.direction === 'column'
|
||||
? '1px solid var(--semi-color-border)'
|
||||
: 'none',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className='app-scrollbar'
|
||||
style={{
|
||||
height: '100%',
|
||||
overflow: 'auto',
|
||||
paddingBottom: layoutConfig.direction === 'row' ? '16px' : '16px',
|
||||
}}
|
||||
>
|
||||
<VideoInputPanel
|
||||
formData={formData}
|
||||
setFormData={setFormData}
|
||||
onCollapse={() => setLeftPanelCollapsed(!leftPanelCollapsed)}
|
||||
collapsed={leftPanelCollapsed}
|
||||
collapsible={layoutConfig.direction === 'row'}
|
||||
selectedModel={selectedModel}
|
||||
setSelectedModel={setSelectedModel}
|
||||
modelInfo={modelInfo}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧:预览+生成区域 */}
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
height: layoutConfig.direction === 'row' ? '100%' : 'auto',
|
||||
minHeight: layoutConfig.direction === 'column' ? '600px' : 'auto',
|
||||
minWidth: 0,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className='app-scrollbar'
|
||||
style={{
|
||||
height: '100%',
|
||||
backgroundColor: 'var(--semi-color-bg-0)',
|
||||
padding: windowWidth > 768 ? '16px' : '12px',
|
||||
overflow: 'auto',
|
||||
}}
|
||||
>
|
||||
<VideoPreviewPanel
|
||||
formData={formData}
|
||||
generating={generating}
|
||||
currentTask={currentTask}
|
||||
onGenerate={handleGenerate}
|
||||
onCancel={handleCancel}
|
||||
selectedModel={selectedModel}
|
||||
selectedTaskForPlay={selectedTaskForPlay}
|
||||
onRegenerate={handleRegenerate}
|
||||
onClearSelectedTask={handleClearSelectedTask}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部:任务队列(区域4) - 使用 absolute 定位,相对于父容器 */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
zIndex: 1000,
|
||||
}}
|
||||
>
|
||||
<VideoTaskQueue
|
||||
visible={taskQueueVisible}
|
||||
setVisible={setTaskQueueVisible}
|
||||
tasks={tasks}
|
||||
onRefresh={refreshTasks}
|
||||
onDelete={deleteTask}
|
||||
onDownload={downloadTask}
|
||||
onPlay={handlePlayTask}
|
||||
onRegenerate={handleRegenerate}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 再生成弹窗 */}
|
||||
<VideoRegenerateModal
|
||||
visible={regenerateModalVisible}
|
||||
onCancel={() => setRegenerateModalVisible(false)}
|
||||
onConfirm={handleRegenerateConfirm}
|
||||
task={taskToRegenerate}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoGenerationTab;
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Card, Empty } from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { IllustrationConstruction } from '../../../../components/common/illustrations';
|
||||
|
||||
const VideoRemixTab = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Empty
|
||||
image={<IllustrationConstruction style={{ width: 150, height: 150 }} />}
|
||||
title={t('视频 Remix')}
|
||||
description={t('此功能正在开发中,敬请期待')}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoRemixTab;
|
||||
@@ -0,0 +1,246 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useMemo, useState, useEffect } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
BrainCircuit,
|
||||
Image,
|
||||
Video,
|
||||
Sparkles,
|
||||
} from 'lucide-react';
|
||||
import { useSidebarCollapsed } from '../../../hooks/common/useSidebarCollapsed';
|
||||
import { useExperienceModules } from '../useExperienceModules';
|
||||
|
||||
const ExperienceSidebar = () => {
|
||||
const { t } = useTranslation();
|
||||
const [collapsed, toggleCollapsed] = useSidebarCollapsed();
|
||||
const [selectedKeys, setSelectedKeys] = useState([]);
|
||||
const location = useLocation();
|
||||
const { isAvailable } = useExperienceModules();
|
||||
|
||||
// 统一单一品牌色高亮(云平台风格),不再每项一种颜色
|
||||
const allNavItems = useMemo(
|
||||
() => [
|
||||
{
|
||||
text: t('云端大脑'),
|
||||
itemKey: 'cloud-brain',
|
||||
configKey: 'cloudBrain',
|
||||
to: '/experience-center/cloud-brain',
|
||||
icon: BrainCircuit,
|
||||
beta: true,
|
||||
},
|
||||
{
|
||||
text: t('图片生成'),
|
||||
itemKey: 'image-generation',
|
||||
configKey: 'imageGeneration',
|
||||
to: '/experience-center/image-generation',
|
||||
icon: Image,
|
||||
},
|
||||
{
|
||||
text: t('视频生成'),
|
||||
itemKey: 'video-generation',
|
||||
configKey: 'videoGeneration',
|
||||
to: '/experience-center/video-generation',
|
||||
icon: Video,
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
// 根据配置过滤导航项(与默认落地页共用 useExperienceModules 判定)
|
||||
const navItems = useMemo(
|
||||
() => allNavItems.filter((item) => isAvailable(item.configKey)),
|
||||
[allNavItems, isAvailable],
|
||||
);
|
||||
|
||||
// 根据当前路径设置选中的菜单项
|
||||
useEffect(() => {
|
||||
const currentPath = location.pathname;
|
||||
const matchingItem = navItems.find((item) =>
|
||||
currentPath.startsWith(item.to),
|
||||
);
|
||||
|
||||
if (matchingItem) {
|
||||
setSelectedKeys([matchingItem.itemKey]);
|
||||
}
|
||||
}, [location.pathname, navItems]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
relative flex flex-col h-full transition-all duration-300 ease-out
|
||||
bg-white/60 dark:bg-neutral-900/60 backdrop-blur-2xl backdrop-saturate-[1.8]
|
||||
border-r border-white/40 dark:border-neutral-700/50
|
||||
shadow-[1px_0_24px_-4px_rgba(0,0,0,0.06)] dark:shadow-[1px_0_24px_-4px_rgba(0,0,0,0.3)]
|
||||
${collapsed ? 'w-[68px]' : 'w-[240px]'}
|
||||
`}
|
||||
>
|
||||
{/* 毛玻璃内层光泽 */}
|
||||
<div className='absolute inset-0 bg-gradient-to-b from-white/40 via-white/10 to-white/20 dark:from-white/[0.06] dark:via-transparent dark:to-white/[0.03] pointer-events-none' />
|
||||
{/* 顶部装饰渐变 —— /8 /3 步进 Tailwind 不生成,改用 /10 两 stop 确保可见 */}
|
||||
<div className='absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-brand-from/10 to-transparent pointer-events-none' />
|
||||
|
||||
{/* Logo/标题区域 */}
|
||||
{!collapsed && (
|
||||
<div className='px-4 pt-5 pb-3'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='p-1.5 bg-gradient-to-br from-brand-from to-brand-to rounded-lg'>
|
||||
<Sparkles size={16} className='text-white' />
|
||||
</div>
|
||||
<span className='font-bold text-gray-900 dark:text-white'>
|
||||
{t('体验中心')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 导航区域 */}
|
||||
<nav
|
||||
className={`relative flex-1 px-3 ${collapsed ? 'pt-4' : 'pt-2'} space-y-1.5 overflow-y-auto overflow-x-hidden`}
|
||||
>
|
||||
{navItems.map((item) => {
|
||||
const isSelected = selectedKeys.includes(item.itemKey);
|
||||
const IconComponent = item.icon;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.itemKey}
|
||||
to={item.to}
|
||||
onClick={() => setSelectedKeys([item.itemKey])}
|
||||
className={`
|
||||
group relative flex items-center gap-3 rounded-xl transition-all duration-200
|
||||
${collapsed ? 'justify-center p-3' : 'px-3 py-2.5'}
|
||||
${
|
||||
isSelected
|
||||
? 'bg-brand/10 dark:bg-brand/15 shadow-sm shadow-brand/5'
|
||||
: 'hover:bg-brand/5 dark:hover:bg-brand/10'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{/* 选中指示器 —— 统一品牌色 */}
|
||||
{isSelected && (
|
||||
<div className='absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 rounded-r-full bg-gradient-to-b from-brand-from to-brand-to' />
|
||||
)}
|
||||
|
||||
{/* 图标 —— 激活:品牌渐变实底;非激活:中性,hover 转品牌 */}
|
||||
<div
|
||||
className={`
|
||||
relative flex-shrink-0 p-1.5 rounded-lg transition-all duration-200
|
||||
${
|
||||
isSelected
|
||||
? 'bg-gradient-to-br from-brand-from to-brand-to shadow-lg shadow-brand/25'
|
||||
: 'bg-gray-100/80 dark:bg-neutral-800/80 group-hover:bg-brand/10 group-hover:scale-105'
|
||||
}
|
||||
`}
|
||||
>
|
||||
<IconComponent
|
||||
size={18}
|
||||
strokeWidth={2}
|
||||
className={
|
||||
isSelected
|
||||
? 'text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 group-hover:text-brand-deep dark:group-hover:text-brand-from transition-colors'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 文字 */}
|
||||
{!collapsed && (
|
||||
<span className='flex min-w-0 items-center gap-2'>
|
||||
<span
|
||||
className={`
|
||||
text-sm transition-colors truncate
|
||||
${
|
||||
isSelected
|
||||
? 'text-brand-deep dark:text-brand-from font-semibold'
|
||||
: 'font-medium text-gray-600 dark:text-gray-300 group-hover:text-brand-deep dark:group-hover:text-brand-from'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{item.text}
|
||||
</span>
|
||||
{item.beta && (
|
||||
<span className='shrink-0 rounded-full border border-orange-300/70 bg-orange-50 px-1.5 py-0.5 font-mono text-[8px] font-bold tracking-wider text-orange-700'>
|
||||
BETA
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{/* Tooltip for collapsed state */}
|
||||
{collapsed && (
|
||||
<div
|
||||
className='
|
||||
absolute left-full ml-2 px-2.5 py-1.5
|
||||
bg-gray-900 dark:bg-white text-white dark:text-gray-900
|
||||
text-xs font-medium rounded-lg shadow-lg
|
||||
opacity-0 invisible group-hover:opacity-100 group-hover:visible
|
||||
transition-all duration-200 whitespace-nowrap z-50
|
||||
'
|
||||
>
|
||||
{item.text}
|
||||
<div
|
||||
className='absolute left-0 top-1/2 -translate-x-1 -translate-y-1/2
|
||||
border-4 border-transparent border-r-gray-900 dark:border-r-white'
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* 底部分隔线装饰 */}
|
||||
<div className='mx-4 h-px bg-gradient-to-r from-transparent via-gray-200/60 dark:via-neutral-700/60 to-transparent' />
|
||||
|
||||
{/* 底部折叠按钮 */}
|
||||
<div className='relative p-3'>
|
||||
<button
|
||||
onClick={toggleCollapsed}
|
||||
className={`
|
||||
flex items-center justify-center gap-2 w-full py-2 rounded-lg
|
||||
text-gray-500 dark:text-gray-400 text-sm font-medium
|
||||
bg-white/50 dark:bg-neutral-800/50
|
||||
border border-gray-200/40 dark:border-neutral-700/40
|
||||
hover:bg-brand/10 dark:hover:bg-brand/15
|
||||
hover:text-brand-deep dark:hover:text-brand-from
|
||||
hover:border-brand/30
|
||||
transition-all duration-200
|
||||
${collapsed ? 'px-2' : 'px-3'}
|
||||
`}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRight size={16} strokeWidth={2.5} />
|
||||
) : (
|
||||
<>
|
||||
<ChevronLeft size={16} strokeWidth={2.5} />
|
||||
<span>{t('收起')}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExperienceSidebar;
|
||||
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import ImageGenerationTab from './AICreation/ImageGenerationTab';
|
||||
|
||||
const ImageGeneration = () => {
|
||||
return (
|
||||
<div className='h-full min-h-0'>
|
||||
<ImageGenerationTab />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ImageGeneration;
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import Token from '../../Token';
|
||||
|
||||
const KeyManagement = () => {
|
||||
return <Token />;
|
||||
};
|
||||
|
||||
export default KeyManagement;
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import Playground from '../../Playground';
|
||||
|
||||
const TextModel = () => {
|
||||
return (
|
||||
<div className='experience-text-model h-full relative overflow-hidden'>
|
||||
{/* 动态背景层 */}
|
||||
<div className='absolute inset-0 pointer-events-none'>
|
||||
{/* 渐变背景 —— 角落晕染走 bg-glow-to。
|
||||
* 透明度刻意高于 UserCenter (/20) —— 本页 ChatArea 有 bg-white/60 毛玻璃
|
||||
* 容器几乎全屏遮罩,再叠底部 from-white/30 装饰条,右下角实际可见 alpha
|
||||
* 会被双层 overlay 削到 ~7% 几乎不可见。/50 light 下穿透两层后 ~14% 才有
|
||||
* 与其他页面同水平的视觉强度。结构特例,不强行与 UserCenter 对齐刻度。 */}
|
||||
<div className='absolute inset-0 bg-gradient-to-b from-slate-50 via-white to-bg-glow-to/50 dark:from-[#0a0a0f] dark:via-[#0f0f18] dark:to-bg-glow-to/20' />
|
||||
|
||||
{/* 动态光球 —— 三个 blob 走 bg-glow-from / to 两 stop */}
|
||||
<div className='absolute top-[5%] right-[10%] w-[400px] h-[400px] rounded-full bg-gradient-to-br from-bg-glow-from/15 to-bg-glow-to/15 dark:from-bg-glow-from/10 dark:to-bg-glow-to/10 blur-[100px] animate-pulse' />
|
||||
<div
|
||||
className='absolute bottom-[10%] left-[5%] w-[350px] h-[350px] rounded-full bg-gradient-to-br from-bg-glow-from/15 to-bg-glow-to/15 dark:from-bg-glow-from/10 dark:to-bg-glow-to/10 blur-[100px] animate-pulse'
|
||||
style={{ animationDelay: '1.5s' }}
|
||||
/>
|
||||
<div
|
||||
className='absolute top-[40%] left-[30%] w-[250px] h-[250px] rounded-full bg-gradient-to-br from-bg-glow-from/10 to-bg-glow-to/10 dark:from-bg-glow-from/5 dark:to-bg-glow-to/5 blur-[80px] animate-pulse'
|
||||
style={{ animationDelay: '3s' }}
|
||||
/>
|
||||
|
||||
{/* 装饰性网格 —— 与全页背景统一走 bg-glow-* CSS 变量 */}
|
||||
<div
|
||||
className='absolute inset-0 opacity-[0.02] dark:opacity-[0.04]'
|
||||
style={{
|
||||
backgroundImage: `
|
||||
radial-gradient(circle at 25% 25%, color-mix(in srgb, var(--bg-glow-from) 30%, transparent) 0%, transparent 50%),
|
||||
radial-gradient(circle at 75% 75%, color-mix(in srgb, var(--bg-glow-to) 30%, transparent) 0%, transparent 50%)
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 顶部装饰线 */}
|
||||
<div className='absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-brand-via/30 to-transparent' />
|
||||
</div>
|
||||
|
||||
{/* 内容区域 */}
|
||||
<div className='relative z-10 h-full pb-2'>
|
||||
<Playground isExperienceMode={true} />
|
||||
</div>
|
||||
|
||||
{/* 底部装饰 - z-index 低于内容区域,避免遮挡输入框 */}
|
||||
<div className='absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-white/30 dark:from-neutral-950/30 to-transparent pointer-events-none z-[5]' />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TextModel;
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Video, Sparkles, Clapperboard, Film, Play } from 'lucide-react';
|
||||
import VideoGenerationTab from './AICreation/VideoGenerationTab';
|
||||
|
||||
const VideoGeneration = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className='h-full flex flex-col p-6 relative overflow-hidden'>
|
||||
{/* 背景由父级 ExperienceCenter 的 PageBackground(rich) 统一提供,此处不再渲染 */}
|
||||
|
||||
{/* Header */}
|
||||
<div className='relative z-10 flex-shrink-0 mb-6'>
|
||||
<div className='flex items-center gap-4'>
|
||||
{/* 图标容器 */}
|
||||
<div className='relative'>
|
||||
<div className='absolute -inset-2 bg-gradient-to-r from-cyan-500/30 to-blue-500/30 rounded-2xl blur-lg opacity-60' />
|
||||
<div className='relative p-3 bg-gradient-to-br from-cyan-500 via-blue-500 to-brand-to rounded-2xl shadow-xl shadow-cyan-500/30'>
|
||||
<Video size={26} className='text-white' />
|
||||
</div>
|
||||
<Sparkles
|
||||
size={16}
|
||||
className='absolute -top-1 -right-1 text-amber-400 animate-pulse'
|
||||
/>
|
||||
|
||||
{/* 播放动画指示器 */}
|
||||
<div className='absolute -bottom-1 -left-1 w-5 h-5 rounded-full bg-green-500 flex items-center justify-center shadow-lg shadow-green-500/50'>
|
||||
<Play size={10} className='text-white ml-0.5' fill='white' />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 标题文字 */}
|
||||
<div>
|
||||
<h1 className='text-2xl md:text-3xl font-bold flex items-center gap-2'>
|
||||
<span className='bg-clip-text text-transparent bg-gradient-to-r from-cyan-600 via-blue-600 to-brand-to dark:from-cyan-400 dark:via-blue-400 dark:to-brand-to'>
|
||||
{t('视频生成')}
|
||||
</span>
|
||||
</h1>
|
||||
<p className='text-sm text-gray-500 dark:text-gray-400 mt-1'>
|
||||
{t('使用 AI 创建令人惊叹的视频内容')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 右侧装饰标签 */}
|
||||
<div className='hidden md:flex items-center gap-2 ml-auto'>
|
||||
<div className='flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gradient-to-r from-cyan-50 to-teal-50 dark:from-cyan-950/30 dark:to-teal-950/30 border border-cyan-200/50 dark:border-cyan-800/30'>
|
||||
<Clapperboard size={14} className='text-cyan-500' />
|
||||
<span className='text-xs font-medium text-cyan-600 dark:text-cyan-400'>
|
||||
{t('图生视频')}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gradient-to-r from-blue-50 to-brand-to/5 dark:from-blue-950/30 dark:to-brand-to/30 border border-blue-200/50 dark:border-blue-800/30'>
|
||||
<Film size={14} className='text-blue-500' />
|
||||
<span className='text-xs font-medium text-blue-600 dark:text-blue-400'>
|
||||
{t('文生视频')}
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-gradient-to-r from-brand-from/5 to-brand-to/5 dark:from-brand-from/30 dark:to-brand-to/30 border border-brand/50 dark:border-brand-deep/30'>
|
||||
<Sparkles size={14} className='text-brand' />
|
||||
<span className='text-xs font-medium text-brand-deep dark:text-brand-from'>
|
||||
{t('多模型支持')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className='relative z-10 flex-1 min-h-0'>
|
||||
{/* 卡片装饰边框 */}
|
||||
<div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-500/20 via-blue-500/20 to-brand-to/20 rounded-[20px] blur-sm opacity-60' />
|
||||
|
||||
{/* 内容卡片 */}
|
||||
<div className='relative h-full bg-white/70 dark:bg-neutral-900/70 backdrop-blur-xl rounded-2xl border border-white/50 dark:border-neutral-800/50 shadow-xl shadow-cyan-500/5 overflow-hidden'>
|
||||
{/* 顶部装饰线 */}
|
||||
<div className='absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-cyan-500/50 to-transparent' />
|
||||
|
||||
{/* 左侧装饰线 */}
|
||||
<div className='absolute top-0 bottom-0 left-0 w-[2px] bg-gradient-to-b from-transparent via-blue-500/30 to-transparent' />
|
||||
|
||||
<VideoGenerationTab />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default VideoGeneration;
|
||||
@@ -0,0 +1,219 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useContext } from 'react';
|
||||
import { Navigate, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { BrainCircuit, Image, Video } from 'lucide-react';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import PageBackground from '../../components/common/PageBackground';
|
||||
import TextModel from './components/TextModel';
|
||||
import ImageGeneration from './components/ImageGeneration';
|
||||
import VideoGeneration from './components/VideoGeneration';
|
||||
import KeyManagement from './components/KeyManagement';
|
||||
import ExperienceSidebar from './components/ExperienceSidebar';
|
||||
import CloudBrain from '../CloudBrain';
|
||||
import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi';
|
||||
import Loading from '../../components/common/ui/Loading';
|
||||
import { DEFAULT_LOGIN_REDIRECT } from '../../helpers/data';
|
||||
import {
|
||||
EXPERIENCE_MODULES,
|
||||
useExperienceModules,
|
||||
} from './useExperienceModules';
|
||||
|
||||
// 移动端底部导航组件
|
||||
const MobileBottomNav = ({ currentPath, navigate, isAvailable }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 与桌面侧边栏共用 useExperienceModules 判定,运营关闭的子页两端一致隐藏
|
||||
const navItems = [
|
||||
{
|
||||
key: 'cloud-brain',
|
||||
configKey: 'cloudBrain',
|
||||
icon: BrainCircuit,
|
||||
label: t('云端大脑'),
|
||||
path: '/experience-center/cloud-brain',
|
||||
gradient: 'from-emerald-600 to-orange-500',
|
||||
beta: true,
|
||||
},
|
||||
{
|
||||
key: 'image',
|
||||
configKey: 'imageGeneration',
|
||||
icon: Image,
|
||||
label: t('图片'),
|
||||
path: '/experience-center/image-generation',
|
||||
gradient: 'from-pink-500 to-rose-600',
|
||||
},
|
||||
{
|
||||
key: 'video',
|
||||
configKey: 'videoGeneration',
|
||||
icon: Video,
|
||||
label: t('视频'),
|
||||
path: '/experience-center/video-generation',
|
||||
gradient: 'from-cyan-500 to-blue-600',
|
||||
},
|
||||
].filter((item) => isAvailable(item.configKey));
|
||||
|
||||
return (
|
||||
<div className='md:hidden fixed bottom-0 left-0 right-0 z-50 bg-white/90 dark:bg-neutral-900/90 backdrop-blur-xl border-t border-gray-200/80 dark:border-neutral-800/80 safe-area-inset-bottom'>
|
||||
<div className='flex items-center justify-around h-14'>
|
||||
{navItems.map((item) => {
|
||||
const isActive = currentPath.includes(item.key);
|
||||
const IconComponent = item.icon;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={item.key}
|
||||
onClick={() => navigate(item.path)}
|
||||
className={`relative flex flex-col items-center justify-center flex-1 h-full transition-all ${
|
||||
isActive ? 'scale-105' : 'opacity-60'
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`p-1.5 rounded-lg ${isActive ? `bg-gradient-to-br ${item.gradient}` : ''}`}
|
||||
>
|
||||
<IconComponent
|
||||
size={20}
|
||||
className={
|
||||
isActive ? 'text-white' : 'text-gray-500 dark:text-gray-400'
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className={`text-[10px] mt-0.5 font-medium ${
|
||||
isActive
|
||||
? 'text-gray-900 dark:text-white'
|
||||
: 'text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{item.label}
|
||||
</span>
|
||||
{item.beta && (
|
||||
<span className='absolute top-0.5 right-[18%] rounded-full bg-orange-500 px-1 font-mono text-[7px] font-bold tracking-wide text-white'>
|
||||
BETA
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const ExperienceCenter = () => {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const { ready, orgOnly, isAvailable, defaultPath } = useExperienceModules();
|
||||
|
||||
// 跑马灯公告是否存在(用于动态计算顶部间距)
|
||||
const hasMarquee = !!statusState?.status?.marquee_content?.trim();
|
||||
|
||||
// 默认落地:进第一个对当前用户可用的子页;一个都没有时,org_only 用户回企业
|
||||
// 空间,其余用户去默认登录落地页。兜底目标都不在体验中心内,不会重定向循环。
|
||||
const fallbackPath =
|
||||
defaultPath || (orgOnly ? '/org' : DEFAULT_LOGIN_REDIRECT);
|
||||
const isEntryPath = [
|
||||
'/experience-center',
|
||||
'/experience-center/',
|
||||
// 兼容旧路由
|
||||
'/experience-center/ai-creation',
|
||||
].includes(location.pathname);
|
||||
if (isEntryPath) {
|
||||
// 配置/登录态就绪前不判定:默认配置全开,抢跑会落到随后才知道已关闭的页
|
||||
return ready ? <Navigate to={fallbackPath} replace /> : <Loading />;
|
||||
}
|
||||
|
||||
// 运营关闭(或分组不可见、org_only 被后端拦截)的子页,直达链接也转去可用页,
|
||||
// 避免停在菜单里看不到、接口又全报错的页面。大模型体验不在 EXPERIENCE_MODULES
|
||||
// 中,旧链接仍可直达。
|
||||
const currentModule = EXPERIENCE_MODULES.find((m) =>
|
||||
location.pathname.startsWith(m.path),
|
||||
);
|
||||
if (ready && currentModule && !isAvailable(currentModule.configKey)) {
|
||||
return <Navigate to={fallbackPath} replace />;
|
||||
}
|
||||
|
||||
const isTextModel = location.pathname.includes('text-model');
|
||||
const isCloudBrain = location.pathname.includes('cloud-brain');
|
||||
const isVideoGeneration = location.pathname.includes('video-generation');
|
||||
const isImageGeneration = location.pathname.includes('image-generation');
|
||||
// 这些页面内部有自己的滚动容器,不需要外层的 overflow-y-auto
|
||||
const noPadding =
|
||||
isTextModel || isCloudBrain || isVideoGeneration || isImageGeneration;
|
||||
|
||||
if (!CLOUD_BRAIN_UI_ENABLED && isCloudBrain) {
|
||||
return <Navigate to='/experience-center' replace />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex flex-col md:flex-row h-screen bg-[var(--surface-bg-base)] transition-colors duration-300 overflow-hidden ${hasMarquee ? 'pt-[96px] sm:pt-[104px]' : 'pt-14 sm:pt-16'}`}
|
||||
>
|
||||
{/* Sidebar - 桌面端 */}
|
||||
<div className='hidden md:block'>
|
||||
<ExperienceSidebar />
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<main
|
||||
className={`
|
||||
flex-1 overflow-hidden relative pb-16 md:pb-2
|
||||
${noPadding ? '' : 'p-4 sm:p-6'}
|
||||
`}
|
||||
>
|
||||
{/* 统一页面背景层 —— 除 text-model 外,ExperienceCenter 是其子页面的唯一背景来源,
|
||||
* 子组件不再各自渲染背景,避免双层叠加。
|
||||
* text-model 特例:TextModel 自带 via-white 亮底保证聊天可读性,由其自身渲染,此处跳过。
|
||||
* 沉浸式生成页(视频/图片)用 rich 大光球,秘钥管理(Token 列表)用 subtle。 */}
|
||||
{!isTextModel && (
|
||||
<PageBackground
|
||||
variant={isVideoGeneration || isImageGeneration ? 'rich' : 'subtle'}
|
||||
animate
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 内容区域 */}
|
||||
<div
|
||||
className={`relative z-10 h-full ${noPadding ? '' : 'overflow-y-auto'}`}
|
||||
>
|
||||
{location.pathname.includes('image-generation') && (
|
||||
<ImageGeneration />
|
||||
)}
|
||||
{location.pathname.includes('video-generation') && (
|
||||
<VideoGeneration />
|
||||
)}
|
||||
{location.pathname.includes('text-model') && <TextModel />}
|
||||
{CLOUD_BRAIN_UI_ENABLED && isCloudBrain && <CloudBrain />}
|
||||
{location.pathname.includes('key-management') && <KeyManagement />}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
{/* 移动端底部导航栏 */}
|
||||
<MobileBottomNav
|
||||
currentPath={location.pathname}
|
||||
navigate={navigate}
|
||||
isAvailable={isAvailable}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExperienceCenter;
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import { useCallback, useContext, useMemo } from 'react';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { UserContext } from '../../context/User';
|
||||
import { isGroupAllowed } from '../../helpers/navigationVisibility';
|
||||
import { CLOUD_BRAIN_UI_ENABLED } from '../../config/cloudBrainUi';
|
||||
|
||||
// 体验中心子页,顺序即默认落地优先级(/experience-center 进第一个可用项)。
|
||||
// 大模型体验(text-model)已从入口隐藏,路由保留供旧链接访问,不参与默认落地。
|
||||
// 云端大脑为 Beta,排在最后,仅在图片/视频都不可用时兜底。
|
||||
export const EXPERIENCE_MODULES = [
|
||||
{
|
||||
configKey: 'imageGeneration',
|
||||
path: '/experience-center/image-generation',
|
||||
},
|
||||
{
|
||||
configKey: 'videoGeneration',
|
||||
path: '/experience-center/video-generation',
|
||||
},
|
||||
{
|
||||
configKey: 'cloudBrain',
|
||||
path: '/experience-center/cloud-brain',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 体验中心子页可用性:侧边栏、移动端底栏与默认落地页共用同一套判定,
|
||||
* 避免「默认进了一个菜单里看不到的页」。
|
||||
*
|
||||
* - 运营在「侧边栏模块管理」关闭的子页、或限定分组不含当前用户的子页不可用;
|
||||
* - org_only(仅企业资源)用户一律不可用:图片/视频/云端大脑接口均挂了
|
||||
* BlockOrgOnlyMode,进去只会得到「仅允许使用企业资源」的报错。
|
||||
*
|
||||
* ready 为 false 时(站点配置或登录态尚未就绪)调用方不应做重定向判定——
|
||||
* 默认配置是全部开启,抢跑会把用户送进随后才知道已关闭的页,且 replace 不可逆。
|
||||
*/
|
||||
export const useExperienceModules = () => {
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const [userState] = useContext(UserContext);
|
||||
const userGroup = userState?.user?.group || 'default';
|
||||
const orgOnly = userState?.user?.org_only_mode === true;
|
||||
const ready = !!statusState?.status && !!userState?.authChecked;
|
||||
|
||||
const config = useMemo(() => {
|
||||
const defaultConfig = {
|
||||
enabled: true,
|
||||
groups: [],
|
||||
moduleGroups: {},
|
||||
cloudBrain: CLOUD_BRAIN_UI_ENABLED,
|
||||
imageGeneration: true,
|
||||
videoGeneration: true,
|
||||
};
|
||||
|
||||
try {
|
||||
const configStr = statusState?.status?.SidebarModulesAdmin;
|
||||
if (configStr) {
|
||||
const parsed = JSON.parse(configStr);
|
||||
const merged = { ...defaultConfig, ...parsed.experienceCenter };
|
||||
return {
|
||||
...merged,
|
||||
enabled:
|
||||
merged.enabled !== false &&
|
||||
isGroupAllowed(merged.groups, userGroup),
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
// 使用默认配置
|
||||
}
|
||||
return defaultConfig;
|
||||
}, [statusState?.status?.SidebarModulesAdmin, userGroup]);
|
||||
|
||||
const isAvailable = useCallback(
|
||||
(configKey) =>
|
||||
!orgOnly &&
|
||||
config.enabled &&
|
||||
(configKey !== 'cloudBrain' || CLOUD_BRAIN_UI_ENABLED) &&
|
||||
config[configKey] !== false &&
|
||||
isGroupAllowed(config.moduleGroups?.[configKey], userGroup),
|
||||
[orgOnly, config, userGroup],
|
||||
);
|
||||
|
||||
const defaultPath = useMemo(
|
||||
() => EXPERIENCE_MODULES.find((m) => isAvailable(m.configKey))?.path,
|
||||
[isAvailable],
|
||||
);
|
||||
|
||||
return { ready, orgOnly, isAvailable, defaultPath };
|
||||
};
|
||||
@@ -0,0 +1,542 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Card,
|
||||
Spin,
|
||||
Select,
|
||||
Button,
|
||||
Tag,
|
||||
Table,
|
||||
Empty,
|
||||
Toast,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { IconRefresh } from '@douyinfe/semi-icons';
|
||||
import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
|
||||
import { VChart } from '@visactor/react-vchart';
|
||||
import {
|
||||
Upload,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
AlertTriangle,
|
||||
Users,
|
||||
Download,
|
||||
} from 'lucide-react';
|
||||
import { API, showError } from '../../helpers';
|
||||
import { exportToCsv, formatTimestampForCsv } from '../../helpers/exportCsv';
|
||||
|
||||
// 时间范围选项(小时):与 admin 后台后端 uploadAuditMaxRangeHours=720 保持一致
|
||||
const RANGE_OPTIONS_BUILDER = (t) => [
|
||||
{ label: t('最近 1 小时'), value: 1 },
|
||||
{ label: t('最近 24 小时'), value: 24 },
|
||||
{ label: t('最近 7 天'), value: 24 * 7 },
|
||||
{ label: t('最近 30 天'), value: 24 * 30 },
|
||||
];
|
||||
|
||||
// event 大类筛选下拉
|
||||
const EVENT_FILTER_BUILDER = (t) => [
|
||||
{ label: t('全部事件'), value: '' },
|
||||
{ label: t('成功'), value: 'success' },
|
||||
{ label: t('失败(全部)'), value: 'failed' },
|
||||
{ label: t('警告'), value: 'warning' },
|
||||
// 高频精细原因,便于快速定位
|
||||
{ label: t('体积超限'), value: 'rejected_size' },
|
||||
{ label: t('格式不支持'), value: 'rejected_unsupported_format' },
|
||||
{ label: t('策略禁止'), value: 'rejected_by_policy' },
|
||||
{ label: t('COS 上传失败'), value: 'rejected_cos_upload_failed' },
|
||||
{ label: t('文件内容伪装'), value: 'rejected_corrupt_image' },
|
||||
{ label: t('对话期 URL 失效'), value: 'inline_failed' },
|
||||
];
|
||||
|
||||
// event → 中文短描述(i18n key 同名)
|
||||
const EVENT_LABEL = (t, evt) => {
|
||||
if (!evt) return '';
|
||||
const map = {
|
||||
success: t('成功'),
|
||||
rejected_disabled: t('功能未启用'),
|
||||
rejected_cos_unavailable: t('存储未就绪'),
|
||||
rejected_missing_file: t('未提供文件'),
|
||||
rejected_size: t('体积超限'),
|
||||
rejected_unsupported_format: t('格式不支持'),
|
||||
rejected_by_policy: t('策略禁止'),
|
||||
rejected_read_failed: t('读取失败'),
|
||||
rejected_corrupt_image: t('文件内容伪装'),
|
||||
rejected_cos_upload_failed: t('COS 上传失败'),
|
||||
warn_presign_failed: t('预签名失败'),
|
||||
rejected_foreign_url: t('非法 URL'),
|
||||
inline_failed: t('对话期 URL 失效'),
|
||||
};
|
||||
return map[evt] || evt;
|
||||
};
|
||||
|
||||
const eventColor = (evt) => {
|
||||
if (evt === 'success') return 'green';
|
||||
if (evt.startsWith('warn_')) return 'orange';
|
||||
if (evt === 'inline_failed') return 'red';
|
||||
if (evt.startsWith('rejected_')) return 'red';
|
||||
return 'grey';
|
||||
};
|
||||
|
||||
const StatCard = ({ icon, label, value, accent }) => (
|
||||
<Card className='!rounded-2xl !shadow-sm hover:!shadow-md transition-shadow border border-gray-100 dark:border-gray-700'>
|
||||
<div className='flex items-center gap-3 p-1'>
|
||||
<div
|
||||
className={`w-12 h-12 rounded-xl flex items-center justify-center ${accent}`}
|
||||
>
|
||||
{icon}
|
||||
</div>
|
||||
<div className='flex flex-col min-w-0'>
|
||||
<span className='text-xs text-gray-500 dark:text-gray-400 uppercase tracking-wide'>
|
||||
{label}
|
||||
</span>
|
||||
<span className='text-2xl font-semibold text-gray-800 dark:text-gray-100 tabular-nums'>
|
||||
{(value || 0).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
|
||||
export const ExperienceCenterAuditPanel = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
useEffect(() => {
|
||||
initVChartSemiTheme({ isWatchingThemeSwitch: true });
|
||||
}, []);
|
||||
|
||||
const RANGE_OPTIONS = useMemo(() => RANGE_OPTIONS_BUILDER(t), [t]);
|
||||
const EVENT_FILTERS = useMemo(() => EVENT_FILTER_BUILDER(t), [t]);
|
||||
|
||||
const [rangeHours, setRangeHours] = useState(24);
|
||||
const [eventFilter, setEventFilter] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [summary, setSummary] = useState(null);
|
||||
const [trend, setTrend] = useState(null);
|
||||
const [topUsers, setTopUsers] = useState([]);
|
||||
const [recent, setRecent] = useState({ items: [], total: 0 });
|
||||
|
||||
// 用单调递增的 request id 给"过期请求"的回写打钩。用户快速切 range/filter 时,多次
|
||||
// loadAll 会并行飞,只有最后一次的结果应该落到 state — 否则慢响应回来会覆盖新数据,
|
||||
// 出现"下拉显示 7d 但卡片是 1h 数据"的诡异 UI。
|
||||
const requestIdRef = useRef(0);
|
||||
|
||||
// 单次刷新拉全部四块数据(并行)。任何子接口失败不阻塞其他块,避免一处出错全屏白屏
|
||||
const loadAll = useCallback(async () => {
|
||||
const myId = ++requestIdRef.current;
|
||||
setLoading(true);
|
||||
const errors = [];
|
||||
const [summaryRes, trendRes, topUsersRes, recentRes] = await Promise.all([
|
||||
API.get(
|
||||
`/api/admin/playground/upload-audit/summary?range_hours=${rangeHours}`,
|
||||
).catch((e) => {
|
||||
errors.push(['summary', e]);
|
||||
return null;
|
||||
}),
|
||||
API.get(
|
||||
`/api/admin/playground/upload-audit/trend?range_hours=${rangeHours}&bucket=${rangeHours > 48 ? 'day' : 'hour'}`,
|
||||
).catch((e) => {
|
||||
errors.push(['trend', e]);
|
||||
return null;
|
||||
}),
|
||||
API.get(
|
||||
`/api/admin/playground/upload-audit/top-failing-users?range_hours=${rangeHours}&limit=10`,
|
||||
).catch((e) => {
|
||||
errors.push(['top-users', e]);
|
||||
return null;
|
||||
}),
|
||||
API.get(
|
||||
`/api/admin/playground/upload-audit/recent?range_hours=${rangeHours}&event=${encodeURIComponent(eventFilter)}&page=${page}&page_size=${pageSize}`,
|
||||
).catch((e) => {
|
||||
errors.push(['recent', e]);
|
||||
return null;
|
||||
}),
|
||||
]);
|
||||
|
||||
// 过期响应直接丢弃:myId 落后于最新 id 说明用户已经发起新请求了
|
||||
if (myId !== requestIdRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (summaryRes?.data?.success) setSummary(summaryRes.data.data);
|
||||
if (trendRes?.data?.success) setTrend(trendRes.data.data);
|
||||
if (topUsersRes?.data?.success)
|
||||
setTopUsers(topUsersRes.data.data?.items || []);
|
||||
if (recentRes?.data?.success) {
|
||||
setRecent({
|
||||
items: recentRes.data.data?.items || [],
|
||||
total: recentRes.data.data?.total || 0,
|
||||
});
|
||||
}
|
||||
|
||||
// 多块同时失败时,单独把每一块的错误都告诉用户;showError 内部会去重处理(如果 message 一致)
|
||||
if (errors.length > 0) {
|
||||
// 把 4 块名字翻成可读:summary/trend/top-users/recent → 数据看板加载(部分失败)
|
||||
Toast.warning({
|
||||
content: t('数据加载部分失败:{{names}}', {
|
||||
names: errors.map((e) => e[0]).join(', '),
|
||||
}),
|
||||
duration: 4,
|
||||
});
|
||||
// 同时把第一个 axios 错误细节也打到 Toast,方便定位(401/500 等)
|
||||
showError(errors[0][1]);
|
||||
}
|
||||
setLoading(false);
|
||||
}, [rangeHours, eventFilter, page, pageSize, t]);
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, [loadAll]);
|
||||
|
||||
// ----- 趋势图 spec -----
|
||||
const chartSpec = useMemo(() => {
|
||||
const buckets = trend?.buckets || [];
|
||||
if (buckets.length === 0) return null;
|
||||
|
||||
// 转成 vchart 长表
|
||||
const formatTs = (ts) => {
|
||||
const d = new Date(ts * 1000);
|
||||
if (trend?.bucket === 'day') {
|
||||
return `${d.getMonth() + 1}/${d.getDate()}`;
|
||||
}
|
||||
const pad = (n) => ('0' + n).slice(-2);
|
||||
return `${d.getMonth() + 1}/${d.getDate()} ${pad(d.getHours())}:00`;
|
||||
};
|
||||
|
||||
const chartData = buckets.flatMap((b) => [
|
||||
{ ts: formatTs(b.ts), type: t('成功'), value: b.success || 0 },
|
||||
{ ts: formatTs(b.ts), type: t('失败'), value: b.failed || 0 },
|
||||
{ ts: formatTs(b.ts), type: t('警告'), value: b.warning || 0 },
|
||||
]);
|
||||
|
||||
return {
|
||||
type: 'bar',
|
||||
data: [{ id: 'trend', values: chartData }],
|
||||
xField: 'ts',
|
||||
yField: 'value',
|
||||
seriesField: 'type',
|
||||
stack: true,
|
||||
bar: { style: { cornerRadius: [3, 3, 0, 0] } },
|
||||
legends: {
|
||||
visible: true,
|
||||
orient: 'top',
|
||||
position: 'middle',
|
||||
padding: { top: 0, bottom: 16 },
|
||||
},
|
||||
tooltip: {
|
||||
visible: true,
|
||||
mark: {
|
||||
visible: true,
|
||||
content: [
|
||||
{
|
||||
key: (d) => d?.type,
|
||||
value: (d) => `${(d?.value || 0).toLocaleString()} ${t('次')}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
dimension: { visible: true },
|
||||
},
|
||||
axes: [
|
||||
{ orient: 'bottom', label: { autoLimit: true, autoRotate: true } },
|
||||
{ orient: 'left', label: { formatMethod: (v) => v.toLocaleString() } },
|
||||
],
|
||||
color: ['#10b981', '#ef4444', '#f59e0b'],
|
||||
};
|
||||
}, [trend, t]);
|
||||
|
||||
// ----- Recent events table 列定义 -----
|
||||
const recentColumns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: t('时间'),
|
||||
dataIndex: 'created_at',
|
||||
width: 170,
|
||||
render: (ts) => formatTimestampForCsv(ts),
|
||||
},
|
||||
{
|
||||
title: t('用户'),
|
||||
dataIndex: 'username',
|
||||
width: 160,
|
||||
render: (v, row) => v || `(${t('用户')} ${row.user_id})`,
|
||||
},
|
||||
{
|
||||
title: t('事件'),
|
||||
dataIndex: 'event',
|
||||
width: 160,
|
||||
render: (evt) => (
|
||||
<Tag color={eventColor(evt)} size='small' shape='circle'>
|
||||
{EVENT_LABEL(t, evt)}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('详情'),
|
||||
dataIndex: 'detail',
|
||||
ellipsis: { showTitle: true },
|
||||
render: (v) => (
|
||||
<span className='text-xs text-gray-600 dark:text-gray-300 font-mono break-all'>
|
||||
{v || '-'}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
// ----- 导出 CSV:导出当前已加载的 recent 列表 -----
|
||||
const handleExport = useCallback(() => {
|
||||
if (!recent.items.length) {
|
||||
Toast.info({ content: t('没有可导出的记录'), duration: 2 });
|
||||
return;
|
||||
}
|
||||
const cols = [
|
||||
{
|
||||
key: 'created_at',
|
||||
title: t('时间'),
|
||||
format: (r) => formatTimestampForCsv(r.created_at),
|
||||
},
|
||||
{ key: 'user_id', title: 'user_id' },
|
||||
{ key: 'username', title: t('用户') },
|
||||
{
|
||||
key: 'event',
|
||||
title: t('事件'),
|
||||
format: (r) => EVENT_LABEL(t, r.event),
|
||||
},
|
||||
{ key: 'event_raw', title: t('原始事件 key'), format: (r) => r.event },
|
||||
{ key: 'detail', title: t('详情') },
|
||||
];
|
||||
const filename = `experience_center_upload_audit_${new Date().toISOString().slice(0, 10)}.csv`;
|
||||
exportToCsv(cols, recent.items, filename);
|
||||
Toast.success({
|
||||
content: t('已导出 {{n}} 条', { n: recent.items.length }),
|
||||
duration: 2,
|
||||
});
|
||||
}, [recent.items, t]);
|
||||
|
||||
// ----- Top failing users 列定义 -----
|
||||
const topUsersColumns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: t('用户'),
|
||||
dataIndex: 'username',
|
||||
render: (v, row) => v || `(${t('用户')} ${row.user_id})`,
|
||||
},
|
||||
{
|
||||
title: t('失败次数'),
|
||||
dataIndex: 'failure_count',
|
||||
width: 110,
|
||||
render: (v) => (
|
||||
<span className='font-mono font-medium text-red-500 tabular-nums'>
|
||||
{v}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('主要原因'),
|
||||
dataIndex: 'top_reason',
|
||||
render: (evt) => (
|
||||
<Tag color={eventColor(evt)} size='small' shape='circle'>
|
||||
{EVENT_LABEL(t, evt)}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
const total = summary?.total || 0;
|
||||
const successRate =
|
||||
total > 0 ? Math.round(((summary?.success || 0) / total) * 1000) / 10 : 0;
|
||||
|
||||
return (
|
||||
<div className='space-y-5'>
|
||||
{/* 工具栏:时间范围 + 刷新(标题由父 Tab 提供,不重复展示) */}
|
||||
<div className='flex flex-wrap items-center justify-end gap-2'>
|
||||
<Select
|
||||
value={rangeHours}
|
||||
onChange={(v) => {
|
||||
setPage(1);
|
||||
setRangeHours(v);
|
||||
}}
|
||||
optionList={RANGE_OPTIONS}
|
||||
className='min-w-[140px]'
|
||||
/>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<IconRefresh />}
|
||||
onClick={loadAll}
|
||||
loading={loading}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Spin spinning={loading} tip={t('加载中…')}>
|
||||
{/* 四张概览卡 */}
|
||||
<div className='grid grid-cols-2 md:grid-cols-4 gap-3'>
|
||||
<StatCard
|
||||
icon={<Upload className='text-brand' size={22} />}
|
||||
label={t('总事件数')}
|
||||
value={total}
|
||||
accent='bg-brand/5 dark:bg-brand-deep/30'
|
||||
/>
|
||||
<StatCard
|
||||
icon={<CheckCircle2 className='text-emerald-500' size={22} />}
|
||||
label={t('成功 (率)')}
|
||||
value={summary?.success}
|
||||
accent='bg-emerald-50 dark:bg-emerald-900/30'
|
||||
/>
|
||||
<StatCard
|
||||
icon={<XCircle className='text-red-500' size={22} />}
|
||||
label={t('失败')}
|
||||
value={summary?.failed}
|
||||
accent='bg-red-50 dark:bg-red-900/30'
|
||||
/>
|
||||
<StatCard
|
||||
icon={<Users className='text-blue-500' size={22} />}
|
||||
label={t('涉及用户数')}
|
||||
value={summary?.distinct_users}
|
||||
accent='bg-blue-50 dark:bg-blue-900/30'
|
||||
/>
|
||||
</div>
|
||||
{total > 0 && (
|
||||
<div className='text-xs text-gray-500 dark:text-gray-400 px-1 mt-1'>
|
||||
{t('成功率 {{rate}}% · 警告 {{w}} · 默认按 {{bucket}} 聚合', {
|
||||
rate: successRate,
|
||||
w: (summary?.warning || 0).toLocaleString(),
|
||||
bucket: rangeHours > 48 ? t('天') : t('小时'),
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 趋势图 */}
|
||||
<Card
|
||||
className='!rounded-2xl !shadow-sm border border-gray-100 dark:border-gray-700 mt-4'
|
||||
title={
|
||||
<span className='flex items-center gap-2'>
|
||||
<AlertTriangle size={16} className='text-brand' />
|
||||
{t('事件趋势')}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{chartSpec ? (
|
||||
<div style={{ height: 320 }}>
|
||||
<VChart spec={chartSpec} />
|
||||
</div>
|
||||
) : (
|
||||
<Empty description={t('此区间内暂无事件')} />
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* 失败用户 + 最近事件 双列布局(移动端堆叠) */}
|
||||
<div className='grid grid-cols-1 xl:grid-cols-5 gap-4 mt-4'>
|
||||
<Card
|
||||
className='xl:col-span-2 !rounded-2xl !shadow-sm border border-gray-100 dark:border-gray-700'
|
||||
title={
|
||||
<span className='flex items-center gap-2'>
|
||||
<Users size={16} className='text-red-500' />
|
||||
{t('失败 Top 10 用户')}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{topUsers.length === 0 ? (
|
||||
<Empty description={t('此区间内无失败用户')} />
|
||||
) : (
|
||||
<Table
|
||||
columns={topUsersColumns}
|
||||
dataSource={topUsers}
|
||||
pagination={false}
|
||||
size='small'
|
||||
rowKey='user_id'
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
className='xl:col-span-3 !rounded-2xl !shadow-sm border border-gray-100 dark:border-gray-700'
|
||||
title={
|
||||
<span className='flex items-center gap-2'>
|
||||
<Upload size={16} className='text-brand' />
|
||||
{t('最近事件')}
|
||||
</span>
|
||||
}
|
||||
headerExtraContent={
|
||||
// Semi 的 .semi-card-header-wrapper 是 row-reverse 且不换行,
|
||||
// .semi-card 又是 overflow:hidden:160px 的 Select 加导出按钮共约 410px,
|
||||
// 塞进 358px 的卡片头时「导出本页 CSV」被裁掉且点不到
|
||||
<div className='flex flex-wrap items-center justify-end gap-2'>
|
||||
<Select
|
||||
value={eventFilter}
|
||||
onChange={(v) => {
|
||||
setPage(1);
|
||||
setEventFilter(v);
|
||||
}}
|
||||
optionList={EVENT_FILTERS}
|
||||
className='min-w-[160px]'
|
||||
size='small'
|
||||
/>
|
||||
<Button
|
||||
theme='borderless'
|
||||
icon={<Download size={14} />}
|
||||
onClick={handleExport}
|
||||
size='small'
|
||||
>
|
||||
{t('导出本页 CSV')}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Table
|
||||
columns={recentColumns}
|
||||
dataSource={recent.items}
|
||||
size='small'
|
||||
rowKey='id'
|
||||
pagination={{
|
||||
currentPage: page,
|
||||
pageSize,
|
||||
total: recent.total,
|
||||
onPageChange: (p) => setPage(p),
|
||||
onPageSizeChange: (s) => {
|
||||
setPage(1);
|
||||
setPageSize(s);
|
||||
},
|
||||
showSizeChanger: true,
|
||||
pageSizeOpts: [20, 50, 100],
|
||||
showTotal: true,
|
||||
}}
|
||||
empty={<Empty description={t('此区间内暂无事件')} />}
|
||||
/>
|
||||
</Card>
|
||||
</div>
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExperienceCenterAuditPanel;
|
||||
@@ -0,0 +1,898 @@
|
||||
/* 平台专家中心 —— 对标云厂商控制台的信息层级(卡片体系 + KPI 概览 + 分区留白)。
|
||||
配色全部从主题 token 派生,随亮/暗色与品牌色自适应;
|
||||
整页背景交给 index.jsx 的 <PageBackground>,本文件不自绘背景。 */
|
||||
|
||||
.expert-platform-page {
|
||||
--ep-ink: var(--text-primary);
|
||||
--ep-muted: var(--text-secondary);
|
||||
--ep-line: var(--border-subtle);
|
||||
--ep-accent: var(--semi-color-primary);
|
||||
--ep-tint: color-mix(in srgb, var(--semi-color-primary) 10%, transparent);
|
||||
--ep-card: var(--surface-card);
|
||||
--ep-fill: var(--semi-color-fill-0);
|
||||
/* 阴影是中性投影而非配色:与 org-knowledge.css 的抬升体系逐字对齐,
|
||||
不随品牌色变化(这也是本文件里仅有的两处裸色值)。 */
|
||||
--ep-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
|
||||
--ep-shadow-lift: 0 10px 28px rgba(15, 23, 42, 0.09);
|
||||
|
||||
position: relative;
|
||||
/* 页面 shell 统一吃 --surface-bg-base(对照 KeyManagement),
|
||||
光晕由 <PageBackground> 单层叠在其上;overflow 防光斑撑出横向滚动条。 */
|
||||
overflow: hidden;
|
||||
min-height: 100%;
|
||||
background: var(--surface-bg-base);
|
||||
color: var(--ep-ink);
|
||||
/* 顶部 68px = 28px 呼吸间距 + 40px 固定顶栏补偿:
|
||||
全局 Header 是 position:fixed(桌面 64px),console 路由的 Content 只带
|
||||
24px 内边距(跑马灯 40px 另有占位 div 补偿),差额需页面自行让出,
|
||||
否则 hero 标题会被顶栏压住。改动前先读 PageLayout.jsx。
|
||||
左右/底部留白对齐企业中心标准页(p-4 sm:p-6 lg:p-8)。 */
|
||||
padding: 68px 16px 56px;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.expert-platform-page {
|
||||
padding-inline: 24px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.expert-platform-page {
|
||||
padding-inline: 32px;
|
||||
padding-bottom: 64px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.expert-platform-page {
|
||||
/* 移动端 Header 56px、Content 内边距 5px,差额 51px + 呼吸间距 */
|
||||
padding-top: 80px;
|
||||
}
|
||||
}
|
||||
|
||||
/* 单一内容外框:hero / 概览 / 页签栏 / 卡片区共用同一条左右基线,
|
||||
否则页签栏会全幅铺开、与居中收窄的正文错位。 */
|
||||
.expert-platform-shell {
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
max-width: 1560px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* 键盘可达性:统一 focus 环 */
|
||||
.expert-platform-page button:focus-visible,
|
||||
.expert-platform-page a:focus-visible,
|
||||
.expert-platform-page input:focus-visible,
|
||||
.expert-platform-page textarea:focus-visible,
|
||||
.expert-platform-page .semi-tabs-tab:focus-visible {
|
||||
outline: 2px solid
|
||||
color-mix(in srgb, var(--semi-color-primary) 55%, transparent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ===== Hero ===== */
|
||||
|
||||
.expert-hero {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 20px 24px;
|
||||
margin: 0 0 20px;
|
||||
}
|
||||
|
||||
.expert-hero-copy {
|
||||
min-width: 0;
|
||||
max-width: 780px;
|
||||
}
|
||||
|
||||
.expert-eyebrow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
color: var(--ep-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.expert-hero h1 {
|
||||
margin: 8px 0 4px;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.expert-hero-copy > p {
|
||||
margin: 0;
|
||||
color: var(--ep-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.expert-hero-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
/* 三步闭环:文字流程改成可扫读的步骤胶囊 */
|
||||
.expert-flow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin: 14px 0 0;
|
||||
}
|
||||
|
||||
.expert-flow-step {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 5px 13px 5px 6px;
|
||||
border: 1px solid var(--ep-line);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--ep-card) 82%, transparent);
|
||||
color: var(--ep-muted);
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
}
|
||||
|
||||
.expert-flow-step b {
|
||||
display: grid;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
place-items: center;
|
||||
border-radius: 50%;
|
||||
background: var(--ep-tint);
|
||||
color: var(--ep-accent);
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.expert-flow-arrow {
|
||||
color: var(--ep-muted);
|
||||
opacity: 0.5;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
/* ===== KPI 概览 ===== */
|
||||
|
||||
.expert-metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin: 0 0 18px;
|
||||
}
|
||||
|
||||
.expert-metric {
|
||||
position: relative;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 88px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--ep-line);
|
||||
border-radius: 14px;
|
||||
background: var(--ep-card);
|
||||
box-shadow: var(--ep-shadow);
|
||||
transition:
|
||||
transform 180ms ease,
|
||||
box-shadow 180ms ease,
|
||||
border-color 180ms ease;
|
||||
}
|
||||
|
||||
/* 每张指标卡一个维度色(低饱和度点缀,亮暗两色都成立):
|
||||
模板=品牌色、已发布=成功、待审核=次要、模型能力=信息、待对账=警告。 */
|
||||
.expert-metric:nth-child(1) {
|
||||
--metric-accent: var(--semi-color-primary);
|
||||
}
|
||||
.expert-metric:nth-child(2) {
|
||||
--metric-accent: var(--semi-color-success);
|
||||
}
|
||||
.expert-metric:nth-child(3) {
|
||||
/* 走 Semi 调色板的 violet-5 三元组(随亮/暗色级联),与相邻的 info 蓝拉开色相 */
|
||||
--metric-accent: rgb(var(--semi-violet-5, 106 58 199));
|
||||
}
|
||||
.expert-metric:nth-child(4) {
|
||||
--metric-accent: var(--semi-color-info, var(--semi-color-primary));
|
||||
}
|
||||
.expert-metric:nth-child(5) {
|
||||
--metric-accent: var(--semi-color-warning);
|
||||
}
|
||||
|
||||
.expert-metric::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -34px;
|
||||
right: -34px;
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
border-radius: 50%;
|
||||
background: color-mix(in srgb, var(--metric-accent) 9%, transparent);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.expert-metric:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: color-mix(in srgb, var(--metric-accent) 35%, var(--ep-line));
|
||||
box-shadow: var(--ep-shadow-lift);
|
||||
}
|
||||
|
||||
.expert-metric > svg {
|
||||
box-sizing: content-box;
|
||||
flex: 0 0 auto;
|
||||
padding: 11px;
|
||||
border-radius: 12px;
|
||||
color: var(--metric-accent, var(--ep-accent));
|
||||
background: color-mix(in srgb, var(--metric-accent) 12%, transparent);
|
||||
}
|
||||
|
||||
.expert-metric-copy {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.expert-metric-copy strong {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.02em;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.expert-metric-copy strong small {
|
||||
margin-left: 2px;
|
||||
color: var(--ep-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.expert-metric-copy span {
|
||||
margin-top: 3px;
|
||||
overflow: hidden;
|
||||
color: var(--ep-muted);
|
||||
font-size: 12px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (max-width: 1280px) {
|
||||
.expert-metrics {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.expert-metrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.expert-metrics {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.expert-hero-actions {
|
||||
width: 100%;
|
||||
}
|
||||
.expert-hero-actions .semi-button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== 页签 ===== */
|
||||
|
||||
/* 页签栏是分区线:下沿到卡片区必须留出完整一档间距(28px),
|
||||
只靠 Semi 默认的 0 内边距会让卡片顶到分割线上。 */
|
||||
.expert-tabs .semi-tabs-bar {
|
||||
margin-bottom: 0;
|
||||
border-bottom: 1px solid var(--ep-line);
|
||||
}
|
||||
|
||||
.expert-tabs .semi-tabs-content {
|
||||
padding: 28px 0 0;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.expert-tabs .semi-tabs-content {
|
||||
padding-top: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.expert-tab-label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.expert-tab-label em {
|
||||
min-width: 20px;
|
||||
padding: 0 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--ep-fill);
|
||||
color: var(--ep-muted);
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 18px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.expert-tabs .semi-tabs-tab-active .expert-tab-label em {
|
||||
background: var(--ep-tint);
|
||||
color: var(--ep-accent);
|
||||
}
|
||||
|
||||
/* 有待办的页签用警示色徽标,避免运营漏看死信/对账 */
|
||||
.expert-tab-label em.is-alert {
|
||||
background: color-mix(in srgb, var(--semi-color-warning) 16%, transparent);
|
||||
color: color-mix(
|
||||
in srgb,
|
||||
var(--semi-color-warning) 80%,
|
||||
var(--semi-color-text-0)
|
||||
);
|
||||
}
|
||||
|
||||
/* ===== 卡片网格 ===== */
|
||||
|
||||
.expert-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
|
||||
gap: 16px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.expert-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.expert-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 18px;
|
||||
border: 1px solid var(--ep-line);
|
||||
border-radius: 14px;
|
||||
background: var(--ep-card);
|
||||
box-shadow: var(--ep-shadow);
|
||||
transition:
|
||||
transform 200ms ease,
|
||||
box-shadow 200ms ease,
|
||||
border-color 200ms ease,
|
||||
background 200ms ease;
|
||||
}
|
||||
|
||||
/* hover 反馈分三层:顶部品牌色进度条 + 整卡抬升 + 标题着色,
|
||||
键盘 focus 走 :focus-within 得到同样的反馈。 */
|
||||
.expert-card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 2px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--ep-accent),
|
||||
color-mix(in srgb, var(--ep-accent) 15%, transparent)
|
||||
);
|
||||
opacity: 0;
|
||||
transform: scaleX(0.35);
|
||||
transform-origin: left;
|
||||
transition:
|
||||
opacity 200ms ease,
|
||||
transform 260ms ease;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.expert-card:hover,
|
||||
.expert-card:focus-within {
|
||||
transform: translateY(-3px);
|
||||
border-color: color-mix(in srgb, var(--ep-accent) 34%, var(--ep-line));
|
||||
background: color-mix(in srgb, var(--ep-accent) 3%, var(--ep-card));
|
||||
box-shadow: var(--ep-shadow-lift);
|
||||
}
|
||||
|
||||
.expert-card:hover::before,
|
||||
.expert-card:focus-within::before {
|
||||
opacity: 1;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.expert-card:hover .expert-card-title h3,
|
||||
.expert-card:focus-within .expert-card-title h3 {
|
||||
color: var(--ep-accent);
|
||||
}
|
||||
|
||||
/* 骨架屏只是占位,不参与交互反馈 */
|
||||
.expert-card.expert-skeleton:hover,
|
||||
.expert-card.expert-skeleton:focus-within {
|
||||
transform: none;
|
||||
border-color: var(--ep-line);
|
||||
background: var(--ep-card);
|
||||
box-shadow: var(--ep-shadow);
|
||||
}
|
||||
|
||||
.expert-card.expert-skeleton::before {
|
||||
content: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.expert-card,
|
||||
.expert-card::before,
|
||||
.expert-metric {
|
||||
transition: none;
|
||||
}
|
||||
.expert-card:hover,
|
||||
.expert-card:focus-within,
|
||||
.expert-metric:hover {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
|
||||
.expert-card-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.expert-card-title {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.expert-card-title h3 {
|
||||
margin: 0;
|
||||
color: var(--ep-ink);
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
line-height: 1.4;
|
||||
overflow-wrap: anywhere;
|
||||
transition: color 200ms ease;
|
||||
}
|
||||
|
||||
.expert-card-key {
|
||||
color: var(--ep-muted);
|
||||
font-family: 'IBM Plex Mono', 'Cascadia Code', monospace;
|
||||
font-size: 11px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.expert-card-desc {
|
||||
margin: 0;
|
||||
display: -webkit-box;
|
||||
overflow: hidden;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 2;
|
||||
line-clamp: 2;
|
||||
color: var(--ep-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.expert-card-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 6px 10px;
|
||||
color: var(--ep-muted);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.expert-card-tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* 底部动作区:一张卡片只有这一处按钮行(发布 / 紧急停用 / 编辑 同排),
|
||||
贴卡片底对齐,多张卡片的按钮行横向对齐不错位。 */
|
||||
.expert-card-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: auto;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--ep-line) 70%, transparent);
|
||||
}
|
||||
|
||||
.expert-card-foot:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* ===== 版本历史(只读) ===== */
|
||||
|
||||
/* 版本从「每行一个按钮」的列表改成横向徽章:卡片高度收敛,
|
||||
按钮全部归到 .expert-card-foot 那一行。 */
|
||||
.expert-version-strip {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.expert-version-chip {
|
||||
display: inline-flex;
|
||||
max-width: 100%;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px 3px 8px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 999px;
|
||||
background: var(--ep-fill);
|
||||
color: var(--ep-muted);
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
transition:
|
||||
background 150ms ease,
|
||||
border-color 150ms ease;
|
||||
}
|
||||
|
||||
.expert-card:hover .expert-version-chip {
|
||||
border-color: color-mix(in srgb, var(--ep-accent) 14%, transparent);
|
||||
background: color-mix(in srgb, var(--ep-accent) 6%, var(--ep-fill));
|
||||
}
|
||||
|
||||
.expert-version-chip b {
|
||||
color: var(--ep-ink);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.expert-version-chip > span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.expert-version-chip.is-more {
|
||||
color: var(--ep-muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.expert-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--semi-color-text-2);
|
||||
}
|
||||
|
||||
.expert-dot.is-published {
|
||||
background: var(--semi-color-success);
|
||||
}
|
||||
|
||||
.expert-dot.is-draft,
|
||||
.expert-dot.is-pending_review {
|
||||
background: var(--semi-color-warning);
|
||||
}
|
||||
|
||||
.expert-dot.is-revoked {
|
||||
background: var(--semi-color-danger);
|
||||
}
|
||||
|
||||
/* ===== 死信 / 对账行 ===== */
|
||||
|
||||
.expert-dead-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid
|
||||
color-mix(in srgb, var(--semi-color-danger) 22%, var(--ep-line));
|
||||
border-radius: 10px;
|
||||
background: color-mix(in srgb, var(--semi-color-danger) 5%, transparent);
|
||||
}
|
||||
|
||||
.expert-dead-copy {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.expert-dead-copy p {
|
||||
margin: 0;
|
||||
color: var(--ep-muted);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* ===== 空态 / 骨架 / 错误 ===== */
|
||||
|
||||
.expert-empty {
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
justify-items: center;
|
||||
gap: 8px;
|
||||
padding: 46px 24px;
|
||||
border: 1px dashed color-mix(in srgb, var(--ep-accent) 28%, var(--ep-line));
|
||||
border-radius: 14px;
|
||||
background: color-mix(in srgb, var(--ep-card) 55%, transparent);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.expert-empty-icon {
|
||||
display: grid;
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
place-items: center;
|
||||
border-radius: 14px;
|
||||
background: var(--ep-tint);
|
||||
color: var(--ep-accent);
|
||||
}
|
||||
|
||||
.expert-empty h3 {
|
||||
margin: 4px 0 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.expert-empty p {
|
||||
margin: 0;
|
||||
max-width: 440px;
|
||||
color: var(--ep-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.expert-empty .semi-button {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.expert-skeleton {
|
||||
min-height: 190px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.expert-error {
|
||||
margin: 0 0 18px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.expert-error-body {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 14px;
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* ===== 编辑器表单(弹窗内) ===== */
|
||||
|
||||
.expert-editor-form {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.expert-editor-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px 16px;
|
||||
}
|
||||
|
||||
.expert-editor-grid label,
|
||||
.expert-editor-form > label,
|
||||
.expert-modal-form > label {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
color: var(--semi-color-text-1);
|
||||
}
|
||||
|
||||
.expert-editor-grid label.wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
/* Semi 的 Select/InputNumber 默认自适应内容宽,在两列表单里要拉通 */
|
||||
.expert-editor-grid .semi-select,
|
||||
.expert-editor-grid .semi-input-number {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.expert-editor-hint {
|
||||
margin: 0;
|
||||
color: var(--semi-color-text-2);
|
||||
font-size: 12px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* 步骤计划卡片 */
|
||||
.expert-step-card {
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--semi-color-border);
|
||||
border-radius: 12px;
|
||||
background: var(--semi-color-fill-0);
|
||||
}
|
||||
|
||||
.expert-step-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.expert-step-head strong {
|
||||
color: var(--semi-color-text-0);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 模型健康徽标 */
|
||||
.expert-model-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
max-width: 100%;
|
||||
padding: 3px 9px;
|
||||
border-radius: 999px;
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
border: 1px solid var(--semi-color-border);
|
||||
background: var(--semi-color-fill-0);
|
||||
color: var(--semi-color-text-1);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.expert-model-badge.is-ok {
|
||||
border-color: color-mix(in srgb, var(--semi-color-success) 35%, transparent);
|
||||
background: color-mix(in srgb, var(--semi-color-success) 10%, transparent);
|
||||
color: color-mix(
|
||||
in srgb,
|
||||
var(--semi-color-success) 75%,
|
||||
var(--semi-color-text-0)
|
||||
);
|
||||
}
|
||||
|
||||
.expert-model-badge.is-missing {
|
||||
border-color: color-mix(in srgb, var(--semi-color-warning) 45%, transparent);
|
||||
background: color-mix(in srgb, var(--semi-color-warning) 12%, transparent);
|
||||
color: color-mix(
|
||||
in srgb,
|
||||
var(--semi-color-warning) 78%,
|
||||
var(--semi-color-text-0)
|
||||
);
|
||||
}
|
||||
|
||||
.expert-card-models {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* 编辑器顶部工具行:技能绑定 + JSON 模式切换 */
|
||||
.expert-editor-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.expert-editor-toolbar > .semi-select {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.expert-editor-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
/* 对账 / 死信重放弹窗正文 */
|
||||
.expert-modal-form {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.expert-editor-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
/* 专家可用性测试:自检结论 + 候选模型 + 连通性实测三段,靠色条区分通过/阻断 */
|
||||
.expert-diagnose {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
.expert-diagnose-scope {
|
||||
margin: 0;
|
||||
color: var(--semi-color-text-2);
|
||||
font-size: 12px;
|
||||
}
|
||||
.expert-diagnose-checks {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.expert-diagnose-checks li {
|
||||
display: grid;
|
||||
grid-template-columns: 88px minmax(0, 1fr);
|
||||
gap: 10px;
|
||||
align-items: baseline;
|
||||
padding: 8px 12px;
|
||||
border-left: 2px solid var(--semi-color-success);
|
||||
border-radius: 8px;
|
||||
background: var(--semi-color-fill-0);
|
||||
}
|
||||
.expert-diagnose-checks li.is-blocked {
|
||||
border-left-color: var(--semi-color-danger);
|
||||
}
|
||||
.expert-diagnose-checks span {
|
||||
color: var(--semi-color-text-1);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.expert-diagnose-checks small,
|
||||
.expert-diagnose-model small {
|
||||
color: var(--semi-color-text-2);
|
||||
font-size: 12px;
|
||||
word-break: break-word;
|
||||
}
|
||||
.expert-diagnose-models h4,
|
||||
.expert-diagnose-connectivity h4 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.expert-diagnose-model {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 8px 12px;
|
||||
border-left: 2px solid var(--semi-color-success);
|
||||
border-radius: 8px;
|
||||
background: var(--semi-color-fill-0);
|
||||
}
|
||||
.expert-diagnose-model + .expert-diagnose-model {
|
||||
margin-top: 6px;
|
||||
}
|
||||
.expert-diagnose-model.is-blocked {
|
||||
border-left-color: var(--semi-color-danger);
|
||||
}
|
||||
.expert-diagnose-model strong {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.expert-diagnose-model em {
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
background: var(--semi-color-primary-light-default);
|
||||
color: var(--semi-color-primary);
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
}
|
||||
.expert-diagnose-empty {
|
||||
margin: 6px 0 0;
|
||||
color: var(--semi-color-text-2);
|
||||
font-size: 12px;
|
||||
}
|
||||
.expert-diagnose-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Empty } from '@douyinfe/semi-ui';
|
||||
import {
|
||||
IllustrationNoAccess,
|
||||
IllustrationNoAccessDark,
|
||||
} from '../../components/common/illustrations';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const Forbidden = () => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className='flex justify-center items-center h-screen p-8'>
|
||||
<Empty
|
||||
image={<IllustrationNoAccess style={{ width: 250, height: 250 }} />}
|
||||
darkModeImage={
|
||||
<IllustrationNoAccessDark style={{ width: 250, height: 250 }} />
|
||||
}
|
||||
description={t('您无权访问此页面,请联系管理员')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Forbidden;
|
||||
@@ -0,0 +1,822 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, {
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
useRef,
|
||||
useCallback,
|
||||
} from 'react';
|
||||
import { Button } from '@douyinfe/semi-ui';
|
||||
import { API, showError } from '../../helpers';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { useActualTheme } from '../../context/Theme';
|
||||
import { marked } from 'marked';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Moonshot,
|
||||
OpenAI,
|
||||
Zhipu,
|
||||
Claude,
|
||||
Gemini,
|
||||
Wenxin,
|
||||
Spark,
|
||||
DeepSeek,
|
||||
Qwen,
|
||||
Midjourney,
|
||||
} from '@lobehub/icons';
|
||||
import {
|
||||
Cpu,
|
||||
Server,
|
||||
Code,
|
||||
Box,
|
||||
Users,
|
||||
BarChart3,
|
||||
Key,
|
||||
Network,
|
||||
Rocket,
|
||||
MessageSquare,
|
||||
Palette,
|
||||
Video,
|
||||
} from 'lucide-react';
|
||||
|
||||
const Home = () => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
// WeyAi 桌面端下载入口(页脚位置):跟随后台「开启桌面端下载页」开关
|
||||
const weyaiDownloadEnabled =
|
||||
statusState?.status?.weyai_download_enabled === true ||
|
||||
statusState?.status?.weyai_download_enabled === 'true';
|
||||
const actualTheme = useActualTheme();
|
||||
const [homePageContentLoaded, setHomePageContentLoaded] = useState(false);
|
||||
const [homePageContent, setHomePageContent] = useState('');
|
||||
const [iframeError, setIframeError] = useState(false);
|
||||
const [iframeLoading, setIframeLoading] = useState(true);
|
||||
const iframeTimeoutRef = useRef(null);
|
||||
const iframeRef = useRef(null);
|
||||
const isUrl = (str) => {
|
||||
return str.startsWith('https://') || str.startsWith('http://');
|
||||
};
|
||||
|
||||
const displayHomePageContent = async () => {
|
||||
// 只对非URL内容使用localStorage缓存,URL内容总是从API获取最新的
|
||||
const cachedContent = localStorage.getItem('home_page_content') || '';
|
||||
if (cachedContent && !isUrl(cachedContent)) {
|
||||
setHomePageContent(cachedContent);
|
||||
}
|
||||
|
||||
setIframeError(false); // 重置 iframe 错误状态
|
||||
setIframeLoading(true);
|
||||
|
||||
// 清除之前的超时定时器
|
||||
if (iframeTimeoutRef.current) {
|
||||
clearTimeout(iframeTimeoutRef.current);
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await API.get('/api/home_page_content');
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
let content = data;
|
||||
if (!isUrl(data)) {
|
||||
content = marked.parse(data);
|
||||
}
|
||||
setHomePageContent(content);
|
||||
localStorage.setItem('home_page_content', content);
|
||||
|
||||
if (isUrl(data)) {
|
||||
// 设置超时检测 - 如果 5 秒内 iframe 未能正常加载,显示备用界面
|
||||
iframeTimeoutRef.current = setTimeout(() => {
|
||||
// 如果 5 秒后仍在加载状态,且没有收到加载成功的信号,认为加载失败
|
||||
setIframeLoading(false);
|
||||
// 检查 iframe 是否有内容
|
||||
if (iframeRef.current) {
|
||||
try {
|
||||
const doc =
|
||||
iframeRef.current.contentDocument ||
|
||||
iframeRef.current.contentWindow?.document;
|
||||
if (!doc || !doc.body || doc.body.innerHTML === '') {
|
||||
setIframeError(true);
|
||||
}
|
||||
} catch (err) {
|
||||
// 跨域错误说明 iframe 加载成功了,只是无法访问内容
|
||||
// 这种情况不设置错误
|
||||
}
|
||||
}
|
||||
}, 5000);
|
||||
} else {
|
||||
// 非URL内容,立即停止loading状态
|
||||
setIframeLoading(false);
|
||||
}
|
||||
} else {
|
||||
showError(message);
|
||||
setHomePageContent('加载首页内容失败...');
|
||||
setIframeLoading(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load home page content:', error);
|
||||
showError(t('加载首页内容失败'));
|
||||
setHomePageContent('加载首页内容失败...');
|
||||
setIframeLoading(false);
|
||||
} finally {
|
||||
setHomePageContentLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
// iframe 加载成功的回调
|
||||
const handleIframeLoad = useCallback(() => {
|
||||
// 清除超时定时器
|
||||
if (iframeTimeoutRef.current) {
|
||||
clearTimeout(iframeTimeoutRef.current);
|
||||
}
|
||||
setIframeLoading(false);
|
||||
|
||||
// 检测是否真的加载成功
|
||||
try {
|
||||
if (iframeRef.current) {
|
||||
const doc =
|
||||
iframeRef.current.contentDocument ||
|
||||
iframeRef.current.contentWindow?.document;
|
||||
// 如果文档为空或无法访问,可能是被 X-Frame-Options 阻止
|
||||
if (!doc || (doc.body && doc.body.innerHTML === '')) {
|
||||
setIframeError(true);
|
||||
} else {
|
||||
// 发送主题和语言消息
|
||||
iframeRef.current.contentWindow?.postMessage(
|
||||
{ themeMode: actualTheme },
|
||||
'*',
|
||||
);
|
||||
iframeRef.current.contentWindow?.postMessage(
|
||||
{ lang: (i18n.language || '').split('-')[0] },
|
||||
'*',
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
// 跨域访问被拒绝,但这并不意味着 iframe 加载失败
|
||||
// 只是无法访问内容而已,不设置错误
|
||||
console.log('iframe loaded with cross-origin content');
|
||||
}
|
||||
}, [actualTheme, i18n.language]);
|
||||
|
||||
// 清理定时器
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (iframeTimeoutRef.current) {
|
||||
clearTimeout(iframeTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 监听来自 iframe 的导航消息
|
||||
// iframe 内的页面可以通过 postMessage 请求父窗口进行导航
|
||||
// 消息格式: { type: 'navigate', path: '/market' } 或 { type: 'navigate', url: 'https://...' }
|
||||
useEffect(() => {
|
||||
const handleIframeMessage = (event) => {
|
||||
// 安全检查:只在 iframe 存在时处理消息
|
||||
if (!iframeRef.current) return;
|
||||
|
||||
// 安全检查:验证消息来源
|
||||
// 只接受来自 iframe src 同源的消息,或者来自本站的消息
|
||||
if (homePageContent && isUrl(homePageContent)) {
|
||||
try {
|
||||
const iframeSrcOrigin = new URL(homePageContent).origin;
|
||||
// 只接受来自 iframe 源或本站的消息
|
||||
if (
|
||||
event.origin !== iframeSrcOrigin &&
|
||||
event.origin !== window.location.origin
|
||||
) {
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
// URL 解析失败,拒绝消息
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const data = event.data;
|
||||
|
||||
// 处理导航请求
|
||||
if (data && data.type === 'navigate') {
|
||||
if (data.path) {
|
||||
// 内部路径导航,使用 React Router
|
||||
// 安全检查:路径必须以 / 开头,防止 javascript: 等协议注入
|
||||
if (typeof data.path === 'string' && data.path.startsWith('/')) {
|
||||
navigate(data.path);
|
||||
}
|
||||
} else if (data.url) {
|
||||
// 外部 URL,判断是否是同源
|
||||
try {
|
||||
const url = new URL(data.url);
|
||||
if (url.origin === window.location.origin) {
|
||||
// 同源 URL,提取路径使用 React Router 导航
|
||||
navigate(url.pathname + url.search + url.hash);
|
||||
} else {
|
||||
// 跨域 URL,在新窗口打开
|
||||
window.open(data.url, '_blank', 'noopener,noreferrer');
|
||||
}
|
||||
} catch (e) {
|
||||
// URL 解析失败,忽略(不再尝试作为路径处理,防止注入)
|
||||
console.warn('Invalid navigation URL:', data.url);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleIframeMessage);
|
||||
return () => {
|
||||
window.removeEventListener('message', handleIframeMessage);
|
||||
};
|
||||
}, [navigate, homePageContent]);
|
||||
|
||||
useEffect(() => {
|
||||
displayHomePageContent().then();
|
||||
}, []);
|
||||
|
||||
// 核心能力数据 - 全方位 (8 items)
|
||||
const capabilities = [
|
||||
{
|
||||
icon: <Cpu size={28} className='text-cyan-400' />,
|
||||
title: t('多模态模型'),
|
||||
desc: t('支持文本、图像、语音等多种模态接入'),
|
||||
},
|
||||
{
|
||||
icon: <Server size={28} className='text-blue-400' />,
|
||||
title: t('高并发集群'),
|
||||
desc: t('企业级架构设计,轻松应对高并发场景'),
|
||||
},
|
||||
{
|
||||
icon: <Code size={28} className='text-brand-from' />,
|
||||
title: t('极速集成'),
|
||||
desc: t('OpenAI 格式完全兼容,零成本无缝迁移'),
|
||||
},
|
||||
{
|
||||
icon: <Box size={28} className='text-brand-from' />,
|
||||
title: t('按量计费'),
|
||||
desc: t('灵活的计费策略,极具竞争力的价格'),
|
||||
},
|
||||
{
|
||||
icon: <Users size={28} className='text-teal-400' />,
|
||||
title: t('团队协作'),
|
||||
desc: t('支持多用户管理与配额分配,高效协作'),
|
||||
},
|
||||
{
|
||||
icon: <BarChart3 size={28} className='text-emerald-400' />,
|
||||
title: t('数据看板'),
|
||||
desc: t('多维度用量分析与成本监控,一目了然'),
|
||||
},
|
||||
{
|
||||
icon: <Key size={28} className='text-rose-400' />,
|
||||
title: t('令牌管理'),
|
||||
desc: t('精细化的 API Key 权限控制与额度限制'),
|
||||
},
|
||||
{
|
||||
icon: <Network size={28} className='text-sky-400' />,
|
||||
title: t('智能路由'),
|
||||
desc: t('自动选择最优通道,保障请求高可用'),
|
||||
},
|
||||
];
|
||||
|
||||
// 模型列表
|
||||
const modelIcons = [
|
||||
{ Icon: OpenAI, name: 'OpenAI' },
|
||||
{ Icon: Claude.Color, name: 'Claude' },
|
||||
{ Icon: Gemini.Color, name: 'Gemini' },
|
||||
{ Icon: Midjourney, name: 'Midjourney' },
|
||||
{ Icon: Qwen.Color, name: 'Qwen' },
|
||||
{ Icon: DeepSeek.Color, name: 'DeepSeek' },
|
||||
{ Icon: Zhipu.Color, name: 'ChatGLM' },
|
||||
{ Icon: Moonshot, name: 'Moonshot' },
|
||||
{ Icon: Spark.Color, name: 'Spark' },
|
||||
{ Icon: Wenxin.Color, name: 'Wenxin' },
|
||||
];
|
||||
|
||||
// Enterprise Style CSS
|
||||
const enterpriseStyles = `
|
||||
.enterprise-card {
|
||||
background: rgba(255, 255, 255, 0.8);
|
||||
border: 1px solid rgba(226, 232, 240, 1);
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
.dark .enterprise-card {
|
||||
background: rgba(30, 41, 59, 0.6);
|
||||
border: 1px solid rgba(51, 65, 85, 1);
|
||||
}
|
||||
.enterprise-card:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.1);
|
||||
border-color: rgba(59, 130, 246, 0.5); /* Blue hover */
|
||||
}
|
||||
.dark .enterprise-card:hover {
|
||||
box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.3);
|
||||
border-color: rgba(59, 130, 246, 0.5);
|
||||
background: rgba(30, 41, 59, 0.8);
|
||||
}
|
||||
|
||||
.hero-gradient {
|
||||
background: linear-gradient(135deg, #f0f9ff 0%, #dbeafe 100%); /* Light Blue */
|
||||
}
|
||||
.dark .hero-gradient {
|
||||
background: linear-gradient(135deg, #172554 0%, #1e3a8a 100%); /* Dark Blue */
|
||||
}
|
||||
|
||||
.text-3d {
|
||||
text-shadow: 0 4px 6px rgba(0,0,0,0.1), 0 1px 3px rgba(0,0,0,0.08);
|
||||
}
|
||||
.dark .text-3d {
|
||||
text-shadow: 0 4px 6px rgba(0,0,0,0.3), 0 1px 3px rgba(0,0,0,0.2);
|
||||
}
|
||||
|
||||
@keyframes slideInUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(50px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-slide-in {
|
||||
animation: slideInUp 1.2s cubic-bezier(0.2, 0.8, 0.2, 1) forwards;
|
||||
}
|
||||
|
||||
@keyframes flowRight {
|
||||
0% { left: 0; opacity: 0; }
|
||||
20% { opacity: 1; }
|
||||
80% { opacity: 1; }
|
||||
100% { left: 100%; opacity: 0; }
|
||||
}
|
||||
|
||||
.animate-flow-right {
|
||||
animation: flowRight 2s linear infinite;
|
||||
}
|
||||
|
||||
/* Hide scrollbar */
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.no-scrollbar {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
`;
|
||||
|
||||
const showIframe =
|
||||
homePageContentLoaded && homePageContent !== '' && isUrl(homePageContent);
|
||||
|
||||
return (
|
||||
<div
|
||||
// 手机端用 snap-proximity 而非 mandatory:单列堆叠后每屏内容普遍超过一屏高,
|
||||
// mandatory 会强制吸附到屏首、不允许停在中间,等于把超出的部分锁死。
|
||||
// 桌面端维持原来的整屏吸附观感。
|
||||
className={`w-full h-screen overflow-y-scroll snap-y snap-proximity md:snap-mandatory scroll-smooth bg-white dark:bg-slate-950 text-slate-900 dark:text-slate-100 font-sans no-scrollbar ${showIframe ? '' : 'pt-[64px]'}`}
|
||||
>
|
||||
{' '}
|
||||
<style>{enterpriseStyles}</style>
|
||||
{homePageContentLoaded && homePageContent === '' ? (
|
||||
<>
|
||||
{/* Page 1: Hero Section - Custom Background & Layout */}
|
||||
<section className="snap-start w-full min-h-full relative flex items-center overflow-hidden py-20 md:py-0 bg-[url('/assets/home-bg-2.jpg')] bg-cover bg-center">
|
||||
<div className='absolute inset-0 bg-white/60 dark:bg-slate-900/80 backdrop-blur-sm'></div>
|
||||
|
||||
<div className='container mx-auto px-6 z-10 relative min-h-full flex flex-col justify-center items-center'>
|
||||
<div className='flex flex-col items-center text-center max-w-5xl mx-auto w-full pt-10'>
|
||||
{/* Center Column: Text */}
|
||||
<div className='mb-12'>
|
||||
<h1 className='text-5xl md:text-7xl font-bold mb-8 tracking-tight leading-tight text-slate-900 dark:text-white animate-slide-in text-3d'>
|
||||
{t('打造全球领先的')}
|
||||
<span className='block mt-2 text-transparent bg-clip-text bg-gradient-to-r from-blue-600 to-brand-to dark:from-blue-400 dark:to-brand-to'>
|
||||
{t('大模型体验中心')}
|
||||
</span>
|
||||
</h1>
|
||||
|
||||
<p
|
||||
className='text-xl text-slate-600 dark:text-slate-300 max-w-3xl mx-auto mb-10 font-medium leading-relaxed animate-slide-in'
|
||||
style={{ animationDelay: '0.2s' }}
|
||||
>
|
||||
{t(
|
||||
'集成全球顶尖 AI 算力,为开发者提供一站式、高性能、安全稳定的企业级模型服务网关。',
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div
|
||||
className='flex flex-wrap justify-center gap-4 sm:gap-6 animate-slide-in'
|
||||
style={{ animationDelay: '0.4s' }}
|
||||
>
|
||||
<Link to='/console/analytics'>
|
||||
<Button
|
||||
type='tertiary'
|
||||
size='large'
|
||||
className='!bg-blue-600 hover:!bg-blue-700 !font-bold !px-12 !h-14 !rounded-full !text-lg shadow-lg shadow-blue-500/20 hover:shadow-blue-500/30 transition-all hover:-translate-y-1'
|
||||
style={{ color: '#ffffff' }}
|
||||
>
|
||||
{t('立即探索')}{' '}
|
||||
<Rocket
|
||||
size={20}
|
||||
className='ml-2'
|
||||
style={{ color: '#ffffff' }}
|
||||
/>
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to='/about'>
|
||||
<Button
|
||||
type='tertiary'
|
||||
size='large'
|
||||
className='!bg-white dark:!bg-slate-800 hover:!bg-slate-50 dark:hover:!bg-slate-700 !font-bold !px-12 !h-14 !rounded-full !text-lg border !border-slate-200 dark:!border-slate-700 transition-all hover:-translate-y-1'
|
||||
style={{ color: '#334155' }}
|
||||
>
|
||||
{t('了解更多')}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom: Animated Workflow Diagram (Centered) */}
|
||||
<div
|
||||
className='hidden lg:flex justify-center items-center animate-slide-in w-full'
|
||||
style={{ animationDelay: '0.6s' }}
|
||||
>
|
||||
<div className='relative w-full max-w-lg aspect-video rounded-2xl bg-white/40 dark:bg-slate-800/40 backdrop-blur-md border border-white/50 dark:border-slate-600/50 p-8 flex items-center justify-between shadow-2xl'>
|
||||
{/* User Node */}
|
||||
<div className='flex flex-col items-center gap-3 z-10'>
|
||||
<div className='w-14 h-14 rounded-full bg-blue-500 flex items-center justify-center shadow-lg shadow-blue-500/30 ring-4 ring-white/30 dark:ring-slate-700/30'>
|
||||
<Users className='text-white' size={26} />
|
||||
</div>
|
||||
<span className='text-sm font-bold text-slate-700 dark:text-slate-200 bg-white/50 dark:bg-black/50 px-3 py-1 rounded-full backdrop-blur-sm'>
|
||||
Client
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Flow Lines Left -> Center */}
|
||||
<div className='flex-1 h-1 bg-slate-200 dark:bg-slate-700 relative mx-4 rounded-full overflow-hidden'>
|
||||
<div className='absolute top-0 bottom-0 left-0 w-8 bg-gradient-to-r from-transparent via-blue-500 to-transparent animate-flow-right'></div>
|
||||
</div>
|
||||
|
||||
{/* Gateway Node */}
|
||||
<div className='flex flex-col items-center gap-3 z-10'>
|
||||
<div className='relative w-20 h-20 rounded-2xl bg-gradient-to-br from-brand-from to-brand-to flex items-center justify-center shadow-xl shadow-brand/40'>
|
||||
<Network className='text-white' size={36} />
|
||||
<div className='absolute -inset-1 rounded-2xl border border-white/40 animate-pulse'></div>
|
||||
</div>
|
||||
<span className='text-sm font-bold text-brand-deep dark:text-brand-from bg-white/50 dark:bg-black/50 px-3 py-1 rounded-full backdrop-blur-sm'>
|
||||
Gateway
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Flow Lines Center -> Right */}
|
||||
<div className='flex-1 h-1 bg-slate-200 dark:bg-slate-700 relative mx-4 rounded-full overflow-hidden'>
|
||||
<div
|
||||
className='absolute top-0 bottom-0 left-0 w-8 bg-gradient-to-r from-transparent via-brand-via to-transparent animate-flow-right'
|
||||
style={{ animationDelay: '0.5s' }}
|
||||
></div>
|
||||
</div>
|
||||
|
||||
{/* Models Nodes (Stacked) */}
|
||||
<div className='flex flex-col gap-4 z-10'>
|
||||
<div className='w-12 h-12 rounded-xl bg-white dark:bg-slate-800 flex items-center justify-center shadow-md border border-slate-200 dark:border-slate-700 hover:scale-110 transition-transform'>
|
||||
<OpenAI size={24} />
|
||||
</div>
|
||||
<div className='w-12 h-12 rounded-xl bg-white dark:bg-slate-800 flex items-center justify-center shadow-md border border-slate-200 dark:border-slate-700 hover:scale-110 transition-transform'>
|
||||
<Claude.Color size={24} />
|
||||
</div>
|
||||
<div className='w-12 h-12 rounded-xl bg-white dark:bg-slate-800 flex items-center justify-center shadow-md border border-slate-200 dark:border-slate-700 hover:scale-110 transition-transform'>
|
||||
<Gemini.Color size={24} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Page 2: Model Capabilities - Bento Grid Style */}
|
||||
<section className='snap-start w-full min-h-full relative flex items-center justify-center overflow-hidden py-20 md:py-0 bg-slate-50 dark:bg-slate-900'>
|
||||
<div className='container mx-auto px-6 z-10 relative min-h-full flex flex-col justify-center'>
|
||||
<div className='text-center mb-12'>
|
||||
<h2 className='text-4xl md:text-5xl font-bold mb-6 text-slate-900 dark:text-white tracking-tight'>
|
||||
{t('多维感知,全能进化')}
|
||||
</h2>
|
||||
<p className='text-xl text-slate-600 dark:text-slate-400 max-w-2xl mx-auto'>
|
||||
{t(
|
||||
'从文本到多模态,覆盖全场景 AI 需求,为您提供最全面的模型支持',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div // 手机端单列:高度交给内容,行数不写死。原来 h-[500px] + grid-rows-2 只排得下 2 行,
|
||||
// 语音交互/联网与插件两张卡落在未定义行里、被父级 overflow-hidden 裁掉
|
||||
className='grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 md:grid-rows-2 gap-6 max-w-6xl mx-auto w-full h-auto md:h-[500px]'
|
||||
>
|
||||
{/* Large Card: LLM */}
|
||||
<div className='md:col-span-2 md:row-span-2 group enterprise-card rounded-2xl p-8 relative overflow-hidden bg-gradient-to-br from-blue-500/5 to-brand-to/10 border border-blue-200/50 dark:border-blue-900/30 backdrop-blur-sm'>
|
||||
<div className='absolute top-0 right-0 w-64 h-64 bg-blue-500/10 rounded-full blur-3xl -mr-16 -mt-16 transition-opacity group-hover:opacity-70'></div>
|
||||
<div className='relative z-10 h-full flex flex-col'>
|
||||
<div className='mb-6 w-14 h-14 rounded-xl bg-gradient-to-br from-blue-100 to-brand-to/10 dark:from-blue-900/40 dark:to-brand-to/40 flex items-center justify-center text-blue-600 dark:text-blue-400'>
|
||||
<MessageSquare size={32} />
|
||||
</div>
|
||||
<h3 className='text-2xl font-bold mb-4 text-slate-900 dark:text-white'>
|
||||
{t('通用大语言模型')}
|
||||
</h3>
|
||||
<p className='text-slate-600 dark:text-slate-400 text-base leading-relaxed mb-6 flex-grow'>
|
||||
{t(
|
||||
'聚合 OpenAI GPT-4、Claude 3.5、Gemini 1.5 等全球最强 LLM。具备卓越的逻辑推理、代码生成、创意写作及多轮对话能力,满足各种复杂任务需求。',
|
||||
)}
|
||||
</p>
|
||||
<div className='flex gap-2'>
|
||||
<span className='px-3 py-1 rounded-full bg-white/60 dark:bg-slate-800/60 border border-blue-100 dark:border-blue-900/30 text-xs text-blue-700 dark:text-blue-300'>
|
||||
Context Window 128k+
|
||||
</span>
|
||||
<span className='px-3 py-1 rounded-full bg-white/60 dark:bg-slate-800/60 border border-blue-100 dark:border-blue-900/30 text-xs text-blue-700 dark:text-blue-300'>
|
||||
Function Calling
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Medium Card: Vision */}
|
||||
<div className='md:col-span-2 group enterprise-card rounded-2xl p-8 relative overflow-hidden bg-gradient-to-br from-brand-from/5 to-pink-500/10 border border-brand/50 dark:border-brand-deep/30 backdrop-blur-sm'>
|
||||
<div className='absolute top-0 right-0 w-48 h-48 bg-brand/10 rounded-full blur-3xl -mr-10 -mt-10 transition-opacity group-hover:opacity-70'></div>
|
||||
<div className='relative z-10 flex items-start justify-between'>
|
||||
<div>
|
||||
<div className='mb-4 w-12 h-12 rounded-xl bg-gradient-to-br from-brand-from/10 to-pink-100 dark:from-brand-from/40 dark:to-pink-900/40 flex items-center justify-center text-brand-deep dark:text-brand-from'>
|
||||
<Palette size={28} />
|
||||
</div>
|
||||
<h3 className='text-xl font-bold mb-2 text-slate-900 dark:text-white'>
|
||||
{t('视觉理解与生成')}
|
||||
</h3>
|
||||
<p className='text-slate-600 dark:text-slate-400 text-sm'>
|
||||
{t(
|
||||
'支持 Midjourney、DALL-E 3 绘图,以及 GPT-4o 的视觉分析能力。',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Small Card: Audio */}
|
||||
<div className='group enterprise-card rounded-2xl p-6 relative overflow-hidden bg-gradient-to-br from-emerald-500/5 to-teal-500/10 border border-emerald-200/50 dark:border-emerald-900/30 backdrop-blur-sm'>
|
||||
<div className='absolute bottom-0 left-0 w-32 h-32 bg-emerald-500/10 rounded-full blur-2xl -ml-8 -mb-8 transition-opacity group-hover:opacity-70'></div>
|
||||
<div className='relative z-10'>
|
||||
<div className='mb-4 w-10 h-10 rounded-lg bg-gradient-to-br from-emerald-100 to-teal-100 dark:from-emerald-900/40 dark:to-teal-900/40 flex items-center justify-center text-emerald-600 dark:text-emerald-400'>
|
||||
<Cpu size={24} />
|
||||
</div>
|
||||
<h3 className='text-lg font-bold mb-2 text-slate-900 dark:text-white'>
|
||||
{t('语音交互')}
|
||||
</h3>
|
||||
<p className='text-slate-600 dark:text-slate-400 text-xs leading-relaxed'>
|
||||
{t('TTS 语音合成与 Whisper 语音转写,支持情感音色。')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Small Card: Tools/Net */}
|
||||
<div className='group enterprise-card rounded-2xl p-6 relative overflow-hidden bg-gradient-to-br from-orange-500/5 to-amber-500/10 border border-orange-200/50 dark:border-orange-900/30 backdrop-blur-sm'>
|
||||
<div className='absolute bottom-0 right-0 w-32 h-32 bg-orange-500/10 rounded-full blur-2xl -mr-8 -mb-8 transition-opacity group-hover:opacity-70'></div>
|
||||
<div className='relative z-10'>
|
||||
<div className='mb-4 w-10 h-10 rounded-lg bg-gradient-to-br from-orange-100 to-amber-100 dark:from-orange-900/40 dark:to-amber-900/40 flex items-center justify-center text-orange-600 dark:text-orange-400'>
|
||||
<Network size={24} />
|
||||
</div>
|
||||
<h3 className='text-lg font-bold mb-2 text-slate-900 dark:text-white'>
|
||||
{t('联网与插件')}
|
||||
</h3>
|
||||
<p className='text-slate-600 dark:text-slate-400 text-xs leading-relaxed'>
|
||||
{t('实时联网搜索,获取最新资讯,打破模型知识库限制。')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Page 3: Models Section - Clean Grid */}
|
||||
<section className='snap-start w-full min-h-full relative flex items-center justify-center overflow-hidden py-20 md:py-0 bg-white dark:bg-slate-950'>
|
||||
<div className='container mx-auto px-6 z-10 relative min-h-full flex flex-col justify-center'>
|
||||
<div className='text-center mb-16'>
|
||||
<h2 className='text-4xl md:text-5xl font-bold mb-6 text-slate-900 dark:text-white tracking-tight'>
|
||||
{t('支持当前主流的大模型探索')}
|
||||
</h2>
|
||||
<div className='h-1 w-20 bg-orange-600 rounded-full mx-auto'></div>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-2 md:grid-cols-5 gap-6 max-w-6xl mx-auto w-full'>
|
||||
{modelIcons.map((item, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className='group enterprise-card rounded-xl p-6 flex flex-col items-center justify-center gap-4 aspect-square cursor-pointer bg-white dark:bg-slate-800 shadow-sm'
|
||||
>
|
||||
<div className='w-16 h-16 rounded-2xl bg-slate-50 dark:bg-slate-700 flex items-center justify-center group-hover:scale-105 transition-transform duration-300'>
|
||||
<item.Icon
|
||||
size={40}
|
||||
className='text-slate-700 dark:text-slate-200'
|
||||
/>
|
||||
</div>
|
||||
<span className='text-slate-700 dark:text-slate-300 font-semibold group-hover:text-orange-600 dark:group-hover:text-orange-400 transition-colors'>
|
||||
{item.name}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className='mt-16 text-center'>
|
||||
<p className='text-slate-500 dark:text-slate-400 text-sm font-medium tracking-wide'>
|
||||
{t('AND MORE... 持续接入中')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Page 3: Comprehensive Capabilities - Clean Cards */}
|
||||
<section className='snap-start w-full min-h-full relative flex items-center justify-center overflow-hidden py-20 md:py-0 bg-slate-50 dark:bg-slate-900'>
|
||||
<div className='container mx-auto px-6 z-10 relative min-h-full flex flex-col justify-center'>
|
||||
<div className='text-center mb-16'>
|
||||
<h2 className='text-4xl md:text-5xl font-bold mb-6 text-slate-900 dark:text-white'>
|
||||
{t('全方位服务能力')}
|
||||
</h2>
|
||||
<p className='text-slate-600 dark:text-slate-400 text-lg max-w-2xl mx-auto'>
|
||||
{t('不仅仅是 API 转发,更是您 AI 应用的坚实后盾')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-7xl mx-auto w-full'>
|
||||
{capabilities.map((item, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className='enterprise-card p-8 rounded-xl group bg-white dark:bg-slate-800 shadow-sm hover:shadow-xl'
|
||||
>
|
||||
<div className='mb-6 inline-flex p-4 rounded-xl bg-orange-50 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400 group-hover:bg-orange-600 group-hover:text-white transition-colors duration-300'>
|
||||
{item.icon}
|
||||
</div>
|
||||
<h3 className='text-xl font-bold mb-3 text-slate-900 dark:text-white'>
|
||||
{item.title}
|
||||
</h3>
|
||||
<p className='text-slate-600 dark:text-slate-400 text-sm leading-relaxed'>
|
||||
{item.desc}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Page 4: User Experience Entry */}
|
||||
<section className='snap-start w-full min-h-full relative flex items-center justify-center overflow-hidden py-20 md:py-0 bg-white dark:bg-slate-950'>
|
||||
<div className='container mx-auto px-6 z-10 relative min-h-full flex flex-col justify-center text-center'>
|
||||
<h2 className='text-4xl md:text-5xl font-bold mb-8 text-slate-900 dark:text-white'>
|
||||
{t('深度体验 AI 能力')}
|
||||
</h2>
|
||||
<p className='text-xl text-slate-600 dark:text-slate-400 mb-12 max-w-2xl mx-auto'>
|
||||
{t(
|
||||
'直观感受大模型的强大,从视频生成到艺术创作,即刻开启您的 AI 之旅',
|
||||
)}
|
||||
</p>
|
||||
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-8 max-w-4xl mx-auto w-full'>
|
||||
<Link
|
||||
to='/experience-center/video-generation'
|
||||
className='group enterprise-card p-10 rounded-2xl bg-orange-50 dark:bg-orange-900/10 border-orange-100 dark:border-orange-800 hover:border-orange-500 transition-all'
|
||||
>
|
||||
<div className='mb-6 w-16 h-16 mx-auto bg-orange-100 dark:bg-orange-800 rounded-full flex items-center justify-center group-hover:scale-110 transition-transform'>
|
||||
<Video
|
||||
size={32}
|
||||
className='text-orange-600 dark:text-orange-300'
|
||||
/>
|
||||
</div>
|
||||
<h3 className='text-2xl font-bold mb-4 text-slate-900 dark:text-white'>
|
||||
{t('AI 视频生成')}
|
||||
</h3>
|
||||
<p className='text-slate-600 dark:text-slate-400'>
|
||||
{t('上传图片并输入提示词,生成动态视频')}
|
||||
</p>
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
to='/experience-center/image-generation'
|
||||
className='group enterprise-card p-10 rounded-2xl bg-rose-50 dark:bg-rose-900/10 border-rose-100 dark:border-rose-800 hover:border-rose-500 transition-all'
|
||||
>
|
||||
<div className='mb-6 w-16 h-16 mx-auto bg-rose-100 dark:bg-rose-800 rounded-full flex items-center justify-center group-hover:scale-110 transition-transform'>
|
||||
<Palette
|
||||
size={32}
|
||||
className='text-rose-600 dark:text-rose-300'
|
||||
/>
|
||||
</div>
|
||||
<h3 className='text-2xl font-bold mb-4 text-slate-900 dark:text-white'>
|
||||
{t('AI 艺术创作')}
|
||||
</h3>
|
||||
<p className='text-slate-600 dark:text-slate-400'>
|
||||
{t('激发无限创意,一键生成精美图像')}
|
||||
</p>
|
||||
</Link>
|
||||
</div>
|
||||
{weyaiDownloadEnabled && (
|
||||
<div className='mt-12 text-sm text-slate-500 dark:text-slate-400'>
|
||||
<Link
|
||||
to='/weyai/download'
|
||||
className='hover:text-brand-deep dark:hover:text-brand-from underline-offset-4 hover:underline'
|
||||
>
|
||||
{t('下载 WeyAi 桌面端')}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
) : (
|
||||
<div className='overflow-x-hidden w-full h-full'>
|
||||
{isUrl(homePageContent) ? (
|
||||
iframeError ? (
|
||||
// iframe 加载失败时显示备用界面
|
||||
<div className='w-full h-full flex flex-col items-center justify-center bg-gradient-to-br from-gray-50 via-white to-gray-100 dark:from-gray-950 dark:via-gray-900 dark:to-gray-950'>
|
||||
{/* 背景装饰 */}
|
||||
<div className='absolute inset-0 pointer-events-none overflow-hidden'>
|
||||
<div className='absolute -top-40 -right-40 w-96 h-96 bg-gradient-to-br from-brand-from/20 to-brand-to/20 rounded-full blur-3xl' />
|
||||
<div className='absolute -bottom-40 -left-40 w-96 h-96 bg-gradient-to-br from-pink-500/10 to-rose-500/10 rounded-full blur-3xl' />
|
||||
</div>
|
||||
|
||||
<div className='relative z-10 bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl rounded-3xl border border-gray-200/50 dark:border-gray-700/50 shadow-2xl p-12 max-w-lg text-center mx-4'>
|
||||
<div className='w-20 h-20 bg-gradient-to-br from-brand-from to-brand-to rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg shadow-brand/25'>
|
||||
<Network size={36} className='text-white' />
|
||||
</div>
|
||||
<h2 className='text-2xl font-bold text-gray-900 dark:text-white mb-3'>
|
||||
{t('访问外部首页')}
|
||||
</h2>
|
||||
<p className='text-gray-500 dark:text-gray-400 mb-6'>
|
||||
{t(
|
||||
'由于浏览器安全策略限制,无法直接嵌入显示。请点击下方按钮访问。',
|
||||
)}
|
||||
</p>
|
||||
<a
|
||||
href={homePageContent}
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='inline-flex items-center gap-2 px-8 py-4 bg-gradient-to-r from-brand-from to-brand-to hover:from-brand-from hover:to-brand-to text-white font-semibold rounded-2xl shadow-lg shadow-brand/25 hover:shadow-xl hover:-translate-y-0.5 transition-all duration-200'
|
||||
>
|
||||
<Rocket size={20} />
|
||||
{t('立即访问')}
|
||||
</a>
|
||||
<p className='mt-4 text-xs text-gray-400 dark:text-gray-500'>
|
||||
{homePageContent}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{iframeLoading && (
|
||||
<div className='absolute inset-0 flex items-center justify-center bg-white dark:bg-gray-900 z-10'>
|
||||
<div className='flex flex-col items-center gap-4'>
|
||||
<div className='w-12 h-12 border-4 border-brand/30 border-t-brand rounded-full animate-spin' />
|
||||
<p className='text-gray-500 dark:text-gray-400'>
|
||||
{t('正在加载...')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={homePageContent}
|
||||
className='w-full h-full border-none'
|
||||
title='Custom Home'
|
||||
onError={() => {
|
||||
if (iframeTimeoutRef.current) {
|
||||
clearTimeout(iframeTimeoutRef.current);
|
||||
}
|
||||
setIframeLoading(false);
|
||||
setIframeError(true);
|
||||
}}
|
||||
onLoad={handleIframeLoad}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<div
|
||||
className='mt-[60px] container mx-auto px-4'
|
||||
dangerouslySetInnerHTML={{ __html: homePageContent }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Home;
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import UsageLogsTable from '../../components/table/usage-logs';
|
||||
|
||||
const Token = () => (
|
||||
<div className='mt-[60px] px-2'>
|
||||
<UsageLogsTable />
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Token;
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import WeeLogo from '../components/common/logo/WeeLogo';
|
||||
import { Card, Typography } from '@douyinfe/semi-ui';
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
const LogoShowcase = () => {
|
||||
const logoStyles = [
|
||||
{
|
||||
name: 'minimalist',
|
||||
title: '极简线条',
|
||||
description: '简洁的线条设计,柔和的渐变动画,适合现代简约界面',
|
||||
bg: '#f5f5f5',
|
||||
textColor: '#333',
|
||||
},
|
||||
{
|
||||
name: 'modern',
|
||||
title: '现代圆润',
|
||||
description: '圆润的形状设计,浮动动画效果,适合友好亲和的界面',
|
||||
bg: '#ffffff',
|
||||
textColor: '#333',
|
||||
},
|
||||
{
|
||||
name: 'tech',
|
||||
title: '科技未来',
|
||||
description: '科技感强烈的发光效果,扫描线动画,适合科技创新主题',
|
||||
bg: '#0a0e27',
|
||||
textColor: '#5DADE2',
|
||||
},
|
||||
{
|
||||
name: 'wave',
|
||||
title: '波浪流动',
|
||||
description: '流畅的波浪效果,液态动画,适合创意动态的界面',
|
||||
bg: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
|
||||
textColor: '#ffffff',
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='min-h-screen p-8 bg-gradient-to-br from-slate-50 to-blue-50 dark:from-zinc-900 dark:to-zinc-800'>
|
||||
<div className='max-w-6xl mx-auto'>
|
||||
<div className='text-center mb-12'>
|
||||
<Title heading={1} className='!text-4xl !font-bold !mb-4'>
|
||||
WeeLogo 风格展示
|
||||
</Title>
|
||||
<Text className='text-lg text-gray-600 dark:text-gray-300'>
|
||||
选择最适合你的 Logo 风格
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<div className='grid grid-cols-1 md:grid-cols-2 gap-8 mb-12'>
|
||||
{logoStyles.map((style) => (
|
||||
<Card
|
||||
key={style.name}
|
||||
className='overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 hover:scale-105'
|
||||
bodyStyle={{ padding: 0 }}
|
||||
>
|
||||
<div
|
||||
className='flex flex-col items-center justify-center p-12'
|
||||
style={{
|
||||
background: style.bg,
|
||||
minHeight: '300px',
|
||||
}}
|
||||
>
|
||||
<WeeLogo style={style.name} size={64} />
|
||||
</div>
|
||||
<div className='p-6 bg-white dark:bg-zinc-800'>
|
||||
<Title heading={3} className='!text-xl !font-semibold !mb-2'>
|
||||
{style.title}
|
||||
</Title>
|
||||
<Text className='text-gray-600 dark:text-gray-300'>
|
||||
{style.description}
|
||||
</Text>
|
||||
<div className='mt-4 p-3 bg-slate-100 dark:bg-zinc-700 rounded font-mono text-sm'>
|
||||
{'<WeeLogo style="' + style.name + '" size={64} />'}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Card className='p-8 bg-white dark:bg-zinc-800 shadow-lg'>
|
||||
<Title heading={2} className='!text-2xl !font-bold !mb-6'>
|
||||
使用方法
|
||||
</Title>
|
||||
|
||||
<div className='space-y-6'>
|
||||
<div>
|
||||
<Title heading={4} className='!text-lg !font-semibold !mb-3'>
|
||||
1. 导入组件
|
||||
</Title>
|
||||
<div className='p-4 bg-slate-100 dark:bg-zinc-700 rounded font-mono text-sm overflow-x-auto'>
|
||||
{"import WeeLogo from './components/common/logo/WeeLogo';"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Title heading={4} className='!text-lg !font-semibold !mb-3'>
|
||||
2. 在 HeaderLogo 中使用
|
||||
</Title>
|
||||
<div className='p-4 bg-slate-100 dark:bg-zinc-700 rounded font-mono text-sm overflow-x-auto whitespace-pre'>
|
||||
{`<HeaderLogo
|
||||
useSvgLogo={true} // 启用 SVG logo
|
||||
logoStyle="minimalist" // 选择风格
|
||||
// ... 其他 props
|
||||
/>`}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Title heading={4} className='!text-lg !font-semibold !mb-3'>
|
||||
3. 直接使用
|
||||
</Title>
|
||||
<div className='p-4 bg-slate-100 dark:bg-zinc-700 rounded font-mono text-sm overflow-x-auto'>
|
||||
{'<WeeLogo style="tech" size={48} />'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='mt-8 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded'>
|
||||
<Text className='text-blue-800 dark:text-blue-200'>
|
||||
💡 提示: 更多详细信息请查看{' '}
|
||||
<code className='px-2 py-1 bg-blue-100 dark:bg-blue-900 rounded'>
|
||||
web/src/components/common/logo/README.md
|
||||
</code>
|
||||
</Text>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<div className='mt-8 text-center'>
|
||||
<Text className='text-gray-500 dark:text-gray-400'>
|
||||
所有 Logo 风格都支持平滑的动画效果和响应式设计
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LogoShowcase;
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import MjLogsTable from '../../components/table/mj-logs';
|
||||
|
||||
const Midjourney = () => (
|
||||
<div className='mt-[60px] px-2'>
|
||||
<MjLogsTable />
|
||||
</div>
|
||||
);
|
||||
|
||||
export default Midjourney;
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React from 'react';
|
||||
import ModelsTable from '../../components/table/models';
|
||||
|
||||
const ModelPage = () => {
|
||||
return (
|
||||
<div className='mt-[60px] px-2'>
|
||||
<ModelsTable />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ModelPage;
|
||||
@@ -0,0 +1,776 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Card, Row, Col, Table, Spin } from '@douyinfe/semi-ui';
|
||||
import {
|
||||
TrendingUp,
|
||||
DollarSign,
|
||||
Activity,
|
||||
Layers,
|
||||
BarChart3,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// 模拟管理员监控数据
|
||||
const generateMockAdminData = () => {
|
||||
const channels = [
|
||||
'OpenAI GPT-4',
|
||||
'Claude 3.5 Sonnet',
|
||||
'Gemini Pro',
|
||||
'DeepSeek V3',
|
||||
'Qwen Plus',
|
||||
];
|
||||
|
||||
// 生成24小时请求趋势
|
||||
const requestTrend = Array.from({ length: 24 }, (_, i) => ({
|
||||
hour: `${i}:00`,
|
||||
requests: Math.floor(Math.random() * 1000) + 500,
|
||||
}));
|
||||
|
||||
// 生成Token消耗趋势
|
||||
const tokenTrend = Array.from({ length: 12 }, (_, i) => ({
|
||||
time: `${i * 2}:00`,
|
||||
promptTokens: Math.floor(Math.random() * 50000) + 30000,
|
||||
completionTokens: Math.floor(Math.random() * 40000) + 20000,
|
||||
}));
|
||||
|
||||
// 成本分布
|
||||
const costDistribution = channels.map((name) => ({
|
||||
name,
|
||||
cost: Math.random() * 500 + 100,
|
||||
percentage: 0,
|
||||
}));
|
||||
|
||||
const totalCost = costDistribution.reduce((sum, item) => sum + item.cost, 0);
|
||||
costDistribution.forEach((item) => {
|
||||
item.percentage = ((item.cost / totalCost) * 100).toFixed(1);
|
||||
});
|
||||
|
||||
// 错误类型分布
|
||||
const errorTypes = [
|
||||
{ type: '速率超限 (Rate Limit)', count: 156 },
|
||||
{ type: '认证失败 (Auth Failed)', count: 89 },
|
||||
{ type: '超时 (Timeout)', count: 67 },
|
||||
{ type: '配额不足 (Quota Exceeded)', count: 45 },
|
||||
{ type: '模型不可用 (Model Unavailable)', count: 23 },
|
||||
];
|
||||
|
||||
// 渠道详细数据
|
||||
const channelDetails = channels.map((name, index) => ({
|
||||
id: index + 1,
|
||||
name,
|
||||
requests: Math.floor(Math.random() * 5000) + 1000,
|
||||
avgResponseTime: Math.floor(Math.random() * 800) + 200,
|
||||
tokens: Math.floor(Math.random() * 100000) + 50000,
|
||||
cost: costDistribution[index].cost.toFixed(2),
|
||||
successRate: (95 + Math.random() * 5).toFixed(2),
|
||||
}));
|
||||
|
||||
return {
|
||||
kpi: {
|
||||
totalRequests: requestTrend.reduce((sum, item) => sum + item.requests, 0),
|
||||
totalCost: totalCost.toFixed(2),
|
||||
activeChannels: channels.length,
|
||||
avgResponseTime: Math.floor(Math.random() * 300) + 200,
|
||||
},
|
||||
requestTrend,
|
||||
tokenTrend,
|
||||
costDistribution,
|
||||
errorTypes,
|
||||
channelDetails,
|
||||
quotaUsage: 73,
|
||||
};
|
||||
};
|
||||
|
||||
const AdminMonitor = () => {
|
||||
const { t } = useTranslation();
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
setData(generateMockAdminData());
|
||||
setLoading(false);
|
||||
}, 1000);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setData(generateMockAdminData());
|
||||
}, 30000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const renderKPICard = (
|
||||
icon,
|
||||
label,
|
||||
value,
|
||||
suffix = '',
|
||||
color = '#1890ff',
|
||||
) => (
|
||||
<Card
|
||||
style={{
|
||||
background:
|
||||
'linear-gradient(135deg, rgba(24, 144, 255, 0.05) 0%, rgba(24, 144, 255, 0.01) 100%)',
|
||||
border: '1px solid var(--semi-color-border)',
|
||||
borderRadius: '12px',
|
||||
height: '100%',
|
||||
}}
|
||||
bodyStyle={{ padding: '24px' }}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
|
||||
<div
|
||||
style={{
|
||||
width: '48px',
|
||||
height: '48px',
|
||||
borderRadius: '12px',
|
||||
background: `${color}15`,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{React.cloneElement(icon, { size: 24, color })}
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: '13px',
|
||||
color: 'var(--semi-color-text-2)',
|
||||
marginBottom: '4px',
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: '28px',
|
||||
fontWeight: 700,
|
||||
color: 'var(--semi-color-text-0)',
|
||||
lineHeight: 1,
|
||||
}}
|
||||
>
|
||||
{value}
|
||||
{suffix && (
|
||||
<span
|
||||
style={{ fontSize: '16px', fontWeight: 500, marginLeft: '4px' }}
|
||||
>
|
||||
{suffix}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
|
||||
const renderBarChart = (data, maxValue) => {
|
||||
return data.slice(0, 12).map((item, index) => {
|
||||
const percentage = (item.requests / maxValue) * 100;
|
||||
return (
|
||||
<div key={index} style={{ marginBottom: '12px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: '4px',
|
||||
fontSize: '12px',
|
||||
color: 'var(--semi-color-text-2)',
|
||||
}}
|
||||
>
|
||||
<span>{item.hour}</span>
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
{item.requests.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
height: '24px',
|
||||
background: 'var(--semi-color-fill-0)',
|
||||
borderRadius: '6px',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
height: '100%',
|
||||
width: `${percentage}%`,
|
||||
background: 'linear-gradient(90deg, #1890ff 0%, #40a9ff 100%)',
|
||||
borderRadius: '6px',
|
||||
transition: 'width 0.6s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const renderStackedAreaChart = (data) => {
|
||||
const maxTotal = Math.max(
|
||||
...data.map((d) => d.promptTokens + d.completionTokens),
|
||||
);
|
||||
|
||||
return (
|
||||
<div style={{ height: '200px', position: 'relative' }}>
|
||||
<svg
|
||||
width='100%'
|
||||
height='100%'
|
||||
viewBox='0 0 100 100'
|
||||
preserveAspectRatio='none'
|
||||
>
|
||||
<defs>
|
||||
<linearGradient
|
||||
id='promptGradient'
|
||||
x1='0%'
|
||||
y1='0%'
|
||||
x2='0%'
|
||||
y2='100%'
|
||||
>
|
||||
<stop
|
||||
offset='0%'
|
||||
style={{ stopColor: '#52c41a', stopOpacity: 0.6 }}
|
||||
/>
|
||||
<stop
|
||||
offset='100%'
|
||||
style={{ stopColor: '#52c41a', stopOpacity: 0.1 }}
|
||||
/>
|
||||
</linearGradient>
|
||||
<linearGradient
|
||||
id='completionGradient'
|
||||
x1='0%'
|
||||
y1='0%'
|
||||
x2='0%'
|
||||
y2='100%'
|
||||
>
|
||||
<stop
|
||||
offset='0%'
|
||||
style={{ stopColor: '#1890ff', stopOpacity: 0.6 }}
|
||||
/>
|
||||
<stop
|
||||
offset='100%'
|
||||
style={{ stopColor: '#1890ff', stopOpacity: 0.1 }}
|
||||
/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<polyline
|
||||
fill='url(#completionGradient)'
|
||||
stroke='#1890ff'
|
||||
strokeWidth='0.5'
|
||||
points={data
|
||||
.map((d, i) => {
|
||||
const x = (i / (data.length - 1)) * 100;
|
||||
const y = 100 - (d.completionTokens / maxTotal) * 100;
|
||||
return `${x},${y}`;
|
||||
})
|
||||
.join(' ')}
|
||||
/>
|
||||
<polyline
|
||||
fill='url(#promptGradient)'
|
||||
stroke='#52c41a'
|
||||
strokeWidth='0.5'
|
||||
points={data
|
||||
.map((d, i) => {
|
||||
const x = (i / (data.length - 1)) * 100;
|
||||
const total = d.promptTokens + d.completionTokens;
|
||||
const y = 100 - (total / maxTotal) * 100;
|
||||
return `${x},${y}`;
|
||||
})
|
||||
.join(' ')}
|
||||
/>
|
||||
</svg>
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '8px',
|
||||
right: '8px',
|
||||
display: 'flex',
|
||||
gap: '12px',
|
||||
fontSize: '12px',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<div
|
||||
style={{
|
||||
width: '12px',
|
||||
height: '12px',
|
||||
background: '#52c41a',
|
||||
borderRadius: '2px',
|
||||
}}
|
||||
/>
|
||||
<span>Prompt</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
|
||||
<div
|
||||
style={{
|
||||
width: '12px',
|
||||
height: '12px',
|
||||
background: '#1890ff',
|
||||
borderRadius: '2px',
|
||||
}}
|
||||
/>
|
||||
<span>Completion</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderDonutChart = (data) => {
|
||||
const total = data.reduce((sum, item) => sum + item.cost, 0);
|
||||
const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1'];
|
||||
|
||||
let currentAngle = -90;
|
||||
const segments = data.map((item, index) => {
|
||||
const percentage = item.cost / total;
|
||||
const angle = percentage * 360;
|
||||
const startAngle = currentAngle;
|
||||
const endAngle = currentAngle + angle;
|
||||
currentAngle = endAngle;
|
||||
|
||||
const startRad = (startAngle * Math.PI) / 180;
|
||||
const endRad = (endAngle * Math.PI) / 180;
|
||||
|
||||
const x1 = 50 + 40 * Math.cos(startRad);
|
||||
const y1 = 50 + 40 * Math.sin(startRad);
|
||||
const x2 = 50 + 40 * Math.cos(endRad);
|
||||
const y2 = 50 + 40 * Math.sin(endRad);
|
||||
|
||||
const largeArc = angle > 180 ? 1 : 0;
|
||||
|
||||
return {
|
||||
d: `M 50 50 L ${x1} ${y1} A 40 40 0 ${largeArc} 1 ${x2} ${y2} Z`,
|
||||
color: colors[index % colors.length],
|
||||
...item,
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div>
|
||||
<svg width='100%' height='200' viewBox='0 0 100 100'>
|
||||
<circle
|
||||
cx='50'
|
||||
cy='50'
|
||||
r='40'
|
||||
fill='none'
|
||||
stroke='var(--semi-color-fill-0)'
|
||||
strokeWidth='0.5'
|
||||
/>
|
||||
{segments.map((segment, index) => (
|
||||
<path
|
||||
key={index}
|
||||
d={segment.d}
|
||||
fill={segment.color}
|
||||
opacity='0.85'
|
||||
/>
|
||||
))}
|
||||
<circle cx='50' cy='50' r='20' fill='var(--semi-color-bg-1)' />
|
||||
</svg>
|
||||
<div style={{ marginTop: '16px' }}>
|
||||
{segments.map((segment, index) => (
|
||||
<div
|
||||
key={index}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: '8px',
|
||||
fontSize: '12px',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: '12px',
|
||||
height: '12px',
|
||||
background: segment.color,
|
||||
borderRadius: '2px',
|
||||
}}
|
||||
/>
|
||||
<span>{segment.name}</span>
|
||||
</div>
|
||||
<span style={{ fontWeight: 600 }}>
|
||||
${segment.cost.toFixed(2)} ({segment.percentage}%)
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderGaugeChart = (percentage) => {
|
||||
const color =
|
||||
percentage >= 90
|
||||
? 'var(--semi-color-danger)'
|
||||
: percentage >= 75
|
||||
? 'var(--semi-color-warning)'
|
||||
: 'var(--semi-color-success)';
|
||||
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: '20px 0' }}>
|
||||
<svg width='100%' height='120' viewBox='0 0 100 60'>
|
||||
<path
|
||||
d='M 10 50 A 40 40 0 0 1 90 50'
|
||||
fill='none'
|
||||
stroke='var(--semi-color-fill-0)'
|
||||
strokeWidth='8'
|
||||
strokeLinecap='round'
|
||||
/>
|
||||
<path
|
||||
d='M 10 50 A 40 40 0 0 1 90 50'
|
||||
fill='none'
|
||||
stroke={color}
|
||||
strokeWidth='8'
|
||||
strokeLinecap='round'
|
||||
strokeDasharray={`${percentage * 1.256} 125.6`}
|
||||
/>
|
||||
<text
|
||||
x='50'
|
||||
y='45'
|
||||
textAnchor='middle'
|
||||
style={{
|
||||
fontSize: '18px',
|
||||
fontWeight: 700,
|
||||
fill: 'var(--semi-color-text-0)',
|
||||
}}
|
||||
>
|
||||
{percentage}%
|
||||
</text>
|
||||
</svg>
|
||||
<div
|
||||
style={{
|
||||
marginTop: '8px',
|
||||
fontSize: '12px',
|
||||
color: 'var(--semi-color-text-2)',
|
||||
}}
|
||||
>
|
||||
{percentage >= 90 && t('配额即将用尽')}
|
||||
{percentage >= 75 && percentage < 90 && t('配额使用偏高')}
|
||||
{percentage < 75 && t('配额正常')}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderHorizontalBar = (data) => {
|
||||
const maxCount = Math.max(...data.map((d) => d.count));
|
||||
|
||||
return data.map((item, index) => {
|
||||
const percentage = (item.count / maxCount) * 100;
|
||||
return (
|
||||
<div key={index} style={{ marginBottom: '16px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: '6px',
|
||||
fontSize: '13px',
|
||||
}}
|
||||
>
|
||||
<span style={{ color: 'var(--semi-color-text-1)' }}>
|
||||
{item.type}
|
||||
</span>
|
||||
<span
|
||||
style={{ fontWeight: 600, color: 'var(--semi-color-text-0)' }}
|
||||
>
|
||||
{item.count}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
height: '20px',
|
||||
background: 'var(--semi-color-fill-0)',
|
||||
borderRadius: '10px',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
height: '100%',
|
||||
width: `${percentage}%`,
|
||||
background: 'linear-gradient(90deg, #ff4d4f 0%, #ff7875 100%)',
|
||||
borderRadius: '10px',
|
||||
transition: 'width 0.6s cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('渠道名称'),
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 180,
|
||||
render: (text) => <strong>{text}</strong>,
|
||||
},
|
||||
{
|
||||
title: t('请求数'),
|
||||
dataIndex: 'requests',
|
||||
key: 'requests',
|
||||
sorter: (a, b) => a.requests - b.requests,
|
||||
render: (text) => text.toLocaleString(),
|
||||
},
|
||||
{
|
||||
title: t('平均响应时间 (ms)'),
|
||||
dataIndex: 'avgResponseTime',
|
||||
key: 'avgResponseTime',
|
||||
sorter: (a, b) => a.avgResponseTime - b.avgResponseTime,
|
||||
render: (text) => (
|
||||
<span
|
||||
style={{
|
||||
color:
|
||||
text > 500
|
||||
? 'var(--semi-color-danger)'
|
||||
: 'var(--semi-color-success)',
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('Token消耗'),
|
||||
dataIndex: 'tokens',
|
||||
key: 'tokens',
|
||||
sorter: (a, b) => a.tokens - b.tokens,
|
||||
render: (text) => text.toLocaleString(),
|
||||
},
|
||||
{
|
||||
title: t('成本 (¥)'),
|
||||
dataIndex: 'cost',
|
||||
key: 'cost',
|
||||
sorter: (a, b) => parseFloat(a.cost) - parseFloat(b.cost),
|
||||
render: (text) => `¥${text}`,
|
||||
},
|
||||
{
|
||||
title: t('成功率 (%)'),
|
||||
dataIndex: 'successRate',
|
||||
key: 'successRate',
|
||||
sorter: (a, b) => parseFloat(a.successRate) - parseFloat(b.successRate),
|
||||
render: (text) => {
|
||||
const rate = parseFloat(text);
|
||||
return (
|
||||
<span
|
||||
style={{
|
||||
color:
|
||||
rate >= 99
|
||||
? 'var(--semi-color-success)'
|
||||
: rate >= 95
|
||||
? 'var(--semi-color-warning)'
|
||||
: 'var(--semi-color-danger)',
|
||||
}}
|
||||
>
|
||||
{text}%
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: '60px 0' }}>
|
||||
<Spin size='large' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='admin-monitor'>
|
||||
<style>
|
||||
{`
|
||||
.admin-monitor .semi-card {
|
||||
transition: all 0.3s;
|
||||
}
|
||||
|
||||
.admin-monitor .semi-card:hover {
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.chart-card {
|
||||
border: 1px solid var(--semi-color-border);
|
||||
borderRadius: 12px;
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
|
||||
<Col xs={24} sm={12} lg={6}>
|
||||
{renderKPICard(
|
||||
<TrendingUp />,
|
||||
t('过去24小时总请求'),
|
||||
data.kpi.totalRequests.toLocaleString(),
|
||||
'',
|
||||
'#1890ff',
|
||||
)}
|
||||
</Col>
|
||||
<Col xs={24} sm={12} lg={6}>
|
||||
{renderKPICard(
|
||||
<DollarSign />,
|
||||
t('今日预估总成本'),
|
||||
data.kpi.totalCost,
|
||||
'¥',
|
||||
'#52c41a',
|
||||
)}
|
||||
</Col>
|
||||
<Col xs={24} sm={12} lg={6}>
|
||||
{renderKPICard(
|
||||
<Layers />,
|
||||
t('当前活跃渠道'),
|
||||
data.kpi.activeChannels,
|
||||
'',
|
||||
'#722ed1',
|
||||
)}
|
||||
</Col>
|
||||
<Col xs={24} sm={12} lg={6}>
|
||||
{renderKPICard(
|
||||
<Activity />,
|
||||
t('平均响应时间'),
|
||||
data.kpi.avgResponseTime,
|
||||
'ms',
|
||||
'#faad14',
|
||||
)}
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
className='chart-card'
|
||||
title={
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<BarChart3 size={18} />
|
||||
<span>{t('请求趋势')} (24h)</span>
|
||||
</div>
|
||||
}
|
||||
bodyStyle={{ padding: '20px' }}
|
||||
>
|
||||
{renderBarChart(
|
||||
data.requestTrend,
|
||||
Math.max(...data.requestTrend.map((d) => d.requests)),
|
||||
)}
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
className='chart-card'
|
||||
title={
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<DollarSign size={18} />
|
||||
<span>{t('成本分布')}</span>
|
||||
</div>
|
||||
}
|
||||
bodyStyle={{ padding: '20px' }}
|
||||
>
|
||||
{renderDonutChart(data.costDistribution)}
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
className='chart-card'
|
||||
title={
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<Activity size={18} />
|
||||
<span>{t('Token消耗趋势')} (24h)</span>
|
||||
</div>
|
||||
}
|
||||
bodyStyle={{ padding: '20px' }}
|
||||
>
|
||||
{renderStackedAreaChart(data.tokenTrend)}
|
||||
</Card>
|
||||
</Col>
|
||||
<Col xs={24} lg={12}>
|
||||
<Card
|
||||
className='chart-card'
|
||||
title={
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<Layers size={18} />
|
||||
<span>{t('配额使用情况')}</span>
|
||||
</div>
|
||||
}
|
||||
bodyStyle={{ padding: '20px' }}
|
||||
>
|
||||
{renderGaugeChart(data.quotaUsage)}
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
|
||||
<Col span={24}>
|
||||
<Card
|
||||
className='chart-card'
|
||||
title={
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<AlertTriangle size={18} />
|
||||
<span>{t('错误类型分布')} (24h)</span>
|
||||
</div>
|
||||
}
|
||||
bodyStyle={{ padding: '20px' }}
|
||||
>
|
||||
{renderHorizontalBar(data.errorTypes)}
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
<Col span={24}>
|
||||
<Card
|
||||
className='chart-card'
|
||||
title={
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
|
||||
>
|
||||
<BarChart3 size={18} />
|
||||
<span>{t('渠道详细数据')}</span>
|
||||
</div>
|
||||
}
|
||||
bodyStyle={{ padding: 0 }}
|
||||
>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={data.channelDetails}
|
||||
pagination={false}
|
||||
rowKey='id'
|
||||
/>
|
||||
</Card>
|
||||
</Col>
|
||||
</Row>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminMonitor;
|
||||
@@ -0,0 +1,478 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Card, Row, Col, Badge, Empty, Spin } from '@douyinfe/semi-ui';
|
||||
import { Activity, Zap } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
// 模拟渠道数据
|
||||
const generateMockChannels = () => {
|
||||
const channelNames = [
|
||||
'OpenAI GPT-4',
|
||||
'Claude 3.5 Sonnet',
|
||||
'Gemini Pro',
|
||||
'DeepSeek V3',
|
||||
'Qwen Plus',
|
||||
'Moonshot AI',
|
||||
'GLM-4',
|
||||
'Doubao Pro',
|
||||
];
|
||||
|
||||
const statuses = ['available', 'available', 'available', 'busy', 'disabled'];
|
||||
const speedLevels = ['fast', 'fast', 'medium', 'slow'];
|
||||
|
||||
return channelNames.map((name, index) => {
|
||||
const status = statuses[Math.floor(Math.random() * statuses.length)];
|
||||
const speed = speedLevels[Math.floor(Math.random() * speedLevels.length)];
|
||||
|
||||
// 生成稳定性趋势数据(24小时)
|
||||
const stability = Array.from({ length: 24 }, () =>
|
||||
status === 'available'
|
||||
? 85 + Math.random() * 15 // 85-100%
|
||||
: status === 'busy'
|
||||
? 60 + Math.random() * 25 // 60-85%
|
||||
: 0,
|
||||
);
|
||||
|
||||
return {
|
||||
id: index + 1,
|
||||
name,
|
||||
status,
|
||||
speed,
|
||||
speedMs:
|
||||
speed === 'fast'
|
||||
? 200 + Math.random() * 300
|
||||
: speed === 'medium'
|
||||
? 500 + Math.random() * 500
|
||||
: 1000 + Math.random() * 1000,
|
||||
stability,
|
||||
uptime:
|
||||
status === 'available'
|
||||
? 99.5 + Math.random() * 0.5
|
||||
: status === 'busy'
|
||||
? 95 + Math.random() * 4
|
||||
: 0,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const ChannelMonitor = () => {
|
||||
const { t } = useTranslation();
|
||||
const [channels, setChannels] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
// 模拟数据加载
|
||||
setTimeout(() => {
|
||||
setChannels(generateMockChannels());
|
||||
setLoading(false);
|
||||
}, 800);
|
||||
|
||||
// 每30秒刷新一次数据
|
||||
const interval = setInterval(() => {
|
||||
setChannels(generateMockChannels());
|
||||
}, 30000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const getStatusConfig = (status) => {
|
||||
const configs = {
|
||||
available: {
|
||||
color: 'var(--semi-color-success)',
|
||||
bgColor: 'rgba(82, 196, 26, 0.1)',
|
||||
text: t('可用'),
|
||||
dotColor: 'success',
|
||||
},
|
||||
busy: {
|
||||
color: 'var(--semi-color-warning)',
|
||||
bgColor: 'rgba(250, 173, 20, 0.1)',
|
||||
text: t('繁忙'),
|
||||
dotColor: 'warning',
|
||||
},
|
||||
unavailable: {
|
||||
color: 'var(--semi-color-danger)',
|
||||
bgColor: 'rgba(255, 77, 79, 0.1)',
|
||||
text: t('不可用'),
|
||||
dotColor: 'danger',
|
||||
},
|
||||
disabled: {
|
||||
color: '#8c8c8c',
|
||||
bgColor: 'rgba(140, 140, 140, 0.1)',
|
||||
text: t('已关闭'),
|
||||
dotColor: 'tertiary',
|
||||
},
|
||||
};
|
||||
return configs[status] || configs.disabled;
|
||||
};
|
||||
|
||||
const getSpeedConfig = (speed) => {
|
||||
const configs = {
|
||||
fast: {
|
||||
color: 'var(--semi-color-success)',
|
||||
width: '85%',
|
||||
text: t('快'),
|
||||
gradient:
|
||||
'linear-gradient(90deg, var(--semi-color-success) 0%, #95de64 100%)',
|
||||
},
|
||||
medium: {
|
||||
color: 'var(--semi-color-warning)',
|
||||
width: '60%',
|
||||
text: t('中等'),
|
||||
gradient:
|
||||
'linear-gradient(90deg, var(--semi-color-warning) 0%, #ffd666 100%)',
|
||||
},
|
||||
slow: {
|
||||
color: 'var(--semi-color-danger)',
|
||||
width: '35%',
|
||||
text: t('慢'),
|
||||
gradient:
|
||||
'linear-gradient(90deg, var(--semi-color-danger) 0%, #ff7875 100%)',
|
||||
},
|
||||
};
|
||||
return configs[speed] || configs.medium;
|
||||
};
|
||||
|
||||
const renderSparkline = (data) => {
|
||||
if (!data || data.length === 0) return null;
|
||||
|
||||
const max = Math.max(...data);
|
||||
const min = Math.min(...data);
|
||||
const range = max - min || 1;
|
||||
|
||||
const points = data
|
||||
.map((value, index) => {
|
||||
const x = (index / (data.length - 1)) * 100;
|
||||
const y = 100 - ((value - min) / range) * 100;
|
||||
return `${x},${y}`;
|
||||
})
|
||||
.join(' ');
|
||||
|
||||
const avgStability = data.reduce((a, b) => a + b, 0) / data.length;
|
||||
const lineColor =
|
||||
avgStability >= 95
|
||||
? 'var(--semi-color-success)'
|
||||
: avgStability >= 85
|
||||
? 'var(--semi-color-warning)'
|
||||
: 'var(--semi-color-danger)';
|
||||
|
||||
return (
|
||||
<svg
|
||||
width='100%'
|
||||
height='40'
|
||||
viewBox='0 0 100 100'
|
||||
preserveAspectRatio='none'
|
||||
style={{ display: 'block' }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient
|
||||
id={`gradient-${data[0]}`}
|
||||
x1='0%'
|
||||
y1='0%'
|
||||
x2='0%'
|
||||
y2='100%'
|
||||
>
|
||||
<stop
|
||||
offset='0%'
|
||||
style={{ stopColor: lineColor, stopOpacity: 0.3 }}
|
||||
/>
|
||||
<stop
|
||||
offset='100%'
|
||||
style={{ stopColor: lineColor, stopOpacity: 0 }}
|
||||
/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<polyline
|
||||
fill={`url(#gradient-${data[0]})`}
|
||||
stroke='none'
|
||||
points={`0,100 ${points} 100,100`}
|
||||
/>
|
||||
<polyline
|
||||
fill='none'
|
||||
stroke={lineColor}
|
||||
strokeWidth='2'
|
||||
points={points}
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: '60px 0' }}>
|
||||
<Spin size='large' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (channels.length === 0) {
|
||||
return <Empty description={t('暂无渠道数据')} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='channel-monitor'>
|
||||
<style>
|
||||
{`
|
||||
.channel-card {
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
border: 1px solid var(--semi-color-border);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.channel-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
|
||||
border-color: var(--semi-color-primary);
|
||||
}
|
||||
|
||||
.channel-card::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 3px;
|
||||
background: linear-gradient(90deg, var(--semi-color-primary) 0%, var(--semi-color-primary-light-default) 100%);
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s;
|
||||
}
|
||||
|
||||
.channel-card:hover::before {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.speed-bar-container {
|
||||
position: relative;
|
||||
height: 24px;
|
||||
background: var(--semi-color-fill-0);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.speed-bar {
|
||||
height: 100%;
|
||||
border-radius: 12px;
|
||||
transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.metric-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.metric-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
background: var(--semi-color-fill-0);
|
||||
}
|
||||
|
||||
.metric-value {
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: var(--semi-color-text-0);
|
||||
}
|
||||
|
||||
.metric-label {
|
||||
font-size: 12px;
|
||||
color: var(--semi-color-text-2);
|
||||
}
|
||||
`}
|
||||
</style>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
{channels.map((channel) => {
|
||||
const statusConfig = getStatusConfig(channel.status);
|
||||
const speedConfig = getSpeedConfig(channel.speed);
|
||||
|
||||
return (
|
||||
<Col key={channel.id} xs={24} sm={12} lg={8} xl={6}>
|
||||
<Card
|
||||
className='channel-card'
|
||||
bodyStyle={{ padding: '20px' }}
|
||||
style={{ height: '100%' }}
|
||||
>
|
||||
{/* 渠道名称和状态 */}
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: '8px',
|
||||
}}
|
||||
>
|
||||
<h4
|
||||
style={{
|
||||
margin: 0,
|
||||
fontSize: '16px',
|
||||
fontWeight: 600,
|
||||
color: 'var(--semi-color-text-0)',
|
||||
}}
|
||||
>
|
||||
{channel.name}
|
||||
</h4>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
padding: '4px 12px',
|
||||
borderRadius: '12px',
|
||||
fontSize: '12px',
|
||||
fontWeight: 500,
|
||||
color: statusConfig.color,
|
||||
backgroundColor: statusConfig.bgColor,
|
||||
border: `1px solid ${statusConfig.color}30`,
|
||||
}}
|
||||
>
|
||||
<Badge
|
||||
dot
|
||||
type={statusConfig.dotColor}
|
||||
style={{ marginRight: '6px' }}
|
||||
/>
|
||||
{statusConfig.text}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 响应速度 */}
|
||||
<div style={{ marginBottom: '16px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: '8px',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
fontSize: '13px',
|
||||
fontWeight: 500,
|
||||
color: 'var(--semi-color-text-1)',
|
||||
}}
|
||||
>
|
||||
<Zap
|
||||
size={14}
|
||||
style={{ marginRight: '4px', verticalAlign: 'middle' }}
|
||||
/>
|
||||
{t('响应速度')}
|
||||
</span>
|
||||
<span
|
||||
style={{
|
||||
fontSize: '12px',
|
||||
color: 'var(--semi-color-text-2)',
|
||||
}}
|
||||
>
|
||||
{Math.round(channel.speedMs)}ms
|
||||
</span>
|
||||
</div>
|
||||
<div className='speed-bar-container'>
|
||||
<div
|
||||
className='speed-bar'
|
||||
style={{
|
||||
width: speedConfig.width,
|
||||
background: speedConfig.gradient,
|
||||
}}
|
||||
>
|
||||
{speedConfig.text}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 稳定性趋势 */}
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: '8px',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
fontSize: '13px',
|
||||
fontWeight: 500,
|
||||
color: 'var(--semi-color-text-1)',
|
||||
}}
|
||||
>
|
||||
<Activity
|
||||
size={14}
|
||||
style={{ marginRight: '4px', verticalAlign: 'middle' }}
|
||||
/>
|
||||
{t('稳定性')} (24h)
|
||||
</span>
|
||||
<span
|
||||
style={{
|
||||
fontSize: '12px',
|
||||
fontWeight: 600,
|
||||
color:
|
||||
channel.uptime >= 99
|
||||
? 'var(--semi-color-success)'
|
||||
: channel.uptime >= 95
|
||||
? 'var(--semi-color-warning)'
|
||||
: 'var(--semi-color-danger)',
|
||||
}}
|
||||
>
|
||||
{channel.uptime.toFixed(2)}%
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--semi-color-fill-0)',
|
||||
borderRadius: '8px',
|
||||
padding: '8px',
|
||||
}}
|
||||
>
|
||||
{renderSparkline(channel.stability)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</Col>
|
||||
);
|
||||
})}
|
||||
</Row>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChannelMonitor;
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Tabs, Card } from '@douyinfe/semi-ui';
|
||||
import { Activity, Shield } from 'lucide-react';
|
||||
import ChannelMonitor from './ChannelMonitor';
|
||||
import AdminMonitor from './AdminMonitor';
|
||||
|
||||
const MonitorCenter = () => {
|
||||
const [activeTab, setActiveTab] = useState('channel');
|
||||
const [userRole, setUserRole] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const raw = localStorage.getItem('user');
|
||||
if (raw) {
|
||||
try {
|
||||
const user = JSON.parse(raw);
|
||||
setUserRole(user.role || 0);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse user data:', e);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const isAdmin = userRole >= 10;
|
||||
|
||||
return (
|
||||
<div className='mt-[60px] px-2 md:px-6 pb-8'>
|
||||
<div className='max-w-[1600px] mx-auto'>
|
||||
{/* 页面标题 */}
|
||||
<div className='mb-6'>
|
||||
<h1 className='text-3xl font-bold flex items-center gap-3'>
|
||||
<div className='w-10 h-10 rounded-lg bg-gradient-to-br from-blue-500 to-brand-to flex items-center justify-center'>
|
||||
<Activity className='w-6 h-6 text-white' />
|
||||
</div>
|
||||
监控中心
|
||||
</h1>
|
||||
<p className='text-gray-500 mt-2 ml-[52px]'>
|
||||
实时监控渠道状态与系统性能指标
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 标签页 */}
|
||||
<Card className='shadow-lg'>
|
||||
<Tabs
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
type='line'
|
||||
size='large'
|
||||
>
|
||||
<Tabs.TabPane
|
||||
tab={
|
||||
<span className='flex items-center gap-2'>
|
||||
<Activity className='w-4 h-4' />
|
||||
渠道监控
|
||||
</span>
|
||||
}
|
||||
itemKey='channel'
|
||||
>
|
||||
<ChannelMonitor />
|
||||
</Tabs.TabPane>
|
||||
|
||||
{isAdmin && (
|
||||
<Tabs.TabPane
|
||||
tab={
|
||||
<span className='flex items-center gap-2'>
|
||||
<Shield className='w-4 h-4' />
|
||||
管理监控
|
||||
</span>
|
||||
}
|
||||
itemKey='admin'
|
||||
>
|
||||
<AdminMonitor />
|
||||
</Tabs.TabPane>
|
||||
)}
|
||||
</Tabs>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MonitorCenter;
|
||||
@@ -0,0 +1,236 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React from 'react';
|
||||
import {
|
||||
Card,
|
||||
Grid,
|
||||
Typography,
|
||||
Tag,
|
||||
Progress,
|
||||
Empty,
|
||||
Button,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { IconRefresh, IconAlertCircle } from '@douyinfe/semi-icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const { Row, Col } = Grid;
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
const ChannelMonitorView = ({ channelStatus, onRefresh }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 获取状态显示
|
||||
const getStatusConfig = (status) => {
|
||||
switch (status) {
|
||||
case 1: // 在线
|
||||
return { color: 'green', text: t('可用'), icon: '🟢' };
|
||||
case 0: // 离线
|
||||
return { color: 'red', text: t('不可用'), icon: '🔴' };
|
||||
case 2: // 维护中
|
||||
return { color: 'orange', text: t('维护中'), icon: '🟡' };
|
||||
default:
|
||||
return { color: 'grey', text: t('未知'), icon: '⚪' };
|
||||
}
|
||||
};
|
||||
|
||||
// 获取响应速度配置
|
||||
const getSpeedConfig = (responseTime) => {
|
||||
if (responseTime < 1000) {
|
||||
return { level: t('快'), color: 'green', percent: 100, bars: '🟩🟩🟩' };
|
||||
} else if (responseTime < 3000) {
|
||||
return { level: t('中等'), color: 'yellow', percent: 66, bars: '🟨🟨' };
|
||||
} else {
|
||||
return { level: t('慢'), color: 'red', percent: 33, bars: '🟥' };
|
||||
}
|
||||
};
|
||||
|
||||
// 渲染迷你趋势图 (Sparkline)
|
||||
const renderSparkline = (uptime) => {
|
||||
const width = 100;
|
||||
const height = 30;
|
||||
const points = 12;
|
||||
const data = Array.from({ length: points }, (_, i) => {
|
||||
// 模拟趋势数据,基于uptime生成波动
|
||||
const baseValue = uptime * 100;
|
||||
const variance = (Math.random() - 0.5) * 10;
|
||||
return Math.max(0, Math.min(100, baseValue + variance));
|
||||
});
|
||||
|
||||
const pathData = data
|
||||
.map((value, index) => {
|
||||
const x = (index / (points - 1)) * width;
|
||||
const y = height - (value / 100) * height;
|
||||
return `${index === 0 ? 'M' : 'L'} ${x},${y}`;
|
||||
})
|
||||
.join(' ');
|
||||
|
||||
return (
|
||||
<svg width={width} height={height} style={{ display: 'block' }}>
|
||||
<path
|
||||
d={pathData}
|
||||
fill='none'
|
||||
stroke={
|
||||
uptime > 0.9
|
||||
? 'var(--semi-color-success)'
|
||||
: uptime > 0.7
|
||||
? 'var(--semi-color-warning)'
|
||||
: 'var(--semi-color-danger)'
|
||||
}
|
||||
strokeWidth='2'
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
if (!channelStatus || channelStatus.length === 0) {
|
||||
return (
|
||||
<Empty
|
||||
image={<IconAlertCircle size='extra-large' />}
|
||||
title={t('暂无渠道数据')}
|
||||
description={t('请稍后刷新或联系管理员')}
|
||||
>
|
||||
<Button icon={<IconRefresh />} onClick={onRefresh}>
|
||||
{t('刷新数据')}
|
||||
</Button>
|
||||
</Empty>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* 刷新按钮 */}
|
||||
<div style={{ marginBottom: 16, textAlign: 'right' }}>
|
||||
<Button icon={<IconRefresh />} onClick={onRefresh}>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 渠道分组展示 */}
|
||||
{channelStatus.map((group, groupIndex) => (
|
||||
<div key={groupIndex} style={{ marginBottom: 32 }}>
|
||||
<Title heading={4} style={{ marginBottom: 16, color: '#1890ff' }}>
|
||||
📁 {group.categoryName}
|
||||
</Title>
|
||||
|
||||
<Row gutter={[16, 16]}>
|
||||
{group.monitors &&
|
||||
group.monitors.map((channel, index) => {
|
||||
const statusConfig = getStatusConfig(channel.status);
|
||||
const speedConfig = getSpeedConfig(channel.response_time || 0);
|
||||
|
||||
return (
|
||||
<Col key={index} xs={24} sm={12} md={8} lg={6}>
|
||||
<Card
|
||||
title={
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 20 }}>
|
||||
{statusConfig.icon}
|
||||
</span>
|
||||
<Text strong>{channel.name}</Text>
|
||||
</div>
|
||||
}
|
||||
headerStyle={{ borderBottom: '2px solid #f0f0f0' }}
|
||||
bodyStyle={{ padding: 16 }}
|
||||
style={{
|
||||
height: '100%',
|
||||
border: `2px solid ${
|
||||
channel.status === 1
|
||||
? '#52c41a20'
|
||||
: channel.status === 0
|
||||
? '#f5222d20'
|
||||
: '#faad1420'
|
||||
}`,
|
||||
}}
|
||||
>
|
||||
{/* 1. 渠道状态 */}
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('状态')}
|
||||
</Text>
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<Tag color={statusConfig.color} size='large'>
|
||||
{statusConfig.text}
|
||||
</Tag>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 2. 响应速度 */}
|
||||
<div style={{ marginBottom: 16 }}>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
marginBottom: 4,
|
||||
}}
|
||||
>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('响应速度')}
|
||||
</Text>
|
||||
<Text strong size='small'>
|
||||
{speedConfig.level}
|
||||
</Text>
|
||||
</div>
|
||||
<Progress
|
||||
percent={speedConfig.percent}
|
||||
stroke={speedConfig.color}
|
||||
showInfo={false}
|
||||
style={{ marginBottom: 4 }}
|
||||
/>
|
||||
<Text type='tertiary' size='small'>
|
||||
{channel.response_time || 0}ms
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{/* 3. 稳定性 (Sparkline) */}
|
||||
<div>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('稳定性趋势 (24h)')}
|
||||
</Text>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 8,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
{renderSparkline(channel.uptime || 0)}
|
||||
<Text type='success' strong>
|
||||
{((channel.uptime || 0) * 100).toFixed(1)}%
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</Col>
|
||||
);
|
||||
})}
|
||||
</Row>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ChannelMonitorView;
|
||||
@@ -0,0 +1,140 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
Layout,
|
||||
Tabs,
|
||||
TabPane,
|
||||
Typography,
|
||||
Spin,
|
||||
Toast,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
IconActivity,
|
||||
IconLineChart,
|
||||
IconPulse,
|
||||
} from '@douyinfe/semi-icons';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers';
|
||||
import ChannelMonitorView from './components/ChannelMonitorView';
|
||||
import AdminMonitorView from './components/AdminMonitorView';
|
||||
|
||||
const { Content } = Layout;
|
||||
const { Title } = Typography;
|
||||
|
||||
const Monitoring = () => {
|
||||
const { t } = useTranslation();
|
||||
const [activeTab, setActiveTab] = useState('channels');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [channelStatus, setChannelStatus] = useState([]);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
|
||||
// 检查用户权限
|
||||
useEffect(() => {
|
||||
const userRole = localStorage.getItem('role');
|
||||
setIsAdmin(userRole && (userRole === 'admin' || userRole === 'root'));
|
||||
}, []);
|
||||
|
||||
// 获取渠道状态数据
|
||||
const fetchChannelStatus = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.get('/api/channels/status');
|
||||
if (res.data.success) {
|
||||
setChannelStatus(res.data.data || []);
|
||||
} else {
|
||||
Toast.error(res.data.message || '获取渠道状态失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch channel status:', error);
|
||||
Toast.error('获取渠道状态失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchChannelStatus();
|
||||
// 每30秒刷新一次
|
||||
const interval = setInterval(fetchChannelStatus, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<Content style={{ padding: '24px' }}>
|
||||
<div
|
||||
style={{
|
||||
marginBottom: 24,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
}}
|
||||
>
|
||||
<Title heading={2} style={{ margin: 0 }}>
|
||||
<IconPulse style={{ marginRight: 8 }} />
|
||||
{t('监控中心')}
|
||||
</Title>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
type='line'
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
{/* 页签一:渠道监控 (对所有用户可见) */}
|
||||
<TabPane
|
||||
tab={
|
||||
<span>
|
||||
<IconActivity style={{ marginRight: 4 }} />
|
||||
{t('渠道监控')}
|
||||
</span>
|
||||
}
|
||||
itemKey='channels'
|
||||
>
|
||||
<Spin spinning={loading}>
|
||||
<ChannelMonitorView
|
||||
channelStatus={channelStatus}
|
||||
onRefresh={fetchChannelStatus}
|
||||
/>
|
||||
</Spin>
|
||||
</TabPane>
|
||||
|
||||
{/* 页签二:管理监控 (仅对管理员可见) */}
|
||||
{isAdmin && (
|
||||
<TabPane
|
||||
tab={
|
||||
<span>
|
||||
<IconLineChart style={{ marginRight: 4 }} />
|
||||
{t('管理监控')}
|
||||
</span>
|
||||
}
|
||||
itemKey='admin'
|
||||
>
|
||||
<AdminMonitorView />
|
||||
</TabPane>
|
||||
)}
|
||||
</Tabs>
|
||||
</Content>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default Monitoring;
|
||||
@@ -0,0 +1,221 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
Banner,
|
||||
Button,
|
||||
Card,
|
||||
Descriptions,
|
||||
Empty,
|
||||
Modal,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, showError, showSuccess } from '../../helpers';
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
const uToYuan = (u) =>
|
||||
u === undefined || u === null ? '-' : (u / 1e6).toFixed(2);
|
||||
|
||||
/** 我的提成(内部销售自助对账,v2.0 六章:次月对账、3 工作日申诉期) */
|
||||
export default function MyCommission() {
|
||||
const { t } = useTranslation();
|
||||
const [bills, setBills] = useState([]);
|
||||
const [detail, setDetail] = useState(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const res = await API.get('/api/sales/commission/bills');
|
||||
if (res.data.success) setBills(res.data.data || []);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
const openDetail = async (bill) => {
|
||||
const res = await API.get(`/api/sales/commission/bills/${bill.id}/items`);
|
||||
if (res.data.success) setDetail(res.data.data);
|
||||
else showError(res.data.message);
|
||||
};
|
||||
|
||||
const confirm = async (billId) => {
|
||||
const res = await API.post(`/api/sales/commission/bills/${billId}/confirm`);
|
||||
if (res.data.success) {
|
||||
showSuccess(t('对账单已确认'));
|
||||
setDetail(null);
|
||||
load();
|
||||
} else showError(res.data.message);
|
||||
};
|
||||
|
||||
return (
|
||||
// mt-[60px]:顶栏 fixed 定位需自行让位(跑马灯由 PageLayout 占位补偿)
|
||||
<div className='mt-[60px] px-2 pb-4'>
|
||||
<Card>
|
||||
<Title heading={4}>{t('我的提成')}</Title>
|
||||
<Banner
|
||||
type='info'
|
||||
closeIcon={null}
|
||||
style={{ margin: '8px 0' }}
|
||||
description={t(
|
||||
'对账单于次月发出;如有异议请在 3 个工作日内联系管理员,逾期视为确认。当期发放 70%,余 30% 随回款到账释放',
|
||||
)}
|
||||
/>
|
||||
<Table
|
||||
columns={[
|
||||
{ title: t('月份'), dataIndex: 'month' },
|
||||
{ title: t('毛利(元)'), dataIndex: 'gp_uyuan', render: uToYuan },
|
||||
{
|
||||
title: t('个人(元)'),
|
||||
dataIndex: 'personal_uyuan',
|
||||
render: uToYuan,
|
||||
},
|
||||
{
|
||||
title: t('续费(元)'),
|
||||
dataIndex: 'renewal_uyuan',
|
||||
render: uToYuan,
|
||||
},
|
||||
{ title: t('管理(元)'), dataIndex: 'mgmt_uyuan', render: uToYuan },
|
||||
{ title: t('专项(元)'), dataIndex: 'bonus_uyuan', render: uToYuan },
|
||||
{ title: t('当期发(元)'), dataIndex: 'immediate_yuan' },
|
||||
{
|
||||
title: t('回款留存(元)'),
|
||||
render: (r) => (
|
||||
<span>
|
||||
{r.holdback_yuan}{' '}
|
||||
{r.holdback_released && (
|
||||
<Tag color='green'>{t('已释放')}</Tag>
|
||||
)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
render: (v) => (
|
||||
<Tag color={v === 'pending_confirm' ? 'orange' : 'green'}>
|
||||
{v === 'pending_confirm' ? t('待确认') : t('已确认')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
render: (r) => (
|
||||
<span className='flex gap-2'>
|
||||
<Button size='small' onClick={() => openDetail(r)}>
|
||||
{t('明细')}
|
||||
</Button>
|
||||
{r.status === 'pending_confirm' && (
|
||||
<Button
|
||||
size='small'
|
||||
type='primary'
|
||||
onClick={() => confirm(r.id)}
|
||||
>
|
||||
{t('确认')}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
]}
|
||||
dataSource={bills}
|
||||
rowKey='id'
|
||||
pagination={false}
|
||||
scroll={{ x: 'max-content' }}
|
||||
empty={
|
||||
<Empty description={t('暂无提成账单(非销售人员或尚未出账)')} />
|
||||
}
|
||||
/>
|
||||
<Modal
|
||||
title={detail ? `${detail.bill.month} ${t('月提成明细')}` : ''}
|
||||
visible={!!detail}
|
||||
onCancel={() => setDetail(null)}
|
||||
width={760}
|
||||
footer={null}
|
||||
>
|
||||
{detail && (
|
||||
<>
|
||||
<Descriptions
|
||||
row
|
||||
size='small'
|
||||
data={[
|
||||
{
|
||||
key: t('合计(元)'),
|
||||
value: uToYuan(detail.bill.total_uyuan),
|
||||
},
|
||||
{
|
||||
key: t('调整(元)'),
|
||||
value: uToYuan(detail.bill.offset_uyuan),
|
||||
},
|
||||
{
|
||||
key: t('期初结转(元)'),
|
||||
value: uToYuan(detail.bill.carry_in_uyuan),
|
||||
},
|
||||
{ key: t('方案版本'), value: detail.bill.plan_version },
|
||||
]}
|
||||
/>
|
||||
<Table
|
||||
style={{ marginTop: 8 }}
|
||||
columns={[
|
||||
{ title: t('客户名称'), dataIndex: 'customer_name' },
|
||||
{
|
||||
title: t('净消耗(元)'),
|
||||
dataIndex: 'net_uyuan',
|
||||
render: uToYuan,
|
||||
},
|
||||
{
|
||||
title: t('毛利(元)'),
|
||||
dataIndex: 'gp_uyuan',
|
||||
render: uToYuan,
|
||||
},
|
||||
{
|
||||
title: t('客户属性'),
|
||||
render: (r) =>
|
||||
r.is_stock ? (
|
||||
<Tag color='blue'>{t('存量(续费叠加)')}</Tag>
|
||||
) : r.is_new_first ? (
|
||||
<Tag color='green'>{t('新客首月')}</Tag>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('续费提成(元)'),
|
||||
dataIndex: 'renewal_uyuan',
|
||||
render: uToYuan,
|
||||
},
|
||||
]}
|
||||
dataSource={detail.items}
|
||||
rowKey='id'
|
||||
pagination={false}
|
||||
size='small'
|
||||
/>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t(
|
||||
'毛利 = 净消耗 − 底层成本(v2.0 二章口径);提成按实际毛利据实计算',
|
||||
)}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Empty } from '@douyinfe/semi-ui';
|
||||
import {
|
||||
IllustrationNotFound,
|
||||
IllustrationNotFoundDark,
|
||||
} from '../../components/common/illustrations';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const NotFound = () => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className='flex justify-center items-center h-screen p-8'>
|
||||
<Empty
|
||||
image={<IllustrationNotFound style={{ width: 250, height: 250 }} />}
|
||||
darkModeImage={
|
||||
<IllustrationNotFoundDark style={{ width: 250, height: 250 }} />
|
||||
}
|
||||
description={t('页面未找到,请检查您的浏览器地址是否正确')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotFound;
|
||||
@@ -0,0 +1,776 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useContext, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
AutoComplete,
|
||||
Toast,
|
||||
Banner,
|
||||
Avatar,
|
||||
Spin,
|
||||
Checkbox,
|
||||
Modal,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError, getLogo, getSystemName } from '../../helpers';
|
||||
import {
|
||||
setUserData,
|
||||
savePostLoginRedirect,
|
||||
consumePostLoginRedirect,
|
||||
} from '../../helpers/data';
|
||||
import { updateAPI } from '../../helpers/api';
|
||||
import { finishLogin } from '../../helpers/loginFlow';
|
||||
import { UserContext } from '../../context/User';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import GlassCard from '../../components/auth/GlassCard';
|
||||
import AuthCardHeader from '../../components/auth/AuthCardHeader';
|
||||
import AuthLoginTabs from '../../components/auth/AuthLoginTabs';
|
||||
import AuthBackground from '../../components/common/AuthBackground';
|
||||
|
||||
const LAST_ORG_KEY = 'org_login_last';
|
||||
|
||||
// 企业登录页(PR6b):先输企业标识 -> 展示企业品牌与登录方式 -> 密码登录 -> 首登改密。
|
||||
const OrgLogin = () => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const { slug } = useParams();
|
||||
// ?org=<code> 预填企业(企业注册成功后「立即登录」等入口带入),与 slug 一样自动直达 Step2;
|
||||
// ?login=<登录名> 一并预填 Step2 登录名,用户只需输入密码
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const orgParam = (searchParams.get('org') || '').trim();
|
||||
const loginParam = (searchParams.get('login') || '').trim();
|
||||
const [, userDispatch] = useContext(UserContext);
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const statusLoaded = statusState?.status !== undefined;
|
||||
const selfUseModeEnabled = !!statusState?.status?.self_use_mode_enabled;
|
||||
const selfRegisterEnabled = !!statusState?.status?.org_self_register;
|
||||
const directLoginEnabled = !!statusState?.status?.org_direct_login;
|
||||
// 免企业标识直登(方案 §12):'direct'=账号直登(默认),'identifier'=企业标识登录(原流程/回退)
|
||||
const [loginMode, setLoginMode] = useState('direct');
|
||||
const [directForm, setDirectForm] = useState({ login_name: '', password: '' });
|
||||
const [multiMatch, setMultiMatch] = useState(null); // { orgs:[{index,org_id,name,logo}], ticket, password }
|
||||
// 带入 Step2 初值的登录名,避免重复输入:来自 ?login= 预填(注册成功直达)或直登回退时已输的登录名
|
||||
const [pendingLoginName, setPendingLoginName] = useState(loginParam);
|
||||
// 实际生效模式:系统未开直登则始终走企业标识
|
||||
const effectiveMode = directLoginEnabled ? loginMode : 'identifier';
|
||||
|
||||
const logo = getLogo();
|
||||
const systemName = getSystemName();
|
||||
|
||||
// 上次登录企业 {identifier, name, login_name, remember_login_name}:本机记忆,仅读一次。
|
||||
// 始终读取:企业自动直达由 slug 优先(见下方 effect),但登录名回填对 slug 短链流程同样生效。
|
||||
const [savedOrg] = useState(() => {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(LAST_ORG_KEY) || 'null');
|
||||
} catch {
|
||||
return null; // 忽略损坏的本地存储
|
||||
}
|
||||
});
|
||||
|
||||
const [step, setStep] = useState(1); // 1=企业标识 2=登录 3=首登改密
|
||||
const [identifier, setIdentifier] = useState(
|
||||
slug || orgParam ? '' : savedOrg?.identifier || '',
|
||||
);
|
||||
const [orgInfo, setOrgInfo] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
// slug(品牌短链 /org/:slug/login)、?org= 预填或本机记忆的企业存在时,自动查企业并直达 Step2,期间展示加载态
|
||||
const [bootstrapping, setBootstrapping] = useState(
|
||||
Boolean(slug || orgParam || savedOrg?.identifier),
|
||||
);
|
||||
const [creds, setCreds] = useState({ login_name: '', password: '' });
|
||||
const [loginUser, setLoginUser] = useState(null);
|
||||
// 记住登录名(可选):沿用上次显式选择;无记录(含本功能上线前的老记忆)默认开启。共享设备可手动取消。
|
||||
const [rememberLoginName, setRememberLoginName] = useState(
|
||||
() => savedOrg?.remember_login_name ?? true,
|
||||
);
|
||||
const [capsOn, setCapsOn] = useState(false); // 密码框大写锁定提示
|
||||
const autoLookedUpSlug = useRef(null); // 记录已自动直达过的 slug,避免重复请求
|
||||
const autoLookedUpParam = useRef(false); // ?org= 预填仅自动直达一次
|
||||
const autoLookedUpSaved = useRef(false); // 记忆企业仅自动直达一次
|
||||
|
||||
// 企业名称联想(仅对开启「允许被搜索」的企业生效)
|
||||
const [suggestOptions, setSuggestOptions] = useState([]);
|
||||
const suggestTimer = useRef(null); // 防抖计时器
|
||||
const suggestSeq = useRef(0); // 请求序号,防止慢响应覆盖新输入(竞态)
|
||||
|
||||
// 高亮命中片段:把 name 中匹配 keyword 的子串用品牌色包裹(大小写不敏感)。
|
||||
const highlightMatch = (name, keyword) => {
|
||||
const kw = (keyword || '').trim();
|
||||
if (!kw) return name;
|
||||
const idx = name.toLowerCase().indexOf(kw.toLowerCase());
|
||||
if (idx < 0) return name;
|
||||
return (
|
||||
<>
|
||||
{name.slice(0, idx)}
|
||||
<span className='text-brand font-medium'>
|
||||
{name.slice(idx, idx + kw.length)}
|
||||
</span>
|
||||
{name.slice(idx + kw.length)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// 名称联想搜索:250ms 防抖 + 竞态防护;<2 字符不请求。
|
||||
const handleSuggestSearch = (value) => {
|
||||
const kw = (value || '').trim();
|
||||
if (suggestTimer.current) clearTimeout(suggestTimer.current);
|
||||
if (kw.length < 2) {
|
||||
setSuggestOptions([]);
|
||||
return;
|
||||
}
|
||||
suggestTimer.current = setTimeout(async () => {
|
||||
const seq = ++suggestSeq.current;
|
||||
try {
|
||||
const res = await API.get(
|
||||
`/api/org/login/suggest?q=${encodeURIComponent(kw)}`,
|
||||
);
|
||||
if (seq !== suggestSeq.current) return; // 已有更新的请求,丢弃本次结果
|
||||
const items = res.data?.data?.items || [];
|
||||
setSuggestOptions(
|
||||
items.map((it) => ({
|
||||
value: it.code, // 选中后用 code 精确直达
|
||||
label: it.name,
|
||||
name: it.name,
|
||||
logo: it.logo,
|
||||
})),
|
||||
);
|
||||
} catch {
|
||||
if (seq === suggestSeq.current) setSuggestOptions([]);
|
||||
}
|
||||
}, 250);
|
||||
};
|
||||
|
||||
// 仅当当前企业即上次记住的企业时,才回填登录名(切换企业后不串号)。
|
||||
const rememberedLoginName =
|
||||
savedOrg && identifier.trim() === savedOrg.identifier
|
||||
? savedOrg.login_name || ''
|
||||
: '';
|
||||
// Step2 登录名初值(记忆 > ?login=/直登回退带入);有初值时焦点直接给密码框
|
||||
const prefilledLoginName = rememberedLoginName || pendingLoginName;
|
||||
|
||||
// 大写锁定检测:密码框 keydown/keyup 时更新提示。
|
||||
const handleCapsLock = (e) => {
|
||||
if (typeof e.getModifierState === 'function') {
|
||||
setCapsOn(e.getModifierState('CapsLock'));
|
||||
}
|
||||
};
|
||||
|
||||
// 查企业。idArg 仅在自动直达时传入字符串;来自 onClick/onEnterPress 的事件对象一律忽略,改读输入框。
|
||||
const lookupOrg = async (idArg) => {
|
||||
const id = (typeof idArg === 'string' ? idArg : identifier).trim();
|
||||
if (!id) {
|
||||
Toast.warning(t('请输入企业标识'));
|
||||
return;
|
||||
}
|
||||
if (loading) return; // 防抖:避免回车连按重复请求
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.get(
|
||||
`/api/org/login/options?org=${encodeURIComponent(id)}`,
|
||||
);
|
||||
if (res.data.success && res.data.data?.available) {
|
||||
const info = res.data.data;
|
||||
if (!(info.login_methods || []).includes('password')) {
|
||||
Toast.warning(t('该企业未开启密码登录'));
|
||||
return;
|
||||
}
|
||||
setOrgInfo(info);
|
||||
setStep(2);
|
||||
} else {
|
||||
showError(t('企业不存在或不可登录,请联系企业管理员'));
|
||||
}
|
||||
} catch (err) {
|
||||
if (!err?.isAxiosError) {
|
||||
showError(err.message);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 与 /login 对齐的入口参数处理:?redirect= 写回本地存储(新标签页打开也能回跳),
|
||||
// ?expired=true 提示会话过期后从 URL 清除(避免刷新重复提示)。
|
||||
useEffect(() => {
|
||||
const redirect = searchParams.get('redirect');
|
||||
if (redirect) {
|
||||
savePostLoginRedirect(redirect);
|
||||
}
|
||||
if (searchParams.get('expired')) {
|
||||
showError(t('未登录或登录已过期,请重新登录'));
|
||||
const nextParams = new URLSearchParams(searchParams);
|
||||
nextParams.delete('expired');
|
||||
setSearchParams(nextParams, { replace: true });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!slug || autoLookedUpSlug.current === slug) return;
|
||||
autoLookedUpSlug.current = slug; // 防 StrictMode 双触发 / slug 变更时才重查
|
||||
setLoginMode('identifier'); // 品牌短链指向特定企业,走企业标识模式更自然
|
||||
setIdentifier(slug);
|
||||
// 自动直达:成功进 step2,失败回落 step1(输入框已预填,可直接重试)
|
||||
lookupOrg(slug).finally(() => setBootstrapping(false));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [slug]);
|
||||
|
||||
// ?org= 预填(企业注册成功「立即登录」等入口带入企业代码):与 slug 同样自动直达 Step2,
|
||||
// 失败回落 Step1(输入框已预填,可直接重试)。
|
||||
useEffect(() => {
|
||||
if (slug || !orgParam || autoLookedUpParam.current) return;
|
||||
autoLookedUpParam.current = true;
|
||||
setLoginMode('identifier'); // 预填指向特定企业,走企业标识模式
|
||||
setIdentifier(orgParam);
|
||||
lookupOrg(orgParam).finally(() => setBootstrapping(false));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// 无 slug / ?org= 但本机记忆了上次企业:自动查企业并直达 Step2,老用户只需输登录名+密码。
|
||||
// 安全模型与品牌短链一致(企业上下文来自本机记忆,非跨企业探测);失败回落 Step1(输入框已预填,可改填或切换企业)。
|
||||
useEffect(() => {
|
||||
if (slug || orgParam || autoLookedUpSaved.current || !savedOrg?.identifier)
|
||||
return;
|
||||
autoLookedUpSaved.current = true;
|
||||
lookupOrg(savedOrg.identifier).finally(() => setBootstrapping(false));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// 登录成功后的统一收尾(企业标识登录 / 直登 / 直登选择 共用):写本机态、首登改密或进入工作台。
|
||||
const applyLoginSuccess = async (data, loginName, password) => {
|
||||
localStorage.setItem('current_org_id', String(data.current_org_id));
|
||||
setCreds({ login_name: loginName, password });
|
||||
setLoginUser(data.user);
|
||||
if (data.must_change_password) {
|
||||
setUserData(data.user);
|
||||
updateAPI();
|
||||
setCapsOn(false);
|
||||
setStep(3);
|
||||
Toast.info(t('首次登录,请修改初始密码'));
|
||||
} else {
|
||||
await finishLogin({
|
||||
data: data.user,
|
||||
userDispatch,
|
||||
navigate,
|
||||
t,
|
||||
// 消费被保护页跳来时保存的回跳地址(尊重深链意图,同时避免残留值
|
||||
// 影响之后的个人登录);无保存值则进企业工作台
|
||||
redirectOverride: consumePostLoginRedirect('/org/workbench'),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// 免企业标识直登:输登录名+密码 → 唯一命中直达 / 多命中选择 / 高碰撞名回退到企业标识。
|
||||
const doDirectLogin = async () => {
|
||||
const login_name = directForm.login_name.trim();
|
||||
const password = directForm.password;
|
||||
if (!login_name || !password) {
|
||||
Toast.warning(t('请输入登录名和密码'));
|
||||
return;
|
||||
}
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/org/login/direct', { login_name, password });
|
||||
if (res.data.success) {
|
||||
const data = res.data.data;
|
||||
if (data.need_org_hint) {
|
||||
setPendingLoginName(login_name); // 带入 Step2,免重复输入
|
||||
setLoginMode('identifier');
|
||||
Toast.info(t('该账号需补充企业名称或代码后登录'));
|
||||
return;
|
||||
}
|
||||
if (data.multi) {
|
||||
setMultiMatch({ orgs: data.orgs || [], ticket: data.ticket, password });
|
||||
return;
|
||||
}
|
||||
await applyLoginSuccess(data, login_name, password);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!err?.isAxiosError) showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 多命中时选择企业完成登录。
|
||||
const doDirectSelect = async (index) => {
|
||||
if (!multiMatch || loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/org/login/direct/select', {
|
||||
ticket: multiMatch.ticket,
|
||||
index,
|
||||
});
|
||||
if (res.data.success) {
|
||||
const ln = directForm.login_name.trim();
|
||||
const pwd = multiMatch.password;
|
||||
setMultiMatch(null);
|
||||
await applyLoginSuccess(res.data.data, ln, pwd);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!err?.isAxiosError) showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const doLogin = async (values) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/org/login', {
|
||||
org_identifier: identifier.trim(),
|
||||
login_name: values.login_name,
|
||||
password: values.password,
|
||||
});
|
||||
if (res.data.success) {
|
||||
const data = res.data.data;
|
||||
// 记住本次企业用于自动直达;勾选「记住登录名」时一并存登录名(均不含密码)。
|
||||
try {
|
||||
localStorage.setItem(
|
||||
LAST_ORG_KEY,
|
||||
JSON.stringify({
|
||||
identifier: identifier.trim(),
|
||||
name: orgInfo?.org_name || identifier.trim(),
|
||||
remember_login_name: rememberLoginName,
|
||||
login_name: rememberLoginName ? values.login_name : undefined,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// 忽略写入失败
|
||||
}
|
||||
await applyLoginSuccess(data, values.login_name, values.password);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!err?.isAxiosError) {
|
||||
showError(err.message);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const doChangePassword = async (values) => {
|
||||
if (values.new_password !== values.confirm_password) {
|
||||
Toast.warning(t('两次输入的新密码不一致'));
|
||||
return;
|
||||
}
|
||||
// 与后端一致的长度校验(8-20 位),避免无谓往返
|
||||
if (values.new_password.length < 8 || values.new_password.length > 20) {
|
||||
Toast.warning(t('新密码长度需为 8-20 位'));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/org/account/change-initial-password', {
|
||||
old_password: creds.password,
|
||||
new_password: values.new_password,
|
||||
});
|
||||
if (res.data.success) {
|
||||
Toast.success(t('密码已修改'));
|
||||
await finishLogin({
|
||||
data: loginUser,
|
||||
userDispatch,
|
||||
navigate,
|
||||
t,
|
||||
successMessage: '',
|
||||
// 首登改密路径同样消费保存的回跳地址,默认进企业工作台
|
||||
redirectOverride: consumePostLoginRedirect('/org/workbench'),
|
||||
});
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!err?.isAxiosError) {
|
||||
showError(err.message);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className='relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
||||
// 抵扣 PageLayout 跑马灯占位高度,保证占位+容器恰为一屏,避免幽灵滚动
|
||||
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||||
>
|
||||
<AuthBackground />
|
||||
<style>{`
|
||||
@keyframes orgStepEnter {
|
||||
from { opacity: 0; transform: translateY(6px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.org-step-enter { animation: orgStepEnter 0.35s ease-out; }
|
||||
@media (prefers-reduced-motion: reduce) { .org-step-enter { animation: none; } }
|
||||
`}</style>
|
||||
<div className='w-full max-w-md z-10 flex flex-col items-center'>
|
||||
{/* 与其余认证页一致:状态加载完成且非自用模式才展示「个人/企业」切换 */}
|
||||
{statusLoaded && !selfUseModeEnabled && (
|
||||
<div className='w-full max-w-sm mb-4'>
|
||||
<AuthLoginTabs active='enterprise' />
|
||||
</div>
|
||||
)}
|
||||
<GlassCard>
|
||||
<AuthCardHeader
|
||||
wrapperClassName='mb-6'
|
||||
logo={logo}
|
||||
logoNode={
|
||||
orgInfo?.logo ? (
|
||||
<Avatar
|
||||
src={orgInfo.logo}
|
||||
shape='square'
|
||||
className='h-10 w-10 rounded-lg'
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
title={
|
||||
step === 1
|
||||
? t('企业登录')
|
||||
: orgInfo?.org_name || systemName || t('企业登录')
|
||||
}
|
||||
subtitle={
|
||||
step === 1 ? t('使用企业托管账号登录') : t('企业托管账号登录')
|
||||
}
|
||||
/>
|
||||
|
||||
{bootstrapping ? (
|
||||
<div
|
||||
className='flex flex-col items-center justify-center gap-3 py-8'
|
||||
role='status'
|
||||
aria-live='polite'
|
||||
>
|
||||
<Spin size='large' />
|
||||
<span className='text-gray-500 dark:text-gray-400 text-xs'>
|
||||
{t('正在加载企业信息…')}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<div key={step} className='org-step-enter auth-glass-form'>
|
||||
{step === 1 && (
|
||||
<div className='flex flex-col gap-4'>
|
||||
{effectiveMode === 'direct' ? (
|
||||
<>
|
||||
{/* 账号直登:输登录名 + 密码,系统自动定位企业(方案 §12) */}
|
||||
<Input
|
||||
value={directForm.login_name}
|
||||
onChange={(v) =>
|
||||
setDirectForm({ ...directForm, login_name: v })
|
||||
}
|
||||
placeholder={t('登录名')}
|
||||
size='large'
|
||||
autoFocus
|
||||
/>
|
||||
<Input
|
||||
value={directForm.password}
|
||||
onChange={(v) =>
|
||||
setDirectForm({ ...directForm, password: v })
|
||||
}
|
||||
mode='password'
|
||||
placeholder={t('密码')}
|
||||
size='large'
|
||||
onKeyDown={handleCapsLock}
|
||||
onKeyUp={handleCapsLock}
|
||||
onEnterPress={doDirectLogin}
|
||||
/>
|
||||
{capsOn && (
|
||||
<div className='text-xs text-amber-500 -mt-1'>
|
||||
{t('大写锁定已开启')}
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
theme='solid'
|
||||
size='large'
|
||||
block
|
||||
loading={loading}
|
||||
disabled={
|
||||
!directForm.login_name.trim() || !directForm.password
|
||||
}
|
||||
onClick={doDirectLogin}
|
||||
>
|
||||
{t('登录')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='borderless'
|
||||
size='large'
|
||||
block
|
||||
className='!text-gray-500'
|
||||
onClick={() => setLoginMode('identifier')}
|
||||
>
|
||||
{t('用企业名称/代码登录')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<AutoComplete
|
||||
value={identifier}
|
||||
data={suggestOptions}
|
||||
onChange={(v) =>
|
||||
setIdentifier(typeof v === 'string' ? v : '')
|
||||
}
|
||||
onSearch={handleSuggestSearch}
|
||||
onSelect={(code) => {
|
||||
setIdentifier(code);
|
||||
lookupOrg(code); // 选中候选:用 code 精确直达 Step2
|
||||
}}
|
||||
onEnterPress={lookupOrg} // 未选候选时按当前输入精确解析
|
||||
placeholder={t('输入企业名称、企业代码或登录短链')}
|
||||
emptyContent={null}
|
||||
renderItem={(item) => (
|
||||
<div className='flex items-center gap-2 py-0.5'>
|
||||
{item.logo ? (
|
||||
<Avatar
|
||||
src={item.logo}
|
||||
shape='square'
|
||||
className='h-6 w-6 rounded'
|
||||
/>
|
||||
) : (
|
||||
<div className='h-6 w-6 rounded bg-gray-100 dark:bg-white/10' />
|
||||
)}
|
||||
<span className='truncate'>
|
||||
{highlightMatch(item.name, identifier)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
style={{ width: '100%' }}
|
||||
size='large'
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
theme='solid'
|
||||
size='large'
|
||||
block
|
||||
loading={loading}
|
||||
disabled={!identifier.trim()}
|
||||
onClick={lookupOrg}
|
||||
>
|
||||
{t('下一步')}
|
||||
</Button>
|
||||
{directLoginEnabled && (
|
||||
<Button
|
||||
theme='borderless'
|
||||
size='large'
|
||||
block
|
||||
className='!text-gray-500'
|
||||
onClick={() => setLoginMode('direct')}
|
||||
>
|
||||
{t('用账号直接登录')}
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{selfRegisterEnabled && (
|
||||
<>
|
||||
<div className='mt-1 flex items-center gap-3 text-xs text-gray-400'>
|
||||
<span className='h-px flex-1 bg-gray-200 dark:bg-white/10' />
|
||||
<span>{t('还没有企业?')}</span>
|
||||
<span className='h-px flex-1 bg-gray-200 dark:bg-white/10' />
|
||||
</div>
|
||||
<Button
|
||||
theme='borderless'
|
||||
size='large'
|
||||
block
|
||||
className='!text-brand'
|
||||
onClick={() => navigate('/org/register')}
|
||||
>
|
||||
{t('注册企业')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 2 && (
|
||||
<Form
|
||||
onSubmit={doLogin}
|
||||
initValues={{ login_name: prefilledLoginName }}
|
||||
>
|
||||
<Form.Input
|
||||
field='login_name'
|
||||
label={t('企业内登录名')}
|
||||
size='large'
|
||||
autoFocus={!prefilledLoginName}
|
||||
autoComplete='username'
|
||||
rules={[{ required: true, message: t('请输入登录名') }]}
|
||||
/>
|
||||
<Form.Input
|
||||
field='password'
|
||||
label={t('密码')}
|
||||
mode='password'
|
||||
size='large'
|
||||
autoFocus={Boolean(prefilledLoginName)}
|
||||
autoComplete='current-password'
|
||||
onKeyDown={handleCapsLock}
|
||||
onKeyUp={handleCapsLock}
|
||||
rules={[{ required: true, message: t('请输入密码') }]}
|
||||
/>
|
||||
{capsOn && (
|
||||
<div className='text-xs text-amber-500 -mt-1 mb-1'>
|
||||
{t('大写锁定已开启')}
|
||||
</div>
|
||||
)}
|
||||
<div className='flex items-center justify-between'>
|
||||
<Checkbox
|
||||
checked={rememberLoginName}
|
||||
onChange={(e) => setRememberLoginName(e.target.checked)}
|
||||
>
|
||||
<span className='text-xs text-gray-500 dark:text-gray-400'>
|
||||
{t('记住登录名')}
|
||||
</span>
|
||||
</Checkbox>
|
||||
<span className='text-xs text-gray-400 dark:text-gray-500'>
|
||||
{t('忘记密码?请联系企业管理员重置')}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
theme='solid'
|
||||
size='large'
|
||||
block
|
||||
htmlType='submit'
|
||||
loading={loading}
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
{t('登录')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='borderless'
|
||||
size='large'
|
||||
block
|
||||
disabled={loading}
|
||||
style={{ marginTop: 8 }}
|
||||
onClick={() => {
|
||||
setStep(1);
|
||||
setOrgInfo(null);
|
||||
setIdentifier(''); // 主动切换企业时清空,便于输入另一家
|
||||
setCapsOn(false);
|
||||
}}
|
||||
>
|
||||
{t('切换企业')}
|
||||
</Button>
|
||||
</Form>
|
||||
)}
|
||||
|
||||
{step === 3 && (
|
||||
<Form onSubmit={doChangePassword}>
|
||||
<Banner
|
||||
type='warning'
|
||||
closeIcon={null}
|
||||
description={t('首次登录需修改初始密码后方可使用。')}
|
||||
className='mb-3'
|
||||
/>
|
||||
<Form.Input
|
||||
field='new_password'
|
||||
label={t('新密码(8-20 位)')}
|
||||
mode='password'
|
||||
size='large'
|
||||
autoFocus
|
||||
autoComplete='new-password'
|
||||
onKeyDown={handleCapsLock}
|
||||
onKeyUp={handleCapsLock}
|
||||
validate={(value) => {
|
||||
if (!value) return t('请输入新密码');
|
||||
if (value.length < 8 || value.length > 20)
|
||||
return t('新密码长度需为 8-20 位');
|
||||
return '';
|
||||
}}
|
||||
/>
|
||||
<Form.Input
|
||||
field='confirm_password'
|
||||
label={t('确认新密码')}
|
||||
mode='password'
|
||||
size='large'
|
||||
autoComplete='new-password'
|
||||
onKeyDown={handleCapsLock}
|
||||
onKeyUp={handleCapsLock}
|
||||
validate={(value, values) => {
|
||||
if (!value) return t('请再次输入新密码');
|
||||
if (value !== values.new_password)
|
||||
return t('两次输入的新密码不一致');
|
||||
return '';
|
||||
}}
|
||||
/>
|
||||
{capsOn && (
|
||||
<div className='text-xs text-amber-500 -mt-1 mb-1'>
|
||||
{t('大写锁定已开启')}
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
theme='solid'
|
||||
size='large'
|
||||
block
|
||||
htmlType='submit'
|
||||
loading={loading}
|
||||
style={{ marginTop: 16 }}
|
||||
>
|
||||
{t('修改并进入')}
|
||||
</Button>
|
||||
</Form>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</GlassCard>
|
||||
</div>
|
||||
|
||||
{/* 免企业标识直登:命中多个企业时的选择框(方案 §12.3) */}
|
||||
<Modal
|
||||
title={t('选择要进入的企业')}
|
||||
visible={!!multiMatch}
|
||||
onCancel={() => setMultiMatch(null)}
|
||||
footer={null}
|
||||
centered
|
||||
>
|
||||
<div className='flex flex-col gap-2'>
|
||||
<p className='text-sm text-gray-500 dark:text-gray-400 mb-1'>
|
||||
{t('你的账号在以下企业中均可登录,请选择进入哪一个:')}
|
||||
</p>
|
||||
{(multiMatch?.orgs || []).map((o) => (
|
||||
<button
|
||||
key={o.index}
|
||||
type='button'
|
||||
disabled={loading}
|
||||
onClick={() => doDirectSelect(o.index)}
|
||||
className='flex items-center gap-3 w-full p-3 rounded-xl border border-gray-200/80 dark:border-white/10 hover:bg-gray-50 dark:hover:bg-white/[0.06] transition-all text-left disabled:opacity-50'
|
||||
>
|
||||
{o.logo ? (
|
||||
<Avatar src={o.logo} shape='square' className='h-8 w-8 rounded-lg' />
|
||||
) : (
|
||||
<div className='h-8 w-8 rounded-lg bg-gray-100 dark:bg-white/10' />
|
||||
)}
|
||||
<span className='truncate font-medium text-gray-800 dark:text-gray-100'>
|
||||
{o.name}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgLogin;
|
||||
@@ -0,0 +1,384 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useContext, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Form, Button, Toast, Banner } from '@douyinfe/semi-ui';
|
||||
import Turnstile from 'react-turnstile';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError, getLogo, getSystemName } from '../../helpers';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import OrgCredentialResult from '../../components/auth/OrgCredentialResult';
|
||||
import GlassCard from '../../components/auth/GlassCard';
|
||||
import AuthCardHeader from '../../components/auth/AuthCardHeader';
|
||||
import AuthLoginTabs from '../../components/auth/AuthLoginTabs';
|
||||
import AuthBackground from '../../components/common/AuthBackground';
|
||||
import {
|
||||
LOGIN_NAME_PATTERN,
|
||||
isReservedLoginName,
|
||||
} from '../../helpers/orgLoginName';
|
||||
|
||||
/**
|
||||
* 企业自助注册页(原 OrgRegisterModal 弹窗升级而来)。
|
||||
* 与 /login、/register、/org/login 共用同一套认证页布局(背景 + 个人/企业切换 + 玻璃卡片),
|
||||
* 拥有独立 URL 便于直达与分享;注册成功后在本页展示一次性凭证,
|
||||
* 「立即登录」经 /org/login?org=<code> 预填企业代码直达登录第二步。
|
||||
*/
|
||||
const OrgRegister = () => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const status = statusState?.status || {};
|
||||
const statusLoaded = statusState?.status !== undefined;
|
||||
const selfRegisterEnabled = !!status.org_self_register;
|
||||
|
||||
const emailVerifyEnabled = !!status.email_verification;
|
||||
const turnstileEnabled = !!status.turnstile_check;
|
||||
const turnstileSiteKey = status.turnstile_site_key || '';
|
||||
|
||||
const logo = getLogo();
|
||||
const systemName = getSystemName();
|
||||
|
||||
const [values, setValues] = useState({});
|
||||
const formApi = useRef(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [turnstileToken, setTurnstileToken] = useState('');
|
||||
const [codeLoading, setCodeLoading] = useState(false);
|
||||
const [countdown, setCountdown] = useState(0);
|
||||
const [result, setResult] = useState(null); // 注册成功后的一次性凭证
|
||||
|
||||
const startCountdown = () => {
|
||||
setCountdown(30);
|
||||
const timer = setInterval(() => {
|
||||
setCountdown((c) => {
|
||||
if (c <= 1) {
|
||||
clearInterval(timer);
|
||||
return 0;
|
||||
}
|
||||
return c - 1;
|
||||
});
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const sendCode = async () => {
|
||||
const email = (values.contact_email || '').trim();
|
||||
if (!email) {
|
||||
Toast.warning(t('请先输入联系邮箱'));
|
||||
return;
|
||||
}
|
||||
if (turnstileEnabled && !turnstileToken) {
|
||||
Toast.info(t('请稍候,正在进行人机校验'));
|
||||
return;
|
||||
}
|
||||
setCodeLoading(true);
|
||||
try {
|
||||
// 企业注册专用发码:不校验邮箱是否已被个人账号占用(联系邮箱非登录名)
|
||||
const res = await API.get(
|
||||
`/api/org/register/verification?email=${encodeURIComponent(email)}&turnstile=${turnstileToken}`,
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('验证码已发送,请查收邮箱'));
|
||||
startCountdown();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!err?.isAxiosError) showError(err.message);
|
||||
} finally {
|
||||
setCodeLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
let formValues = values;
|
||||
try {
|
||||
formValues = await formApi.current?.validate();
|
||||
} catch {
|
||||
return; // 校验不通过,Form 已高亮
|
||||
}
|
||||
if (turnstileEnabled && !turnstileToken) {
|
||||
Toast.info(t('请稍候,正在进行人机校验'));
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const res = await API.post(
|
||||
`/api/org/register?turnstile=${turnstileToken}`,
|
||||
{
|
||||
name: (formValues.name || '').trim(),
|
||||
owner_login_name: (formValues.owner_login_name || '').trim(),
|
||||
owner_display_name: (formValues.owner_display_name || '').trim(),
|
||||
contact_name: (formValues.contact_name || '').trim(),
|
||||
contact_email: (formValues.contact_email || '').trim(),
|
||||
contact_phone: (formValues.contact_phone || '').trim(),
|
||||
verify_code: (formValues.verify_code || '').trim(),
|
||||
},
|
||||
);
|
||||
if (res.data.success) {
|
||||
setResult(res.data.data); // 展示一次性凭证
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (!err?.isAxiosError) showError(err.message);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderSkeleton = () => (
|
||||
<GlassCard withCornerHalos={false} withAurora={false}>
|
||||
<div className='flex flex-col items-center justify-center mb-5'>
|
||||
<div className='w-14 h-14 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse mb-3' />
|
||||
<div className='w-24 h-5 rounded bg-gray-200/60 dark:bg-white/10 animate-pulse mb-1' />
|
||||
<div className='w-32 h-3 rounded bg-gray-100/80 dark:bg-white/5 animate-pulse' />
|
||||
</div>
|
||||
<div className='space-y-2'>
|
||||
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
|
||||
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
|
||||
<div className='w-full h-10 rounded-xl bg-gray-200/60 dark:bg-white/10 animate-pulse' />
|
||||
</div>
|
||||
</GlassCard>
|
||||
);
|
||||
|
||||
// 平台未开放自助注册:直达此 URL 时给出说明并引导回企业登录
|
||||
const renderDisabled = () => (
|
||||
<GlassCard>
|
||||
<AuthCardHeader
|
||||
wrapperClassName='mb-6'
|
||||
logo={logo}
|
||||
title={systemName || t('注册企业')}
|
||||
subtitle={t('企业注册')}
|
||||
/>
|
||||
<Banner
|
||||
type='info'
|
||||
closeIcon={null}
|
||||
description={t('当前未开放企业自助注册,请联系平台管理员开通企业。')}
|
||||
className='mb-4'
|
||||
/>
|
||||
<Button
|
||||
theme='solid'
|
||||
size='large'
|
||||
block
|
||||
onClick={() => navigate('/org/login')}
|
||||
>
|
||||
{t('返回企业登录')}
|
||||
</Button>
|
||||
</GlassCard>
|
||||
);
|
||||
|
||||
const renderForm = () => (
|
||||
<GlassCard>
|
||||
{/* key 随表单/凭证两态切换,触发与企业登录页一致的步骤过渡动画 */}
|
||||
<div key={result ? 'result' : 'form'} className='org-step-enter'>
|
||||
<AuthCardHeader
|
||||
wrapperClassName='mb-6'
|
||||
logo={logo}
|
||||
title={result ? t('企业注册成功') : t('注册企业')}
|
||||
subtitle={
|
||||
result
|
||||
? t('请妥善保存以下凭证')
|
||||
: t('为你的团队开通企业空间')
|
||||
}
|
||||
/>
|
||||
|
||||
{result ? (
|
||||
<OrgCredentialResult
|
||||
creds={result}
|
||||
onLogin={() =>
|
||||
// 带上企业代码与登录名直达登录第二步,用户只需输入初始密码
|
||||
navigate(
|
||||
`/org/login?org=${encodeURIComponent(result.org_code)}&login=${encodeURIComponent(result.owner_login_name || '')}`,
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<style>{`
|
||||
.org-register-form .semi-form-field {
|
||||
margin-bottom: 14px !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
.org-register-form .semi-form-field-label {
|
||||
margin-bottom: 6px !important;
|
||||
}
|
||||
`}</style>
|
||||
<Form
|
||||
className='org-register-form auth-glass-form'
|
||||
getFormApi={(api) => (formApi.current = api)}
|
||||
onValueChange={(v) => setValues(v)}
|
||||
>
|
||||
<Form.Input
|
||||
field='name'
|
||||
size='large'
|
||||
label={t('企业名称')}
|
||||
placeholder={t('请输入企业名称(登录时可用于搜索定位)')}
|
||||
rules={[{ required: true, message: t('请输入企业名称') }]}
|
||||
/>
|
||||
<Form.Input
|
||||
field='owner_login_name'
|
||||
size='large'
|
||||
label={t('管理员登录名')}
|
||||
placeholder={t('请设置管理员登录名,如 zhang.san')}
|
||||
extraText={t(
|
||||
'登录企业空间使用的管理员账号名,注册后不可修改;请勿使用 admin、root 等通用名',
|
||||
)}
|
||||
rules={[
|
||||
{ required: true, message: t('请设置管理员登录名') },
|
||||
{
|
||||
pattern: LOGIN_NAME_PATTERN,
|
||||
message: t(
|
||||
'登录名需为 3-32 位,以字母开头,仅可包含字母、数字、下划线、点或短横线',
|
||||
),
|
||||
},
|
||||
{
|
||||
validator: (rule, value) => !isReservedLoginName(value),
|
||||
message: t('该登录名为系统保留名称,请换一个登录名'),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Form.Input
|
||||
field='owner_display_name'
|
||||
size='large'
|
||||
label={t('管理员显示名')}
|
||||
placeholder={t('选填')}
|
||||
/>
|
||||
<Form.Input
|
||||
field='contact_name'
|
||||
size='large'
|
||||
label={t('联系人')}
|
||||
placeholder={t('选填')}
|
||||
/>
|
||||
<Form.Input
|
||||
field='contact_email'
|
||||
size='large'
|
||||
label={t('联系邮箱')}
|
||||
placeholder={t('用于接收通知')}
|
||||
rules={
|
||||
emailVerifyEnabled
|
||||
? [{ required: true, message: t('请输入联系邮箱') }]
|
||||
: []
|
||||
}
|
||||
suffix={
|
||||
emailVerifyEnabled ? (
|
||||
<Button
|
||||
size='small'
|
||||
onClick={sendCode}
|
||||
loading={codeLoading}
|
||||
disabled={countdown > 0}
|
||||
>
|
||||
{countdown > 0
|
||||
? `${t('重新发送')} (${countdown})`
|
||||
: t('获取验证码')}
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
{emailVerifyEnabled && (
|
||||
<Form.Input
|
||||
field='verify_code'
|
||||
size='large'
|
||||
label={t('邮箱验证码')}
|
||||
placeholder={t('请输入验证码')}
|
||||
rules={[{ required: true, message: t('请输入验证码') }]}
|
||||
/>
|
||||
)}
|
||||
<Form.Input
|
||||
field='contact_phone'
|
||||
size='large'
|
||||
label={t('联系电话')}
|
||||
placeholder={t('选填')}
|
||||
/>
|
||||
</Form>
|
||||
|
||||
<div className='mt-5'>
|
||||
<Button
|
||||
theme='solid'
|
||||
size='large'
|
||||
block
|
||||
loading={submitting}
|
||||
onClick={handleSubmit}
|
||||
>
|
||||
{t('提交注册')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className='mt-4 flex items-center gap-3 text-xs text-gray-400'>
|
||||
<span className='h-px flex-1 bg-gray-200 dark:bg-white/10' />
|
||||
<span>{t('已有企业?')}</span>
|
||||
<span className='h-px flex-1 bg-gray-200 dark:bg-white/10' />
|
||||
</div>
|
||||
<Button
|
||||
theme='borderless'
|
||||
size='large'
|
||||
block
|
||||
className='!text-brand'
|
||||
onClick={() => navigate('/org/login')}
|
||||
>
|
||||
{t('去登录')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</GlassCard>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className='relative overflow-hidden flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8'
|
||||
// 抵扣 PageLayout 跑马灯占位高度,保证占位+容器恰为一屏,避免幽灵滚动
|
||||
style={{ minHeight: 'calc(100vh - var(--content-top-offset, 0px))' }}
|
||||
>
|
||||
<AuthBackground />
|
||||
<style>{`
|
||||
@keyframes orgStepEnter {
|
||||
from { opacity: 0; transform: translateY(6px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
.org-step-enter { animation: orgStepEnter 0.35s ease-out; }
|
||||
@media (prefers-reduced-motion: reduce) { .org-step-enter { animation: none; } }
|
||||
`}</style>
|
||||
<div className='w-full max-w-md z-10 flex flex-col items-center'>
|
||||
{/* 凭证展示态隐藏切换入口:初始密码仅显示一次,避免误点导航导致凭证丢失 */}
|
||||
{statusLoaded && !status.self_use_mode_enabled && !result && (
|
||||
<div className='w-full max-w-sm mb-4'>
|
||||
<AuthLoginTabs mode='register' active='enterprise' />
|
||||
</div>
|
||||
)}
|
||||
{!statusLoaded
|
||||
? renderSkeleton()
|
||||
: selfRegisterEnabled
|
||||
? renderForm()
|
||||
: renderDisabled()}
|
||||
|
||||
{turnstileEnabled && !result && (
|
||||
<div className='flex justify-center mt-6'>
|
||||
<Turnstile
|
||||
sitekey={turnstileSiteKey}
|
||||
onVerify={(token) => setTurnstileToken(token)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgRegister;
|
||||
@@ -0,0 +1,361 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
Switch,
|
||||
TabPane,
|
||||
Tabs,
|
||||
Tag,
|
||||
Toast,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers';
|
||||
import './org-experts.css';
|
||||
|
||||
const { Title, Paragraph, Text } = Typography;
|
||||
|
||||
const AUDIT_PAGE_SIZE = 30;
|
||||
|
||||
const OrgAgentAudit = ({ orgId, canAuditContent, canManagePolicy }) => {
|
||||
const { t } = useTranslation();
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
const [runs, setRuns] = useState([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [cases, setCases] = useState([]);
|
||||
const [policies, setPolicies] = useState({});
|
||||
const [retention, setRetention] = useState({
|
||||
hot_days: 90,
|
||||
archive_enabled: true,
|
||||
});
|
||||
const [status, setStatus] = useState('');
|
||||
const [reason, setReason] = useState('');
|
||||
const [selected, setSelected] = useState(null);
|
||||
const [confirmRun, setConfirmRun] = useState(null);
|
||||
const [inspecting, setInspecting] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const [runResponse, caseResponse, policyResponse, retentionResponse] =
|
||||
await Promise.all([
|
||||
API.get('/api/org/agent-audit/runs', {
|
||||
headers,
|
||||
params: { status, page, page_size: AUDIT_PAGE_SIZE },
|
||||
}),
|
||||
API.get('/api/org/agent-audit/reconciliation', { headers }),
|
||||
API.get('/api/org/agent-audit/policies', { headers }),
|
||||
API.get('/api/org/agent-audit/retention', { headers }),
|
||||
]);
|
||||
if (runResponse.data?.success) {
|
||||
setRuns(runResponse.data.data || []);
|
||||
setTotal(runResponse.data.total || 0);
|
||||
}
|
||||
if (caseResponse.data?.success) setCases(caseResponse.data.data || []);
|
||||
if (policyResponse.data?.success)
|
||||
setPolicies(policyResponse.data.data || {});
|
||||
if (retentionResponse.data?.success)
|
||||
setRetention((current) => retentionResponse.data.data || current);
|
||||
}, [headers, page, status]);
|
||||
|
||||
useEffect(() => {
|
||||
// The interceptor already toasts HTTP failures; swallow the rejection so
|
||||
// it does not surface as an unhandled promise error.
|
||||
load().catch(() => {});
|
||||
}, [load]);
|
||||
|
||||
const requestInspect = (run) => {
|
||||
if (!canAuditContent) return;
|
||||
const length = reason.trim().length;
|
||||
if (length < 4 || length > 500) {
|
||||
Toast.warning(t('审计原因需为 4 到 500 个字符'));
|
||||
return;
|
||||
}
|
||||
// A real confirmation step: the request is only sent after the auditor
|
||||
// explicitly confirms in the dialog below.
|
||||
setConfirmRun(run);
|
||||
};
|
||||
|
||||
const inspect = async () => {
|
||||
if (!confirmRun) return;
|
||||
setInspecting(true);
|
||||
try {
|
||||
// Reason travels in the POST body: browsers reject non-Latin-1 header
|
||||
// values, so a Chinese reason can never be sent as a request header.
|
||||
const response = await API.post(
|
||||
`/api/org/agent-audit/runs/${confirmRun.id}/content`,
|
||||
{ reason: reason.trim(), confirm: true },
|
||||
{ headers, skipErrorHandler: true },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('读取审计正文失败'));
|
||||
return;
|
||||
}
|
||||
setSelected(response.data.data);
|
||||
setConfirmRun(null);
|
||||
} catch (error) {
|
||||
Toast.error(
|
||||
error?.response?.data?.message ||
|
||||
error?.message ||
|
||||
t('读取审计正文失败'),
|
||||
);
|
||||
} finally {
|
||||
setInspecting(false);
|
||||
}
|
||||
};
|
||||
const saveRetention = async () => {
|
||||
try {
|
||||
const response = await API.put(
|
||||
'/api/org/agent-audit/retention',
|
||||
{
|
||||
hot_days: Number(retention.hot_days),
|
||||
archive_enabled: !!retention.archive_enabled,
|
||||
},
|
||||
{ headers, skipErrorHandler: true },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('保留策略保存失败'));
|
||||
return;
|
||||
}
|
||||
setRetention(response.data.data);
|
||||
Toast.success(t('保留策略已保存'));
|
||||
} catch (error) {
|
||||
Toast.error(
|
||||
error?.response?.data?.message ||
|
||||
error?.message ||
|
||||
t('保留策略保存失败'),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const pageCount = Math.max(1, Math.ceil(total / AUDIT_PAGE_SIZE));
|
||||
|
||||
return (
|
||||
<main className='org-expert-page'>
|
||||
<header className='org-audit-hero'>
|
||||
<div>
|
||||
<Title heading={3}>{t('Agent 任务审计')}</Title>
|
||||
<Paragraph>
|
||||
{t(
|
||||
'元数据默认可见;正文访问需要独立权限、明确原因、二次确认与水印。',
|
||||
)}
|
||||
</Paragraph>
|
||||
</div>
|
||||
<Select
|
||||
value={status}
|
||||
onChange={(value) => {
|
||||
setPage(1);
|
||||
setStatus(value);
|
||||
}}
|
||||
optionList={[
|
||||
{ value: '', label: t('全部状态') },
|
||||
{ value: 'succeeded', label: t('已完成') },
|
||||
{
|
||||
value: 'completed_with_warnings',
|
||||
label: t('完成但有警告'),
|
||||
},
|
||||
{ value: 'failed', label: t('失败') },
|
||||
{ value: 'cancelled', label: t('已取消') },
|
||||
]}
|
||||
/>
|
||||
</header>
|
||||
<Tabs type='line'>
|
||||
<TabPane tab={`${t('任务元数据')} · ${total}`} itemKey='runs'>
|
||||
{canAuditContent && (
|
||||
<div className='org-audit-reason'>
|
||||
<Text>{t('正文审计原因')}</Text>
|
||||
<Input
|
||||
value={reason}
|
||||
onChange={setReason}
|
||||
placeholder={t('原因将写入不可变审计记录')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<section className='org-audit-list'>
|
||||
{runs.map((run) => (
|
||||
<article key={run.id}>
|
||||
<div>
|
||||
<code>{run.id}</code>
|
||||
<Tag>{run.status}</Tag>
|
||||
<Tag
|
||||
color={
|
||||
run.billing_status === 'pending_reconciliation'
|
||||
? 'orange'
|
||||
: 'green'
|
||||
}
|
||||
>
|
||||
{run.billing_status}
|
||||
</Tag>
|
||||
</div>
|
||||
<div className='org-audit-metrics'>
|
||||
<span>
|
||||
{t('专家')} #{run.expert_id}
|
||||
</span>
|
||||
<span>
|
||||
{t('模型')} {run.model_used || '-'}
|
||||
</span>
|
||||
<span>
|
||||
{t('消费')} {run.effective_quota}
|
||||
</span>
|
||||
<span>
|
||||
{t('成员')} #{run.org_member_id}
|
||||
</span>
|
||||
</div>
|
||||
<div className='org-audit-skills'>
|
||||
{(run.matched_skills || []).map((skill) => (
|
||||
<Tag key={skill.id}>{skill.match_reason}</Tag>
|
||||
))}
|
||||
</div>
|
||||
{canAuditContent && (
|
||||
<Button size='small' onClick={() => requestInspect(run)}>
|
||||
{t('二次确认查看正文')}
|
||||
</Button>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
{total > AUDIT_PAGE_SIZE && (
|
||||
<div className='org-audit-pagination'>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={page <= 1}
|
||||
onClick={() => setPage((old) => Math.max(1, old - 1))}
|
||||
>
|
||||
{t('上一页')}
|
||||
</Button>
|
||||
<Text type='tertiary'>
|
||||
{page} / {pageCount}
|
||||
</Text>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={page >= pageCount}
|
||||
onClick={() => setPage((old) => old + 1)}
|
||||
>
|
||||
{t('下一页')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TabPane>
|
||||
<TabPane
|
||||
tab={`${t('待对账')} · ${cases.length}`}
|
||||
itemKey='reconciliation'
|
||||
>
|
||||
<section className='org-audit-list'>
|
||||
{cases.map((item) => (
|
||||
<article key={item.id}>
|
||||
<div>
|
||||
<code>{item.request_id}</code>
|
||||
<Tag color='orange'>{item.status}</Tag>
|
||||
</div>
|
||||
<Text>
|
||||
{item.workload_type} / {item.reason}
|
||||
</Text>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</TabPane>
|
||||
<TabPane tab={t('安全策略')} itemKey='policies'>
|
||||
<section className='org-policy-grid'>
|
||||
<article>
|
||||
<strong>{t('任务保留策略')}</strong>
|
||||
<Text>{t('热数据保留天数')}</Text>
|
||||
<InputNumber
|
||||
min={7}
|
||||
max={3650}
|
||||
disabled={!canManagePolicy}
|
||||
value={retention.hot_days}
|
||||
onChange={(hot_days) =>
|
||||
setRetention((current) => ({ ...current, hot_days }))
|
||||
}
|
||||
/>
|
||||
<Switch
|
||||
disabled={!canManagePolicy}
|
||||
checked={!!retention.archive_enabled}
|
||||
onChange={(archive_enabled) =>
|
||||
setRetention((current) => ({
|
||||
...current,
|
||||
archive_enabled,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
{canManagePolicy && (
|
||||
<Button size='small' onClick={saveRetention}>
|
||||
{t('保存保留策略')}
|
||||
</Button>
|
||||
)}
|
||||
</article>
|
||||
{Object.entries(policies).map(([key, value]) => (
|
||||
<article key={key}>
|
||||
<strong>{key}</strong>
|
||||
<Text>
|
||||
{typeof value === 'string' ? value : JSON.stringify(value)}
|
||||
</Text>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</TabPane>
|
||||
</Tabs>
|
||||
<Modal
|
||||
title={t('确认查看任务正文')}
|
||||
visible={!!confirmRun}
|
||||
onCancel={() => setConfirmRun(null)}
|
||||
onOk={inspect}
|
||||
confirmLoading={inspecting}
|
||||
>
|
||||
<Paragraph>
|
||||
{t('此操作将在返回内容前写入不可变审计记录,正文携带你的专属水印。')}
|
||||
</Paragraph>
|
||||
<Text type='tertiary'>
|
||||
{t('任务')}: <code>{confirmRun?.id}</code>
|
||||
</Text>
|
||||
<Paragraph>
|
||||
{t('审计原因')}: {reason.trim()}
|
||||
</Paragraph>
|
||||
</Modal>
|
||||
<Modal
|
||||
title={t('受保护的任务正文')}
|
||||
visible={!!selected}
|
||||
footer={null}
|
||||
onCancel={() => setSelected(null)}
|
||||
width={920}
|
||||
>
|
||||
{selected && (
|
||||
<div className='org-audit-content'>
|
||||
<Tag color='red'>{selected.watermark}</Tag>
|
||||
<h4>{t('输入')}</h4>
|
||||
<pre>{selected.input}</pre>
|
||||
<h4>{t('步骤')}</h4>
|
||||
{(selected.steps || []).map((step) => (
|
||||
<pre key={step.id}>{step.output_message}</pre>
|
||||
))}
|
||||
<h4>{t('产物')}</h4>
|
||||
<pre>{selected.artifact?.content}</pre>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgAgentAudit;
|
||||
@@ -0,0 +1,472 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { getQuotaPerUnit } from '../../helpers';
|
||||
import { timestamp2string } from '../../helpers/utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { RefreshCw, ScrollText } from 'lucide-react';
|
||||
import {
|
||||
Table,
|
||||
Select,
|
||||
Button,
|
||||
Tag,
|
||||
Tooltip,
|
||||
Tabs,
|
||||
TabPane,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { API } from '../../helpers/api';
|
||||
import { useOrgAuditLogs } from '../../hooks/org/useOrgData';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgStateBlock from './components/OrgStateBlock';
|
||||
import OrgPromptRecords from './OrgPromptRecords';
|
||||
import {
|
||||
formatQuotaAsCNY,
|
||||
isQuotaDetailValue,
|
||||
isZeroUnlimitedQuotaKey,
|
||||
} from './orgAuditFormat';
|
||||
import { parseOrgFeatureFlag } from './orgFeatureFlags';
|
||||
|
||||
const tokenStatusMap = {
|
||||
1: '已启用',
|
||||
2: '已禁用',
|
||||
3: '已过期',
|
||||
4: '已耗尽',
|
||||
};
|
||||
|
||||
const orgStatusMap = {
|
||||
1: '正常',
|
||||
2: '冻结',
|
||||
3: '欠费',
|
||||
};
|
||||
|
||||
const memberStatusMap = {
|
||||
1: '正常',
|
||||
2: '禁用',
|
||||
};
|
||||
|
||||
const targetTypeLabels = {
|
||||
token: '令牌',
|
||||
member: '成员',
|
||||
organization: '企业',
|
||||
invitation: '邀请',
|
||||
};
|
||||
|
||||
const targetTypeColors = {
|
||||
token: 'violet',
|
||||
member: 'blue',
|
||||
organization: 'green',
|
||||
invitation: 'orange',
|
||||
};
|
||||
|
||||
// 操作分类:颜色 + 标签
|
||||
const actionConfig = {
|
||||
create_org: { label: '创建企业', color: 'green' },
|
||||
update_settings: { label: '更新设置', color: 'blue' },
|
||||
dissolve_org: { label: '解散企业', color: 'red' },
|
||||
transfer_ownership: { label: '转让所有权', color: 'orange' },
|
||||
join_org: { label: '加入企业', color: 'green' },
|
||||
leave_org: { label: '退出企业', color: 'orange' },
|
||||
update_quota_alert: { label: '更新配额预警', color: 'blue' },
|
||||
|
||||
invite_member: { label: '邀请成员', color: 'green' },
|
||||
remove_member: { label: '移除成员', color: 'red' },
|
||||
update_member_role: { label: '更新角色', color: 'blue' },
|
||||
update_member_quota: { label: '更新配额', color: 'blue' },
|
||||
update_member_status: { label: '更新状态', color: 'blue' },
|
||||
update_member_model_limits: { label: '更新模型限制', color: 'blue' },
|
||||
update_member_admin_permissions: { label: '更新管理员权限', color: 'blue' },
|
||||
accept_invitation: { label: '接受邀请', color: 'green' },
|
||||
cancel_invitation: { label: '取消邀请', color: 'grey' },
|
||||
|
||||
create_token: { label: '创建令牌', color: 'green' },
|
||||
update_token: { label: '更新令牌', color: 'blue' },
|
||||
delete_token: { label: '删除令牌', color: 'red' },
|
||||
|
||||
admin_create_org: { label: '管理员创建企业', color: 'cyan' },
|
||||
admin_update_org: { label: '管理员更新企业', color: 'cyan' },
|
||||
admin_delete_org: { label: '管理员删除企业', color: 'red' },
|
||||
// 注:建企业时配的初始额度也写这条 action(供预警取"加额时刻",detail.source=org_create_initial),
|
||||
// 渲染时按 source 区分,避免审计阅读者把它误读成"建号当天有人又改了一次额度"
|
||||
admin_adjust_quota: { label: '管理员调整额度', color: 'cyan' },
|
||||
org_alert_mute: { label: '屏蔽预警通知', color: 'grey' },
|
||||
org_alert_unmute: { label: '恢复预警通知', color: 'green' },
|
||||
admin_update_status: { label: '管理员更新状态', color: 'cyan' },
|
||||
};
|
||||
|
||||
const detailKeyLabels = {
|
||||
name: '名称',
|
||||
code: '邀请码',
|
||||
status: '状态',
|
||||
unlimited_quota: '无限额度',
|
||||
remain_quota: '剩余额度',
|
||||
quota_limit: '额度上限',
|
||||
email: '邮箱',
|
||||
role: '角色',
|
||||
from: '原值',
|
||||
to: '新值',
|
||||
member_id: '成员ID',
|
||||
method: '方式',
|
||||
model_limits_enabled: '模型限制',
|
||||
model_limits: '可用模型',
|
||||
threshold: '预警阈值',
|
||||
owner: '所有者',
|
||||
amount: '调整额度',
|
||||
org_name: '企业名称',
|
||||
before_quota: '调整前额度',
|
||||
expired_time: '过期时间',
|
||||
allow_ips: 'IP白名单',
|
||||
group: '分组',
|
||||
max_members: '最大成员数',
|
||||
max_tokens: '最大令牌数',
|
||||
default_member_quota: '新成员默认额度上限',
|
||||
cycle_quota: '周期额度',
|
||||
cycle_quota_delta: '周期额度增量',
|
||||
quota_period: '配额周期',
|
||||
};
|
||||
|
||||
// 根据 action 上下文选择正确的 status 映射
|
||||
function getStatusLabel(action, value) {
|
||||
if (
|
||||
action.startsWith('admin_') ||
|
||||
action === 'create_org' ||
|
||||
action === 'dissolve_org'
|
||||
) {
|
||||
return orgStatusMap[value];
|
||||
}
|
||||
if (action.includes('member')) {
|
||||
return memberStatusMap[value];
|
||||
}
|
||||
return tokenStatusMap[value];
|
||||
}
|
||||
|
||||
function formatDetailValue(action, key, value, t, quotaPerUnit) {
|
||||
if (isQuotaDetailValue(action, key)) {
|
||||
// 保留旧行为:空字符串表示「已清除」,不能落进 Number('')===0 → ¥0.00
|
||||
if (typeof value === 'string' && value === '') {
|
||||
return t('已清除');
|
||||
}
|
||||
// 上限类字段 0 = 不限制(后端 QuotaLimit <= 0 跳过限额),显示 ¥0.00 会误导为零额度
|
||||
if (Number(value) === 0 && isZeroUnlimitedQuotaKey(key)) {
|
||||
return t('不限制');
|
||||
}
|
||||
return formatQuotaAsCNY(value, quotaPerUnit);
|
||||
}
|
||||
if (key === 'status') {
|
||||
const label = getStatusLabel(action, value);
|
||||
return label ? t(label) : String(value);
|
||||
}
|
||||
if (key === 'unlimited_quota' || key === 'model_limits_enabled') {
|
||||
return value ? t('是') : t('否');
|
||||
}
|
||||
if (key === 'expired_time') {
|
||||
if (value === -1) return t('永不过期');
|
||||
return timestamp2string(value);
|
||||
}
|
||||
if (typeof value === 'string' && value === '') {
|
||||
return t('已清除');
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function formatDetail(action, obj, t, quotaPerUnit) {
|
||||
if (!obj) return '-';
|
||||
const parts = [];
|
||||
|
||||
Object.entries(obj).forEach(([k, v]) => {
|
||||
if (v === null || v === undefined) return;
|
||||
const label = t(detailKeyLabels[k] || k);
|
||||
parts.push(label + ': ' + formatDetailValue(action, k, v, t, quotaPerUnit));
|
||||
});
|
||||
|
||||
return parts.length > 0 ? parts.join(', ') : '-';
|
||||
}
|
||||
|
||||
function formatRelativeTime(timestamp, t) {
|
||||
if (!timestamp) return '-';
|
||||
const now = Date.now();
|
||||
const diff = now - timestamp * 1000;
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (seconds < 60) return t('刚刚');
|
||||
if (minutes < 60) return minutes + t('分钟前');
|
||||
if (hours < 24) return hours + t('小时前');
|
||||
if (days < 30) return days + t('天前');
|
||||
return new Date(timestamp * 1000).toLocaleDateString();
|
||||
}
|
||||
|
||||
const OrgAudit = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const quotaPerUnit = getQuotaPerUnit();
|
||||
const { logs, total, loading, fetch } = useOrgAuditLogs(orgId);
|
||||
const [page, setPage] = useState(1);
|
||||
const [actionFilter, setActionFilter] = useState('');
|
||||
const [activeTab, setActiveTab] = useState('operations');
|
||||
// 提示词记录 tab 由企业 feature flag(prompt_archive)控制显隐
|
||||
const [promptArchiveEnabled, setPromptArchiveEnabled] = useState(false);
|
||||
// 且需当前用户具备查看权限(owner 恒真;admin 需 owner 授予),与后端 RequireOrgAdminPermission 对齐
|
||||
const [canViewPromptRecords, setCanViewPromptRecords] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(page, 20, actionFilter);
|
||||
}, [fetch, page, actionFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
let cancelled = false;
|
||||
// 切换企业先隐藏,避免上一企业的 flag/权限残留
|
||||
setPromptArchiveEnabled(false);
|
||||
setCanViewPromptRecords(false);
|
||||
// 两个判断相互独立:feature flag 与个人权限各自 try,一个失败不牵连另一个(避免整块 tab 误隐)
|
||||
(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/org/info', {
|
||||
headers: { 'X-Org-Id': String(orgId) },
|
||||
});
|
||||
const flags = res.data?.data?.organization?.feature_flags;
|
||||
// 解析语义必须与后端 RequireOrgFeature 一致,否则 tab 显隐与接口放行口径割裂
|
||||
if (!cancelled)
|
||||
setPromptArchiveEnabled(parseOrgFeatureFlag(flags, 'prompt_archive'));
|
||||
} catch {
|
||||
// 忽略:无 flag 时不展示提示词 tab
|
||||
}
|
||||
})();
|
||||
(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/org/me/summary', {
|
||||
headers: { 'X-Org-Id': String(orgId) },
|
||||
});
|
||||
// 与后端 RequireOrgAdminPermission 对齐:owner 恒真,admin 依 owner 授予
|
||||
if (!cancelled)
|
||||
setCanViewPromptRecords(
|
||||
!!res.data?.data?.member?.can_view_prompt_records,
|
||||
);
|
||||
} catch {
|
||||
// 忽略:拉取失败时按无权限处理(fail-closed)
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [orgId]);
|
||||
|
||||
const actionOptions = [
|
||||
{ value: '', label: t('全部操作') },
|
||||
// 企业操作
|
||||
{ value: 'create_org', label: t('创建企业') },
|
||||
{ value: 'update_settings', label: t('更新设置') },
|
||||
{ value: 'transfer_ownership', label: t('转让所有权') },
|
||||
{ value: 'update_quota_alert', label: t('更新配额预警') },
|
||||
{ value: 'dissolve_org', label: t('解散企业') },
|
||||
// 成员操作
|
||||
{ value: 'invite_member', label: t('邀请成员') },
|
||||
{ value: 'accept_invitation', label: t('接受邀请') },
|
||||
{ value: 'cancel_invitation', label: t('取消邀请') },
|
||||
{ value: 'join_org', label: t('加入企业') },
|
||||
{ value: 'leave_org', label: t('退出企业') },
|
||||
{ value: 'remove_member', label: t('移除成员') },
|
||||
{ value: 'update_member_role', label: t('更新角色') },
|
||||
{ value: 'update_member_quota', label: t('更新配额') },
|
||||
{ value: 'update_member_status', label: t('更新状态') },
|
||||
{ value: 'update_member_model_limits', label: t('更新模型限制') },
|
||||
{ value: 'update_member_admin_permissions', label: t('更新管理员权限') },
|
||||
// 令牌操作
|
||||
{ value: 'create_token', label: t('创建令牌') },
|
||||
{ value: 'update_token', label: t('更新令牌') },
|
||||
{ value: 'delete_token', label: t('删除令牌') },
|
||||
// 管理员操作
|
||||
{ value: 'admin_create_org', label: t('管理员创建企业') },
|
||||
{ value: 'admin_update_org', label: t('管理员更新企业') },
|
||||
{ value: 'admin_delete_org', label: t('管理员删除企业') },
|
||||
{ value: 'admin_adjust_quota', label: t('管理员调整额度') },
|
||||
{ value: 'admin_update_status', label: t('管理员更新状态') },
|
||||
];
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('操作者'),
|
||||
dataIndex: 'operator_name',
|
||||
width: 120,
|
||||
render: (name, record) => (
|
||||
<span className='text-sm text-gray-700 dark:text-gray-300 truncate'>
|
||||
{name || `User#${record.operator_id}`}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
dataIndex: 'action',
|
||||
width: 170,
|
||||
render: (action, record) => {
|
||||
const config = actionConfig[action];
|
||||
if (!config) return <Tag size='small'>{action}</Tag>;
|
||||
// 建企业时配的初始额度复用 admin_adjust_quota(供预警取"加额时刻"),
|
||||
// 但它不是二次人工调额,按 detail.source 区分展示
|
||||
let label = config.label;
|
||||
if (action === 'admin_adjust_quota') {
|
||||
try {
|
||||
const detail = record?.detail ? JSON.parse(record.detail) : null;
|
||||
if (detail?.source === 'org_create_initial') {
|
||||
label = '建企业初始额度';
|
||||
}
|
||||
} catch {
|
||||
// detail 非 JSON 时按默认标签展示
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Tag size='small' color={config.color} type='light'>
|
||||
{t(label)}
|
||||
</Tag>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('目标类型'),
|
||||
dataIndex: 'target_type',
|
||||
width: 90,
|
||||
render: (type) => (
|
||||
<Tag size='small' color={targetTypeColors[type] || 'grey'} type='ghost'>
|
||||
{t(targetTypeLabels[type] || type)}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('详情'),
|
||||
dataIndex: 'detail',
|
||||
render: (detail, record) => {
|
||||
if (!detail)
|
||||
return <span className='text-gray-400 dark:text-gray-500'>-</span>;
|
||||
try {
|
||||
const obj = JSON.parse(detail);
|
||||
const text = formatDetail(record.action, obj, t, quotaPerUnit);
|
||||
if (text.length > 60) {
|
||||
return (
|
||||
<Tooltip
|
||||
content={text}
|
||||
position='topLeft'
|
||||
style={{ maxWidth: 400 }}
|
||||
>
|
||||
<span className='text-xs text-gray-600 dark:text-gray-400 cursor-default truncate block max-w-xs'>
|
||||
{text}
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className='text-xs text-gray-600 dark:text-gray-400'>
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
} catch {
|
||||
return (
|
||||
<span className='text-xs text-gray-600 dark:text-gray-400'>
|
||||
{detail}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('时间'),
|
||||
dataIndex: 'created_at',
|
||||
width: 140,
|
||||
render: (v) =>
|
||||
v ? (
|
||||
<Tooltip content={new Date(v * 1000).toLocaleString('zh-CN')}>
|
||||
<span className='text-xs text-gray-500 dark:text-gray-400 cursor-default'>
|
||||
{formatRelativeTime(v, t)}
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
'-'
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
title={t('审计日志')}
|
||||
subtitle={t('查看企业操作记录')}
|
||||
actions={
|
||||
activeTab === 'operations' ? (
|
||||
<>
|
||||
<Button
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={() => fetch(page, 20, actionFilter)}
|
||||
loading={loading}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
<Select
|
||||
value={actionFilter}
|
||||
onChange={(v) => {
|
||||
setActionFilter(v);
|
||||
setPage(1);
|
||||
}}
|
||||
optionList={actionOptions}
|
||||
style={{ width: 200 }}
|
||||
placeholder={t('筛选操作')}
|
||||
filter
|
||||
/>
|
||||
</>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
<Tabs
|
||||
type='line'
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
className='mt-2'
|
||||
>
|
||||
<TabPane tab={t('操作审计')} itemKey='operations'>
|
||||
<OrgPanel bodyClassName='overflow-x-auto' className='mt-4'>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={logs}
|
||||
loading={loading}
|
||||
rowKey='id'
|
||||
pagination={{
|
||||
currentPage: page,
|
||||
pageSize: 20,
|
||||
total,
|
||||
onPageChange: setPage,
|
||||
}}
|
||||
empty={
|
||||
<OrgStateBlock icon={ScrollText} title={t('暂无审计日志')} />
|
||||
}
|
||||
/>
|
||||
</OrgPanel>
|
||||
</TabPane>
|
||||
|
||||
{promptArchiveEnabled && canViewPromptRecords && (
|
||||
<TabPane tab={t('提示词记录')} itemKey='prompt-records'>
|
||||
<OrgPromptRecords key={orgId} orgId={orgId} />
|
||||
</TabPane>
|
||||
)}
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgAudit;
|
||||
@@ -0,0 +1,543 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Form,
|
||||
Toast,
|
||||
Tag,
|
||||
Progress,
|
||||
Banner,
|
||||
Popconfirm,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { RefreshCw, Plus, Pencil, Trash2 } from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import {
|
||||
renderQuota,
|
||||
displayAmountToQuota,
|
||||
quotaToDisplayAmount,
|
||||
getQuotaInputUnit,
|
||||
} from '../../helpers/render';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgModal from './components/OrgModal';
|
||||
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
const subjectTypeLabel = (t, st) =>
|
||||
({
|
||||
department: t('部门'),
|
||||
project: t('项目'),
|
||||
member: t('成员'),
|
||||
token: t('令牌'),
|
||||
org: t('企业'),
|
||||
})[st] || st;
|
||||
|
||||
const cycleLabel = (t, c) =>
|
||||
({
|
||||
none: t('不限周期'),
|
||||
daily: t('每日'),
|
||||
weekly: t('每周'),
|
||||
monthly: t('每月'),
|
||||
custom: t('自定义'),
|
||||
})[c] || c;
|
||||
|
||||
// 预算中心:管理员配置部门/项目预算 cap(§5.3)。只提 cap,不增企业池。
|
||||
const OrgBudgets = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const [list, setList] = useState([]);
|
||||
// null=未知(接口未返回该字段的旧后端),true/false=预算 cap 是否真正在扣费链路生效
|
||||
const [enforcementEnabled, setEnforcementEnabled] = useState(null);
|
||||
// 未生效的细分原因:平台级引擎急停(engine=false) vs 企业未开「预算实时拦截」
|
||||
const [engineEnabled, setEngineEnabled] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [depts, setDepts] = useState([]);
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [formApi, setFormApi] = useState(null);
|
||||
const [subjectType, setSubjectType] = useState('project');
|
||||
// 编辑中的预算行;null=新建。后端 PUT 为按主体 upsert,编辑复用同一接口
|
||||
const [editing, setEditing] = useState(null);
|
||||
|
||||
// 金额输入单位跟随站点展示货币(TOKENS 模式为原始额度单位)。
|
||||
// 每次 render 实时读取,避免货币配置异步落地后 label 与换算口径脱节
|
||||
const unit = getQuotaInputUnit();
|
||||
const quotaFieldLabel = (name) =>
|
||||
unit.isToken
|
||||
? `${name}(${t('额度单位')},0=${t('不限')})`
|
||||
: `${name}(${unit.symbol},0=${t('不限')})`;
|
||||
|
||||
const fetchAll = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [b, d, p] = await Promise.all([
|
||||
API.get('/api/org/budget', { headers: getOrgHeaders(orgId) }),
|
||||
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }),
|
||||
API.get('/api/org/project', { headers: getOrgHeaders(orgId) }),
|
||||
]);
|
||||
if (b.data.success) {
|
||||
// 新后端返回 {items, enforcement_enabled, engine_enabled};兼容旧后端直接返回数组
|
||||
const payload = b.data.data;
|
||||
if (Array.isArray(payload)) {
|
||||
setList(payload || []);
|
||||
setEnforcementEnabled(null);
|
||||
setEngineEnabled(null);
|
||||
} else {
|
||||
setList(payload?.items || []);
|
||||
setEnforcementEnabled(payload?.enforcement_enabled ?? null);
|
||||
setEngineEnabled(payload?.engine_enabled ?? null);
|
||||
}
|
||||
} else {
|
||||
showError(b.data.message);
|
||||
// 拉取失败回到「未知」,避免 Banner 停留在陈旧状态
|
||||
setEnforcementEnabled(null);
|
||||
setEngineEnabled(null);
|
||||
}
|
||||
if (d.data.success) setDepts(d.data.data || []);
|
||||
if (p.data.success) setProjects(p.data.data || []);
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
setEnforcementEnabled(null);
|
||||
setEngineEnabled(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAll();
|
||||
}, [fetchAll]);
|
||||
|
||||
// 主体名称与存在性优先取后端 subject_* 字段(覆盖成员/令牌,且能区分「已删除」与「已停用」);
|
||||
// 旧后端未返回时回落到本地部门/项目列表匹配。
|
||||
const subjectOf = useCallback(
|
||||
(r) => {
|
||||
const st = r.subject_type;
|
||||
if (r.subject_exists !== undefined) {
|
||||
return {
|
||||
name: r.subject_name || `#${r.subject_id}`,
|
||||
exists: !!r.subject_exists,
|
||||
disabled: r.subject_status === 2,
|
||||
};
|
||||
}
|
||||
if (st === 'department') {
|
||||
const d = depts.find((x) => x.id === r.subject_id);
|
||||
return {
|
||||
name: d?.name || `#${r.subject_id}`,
|
||||
exists: !!d,
|
||||
disabled: d?.status === 2,
|
||||
};
|
||||
}
|
||||
if (st === 'project') {
|
||||
const p = projects.find((x) => x.id === r.subject_id);
|
||||
return {
|
||||
name: p?.name || `#${r.subject_id}`,
|
||||
exists: !!p,
|
||||
disabled: p?.status === 2,
|
||||
};
|
||||
}
|
||||
// 旧后端下成员/令牌无从解析,按存在处理,避免误标「已删除」
|
||||
return { name: `#${r.subject_id}`, exists: true, disabled: false };
|
||||
},
|
||||
[depts, projects],
|
||||
);
|
||||
|
||||
const subjectIdOptions = useMemo(() => {
|
||||
if (subjectType === 'department')
|
||||
return depts.map((d) => ({ label: d.name, value: d.id }));
|
||||
if (subjectType === 'project')
|
||||
return projects.map((p) => ({ label: p.name, value: p.id }));
|
||||
return [];
|
||||
}, [subjectType, depts, projects]);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setSubjectType('project');
|
||||
setModalVisible(true);
|
||||
};
|
||||
|
||||
const openEdit = (row) => {
|
||||
setEditing(row);
|
||||
setSubjectType(row.subject_type);
|
||||
setModalVisible(true);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (modalVisible && formApi) {
|
||||
if (editing) {
|
||||
// 编辑:金额字段回填为展示货币数值(与提交换算互逆)
|
||||
formApi.setValues({
|
||||
cycle_type: editing.cycle_type || 'none',
|
||||
custom_cycle_days: editing.custom_cycle_days || 0,
|
||||
over_limit_action: editing.over_limit_action || 'block',
|
||||
cycle_quota: quotaToDisplayAmount(editing.cycle_quota || 0),
|
||||
total_quota: quotaToDisplayAmount(editing.total_quota || 0),
|
||||
status: editing.status === 2 ? 2 : 1,
|
||||
});
|
||||
} else {
|
||||
// subject_id/custom_cycle_days 需显式重置:setValues 为合并模式,
|
||||
// 上一次编辑/新建的残留值会泄漏进本次提交
|
||||
formApi.setValues({
|
||||
subject_type: 'project',
|
||||
subject_id: undefined,
|
||||
cycle_type: 'monthly',
|
||||
custom_cycle_days: 0,
|
||||
over_limit_action: 'block',
|
||||
cycle_quota: 0,
|
||||
total_quota: 0,
|
||||
status: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [modalVisible, formApi, editing]);
|
||||
|
||||
const submit = async () => {
|
||||
if (!formApi) return;
|
||||
let v;
|
||||
try {
|
||||
v = await formApi.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await API.put(
|
||||
'/api/org/budget',
|
||||
{
|
||||
// 编辑时主体不可变,取自被编辑行;后端按主体 upsert
|
||||
subject_type: editing ? editing.subject_type : v.subject_type,
|
||||
subject_id: editing ? editing.subject_id : v.subject_id,
|
||||
cycle_type: v.cycle_type,
|
||||
cycle_quota: displayAmountToQuota(v.cycle_quota || 0),
|
||||
total_quota: displayAmountToQuota(v.total_quota || 0),
|
||||
// 弹窗未提供该字段的输入控件,编辑时从被编辑行透传,不依赖表单状态
|
||||
// (若表单丢弃未注册字段,这里取 0 会把存量自定义周期静默改成 30 天兜底)
|
||||
custom_cycle_days: editing
|
||||
? editing.custom_cycle_days || 0
|
||||
: v.custom_cycle_days || 0,
|
||||
over_limit_action: v.over_limit_action,
|
||||
// 不传 status 后端会默认置回启用,编辑停用中的预算会被悄悄激活,必须显式携带
|
||||
status: v.status === 2 ? 2 : 1,
|
||||
},
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('预算已保存'));
|
||||
setModalVisible(false);
|
||||
fetchAll();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (record) => {
|
||||
try {
|
||||
const res = await API.delete(`/api/org/budget/${record.id}`, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
Toast.success(t('预算已删除'));
|
||||
fetchAll();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('主体'),
|
||||
render: (_, r) => {
|
||||
const subj = subjectOf(r);
|
||||
return (
|
||||
<span>
|
||||
<Tag color='blue' size='small'>
|
||||
{subjectTypeLabel(t, r.subject_type)}
|
||||
</Tag>{' '}
|
||||
<span className={subj.exists ? '' : 'text-gray-400 line-through'}>
|
||||
{subj.name}
|
||||
</span>{' '}
|
||||
{!subj.exists && (
|
||||
<Tag color='red' size='small'>
|
||||
{t('主体已删除')}
|
||||
</Tag>
|
||||
)}
|
||||
{subj.exists && subj.disabled && (
|
||||
<Tag color='grey' size='small'>
|
||||
{t('已停用')}
|
||||
</Tag>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('周期'),
|
||||
dataIndex: 'cycle_type',
|
||||
render: (v) => cycleLabel(t, v),
|
||||
width: 90,
|
||||
},
|
||||
{
|
||||
title: t('周期用量 / cap'),
|
||||
width: 220,
|
||||
render: (_, r) => {
|
||||
if (!r.cycle_quota)
|
||||
return <span className='text-xs text-gray-400'>{t('不限')}</span>;
|
||||
const pct = Math.min(
|
||||
100,
|
||||
Math.round((r.used_in_cycle / r.cycle_quota) * 100),
|
||||
);
|
||||
return (
|
||||
<div>
|
||||
<Progress
|
||||
percent={pct}
|
||||
size='small'
|
||||
stroke={pct >= 90 ? 'var(--semi-color-danger)' : undefined}
|
||||
/>
|
||||
<span className='text-xs text-gray-500'>
|
||||
{renderQuota(r.used_in_cycle, 2)}
|
||||
{r.reserved_in_cycle > 0
|
||||
? ` (+${renderQuota(r.reserved_in_cycle, 2)} ${t('预留')})`
|
||||
: ''}
|
||||
{' / '}
|
||||
{renderQuota(r.cycle_quota, 2)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('超限动作'),
|
||||
dataIndex: 'over_limit_action',
|
||||
// 90px 是按中文两字标签定的,泰语最短的地道说法 "เมื่อเกินขีดจำกัด" 也要 ~150px;
|
||||
// 这一列没有更短的译法,只能让列让位(其余列头已在 kt_overrides_th.json 收敛用词)
|
||||
width: 150,
|
||||
render: () => t('拦截'),
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: 80,
|
||||
render: (v) => (
|
||||
<Tag color={v === 1 ? 'green' : 'grey'}>
|
||||
{v === 1 ? t('启用') : t('停用')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 160,
|
||||
render: (_, r) => {
|
||||
const subj = subjectOf(r);
|
||||
return (
|
||||
<div className='flex gap-1'>
|
||||
{/* 主体已删除的孤儿行改不了(后端 upsert 会因主体不存在报错),只留删除 */}
|
||||
{subj.exists && (
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
icon={<Pencil size={14} />}
|
||||
onClick={() => openEdit(r)}
|
||||
>
|
||||
{t('编辑')}
|
||||
</Button>
|
||||
)}
|
||||
<Popconfirm
|
||||
title={t('确认删除该预算?')}
|
||||
content={t(
|
||||
'删除后该主体不再受此额度上限约束,历史用量流水保留不受影响',
|
||||
)}
|
||||
onConfirm={() => handleDelete(r)}
|
||||
>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
type='danger'
|
||||
icon={<Trash2 size={14} />}
|
||||
>
|
||||
{t('删除')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
title={t('预算中心')}
|
||||
subtitle={t('部门 / 项目 / 成员的额度上限')}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<RefreshCw size={14} />}
|
||||
loading={loading}
|
||||
onClick={fetchAll}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='solid'
|
||||
icon={<Plus size={14} />}
|
||||
onClick={openCreate}
|
||||
>
|
||||
{t('配置预算')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{enforcementEnabled === false && (
|
||||
<Banner
|
||||
type='warning'
|
||||
closeIcon={null}
|
||||
description={
|
||||
engineEnabled === false
|
||||
? t(
|
||||
'预算引擎已被平台全局急停:所有企业的预算拦截与用量统计均暂停,恢复需平台管理员开启系统开关,与本企业配置无关。',
|
||||
)
|
||||
: t(
|
||||
'预算实时拦截当前未生效:这里的配置只会被保存,不会拦截超额调用,也不会累计用量统计。请联系平台管理员开启本企业的「预算实时拦截」功能。',
|
||||
)
|
||||
}
|
||||
className='mb-4'
|
||||
/>
|
||||
)}
|
||||
<Banner
|
||||
type='info'
|
||||
closeIcon={null}
|
||||
description={t(
|
||||
'预算只设置「最多能花多少」的上限(cap),不增加企业真实额度池;提额仅提高上限。',
|
||||
)}
|
||||
className='mb-4'
|
||||
/>
|
||||
|
||||
<OrgPanel padding='p-2'>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={list}
|
||||
loading={loading}
|
||||
pagination={false}
|
||||
rowKey='id'
|
||||
/>
|
||||
</OrgPanel>
|
||||
|
||||
<OrgModal
|
||||
title={editing ? t('编辑预算') : t('配置预算')}
|
||||
visible={modalVisible}
|
||||
onOk={submit}
|
||||
onCancel={() => setModalVisible(false)}
|
||||
okText={t('保存')}
|
||||
cancelText={t('取消')}
|
||||
>
|
||||
<Form getFormApi={setFormApi}>
|
||||
{editing ? (
|
||||
<div className='mb-3'>
|
||||
<Tag color='blue' size='small'>
|
||||
{subjectTypeLabel(t, editing.subject_type)}
|
||||
</Tag>{' '}
|
||||
{subjectOf(editing).name}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Form.Select
|
||||
field='subject_type'
|
||||
label={t('主体类型')}
|
||||
optionList={[
|
||||
{ label: t('项目'), value: 'project' },
|
||||
{ label: t('部门'), value: 'department' },
|
||||
]}
|
||||
onChange={(v) => setSubjectType(v)}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.Select
|
||||
field='subject_id'
|
||||
label={t('主体')}
|
||||
optionList={subjectIdOptions}
|
||||
rules={[{ required: true, message: t('请选择主体') }]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<Form.Select
|
||||
field='cycle_type'
|
||||
label={t('周期')}
|
||||
optionList={[
|
||||
{ label: t('每月'), value: 'monthly' },
|
||||
{ label: t('每周'), value: 'weekly' },
|
||||
{ label: t('每日'), value: 'daily' },
|
||||
{ label: t('不限周期'), value: 'none' },
|
||||
// 该 UI 暂不支持新建自定义周期,仅在编辑存量自定义周期预算时保留原值
|
||||
...(editing?.cycle_type === 'custom'
|
||||
? [{ label: t('自定义'), value: 'custom' }]
|
||||
: []),
|
||||
]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.InputNumber
|
||||
field='cycle_quota'
|
||||
label={quotaFieldLabel(t('周期上限'))}
|
||||
min={0}
|
||||
precision={unit.isToken ? 0 : 2}
|
||||
suffix={unit.isToken ? null : unit.symbol}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.InputNumber
|
||||
field='total_quota'
|
||||
label={quotaFieldLabel(t('总上限'))}
|
||||
min={0}
|
||||
precision={unit.isToken ? 0 : 2}
|
||||
suffix={unit.isToken ? null : unit.symbol}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.Select
|
||||
field='over_limit_action'
|
||||
label={t('超限动作')}
|
||||
optionList={[{ label: t('拦截'), value: 'block' }]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
{editing && (
|
||||
<Form.Select
|
||||
field='status'
|
||||
label={t('状态')}
|
||||
optionList={[
|
||||
{ label: t('启用'), value: 1 },
|
||||
{ label: t('停用'), value: 2 },
|
||||
]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
)}
|
||||
</Form>
|
||||
</OrgModal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgBudgets;
|
||||
@@ -0,0 +1,757 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
SideSheet,
|
||||
Switch,
|
||||
TabPane,
|
||||
Tabs,
|
||||
Tag,
|
||||
TextArea,
|
||||
Toast,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { Cable, KeyRound, Plus, RefreshCw, ShieldCheck } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers/api';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuidePill,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import './org-connectors.css';
|
||||
|
||||
const headersFor = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
const blankConnector = {
|
||||
definition_id: undefined,
|
||||
instance_key: '',
|
||||
display_name: '',
|
||||
base_url: '',
|
||||
config: '{}',
|
||||
allowed_hosts: '',
|
||||
allowed_cidrs: '',
|
||||
egress_policy: 'public_https',
|
||||
};
|
||||
|
||||
const parseLines = (value) =>
|
||||
value
|
||||
.split(/[,\n]/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const OrgConnectors = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const headers = useMemo(() => headersFor(orgId), [orgId]);
|
||||
const [definitions, setDefinitions] = useState([]);
|
||||
const [connectors, setConnectors] = useState([]);
|
||||
const [grants, setGrants] = useState([]);
|
||||
const [audit, setAudit] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [credentialOpen, setCredentialOpen] = useState(false);
|
||||
const [grantOpen, setGrantOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [form, setForm] = useState(blankConnector);
|
||||
const [selected, setSelected] = useState(null);
|
||||
const [credential, setCredential] = useState(
|
||||
'{\n "headers": {\n "Authorization": "Bearer ..."\n }\n}',
|
||||
);
|
||||
const [grant, setGrant] = useState({
|
||||
grant_key: '',
|
||||
connector_id: undefined,
|
||||
expert_id: undefined,
|
||||
scope_type: 'organization',
|
||||
scope_id: 0,
|
||||
method_keys: [],
|
||||
access_level: 'read',
|
||||
confirmation_policy: 'write',
|
||||
external_allowed: false,
|
||||
max_calls_per_run: 5,
|
||||
max_result_bytes: 65536,
|
||||
});
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [
|
||||
definitionResponse,
|
||||
connectorResponse,
|
||||
grantResponse,
|
||||
auditResponse,
|
||||
] = await Promise.all([
|
||||
API.get('/api/org/connectors/definitions', { headers }),
|
||||
API.get('/api/org/connectors', { headers }),
|
||||
API.get('/api/org/connectors/grants', { headers }),
|
||||
API.get('/api/org/connectors/audit', { headers }),
|
||||
]);
|
||||
setDefinitions(definitionResponse.data?.data || []);
|
||||
setConnectors(connectorResponse.data?.data || []);
|
||||
setGrants(grantResponse.data?.data || []);
|
||||
setAudit(auditResponse.data?.data || []);
|
||||
} catch (error) {
|
||||
Toast.error(error?.response?.data?.message || error.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [headers]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const definitionsById = useMemo(
|
||||
() => new Map(definitions.map((item) => [item.definition.id, item])),
|
||||
[definitions],
|
||||
);
|
||||
const connectorRows = useMemo(
|
||||
() => connectors.map((item) => item.connector || item),
|
||||
[connectors],
|
||||
);
|
||||
const connectorViewById = useMemo(
|
||||
() =>
|
||||
new Map(connectors.map((item) => [(item.connector || item).id, item])),
|
||||
[connectors],
|
||||
);
|
||||
const selectedGrantConnector = connectorRows.find(
|
||||
(item) => item.id === grant.connector_id,
|
||||
);
|
||||
const grantDefinition = selectedGrantConnector
|
||||
? definitionsById.get(selectedGrantConnector.definition_id)
|
||||
: null;
|
||||
// Method options must come from the instance's PINNED definition version
|
||||
// (the backend validates against it); the definition catalog only carries
|
||||
// the latest version, whose new methods would be rejected on save.
|
||||
const grantConnectorView = grant.connector_id
|
||||
? connectorViewById.get(grant.connector_id)
|
||||
: null;
|
||||
const grantMethodOptions =
|
||||
grantConnectorView?.methods || grantDefinition?.methods || [];
|
||||
const grantConnectorType =
|
||||
grantDefinition?.version?.connector_type ||
|
||||
grantDefinition?.definition?.connector_type ||
|
||||
'';
|
||||
|
||||
const openCreate = () => {
|
||||
setSelected(null);
|
||||
setForm(blankConnector);
|
||||
setEditorOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (row) => {
|
||||
setSelected(row);
|
||||
setForm({
|
||||
id: row.id,
|
||||
definition_id: row.definition_id,
|
||||
definition_version_id: row.definition_version_id,
|
||||
instance_key: row.instance_key,
|
||||
display_name: row.display_name,
|
||||
base_url: row.base_url || '',
|
||||
config: row.config || row.ConfigJSON || row.config_json || '{}',
|
||||
allowed_hosts: (() => {
|
||||
try {
|
||||
return JSON.parse(
|
||||
row.allowed_hosts || row.allowed_hosts_json || '[]',
|
||||
).join('\n');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})(),
|
||||
allowed_cidrs: (() => {
|
||||
try {
|
||||
return JSON.parse(
|
||||
row.allowed_cidrs || row.allowed_cidrs_json || '[]',
|
||||
).join('\n');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})(),
|
||||
egress_policy: row.egress_policy || 'public_https',
|
||||
});
|
||||
setEditorOpen(true);
|
||||
};
|
||||
|
||||
const saveConnector = async () => {
|
||||
let config;
|
||||
try {
|
||||
config = JSON.parse(form.config || '{}');
|
||||
} catch {
|
||||
Toast.warning(t('配置必须是有效 JSON'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload = {
|
||||
...form,
|
||||
config,
|
||||
allowed_hosts: parseLines(form.allowed_hosts),
|
||||
allowed_cidrs: parseLines(form.allowed_cidrs),
|
||||
};
|
||||
const url = form.id
|
||||
? `/api/org/connectors/${form.id}`
|
||||
: '/api/org/connectors';
|
||||
const response = form.id
|
||||
? await API.put(url, payload, { headers })
|
||||
: await API.post(url, payload, { headers });
|
||||
if (!response.data?.success) throw new Error(response.data?.message);
|
||||
setEditorOpen(false);
|
||||
Toast.success(t('Connector 配置已保存'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
Toast.error(error?.response?.data?.message || error.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const saveCredential = async () => {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(credential);
|
||||
} catch {
|
||||
Toast.warning(t('凭据必须是有效 JSON'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await API.put(
|
||||
`/api/org/connectors/${selected.id}/credential`,
|
||||
{ credential: parsed },
|
||||
{ headers },
|
||||
);
|
||||
setCredentialOpen(false);
|
||||
Toast.success(t('凭据已加密轮换,旧凭据已停用'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
Toast.error(error?.response?.data?.message || error.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const saveGrant = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await API.post('/api/org/connectors/grants', grant, { headers });
|
||||
setGrantOpen(false);
|
||||
Toast.success(t('授权版本已发布'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
Toast.error(error?.response?.data?.message || error.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const revoke = (row) => {
|
||||
Modal.confirm({
|
||||
title: t('撤销 Connector'),
|
||||
content: t('撤销后,排队和等待确认的调用都会在执行前重新校验并被阻断。'),
|
||||
onOk: async () => {
|
||||
await API.post(
|
||||
`/api/org/connectors/${row.id}/revoke`,
|
||||
{ reason: 'Revoked from organization connector console' },
|
||||
{ headers },
|
||||
);
|
||||
await load();
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// 使用指引:连接器从接入到可被专家调用的四步,完成态由真实数据驱动。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-connectors',
|
||||
ready: !loading,
|
||||
title: t('业务系统连接器 · 使用指引'),
|
||||
intro: t(
|
||||
'配置实例 → 加密凭据 → 发布授权 → 审计治理,让专家安全地调用业务系统',
|
||||
),
|
||||
steps: [
|
||||
{
|
||||
title: t('配置 Connector 实例'),
|
||||
detail: t('选择连接器类型,设置地址与网络边界'),
|
||||
done: connectorRows.length > 0,
|
||||
cta: t('去配置实例'),
|
||||
onAction: openCreate,
|
||||
points: [
|
||||
t('填写实例键、显示名与 Base URL;主机白名单精确到域名'),
|
||||
t('出网策略二选一:公网 HTTPS,或已审批的内网 CIDR 段'),
|
||||
t('能力边界用 JSON 描述,保存前会做合法性校验'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('轮换加密凭据'),
|
||||
detail: t('凭据只进不出,界面永远只显示哈希后缀'),
|
||||
done: connectors.some((item) => Boolean(item.credential)),
|
||||
points: [
|
||||
t('在实例卡片点「轮换凭据」,粘贴 JSON 形式的认证头'),
|
||||
t('轮换后旧凭据立即停用;服务端不会回显明文'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('发布授权版本'),
|
||||
detail: t('按「专家 × 范围」发布不可变授权,专家才可调用'),
|
||||
done: grants.length > 0,
|
||||
points: [
|
||||
t('在「授权矩阵」页点「发布授权」,选择连接器、专家与范围'),
|
||||
t(
|
||||
'访问级别 read/write 与确认策略 never/write/always 决定哪些调用需成员确认',
|
||||
),
|
||||
t('每次任务的调用次数与返回字节都有上限,防止失控'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('审计与治理'),
|
||||
detail: t('每次调用都有审计记录,出问题可随时撤销'),
|
||||
done: grants.length > 0,
|
||||
points: [
|
||||
t('「审计」页记录每次调用的动作、状态与摘要'),
|
||||
t('「撤销」实例后,排队和等待确认的调用都会在执行前被阻断'),
|
||||
],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('成员没有确认操作的入口?'),
|
||||
a: t(
|
||||
'确认发生在云端大脑的任务详情里;成员可在「我的业务系统授权」查看自己的授权范围',
|
||||
),
|
||||
},
|
||||
{
|
||||
q: t('HTTP 类型连接器发布授权被拦?'),
|
||||
a: t('需要先开启「允许向已审批外部系统发送必要参数」开关'),
|
||||
},
|
||||
],
|
||||
});
|
||||
const closeGuide = guide.close;
|
||||
// 抽屉进度是组织私有的:切组织时关闭,避免带着旧组织的完成态短暂展示。
|
||||
useEffect(() => {
|
||||
closeGuide();
|
||||
}, [orgId, closeGuide]);
|
||||
return (
|
||||
<main className='org-connector-page'>
|
||||
<header className='org-connector-hero'>
|
||||
<div>
|
||||
<h1>{t('业务系统连接器')}</h1>
|
||||
<p>{t('凭据、授权范围、写操作确认和调用审计在同一控制面闭环。')}</p>
|
||||
</div>
|
||||
<div className='org-connector-actions'>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
<Button
|
||||
icon={<RefreshCw size={16} />}
|
||||
loading={loading}
|
||||
onClick={load}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
<Button theme='solid' icon={<Plus size={16} />} onClick={openCreate}>
|
||||
{t('配置 Connector')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<PageGuidePill guide={guide} />
|
||||
<PageGuideDrawer guide={guide} />
|
||||
|
||||
<Tabs type='line'>
|
||||
<TabPane
|
||||
tab={`${t('实例')} · ${connectorRows.length}`}
|
||||
itemKey='instances'
|
||||
>
|
||||
<section className='org-connector-grid'>
|
||||
{connectorRows.map((row) => {
|
||||
const definition = definitionsById.get(row.definition_id);
|
||||
const credentialState = connectorViewById.get(row.id)?.credential;
|
||||
return (
|
||||
<article key={row.id} className='org-connector-card'>
|
||||
<div className='org-connector-card-top'>
|
||||
<span className='org-connector-icon'>
|
||||
<Cable size={20} />
|
||||
</span>
|
||||
<Tag color={row.status === 'active' ? 'green' : 'red'}>
|
||||
{row.status}
|
||||
</Tag>
|
||||
</div>
|
||||
<h3>{row.display_name}</h3>
|
||||
<p>
|
||||
{definition?.version?.description_zh ||
|
||||
definition?.version?.description_en}
|
||||
</p>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{t('实例键')}</dt>
|
||||
<dd>{row.instance_key}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{t('网络策略')}</dt>
|
||||
<dd>{row.egress_policy}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{t('凭据')}</dt>
|
||||
<dd>
|
||||
{credentialState
|
||||
? `•••• ${credentialState.masked_suffix}`
|
||||
: t('未配置')}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
<div className='org-connector-card-actions'>
|
||||
<Button size='small' onClick={() => openEdit(row)}>
|
||||
{t('配置')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
icon={<KeyRound size={14} />}
|
||||
onClick={() => {
|
||||
setSelected(row);
|
||||
setCredentialOpen(true);
|
||||
}}
|
||||
>
|
||||
{t('轮换凭据')}
|
||||
</Button>
|
||||
{row.status === 'active' && (
|
||||
<Button
|
||||
size='small'
|
||||
type='danger'
|
||||
onClick={() => revoke(row)}
|
||||
>
|
||||
{t('撤销')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
</TabPane>
|
||||
|
||||
<TabPane tab={`${t('授权矩阵')} · ${grants.length}`} itemKey='grants'>
|
||||
<div className='org-connector-section-head'>
|
||||
<p>
|
||||
{t('授权按专家与组织、部门、项目或成员范围发布为不可变版本。')}
|
||||
</p>
|
||||
<Button
|
||||
theme='solid'
|
||||
icon={<ShieldCheck size={16} />}
|
||||
onClick={() => {
|
||||
setGrant((current) => ({
|
||||
...current,
|
||||
connector_id: connectorRows[0]?.id,
|
||||
}));
|
||||
setGrantOpen(true);
|
||||
}}
|
||||
>
|
||||
{t('发布授权')}
|
||||
</Button>
|
||||
</div>
|
||||
<section className='org-connector-list'>
|
||||
{grants.map((item) => (
|
||||
<article key={item.id}>
|
||||
<div>
|
||||
<strong>
|
||||
{item.scope_type} #{item.scope_id || 0}
|
||||
</strong>
|
||||
<Tag>v{item.version}</Tag>
|
||||
</div>
|
||||
<code>{item.method_keys}</code>
|
||||
<span>
|
||||
{item.access_level} · {item.confirmation_policy} ·{' '}
|
||||
{item.max_calls_per_run}/run
|
||||
</span>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</TabPane>
|
||||
|
||||
<TabPane tab={`${t('审计')} · ${audit.length}`} itemKey='audit'>
|
||||
<section className='org-connector-list org-connector-audit'>
|
||||
{audit.map((item) => (
|
||||
<article key={item.id}>
|
||||
<div>
|
||||
<strong>{item.action}</strong>
|
||||
<Tag color={item.status === 'succeeded' ? 'green' : 'orange'}>
|
||||
{item.status}
|
||||
</Tag>
|
||||
</div>
|
||||
<code>{item.method_key || item.tool_call_id || '-'}</code>
|
||||
<span>{item.summary}</span>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
</TabPane>
|
||||
</Tabs>
|
||||
|
||||
<SideSheet
|
||||
title={form.id ? t('编辑 Connector') : t('配置 Connector')}
|
||||
visible={editorOpen}
|
||||
onCancel={() => setEditorOpen(false)}
|
||||
width={520}
|
||||
footer={
|
||||
<Button theme='solid' loading={saving} onClick={saveConnector}>
|
||||
{t('保存配置')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className='org-connector-form'>
|
||||
<label>
|
||||
{t('Connector 类型')}
|
||||
<Select
|
||||
value={form.definition_id}
|
||||
disabled={!!form.id}
|
||||
onChange={(value) => setForm({ ...form, definition_id: value })}
|
||||
optionList={definitions.map((item) => ({
|
||||
value: item.definition.id,
|
||||
label: item.version.name_zh || item.version.name_en,
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('实例键')}
|
||||
<Input
|
||||
value={form.instance_key}
|
||||
onChange={(value) => setForm({ ...form, instance_key: value })}
|
||||
placeholder='gitlab_primary'
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('显示名称')}
|
||||
<Input
|
||||
value={form.display_name}
|
||||
onChange={(value) => setForm({ ...form, display_name: value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('Base URL(HTTP 类型)')}
|
||||
<Input
|
||||
value={form.base_url}
|
||||
onChange={(value) => setForm({ ...form, base_url: value })}
|
||||
placeholder='https://api.example.com'
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('精确域名白名单')}
|
||||
<TextArea
|
||||
value={form.allowed_hosts}
|
||||
onChange={(value) => setForm({ ...form, allowed_hosts: value })}
|
||||
placeholder='api.example.com'
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('出站策略')}
|
||||
<Select
|
||||
value={form.egress_policy}
|
||||
onChange={(value) => setForm({ ...form, egress_policy: value })}
|
||||
optionList={[
|
||||
{ value: 'public_https', label: 'Public HTTPS' },
|
||||
{ value: 'approved_private', label: 'Approved private CIDR' },
|
||||
]}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('授权 CIDR(仅运维审批私网)')}
|
||||
<TextArea
|
||||
value={form.allowed_cidrs}
|
||||
onChange={(value) => setForm({ ...form, allowed_cidrs: value })}
|
||||
placeholder={'10.20.0.0/16\nfd00:1::/48'}
|
||||
/>
|
||||
<span className='org-connector-note'>
|
||||
{t(
|
||||
'仅接受具体的私网网段:IPv4 须为 RFC1918 且前缀 ≥ /16,IPv6 须为 fc00::/7 内且前缀 ≥ /48;每行一条。',
|
||||
)}
|
||||
</span>
|
||||
</label>
|
||||
<label>
|
||||
{t('能力边界 JSON')}
|
||||
<TextArea
|
||||
autosize
|
||||
value={form.config}
|
||||
onChange={(value) => setForm({ ...form, config: value })}
|
||||
placeholder='{"project_ids":["123"],"path_prefixes":["src/"]}'
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</SideSheet>
|
||||
|
||||
<Modal
|
||||
title={t('轮换加密凭据')}
|
||||
visible={credentialOpen}
|
||||
onCancel={() => setCredentialOpen(false)}
|
||||
onOk={saveCredential}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
<p className='org-connector-note'>
|
||||
{t('提交后只显示哈希尾号,服务端不会回显明文。')}
|
||||
</p>
|
||||
<TextArea autosize value={credential} onChange={setCredential} />
|
||||
</Modal>
|
||||
|
||||
<SideSheet
|
||||
title={t('发布授权版本')}
|
||||
visible={grantOpen}
|
||||
onCancel={() => setGrantOpen(false)}
|
||||
width={520}
|
||||
footer={
|
||||
<Button theme='solid' loading={saving} onClick={saveGrant}>
|
||||
{t('发布授权')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className='org-connector-form'>
|
||||
<label>
|
||||
{t('授权键')}
|
||||
<Input
|
||||
value={grant.grant_key}
|
||||
onChange={(value) => setGrant({ ...grant, grant_key: value })}
|
||||
placeholder='gitlab_read_engineering'
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('Connector 实例')}
|
||||
<Select
|
||||
value={grant.connector_id}
|
||||
onChange={(value) =>
|
||||
setGrant({ ...grant, connector_id: value, method_keys: [] })
|
||||
}
|
||||
optionList={connectorRows
|
||||
.filter((item) => item.status === 'active')
|
||||
.map((item) => ({ value: item.id, label: item.display_name }))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('专家 ID')}
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={grant.expert_id}
|
||||
onChange={(value) => setGrant({ ...grant, expert_id: value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('范围')}
|
||||
<Select
|
||||
value={grant.scope_type}
|
||||
onChange={(value) =>
|
||||
setGrant({
|
||||
...grant,
|
||||
scope_type: value,
|
||||
scope_id: value === 'organization' ? 0 : undefined,
|
||||
})
|
||||
}
|
||||
optionList={[
|
||||
'organization',
|
||||
'department',
|
||||
'project',
|
||||
'member',
|
||||
].map((value) => ({ value, label: value }))}
|
||||
/>
|
||||
</label>
|
||||
{grant.scope_type !== 'organization' && (
|
||||
<label>
|
||||
{t('范围 ID')}
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={grant.scope_id}
|
||||
onChange={(value) => setGrant({ ...grant, scope_id: value })}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
{t('允许的方法')}
|
||||
<Select
|
||||
multiple
|
||||
value={grant.method_keys}
|
||||
onChange={(value) => setGrant({ ...grant, method_keys: value })}
|
||||
optionList={grantMethodOptions.map((item) => ({
|
||||
value: item.method_key,
|
||||
label: `${item.name_zh || item.name_en} · ${item.operation_type}`,
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('访问级别')}
|
||||
<Select
|
||||
value={grant.access_level}
|
||||
onChange={(value) => setGrant({ ...grant, access_level: value })}
|
||||
optionList={[
|
||||
{ value: 'read', label: 'read' },
|
||||
{ value: 'write', label: 'write' },
|
||||
]}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('确认策略')}
|
||||
<Select
|
||||
value={grant.confirmation_policy}
|
||||
onChange={(value) =>
|
||||
setGrant({ ...grant, confirmation_policy: value })
|
||||
}
|
||||
optionList={['never', 'write', 'always'].map((value) => ({
|
||||
value,
|
||||
label: value,
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className='org-connector-switch'>
|
||||
<span>{t('允许向已审批外部系统发送必要参数')}</span>
|
||||
<Switch
|
||||
checked={grant.external_allowed}
|
||||
onChange={(value) =>
|
||||
setGrant({ ...grant, external_allowed: value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{grantConnectorType === 'http' && !grant.external_allowed && (
|
||||
<p className='org-connector-note'>
|
||||
{t(
|
||||
'HTTP 类型 Connector 必须开启此开关才会在任务运行时生效,关闭状态下无法发布授权。',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<label>
|
||||
{t('单任务调用上限')}
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={10}
|
||||
value={grant.max_calls_per_run}
|
||||
onChange={(value) =>
|
||||
setGrant({ ...grant, max_calls_per_run: value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('结果上限(字节)')}
|
||||
<InputNumber
|
||||
min={1024}
|
||||
max={1048576}
|
||||
value={grant.max_result_bytes}
|
||||
onChange={(value) =>
|
||||
setGrant({ ...grant, max_result_bytes: value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</SideSheet>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgConnectors;
|
||||
@@ -0,0 +1,299 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useState, useCallback, useEffect, useContext } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Building2,
|
||||
KeyRound,
|
||||
ArrowRight,
|
||||
HelpCircle,
|
||||
Home,
|
||||
AlertTriangle,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
import { Input, Button, Toast } from '@douyinfe/semi-ui';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import { UserContext } from '../../context/User';
|
||||
import Loading from '../../components/common/ui/Loading';
|
||||
import PageBackground from '../../components/common/PageBackground';
|
||||
|
||||
// 企业创建已收归系统管理员手动创建(/api/admin/organizations/)。
|
||||
// 此页面是「无企业归属」用户的落地引导页,按意图区分三态:
|
||||
// join —— 用户不属于任何企业,展示企业代码加入入口
|
||||
// inactive —— 用户有企业但均非活跃(冻结/欠费/待激活),引导联系管理员,避免误导其"加入"
|
||||
// error —— 企业列表加载失败,提供重试
|
||||
const ORG_STATUS_TEXT = {
|
||||
2: '已被冻结',
|
||||
3: '已欠费',
|
||||
4: '待激活',
|
||||
};
|
||||
|
||||
const OrgCreate = () => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [userState] = useContext(UserContext);
|
||||
const isOrgOnly = userState?.user?.org_only_mode === true;
|
||||
const [joinLoading, setJoinLoading] = useState(false);
|
||||
const [orgCode, setOrgCode] = useState('');
|
||||
// 'checking' | 'join' | 'inactive' | 'error'
|
||||
const [mode, setMode] = useState('checking');
|
||||
const [inactiveOrgs, setInactiveOrgs] = useState([]);
|
||||
|
||||
// 检查用户企业归属并决定落地状态。
|
||||
// 有 active(status=1) 企业 → 写入 current_org_id 并跳转控制台(仅认 active,防冻结企业死循环)。
|
||||
const runCheck = useCallback(async () => {
|
||||
setMode('checking');
|
||||
try {
|
||||
const res = await API.get('/api/org/list');
|
||||
if (res.data.success) {
|
||||
const orgs = res.data.data || [];
|
||||
const activeOrgs = orgs.filter((o) => o.status === 1);
|
||||
if (activeOrgs.length > 0) {
|
||||
const savedOrgId = parseInt(
|
||||
localStorage.getItem('current_org_id') || '0',
|
||||
10,
|
||||
);
|
||||
const savedOrg =
|
||||
savedOrgId > 0 ? activeOrgs.find((o) => o.id === savedOrgId) : null;
|
||||
const targetOrg = savedOrg || activeOrgs[0];
|
||||
localStorage.setItem('current_org_id', String(targetOrg.id));
|
||||
navigate('/org/dashboard', { replace: true });
|
||||
return;
|
||||
}
|
||||
if (orgs.length > 0) {
|
||||
setInactiveOrgs(orgs);
|
||||
setMode('inactive');
|
||||
return;
|
||||
}
|
||||
setMode('join');
|
||||
return;
|
||||
}
|
||||
setMode('error');
|
||||
} catch {
|
||||
setMode('error');
|
||||
}
|
||||
}, [navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
runCheck();
|
||||
}, [runCheck]);
|
||||
|
||||
const handleJoin = useCallback(async () => {
|
||||
if (!orgCode.trim()) {
|
||||
Toast.warning(t('请输入企业代码'));
|
||||
return;
|
||||
}
|
||||
setJoinLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/org/join', { code: orgCode.trim() });
|
||||
if (res.data.success) {
|
||||
Toast.success(t('成功加入企业'));
|
||||
const data = res.data.data;
|
||||
if (data && data.organization && data.organization.id) {
|
||||
localStorage.setItem('current_org_id', String(data.organization.id));
|
||||
}
|
||||
navigate('/org/dashboard');
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setJoinLoading(false);
|
||||
}
|
||||
}, [orgCode, t, navigate]);
|
||||
|
||||
if (mode === 'checking') {
|
||||
return <Loading />;
|
||||
}
|
||||
|
||||
// 非 org_only 用户提供「返回首页」出口,避免被困在本页;org_only 员工受守卫限制在 /org,不提供。
|
||||
const backHome = !isOrgOnly && (
|
||||
<div className='mt-6 text-center'>
|
||||
<button
|
||||
onClick={() => navigate('/')}
|
||||
className='inline-flex items-center gap-1.5 text-sm text-gray-400 dark:text-gray-500 hover:text-brand-deep transition-colors'
|
||||
>
|
||||
<Home size={14} />
|
||||
{t('返回首页')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className='org-center relative min-h-screen flex items-center justify-center bg-[var(--surface-bg-base)] py-16 px-4 transition-colors duration-300'>
|
||||
{/* 统一页面背景层 —— 唯一背景来源,走 bg-glow-* 主题变量 */}
|
||||
<PageBackground />
|
||||
|
||||
<div className='w-full max-w-md relative z-10'>
|
||||
{mode === 'join' && (
|
||||
<>
|
||||
<div className='text-center mb-7'>
|
||||
<div className='inline-flex p-4 rounded-2xl bg-gradient-to-br from-brand-from via-brand-via to-brand-to mb-5 shadow-lg shadow-brand/25 dark:shadow-brand/15'>
|
||||
<Building2 size={34} className='text-white' />
|
||||
</div>
|
||||
<h1 className='text-3xl font-bold text-gray-900 dark:text-white'>
|
||||
{t('加入企业')}
|
||||
</h1>
|
||||
<p className='text-gray-500 dark:text-gray-400 mt-2.5 leading-relaxed'>
|
||||
{t('输入企业管理员提供的企业代码,即可加入你的团队')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className='rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-sm)] p-6 sm:p-7 transition-colors duration-300'>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2'>
|
||||
{t('企业代码')}
|
||||
</label>
|
||||
<Input
|
||||
value={orgCode}
|
||||
onChange={(v) => setOrgCode(v)}
|
||||
placeholder={t('请输入 8 位企业代码')}
|
||||
size='large'
|
||||
prefix={<KeyRound size={18} className='text-gray-400 ml-1' />}
|
||||
onEnterPress={handleJoin}
|
||||
className='tracking-wide'
|
||||
/>
|
||||
<Button
|
||||
type='primary'
|
||||
size='large'
|
||||
block
|
||||
loading={joinLoading}
|
||||
onClick={handleJoin}
|
||||
icon={<ArrowRight size={18} />}
|
||||
iconPosition='right'
|
||||
className='mt-4'
|
||||
>
|
||||
{t('加入企业')}
|
||||
</Button>
|
||||
|
||||
<div className='mt-5 pt-5 border-t border-gray-100 dark:border-neutral-800 flex items-start gap-2.5'>
|
||||
<HelpCircle
|
||||
size={16}
|
||||
className='text-gray-400 dark:text-gray-500 mt-0.5 flex-shrink-0'
|
||||
/>
|
||||
<p className='text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
|
||||
{t(
|
||||
'没有企业代码?请联系你的企业管理员获取,或由管理员直接为你创建企业账号。',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{backHome}
|
||||
</>
|
||||
)}
|
||||
|
||||
{mode === 'inactive' && (
|
||||
<>
|
||||
<div className='text-center mb-7'>
|
||||
<div className='inline-flex p-4 rounded-2xl bg-gradient-to-br from-amber-400 to-amber-500 mb-5 shadow-lg shadow-amber-500/25 dark:shadow-amber-500/15'>
|
||||
<AlertTriangle size={34} className='text-white' />
|
||||
</div>
|
||||
<h1 className='text-3xl font-bold text-gray-900 dark:text-white'>
|
||||
{t('企业暂不可用')}
|
||||
</h1>
|
||||
<p className='text-gray-500 dark:text-gray-400 mt-2.5 leading-relaxed'>
|
||||
{t('你所属的企业当前无法访问,请联系管理员处理')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className='rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-sm)] p-6 sm:p-7 transition-colors duration-300'>
|
||||
<div className='space-y-2.5'>
|
||||
{inactiveOrgs.map((org) => (
|
||||
<div
|
||||
key={org.id}
|
||||
className='flex items-center justify-between gap-3 p-3 rounded-xl bg-gray-50 dark:bg-neutral-800/60 border border-gray-100 dark:border-neutral-800'
|
||||
>
|
||||
<div className='flex items-center gap-2.5 min-w-0'>
|
||||
<Building2
|
||||
size={16}
|
||||
className='text-gray-400 flex-shrink-0'
|
||||
/>
|
||||
<span className='text-sm font-medium text-gray-900 dark:text-white truncate'>
|
||||
{org.name || t('企业') + ' #' + org.id}
|
||||
</span>
|
||||
</div>
|
||||
<span className='text-xs font-medium text-amber-600 dark:text-amber-400 flex-shrink-0'>
|
||||
{t(ORG_STATUS_TEXT[org.status] || '不可用')}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className='mt-5 pt-5 border-t border-gray-100 dark:border-neutral-800 flex items-start gap-2.5'>
|
||||
<HelpCircle
|
||||
size={16}
|
||||
className='text-gray-400 dark:text-gray-500 mt-0.5 flex-shrink-0'
|
||||
/>
|
||||
<p className='text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
|
||||
{t(
|
||||
'企业激活、解冻或续费由平台管理员处理,请联系企业管理员或平台客服。',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size='large'
|
||||
block
|
||||
icon={<RefreshCw size={16} />}
|
||||
onClick={runCheck}
|
||||
className='mt-4'
|
||||
>
|
||||
{t('刷新状态')}
|
||||
</Button>
|
||||
</div>
|
||||
{backHome}
|
||||
</>
|
||||
)}
|
||||
|
||||
{mode === 'error' && (
|
||||
<>
|
||||
<div className='text-center mb-7'>
|
||||
<div className='inline-flex p-4 rounded-2xl bg-gradient-to-br from-red-400 to-red-500 mb-5 shadow-lg shadow-red-500/25 dark:shadow-red-500/15'>
|
||||
<AlertTriangle size={34} className='text-white' />
|
||||
</div>
|
||||
<h1 className='text-3xl font-bold text-gray-900 dark:text-white'>
|
||||
{t('加载失败')}
|
||||
</h1>
|
||||
<p className='text-gray-500 dark:text-gray-400 mt-2.5 leading-relaxed'>
|
||||
{t('无法获取你的企业信息,请检查网络后重试')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className='rounded-xl border border-[var(--border-subtle)] bg-[var(--surface-card)] shadow-[var(--elevation-sm)] p-6 sm:p-7 transition-colors duration-300'>
|
||||
<Button
|
||||
type='primary'
|
||||
size='large'
|
||||
block
|
||||
icon={<RefreshCw size={16} />}
|
||||
onClick={runCheck}
|
||||
>
|
||||
{t('重试')}
|
||||
</Button>
|
||||
</div>
|
||||
{backHome}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgCreate;
|
||||
@@ -0,0 +1,895 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
useCallback,
|
||||
useContext,
|
||||
useRef,
|
||||
} from 'react';
|
||||
import { timestamp2string } from '../../helpers/utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
BarChart2,
|
||||
Users,
|
||||
Key,
|
||||
Wallet,
|
||||
TrendingUp,
|
||||
ArrowRight,
|
||||
ShieldCheck,
|
||||
Crown,
|
||||
Shield,
|
||||
PiggyBank,
|
||||
Flame,
|
||||
Coins,
|
||||
RefreshCw,
|
||||
Search,
|
||||
FileText,
|
||||
CreditCard,
|
||||
Activity,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
Progress,
|
||||
Table,
|
||||
Tag,
|
||||
Button,
|
||||
DatePicker,
|
||||
Input,
|
||||
Spin,
|
||||
Tooltip,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { useOrgDashboard, useOrgQuota } from '../../hooks/org/useOrgData';
|
||||
import { renderQuota } from '../../helpers/render';
|
||||
import { API, showError } from '../../helpers';
|
||||
import Loading from '../../components/common/ui/Loading';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgAnalyticsPanel from './components/OrgAnalyticsPanel';
|
||||
import StatCard from './components/OrgStatCard';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgSideSheet from './components/OrgSideSheet';
|
||||
import OrgStateBlock from './components/OrgStateBlock';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
|
||||
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
// 周期配额:daily/weekly/monthly 才有「周期内已用/重置」概念;none 为终身累计。
|
||||
const isPeriodicQuotaPeriod = (period) =>
|
||||
period === 'daily' || period === 'weekly' || period === 'monthly';
|
||||
|
||||
const safeQuotaNumber = (value) => Math.max(0, Number(value || 0));
|
||||
|
||||
// 用量阈值 → 语义色(Semi token,随明暗主题自适应)。
|
||||
// 页面内所有「使用进度」类指示(统计卡进度条 / 使用率大进度条 / 成员表进度条)
|
||||
// 统一走这一套:>80% 危险、>60% 警告、其余正常。
|
||||
const usageStrokeColor = (percent) =>
|
||||
percent > 80
|
||||
? 'var(--semi-color-danger)'
|
||||
: percent > 60
|
||||
? 'var(--semi-color-warning)'
|
||||
: 'var(--semi-color-success)';
|
||||
|
||||
const quotaPeriodLimitLabel = (t, period) => {
|
||||
switch (period) {
|
||||
case 'daily':
|
||||
return t('每日个人上限');
|
||||
case 'weekly':
|
||||
return t('每周个人上限');
|
||||
case 'monthly':
|
||||
return t('每月个人上限');
|
||||
default:
|
||||
return t('个人终身上限');
|
||||
}
|
||||
};
|
||||
|
||||
const isFeatureEnabled = (flags, key) => {
|
||||
const value = flags?.[key];
|
||||
return value === true || value === 'true' || value === '1' || value === 1;
|
||||
};
|
||||
|
||||
// 状态配置
|
||||
const getStatusConfig = (status, t) => {
|
||||
const map = {
|
||||
1: { label: t('正常'), tagLabel: t('运行正常'), color: 'green' },
|
||||
2: { label: t('冻结'), tagLabel: t('已被冻结'), color: 'red' },
|
||||
3: { label: t('欠费'), tagLabel: t('额度不足'), color: 'orange' },
|
||||
};
|
||||
return map[status] || { label: '-', tagLabel: '-', color: 'grey' };
|
||||
};
|
||||
|
||||
// 成员用量明细抽屉组件
|
||||
const MemberUsageSheet = ({ visible, onClose, member, orgId, t }) => {
|
||||
const [logs, setLogs] = useState([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [dateRange, setDateRange] = useState([]);
|
||||
const [modelName, setModelName] = useState('');
|
||||
const [appliedFilters, setAppliedFilters] = useState({
|
||||
dateRange: [],
|
||||
modelName: '',
|
||||
});
|
||||
const requestSeq = useRef(0);
|
||||
const pageSize = 20;
|
||||
|
||||
const fetchLogs = useCallback(
|
||||
async (p = 1, filters = appliedFilters) => {
|
||||
if (!member || !orgId) return;
|
||||
const seq = ++requestSeq.current;
|
||||
setLoading(true);
|
||||
try {
|
||||
let url = `/api/org/logs?user_id=${member.user_id}&p=${p}&page_size=${pageSize}`;
|
||||
if (filters.dateRange && filters.dateRange.length === 2) {
|
||||
if (filters.dateRange[0])
|
||||
url += `&start_timestamp=${Math.floor(filters.dateRange[0].getTime() / 1000)}`;
|
||||
if (filters.dateRange[1])
|
||||
url += `&end_timestamp=${Math.floor(filters.dateRange[1].getTime() / 1000)}`;
|
||||
}
|
||||
if (filters.modelName)
|
||||
url += `&model_name=${encodeURIComponent(filters.modelName)}`;
|
||||
const res = await API.get(url, { headers: getOrgHeaders(orgId) });
|
||||
if (seq !== requestSeq.current) return;
|
||||
if (res.data.success) {
|
||||
setLogs(res.data.data?.items || []);
|
||||
// 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,保留首页已知总数,
|
||||
// 否则 total 变 -1 会让"total > pageSize"不成立、分页器消失(与 useOrgLogs 同款约定)
|
||||
const nextTotal = res.data.data?.total;
|
||||
if (typeof nextTotal === 'number' && nextTotal >= 0) {
|
||||
setTotal(nextTotal);
|
||||
}
|
||||
setPage(p);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (seq === requestSeq.current) showError(err.message);
|
||||
} finally {
|
||||
if (seq === requestSeq.current) setLoading(false);
|
||||
}
|
||||
},
|
||||
[member, orgId, appliedFilters],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (visible && member && orgId) {
|
||||
// 重置过滤条件和分页状态
|
||||
setDateRange([]);
|
||||
setModelName('');
|
||||
setAppliedFilters({ dateRange: [], modelName: '' });
|
||||
setPage(1);
|
||||
setLogs([]);
|
||||
setTotal(0);
|
||||
// 直接发起无过滤的请求(不依赖 state 更新)
|
||||
const loadInitial = async () => {
|
||||
const seq = ++requestSeq.current;
|
||||
setLoading(true);
|
||||
try {
|
||||
const url = `/api/org/logs?user_id=${member.user_id}&p=1&page_size=${pageSize}`;
|
||||
const res = await API.get(url, { headers: getOrgHeaders(orgId) });
|
||||
if (seq !== requestSeq.current) return;
|
||||
if (res.data.success) {
|
||||
setLogs(res.data.data?.items || []);
|
||||
setTotal(res.data.data?.total || 0);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (seq === requestSeq.current) showError(err.message);
|
||||
} finally {
|
||||
if (seq === requestSeq.current) setLoading(false);
|
||||
}
|
||||
};
|
||||
loadInitial();
|
||||
}
|
||||
}, [visible, member, orgId]);
|
||||
|
||||
const handleSearch = () => {
|
||||
const filters = { dateRange, modelName: modelName.trim() };
|
||||
setAppliedFilters(filters);
|
||||
fetchLogs(1, filters);
|
||||
};
|
||||
|
||||
const logColumns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: t('时间'),
|
||||
dataIndex: 'created_at',
|
||||
width: 160,
|
||||
render: (v) => (v ? timestamp2string(v) : '-'),
|
||||
},
|
||||
{
|
||||
title: t('模型'),
|
||||
dataIndex: 'model_name',
|
||||
width: 180,
|
||||
ellipsis: true,
|
||||
render: (v) => (
|
||||
<code className='text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-neutral-800 rounded'>
|
||||
{v || '-'}
|
||||
</code>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('Token 用量'),
|
||||
width: 120,
|
||||
render: (_, record) => (
|
||||
<div className='text-xs text-gray-600 dark:text-gray-400'>
|
||||
<span title='Prompt'>{record.prompt_tokens || 0}</span>
|
||||
<span className='mx-1 text-gray-300 dark:text-gray-600'>/</span>
|
||||
<span title='Completion'>{record.completion_tokens || 0}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('消耗额度'),
|
||||
dataIndex: 'quota',
|
||||
width: 100,
|
||||
align: 'right',
|
||||
render: (v) => (
|
||||
<span className='text-orange-600 dark:text-orange-400 font-medium text-sm'>
|
||||
{renderQuota(v, 6)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<OrgSideSheet
|
||||
title={
|
||||
<div className='flex items-center gap-2'>
|
||||
<FileText size={18} className='text-brand-deep' />
|
||||
<span>{member?.display_name || member?.username || ''}</span>
|
||||
<span className='text-sm text-gray-400 font-normal'>
|
||||
- {t('用量明细')}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
visible={visible}
|
||||
onCancel={onClose}
|
||||
placement='right'
|
||||
width={640}
|
||||
bodyStyle={{ background: 'var(--semi-color-bg-0)' }}
|
||||
style={{ background: 'var(--semi-color-bg-0)' }}
|
||||
mask={true}
|
||||
maskClosable={true}
|
||||
maskStyle={{
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.45)',
|
||||
backdropFilter: 'blur(4px)',
|
||||
WebkitBackdropFilter: 'blur(4px)',
|
||||
}}
|
||||
>
|
||||
<div className='space-y-4'>
|
||||
{/* 过滤器 */}
|
||||
<div className='flex flex-wrap items-end gap-3 p-3 bg-white dark:bg-neutral-900 rounded-lg border border-gray-200 dark:border-neutral-800'>
|
||||
<div className='flex-1 min-w-[200px]'>
|
||||
<div className='text-xs text-gray-500 dark:text-gray-400 mb-1'>
|
||||
{t('时间范围')}
|
||||
</div>
|
||||
<DatePicker
|
||||
type='dateTimeRange'
|
||||
density='compact'
|
||||
value={dateRange}
|
||||
onChange={setDateRange}
|
||||
placeholder={[t('开始时间'), t('结束时间')]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</div>
|
||||
<div className='min-w-[140px]'>
|
||||
<div className='text-xs text-gray-500 dark:text-gray-400 mb-1'>
|
||||
{t('模型名称')}
|
||||
</div>
|
||||
<Input
|
||||
size='small'
|
||||
placeholder={t('输入模型名称')}
|
||||
value={modelName}
|
||||
onChange={setModelName}
|
||||
onEnterPress={handleSearch}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
size='small'
|
||||
theme='solid'
|
||||
icon={<Search size={14} />}
|
||||
onClick={handleSearch}
|
||||
loading={loading}
|
||||
>
|
||||
{t('查询')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* 统计 */}
|
||||
<div className='text-xs text-gray-400 dark:text-gray-500'>
|
||||
{t('共 {{count}} 条记录', { count: total })}
|
||||
</div>
|
||||
|
||||
{/* 日志表格 */}
|
||||
{loading && logs.length === 0 ? (
|
||||
<div className='flex items-center justify-center py-12'>
|
||||
<Spin />
|
||||
</div>
|
||||
) : (
|
||||
<Table
|
||||
columns={logColumns}
|
||||
dataSource={logs}
|
||||
rowKey='id'
|
||||
size='small'
|
||||
loading={loading}
|
||||
pagination={
|
||||
total > pageSize
|
||||
? {
|
||||
currentPage: page,
|
||||
pageSize,
|
||||
total,
|
||||
onPageChange: (p) => fetchLogs(p),
|
||||
}
|
||||
: false
|
||||
}
|
||||
empty={
|
||||
<div className='py-8 text-center'>
|
||||
<div className='inline-flex p-3 rounded-full bg-gray-100 dark:bg-neutral-800 mb-2'>
|
||||
<FileText
|
||||
size={20}
|
||||
className='text-gray-400 dark:text-gray-500'
|
||||
/>
|
||||
</div>
|
||||
<p className='text-gray-400 dark:text-gray-500 text-sm'>
|
||||
{t('暂无用量记录')}
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</OrgSideSheet>
|
||||
);
|
||||
};
|
||||
|
||||
const OrgDashboard = ({ orgId, orgRole, featureFlags }) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const { data, loading, fetch } = useOrgDashboard(orgId);
|
||||
const {
|
||||
data: quotaData,
|
||||
loading: quotaLoading,
|
||||
fetch: fetchQuota,
|
||||
} = useOrgQuota(orgId);
|
||||
const [usageSheetVisible, setUsageSheetVisible] = useState(false);
|
||||
const [selectedMember, setSelectedMember] = useState(null);
|
||||
|
||||
const isAdmin =
|
||||
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
|
||||
const analyticsEnabled = isFeatureEnabled(featureFlags, 'analytics');
|
||||
const analyticsModuleOn = useMemo(() => {
|
||||
const cfg = normalizeSidebarModulesAdmin(
|
||||
statusState?.status?.SidebarModulesAdmin,
|
||||
).orgCenter;
|
||||
return cfg?.enabled !== false && cfg?.analytics !== false;
|
||||
}, [statusState?.status?.SidebarModulesAdmin]);
|
||||
const showAnalytics = isAdmin && analyticsEnabled && analyticsModuleOn;
|
||||
|
||||
const handleViewMemberUsage = useCallback((member) => {
|
||||
setSelectedMember(member);
|
||||
setUsageSheetVisible(true);
|
||||
}, []);
|
||||
|
||||
// 成员额度表格列(useMemo 必须在所有早返回之前,保证 hooks 调用顺序一致)
|
||||
const memberColumns = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: t('成员'),
|
||||
dataIndex: 'display_name',
|
||||
width: 200,
|
||||
render: (text, record) => (
|
||||
<div className='flex items-center gap-2.5'>
|
||||
<div className='flex-shrink-0 w-8 h-8 rounded-full bg-brand/10 text-brand flex items-center justify-center text-xs font-semibold'>
|
||||
{(text || record.username || '?').charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className='min-w-0'>
|
||||
{isAdmin ? (
|
||||
<div
|
||||
className='font-medium text-brand-deep truncate text-sm cursor-pointer hover:text-brand hover:underline transition-colors'
|
||||
onClick={() => handleViewMemberUsage(record)}
|
||||
>
|
||||
{text || record.username}
|
||||
</div>
|
||||
) : (
|
||||
<div className='font-medium text-gray-900 dark:text-white truncate text-sm'>
|
||||
{text || record.username}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('角色'),
|
||||
dataIndex: 'role',
|
||||
width: 100,
|
||||
align: 'center',
|
||||
render: (role) => {
|
||||
const config = {
|
||||
owner: { label: t('所有者'), color: 'red', icon: Crown },
|
||||
admin: { label: t('管理员'), color: 'blue', icon: ShieldCheck },
|
||||
dept_admin: {
|
||||
label: t('部门管理员'),
|
||||
color: 'cyan',
|
||||
icon: ShieldCheck,
|
||||
},
|
||||
super_admin: {
|
||||
label: t('超级管理员'),
|
||||
color: 'violet',
|
||||
icon: ShieldCheck,
|
||||
},
|
||||
member: { label: t('成员'), color: 'grey', icon: Shield },
|
||||
};
|
||||
const c = config[role] || config.member;
|
||||
return (
|
||||
<div className='flex items-center justify-center gap-1'>
|
||||
<c.icon
|
||||
size={12}
|
||||
className={
|
||||
role === 'owner'
|
||||
? 'text-amber-500'
|
||||
: role === 'admin' ||
|
||||
role === 'dept_admin' ||
|
||||
role === 'super_admin'
|
||||
? 'text-brand-deep'
|
||||
: 'text-gray-400 dark:text-gray-500'
|
||||
}
|
||||
/>
|
||||
<Tag size='small' color={c.color}>
|
||||
{c.label}
|
||||
</Tag>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('周期内已用'),
|
||||
dataIndex: 'quota_used_in_period',
|
||||
width: 120,
|
||||
align: 'right',
|
||||
render: (v, record) =>
|
||||
isPeriodicQuotaPeriod(record.quota_period) ? (
|
||||
<span className='text-gray-700 dark:text-gray-300 font-medium'>
|
||||
{renderQuota(safeQuotaNumber(v), 2)}
|
||||
</span>
|
||||
) : (
|
||||
<span className='text-xs text-gray-400 dark:text-gray-500'>—</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('总已用额度'),
|
||||
dataIndex: 'used_quota',
|
||||
width: 120,
|
||||
align: 'right',
|
||||
render: (v) => (
|
||||
<span className='text-gray-700 dark:text-gray-300 font-medium'>
|
||||
{renderQuota(safeQuotaNumber(v), 2)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('额度上限/周期'),
|
||||
dataIndex: 'quota_limit',
|
||||
width: 150,
|
||||
align: 'right',
|
||||
render: (v, record) => {
|
||||
const quotaLimit = safeQuotaNumber(v);
|
||||
return quotaLimit > 0 ? (
|
||||
<div className='text-right'>
|
||||
<div className='text-gray-700 dark:text-gray-300'>
|
||||
{renderQuota(quotaLimit, 2)}
|
||||
</div>
|
||||
<div
|
||||
className={`text-[11px] ${
|
||||
isPeriodicQuotaPeriod(record.quota_period)
|
||||
? 'text-gray-400 dark:text-gray-500'
|
||||
: 'text-amber-500'
|
||||
}`}
|
||||
>
|
||||
{quotaPeriodLimitLabel(t, record.quota_period)}
|
||||
{!isPeriodicQuotaPeriod(record.quota_period) &&
|
||||
` · ${t('不重置')}`}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<span className='text-gray-400 dark:text-gray-500'>
|
||||
{t('不限')}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('使用进度'),
|
||||
width: 160,
|
||||
render: (_, record) => {
|
||||
const quotaLimit = safeQuotaNumber(record.quota_limit);
|
||||
if (quotaLimit <= 0) {
|
||||
return (
|
||||
<span className='text-xs text-gray-400 dark:text-gray-500'>
|
||||
-
|
||||
</span>
|
||||
);
|
||||
}
|
||||
// 周期模式按「周期内已用 / 上限」;终身模式按「总已用 / 上限」。
|
||||
const usedForProgress = isPeriodicQuotaPeriod(record.quota_period)
|
||||
? safeQuotaNumber(record.quota_used_in_period)
|
||||
: safeQuotaNumber(record.used_quota);
|
||||
const percent = Math.min(
|
||||
100,
|
||||
Math.round((usedForProgress / quotaLimit) * 100),
|
||||
);
|
||||
return (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Progress
|
||||
percent={percent}
|
||||
size='small'
|
||||
style={{ width: 100 }}
|
||||
stroke={usageStrokeColor(percent)}
|
||||
/>
|
||||
<span className='text-xs text-gray-500 dark:text-gray-400 w-8 text-right'>
|
||||
{percent}%
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
[t, isAdmin, handleViewMemberUsage],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetch();
|
||||
fetchQuota();
|
||||
}, [fetch, fetchQuota]);
|
||||
|
||||
if (loading && !data) {
|
||||
return <Loading />;
|
||||
}
|
||||
|
||||
// 额度使用率(防御性处理)
|
||||
const totalQuota = data
|
||||
? Number(data.quota || 0) + Number(data.used_quota || 0)
|
||||
: 0;
|
||||
const usedQuota = Number(data?.used_quota || 0);
|
||||
const usedPercent =
|
||||
totalQuota > 0
|
||||
? Math.min(100, Math.round((usedQuota / totalQuota) * 100))
|
||||
: 0;
|
||||
|
||||
// 成员/令牌容量占用率:与其他使用进度共用同一套阈值语义色
|
||||
const memberPercent =
|
||||
data?.max_members > 0
|
||||
? Math.min(
|
||||
100,
|
||||
Math.round((Number(data.member_count || 0) / data.max_members) * 100),
|
||||
)
|
||||
: 0;
|
||||
const tokenPercent =
|
||||
data?.max_tokens > 0
|
||||
? Math.min(
|
||||
100,
|
||||
Math.round((Number(data.token_count || 0) / data.max_tokens) * 100),
|
||||
)
|
||||
: 0;
|
||||
|
||||
const statusConfig = getStatusConfig(data?.status, t);
|
||||
|
||||
// 成员明细对账:成员合计(终身已用)与企业池已用(org.UsedQuota)通常不相等,
|
||||
// 差额为「未归属」消费(令牌未绑定成员 / 管理员直接使用 / 成员跟踪前的历史),
|
||||
// 显式列出避免用户误以为成员明细加总应等于顶部「已用额度」。
|
||||
const memberQuotaRows = quotaData?.member_quotas || [];
|
||||
const memberQuotaPage = Number(quotaData?.member_page || 1);
|
||||
const memberQuotaPageSize = Number(quotaData?.member_page_size || 10);
|
||||
const memberQuotaTotal = Number(
|
||||
quotaData?.member_total ?? memberQuotaRows.length,
|
||||
);
|
||||
const memberUsedSum = Number(
|
||||
quotaData?.member_used_quota ??
|
||||
memberQuotaRows.reduce(
|
||||
(sum, m) => sum + Math.max(0, Number(m.used_quota || 0)),
|
||||
0,
|
||||
),
|
||||
);
|
||||
const poolUsedQuota = Number(quotaData?.used_quota ?? data?.used_quota ?? 0);
|
||||
const unattributedQuota = Math.max(0, poolUsedQuota - memberUsedSum);
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8 space-y-6'>
|
||||
{/* Header */}
|
||||
<OrgPageHeader
|
||||
icon={BarChart2}
|
||||
title={t('企业概览')}
|
||||
subtitle={t(
|
||||
'聚合企业额度、组织规模与成员消耗,和个人工作台保持职责分离',
|
||||
)}
|
||||
actions={
|
||||
<>
|
||||
{isAdmin && (
|
||||
<Button
|
||||
icon={<CreditCard size={14} />}
|
||||
theme='solid'
|
||||
type='primary'
|
||||
onClick={() => navigate('/org/recharge')}
|
||||
className='!bg-gradient-to-r !from-emerald-500 !to-emerald-600 !border-0 !shadow-md !shadow-emerald-500/30'
|
||||
>
|
||||
{t('立即充值')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={() => {
|
||||
fetch();
|
||||
fetchQuota(memberQuotaPage, memberQuotaPageSize);
|
||||
}}
|
||||
loading={loading || quotaLoading}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 统计卡片 - 三列 */}
|
||||
<div className='grid grid-cols-1 sm:grid-cols-3 gap-4'>
|
||||
<StatCard
|
||||
icon={Users}
|
||||
title={t('企业成员')}
|
||||
value={data?.member_count ?? 0}
|
||||
tone='brand'
|
||||
loading={loading}
|
||||
subtitle={
|
||||
data?.max_members > 0
|
||||
? `${t('上限')}: ${data.max_members}`
|
||||
: t('不限')
|
||||
}
|
||||
extra={
|
||||
data?.max_members > 0 && (
|
||||
<Progress
|
||||
percent={memberPercent}
|
||||
size='small'
|
||||
stroke={usageStrokeColor(memberPercent)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<StatCard
|
||||
icon={Key}
|
||||
title={t('企业令牌')}
|
||||
value={data?.token_count ?? 0}
|
||||
tone='amber'
|
||||
loading={loading}
|
||||
subtitle={
|
||||
data?.max_tokens > 0
|
||||
? `${t('上限')}: ${data.max_tokens}`
|
||||
: t('不限')
|
||||
}
|
||||
extra={
|
||||
data?.max_tokens > 0 && (
|
||||
<Progress
|
||||
percent={tokenPercent}
|
||||
size='small'
|
||||
stroke={usageStrokeColor(tokenPercent)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<StatCard
|
||||
icon={TrendingUp}
|
||||
title={t('企业状态')}
|
||||
value={statusConfig.label}
|
||||
tone='sky'
|
||||
loading={loading}
|
||||
extra={
|
||||
data && (
|
||||
<Tag
|
||||
size='small'
|
||||
color={statusConfig.color}
|
||||
type='light'
|
||||
className='mt-0.5'
|
||||
>
|
||||
{statusConfig.tagLabel}
|
||||
</Tag>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 额度使用详情 - 全宽 */}
|
||||
<OrgPanel icon={Wallet} title={t('额度使用详情')} padding='p-5'>
|
||||
<div className='grid grid-cols-1 sm:grid-cols-3 gap-4'>
|
||||
{/* 总额度 */}
|
||||
<div className='flex items-center gap-3 p-4 rounded-xl bg-gray-50/80 dark:bg-neutral-800/50 border border-gray-100 dark:border-neutral-700/50'>
|
||||
<div className='p-2 rounded-lg bg-brand/10'>
|
||||
<Coins size={16} className='text-brand-deep' />
|
||||
</div>
|
||||
<div>
|
||||
<div className='text-xs font-medium text-gray-400 dark:text-gray-500 mb-0.5'>
|
||||
{t('总额度')}
|
||||
</div>
|
||||
<div className='text-lg font-bold text-gray-900 dark:text-white'>
|
||||
{data ? renderQuota(totalQuota, 2) : '-'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* 已用额度 */}
|
||||
<div className='flex items-center gap-3 p-4 rounded-xl bg-orange-50/80 dark:bg-orange-900/10 border border-orange-100 dark:border-orange-800/30'>
|
||||
<div className='p-2 rounded-lg bg-orange-100 dark:bg-orange-900/30'>
|
||||
<Flame
|
||||
size={16}
|
||||
className='text-orange-600 dark:text-orange-400'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className='text-xs font-medium text-gray-400 dark:text-gray-500 mb-0.5'>
|
||||
{t('已用额度')}
|
||||
</div>
|
||||
<div className='text-lg font-bold text-orange-600 dark:text-orange-400'>
|
||||
{data ? renderQuota(usedQuota, 2) : '-'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/* 剩余额度 */}
|
||||
<div className='flex items-center gap-3 p-4 rounded-xl bg-emerald-50/80 dark:bg-emerald-900/10 border border-emerald-100 dark:border-emerald-800/30'>
|
||||
<div className='p-2 rounded-lg bg-emerald-100 dark:bg-emerald-900/30'>
|
||||
<PiggyBank
|
||||
size={16}
|
||||
className='text-emerald-600 dark:text-emerald-400'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div className='text-xs font-medium text-gray-400 dark:text-gray-500 mb-0.5'>
|
||||
{t('剩余额度')}
|
||||
</div>
|
||||
<div className='text-lg font-bold text-emerald-600 dark:text-emerald-400'>
|
||||
{data ? renderQuota(Number(data.quota || 0), 2) : '-'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 使用率进度条 */}
|
||||
<div className='mt-5 pt-4 border-t border-gray-100 dark:border-neutral-800'>
|
||||
<div className='flex items-center justify-between mb-2'>
|
||||
<span className='text-sm text-gray-500 dark:text-gray-400'>
|
||||
{t('使用率(累计)')}
|
||||
</span>
|
||||
<span
|
||||
className='text-sm font-semibold'
|
||||
style={{ color: usageStrokeColor(usedPercent) }}
|
||||
>
|
||||
{usedPercent}%
|
||||
</span>
|
||||
</div>
|
||||
<div className='w-full h-3 bg-gray-100 dark:bg-neutral-800 rounded-full overflow-hidden'>
|
||||
{/* 渐变由同一语义色的浅调 → 本色构成(单色相),
|
||||
不再引入第二色相(旧 emerald→teal 与用量分析的 teal 系列色撞车) */}
|
||||
<div
|
||||
className='h-full rounded-full transition-all duration-1000 ease-out'
|
||||
style={{
|
||||
width: `${Math.max(usedPercent, 0)}%`,
|
||||
background: `linear-gradient(90deg, color-mix(in srgb, ${usageStrokeColor(usedPercent)} 72%, #fff) 0%, ${usageStrokeColor(usedPercent)} 100%)`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</OrgPanel>
|
||||
|
||||
{/* 成员用量明细 */}
|
||||
<OrgPanel
|
||||
icon={Users}
|
||||
title={t('成员用量明细')}
|
||||
padding='p-5'
|
||||
bodyClassName='overflow-x-auto'
|
||||
actions={
|
||||
<Link
|
||||
to='/org/members'
|
||||
className='flex items-center gap-1 text-xs text-brand-deep hover:text-brand transition-colors'
|
||||
>
|
||||
{t('查看全部')}
|
||||
<ArrowRight size={12} />
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
<Table
|
||||
columns={memberColumns}
|
||||
dataSource={memberQuotaRows}
|
||||
loading={quotaLoading}
|
||||
rowKey='member_id'
|
||||
pagination={
|
||||
memberQuotaTotal > memberQuotaPageSize
|
||||
? {
|
||||
currentPage: memberQuotaPage,
|
||||
pageSize: memberQuotaPageSize,
|
||||
total: memberQuotaTotal,
|
||||
showSizeChanger: false,
|
||||
onPageChange: (page) => fetchQuota(page, memberQuotaPageSize),
|
||||
}
|
||||
: false
|
||||
}
|
||||
size='small'
|
||||
empty={<OrgStateBlock icon={Users} title={t('暂无成员数据')} />}
|
||||
/>
|
||||
{memberQuotaRows.length > 0 && (
|
||||
<div className='mt-3 pt-3 border-t border-gray-100 dark:border-neutral-800 flex flex-wrap items-center gap-x-6 gap-y-1 text-xs'>
|
||||
<span className='text-gray-500 dark:text-gray-400'>
|
||||
{t('成员合计已用')}:
|
||||
<span className='font-medium text-gray-700 dark:text-gray-300'>
|
||||
{renderQuota(memberUsedSum, 2)}
|
||||
</span>
|
||||
</span>
|
||||
<span className='text-gray-500 dark:text-gray-400'>
|
||||
{t('企业池已用')}:
|
||||
<span className='font-medium text-gray-700 dark:text-gray-300'>
|
||||
{renderQuota(poolUsedQuota, 2)}
|
||||
</span>
|
||||
</span>
|
||||
{unattributedQuota > 0 && (
|
||||
<Tooltip
|
||||
content={t(
|
||||
'企业池已用包含未绑定到具体成员的消费(如管理员直接使用、令牌未分配成员、成员跟踪前的历史数据),因此成员合计通常小于企业池已用。',
|
||||
)}
|
||||
>
|
||||
<span className='text-amber-600 dark:text-amber-400 cursor-help'>
|
||||
{t('未归属差额')}:
|
||||
<span className='font-medium'>
|
||||
{renderQuota(unattributedQuota, 2)}
|
||||
</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</OrgPanel>
|
||||
|
||||
{showAnalytics && (
|
||||
<div className='space-y-3'>
|
||||
<div className='flex items-center gap-2 px-1'>
|
||||
<Activity size={16} className='text-brand-deep' />
|
||||
<div>
|
||||
<div className='font-semibold text-gray-950 dark:text-white'>
|
||||
{t('多维用量分析')}
|
||||
</div>
|
||||
<div className='text-xs text-gray-500 dark:text-gray-400'>
|
||||
{t('管理员专属经营数据,避免与个人工作台重复展示')}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<OrgAnalyticsPanel orgId={orgId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 成员用量明细抽屉 */}
|
||||
<MemberUsageSheet
|
||||
visible={usageSheetVisible}
|
||||
onClose={() => setUsageSheetVisible(false)}
|
||||
member={selectedMember}
|
||||
orgId={orgId}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgDashboard;
|
||||
@@ -0,0 +1,65 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Tabs, TabPane } from '@douyinfe/semi-ui';
|
||||
import OrgDsPolicy from './datasecurity/OrgDsPolicy';
|
||||
import OrgDsRules from './datasecurity/OrgDsRules';
|
||||
import OrgDsTest from './datasecurity/OrgDsTest';
|
||||
import OrgDsHitLogs from './datasecurity/OrgDsHitLogs';
|
||||
import OrgDsChanges from './datasecurity/OrgDsChanges';
|
||||
|
||||
// OrgDataSecurity 企业自助数据安全 tab(/org/settings,功能开关 data_security 控制)。
|
||||
// 五个子 tab:策略配置(覆盖平台默认,只能收紧)/ 自定义规则(企业私有,只增加检测项)/
|
||||
// 脱敏测试 / 命中审计(本企业口径统计+明细)/ 变更记录(审批与生效留痕)。
|
||||
// 父组件以 key={orgId} 挂载,切换企业时整棵子树重挂载,各子 tab 无跨企业残留。
|
||||
// lazyRender:只在首次激活时挂载子 tab,避免一进页面并发拉全部数据。
|
||||
// 页签形态:这是「企业设置」一级页签里的下一层,必须与一级的下划线页签区分开,
|
||||
// 所以走 button 型 + .org-nested-tabs(styles/org.css 第 6 节)的分段控件观感;
|
||||
// 两层都用 line 型时上下两条页签条完全同形,用户读不出层级。
|
||||
const OrgDataSecurity = ({ orgId, isSuperAdmin, refreshVersion = 0 }) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className='org-nested-tabs'>
|
||||
<Tabs type='button' lazyRender keepDOM>
|
||||
<TabPane tab={t('策略配置')} itemKey='policy'>
|
||||
<OrgDsPolicy
|
||||
orgId={orgId}
|
||||
isSuperAdmin={isSuperAdmin}
|
||||
refreshVersion={refreshVersion}
|
||||
/>
|
||||
</TabPane>
|
||||
<TabPane tab={t('自定义规则')} itemKey='rules'>
|
||||
<OrgDsRules orgId={orgId} isSuperAdmin={isSuperAdmin} />
|
||||
</TabPane>
|
||||
<TabPane tab={t('脱敏测试')} itemKey='test'>
|
||||
<OrgDsTest orgId={orgId} />
|
||||
</TabPane>
|
||||
<TabPane tab={t('命中审计')} itemKey='hitlogs'>
|
||||
<OrgDsHitLogs orgId={orgId} />
|
||||
</TabPane>
|
||||
<TabPane tab={t('变更记录')} itemKey='changes'>
|
||||
<OrgDsChanges orgId={orgId} />
|
||||
</TabPane>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgDataSecurity;
|
||||
@@ -0,0 +1,366 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Banner, Button, Form, Toast, Empty, Spin } from '@douyinfe/semi-ui';
|
||||
import { RefreshCw, Plus, Network } from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import { useActualTheme } from '../../context/Theme';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgModal from './components/OrgModal';
|
||||
import DeptFlowCanvas from './components/DeptFlowCanvas';
|
||||
import { buildDeptTreeData } from './components/deptTree';
|
||||
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
// 部门管理:组织架构画布(多棵树)+ 节点内操作;移动走后端 MoveDepartmentTx 级联 path
|
||||
const OrgDepartments = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const actualTheme = useActualTheme();
|
||||
const [list, setList] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [editing, setEditing] = useState(null); // null=新建,否则为编辑对象
|
||||
const [createParentId, setCreateParentId] = useState(0); // 新建时预填父部门
|
||||
const [formApi, setFormApi] = useState(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [direction, setDirection] = useState('TB'); // TB 纵向 / LR 横向
|
||||
const [members, setMembers] = useState([]); // 活跃成员(含 department_id),供画布展示成员数/列表
|
||||
const [budgets, setBudgets] = useState([]); // 部门预算行,供画布节点展示预算用量
|
||||
// 预算拦截是否生效:false 时不渲染用量条(used 恒为 0,显示会误导管理员"本月没花钱")
|
||||
const [budgetEnforced, setBudgetEnforced] = useState(null);
|
||||
|
||||
const fetchList = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [res, mres, bres] = await Promise.all([
|
||||
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }),
|
||||
// 成员数据仅是画布辅助信息:网络失败兜底为 null,不连坐部门树
|
||||
API.get('/api/org/members/all', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
}).catch(() => null),
|
||||
// 部门预算仅是画布辅助信息:失败/未开启预算功能时静默降级为不展示。
|
||||
// skipErrorHandler:若后端将来把 feature 未开改成真 4xx,.catch 拦不住
|
||||
// axios 全局拦截器的 toast,必须在请求层显式静默
|
||||
API.get('/api/org/budget?subject_type=department', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
skipErrorHandler: true,
|
||||
}).catch(() => null),
|
||||
]);
|
||||
if (res.data.success) {
|
||||
setList(res.data.data || []);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
// 成员列表仅用于画布展示,拉取失败不阻塞部门树
|
||||
if (mres?.data?.success) setMembers(mres.data.data || []);
|
||||
if (bres?.data?.success) {
|
||||
// 新后端返回 {items, enforcement_enabled};兼容旧后端直接返回数组
|
||||
const payload = bres.data.data;
|
||||
const items = Array.isArray(payload) ? payload : payload?.items || [];
|
||||
setBudgets(items.filter((b) => b.subject_type === 'department'));
|
||||
setBudgetEnforced(
|
||||
Array.isArray(payload)
|
||||
? null
|
||||
: (payload?.enforcement_enabled ?? null),
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setLoaded(true);
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchList();
|
||||
}, [fetchList]);
|
||||
|
||||
// 上级部门树:编辑时排除自身及其整棵子树(path 前缀判断,避免选出环)。
|
||||
// 与成员分配不同,上级可以是任意层级节点(disableNonLeaf=false),停用部门不可作新上级。
|
||||
const parentTreeData = useMemo(
|
||||
() => [
|
||||
{ label: t('顶级部门'), value: 0, key: '0' },
|
||||
...buildDeptTreeData(list, {
|
||||
disableNonLeaf: false,
|
||||
excludeSubtreeOf: editing,
|
||||
disabledLabel: t('已停用'),
|
||||
}),
|
||||
],
|
||||
[list, editing, t],
|
||||
);
|
||||
|
||||
// 弹窗内实时跟踪所选上级(表单值变化同步),用于「上级已有直属成员」提示
|
||||
const [modalParentId, setModalParentId] = useState(0);
|
||||
const memberCountByDept = useMemo(() => {
|
||||
const m = {};
|
||||
members.forEach((mm) => {
|
||||
if (mm.department_id)
|
||||
m[mm.department_id] = (m[mm.department_id] || 0) + 1;
|
||||
});
|
||||
return m;
|
||||
}, [members]);
|
||||
const parentMemberCount =
|
||||
modalParentId > 0 ? memberCountByDept[modalParentId] || 0 : 0;
|
||||
|
||||
const openCreate = useCallback((parentId = 0) => {
|
||||
setEditing(null);
|
||||
setCreateParentId(parentId);
|
||||
setModalParentId(parentId);
|
||||
setModalVisible(true);
|
||||
}, []);
|
||||
|
||||
const openEdit = useCallback((record) => {
|
||||
setEditing(record);
|
||||
setModalParentId(record.parent_id || 0);
|
||||
setModalVisible(true);
|
||||
}, []);
|
||||
|
||||
const handleAddChild = useCallback(
|
||||
(parent) => openCreate(parent.id),
|
||||
[openCreate],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (modalVisible && formApi) {
|
||||
if (editing) {
|
||||
formApi.setValues({
|
||||
name: editing.name,
|
||||
parent_id: editing.parent_id || 0,
|
||||
sort: editing.sort || 0,
|
||||
status: editing.status || 1,
|
||||
});
|
||||
} else {
|
||||
formApi.setValues({
|
||||
name: '',
|
||||
parent_id: createParentId,
|
||||
sort: 0,
|
||||
status: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [modalVisible, editing, createParentId, formApi]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!formApi || saving) return;
|
||||
let values;
|
||||
try {
|
||||
values = await formApi.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
let res;
|
||||
if (editing) {
|
||||
res = await API.put(`/api/org/dept/${editing.id}`, values, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
} else {
|
||||
res = await API.post('/api/org/dept', values, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
}
|
||||
if (res.data.success) {
|
||||
Toast.success(editing ? t('部门已更新') : t('部门已创建'));
|
||||
setModalVisible(false);
|
||||
fetchList();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = useCallback(
|
||||
async (record) => {
|
||||
try {
|
||||
const res = await API.delete(`/api/org/dept/${record.id}`, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
Toast.success(t('部门已删除'));
|
||||
fetchList();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
},
|
||||
[orgId, t, fetchList],
|
||||
);
|
||||
|
||||
// 画布连线触发:把 childId 移到 parentId 之下(后端 MoveDepartmentTx 防环并级联 path)
|
||||
const handleMove = useCallback(
|
||||
async (childId, parentId) => {
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/dept/${childId}`,
|
||||
{ parent_id: parentId },
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('部门层级已调整'));
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
fetchList();
|
||||
}
|
||||
},
|
||||
[orgId, t, fetchList],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
icon={Network}
|
||||
title={t('部门管理')}
|
||||
subtitle={t('组织架构与部门预算')}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<RefreshCw size={14} />}
|
||||
loading={loading}
|
||||
onClick={fetchList}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='solid'
|
||||
icon={<Plus size={14} />}
|
||||
onClick={() => openCreate(0)}
|
||||
>
|
||||
{t('新建顶级部门')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<OrgPanel padding='p-0'>
|
||||
<div className='h-[calc(100vh-270px)] min-h-[480px]'>
|
||||
{!loaded && loading ? (
|
||||
<div className='flex h-full items-center justify-center'>
|
||||
<Spin size='large' />
|
||||
</div>
|
||||
) : list.length === 0 ? (
|
||||
<div className='flex h-full items-center justify-center'>
|
||||
<Empty
|
||||
description={t('暂无部门,创建第一个部门开始搭建组织架构')}
|
||||
>
|
||||
<Button
|
||||
theme='solid'
|
||||
icon={<Plus size={14} />}
|
||||
onClick={() => openCreate(0)}
|
||||
>
|
||||
{t('新建顶级部门')}
|
||||
</Button>
|
||||
</Empty>
|
||||
</div>
|
||||
) : (
|
||||
<DeptFlowCanvas
|
||||
orgId={orgId}
|
||||
depts={list}
|
||||
members={members}
|
||||
budgets={budgetEnforced === false ? [] : budgets}
|
||||
direction={direction}
|
||||
onDirectionChange={setDirection}
|
||||
colorMode={actualTheme === 'dark' ? 'dark' : 'light'}
|
||||
onAddChild={handleAddChild}
|
||||
onEdit={openEdit}
|
||||
onDelete={handleDelete}
|
||||
onMove={handleMove}
|
||||
onSaved={fetchList}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</OrgPanel>
|
||||
|
||||
<OrgModal
|
||||
title={editing ? t('编辑部门') : t('新建部门')}
|
||||
visible={modalVisible}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalVisible(false)}
|
||||
okText={t('保存')}
|
||||
cancelText={t('取消')}
|
||||
confirmLoading={saving}
|
||||
>
|
||||
{parentMemberCount > 0 && (
|
||||
<Banner
|
||||
type='info'
|
||||
closeIcon={null}
|
||||
className='mb-3'
|
||||
description={`${t('所选上级部门已有')} ${parentMemberCount} ${t('名直属成员,新增下级后建议将这些成员迁移到末级部门')}`}
|
||||
/>
|
||||
)}
|
||||
<Form
|
||||
getFormApi={setFormApi}
|
||||
onValueChange={(values) =>
|
||||
setModalParentId((prev) => values.parent_id ?? prev)
|
||||
}
|
||||
>
|
||||
<Form.Input
|
||||
field='name'
|
||||
label={t('部门名称')}
|
||||
rules={[{ required: true, message: t('请输入部门名称') }]}
|
||||
/>
|
||||
<Form.TreeSelect
|
||||
field='parent_id'
|
||||
label={t('上级部门')}
|
||||
treeData={parentTreeData}
|
||||
filterTreeNode
|
||||
showFilteredOnly
|
||||
expandAll
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.InputNumber
|
||||
field='sort'
|
||||
label={t('排序')}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
{editing && (
|
||||
<Form.Select
|
||||
field='status'
|
||||
label={t('状态')}
|
||||
optionList={[
|
||||
{ label: t('启用'), value: 1 },
|
||||
{ label: t('停用'), value: 2 },
|
||||
]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
)}
|
||||
</Form>
|
||||
</OrgModal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgDepartments;
|
||||
@@ -0,0 +1,547 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Select,
|
||||
Tabs,
|
||||
TabPane,
|
||||
Tag,
|
||||
Toast,
|
||||
Empty,
|
||||
Spin,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
RefreshCw,
|
||||
Users,
|
||||
TrendingUp,
|
||||
FileClock,
|
||||
Check,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError, collectPagedItems } from '../../helpers';
|
||||
import { renderQuota } from '../../helpers/render';
|
||||
import QuotaInput from '../../components/common/ui/QuotaInput';
|
||||
import { timestamp2string } from '../../helpers/utils';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgModal from './components/OrgModal';
|
||||
import { orgStatusColor } from './components/orgStatus';
|
||||
|
||||
const { Text } = Typography;
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
const reqStatusTag = (t, status) => {
|
||||
const map = {
|
||||
pending: t('待审批'),
|
||||
approved: t('已通过'),
|
||||
rejected: t('已拒绝'),
|
||||
canceled: t('已取消'),
|
||||
expired: t('已过期'),
|
||||
};
|
||||
return <Tag color={orgStatusColor(status)}>{map[status] || status}</Tag>;
|
||||
};
|
||||
|
||||
const parseDelta = (payload) => {
|
||||
try {
|
||||
return JSON.parse(payload || '{}').cycle_quota_delta || 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
const isFeatureEnabled = (flags, key) => {
|
||||
const v = flags?.[key];
|
||||
return v === true || v === 'true' || v === '1' || v === 1;
|
||||
};
|
||||
|
||||
// 部门管理(阶段一):部门负责人管理本部门子树——成员额度 / 部门用量 / 部门审批。
|
||||
const OrgDeptManage = ({ orgId, featureFlags }) => {
|
||||
const { t } = useTranslation();
|
||||
const approvalEnabled = isFeatureEnabled(featureFlags, 'approval');
|
||||
const [departments, setDepartments] = useState([]);
|
||||
const [deptId, setDeptId] = useState(null);
|
||||
const [myMemberId, setMyMemberId] = useState(0);
|
||||
const [tab, setTab] = useState('members');
|
||||
|
||||
const [members, setMembers] = useState([]);
|
||||
const [membersLoading, setMembersLoading] = useState(false);
|
||||
const [stat, setStat] = useState(null);
|
||||
const [ranking, setRanking] = useState([]);
|
||||
const [usageLoading, setUsageLoading] = useState(false);
|
||||
const [requests, setRequests] = useState([]);
|
||||
const [reqLoading, setReqLoading] = useState(false);
|
||||
|
||||
const [quotaModal, setQuotaModal] = useState(false);
|
||||
const [quotaTarget, setQuotaTarget] = useState(null);
|
||||
const [quotaValue, setQuotaValue] = useState(0);
|
||||
const [quotaPeriod, setQuotaPeriod] = useState('none');
|
||||
const [quotaSaving, setQuotaSaving] = useState(false);
|
||||
|
||||
// 翻页把一次加载从 1 个请求放大到最多 20 个,切部门/切页签的竞态窗口随之
|
||||
// 变大:旧部门的翻页循环若在新请求之后才结束,会用旧部门的数据覆盖列表。
|
||||
const membersSeqRef = useRef(0);
|
||||
const requestsSeqRef = useRef(0);
|
||||
|
||||
const headers = useMemo(() => getOrgHeaders(orgId), [orgId]);
|
||||
|
||||
const fetchScope = useCallback(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/org/me/dept-scope', { headers });
|
||||
if (res.data.success) {
|
||||
const list = res.data.data?.departments || [];
|
||||
setDepartments(list);
|
||||
setMyMemberId(res.data.data?.member_id || 0);
|
||||
setDeptId((prev) => prev || (list[0] ? list[0].id : null));
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
}, [headers]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchScope();
|
||||
}, [fetchScope]);
|
||||
|
||||
const fetchMembers = useCallback(async () => {
|
||||
if (!deptId) return;
|
||||
const seq = ++membersSeqRef.current;
|
||||
setMembersLoading(true);
|
||||
try {
|
||||
// 后端 GetPageQuery 把 page_size 静默钳到 100(见 helpers/paging.js),
|
||||
// 单次请求只拿得到 100 条——部门人数超过 100 时成员列表会静默缺人。
|
||||
const { items, message } = await collectPagedItems(
|
||||
(page, size) =>
|
||||
API.get(
|
||||
`/api/org/dept-managed/members?dept_id=${deptId}&p=${page}&page_size=${size}`,
|
||||
{ headers },
|
||||
),
|
||||
{ shouldAbort: () => seq !== membersSeqRef.current },
|
||||
);
|
||||
if (seq !== membersSeqRef.current) return;
|
||||
setMembers(items);
|
||||
if (message) showError(message);
|
||||
} catch (err) {
|
||||
if (seq === membersSeqRef.current) showError(err.message);
|
||||
} finally {
|
||||
if (seq === membersSeqRef.current) setMembersLoading(false);
|
||||
}
|
||||
}, [deptId, headers]);
|
||||
|
||||
const fetchUsage = useCallback(async () => {
|
||||
if (!deptId) return;
|
||||
setUsageLoading(true);
|
||||
try {
|
||||
const [s, r] = await Promise.all([
|
||||
API.get(`/api/org/dept-managed/stat?dept_id=${deptId}`, { headers }),
|
||||
API.get(`/api/org/dept-managed/ranking?dept_id=${deptId}&limit=20`, {
|
||||
headers,
|
||||
}),
|
||||
]);
|
||||
if (s.data.success) setStat(s.data.data);
|
||||
if (r.data.success) setRanking(r.data.data || []);
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setUsageLoading(false);
|
||||
}
|
||||
}, [deptId, headers]);
|
||||
|
||||
const fetchRequests = useCallback(async () => {
|
||||
const seq = ++requestsSeqRef.current;
|
||||
setReqLoading(true);
|
||||
try {
|
||||
// 逐页取全:后端把 page_size 静默钳到 100(见 helpers/paging.js)。
|
||||
const { items, message } = await collectPagedItems(
|
||||
(page, size) =>
|
||||
API.get(
|
||||
`/api/org/requests?status=pending&p=${page}&page_size=${size}`,
|
||||
{ headers },
|
||||
),
|
||||
{ shouldAbort: () => seq !== requestsSeqRef.current },
|
||||
);
|
||||
if (seq !== requestsSeqRef.current) return;
|
||||
setRequests(items);
|
||||
if (message) showError(message);
|
||||
} catch (err) {
|
||||
if (seq === requestsSeqRef.current) showError(err.message);
|
||||
} finally {
|
||||
if (seq === requestsSeqRef.current) setReqLoading(false);
|
||||
}
|
||||
}, [headers]);
|
||||
|
||||
// 部门变化时始终加载成员(成员额度表 + 审批中申请人名称映射都依赖它)
|
||||
useEffect(() => {
|
||||
if (deptId) fetchMembers();
|
||||
}, [deptId, fetchMembers]);
|
||||
|
||||
useEffect(() => {
|
||||
if (tab === 'usage') fetchUsage();
|
||||
else if (tab === 'approvals' && approvalEnabled) fetchRequests();
|
||||
}, [tab, deptId, approvalEnabled, fetchUsage, fetchRequests]);
|
||||
|
||||
const nameMap = useMemo(() => {
|
||||
const m = {};
|
||||
members.forEach((x) => {
|
||||
m[x.id] = x.remark || x.display_name || x.username || `#${x.id}`;
|
||||
});
|
||||
return m;
|
||||
}, [members]);
|
||||
|
||||
const openQuota = (record) => {
|
||||
setQuotaTarget(record);
|
||||
setQuotaValue(record.quota_limit || 0);
|
||||
setQuotaPeriod(record.quota_period || 'none');
|
||||
setQuotaModal(true);
|
||||
};
|
||||
|
||||
const submitQuota = async () => {
|
||||
if (!quotaTarget) return;
|
||||
setQuotaSaving(true);
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/dept-managed/members/${quotaTarget.id}/quota`,
|
||||
{
|
||||
quota_limit: Math.max(0, Number(quotaValue) || 0),
|
||||
quota_period: quotaPeriod,
|
||||
},
|
||||
{ headers },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('额度已更新'));
|
||||
setQuotaModal(false);
|
||||
fetchMembers();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setQuotaSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const decide = async (id, decision) => {
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/requests/${id}/decision`,
|
||||
{ decision },
|
||||
{ headers },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(decision === 'approved' ? t('已通过') : t('已拒绝'));
|
||||
fetchRequests();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const memberColumns = [
|
||||
{
|
||||
title: t('成员'),
|
||||
dataIndex: 'display_name',
|
||||
render: (v, r) => r.remark || v || r.username || `#${r.id}`,
|
||||
},
|
||||
{
|
||||
title: t('已用额度'),
|
||||
dataIndex: 'used_quota',
|
||||
render: (v) => renderQuota(v || 0, 2),
|
||||
},
|
||||
{
|
||||
title: t('额度上限'),
|
||||
dataIndex: 'quota_limit',
|
||||
render: (v) => (v > 0 ? renderQuota(v, 2) : t('不限')),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
render: (_, r) => (
|
||||
<Button size='small' theme='light' onClick={() => openQuota(r)}>
|
||||
{t('改额度')}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const rankColumns = [
|
||||
{
|
||||
title: t('成员'),
|
||||
dataIndex: 'display_name',
|
||||
render: (v, r) => v || r.username || `#${r.user_id}`,
|
||||
},
|
||||
{
|
||||
title: t('消耗'),
|
||||
dataIndex: 'quota',
|
||||
render: (v) => renderQuota(v || 0, 6),
|
||||
},
|
||||
{ title: t('请求数'), dataIndex: 'requests' },
|
||||
{ title: t('Token'), dataIndex: 'tokens' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
title={t('部门管理')}
|
||||
subtitle={t('管理本部门成员额度、用量与审批')}
|
||||
actions={
|
||||
<>
|
||||
<Select
|
||||
value={deptId}
|
||||
onChange={setDeptId}
|
||||
placeholder={t('选择部门')}
|
||||
style={{ width: 180 }}
|
||||
optionList={departments.map((d) => ({
|
||||
label: `${d.name}(${d.member_count})`,
|
||||
value: d.id,
|
||||
}))}
|
||||
/>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={() => {
|
||||
if (tab === 'members') fetchMembers();
|
||||
else if (tab === 'usage') fetchUsage();
|
||||
else fetchRequests();
|
||||
}}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{departments.length === 0 ? (
|
||||
<Empty
|
||||
description={t('您当前没有管辖的部门')}
|
||||
style={{ padding: 60 }}
|
||||
/>
|
||||
) : (
|
||||
<OrgPanel>
|
||||
<Tabs activeKey={tab} onChange={setTab} type='line'>
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='inline-flex items-center gap-1.5'>
|
||||
<Users size={14} /> {t('成员额度')}
|
||||
</span>
|
||||
}
|
||||
itemKey='members'
|
||||
>
|
||||
<Table
|
||||
columns={memberColumns}
|
||||
dataSource={members}
|
||||
loading={membersLoading}
|
||||
rowKey='id'
|
||||
pagination={false}
|
||||
empty={<Empty description={t('暂无成员')} />}
|
||||
/>
|
||||
</TabPane>
|
||||
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='inline-flex items-center gap-1.5'>
|
||||
<TrendingUp size={14} /> {t('部门用量')}
|
||||
</span>
|
||||
}
|
||||
itemKey='usage'
|
||||
>
|
||||
{usageLoading ? (
|
||||
<div className='flex justify-center py-10'>
|
||||
<Spin />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className='flex gap-4 mb-4'>
|
||||
<div className='px-4 py-3 rounded-lg bg-[var(--semi-color-fill-0)]'>
|
||||
<div className='text-xs text-gray-500'>
|
||||
{t('累计消耗')}
|
||||
</div>
|
||||
<div className='text-lg font-semibold'>
|
||||
{renderQuota(stat?.quota || 0, 2)}
|
||||
</div>
|
||||
</div>
|
||||
<div className='px-4 py-3 rounded-lg bg-[var(--semi-color-fill-0)]'>
|
||||
<div className='text-xs text-gray-500'>{t('请求数')}</div>
|
||||
<div className='text-lg font-semibold'>
|
||||
{stat?.rpm || 0}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
columns={rankColumns}
|
||||
dataSource={ranking}
|
||||
rowKey='user_id'
|
||||
pagination={false}
|
||||
empty={<Empty description={t('暂无用量数据')} />}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</TabPane>
|
||||
|
||||
{approvalEnabled && (
|
||||
<TabPane
|
||||
tab={
|
||||
<span className='inline-flex items-center gap-1.5'>
|
||||
<FileClock size={14} /> {t('部门审批')}
|
||||
</span>
|
||||
}
|
||||
itemKey='approvals'
|
||||
>
|
||||
{reqLoading ? (
|
||||
<div className='flex justify-center py-10'>
|
||||
<Spin />
|
||||
</div>
|
||||
) : requests.length === 0 ? (
|
||||
<Empty
|
||||
description={t('暂无待审批工单')}
|
||||
style={{ padding: 40 }}
|
||||
/>
|
||||
) : (
|
||||
<div className='flex flex-col divide-y divide-[var(--semi-color-border)]'>
|
||||
{requests.map((r) => (
|
||||
<div
|
||||
key={r.id}
|
||||
className='flex items-center justify-between py-3 gap-3 flex-wrap'
|
||||
>
|
||||
<div className='min-w-0'>
|
||||
<Text>
|
||||
{nameMap[r.requester_id] || `#${r.requester_id}`} ·{' '}
|
||||
{t('提额')} {renderQuota(parseDelta(r.payload), 2)}
|
||||
</Text>
|
||||
<div>
|
||||
<Text type='tertiary' size='small'>
|
||||
{r.reason ? r.reason + ' · ' : ''}
|
||||
{r.created_at
|
||||
? timestamp2string(r.created_at)
|
||||
: ''}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
{reqStatusTag(t, r.status)}
|
||||
{r.status === 'pending' &&
|
||||
r.requester_id === myMemberId && (
|
||||
<Tag color='grey'>{t('我的申请')}</Tag>
|
||||
)}
|
||||
{r.status === 'pending' &&
|
||||
r.requester_id !== myMemberId && (
|
||||
<>
|
||||
<Button
|
||||
size='small'
|
||||
theme='solid'
|
||||
icon={<Check size={14} />}
|
||||
onClick={() => decide(r.id, 'approved')}
|
||||
>
|
||||
{t('通过')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
type='danger'
|
||||
theme='light'
|
||||
icon={<X size={14} />}
|
||||
onClick={() => decide(r.id, 'rejected')}
|
||||
>
|
||||
{t('拒绝')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TabPane>
|
||||
)}
|
||||
</Tabs>
|
||||
</OrgPanel>
|
||||
)}
|
||||
|
||||
<OrgModal
|
||||
title={t('修改成员额度上限')}
|
||||
visible={quotaModal}
|
||||
onOk={submitQuota}
|
||||
onCancel={() => setQuotaModal(false)}
|
||||
okText={t('保存')}
|
||||
cancelText={t('取消')}
|
||||
confirmLoading={quotaSaving}
|
||||
>
|
||||
<p className='text-sm text-gray-500 mb-1'>
|
||||
{quotaTarget
|
||||
? quotaTarget.remark ||
|
||||
quotaTarget.display_name ||
|
||||
quotaTarget.username
|
||||
: ''}
|
||||
</p>
|
||||
<p className='text-xs text-gray-400 mb-2'>
|
||||
{t(
|
||||
'设置该成员的个人额度上限(已用额度达到上限即受限),0 表示不限制;与「提额审批」提升的预算 cap 是不同机制。',
|
||||
)}
|
||||
</p>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
|
||||
{t('配额周期')}
|
||||
</label>
|
||||
<Select
|
||||
value={quotaPeriod}
|
||||
onChange={(v) => setQuotaPeriod(v)}
|
||||
style={{ width: '100%' }}
|
||||
optionList={[
|
||||
{ label: t('不限周期(终身累计)'), value: 'none' },
|
||||
{ label: t('每日'), value: 'daily' },
|
||||
{ label: t('每周'), value: 'weekly' },
|
||||
{ label: t('每月'), value: 'monthly' },
|
||||
]}
|
||||
/>
|
||||
<p className='text-xs text-gray-400 dark:text-gray-500 mt-1 mb-2'>
|
||||
{quotaPeriod === 'none'
|
||||
? t('终身累计:成员历史消耗达到上限即受限,不重置。')
|
||||
: quotaPeriod === 'monthly'
|
||||
? t(
|
||||
'自然月重置:每月 1 日 00:00 清零,周期为当月 1 日至下月 1 日前。',
|
||||
)
|
||||
: t(
|
||||
'按周期重置:每个周期开始时已用额度清零,上限为单个周期内的可用额度。',
|
||||
)}
|
||||
</p>
|
||||
<label className='block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1.5'>
|
||||
{t('额度上限')}
|
||||
</label>
|
||||
<QuotaInput
|
||||
value={quotaValue}
|
||||
onChange={setQuotaValue}
|
||||
minQuota={0}
|
||||
style={{ width: '100%' }}
|
||||
placeholder={t('请输入金额,0 表示不限制')}
|
||||
/>
|
||||
</OrgModal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgDeptManage;
|
||||
@@ -0,0 +1,784 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Popconfirm,
|
||||
Select,
|
||||
Table,
|
||||
Tag,
|
||||
TextArea,
|
||||
Toast,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
Activity,
|
||||
FlaskConical,
|
||||
Gauge,
|
||||
RefreshCw,
|
||||
ShieldAlert,
|
||||
} from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers';
|
||||
import { useIsMobile } from '../../hooks/common/useIsMobile';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import './org-effectiveness.css';
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
const dimensions = [
|
||||
{ value: 'organization', label: '企业总览' },
|
||||
{ value: 'department', label: '部门' },
|
||||
{ value: 'project', label: '项目' },
|
||||
{ value: 'expert', label: '专家' },
|
||||
{ value: 'skill', label: 'Skill' },
|
||||
];
|
||||
|
||||
const initialExperiment = {
|
||||
name: '',
|
||||
skill_id: 0,
|
||||
version_a_id: 0,
|
||||
version_b_id: 0,
|
||||
stable_version_id: 0,
|
||||
hypothesis: '',
|
||||
primary_metric: 'quality.adoption_rate',
|
||||
guardrail_metrics: 'efficiency.quota,quality.return_rate',
|
||||
target_sample: 100,
|
||||
allocation_bps: 5000,
|
||||
stop_conditions: '{"max_cost_increase":0.2,"min_quality_score":60}',
|
||||
};
|
||||
|
||||
const OrgEffectiveness = ({ orgId, canManagePolicy, canManageSkills }) => {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
const [dimension, setDimension] = useState('organization');
|
||||
const [dimensionId, setDimensionId] = useState(0);
|
||||
const [data, setData] = useState({ metrics: [], alerts: [], states: [] });
|
||||
const [experiments, setExperiments] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [experimentVisible, setExperimentVisible] = useState(false);
|
||||
const [experiment, setExperiment] = useState(initialExperiment);
|
||||
const [comparisonSkillId, setComparisonSkillId] = useState(0);
|
||||
const [comparison, setComparison] = useState([]);
|
||||
// 直连链路的技能使用统计(方案 §5.3)。云脑面的效能由 agent_effectiveness 覆盖,
|
||||
// 直连面此前完全没有回流口径——同一个技能在网关上被用了多少次是看不到的。
|
||||
const [directUsage, setDirectUsage] = useState([]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params = {};
|
||||
if (dimension !== 'organization') {
|
||||
params.dimension_type = dimension;
|
||||
params.dimension_id = dimensionId;
|
||||
} else {
|
||||
params.dimension_type = 'organization';
|
||||
params.dimension_id = 0;
|
||||
}
|
||||
const [metrics, experimentRows, usageRows] = await Promise.all([
|
||||
API.get('/api/org/effectiveness', { headers, params }),
|
||||
API.get('/api/org/effectiveness/experiments', { headers }),
|
||||
API.get('/api/org/effectiveness/skill-usage', { headers }),
|
||||
]);
|
||||
if (metrics.data?.success) setData(metrics.data.data || {});
|
||||
if (experimentRows.data?.success)
|
||||
setExperiments(experimentRows.data.data || []);
|
||||
// 直连统计失败不阻断整页:它是新增的补充维度,企业若未开 agent_effectiveness
|
||||
// 功能开关、或成员无 agent_effect_view 权限,该接口会拒绝,此时留空即可。
|
||||
setDirectUsage(usageRows.data?.success ? usageRows.data.data || [] : []);
|
||||
} catch (error) {
|
||||
Toast.error(error.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [dimension, dimensionId, headers]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const metric = useMemo(() => {
|
||||
const result = new Map();
|
||||
for (const row of data.metrics || []) {
|
||||
const current = result.get(row.metric_key) || {
|
||||
value: 0,
|
||||
numerator: 0,
|
||||
denominator: 0,
|
||||
};
|
||||
current.value += Number(row.value || 0);
|
||||
current.numerator += Number(row.numerator || 0);
|
||||
current.denominator += Number(row.denominator || 0);
|
||||
current.latest = row;
|
||||
result.set(row.metric_key, current);
|
||||
}
|
||||
return result;
|
||||
}, [data.metrics]);
|
||||
|
||||
const value = (key, rate = false) => {
|
||||
const row = metric.get(key);
|
||||
if (!row) return 0;
|
||||
return rate && row.denominator
|
||||
? row.numerator / row.denominator
|
||||
: row.value;
|
||||
};
|
||||
|
||||
const aggregateToday = async () => {
|
||||
const metricDate = new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).format(new Date());
|
||||
const response = await API.post(
|
||||
'/api/org/effectiveness/aggregate',
|
||||
{ metric_date: metricDate },
|
||||
{ headers },
|
||||
);
|
||||
if (response.data?.success) {
|
||||
Toast.success(t('聚合已完成'));
|
||||
await load();
|
||||
}
|
||||
};
|
||||
|
||||
const createExperiment = async () => {
|
||||
let stopConditions;
|
||||
try {
|
||||
stopConditions = JSON.parse(experiment.stop_conditions);
|
||||
} catch {
|
||||
Toast.error(t('停止条件必须是合法 JSON'));
|
||||
return;
|
||||
}
|
||||
const response = await API.post(
|
||||
'/api/org/effectiveness/experiments',
|
||||
{
|
||||
...experiment,
|
||||
guardrail_metrics: experiment.guardrail_metrics
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean),
|
||||
stop_conditions: stopConditions,
|
||||
},
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('创建失败'));
|
||||
return;
|
||||
}
|
||||
setExperimentVisible(false);
|
||||
setExperiment(initialExperiment);
|
||||
await load();
|
||||
};
|
||||
|
||||
const experimentAction = async (row, action) => {
|
||||
const endpoint = `/api/org/effectiveness/experiments/${row.id}/${action}`;
|
||||
const payload =
|
||||
action === 'start'
|
||||
? {}
|
||||
: {
|
||||
rollback: true,
|
||||
winner_version_id: row.stable_version_id,
|
||||
reason: '管理员立即停止并回退到稳定版本',
|
||||
};
|
||||
const response = await API.post(endpoint, payload, { headers });
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return;
|
||||
}
|
||||
await load();
|
||||
};
|
||||
|
||||
// 实验此前只能建、只能起停:建错的草稿和终态实验会永久堆在列表里。
|
||||
// 运行中的实验后端会拒绝删除(须先停止或回退),这里按状态禁用按钮先行拦一层。
|
||||
const deleteExperiment = async (row) => {
|
||||
const response = await API.delete(
|
||||
`/api/org/effectiveness/experiments/${row.id}`,
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return;
|
||||
}
|
||||
Toast.success(t('实验已删除'));
|
||||
await load();
|
||||
};
|
||||
|
||||
const loadComparison = async () => {
|
||||
if (!comparisonSkillId) return;
|
||||
const response = await API.get(
|
||||
`/api/org/effectiveness/quality/skills/${comparisonSkillId}/versions`,
|
||||
{ headers },
|
||||
);
|
||||
if (response.data?.success) setComparison(response.data.data || []);
|
||||
};
|
||||
|
||||
const showAlertSamples = (row) => {
|
||||
let ids = [];
|
||||
try {
|
||||
ids = JSON.parse(row.sample_run_ids || '[]');
|
||||
} catch {
|
||||
ids = [];
|
||||
}
|
||||
Modal.info({
|
||||
title: t('告警任务样本'),
|
||||
content: (
|
||||
<div className='org-effect-samples'>
|
||||
{ids.map((id) => (
|
||||
<code key={id}>{id}</code>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const cards = [
|
||||
{
|
||||
label: t('覆盖任务'),
|
||||
value: Math.round(value('coverage.task_count')).toLocaleString(),
|
||||
detail: `${Math.round(value('coverage.active_member_count'))} ${t('活跃员工')}`,
|
||||
icon: Activity,
|
||||
},
|
||||
{
|
||||
label: t('节省时间'),
|
||||
value: `${Math.round(value('efficiency.saved_minutes'))} min`,
|
||||
detail: `${Math.round(value('efficiency.manual_minutes'))} min ${t('人工基线')}`,
|
||||
icon: Gauge,
|
||||
},
|
||||
{
|
||||
label: t('质量评分'),
|
||||
value: metric.has('quality.score')
|
||||
? value('quality.score', true).toFixed(1)
|
||||
: t('数据不足'),
|
||||
detail: `${Math.round(value('quality.feedback_count'))} ${t('反馈样本')}`,
|
||||
icon: FlaskConical,
|
||||
},
|
||||
{
|
||||
label: t('治理风险'),
|
||||
value: Math.round(value('governance.failed_tool_call_count')),
|
||||
detail: `${Math.round(value('governance.write_call_count'))} ${t('写操作')}`,
|
||||
icon: ShieldAlert,
|
||||
},
|
||||
];
|
||||
|
||||
// 使用指引:看板阅读指南(无上手流程,不出进度胶囊)——重点解释
|
||||
// 每个指标的口径和数据来源,避免管理员把抽样数据当精确账。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-effectiveness',
|
||||
title: t('效能分析 · 使用指引'),
|
||||
intro: t('回答四个问题:谁在用、省了多少时间、成本对不对账、质量是否改善'),
|
||||
steps: [
|
||||
{
|
||||
title: t('选维度查看'),
|
||||
detail: t('从企业总览切到部门 / 项目 / 专家 / Skill 维度'),
|
||||
points: [
|
||||
t('非总览维度需在旁边输入框填对应 ID(部门 ID、项目 ID 等)'),
|
||||
t('切换后数据自动刷新;「刷新」按钮可随时重拉'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('读懂四张指标卡'),
|
||||
detail: t('覆盖、节省、质量、风险各一张'),
|
||||
points: [
|
||||
t('「节省时间」的基线来自成员完成任务后的「确认节省时间」抽样'),
|
||||
t('「质量评分」样本不足时显示「数据不足」,不是故障'),
|
||||
t('「治理风险」统计失败的工具调用与写操作次数'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('下钻分析'),
|
||||
detail: t('从汇总数字追到具体任务与版本'),
|
||||
points: [
|
||||
t('「成本对账」三栏:运行结算、消费明细、差额;差额红色需关注'),
|
||||
t('「质量告警」每行可「下钻」查看样本任务 ID'),
|
||||
t('「灰度版本质量对比」输入 Skill ID 可对比各版本首交付通过率'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('让数据更准'),
|
||||
detail: t('看板质量取决于回流数据的完整度'),
|
||||
points: [
|
||||
t('鼓励成员在任务完成后点 👍/👎 并填写「确认节省时间」'),
|
||||
t('「网关直连技能使用」需密钥开启「技能注入」后才有数据'),
|
||||
t('注意:直连面板的 token 与额度是整请求口径,不能跨技能相加'),
|
||||
],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('指标全是 0 或「数据不足」?'),
|
||||
a: t('刚启用时样本少属正常,随任务量与成员反馈积累会逐步补全'),
|
||||
},
|
||||
{
|
||||
q: t('「重算今日」是干什么的?'),
|
||||
a: t(
|
||||
'管理员手动触发当日指标聚合(按 Asia/Shanghai 日期),通常无需使用',
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
return (
|
||||
<div className='org-effect-page'>
|
||||
<header className='org-effect-hero'>
|
||||
<div>
|
||||
<Title heading={2}>{t('效能分析')}</Title>
|
||||
<Text type='tertiary'>
|
||||
{t('回答谁在用、节省多少时间、成本是否对账、质量与安全是否改善。')}
|
||||
</Text>
|
||||
</div>
|
||||
<div className='org-effect-toolbar'>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
<Select
|
||||
value={dimension}
|
||||
optionList={dimensions}
|
||||
onChange={setDimension}
|
||||
/>
|
||||
{dimension !== 'organization' && (
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={dimensionId}
|
||||
onChange={setDimensionId}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
icon={<RefreshCw size={15} />}
|
||||
loading={loading}
|
||||
onClick={load}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
{canManagePolicy && (
|
||||
<Button onClick={aggregateToday}>{t('重算今日')}</Button>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
<PageGuideDrawer guide={guide} />
|
||||
|
||||
<section className='org-effect-grid'>
|
||||
{cards.map(({ label, value: cardValue, detail, icon: Icon }) => (
|
||||
<article className='org-effect-card' key={label}>
|
||||
<Icon size={20} />
|
||||
<Text>{label}</Text>
|
||||
<strong>{cardValue}</strong>
|
||||
<small>{detail}</small>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<OrgPanel title={t('网关直连技能使用(近 30 天)')}>
|
||||
{directUsage.length === 0 ? (
|
||||
<Text type='tertiary'>
|
||||
{t(
|
||||
'暂无数据。开启密钥的「技能注入」后,用该密钥直连调用的技能使用情况会回流到这里。',
|
||||
)}
|
||||
</Text>
|
||||
) : (
|
||||
<>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t(
|
||||
'统计口径:token 与额度是整条请求的量级,多技能同时命中时全额计入每个技能,不是按技能分摊的成本,勿相加。',
|
||||
)}
|
||||
</Text>
|
||||
<Table
|
||||
size='small'
|
||||
pagination={false}
|
||||
dataSource={directUsage}
|
||||
rowKey='skill_id'
|
||||
columns={[
|
||||
{
|
||||
title: t('技能'),
|
||||
dataIndex: 'name',
|
||||
render: (name, record) =>
|
||||
name || record.canonical_id || `#${record.skill_id}`,
|
||||
},
|
||||
{ title: t('调用次数'), dataIndex: 'request_count' },
|
||||
{
|
||||
title: t('占比'),
|
||||
dataIndex: 'share_percent',
|
||||
render: (share) => `${(share || 0).toFixed(1)}%`,
|
||||
},
|
||||
{
|
||||
title: t('提示词 token'),
|
||||
dataIndex: 'prompt_tokens',
|
||||
render: (tokens) => (tokens || 0).toLocaleString(),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</OrgPanel>
|
||||
|
||||
<div className='org-effect-columns'>
|
||||
<OrgPanel title={t('成本对账')}>
|
||||
<div className='org-effect-reconcile'>
|
||||
<span>{t('运行结算')}</span>
|
||||
<b>{Math.round(value('efficiency.quota')).toLocaleString()}</b>
|
||||
<span>{t('消费明细')}</span>
|
||||
<b>
|
||||
{Math.round(
|
||||
value('efficiency.settlement_quota') +
|
||||
value('efficiency.adjustment_quota'),
|
||||
).toLocaleString()}
|
||||
</b>
|
||||
<span>{t('差额')}</span>
|
||||
<b
|
||||
className={
|
||||
value('efficiency.reconciliation_gap') ? 'is-risk' : 'is-ok'
|
||||
}
|
||||
>
|
||||
{Math.round(
|
||||
value('efficiency.reconciliation_gap'),
|
||||
).toLocaleString()}
|
||||
</b>
|
||||
</div>
|
||||
</OrgPanel>
|
||||
<OrgPanel title={t('质量告警')}>
|
||||
{isMobile ? (
|
||||
<div className='org-effect-mobile-list'>
|
||||
{(data.alerts || []).map((row) => (
|
||||
<article key={row.id}>
|
||||
<div>
|
||||
<strong>Skill #{row.dimension_id}</strong>
|
||||
<Tag color={row.status === 'open' ? 'red' : 'green'}>
|
||||
{row.status}
|
||||
</Tag>
|
||||
</div>
|
||||
<span>
|
||||
{t('评分')}: {Number(row.score).toFixed(1)}
|
||||
</span>
|
||||
<span>
|
||||
{t('样本')}: {row.sample_count}
|
||||
</span>
|
||||
<Button size='small' onClick={() => showAlertSamples(row)}>
|
||||
{t('下钻')}
|
||||
</Button>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Table
|
||||
size='small'
|
||||
pagination={false}
|
||||
dataSource={data.alerts || []}
|
||||
columns={[
|
||||
{ title: t('Skill'), dataIndex: 'dimension_id' },
|
||||
{
|
||||
title: t('评分'),
|
||||
dataIndex: 'score',
|
||||
render: (score) => Number(score).toFixed(1),
|
||||
},
|
||||
{ title: t('样本'), dataIndex: 'sample_count' },
|
||||
{
|
||||
title: t('样本任务'),
|
||||
render: (_, row) => (
|
||||
<Button size='small' onClick={() => showAlertSamples(row)}>
|
||||
{t('下钻')}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
render: (status) => (
|
||||
<Tag color={status === 'open' ? 'red' : 'green'}>
|
||||
{status}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</OrgPanel>
|
||||
</div>
|
||||
|
||||
<OrgPanel
|
||||
title={t('灰度版本质量对比')}
|
||||
actions={
|
||||
<div className='flex gap-2'>
|
||||
<InputNumber
|
||||
min={1}
|
||||
placeholder='Skill ID'
|
||||
value={comparisonSkillId}
|
||||
onChange={setComparisonSkillId}
|
||||
/>
|
||||
<Button onClick={loadComparison}>{t('下钻版本')}</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{isMobile ? (
|
||||
<div className='org-effect-mobile-list'>
|
||||
{comparison.map((row) => (
|
||||
<article key={row.version_id}>
|
||||
<strong>
|
||||
{t('版本')} #{row.version_id}
|
||||
</strong>
|
||||
<span>
|
||||
{t('首次交付样本')}: {row.first_delivery_count}
|
||||
</span>
|
||||
<span>
|
||||
{t('首次交付通过率')}:{' '}
|
||||
{row.data_sufficient
|
||||
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
|
||||
: t('数据不足')}
|
||||
</span>
|
||||
<span>
|
||||
{t('退回率')}:{' '}
|
||||
{row.data_sufficient
|
||||
? `${(row.return_rate * 100).toFixed(1)}%`
|
||||
: t('数据不足')}
|
||||
</span>
|
||||
<span>
|
||||
{t('平均成本')}:{' '}
|
||||
{row.data_sufficient
|
||||
? Number(row.average_quota).toFixed(1)
|
||||
: t('数据不足')}
|
||||
</span>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Table
|
||||
pagination={false}
|
||||
dataSource={comparison}
|
||||
columns={[
|
||||
{ title: t('版本'), dataIndex: 'version_id' },
|
||||
{ title: t('首次交付样本'), dataIndex: 'first_delivery_count' },
|
||||
{
|
||||
title: t('首次交付通过率'),
|
||||
render: (_, row) =>
|
||||
row.data_sufficient
|
||||
? `${(row.first_delivery_pass_rate * 100).toFixed(1)}%`
|
||||
: t('数据不足'),
|
||||
},
|
||||
{
|
||||
title: t('退回率'),
|
||||
render: (_, row) =>
|
||||
row.data_sufficient
|
||||
? `${(row.return_rate * 100).toFixed(1)}%`
|
||||
: t('数据不足'),
|
||||
},
|
||||
{
|
||||
title: t('平均成本'),
|
||||
render: (_, row) =>
|
||||
row.data_sufficient
|
||||
? Number(row.average_quota).toFixed(1)
|
||||
: t('数据不足'),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</OrgPanel>
|
||||
|
||||
<OrgPanel
|
||||
title={t('Skill A/B 实验')}
|
||||
actions={
|
||||
canManageSkills ? (
|
||||
<Button onClick={() => setExperimentVisible(true)}>
|
||||
{t('新建实验')}
|
||||
</Button>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{isMobile ? (
|
||||
<div className='org-effect-mobile-list'>
|
||||
{experiments.map((row) => (
|
||||
<article key={row.id}>
|
||||
<div>
|
||||
<strong>{row.name}</strong>
|
||||
<Tag>{row.status}</Tag>
|
||||
</div>
|
||||
<span>Skill #{row.skill_id}</span>
|
||||
<span>
|
||||
A / B: {row.version_a_id} / {row.version_b_id}
|
||||
</span>
|
||||
<span>
|
||||
{t('目标样本')}: {row.target_sample}
|
||||
</span>
|
||||
{canManageSkills && (
|
||||
<div className='flex gap-1'>
|
||||
<Button
|
||||
size='small'
|
||||
type={row.status === 'running' ? 'danger' : 'primary'}
|
||||
disabled={!['draft', 'running'].includes(row.status)}
|
||||
onClick={() =>
|
||||
experimentAction(
|
||||
row,
|
||||
row.status === 'draft' ? 'start' : 'stop',
|
||||
)
|
||||
}
|
||||
>
|
||||
{row.status === 'draft' ? t('开始') : t('停止并回退')}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={t('确认删除该实验?')}
|
||||
content={t(
|
||||
'删除后实验配置与分桶结果一并清除,起停记录已在审计中留痕。',
|
||||
)}
|
||||
onConfirm={() => deleteExperiment(row)}
|
||||
>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
type='danger'
|
||||
disabled={row.status === 'running'}
|
||||
>
|
||||
{t('删除')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Table
|
||||
pagination={false}
|
||||
dataSource={experiments}
|
||||
columns={[
|
||||
{ title: t('实验'), dataIndex: 'name' },
|
||||
{ title: 'Skill', dataIndex: 'skill_id' },
|
||||
{
|
||||
title: 'A / B',
|
||||
render: (_, row) => `${row.version_a_id} / ${row.version_b_id}`,
|
||||
},
|
||||
{ title: t('目标样本'), dataIndex: 'target_sample' },
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
render: (status) => <Tag>{status}</Tag>,
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
render: (_, row) =>
|
||||
canManageSkills && (
|
||||
<div className='flex gap-1'>
|
||||
<Button
|
||||
size='small'
|
||||
type={row.status === 'running' ? 'danger' : 'primary'}
|
||||
disabled={!['draft', 'running'].includes(row.status)}
|
||||
onClick={() =>
|
||||
experimentAction(
|
||||
row,
|
||||
row.status === 'draft' ? 'start' : 'stop',
|
||||
)
|
||||
}
|
||||
>
|
||||
{row.status === 'draft' ? t('开始') : t('停止并回退')}
|
||||
</Button>
|
||||
<Popconfirm
|
||||
title={t('确认删除该实验?')}
|
||||
content={t(
|
||||
'删除后实验配置与分桶结果一并清除,起停记录已在审计中留痕。',
|
||||
)}
|
||||
onConfirm={() => deleteExperiment(row)}
|
||||
>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
type='danger'
|
||||
disabled={row.status === 'running'}
|
||||
>
|
||||
{t('删除')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</OrgPanel>
|
||||
|
||||
<Modal
|
||||
title={t('新建 Skill A/B 实验')}
|
||||
visible={experimentVisible}
|
||||
onCancel={() => setExperimentVisible(false)}
|
||||
onOk={createExperiment}
|
||||
width={680}
|
||||
>
|
||||
<div className='org-effect-form'>
|
||||
<Input
|
||||
placeholder={t('实验名称')}
|
||||
value={experiment.name}
|
||||
onChange={(name) => setExperiment({ ...experiment, name })}
|
||||
/>
|
||||
{[
|
||||
'skill_id',
|
||||
'version_a_id',
|
||||
'version_b_id',
|
||||
'stable_version_id',
|
||||
].map((key) => (
|
||||
<InputNumber
|
||||
key={key}
|
||||
min={1}
|
||||
placeholder={key}
|
||||
value={experiment[key]}
|
||||
onChange={(next) => setExperiment({ ...experiment, [key]: next })}
|
||||
/>
|
||||
))}
|
||||
<TextArea
|
||||
placeholder={t('实验假设')}
|
||||
value={experiment.hypothesis}
|
||||
onChange={(hypothesis) =>
|
||||
setExperiment({ ...experiment, hypothesis })
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
placeholder={t('主指标')}
|
||||
value={experiment.primary_metric}
|
||||
onChange={(primary_metric) =>
|
||||
setExperiment({ ...experiment, primary_metric })
|
||||
}
|
||||
/>
|
||||
<Input
|
||||
placeholder={t('护栏指标,逗号分隔')}
|
||||
value={experiment.guardrail_metrics}
|
||||
onChange={(guardrail_metrics) =>
|
||||
setExperiment({ ...experiment, guardrail_metrics })
|
||||
}
|
||||
/>
|
||||
<InputNumber
|
||||
min={10}
|
||||
placeholder={t('目标样本')}
|
||||
value={experiment.target_sample}
|
||||
onChange={(target_sample) =>
|
||||
setExperiment({ ...experiment, target_sample })
|
||||
}
|
||||
/>
|
||||
<TextArea
|
||||
placeholder={t('停止条件 JSON')}
|
||||
value={experiment.stop_conditions}
|
||||
onChange={(stop_conditions) =>
|
||||
setExperiment({ ...experiment, stop_conditions })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgEffectiveness;
|
||||
@@ -0,0 +1,646 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
TabPane,
|
||||
Tabs,
|
||||
Tag,
|
||||
TextArea,
|
||||
Toast,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuidePill,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import './org-experts.css';
|
||||
|
||||
const { Title, Paragraph, Text } = Typography;
|
||||
|
||||
const emptyForm = {
|
||||
definition_id: 0,
|
||||
expert_key: '',
|
||||
source_expert_id: 0,
|
||||
name_zh: '',
|
||||
name_en: '',
|
||||
description_zh: '',
|
||||
description_en: '',
|
||||
scenario_zh: '',
|
||||
scenario_en: '',
|
||||
system_prompt_zh: '',
|
||||
system_prompt_en: '',
|
||||
default_model: '',
|
||||
fallback_models: '',
|
||||
input_schema:
|
||||
'{\n "type": "object",\n "properties": {\n "task": { "type": "string" }\n },\n "required": ["task"]\n}',
|
||||
required_sections_zh: '',
|
||||
required_sections_en: '',
|
||||
forbidden_placeholders: '',
|
||||
contract_type: 'markdown',
|
||||
artifact_mode: 'inline',
|
||||
artifact_file_name: '',
|
||||
artifact_content_type: '',
|
||||
max_output_tokens: 2048,
|
||||
max_total_output_tokens: 4096,
|
||||
max_step_quota: 100000,
|
||||
max_task_quota: 200000,
|
||||
default_language: 'zh',
|
||||
safety_policy_ref: 'org-default',
|
||||
step_plan:
|
||||
'[\n {\n "key": "primary",\n "name_zh": "生成交付物",\n "name_en": "Generate deliverable",\n "instruction_zh": "根据任务生成最终交付物。",\n "instruction_en": "Generate the final deliverable for the task.",\n "max_output_tokens": 2048\n }\n]',
|
||||
};
|
||||
|
||||
const csv = (value) =>
|
||||
String(value || '')
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const OrgExperts = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
const [definitions, setDefinitions] = useState([]);
|
||||
const [sources, setSources] = useState([]);
|
||||
// 首次加载完成前进度胶囊不渲染,避免对老用户闪现「0/4」。
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [form, setForm] = useState(emptyForm);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
// allSettled: a transient catalog failure must not discard the managed
|
||||
// expert list and render a misleading "no experts yet" empty state.
|
||||
const [managed, catalog] = await Promise.allSettled([
|
||||
API.get('/api/org/experts', { headers, skipErrorHandler: true }),
|
||||
// Mirrored under the experts router so an admin holding only
|
||||
// expert_manage (without the cloud_brain admin permission) can still
|
||||
// load the platform source catalog.
|
||||
API.get('/api/org/experts/catalog?locale=zh', {
|
||||
headers,
|
||||
skipErrorHandler: true,
|
||||
}),
|
||||
]);
|
||||
if (managed.status === 'fulfilled' && managed.value.data?.success) {
|
||||
setDefinitions(managed.value.data.data || []);
|
||||
} else {
|
||||
const message =
|
||||
managed.status === 'fulfilled'
|
||||
? managed.value.data?.message
|
||||
: managed.reason?.response?.data?.message;
|
||||
Toast.error(message || t('企业专家列表加载失败'));
|
||||
}
|
||||
if (catalog.status === 'fulfilled' && catalog.value.data?.success) {
|
||||
setSources(
|
||||
(catalog.value.data.data || []).filter((item) => !item.organization_id),
|
||||
);
|
||||
} else {
|
||||
const message =
|
||||
catalog.status === 'fulfilled'
|
||||
? catalog.value.data?.message
|
||||
: catalog.reason?.response?.data?.message;
|
||||
Toast.error(message || t('平台专家目录不可用,请检查管理权限'));
|
||||
}
|
||||
setLoaded(true);
|
||||
}, [headers, t]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
|
||||
const update = (key, value) =>
|
||||
setForm((current) => ({ ...current, [key]: value }));
|
||||
const beginVersion = (view) => {
|
||||
const current = view?.current;
|
||||
if (!current) {
|
||||
// A definition whose first version is still draft/pending_review has no
|
||||
// `current`; keep its identity so the new version attaches to it
|
||||
// instead of colliding with the (organization_id, expert_key) unique
|
||||
// index as a brand-new definition.
|
||||
setForm({
|
||||
...emptyForm,
|
||||
definition_id: view?.definition?.id || 0,
|
||||
expert_key: view?.definition?.expert_key || '',
|
||||
});
|
||||
} else {
|
||||
let contract = {};
|
||||
try {
|
||||
contract = JSON.parse(current.output_contract || '{}');
|
||||
} catch {
|
||||
contract = {};
|
||||
}
|
||||
setForm({
|
||||
...emptyForm,
|
||||
definition_id: view.definition.id,
|
||||
expert_key: current.expert_key,
|
||||
source_expert_id: current.source_expert_id,
|
||||
name_zh: current.name_zh,
|
||||
name_en: current.name_en,
|
||||
description_zh: current.description_zh,
|
||||
description_en: current.description_en,
|
||||
scenario_zh: current.scenario_zh,
|
||||
scenario_en: current.scenario_en,
|
||||
system_prompt_zh: '',
|
||||
system_prompt_en: '',
|
||||
default_model: current.default_model,
|
||||
fallback_models: (() => {
|
||||
try {
|
||||
return JSON.parse(current.fallback_models || '[]').join(', ');
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
})(),
|
||||
input_schema: current.input_schema || emptyForm.input_schema,
|
||||
required_sections_zh: (contract.required_sections_zh || []).join(', '),
|
||||
required_sections_en: (contract.required_sections_en || []).join(', '),
|
||||
forbidden_placeholders: (contract.forbidden_placeholders || []).join(
|
||||
', ',
|
||||
),
|
||||
contract_type: contract.type || 'markdown',
|
||||
artifact_mode: contract.artifact_mode || 'inline',
|
||||
artifact_file_name: contract.file_name || '',
|
||||
artifact_content_type: contract.content_type || '',
|
||||
max_output_tokens: current.max_output_tokens,
|
||||
max_total_output_tokens: current.max_total_output_tokens,
|
||||
max_step_quota: current.max_step_quota,
|
||||
max_task_quota: current.max_task_quota,
|
||||
default_language: current.default_language,
|
||||
safety_policy_ref: current.safety_policy_ref,
|
||||
step_plan: current.step_plan || emptyForm.step_plan,
|
||||
});
|
||||
}
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
let inputSchema;
|
||||
let stepPlan;
|
||||
try {
|
||||
inputSchema = JSON.parse(form.input_schema);
|
||||
stepPlan = JSON.parse(form.step_plan);
|
||||
} catch {
|
||||
Toast.error(t('输入 Schema 与步骤计划必须是合法 JSON'));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const response = await API.post(
|
||||
'/api/org/experts/versions',
|
||||
{
|
||||
...form,
|
||||
fallback_models: csv(form.fallback_models),
|
||||
input_schema: inputSchema,
|
||||
output_contract: {
|
||||
type: form.contract_type,
|
||||
required_sections_zh: csv(form.required_sections_zh),
|
||||
required_sections_en: csv(form.required_sections_en),
|
||||
required_table_columns: [],
|
||||
require_citations: false,
|
||||
forbidden_placeholders: csv(form.forbidden_placeholders),
|
||||
repair_once: true,
|
||||
artifact_mode: form.artifact_mode,
|
||||
file_name:
|
||||
form.artifact_mode === 'file' ? form.artifact_file_name : '',
|
||||
content_type:
|
||||
form.artifact_mode === 'file' ? form.artifact_content_type : '',
|
||||
},
|
||||
step_plan: stepPlan,
|
||||
skill_ids: [],
|
||||
},
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('保存失败'));
|
||||
return;
|
||||
}
|
||||
Toast.success(t('专家草稿版本已创建'));
|
||||
setOpen(false);
|
||||
await load();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async (id) => {
|
||||
const response = await API.post(
|
||||
`/api/org/experts/versions/${id}/submit`,
|
||||
{},
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('提交失败'));
|
||||
return;
|
||||
}
|
||||
Toast.success(t('已提交平台审核'));
|
||||
await load();
|
||||
};
|
||||
|
||||
// 使用指引:企业专家从派生到上岗的流程,完成态由专家/版本数据驱动。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-experts',
|
||||
ready: loaded,
|
||||
title: t('企业专家工坊 · 使用指引'),
|
||||
intro: t('派生 → 配置 → 平台审核 → 发布上岗,版本不可变、全程留审计'),
|
||||
steps: [
|
||||
{
|
||||
title: t('从平台来源派生专家'),
|
||||
detail: t('选择一个平台专家作为安全基线开始创建'),
|
||||
done: definitions.length > 0,
|
||||
cta: t('去创建专家'),
|
||||
onAction: () => beginVersion(null),
|
||||
points: [
|
||||
t('专家标识创建后不可更改;「平台来源」决定继承哪套安全基线'),
|
||||
t('填写中英文名称、说明与适用场景,成员在云端大脑会看到这些信息'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('配置模型与输出契约'),
|
||||
detail: t('默认模型、降级序列、提示词与交付格式'),
|
||||
done: definitions.length > 0,
|
||||
points: [
|
||||
t('「身份与模型」页配置默认模型与逗号分隔的降级模型序列'),
|
||||
t(
|
||||
'「提示词与契约」页定义系统提示词、输入 Schema 与产物形式(页面文本或安全文件)',
|
||||
),
|
||||
t('「步骤与预算」页规划多步骤交付路径和 token 预算上限'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('提交平台审核'),
|
||||
detail: t('保存生成草稿版本,草稿需平台审核后才能发布'),
|
||||
done: definitions.some((view) =>
|
||||
(view.versions || []).some((version) => version.status !== 'draft'),
|
||||
),
|
||||
points: [
|
||||
t('在专家卡片的版本列表里对 draft 版本点「提交审核」'),
|
||||
t('每个版本不可变:审核中发现问题就「创建新版本」修正后重新提交'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('发布后到云端大脑分发'),
|
||||
detail: t('审核通过的版本成为当前版本,再决定谁能用'),
|
||||
done: definitions.some((view) => Boolean(view.current)),
|
||||
points: [
|
||||
t(
|
||||
'到「云端大脑」右上角「管理企业专家」按全企业/部门/项目/成员启停分发',
|
||||
),
|
||||
t('停用后该范围内成员无法创建新任务,进行中任务按安全策略结算'),
|
||||
],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('版本一直是 draft?'),
|
||||
a: t('草稿不会自动送审,需要在版本列表手动点「提交审核」'),
|
||||
},
|
||||
{
|
||||
q: t('专家显示「等待首个版本发布」?'),
|
||||
a: t('尚无审核通过的版本;通过后自动成为当前版本'),
|
||||
},
|
||||
],
|
||||
});
|
||||
const closeGuide = guide.close;
|
||||
// 抽屉进度是组织私有的:切组织时关闭并复位 loaded,
|
||||
// 否则重取窗口内胶囊会按旧组织数据渲染完成态。
|
||||
useEffect(() => {
|
||||
setLoaded(false);
|
||||
closeGuide();
|
||||
}, [orgId, closeGuide]);
|
||||
return (
|
||||
<main className='org-expert-page'>
|
||||
<header className='org-expert-hero'>
|
||||
<div>
|
||||
<Title heading={3}>{t('企业专家工坊')}</Title>
|
||||
<Paragraph>
|
||||
{t(
|
||||
'从平台安全基线派生不可变版本,配置模型、契约与多步骤交付路径。',
|
||||
)}
|
||||
</Paragraph>
|
||||
</div>
|
||||
<div className='org-expert-hero-actions'>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
<Button
|
||||
theme='solid'
|
||||
type='primary'
|
||||
onClick={() => beginVersion(null)}
|
||||
>
|
||||
{t('创建企业专家')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
<PageGuidePill guide={guide} />
|
||||
<PageGuideDrawer guide={guide} />
|
||||
|
||||
<section className='org-expert-grid'>
|
||||
{definitions.length === 0 ? (
|
||||
<div className='org-expert-empty'>
|
||||
<strong>{t('尚未创建企业专家')}</strong>
|
||||
<Text type='tertiary'>
|
||||
{t('选择一个平台专家作为安全来源开始派生。')}
|
||||
</Text>
|
||||
</div>
|
||||
) : (
|
||||
definitions.map((view) => (
|
||||
<OrgPanel
|
||||
key={view.definition.id}
|
||||
title={view.current?.name_zh || view.definition.expert_key}
|
||||
actions={<Tag color='green'>{view.definition.status}</Tag>}
|
||||
>
|
||||
<Paragraph>
|
||||
{view.current?.description_zh || t('等待首个版本发布')}
|
||||
</Paragraph>
|
||||
<div className='org-expert-version-list'>
|
||||
{(view.versions || []).map((version) => (
|
||||
<div key={version.id}>
|
||||
<span>v{version.version}</span>
|
||||
<Tag>{version.status}</Tag>
|
||||
{version.status === 'draft' && (
|
||||
<Button size='small' onClick={() => submit(version.id)}>
|
||||
{t('提交审核')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<Button onClick={() => beginVersion(view)}>
|
||||
{t('创建新版本')}
|
||||
</Button>
|
||||
</OrgPanel>
|
||||
))
|
||||
)}
|
||||
</section>
|
||||
|
||||
<Modal
|
||||
title={form.definition_id ? t('创建专家新版本') : t('创建企业专家')}
|
||||
visible={open}
|
||||
onCancel={() => setOpen(false)}
|
||||
onOk={save}
|
||||
confirmLoading={saving}
|
||||
width={880}
|
||||
className='org-expert-modal'
|
||||
>
|
||||
<Tabs type='line'>
|
||||
<TabPane tab={t('身份与模型')} itemKey='identity'>
|
||||
<div className='org-expert-form-grid'>
|
||||
<label>
|
||||
{t('专家标识')}
|
||||
<Input
|
||||
value={form.expert_key}
|
||||
disabled={!!form.definition_id}
|
||||
onChange={(v) => update('expert_key', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('平台来源')}
|
||||
<Select
|
||||
value={form.source_expert_id || undefined}
|
||||
onChange={(v) => update('source_expert_id', v)}
|
||||
optionList={sources.map((item) => ({
|
||||
value: item.id,
|
||||
label: `${item.name} · v${item.version}`,
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('中文名称')}
|
||||
<Input
|
||||
value={form.name_zh}
|
||||
onChange={(v) => update('name_zh', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('英文名称')}
|
||||
<Input
|
||||
value={form.name_en}
|
||||
onChange={(v) => update('name_en', v)}
|
||||
/>
|
||||
</label>
|
||||
<label className='wide'>
|
||||
{t('中文描述')}
|
||||
<TextArea
|
||||
value={form.description_zh}
|
||||
onChange={(v) => update('description_zh', v)}
|
||||
/>
|
||||
</label>
|
||||
<label className='wide'>
|
||||
{t('英文描述')}
|
||||
<TextArea
|
||||
value={form.description_en}
|
||||
onChange={(v) => update('description_en', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('中文场景')}
|
||||
<Input
|
||||
value={form.scenario_zh}
|
||||
onChange={(v) => update('scenario_zh', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('英文场景')}
|
||||
<Input
|
||||
value={form.scenario_en}
|
||||
onChange={(v) => update('scenario_en', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('默认模型')}
|
||||
<Input
|
||||
value={form.default_model}
|
||||
onChange={(v) => update('default_model', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('降级模型序列')}
|
||||
<Input
|
||||
value={form.fallback_models}
|
||||
onChange={(v) => update('fallback_models', v)}
|
||||
placeholder='model-a, model-b'
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</TabPane>
|
||||
<TabPane tab={t('提示词与契约')} itemKey='contract'>
|
||||
<div className='org-expert-form-grid'>
|
||||
<label className='wide'>
|
||||
{t('中文系统提示词')}
|
||||
<TextArea
|
||||
autosize={{ minRows: 5, maxRows: 12 }}
|
||||
value={form.system_prompt_zh}
|
||||
onChange={(v) => update('system_prompt_zh', v)}
|
||||
/>
|
||||
</label>
|
||||
<label className='wide'>
|
||||
{t('英文系统提示词')}
|
||||
<TextArea
|
||||
autosize={{ minRows: 5, maxRows: 12 }}
|
||||
value={form.system_prompt_en}
|
||||
onChange={(v) => update('system_prompt_en', v)}
|
||||
/>
|
||||
</label>
|
||||
<label className='wide'>
|
||||
{t('输入 JSON Schema')}
|
||||
<TextArea
|
||||
className='mono'
|
||||
autosize={{ minRows: 6, maxRows: 14 }}
|
||||
value={form.input_schema}
|
||||
onChange={(v) => update('input_schema', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('输出类型')}
|
||||
<Select
|
||||
value={form.contract_type}
|
||||
onChange={(v) => update('contract_type', v)}
|
||||
optionList={['markdown', 'json', 'text'].map((v) => ({
|
||||
value: v,
|
||||
label: v,
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('默认语言')}
|
||||
<Select
|
||||
value={form.default_language}
|
||||
onChange={(v) => update('default_language', v)}
|
||||
optionList={[
|
||||
{ value: 'zh', label: '中文' },
|
||||
{ value: 'en', label: 'English' },
|
||||
]}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('产物交付方式')}
|
||||
<Select
|
||||
value={form.artifact_mode}
|
||||
onChange={(v) => update('artifact_mode', v)}
|
||||
optionList={[
|
||||
{ value: 'inline', label: t('页面内文本') },
|
||||
{ value: 'file', label: t('安全文件下载') },
|
||||
]}
|
||||
/>
|
||||
</label>
|
||||
{form.artifact_mode === 'file' && (
|
||||
<>
|
||||
<label>
|
||||
{t('文件名')}
|
||||
<Input
|
||||
value={form.artifact_file_name}
|
||||
onChange={(v) => update('artifact_file_name', v)}
|
||||
placeholder='artifact.md'
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('文件 MIME 类型')}
|
||||
<Select
|
||||
value={form.artifact_content_type || undefined}
|
||||
onChange={(v) => update('artifact_content_type', v)}
|
||||
optionList={[
|
||||
{ value: 'text/markdown', label: 'text/markdown' },
|
||||
{
|
||||
value: 'application/json',
|
||||
label: 'application/json',
|
||||
},
|
||||
{ value: 'text/plain', label: 'text/plain' },
|
||||
{ value: 'text/csv', label: 'text/csv' },
|
||||
]}
|
||||
/>
|
||||
</label>
|
||||
<p className='wide org-expert-help'>
|
||||
{t(
|
||||
'文件会先校验格式、拦截 CSV 公式注入并通过恶意软件扫描,再写入带版本号的私有 COS;下载链接每次重新鉴权且仅短期有效。',
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<label>
|
||||
{t('中文必需章节')}
|
||||
<Input
|
||||
value={form.required_sections_zh}
|
||||
onChange={(v) => update('required_sections_zh', v)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
{t('英文必需章节')}
|
||||
<Input
|
||||
value={form.required_sections_en}
|
||||
onChange={(v) => update('required_sections_en', v)}
|
||||
/>
|
||||
</label>
|
||||
<label className='wide'>
|
||||
{t('禁用占位符')}
|
||||
<Input
|
||||
value={form.forbidden_placeholders}
|
||||
onChange={(v) => update('forbidden_placeholders', v)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</TabPane>
|
||||
<TabPane tab={t('步骤与预算')} itemKey='steps'>
|
||||
<div className='org-expert-form-grid'>
|
||||
<label className='wide'>
|
||||
{t('步骤计划 JSON')}
|
||||
<TextArea
|
||||
className='mono'
|
||||
autosize={{ minRows: 10, maxRows: 20 }}
|
||||
value={form.step_plan}
|
||||
onChange={(v) => update('step_plan', v)}
|
||||
/>
|
||||
</label>
|
||||
{[
|
||||
'max_output_tokens',
|
||||
'max_total_output_tokens',
|
||||
'max_step_quota',
|
||||
'max_task_quota',
|
||||
].map((key) => (
|
||||
<label key={key}>
|
||||
{key}
|
||||
<InputNumber
|
||||
value={form[key]}
|
||||
min={1}
|
||||
onChange={(v) => update(key, Number(v))}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<label className='wide'>
|
||||
{t('安全策略引用')}
|
||||
<Input
|
||||
value={form.safety_policy_ref}
|
||||
onChange={(v) => update('safety_policy_ref', v)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</TabPane>
|
||||
</Tabs>
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgExperts;
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,753 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Form,
|
||||
Toast,
|
||||
Tag,
|
||||
Popconfirm,
|
||||
Banner,
|
||||
Typography,
|
||||
Tooltip,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
RefreshCw,
|
||||
UserPlus,
|
||||
Upload as UploadIcon,
|
||||
KeyRound,
|
||||
IdCard,
|
||||
} from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError, collectPagedItems } from '../../helpers';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgModal from './components/OrgModal';
|
||||
import DeptTreeSelect from './components/DeptTreeSelect';
|
||||
import {
|
||||
buildDeptTreeData,
|
||||
buildDeptFullNameMap,
|
||||
hasChildDept,
|
||||
} from './components/deptTree';
|
||||
import { isOrgFeatureEnabled } from './orgFeatureFlags';
|
||||
|
||||
const { Text } = Typography;
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
const formatImportError = (t, row) => {
|
||||
const params = row?.error_params || {};
|
||||
switch (row?.error_code) {
|
||||
case 'login_name_required':
|
||||
return t('企业内登录名必填');
|
||||
case 'login_name_too_long':
|
||||
return t(
|
||||
'企业内登录名不能超过 {{max}} 个字符,当前 {{actual}} 个字符',
|
||||
params,
|
||||
);
|
||||
case 'employee_no_too_long':
|
||||
return t('工号不能超过 {{max}} 个字符', params);
|
||||
case 'login_name_exists':
|
||||
return t('企业内登录名已存在');
|
||||
case 'login_name_reserved':
|
||||
return t('该登录名为系统保留名称,请换一个登录名');
|
||||
case 'email_exists':
|
||||
return t('该邮箱已是平台用户,请使用企业代码加入企业');
|
||||
case 'member_limit_reached':
|
||||
return t('企业成员数量已达到上限 {{max}}', params);
|
||||
case 'password_generation_failed':
|
||||
return t('初始密码生成失败,请重试');
|
||||
case 'create_failed':
|
||||
return t('账号创建失败,请检查数据后重试');
|
||||
default:
|
||||
return row?.error || t('导入失败');
|
||||
}
|
||||
};
|
||||
|
||||
// 状态色遵循 components/orgStatus.js 的统一口径:正常=green,停用/离职=grey(归档态,非错误态)
|
||||
const statusTag = (t, s) =>
|
||||
s === 1 ? (
|
||||
<Tag color='green'>{t('正常')}</Tag>
|
||||
) : (
|
||||
<Tag color='grey'>{t('已停用/离职')}</Tag>
|
||||
);
|
||||
|
||||
// 员工账号:企业托管账号生命周期(建号/CSV导入/重置密码/离职回收,PR6a)。
|
||||
const OrgMemberAccounts = ({
|
||||
orgId,
|
||||
orgRole = null,
|
||||
embedded = false,
|
||||
featureFlags = null,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
// 企业管理员只能重置本企业托管账号;平台超管额外可重置个人账号(后端同口径校验)
|
||||
const isSuperAdmin = orgRole === 'super_admin';
|
||||
// dept 功能开关关闭时:不请求 /api/org/dept(后端 403),并隐藏部门列/分配入口/建号主部门字段
|
||||
const deptEnabled = isOrgFeatureEnabled(featureFlags, 'dept');
|
||||
const [members, setMembers] = useState([]);
|
||||
const [membersTotal, setMembersTotal] = useState(0);
|
||||
const [depts, setDepts] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const [createVisible, setCreateVisible] = useState(false);
|
||||
const [createFormApi, setCreateFormApi] = useState(null);
|
||||
const [pwdResult, setPwdResult] = useState(null); // {username, login_name, initial_password}
|
||||
|
||||
const [importVisible, setImportVisible] = useState(false);
|
||||
const [importResult, setImportResult] = useState(null);
|
||||
const [importFile, setImportFile] = useState(null);
|
||||
|
||||
const [deptAssignFor, setDeptAssignFor] = useState(null); // 正在分配部门的成员
|
||||
const [deptAssignVal, setDeptAssignVal] = useState(0);
|
||||
|
||||
const fetchAll = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const [m, d] = await Promise.all([
|
||||
// 逐页取全:后端把 page_size 静默钳到 100。本页表格用的是**前端分页**
|
||||
// (pageSize 15),单次只取 100 条会让管理员翻到最后一页、以为已看完
|
||||
// 全部员工,而第 101 位之后的人根本不在表格里——total 也会与实际
|
||||
// 行数对不上。
|
||||
collectPagedItems((page, size) =>
|
||||
API.get(`/api/org/members?p=${page}&page_size=${size}`, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
}),
|
||||
),
|
||||
deptEnabled
|
||||
? // 部门数据仅用于列展示与分配弹窗:网络失败兜底为 null,不连坐员工列表
|
||||
API.get('/api/org/dept', { headers: getOrgHeaders(orgId) }).catch(
|
||||
() => null,
|
||||
)
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
setMembers(m.items);
|
||||
setMembersTotal(m.total);
|
||||
if (m.message) showError(m.message);
|
||||
// 触达 20 页上限(2000 人)时必须明说:本页顶部显示的是后端真实总数,
|
||||
// 不提示的话又会变成"数字与表格行数对不上"的静默截断——正是本轮要消除的问题。
|
||||
if (m.truncated)
|
||||
showError(
|
||||
t(
|
||||
'员工数量超出单次加载上限,列表可能不完整,请用搜索或部门筛选缩小范围',
|
||||
),
|
||||
);
|
||||
if (d) {
|
||||
if (d.data.success) setDepts(d.data.data || []);
|
||||
else showError(d.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [orgId, deptEnabled, t]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchAll();
|
||||
}, [fetchAll]);
|
||||
|
||||
// 建号弹窗主部门的树数据(与分配弹窗同规则:末级可选、停用置灰)
|
||||
const deptTreeData = useMemo(
|
||||
() => buildDeptTreeData(depts, { disabledLabel: t('已停用') }),
|
||||
[depts, t],
|
||||
);
|
||||
const deptNameMap = useMemo(() => {
|
||||
const m = {};
|
||||
depts.forEach((d) => (m[d.id] = d.name));
|
||||
return m;
|
||||
}, [depts]);
|
||||
const deptFullNameMap = useMemo(() => buildDeptFullNameMap(depts), [depts]);
|
||||
// 当前归属部门如今已停用或有了下级(存量数据):仍正常回显,仅提示建议迁移
|
||||
const assignCurrentDeptBlocked = useMemo(() => {
|
||||
const deptId = deptAssignFor?.department_id;
|
||||
if (!deptId) return false;
|
||||
const dept = depts.find((d) => d.id === deptId);
|
||||
if (!dept) return false;
|
||||
return dept.status !== 1 || hasChildDept(depts, deptId);
|
||||
}, [deptAssignFor, depts]);
|
||||
|
||||
const assignDept = async () => {
|
||||
if (!deptAssignFor) return;
|
||||
// 未变化直接关闭:存量归属可能已不满足「末级+启用」校验,原样提交会被后端拒绝
|
||||
if ((deptAssignVal || 0) === (deptAssignFor.department_id || 0)) {
|
||||
setDeptAssignFor(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/members/${deptAssignFor.id}/dept`,
|
||||
{ department_id: deptAssignVal || 0 },
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('部门已分配'));
|
||||
setDeptAssignFor(null);
|
||||
fetchAll();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const submitCreate = async () => {
|
||||
if (!createFormApi) return;
|
||||
let v;
|
||||
try {
|
||||
v = await createFormApi.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
// 统一 trim 后再判空/提交:纯空格登录名在这里即被拦下,而不是到后端才报错。
|
||||
// 后端建号硬性要求 login_name(登录只认登录名),提示与后端对齐,不再误导"填邮箱也行"。
|
||||
const loginName = (v.login_name || '').trim();
|
||||
const email = (v.email || '').trim();
|
||||
if (!loginName) {
|
||||
Toast.warning(t('请填写企业内登录名'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await API.post(
|
||||
'/api/org/members/create-account',
|
||||
{
|
||||
login_name: loginName,
|
||||
display_name: (v.display_name || '').trim(),
|
||||
email,
|
||||
employee_no: (v.employee_no || '').trim(),
|
||||
department_id: v.department_id || 0,
|
||||
},
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
setCreateVisible(false);
|
||||
setPwdResult({
|
||||
username: res.data.data.username,
|
||||
login_name: res.data.data.login_name,
|
||||
initial_password: res.data.data.initial_password,
|
||||
login_name_global_collision:
|
||||
res.data.data.login_name_global_collision,
|
||||
});
|
||||
fetchAll();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const submitImport = async () => {
|
||||
if (!importFile) {
|
||||
Toast.warning(t('请选择 CSV 文件'));
|
||||
return;
|
||||
}
|
||||
const fd = new FormData();
|
||||
fd.append('file', importFile);
|
||||
try {
|
||||
const res = await API.post('/api/org/members/import', fd, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
setImportResult(res.data.data);
|
||||
fetchAll();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const resetPassword = async (member) => {
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/members/${member.id}/reset-password`,
|
||||
{},
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
// 回显被重置的账号:个人账号没有企业内登录名,只能凭系统用户名登录,不回显就无从告知本人。
|
||||
// 托管账号只回显企业内登录名:其系统用户名是 o{orgId}_随机串,企业登录入口不认,
|
||||
// 回显会被误读成“用户名被改了”并分发给员工,导致登录失败
|
||||
const isManaged = member.created_by_org_id === member.organization_id;
|
||||
setPwdResult({
|
||||
username: isManaged && member.login_name ? '' : member.username || '',
|
||||
login_name: member.login_name || '',
|
||||
initial_password: res.data.data.temp_password,
|
||||
reset: true,
|
||||
});
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const offboard = async (memberId) => {
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/members/${memberId}/offboard`,
|
||||
{},
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('已离职回收'));
|
||||
fetchAll();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('成员'),
|
||||
render: (_, r) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<span>{r.display_name || r.username || `#${r.user_id}`}</span>
|
||||
{r.created_by_org_id !== r.organization_id && (
|
||||
<Tooltip
|
||||
content={t('通过企业代码加入的个人平台账号,非本企业托管')}
|
||||
>
|
||||
<Tag size='small' color='blue'>
|
||||
{t('个人账号')}
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('企业内登录名'),
|
||||
dataIndex: 'login_name',
|
||||
render: (v) => v || '-',
|
||||
},
|
||||
...(deptEnabled
|
||||
? [
|
||||
{
|
||||
title: t('部门'),
|
||||
dataIndex: 'department_id',
|
||||
width: 120,
|
||||
render: (v) =>
|
||||
v ? (
|
||||
<Tooltip content={deptFullNameMap[v] || `#${v}`}>
|
||||
<span>{deptNameMap[v] || `#${v}`}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span className='text-gray-400'>{t('未分配')}</span>
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ title: t('工号'), dataIndex: 'employee_no', render: (v) => v || '-' },
|
||||
{
|
||||
title: t('角色'),
|
||||
dataIndex: 'role',
|
||||
width: 90,
|
||||
render: (v) =>
|
||||
v === 'owner'
|
||||
? t('Owner')
|
||||
: v === 'admin'
|
||||
? t('Admin')
|
||||
: v === 'dept_admin'
|
||||
? t('Dept Admin')
|
||||
: t('Member'),
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: 110,
|
||||
render: (v) => statusTag(t, v),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 300,
|
||||
render: (_, r) => {
|
||||
const managed = r.created_by_org_id === r.organization_id;
|
||||
const canReset = managed || isSuperAdmin;
|
||||
return (
|
||||
<div className='flex items-center gap-2'>
|
||||
{deptEnabled && (
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
onClick={() => {
|
||||
setDeptAssignFor(r);
|
||||
setDeptAssignVal(r.department_id || 0);
|
||||
}}
|
||||
>
|
||||
{t('分配部门')}
|
||||
</Button>
|
||||
)}
|
||||
{canReset ? (
|
||||
<Popconfirm
|
||||
title={t('重置该账号密码?')}
|
||||
content={
|
||||
managed
|
||||
? t('将生成一次性临时密码,并要求首次登录改密')
|
||||
: t(
|
||||
'该成员为个人平台账号,重置后其平台登录密码同步失效,请将临时密码安全告知本人',
|
||||
)
|
||||
}
|
||||
onConfirm={() => resetPassword(r)}
|
||||
>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
icon={<KeyRound size={14} />}
|
||||
>
|
||||
{t('重置密码')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
) : (
|
||||
<Tooltip content={t('个人平台账号,请由本人通过找回密码修改')}>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
disabled
|
||||
icon={<KeyRound size={14} />}
|
||||
>
|
||||
{t('重置密码')}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{r.status === 1 && r.role !== 'owner' && (
|
||||
<Popconfirm
|
||||
title={t('确认离职回收该成员?')}
|
||||
content={t(
|
||||
'将禁用其企业成员身份与全部企业 Token,保留历史,不删除用户',
|
||||
)}
|
||||
onConfirm={() => offboard(r.id)}
|
||||
>
|
||||
<Button size='small' theme='light' type='danger'>
|
||||
{t('离职回收')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const actions = (
|
||||
<>
|
||||
<Button theme='light' icon={<RefreshCw size={14} />} onClick={fetchAll}>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<UploadIcon size={14} />}
|
||||
onClick={() => {
|
||||
setImportResult(null);
|
||||
setImportFile(null);
|
||||
setImportVisible(true);
|
||||
}}
|
||||
>
|
||||
{t('CSV 导入')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='solid'
|
||||
icon={<UserPlus size={14} />}
|
||||
onClick={() => setCreateVisible(true)}
|
||||
>
|
||||
{t('创建员工账号')}
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={embedded ? 'space-y-4' : 'p-4 sm:p-6 lg:p-8'}>
|
||||
{embedded ? (
|
||||
<div className='flex items-start justify-between gap-3 flex-wrap rounded-2xl border border-dashed border-brand/25 bg-brand/5 p-4 dark:border-brand/25 dark:bg-brand/10'>
|
||||
<div className='flex items-start gap-3'>
|
||||
<span className='inline-flex h-10 w-10 items-center justify-center rounded-2xl bg-white text-brand-deep shadow-sm dark:bg-white/10 dark:text-brand-from'>
|
||||
<IdCard size={18} />
|
||||
</span>
|
||||
<div>
|
||||
<div className='font-semibold text-gray-950 dark:text-white'>
|
||||
{t('员工账号')}
|
||||
</div>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('集中管理员工登录、批量导入、重置密码与离职回收')}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2 flex-wrap justify-end'>
|
||||
{actions}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<OrgPageHeader
|
||||
icon={IdCard}
|
||||
title={t('员工账号')}
|
||||
subtitle={t('集中管理员工登录账号')}
|
||||
actions={actions}
|
||||
/>
|
||||
)}
|
||||
|
||||
{membersTotal > members.length && (
|
||||
<Banner
|
||||
type='warning'
|
||||
closeIcon={null}
|
||||
className='mb-3'
|
||||
description={t(
|
||||
'员工账号数量已达 100 条上限,当前仅显示前 100 条,请使用搜索定位具体成员。',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<OrgPanel padding='p-2'>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={members}
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showSizeChanger: false }}
|
||||
rowKey='id'
|
||||
/>
|
||||
</OrgPanel>
|
||||
|
||||
{/* 创建账号 */}
|
||||
<OrgModal
|
||||
title={t('创建员工账号')}
|
||||
visible={createVisible}
|
||||
onOk={submitCreate}
|
||||
onCancel={() => setCreateVisible(false)}
|
||||
okText={t('创建')}
|
||||
cancelText={t('取消')}
|
||||
>
|
||||
<Form getFormApi={setCreateFormApi}>
|
||||
<Form.Input
|
||||
field='login_name'
|
||||
label={t('企业内登录名')}
|
||||
placeholder={t('企业内唯一,如 zhangsan')}
|
||||
rules={[
|
||||
{
|
||||
// 与后端一致按码点计数;不用 maxLength 静默截断,让用户明确看到超长提醒
|
||||
validator: (rule, value) =>
|
||||
!value || Array.from(value.trim()).length <= 64,
|
||||
message: t('登录名不能超过 64 个字符'),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Form.Input field='display_name' label={t('姓名/显示名')} />
|
||||
<Form.Input
|
||||
field='email'
|
||||
label={t('邮箱(可选)')}
|
||||
placeholder={t('已是平台用户的邮箱请改用企业代码加入')}
|
||||
rules={[
|
||||
{
|
||||
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
|
||||
message: t('邮箱格式不正确'),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Form.Input
|
||||
field='employee_no'
|
||||
label={t('工号(可选)')}
|
||||
rules={[
|
||||
{
|
||||
validator: (rule, value) =>
|
||||
!value || Array.from(value.trim()).length <= 64,
|
||||
message: t('工号不能超过 64 个字符'),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
{deptEnabled && (
|
||||
<Form.TreeSelect
|
||||
field='department_id'
|
||||
label={t('主部门')}
|
||||
treeData={deptTreeData}
|
||||
showClear
|
||||
filterTreeNode
|
||||
showFilteredOnly
|
||||
expandAll
|
||||
placeholder={t('未分配')}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
)}
|
||||
</Form>
|
||||
</OrgModal>
|
||||
|
||||
{/* 一次性密码结果 */}
|
||||
<OrgModal
|
||||
title={pwdResult?.reset ? t('密码已重置') : t('账号已创建')}
|
||||
visible={!!pwdResult}
|
||||
onCancel={() => setPwdResult(null)}
|
||||
footer={
|
||||
<Button theme='solid' onClick={() => setPwdResult(null)}>
|
||||
{t('我已记录')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<Banner
|
||||
type='warning'
|
||||
closeIcon={null}
|
||||
description={t(
|
||||
'初始密码仅显示这一次,请立即复制并安全分发给员工。关闭后无法再次查看。',
|
||||
)}
|
||||
className='mb-3'
|
||||
/>
|
||||
{pwdResult?.username ? (
|
||||
<div className='mb-2'>
|
||||
<Text type='tertiary'>{t('系统用户名')}: </Text>
|
||||
<Text copyable>{pwdResult.username}</Text>
|
||||
</div>
|
||||
) : null}
|
||||
{pwdResult?.login_name ? (
|
||||
<div className='mb-2'>
|
||||
<Text type='tertiary'>{t('企业内登录名')}: </Text>
|
||||
<Text copyable>{pwdResult.login_name}</Text>
|
||||
</div>
|
||||
) : null}
|
||||
{pwdResult?.login_name_global_collision ? (
|
||||
<Banner
|
||||
type='info'
|
||||
closeIcon={null}
|
||||
description={t(
|
||||
'提示:该登录名在其他企业也存在。若已开启「免企业标识直接登录」,该员工登录时可能需要从多个企业中选择。可考虑使用更唯一的登录名(如加工号)。',
|
||||
)}
|
||||
className='mb-3'
|
||||
/>
|
||||
) : null}
|
||||
<div>
|
||||
<Text type='tertiary'>{t('初始密码')}: </Text>
|
||||
<Text copyable strong>
|
||||
{pwdResult?.initial_password}
|
||||
</Text>
|
||||
</div>
|
||||
</OrgModal>
|
||||
|
||||
{/* 分配部门 */}
|
||||
<OrgModal
|
||||
title={`${t('分配部门')} - ${deptAssignFor?.display_name || deptAssignFor?.username || ''}`}
|
||||
visible={!!deptAssignFor}
|
||||
onOk={assignDept}
|
||||
onCancel={() => setDeptAssignFor(null)}
|
||||
okText={t('保存')}
|
||||
cancelText={t('取消')}
|
||||
>
|
||||
{assignCurrentDeptBlocked && (
|
||||
<Banner
|
||||
type='info'
|
||||
closeIcon={null}
|
||||
className='mb-3'
|
||||
description={t(
|
||||
'该成员当前归属的部门已停用或已有下级部门,建议迁移到具体的末级部门。',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<DeptTreeSelect
|
||||
depts={depts}
|
||||
value={deptAssignVal}
|
||||
onChange={setDeptAssignVal}
|
||||
/>
|
||||
</OrgModal>
|
||||
|
||||
{/* CSV 导入 */}
|
||||
<OrgModal
|
||||
title={t('CSV 批量导入')}
|
||||
visible={importVisible}
|
||||
onOk={importResult ? () => setImportVisible(false) : submitImport}
|
||||
onCancel={() => setImportVisible(false)}
|
||||
okText={importResult ? t('完成') : t('开始导入')}
|
||||
cancelText={t('取消')}
|
||||
width={620}
|
||||
>
|
||||
{!importResult ? (
|
||||
<>
|
||||
<Banner
|
||||
type='info'
|
||||
closeIcon={null}
|
||||
className='mb-3'
|
||||
description={t(
|
||||
'表头需含 login_name,display_name,email,employee_no(login_name 必填,不超过 64 个字符)。单次最多 500 行。每个账号返回一次性初始密码。',
|
||||
)}
|
||||
/>
|
||||
<input
|
||||
type='file'
|
||||
accept='.csv'
|
||||
onChange={(e) => setImportFile(e.target.files?.[0] || null)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Banner
|
||||
type={importResult.failed > 0 ? 'warning' : 'success'}
|
||||
closeIcon={null}
|
||||
className='mb-3'
|
||||
description={`${t('成功')} ${importResult.success} · ${t('失败')} ${importResult.failed} / ${t('共')} ${importResult.total}`}
|
||||
/>
|
||||
<Table
|
||||
size='small'
|
||||
pagination={false}
|
||||
rowKey={(r) => `${r.row}`}
|
||||
dataSource={importResult.details || []}
|
||||
columns={[
|
||||
{ title: t('行'), dataIndex: 'row', width: 50 },
|
||||
{ title: t('登录名'), dataIndex: 'login_name' },
|
||||
{
|
||||
title: t('结果'),
|
||||
render: (_, r) =>
|
||||
r.success ? (
|
||||
<span>
|
||||
<Tag color='green' size='small'>
|
||||
{t('成功')}
|
||||
</Tag>{' '}
|
||||
<Text
|
||||
size='small'
|
||||
copyable={{ content: r.initial_password }}
|
||||
>
|
||||
{t('初始密码')}
|
||||
</Text>
|
||||
</span>
|
||||
) : (
|
||||
<Tooltipless error={formatImportError(t, r)} t={t} />
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('初始密码仅此一次,请及时导出/分发。')}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</OrgModal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 简单错误展示(避免引入额外组件)
|
||||
const Tooltipless = ({ error, t }) => (
|
||||
<span>
|
||||
<Tag color='red' size='small'>
|
||||
{t('失败')}
|
||||
</Tag>{' '}
|
||||
<Text type='danger' size='small'>
|
||||
{error}
|
||||
</Text>
|
||||
</span>
|
||||
);
|
||||
|
||||
export default OrgMemberAccounts;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import OrgSubpageTabs from './components/OrgSubpageTabs';
|
||||
import OrgMySkills from './OrgMySkills';
|
||||
import OrgMyConnectors from './OrgMyConnectors';
|
||||
|
||||
/**
|
||||
* 我的 AI 能力:成员自助视图的合并入口(我的技能 + 业务系统授权)。
|
||||
*
|
||||
* 两个页签都是 isMemberActor 守卫的只读/自助页,各自受不同的企业功能位
|
||||
* (skill_market / connector)与站点级模块开关控制,由 showSkills /
|
||||
* showConnectors 决定可见性。旧路由 /org/my-skills、/org/my-connectors
|
||||
* 重定向到对应页签。
|
||||
*/
|
||||
const OrgMyCapabilities = ({
|
||||
orgId,
|
||||
showSkills = true,
|
||||
showConnectors = true,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<OrgSubpageTabs
|
||||
tabs={[
|
||||
showSkills && {
|
||||
key: 'skills',
|
||||
label: t('我的技能'),
|
||||
node: <OrgMySkills orgId={orgId} />,
|
||||
},
|
||||
showConnectors && {
|
||||
key: 'connectors',
|
||||
label: t('业务系统授权'),
|
||||
node: <OrgMyConnectors orgId={orgId} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgMyCapabilities;
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { Button, Empty, Tag } from '@douyinfe/semi-ui';
|
||||
import { Cable, LockKeyhole } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers/api';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import './org-connectors.css';
|
||||
|
||||
const OrgMyConnectors = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
const [items, setItems] = useState([]);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
API.get('/api/org/connectors/mine', { headers, skipErrorHandler: true })
|
||||
.then((response) => {
|
||||
if (!active) return;
|
||||
if (response.data?.success) {
|
||||
setItems(response.data.data || []);
|
||||
setLoadError('');
|
||||
} else {
|
||||
// A failed load must not masquerade as "no authorizations".
|
||||
setLoadError(response.data?.message || t('授权列表加载失败'));
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (active)
|
||||
setLoadError(
|
||||
error?.response?.data?.message ||
|
||||
error?.message ||
|
||||
t('授权列表加载失败'),
|
||||
);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [headers, t]);
|
||||
|
||||
// 使用指引:成员视角的阅读式说明(无上手流程,不出进度胶囊)。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-my-connectors',
|
||||
title: t('我的业务系统授权 · 使用指引'),
|
||||
intro: t('这里列出专家在任务中可以代表你调用的业务系统与边界'),
|
||||
steps: [
|
||||
{
|
||||
title: t('看懂授权卡片'),
|
||||
detail: t('一张卡片对应一个已授权的业务系统连接器'),
|
||||
points: [
|
||||
t('右上角标签是访问级别:read 只读,write 可执行写操作'),
|
||||
t('卡片中的标签列出专家可调用的具体方法'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('理解确认策略'),
|
||||
detail: t('确认策略决定哪些调用执行前需要你亲自确认'),
|
||||
points: [
|
||||
t('never 无需确认;write 写操作前确认;always 每次调用都确认'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('任务中的确认操作'),
|
||||
detail: t('确认动作发生在云端大脑的任务详情页'),
|
||||
points: [
|
||||
t('专家发起调用时任务会停在「等待操作确认」'),
|
||||
t('展开「查看冻结参数」核对操作内容,填写原因后确认或拒绝'),
|
||||
t('长时间不处理会确认超时,任务按已发生用量结算'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('需要调整授权'),
|
||||
detail: t('授权由企业管理员统一发布与撤销'),
|
||||
points: [t('缺少某个系统的授权或范围不足时,请联系企业管理员')],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('列表是空的?'),
|
||||
a: t('管理员发布授权并覆盖到你之后才会显示,请联系企业管理员'),
|
||||
},
|
||||
{
|
||||
q: t('「企业服务账号由管理员管理」是什么意思?'),
|
||||
a: t('该连接器以企业级凭据运行,个人无法自行撤销'),
|
||||
},
|
||||
],
|
||||
});
|
||||
return (
|
||||
<main className='org-connector-page'>
|
||||
<header className='org-connector-hero'>
|
||||
<div>
|
||||
<h1>{t('我的业务系统授权')}</h1>
|
||||
<p>{t('查看专家在任务中可代表你调用的业务系统、方法和确认策略。')}</p>
|
||||
</div>
|
||||
<div className='org-connector-actions'>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
</div>
|
||||
</header>
|
||||
<PageGuideDrawer guide={guide} />
|
||||
{loadError ? (
|
||||
<Empty title={t('授权列表加载失败')} description={loadError} />
|
||||
) : items.length === 0 ? (
|
||||
<Empty
|
||||
title={t('当前没有 Connector 授权')}
|
||||
description={t('管理员发布授权并覆盖到你后会显示在这里。')}
|
||||
/>
|
||||
) : (
|
||||
<section className='org-connector-grid'>
|
||||
{items.map((item) => (
|
||||
<article className='org-connector-card' key={item.grant.id}>
|
||||
<div className='org-connector-card-top'>
|
||||
<span className='org-connector-icon'>
|
||||
<Cable size={20} />
|
||||
</span>
|
||||
<Tag
|
||||
color={
|
||||
item.grant.access_level === 'write' ? 'orange' : 'green'
|
||||
}
|
||||
>
|
||||
{item.grant.access_level}
|
||||
</Tag>
|
||||
</div>
|
||||
<h3>{item.connector_name}</h3>
|
||||
<p>{item.definition_name}</p>
|
||||
<div className='org-connector-tags'>
|
||||
{item.methods.map((method) => (
|
||||
<Tag key={method}>{method}</Tag>
|
||||
))}
|
||||
</div>
|
||||
<p>
|
||||
<LockKeyhole size={14} /> {t('确认策略')}:{' '}
|
||||
{item.grant.confirmation_policy}
|
||||
</p>
|
||||
<Button disabled={!item.revocable}>
|
||||
{item.revocable
|
||||
? t('撤销个人委托')
|
||||
: t('企业服务账号由管理员管理')}
|
||||
</Button>
|
||||
</article>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgMyConnectors;
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Switch, Toast, Typography } from '@douyinfe/semi-ui';
|
||||
import { LockKeyhole } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers';
|
||||
import {
|
||||
AssignmentModeTag,
|
||||
ScopeSourceBadge,
|
||||
SkillEmptyGuide,
|
||||
} from '../../components/skill';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import './org-skills.css';
|
||||
|
||||
const { Title, Paragraph, Text } = Typography;
|
||||
|
||||
const OrgMySkills = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
const [items, setItems] = useState([]);
|
||||
const load = useCallback(async () => {
|
||||
const response = await API.get('/api/org/skills/mine', { headers });
|
||||
if (response.data?.success) {
|
||||
setItems(response.data.data || []);
|
||||
}
|
||||
}, [headers]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const choose = async (item, enabled) => {
|
||||
const response = await API.put(
|
||||
`/api/org/skills/mine/${item.skill_id}`,
|
||||
{ enabled },
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return;
|
||||
}
|
||||
await load();
|
||||
};
|
||||
// 使用指引:成员视角的阅读式说明(无上手流程,不出进度胶囊)。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-my-skills',
|
||||
title: t('我的技能 · 使用指引'),
|
||||
intro: t('这里是任务运行时真实生效的能力集,来源与状态一目了然'),
|
||||
steps: [
|
||||
{
|
||||
title: t('看懂每一行'),
|
||||
detail: t('名称 + 版本号是企业审核过的不可变技能版本'),
|
||||
points: [
|
||||
t('「必需锁定」带锁图标,是管理员强制启用的技能,不可关闭'),
|
||||
t(
|
||||
'标签含义:必需锁定 / 默认开启 / 推荐 / 可选,决定技能如何对你生效',
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('追溯生效来源'),
|
||||
detail: t('来源徽章回答「为什么这个技能对我生效」'),
|
||||
points: [
|
||||
t('徽章显示分发范围(企业 / 部门 / 项目 / 角色 / 成员)与目标值'),
|
||||
t('鼠标悬停可见该来源的分发模式与激活方式'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('启停技能'),
|
||||
detail: t('用每行右侧开关控制技能是否对自己生效'),
|
||||
points: [
|
||||
t('关闭后,专家执行你的任务时不再注入该能力'),
|
||||
t('带锁的必需技能开关为灰色,如需调整请联系企业管理员'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('想要新技能'),
|
||||
detail: t('到技能超市点「我想要」,把诉求告诉管理员'),
|
||||
points: [
|
||||
t('管理员启用并创建分发策略覆盖到你之后,技能会自动出现在这里'),
|
||||
],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('技能列表为空?'),
|
||||
a: t('企业管理员在技能超市为企业启用并分发后才会显示'),
|
||||
},
|
||||
{
|
||||
q: t('开关是灰色的?'),
|
||||
a: t('该技能被管理员设为「必需锁定」,不可自行关闭'),
|
||||
},
|
||||
],
|
||||
});
|
||||
return (
|
||||
<main className='org-skills-page'>
|
||||
<header className='org-skills-hero'>
|
||||
<div>
|
||||
<Title heading={3}>{t('我的技能')}</Title>
|
||||
<Paragraph>
|
||||
{t(
|
||||
'这里展示与任务运行时相同的有效能力集,以及每项技能为什么对你生效。',
|
||||
)}
|
||||
</Paragraph>
|
||||
</div>
|
||||
<div className='org-skills-hero-actions'>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
</div>
|
||||
</header>
|
||||
<PageGuideDrawer guide={guide} />
|
||||
{items.length === 0 ? (
|
||||
<SkillEmptyGuide
|
||||
title={t('当前没有可用技能')}
|
||||
description={t('企业管理员启用并分发后会显示在这里。')}
|
||||
/>
|
||||
) : (
|
||||
<section className='org-my-skills'>
|
||||
{items
|
||||
.filter((item) => item.mode !== 'forbidden')
|
||||
.map((item) => {
|
||||
const locked = item.mode === 'required_locked';
|
||||
return (
|
||||
<article key={item.skill_id}>
|
||||
<div>
|
||||
<span className='org-my-skill-title'>
|
||||
{locked && <LockKeyhole size={16} />}
|
||||
<Text strong>
|
||||
{item.customization?.display_name || item.canonical_id}
|
||||
</Text>
|
||||
<AssignmentModeTag mode={item.mode} />
|
||||
</span>
|
||||
<Paragraph>
|
||||
{item.customization?.description_zh ||
|
||||
item.customization?.usage_boundary ||
|
||||
t('企业已审核的方法能力')}
|
||||
</Paragraph>
|
||||
<div className='org-my-skill-sources'>
|
||||
{(item.sources || []).map((source) => (
|
||||
<ScopeSourceBadge
|
||||
key={source.id}
|
||||
source={`${source.scope_type}:${source.scope_id || source.scope_value || 'all'}`}
|
||||
detail={`${source.mode} / ${source.activation}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Text type='tertiary'>v#{item.version_id}</Text>
|
||||
<Switch
|
||||
disabled={locked}
|
||||
checked={item.enabled}
|
||||
onChange={(enabled) => choose(item, enabled)}
|
||||
/>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgMySkills;
|
||||
@@ -0,0 +1,520 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useContext, useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Button,
|
||||
InputNumber,
|
||||
Spin,
|
||||
Tabs,
|
||||
TabPane,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
Bell,
|
||||
Building2,
|
||||
KeyRound,
|
||||
Pencil,
|
||||
UserRound,
|
||||
UserCog,
|
||||
Wallet,
|
||||
} from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import {
|
||||
showError,
|
||||
showSuccess,
|
||||
setUserData,
|
||||
parseUserSetting,
|
||||
USER_AVATAR_TYPES,
|
||||
getAvatarPresetById,
|
||||
getDefaultAvatarPresetId,
|
||||
} from '../../helpers';
|
||||
import { renderQuota } from '../../helpers/render';
|
||||
import { UserContext } from '../../context/User';
|
||||
import NotifyChannelForm from '../../components/settings/NotifyChannelForm';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgAvatarSection from './components/OrgAvatarSection';
|
||||
import OrgNicknameModal from './components/OrgNicknameModal';
|
||||
import OrgPasswordModal from './components/OrgPasswordModal';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
const roleLabel = (t, role) =>
|
||||
role === 'owner'
|
||||
? t('所有者')
|
||||
: role === 'admin'
|
||||
? t('管理员')
|
||||
: role === 'super_admin'
|
||||
? t('超级管理员')
|
||||
: t('成员');
|
||||
|
||||
const PERIODIC_QUOTA_PERIODS = new Set(['daily', 'weekly', 'monthly']);
|
||||
|
||||
const quotaPeriodHint = (t, period) => {
|
||||
switch (period) {
|
||||
case 'daily':
|
||||
return t('每日重置');
|
||||
case 'weekly':
|
||||
return t('每周重置');
|
||||
case 'monthly':
|
||||
return t('每月重置');
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
// 信息行:label + 右侧内容(个人资料/企业身份卡片共用)
|
||||
const InfoRow = ({ label, children, last = false }) => (
|
||||
<div
|
||||
className={`flex items-center justify-between gap-3 py-3 ${
|
||||
last ? '' : 'border-b border-[var(--border-subtle)]'
|
||||
}`}
|
||||
>
|
||||
<Text type='tertiary' className='flex-shrink-0'>
|
||||
{label}
|
||||
</Text>
|
||||
<div className='flex items-center gap-2 min-w-0'>{children}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
/*
|
||||
* 成员个人设置页(/org/personal-settings,全员可见)。
|
||||
* 企业中心是独立空间:改密/昵称走企业端接口,通知为企业维度的成员配额预警,
|
||||
* 不出现个人余额概念(方案 docs/06-企业运营治理中心/11-企业用户个人设置页面方案.md)。
|
||||
*/
|
||||
const OrgPersonalSettings = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const [userState, userDispatch] = useContext(UserContext);
|
||||
|
||||
const [summary, setSummary] = useState(null);
|
||||
const [summaryLoading, setSummaryLoading] = useState(true);
|
||||
const [nickModal, setNickModal] = useState(false);
|
||||
const [pwdModal, setPwdModal] = useState(false);
|
||||
|
||||
// 头像:与个人中心共用 user.setting 存储,保存走企业端 /me/profile 后端合并
|
||||
const [avatarSettings, setAvatarSettings] = useState({
|
||||
avatarType: USER_AVATAR_TYPES.PRESET,
|
||||
avatarPreset: getDefaultAvatarPresetId(userState?.user),
|
||||
customAvatarUrl: '',
|
||||
});
|
||||
const [savingAvatar, setSavingAvatar] = useState(false);
|
||||
|
||||
// 通知:企业维度(成员配额预警),存 organization_members
|
||||
const [notifyValue, setNotifyValue] = useState({ notify_type: 'email' });
|
||||
const [alertThreshold, setAlertThreshold] = useState(0);
|
||||
const [savingNotify, setSavingNotify] = useState(false);
|
||||
|
||||
// 系统超管直通企业时无真实成员行(member.id=0),通知设置无从挂靠
|
||||
const isSuperAdminView =
|
||||
summary?.member?.role === 'super_admin' || summary?.member?.id === 0;
|
||||
|
||||
const fetchSummary = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
try {
|
||||
const res = await API.get('/api/org/me/summary', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
setSummary(res.data.data);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setSummaryLoading(false);
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
const fetchNotifySetting = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
try {
|
||||
const res = await API.get('/api/org/me/notify-setting', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success && res.data.data) {
|
||||
const d = res.data.data;
|
||||
setNotifyValue({
|
||||
notify_type: d.notify_type || 'email',
|
||||
notification_email: d.notification_email || '',
|
||||
webhook_url: d.webhook_url || '',
|
||||
webhook_secret: d.webhook_secret || '',
|
||||
});
|
||||
setAlertThreshold(d.quota_alert_threshold || 0);
|
||||
}
|
||||
} catch (err) {
|
||||
// 超管直通等场景后端返回错误,静默降级(通知区块会被禁用)
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSummary();
|
||||
fetchNotifySetting();
|
||||
}, [fetchSummary, fetchNotifySetting]);
|
||||
|
||||
// 从 user.setting 初始化头像(与个人中心 PersonalSetting 同款逻辑)
|
||||
useEffect(() => {
|
||||
if (userState?.user?.setting) {
|
||||
const settings = parseUserSetting(userState.user.setting);
|
||||
setAvatarSettings({
|
||||
avatarType: Object.values(USER_AVATAR_TYPES).includes(
|
||||
settings.avatar_type,
|
||||
)
|
||||
? settings.avatar_type
|
||||
: USER_AVATAR_TYPES.PRESET,
|
||||
avatarPreset: getAvatarPresetById(
|
||||
settings.avatar_preset || getDefaultAvatarPresetId(userState.user),
|
||||
).id,
|
||||
customAvatarUrl: settings.custom_avatar_url || '',
|
||||
});
|
||||
} else if (userState?.user) {
|
||||
setAvatarSettings((prev) => ({
|
||||
...prev,
|
||||
avatarPreset:
|
||||
prev.avatarPreset || getDefaultAvatarPresetId(userState.user),
|
||||
}));
|
||||
}
|
||||
}, [userState?.user?.id, userState?.user?.setting]);
|
||||
|
||||
const handleAvatarSettingChange = (type, value) => {
|
||||
setAvatarSettings((prev) => ({ ...prev, [type]: value }));
|
||||
};
|
||||
|
||||
// 头像保存后刷新 UserContext,全局顶栏头像即时更新(/api/user/self 对企业员工放行)
|
||||
const refreshUserSelf = async () => {
|
||||
try {
|
||||
const res = await API.get('/api/user/self');
|
||||
if (res.data.success) {
|
||||
userDispatch({ type: 'login', payload: res.data.data });
|
||||
setUserData(res.data.data);
|
||||
}
|
||||
} catch (err) {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const saveAvatarSettings = async () => {
|
||||
if (
|
||||
avatarSettings.avatarType === USER_AVATAR_TYPES.CUSTOM &&
|
||||
!avatarSettings.customAvatarUrl?.trim()
|
||||
) {
|
||||
showError(t('请先填写自定义头像图片 URL'));
|
||||
return;
|
||||
}
|
||||
setSavingAvatar(true);
|
||||
try {
|
||||
const res = await API.put(
|
||||
'/api/org/me/profile',
|
||||
{
|
||||
avatar_type: avatarSettings.avatarType,
|
||||
avatar_preset: avatarSettings.avatarPreset,
|
||||
custom_avatar_url: avatarSettings.customAvatarUrl,
|
||||
},
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
showSuccess(t('头像设置已保存'));
|
||||
await refreshUserSelf();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(t('头像设置保存失败'));
|
||||
} finally {
|
||||
setSavingAvatar(false);
|
||||
}
|
||||
};
|
||||
|
||||
const saveNotifySettings = async () => {
|
||||
const type = notifyValue.notify_type || 'email';
|
||||
if (type === 'email' && !notifyValue.notification_email?.trim()) {
|
||||
showError(t('请填写有效的通知邮箱'));
|
||||
return;
|
||||
}
|
||||
if (type === 'webhook' && !notifyValue.webhook_url?.trim()) {
|
||||
showError(t('Webhook地址不能为空'));
|
||||
return;
|
||||
}
|
||||
setSavingNotify(true);
|
||||
try {
|
||||
const res = await API.put(
|
||||
'/api/org/me/notify-setting',
|
||||
{
|
||||
notify_type: type,
|
||||
notification_email: notifyValue.notification_email || '',
|
||||
webhook_url: notifyValue.webhook_url || '',
|
||||
webhook_secret: notifyValue.webhook_secret || '',
|
||||
quota_alert_threshold: Number(alertThreshold) || 0,
|
||||
},
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
showSuccess(t('通知设置已保存'));
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setSavingNotify(false);
|
||||
}
|
||||
};
|
||||
|
||||
const member = summary?.member || {};
|
||||
const myQuota = summary?.my_quota || {};
|
||||
const quotaLimit = Number(myQuota.quota_limit || 0);
|
||||
const isPeriodic = PERIODIC_QUOTA_PERIODS.has(myQuota.quota_period);
|
||||
const usedQuota = Number(
|
||||
isPeriodic ? myQuota.quota_used_in_period || 0 : myQuota.used_quota || 0,
|
||||
);
|
||||
const remainQuota = Math.max(0, quotaLimit - usedQuota);
|
||||
// 展示百分比:耗尽=100;否则四舍五入,但「有用量至少 1%、未耗尽最多 99%」,
|
||||
// 避免"有微量用量却显示 0%"或"未用尽却显示 100%"的误导。进度条与文案共用同一值。
|
||||
const usedPct =
|
||||
quotaLimit <= 0
|
||||
? 0
|
||||
: usedQuota >= quotaLimit
|
||||
? 100
|
||||
: Math.min(
|
||||
99,
|
||||
Math.max(
|
||||
usedQuota > 0 ? 1 : 0,
|
||||
Math.round((usedQuota / quotaLimit) * 100),
|
||||
),
|
||||
);
|
||||
// 进度条随用量升温:正常品牌色,≥80% 转琥珀,≥95% 转红,给成员用尽预警
|
||||
const quotaBarClass =
|
||||
usedPct >= 95 ? 'bg-red-500' : usedPct >= 80 ? 'bg-amber-500' : 'bg-brand';
|
||||
const displayName =
|
||||
member.display_name ||
|
||||
userState?.user?.display_name ||
|
||||
userState?.user?.username ||
|
||||
'';
|
||||
|
||||
if (summaryLoading) {
|
||||
return (
|
||||
<div className='flex items-center justify-center h-full min-h-[240px]'>
|
||||
<Spin size='large' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
icon={UserCog}
|
||||
title={t('个人设置')}
|
||||
subtitle={t('管理你的头像、昵称、密码与通知偏好')}
|
||||
/>
|
||||
|
||||
<Tabs type='line' className='mt-2'>
|
||||
<TabPane tab={t('个人资料')} itemKey='profile'>
|
||||
{/* 头像设置上移至页面上半部分,作为视觉锚点,保存走企业端接口 */}
|
||||
<div className='mt-4'>
|
||||
<OrgAvatarSection
|
||||
t={t}
|
||||
userState={userState}
|
||||
avatarSettings={avatarSettings}
|
||||
handleAvatarSettingChange={handleAvatarSettingChange}
|
||||
saveAvatarSettings={saveAvatarSettings}
|
||||
saving={savingAvatar}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 基本资料 / 企业身份 / 个人配额:三栏均分,卡片等高,避免高度失衡 */}
|
||||
<div className='mt-4 grid grid-cols-1 lg:grid-cols-3 gap-4'>
|
||||
{/* 基本资料:昵称 + 登录密码(复用工作台同款弹窗与企业端接口) */}
|
||||
<OrgPanel title={t('基本资料')} icon={UserRound} padding='px-5 py-2'>
|
||||
<InfoRow label={t('昵称')}>
|
||||
<Text className='truncate'>{displayName || t('未设置')}</Text>
|
||||
<Button
|
||||
theme='light'
|
||||
size='small'
|
||||
icon={<Pencil size={13} />}
|
||||
onClick={() => setNickModal(true)}
|
||||
>
|
||||
{t('编辑')}
|
||||
</Button>
|
||||
</InfoRow>
|
||||
<InfoRow label={t('登录密码')} last>
|
||||
<Text type='tertiary'>••••••••</Text>
|
||||
<Button
|
||||
theme='light'
|
||||
size='small'
|
||||
icon={<KeyRound size={13} />}
|
||||
onClick={() => setPwdModal(true)}
|
||||
>
|
||||
{t('修改密码')}
|
||||
</Button>
|
||||
</InfoRow>
|
||||
</OrgPanel>
|
||||
|
||||
{/* 企业身份只读信息(数据源 /api/org/me/summary,与工作台一致) */}
|
||||
<OrgPanel title={t('企业身份')} icon={Building2} padding='px-5 py-2'>
|
||||
<InfoRow label={t('所属企业')}>
|
||||
<Text className='truncate'>
|
||||
{summary?.organization?.name || '-'}
|
||||
</Text>
|
||||
</InfoRow>
|
||||
<InfoRow label={t('我的角色')}>
|
||||
<span className='inline-flex items-center rounded-full bg-brand/10 text-brand px-2.5 py-0.5 text-xs font-medium'>
|
||||
{roleLabel(t, member.role)}
|
||||
</span>
|
||||
</InfoRow>
|
||||
<InfoRow label={t('所属部门')} last>
|
||||
<Text className='truncate'>
|
||||
{member.department_name || t('未分配')}
|
||||
</Text>
|
||||
</InfoRow>
|
||||
</OrgPanel>
|
||||
|
||||
{/* 个人配额:成员高频关注项,抽成带进度条的重点块 */}
|
||||
<OrgPanel title={t('个人配额')} icon={Wallet} padding='p-5'>
|
||||
{quotaLimit > 0 ? (
|
||||
<div>
|
||||
<div className='flex items-end justify-between gap-3'>
|
||||
<div className='min-w-0'>
|
||||
<div className='text-xs text-[var(--text-secondary)]'>
|
||||
{t('剩余可用')}
|
||||
</div>
|
||||
<div className='mt-0.5 text-2xl font-semibold text-[var(--text-primary)] truncate'>
|
||||
{renderQuota(remainQuota)}
|
||||
</div>
|
||||
</div>
|
||||
<div className='shrink-0 text-right text-xs text-gray-500 dark:text-gray-400 leading-relaxed'>
|
||||
<div>
|
||||
{t('已用')} {renderQuota(usedQuota)}
|
||||
</div>
|
||||
<div>
|
||||
{t('总额')} {renderQuota(quotaLimit)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className='mt-3 h-2 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-white/[0.08]'>
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-300 ${quotaBarClass}`}
|
||||
style={{ width: `${usedPct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className='mt-2 flex items-center justify-between text-xs'>
|
||||
<span className='text-gray-500 dark:text-gray-400'>
|
||||
{t('已用')} {usedPct}%
|
||||
</span>
|
||||
{isPeriodic && (
|
||||
<span className='text-brand font-medium'>
|
||||
{quotaPeriodHint(t, myQuota.quota_period)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className='flex items-center gap-2 py-1.5'>
|
||||
<span className='inline-flex items-center rounded-full bg-brand/10 text-brand px-2.5 py-0.5 text-xs font-medium'>
|
||||
{t('不限额')}
|
||||
</span>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('企业未对你设置配额上限')}
|
||||
</Text>
|
||||
</div>
|
||||
)}
|
||||
</OrgPanel>
|
||||
</div>
|
||||
</TabPane>
|
||||
|
||||
<TabPane
|
||||
tab={t('通知设置')}
|
||||
itemKey='notify'
|
||||
disabled={isSuperAdminView}
|
||||
>
|
||||
<OrgPanel
|
||||
title={t('配额预警通知')}
|
||||
subtitle={t(
|
||||
'企业分配给你的额度即将用尽或已用尽时,通过以下渠道提醒你',
|
||||
)}
|
||||
icon={Bell}
|
||||
padding='p-5'
|
||||
className='mt-4'
|
||||
actions={
|
||||
<Button
|
||||
theme='solid'
|
||||
loading={savingNotify}
|
||||
onClick={saveNotifySettings}
|
||||
>
|
||||
{t('保存通知设置')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<NotifyChannelForm
|
||||
value={notifyValue}
|
||||
onChange={setNotifyValue}
|
||||
channels={['email', 'webhook']}
|
||||
emailPlaceholder={t('必填,用于接收预警通知')}
|
||||
/>
|
||||
|
||||
<div className='mt-5 pt-4 border-t border-[var(--border-subtle)]'>
|
||||
<label className='block text-sm font-medium text-[var(--text-primary)] mb-2'>
|
||||
{t('预警阈值')}
|
||||
</label>
|
||||
{quotaLimit > 0 ? (
|
||||
<>
|
||||
<InputNumber
|
||||
value={alertThreshold}
|
||||
onChange={(v) => setAlertThreshold(v)}
|
||||
min={0}
|
||||
step={1000}
|
||||
style={{ width: '100%', maxWidth: 260 }}
|
||||
/>
|
||||
<div className='mt-2'>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('剩余额度低于该值时提醒,0 表示关闭')}
|
||||
{Number(alertThreshold) > 0 &&
|
||||
` · ${t('约合')} ${renderQuota(Number(alertThreshold))}`}
|
||||
{` · ${t('当前剩余')} ${renderQuota(remainQuota)}`}
|
||||
</Text>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<Text type='tertiary'>
|
||||
{t('企业未对你设置配额上限,无需配置预警')}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
</OrgPanel>
|
||||
</TabPane>
|
||||
</Tabs>
|
||||
|
||||
<OrgNicknameModal
|
||||
visible={nickModal}
|
||||
onClose={() => setNickModal(false)}
|
||||
orgId={orgId}
|
||||
currentName={displayName}
|
||||
onSuccess={() => {
|
||||
fetchSummary();
|
||||
refreshUserSelf();
|
||||
}}
|
||||
/>
|
||||
<OrgPasswordModal visible={pwdModal} onClose={() => setPwdModal(false)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgPersonalSettings;
|
||||
@@ -0,0 +1,654 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Modal,
|
||||
Table,
|
||||
Tag,
|
||||
TextArea,
|
||||
Toast,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { Code2, FileCheck2, OctagonX, RotateCcw } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API, getUserIdFromLocalStorage } from '../../helpers';
|
||||
import { useIsMobile } from '../../hooks/common/useIsMobile';
|
||||
import { SkillEmptyGuide } from '../../components/skill';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuidePill,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import './org-skills.css';
|
||||
|
||||
const { Title, Text, Paragraph } = Typography;
|
||||
const blankSkill = {
|
||||
canonical_id: '',
|
||||
body: '# Method\n\nDescribe a safe, evidence-led method.',
|
||||
name_zh: '',
|
||||
name_en: '',
|
||||
description_zh: '',
|
||||
description_en: '',
|
||||
triggers_zh: '',
|
||||
triggers_en: '',
|
||||
scenarios_zh: '',
|
||||
scenarios_en: '',
|
||||
compact_constraint_zh: '',
|
||||
compact_constraint_en: '',
|
||||
default_output_language: 'auto',
|
||||
capabilities: 'prompt_only',
|
||||
tags: 'internal',
|
||||
change_statement: '',
|
||||
};
|
||||
const split = (value) =>
|
||||
String(value || '')
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const OrgPrivateSkills = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
const [items, setItems] = useState([]);
|
||||
// 首次加载完成前进度胶囊不渲染,避免对老用户闪现「0/4」。
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [editorVisible, setEditorVisible] = useState(false);
|
||||
const [editingSkill, setEditingSkill] = useState(null);
|
||||
const [form, setForm] = useState(blankSkill);
|
||||
const [evidenceVersion, setEvidenceVersion] = useState(null);
|
||||
const [historySkill, setHistorySkill] = useState(null);
|
||||
const [history, setHistory] = useState([]);
|
||||
const [evidence, setEvidence] = useState({
|
||||
model: '',
|
||||
input: '',
|
||||
});
|
||||
const load = useCallback(async () => {
|
||||
// finally 保证请求失败也置 loaded:拦截器已 toast,此处只需不让
|
||||
// 未捕获 reject 把 loaded 卡在 false。
|
||||
try {
|
||||
const response = await API.get('/api/org/skills/private', { headers });
|
||||
if (response.data?.success) setItems(response.data.data || []);
|
||||
} finally {
|
||||
setLoaded(true);
|
||||
}
|
||||
}, [headers]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const payload = () => ({
|
||||
...form,
|
||||
triggers_zh: split(form.triggers_zh),
|
||||
triggers_en: split(form.triggers_en),
|
||||
scenarios_zh: split(form.scenarios_zh),
|
||||
scenarios_en: split(form.scenarios_en),
|
||||
capabilities: split(form.capabilities),
|
||||
tags: split(form.tags),
|
||||
});
|
||||
// Backend business rejections arrive as HTTP 4xx (axios throws); read the
|
||||
// response body so the audited reason reaches the user instead of a generic
|
||||
// "Request failed with status code 409".
|
||||
const backendMessage = (error, fallback) =>
|
||||
error?.response?.data?.message || error?.message || fallback;
|
||||
const save = async () => {
|
||||
const endpoint = editingSkill
|
||||
? `/api/org/skills/private/${editingSkill.id}/versions`
|
||||
: '/api/org/skills/private';
|
||||
try {
|
||||
const response = await API.post(endpoint, payload(), {
|
||||
headers,
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('保存失败'));
|
||||
return;
|
||||
}
|
||||
setEditorVisible(false);
|
||||
setEditingSkill(null);
|
||||
setForm(blankSkill);
|
||||
await load();
|
||||
} catch (error) {
|
||||
Toast.error(backendMessage(error, t('保存失败')));
|
||||
}
|
||||
};
|
||||
const recordEvidence = async () => {
|
||||
if (!evidence.model.trim() || !evidence.input.trim()) {
|
||||
Toast.error(t('模型名称与测试输入不能为空'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await API.post(
|
||||
`/api/org/skills/private/versions/${evidenceVersion}/test`,
|
||||
{ model: evidence.model, input: evidence.input },
|
||||
{ headers, skipErrorHandler: true },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('模型实测失败'));
|
||||
return;
|
||||
}
|
||||
Toast.success(t('模型实测完成,证据已落库'));
|
||||
setEvidenceVersion(null);
|
||||
await load();
|
||||
} catch (error) {
|
||||
Toast.error(backendMessage(error, t('模型实测失败')));
|
||||
}
|
||||
};
|
||||
const action = async (endpoint, body = {}) => {
|
||||
try {
|
||||
const response = await API.post(endpoint, body, {
|
||||
headers,
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return;
|
||||
}
|
||||
Toast.success(t('操作完成'));
|
||||
await load();
|
||||
} catch (error) {
|
||||
Toast.error(backendMessage(error, t('操作失败')));
|
||||
}
|
||||
};
|
||||
const openHistory = async (skill) => {
|
||||
try {
|
||||
const response = await API.get(
|
||||
`/api/org/skills/private/${skill.id}/versions`,
|
||||
{ headers, skipErrorHandler: true },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('历史版本加载失败'));
|
||||
return;
|
||||
}
|
||||
setHistory(response.data.data || []);
|
||||
setHistorySkill(skill);
|
||||
} catch (error) {
|
||||
Toast.error(backendMessage(error, t('历史版本加载失败')));
|
||||
}
|
||||
};
|
||||
const askReason = (title, onOk) => {
|
||||
let reason = '';
|
||||
Modal.confirm({
|
||||
title,
|
||||
content: (
|
||||
<TextArea
|
||||
placeholder={t('请输入可审计原因')}
|
||||
onChange={(value) => {
|
||||
reason = value;
|
||||
}}
|
||||
/>
|
||||
),
|
||||
onOk: () => onOk(reason),
|
||||
});
|
||||
};
|
||||
const renderSkillActions = (row) => {
|
||||
const versionId = row.version?.id;
|
||||
const currentUserId = Number(getUserIdFromLocalStorage()) || 0;
|
||||
// Two-person review is enforced server side; mirror it here so buttons
|
||||
// that are guaranteed to be rejected are not clickable.
|
||||
const isAuthor =
|
||||
currentUserId > 0 && Number(row.version?.created_by) === currentUserId;
|
||||
const isReviewer =
|
||||
currentUserId > 0 && Number(row.review?.reviewer_id) === currentUserId;
|
||||
return (
|
||||
<div className='flex flex-wrap gap-2'>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={row.definition.emergency_stopped}
|
||||
onClick={() => {
|
||||
setEditingSkill(row.definition);
|
||||
setForm({
|
||||
...blankSkill,
|
||||
canonical_id: row.definition.canonical_id,
|
||||
});
|
||||
setEditorVisible(true);
|
||||
}}
|
||||
>
|
||||
{t('新版本')}
|
||||
</Button>
|
||||
<Button size='small' onClick={() => openHistory(row.definition)}>
|
||||
{t('历史版本')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={!versionId}
|
||||
onClick={() => {
|
||||
// Clear residue from a previous version's test before reopening.
|
||||
setEvidence({ model: '', input: '' });
|
||||
setEvidenceVersion(versionId);
|
||||
}}
|
||||
>
|
||||
{t('执行模型实测')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={!versionId || row.review?.status !== 'pending' || isAuthor}
|
||||
onClick={() =>
|
||||
action(`/api/org/skills/private/versions/${versionId}/review/start`)
|
||||
}
|
||||
>
|
||||
{isAuthor && row.review?.status === 'pending'
|
||||
? t('待他人审核')
|
||||
: t('领取审核')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
icon={<FileCheck2 size={14} />}
|
||||
disabled={
|
||||
!versionId || row.review?.status !== 'reviewing' || !isReviewer
|
||||
}
|
||||
onClick={() =>
|
||||
action(
|
||||
`/api/org/skills/private/versions/${versionId}/review/decision`,
|
||||
{ approved: true, conclusion: { decision: 'approved' } },
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('通过')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
type='danger'
|
||||
disabled={
|
||||
!versionId || row.review?.status !== 'reviewing' || !isReviewer
|
||||
}
|
||||
onClick={() =>
|
||||
action(
|
||||
`/api/org/skills/private/versions/${versionId}/review/decision`,
|
||||
{ approved: false, conclusion: { decision: 'rejected' } },
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('驳回')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={!versionId || row.review?.status !== 'approved'}
|
||||
onClick={() =>
|
||||
action(`/api/org/skills/private/versions/${versionId}/publish`)
|
||||
}
|
||||
>
|
||||
{t('发布')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
icon={<RotateCcw size={14} />}
|
||||
disabled={!versionId}
|
||||
onClick={() =>
|
||||
askReason(t('回滚到当前列表版本'), (reason) =>
|
||||
action(
|
||||
`/api/org/skills/private/${row.definition.id}/versions/${versionId}/rollback`,
|
||||
{ reason },
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('回滚')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
type='danger'
|
||||
icon={<OctagonX size={14} />}
|
||||
disabled={row.definition.emergency_stopped}
|
||||
onClick={() =>
|
||||
askReason(t('紧急停用 Skill'), (reason) =>
|
||||
action(
|
||||
`/api/org/skills/private/${row.definition.id}/emergency-stop`,
|
||||
{ reason },
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{t('紧急停用')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
const openCreateEditor = () => {
|
||||
setEditingSkill(null);
|
||||
setForm(blankSkill);
|
||||
setEditorVisible(true);
|
||||
};
|
||||
// 使用指引:自研 Skill 从创建到发布的门禁流程,完成态由列表真实数据驱动。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-private-skills',
|
||||
ready: loaded,
|
||||
title: t('企业自研 Skill · 使用指引'),
|
||||
intro: t('创建 → 模型实测 → 双人审核 → 发布,每一步都留审计'),
|
||||
steps: [
|
||||
{
|
||||
title: t('创建私有 Skill'),
|
||||
detail: t('撰写方法正文与中英文元数据'),
|
||||
done: items.length > 0,
|
||||
cta: t('去创建'),
|
||||
onAction: openCreateEditor,
|
||||
points: [
|
||||
t('Skill Markdown 正文就是方法内容,创建后版本不可变'),
|
||||
t('后续改动走「新版本」,历史版本全部保留可回滚'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('执行模型实测'),
|
||||
detail: t('用真实模型跑一遍正文,产生审核证据'),
|
||||
done: items.some((row) => row.runtime?.conclusion === 'pass'),
|
||||
points: [
|
||||
t('「执行模型实测」会实际调用所选模型执行该版本正文'),
|
||||
t('真实响应自动落库为审核证据;扫描列变绿色 pass 即通过'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('双人审核'),
|
||||
detail: t('作者不能审核自己的版本'),
|
||||
done: items.some((row) => row.review?.status === 'approved'),
|
||||
points: [
|
||||
t('作者视角按钮显示「待他人审核」;其他管理员「领取审核」'),
|
||||
t('领取后由审核人「通过」或「驳回」,结论进入审计'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('发布与治理'),
|
||||
detail: t('审核通过后发布;回滚与紧急停用随时可用'),
|
||||
// 后端 SkillState 发布态只有 'published'(model/skill_supply.go)。
|
||||
done: items.some((row) => row.definition.status === 'published'),
|
||||
points: [
|
||||
t('「发布」后技能按企业分发策略对成员生效,范围在「分发与锁定」配置'),
|
||||
t('「回滚」可退回任一审核通过的历史版本,「紧急停用」立即止血'),
|
||||
t('回滚与紧急停用都必须填写可审计原因'),
|
||||
],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('「领取审核」按钮点不了?'),
|
||||
a: t('你是该版本的作者,双人审核要求由其他管理员领取'),
|
||||
},
|
||||
{
|
||||
q: t('技能被紧急停用后能恢复吗?'),
|
||||
a: t('解除停用前无法创建新版本;恢复操作同样需要可审计原因'),
|
||||
},
|
||||
],
|
||||
});
|
||||
const closeGuide = guide.close;
|
||||
// 抽屉进度是组织私有的:切组织时关闭并复位 loaded,
|
||||
// 否则重取窗口内胶囊会按旧组织数据渲染完成态。
|
||||
useEffect(() => {
|
||||
setLoaded(false);
|
||||
closeGuide();
|
||||
}, [orgId, closeGuide]);
|
||||
return (
|
||||
<div className='org-skills-page'>
|
||||
<header className='org-skills-hero'>
|
||||
<div>
|
||||
<Title heading={3}>{t('企业自研 Skill')}</Title>
|
||||
<Text type='tertiary'>
|
||||
{t(
|
||||
'版本内容不可变;兼容扫描、双人审核、发布、回滚与紧急停用均保留审计。',
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
<div className='org-skills-hero-actions'>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
<Button icon={<Code2 size={16} />} onClick={openCreateEditor}>
|
||||
{t('创建私有 Skill')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
<PageGuidePill guide={guide} />
|
||||
<PageGuideDrawer guide={guide} />
|
||||
<OrgPanel>
|
||||
{items.length === 0 ? (
|
||||
<SkillEmptyGuide
|
||||
title={t('还没有自研 Skill')}
|
||||
description={t(
|
||||
'把企业沉淀的方法写成 Skill,经实测与双人审核后发布给成员使用。',
|
||||
)}
|
||||
actionLabel={t('创建私有 Skill')}
|
||||
onAction={openCreateEditor}
|
||||
/>
|
||||
) : isMobile ? (
|
||||
<div className='org-skill-mobile-list'>
|
||||
{items.map((row) => (
|
||||
<article key={row.definition.id}>
|
||||
<div>
|
||||
<strong>{row.definition.canonical_id}</strong>
|
||||
<Tag
|
||||
color={row.definition.emergency_stopped ? 'red' : 'blue'}
|
||||
>
|
||||
{row.definition.status}
|
||||
</Tag>
|
||||
</div>
|
||||
<span>
|
||||
{t('版本')}: {row.version?.version_no || '-'}
|
||||
</span>
|
||||
<span>
|
||||
{t('扫描')}: {row.runtime?.conclusion || '-'}
|
||||
</span>
|
||||
<span>
|
||||
{t('审核')}: {row.review?.status || '-'}
|
||||
</span>
|
||||
{renderSkillActions(row)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Table
|
||||
pagination={false}
|
||||
dataSource={items}
|
||||
rowKey={(row) => row.definition.id}
|
||||
columns={[
|
||||
{
|
||||
title: t('标识'),
|
||||
render: (_, row) => row.definition.canonical_id,
|
||||
},
|
||||
{
|
||||
title: t('版本'),
|
||||
render: (_, row) => row.version?.version_no || '-',
|
||||
},
|
||||
{
|
||||
title: t('扫描'),
|
||||
render: (_, row) => (
|
||||
<Tag
|
||||
color={
|
||||
row.runtime?.conclusion === 'pass' ? 'green' : 'orange'
|
||||
}
|
||||
>
|
||||
{row.runtime?.conclusion || '-'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('审核'),
|
||||
render: (_, row) => <Tag>{row.review?.status || '-'}</Tag>,
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
render: (_, row) => (
|
||||
<Tag
|
||||
color={row.definition.emergency_stopped ? 'red' : 'blue'}
|
||||
>
|
||||
{row.definition.status}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 430,
|
||||
render: (_, row) => renderSkillActions(row),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</OrgPanel>
|
||||
<Modal
|
||||
title={editingSkill ? t('创建不可变新版本') : t('创建企业私有 Skill')}
|
||||
visible={editorVisible}
|
||||
onCancel={() => setEditorVisible(false)}
|
||||
onOk={save}
|
||||
width={820}
|
||||
>
|
||||
<div className='org-private-skill-form'>
|
||||
<Input
|
||||
disabled={!!editingSkill}
|
||||
placeholder='canonical_id'
|
||||
value={form.canonical_id}
|
||||
onChange={(canonical_id) => setForm({ ...form, canonical_id })}
|
||||
/>
|
||||
{[
|
||||
'name_zh',
|
||||
'name_en',
|
||||
'description_zh',
|
||||
'description_en',
|
||||
'triggers_zh',
|
||||
'triggers_en',
|
||||
'scenarios_zh',
|
||||
'scenarios_en',
|
||||
'compact_constraint_zh',
|
||||
'compact_constraint_en',
|
||||
'tags',
|
||||
'change_statement',
|
||||
].map((key) => (
|
||||
<Input
|
||||
key={key}
|
||||
placeholder={key}
|
||||
value={form[key]}
|
||||
onChange={(value) => setForm({ ...form, [key]: value })}
|
||||
/>
|
||||
))}
|
||||
<TextArea
|
||||
rows={10}
|
||||
placeholder='Skill Markdown'
|
||||
value={form.body}
|
||||
onChange={(body) => setForm({ ...form, body })}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
<Modal
|
||||
title={t('执行真实模型测试')}
|
||||
visible={!!evidenceVersion}
|
||||
onCancel={() => setEvidenceVersion(null)}
|
||||
onOk={recordEvidence}
|
||||
>
|
||||
<div className='org-private-skill-form'>
|
||||
<Input
|
||||
placeholder={t('模型名称')}
|
||||
value={evidence.model}
|
||||
onChange={(model) => setEvidence({ ...evidence, model })}
|
||||
/>
|
||||
<TextArea
|
||||
placeholder={t('测试输入')}
|
||||
value={evidence.input}
|
||||
onChange={(input) => setEvidence({ ...evidence, input })}
|
||||
/>
|
||||
<Paragraph type='tertiary'>
|
||||
{t(
|
||||
'提交后将实际调用所选模型执行该版本正文,真实响应自动落库为审核证据。',
|
||||
)}
|
||||
</Paragraph>
|
||||
</div>
|
||||
</Modal>
|
||||
<Modal
|
||||
title={t('不可变历史版本')}
|
||||
visible={!!historySkill}
|
||||
onCancel={() => setHistorySkill(null)}
|
||||
footer={null}
|
||||
width={760}
|
||||
>
|
||||
{isMobile ? (
|
||||
<div className='org-skill-mobile-list'>
|
||||
{history.map((row) => (
|
||||
<article key={row.version.id}>
|
||||
<strong>
|
||||
v{row.version.version_no} / #{row.version.id}
|
||||
</strong>
|
||||
<span>
|
||||
{t('扫描')}: {row.runtime?.conclusion || '-'}
|
||||
</span>
|
||||
<span>
|
||||
{t('审核')}: {row.review?.status || '-'}
|
||||
</span>
|
||||
<Button
|
||||
size='small'
|
||||
icon={<RotateCcw size={14} />}
|
||||
disabled={row.review?.status !== 'approved'}
|
||||
onClick={() =>
|
||||
askReason(t('回滚到该历史版本'), async (reason) => {
|
||||
await action(
|
||||
`/api/org/skills/private/${historySkill.id}/versions/${row.version.id}/rollback`,
|
||||
{ reason },
|
||||
);
|
||||
setHistorySkill(null);
|
||||
})
|
||||
}
|
||||
>
|
||||
{t('回滚')}
|
||||
</Button>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Table
|
||||
pagination={false}
|
||||
dataSource={history}
|
||||
rowKey={(row) => row.version.id}
|
||||
columns={[
|
||||
{
|
||||
title: t('版本'),
|
||||
render: (_, row) => `v${row.version.version_no}`,
|
||||
},
|
||||
{ title: t('版本 ID'), render: (_, row) => row.version.id },
|
||||
{
|
||||
title: t('扫描'),
|
||||
render: (_, row) => row.runtime?.conclusion || '-',
|
||||
},
|
||||
{
|
||||
title: t('审核'),
|
||||
render: (_, row) => row.review?.status || '-',
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
render: (_, row) => (
|
||||
<Button
|
||||
size='small'
|
||||
icon={<RotateCcw size={14} />}
|
||||
disabled={row.review?.status !== 'approved'}
|
||||
onClick={() =>
|
||||
askReason(t('回滚到该历史版本'), async (reason) => {
|
||||
await action(
|
||||
`/api/org/skills/private/${historySkill.id}/versions/${row.version.id}/rollback`,
|
||||
{ reason },
|
||||
);
|
||||
setHistorySkill(null);
|
||||
})
|
||||
}
|
||||
>
|
||||
{t('回滚')}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export default OrgPrivateSkills;
|
||||
@@ -0,0 +1,346 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Select,
|
||||
Input,
|
||||
Tag,
|
||||
Toast,
|
||||
Popconfirm,
|
||||
Empty,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { RefreshCw, Plus, Pencil } from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgModal from './components/OrgModal';
|
||||
|
||||
const { Text } = Typography;
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
const memberName = (m) =>
|
||||
m.remark || m.display_name || m.username || `#${m.org_member_id}`;
|
||||
|
||||
// 我的项目(阶段一):项目经理(项目负责人/项目管理员)自助管理项目成员与项目名。
|
||||
const OrgProjectManage = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [memberOptions, setMemberOptions] = useState([]);
|
||||
const [projectId, setProjectId] = useState(null);
|
||||
const [members, setMembers] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const [addModal, setAddModal] = useState(false);
|
||||
const [addMemberId, setAddMemberId] = useState(null);
|
||||
const [addRole, setAddRole] = useState('project_member');
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
const [renameModal, setRenameModal] = useState(false);
|
||||
const [renameValue, setRenameValue] = useState('');
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
|
||||
const headers = useMemo(() => getOrgHeaders(orgId), [orgId]);
|
||||
const currentProject = useMemo(
|
||||
() => projects.find((p) => p.id === projectId) || null,
|
||||
[projects, projectId],
|
||||
);
|
||||
|
||||
const fetchScope = useCallback(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/org/me/project-scope', { headers });
|
||||
if (res.data.success) {
|
||||
const list = res.data.data?.projects || [];
|
||||
setProjects(list);
|
||||
setMemberOptions(res.data.data?.member_options || []);
|
||||
setProjectId((prev) => prev || (list[0] ? list[0].id : null));
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
}, [headers]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchScope();
|
||||
}, [fetchScope]);
|
||||
|
||||
const fetchMembers = useCallback(async () => {
|
||||
if (!projectId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.get(`/api/org/project/${projectId}/members`, {
|
||||
headers,
|
||||
});
|
||||
if (res.data.success) setMembers(res.data.data || []);
|
||||
else showError(res.data.message);
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [projectId, headers]);
|
||||
|
||||
useEffect(() => {
|
||||
if (projectId) fetchMembers();
|
||||
}, [projectId, fetchMembers]);
|
||||
|
||||
// 可添加成员:排除已在项目中的
|
||||
const addableOptions = useMemo(() => {
|
||||
const inProject = new Set(members.map((m) => m.org_member_id));
|
||||
return memberOptions
|
||||
.filter((o) => !inProject.has(o.member_id))
|
||||
.map((o) => ({ label: o.name, value: o.member_id }));
|
||||
}, [memberOptions, members]);
|
||||
|
||||
const submitAdd = async () => {
|
||||
if (!addMemberId) {
|
||||
Toast.warning(t('请选择成员'));
|
||||
return;
|
||||
}
|
||||
setAdding(true);
|
||||
try {
|
||||
const res = await API.post(
|
||||
`/api/org/project/${projectId}/members`,
|
||||
{ org_member_id: addMemberId, role: addRole },
|
||||
{ headers },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('成员已添加'));
|
||||
setAddModal(false);
|
||||
setAddMemberId(null);
|
||||
setAddRole('project_member');
|
||||
fetchMembers();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setAdding(false);
|
||||
}
|
||||
};
|
||||
|
||||
const removeMember = async (orgMemberId) => {
|
||||
try {
|
||||
const res = await API.delete(
|
||||
`/api/org/project/${projectId}/members/${orgMemberId}`,
|
||||
{ headers },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('成员已移除'));
|
||||
fetchMembers();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const submitRename = async () => {
|
||||
const name = renameValue.trim();
|
||||
if (!name) {
|
||||
showError(t('项目名称不能为空'));
|
||||
return;
|
||||
}
|
||||
setRenaming(true);
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/project/${projectId}`,
|
||||
{ name },
|
||||
{ headers },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('项目已更新'));
|
||||
setRenameModal(false);
|
||||
fetchScope();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setRenaming(false);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: t('成员'), render: (_, r) => memberName(r) },
|
||||
{
|
||||
title: t('项目角色'),
|
||||
dataIndex: 'role',
|
||||
render: (v) => (
|
||||
<Tag color={v === 'project_admin' ? 'blue' : 'grey'}>
|
||||
{v === 'project_admin' ? t('项目管理员') : t('项目成员')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
render: (_, r) => (
|
||||
<Popconfirm
|
||||
title={t('确认移除该成员?')}
|
||||
content={t('移除后该成员将失去对本项目的访问权限。')}
|
||||
onConfirm={() => removeMember(r.org_member_id)}
|
||||
>
|
||||
<Button size='small' type='danger' theme='light'>
|
||||
{t('移除')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
title={t('我的项目')}
|
||||
subtitle={t('管理您负责的项目成员')}
|
||||
actions={
|
||||
<>
|
||||
<Select
|
||||
value={projectId}
|
||||
onChange={setProjectId}
|
||||
placeholder={t('选择项目')}
|
||||
style={{ width: 200 }}
|
||||
optionList={projects.map((p) => ({
|
||||
label: p.code ? `${p.name}(${p.code})` : p.name,
|
||||
value: p.id,
|
||||
}))}
|
||||
/>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={() => {
|
||||
fetchScope();
|
||||
fetchMembers();
|
||||
}}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{projects.length === 0 ? (
|
||||
<Empty
|
||||
description={t('您当前没有负责的项目')}
|
||||
style={{ padding: 60 }}
|
||||
/>
|
||||
) : (
|
||||
<OrgPanel>
|
||||
<div className='flex items-center justify-between mb-3 flex-wrap gap-2'>
|
||||
<div>
|
||||
<Text strong>{currentProject?.name || ''}</Text>
|
||||
{currentProject?.code && (
|
||||
<Text type='tertiary' size='small' className='ml-2'>
|
||||
{currentProject.code}
|
||||
</Text>
|
||||
)}
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
icon={<Pencil size={14} />}
|
||||
onClick={() => {
|
||||
setRenameValue(currentProject?.name || '');
|
||||
setRenameModal(true);
|
||||
}}
|
||||
>
|
||||
{t('重命名')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
theme='solid'
|
||||
icon={<Plus size={14} />}
|
||||
onClick={() => setAddModal(true)}
|
||||
>
|
||||
{t('添加成员')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={members}
|
||||
loading={loading}
|
||||
rowKey='org_member_id'
|
||||
pagination={false}
|
||||
empty={<Empty description={t('暂无项目成员')} />}
|
||||
/>
|
||||
</OrgPanel>
|
||||
)}
|
||||
|
||||
{/* 添加成员 */}
|
||||
<OrgModal
|
||||
title={t('添加项目成员')}
|
||||
visible={addModal}
|
||||
onOk={submitAdd}
|
||||
onCancel={() => setAddModal(false)}
|
||||
okText={t('添加')}
|
||||
cancelText={t('取消')}
|
||||
confirmLoading={adding}
|
||||
>
|
||||
<div className='space-y-3'>
|
||||
<Select
|
||||
placeholder={t('选择成员')}
|
||||
style={{ width: '100%' }}
|
||||
value={addMemberId}
|
||||
onChange={setAddMemberId}
|
||||
filter
|
||||
optionList={addableOptions}
|
||||
/>
|
||||
<Select
|
||||
style={{ width: '100%' }}
|
||||
value={addRole}
|
||||
onChange={setAddRole}
|
||||
optionList={[
|
||||
{ label: t('项目成员'), value: 'project_member' },
|
||||
{ label: t('项目管理员'), value: 'project_admin' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</OrgModal>
|
||||
|
||||
{/* 重命名项目 */}
|
||||
<OrgModal
|
||||
title={t('重命名项目')}
|
||||
visible={renameModal}
|
||||
onOk={submitRename}
|
||||
onCancel={() => setRenameModal(false)}
|
||||
okText={t('保存')}
|
||||
cancelText={t('取消')}
|
||||
confirmLoading={renaming}
|
||||
>
|
||||
<Input
|
||||
value={renameValue}
|
||||
onChange={setRenameValue}
|
||||
placeholder={t('请输入项目名称')}
|
||||
onEnterPress={submitRename}
|
||||
/>
|
||||
</OrgModal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgProjectManage;
|
||||
@@ -0,0 +1,554 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Form,
|
||||
Toast,
|
||||
Popconfirm,
|
||||
Tag,
|
||||
Select,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { RefreshCw, Plus, Users } from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError, collectPagedItems } from '../../helpers';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgModal from './components/OrgModal';
|
||||
import OrgScopedLimitButtons from './components/OrgScopedLimitButtons';
|
||||
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
// 项目管理:项目增删改 + 项目成员管理(成本归属/项目预算 cap 的载体)
|
||||
const OrgProjects = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const [list, setList] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [members, setMembers] = useState([]); // 企业全部成员(用于成员选择)
|
||||
|
||||
const [modalVisible, setModalVisible] = useState(false);
|
||||
const [editing, setEditing] = useState(null);
|
||||
const [formApi, setFormApi] = useState(null);
|
||||
|
||||
const [memberModal, setMemberModal] = useState(null); // 当前管理成员的项目
|
||||
const [projectMembers, setProjectMembers] = useState([]);
|
||||
const [addMemberIds, setAddMemberIds] = useState([]); // 支持一次添加多个成员
|
||||
const [addMemberRole, setAddMemberRole] = useState('project_member');
|
||||
|
||||
const [tokenModal, setTokenModal] = useState(null); // 当前管理令牌的项目
|
||||
const [orgTokens, setOrgTokens] = useState([]);
|
||||
|
||||
const fetchList = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.get('/api/org/project', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
setList(res.data.data || []);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
const fetchMembers = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
try {
|
||||
// 逐页取全:后端把 page_size 静默钳到 100,成员超过 100 人时
|
||||
// 原先的单次请求会让第 101 位之后的人无法被选进项目。
|
||||
const { items } = await collectPagedItems((page, size) =>
|
||||
API.get(`/api/org/members?p=${page}&page_size=${size}`, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
}),
|
||||
);
|
||||
setMembers(items);
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchList();
|
||||
fetchMembers();
|
||||
}, [fetchList, fetchMembers]);
|
||||
|
||||
const memberNameMap = useMemo(() => {
|
||||
const m = {};
|
||||
members.forEach((mem) => {
|
||||
m[mem.id] = mem.display_name || mem.username || `#${mem.id}`;
|
||||
});
|
||||
return m;
|
||||
}, [members]);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditing(null);
|
||||
setModalVisible(true);
|
||||
};
|
||||
const openEdit = (record) => {
|
||||
setEditing(record);
|
||||
setModalVisible(true);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (modalVisible && formApi) {
|
||||
if (editing) {
|
||||
formApi.setValues({
|
||||
code: editing.code,
|
||||
name: editing.name,
|
||||
status: editing.status || 1,
|
||||
});
|
||||
} else {
|
||||
formApi.setValues({ code: '', name: '', status: 1 });
|
||||
}
|
||||
}
|
||||
}, [modalVisible, editing, formApi]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!formApi) return;
|
||||
let values;
|
||||
try {
|
||||
values = await formApi.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
let res;
|
||||
if (editing) {
|
||||
res = await API.put(`/api/org/project/${editing.id}`, values, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
} else {
|
||||
res = await API.post('/api/org/project', values, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
}
|
||||
if (res.data.success) {
|
||||
Toast.success(editing ? t('项目已更新') : t('项目已创建'));
|
||||
setModalVisible(false);
|
||||
fetchList();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDisable = async (record) => {
|
||||
try {
|
||||
const res = await API.delete(`/api/org/project/${record.id}`, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
Toast.success(t('项目已停用'));
|
||||
fetchList();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const openMembers = async (record) => {
|
||||
setMemberModal(record);
|
||||
setAddMemberIds([]);
|
||||
setAddMemberRole('project_member');
|
||||
try {
|
||||
const res = await API.get(`/api/org/project/${record.id}/members`, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
setProjectMembers(res.data.data || []);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddMember = async () => {
|
||||
if (!addMemberIds.length) {
|
||||
Toast.warning(t('请选择成员'));
|
||||
return;
|
||||
}
|
||||
// 逐个添加(后端为单成员接口)。用 allSettled 保证个别网络失败不会中断
|
||||
// 其余请求,且无论结果如何都刷新一次,让表格反映后端真实状态。
|
||||
const results = await Promise.allSettled(
|
||||
addMemberIds.map((id) =>
|
||||
API.post(
|
||||
`/api/org/project/${memberModal.id}/members`,
|
||||
{ org_member_id: id, role: addMemberRole },
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
),
|
||||
),
|
||||
);
|
||||
const firstError = results.find(
|
||||
(r) => r.status === 'rejected' || !r.value?.data?.success,
|
||||
);
|
||||
if (!firstError) {
|
||||
Toast.success(t('成员已添加'));
|
||||
} else {
|
||||
const msg =
|
||||
firstError.status === 'rejected'
|
||||
? firstError.reason?.message || t('网络错误')
|
||||
: firstError.value.data.message;
|
||||
showError(t('部分成员添加失败:{{msg}}', { msg }));
|
||||
}
|
||||
openMembers(memberModal);
|
||||
};
|
||||
|
||||
const handleRemoveMember = async (orgMemberId) => {
|
||||
try {
|
||||
const res = await API.delete(
|
||||
`/api/org/project/${memberModal.id}/members/${orgMemberId}`,
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('成员已移除'));
|
||||
openMembers(memberModal);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const projectNameMap = useMemo(() => {
|
||||
const m = {};
|
||||
list.forEach((p) => (m[p.id] = p.name));
|
||||
return m;
|
||||
}, [list]);
|
||||
|
||||
const openTokens = async (project) => {
|
||||
setTokenModal(project);
|
||||
try {
|
||||
const { items } = await collectPagedItems((page, size) =>
|
||||
API.get(`/api/org/tokens?p=${page}&page_size=${size}`, {
|
||||
headers: getOrgHeaders(orgId),
|
||||
}),
|
||||
);
|
||||
setOrgTokens(items);
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const bindToken = async (tokenId, projectId) => {
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/tokens/${tokenId}/project`,
|
||||
{ project_id: projectId },
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(projectId ? t('已绑定到本项目') : t('已解绑'));
|
||||
openTokens(tokenModal);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
// 可添加的成员(排除已在项目中的)
|
||||
const addableMembers = useMemo(() => {
|
||||
const inProject = new Set(projectMembers.map((pm) => pm.org_member_id));
|
||||
return members
|
||||
.filter((mem) => !inProject.has(mem.id))
|
||||
.map((mem) => ({
|
||||
label: mem.display_name || mem.username || `#${mem.id}`,
|
||||
value: mem.id,
|
||||
}));
|
||||
}, [members, projectMembers]);
|
||||
|
||||
const columns = [
|
||||
{ title: t('项目编码'), dataIndex: 'code' },
|
||||
{ title: t('项目名称'), dataIndex: 'name' },
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (v) => (
|
||||
<Tag color={v === 1 ? 'green' : 'grey'}>
|
||||
{v === 1 ? t('启用') : t('停用')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('到期时间'),
|
||||
dataIndex: 'expired_at',
|
||||
width: 120,
|
||||
render: (v) => (v ? new Date(v * 1000).toLocaleDateString() : '-'),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 420,
|
||||
render: (_, record) => (
|
||||
<div className='flex items-center gap-2 flex-wrap'>
|
||||
<OrgScopedLimitButtons
|
||||
orgId={orgId}
|
||||
record={record}
|
||||
apiBase='/api/org/project'
|
||||
scopeLabel='项目'
|
||||
onSaved={fetchList}
|
||||
/>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
icon={<Users size={14} />}
|
||||
onClick={() => openMembers(record)}
|
||||
>
|
||||
{t('成员')}
|
||||
</Button>
|
||||
<Button size='small' theme='light' onClick={() => openTokens(record)}>
|
||||
{t('令牌')}
|
||||
</Button>
|
||||
<Button size='small' theme='light' onClick={() => openEdit(record)}>
|
||||
{t('编辑')}
|
||||
</Button>
|
||||
{record.status === 1 && (
|
||||
<Popconfirm
|
||||
title={t('确认停用该项目?')}
|
||||
content={t('停用后保留历史,不再接受新调用绑定')}
|
||||
onConfirm={() => handleDisable(record)}
|
||||
>
|
||||
<Button size='small' theme='light' type='danger'>
|
||||
{t('停用')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
title={t('项目管理')}
|
||||
subtitle={t('项目成员与项目预算')}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={fetchList}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='solid'
|
||||
icon={<Plus size={14} />}
|
||||
onClick={openCreate}
|
||||
>
|
||||
{t('新建项目')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<OrgPanel padding='p-2'>
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={list}
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showSizeChanger: false }}
|
||||
rowKey='id'
|
||||
/>
|
||||
</OrgPanel>
|
||||
|
||||
{/* 项目创建/编辑 */}
|
||||
<OrgModal
|
||||
title={editing ? t('编辑项目') : t('新建项目')}
|
||||
visible={modalVisible}
|
||||
onOk={handleSubmit}
|
||||
onCancel={() => setModalVisible(false)}
|
||||
okText={t('保存')}
|
||||
cancelText={t('取消')}
|
||||
>
|
||||
<Form getFormApi={setFormApi}>
|
||||
<Form.Input
|
||||
field='code'
|
||||
label={t('项目编码')}
|
||||
disabled={!!editing}
|
||||
rules={[{ required: true, message: t('请输入项目编码') }]}
|
||||
/>
|
||||
<Form.Input
|
||||
field='name'
|
||||
label={t('项目名称')}
|
||||
rules={[{ required: true, message: t('请输入项目名称') }]}
|
||||
/>
|
||||
{editing && (
|
||||
<Form.Select
|
||||
field='status'
|
||||
label={t('状态')}
|
||||
optionList={[
|
||||
{ label: t('启用'), value: 1 },
|
||||
{ label: t('停用'), value: 2 },
|
||||
]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
)}
|
||||
</Form>
|
||||
</OrgModal>
|
||||
|
||||
{/* 项目成员管理 */}
|
||||
<OrgModal
|
||||
title={`${t('项目成员')} - ${memberModal?.name || ''}`}
|
||||
visible={!!memberModal}
|
||||
onCancel={() => setMemberModal(null)}
|
||||
footer={null}
|
||||
>
|
||||
<div className='flex items-center gap-2 mb-4'>
|
||||
<Select
|
||||
placeholder={t('选择成员')}
|
||||
optionList={addableMembers}
|
||||
value={addMemberIds}
|
||||
onChange={setAddMemberIds}
|
||||
filter
|
||||
multiple
|
||||
maxTagCount={2}
|
||||
showClear
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
<Select
|
||||
value={addMemberRole}
|
||||
onChange={setAddMemberRole}
|
||||
optionList={[
|
||||
{ label: t('项目成员'), value: 'project_member' },
|
||||
{ label: t('项目管理员'), value: 'project_admin' },
|
||||
]}
|
||||
style={{ width: 130 }}
|
||||
/>
|
||||
<Button theme='solid' onClick={handleAddMember}>
|
||||
{t('添加')}
|
||||
</Button>
|
||||
</div>
|
||||
<Table
|
||||
columns={[
|
||||
{
|
||||
title: t('成员'),
|
||||
dataIndex: 'org_member_id',
|
||||
render: (v) => memberNameMap[v] || `#${v}`,
|
||||
},
|
||||
{
|
||||
title: t('角色'),
|
||||
dataIndex: 'role',
|
||||
width: 110,
|
||||
render: (v) =>
|
||||
v === 'project_admin' ? t('项目管理员') : t('项目成员'),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 90,
|
||||
render: (_, record) => (
|
||||
<Popconfirm
|
||||
title={t('确认移除该成员?')}
|
||||
content={t('移除后该成员将失去对本项目的访问权限。')}
|
||||
okType='danger'
|
||||
position='left'
|
||||
onConfirm={() => handleRemoveMember(record.org_member_id)}
|
||||
>
|
||||
<Button size='small' theme='light' type='danger'>
|
||||
{t('移除')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
),
|
||||
},
|
||||
]}
|
||||
dataSource={projectMembers}
|
||||
pagination={false}
|
||||
rowKey='org_member_id'
|
||||
size='small'
|
||||
/>
|
||||
</OrgModal>
|
||||
|
||||
{/* 项目令牌绑定 */}
|
||||
<OrgModal
|
||||
title={`${t('项目令牌')} - ${tokenModal?.name || ''}`}
|
||||
visible={!!tokenModal}
|
||||
onCancel={() => setTokenModal(null)}
|
||||
footer={null}
|
||||
width={560}
|
||||
>
|
||||
<Table
|
||||
columns={[
|
||||
{ title: t('令牌'), dataIndex: 'name' },
|
||||
{
|
||||
title: t('当前归属'),
|
||||
dataIndex: 'project_id',
|
||||
width: 130,
|
||||
render: (v) =>
|
||||
!v ? (
|
||||
<Tag size='small'>{t('未绑定')}</Tag>
|
||||
) : v === tokenModal?.id ? (
|
||||
<Tag color='green' size='small'>
|
||||
{t('本项目')}
|
||||
</Tag>
|
||||
) : (
|
||||
<Tag color='blue' size='small'>
|
||||
{projectNameMap[v] || `#${v}`}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 130,
|
||||
render: (_, tk) =>
|
||||
tk.project_id === tokenModal?.id ? (
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
type='danger'
|
||||
onClick={() => bindToken(tk.id, 0)}
|
||||
>
|
||||
{t('解绑')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
onClick={() => bindToken(tk.id, tokenModal.id)}
|
||||
>
|
||||
{t('绑定到本项目')}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]}
|
||||
dataSource={orgTokens}
|
||||
pagination={false}
|
||||
rowKey='id'
|
||||
size='small'
|
||||
/>
|
||||
</OrgModal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgProjects;
|
||||
@@ -0,0 +1,650 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Copy,
|
||||
Database,
|
||||
MessageSquareText,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
Search,
|
||||
SlidersHorizontal,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Input,
|
||||
Select,
|
||||
Tag,
|
||||
Tooltip,
|
||||
DatePicker,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { copy, getQuotaPerUnit, showError, showSuccess } from '../../helpers';
|
||||
import { API } from '../../helpers/api';
|
||||
import { useOrgPromptRecords } from '../../hooks/org/useOrgData';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgStateBlock from './components/OrgStateBlock';
|
||||
import { formatQuotaAsCNY } from './orgAuditFormat';
|
||||
|
||||
const emptyFilters = {
|
||||
memberId: '',
|
||||
modelName: '',
|
||||
keyword: '',
|
||||
startTimestamp: 0,
|
||||
endTimestamp: 0,
|
||||
};
|
||||
|
||||
const tokenNumberFormatter = new Intl.NumberFormat('zh-CN');
|
||||
const formatTokenCount = (value) =>
|
||||
tokenNumberFormatter.format(Number(value) || 0);
|
||||
|
||||
// 下钻明细:一条提示词记录 → 该次用户输入的全部接口调用行(首调 + agent 中间调用)。
|
||||
// 数据来自平台消费日志(logs.prompt_group_key 索引等值查询),展开行时按需拉取。
|
||||
const PromptCallDetails = ({ orgId, groupKey }) => {
|
||||
const { t } = useTranslation();
|
||||
const quotaPerUnit = getQuotaPerUnit();
|
||||
const [calls, setCalls] = useState(null); // null = 加载中
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/org/prompt-archive/records/calls', {
|
||||
headers: { 'X-Org-Id': String(orgId) },
|
||||
params: { group_key: groupKey },
|
||||
});
|
||||
if (cancelled) return;
|
||||
if (res.data.success) {
|
||||
setCalls(res.data.data?.items || []);
|
||||
} else {
|
||||
setError(res.data.message || t('查询失败'));
|
||||
setCalls([]);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!cancelled) {
|
||||
setError(e.message);
|
||||
setCalls([]);
|
||||
}
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [orgId, groupKey, t]);
|
||||
|
||||
if (calls === null) {
|
||||
return (
|
||||
<div className='text-xs text-gray-400 dark:text-gray-500 mt-2'>
|
||||
{t('调用明细加载中…')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (error) {
|
||||
return (
|
||||
<div className='text-xs text-red-500 mt-2'>
|
||||
{t('调用明细加载失败')}:{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (calls.length === 0) {
|
||||
return (
|
||||
<div className='text-xs text-gray-400 dark:text-gray-500 mt-2'>
|
||||
{t('无关联调用明细(该记录产生于下钻功能上线之前,或消费日志已清理)')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className='mt-3'>
|
||||
<div className='text-xs font-medium text-gray-500 dark:text-gray-400 mb-1'>
|
||||
{t('调用明细')}({calls.length}
|
||||
{calls.length >= 200 ? '+' : ''})
|
||||
<span className='ml-2 font-normal text-gray-400 dark:text-gray-500'>
|
||||
{t(
|
||||
'明细为该提示词的全部调用;跨 30 分钟统计桶或多令牌时,条数可能多于本行调用次数',
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className='overflow-x-auto'>
|
||||
<table className='w-full text-xs text-gray-600 dark:text-gray-400'>
|
||||
<thead>
|
||||
<tr className='text-left text-gray-400 dark:text-gray-500'>
|
||||
<th className='py-1 pr-3 font-normal'>{t('时间')}</th>
|
||||
<th className='py-1 pr-3 font-normal'>{t('模型')}</th>
|
||||
<th className='py-1 pr-3 font-normal'>{t('输入/输出 tokens')}</th>
|
||||
<th className='py-1 pr-3 font-normal'>{t('花费')}</th>
|
||||
<th className='py-1 pr-3 font-normal'>{t('耗时')}</th>
|
||||
<th className='py-1 pr-3 font-normal'>{t('流式')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{calls.map((log) => (
|
||||
<tr
|
||||
key={log.id}
|
||||
className='border-t border-gray-100 dark:border-white/[0.06]'
|
||||
>
|
||||
<td className='py-1 pr-3'>
|
||||
{new Date(log.created_at * 1000).toLocaleString('zh-CN')}
|
||||
</td>
|
||||
<td className='py-1 pr-3'>{log.model_name}</td>
|
||||
<td className='py-1 pr-3'>
|
||||
{log.prompt_tokens} / {log.completion_tokens}
|
||||
</td>
|
||||
<td className='py-1 pr-3'>
|
||||
{formatQuotaAsCNY(log.quota, quotaPerUnit)}
|
||||
</td>
|
||||
<td className='py-1 pr-3'>{log.use_time}s</td>
|
||||
<td className='py-1 pr-3'>
|
||||
{log.is_stream ? t('是') : t('否')}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 提示词记录审计表(方案 §35 一期):数据来自企业自行配置的数据库,
|
||||
// 一行 = 一次「用户输入 → 最终 AI 返回」,agent 中间过程调用只累计次数与花费。
|
||||
const OrgPromptRecords = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
const quotaPerUnit = getQuotaPerUnit();
|
||||
const { records, total, loading, error, fetch } = useOrgPromptRecords(orgId);
|
||||
const [page, setPage] = useState(1);
|
||||
const [members, setMembers] = useState([]);
|
||||
const [membersLoading, setMembersLoading] = useState(true);
|
||||
const [selectedMemberId, setSelectedMemberId] = useState('');
|
||||
const [modelName, setModelName] = useState('');
|
||||
const [keyword, setKeyword] = useState('');
|
||||
const [timeRange, setTimeRange] = useState(null);
|
||||
const [appliedFilters, setAppliedFilters] = useState(emptyFilters);
|
||||
|
||||
const buildFilters = () => {
|
||||
const [start, end] = Array.isArray(timeRange) ? timeRange : [null, null];
|
||||
return {
|
||||
memberId: selectedMemberId,
|
||||
modelName: modelName.trim(),
|
||||
keyword: keyword.trim(),
|
||||
startTimestamp: start ? Math.floor(start.getTime() / 1000) : 0,
|
||||
endTimestamp: end ? Math.floor(end.getTime() / 1000) : 0,
|
||||
};
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedMemberId('');
|
||||
setModelName('');
|
||||
setKeyword('');
|
||||
setTimeRange(null);
|
||||
setAppliedFilters(emptyFilters);
|
||||
setPage(1);
|
||||
}, [orgId]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setMembers([]);
|
||||
setMembersLoading(true);
|
||||
(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/org/prompt-archive/members', {
|
||||
headers: { 'X-Org-Id': String(orgId) },
|
||||
});
|
||||
if (!cancelled && res.data.success) {
|
||||
setMembers(res.data.data?.items || []);
|
||||
} else if (!cancelled) {
|
||||
showError(res.data.message || t('加载历史成员失败'));
|
||||
}
|
||||
} catch (err) {
|
||||
if (!cancelled) {
|
||||
setMembers([]);
|
||||
showError(err.message);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setMembersLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [orgId, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (membersLoading) return;
|
||||
fetch(page, 20, appliedFilters);
|
||||
}, [appliedFilters, fetch, membersLoading, page]);
|
||||
|
||||
const applyFilter = () => {
|
||||
setAppliedFilters(buildFilters());
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const resetFilters = () => {
|
||||
setSelectedMemberId('');
|
||||
setModelName('');
|
||||
setKeyword('');
|
||||
setTimeRange(null);
|
||||
setAppliedFilters(emptyFilters);
|
||||
setPage(1);
|
||||
};
|
||||
|
||||
const memberOptions = useMemo(
|
||||
() => [
|
||||
{ value: '', label: t('全部成员') },
|
||||
...members.map((member) => {
|
||||
const name = member.name || member.username || `User#${member.user_id}`;
|
||||
return {
|
||||
value: member.member_id,
|
||||
label:
|
||||
member.status === 1 ? name : t('{{name}}(历史成员)', { name }),
|
||||
};
|
||||
}),
|
||||
],
|
||||
[members, t],
|
||||
);
|
||||
|
||||
const getMemberName = (record) => {
|
||||
const member = members.find(
|
||||
(item) => String(item.member_id) === String(record.org_member_id),
|
||||
);
|
||||
return (
|
||||
record.member_name ||
|
||||
member?.name ||
|
||||
member?.remark ||
|
||||
member?.display_name ||
|
||||
record.username ||
|
||||
`User#${record.user_id}`
|
||||
);
|
||||
};
|
||||
|
||||
const handleCopyPrompt = async (event, prompt) => {
|
||||
event?.stopPropagation();
|
||||
const text = prompt || '';
|
||||
if (!text) return;
|
||||
if (await copy(text)) {
|
||||
showSuccess(t('已复制提示词'));
|
||||
} else {
|
||||
showError(t('复制失败,请手动复制'));
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{
|
||||
title: t('成员'),
|
||||
dataIndex: 'member_name',
|
||||
width: 180,
|
||||
render: (_, record) => {
|
||||
const name = getMemberName(record);
|
||||
return (
|
||||
<Tooltip content={name} position='topLeft'>
|
||||
<div className='flex min-w-0 max-w-[164px] items-center gap-2.5 whitespace-nowrap'>
|
||||
<span className='inline-flex h-7 w-7 flex-none items-center justify-center rounded-full bg-brand/10 text-xs font-semibold text-brand'>
|
||||
{name.trim().slice(0, 1).toUpperCase() || '#'}
|
||||
</span>
|
||||
<span className='min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium text-[var(--text-primary)]'>
|
||||
{name}
|
||||
</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('模型'),
|
||||
dataIndex: 'model_name',
|
||||
width: 170,
|
||||
render: (v) => (
|
||||
<Tooltip content={v || '-'} position='top'>
|
||||
<Tag
|
||||
size='small'
|
||||
color='violet'
|
||||
type='light'
|
||||
style={{ maxWidth: 154 }}
|
||||
>
|
||||
<span className='block overflow-hidden text-ellipsis whitespace-nowrap'>
|
||||
{v || '-'}
|
||||
</span>
|
||||
</Tag>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('提示词'),
|
||||
dataIndex: 'prompt',
|
||||
render: (prompt) => {
|
||||
const text = prompt || '';
|
||||
const brief = text.length > 80 ? text.slice(0, 80) + '…' : text;
|
||||
const preview = text.length > 240 ? text.slice(0, 240) + '…' : text;
|
||||
return (
|
||||
<div className='flex w-full min-w-0 items-center gap-1.5'>
|
||||
<Tooltip
|
||||
content={preview}
|
||||
position='topLeft'
|
||||
style={{ maxWidth: 480 }}
|
||||
>
|
||||
<span className='min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap text-[13px] leading-5 text-gray-600 dark:text-gray-300'>
|
||||
{brief || '-'}
|
||||
</span>
|
||||
</Tooltip>
|
||||
{text && (
|
||||
<Tooltip content={t('复制提示词')} position='top'>
|
||||
<button
|
||||
type='button'
|
||||
aria-label={t('复制提示词')}
|
||||
className='inline-flex h-7 w-7 flex-none items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-brand/10 hover:text-brand focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40'
|
||||
onClick={(event) => handleCopyPrompt(event, text)}
|
||||
>
|
||||
<Copy size={14} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('来源'),
|
||||
dataIndex: 'source',
|
||||
width: 90,
|
||||
render: (v) => (
|
||||
<Tag
|
||||
size='small'
|
||||
color={v === 'playground' ? 'blue' : v === 'mobile' ? 'teal' : 'grey'}
|
||||
type='ghost'
|
||||
>
|
||||
{v === 'playground' ? t('对话面板') : v === 'mobile' ? 'App' : 'API'}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('调用次数'),
|
||||
dataIndex: 'call_count',
|
||||
width: 90,
|
||||
render: (v) => (
|
||||
<span className='inline-flex min-w-7 justify-center rounded-md bg-gray-100 px-2 py-0.5 text-xs font-semibold text-gray-700 dark:bg-white/[0.06] dark:text-gray-300'>
|
||||
{formatTokenCount(v)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('总花费'),
|
||||
dataIndex: 'total_quota',
|
||||
width: 110,
|
||||
render: (v) => (
|
||||
<span className='whitespace-nowrap text-sm font-semibold text-[var(--text-primary)]'>
|
||||
{formatQuotaAsCNY(v, quotaPerUnit)}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('Token 消耗'),
|
||||
dataIndex: 'prompt_tokens',
|
||||
width: 230,
|
||||
render: (v, record) => (
|
||||
<Tooltip
|
||||
content={
|
||||
t('输入 / 输出 tokens(全过程累计)') +
|
||||
`,${t('缓存命中')} ${record.cache_hit_tokens || 0}` +
|
||||
`,${t('缓存创建')} ${record.cache_creation_tokens || 0}`
|
||||
}
|
||||
position='top'
|
||||
>
|
||||
<div className='grid cursor-default grid-cols-2 gap-x-4 gap-y-1 whitespace-nowrap text-xs'>
|
||||
<span className='text-gray-400 dark:text-gray-500'>
|
||||
{t('输入')}
|
||||
</span>
|
||||
<span className='text-right font-medium tabular-nums text-gray-700 dark:text-gray-300'>
|
||||
{formatTokenCount(v)}
|
||||
</span>
|
||||
<span className='text-gray-400 dark:text-gray-500'>
|
||||
{t('输出')}
|
||||
</span>
|
||||
<span className='text-right font-medium tabular-nums text-gray-700 dark:text-gray-300'>
|
||||
{formatTokenCount(record.completion_tokens)}
|
||||
</span>
|
||||
<span className='text-amber-600 dark:text-amber-400'>
|
||||
{t('缓存创建')}
|
||||
</span>
|
||||
<span className='text-right font-medium tabular-nums text-amber-700 dark:text-amber-300'>
|
||||
{formatTokenCount(record.cache_creation_tokens)}
|
||||
</span>
|
||||
<span className='text-emerald-600 dark:text-emerald-400'>
|
||||
{t('缓存命中')}
|
||||
</span>
|
||||
<span className='text-right font-medium tabular-nums text-emerald-700 dark:text-emerald-300'>
|
||||
{formatTokenCount(record.cache_hit_tokens)}
|
||||
</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('时间'),
|
||||
dataIndex: 'last_at',
|
||||
width: 175,
|
||||
render: (v, record) => (
|
||||
<Tooltip
|
||||
content={
|
||||
t('首次') +
|
||||
': ' +
|
||||
new Date(record.first_at * 1000).toLocaleString('zh-CN') +
|
||||
',' +
|
||||
t('最后') +
|
||||
': ' +
|
||||
new Date(v * 1000).toLocaleString('zh-CN')
|
||||
}
|
||||
>
|
||||
<span className='cursor-default whitespace-nowrap text-xs tabular-nums text-gray-500 dark:text-gray-400'>
|
||||
{v ? new Date(v * 1000).toLocaleString('zh-CN') : '-'}
|
||||
</span>
|
||||
</Tooltip>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const expandedRowRender = (record) => (
|
||||
<div className='bg-gray-50/70 p-4 text-sm dark:bg-white/[0.02] sm:p-5'>
|
||||
<div className='mb-2.5 flex items-center justify-between gap-3'>
|
||||
<div className='min-w-0 text-xs text-gray-400 dark:text-gray-500'>
|
||||
{record.trace_id
|
||||
? `Trace ID: ${record.trace_id}`
|
||||
: t('归组方式:启发式(同一输入 30 分钟内的调用自动归为一条)')}
|
||||
{record.truncated ? ` · ${t('内容超长已截断')}` : ''}
|
||||
</div>
|
||||
{record.prompt && (
|
||||
<button
|
||||
type='button'
|
||||
className='inline-flex h-8 flex-none items-center gap-1.5 rounded-lg border border-[var(--border-subtle)] bg-[var(--surface-card)] px-2.5 text-xs font-medium text-gray-600 transition-colors hover:border-brand/30 hover:bg-brand/5 hover:text-brand focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40 dark:text-gray-300'
|
||||
onClick={(event) => handleCopyPrompt(event, record.prompt)}
|
||||
>
|
||||
<Copy size={14} />
|
||||
{t('复制提示词')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<pre className='max-h-80 overflow-y-auto whitespace-pre-wrap break-words rounded-lg border border-[var(--border-subtle)] bg-[var(--surface-card)] p-3.5 text-xs leading-5 text-gray-700 dark:text-gray-300'>
|
||||
{record.prompt || '-'}
|
||||
</pre>
|
||||
{record.group_key && (
|
||||
<PromptCallDetails orgId={orgId} groupKey={record.group_key} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
const activeFilterCount =
|
||||
Number(Boolean(appliedFilters.memberId)) +
|
||||
Number(Boolean(appliedFilters.modelName)) +
|
||||
Number(Boolean(appliedFilters.keyword)) +
|
||||
Number(
|
||||
Boolean(appliedFilters.startTimestamp || appliedFilters.endTimestamp),
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='mb-4 mt-4 flex items-start gap-3 rounded-xl border border-brand/15 bg-brand/[0.045] px-4 py-3 text-xs leading-5 text-gray-600 dark:text-gray-300'>
|
||||
<Database size={16} className='mt-0.5 flex-none text-brand' />
|
||||
<div>
|
||||
<div className='font-medium text-[var(--text-primary)]'>
|
||||
{t('企业自有提示词记录库')}
|
||||
</div>
|
||||
<div className='mt-0.5 text-gray-500 dark:text-gray-400'>
|
||||
{t(
|
||||
'数据来自「企业设置 → 提示词采集」中配置的自有数据库,仅记录成员输入,不包含 AI 回复。',
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<OrgPanel
|
||||
icon={SlidersHorizontal}
|
||||
title={t('筛选条件')}
|
||||
subtitle={
|
||||
activeFilterCount > 0
|
||||
? t('已应用 {{count}} 个筛选条件', { count: activeFilterCount })
|
||||
: t('可按成员、模型、关键词和时间范围组合查询')
|
||||
}
|
||||
className='mb-4'
|
||||
>
|
||||
<div className='grid grid-cols-1 items-end gap-3 sm:grid-cols-2 xl:grid-cols-[180px_180px_minmax(200px,1fr)_360px_auto]'>
|
||||
<label className='min-w-0'>
|
||||
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
|
||||
{t('企业成员')}
|
||||
</span>
|
||||
<Select
|
||||
value={selectedMemberId}
|
||||
onChange={setSelectedMemberId}
|
||||
optionList={memberOptions}
|
||||
placeholder={t('全部成员')}
|
||||
style={{ width: '100%' }}
|
||||
loading={membersLoading}
|
||||
filter
|
||||
/>
|
||||
</label>
|
||||
<label className='min-w-0'>
|
||||
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
|
||||
{t('模型')}
|
||||
</span>
|
||||
<Input
|
||||
value={modelName}
|
||||
onChange={setModelName}
|
||||
placeholder={t('输入模型名称')}
|
||||
showClear
|
||||
onEnterPress={applyFilter}
|
||||
/>
|
||||
</label>
|
||||
<label className='min-w-0'>
|
||||
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
|
||||
{t('提示词')}
|
||||
</span>
|
||||
<Input
|
||||
value={keyword}
|
||||
onChange={setKeyword}
|
||||
placeholder={t('搜索提示词关键词')}
|
||||
showClear
|
||||
onEnterPress={applyFilter}
|
||||
/>
|
||||
</label>
|
||||
<label className='min-w-0 sm:col-span-2 xl:col-span-1'>
|
||||
<span className='mb-1.5 block text-xs text-gray-500 dark:text-gray-400'>
|
||||
{t('时间范围')}
|
||||
</span>
|
||||
<DatePicker
|
||||
type='dateTimeRange'
|
||||
density='compact'
|
||||
value={timeRange}
|
||||
onChange={setTimeRange}
|
||||
placeholder={[t('开始时间'), t('结束时间')]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
</label>
|
||||
<div className='flex flex-wrap gap-2 sm:col-span-2 xl:col-span-1 xl:flex-nowrap'>
|
||||
<Button
|
||||
type='primary'
|
||||
icon={<Search size={14} />}
|
||||
onClick={applyFilter}
|
||||
loading={loading || membersLoading}
|
||||
>
|
||||
{t('查询')}
|
||||
</Button>
|
||||
<Button icon={<RotateCcw size={14} />} onClick={resetFilters}>
|
||||
{t('重置')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</OrgPanel>
|
||||
|
||||
<OrgPanel
|
||||
title={t('提示词调用记录')}
|
||||
subtitle={
|
||||
loading
|
||||
? t('正在加载记录…')
|
||||
: t('共 {{count}} 条记录,展开行可查看完整提示词与调用明细', {
|
||||
count: total,
|
||||
})
|
||||
}
|
||||
actions={
|
||||
<Button
|
||||
icon={<RefreshCw size={14} />}
|
||||
onClick={() => fetch(page, 20, appliedFilters)}
|
||||
loading={loading || membersLoading}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
}
|
||||
padding='p-0'
|
||||
bodyClassName='overflow-x-auto'
|
||||
>
|
||||
{/* 宽屏占满卡片,窄屏保持 1400px 最小宽度并由外层横向滚动。 */}
|
||||
<Table
|
||||
className='org-prompt-records-table'
|
||||
columns={columns}
|
||||
dataSource={records}
|
||||
loading={loading}
|
||||
rowKey='id'
|
||||
expandedRowRender={expandedRowRender}
|
||||
expandRowByClick
|
||||
onRow={() => ({ className: 'cursor-pointer' })}
|
||||
scroll={{ x: 'max(100%, 1400px)' }}
|
||||
pagination={{
|
||||
currentPage: page,
|
||||
pageSize: 20,
|
||||
total,
|
||||
onPageChange: setPage,
|
||||
}}
|
||||
empty={
|
||||
<OrgStateBlock
|
||||
icon={MessageSquareText}
|
||||
title={error || t('暂无提示词记录')}
|
||||
description={
|
||||
error
|
||||
? t(
|
||||
'请企业所有者在「企业设置 → 提示词采集」中完成数据库配置并初始化数据表',
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</OrgPanel>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgPromptRecords;
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { Typography } from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import QualityDashboard from '../../components/quality/QualityDashboard';
|
||||
import './org-quality.css';
|
||||
|
||||
const { Title, Text } = Typography;
|
||||
|
||||
/** 企业中心 · 调用质量:只见本企业数据,渠道与上游细节由后端屏蔽 */
|
||||
const OrgQuality = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-quality',
|
||||
title: t('调用质量 · 使用指引'),
|
||||
intro: t('回答三个问题:调用成不成功、失败怪谁、哪些成员 / 模型受影响最大'),
|
||||
steps: [
|
||||
{
|
||||
title: t('读懂结局'),
|
||||
detail: t('每次调用只归入一种结局'),
|
||||
points: [
|
||||
t(
|
||||
'「兜底成功」:首选线路失败,平台自动切换备用线路后成功,对使用者无感',
|
||||
),
|
||||
t('「兜底失败」:所有备用线路都失败,需要关注'),
|
||||
t(
|
||||
'「客户端中断」「内容安全拦截」默认不计入成功率分母,可在「更多筛选」中勾选纳入',
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('区分责任方'),
|
||||
detail: t('失败按原因归类,便于判断是否需要自查'),
|
||||
points: [
|
||||
t('「请求参数问题」「额度 / 限流」通常可由企业侧调整解决'),
|
||||
t('「服务侧故障」由平台负责处理,持续偏高可联系平台'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('下钻定位'),
|
||||
detail: t('从汇总一路点到具体请求'),
|
||||
points: [
|
||||
t('点击指标卡直接查看对应结局的请求明细'),
|
||||
t(
|
||||
'点击趋势柱子放大到该时段;点击分布表格的行按该部门 / 成员 / 模型筛选',
|
||||
),
|
||||
t('按成员 / 部门 / 项目筛选时直接统计调用日志,时间范围最长 7 天'),
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return (
|
||||
<div className='org-quality-page'>
|
||||
<header className='org-quality-hero'>
|
||||
<div className='min-w-0'>
|
||||
<div className='org-quality-eyebrow'>{t('调用质量')}</div>
|
||||
<Title heading={3}>{t('企业调用质量')}</Title>
|
||||
<Text type='tertiary'>
|
||||
{t(
|
||||
'查看本企业调用的成功率、自动兜底效果与失败原因,定位受影响的成员与模型。',
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
</header>
|
||||
<PageGuideDrawer guide={guide} />
|
||||
<QualityDashboard scope='org' orgId={orgId} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgQuality;
|
||||
@@ -0,0 +1,855 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useEffect, useState, useCallback, useMemo } from 'react';
|
||||
import { timestamp2string } from '../../helpers/utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Typography,
|
||||
Button,
|
||||
Spin,
|
||||
Table,
|
||||
Tag,
|
||||
InputNumber,
|
||||
Select,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
CreditCard,
|
||||
Wallet,
|
||||
TrendingUp,
|
||||
Coins,
|
||||
History,
|
||||
CheckCircle,
|
||||
Clock,
|
||||
XCircle,
|
||||
Pencil,
|
||||
} from 'lucide-react';
|
||||
import {
|
||||
API,
|
||||
showError,
|
||||
showInfo,
|
||||
showSuccess,
|
||||
renderQuota,
|
||||
getQuotaPerUnit,
|
||||
} from '../../helpers';
|
||||
import AmountCard from '../Recharge/AmountCard';
|
||||
import WechatQRModal from '../../components/topup/modals/WechatQRModal';
|
||||
import PaymentConfirmModal from '../../components/topup/modals/PaymentConfirmModal';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import { orgStatusColor } from './components/orgStatus';
|
||||
import {
|
||||
formatPayPalUSD,
|
||||
getPayPalReturnState,
|
||||
parsePayPalQuote,
|
||||
requestPayPalOrder,
|
||||
removePayPalReturnState,
|
||||
} from '../../helpers/paypalPayment';
|
||||
|
||||
const { Text, Title } = Typography;
|
||||
|
||||
const OrgRecharge = ({ orgId }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// 企业信息
|
||||
const [orgQuota, setOrgQuota] = useState(0);
|
||||
const [orgUsedQuota, setOrgUsedQuota] = useState(0);
|
||||
|
||||
// 充值配置
|
||||
const [presetAmounts, setPresetAmounts] = useState([]);
|
||||
const [payMethods, setPayMethods] = useState([]);
|
||||
const [enableWechatTopUp, setEnableWechatTopUp] = useState(false);
|
||||
const [enableAlipayTopUp, setEnableAlipayTopUp] = useState(false);
|
||||
const [enablePayPalTopUp, setEnablePayPalTopUp] = useState(false);
|
||||
const [infoLoading, setInfoLoading] = useState(true);
|
||||
|
||||
// 充值交互状态
|
||||
const [selectedPreset, setSelectedPreset] = useState(null);
|
||||
const [selectedPresetObj, setSelectedPresetObj] = useState(null);
|
||||
const [payWay, setPayWay] = useState('');
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [confirmLoading, setConfirmLoading] = useState(false);
|
||||
const [amountLoading, setAmountLoading] = useState(false);
|
||||
const [payPalQuote, setPayPalQuote] = useState(null);
|
||||
|
||||
// 自定义充值(与预设档位互斥;自定义金额无折扣,原价到账)
|
||||
const [isCustomMode, setIsCustomMode] = useState(false);
|
||||
const [customAmount, setCustomAmount] = useState(null);
|
||||
const [customUnit, setCustomUnit] = useState(1000); // 1000=千 / 10000=万
|
||||
|
||||
const customEffectiveAmount = useMemo(() => {
|
||||
if (!customAmount || customAmount < 1) return 0;
|
||||
return Math.floor(Number(customAmount)) * customUnit;
|
||||
}, [customAmount, customUnit]);
|
||||
|
||||
const customValid = customEffectiveAmount >= 1000;
|
||||
|
||||
// 当前生效的金额/折扣/赠送(自定义优先)
|
||||
const effectiveAmountYuan = isCustomMode
|
||||
? customEffectiveAmount
|
||||
: selectedPresetObj?.value || 0;
|
||||
const effectiveDiscount = isCustomMode
|
||||
? 1.0
|
||||
: selectedPresetObj?.discount || 1.0;
|
||||
const effectiveBonus = isCustomMode ? 0 : selectedPresetObj?.bonus || 0;
|
||||
|
||||
// 微信二维码
|
||||
const [wechatQRVisible, setWechatQRVisible] = useState(false);
|
||||
const [wechatOrderData, setWechatOrderData] = useState(null);
|
||||
|
||||
// 充值记录
|
||||
const [history, setHistory] = useState([]);
|
||||
const [historyTotal, setHistoryTotal] = useState(0);
|
||||
const [historyPage, setHistoryPage] = useState(1);
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
const [refreshHistory, setRefreshHistory] = useState(0);
|
||||
|
||||
const orgHeaders = { 'X-Org-Id': String(orgId) };
|
||||
|
||||
// 获取企业配额
|
||||
const fetchOrgQuota = useCallback(async () => {
|
||||
try {
|
||||
const res = await API.get('/api/org/quota', { headers: orgHeaders });
|
||||
if (res.data.success) {
|
||||
const { quota, used_quota } = res.data.data;
|
||||
setOrgQuota(quota || 0);
|
||||
setOrgUsedQuota(used_quota || 0);
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
// 获取充值配置
|
||||
const fetchTopUpInfo = useCallback(async () => {
|
||||
setInfoLoading(true);
|
||||
try {
|
||||
const res = await API.get('/api/org/topup/info', { headers: orgHeaders });
|
||||
if (res.data.success) {
|
||||
const data = res.data.data;
|
||||
setEnableWechatTopUp(data.enable_wechat_topup || false);
|
||||
setEnableAlipayTopUp(data.enable_alipay_topup || false);
|
||||
setEnablePayPalTopUp(data.enable_paypal_topup || false);
|
||||
setPayMethods(data.pay_methods || []);
|
||||
|
||||
if (data.amount_options_v2 && data.amount_options_v2.length > 0) {
|
||||
const sorted = [...data.amount_options_v2].sort(
|
||||
(a, b) => (a.sort || 0) - (b.sort || 0),
|
||||
);
|
||||
setPresetAmounts(
|
||||
sorted.map((opt) => ({
|
||||
id: opt.id,
|
||||
value: opt.amount,
|
||||
discount: opt.discount || 1.0,
|
||||
label: opt.label,
|
||||
badge: opt.badge,
|
||||
badgeColor: opt.badge_color,
|
||||
isRecommend: opt.is_recommend,
|
||||
isHot: opt.is_hot,
|
||||
bonus: opt.bonus,
|
||||
minVipLevel: opt.min_vip_level,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
showError(t('获取充值配置失败'));
|
||||
} finally {
|
||||
setInfoLoading(false);
|
||||
}
|
||||
}, [orgId]);
|
||||
|
||||
// 获取充值记录
|
||||
const fetchHistory = useCallback(
|
||||
async (page = 1) => {
|
||||
setHistoryLoading(true);
|
||||
try {
|
||||
const res = await API.get(`/api/org/topup?p=${page}&page_size=10`, {
|
||||
headers: orgHeaders,
|
||||
});
|
||||
if (res.data.success) {
|
||||
const data = res.data.data;
|
||||
setHistory(data.items || []);
|
||||
setHistoryTotal(data.total || 0);
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
} finally {
|
||||
setHistoryLoading(false);
|
||||
}
|
||||
},
|
||||
[orgId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchOrgQuota();
|
||||
fetchTopUpInfo();
|
||||
}, [fetchOrgQuota, fetchTopUpInfo]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchHistory(historyPage);
|
||||
}, [fetchHistory, historyPage, refreshHistory]);
|
||||
|
||||
useEffect(() => {
|
||||
const result = getPayPalReturnState(window.location.search);
|
||||
if (!result) return;
|
||||
if (result.status === 'success') showSuccess(t('PayPal 充值成功'));
|
||||
else if (result.status === 'pending')
|
||||
showInfo(t('PayPal 支付处理中,请稍后查看充值记录'));
|
||||
else if (result.status === 'cancelled') showInfo(t('已取消 PayPal 支付'));
|
||||
else showError(t('PayPal 支付确认失败,请稍后重试'));
|
||||
fetchOrgQuota();
|
||||
setRefreshHistory((previous) => previous + 1);
|
||||
window.history.replaceState(
|
||||
{},
|
||||
'',
|
||||
removePayPalReturnState(window.location.href),
|
||||
);
|
||||
// The callback query must be consumed exactly once on page entry.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const selectPreset = (preset) => {
|
||||
setSelectedPreset(preset.id);
|
||||
setSelectedPresetObj(preset);
|
||||
setIsCustomMode(false);
|
||||
setCustomAmount(null);
|
||||
};
|
||||
|
||||
const handleCustomAmountChange = (v) => {
|
||||
setCustomAmount(v);
|
||||
if (v && Number(v) > 0) {
|
||||
setIsCustomMode(true);
|
||||
setSelectedPreset(null);
|
||||
setSelectedPresetObj(null);
|
||||
} else {
|
||||
setIsCustomMode(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCustomUnitChange = (v) => {
|
||||
setCustomUnit(v);
|
||||
if (customAmount && Number(customAmount) > 0) {
|
||||
setIsCustomMode(true);
|
||||
setSelectedPreset(null);
|
||||
setSelectedPresetObj(null);
|
||||
}
|
||||
};
|
||||
|
||||
// 自定义充值快速选择档位
|
||||
const customQuickPicks = [
|
||||
{ amount: 1, unit: 1000 },
|
||||
{ amount: 5, unit: 1000 },
|
||||
{ amount: 1, unit: 10000 },
|
||||
{ amount: 5, unit: 10000 },
|
||||
{ amount: 10, unit: 10000 },
|
||||
];
|
||||
|
||||
const applyCustomQuickPick = (amount, unit) => {
|
||||
setCustomAmount(amount);
|
||||
setCustomUnit(unit);
|
||||
setIsCustomMode(true);
|
||||
setSelectedPreset(null);
|
||||
setSelectedPresetObj(null);
|
||||
};
|
||||
|
||||
// 自定义充值预览额度(与后端 service.CalculateQuota 一致:originalMoney * QuotaPerUnit + bonus,自定义 bonus=0)
|
||||
const customPreviewQuota =
|
||||
customEffectiveAmount > 0
|
||||
? customEffectiveAmount * (getQuotaPerUnit() || 500000)
|
||||
: 0;
|
||||
|
||||
const handlePreTopUp = async (paymentType) => {
|
||||
if (isCustomMode) {
|
||||
if (!customValid) {
|
||||
showError(t('自定义充值金额最少为 1000 元'));
|
||||
return;
|
||||
}
|
||||
} else if (!selectedPresetObj) {
|
||||
showError(t('请先选择充值金额'));
|
||||
return;
|
||||
}
|
||||
setPayWay(paymentType);
|
||||
if (paymentType === 'paypal') {
|
||||
if (!enablePayPalTopUp) {
|
||||
showError(t('管理员未开启 PayPal 充值!'));
|
||||
return;
|
||||
}
|
||||
setAmountLoading(true);
|
||||
try {
|
||||
const response = await API.post(
|
||||
'/api/org/topup/paypal/amount',
|
||||
buildPayBody(),
|
||||
{ headers: orgHeaders },
|
||||
);
|
||||
if (!response.data.success) {
|
||||
throw new Error(response.data.message || t('获取金额失败'));
|
||||
}
|
||||
setPayPalQuote(parsePayPalQuote(response));
|
||||
} catch (error) {
|
||||
showError(error?.message || t('获取金额失败'));
|
||||
return;
|
||||
} finally {
|
||||
setAmountLoading(false);
|
||||
}
|
||||
}
|
||||
setConfirmOpen(true);
|
||||
};
|
||||
|
||||
const buildPayBody = () =>
|
||||
isCustomMode
|
||||
? { custom_amount: customEffectiveAmount }
|
||||
: { amount_option_id: selectedPresetObj.id };
|
||||
|
||||
const isMobile = /iPhone|Android|iPad|Mobile/i.test(navigator.userAgent);
|
||||
|
||||
const handleConfirmPay = async () => {
|
||||
if (!isCustomMode && !selectedPresetObj) return;
|
||||
if (isCustomMode && !customValid) return;
|
||||
setConfirmLoading(true);
|
||||
try {
|
||||
let res;
|
||||
const payBody = buildPayBody();
|
||||
if (payWay === 'wxpay' && enableWechatTopUp) {
|
||||
const wechatEndpoint = isMobile
|
||||
? '/api/org/topup/wechat/h5'
|
||||
: '/api/org/topup/wechat/native';
|
||||
res = await API.post(wechatEndpoint, payBody, { headers: orgHeaders });
|
||||
if (res.data.success) {
|
||||
if (isMobile) {
|
||||
// H5:直接跳转微信支付页
|
||||
window.location.href = res.data.data.h5_url;
|
||||
setConfirmOpen(false);
|
||||
const onFocus = () => {
|
||||
fetchOrgQuota();
|
||||
setRefreshHistory((p) => p + 1);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
};
|
||||
window.addEventListener('focus', onFocus);
|
||||
} else {
|
||||
// Native:弹出二维码
|
||||
setWechatOrderData(res.data.data);
|
||||
setConfirmOpen(false);
|
||||
setWechatQRVisible(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else if (payWay === 'paypal' && enablePayPalTopUp) {
|
||||
res = await requestPayPalOrder(
|
||||
API,
|
||||
'/api/org/topup/paypal',
|
||||
{ ...payBody, quote_token: payPalQuote?.quoteToken },
|
||||
{ headers: orgHeaders, skipErrorHandler: true },
|
||||
);
|
||||
if (res.data.success && res.data.data?.approval_url) {
|
||||
setPayPalQuote(parsePayPalQuote(res));
|
||||
window.location.href = res.data.data.approval_url;
|
||||
return;
|
||||
}
|
||||
if (
|
||||
res.status === 202 &&
|
||||
res.data?.message === 'PAYPAL_ORDER_CREATING'
|
||||
) {
|
||||
showInfo(t('PayPal 订单创建中,请稍后重试'));
|
||||
return;
|
||||
}
|
||||
} else if (payWay === 'alipay' && enableAlipayTopUp) {
|
||||
const alipayEndpoint = isMobile
|
||||
? '/api/org/topup/alipay/wap'
|
||||
: '/api/org/topup/alipay/pc';
|
||||
res = await API.post(alipayEndpoint, payBody, { headers: orgHeaders });
|
||||
if (res.data.success) {
|
||||
// Safari 会拦截 await 之后的 window.open(用户手势已过期),改为同标签跳转
|
||||
const isSafari =
|
||||
navigator.userAgent.indexOf('Safari') > -1 &&
|
||||
navigator.userAgent.indexOf('Chrome') < 1;
|
||||
if (isSafari) {
|
||||
window.location.href = res.data.data.pay_url;
|
||||
return;
|
||||
}
|
||||
window.open(res.data.data.pay_url, '_blank');
|
||||
setConfirmOpen(false);
|
||||
// 用户从支付宝标签页切回时自动刷新余额和记录
|
||||
const onFocus = () => {
|
||||
fetchOrgQuota();
|
||||
setRefreshHistory((p) => p + 1);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
};
|
||||
window.addEventListener('focus', onFocus);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// 失败处理
|
||||
const msg = res?.data?.message || t('支付请求失败');
|
||||
showError(msg);
|
||||
} catch (e) {
|
||||
const code = e?.response?.data?.message;
|
||||
if (payWay === 'paypal' && code?.startsWith('PAYPAL_QUOTE_')) {
|
||||
try {
|
||||
const response = await API.post(
|
||||
'/api/org/topup/paypal/amount',
|
||||
buildPayBody(),
|
||||
{ headers: orgHeaders },
|
||||
);
|
||||
if (!response.data.success) throw new Error(response.data.message);
|
||||
setPayPalQuote(parsePayPalQuote(response));
|
||||
showInfo(t('PayPal 报价已更新,请重新确认'));
|
||||
} catch {
|
||||
showError(t('获取金额失败'));
|
||||
}
|
||||
} else {
|
||||
showError(e?.response?.data?.message || t('支付请求失败'));
|
||||
}
|
||||
} finally {
|
||||
setConfirmLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleWechatComplete = (success) => {
|
||||
setWechatQRVisible(false);
|
||||
setWechatOrderData(null);
|
||||
if (success) {
|
||||
showSuccess(t('充值成功!'));
|
||||
fetchOrgQuota();
|
||||
setRefreshHistory((p) => p + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const renderAmount = () => {
|
||||
if (payWay === 'paypal') {
|
||||
return formatPayPalUSD(payPalQuote?.payAmount);
|
||||
}
|
||||
if (effectiveAmountYuan <= 0) return '';
|
||||
const pay = effectiveAmountYuan * effectiveDiscount;
|
||||
return `${pay.toFixed(2)} ${t('元')}`;
|
||||
};
|
||||
|
||||
// 充值记录状态渲染
|
||||
const renderStatus = (status) => {
|
||||
const map = {
|
||||
success: {
|
||||
icon: <CheckCircle size={12} />,
|
||||
text: t('成功'),
|
||||
},
|
||||
pending: {
|
||||
icon: <Clock size={12} />,
|
||||
text: t('待支付'),
|
||||
},
|
||||
expired: { icon: <XCircle size={12} />, text: t('已过期') },
|
||||
};
|
||||
const s = map[status] || { icon: null, text: status };
|
||||
return (
|
||||
<Tag
|
||||
color={orgStatusColor(status)}
|
||||
size='small'
|
||||
className='flex items-center gap-1'
|
||||
>
|
||||
{s.icon}
|
||||
{s.text}
|
||||
</Tag>
|
||||
);
|
||||
};
|
||||
|
||||
const historyColumns = [
|
||||
{
|
||||
title: t('订单号'),
|
||||
dataIndex: 'trade_no',
|
||||
render: (v) => (
|
||||
<Text size='small' className='font-mono'>
|
||||
{v}
|
||||
</Text>
|
||||
),
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: t('金额'),
|
||||
dataIndex: 'money',
|
||||
render: (v) => <Text size='small'>¥{Number(v).toFixed(2)}</Text>,
|
||||
width: 90,
|
||||
},
|
||||
{
|
||||
title: t('获得额度'),
|
||||
dataIndex: 'amount',
|
||||
render: (v) => <Text size='small'>{renderQuota(v)}</Text>,
|
||||
width: 110,
|
||||
},
|
||||
{
|
||||
title: t('支付方式'),
|
||||
dataIndex: 'payment_channel',
|
||||
render: (v) => (
|
||||
<Text size='small'>
|
||||
{v === 'paypal_checkout' ? 'PayPal' : v || '-'}
|
||||
</Text>
|
||||
),
|
||||
width: 110,
|
||||
},
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
render: (v) => renderStatus(v),
|
||||
width: 90,
|
||||
},
|
||||
{
|
||||
title: t('时间'),
|
||||
dataIndex: 'create_time',
|
||||
render: (v) => <Text size='small'>{timestamp2string(v)}</Text>,
|
||||
width: 160,
|
||||
},
|
||||
];
|
||||
|
||||
const hasAnyPayment =
|
||||
enableWechatTopUp || enableAlipayTopUp || enablePayPalTopUp;
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8 space-y-6'>
|
||||
<OrgPageHeader title={t('企业充值')} subtitle={t('为企业账户充值额度')} />
|
||||
|
||||
{/* 签名时刻:余额展示区(本页唯一的品牌渐变区,渐变走 --brand-* token 随预设切换) */}
|
||||
<div className='relative overflow-hidden bg-gradient-to-r from-brand-from via-brand-via to-brand-to rounded-xl p-5 shadow-[var(--elevation-md)]'>
|
||||
<div className='flex items-center justify-between gap-4 flex-wrap'>
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='p-2 bg-white/15 rounded-lg'>
|
||||
<Wallet size={20} className='text-white' />
|
||||
</div>
|
||||
<div>
|
||||
<Text className='!text-white/80 text-xs font-medium block'>
|
||||
{t('企业可用余额')}
|
||||
</Text>
|
||||
<Title heading={4} className='!text-white !mb-0 tabular-nums'>
|
||||
{renderQuota(orgQuota)}
|
||||
</Title>
|
||||
</div>
|
||||
</div>
|
||||
<div className='w-px h-10 bg-white/20 flex-shrink-0' />
|
||||
<div className='flex items-center gap-3'>
|
||||
<div className='p-2 bg-white/10 rounded-lg'>
|
||||
<TrendingUp size={18} className='text-white/80' />
|
||||
</div>
|
||||
<div>
|
||||
<Text className='!text-white/60 text-xs block'>
|
||||
{t('累计消耗')}
|
||||
</Text>
|
||||
<Text className='!text-white font-semibold text-sm tabular-nums'>
|
||||
{renderQuota(orgUsedQuota)}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 充值区域 */}
|
||||
<OrgPanel icon={Coins} title={t('选择充值档位')}>
|
||||
{infoLoading ? (
|
||||
<div className='py-10 flex justify-center'>
|
||||
<Spin />
|
||||
</div>
|
||||
) : presetAmounts.length > 0 ? (
|
||||
<>
|
||||
<div className='grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2.5 mb-4'>
|
||||
{presetAmounts.map((preset, idx) => (
|
||||
<AmountCard
|
||||
key={idx}
|
||||
preset={preset}
|
||||
selected={selectedPreset === preset.id}
|
||||
onClick={() => selectPreset(preset)}
|
||||
topupInfo={{ amount_options: [], discount: {} }}
|
||||
priceRatio={1}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 自定义充值(与档位互斥;自定义金额无折扣,原价到账) */}
|
||||
<div
|
||||
className={`mb-5 rounded-xl border-2 border-dashed transition-all ${
|
||||
isCustomMode
|
||||
? 'border-emerald-400 bg-gradient-to-br from-emerald-50/60 to-emerald-50/25 dark:from-emerald-900/15 dark:to-emerald-900/10 dark:border-emerald-600 shadow-sm shadow-emerald-500/5'
|
||||
: 'border-gray-200 dark:border-neutral-700 hover:border-emerald-300 dark:hover:border-emerald-700'
|
||||
}`}
|
||||
>
|
||||
{/* 头部 */}
|
||||
<div className='px-4 pt-3.5 pb-2.5 flex items-center justify-between flex-wrap gap-1.5'>
|
||||
<div className='flex items-center gap-1.5'>
|
||||
<div className='p-1 rounded-md bg-emerald-100 dark:bg-emerald-900/40'>
|
||||
<Pencil
|
||||
size={12}
|
||||
className='text-emerald-600 dark:text-emerald-400'
|
||||
/>
|
||||
</div>
|
||||
<Text
|
||||
strong
|
||||
className='text-gray-800 dark:text-gray-200 text-sm'
|
||||
>
|
||||
{t('自定义充值')}
|
||||
</Text>
|
||||
{isCustomMode && (
|
||||
<Tag color='green' size='small'>
|
||||
{t('已选')}
|
||||
</Tag>
|
||||
)}
|
||||
</div>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('原价到账,不参与折扣')}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{/* 输入区 */}
|
||||
<div className='px-4 pb-3'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<InputNumber
|
||||
value={customAmount}
|
||||
onChange={handleCustomAmountChange}
|
||||
min={1}
|
||||
precision={0}
|
||||
hideButtons
|
||||
size='large'
|
||||
placeholder={t('请输入整数,如 1、5、10')}
|
||||
className='!flex-1'
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Select
|
||||
value={customUnit}
|
||||
onChange={handleCustomUnitChange}
|
||||
size='large'
|
||||
style={{ width: 96 }}
|
||||
optionList={[
|
||||
{ label: t('千'), value: 1000 },
|
||||
{ label: t('万'), value: 10000 },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 快速选择 */}
|
||||
<div className='mt-2.5 flex items-center gap-1.5 flex-wrap'>
|
||||
<Text
|
||||
type='tertiary'
|
||||
size='small'
|
||||
className='!text-xs flex-shrink-0'
|
||||
>
|
||||
{t('快速选择:')}
|
||||
</Text>
|
||||
{customQuickPicks.map((pick) => {
|
||||
const active =
|
||||
isCustomMode &&
|
||||
Number(customAmount) === pick.amount &&
|
||||
customUnit === pick.unit;
|
||||
const label = `${pick.amount}${pick.unit === 1000 ? t('千') : t('万')}`;
|
||||
return (
|
||||
<button
|
||||
key={`${pick.amount}-${pick.unit}`}
|
||||
type='button'
|
||||
onClick={() =>
|
||||
applyCustomQuickPick(pick.amount, pick.unit)
|
||||
}
|
||||
className={`px-2.5 py-0.5 rounded-md text-xs font-medium transition-colors border ${
|
||||
active
|
||||
? 'bg-emerald-500 text-white border-emerald-500 shadow-sm shadow-emerald-500/20'
|
||||
: 'bg-white dark:bg-neutral-800 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-neutral-700 hover:border-emerald-300 hover:text-emerald-600 dark:hover:border-emerald-700 dark:hover:text-emerald-400'
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 实时预览(仅在金额合法时显示) */}
|
||||
{customEffectiveAmount > 0 && customValid && (
|
||||
<div className='mx-4 mb-3 rounded-lg p-3 bg-[var(--surface-card)] border border-[var(--border-subtle)]'>
|
||||
<div className='flex items-center justify-between gap-3 flex-wrap'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='w-7 h-7 rounded-lg bg-rose-500/10 text-rose-600 dark:text-rose-400 flex items-center justify-center'>
|
||||
<Wallet size={14} />
|
||||
</div>
|
||||
<div>
|
||||
<Text
|
||||
type='tertiary'
|
||||
size='small'
|
||||
className='!text-xs block leading-tight'
|
||||
>
|
||||
{t('实付金额')}
|
||||
</Text>
|
||||
<Text
|
||||
strong
|
||||
className='!text-rose-600 dark:!text-rose-400 text-base leading-tight'
|
||||
>
|
||||
¥{customEffectiveAmount.toLocaleString()}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='w-7 h-7 rounded-lg bg-amber-500/10 text-amber-600 dark:text-amber-400 flex items-center justify-center'>
|
||||
<Coins size={14} />
|
||||
</div>
|
||||
<div className='text-right'>
|
||||
<Text
|
||||
type='tertiary'
|
||||
size='small'
|
||||
className='!text-xs block leading-tight'
|
||||
>
|
||||
{t('获得额度')}
|
||||
</Text>
|
||||
<Text
|
||||
strong
|
||||
className='!text-amber-600 dark:!text-amber-400 text-base leading-tight'
|
||||
>
|
||||
{renderQuota(customPreviewQuota)}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 底部说明(金额不达标时变橙色) */}
|
||||
<div className='px-4 pb-3'>
|
||||
<Text
|
||||
size='small'
|
||||
className={`!text-xs ${
|
||||
customEffectiveAmount > 0 && !customValid
|
||||
? '!text-amber-600 dark:!text-amber-400'
|
||||
: '!text-gray-400 dark:!text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{customEffectiveAmount > 0 && !customValid
|
||||
? `${t('当前 ¥')}${customEffectiveAmount.toLocaleString()}${t(',未达到最低 ¥1,000')}`
|
||||
: t('最少 1000 元,必须为 1000 元的整倍数')}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 支付方式 */}
|
||||
<div className='flex items-center gap-2 mb-3'>
|
||||
<div className='p-1.5 rounded-lg bg-brand/10 text-brand'>
|
||||
<CreditCard size={14} />
|
||||
</div>
|
||||
<Text strong className='text-gray-800 dark:text-gray-200'>
|
||||
{t('支付方式')}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{hasAnyPayment ? (
|
||||
<div className='flex flex-wrap gap-3'>
|
||||
{payMethods.map((method) => {
|
||||
const isWechat = method.type === 'wxpay';
|
||||
const isAlipay = method.type === 'alipay';
|
||||
const isPayPal = method.type === 'paypal';
|
||||
const disabled =
|
||||
(isWechat && !enableWechatTopUp) ||
|
||||
(isAlipay && !enableAlipayTopUp) ||
|
||||
(isPayPal && !enablePayPalTopUp);
|
||||
return (
|
||||
<Button
|
||||
key={method.type}
|
||||
theme={payWay === method.type ? 'solid' : 'light'}
|
||||
type={payWay === method.type ? 'primary' : 'tertiary'}
|
||||
disabled={disabled}
|
||||
loading={amountLoading && payWay === method.type}
|
||||
onClick={() => handlePreTopUp(method.type)}
|
||||
className={`!rounded-lg !px-5 !py-2.5 !h-auto transition-colors ${
|
||||
payWay === method.type
|
||||
? ''
|
||||
: 'hover:!bg-brand/5 dark:hover:!bg-brand-deep/20 hover:!border-brand-from'
|
||||
}`}
|
||||
>
|
||||
{method.name}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('暂无可用的支付方式,请联系管理员配置')}
|
||||
</Text>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Text type='tertiary'>{t('暂无充值档位,请联系管理员配置')}</Text>
|
||||
)}
|
||||
</OrgPanel>
|
||||
|
||||
{/* 充值记录 */}
|
||||
<OrgPanel
|
||||
icon={History}
|
||||
title={t('充值记录')}
|
||||
bodyClassName='overflow-x-auto'
|
||||
>
|
||||
<Table
|
||||
columns={historyColumns}
|
||||
dataSource={history}
|
||||
loading={historyLoading}
|
||||
pagination={{
|
||||
currentPage: historyPage,
|
||||
total: historyTotal,
|
||||
pageSize: 10,
|
||||
onPageChange: setHistoryPage,
|
||||
}}
|
||||
size='small'
|
||||
empty={<Text type='tertiary'>{t('暂无充值记录')}</Text>}
|
||||
/>
|
||||
</OrgPanel>
|
||||
|
||||
{/* 支付确认弹窗 */}
|
||||
<PaymentConfirmModal
|
||||
t={t}
|
||||
open={confirmOpen}
|
||||
onlineTopUp={handleConfirmPay}
|
||||
handleCancel={() => setConfirmOpen(false)}
|
||||
confirmLoading={confirmLoading}
|
||||
topUpCount={effectiveAmountYuan}
|
||||
renderQuotaWithAmount={() => {
|
||||
if (payWay === 'paypal' && payPalQuote?.quota) {
|
||||
return renderQuota(payPalQuote.quota);
|
||||
}
|
||||
if (effectiveAmountYuan <= 0) return renderQuota(0);
|
||||
// 额度 = 原始金额 × QuotaPerUnit + 赠送额度(与后端 CalculateQuota 逻辑一致,折扣只影响实付金额,不影响获得的额度)
|
||||
const quotaPerUnit = getQuotaPerUnit() || 500000;
|
||||
const baseQuota = effectiveAmountYuan * quotaPerUnit;
|
||||
return renderQuota(baseQuota + effectiveBonus);
|
||||
}}
|
||||
amountLoading={amountLoading}
|
||||
renderAmount={renderAmount}
|
||||
payWay={payWay}
|
||||
payMethods={payMethods}
|
||||
amountNumber={
|
||||
payWay === 'paypal' ? 0 : effectiveAmountYuan * effectiveDiscount
|
||||
}
|
||||
discountRate={payWay === 'paypal' ? 1 : effectiveDiscount}
|
||||
payPalQuote={payPalQuote}
|
||||
/>
|
||||
|
||||
{/* 微信二维码弹窗 */}
|
||||
<WechatQRModal
|
||||
visible={wechatQRVisible}
|
||||
onClose={handleWechatComplete}
|
||||
orderData={wechatOrderData}
|
||||
pollFn={async (tradeNo) => {
|
||||
const res = await API.get(
|
||||
`/api/org/topup?p=1&page_size=1&keyword=${tradeNo}`,
|
||||
{ headers: orgHeaders },
|
||||
);
|
||||
const items = res.data.data?.items || [];
|
||||
return items.length > 0 ? items[0] : null;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgRecharge;
|
||||
@@ -0,0 +1,307 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Table,
|
||||
Button,
|
||||
Tag,
|
||||
Toast,
|
||||
Input,
|
||||
Empty,
|
||||
Popconfirm,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { RefreshCw, Check, X } from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError, collectPagedItems } from '../../helpers';
|
||||
import { renderQuota } from '../../helpers/render';
|
||||
import OrgPageHeader from './components/OrgPageHeader';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import OrgModal from './components/OrgModal';
|
||||
import { orgStatusColor } from './components/orgStatus';
|
||||
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
|
||||
const isFeatureEnabled = (flags, key) => {
|
||||
const value = flags?.[key];
|
||||
return value === true || value === 'true' || value === '1' || value === 1;
|
||||
};
|
||||
|
||||
// 预算主体(dept/project/org/token 的提额加的是预算 cap,需开启实时拦截才生效);
|
||||
// member 主体改的是个人 quota_limit,始终生效。
|
||||
const BUDGET_SUBJECT_TYPES = ['department', 'project', 'org', 'token'];
|
||||
|
||||
const statusTag = (t, s) => {
|
||||
const m = {
|
||||
pending: { x: t('待审批') },
|
||||
approved: { x: t('已通过') },
|
||||
rejected: { x: t('已拒绝') },
|
||||
canceled: { x: t('已取消') },
|
||||
expired: { x: t('已过期') },
|
||||
};
|
||||
const v = m[s] || { x: s };
|
||||
return <Tag color={orgStatusColor(s)}>{v.x}</Tag>;
|
||||
};
|
||||
|
||||
const parseDelta = (payload) => {
|
||||
try {
|
||||
return JSON.parse(payload || '{}').cycle_quota_delta || 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
// 审批中心:管理员审批提额申请(PR7)。通过即原子提高目标预算 cap。
|
||||
const OrgRequests = ({ orgId, orgRole, featureFlags }) => {
|
||||
const { t } = useTranslation();
|
||||
const isApprover =
|
||||
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
|
||||
const enforcementOff = !isFeatureEnabled(featureFlags, 'budget_enforcement');
|
||||
const [list, setList] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [statusFilter, setStatusFilter] = useState('pending');
|
||||
const [rejectFor, setRejectFor] = useState(null);
|
||||
const [rejectComment, setRejectComment] = useState('');
|
||||
const listSeqRef = useRef(0);
|
||||
|
||||
const fetchList = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
// 翻页把一次加载从 1 个请求放大到最多 20 个,切换筛选的竞态窗口随之变大:
|
||||
// 旧筛选的翻页循环若在新请求之后才结束,会用旧数据覆盖列表。用 seq 围栏
|
||||
// 让过期的循环提前停止、且不再 setState。
|
||||
const seq = ++listSeqRef.current;
|
||||
setLoading(true);
|
||||
try {
|
||||
// 逐页取全:后端把 page_size 静默钳到 100,申请数超过 100 条时
|
||||
// 原先的单次请求会让较早的申请无声消失在列表外。
|
||||
const { items, message } = await collectPagedItems(
|
||||
(page, size) =>
|
||||
// 页码参数必须是 p —— common.GetPageQuery 只读 p/ps/size,从不读
|
||||
// page。原先写死 page=1 时这个错误无害(后端拿不到就默认第 1 页),
|
||||
// 改成翻页后却会让每一页都返回第 1 页,把同样的 100 条累加多次。
|
||||
API.get(
|
||||
`/api/org/requests?p=${page}&page_size=${size}${statusFilter ? `&status=${statusFilter}` : ''}`,
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
),
|
||||
{ shouldAbort: () => seq !== listSeqRef.current },
|
||||
);
|
||||
if (seq !== listSeqRef.current) return;
|
||||
setList(items);
|
||||
if (message) showError(message);
|
||||
} catch (err) {
|
||||
if (seq === listSeqRef.current) showError(err.message);
|
||||
} finally {
|
||||
if (seq === listSeqRef.current) setLoading(false);
|
||||
}
|
||||
}, [orgId, statusFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchList();
|
||||
}, [fetchList]);
|
||||
|
||||
const decide = async (id, decision, comment) => {
|
||||
try {
|
||||
const res = await API.put(
|
||||
`/api/org/requests/${id}/decision`,
|
||||
{ decision, comment: comment || '' },
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(decision === 'approved' ? t('已通过') : t('已拒绝'));
|
||||
setRejectFor(null);
|
||||
setRejectComment('');
|
||||
fetchList();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const columns = [
|
||||
{ title: 'ID', dataIndex: 'id', width: 60 },
|
||||
{
|
||||
title: t('类型'),
|
||||
dataIndex: 'request_type',
|
||||
width: 90,
|
||||
render: (v) => (v === 'quota' ? t('提额') : v),
|
||||
},
|
||||
{
|
||||
title: t('对象'),
|
||||
width: 160,
|
||||
ellipsis: true,
|
||||
render: (_, r) => {
|
||||
const label =
|
||||
{
|
||||
project: t('项目'),
|
||||
department: t('部门'),
|
||||
member: t('成员'),
|
||||
token: t('令牌'),
|
||||
org: t('企业'),
|
||||
}[r.subject_type] || r.subject_type;
|
||||
// 后端已富化 subject_name;主体被删除等极端情况回退为 #ID
|
||||
return r.subject_name
|
||||
? `${label} · ${r.subject_name}`
|
||||
: `${label} #${r.subject_id}`;
|
||||
},
|
||||
},
|
||||
{
|
||||
title: t('提额'),
|
||||
width: 110,
|
||||
render: (_, r) =>
|
||||
r.request_type === 'quota'
|
||||
? renderQuota(parseDelta(r.payload), 2)
|
||||
: '-',
|
||||
},
|
||||
{ title: t('理由'), dataIndex: 'reason', ellipsis: true },
|
||||
{
|
||||
title: t('状态'),
|
||||
dataIndex: 'status',
|
||||
width: 90,
|
||||
render: (v) => statusTag(t, v),
|
||||
},
|
||||
{
|
||||
title: t('操作'),
|
||||
width: 220,
|
||||
render: (_, r) =>
|
||||
isApprover && r.status === 'pending' ? (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Popconfirm
|
||||
title={t('确认通过该提额申请?')}
|
||||
content={
|
||||
<div className='max-w-xs'>
|
||||
<div>
|
||||
{r.request_type === 'quota'
|
||||
? `${t('通过后将立即提高目标额度上限')} ${renderQuota(parseDelta(r.payload), 2)}`
|
||||
: t('通过后将立即生效')}
|
||||
</div>
|
||||
{enforcementOff &&
|
||||
BUDGET_SUBJECT_TYPES.includes(r.subject_type) && (
|
||||
<div className='mt-1.5 text-xs text-amber-600 dark:text-amber-400'>
|
||||
{t(
|
||||
'注意:企业未开启「预算实时拦截」,本次提额不会立即影响实际使用,请先在企业设置开启。',
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
okType='warning'
|
||||
position='topRight'
|
||||
onConfirm={() => decide(r.id, 'approved')}
|
||||
>
|
||||
<Button
|
||||
size='small'
|
||||
theme='solid'
|
||||
type='primary'
|
||||
icon={<Check size={14} />}
|
||||
>
|
||||
{t('通过')}
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
type='danger'
|
||||
icon={<X size={14} />}
|
||||
onClick={() => setRejectFor(r.id)}
|
||||
>
|
||||
{t('拒绝')}
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<span className='text-xs text-gray-400'>-</span>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const filters = ['pending', 'approved', 'rejected', ''];
|
||||
|
||||
return (
|
||||
<div className='p-4 sm:p-6 lg:p-8'>
|
||||
<OrgPageHeader
|
||||
title={isApprover ? t('审批中心') : t('我的申请')}
|
||||
subtitle={t('提额申请与审批')}
|
||||
actions={
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<RefreshCw size={14} />}
|
||||
loading={loading}
|
||||
onClick={fetchList}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className='flex items-center gap-2 mb-3'>
|
||||
{filters.map((f) => (
|
||||
<Button
|
||||
key={f || 'all'}
|
||||
size='small'
|
||||
theme={statusFilter === f ? 'solid' : 'light'}
|
||||
onClick={() => setStatusFilter(f)}
|
||||
>
|
||||
{f === 'pending'
|
||||
? t('待审批')
|
||||
: f === 'approved'
|
||||
? t('已通过')
|
||||
: f === 'rejected'
|
||||
? t('已拒绝')
|
||||
: t('全部')}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<OrgPanel padding='p-2'>
|
||||
{list.length === 0 && !loading ? (
|
||||
<Empty description={t('暂无申请')} style={{ padding: 40 }} />
|
||||
) : (
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={list}
|
||||
loading={loading}
|
||||
pagination={{ pageSize: 15, showSizeChanger: false }}
|
||||
rowKey='id'
|
||||
/>
|
||||
)}
|
||||
</OrgPanel>
|
||||
|
||||
<OrgModal
|
||||
title={t('拒绝申请')}
|
||||
visible={!!rejectFor}
|
||||
onOk={() => decide(rejectFor, 'rejected', rejectComment)}
|
||||
onCancel={() => {
|
||||
setRejectFor(null);
|
||||
setRejectComment('');
|
||||
}}
|
||||
okText={t('确认拒绝')}
|
||||
cancelText={t('取消')}
|
||||
>
|
||||
<Input
|
||||
placeholder={t('拒绝理由(可选)')}
|
||||
value={rejectComment}
|
||||
onChange={setRejectComment}
|
||||
/>
|
||||
</OrgModal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgRequests;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,784 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
BarChart2,
|
||||
Users,
|
||||
Key,
|
||||
FileSearch,
|
||||
Receipt,
|
||||
Settings,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Building2,
|
||||
Search,
|
||||
X,
|
||||
CreditCard,
|
||||
Network,
|
||||
FolderKanban,
|
||||
LayoutGrid,
|
||||
Wallet,
|
||||
FileClock,
|
||||
UserRound,
|
||||
BrainCircuit,
|
||||
LibraryBig,
|
||||
Blocks,
|
||||
ListChecks,
|
||||
Bot,
|
||||
ShieldCheck,
|
||||
Cable,
|
||||
Gauge,
|
||||
Sparkles,
|
||||
Activity,
|
||||
} from 'lucide-react';
|
||||
import { useSidebarCollapsed } from '../../hooks/common/useSidebarCollapsed';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
|
||||
import { canAccessOrgSettings } from './orgFeatureFlags';
|
||||
import {
|
||||
CLOUD_BRAIN_UI_ENABLED,
|
||||
isCloudBrainOrgPath,
|
||||
} from '../../config/cloudBrainUi';
|
||||
|
||||
const pathFeatureRequirements = {
|
||||
'/org/cloud-brain': 'cloud_brain',
|
||||
'/org/knowledge': 'knowledge_base',
|
||||
'/org/skill-center': 'skill_market',
|
||||
'/org/skill-assignments': 'skill_market',
|
||||
'/org/experts': 'expert',
|
||||
'/org/agent-audit': 'cloud_brain',
|
||||
'/org/connectors': 'connector',
|
||||
'/org/effectiveness': 'agent_effectiveness',
|
||||
'/org/quality': 'quality_monitor',
|
||||
'/org/departments': 'dept',
|
||||
'/org/projects': 'project',
|
||||
'/org/budgets': 'budget',
|
||||
'/org/requests': 'approval',
|
||||
'/org/project-manage': 'project',
|
||||
};
|
||||
|
||||
const isFeatureEnabled = (flags, key) => {
|
||||
if (!key) return true;
|
||||
const value = flags?.[key];
|
||||
return value === true || value === 'true' || value === '1' || value === 1;
|
||||
};
|
||||
|
||||
const OrgSidebar = ({
|
||||
orgName,
|
||||
orgRole,
|
||||
featureFlags,
|
||||
isDeptManager = false,
|
||||
isProjectManager = false,
|
||||
canManageKnowledge = false,
|
||||
canManageSkills = false,
|
||||
canAssignSkills = false,
|
||||
canManageExperts = false,
|
||||
canManageConnectors = false,
|
||||
canAuditAgentMetadata = false,
|
||||
canViewAgentEffect = false,
|
||||
canViewQuality = false,
|
||||
isMemberActor = true,
|
||||
onNavigate,
|
||||
mobile = false,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const location = useLocation();
|
||||
const [collapsedState, toggleCollapsed] = useSidebarCollapsed();
|
||||
// 移动端抽屉里始终展开,不允许折叠
|
||||
const collapsed = mobile ? false : collapsedState;
|
||||
const [statusState] = useContext(StatusContext);
|
||||
const orgConfig = useMemo(
|
||||
() =>
|
||||
normalizeSidebarModulesAdmin(statusState?.status?.SidebarModulesAdmin)
|
||||
.orgCenter,
|
||||
[statusState?.status?.SidebarModulesAdmin],
|
||||
);
|
||||
|
||||
const isAdmin =
|
||||
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
|
||||
// owner/超管可管理完整设置;普通管理员仅在平台授权数据安全自助配置时进入该页。
|
||||
const canManageSettings = canAccessOrgSettings(orgRole, featureFlags);
|
||||
const roleLabel = useMemo(() => {
|
||||
if (orgRole === 'super_admin') return t('超级管理员');
|
||||
if (orgRole === 'owner') return t('所有者');
|
||||
if (orgRole === 'admin') return t('企业管理员');
|
||||
if (orgRole === 'dept_admin' && isProjectManager)
|
||||
return t('部门/项目管理员');
|
||||
if (orgRole === 'dept_admin' || isDeptManager) return t('部门管理员');
|
||||
if (isProjectManager) return t('项目管理员');
|
||||
return t('成员');
|
||||
}, [t, orgRole, isDeptManager, isProjectManager]);
|
||||
|
||||
// 菜单分组(云平台风格的分组导航,给扁平的十几个入口建立层次)
|
||||
const groups = useMemo(
|
||||
() => [
|
||||
{ key: 'overview', label: t('概览') },
|
||||
{ key: 'ai', label: t('AI 能力管理') },
|
||||
{ key: 'org', label: t('组织管理') },
|
||||
{ key: 'governance', label: t('额度与治理') },
|
||||
{ key: 'records', label: t('财务与日志') },
|
||||
{ key: 'settings', label: t('系统设置') },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
// 统一单一品牌色高亮(云平台风格),不再每项一种颜色
|
||||
const items = useMemo(() => {
|
||||
if (orgConfig?.enabled === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// adminOnly 仅 owner/admin/super_admin 可见;其余所有成员可见
|
||||
const all = [
|
||||
{
|
||||
itemKey: '/org/workbench',
|
||||
text: t('工作台'),
|
||||
icon: LayoutGrid,
|
||||
group: 'overview',
|
||||
},
|
||||
{
|
||||
itemKey: '/org/cloud-brain',
|
||||
text: t('云端大脑'),
|
||||
icon: BrainCircuit,
|
||||
group: 'overview',
|
||||
beta: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/knowledge',
|
||||
text: t('企业知识'),
|
||||
icon: LibraryBig,
|
||||
group: 'overview',
|
||||
adminOnly: true,
|
||||
knowledgePermission: true,
|
||||
beta: true,
|
||||
},
|
||||
{
|
||||
// 我的技能 + 业务系统授权合并页:成员自助视图,归入概览组,
|
||||
// 让「AI 能力管理」成为纯管理员分组。
|
||||
itemKey: '/org/my-capabilities',
|
||||
text: t('我的 AI 能力'),
|
||||
icon: Sparkles,
|
||||
group: 'overview',
|
||||
},
|
||||
{
|
||||
// 企业技能库 + 企业自研 Skill 合并页;平台技能的启用在技能超市完成
|
||||
itemKey: '/org/skill-center',
|
||||
text: t('技能中心'),
|
||||
icon: Blocks,
|
||||
group: 'ai',
|
||||
adminOnly: true,
|
||||
skillManage: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/skill-assignments',
|
||||
text: t('分发与锁定'),
|
||||
icon: ListChecks,
|
||||
group: 'ai',
|
||||
assignmentPermission: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/experts',
|
||||
text: t('企业专家工坊'),
|
||||
icon: Bot,
|
||||
group: 'ai',
|
||||
adminOnly: true,
|
||||
expertManage: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/connectors',
|
||||
text: t('Connector 管理'),
|
||||
icon: Cable,
|
||||
group: 'ai',
|
||||
adminOnly: true,
|
||||
connectorManage: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/effectiveness',
|
||||
text: t('效能分析'),
|
||||
icon: Gauge,
|
||||
group: 'overview',
|
||||
adminOnly: true,
|
||||
effectView: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/quality',
|
||||
text: t('调用质量'),
|
||||
icon: Activity,
|
||||
group: 'overview',
|
||||
adminOnly: true,
|
||||
qualityView: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/agent-audit',
|
||||
text: t('Agent 任务审计'),
|
||||
icon: ShieldCheck,
|
||||
group: 'records',
|
||||
agentAudit: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/dashboard',
|
||||
text: t('数据看板'),
|
||||
icon: BarChart2,
|
||||
group: 'overview',
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/members',
|
||||
text: t('员工管理'),
|
||||
icon: Users,
|
||||
group: 'org',
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/dept-manage',
|
||||
text: t('部门管理'),
|
||||
icon: Network,
|
||||
group: 'org',
|
||||
deptScope: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/project-manage',
|
||||
text: t('我的项目'),
|
||||
icon: FolderKanban,
|
||||
group: 'org',
|
||||
projectScope: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/departments',
|
||||
text: t('部门管理'),
|
||||
icon: Network,
|
||||
group: 'org',
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/projects',
|
||||
text: t('项目管理'),
|
||||
icon: FolderKanban,
|
||||
group: 'org',
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/budgets',
|
||||
text: t('预算中心'),
|
||||
icon: Wallet,
|
||||
group: 'governance',
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/requests',
|
||||
text: isAdmin ? t('审批中心') : t('我的申请'),
|
||||
icon: FileClock,
|
||||
group: 'governance',
|
||||
},
|
||||
{
|
||||
itemKey: '/org/tokens',
|
||||
text: t('令牌管理'),
|
||||
icon: Key,
|
||||
group: 'governance',
|
||||
},
|
||||
{
|
||||
itemKey: '/org/recharge',
|
||||
text: t('企业充值'),
|
||||
icon: CreditCard,
|
||||
group: 'records',
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/logs',
|
||||
text: isAdmin || isDeptManager ? t('消耗明细') : t('我的消耗明细'),
|
||||
icon: Receipt,
|
||||
group: 'records',
|
||||
},
|
||||
{
|
||||
itemKey: '/org/audit',
|
||||
text: t('审计日志'),
|
||||
icon: FileSearch,
|
||||
group: 'records',
|
||||
adminOnly: true,
|
||||
},
|
||||
{
|
||||
itemKey: '/org/personal-settings',
|
||||
text: t('个人设置'),
|
||||
icon: UserRound,
|
||||
group: 'settings',
|
||||
},
|
||||
{
|
||||
itemKey: '/org/settings',
|
||||
text: t('企业设置'),
|
||||
icon: Settings,
|
||||
group: 'settings',
|
||||
ownerOnly: true,
|
||||
},
|
||||
];
|
||||
|
||||
const visibilityByPath = {
|
||||
'/org/workbench': 'workbench',
|
||||
'/org/cloud-brain': 'cloudBrain',
|
||||
'/org/knowledge': 'knowledge',
|
||||
'/org/skill-assignments': 'skillAssignments',
|
||||
'/org/experts': 'experts',
|
||||
'/org/agent-audit': 'agentAudit',
|
||||
'/org/connectors': 'connectors',
|
||||
'/org/effectiveness': 'effectiveness',
|
||||
'/org/quality': 'quality',
|
||||
'/org/dashboard': 'dashboard',
|
||||
'/org/members': 'members',
|
||||
'/org/departments': 'departments',
|
||||
'/org/projects': 'projects',
|
||||
'/org/dept-manage': 'deptManage',
|
||||
'/org/project-manage': 'projectManage',
|
||||
'/org/budgets': 'budgets',
|
||||
'/org/requests': 'requests',
|
||||
'/org/tokens': 'tokens',
|
||||
'/org/logs': 'logs',
|
||||
'/org/audit': 'audit',
|
||||
'/org/recharge': 'recharge',
|
||||
'/org/settings': 'settings',
|
||||
};
|
||||
|
||||
return all.filter((item) => {
|
||||
if (!CLOUD_BRAIN_UI_ENABLED && isCloudBrainOrgPath(item.itemKey)) {
|
||||
return false;
|
||||
}
|
||||
if (item.adminOnly && !isAdmin) return false;
|
||||
// 平台超管(无成员身份)访问成员型入口必被 member_actor_required 拒绝。
|
||||
if (!isMemberActor && item.itemKey === '/org/my-capabilities')
|
||||
return false;
|
||||
if (item.knowledgePermission && !canManageKnowledge) return false;
|
||||
if (item.skillManage && !canManageSkills) return false;
|
||||
// 与路由守卫一致:分发页要求 (isAdmin || isDeptManager) && canAssignSkills,
|
||||
// 只查权限位会给无管辖部门的 dept_admin 一个点击即被重定向的死入口。
|
||||
if (
|
||||
item.assignmentPermission &&
|
||||
!(canAssignSkills && (isAdmin || isDeptManager))
|
||||
)
|
||||
return false;
|
||||
if (item.expertManage && !canManageExperts) return false;
|
||||
// 不变量:除 can_assign_skills 外,全部 can_* 都由
|
||||
// MemberHasAdminPermission 计算,对非 owner/admin 恒 false——即权限位
|
||||
// 本身已蕴含 isAdmin,菜单无需重复判角色。路由守卫(Organization/index.jsx)
|
||||
// 写成 isAdmin && can_xxx 是防御性冗余,两者当前等价。
|
||||
// ⚠️ 若将来把某个权限下放给 dept_admin(做法参照 can_assign_skills 的
|
||||
// `Role == DeptAdmin || MemberHasAdminPermission(...)`),该不变量即被打破,
|
||||
// 必须同步在这里补角色条件,否则会变成"菜单可见但路由守卫拒绝"的死入口。
|
||||
if (item.agentAudit && !canAuditAgentMetadata) return false;
|
||||
if (item.effectView && !canViewAgentEffect) return false;
|
||||
if (item.qualityView && !canViewQuality) return false;
|
||||
if (item.connectorManage && !canManageConnectors) return false;
|
||||
// 与路由守卫一致:管理员只有 data_security 授权后才显示设置入口。
|
||||
if (item.ownerOnly && !canManageSettings) return false;
|
||||
// 部门管理:仅部门负责人可见(与路由门控一致;纯管理员用员工管理页,避免点了被重定向)
|
||||
if (item.deptScope && !isDeptManager) return false;
|
||||
// 我的项目:仅项目经理可见(同上,纯管理员用项目管理页)
|
||||
if (item.projectScope && !isProjectManager) return false;
|
||||
const key = visibilityByPath[item.itemKey];
|
||||
const requiredFeature = pathFeatureRequirements[item.itemKey];
|
||||
// 合并页跨两个模块开关/功能位,任一页签可见即显示入口(与路由守卫同口径)
|
||||
if (item.itemKey === '/org/my-capabilities') {
|
||||
return (
|
||||
(orgConfig?.mySkills !== false &&
|
||||
isFeatureEnabled(featureFlags, 'skill_market')) ||
|
||||
(orgConfig?.myConnectors !== false &&
|
||||
isFeatureEnabled(featureFlags, 'connector'))
|
||||
);
|
||||
}
|
||||
if (item.itemKey === '/org/skill-center') {
|
||||
return (
|
||||
isFeatureEnabled(featureFlags, 'skill_market') &&
|
||||
(orgConfig?.skillLibrary !== false ||
|
||||
orgConfig?.privateSkills !== false)
|
||||
);
|
||||
}
|
||||
if (item.itemKey === '/org/members') {
|
||||
return (
|
||||
(orgConfig?.members !== false ||
|
||||
orgConfig?.memberAccounts !== false) &&
|
||||
isFeatureEnabled(featureFlags, requiredFeature)
|
||||
);
|
||||
}
|
||||
return (
|
||||
(!key || orgConfig?.[key] !== false) &&
|
||||
isFeatureEnabled(featureFlags, requiredFeature)
|
||||
);
|
||||
});
|
||||
}, [
|
||||
t,
|
||||
isAdmin,
|
||||
canManageSettings,
|
||||
isDeptManager,
|
||||
isProjectManager,
|
||||
canManageKnowledge,
|
||||
canManageSkills,
|
||||
canAssignSkills,
|
||||
canManageExperts,
|
||||
canAuditAgentMetadata,
|
||||
canViewAgentEffect,
|
||||
canViewQuality,
|
||||
isMemberActor,
|
||||
canManageConnectors,
|
||||
orgConfig,
|
||||
featureFlags,
|
||||
]);
|
||||
|
||||
// 按分组聚合,保持 groups 顺序,自动跳过空组
|
||||
const groupedItems = useMemo(
|
||||
() =>
|
||||
groups
|
||||
.map((g) => ({ ...g, items: items.filter((it) => it.group === g.key) }))
|
||||
.filter((g) => g.items.length > 0),
|
||||
[groups, items],
|
||||
);
|
||||
|
||||
// 菜单搜索:命中项按分组展示;搜索中忽略折叠状态,保证结果可见
|
||||
const [searchText, setSearchText] = useState('');
|
||||
const searchInputRef = useRef(null);
|
||||
const navRef = useRef(null);
|
||||
const query = searchText.trim().toLowerCase();
|
||||
const visibleGroups = useMemo(() => {
|
||||
if (!query) return groupedItems;
|
||||
return groupedItems
|
||||
.map((g) => ({
|
||||
...g,
|
||||
items: g.items.filter((it) => it.text.toLowerCase().includes(query)),
|
||||
}))
|
||||
.filter((g) => g.items.length > 0);
|
||||
}, [groupedItems, query]);
|
||||
|
||||
// 二级分组折叠:仅记录用户手动收起的组,跨会话记忆
|
||||
const FOLDED_GROUPS_KEY = 'org_sidebar_folded_groups';
|
||||
const [foldedGroups, setFoldedGroups] = useState(() => {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(FOLDED_GROUPS_KEY) || '[]');
|
||||
return Array.isArray(saved) ? saved : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
const toggleGroup = (key) => {
|
||||
setFoldedGroups((prev) => {
|
||||
const next = prev.includes(key)
|
||||
? prev.filter((k) => k !== key)
|
||||
: [...prev, key];
|
||||
try {
|
||||
localStorage.setItem(FOLDED_GROUPS_KEY, JSON.stringify(next));
|
||||
} catch {
|
||||
/* 隐私模式等场景下写入失败可忽略,仅丢失记忆 */
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const getSelectedKey = () => {
|
||||
if (location.pathname === '/org/member-accounts') {
|
||||
return '/org/members';
|
||||
}
|
||||
if (items.some((item) => item.itemKey === location.pathname)) {
|
||||
return location.pathname;
|
||||
}
|
||||
if (location.pathname === '/org' || location.pathname === '/org/') {
|
||||
return items[0]?.itemKey || '';
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const selectedKey = getSelectedKey();
|
||||
|
||||
// 当前路由所在分组自动展开(仅本次会话,不覆盖用户的持久化选择)
|
||||
useEffect(() => {
|
||||
const activeGroup = groupedItems.find((g) =>
|
||||
g.items.some((it) => it.itemKey === selectedKey),
|
||||
)?.key;
|
||||
if (!activeGroup) return;
|
||||
setFoldedGroups((prev) =>
|
||||
prev.includes(activeGroup) ? prev.filter((k) => k !== activeGroup) : prev,
|
||||
);
|
||||
}, [selectedKey, groupedItems]);
|
||||
|
||||
// 选中项滚入可视区(分组较多时避免高亮项被折叠区/滚动区遮住)
|
||||
useEffect(() => {
|
||||
const el = navRef.current?.querySelector('[data-active="true"]');
|
||||
el?.scrollIntoView({ block: 'nearest' });
|
||||
}, [selectedKey]);
|
||||
|
||||
// 搜索命中片段高亮
|
||||
const renderItemText = (text) => {
|
||||
if (!query) return text;
|
||||
const idx = text.toLowerCase().indexOf(query);
|
||||
if (idx === -1) return text;
|
||||
return (
|
||||
<>
|
||||
{text.slice(0, idx)}
|
||||
<mark className='rounded-sm bg-brand/20 px-0.5 text-inherit'>
|
||||
{text.slice(idx, idx + query.length)}
|
||||
</mark>
|
||||
{text.slice(idx + query.length)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`
|
||||
relative flex flex-col h-full transition-all duration-300 ease-out
|
||||
bg-[var(--surface-sidebar)]
|
||||
border-r border-[var(--border-subtle)]
|
||||
${collapsed ? 'w-[68px]' : 'w-[240px]'}
|
||||
`}
|
||||
>
|
||||
{/* 标题区域 */}
|
||||
{!collapsed && (
|
||||
<div className='px-4 pt-5 pb-3'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<div className='p-1.5 rounded-lg bg-brand/10 text-brand'>
|
||||
<Building2 size={16} />
|
||||
</div>
|
||||
<div className='min-w-0'>
|
||||
<span className='font-bold text-gray-900 dark:text-white block truncate text-sm'>
|
||||
{orgName || t('企业中心')}
|
||||
</span>
|
||||
{orgRole && (
|
||||
<span className='text-[10px] text-gray-500 dark:text-gray-400'>
|
||||
{roleLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 菜单搜索(折叠态显示放大镜按钮,点击先展开侧栏再聚焦输入框) */}
|
||||
{!collapsed ? (
|
||||
<div className='px-3 pb-1'>
|
||||
<div className='relative'>
|
||||
<Search
|
||||
size={14}
|
||||
className='pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500'
|
||||
/>
|
||||
<input
|
||||
ref={searchInputRef}
|
||||
type='text'
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') setSearchText('');
|
||||
}}
|
||||
placeholder={t('搜索菜单')}
|
||||
aria-label={t('搜索菜单')}
|
||||
className='h-8 w-full rounded-lg border border-transparent bg-[var(--semi-color-fill-0)] pl-8 pr-7 text-sm text-[var(--text-primary)] outline-none transition-colors duration-200 placeholder:text-gray-400 focus:border-brand/40 focus:bg-[var(--surface-card)] dark:placeholder:text-gray-500'
|
||||
/>
|
||||
{searchText && (
|
||||
<button
|
||||
type='button'
|
||||
onClick={() => setSearchText('')}
|
||||
aria-label={t('清空搜索')}
|
||||
className='absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-gray-400 transition-colors hover:text-gray-700 dark:hover:text-gray-200'
|
||||
>
|
||||
<X size={13} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className='px-3 pb-1 pt-3'>
|
||||
<button
|
||||
type='button'
|
||||
onClick={() => {
|
||||
toggleCollapsed();
|
||||
setTimeout(() => searchInputRef.current?.focus(), 350);
|
||||
}}
|
||||
aria-label={t('搜索菜单')}
|
||||
className='flex w-full items-center justify-center rounded-lg p-2 text-gray-500 transition-colors duration-200 hover:bg-brand/10 hover:text-brand-deep dark:text-gray-400 dark:hover:bg-brand/15 dark:hover:text-brand-from'
|
||||
>
|
||||
<Search size={16} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 导航区域 */}
|
||||
<nav
|
||||
ref={navRef}
|
||||
className='app-scrollbar relative flex-1 px-3 pt-1 pb-2 overflow-y-auto overflow-x-hidden'
|
||||
>
|
||||
{query && visibleGroups.length === 0 && (
|
||||
<div className='px-2 py-8 text-center text-xs text-gray-400 dark:text-gray-500'>
|
||||
{t('没有匹配的菜单')}
|
||||
</div>
|
||||
)}
|
||||
{visibleGroups.map((group, gi) => {
|
||||
// 搜索中强制展开,保证命中项可见;平时遵循用户的折叠选择
|
||||
const folded = !query && foldedGroups.includes(group.key);
|
||||
return (
|
||||
<div key={group.key} className={gi > 0 ? 'mt-3' : ''}>
|
||||
{/* 分组标题(展开态,可点击折叠)/ 分隔线(折叠态) */}
|
||||
{!collapsed ? (
|
||||
<button
|
||||
type='button'
|
||||
onClick={() => toggleGroup(group.key)}
|
||||
aria-expanded={!folded}
|
||||
className='mb-1 flex w-full select-none items-center gap-1.5 rounded-md px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-gray-400 transition-colors duration-200 hover:bg-[var(--semi-color-fill-0)] hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300'
|
||||
>
|
||||
<span className='truncate'>{group.label}</span>
|
||||
<span className='ml-auto text-[10px] font-normal tabular-nums opacity-70'>
|
||||
{group.items.length}
|
||||
</span>
|
||||
<ChevronDown
|
||||
size={13}
|
||||
className={`shrink-0 transition-transform duration-200 ${folded ? '-rotate-90' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
gi > 0 && (
|
||||
<div className='mx-2 mb-3 h-px bg-gray-200/50 dark:bg-neutral-700/50' />
|
||||
)
|
||||
)}
|
||||
|
||||
{/* grid-rows 0fr→1fr 实现平滑的折叠动画 */}
|
||||
<div
|
||||
className={`grid transition-[grid-template-rows] duration-200 ease-out ${
|
||||
folded && !collapsed ? 'grid-rows-[0fr]' : 'grid-rows-[1fr]'
|
||||
}`}
|
||||
>
|
||||
<div className='overflow-hidden'>
|
||||
<div className='space-y-1.5 pb-0.5'>
|
||||
{group.items.map((item) => {
|
||||
const isSelected = selectedKey === item.itemKey;
|
||||
const IconComponent = item.icon;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={item.itemKey}
|
||||
to={item.itemKey}
|
||||
onClick={() => onNavigate?.()}
|
||||
data-active={isSelected || undefined}
|
||||
className={`
|
||||
group relative flex items-center gap-3 rounded-lg transition-colors duration-200
|
||||
${collapsed ? 'justify-center p-3' : 'px-3 py-2'}
|
||||
${
|
||||
isSelected
|
||||
? 'bg-brand/10 dark:bg-brand/15'
|
||||
: 'hover:bg-brand/5 dark:hover:bg-brand/10'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{isSelected && (
|
||||
<div className='absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 rounded-r-full bg-brand transition-all duration-200' />
|
||||
)}
|
||||
|
||||
<div
|
||||
className={`
|
||||
relative flex-shrink-0 p-1.5 rounded-lg transition-colors duration-200
|
||||
${
|
||||
isSelected
|
||||
? 'bg-brand text-white'
|
||||
: 'text-gray-500 dark:text-gray-400 group-hover:text-brand-deep dark:group-hover:text-brand-from'
|
||||
}
|
||||
`}
|
||||
>
|
||||
<IconComponent size={18} strokeWidth={2} />
|
||||
</div>
|
||||
|
||||
{!collapsed && (
|
||||
<span className='flex min-w-0 items-center gap-2'>
|
||||
<span
|
||||
className={`
|
||||
text-sm transition-colors truncate
|
||||
${
|
||||
isSelected
|
||||
? 'text-brand-deep dark:text-brand-from font-semibold'
|
||||
: 'font-medium text-gray-600 dark:text-gray-300 group-hover:text-brand-deep dark:group-hover:text-brand-from'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{renderItemText(item.text)}
|
||||
</span>
|
||||
{item.beta && (
|
||||
<span className='shrink-0 rounded-full border border-orange-300/70 bg-orange-50 px-1.5 py-0.5 font-mono text-[8px] font-bold tracking-wider text-orange-700 dark:border-orange-700/50 dark:bg-orange-950/40 dark:text-orange-300'>
|
||||
BETA
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{collapsed && (
|
||||
<div
|
||||
className='
|
||||
absolute left-full ml-2 px-2.5 py-1.5
|
||||
bg-gray-900 dark:bg-white text-white dark:text-gray-900
|
||||
text-xs font-medium rounded-lg shadow-lg
|
||||
opacity-0 invisible group-hover:opacity-100 group-hover:visible
|
||||
transition-all duration-200 whitespace-nowrap z-50
|
||||
'
|
||||
>
|
||||
{item.text}
|
||||
<div
|
||||
className='absolute left-0 top-1/2 -translate-x-1 -translate-y-1/2
|
||||
border-4 border-transparent border-r-gray-900 dark:border-r-white'
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* 底部分隔线 */}
|
||||
{!mobile && (
|
||||
<div className='mx-4 h-px bg-gradient-to-r from-transparent via-gray-200/60 dark:via-neutral-700/60 to-transparent' />
|
||||
)}
|
||||
|
||||
{/* 折叠按钮(移动端抽屉里不显示) */}
|
||||
{!mobile && (
|
||||
<div className='relative p-3'>
|
||||
<button
|
||||
onClick={toggleCollapsed}
|
||||
className={`
|
||||
flex items-center justify-center gap-2 w-full py-2 rounded-lg
|
||||
text-gray-500 dark:text-gray-400 text-sm font-medium
|
||||
border border-[var(--border-subtle)]
|
||||
hover:bg-brand/10 dark:hover:bg-brand/15
|
||||
hover:text-brand-deep dark:hover:text-brand-from
|
||||
hover:border-brand/30 transition-colors duration-200
|
||||
${collapsed ? 'px-2' : 'px-3'}
|
||||
`}
|
||||
>
|
||||
{collapsed ? (
|
||||
<ChevronRight size={16} strokeWidth={2.5} />
|
||||
) : (
|
||||
<>
|
||||
<ChevronLeft size={16} strokeWidth={2.5} />
|
||||
<span>{t('收起')}</span>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgSidebar;
|
||||
@@ -0,0 +1,478 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
Table,
|
||||
Toast,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { API } from '../../helpers';
|
||||
import {
|
||||
ActivationModeTag,
|
||||
AssignmentModeTag,
|
||||
SkillEmptyGuide,
|
||||
} from '../../components/skill';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuidePill,
|
||||
PageGuideTrigger,
|
||||
flashGuideTarget,
|
||||
} from '../../components/common/PageGuide';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import './org-skills.css';
|
||||
|
||||
const { Title, Paragraph, Text } = Typography;
|
||||
|
||||
const defaultForm = {
|
||||
skill_id: 0,
|
||||
scope_type: 'organization',
|
||||
scope_id: 0,
|
||||
scope_value: '',
|
||||
mode: 'optional',
|
||||
activation: 'manual',
|
||||
version_policy: 'follow',
|
||||
version_id: 0,
|
||||
effective_from: 0,
|
||||
effective_to: 0,
|
||||
};
|
||||
|
||||
const OrgSkillAssignments = ({ orgId, orgRole = '' }) => {
|
||||
const { t } = useTranslation();
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
// Department admins are legitimate assignment actors but can only target
|
||||
// their own subtree; offering organization/project/member scopes would
|
||||
// produce guaranteed backend rejections.
|
||||
const isDeptAdmin = orgRole === 'dept_admin';
|
||||
const deptDefaultForm = useMemo(
|
||||
() =>
|
||||
isDeptAdmin ? { ...defaultForm, scope_type: 'department' } : defaultForm,
|
||||
[isDeptAdmin],
|
||||
);
|
||||
const scopeOptions = isDeptAdmin
|
||||
? ['department', 'department_leader']
|
||||
: [
|
||||
'organization',
|
||||
'department',
|
||||
'project',
|
||||
'role',
|
||||
'department_leader',
|
||||
'member',
|
||||
];
|
||||
const [items, setItems] = useState([]);
|
||||
const [library, setLibrary] = useState([]);
|
||||
// 首次加载完成前进度胶囊不渲染,避免对老用户闪现「0/4」。
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [previewMember, setPreviewMember] = useState(0);
|
||||
const [preview, setPreview] = useState([]);
|
||||
const [form, setForm] = useState(deptDefaultForm);
|
||||
const load = useCallback(async () => {
|
||||
// finally 保证请求失败也置 loaded:拦截器已 toast,此处只需不让
|
||||
// 未捕获 reject 把 loaded 卡在 false。
|
||||
try {
|
||||
const [assignments, policies] = await Promise.all([
|
||||
API.get('/api/org/skills/assignments', { headers }),
|
||||
// The options endpoint is readable by every assignment actor;
|
||||
// /library requires skill_manage, which dept_admin does not hold.
|
||||
API.get('/api/org/skills/assignments/options', { headers }),
|
||||
]);
|
||||
if (assignments.data?.success) setItems(assignments.data.data || []);
|
||||
if (policies.data?.success)
|
||||
setLibrary((policies.data.data || []).filter((item) => item.enabled));
|
||||
} finally {
|
||||
setLoaded(true);
|
||||
}
|
||||
}, [headers]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
const save = async () => {
|
||||
try {
|
||||
const response = await API.post('/api/org/skills/assignments', form, {
|
||||
headers,
|
||||
skipErrorHandler: true,
|
||||
});
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('保存失败'));
|
||||
return;
|
||||
}
|
||||
(response.data.warnings || []).forEach((warning) =>
|
||||
Toast.warning(warning),
|
||||
);
|
||||
setVisible(false);
|
||||
setForm(deptDefaultForm);
|
||||
await load();
|
||||
} catch (error) {
|
||||
Toast.error(
|
||||
error.response?.data?.message || error.message || t('保存失败'),
|
||||
);
|
||||
}
|
||||
};
|
||||
const remove = async (id) => {
|
||||
const response = await API.delete(`/api/org/skills/assignments/${id}`, {
|
||||
headers,
|
||||
});
|
||||
if (response.data?.success) await load();
|
||||
};
|
||||
// 指引步骤④「用预览验证」的完成态按组织持久化:preview 是会话内状态,
|
||||
// 不落盘的话每次进页胶囊都会复活(与知识页 verified-key 同语义)。
|
||||
// setItem 在隐私模式/配额耗尽时会抛异常,必须吞掉。
|
||||
const previewedKey = `org-skill-assignments-previewed-${orgId}`;
|
||||
const runPreview = async () => {
|
||||
const response = await API.get('/api/org/skills/preview', {
|
||||
headers,
|
||||
params: { member_id: previewMember },
|
||||
});
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('预览失败'));
|
||||
return;
|
||||
}
|
||||
setPreview(response.data.data || []);
|
||||
try {
|
||||
window.localStorage.setItem(previewedKey, '1');
|
||||
} catch {
|
||||
// 忽略:仅损失跨会话记忆
|
||||
}
|
||||
};
|
||||
const previewVerified = (() => {
|
||||
try {
|
||||
return window.localStorage.getItem(previewedKey) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
const columns = [
|
||||
{ title: t('Skill'), dataIndex: 'skill_id' },
|
||||
{
|
||||
title: t('范围'),
|
||||
render: (_, row) =>
|
||||
`${row.scope_type}:${row.scope_id || row.scope_value || 'all'}`,
|
||||
},
|
||||
{
|
||||
title: t('模式'),
|
||||
render: (_, row) => <AssignmentModeTag mode={row.mode} />,
|
||||
},
|
||||
{
|
||||
title: t('激活'),
|
||||
render: (_, row) => <ActivationModeTag mode={row.activation} />,
|
||||
},
|
||||
{ title: t('版本策略'), dataIndex: 'version_policy' },
|
||||
{
|
||||
title: t('操作'),
|
||||
render: (_, row) => (
|
||||
<Button type='danger' theme='borderless' onClick={() => remove(row.id)}>
|
||||
{t('删除')}
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
];
|
||||
const openCreateModal = () => {
|
||||
setForm(deptDefaultForm);
|
||||
setVisible(true);
|
||||
};
|
||||
// 使用指引:分发策略决定「谁能用哪些技能」,完成态由策略/预览数据驱动。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-skill-assignments',
|
||||
ready: loaded,
|
||||
title: t('分发与锁定 · 使用指引'),
|
||||
intro: t('技能启用后,靠分发策略决定对哪些成员生效'),
|
||||
steps: [
|
||||
{
|
||||
title: t('创建分发策略'),
|
||||
detail: t('选技能、选范围、定模式,一条策略就是一条生效规则'),
|
||||
done: items.length > 0,
|
||||
cta: t('去创建策略'),
|
||||
onAction: openCreateModal,
|
||||
points: [
|
||||
t(
|
||||
'可选范围:全企业 / 部门子树 / 项目 / 角色 / 部门负责人 / 指定成员',
|
||||
),
|
||||
isDeptAdmin
|
||||
? t('部门管理员只能面向本部门子树与部门负责人分发')
|
||||
: t('技能下拉里只出现已在技能库启用的技能'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('理解模式与激活'),
|
||||
detail: t('模式决定成员能否关闭,激活决定何时注入'),
|
||||
done: items.length > 0,
|
||||
points: [
|
||||
t('模式:必需锁定(强制启用不可关)/ 默认开启 / 推荐 / 可选 / 禁止'),
|
||||
t(
|
||||
'激活:always 始终注入 / auto 按任务自动匹配 / manual 成员手动开启',
|
||||
),
|
||||
t('多条策略叠加时按范围精细度取胜;保存时的黄色提示会指出冲突'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('版本策略'),
|
||||
detail: t('决定成员用的是哪个版本'),
|
||||
done: items.length > 0,
|
||||
points: [
|
||||
t('「跟随升级」自动使用企业技能库的当前版本'),
|
||||
t('「锁定版本」填写版本 ID,把该范围固定在指定版本上'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('用预览验证'),
|
||||
detail: t('回答「为什么成员 X 有 / 没有技能 Y」'),
|
||||
done: preview.length > 0 || previewVerified,
|
||||
cta: t('去预览'),
|
||||
onAction: () =>
|
||||
flashGuideTarget(
|
||||
'.org-skill-preview',
|
||||
'.org-skill-preview-controls input',
|
||||
),
|
||||
points: [
|
||||
t('在「成员能力预览」输入成员 ID,查看该成员最终生效的能力集'),
|
||||
t('每行展示生效来源链,与成员「我的技能」页看到的一致'),
|
||||
],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('创建时弹出黄色警告?'),
|
||||
a: t('策略已保存,警告提示与既有策略存在覆盖或冲突,按提示核对即可'),
|
||||
},
|
||||
{
|
||||
q: t('下拉里找不到想分发的技能?'),
|
||||
a: t('先到「技能超市」为企业启用该技能,使其进入企业技能库'),
|
||||
},
|
||||
],
|
||||
});
|
||||
const closeGuide = guide.close;
|
||||
// 预览结果与抽屉进度都是组织私有状态:切组织时清空/关闭并复位 loaded,
|
||||
// 否则旧组织的预览行/策略数据会把新组织的完成态渲染错。
|
||||
useEffect(() => {
|
||||
setPreview([]);
|
||||
setPreviewMember(0);
|
||||
setLoaded(false);
|
||||
closeGuide();
|
||||
}, [orgId, closeGuide]);
|
||||
return (
|
||||
<main className='org-skills-page'>
|
||||
<header className='org-skills-hero'>
|
||||
<div>
|
||||
<Title heading={3}>{t('分发与锁定')}</Title>
|
||||
<Paragraph>
|
||||
{t(
|
||||
'按企业、部门子树、项目、角色、负责人或成员分发,并实时预览最终能力集。',
|
||||
)}
|
||||
</Paragraph>
|
||||
</div>
|
||||
<div className='org-skills-hero-actions'>
|
||||
<PageGuideTrigger guide={guide} />
|
||||
<Button theme='solid' type='primary' onClick={openCreateModal}>
|
||||
{t('创建分发策略')}
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
<PageGuidePill guide={guide} />
|
||||
<PageGuideDrawer guide={guide} />
|
||||
<OrgPanel title={t('策略列表')}>
|
||||
{items.length === 0 ? (
|
||||
<SkillEmptyGuide
|
||||
title={t('还没有分发策略')}
|
||||
description={t(
|
||||
'技能启用后还需要分发策略才会对成员生效,先创建第一条。',
|
||||
)}
|
||||
actionLabel={t('创建分发策略')}
|
||||
onAction={openCreateModal}
|
||||
/>
|
||||
) : (
|
||||
<Table
|
||||
columns={columns}
|
||||
dataSource={items}
|
||||
rowKey='id'
|
||||
pagination={false}
|
||||
/>
|
||||
)}
|
||||
</OrgPanel>
|
||||
<OrgPanel title={t('成员能力预览')} className='org-skill-preview'>
|
||||
<div className='org-skill-preview-controls'>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={previewMember}
|
||||
onChange={setPreviewMember}
|
||||
placeholder={t('成员 ID')}
|
||||
/>
|
||||
<Button onClick={runPreview}>{t('预览')}</Button>
|
||||
</div>
|
||||
{preview.map((item) => (
|
||||
<div key={item.skill_id} className='org-skill-preview-row'>
|
||||
<Text strong>{item.canonical_id}</Text>
|
||||
<AssignmentModeTag mode={item.mode} />
|
||||
<Text>{item.enabled ? t('生效') : t('未生效')}</Text>
|
||||
<Text type='tertiary'>
|
||||
{(item.sources || [])
|
||||
.map(
|
||||
(source) =>
|
||||
`${source.scope_type}:${source.scope_id || source.scope_value || 'all'}`,
|
||||
)
|
||||
.join(' > ')}
|
||||
</Text>
|
||||
</div>
|
||||
))}
|
||||
</OrgPanel>
|
||||
<Modal
|
||||
title={t('创建分发策略')}
|
||||
visible={visible}
|
||||
onCancel={() => setVisible(false)}
|
||||
onOk={save}
|
||||
>
|
||||
<div className='org-skill-form'>
|
||||
<label>
|
||||
<Text>Skill</Text>
|
||||
<Select
|
||||
value={form.skill_id}
|
||||
onChange={(skill_id) => setForm((old) => ({ ...old, skill_id }))}
|
||||
>
|
||||
{library.map((item) => (
|
||||
<Select.Option key={item.skill_id} value={item.skill_id}>
|
||||
Skill #{item.skill_id}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</label>
|
||||
<label>
|
||||
<Text>{t('范围')}</Text>
|
||||
<Select
|
||||
value={form.scope_type}
|
||||
onChange={(scope_type) =>
|
||||
setForm((old) => ({
|
||||
...old,
|
||||
scope_type,
|
||||
scope_id: scope_type === 'organization' ? 0 : old.scope_id,
|
||||
}))
|
||||
}
|
||||
>
|
||||
{scopeOptions.map((value) => (
|
||||
<Select.Option key={value} value={value}>
|
||||
{value}
|
||||
</Select.Option>
|
||||
))}
|
||||
{!isDeptAdmin && (
|
||||
<Select.Option value='expert'>{t('指定专家')}</Select.Option>
|
||||
)}
|
||||
</Select>
|
||||
</label>
|
||||
{form.scope_type !== 'organization' && form.scope_type !== 'role' && (
|
||||
<label>
|
||||
<Text>Scope ID</Text>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={form.scope_id}
|
||||
onChange={(scope_id) =>
|
||||
setForm((old) => ({ ...old, scope_id }))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{form.scope_type === 'role' && (
|
||||
<label>
|
||||
<Text>{t('角色')}</Text>
|
||||
<Select
|
||||
value={form.scope_value}
|
||||
onChange={(scope_value) =>
|
||||
setForm((old) => ({ ...old, scope_value }))
|
||||
}
|
||||
>
|
||||
{['owner', 'admin', 'dept_admin', 'member'].map((value) => (
|
||||
<Select.Option key={value} value={value}>
|
||||
{value}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</label>
|
||||
)}
|
||||
<label>
|
||||
<Text>{t('模式')}</Text>
|
||||
<Select
|
||||
value={form.mode}
|
||||
onChange={(mode) => setForm((old) => ({ ...old, mode }))}
|
||||
>
|
||||
{[
|
||||
'required_locked',
|
||||
'default_on',
|
||||
'recommended',
|
||||
'optional',
|
||||
'forbidden',
|
||||
].map((value) => (
|
||||
<Select.Option key={value} value={value}>
|
||||
{value}
|
||||
</Select.Option>
|
||||
))}
|
||||
</Select>
|
||||
</label>
|
||||
<label>
|
||||
<Text>{t('激活')}</Text>
|
||||
<Select
|
||||
value={form.activation}
|
||||
onChange={(activation) =>
|
||||
setForm((old) => ({ ...old, activation }))
|
||||
}
|
||||
>
|
||||
{['always', 'auto', 'manual'].map((value) => (
|
||||
<Select.Option key={value} value={value}>
|
||||
{value}
|
||||
</Select.Option>
|
||||
))}
|
||||
<Select.Option value='workflow_step' disabled>
|
||||
{t('工作流步骤(ADR 批准并独立立项后开放)')}
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</label>
|
||||
<label>
|
||||
<Text>{t('版本策略')}</Text>
|
||||
<Select
|
||||
value={form.version_policy}
|
||||
onChange={(version_policy) =>
|
||||
setForm((old) => ({ ...old, version_policy }))
|
||||
}
|
||||
>
|
||||
<Select.Option value='follow'>{t('跟随升级')}</Select.Option>
|
||||
<Select.Option value='locked'>{t('锁定版本')}</Select.Option>
|
||||
</Select>
|
||||
</label>
|
||||
{form.version_policy === 'locked' && (
|
||||
<label>
|
||||
<Text>Version ID</Text>
|
||||
<InputNumber
|
||||
min={1}
|
||||
value={form.version_id}
|
||||
onChange={(version_id) =>
|
||||
setForm((old) => ({ ...old, version_id }))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgSkillAssignments;
|
||||
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import OrgSubpageTabs from './components/OrgSubpageTabs';
|
||||
import OrgSkillLibrary from './OrgSkillLibrary';
|
||||
import OrgPrivateSkills from './OrgPrivateSkills';
|
||||
|
||||
/**
|
||||
* 技能中心:企业技能库 + 企业自研 Skill 的合并入口。
|
||||
*
|
||||
* 两个页签共用同一权限口径(isAdmin && canManageSkills),差异只在站点级
|
||||
* 模块开关,由 showLibrary / showPrivate 控制。
|
||||
*
|
||||
* 平台技能的"引入企业"有两条路径:企业管理员可在平台技能超市
|
||||
* (/skill-market,原独立的企业技能市场页已并入其中,旧路由重定向过去)
|
||||
* 就地启用;企业技能库页内的「引入技能」抽屉则是平台超管与被顶栏配置挡在
|
||||
* 超市之外的 org_only 管理员的入口。两条路径写同一端点、同一审计。
|
||||
*/
|
||||
const OrgSkillCenter = ({
|
||||
orgId,
|
||||
orgRole,
|
||||
canAssignSkills = false,
|
||||
showLibrary = true,
|
||||
showPrivate = true,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<OrgSubpageTabs
|
||||
tabs={[
|
||||
showLibrary && {
|
||||
key: 'library',
|
||||
label: t('企业技能库'),
|
||||
// orgRole 用于识别平台超管(超市页解析不出其企业上下文,页内引入
|
||||
// 抽屉是其唯一的"代客开通"入口);canAssignSkills 决定引入成功后的
|
||||
// 指引指向哪里——超管的该权限位后端恒 false,不能让文案把人指向
|
||||
// 一个结构上进不去的页面。两者都复用父层已取的 /api/org/info。
|
||||
node: (
|
||||
<OrgSkillLibrary
|
||||
orgId={orgId}
|
||||
orgRole={orgRole}
|
||||
canAssignSkills={canAssignSkills}
|
||||
/>
|
||||
),
|
||||
},
|
||||
showPrivate && {
|
||||
key: 'private',
|
||||
label: t('企业自研 Skill'),
|
||||
node: <OrgPrivateSkills orgId={orgId} />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgSkillCenter;
|
||||
@@ -0,0 +1,839 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import React, {
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import {
|
||||
Button,
|
||||
Empty,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
SideSheet,
|
||||
Switch,
|
||||
Tag,
|
||||
TextArea,
|
||||
Toast,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import { Search } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { API } from '../../helpers';
|
||||
import {
|
||||
LicenseBadge,
|
||||
RiskBadge,
|
||||
SkillEmptyGuide,
|
||||
SkillStatusTag,
|
||||
} from '../../components/skill';
|
||||
import {
|
||||
usePageGuide,
|
||||
PageGuideDrawer,
|
||||
PageGuideTrigger,
|
||||
} from '../../components/common/PageGuide';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { normalizeSidebarModulesAdmin } from '../../constants/sidebarModules';
|
||||
import './org-skills.css';
|
||||
|
||||
const { Title, Text, Paragraph } = Typography;
|
||||
|
||||
const jsonList = (value) => {
|
||||
try {
|
||||
const parsed = JSON.parse(value || '[]');
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const OrgSkillLibrary = ({ orgId, orgRole, canAssignSkills = false }) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [statusState] = useContext(StatusContext);
|
||||
// 平台超管(查看企业时 org_role=super_admin、无成员身份)拿不到 /api/org/list
|
||||
// 里的这个企业,所以在平台超市页 activeOrg 解析不出来、没有启用面。他们的
|
||||
// 企业上下文只有在 /org 内才明确(current_org_id),因此页内引入抽屉是超管
|
||||
// 唯一可用的"代客开通"入口。
|
||||
const isPlatformSuperAdmin = orgRole === 'super_admin';
|
||||
// 与技能超市页同一开关:站点关闭「技能超市 · 为企业启用」后,超市页不再有
|
||||
// 启用按钮,跳过去的入口必须同步收起,否则就是一条通向空手而归的路。
|
||||
// 超管不受此开关约束——该开关的语义正是"仅平台可代为启用"。
|
||||
const selfEnableAllowed = useMemo(() => {
|
||||
const orgCenter = normalizeSidebarModulesAdmin(
|
||||
statusState?.status?.SidebarModulesAdmin,
|
||||
).orgCenter;
|
||||
return orgCenter?.enabled !== false && orgCenter?.skillMarket !== false;
|
||||
}, [statusState?.status?.SidebarModulesAdmin]);
|
||||
const canImport = selfEnableAllowed || isPlatformSuperAdmin;
|
||||
const headers = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
|
||||
const [items, setItems] = useState([]);
|
||||
const [catalog, setCatalog] = useState(new Map());
|
||||
const [selected, setSelected] = useState(null);
|
||||
const [derivePolicy, setDerivePolicy] = useState(null);
|
||||
const [derivedVersions, setDerivedVersions] = useState([]);
|
||||
const [evidenceVersion, setEvidenceVersion] = useState(null);
|
||||
const [evidence, setEvidence] = useState({
|
||||
model: '',
|
||||
input: '',
|
||||
});
|
||||
// 页内引入:直接复用 load() 已经取回的 catalog(/api/org/skills/market),
|
||||
// 不额外发请求。主要服务平台超管——超市页对其解析不出企业上下文;对普通
|
||||
// 管理员它是"就地快速添加",与超市页的分页/分类/需求热度视图互补。
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
const [importKeyword, setImportKeyword] = useState('');
|
||||
const [importingId, setImportingId] = useState(0);
|
||||
// 三态分离:首次加载完成前不渲染空态(否则闪一下"技能库为空"),
|
||||
// 加载失败要说人话且与"确实为空"区分开。
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [loadError, setLoadError] = useState({ library: '', catalog: '' });
|
||||
const [form, setForm] = useState({
|
||||
display_name: '',
|
||||
description_zh: '',
|
||||
applicable_roles: '[]',
|
||||
usage_boundary: '',
|
||||
default_activation: 'manual',
|
||||
derived_version_id: 0,
|
||||
});
|
||||
const load = useCallback(async () => {
|
||||
// allSettled 而非 all:任一端点失败都会让两个 setState 都不执行,于是主
|
||||
// 列表显示"企业技能库为空"、抽屉显示"平台目录暂无可用技能"——把硬故障
|
||||
// 说成"平台还没上架技能",安抚性文案盖住真实错误。分别降级并记录错误态。
|
||||
const [libraryOutcome, marketOutcome] = await Promise.allSettled([
|
||||
API.get('/api/org/skills/library', { headers, skipErrorHandler: true }),
|
||||
API.get('/api/org/skills/market', { headers, skipErrorHandler: true }),
|
||||
]);
|
||||
const pick = (outcome) =>
|
||||
outcome.status === 'fulfilled' ? outcome.value : null;
|
||||
const libraryRes = pick(libraryOutcome);
|
||||
const marketRes = pick(marketOutcome);
|
||||
const readError = (outcome, res) =>
|
||||
outcome.status === 'rejected'
|
||||
? outcome.reason?.response?.data?.message ||
|
||||
outcome.reason?.message ||
|
||||
t('加载失败')
|
||||
: res?.data?.success
|
||||
? ''
|
||||
: res?.data?.message || t('加载失败');
|
||||
if (libraryRes?.data?.success) setItems(libraryRes.data.data || []);
|
||||
if (marketRes?.data?.success)
|
||||
setCatalog(
|
||||
new Map(
|
||||
(marketRes.data.data || []).map((item) => [item.definition.id, item]),
|
||||
),
|
||||
);
|
||||
setLoadError({
|
||||
library: readError(libraryOutcome, libraryRes),
|
||||
catalog: readError(marketOutcome, marketRes),
|
||||
});
|
||||
setLoaded(true);
|
||||
}, [headers, t]);
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
// 库里已有的技能(无论启停)不重复出现在引入列表里——它们的启停归本页主列表管。
|
||||
const libraryIds = useMemo(
|
||||
() => new Set(items.map((policy) => policy.skill_id)),
|
||||
[items],
|
||||
);
|
||||
const catalogName = useCallback(
|
||||
(item) =>
|
||||
item?.locales?.find((locale) => locale.locale === 'zh')?.name ||
|
||||
item?.locales?.[0]?.name ||
|
||||
item?.definition?.canonical_id ||
|
||||
`Skill #${item?.definition?.id}`,
|
||||
[],
|
||||
);
|
||||
const importCandidates = useMemo(() => {
|
||||
const keyword = importKeyword.trim().toLowerCase();
|
||||
return [...catalog.values()]
|
||||
.filter((item) => !libraryIds.has(item.definition.id))
|
||||
.filter((item) => {
|
||||
if (!keyword) return true;
|
||||
return (
|
||||
catalogName(item).toLowerCase().includes(keyword) ||
|
||||
String(item.definition?.canonical_id || '')
|
||||
.toLowerCase()
|
||||
.includes(keyword)
|
||||
);
|
||||
});
|
||||
}, [catalog, libraryIds, importKeyword, catalogName]);
|
||||
const importSkill = async (skillId) => {
|
||||
// 有请求在飞时不接受新点击:单值 importingId 无法表达多个并发,
|
||||
// 先完成的那个会把 loading 清掉,让仍在飞行的按钮看起来可再点。
|
||||
if (importingId) return;
|
||||
setImportingId(skillId);
|
||||
let enabled = false;
|
||||
try {
|
||||
// 与技能超市页同一端点。失败分两路:controller 的 brainError 走 400/422
|
||||
// (axios reject,故需 skipErrorHandler 避免双 Toast),中间件 abortOrg
|
||||
// 走 200+success:false(axios 不 reject,只有 !success 分支能兜住)。
|
||||
const response = await API.put(
|
||||
`/api/org/skills/library/${skillId}/enabled`,
|
||||
{ enabled: true },
|
||||
{ headers, skipErrorHandler: true },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
throw new Error(response.data?.message || t('操作失败'));
|
||||
}
|
||||
enabled = true;
|
||||
// 平台超管的 can_assign_skills 后端恒 false(无成员身份,分发路由的
|
||||
// RequireOrgMemberActor 必拒),菜单里也没有该入口。把他们指向"分发与
|
||||
// 锁定"等于指向一个进不去的页面——代客开通的收尾必须由企业管理员完成。
|
||||
Toast.success({
|
||||
content: canAssignSkills
|
||||
? t('已加入企业技能库;还需在「分发与锁定」建策略,成员才可用')
|
||||
: t(
|
||||
'已加入企业技能库;还需由企业管理员在「分发与锁定」建策略,成员才可用',
|
||||
),
|
||||
duration: 6,
|
||||
});
|
||||
} catch (error) {
|
||||
Toast.error(
|
||||
error?.response?.data?.message || error?.message || t('操作失败'),
|
||||
);
|
||||
} finally {
|
||||
setImportingId(0);
|
||||
}
|
||||
if (!enabled) return;
|
||||
// 启用即视为采纳该技能下的员工诉求(与技能超市页同口径);处置失败静默,
|
||||
// 下次进页面还会看到该诉求。不做的话超市页的「N 人想要」永不消失。
|
||||
try {
|
||||
await API.put(
|
||||
`/api/org/skills/demand/${skillId}`,
|
||||
{ status: 'accepted' },
|
||||
{ headers, skipErrorHandler: true },
|
||||
);
|
||||
} catch (_error) {
|
||||
/* 见上:静默 */
|
||||
}
|
||||
// 刷新放在 try 之外:load() 内部的 GET 未跳过全局拦截器,放在同一个 try 里
|
||||
// 会在刷新失败时叠加一条"失败"Toast(且是 axios 英文原文),而启用其实已
|
||||
// 经成功。失败时保持旧列表即可,用户再操作一次会自然重拉。
|
||||
await load().catch(() => {});
|
||||
};
|
||||
const openCustomization = (policy, derivedVersionId) => {
|
||||
const customization = policy.customization || {};
|
||||
setForm({
|
||||
display_name: customization.display_name || '',
|
||||
description_zh: customization.description_zh || '',
|
||||
applicable_roles: customization.applicable_roles || '[]',
|
||||
usage_boundary: customization.usage_boundary || '',
|
||||
default_activation: customization.default_activation || 'manual',
|
||||
derived_version_id:
|
||||
derivedVersionId ?? customization.derived_version_id ?? 0,
|
||||
});
|
||||
setSelected(policy);
|
||||
};
|
||||
const configure = async (policy, patch) => {
|
||||
const payload = {
|
||||
enabled: policy.enabled,
|
||||
emergency_stopped: policy.emergency_stopped,
|
||||
version_policy: policy.version_policy || 'follow',
|
||||
locked_version_id: policy.locked_version_id || 0,
|
||||
...patch,
|
||||
};
|
||||
const response = await API.put(
|
||||
`/api/org/skills/library/${policy.skill_id}/policy`,
|
||||
payload,
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return;
|
||||
}
|
||||
await load();
|
||||
};
|
||||
const saveCustomization = async () => {
|
||||
const payload = {
|
||||
...form,
|
||||
applicable_roles_json: form.applicable_roles || '[]',
|
||||
};
|
||||
const response = await API.put(
|
||||
`/api/org/skills/library/${selected.skill_id}/customization`,
|
||||
payload,
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return;
|
||||
}
|
||||
Toast.success(t('企业定制已保存'));
|
||||
setSelected(null);
|
||||
await load();
|
||||
};
|
||||
const [deriveForm, setDeriveForm] = useState({
|
||||
body: '',
|
||||
name_zh: '',
|
||||
name_en: '',
|
||||
description_zh: '',
|
||||
description_en: '',
|
||||
triggers_zh: '',
|
||||
triggers_en: '',
|
||||
scenarios_zh: '',
|
||||
scenarios_en: '',
|
||||
compact_constraint_zh: '',
|
||||
compact_constraint_en: '',
|
||||
change_statement: '',
|
||||
default_output_language: 'auto',
|
||||
capabilities: ['prompt_only'],
|
||||
tags: [],
|
||||
});
|
||||
const saveDerived = async () => {
|
||||
const list = (value) =>
|
||||
String(value || '')
|
||||
.split(',')
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
const parentVersion = catalog.get(derivePolicy.skill_id)?.version;
|
||||
if (!parentVersion) {
|
||||
Toast.error(t('平台当前版本不可用,无法创建派生版本'));
|
||||
return;
|
||||
}
|
||||
if (!String(deriveForm.body || '').trim()) {
|
||||
Toast.warning(t('请先填写派生版本正文(body)'));
|
||||
return;
|
||||
}
|
||||
const response = await API.post(
|
||||
`/api/org/skills/versions/${parentVersion.id}/derive`,
|
||||
{
|
||||
...deriveForm,
|
||||
triggers_zh: list(deriveForm.triggers_zh),
|
||||
triggers_en: list(deriveForm.triggers_en),
|
||||
scenarios_zh: list(deriveForm.scenarios_zh),
|
||||
scenarios_en: list(deriveForm.scenarios_en),
|
||||
},
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return;
|
||||
}
|
||||
Toast.success(t('企业派生版本已创建,请完成模型实测和审核后再激活'));
|
||||
await loadDerivedVersions(derivePolicy.skill_id);
|
||||
await load();
|
||||
};
|
||||
const loadDerivedVersions = async (skillId) => {
|
||||
const response = await API.get(
|
||||
`/api/org/skills/library/${skillId}/derived-versions`,
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('派生版本加载失败'));
|
||||
return;
|
||||
}
|
||||
setDerivedVersions(response.data.data || []);
|
||||
};
|
||||
const openDerived = async (policy) => {
|
||||
const catalogItem = catalog.get(policy.skill_id);
|
||||
const version = catalogItem?.version;
|
||||
const zh = catalogItem?.locales?.find((item) => item.locale === 'zh') || {};
|
||||
const en = catalogItem?.locales?.find((item) => item.locale === 'en') || {};
|
||||
setDeriveForm({
|
||||
// The platform never serializes version bodies to organizations, so a
|
||||
// derived version's full body must be authored here from scratch.
|
||||
body: '',
|
||||
name_zh: zh.name || '',
|
||||
name_en: en.name || '',
|
||||
description_zh: zh.description || '',
|
||||
description_en: en.description || '',
|
||||
triggers_zh: jsonList(zh.triggers).join(', '),
|
||||
triggers_en: jsonList(en.triggers).join(', '),
|
||||
scenarios_zh: jsonList(zh.scenarios).join(', '),
|
||||
scenarios_en: jsonList(en.scenarios).join(', '),
|
||||
compact_constraint_zh: zh.compact_constraint || '',
|
||||
compact_constraint_en: en.compact_constraint || '',
|
||||
change_statement: '',
|
||||
default_output_language: version?.default_output_language || 'auto',
|
||||
capabilities: jsonList(version?.capabilities),
|
||||
tags: jsonList(version?.tags),
|
||||
});
|
||||
setDerivePolicy(policy);
|
||||
setDerivedVersions([]);
|
||||
await loadDerivedVersions(policy.skill_id);
|
||||
};
|
||||
const derivedAction = async (versionId, suffix, body = {}) => {
|
||||
const response = await API.post(
|
||||
`/api/org/skills/versions/${versionId}/${suffix}`,
|
||||
body,
|
||||
{ headers },
|
||||
);
|
||||
if (!response.data?.success) {
|
||||
Toast.error(response.data?.message || t('操作失败'));
|
||||
return false;
|
||||
}
|
||||
await loadDerivedVersions(derivePolicy.skill_id);
|
||||
return true;
|
||||
};
|
||||
const recordDerivedEvidence = async () => {
|
||||
if (!evidence.model.trim() || !evidence.input.trim()) {
|
||||
Toast.error(t('模型名称与测试输入不能为空'));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
await derivedAction(evidenceVersion, 'test', {
|
||||
model: evidence.model,
|
||||
input: evidence.input,
|
||||
})
|
||||
) {
|
||||
Toast.success(t('模型实测完成,证据已落库'));
|
||||
setEvidenceVersion(null);
|
||||
}
|
||||
};
|
||||
// 使用指引:技能库四项治理动作的阅读式说明(无上手流程,不出进度胶囊)。
|
||||
const guide = usePageGuide({
|
||||
guideKey: 'org-skill-library',
|
||||
title: t('企业技能库 · 使用指引'),
|
||||
intro: t('已启用技能的治理中心:启停、版本、止血与企业化定制'),
|
||||
steps: [
|
||||
{
|
||||
title: t('启用状态与版本策略'),
|
||||
detail: t('每行开关控制启用;版本策略决定是否跟随平台升级'),
|
||||
points: [
|
||||
t('「跟随平台升级」自动使用平台最新审核版本'),
|
||||
t('「锁定版本」把当前版本固定下来,平台升级不影响企业在用版本'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('紧急停用'),
|
||||
detail: t('发现质量或安全问题时的止血开关'),
|
||||
points: [t('点「紧急停用」该技能立即对全企业失效,点「恢复」重新生效')],
|
||||
},
|
||||
{
|
||||
title: t('企业展示定制'),
|
||||
detail: t('把平台技能翻译成员工看得懂的说法'),
|
||||
points: [
|
||||
t('可设置企业内展示名称、中文说明与使用边界'),
|
||||
t('成员在「我的技能」里看到的就是这里配置的内容'),
|
||||
],
|
||||
},
|
||||
{
|
||||
title: t('内容派生'),
|
||||
detail: t('基于平台版本创建带企业知识的派生版本'),
|
||||
points: [
|
||||
t('派生版本的正文需要自行撰写——平台不会下发原始正文'),
|
||||
t(
|
||||
'流程:创建派生 → 执行模型实测 → 领取审核 → 审核通过 → 设为企业版本',
|
||||
),
|
||||
t('模型实测会真实调用所选模型,响应自动留档为审核证据'),
|
||||
],
|
||||
},
|
||||
],
|
||||
faq: [
|
||||
{
|
||||
q: t('技能库为空?'),
|
||||
a: t('点页面右上角「引入技能」,从平台目录中为企业启用'),
|
||||
},
|
||||
{
|
||||
q: t('已启用但成员看不到?'),
|
||||
a: t('还需要在「分发与锁定」创建分发策略覆盖到目标成员'),
|
||||
},
|
||||
],
|
||||
});
|
||||
return (
|
||||
<main className='org-skills-page'>
|
||||
<header className='org-skills-hero'>
|
||||
<div>
|
||||
<Title heading={3}>{t('企业技能库')}</Title>
|
||||
<Paragraph>
|
||||
{t('控制启用状态、版本锁定、紧急停用和企业展示定制。')}
|
||||
</Paragraph>
|
||||
</div>
|
||||
<div className='org-skills-hero-actions'>
|
||||
{/* 页内引入:对平台超管这是唯一可用入口(超市页解析不出其企业上下文);
|
||||
对普通管理员是就地快速添加。数据复用已加载的 catalog,不额外发请求。 */}
|
||||
{canImport ? (
|
||||
<Button theme='solid' onClick={() => setImportOpen(true)}>
|
||||
{t('引入技能')}
|
||||
</Button>
|
||||
) : null}
|
||||
{/* 浏览完整平台目录(分页/搜索/分类)仍去超市页;超管在那里没有企业
|
||||
上下文,故不对其展示,避免点过去发现无法启用。 */}
|
||||
{selfEnableAllowed && !isPlatformSuperAdmin ? (
|
||||
<Button
|
||||
theme='borderless'
|
||||
onClick={() => navigate('/skill-market')}
|
||||
>
|
||||
{t('浏览技能超市')}
|
||||
</Button>
|
||||
) : null}
|
||||
<PageGuideTrigger guide={guide} />
|
||||
</div>
|
||||
</header>
|
||||
<PageGuideDrawer guide={guide} />
|
||||
{!loaded ? (
|
||||
<SkillEmptyGuide title={t('正在加载企业技能库')} />
|
||||
) : loadError.library ? (
|
||||
// 错误态必须与"确实为空"分开:否则接口 5xx 会被渲染成
|
||||
// "企业技能库为空 / 点引入技能",把硬故障说成正常状态。
|
||||
<SkillEmptyGuide
|
||||
title={t('企业技能库加载失败')}
|
||||
description={loadError.library}
|
||||
actionLabel={t('重试')}
|
||||
onAction={() => void load()}
|
||||
/>
|
||||
) : items.length === 0 ? (
|
||||
<SkillEmptyGuide
|
||||
title={t('企业技能库为空')}
|
||||
description={
|
||||
canImport
|
||||
? t('点「引入技能」从平台目录中为企业启用 Skill。')
|
||||
: t('平台已关闭自助启用,请联系平台管理员为企业启用 Skill。')
|
||||
}
|
||||
actionLabel={canImport ? t('引入技能') : undefined}
|
||||
onAction={canImport ? () => setImportOpen(true) : undefined}
|
||||
/>
|
||||
) : (
|
||||
<section className='org-skill-library-list'>
|
||||
{items.map((policy) => (
|
||||
<OrgPanel
|
||||
key={policy.id}
|
||||
title={
|
||||
catalog
|
||||
.get(policy.skill_id)
|
||||
?.locales?.find((item) => item.locale === 'zh')?.name ||
|
||||
`Skill #${policy.skill_id}`
|
||||
}
|
||||
actions={
|
||||
<SkillStatusTag
|
||||
status={
|
||||
policy.emergency_stopped
|
||||
? 'quarantined'
|
||||
: policy.enabled
|
||||
? 'published'
|
||||
: 'withdrawn'
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className='org-skill-policy-row'>
|
||||
<label>
|
||||
<Text>{t('启用')}</Text>
|
||||
<Switch
|
||||
checked={policy.enabled}
|
||||
onChange={(enabled) => configure(policy, { enabled })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<Text>{t('版本策略')}</Text>
|
||||
<Select
|
||||
value={policy.version_policy || 'follow'}
|
||||
onChange={(version_policy) =>
|
||||
configure(policy, {
|
||||
version_policy,
|
||||
locked_version_id:
|
||||
version_policy === 'locked'
|
||||
? catalog.get(policy.skill_id)?.version?.id || 0
|
||||
: 0,
|
||||
})
|
||||
}
|
||||
>
|
||||
<Select.Option value='follow'>
|
||||
{t('跟随平台升级')}
|
||||
</Select.Option>
|
||||
<Select.Option value='locked'>
|
||||
{t('锁定版本')}
|
||||
</Select.Option>
|
||||
</Select>
|
||||
</label>
|
||||
<Button
|
||||
type='danger'
|
||||
onClick={() =>
|
||||
configure(policy, {
|
||||
emergency_stopped: !policy.emergency_stopped,
|
||||
})
|
||||
}
|
||||
>
|
||||
{policy.emergency_stopped ? t('恢复') : t('紧急停用')}
|
||||
</Button>
|
||||
<Button onClick={() => openCustomization(policy)}>
|
||||
{t('企业定制')}
|
||||
</Button>
|
||||
<Button onClick={() => void openDerived(policy)}>
|
||||
{t('内容派生')}
|
||||
</Button>
|
||||
</div>
|
||||
</OrgPanel>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
<Modal
|
||||
title={t('企业展示定制')}
|
||||
visible={!!selected}
|
||||
onCancel={() => setSelected(null)}
|
||||
onOk={saveCustomization}
|
||||
>
|
||||
<div className='org-skill-form'>
|
||||
<label>
|
||||
<Text>{t('展示名称')}</Text>
|
||||
<TextArea
|
||||
value={form.display_name}
|
||||
onChange={(value) =>
|
||||
setForm((old) => ({ ...old, display_name: value }))
|
||||
}
|
||||
autosize
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<Text>{t('中文说明')}</Text>
|
||||
<TextArea
|
||||
value={form.description_zh}
|
||||
onChange={(value) =>
|
||||
setForm((old) => ({ ...old, description_zh: value }))
|
||||
}
|
||||
autosize
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<Text>{t('使用边界')}</Text>
|
||||
<TextArea
|
||||
value={form.usage_boundary}
|
||||
onChange={(value) =>
|
||||
setForm((old) => ({ ...old, usage_boundary: value }))
|
||||
}
|
||||
autosize
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<Text>{t('已审核派生版本 ID')}</Text>
|
||||
<InputNumber
|
||||
min={0}
|
||||
value={form.derived_version_id}
|
||||
onChange={(derived_version_id) =>
|
||||
setForm((old) => ({ ...old, derived_version_id }))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
<Modal
|
||||
title={t('创建企业派生版本')}
|
||||
visible={!!derivePolicy}
|
||||
onCancel={() => setDerivePolicy(null)}
|
||||
onOk={saveDerived}
|
||||
width={760}
|
||||
>
|
||||
<div className='org-skill-form'>
|
||||
{derivedVersions.map((item) => (
|
||||
<div key={item.version.id} className='org-skill-policy-row'>
|
||||
<Text>v{item.version.version_no}</Text>
|
||||
<Tag>{item.runtime?.conclusion || 'scan_pending'}</Tag>
|
||||
<Tag>{item.review?.status || 'pending'}</Tag>
|
||||
<Button
|
||||
size='small'
|
||||
onClick={() => {
|
||||
// Reset the captured inputs on every open: the Form fields
|
||||
// remount empty, so stale state from a previous version's
|
||||
// test must never be silently submitted for this one.
|
||||
setEvidence({ model: '', input: '' });
|
||||
setEvidenceVersion(item.version.id);
|
||||
}}
|
||||
>
|
||||
{t('执行模型实测')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={item.review?.status !== 'pending'}
|
||||
onClick={() =>
|
||||
void derivedAction(item.version.id, 'review/start')
|
||||
}
|
||||
>
|
||||
{t('领取审核')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={item.review?.status !== 'reviewing'}
|
||||
onClick={() =>
|
||||
void derivedAction(item.version.id, 'review/decision', {
|
||||
approved: true,
|
||||
conclusion: { decision: 'approved' },
|
||||
})
|
||||
}
|
||||
>
|
||||
{t('审核通过')}
|
||||
</Button>
|
||||
<Button
|
||||
size='small'
|
||||
disabled={item.review?.status !== 'approved'}
|
||||
onClick={() => {
|
||||
openCustomization(derivePolicy, item.version.id);
|
||||
setDerivePolicy(null);
|
||||
}}
|
||||
>
|
||||
{t('设为企业版本')}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{[
|
||||
'name_zh',
|
||||
'name_en',
|
||||
'description_zh',
|
||||
'description_en',
|
||||
'triggers_zh',
|
||||
'triggers_en',
|
||||
'scenarios_zh',
|
||||
'scenarios_en',
|
||||
'compact_constraint_zh',
|
||||
'compact_constraint_en',
|
||||
'change_statement',
|
||||
].map((field) => (
|
||||
<label key={field}>
|
||||
<Text>{field}</Text>
|
||||
<TextArea
|
||||
value={deriveForm[field]}
|
||||
onChange={(value) =>
|
||||
setDeriveForm((old) => ({ ...old, [field]: value }))
|
||||
}
|
||||
autosize
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<label>
|
||||
<Text>body</Text>
|
||||
<TextArea
|
||||
value={deriveForm.body}
|
||||
onChange={(value) =>
|
||||
setDeriveForm((old) => ({ ...old, body: value }))
|
||||
}
|
||||
placeholder={t(
|
||||
'平台正文不会同步到企业侧,请在此完整撰写派生版本的正文内容',
|
||||
)}
|
||||
autosize={{ minRows: 10 }}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</Modal>
|
||||
<Modal
|
||||
title={t('执行真实模型测试')}
|
||||
visible={!!evidenceVersion}
|
||||
onCancel={() => setEvidenceVersion(null)}
|
||||
onOk={recordDerivedEvidence}
|
||||
>
|
||||
{/* Plain controlled inputs: Semi Form fields keep their own state and
|
||||
ignore the value prop, which previously let stale state diverge
|
||||
from what the user saw on screen. */}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<Input
|
||||
placeholder={t('模型')}
|
||||
value={evidence.model}
|
||||
onChange={(model) => setEvidence((old) => ({ ...old, model }))}
|
||||
/>
|
||||
<TextArea
|
||||
placeholder={t('测试输入')}
|
||||
value={evidence.input}
|
||||
onChange={(input) => setEvidence((old) => ({ ...old, input }))}
|
||||
/>
|
||||
<Paragraph type='tertiary'>
|
||||
{t(
|
||||
'提交后将实际调用所选模型执行该版本正文,真实响应自动落库为审核证据。',
|
||||
)}
|
||||
</Paragraph>
|
||||
</div>
|
||||
</Modal>
|
||||
<SideSheet
|
||||
title={t('引入技能')}
|
||||
visible={importOpen}
|
||||
onCancel={() => {
|
||||
setImportOpen(false);
|
||||
setImportKeyword('');
|
||||
}}
|
||||
width={560}
|
||||
className='org-sidesheet'
|
||||
>
|
||||
<div className='org-skill-import'>
|
||||
<Paragraph type='tertiary'>
|
||||
{t(
|
||||
'从平台已审核的技能目录中为本企业启用。启用后还需在「分发与锁定」建策略,成员才可用。',
|
||||
)}
|
||||
</Paragraph>
|
||||
<Input
|
||||
value={importKeyword}
|
||||
onChange={setImportKeyword}
|
||||
prefix={<Search size={15} />}
|
||||
placeholder={t('搜索技能名称或标识')}
|
||||
showClear
|
||||
/>
|
||||
{!loaded ? (
|
||||
<Empty title={t('正在加载平台目录')} />
|
||||
) : loadError.catalog ? (
|
||||
// 同上:目录接口失败不能显示成"平台暂无可用技能"。
|
||||
<Empty
|
||||
title={t('平台目录加载失败')}
|
||||
description={loadError.catalog}
|
||||
/>
|
||||
) : importCandidates.length === 0 ? (
|
||||
<Empty
|
||||
title={
|
||||
catalog.size === 0
|
||||
? t('平台目录暂无可用技能')
|
||||
: importKeyword.trim()
|
||||
? t('没有匹配的技能')
|
||||
: t('平台目录中的技能都已在企业技能库中')
|
||||
}
|
||||
description={
|
||||
catalog.size === 0
|
||||
? t('平台审核通过的技能会出现在这里,稍后再来看看。')
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<ul className='org-skill-import-list'>
|
||||
{importCandidates.map((item) => (
|
||||
<li key={item.definition.id}>
|
||||
<div className='org-skill-import-main'>
|
||||
<Text strong>{catalogName(item)}</Text>
|
||||
<Text type='tertiary' size='small'>
|
||||
{item.definition?.canonical_id} · v
|
||||
{item.version?.version_no}
|
||||
</Text>
|
||||
</div>
|
||||
{/* 合规徽章与启用按钮同排:启用是留审计的治理写入,
|
||||
许可证决策与运行时安全结论必须在决策点可见。 */}
|
||||
<div className='org-skill-import-actions'>
|
||||
<LicenseBadge
|
||||
expression={item.license?.expression}
|
||||
decision={item.license?.decision}
|
||||
/>
|
||||
<RiskBadge conclusion={item.runtime?.conclusion} />
|
||||
<Button
|
||||
size='small'
|
||||
theme='solid'
|
||||
loading={importingId === item.definition.id}
|
||||
onClick={() => void importSkill(item.definition.id)}
|
||||
>
|
||||
{t('启用')}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</SideSheet>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgSkillLibrary;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,630 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { timestamp2string } from '../../helpers/utils';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Button,
|
||||
Tag,
|
||||
Progress,
|
||||
Form,
|
||||
Toast,
|
||||
Empty,
|
||||
Spin,
|
||||
Typography,
|
||||
} from '@douyinfe/semi-ui';
|
||||
import {
|
||||
Wallet,
|
||||
Key,
|
||||
FileClock,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Pencil,
|
||||
Clock,
|
||||
TrendingUp,
|
||||
Coins,
|
||||
KeyRound,
|
||||
} from 'lucide-react';
|
||||
import { API } from '../../helpers/api';
|
||||
import { showError } from '../../helpers';
|
||||
import {
|
||||
renderQuota,
|
||||
getCurrencyConfig,
|
||||
displayAmountToQuota,
|
||||
} from '../../helpers/render';
|
||||
import OrgHero from './components/OrgHero';
|
||||
import OrgModal from './components/OrgModal';
|
||||
import OrgNicknameModal from './components/OrgNicknameModal';
|
||||
import OrgPasswordModal from './components/OrgPasswordModal';
|
||||
import { orgStatusColor } from './components/orgStatus';
|
||||
import OrgPanel from './components/OrgPanel';
|
||||
import StatCard from './components/OrgStatCard';
|
||||
|
||||
// 时段问候(工作台 hero 签名区的 eyebrow)
|
||||
const getGreeting = (t) => {
|
||||
const hour = new Date().getHours();
|
||||
if (hour < 6) return t('凌晨好');
|
||||
if (hour < 12) return t('早上好');
|
||||
if (hour < 14) return t('中午好');
|
||||
if (hour < 18) return t('下午好');
|
||||
return t('晚上好');
|
||||
};
|
||||
|
||||
const { Text, Title } = Typography;
|
||||
const getOrgHeaders = (orgId) => ({ 'X-Org-Id': String(orgId) });
|
||||
const PERIODIC_QUOTA_PERIODS = new Set(['daily', 'weekly', 'monthly']);
|
||||
|
||||
const isPeriodicQuotaPeriod = (period) => PERIODIC_QUOTA_PERIODS.has(period);
|
||||
const safeQuotaNumber = (value) => Math.max(0, Number(value || 0));
|
||||
|
||||
const quotaPeriodResetHint = (t, period) => {
|
||||
switch (period) {
|
||||
case 'daily':
|
||||
return t('每日 00:00 重置(企业时区)');
|
||||
case 'weekly':
|
||||
return t('每周一 00:00 重置(企业时区)');
|
||||
case 'monthly':
|
||||
return t('自然月:每月 1 日 00:00 重置');
|
||||
default:
|
||||
return t('按周期重置');
|
||||
}
|
||||
};
|
||||
|
||||
const quotaPeriodLimitLabel = (t, period) => {
|
||||
switch (period) {
|
||||
case 'daily':
|
||||
return t('每日个人上限');
|
||||
case 'weekly':
|
||||
return t('每周个人上限');
|
||||
case 'monthly':
|
||||
return t('每月个人上限');
|
||||
default:
|
||||
return t('个人终身上限');
|
||||
}
|
||||
};
|
||||
|
||||
const roleLabel = (t, role) =>
|
||||
role === 'owner'
|
||||
? t('所有者')
|
||||
: role === 'admin'
|
||||
? t('管理员')
|
||||
: role === 'super_admin'
|
||||
? t('超级管理员')
|
||||
: t('成员');
|
||||
|
||||
const reqStatusTag = (t, status) => {
|
||||
const map = {
|
||||
pending: { text: t('待审批') },
|
||||
approved: { text: t('已通过') },
|
||||
rejected: { text: t('已拒绝') },
|
||||
canceled: { text: t('已取消') },
|
||||
expired: { text: t('已过期') },
|
||||
};
|
||||
const s = map[status] || { text: status };
|
||||
return <Tag color={orgStatusColor(status)}>{s.text}</Tag>;
|
||||
};
|
||||
|
||||
const isFeatureEnabled = (flags, key) => {
|
||||
const value = flags?.[key];
|
||||
return value === true || value === 'true' || value === '1' || value === 1;
|
||||
};
|
||||
|
||||
// 用量趋势小块:窗口标题 + 消耗 + 请求数
|
||||
const UsageBlock = ({ t, title, data }) => (
|
||||
<div className='flex-1 min-w-[140px] rounded-lg border border-[var(--border-subtle)] bg-[var(--surface-card)] px-4 py-3'>
|
||||
<div className='text-xs font-medium text-gray-500 dark:text-gray-400 mb-1'>
|
||||
{title}
|
||||
</div>
|
||||
<div className='text-lg font-semibold tabular-nums text-[var(--text-primary)]'>
|
||||
{renderQuota(data?.quota || 0, 2)}
|
||||
</div>
|
||||
<div className='text-xs text-gray-500 mt-0.5'>
|
||||
{t('请求数')} {data?.requests || 0} · {t('Token 总量')}{' '}
|
||||
{data?.tokens || 0}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// 企业工作台:员工自助门户(§36.1)——个人额度/用量统计/令牌/申请。
|
||||
const OrgWorkbench = ({ orgId, orgRole, featureFlags }) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [summary, setSummary] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [projects, setProjects] = useState([]);
|
||||
const [reqModal, setReqModal] = useState(false);
|
||||
const [formApi, setFormApi] = useState(null);
|
||||
const [nickModal, setNickModal] = useState(false);
|
||||
// 自助改密(方案 §12.8)
|
||||
const [pwdModal, setPwdModal] = useState(false);
|
||||
const [approvers, setApprovers] = useState([]);
|
||||
|
||||
const approvalEnabled = isFeatureEnabled(featureFlags, 'approval');
|
||||
const projectEnabled = isFeatureEnabled(featureFlags, 'project');
|
||||
const role = orgRole || summary?.member?.role;
|
||||
|
||||
const fetchSummary = useCallback(
|
||||
async (silent = false) => {
|
||||
if (!orgId) return;
|
||||
if (!silent) setLoading(true);
|
||||
try {
|
||||
const res = await API.get('/api/org/me/summary', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) {
|
||||
setSummary(res.data.data);
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
} finally {
|
||||
if (!silent) setLoading(false);
|
||||
}
|
||||
},
|
||||
[orgId],
|
||||
);
|
||||
|
||||
const fetchProjects = useCallback(async () => {
|
||||
if (!orgId || !projectEnabled) {
|
||||
setProjects([]);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await API.get('/api/org/project', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) setProjects(res.data.data || []);
|
||||
} catch {
|
||||
/* 忽略:提额申请仍可选部门 */
|
||||
}
|
||||
}, [orgId, projectEnabled]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSummary();
|
||||
fetchProjects();
|
||||
}, [fetchSummary, fetchProjects]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!orgId) return undefined;
|
||||
|
||||
let lastRefreshAt = 0;
|
||||
const refreshSilently = () => {
|
||||
const now = Date.now();
|
||||
if (now - lastRefreshAt < 5000) return;
|
||||
lastRefreshAt = now;
|
||||
fetchSummary(true);
|
||||
};
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
refreshSilently();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('focus', refreshSilently);
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
const timer = window.setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
refreshSilently();
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('focus', refreshSilently);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [orgId, fetchSummary]);
|
||||
|
||||
const quotaLimit = safeQuotaNumber(summary?.my_quota?.quota_limit);
|
||||
const usedQuota = safeQuotaNumber(summary?.my_quota?.used_quota);
|
||||
const totalUsedQuota = safeQuotaNumber(
|
||||
summary?.my_quota?.total_used_quota ?? usedQuota,
|
||||
);
|
||||
const quotaPeriod = summary?.my_quota?.quota_period || 'none';
|
||||
const resetSource = summary?.reset_source || '';
|
||||
const resetAt = safeQuotaNumber(summary?.reset_at);
|
||||
const usage = summary?.usage || {};
|
||||
const quotaIsPeriodic = isPeriodicQuotaPeriod(quotaPeriod);
|
||||
const quotaResetHint = quotaPeriodResetHint(t, quotaPeriod);
|
||||
|
||||
const quotaPercent = useMemo(() => {
|
||||
if (!quotaLimit || quotaLimit <= 0) return 0;
|
||||
return Math.min(100, Math.round((usedQuota / quotaLimit) * 100));
|
||||
}, [quotaLimit, usedQuota]);
|
||||
|
||||
// 可用额度:有个人上限时 = 上限-已用;无个人上限时不展示整个企业池数字
|
||||
// (会被成员误读为「我的额度」),仅提示从共享池扣减。
|
||||
const availableDisplay = useMemo(() => {
|
||||
if (quotaLimit > 0) {
|
||||
return renderQuota(Math.max(0, quotaLimit - usedQuota), 2);
|
||||
}
|
||||
return t('共享企业池');
|
||||
}, [quotaLimit, usedQuota, t]);
|
||||
|
||||
const availableHint =
|
||||
quotaLimit > 0
|
||||
? quotaIsPeriodic
|
||||
? t('当前周期个人额度剩余')
|
||||
: t('个人额度上限内剩余')
|
||||
: t('未设个人上限,从企业统一额度池扣减');
|
||||
|
||||
const quotaUsageLabel = quotaIsPeriodic
|
||||
? t('本周期已用额度')
|
||||
: t('总已用额度');
|
||||
const quotaLimitLabel = quotaPeriodLimitLabel(t, quotaPeriod);
|
||||
const quotaLimitHint =
|
||||
quotaLimit > 0
|
||||
? quotaIsPeriodic
|
||||
? `${quotaLimitLabel} ${renderQuota(quotaLimit, 2)} · ${quotaResetHint}`
|
||||
: `${quotaLimitLabel} ${renderQuota(quotaLimit, 2)}`
|
||||
: t('未设个人上限');
|
||||
const resetHint =
|
||||
resetAt > 0
|
||||
? resetSource === 'member_quota'
|
||||
? quotaResetHint
|
||||
: resetSource === 'budget'
|
||||
? t('按预算周期重置')
|
||||
: t('按周期重置')
|
||||
: quotaIsPeriodic
|
||||
? quotaResetHint
|
||||
: t('无重置周期');
|
||||
const resetValue =
|
||||
resetAt > 0
|
||||
? timestamp2string(resetAt)
|
||||
: quotaIsPeriodic
|
||||
? t('待初始化')
|
||||
: t('不重置');
|
||||
|
||||
// 提额输入单位:跟随站点展示货币(TOKENS 模式下为原始额度单位)。
|
||||
// 每次 render 重新读取,不能用空依赖 memo:货币配置由 /api/status 异步写入
|
||||
// localStorage,冻结快照会导致 label 单位与提交时的换算口径脱节
|
||||
const deltaCurrency = getCurrencyConfig();
|
||||
const deltaIsToken = deltaCurrency.type === 'TOKENS';
|
||||
const deltaLabel = deltaIsToken
|
||||
? t('提额数量(额度单位)')
|
||||
: `${t('提额数量')}(${deltaCurrency.symbol})`;
|
||||
|
||||
// 提额申请目标选项:优先申请个人额度;部门/项目属于预算额度,周期可能不同。
|
||||
const subjectOptions = useMemo(() => {
|
||||
const opts = [];
|
||||
if (summary?.member?.id && quotaLimit > 0) {
|
||||
opts.push({
|
||||
label: `${t('我的个人额度')}(${quotaLimitLabel})`,
|
||||
value: `member:${summary.member.id}`,
|
||||
});
|
||||
}
|
||||
if (summary?.member?.department_id) {
|
||||
opts.push({
|
||||
label: `${t('部门')}:${summary.member.department_name || '#' + summary.member.department_id}`,
|
||||
value: `department:${summary.member.department_id}`,
|
||||
});
|
||||
}
|
||||
projects.forEach((p) => {
|
||||
opts.push({ label: `${t('项目')}:${p.name}`, value: `project:${p.id}` });
|
||||
});
|
||||
return opts;
|
||||
}, [summary, projects, quotaLimit, quotaLimitLabel, t]);
|
||||
|
||||
const openReqModal = async () => {
|
||||
setReqModal(true);
|
||||
try {
|
||||
const res = await API.get('/api/org/me/approvers', {
|
||||
headers: getOrgHeaders(orgId),
|
||||
});
|
||||
if (res.data.success) setApprovers(res.data.data?.approvers || []);
|
||||
} catch {
|
||||
/* 忽略:无上级候选时仅保留「企业管理员」默认项 */
|
||||
}
|
||||
};
|
||||
|
||||
const submitRequest = async () => {
|
||||
if (!formApi) return;
|
||||
let values;
|
||||
try {
|
||||
values = await formApi.validate();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const [subject_type, subject_id] = String(values.subject).split(':');
|
||||
try {
|
||||
const res = await API.post(
|
||||
'/api/org/requests',
|
||||
{
|
||||
request_type: 'quota',
|
||||
subject_type,
|
||||
subject_id: parseInt(subject_id, 10),
|
||||
cycle_quota_delta: displayAmountToQuota(values.delta),
|
||||
approver_member_id: values.approver || 0,
|
||||
reason: values.reason || '',
|
||||
},
|
||||
{ headers: getOrgHeaders(orgId) },
|
||||
);
|
||||
if (res.data.success) {
|
||||
Toast.success(t('提额申请已提交,等待管理员审批'));
|
||||
setReqModal(false);
|
||||
fetchSummary();
|
||||
} else {
|
||||
showError(res.data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
showError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const openNickModal = () => {
|
||||
setNickModal(true);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className='flex items-center justify-center h-full'>
|
||||
<Spin size='large' />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const memberName =
|
||||
summary?.member?.display_name || summary?.member?.username || '';
|
||||
|
||||
return (
|
||||
<div className='org-stagger p-4 sm:p-6 lg:p-8 space-y-5'>
|
||||
{/* 签名时刻:hero 问候区(每页至多一个签名渐变区,见方案 A+ 冲击力护栏) */}
|
||||
<OrgHero
|
||||
eyebrow={`${getGreeting(t)}${memberName ? ',' + memberName : ''}`}
|
||||
title={summary?.organization?.name || t('企业工作台')}
|
||||
subtitle={`${t('个人工作台')} · ${t('我的角色')}:${roleLabel(t, role)}${summary?.member?.department_name ? ' · ' + summary.member.department_name : ''}`}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<Pencil size={14} />}
|
||||
onClick={openNickModal}
|
||||
>
|
||||
{t('编辑昵称')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<KeyRound size={14} />}
|
||||
onClick={() => setPwdModal(true)}
|
||||
>
|
||||
{t('修改密码')}
|
||||
</Button>
|
||||
<Button
|
||||
theme='light'
|
||||
icon={<RefreshCw size={14} />}
|
||||
loading={loading}
|
||||
onClick={() => {
|
||||
fetchSummary();
|
||||
fetchProjects();
|
||||
}}
|
||||
>
|
||||
{t('刷新')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* 关键指标卡组 */}
|
||||
<div className='grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4'>
|
||||
<StatCard
|
||||
icon={Coins}
|
||||
label={quotaUsageLabel}
|
||||
value={renderQuota(usedQuota, 2)}
|
||||
hint={quotaLimitHint}
|
||||
/>
|
||||
<StatCard
|
||||
icon={Wallet}
|
||||
label={t('可用额度')}
|
||||
value={availableDisplay}
|
||||
hint={availableHint}
|
||||
/>
|
||||
<StatCard
|
||||
icon={Clock}
|
||||
label={t('额度重置时间')}
|
||||
value={resetValue}
|
||||
hint={resetHint}
|
||||
/>
|
||||
<StatCard
|
||||
icon={FileClock}
|
||||
label={t('待处理申请')}
|
||||
countTo={summary?.pending_request_count ?? 0}
|
||||
hint={t('我提交的提额申请')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 我的额度进度 + 我的令牌 */}
|
||||
<div className='grid grid-cols-1 md:grid-cols-3 gap-4'>
|
||||
<OrgPanel className='md:col-span-2'>
|
||||
<div className='flex items-center gap-2 mb-3'>
|
||||
<Wallet size={18} className='text-brand-deep' />
|
||||
<Text strong>{t('我的额度')}</Text>
|
||||
</div>
|
||||
{quotaLimit > 0 ? (
|
||||
<>
|
||||
<Progress
|
||||
percent={quotaPercent}
|
||||
stroke={
|
||||
quotaPercent >= 90 ? 'var(--semi-color-danger)' : undefined
|
||||
}
|
||||
style={{ marginBottom: 8 }}
|
||||
/>
|
||||
<Text type='tertiary' size='small'>
|
||||
{quotaIsPeriodic ? t('本周期已用') : t('已用')}{' '}
|
||||
{renderQuota(usedQuota, 2)} / {renderQuota(quotaLimit, 2)}
|
||||
{quotaIsPeriodic
|
||||
? ` · ${t('累计已用')} ${renderQuota(totalUsedQuota, 2)}`
|
||||
: ''}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('未设个人上限,使用企业统一额度池')}
|
||||
</Text>
|
||||
)}
|
||||
<div className='mt-2'>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t('实际可用还受所在部门/项目及企业预算约束。')}
|
||||
</Text>
|
||||
</div>
|
||||
<div className='mt-3'>
|
||||
<Button
|
||||
size='small'
|
||||
icon={<Plus size={14} />}
|
||||
onClick={openReqModal}
|
||||
disabled={!approvalEnabled || subjectOptions.length === 0}
|
||||
>
|
||||
{t('申请提额')}
|
||||
</Button>
|
||||
</div>
|
||||
</OrgPanel>
|
||||
|
||||
<OrgPanel>
|
||||
<div className='flex items-center gap-2 mb-3'>
|
||||
<Key size={18} className='text-brand-deep' />
|
||||
<Text strong>{t('我的令牌')}</Text>
|
||||
</div>
|
||||
<Title heading={2} style={{ margin: '4px 0' }}>
|
||||
{summary?.token_count ?? 0}
|
||||
</Title>
|
||||
<Button
|
||||
size='small'
|
||||
theme='light'
|
||||
onClick={() => navigate('/org/tokens')}
|
||||
>
|
||||
{t('管理令牌')}
|
||||
</Button>
|
||||
</OrgPanel>
|
||||
</div>
|
||||
|
||||
{/* 个人用量趋势 */}
|
||||
<OrgPanel>
|
||||
<div className='flex items-center gap-2 mb-3'>
|
||||
<TrendingUp size={18} className='text-brand-deep' />
|
||||
<Text strong>{t('个人用量趋势')}</Text>
|
||||
</div>
|
||||
<div className='flex flex-wrap gap-4'>
|
||||
<UsageBlock t={t} title={t('今日')} data={usage.today} />
|
||||
<UsageBlock t={t} title={t('近 7 天')} data={usage.last7d} />
|
||||
<UsageBlock t={t} title={t('近 30 天')} data={usage.last30d} />
|
||||
<UsageBlock t={t} title={t('累计')} data={usage.total} />
|
||||
</div>
|
||||
</OrgPanel>
|
||||
|
||||
{/* 最近申请 */}
|
||||
<OrgPanel>
|
||||
<div className='flex items-center gap-2 mb-3'>
|
||||
<FileClock size={18} className='text-brand-deep' />
|
||||
<Text strong>{t('最近申请')}</Text>
|
||||
</div>
|
||||
{summary?.recent_requests?.length ? (
|
||||
<div className='flex flex-col divide-y divide-[var(--semi-color-border)]'>
|
||||
{summary.recent_requests.map((r) => (
|
||||
<div
|
||||
key={r.id}
|
||||
className='flex items-center justify-between py-2.5'
|
||||
>
|
||||
<div>
|
||||
<Text>
|
||||
{r.request_type === 'quota'
|
||||
? t('提额申请')
|
||||
: r.request_type}
|
||||
{r.reason ? ` · ${r.reason}` : ''}
|
||||
</Text>
|
||||
<div>
|
||||
<Text type='tertiary' size='small'>
|
||||
{r.created_at ? timestamp2string(r.created_at) : ''}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
{reqStatusTag(t, r.status)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Empty description={t('暂无申请记录')} />
|
||||
)}
|
||||
</OrgPanel>
|
||||
|
||||
{/* 提额申请弹窗 */}
|
||||
<OrgModal
|
||||
title={t('申请提额')}
|
||||
visible={reqModal}
|
||||
onOk={submitRequest}
|
||||
onCancel={() => setReqModal(false)}
|
||||
okText={t('提交申请')}
|
||||
cancelText={t('取消')}
|
||||
>
|
||||
<Form getFormApi={setFormApi}>
|
||||
<Form.Select
|
||||
field='subject'
|
||||
label={t('提额对象')}
|
||||
initValue={subjectOptions[0]?.value}
|
||||
optionList={subjectOptions}
|
||||
rules={[{ required: true, message: t('请选择提额对象') }]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Text type='tertiary' size='small'>
|
||||
{t(
|
||||
'个人额度用于解除您自己的使用上限;部门/项目额度属于预算上限,可能有独立周期。',
|
||||
)}
|
||||
</Text>
|
||||
<Form.InputNumber
|
||||
field='delta'
|
||||
label={deltaLabel}
|
||||
min={deltaIsToken ? 1 : 0.01}
|
||||
precision={deltaIsToken ? 0 : 2}
|
||||
suffix={deltaIsToken ? null : deltaCurrency.symbol}
|
||||
rules={[{ required: true, message: t('请输入提额数量') }]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.Select
|
||||
field='approver'
|
||||
label={t('审批人')}
|
||||
initValue={0}
|
||||
optionList={[
|
||||
{ label: t('企业管理员(默认)'), value: 0 },
|
||||
...approvers.map((a) => ({
|
||||
label: `${t('上级')}:${a.name}`,
|
||||
value: a.member_id,
|
||||
})),
|
||||
]}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Form.TextArea field='reason' label={t('申请理由')} maxCount={200} />
|
||||
</Form>
|
||||
</OrgModal>
|
||||
|
||||
{/* 编辑昵称弹窗(共享组件,与个人设置页共用) */}
|
||||
<OrgNicknameModal
|
||||
visible={nickModal}
|
||||
onClose={() => setNickModal(false)}
|
||||
orgId={orgId}
|
||||
currentName={summary?.member?.display_name || ''}
|
||||
onSuccess={() => fetchSummary()}
|
||||
/>
|
||||
|
||||
{/* 自助改密(方案 §12.8,共享组件) */}
|
||||
<OrgPasswordModal visible={pwdModal} onClose={() => setPwdModal(false)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default OrgWorkbench;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user