Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+650
View File
@@ -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;