useTaskLogsData.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. Copyright (C) 2025 QuantumNous
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <https://www.gnu.org/licenses/>.
  13. For commercial licensing, please contact support@quantumnous.com
  14. */
  15. import { useState, useEffect } from 'react';
  16. import { useTranslation } from 'react-i18next';
  17. import { Modal } from '@douyinfe/semi-ui';
  18. import {
  19. API,
  20. copy,
  21. isAdmin,
  22. showError,
  23. showSuccess,
  24. timestamp2string
  25. } from '../../helpers';
  26. import { ITEMS_PER_PAGE } from '../../constants';
  27. import { useTableCompactMode } from '../common/useTableCompactMode';
  28. export const useTaskLogsData = () => {
  29. const { t } = useTranslation();
  30. // Define column keys for selection
  31. const COLUMN_KEYS = {
  32. SUBMIT_TIME: 'submit_time',
  33. FINISH_TIME: 'finish_time',
  34. DURATION: 'duration',
  35. CHANNEL: 'channel',
  36. PLATFORM: 'platform',
  37. TYPE: 'type',
  38. TASK_ID: 'task_id',
  39. TASK_STATUS: 'task_status',
  40. PROGRESS: 'progress',
  41. FAIL_REASON: 'fail_reason',
  42. RESULT_URL: 'result_url',
  43. };
  44. // Basic state
  45. const [logs, setLogs] = useState([]);
  46. const [loading, setLoading] = useState(false);
  47. const [activePage, setActivePage] = useState(1);
  48. const [logCount, setLogCount] = useState(0);
  49. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  50. // User and admin
  51. const isAdminUser = isAdmin();
  52. // Role-specific storage key to prevent different roles from overwriting each other
  53. const STORAGE_KEY = isAdminUser ? 'task-logs-table-columns-admin' : 'task-logs-table-columns-user';
  54. // Modal state
  55. const [isModalOpen, setIsModalOpen] = useState(false);
  56. const [modalContent, setModalContent] = useState('');
  57. // 新增:视频预览弹窗状态
  58. const [isVideoModalOpen, setIsVideoModalOpen] = useState(false);
  59. const [videoUrl, setVideoUrl] = useState('');
  60. // Form state
  61. const [formApi, setFormApi] = useState(null);
  62. let now = new Date();
  63. let zeroNow = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  64. const formInitValues = {
  65. channel_id: '',
  66. task_id: '',
  67. dateRange: [
  68. timestamp2string(zeroNow.getTime() / 1000),
  69. timestamp2string(now.getTime() / 1000 + 3600)
  70. ],
  71. };
  72. // Column visibility state
  73. const [visibleColumns, setVisibleColumns] = useState({});
  74. const [showColumnSelector, setShowColumnSelector] = useState(false);
  75. // Compact mode
  76. const [compactMode, setCompactMode] = useTableCompactMode('taskLogs');
  77. // Load saved column preferences from localStorage
  78. useEffect(() => {
  79. const savedColumns = localStorage.getItem(STORAGE_KEY);
  80. if (savedColumns) {
  81. try {
  82. const parsed = JSON.parse(savedColumns);
  83. const defaults = getDefaultColumnVisibility();
  84. const merged = { ...defaults, ...parsed };
  85. // For non-admin users, force-hide admin-only columns (does not touch admin settings)
  86. if (!isAdminUser) {
  87. merged[COLUMN_KEYS.CHANNEL] = false;
  88. }
  89. setVisibleColumns(merged);
  90. } catch (e) {
  91. console.error('Failed to parse saved column preferences', e);
  92. initDefaultColumns();
  93. }
  94. } else {
  95. initDefaultColumns();
  96. }
  97. }, []);
  98. // Get default column visibility based on user role
  99. const getDefaultColumnVisibility = () => {
  100. return {
  101. [COLUMN_KEYS.SUBMIT_TIME]: true,
  102. [COLUMN_KEYS.FINISH_TIME]: true,
  103. [COLUMN_KEYS.DURATION]: true,
  104. [COLUMN_KEYS.CHANNEL]: isAdminUser,
  105. [COLUMN_KEYS.PLATFORM]: true,
  106. [COLUMN_KEYS.TYPE]: true,
  107. [COLUMN_KEYS.TASK_ID]: true,
  108. [COLUMN_KEYS.TASK_STATUS]: true,
  109. [COLUMN_KEYS.PROGRESS]: true,
  110. [COLUMN_KEYS.FAIL_REASON]: true,
  111. [COLUMN_KEYS.RESULT_URL]: true,
  112. };
  113. };
  114. // Initialize default column visibility
  115. const initDefaultColumns = () => {
  116. const defaults = getDefaultColumnVisibility();
  117. setVisibleColumns(defaults);
  118. localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
  119. };
  120. // Handle column visibility change
  121. const handleColumnVisibilityChange = (columnKey, checked) => {
  122. const updatedColumns = { ...visibleColumns, [columnKey]: checked };
  123. setVisibleColumns(updatedColumns);
  124. };
  125. // Handle "Select All" checkbox
  126. const handleSelectAll = (checked) => {
  127. const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
  128. const updatedColumns = {};
  129. allKeys.forEach((key) => {
  130. if (key === COLUMN_KEYS.CHANNEL && !isAdminUser) {
  131. updatedColumns[key] = false;
  132. } else {
  133. updatedColumns[key] = checked;
  134. }
  135. });
  136. setVisibleColumns(updatedColumns);
  137. };
  138. // Persist column settings to the role-specific STORAGE_KEY
  139. useEffect(() => {
  140. if (Object.keys(visibleColumns).length > 0) {
  141. localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
  142. }
  143. }, [visibleColumns]);
  144. // Get form values helper function
  145. const getFormValues = () => {
  146. const formValues = formApi ? formApi.getValues() : {};
  147. // 处理时间范围
  148. let start_timestamp = timestamp2string(zeroNow.getTime() / 1000);
  149. let end_timestamp = timestamp2string(now.getTime() / 1000 + 3600);
  150. if (formValues.dateRange && Array.isArray(formValues.dateRange) && formValues.dateRange.length === 2) {
  151. start_timestamp = formValues.dateRange[0];
  152. end_timestamp = formValues.dateRange[1];
  153. }
  154. return {
  155. channel_id: formValues.channel_id || '',
  156. task_id: formValues.task_id || '',
  157. start_timestamp,
  158. end_timestamp,
  159. };
  160. };
  161. // Enrich logs data
  162. const enrichLogs = (items) => {
  163. return items.map((log) => ({
  164. ...log,
  165. timestamp2string: timestamp2string(log.created_at),
  166. key: '' + log.id,
  167. }));
  168. };
  169. // Sync page data
  170. const syncPageData = (payload) => {
  171. const items = enrichLogs(payload.items || []);
  172. setLogs(items);
  173. setLogCount(payload.total || 0);
  174. setActivePage(payload.page || 1);
  175. setPageSize(payload.page_size || pageSize);
  176. };
  177. // Load logs function
  178. const loadLogs = async (page = 1, size = pageSize) => {
  179. setLoading(true);
  180. const { channel_id, task_id, start_timestamp, end_timestamp } = getFormValues();
  181. let localStartTimestamp = parseInt(Date.parse(start_timestamp) / 1000);
  182. let localEndTimestamp = parseInt(Date.parse(end_timestamp) / 1000);
  183. let url = isAdminUser
  184. ? `/api/task/?p=${page}&page_size=${size}&channel_id=${channel_id}&task_id=${task_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`
  185. : `/api/task/self?p=${page}&page_size=${size}&task_id=${task_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
  186. const res = await API.get(url);
  187. const { success, message, data } = res.data;
  188. if (success) {
  189. syncPageData(data);
  190. } else {
  191. showError(message);
  192. }
  193. setLoading(false);
  194. };
  195. // Page handlers
  196. const handlePageChange = (page) => {
  197. loadLogs(page, pageSize).then();
  198. };
  199. const handlePageSizeChange = async (size) => {
  200. localStorage.setItem('task-page-size', size + '');
  201. await loadLogs(1, size);
  202. };
  203. // Refresh function
  204. const refresh = async () => {
  205. await loadLogs(1, pageSize);
  206. };
  207. // Copy text function
  208. const copyText = async (text) => {
  209. if (await copy(text)) {
  210. showSuccess(t('已复制:') + text);
  211. } else {
  212. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  213. }
  214. };
  215. // Modal handlers
  216. const openContentModal = (content) => {
  217. setModalContent(content);
  218. setIsModalOpen(true);
  219. };
  220. // 新增:打开视频预览弹窗
  221. const openVideoModal = (url) => {
  222. setVideoUrl(url);
  223. setIsVideoModalOpen(true);
  224. };
  225. // Initialize data
  226. useEffect(() => {
  227. const localPageSize = parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE;
  228. setPageSize(localPageSize);
  229. loadLogs(1, localPageSize).then();
  230. }, []);
  231. return {
  232. // Basic state
  233. logs,
  234. loading,
  235. activePage,
  236. logCount,
  237. pageSize,
  238. isAdminUser,
  239. // Modal state
  240. isModalOpen,
  241. setIsModalOpen,
  242. modalContent,
  243. // 新增:视频弹窗状态
  244. isVideoModalOpen,
  245. setIsVideoModalOpen,
  246. videoUrl,
  247. // Form state
  248. formApi,
  249. setFormApi,
  250. formInitValues,
  251. getFormValues,
  252. // Column visibility
  253. visibleColumns,
  254. showColumnSelector,
  255. setShowColumnSelector,
  256. handleColumnVisibilityChange,
  257. handleSelectAll,
  258. initDefaultColumns,
  259. COLUMN_KEYS,
  260. // Compact mode
  261. compactMode,
  262. setCompactMode,
  263. // Functions
  264. loadLogs,
  265. handlePageChange,
  266. handlePageSizeChange,
  267. refresh,
  268. copyText,
  269. openContentModal,
  270. openVideoModal, // 新增
  271. enrichLogs,
  272. syncPageData,
  273. // Translation
  274. t,
  275. };
  276. };