Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,522 @@
|
||||
/*
|
||||
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 { useState, useEffect, useRef, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Modal } from '@douyinfe/semi-ui';
|
||||
import {
|
||||
API,
|
||||
copy,
|
||||
isAdmin,
|
||||
showError,
|
||||
showSuccess,
|
||||
timestamp2string,
|
||||
} from '../../helpers';
|
||||
import { EVENTS, emit } from '../../helpers/eventBus';
|
||||
import { ITEMS_PER_PAGE } from '../../constants';
|
||||
import { useTableCompactMode } from '../common/useTableCompactMode';
|
||||
|
||||
export const useTaskLogsData = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Define column keys for selection
|
||||
// 注意:这里列出的 key 必须与 TaskLogsColumnDefs.getTaskLogsColumns 返回的列 key 一一对应,
|
||||
// 否则会在 localStorage 中留下无效状态并误导列选择器显示
|
||||
const COLUMN_KEYS = {
|
||||
SUBMIT_TIME: 'submit_time',
|
||||
FINISH_TIME: 'finish_time',
|
||||
DURATION: 'duration',
|
||||
CHANNEL: 'channel',
|
||||
PLATFORM: 'platform',
|
||||
TYPE: 'type',
|
||||
MODEL: 'model',
|
||||
TASK_ID: 'task_id',
|
||||
TASK_STATUS: 'task_status',
|
||||
PROGRESS: 'progress',
|
||||
QUOTA: 'quota',
|
||||
FAIL_REASON: 'fail_reason',
|
||||
};
|
||||
|
||||
// Basic state
|
||||
const [logs, setLogs] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [activePage, setActivePage] = useState(1);
|
||||
const [logCount, setLogCount] = useState(0);
|
||||
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
|
||||
|
||||
// User and admin
|
||||
const isAdminUser = isAdmin();
|
||||
// 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';
|
||||
|
||||
// Modal state
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [modalContent, setModalContent] = useState('');
|
||||
|
||||
// 新增:视频预览弹窗状态
|
||||
// videoUrl:用于 <video> 标签播放,走后端代理 /v1/videos/:id/content 避免跨域
|
||||
// videoSourceUrl:上游原始可分享 URL,供"复制链接"使用,避免用户拿到无法外部访问的代理路径
|
||||
const [isVideoModalOpen, setIsVideoModalOpen] = useState(false);
|
||||
const [videoUrl, setVideoUrl] = useState('');
|
||||
const [videoSourceUrl, setVideoSourceUrl] = useState('');
|
||||
|
||||
// Form state
|
||||
const [formApi, setFormApi] = useState(null);
|
||||
|
||||
// 每次调用都返回"此刻"的默认时间范围,避免长时间驻留页面后
|
||||
// 点击"重置"仍得到页面加载时的"今日"(跨日 bug)
|
||||
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),
|
||||
];
|
||||
};
|
||||
|
||||
const getFreshInitValues = () => ({
|
||||
channel_id: '',
|
||||
task_id: '',
|
||||
user_id: '',
|
||||
status: '',
|
||||
action: '',
|
||||
dateRange: getFreshDateRange(),
|
||||
});
|
||||
|
||||
// 统一的 URL 双向同步字段列表,读取和写入用同一份,避免两处维护漂移
|
||||
const URL_SYNC_FIELDS = [
|
||||
'channel_id',
|
||||
'task_id',
|
||||
'user_id',
|
||||
'status',
|
||||
'action',
|
||||
];
|
||||
|
||||
// URL → 初始表单值:支持直接粘贴包含过滤条件的链接,典型场景是管理员分享"查某用户的任务"
|
||||
// 用 useRef 锁定挂载那一刻的 URL 值,避免每次 render 都重读 window.location(浪费 + 若后续被别处改写会漂移)
|
||||
const initialFormValuesRef = useRef(null);
|
||||
if (initialFormValuesRef.current === null) {
|
||||
const fresh = getFreshInitValues();
|
||||
if (typeof window !== 'undefined') {
|
||||
const sp = new URLSearchParams(window.location.search);
|
||||
URL_SYNC_FIELDS.forEach((key) => {
|
||||
const v = sp.get(key);
|
||||
if (v != null && v !== '') fresh[key] = v;
|
||||
});
|
||||
}
|
||||
initialFormValuesRef.current = fresh;
|
||||
}
|
||||
const formInitValues = initialFormValuesRef.current;
|
||||
|
||||
// Column visibility state
|
||||
const [visibleColumns, setVisibleColumns] = useState({});
|
||||
const [showColumnSelector, setShowColumnSelector] = useState(false);
|
||||
|
||||
// Compact mode
|
||||
const [compactMode, setCompactMode] = useTableCompactMode('taskLogs');
|
||||
|
||||
// Load saved column preferences from localStorage
|
||||
useEffect(() => {
|
||||
const savedColumns = localStorage.getItem(STORAGE_KEY);
|
||||
if (savedColumns) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedColumns);
|
||||
const defaults = getDefaultColumnVisibility();
|
||||
const merged = { ...defaults, ...parsed };
|
||||
|
||||
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
|
||||
if (!isAdminUser) {
|
||||
merged[COLUMN_KEYS.CHANNEL] = false;
|
||||
}
|
||||
setVisibleColumns(merged);
|
||||
} catch (e) {
|
||||
console.error('Failed to parse saved column preferences', e);
|
||||
initDefaultColumns();
|
||||
}
|
||||
} else {
|
||||
initDefaultColumns();
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Get default column visibility based on user role
|
||||
const getDefaultColumnVisibility = () => {
|
||||
return {
|
||||
[COLUMN_KEYS.SUBMIT_TIME]: true,
|
||||
[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,
|
||||
[COLUMN_KEYS.TASK_STATUS]: true,
|
||||
[COLUMN_KEYS.PROGRESS]: true,
|
||||
[COLUMN_KEYS.QUOTA]: true,
|
||||
[COLUMN_KEYS.FAIL_REASON]: true,
|
||||
};
|
||||
};
|
||||
|
||||
// Initialize default column visibility
|
||||
const initDefaultColumns = () => {
|
||||
const defaults = getDefaultColumnVisibility();
|
||||
setVisibleColumns(defaults);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
|
||||
};
|
||||
|
||||
// Handle column visibility change
|
||||
const handleColumnVisibilityChange = (columnKey, checked) => {
|
||||
const updatedColumns = { ...visibleColumns, [columnKey]: checked };
|
||||
setVisibleColumns(updatedColumns);
|
||||
};
|
||||
|
||||
// Handle "Select All" checkbox
|
||||
const handleSelectAll = (checked) => {
|
||||
const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
|
||||
const updatedColumns = {};
|
||||
|
||||
allKeys.forEach((key) => {
|
||||
if (key === COLUMN_KEYS.CHANNEL && !isAdminUser) {
|
||||
updatedColumns[key] = false;
|
||||
} else {
|
||||
updatedColumns[key] = checked;
|
||||
}
|
||||
});
|
||||
|
||||
setVisibleColumns(updatedColumns);
|
||||
};
|
||||
|
||||
// Persist column settings to the role-specific STORAGE_KEY
|
||||
useEffect(() => {
|
||||
if (Object.keys(visibleColumns).length > 0) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
|
||||
}
|
||||
}, [visibleColumns]);
|
||||
|
||||
// Get form values helper function
|
||||
const getFormValues = () => {
|
||||
// formApi 尚未注册时(首次挂载后、Form 回调前的短窗口),回落到初始 URL 派生值
|
||||
// 否则 URL 带的 ?task_id=xxx 在第一次 loadLogs 时会被当成空字符串,导致初始列表不过滤
|
||||
const formValues = formApi ? formApi.getValues() : formInitValues;
|
||||
|
||||
// 处理时间范围:每次调用时取"此刻"的默认值,避免闭包陈旧
|
||||
const [freshStart, freshEnd] = getFreshDateRange();
|
||||
let start_timestamp = freshStart;
|
||||
let end_timestamp = freshEnd;
|
||||
|
||||
if (
|
||||
formValues.dateRange &&
|
||||
Array.isArray(formValues.dateRange) &&
|
||||
formValues.dateRange.length === 2
|
||||
) {
|
||||
start_timestamp = formValues.dateRange[0];
|
||||
end_timestamp = formValues.dateRange[1];
|
||||
}
|
||||
|
||||
// 所有字符串字段做 trim,避免复制粘贴带上首尾空格导致精确匹配失败
|
||||
return {
|
||||
channel_id: (formValues.channel_id || '').trim(),
|
||||
task_id: (formValues.task_id || '').trim(),
|
||||
// user_id 仅管理员表单有,非管理员下默认 '' ;剥离非数字兼容 IME 粘贴
|
||||
user_id: (formValues.user_id || '').toString().replace(/\D/g, ''),
|
||||
status: (formValues.status || '').trim(),
|
||||
action: (formValues.action || '').trim(),
|
||||
start_timestamp,
|
||||
end_timestamp,
|
||||
};
|
||||
};
|
||||
|
||||
// Enrich logs data
|
||||
const enrichLogs = (items) => {
|
||||
if (!Array.isArray(items)) return [];
|
||||
return items.map((log) => ({
|
||||
...log,
|
||||
timestamp2string: timestamp2string(log.created_at),
|
||||
key: '' + log.id,
|
||||
}));
|
||||
};
|
||||
|
||||
// 上一次数据中各任务的 status,用于检测"新完成"的任务
|
||||
const prevStatusMapRef = useRef({});
|
||||
|
||||
// Sync page data
|
||||
const syncPageData = (payload) => {
|
||||
const items = enrichLogs(payload?.items || []);
|
||||
|
||||
// 检测终态转变(SUCCESS / FAILURE)——新完成的任务会触发后端生成使用日志,
|
||||
// 发事件让 usage-logs 统计即时刷新,避免用户切到使用日志 tab 时看到陈旧数据
|
||||
const prev = prevStatusMapRef.current;
|
||||
const TERMINAL = new Set(['SUCCESS', 'FAILURE']);
|
||||
const nextMap = {};
|
||||
let anyJustCompleted = false;
|
||||
items.forEach((it) => {
|
||||
nextMap[it.id] = it.status;
|
||||
if (
|
||||
TERMINAL.has(it.status) &&
|
||||
prev[it.id] !== undefined &&
|
||||
!TERMINAL.has(prev[it.id])
|
||||
) {
|
||||
anyJustCompleted = true;
|
||||
}
|
||||
});
|
||||
prevStatusMapRef.current = nextMap;
|
||||
if (anyJustCompleted) {
|
||||
emit(EVENTS.TASK_COMPLETED);
|
||||
}
|
||||
|
||||
setLogs(items);
|
||||
setLogCount(payload?.total || 0);
|
||||
setActivePage(payload?.page || 1);
|
||||
setPageSize(payload?.page_size || pageSize);
|
||||
};
|
||||
|
||||
// 请求序列号:后发起的请求获得更大的 id,异步回来时丢弃已过期响应
|
||||
// 避免快速翻页/切换过滤条件时,慢响应覆盖最新结果
|
||||
const requestIdRef = useRef(0);
|
||||
|
||||
// Load logs function
|
||||
// silent=true 时用于后台轮询,不触发 loading spinner,避免表格每 10s 闪烁
|
||||
const loadLogs = async (page = 1, size = pageSize, silent = false) => {
|
||||
const reqId = ++requestIdRef.current;
|
||||
if (!silent) setLoading(true);
|
||||
const {
|
||||
channel_id,
|
||||
task_id,
|
||||
user_id,
|
||||
status,
|
||||
action,
|
||||
start_timestamp,
|
||||
end_timestamp,
|
||||
} = getFormValues();
|
||||
let localStartTimestamp = parseInt(Date.parse(start_timestamp) / 1000);
|
||||
let localEndTimestamp = parseInt(Date.parse(end_timestamp) / 1000);
|
||||
// 时间范围校验:起始晚于结束视为非法,避免白发一轮请求并给出提示
|
||||
if (
|
||||
Number.isFinite(localStartTimestamp) &&
|
||||
Number.isFinite(localEndTimestamp) &&
|
||||
localStartTimestamp > localEndTimestamp
|
||||
) {
|
||||
if (!silent) {
|
||||
showError(t('开始时间不能晚于结束时间'));
|
||||
if (reqId === requestIdRef.current) setLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const params = new URLSearchParams({
|
||||
p: page,
|
||||
page_size: size,
|
||||
task_id,
|
||||
start_timestamp: localStartTimestamp,
|
||||
end_timestamp: localEndTimestamp,
|
||||
});
|
||||
// 空值不带到 URL,保持 query 简洁,也避免后端误把空串当作精确匹配
|
||||
if (status) params.set('status', status);
|
||||
if (action) params.set('action', action);
|
||||
if (isAdminUser) {
|
||||
params.set('channel_id', channel_id);
|
||||
// 与使用日志对齐:管理员可按 user_id 过滤任务日志
|
||||
if (user_id) params.set('user_id', user_id);
|
||||
}
|
||||
const url = isAdminUser
|
||||
? `/api/task/?${params.toString()}`
|
||||
: `/api/task/self?${params.toString()}`;
|
||||
try {
|
||||
const res = await API.get(url);
|
||||
// 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出
|
||||
if (reqId !== requestIdRef.current) return;
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
syncPageData(data);
|
||||
} else if (!silent) {
|
||||
showError(message);
|
||||
}
|
||||
} catch (err) {
|
||||
if (reqId !== requestIdRef.current) return;
|
||||
if (!silent) showError(err);
|
||||
} finally {
|
||||
// 只有当自己仍是最新请求时才结束 loading,防止旧请求提前关闭 spinner
|
||||
if (!silent && reqId === requestIdRef.current) setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Page handlers
|
||||
const handlePageChange = (page) => {
|
||||
loadLogs(page, pageSize).then();
|
||||
};
|
||||
|
||||
const handlePageSizeChange = async (size) => {
|
||||
localStorage.setItem('task-page-size', size + '');
|
||||
await loadLogs(1, size);
|
||||
};
|
||||
|
||||
// 把当前表单过滤条件同步到浏览器 URL,便于用户分享链接
|
||||
// 只写入非空值,保持 URL 简洁;tab 和 utm_* 等其他 query 参数原样保留
|
||||
const syncFiltersToUrl = () => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const formValues = formApi ? formApi.getValues() : {};
|
||||
const sp = new URLSearchParams(window.location.search);
|
||||
URL_SYNC_FIELDS.forEach((key) => {
|
||||
const v = (formValues[key] || '').toString().trim();
|
||||
if (v) sp.set(key, v);
|
||||
else sp.delete(key);
|
||||
});
|
||||
const newQuery = sp.toString();
|
||||
const newUrl =
|
||||
window.location.pathname +
|
||||
(newQuery ? '?' + newQuery : '') +
|
||||
window.location.hash;
|
||||
// replaceState:不新增历史记录项,避免每次查询都污染后退栈
|
||||
window.history.replaceState({}, '', newUrl);
|
||||
};
|
||||
|
||||
// Refresh function
|
||||
const refresh = async () => {
|
||||
syncFiltersToUrl();
|
||||
await loadLogs(1, pageSize);
|
||||
};
|
||||
|
||||
// Copy text function
|
||||
const copyText = async (text) => {
|
||||
if (await copy(text)) {
|
||||
showSuccess(t('已复制:') + text);
|
||||
} else {
|
||||
Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
|
||||
}
|
||||
};
|
||||
|
||||
// Modal handlers
|
||||
const openContentModal = (content) => {
|
||||
setModalContent(content);
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
// 新增:打开视频预览弹窗
|
||||
// proxyUrl 是播放用的代理地址;sourceUrl 是上游可分享 URL(可选)
|
||||
const openVideoModal = (proxyUrl, sourceUrl = '') => {
|
||||
setVideoUrl(proxyUrl);
|
||||
setVideoSourceUrl(sourceUrl || proxyUrl);
|
||||
setIsVideoModalOpen(true);
|
||||
};
|
||||
|
||||
// Initialize data
|
||||
useEffect(() => {
|
||||
const localPageSize =
|
||||
parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE;
|
||||
setPageSize(localPageSize);
|
||||
loadLogs(1, localPageSize).then();
|
||||
}, []);
|
||||
|
||||
// 存在进行中的任务时,自动轮询刷新(10s 间隔),无 pending 则停止,避免无谓请求
|
||||
const loadLogsRef = useRef(loadLogs);
|
||||
loadLogsRef.current = loadLogs;
|
||||
|
||||
// 派生稳定布尔值:只在"是否存在 pending 任务"真正翻转时才变
|
||||
// 避免每次静默刷新 logs 引用变化都导致 interval 被清理 + 重建,使 10s 间隔不稳定
|
||||
const hasPending = useMemo(
|
||||
() =>
|
||||
logs.some(
|
||||
(log) =>
|
||||
log.status === 'IN_PROGRESS' ||
|
||||
log.status === 'SUBMITTED' ||
|
||||
log.status === 'QUEUED' ||
|
||||
!log.status,
|
||||
),
|
||||
[logs],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasPending) return undefined;
|
||||
const tick = () => {
|
||||
// 浏览器标签不可见时跳过一轮,避免用户离开页面后继续白白打后端
|
||||
// (用户切回来时 visibilitychange 会立即触发一次补刷新)
|
||||
if (typeof document !== 'undefined' && document.hidden) return;
|
||||
// silent=true:后台静默刷新,不弹 loading、不弹错误提示
|
||||
loadLogsRef.current(activePage, pageSize, true);
|
||||
};
|
||||
const timer = setInterval(tick, 10000);
|
||||
const onVis = () => {
|
||||
if (typeof document !== 'undefined' && !document.hidden) tick();
|
||||
};
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', onVis);
|
||||
}
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
if (typeof document !== 'undefined') {
|
||||
document.removeEventListener('visibilitychange', onVis);
|
||||
}
|
||||
};
|
||||
}, [hasPending, activePage, pageSize]);
|
||||
|
||||
return {
|
||||
// Basic state
|
||||
logs,
|
||||
loading,
|
||||
activePage,
|
||||
logCount,
|
||||
pageSize,
|
||||
isAdminUser,
|
||||
|
||||
// Modal state
|
||||
isModalOpen,
|
||||
setIsModalOpen,
|
||||
modalContent,
|
||||
|
||||
// 新增:视频弹窗状态
|
||||
isVideoModalOpen,
|
||||
setIsVideoModalOpen,
|
||||
videoUrl,
|
||||
videoSourceUrl,
|
||||
|
||||
// Form state
|
||||
formApi,
|
||||
setFormApi,
|
||||
formInitValues,
|
||||
getFormValues,
|
||||
getFreshInitValues,
|
||||
|
||||
// Column visibility
|
||||
visibleColumns,
|
||||
showColumnSelector,
|
||||
setShowColumnSelector,
|
||||
handleColumnVisibilityChange,
|
||||
handleSelectAll,
|
||||
initDefaultColumns,
|
||||
COLUMN_KEYS,
|
||||
|
||||
// Compact mode
|
||||
compactMode,
|
||||
setCompactMode,
|
||||
|
||||
// Functions
|
||||
loadLogs,
|
||||
handlePageChange,
|
||||
handlePageSizeChange,
|
||||
refresh,
|
||||
copyText,
|
||||
openContentModal,
|
||||
openVideoModal, // 新增
|
||||
enrichLogs,
|
||||
syncPageData,
|
||||
|
||||
// Translation
|
||||
t,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user