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
+264
View File
@@ -0,0 +1,264 @@
/*
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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { API } from '../../helpers';
import {
QUALITY_ERROR_TEXT,
TIME_RANGES,
} from '../../components/quality/qualityConstants';
// 筛选条件全部同步到 URL(q_ 前缀),刷新 / 分享链接可还原同一视图。
const FILTER_KEYS = [
'range',
'start',
'end',
'granularity',
'model',
'channel_id',
'group',
'org_id',
'user_id',
'token_id',
'dept_id',
'project_id',
'path',
'error_code',
'status_code',
'outcome',
'fault_side',
'source',
'include_abort',
'include_blocked',
];
export const DEFAULT_FILTERS = {
range: '24h',
start: '',
end: '',
granularity: 'auto',
model: '',
channel_id: '',
group: '',
org_id: '',
user_id: '',
token_id: '',
dept_id: '',
project_id: '',
path: '',
error_code: '',
status_code: '',
outcome: '',
fault_side: '',
source: '',
include_abort: '',
include_blocked: '',
};
const readFiltersFromURL = () => {
const next = { ...DEFAULT_FILTERS };
try {
const params = new URLSearchParams(window.location.search);
FILTER_KEYS.forEach((key) => {
const v = params.get(`q_${key}`);
if (v !== null) next[key] = v;
});
} catch (_e) {
// URL 不可解析时使用默认筛选
}
return next;
};
const writeFiltersToURL = (filters) => {
try {
const url = new URL(window.location.href);
FILTER_KEYS.forEach((key) => {
const v = filters[key];
if (v === '' || v === undefined || v === DEFAULT_FILTERS[key]) {
url.searchParams.delete(`q_${key}`);
} else {
url.searchParams.set(`q_${key}`, v);
}
});
window.history.replaceState(null, '', url.toString());
} catch (_e) {
// 忽略
}
};
export const resolveWindow = (filters) => {
if (filters.range === 'custom' && filters.start && filters.end) {
return { start: Number(filters.start), end: Number(filters.end) };
}
const now = Math.floor(Date.now() / 1000);
const preset =
TIME_RANGES.find((r) => r.value === filters.range) || TIME_RANGES[2];
return { start: now - preset.seconds, end: now };
};
export const buildQualityParams = (filters) => {
const { start, end } = resolveWindow(filters);
const params = { start, end };
FILTER_KEYS.forEach((key) => {
if (['range', 'start', 'end'].includes(key)) return;
const v = filters[key];
if (v !== '' && v !== undefined && v !== null) params[key] = v;
});
return params;
};
/**
* 调用质量看板数据 hook。
* @param {'platform'|'org'} scope
* @param {boolean} enabled 页签未激活时不发请求
* @param {number} [orgId] 企业侧显式注入 X-Org-Id
*/
const useQualityDashboard = (scope, enabled, orgId) => {
const base = scope === 'org' ? '/api/org/quality' : '/api/analytics/quality';
const headers = useMemo(
() => (scope === 'org' && orgId ? { 'X-Org-Id': String(orgId) } : {}),
[scope, orgId],
);
const [filters, setFiltersState] = useState(readFiltersFromURL);
const [options, setOptions] = useState({});
const [summary, setSummary] = useState(null);
const [trend, setTrend] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [refreshKey, setRefreshKey] = useState(0);
const seq = useRef(0);
// 统一把 HTTP 错误与 success:false 归一成带 code 的 Error,由看板就地展示可读文案
// (skipErrorHandler:不走全局 toast,避免同一错误弹两次)
const unwrap = async (promise) => {
// 优先用后端错误码;中间件拒绝(企业冻结 / 权限不足等)只给了中文提示时改用提示文案
const toError = (body) => {
const code = body.code && QUALITY_ERROR_TEXT[body.code] ? body.code : '';
const err = new Error(body.message || 'query_failed');
err.code = code || body.message || body.code || 'query_failed';
return err;
};
let res;
try {
res = await promise;
} catch (e) {
throw toError(e?.response?.data || {});
}
const body = res?.data || {};
if (!body.success) {
throw toError(body);
}
return body.data;
};
const get = useCallback(
(path, params) =>
unwrap(
API.get(`${base}${path}`, { params, headers, skipErrorHandler: true }),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[base, headers],
);
const send = useCallback(
(method, path, data) =>
unwrap(
method === 'delete'
? API.delete(`${base}${path}`, { headers, skipErrorHandler: true })
: API[method](`${base}${path}`, data, {
headers,
skipErrorHandler: true,
}),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[base, headers],
);
const setFilters = useCallback((patch) => {
setFiltersState((prev) => {
const next = { ...prev, ...patch };
writeFiltersToURL(next);
return next;
});
}, []);
const resetFilters = useCallback(() => {
writeFiltersToURL(DEFAULT_FILTERS);
setFiltersState({ ...DEFAULT_FILTERS });
}, []);
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
const params = useMemo(
() => buildQualityParams(filters),
// refreshKey 参与依赖:预设时间范围在刷新时重新以当前时刻为终点
// eslint-disable-next-line react-hooks/exhaustive-deps
[filters, refreshKey],
);
useEffect(() => {
if (!enabled) return;
get('/options', {})
.then((data) => setOptions(data || {}))
.catch(() => setOptions({}));
}, [enabled, get]);
useEffect(() => {
if (!enabled) return;
const current = ++seq.current;
setLoading(true);
setError('');
Promise.all([get('/summary', params), get('/trend', params)])
.then(([s, tr]) => {
if (current !== seq.current) return;
setSummary(s);
setTrend(tr);
})
.catch((err) => {
if (current !== seq.current) return;
setSummary(null);
setTrend(null);
setError(err.code || err.message || 'query_failed');
})
.finally(() => {
if (current === seq.current) setLoading(false);
});
}, [enabled, get, params]);
return {
scope,
base,
headers,
filters,
setFilters,
resetFilters,
params,
options,
summary,
trend,
loading,
error,
refresh,
refreshKey,
get,
send,
};
};
export default useQualityDashboard;