Files
SupplierSystem/src/App.tsx
T
Ubuntu bcbca32d94
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
feat(订单): 送货单分享链接(免登录公开页 /d/<令牌>)
开发者需求:订单列表加一个分享链接,点开是一张送货单(商品名 / 单位 / 总数量 / 单价(销售价) / 金额)。

实现:
- 新表 public.order_share_links(token / branch_code / order_code / expires_at / revoked_at / created_by)
  —— 放 public 而非租户 schema:公开接口先拿 token 才知道读哪个租户,这映射天生平台级,
  且不必动 tenant_business_tables() 与新租户克隆函数
- 三个受保护接口(需 order_manage 类权限):POST/GET/DELETE /orders/:orderCode/share-link
- 公开接口 GET /api/public/delivery-note/:token(免登录、限流 60/分,投影后返回)
- 前端公开页 /d/:token(在登录守卫之外,与溯源公开页 /t/:code 同款)+ 可打印(window.print + @media print)
- 订单列表行新增「分享」(生成/复用后复制链接)与「停止分享」;列表接口用一次查询附加 share_url
- 金额大写工具 server/src/utils/amountInWords.ts(仓库此前没有)

口径(开发者 2026-10-15 裁决):
- 单价取 order_items.price(销售价),**绝不**返回 unit_cost 成本价
- **不显示「收款记录」行**(库里只有结算单级收款、没有按单收款,不编数字)
- 令牌 32 位随机、30 天过期、可撤销;**独立进货单拒绝分享**(不是给客户的货)
- 分享入口只放 Web 订单管理列表

真接口验证(本地 BR002,改后;验证后已清理:分享行 0、账号分公司还原 BR001):
- POST share-link → 32 位令牌 + public_url /d/<token> + 30 天后过期;重复调用 reused=true 同令牌
- 免登录取送货单 200:客户 财富中心 / 合计 384.00 / 叁佰捌拾肆元整 / 明细含 品名·单位·数量·单价·金额;
  返回体与明细均**无成本价字段**(已断言 cost 相关键为 0)
- 散客单 → 客户名「散客录单」;独立进货单 → 400 independent_inbound_not_shareable
- DELETE 停止分享 → 公开页立即 410 share_link_revoked
- 列表接口:有有效分享的行带 share_url,其余 null
- 前端 /d/:token 路由 200;前端与后端 npx tsc --noEmit 均 0 错误
- 全量测试:后端 26 文件/33 用例失败、前端 3 文件/6 用例失败 = 与基线一致,失败文件名无新增
  (新增测试 orderShareLink 16/16、PublicDeliveryNote.contract 10/10 全绿)
- 设计门禁 run-all.sh --verify:通过 8 / 未通过 1(check-ai-cost 既有红)/ 未执行 1 = 基线

新增界面文字(按仓库规则列出):分享 / 停止分享 / 分享链接已复制 / 生成分享链接失败 / 已停止分享
(公开页文案为单据本身:送货单、编号、产品、单位、总数量、单价、金额、备注、合计、订货电话、订货地址、制单人、收货人(签字))。

⚠️ 生效条件:服务端需部署才在线上生效(需开发者明确部署指令);前端需重新构建(部署流程内)。

设计:docs/design/20261015-订单送货单分享链接(免登录公开页).md
2026-10-15 12:37:28 +08:00

270 lines
9.5 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,
}));
/** 免登录送货单公开页(订单分享链接落地页,与 /t/:code 同款:不进登录守卫) */
const PublicDeliveryNote = lazy(async () => ({
default: (await importWithRetry(() => import('./pages/orders/PublicDeliveryNote'))).PublicDeliveryNote,
}));
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="/d/:token"
element={
<Suspense fallback={<RouteFallback />}>
<PublicDeliveryNote />
</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;