Files
SupplierSystem/src/App.tsx
T
Ubuntu e3ab44324b
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(前端路由): 失效地址不再白屏 —— 补 path="*" 全局兜底(开发者实测「网页无法进入」)
现象:开发者带 `/market-monitor` 老书签打开 8444,看到**纯白页面**,怀疑「供应商系统后端被关了」。

先证伪(nginx 日志 13:13:06 那一次,认证用户 mj):
  GET /market-monitor 304、/bundle.js 304、/api/auth/user 304、POST /api/data/query ×4 全 200
  ⇒ **后端完全正常**(3022 /api/health = ok、3021 = 200)。8444 的 Basic auth 是 2026-10-08 就有的
    nginx 配置(/etc/nginx/sites-available/supplier-dev.conf),非本次引入。

真因:客户端。`/market-monitor` 已随「隐藏市场价格监控」(8d3865a)摘除,而 App.tsx 的 <Routes>
**没有 `path="*"` 兜底** ⇒ 一条都匹配不上时 React Router 渲染 null ⇒ 整页空白、且无任何提示。
(本 SPA 原本对任何未知地址都是白屏,只是这次"以前有效的地址"变成了失效地址。)

修法(一行路由 + 回归守卫,**不回退隐藏功能**):
  · src/App.tsx:在 LayoutShell(已登录守卫)之内补 <Route path="*" element={<HomeRedirect />} />
    ⇒ 任何失效/敲错的地址自动回该账号落地页;未登录仍先送 /login。
  · 为什么不自环:兜底目标 getDefaultHomePath(...) 末位是**不需要任何权限**的 /no-access
    (该函数注释记着上一次"无权限→回首页→无权页"的自环事故)。
  · 影响面:通用兜底,所有未知地址都受益,不只修 /market-monitor。

回归守卫 src/utils/unknownRouteFallback.test.ts(4 例):`*` 路由存在、落在 LayoutShell 之内
(未登录守卫不被绕过)、任意身份不可用时目标为 /no-access、已隐藏地址确实无路由。
实测已上线:3021 提供的 bundle 里出现 `path: "*"`(webpack 重新编译成功),/market-monitor 仍 200 返回
index.html ⇒ 客户端会跳落地页而不再空白。

验证:tsc --noEmit 通过;新用例 4/4;前端全量 726 用例 / 145 文件 ⇒ 失败仅另一条工作线遗留的
SystemConfig.allowZeroCost 2 例(非本次引入);门禁同基线(8 通过 / check-ai-cost 有意为红 / verify-facts 未执行)。
设计记录:docs/design/20261027-隐藏市场价格监控功能.md §5
2026-10-11 13:20:05 +08:00

258 lines
9.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { ThemeProvider, useTheme } from './hooks/useTheme';
import { I18nProvider, useI18n } from './i18n/I18nProvider';
import { AuthProvider, useAuth, type UserRole } from './hooks/useAuth';
import { ErrorBoundary } from './components/ErrorBoundary';
import { Layout } from './components/Layout';
import { Login } from './pages/auth/Login';
import { ChangePassword } from './pages/auth/ChangePassword';
import { NoAccess } from './pages/auth/NoAccess';
import { getDefaultHomePath } from './utils/authRouting';
import { MenuLayoutProvider, useMenuLayout } from './hooks/useMenuLayout';
import { findRuntimeMenuLabelByPath } from './utils/menuLayout';
import { translateRuntimeMenuTree } from './i18n/translateMenu';
import { renderModuleRoutes } from './modules/routes';
import { importWithRetry } from './utils/lazyRetry';
const PurchaserDashboard = lazy(async () => ({
default: (await importWithRetry(() => import('./pages/purchase/PurchaserDashboard'))).PurchaserDashboard,
}));
const PublicTrace = lazy(async () => ({
default: (await importWithRetry(() => import('./pages/inventory/PublicTrace'))).PublicTrace,
}));
function RouteFallback() {
return (
<div className="min-h-[40vh] flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--app-theme-accent)]"></div>
</div>
);
}
function HomeRedirect() {
const { isLoading, profile, hasRole, hasPermission } = useAuth();
if (isLoading || !profile) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--app-theme-accent)]"></div>
</div>
);
}
return <Navigate to={getDefaultHomePath(hasRole, hasPermission)} replace />;
}
function DocumentTitle() {
const location = useLocation();
const { menuItems } = useMenuLayout();
const { t, locale } = useI18n();
const appTitle = t('layout.appTitle');
React.useEffect(() => {
const pageLabel = findRuntimeMenuLabelByPath(
translateRuntimeMenuTree(menuItems, t, locale),
location.pathname
);
document.title = pageLabel ? `${pageLabel} · ${appTitle}` : appTitle;
}, [location.pathname, menuItems, appTitle, t, locale]);
return null;
}
function LayoutShell() {
const { isLoading, isAuthenticated, profile } = useAuth();
const location = useLocation();
// 须等 session bootstrap 结束,否则刷新深链时 session 尚空会被误踢去 /login,
// 再由 PublicRoute 送回默认首页(丢失当前路由)。
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--app-theme-accent)]"></div>
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" replace state={{ from: location }} />;
}
if (!profile) {
return <Navigate to="/login" replace state={{ from: location }} />;
}
return (
<MenuLayoutProvider>
<DocumentTitle />
<Layout />
</MenuLayoutProvider>
);
}
const ProtectedRoute: React.FC<{
children: React.ReactNode;
permission?: string | string[];
roles?: UserRole | UserRole[];
/** permission+roles 同时存在时:all=AND(默认),any=OR */
accessMatch?: 'all' | 'any';
}> = ({ children, permission, roles, accessMatch = 'all' }) => {
const { isAuthenticated, isLoading, hasPermission, hasRole, profile } = useAuth();
const location = useLocation();
if (isLoading || (isAuthenticated && !profile)) {
if (!isLoading && isAuthenticated && !profile) {
return <Navigate to="/login" replace state={{ from: location }} />;
}
return (
<div className="min-h-screen flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--app-theme-accent)]"></div>
</div>
);
}
if (!isAuthenticated) {
return <Navigate to="/login" replace state={{ from: location }} />;
}
// 资料尚未带上角色/权限时先等待,避免误判无权限并踢回默认首页
if (!profile || (!profile.roles?.length && !profile.permissions?.length)) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--app-theme-accent)]"></div>
</div>
);
}
const roleOk = !roles || hasRole(roles);
const permOk = !permission || hasPermission(permission);
const allowed =
permission && roles
? accessMatch === 'any'
? roleOk || permOk
: roleOk && permOk
: roleOk && permOk;
if (!allowed) {
// 无权限:回默认首页(不是刷新丢路由;仅当前页无权时)
return <Navigate to={getDefaultHomePath(hasRole, hasPermission)} replace />;
}
return <>{children}</>;
};
const PublicRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { isAuthenticated, isLoading, profile, getHomePath } = useAuth();
const location = useLocation();
if (isLoading || (isAuthenticated && !profile)) {
if (!isLoading && isAuthenticated && !profile) {
return <>{children}</>;
}
return (
<div className="min-h-screen flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[var(--app-theme-accent)]"></div>
</div>
);
}
if (isAuthenticated) {
const from = (location.state as { from?: { pathname?: string; search?: string } } | null)?.from;
const fromPath = from?.pathname;
if (fromPath && fromPath !== '/login') {
return <Navigate to={`${fromPath}${from?.search || ''}`} replace />;
}
return <Navigate to={getHomePath()} replace />;
}
return <>{children}</>;
};
function AppContent() {
const { theme } = useTheme();
return (
<ErrorBoundary>
<div className="min-h-screen w-full" data-theme={theme}>
<BrowserRouter>
<Suspense fallback={<RouteFallback />}>
<Routes>
<Route
path="/t/:code"
element={
<Suspense fallback={<RouteFallback />}>
<PublicTrace />
</Suspense>
}
/>
<Route
path="/login"
element={
<PublicRoute>
<Login />
</PublicRoute>
}
/>
<Route
path="/change-password"
element={
<ProtectedRoute>
<ChangePassword />
</ProtectedRoute>
}
/>
{/* 无可用功能兜底页:**刻意不带任何 permission/roles**,任何已登录账号都能进。
用于「能登录但无任何可进页面」的账号(如客户门户残骸账号),避免
「无权限 → 回默认首页 → 又是无权页」的自环。见 NoAccess.tsx 顶部说明。 */}
<Route
path="/no-access"
element={
<ProtectedRoute>
<NoAccess />
</ProtectedRoute>
}
/>
<Route path="/supplier/login" element={<Navigate to="/login" replace />} />
<Route path="/purchaser/login" element={<Navigate to="/login" replace />} />
<Route path="/delivery/login" element={<Navigate to="/login" replace />} />
<Route
path="/purchaser/dashboard"
element={
<ProtectedRoute roles="purchaser">
<Suspense fallback={<RouteFallback />}>
<PurchaserDashboard />
</Suspense>
</ProtectedRoute>
}
/>
<Route path="/" element={<LayoutShell />}>
<Route index element={<HomeRedirect />} />
{renderModuleRoutes(ProtectedRoute)}
{/* 未知 / 已失效地址兜底(2026-10-11):本 SPA 原先没有 `*` 路由,
一条都没匹配上时**整页白屏**(没有任何提示)。隐藏「市场价格监控」后,
老书签 `/market-monitor` 正是这种情况(后端正常、请求全 200,用户只看到空白)。
复用首页落地逻辑:等 session bootstrap 结束再跳,且 `getDefaultHomePath`
自带 `/no-access` 兜底,不会「回首页又是无权页」自环。 */}
<Route path="*" element={<HomeRedirect />} />
</Route>
</Routes>
</Suspense>
</BrowserRouter>
</div>
</ErrorBoundary>
);
}
function App() {
return (
<I18nProvider>
<ThemeProvider>
<AuthProvider>
<AppContent />
</AuthProvider>
</ThemeProvider>
</I18nProvider>
);
}
export default App;