feat(org): expose enterprise drawing and task logs

(cherry picked from commit b80afd273c)
This commit is contained in:
qiubaishen
2026-11-06 18:52:10 +08:00
committed by zhanjunhao
parent a075732cb4
commit b0860467d5
9 changed files with 359 additions and 221 deletions
@@ -55,7 +55,6 @@ export const exportTaskLogsPageCsv = (logs, isAdminUser, t) => {
{ key: 'channel_name', title: t('渠道名称') },
]
: []),
{ key: 'platform', title: t('平台') },
{ key: 'action', title: t('类型') },
{
key: 'model',
@@ -35,7 +35,6 @@ import {
Video,
Sparkles,
Timer,
Image as ImageIcon,
ImagePlus,
Coins,
Cpu,
@@ -48,7 +47,6 @@ import {
IMAGE_ACTION_GENERATE,
IMAGE_ACTION_EDIT,
} from '../../../constants/common.constant';
import { CHANNEL_OPTIONS } from '../../../constants/channel.constants';
import { renderQuota } from '../../../helpers';
// 仅保留与下方 COLOR_CONFIG 一一对应的色值,避免 amber/lime/violet/teal/indigo/light-blue
@@ -231,34 +229,6 @@ const renderType = (type, t) => {
);
};
const renderPlatform = (platform, t) => {
let option = CHANNEL_OPTIONS.find(
(opt) => String(opt.value) === String(platform),
);
if (option) {
return (
<CustomTag
icon={Video}
label={option.label}
colorKey={option.color || 'cyan'}
/>
);
}
if (platform === 'suno') {
return <CustomTag icon={Music} label='Suno' colorKey='green' />;
}
if (platform === 'image') {
return <CustomTag icon={ImageIcon} label={t('图片')} colorKey='cyan' />;
}
if (platform === 'video') {
return <CustomTag icon={Video} label={t('视频')} colorKey='blue' />;
}
if (platform === 'mj') {
return <CustomTag icon={Sparkles} label='Midjourney' colorKey='purple' />;
}
return <CustomTag icon={HelpCircle} label={t('未知')} colorKey='grey' />;
};
const renderStatus = (type, t) => {
const statusConfig = {
SUCCESS: { icon: CheckCircle, label: t('成功'), color: 'green' },
@@ -356,12 +326,6 @@ const applyTaskRecordPresentation = (columns, { COLUMN_KEYS }) =>
);
},
};
case COLUMN_KEYS.PLATFORM:
return {
...column,
render: (text, record, index) =>
unwrap(text, record, index)?.props?.label ?? '-',
};
case COLUMN_KEYS.TYPE:
return {
...column,
@@ -429,6 +393,7 @@ export const getTaskLogsColumns = ({
copyText,
openContentModal,
isAdminUser,
isRootUser = false,
openVideoModal,
usageRecordMode = false,
}) => {
@@ -482,14 +447,6 @@ export const getTaskLogsColumns = ({
);
},
},
{
key: COLUMN_KEYS.PLATFORM,
title: t('平台'),
dataIndex: 'platform',
render: (text, record, index) => {
return <div>{renderPlatform(text, t)}</div>;
},
},
{
key: COLUMN_KEYS.TYPE,
title: t('类型'),
@@ -532,10 +489,16 @@ export const getTaskLogsColumns = ({
return (
<Typography.Text
ellipsis={{ showTooltip: true }}
onClick={() => {
openContentModal(JSON.stringify(record, null, 2));
}}
className='cursor-pointer hover:text-blue-500 dark:hover:text-blue-400 transition-colors font-mono text-xs'
onClick={
isRootUser
? () => openContentModal(JSON.stringify(record, null, 2))
: undefined
}
className={
isRootUser
? 'cursor-pointer hover:text-blue-500 dark:hover:text-blue-400 transition-colors font-mono text-xs'
: 'font-mono text-xs'
}
>
{text}
</Typography.Text>
@@ -51,6 +51,7 @@ const TaskLogsFilters = ({
isAdminUser,
getFreshInitValues,
usageRecordMode = false,
hideDateRange = false,
t,
}) => {
const SearchIcon = Search;
@@ -268,25 +269,27 @@ const TaskLogsFilters = ({
{/* 搜索字段网格 */}
<div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3'>
{/* 时间选择器 */}
<div className='col-span-1 lg:col-span-2'>
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-500/20 to-blue-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.DatePicker
field='dateRange'
className='w-full'
type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]}
showClear
pure
size='small'
prefix={<InputPrefix icon={Calendar} />}
presets={datePresets}
/>
{/* 时间选择器:企业页复用上方消费记录的已提交时间范围 */}
{!hideDateRange && (
<div className='col-span-1 lg:col-span-2'>
<div className='relative group'>
<div className='absolute -inset-0.5 bg-gradient-to-r from-cyan-500/20 to-blue-500/20 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-300 blur-sm' />
<div className='relative'>
<Form.DatePicker
field='dateRange'
className='w-full'
type='dateTimeRange'
placeholder={[t('开始时间'), t('结束时间')]}
showClear
pure
size='small'
prefix={<InputPrefix icon={Calendar} />}
presets={datePresets}
/>
</div>
</div>
</div>
</div>
)}
{/* 任务 ID */}
<div className='relative group'>
@@ -42,6 +42,7 @@ const TaskLogsTable = (taskLogsData) => {
openContentModal,
openVideoModal,
isAdminUser,
isRootUser,
t,
COLUMN_KEYS,
usageRecordMode = false,
@@ -57,6 +58,7 @@ const TaskLogsTable = (taskLogsData) => {
openVideoModal,
isAdminUser,
usageRecordMode,
isRootUser,
});
}, [
t,
@@ -66,6 +68,7 @@ const TaskLogsTable = (taskLogsData) => {
openVideoModal,
isAdminUser,
usageRecordMode,
isRootUser,
]);
// Filter columns based on visibility settings
+19 -3
View File
@@ -34,8 +34,19 @@ import { useTaskLogsData } from '../../../hooks/task-logs/useTaskLogsData';
import { useIsMobile } from '../../../hooks/common/useIsMobile';
import { createCardProPagination } from '../../../helpers/utils';
const TaskLogsPage = ({ usageRecordMode = false }) => {
const taskLogsData = useTaskLogsData();
const TaskLogsPage = ({
usageRecordMode = false,
organizationMode = false,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision = 0,
}) => {
const taskLogsData = useTaskLogsData({
organizationMode,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision,
});
const isMobile = useIsMobile();
// 与 CardPro 一致:移动端默认收起筛选区,仅视图状态
const [showMobileFilters, setShowMobileFilters] = useState(false);
@@ -167,7 +178,12 @@ const TaskLogsPage = ({ usageRecordMode = false }) => {
statsArea={
<TaskLogsActions {...taskLogsData} logs={taskLogsData.logs} />
}
searchArea={<TaskLogsFilters {...taskLogsData} />}
searchArea={
<TaskLogsFilters
{...taskLogsData}
hideDateRange={taskLogsData.usesSharedDateRange}
/>
}
paginationArea={createCardProPagination({
currentPage: taskLogsData.activePage,
pageSize: taskLogsData.pageSize,
@@ -30,6 +30,7 @@ const ColumnSelectorModal = ({
initDefaultColumns,
COLUMN_KEYS,
isAdminUser,
isRootUser,
copyText,
openContentModal,
t,
@@ -41,6 +42,7 @@ const ColumnSelectorModal = ({
copyText,
openContentModal,
isAdminUser,
isRootUser,
});
// 计算"全选"状态时应忽略的 key:当前角色下不可见的管理员专属列
+63 -23
View File
@@ -24,6 +24,7 @@ import {
API,
copy,
isAdmin,
isRoot,
showError,
showSuccess,
timestamp2string,
@@ -33,7 +34,25 @@ import { resolveColumnVisibility } from '../../helpers/columnVisibility';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useTaskLogsData = () => {
const DEFAULT_TASK_RANGE_DAYS = 7;
const toUnixTimestamp = (value) => {
if (typeof value === 'number' && Number.isFinite(value)) {
return Math.floor(value);
}
if (value instanceof Date) {
return Math.floor(value.getTime() / 1000);
}
const parsed = Date.parse(value);
return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : NaN;
};
export const useTaskLogsData = ({
organizationMode = false,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision = 0,
} = {}) => {
const { t } = useTranslation();
// Define column keys for selection
@@ -44,7 +63,6 @@ export const useTaskLogsData = () => {
FINISH_TIME: 'finish_time',
DURATION: 'duration',
CHANNEL: 'channel',
PLATFORM: 'platform',
TYPE: 'type',
MODEL: 'model',
TASK_ID: 'task_id',
@@ -62,11 +80,15 @@ export const useTaskLogsData = () => {
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
// User and admin
const isAdminUser = isAdmin();
const isAdminUser = !organizationMode && isAdmin();
// 任务 ID 详情包含完整任务记录,仅系统超级管理员可查看;企业用户始终不可打开
const isRootUser = !organizationMode && isRoot();
// Role-specific storage key to prevent different roles from overwriting each other
const STORAGE_KEY = isAdminUser
? 'task-logs-table-columns-admin'
: 'task-logs-table-columns-user';
const STORAGE_KEY = organizationMode
? 'task-logs-table-columns-organization'
: isAdminUser
? 'task-logs-table-columns-admin'
: 'task-logs-table-columns-user';
// Modal state
const [isModalOpen, setIsModalOpen] = useState(false);
@@ -82,15 +104,20 @@ export const useTaskLogsData = () => {
// Form state
const [formApi, setFormApi] = useState(null);
// 每次调用都返回"此刻"的默认时间范围,避免长时间驻留页面后
// 点击"重置"仍得到页面加载时的"今日"(跨日 bug)
const usesSharedDateRange =
organizationMode &&
Number.isFinite(Number(sharedStartTimestamp)) &&
Number.isFinite(Number(sharedEndTimestamp));
// 每次调用都返回"此刻"的默认时间范围,默认最近 7 天,避免任务页首屏
// 只查当天而遗漏历史任务;返回 Date 对象以便日期控件正确显示。
const getFreshDateRange = () => {
const now = new Date();
const zeroNow = new Date(now.getFullYear(), now.getMonth(), now.getDate());
return [
timestamp2string(zeroNow.getTime() / 1000),
timestamp2string(now.getTime() / 1000 + 3600),
];
now.setSeconds(0, 0);
const start = new Date(
now.getTime() - DEFAULT_TASK_RANGE_DAYS * 24 * 60 * 60 * 1000,
);
return [start, now];
};
const getFreshInitValues = () => ({
@@ -153,7 +180,6 @@ export const useTaskLogsData = () => {
[COLUMN_KEYS.FINISH_TIME]: true,
[COLUMN_KEYS.DURATION]: true,
[COLUMN_KEYS.CHANNEL]: isAdminUser,
[COLUMN_KEYS.PLATFORM]: true,
[COLUMN_KEYS.TYPE]: true,
[COLUMN_KEYS.MODEL]: true,
[COLUMN_KEYS.TASK_ID]: true,
@@ -206,12 +232,17 @@ export const useTaskLogsData = () => {
// 否则 URL 带的 ?task_id=xxx 在第一次 loadLogs 时会被当成空字符串,导致初始列表不过滤
const formValues = formApi ? formApi.getValues() : formInitValues;
// 处理时间范围:每次调用时取"此刻"的默认值,避免闭包陈旧
// 企业页复用上方已经提交的时间范围;个人/平台任务页使用自己的日期控件。
const [freshStart, freshEnd] = getFreshDateRange();
let start_timestamp = freshStart;
let end_timestamp = freshEnd;
let start_timestamp = usesSharedDateRange
? Number(sharedStartTimestamp)
: freshStart;
let end_timestamp = usesSharedDateRange
? Number(sharedEndTimestamp)
: freshEnd;
if (
!usesSharedDateRange &&
formValues.dateRange &&
Array.isArray(formValues.dateRange) &&
formValues.dateRange.length === 2
@@ -295,8 +326,8 @@ export const useTaskLogsData = () => {
start_timestamp,
end_timestamp,
} = getFormValues();
let localStartTimestamp = parseInt(Date.parse(start_timestamp) / 1000);
let localEndTimestamp = parseInt(Date.parse(end_timestamp) / 1000);
let localStartTimestamp = toUnixTimestamp(start_timestamp);
let localEndTimestamp = toUnixTimestamp(end_timestamp);
// 时间范围校验:起始晚于结束视为非法,避免白发一轮请求并给出提示
if (
Number.isFinite(localStartTimestamp) &&
@@ -324,9 +355,11 @@ export const useTaskLogsData = () => {
// 与使用日志对齐:管理员可按 user_id 过滤任务日志
if (user_id) params.set('user_id', user_id);
}
const url = isAdminUser
? `/api/task/?${params.toString()}`
: `/api/task/self?${params.toString()}`;
const url = organizationMode
? `/api/org/tasks?${params.toString()}`
: isAdminUser
? `/api/task/?${params.toString()}`
: `/api/task/self?${params.toString()}`;
try {
const res = await API.get(url);
// 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出
@@ -411,7 +444,12 @@ export const useTaskLogsData = () => {
parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE;
setPageSize(localPageSize);
loadLogs(1, localPageSize).then();
}, []);
}, [
organizationMode,
sharedStartTimestamp,
sharedEndTimestamp,
sharedFilterRevision,
]);
// 存在进行中的任务时,自动轮询刷新(10s 间隔),无 pending 则停止,避免无谓请求
const loadLogsRef = useRef(loadLogs);
@@ -463,6 +501,8 @@ export const useTaskLogsData = () => {
logCount,
pageSize,
isAdminUser,
isRootUser,
usesSharedDateRange,
// Modal state
isModalOpen,
+146 -129
View File
@@ -47,6 +47,7 @@ import {
import OrgPageHeader from './components/OrgPageHeader';
import { OrgFilterCard, OrgListCard } from './components/OrgListCard';
import OrgModal from './components/OrgModal';
import TaskLogsTable from '../../components/table/task-logs';
import {
API,
showError,
@@ -233,6 +234,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
const [page, setPage] = useState(1);
const pageSize = 20;
const [activeTab, setActiveTab] = useState('logs');
const [taskFilterRevision, setTaskFilterRevision] = useState(0);
const isAdmin =
orgRole === 'owner' || orgRole === 'admin' || orgRole === 'super_admin';
const canViewTeamUsage = isAdmin || isDeptManager;
@@ -344,6 +346,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
);
}
setPage(1);
setTaskFilterRevision((revision) => revision + 1);
};
// 重置:回到默认状态(滚动最近 7 天、不限成员/模型)
@@ -364,6 +367,7 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
});
}
setPage(1);
setTaskFilterRevision((revision) => revision + 1);
};
// 导出弹窗状态(导出方式 + 字段勾选从 localStorage 恢复)
@@ -778,144 +782,157 @@ const OrgLogs = ({ orgId, orgRole, isDeptManager = false }) => {
onChange={setActiveTab}
items={[
{ key: 'logs', label: t('明细日志') },
{ key: 'tasks', label: t('绘图与视频') },
...(canViewTeamUsage
? [{ key: 'ranking', label: t('成员排行') }]
: []),
]}
/>
{/* 筛选栏(原型 .ee-filter-card / .eex-filter-grid) */}
<OrgFilterCard
className='oc-exp-filter'
actions={
<>
<Button onClick={handleReset}>{t('重置')}</Button>
<Button
type='primary'
icon={<Search size={16} />}
onClick={() => handleSearch(false)}
loading={loading}
>
{t('搜索')}
</Button>
</>
}
>
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('成员')}>
{canViewTeamUsage ? (
<Select
value={selectedUserId}
onChange={setSelectedUserId}
optionList={memberOptions}
style={{ width: '100%' }}
placeholder={isAdmin ? t('全部成员') : t('全部部门成员')}
filter
{activeTab === 'tasks' ? (
<TaskLogsTable
usageRecordMode
organizationMode
sharedStartTimestamp={appliedFilters.startTimestamp}
sharedEndTimestamp={appliedFilters.endTimestamp}
sharedFilterRevision={taskFilterRevision}
/>
) : (
<>
{/* 筛选栏(原型 .ee-filter-card / .eex-filter-grid) */}
<OrgFilterCard
className='oc-exp-filter'
actions={
<>
<Button onClick={handleReset}>{t('重置')}</Button>
<Button
type='primary'
icon={<Search size={16} />}
onClick={() => handleSearch(false)}
loading={loading}
>
{t('搜索')}
</Button>
</>
}
>
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('成员')}>
{canViewTeamUsage ? (
<Select
value={selectedUserId}
onChange={setSelectedUserId}
optionList={memberOptions}
style={{ width: '100%' }}
placeholder={isAdmin ? t('全部成员') : t('全部部门成员')}
filter
/>
) : (
<div className='oc-exp-self'>{t('仅本人')}</div>
)}
</AntForm.Item>
</AntForm>
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('时间范围')}>
<DatePicker
type='dateTimeRange'
value={dateRange}
onChange={(v) => {
setDateRange(v);
setIsDefaultRange(false);
}}
placeholder={[t('开始时间'), t('结束时间')]}
style={{ width: '100%' }}
/>
</AntForm.Item>
</AntForm>
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('模型名称')}>
<Input
placeholder={t('请输入模型名称')}
value={modelName}
onChange={setModelName}
onEnterPress={() => handleSearch(false)}
/>
</AntForm.Item>
</AntForm>
</OrgFilterCard>
<OrgListCard
title={activeTab === 'ranking' ? t('成员排行') : t('明细日志')}
tools={
<>
<Button
icon={<Download size={16} />}
onClick={() => setExportModalVisible(true)}
>
{t('导出')}
</Button>
<Button
icon={<RefreshCw size={16} />}
onClick={() => handleSearch(true)}
loading={loading}
>
{t('刷新')}
</Button>
</>
}
>
{activeTab === 'ranking' && canViewTeamUsage ? (
<Table
columns={rankingColumns}
dataSource={ranking}
loading={rankingLoading}
rowKey='user_id'
pagination={false}
scroll={{ x: 790 }}
empty={
<div className='py-10 text-center'>
<div className='inline-flex p-3 rounded-full bg-gray-100 dark:bg-neutral-800 mb-3'>
<Trophy
size={24}
className='text-gray-400 dark:text-gray-500'
/>
</div>
<p className='text-gray-400 dark:text-gray-500 text-sm'>
{t('暂无排行数据')}
</p>
</div>
}
/>
) : (
<div className='oc-exp-self'>{t('仅本人')}</div>
<Table
columns={logColumns}
dataSource={logs}
loading={loading}
rowKey='id'
scroll={{ x: 1285 }}
pagination={{
currentPage: page,
pageSize,
total,
showSizeChanger: false,
onPageChange: (p) => doPageFetch(p),
showTotal: (n) => t('共 {{total}} 条', { total: n }),
}}
empty={
<div className='py-10 text-center'>
<div className='inline-flex p-3 rounded-full bg-gray-100 dark:bg-neutral-800 mb-3'>
<Receipt
size={24}
className='text-gray-400 dark:text-gray-500'
/>
</div>
<p className='text-gray-400 dark:text-gray-500 text-sm'>
{t('暂无消耗记录')}
</p>
</div>
}
/>
)}
</AntForm.Item>
</AntForm>
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('时间范围')}>
<DatePicker
type='dateTimeRange'
value={dateRange}
onChange={(v) => {
setDateRange(v);
setIsDefaultRange(false);
}}
placeholder={[t('开始时间'), t('结束时间')]}
style={{ width: '100%' }}
/>
</AntForm.Item>
</AntForm>
<AntForm layout='vertical' requiredMark={false} component='div'>
<AntForm.Item label={t('模型名称')}>
<Input
placeholder={t('请输入模型名称')}
value={modelName}
onChange={setModelName}
onEnterPress={() => handleSearch(false)}
/>
</AntForm.Item>
</AntForm>
</OrgFilterCard>
<OrgListCard
title={activeTab === 'ranking' ? t('成员排行') : t('明细日志')}
tools={
<>
<Button
icon={<Download size={16} />}
onClick={() => setExportModalVisible(true)}
>
{t('导出')}
</Button>
<Button
icon={<RefreshCw size={16} />}
onClick={() => handleSearch(true)}
loading={loading}
>
{t('刷新')}
</Button>
</>
}
>
{activeTab === 'ranking' && canViewTeamUsage ? (
<Table
columns={rankingColumns}
dataSource={ranking}
loading={rankingLoading}
rowKey='user_id'
pagination={false}
scroll={{ x: 790 }}
empty={
<div className='py-10 text-center'>
<div className='inline-flex p-3 rounded-full bg-gray-100 dark:bg-neutral-800 mb-3'>
<Trophy
size={24}
className='text-gray-400 dark:text-gray-500'
/>
</div>
<p className='text-gray-400 dark:text-gray-500 text-sm'>
{t('暂无排行数据')}
</p>
</div>
}
/>
) : (
<Table
columns={logColumns}
dataSource={logs}
loading={loading}
rowKey='id'
scroll={{ x: 1285 }}
pagination={{
currentPage: page,
pageSize,
total,
showSizeChanger: false,
onPageChange: (p) => doPageFetch(p),
showTotal: (n) => t('共 {{total}} 条', { total: n }),
}}
empty={
<div className='py-10 text-center'>
<div className='inline-flex p-3 rounded-full bg-gray-100 dark:bg-neutral-800 mb-3'>
<Receipt
size={24}
className='text-gray-400 dark:text-gray-500'
/>
</div>
<p className='text-gray-400 dark:text-gray-500 text-sm'>
{t('暂无消耗记录')}
</p>
</div>
}
/>
)}
</OrgListCard>
</OrgListCard>
</>
)}
{/* 导出弹窗:汇总 / 按用户 + 字段选择 */}
<OrgModal