useTaskLogsData.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. // Form state
  58. const [formApi, setFormApi] = useState(null);
  59. let now = new Date();
  60. let zeroNow = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  61. const formInitValues = {
  62. channel_id: '',
  63. task_id: '',
  64. dateRange: [
  65. timestamp2string(zeroNow.getTime() / 1000),
  66. timestamp2string(now.getTime() / 1000 + 3600)
  67. ],
  68. };
  69. // Column visibility state
  70. const [visibleColumns, setVisibleColumns] = useState({});
  71. const [showColumnSelector, setShowColumnSelector] = useState(false);
  72. // Compact mode
  73. const [compactMode, setCompactMode] = useTableCompactMode('taskLogs');
  74. // Load saved column preferences from localStorage
  75. useEffect(() => {
  76. const savedColumns = localStorage.getItem(STORAGE_KEY);
  77. if (savedColumns) {
  78. try {
  79. const parsed = JSON.parse(savedColumns);
  80. const defaults = getDefaultColumnVisibility();
  81. const merged = { ...defaults, ...parsed };
  82. // For non-admin users, force-hide admin-only columns (does not touch admin settings)
  83. if (!isAdminUser) {
  84. merged[COLUMN_KEYS.CHANNEL] = false;
  85. }
  86. setVisibleColumns(merged);
  87. } catch (e) {
  88. console.error('Failed to parse saved column preferences', e);
  89. initDefaultColumns();
  90. }
  91. } else {
  92. initDefaultColumns();
  93. }
  94. }, []);
  95. // Get default column visibility based on user role
  96. const getDefaultColumnVisibility = () => {
  97. return {
  98. [COLUMN_KEYS.SUBMIT_TIME]: true,
  99. [COLUMN_KEYS.FINISH_TIME]: true,
  100. [COLUMN_KEYS.DURATION]: true,
  101. [COLUMN_KEYS.CHANNEL]: isAdminUser,
  102. [COLUMN_KEYS.PLATFORM]: true,
  103. [COLUMN_KEYS.TYPE]: true,
  104. [COLUMN_KEYS.TASK_ID]: true,
  105. [COLUMN_KEYS.TASK_STATUS]: true,
  106. [COLUMN_KEYS.PROGRESS]: true,
  107. [COLUMN_KEYS.FAIL_REASON]: true,
  108. [COLUMN_KEYS.RESULT_URL]: true,
  109. };
  110. };
  111. // Initialize default column visibility
  112. const initDefaultColumns = () => {
  113. const defaults = getDefaultColumnVisibility();
  114. setVisibleColumns(defaults);
  115. localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
  116. };
  117. // Handle column visibility change
  118. const handleColumnVisibilityChange = (columnKey, checked) => {
  119. const updatedColumns = { ...visibleColumns, [columnKey]: checked };
  120. setVisibleColumns(updatedColumns);
  121. };
  122. // Handle "Select All" checkbox
  123. const handleSelectAll = (checked) => {
  124. const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
  125. const updatedColumns = {};
  126. allKeys.forEach((key) => {
  127. if (key === COLUMN_KEYS.CHANNEL && !isAdminUser) {
  128. updatedColumns[key] = false;
  129. } else {
  130. updatedColumns[key] = checked;
  131. }
  132. });
  133. setVisibleColumns(updatedColumns);
  134. };
  135. // Persist column settings to the role-specific STORAGE_KEY
  136. useEffect(() => {
  137. if (Object.keys(visibleColumns).length > 0) {
  138. localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
  139. }
  140. }, [visibleColumns]);
  141. // Get form values helper function
  142. const getFormValues = () => {
  143. const formValues = formApi ? formApi.getValues() : {};
  144. // 处理时间范围
  145. let start_timestamp = timestamp2string(zeroNow.getTime() / 1000);
  146. let end_timestamp = timestamp2string(now.getTime() / 1000 + 3600);
  147. if (formValues.dateRange && Array.isArray(formValues.dateRange) && formValues.dateRange.length === 2) {
  148. start_timestamp = formValues.dateRange[0];
  149. end_timestamp = formValues.dateRange[1];
  150. }
  151. return {
  152. channel_id: formValues.channel_id || '',
  153. task_id: formValues.task_id || '',
  154. start_timestamp,
  155. end_timestamp,
  156. };
  157. };
  158. // Enrich logs data
  159. const enrichLogs = (items) => {
  160. return items.map((log) => ({
  161. ...log,
  162. timestamp2string: timestamp2string(log.created_at),
  163. key: '' + log.id,
  164. }));
  165. };
  166. // Sync page data
  167. const syncPageData = (payload) => {
  168. const items = enrichLogs(payload.items || []);
  169. setLogs(items);
  170. setLogCount(payload.total || 0);
  171. setActivePage(payload.page || 1);
  172. setPageSize(payload.page_size || pageSize);
  173. };
  174. // Load logs function
  175. const loadLogs = async (page = 1, size = pageSize) => {
  176. setLoading(true);
  177. const { channel_id, task_id, start_timestamp, end_timestamp } = getFormValues();
  178. let localStartTimestamp = parseInt(Date.parse(start_timestamp) / 1000);
  179. let localEndTimestamp = parseInt(Date.parse(end_timestamp) / 1000);
  180. let url = isAdminUser
  181. ? `/api/task/?p=${page}&page_size=${size}&channel_id=${channel_id}&task_id=${task_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`
  182. : `/api/task/self?p=${page}&page_size=${size}&task_id=${task_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
  183. const res = await API.get(url);
  184. const { success, message, data } = res.data;
  185. if (success) {
  186. syncPageData(data);
  187. } else {
  188. showError(message);
  189. }
  190. setLoading(false);
  191. };
  192. // Page handlers
  193. const handlePageChange = (page) => {
  194. loadLogs(page, pageSize).then();
  195. };
  196. const handlePageSizeChange = async (size) => {
  197. localStorage.setItem('task-page-size', size + '');
  198. await loadLogs(1, size);
  199. };
  200. // Refresh function
  201. const refresh = async () => {
  202. await loadLogs(1, pageSize);
  203. };
  204. // Copy text function
  205. const copyText = async (text) => {
  206. if (await copy(text)) {
  207. showSuccess(t('已复制:') + text);
  208. } else {
  209. Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
  210. }
  211. };
  212. // Modal handlers
  213. const openContentModal = (content) => {
  214. setModalContent(content);
  215. setIsModalOpen(true);
  216. };
  217. // Initialize data
  218. useEffect(() => {
  219. const localPageSize = parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE;
  220. setPageSize(localPageSize);
  221. loadLogs(1, localPageSize).then();
  222. }, []);
  223. return {
  224. // Basic state
  225. logs,
  226. loading,
  227. activePage,
  228. logCount,
  229. pageSize,
  230. isAdminUser,
  231. // Modal state
  232. isModalOpen,
  233. setIsModalOpen,
  234. modalContent,
  235. // Form state
  236. formApi,
  237. setFormApi,
  238. formInitValues,
  239. getFormValues,
  240. // Column visibility
  241. visibleColumns,
  242. showColumnSelector,
  243. setShowColumnSelector,
  244. handleColumnVisibilityChange,
  245. handleSelectAll,
  246. initDefaultColumns,
  247. COLUMN_KEYS,
  248. // Compact mode
  249. compactMode,
  250. setCompactMode,
  251. // Functions
  252. loadLogs,
  253. handlePageChange,
  254. handlePageSizeChange,
  255. refresh,
  256. copyText,
  257. openContentModal,
  258. enrichLogs,
  259. syncPageData,
  260. // Translation
  261. t,
  262. };
  263. };