fix(ui): 修复登录与并发请求并统一表格、主题和页面展示
验证:868 项单测、ESLint、Prettier、UI 依赖审计和差异检查通过。
This commit is contained in:
+24
-32
@@ -19,6 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
|
||||
import {
|
||||
getUserIdFromLocalStorage,
|
||||
redirectToExpiredLogin,
|
||||
showError,
|
||||
formatMessageForAPI,
|
||||
isValidMessage,
|
||||
@@ -29,6 +30,7 @@ import i18next from 'i18next';
|
||||
import { MESSAGE_ROLES } from '../constants/playground.constants';
|
||||
import { getServerURL } from './config';
|
||||
import { buildGetRequestKey, getHeaderValue } from './requestDedupe';
|
||||
import { installRequestLifecycle } from './requestLifecycle';
|
||||
|
||||
function createAPIInstance() {
|
||||
const serverURL = getServerURL();
|
||||
@@ -41,14 +43,20 @@ function createAPIInstance() {
|
||||
});
|
||||
}
|
||||
|
||||
export let API = createAPIInstance();
|
||||
export let API;
|
||||
let retireAPI;
|
||||
|
||||
function patchAPIInstance(instance) {
|
||||
const originalGet = instance.get.bind(instance);
|
||||
const inFlightGetRequests = new Map();
|
||||
|
||||
instance.get = (url, config = {}) => {
|
||||
if (config?.disableDuplicate) {
|
||||
if (
|
||||
config?.disableDuplicate ||
|
||||
config?.signal ||
|
||||
config?.cancelToken ||
|
||||
config?.requestGroup
|
||||
) {
|
||||
return originalGet(url, config);
|
||||
}
|
||||
|
||||
@@ -56,12 +64,13 @@ function patchAPIInstance(instance) {
|
||||
url.startsWith('/api/org/') && typeof localStorage !== 'undefined'
|
||||
? localStorage.getItem('current_org_id') || ''
|
||||
: '';
|
||||
const key = buildGetRequestKey(
|
||||
const requestKey = buildGetRequestKey(
|
||||
url,
|
||||
config,
|
||||
fallbackOrgId,
|
||||
getUserIdFromLocalStorage(),
|
||||
);
|
||||
const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}`;
|
||||
if (inFlightGetRequests.has(key)) {
|
||||
return inFlightGetRequests.get(key);
|
||||
}
|
||||
@@ -75,23 +84,6 @@ function patchAPIInstance(instance) {
|
||||
};
|
||||
}
|
||||
|
||||
patchAPIInstance(API);
|
||||
|
||||
// 添加 response interceptor 的函数
|
||||
function addResponseInterceptor(instance) {
|
||||
instance.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
// 如果请求配置中显式要求跳过全局错误处理,则不弹出默认错误提示
|
||||
if (error.config && error.config.skipErrorHandler) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
showError(error);
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头
|
||||
function addOrgHeaderInterceptor(instance) {
|
||||
instance.interceptors.request.use((config) => {
|
||||
@@ -107,19 +99,21 @@ function addOrgHeaderInterceptor(instance) {
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化时添加 interceptor
|
||||
addResponseInterceptor(API);
|
||||
addOrgHeaderInterceptor(API);
|
||||
|
||||
export function updateAPI() {
|
||||
API = createAPIInstance();
|
||||
|
||||
patchAPIInstance(API);
|
||||
// 重新添加 interceptors
|
||||
addResponseInterceptor(API);
|
||||
addOrgHeaderInterceptor(API);
|
||||
const instance = createAPIInstance();
|
||||
patchAPIInstance(instance);
|
||||
addOrgHeaderInterceptor(instance);
|
||||
const previous = retireAPI;
|
||||
retireAPI = installRequestLifecycle(instance, {
|
||||
onError: (error) => showError(error, { redirectOnUnauthorized: false }),
|
||||
onSessionExpired: redirectToExpiredLogin,
|
||||
});
|
||||
API = instance;
|
||||
previous?.();
|
||||
}
|
||||
|
||||
updateAPI();
|
||||
|
||||
// playground
|
||||
|
||||
// 构建API请求负载
|
||||
@@ -310,8 +304,6 @@ export const processGroupsData = (data, userGroup) => {
|
||||
return groupOptions;
|
||||
};
|
||||
|
||||
// 原来components中的utils.js
|
||||
|
||||
export async function getOAuthState() {
|
||||
let path = '/api/oauth/state';
|
||||
let affCode = localStorage.getItem('aff');
|
||||
|
||||
@@ -25,11 +25,7 @@ import { StatusContext } from '../context/Status';
|
||||
import { canAccessDelegatedAdminPage } from './adminDelegation';
|
||||
import { ADMIN_DELEGATION_OPTION_KEY } from '../constants/settingTabs';
|
||||
import Loading from '../components/common/ui/Loading';
|
||||
import {
|
||||
getUserData,
|
||||
isSafePostLoginRedirect,
|
||||
savePostLoginRedirect,
|
||||
} from './data';
|
||||
import { getUserData, isSafePostLoginRedirect } from './data';
|
||||
import { authRedirectTarget } from './authRedirect';
|
||||
|
||||
/**
|
||||
@@ -49,11 +45,9 @@ export const isAuthPagePath = (pathname) =>
|
||||
/^\/org\/[^/]+\/login$/.test(pathname);
|
||||
|
||||
// 未登录统一引导到企业登录(本产品主推企业用户;个人用户可经页内切换回 /login)。
|
||||
// 回跳地址已存本地(savePostLoginRedirect),切换到个人登录后仍可正常回跳。
|
||||
const getLoginTarget = (location) => {
|
||||
const target = `${location.pathname}${location.search}${location.hash}`;
|
||||
if (isSafePostLoginRedirect(target)) {
|
||||
savePostLoginRedirect(target);
|
||||
return `/org/login?redirect=${encodeURIComponent(target)}`;
|
||||
}
|
||||
return '/org/login';
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
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 { colord, extend } from 'colord';
|
||||
import a11yPlugin from 'colord/plugins/a11y';
|
||||
import mixPlugin from 'colord/plugins/mix';
|
||||
|
||||
extend([a11yPlugin, mixPlugin]);
|
||||
|
||||
export const PROTOTYPE_LIGHT_PRIMARY = '#b96508';
|
||||
export const PROTOTYPE_DARK_PRIMARY = '#d1963a';
|
||||
export const PROTOTYPE_DARK_SEED = '#f2ad41';
|
||||
|
||||
const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
|
||||
|
||||
function toneAtContrast(color, surface, minimum, lighter) {
|
||||
const { h: hue, s: saturation } = color.toHsl();
|
||||
const tone = (lightness) => colord({ h: hue, s: saturation, l: lightness });
|
||||
let low = 0;
|
||||
let high = 100;
|
||||
for (let step = 0; step < 12; step++) {
|
||||
const middle = (low + high) / 2;
|
||||
if (tone(middle).contrast(surface) >= minimum === lighter) high = middle;
|
||||
else low = middle;
|
||||
}
|
||||
return tone(lighter ? high : low);
|
||||
}
|
||||
|
||||
const readable = (color, surface, dark) =>
|
||||
color.contrast(surface) >= 4.7
|
||||
? color
|
||||
: toneAtContrast(color, surface, 4.7, dark);
|
||||
|
||||
export function resolveBrandPalette(configured, dark, surface) {
|
||||
const prototype = dark ? PROTOTYPE_DARK_PRIMARY : PROTOTYPE_LIGHT_PRIMARY;
|
||||
const parsed = colord(configured);
|
||||
const input = parsed.isValid() ? parsed.alpha(1) : colord(prototype);
|
||||
const isPrototype = input.toHex() === prototype;
|
||||
const hsl = input.toHsl();
|
||||
const seed = isPrototype
|
||||
? input
|
||||
: colord({ ...hsl, s: Math.min(hsl.s, 68), l: clamp(hsl.l, 28, 70) });
|
||||
const onSolid = dark ? '#11151c' : '#ffffff';
|
||||
let normal;
|
||||
let hover;
|
||||
let active;
|
||||
if (dark) {
|
||||
const base = seed.contrast(onSolid);
|
||||
const target = clamp(base, 5.3, isPrototype ? 7.2 : 6.45);
|
||||
const fill = (ratio) => toneAtContrast(seed, onSolid, ratio, true);
|
||||
normal = base === target ? seed : fill(target);
|
||||
hover = fill(target + 0.5);
|
||||
active = fill(target - 0.55);
|
||||
} else {
|
||||
normal = readable(seed, onSolid, false);
|
||||
hover = normal.darken(0.035);
|
||||
active = normal.darken(0.07);
|
||||
}
|
||||
const backdrop = colord(surface);
|
||||
const tint = backdrop.mix(normal, dark ? 0.14 : 0.085);
|
||||
const tintHover = backdrop.mix(normal, dark ? 0.2 : 0.135);
|
||||
const ink = readable(normal, tintHover, dark).toHex();
|
||||
return {
|
||||
isPrototype,
|
||||
onSolid,
|
||||
normal: normal.toHex(),
|
||||
hover: hover.toHex(),
|
||||
active: active.toHex(),
|
||||
accent: isPrototype ? (dark ? PROTOTYPE_DARK_SEED : prototype) : ink,
|
||||
selectionBg: isPrototype ? (dark ? '#382b1b' : '#fff3df') : tint.toHex(),
|
||||
selectionText: isPrototype ? (dark ? PROTOTYPE_DARK_SEED : '#a45a07') : ink,
|
||||
tint: tint.toHex(),
|
||||
tintHover: tintHover.toHex(),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveGradientLabel(stops, surface) {
|
||||
const backdrop = colord(surface);
|
||||
const base = backdrop.toRgb();
|
||||
const colors = stops.map((stop) => {
|
||||
const parsed = colord(stop);
|
||||
return parsed.isValid() ? parsed.toRgb() : base;
|
||||
});
|
||||
const composite = (channel, from, to, progress) =>
|
||||
from[channel] * from.a * (1 - progress) +
|
||||
to[channel] * to.a * progress +
|
||||
base[channel] * (1 - from.a * (1 - progress) - to.a * progress);
|
||||
const samples = colors.flatMap((from, index) => {
|
||||
const to = colors[index + 1] ?? from;
|
||||
return [0, 0.25, 0.5, 0.75].map((progress) =>
|
||||
colord({
|
||||
r: composite('r', from, to, progress),
|
||||
g: composite('g', from, to, progress),
|
||||
b: composite('b', from, to, progress),
|
||||
}),
|
||||
);
|
||||
});
|
||||
const inks = ['#ffffff', '#11151c'];
|
||||
const minimum = (ink) =>
|
||||
Math.min(...samples.map((sample) => sample.contrast(ink)));
|
||||
const chosen = minimum(inks[0]) >= minimum(inks[1]) ? inks[0] : inks[1];
|
||||
if (samples.length > 0 && minimum(chosen) >= 4.5) return { color: chosen };
|
||||
return {
|
||||
color:
|
||||
backdrop.contrast(inks[0]) >= backdrop.contrast(inks[1])
|
||||
? inks[0]
|
||||
: inks[1],
|
||||
background: backdrop.toHex(),
|
||||
};
|
||||
}
|
||||
+35
-3
@@ -145,11 +145,43 @@ export function isSafePostLoginRedirect(path) {
|
||||
export function savePostLoginRedirect(path) {
|
||||
if (isSafePostLoginRedirect(path)) {
|
||||
sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, path);
|
||||
} else {
|
||||
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
export function consumePostLoginRedirect(defaultPath = DEFAULT_LOGIN_REDIRECT) {
|
||||
const path = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY);
|
||||
export function consumePostLoginRedirect({
|
||||
redirect = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY),
|
||||
enterprise = false,
|
||||
orgOnly = false,
|
||||
} = {}) {
|
||||
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
|
||||
return isSafePostLoginRedirect(path) ? path : defaultPath;
|
||||
const fallback = enterprise
|
||||
? '/org/workbench'
|
||||
: orgOnly
|
||||
? '/org'
|
||||
: DEFAULT_LOGIN_REDIRECT;
|
||||
if (!isSafePostLoginRedirect(redirect)) return fallback;
|
||||
|
||||
let normalizedPath;
|
||||
try {
|
||||
const base = 'https://login.invalid';
|
||||
const target = new URL(redirect, base);
|
||||
if (target.origin !== base) return fallback;
|
||||
normalizedPath =
|
||||
decodeURI(target.pathname).toLowerCase().replace(/\/+$/, '') || '/';
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
if (
|
||||
!isSafePostLoginRedirect(normalizedPath) ||
|
||||
normalizedPath === '/forbidden' ||
|
||||
normalizedPath === '/user/reset'
|
||||
)
|
||||
return fallback;
|
||||
if (!enterprise && !orgOnly && /^\/org(?:\/|$)/.test(normalizedPath))
|
||||
return fallback;
|
||||
if ((enterprise || orgOnly) && /^\/console(?:\/|$)/.test(normalizedPath))
|
||||
return fallback;
|
||||
return redirect;
|
||||
}
|
||||
|
||||
+16
-17
@@ -19,7 +19,7 @@ For commercial licensing, please contact support@quantumnous.com
|
||||
|
||||
import { API, updateAPI } from './api';
|
||||
import { clearUserData, consumePostLoginRedirect, setUserData } from './data';
|
||||
import { showError, showSuccess } from './utils';
|
||||
import { showError } from './utils';
|
||||
|
||||
const SESSION_NOT_PERSISTED_MESSAGE =
|
||||
'登录成功但浏览器未能保存登录会话,请确认 Cookie 未被拦截后重试';
|
||||
@@ -35,8 +35,8 @@ export async function finishLogin({
|
||||
userDispatch,
|
||||
navigate,
|
||||
t = (s) => s,
|
||||
successMessage,
|
||||
redirectOverride,
|
||||
redirect,
|
||||
enterprise = false,
|
||||
}) {
|
||||
setUserData(data);
|
||||
// Recreate the axios instance so any in-flight request map from a prior
|
||||
@@ -49,7 +49,11 @@ export async function finishLogin({
|
||||
skipErrorHandler: true,
|
||||
disableDuplicate: true,
|
||||
});
|
||||
if (!res.data?.success || !res.data?.data) {
|
||||
if (
|
||||
!res.data?.success ||
|
||||
data?.id == null ||
|
||||
String(res.data?.data?.id) !== String(data.id)
|
||||
) {
|
||||
throw new Error(res.data?.message || 'session verify failed');
|
||||
}
|
||||
verifiedUser = res.data.data;
|
||||
@@ -64,18 +68,13 @@ export async function finishLogin({
|
||||
setUserData(verifiedUser);
|
||||
userDispatch({ type: 'login', payload: verifiedUser });
|
||||
|
||||
const message =
|
||||
successMessage === undefined ? t('登录成功!') : successMessage;
|
||||
if (message) {
|
||||
showSuccess(message);
|
||||
}
|
||||
// org_only(仅企业资源)用户默认落企业空间,与 AuthRedirect 一致:默认落地页
|
||||
// (密钥管理)挂载即调用被 BlockOrgOnlyMode 拦截的 /api/token,会先弹报错再被
|
||||
// orgConfined 踢回 /org;企业中心整体关闭时 orgConfined 不生效,会一直停在报错页
|
||||
const defaultRedirect =
|
||||
verifiedUser.org_only_mode === true ? '/org' : undefined;
|
||||
navigate(redirectOverride ?? consumePostLoginRedirect(defaultRedirect), {
|
||||
replace: true,
|
||||
});
|
||||
navigate(
|
||||
consumePostLoginRedirect({
|
||||
redirect,
|
||||
enterprise,
|
||||
orgOnly: verifiedUser.org_only_mode === true,
|
||||
}),
|
||||
{ replace: true },
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/*
|
||||
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 { CanceledError, isCancel } from 'axios';
|
||||
|
||||
const PUBLIC_API_PATH =
|
||||
/^\/api\/(?:status|setup|i18n|notice|about|privacy_policy|user_agreement|home_page_content|customer-service|verification|reset_password|oauth|user\/(?:login|register|reset|passkey\/login)|org\/(?:login|register))(?:\/|$)/;
|
||||
const READ_METHODS = new Set(['get', 'head', 'options']);
|
||||
|
||||
function isSessionBound(config) {
|
||||
const pathname = config?.url?.split(/[?#]/, 1)[0];
|
||||
return (
|
||||
config?.sessionBound !== false &&
|
||||
pathname?.startsWith('/api/') &&
|
||||
!PUBLIC_API_PATH.test(pathname)
|
||||
);
|
||||
}
|
||||
|
||||
function combineSignals(signals, config, cleanups) {
|
||||
const inputs = [...new Set(signals.filter(Boolean))];
|
||||
if (inputs.length < 2) return inputs[0];
|
||||
if (typeof AbortSignal.any === 'function') return AbortSignal.any(inputs);
|
||||
|
||||
const controller = new AbortController();
|
||||
const abort = () => controller.abort();
|
||||
for (const input of inputs) {
|
||||
if (input.aborted) abort();
|
||||
else input.addEventListener('abort', abort, { once: true });
|
||||
}
|
||||
cleanups.set(config, () => {
|
||||
for (const input of inputs) input.removeEventListener('abort', abort);
|
||||
});
|
||||
return controller.signal;
|
||||
}
|
||||
|
||||
export function installRequestLifecycle(
|
||||
instance,
|
||||
{ onError, onSessionExpired },
|
||||
) {
|
||||
const session = new AbortController();
|
||||
const cleanups = new WeakMap();
|
||||
|
||||
instance.interceptors.request.use((config) => {
|
||||
const sessionBound = isSessionBound(config);
|
||||
const read = READ_METHODS.has(config.method);
|
||||
const groupSignal = read ? config.requestGroup?.signal : undefined;
|
||||
if ((sessionBound && session.signal.aborted) || groupSignal?.aborted) {
|
||||
throw new CanceledError(undefined, config);
|
||||
}
|
||||
config.signal = combineSignals(
|
||||
[config.signal, read && sessionBound && session.signal, groupSignal],
|
||||
config,
|
||||
cleanups,
|
||||
);
|
||||
return config;
|
||||
});
|
||||
|
||||
const cleanup = (config) => {
|
||||
cleanups.get(config)?.();
|
||||
cleanups.delete(config);
|
||||
};
|
||||
|
||||
instance.interceptors.response.use(
|
||||
(response) => {
|
||||
cleanup(response.config);
|
||||
return response;
|
||||
},
|
||||
(error) => {
|
||||
const { config, response } = error;
|
||||
cleanup(config);
|
||||
const sessionBound = isSessionBound(config);
|
||||
const read = READ_METHODS.has(config?.method);
|
||||
if (isCancel(error)) throw error;
|
||||
if (sessionBound && session.signal.aborted) {
|
||||
if (read) throw new CanceledError(undefined, config);
|
||||
throw error;
|
||||
}
|
||||
if (response?.status >= 400 && read) config.requestGroup?.abort();
|
||||
|
||||
if (!config?.skipErrorHandler) {
|
||||
if (response?.status === 401 && sessionBound) {
|
||||
session.abort();
|
||||
onSessionExpired();
|
||||
} else {
|
||||
onError(error);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
|
||||
return () => session.abort();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
export const toFiniteNumber = (value) => {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : null;
|
||||
};
|
||||
|
||||
export const formatPercent = (value, digits = 1, fallback = '-') => {
|
||||
const number = toFiniteNumber(value);
|
||||
return number === null ? fallback : `${number.toFixed(digits)}%`;
|
||||
};
|
||||
|
||||
export const formatRatioPercent = (part, total, digits = 1, fallback = '-') => {
|
||||
const numerator = toFiniteNumber(part);
|
||||
const denominator = toFiniteNumber(total);
|
||||
if (numerator === null || denominator === null || denominator <= 0) {
|
||||
return fallback;
|
||||
}
|
||||
return formatPercent((numerator / denominator) * 100, digits, fallback);
|
||||
};
|
||||
|
||||
export const formatUserReference = (name, id, fallback = '-') => {
|
||||
const displayName = typeof name === 'string' ? name.trim() : name;
|
||||
if (displayName) return String(displayName);
|
||||
|
||||
const userId = toFiniteNumber(id);
|
||||
return userId === null ? fallback : `User#${userId}`;
|
||||
};
|
||||
|
||||
export const formatIdReference = (id, fallback = '-') => {
|
||||
if (id === null || id === undefined || id === '') return fallback;
|
||||
const value = String(id).trim();
|
||||
return value ? `#${value}` : fallback;
|
||||
};
|
||||
+56
-53
@@ -28,12 +28,7 @@ import {
|
||||
import { MOBILE_BREAKPOINT } from '../hooks/common/useIsMobile';
|
||||
// 官方价折扣计算(纯函数):管理端与市场页共用
|
||||
import { buildOfficialComparison, formatDiscountLabel } from './officialPrice';
|
||||
import {
|
||||
clearUserData,
|
||||
getUserData,
|
||||
isSafePostLoginRedirect,
|
||||
savePostLoginRedirect,
|
||||
} from './data';
|
||||
import { clearUserData, getUserData, isSafePostLoginRedirect } from './data';
|
||||
|
||||
const HTMLToastContent = ({ htmlContent }) => {
|
||||
return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
|
||||
@@ -128,56 +123,64 @@ if (isMobileScreen) {
|
||||
// showNoticeOptions.transition = 'flip';
|
||||
}
|
||||
|
||||
export function showError(error) {
|
||||
console.error(error);
|
||||
if (error.message) {
|
||||
if (error.name === 'AxiosError') {
|
||||
// 检查 response 是否存在(网络错误时 response 为 undefined)
|
||||
if (!error.response) {
|
||||
Toast.error(i18next.t('错误:网络请求失败,请检查网络连接'));
|
||||
return;
|
||||
}
|
||||
switch (error.response.status) {
|
||||
case 401:
|
||||
// 清除用户状态
|
||||
clearUserData();
|
||||
const currentPath = `${window.location.pathname}${window.location.search}${window.location.hash}`;
|
||||
const redirect = isSafePostLoginRedirect(currentPath)
|
||||
? `&redirect=${encodeURIComponent(currentPath)}`
|
||||
: '';
|
||||
if (redirect) {
|
||||
savePostLoginRedirect(currentPath);
|
||||
}
|
||||
// toast.error('错误:未登录或登录已过期,请重新登录!', showErrorOptions);
|
||||
// 会话过期统一回企业登录(默认登录入口),OrgLogin 会识别 expired/redirect 参数
|
||||
window.location.href = `/org/login?expired=true${redirect}`;
|
||||
break;
|
||||
case 429:
|
||||
Toast.error(i18next.t('错误:请求次数过多,请稍后再试!'));
|
||||
break;
|
||||
case 500:
|
||||
Toast.error(i18next.t('错误:服务器内部错误,请联系管理员!'));
|
||||
break;
|
||||
case 405:
|
||||
Toast.info(i18next.t('本站仅作演示之用,无服务端!'));
|
||||
break;
|
||||
default: {
|
||||
// 后端业务错误(4xx/5xx)带有面向用户的 message 字段;
|
||||
// 优先展示它,而不是 axios 的 "Request failed with status code XXX"。
|
||||
const backendMessage = error.response?.data?.message;
|
||||
Toast.error(
|
||||
i18next.t('错误:{{message}}', {
|
||||
message: backendMessage || error.message,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
let redirectingToLogin = false;
|
||||
const reportedRequestErrors = new WeakSet();
|
||||
|
||||
export function redirectToExpiredLogin() {
|
||||
if (redirectingToLogin) return;
|
||||
redirectingToLogin = true;
|
||||
clearUserData();
|
||||
const { pathname, search, hash } = window.location;
|
||||
const currentPath = `${pathname}${search}${hash}`;
|
||||
const redirect = isSafePostLoginRedirect(currentPath)
|
||||
? `&redirect=${encodeURIComponent(currentPath)}`
|
||||
: '';
|
||||
window.location.replace(`/org/login?expired=true${redirect}`);
|
||||
}
|
||||
|
||||
export function showError(error, { redirectOnUnauthorized = true } = {}) {
|
||||
if (
|
||||
error?.code === 'ERR_CANCELED' ||
|
||||
error === 'canceled' ||
|
||||
(redirectingToLogin && error === 'Request failed with status code 401')
|
||||
)
|
||||
return;
|
||||
|
||||
if (error?.isAxiosError || error?.name === 'AxiosError') {
|
||||
if (reportedRequestErrors.has(error)) return;
|
||||
reportedRequestErrors.add(error);
|
||||
|
||||
const status = error.response?.status;
|
||||
if (status === 401 && redirectOnUnauthorized) {
|
||||
redirectToExpiredLogin();
|
||||
return;
|
||||
}
|
||||
Toast.error(i18next.t('错误:{{message}}', { message: error.message }));
|
||||
} else {
|
||||
Toast.error(i18next.t('错误:{{message}}', { message: error }));
|
||||
if (status === 405) {
|
||||
Toast.info({
|
||||
key: 'http-error:405',
|
||||
content: i18next.t('本站仅作演示之用,无服务端!'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
let content;
|
||||
if (!error.response) {
|
||||
content = i18next.t('错误:网络请求失败,请检查网络连接');
|
||||
} else if (status === 429) {
|
||||
content = i18next.t('错误:请求次数过多,请稍后再试!');
|
||||
} else if (status === 500) {
|
||||
content = i18next.t('错误:服务器内部错误,请联系管理员!');
|
||||
} else {
|
||||
content = i18next.t('错误:{{message}}', {
|
||||
message: error.response.data?.message || error.message,
|
||||
});
|
||||
}
|
||||
Toast.error({ key: `http-error:${content}`, content });
|
||||
return;
|
||||
}
|
||||
console.error(error);
|
||||
Toast.error(
|
||||
i18next.t('错误:{{message}}', { message: error?.message || error }),
|
||||
);
|
||||
}
|
||||
|
||||
export function showWarning(message) {
|
||||
|
||||
Reference in New Issue
Block a user