Commit 6742ea3c by 前端

Merge branch 'v1.0.0' into 'master'

上线合并

See merge request !3
2 parents c6da9e3a a7f56d97
Pipeline #374 for 6742ea3c failed in 0 seconds
Showing 54 changed files with 1777 additions and 290 deletions
...@@ -6,12 +6,18 @@ VITE_API_TARGET=http://192.168.3.197:8788 ...@@ -6,12 +6,18 @@ VITE_API_TARGET=http://192.168.3.197:8788
# ===== 代理 / 直连 开关(切换后端接法只需改这一行,保存后 dev server 会自动重启)===== # ===== 代理 / 直连 开关(切换后端接法只需改这一行,保存后 dev server 会自动重启)=====
# proxy (默认)前端打 /api,由 Vite 代理转发到 VITE_API_TARGET。 # proxy (默认)前端打 /api,由 Vite 代理转发到 VITE_API_TARGET。
# 浏览器只与 localhost:5173 同源通信,跨域由 Vite 服务端完成 → 不触发 CORS。 # 浏览器只与 localhost:5173 同源通信,跨域由 Vite 服务端完成 → 不触发 CORS。
# direct 浏览器直打 http://192.168.1.117:8788,不带 /api 前缀。 # direct 浏览器按「当前访问地址」动态直连后端(默认同源、映射表可改写、VITE_API_TARGET 兜底),不带 /api 前缀。
# 请求变成跨域,必须后端对当前来源返回 CORS 头(ACAO 等),否则浏览器直接拦截。 # 请求变成跨域,必须后端对当前来源返回 CORS 头(ACAO 等),否则浏览器直接拦截。
# 注意:直连时带 /api 前缀会被后端计入签名校验路径 → 与前端签的 /system/auth/login 不一致 → 10011, # 注意:直连时带 /api 前缀会被后端计入签名校验路径 → 与前端签的 /system/auth/login 不一致 → 10011,
# 故 direct 模式的 baseURL 由 VITE_API_TARGET 推导,不含 /api。改完保存即自动重启,无需手动 Ctrl+C。 # 故 direct 模式的 baseURL 由访问地址动态解析(不含 /api)。改完保存即自动重启,无需手动 Ctrl+C。
VITE_API_MODE=direct VITE_API_MODE=direct
# ===== 后端统一 context-path(所有接口前缀,纯配置,代码无默认值)=====
# 后端接口统一加在 /system 等之前的这一段路径,如 /youjia/system/auth/login。
# 前端会在「实际请求」与「签名原文第 2 行」中统一带上它,必须和后端 request.getRequestURI() 前缀一致,否则 10011。
# 留空(VITE_API_CONTEXT_PATH=)即不加任何前缀,兼容无 context-path 的后端;要加就显式写上 /youjia。
VITE_API_CONTEXT_PATH=/youjia
# ===== 密钥材料:统一放在项目根 keys/ 目录,不再写进 .env ===== # ===== 密钥材料:统一放在项目根 keys/ 目录,不再写进 .env =====
# keys/client_private.pem —— 客户端私钥(PKCS#8 PEM,请求加签),由后端交付 # keys/client_private.pem —— 客户端私钥(PKCS#8 PEM,请求加签),由后端交付
# keys/server_public.pem —— 服务端公钥(PKCS#8 PEM,响应验签) # keys/server_public.pem —— 服务端公钥(PKCS#8 PEM,响应验签)
......
...@@ -13,3 +13,35 @@ ...@@ -13,3 +13,35 @@
- 09:12 补充:聚焦(focus)时淡色背景重现。根因:新版 Chrome 在 input 聚焦时会把 autofill 背景重放一遍,且此时 `:-webkit-autofill` 伪类不稳定匹配(背景改由 UA 内联样式绘制),仅靠伪类盖不住。强化:直接对 `.uj-login-card` 内 `.ant-input` / `.ant-input-affix-wrapper` 的所有态(含 focus/hover/active/focused)强制 `background-color:#fff !important` 压过浏览器与 antd 背景,autofill 伪类仅作 box-shadow 兜底。 - 09:12 补充:聚焦(focus)时淡色背景重现。根因:新版 Chrome 在 input 聚焦时会把 autofill 背景重放一遍,且此时 `:-webkit-autofill` 伪类不稳定匹配(背景改由 UA 内联样式绘制),仅靠伪类盖不住。强化:直接对 `.uj-login-card` 内 `.ant-input` / `.ant-input-affix-wrapper` 的所有态(含 focus/hover/active/focused)强制 `background-color:#fff !important` 压过浏览器与 antd 背景,autofill 伪类仅作 box-shadow 兜底。
- 09:18 修正:用户确认淡蓝/淡黄仍未消除。根因非伪类/聚焦,而是特异性不足——antd 6 CSS-in-JS 把 .ant-input 的 background 注入到 head 末尾(晚于 design.css 加载),原选择器被 antd 规则盖过。修正:选择器重复 class 抬特异性(.ant-input.ant-input 等)+ 补全 antd6 变体(outlined/password/focused),background 改简写 #fff !important;autofill 伪类加 background:#fff !important + inset 阴影 + 9999s 过渡。 - 09:18 修正:用户确认淡蓝/淡黄仍未消除。根因非伪类/聚焦,而是特异性不足——antd 6 CSS-in-JS 把 .ant-input 的 background 注入到 head 末尾(晚于 design.css 加载),原选择器被 antd 规则盖过。修正:选择器重复 class 抬特异性(.ant-input.ant-input 等)+ 补全 antd6 变体(outlined/password/focused),background 改简写 #fff !important;autofill 伪类加 background:#fff !important + inset 阴影 + 9999s 过渡。
- 09:29 最终纠正(用户指出"第一版方向对、后续改崩了"):09:12/09:18 两版**方向全错**——autofill 淡色只能用 `box-shadow: 0 0 0 1000px #fff inset` 盖,改 `background` 无效,所以越改越没效果。聚焦态重现的真正根因是 Chrome 聚焦时用标准 `:autofill`(无前缀)伪类,第一版只盖了 `:-webkit-autofill`,漏了 `:autofill`。最终方案:删除所有 background 强制规则,回归 box-shadow inset #fff 方案,并补 `input:autofill(:hover/:focus/:active)` 覆盖聚焦态。纯 CSS,无 TS 变动。 - 09:29 最终纠正(用户指出"第一版方向对、后续改崩了"):09:12/09:18 两版**方向全错**——autofill 淡色只能用 `box-shadow: 0 0 0 1000px #fff inset` 盖,改 `background` 无效,所以越改越没效果。聚焦态重现的真正根因是 Chrome 聚焦时用标准 `:autofill`(无前缀)伪类,第一版只盖了 `:-webkit-autofill`,漏了 `:autofill`。最终方案:删除所有 background 强制规则,回归 box-shadow inset #fff 方案,并补 `input:autofill(:hover/:focus/:active)` 覆盖聚焦态。纯 CSS,无 TS 变动。
## 后端地址按访问地址动态解析(10:16)
- 诉求:direct 模式下,后端地址随「当前访问地址」自动决定(如访问 youjia.dev.glsx.com.cn → 后端 youjia.dev.glsx.com.cn),支持映射表改写为别的后端,VITE_API_TARGET 仅作兜底。
- 新增 `src/api/core/backend-resolver.ts`(浏览器侧):`resolveBackendOrigin()` 解析优先级 = 映射表 HOST_BACKEND_MAP 命中 → 默认 `window.location.origin`(同源)→ VITE_API_TARGET 兜底(非浏览器/异常 origin)。独立成模块是因为 api-mode.ts 被 Node 侧(vite.config 代理)与浏览器侧共用、禁止用 window;动态解析只能放浏览器侧,只影响 direct 模式。
- `src/api/core/config.ts`:`BACKEND_BASE_URL = API_MODE.useProxy ? '/api' : resolveBackendOrigin()`,direct 的 SIGN_CONFIG.BASE_URL 改用动态值;proxy 模式(开发代理 /api)完全不动,target 仍由 Node 侧 VITE_API_TARGET 定。
- `.env` 注释更新:VITE_API_TARGET 标注为「兜底值」。
- 风险提醒(待超人确认):direct 模式 baseURL 现在是动态 origin,它参与请求签名 canonical 第 2 行,需后端验签口径一致(按当前后端 origin),否则可能 10011。
- tsc --noEmit 通过(EXIT=0)。
## 后端地址兼容 http/https 映射(11:38)
- 诉求:映射值要兼容 http 与 https,不必写死协议。
- backend-resolver.ts 新增 `currentProtocol()`(取 window.location.protocol,非浏览器回退 https)+ `withProtocol(raw)`:已含协议原样;`//host` 协议相对→跟当前页协议;仅 host→补当前页协议。mapped 分支改用 `withProtocol(mapped)`。
- 效果:映射表写 `'192.168.1.237': 'youjia.dev.glsx.com.cn'` 时,http 访问解析为 http 后端、https 访问解析为 https 后端;写全协议则不跟随。
- 已更新映射表示例注释演示三种写法。tsc 通过(EXIT=0)。
## 后端统一 context-path /youjia 配置点(14:11)
- 诉求:后端接口统一加了 /youjia 前缀(真实路径 /youjia/system/...),问在哪里配置。
- 关键点:不能挂到 baseURL 上——baseURL 后续的 canonPath 剥离逻辑(`http.ts:67` `path.slice(basePath.length)`)会把 /youjia 一并剥掉,导致签名第 2 行仍是 /system/... 与后端 getRequestURI() 不一致 → 10011。正确做法是在请求拦截器给 `config.url` 预拼前缀。
- `src/api/core/config.ts`:新增 `API_CONTEXT_PATH` 常量(env 驱动 `VITE_API_CONTEXT_PATH`,缺省 `/youjia`,置空则无前缀)。
- `src/api/core/http.ts`:拦截器顶部按 `API_CONTEXT_PATH` 给相对路径 url 补前缀(绝对 URL/已带前缀跳过)。proxy 模式实际请求 `/api/youjia/...`(vite 代理 rewrite 仅剥 /api,保留 /youjia → 转发 /youjia/...);direct 模式 `origin/youjia/...`。两种模式的 canonPath 均正确得到 `/youjia/system/...`,与后端一致。
- `.env` 新增 `VITE_API_CONTEXT_PATH=/youjia` 及说明。
- 全程唯一 axios 实例(http.ts),无绕过拦截器的 fetch;initSign 拉公钥也统一带上前缀。tsc --noEmit 通过(EXIT=0)。
## backend-resolver 迭代:本地开发回退 + DEV 判断(15:27)
- 问题:原逻辑映射表未命中→默认同源,开发者用 192.168.x.x/localhost 访问前端时打到自己机器上不存在的后端,需每人把自己 IP 写进映射表,不可持续。
- 第一版(15:19):新增 isLocalDevHost(hostNoPort) 判断 localhost/127.0.0.1/私有网段(10.x/172.16-31.x/192.168.x/169.254.x),命中则回退 VITE_API_TARGET;映射表清空开发者 IP 示例。
- 第二版(15:27,用户提议用 DEV 判断):isLocalDevHost 按访问地址、import.meta.env.DEV 按构建模式,维度不同不能简单互替(反例:测试服务器以 IP 部署 build 产物,DEV=false 但 IP 应回退)。最终合并为 (import.meta.env.DEV || isLocalDevHost(hostNoPort)) && envTarget → 回退 envTarget;开发者 pnpm dev 零配置,测试服务器 IP 部署也能兜底。
- 文件:src/api/core/backend-resolver.ts。tsc --noEmit 通过(EXIT=0)。
# 2026-10-13 工作日志
## 请求签名 10011:半角括号 ( ) 触发签名/发送 query 编码不一致(16:04 提出,16:15 更正)
- 现象:同一 approval/pending 接口,productCategory 含半角括号 `3级(集锦)` 的请求报 10011,而含全角括号 `改装豆(原厂)` 的请求正常返回。**不是"有没有括号"的问题,是半角 `()` vs 全角 `()` 的编码差异**。
- 根因(已用 node 实测 URLSearchParams / encodeURIComponent 两种编码确认):
- 前端签名 query 原先由 `URLSearchParams.append` 构造 → 半角 `( )` 被编码成 `%28%29`;
- axios 默认用 `encodeURIComponent` 序列化 params(项目无自定义 paramsSerializer)→ 半角 `( )` **保持原样**;
- 后端按"实际收到的原始 query"验签,即 literal `( )`。于是签名里是 `%28%29`、实际收到是 `( )` → 错位 → 10011。
- 全角 `()` 在两种编码下都编成 `%EF%BC%88/%EF%BC%89`,结果一致,故全角那条始终正常,正是这个对照暴露了半角才是真凶。
- 修复(src/api/core/http.ts):query 构造由 `decodeURIComponent(encodeURIComponent(v))`(错误方向,会把原本正常的全角请求也改坏)改回**对 key/value 用 `encodeURIComponent` 重建**(与 axios 发送、后端收包口径逐字节一致);按 key 字典序排序不变。tsc --noEmit 通过(EXIT=0)。
- 教训:签名 canonical 的 query 必须与"axios 实际发出的 query"完全一致;选错编码器(URLSearchParams/encodeURIComponent/解码)都会在特殊字符上翻车,且只在含半角括号等"编码边界字符"时暴露——无括号接口编解码后对等,表现正常,容易误判。
## 签名 10011 收尾:把"其他特殊符号"一并根治(16:18 提出,已落地)
- 超人追问:问题已暴露,是否还有其他特殊符号没堵。用 node 实测 `URLSearchParams` vs `encodeURIComponent` 全量差异,结果不一致的共 5 个:半角 `()`、空格(`+`/`%20`)、`'`、`~`、`!`。`()` 已爆,其余 4 个属同级别潜伏雷(尤其空格,业务参数易含)。
- 根因共性:都是"签名用的编码器"与"axios 实际发送编码器"口径不同。逐字符打补丁是 whack-a-mole,不彻底。
- 修复(src/api/core/http.ts):新增 `serializeRequestParams(config)` + `sortParamsByKey(params)`,签名 query **直接复用 axios 自身的 `config.paramsSerializer`** 生成(数组/特殊字符等所有情况与线上逐字节同源),兜底退化为 encodeURIComponent(=axios 默认);内联在 `config.url` 的 `?x=y` 走 `full.search` 原样保留(axios 不重编码),再与 params 合并按 key 升序排序对齐后端 canonical。
- 效果:签名 query 与线上发送 query 结构性同源,任何字符(含未来新增)都不可能再出现编码分歧;不只是修了 `()`。
- tsc --noEmit 通过(EXIT=0)。
## http.ts 按功能拆分:抽出 signCanonical.ts(16:31 起,已落地)
- 超人反馈 http.ts 开始臃肿,要求把功能函数拆到 utils。新增 `src/api/core/signCanonical.ts`,收纳全部「签名 canonical 构造」纯函数(无 axios 实例依赖、无模块级状态、输入 config 输出字符串):
- `serializeRequestParams(config)`(复用 axios 自身 paramsSerializer,含 sortParamsByKey 内部辅助)
- `buildCanonicalTarget(config)` → `{ canonPath, query }`(路径斜杠压缩 + query 与线上同源,含 5 字符差异表注释)
- `extractMediaType(headers, isForm, hasBody)`
- `buildSignCanonical(parts)`(8 行 \n 拼接)、`maskDebugCanonical(canonical)`(密码脱敏)
- http.ts 仅保留:axios 实例、请求拦截(token/context-path/装配调用)、401 回调、响应拦截(验签+统一错误)、initSign/ensureSignReady。请求拦截体从 ~50 行压到 ~30 行,签名细节均委托 signCanonical。
- 行为完全保持:路径解析、query 序列化、Content-Type、canonical 拼接逐项核对与改动前一致;`existingCt` 局部变量消解(改由 extractMediaType 内部处理,末段 Content-Type 兜底改判 `!headers['Content-Type'] && !headers['content-type']`)。tsc --noEmit 通过(EXIT=0)。
...@@ -91,6 +91,6 @@ Windows 荳玖凶 `nvm use` 謠千、コ邉サ扈滄得謗・隶ソ髣ョ陲ォ諡堤サ晢シ悟庄蝨ィ邂。逅遭扈育 ...@@ -91,6 +91,6 @@ Windows 荳玖凶 `nvm use` 謠千、コ邉サ扈滄得謗・隶ソ髣ョ陲ォ諡堤サ晢シ悟庄蝨ィ邂。逅遭扈育
开发代理:`/api` → `http://192.168.3.197:8788`,配置位于 `vite.config.ts`。需处于可访问后端的内网;生产环境应配置对应网关代理。 开发代理:`/api` → `http://192.168.3.197:8788`,配置位于 `vite.config.ts`。需处于可访问后端的内网;生产环境应配置对应网关代理。
门店审批与门店列表已连接 `/store/approval/*`、`/store/listing/*`。筛选和详情共用 `src/features/store/dictionaries.ts` 本地字典,查询提交中文业务值,未知回显值原样展示;新增业务场景或产品分类在此维护。查看权限及按钮权限取登录接口的 `permCodes`;审批状态和层级以后端返回为准。详情按一条「门店+业务场景」记录展示,批量审批使用后端批量接口,重新提交入口及对接已屏蔽,导出直接下载当前筛选结果。 门店审批与门店列表已连接 `/store/approval/*`、`/store/listing/*`。业务场景和产品分类筛选使用后端分类查询接口;产品分类支持远程搜索和下拉滚动分页加载,不预先拉取全部选项,查询仍提交中文名称。详情保留 `src/features/store/dictionaries.ts` 的显示映射,未知回显值原样展示,不调用 `/store/import/spec`。查看权限及按钮权限取登录接口的 `permCodes`;审批状态和层级以后端返回为准。详情按一条「门店+业务场景」记录展示,批量审批使用后端批量接口,重新提交入口及对接已屏蔽,导出直接下载当前筛选结果。
审批和列表接口通过 `lossless-json` 保留长 ID、金额及比例原文;运营成本合计直接展示 `costTotal`,不从已格式化单价或分类明细重新计算。真实页面联调记录位于 `artifacts/store-ui-selftest-2026-10-09/`。 审批和列表接口通过 `lossless-json` 保留长 ID、金额及比例原文;运营成本合计直接展示 `costTotal`,不从已格式化单价或分类明细重新计算。真实页面联调记录位于 `artifacts/store-ui-selftest-2026-10-09/`。
...@@ -18,7 +18,7 @@ export function UModal(props: ModalProps) { ...@@ -18,7 +18,7 @@ export function UModal(props: ModalProps) {
<Modal <Modal
centered={centered} centered={centered}
destroyOnHidden={destroyOnHidden} destroyOnHidden={destroyOnHidden}
mask={mask ?? (maskClosable === undefined ? undefined : { closable: maskClosable })} mask={mask ?? (maskClosable === undefined ? { closable: false } : { closable: maskClosable })}
okButtonProps={{ type: 'primary', ...okButtonProps }} okButtonProps={{ type: 'primary', ...okButtonProps }}
{...rest} {...rest}
/> />
......
...@@ -22,7 +22,14 @@ export const PermButton = forwardRef<HTMLButtonElement, PermButtonProps>( ...@@ -22,7 +22,14 @@ export const PermButton = forwardRef<HTMLButtonElement, PermButtonProps>(
if (!ok && fallback === 'hide') return null; if (!ok && fallback === 'hide') return null;
const btn = <UButton ref={ref} {...rest} disabled={!ok || rest.disabled} />; const btn = (
<UButton
ref={ref}
{...rest}
disabled={!ok || rest.disabled}
style={rest.type === 'text' ? { ...rest.style, paddingInline: 0 } : rest.style}
/>
);
if (!ok && fallback === 'disabled' && unauthorizedTip) { if (!ok && fallback === 'disabled' && unauthorizedTip) {
return <UTooltip title={unauthorizedTip}>{btn}</UTooltip>; return <UTooltip title={unauthorizedTip}>{btn}</UTooltip>;
......
/*
* @Author: liimin 17653212@qq.com
* @Date: 2026-10-12 10:21:57
* @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2026-10-12 11:48:50
* @FilePath: \uj-store\src\api\core\backend-resolver.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
// 浏览器侧:根据「当前访问地址」动态解析后端服务地址。
// 映射表用于「访问域名 → 不同后端」的显式改写(可选,优先级最高)。
// 开发者无需在此登记自己的 IP —— 本地 / 开发地址(localhost、127.0.0.1、私有网段 IP 如 192.168.x.x)
// 会自动回退到 .env 的 VITE_API_TARGET(默认测试服务器),避免「用自己 IP 访问前端却打到自己机器上
// 根本不存在的后端」导致请求全部失败。只有正式域名(youjia.dev.glsx.com.cn 等)才走同源。
const HOST_BACKEND_MAP: Record<string, string> = {
// 例:把某个生产/预发前端域名映射到指定后端(不受本地回退规则影响)
// 'youjia.dev.glsx.com.cn': 'youjia-api.glsx.com.cn',
};
function stripTrailingSlash(url: string): string {
return url.replace(/\/+$/, '');
}
/** 当前页面协议('http:' / 'https:');非浏览器环境回退 https。 */
function currentProtocol(): string {
if (typeof window !== 'undefined' && window.location) return window.location.protocol;
return 'https:';
}
/**
* 判断 host(不含端口)是否为「本地 / 开发地址」,需要回退到 .env 默认服务端:
* - localhost / 127.0.0.1 / ::1
* - 私有网段:10.x.x.x、172.16-31.x.x、192.168.x.x、169.254.x.x(链路本地)
* 这些地址下开发者机器上通常没有后端,用同源 IP 访问必然失败。
*/
function isLocalDevHost(hostNoPort: string): boolean {
const h = hostNoPort.toLowerCase();
if (h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]') return true;
const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (!m) return false;
const a = Number(m[1]);
const b = Number(m[2]);
if (a === 10) return true; // 10.0.0.0/8
if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12
if (a === 192 && b === 168) return true; // 192.168.0.0/16
if (a === 169 && b === 254) return true; // 169.254.0.0/16 链路本地
return false;
}
/**
* 给映射值补协议,兼容 http / https:
* - 已含协议(http:// / https://)→ 原样返回;
* - 协议相对(//host)→ 跟随当前页协议;
* - 仅 host(youjia-api.xxx.com / host:port / host/path)→ 跟随当前页协议补上。
* 这样映射表不必写死协议,http 访问解析到 http 后端、https 访问解析到 https 后端。
*/
function withProtocol(raw: string): string {
const v = raw.trim();
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(v)) return v;
if (v.startsWith('//')) return currentProtocol() + v;
return currentProtocol() + '//' + v;
}
/**
* 解析 direct 模式下的后端 origin。仅在浏览器侧调用(config.ts 加载期),Node 侧不会走到此函数。
* 优先级:① 映射表 HOST_BACKEND_MAP(显式改写,最高)② 本地/开发地址(localhost、私有网段 IP)→ .env 的 VITE_API_TARGET
* ③ 非本地(正式域名)→ 同源 window.location.origin ④ 兜底 → VITE_API_TARGET
*/
export function resolveBackendOrigin(): string {
const envTarget = stripTrailingSlash(
String((import.meta.env as Record<string, string | undefined>).VITE_API_TARGET ?? '').trim(),
);
if (typeof window === 'undefined' || !window.location) return envTarget;
const host = window.location.host; // 含端口
const hostNoPort = host.split(':')[0];
const mapped = HOST_BACKEND_MAP[host] ?? HOST_BACKEND_MAP[hostNoPort];
if (mapped) return stripTrailingSlash(withProtocol(mapped));
// 开发模式(DEV,即 pnpm dev)→ 直接用 .env 默认服务端,开发者无需配自己的 IP;
// 非开发模式但用本地/私有 IP 访问(如测试服务器以 IP 部署)→ 同样回退到默认服务端;
// 正式域名(youjia.dev.glsx.com.cn 等)→ 走下方同源逻辑。
if ((import.meta.env.DEV || isLocalDevHost(hostNoPort)) && envTarget) return envTarget;
const origin = window.location.origin;
if (origin && origin !== 'null' && !origin.startsWith('file:')) return origin;
// 极端兜底:非浏览器 / origin 不可用 / env 未配置
return envTarget;
}
...@@ -2,21 +2,36 @@ ...@@ -2,21 +2,36 @@
// 规范见《优加门店上架系统 · 前后端 RSA 非对称加签对接说明》 // 规范见《优加门店上架系统 · 前后端 RSA 非对称加签对接说明》
import { resolveApiMode } from './api-mode'; import { resolveApiMode } from './api-mode';
import { resolveBackendOrigin } from './backend-resolver';
// 「代理 / 直连」单一开关。推导逻辑在 ./api-mode.ts,与 vite.config.ts 共用, // 「代理 / 直连」单一开关。推导逻辑在 ./api-mode.ts,与 vite.config.ts 共用,
// 保证 config 里的 server.proxy 与这里的 baseURL 永远一致。 // 保证 config 里的 server.proxy 与这里的 baseURL 永远一致。
export const API_MODE = resolveApiMode(import.meta.env as Record<string, string | undefined>); export const API_MODE = resolveApiMode(import.meta.env as Record<string, string | undefined>);
// 后端统一 context-path:所有接口 URL 都带此前缀(如 /youjia/system/auth/login)。
// 纯配置驱动,缺省为空(不加任何前缀)。要加就由 .env 的 VITE_API_CONTEXT_PATH 显式指定。
// 该前缀会同时出现在「实际请求路径」与「签名 canonical 第 2 行」中(见 http.ts 拦截器预拼),
// 必须和后端 request.getRequestURI() 的前缀严格一致,否则签名校验 10011。
export const API_CONTEXT_PATH = (() => {
const raw = String((import.meta.env as any).VITE_API_CONTEXT_PATH ?? '').trim();
if (!raw) return '';
return (raw.startsWith('/') ? raw : '/' + raw).replace(/\/+$/, '');
})();
// direct 模式下 baseURL 不再写死 VITE_API_TARGET,而是按「当前访问地址」动态推导
// (映射表优先、默认同源、VITE_API_TARGET 兜底,见 backend-resolver.ts);
// proxy 模式仍是同源 '/api',由 Node 侧 Vite 代理转发到 VITE_API_TARGET,与此无关。
const BACKEND_BASE_URL = API_MODE.useProxy ? '/api' : resolveBackendOrigin();
export const SIGN_CONFIG = { export const SIGN_CONFIG = {
/** 应用标识,须在服务端 app-ids 白名单内 */ /** 应用标识,须在服务端 app-ids 白名单内 */
APP_ID: 'youjia-web', APP_ID: 'youjia-web',
/** 签名算法,默认 SHA256withRSA */ /** 签名算法,默认 SHA256withRSA */
ALGORITHM: 'SHA256withRSA' as const, ALGORITHM: 'SHA256withRSA' as const,
/** 接口 baseURL(参与请求签名原文第 2 行)。 /** 接口 baseURL(参与请求签名原文第 2 行)。
* 由 VITE_API_MODE 推导,不要再手工填 VITE_API_BASE_URL:
* proxy → '/api'(相对路径,由 Vite 代理转发到 VITE_API_TARGET) * proxy → '/api'(相对路径,由 Vite 代理转发到 VITE_API_TARGET)
* direct → 后端完整地址(无 /api 前缀;带 /api 会被后端计入签名路径 → 10011) */ * direct → 按访问地址动态解析的后端完整地址(无 /api 前缀;带 /api 会被后端计入签名路径 → 10011) */
BASE_URL: API_MODE.baseURL, BASE_URL: BACKEND_BASE_URL,
}; };
// 是否启用「请求加签 + 响应验签」整套机制。 // 是否启用「请求加签 + 响应验签」整套机制。
......
...@@ -11,9 +11,15 @@ import { ...@@ -11,9 +11,15 @@ import {
setServerPublicKey, setServerPublicKey,
uuid, uuid,
} from './sign'; } from './sign';
import { SIGN_CONFIG, SIGN_ENABLED } from './config'; import { SIGN_CONFIG, SIGN_ENABLED, API_CONTEXT_PATH } from './config';
import { getToken, clearToken } from './token'; import { getToken, clearToken } from './token';
import { parseStoreResponse } from './storeJson'; import { parseStoreResponse } from './storeJson';
import {
buildCanonicalTarget,
extractMediaType,
buildSignCanonical,
maskDebugCanonical,
} from './signCanonical';
const http: AxiosInstance = axios.create({ const http: AxiosInstance = axios.create({
baseURL: SIGN_CONFIG.BASE_URL, baseURL: SIGN_CONFIG.BASE_URL,
...@@ -30,6 +36,18 @@ http.interceptors.request.use((config: any) => { ...@@ -30,6 +36,18 @@ http.interceptors.request.use((config: any) => {
if (token) headers['Authorization'] = `Bearer ${token}`; if (token) headers['Authorization'] = `Bearer ${token}`;
config.headers = headers; config.headers = headers;
// 后端统一 context-path:在 url 前补 /youjia,使「实际请求路径」与「签名 canonical 第 2 行」
// 都带上该前缀,与后端 request.getRequestURI() 对齐(否则 10011)。
// 仅相对路径补;绝对 URL(含协议)或已带该前缀则跳过。proxy / direct 两种模式统一在此处理。
if (
API_CONTEXT_PATH &&
config.url &&
!/^https?:\/\//i.test(config.url) &&
!config.url.startsWith(API_CONTEXT_PATH)
) {
config.url = API_CONTEXT_PATH + (config.url.startsWith('/') ? config.url : '/' + config.url);
}
// 未启用签名(开发期借后端宽松模式直接放行)或未配置私钥时不签名 // 未启用签名(开发期借后端宽松模式直接放行)或未配置私钥时不签名
if (!SIGN_ENABLED || !isSignReady()) return config; if (!SIGN_ENABLED || !isSignReady()) return config;
...@@ -40,54 +58,28 @@ http.interceptors.request.use((config: any) => { ...@@ -40,54 +58,28 @@ http.interceptors.request.use((config: any) => {
config.data = JSON.stringify(config.data); config.data = JSON.stringify(config.data);
} }
// 2) 解析真实 path(含 context-path)与查询串(来自 url + params,按字典序升序) // 2) 解析真实 path(含 context-path)与查询串:统一委托 signCanonical 构造。
const basePath = (config.baseURL || '').replace(/\/$/, ''); // 路径斜杠压缩、query 与 axios 线上编码同源(含 ( ) 空格 ' ~ ! 等特殊字符)等细节均在 signCanonical.ts。
let urlPath = config.url || ''; const { canonPath, query } = buildCanonicalTarget(config);
if (/^https?:\/\//i.test(urlPath)) {
const u = new URL(urlPath);
urlPath = u.pathname + u.search;
} else {
urlPath = urlPath.replace(/^\//, '');
}
// 拼接 base + path,并压缩路径中的重复斜杠。
// 注意:不能用全局 /\/{2,}/ → '/' 替换——basePath 为完整地址时会把 'http://' 压成 'http:/',
// new URL() 随即把 host:port 误当作 path,canonical 第 2 行会变成
// '/192.168.1.117:8788/system/auth/login'(正确应为 '/system/auth/login')→ 后端验签必失败。
// 故只压缩「前面不是冒号」的重复斜杠,跳过协议里的 //。
const full = new URL(`${basePath}/${urlPath}`.replace(/(^|[^:])\/{2,}/g, '$1/'), 'http://_');
if (config.params && typeof config.params === 'object') {
Object.entries(config.params).forEach(([k, v]) => {
if (v !== undefined && v !== null) full.searchParams.append(String(k), String(v));
});
}
const path = full.pathname; // 浏览器侧完整路径,直连模式下为 /system/auth/login(无 /api 前缀)
// 待签名原文的 path 必须与后端 request.getRequestURI() 一致。
// 直连模式下 baseURL 是完整地址(如 http://192.168.1.117:8788),path 不含 /api,直接作为 canonical 第 2 行;
// 与参考 sign-client.html(直连 /system/auth/login)对齐。若走代理(baseURL='/api')则此处会再摘掉 /api 前缀。
const canonPath = basePath && path.startsWith(basePath) ? path.slice(basePath.length) : path;
const query = full.search.slice(1).split('&').filter(Boolean).sort().join('&');
// 3) Content-Type 仅取媒体类型;文件上传固定 multipart/form-data,且请求体不参与签名(§3.1/§9.6) // 3) Content-Type 仅取媒体类型;文件上传固定 multipart/form-data,且请求体不参与签名(§3.1/§9.6)
const existingCt = headers['Content-Type'] || headers['content-type']; const media = extractMediaType(headers, isForm, !!config.data);
const media = isForm
? 'multipart/form-data'
: (existingCt || (config.data ? 'application/json' : '')).split(';')[0].trim().toLowerCase();
const timestamp = String(Date.now()); const timestamp = String(Date.now());
const nonce = uuid(); const nonce = uuid();
const bodyStr = isForm ? '' : config.data || ''; const bodyStr = isForm ? '' : config.data || '';
// 待签名原文:8 行 \n 连接,末尾不加换行(§3.1) // 待签名原文:8 行 \n 连接,末尾不加换行(§3.1)
const canonical = [ const canonical = buildSignCanonical({
(config.method || 'GET').toUpperCase(), method: (config.method || 'GET').toUpperCase(),
canonPath, path: canonPath,
query, query,
media, media,
timestamp, timestamp,
nonce, nonce,
APP_ID, appId: APP_ID,
bodyStr, body: bodyStr,
].join('\n'); });
const signValue = rsaSign(canonical); const signValue = rsaSign(canonical);
headers['X-App-Id'] = APP_ID; headers['X-App-Id'] = APP_ID;
...@@ -99,7 +91,7 @@ http.interceptors.request.use((config: any) => { ...@@ -99,7 +91,7 @@ http.interceptors.request.use((config: any) => {
// 调试开关(VITE_SIGN_DEBUG=true):打印待签名原文与签名头,便于后端核对 // 调试开关(VITE_SIGN_DEBUG=true):打印待签名原文与签名头,便于后端核对
// canonical/算法是否与其一致。注意:原文含请求体(登录含明文密码),仅本地调试用。 // canonical/算法是否与其一致。注意:原文含请求体(登录含明文密码),仅本地调试用。
if ((import.meta.env as any).VITE_SIGN_DEBUG === 'true') { if ((import.meta.env as any).VITE_SIGN_DEBUG === 'true') {
const safeCanonical = canonical.replace(/"password"\s*:\s*"[^"]*"/g, '"password":"***"'); const safeCanonical = maskDebugCanonical(canonical);
console.warn( console.warn(
'[sign:debug] canonical:\n' + '[sign:debug] canonical:\n' +
safeCanonical + safeCanonical +
...@@ -115,7 +107,7 @@ http.interceptors.request.use((config: any) => { ...@@ -115,7 +107,7 @@ http.interceptors.request.use((config: any) => {
}), }),
); );
} }
if (config.data && !isForm && !existingCt) { if (config.data && !isForm && !headers['Content-Type'] && !headers['content-type']) {
headers['Content-Type'] = 'application/json'; headers['Content-Type'] = 'application/json';
} }
config.headers = headers; config.headers = headers;
......
// 请求签名 canonical 构造工具(规范 §三/§五)
// 集中封装「签名算什么」所需的纯函数,与 http.ts 的请求拦截解耦,便于单测与排错。
// 本模块不依赖 axios 实例、不持有模块级状态,输入 config 输出字符串,无副作用。
// ---------- query 序列化:与 axios 线上编码同源 ----------
// 仅对纯对象按 key 升序排列(与后端 canonical 顺序一致);数组 / URLSearchParams 等保持原样交给序列化器。
function sortParamsByKey(params: any): any {
if (
!params ||
typeof params !== 'object' ||
Array.isArray(params) ||
params instanceof URLSearchParams
) {
return params;
}
const out: Record<string, any> = {};
Object.keys(params)
.filter((k) => params[k] !== undefined && params[k] !== null)
.sort()
.forEach((k) => (out[k] = params[k]));
return out;
}
// 复用 axios 自身将使用的 paramsSerializer,确保「签名算什么」==「线上发什么」。
// 未显式配置 serializer 时退化为 axios 默认口径(encodeURIComponent per key/value)。
export function serializeRequestParams(config: any): string {
const params = sortParamsByKey(config.params);
const ps = config.paramsSerializer;
if (ps && typeof ps === 'object' && typeof ps.serialize === 'function') {
return ps.serialize(params) || '';
}
if (typeof ps === 'function') return ps(params) || '';
if (params && typeof params === 'object') {
return Object.keys(params)
.filter((k) => params[k] !== undefined && params[k] !== null)
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(String(params[k]))}`)
.join('&');
}
return '';
}
// ---------- 路径与 query 解析 ----------
function normalizeBase(baseURL?: string): string {
return (baseURL || '').replace(/\/$/, '');
}
// 摘出 path + 内联 query:绝对 URL 取 pathname+search;相对路径去掉前导斜杠(交给下方 base 拼接)。
function normalizeUrlPath(url?: string): string {
let urlPath = url || '';
if (/^https?:\/\//i.test(urlPath)) {
const u = new URL(urlPath);
urlPath = u.pathname + u.search;
} else {
urlPath = urlPath.replace(/^\//, '');
}
return urlPath;
}
export interface CanonicalTarget {
canonPath: string;
query: string;
}
// 解析「签名 canonical 第 2 行 path」与「第 3 行 query」,二者同源、一次算清。
// 关键约束:
// 1) 路径只压缩「前面不是冒号」的重复斜杠(/(^|[^:])\/{2,}/g)——basePath 为完整地址时若全局替换会把
// 'http://' 压成 'http:/',new URL() 随即把 host:port 误当 path,canonical 第 2 行变成
// '/192.168.1.117:8788/system/auth/login'(正确应为 '/system/auth/login')→ 后端验签必失败。
// 2) query 必须与 axios 实际发出的 query 逐字节一致,否则后端验签 10011。
// 根因:同一份 params,URLSearchParams 与 axios 默认(encodeURIComponent)对部分字符编码口径不同:
// 半角括号 () → URLSearchParams=%28%29 / axios=( ) ★ 已爆出的 10011
// 空格 → URLSearchParams=+ / axios=%20
// 单引号 ' → URLSearchParams=%27 / axios='
// 波浪号 ~ → URLSearchParams=%7E / axios=~
// 叹号 ! → URLSearchParams=%21 / axios=!
// 故一律复用 axios 自身的 paramsSerializer 序列化 config.params(数组/特殊字符等所有情况与线上同源),
// 再与内联在 config.url 里的 ?x=y(原样保留,axios 不会重编码它)合并、按 key 升序排序。
export function buildCanonicalTarget(config: any): CanonicalTarget {
const basePath = normalizeBase(config.baseURL);
const urlPath = normalizeUrlPath(config.url);
// 只压缩「前面不是冒号」的重复斜杠,跳过协议里的 //。
const full = new URL(`${basePath}/${urlPath}`.replace(/(^|[^:])\/{2,}/g, '$1/'), 'http://_');
const path = full.pathname; // 浏览器侧完整路径,直连模式下为 /system/auth/login(无 /api 前缀)
// 直连模式下 baseURL 是完整地址(如 http://192.168.1.117:8788),path 不含 /api,直接作为 canonical 第 2 行;
// 与参考 sign-client.html(直连 /system/auth/login)对齐。若走代理(baseURL='/api')则此处会再摘掉 /api 前缀。
const canonPath = basePath && path.startsWith(basePath) ? path.slice(basePath.length) : path;
const inlineQuery = full.search.replace(/^\?/, '');
const paramsQuery = serializeRequestParams(config);
const tokens: string[] = [];
if (inlineQuery) tokens.push(...inlineQuery.split('&').filter(Boolean));
if (paramsQuery) tokens.push(...paramsQuery.split('&').filter(Boolean));
return { canonPath, query: tokens.sort().join('&') };
}
// ---------- Content-Type(仅取媒体类型) ----------
// 文件上传固定 multipart/form-data 且请求体不参与签名;其余取已有 Content-Type 或按是否有 body 补 application/json。
export function extractMediaType(
headers: Record<string, any>,
isForm: boolean,
hasBody: boolean,
): string {
const existingCt = headers['Content-Type'] || headers['content-type'];
return isForm
? 'multipart/form-data'
: (existingCt || (hasBody ? 'application/json' : '')).split(';')[0].trim().toLowerCase();
}
// ---------- canonical 拼接与脱敏 ----------
export interface SignParts {
method: string;
path: string;
query: string;
media: string;
timestamp: string;
nonce: string;
appId: string;
body: string;
}
// 待签名原文:8 行 \n 连接,末尾不加换行(§3.1)。
export function buildSignCanonical(p: SignParts): string {
return [p.method, p.path, p.query, p.media, p.timestamp, p.nonce, p.appId, p.body].join('\n');
}
// 调试脱敏:把 canonical 里的明文密码替换为 ***(VITE_SIGN_DEBUG=true 时打印用)。
export function maskDebugCanonical(canonical: string): string {
return canonical.replace(/"password"\s*:\s*"[^"]*"/g, '"password":"***"');
}
...@@ -5,6 +5,12 @@ import { setToken } from '../../core/token'; ...@@ -5,6 +5,12 @@ import { setToken } from '../../core/token';
import * as signing from '../../core/sign'; import * as signing from '../../core/sign';
import { store } from '../store'; import { store } from '../store';
// 业务路径契约独立于本机 .env 的部署前缀;公共 /youjia 前缀由 HTTP 层统一添加。
vi.mock('../../core/config', async (importOriginal) => ({
...(await importOriginal<typeof import('../../core/config')>()),
API_CONTEXT_PATH: '',
}));
const originalAdapter = http.defaults.adapter; const originalAdapter = http.defaults.adapter;
const approvalRecord = { const approvalRecord = {
listingId: '9007199254740993', listingId: '9007199254740993',
...@@ -73,6 +79,69 @@ afterEach(() => { ...@@ -73,6 +79,69 @@ afterEach(() => {
}); });
describe('store API contract', () => { describe('store API contract', () => {
it('loads scene options with flat paging and search parameters and preserves scene names', async () => {
serve((config) => {
expect(config.method).toBe('get');
expect(config.url).toBe('/store/category/scenes');
expect(config.params).toEqual({ current: 2, size: 20, name: '售后', status: 1 });
return {
data: result([
{ id: 201, name: '售后会员权益升级', baseSceneCode: '110102', status: 1 },
{ id: 202, name: '售后众筹', baseSceneCode: '110103', status: 1 },
]),
};
});
expect(await store.listScenes({ current: 2, size: 20, name: '售后', status: 1 })).toEqual([
{ id: 201, name: '售后会员权益升级', baseSceneCode: '110102', status: 1 },
{ id: 202, name: '售后众筹', baseSceneCode: '110103', status: 1 },
]);
});
it('loads only the requested goods category page and preserves its category hierarchy', async () => {
let requestCount = 0;
serve((config) => {
requestCount += 1;
expect(config.method).toBe('get');
expect(config.url).toBe('/store/category/goods/page');
expect(config.params).toEqual({ current: 3, size: 20, categoryName: '太阳膜' });
return {
data: result({
records: [
{
id: 51,
categoryType: 6,
categoryName: '太阳膜',
children: [{ id: 52, categoryType: 7, categoryName: '原厂', children: [] }],
},
],
current: 3,
size: 20,
total: 81,
pages: 5,
}),
};
});
expect(
await store.listGoodsCategories({ current: 3, size: 20, categoryName: '太阳膜' }),
).toEqual({
records: [
{
id: 51,
categoryType: 6,
categoryName: '太阳膜',
children: [{ id: 52, categoryType: 7, categoryName: '原厂', children: [] }],
},
],
current: 3,
size: 20,
total: 81,
pages: 5,
});
expect(requestCount).toBe(1);
});
it.each([ it.each([
['todo', '/store/approval/pending'], ['todo', '/store/approval/pending'],
['done', '/store/approval/done'], ['done', '/store/approval/done'],
......
...@@ -8,10 +8,14 @@ import type { ...@@ -8,10 +8,14 @@ import type {
ListingPageParams, ListingPageParams,
StoreChangeLog, StoreChangeLog,
StoreColumnConfig, StoreColumnConfig,
StoreGoodsCategory,
StoreGoodsCategoryQuery,
StoreId, StoreId,
StoreListingDetail, StoreListingDetail,
StoreListingRow, StoreListingRow,
StorePage, StorePage,
StoreScene,
StoreSceneQuery,
} from './storeTypes'; } from './storeTypes';
export * from './storeTypes'; export * from './storeTypes';
...@@ -149,6 +153,17 @@ const APPROVAL_PATHS: Record<ApproveTab, string> = { ...@@ -149,6 +153,17 @@ const APPROVAL_PATHS: Record<ApproveTab, string> = {
}; };
class Store extends ApiClient { class Store extends ApiClient {
listScenes(params: StoreSceneQuery = {}) {
return this.get<StoreScene[]>('/store/category/scenes', params as Record<string, unknown>);
}
listGoodsCategories(params: StoreGoodsCategoryQuery = {}) {
return this.get<StorePage<StoreGoodsCategory>>(
'/store/category/goods/page',
params as Record<string, unknown>,
);
}
listStores(params: ListingPageParams = {}) { listStores(params: ListingPageParams = {}) {
return this.get<StorePage<StoreListingRow>>( return this.get<StorePage<StoreListingRow>>(
'/store/listing/page', '/store/listing/page',
......
...@@ -11,6 +11,65 @@ export interface StorePage<T> { ...@@ -11,6 +11,65 @@ export interface StorePage<T> {
pages: number; pages: number;
} }
/** GET /store/category/scenes 的扁平查询参数。 */
export interface StoreSceneQuery {
current?: number;
size?: number;
name?: string;
bizTypeCode?: string;
subTypeCode?: string;
sceneType?: number;
businessType?: number;
status?: number;
baseSceneCode?: string;
}
export interface StoreScene {
id?: StoreId | null;
num?: string | null;
name?: string | null;
baseSceneCode?: string | null;
bizTypeCode?: string | null;
bizTypeName?: string | null;
subTypeCode?: string | null;
subTypeName?: string | null;
description?: string | null;
sceneType?: number | null;
businessType?: number | null;
status?: number | null;
statusName?: string | null;
tagIds?: StoreId[] | null;
tagNames?: string[] | null;
createdBy?: string | null;
createdDate?: string | null;
updatedBy?: string | null;
updatedDate?: string | null;
}
/** GET /store/category/goods/page;分类名称由后端模糊匹配。 */
export interface StoreGoodsCategoryQuery {
current?: number;
size?: number;
categoryName?: string;
}
export interface StoreGoodsCategory {
id?: StoreId | null;
categoryType?: number | null;
categoryName?: string | null;
sceneType?: string | null;
sceneName?: string | null;
createdBy?: string | null;
createdDate?: string | null;
updatedBy?: string | null;
updatedDate?: string | null;
goodsSource?: string | null;
parentId?: StoreId | null;
level?: string | null;
systemCategory?: string | null;
children?: StoreGoodsCategory[] | null;
}
export interface ApprovalPageParams { export interface ApprovalPageParams {
current?: number; current?: number;
size?: number; size?: number;
......
...@@ -76,6 +76,10 @@ export function CombiForm<T extends Record<string, unknown>>({ ...@@ -76,6 +76,10 @@ export function CombiForm<T extends Record<string, unknown>>({
<USelect <USelect
options={field.options} options={field.options}
mode={field.type === 'selectMultiple' ? 'multiple' : undefined} mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
placeholder={
field.selectProps?.placeholder ??
'请选择' + (typeof field.label === 'string' ? field.label : '')
}
disabled={disabled} disabled={disabled}
style={{ width: '100%' }} style={{ width: '100%' }}
{...field.selectProps} {...field.selectProps}
......
...@@ -79,7 +79,7 @@ export function DataTable<T extends object>({ ...@@ -79,7 +79,7 @@ export function DataTable<T extends object>({
rowSelection, rowSelection,
actionColumnTitle = '操作', actionColumnTitle = '操作',
actionColumnWidth, actionColumnWidth,
actionColumnFixed, actionColumnFixed = 'right',
toolbarClassName, toolbarClassName,
toolbarTitle, toolbarTitle,
fillHeight = false, fillHeight = false,
...@@ -126,12 +126,21 @@ export function DataTable<T extends object>({ ...@@ -126,12 +126,21 @@ export function DataTable<T extends object>({
onClick: () => void, onClick: () => void,
key: string, key: string,
isRowAction = false, isRowAction = false,
style?: CSSProperties,
) => { ) => {
const type = action.type ?? (isRowAction ? ('text' as const) : undefined);
const buttonProps = { const buttonProps = {
danger: action.danger, danger: action.danger,
disabled: action.disabled, disabled: action.disabled,
onClick, onClick,
type: action.type ?? (isRowAction ? ('link' as const) : undefined), type,
style:
isRowAction && type === 'text'
? {
color: action.danger ? 'var(--ant-color-error)' : 'var(--ant-color-primary)',
...style,
}
: style,
}; };
return action.permission ? ( return action.permission ? (
...@@ -150,12 +159,14 @@ export function DataTable<T extends object>({ ...@@ -150,12 +159,14 @@ export function DataTable<T extends object>({
key: '__actions', key: '__actions',
width: actionColumnWidth, width: actionColumnWidth,
fixed: actionColumnFixed, fixed: actionColumnFixed,
render: (_: unknown, record: T) => render: (_: unknown, record: T) => {
rowActions const visibleActions = rowActions.filter((action) => action.visible?.(record) ?? true);
.filter((action) => action.visible?.(record) ?? true) const lastPermissionActionIndex = visibleActions.reduce(
.map((action, index) => { (lastIndex, action, index) => (action.permission ? index : lastIndex),
const label = -1,
typeof action.label === 'function' ? action.label(record) : action.label; );
return visibleActions.map((action, index) => {
const label = typeof action.label === 'function' ? action.label(record) : action.label;
const danger = const danger =
typeof action.danger === 'function' ? action.danger(record) : action.danger; typeof action.danger === 'function' ? action.danger(record) : action.danger;
return renderActionButton( return renderActionButton(
...@@ -163,8 +174,12 @@ export function DataTable<T extends object>({ ...@@ -163,8 +174,12 @@ export function DataTable<T extends object>({
() => action.onClick(record), () => action.onClick(record),
`row-action-${index}`, `row-action-${index}`,
true, true,
action.permission && index < lastPermissionActionIndex
? { marginRight: 8 }
: undefined,
); );
}), });
},
} }
: undefined; : undefined;
const sourceColumns: DataTableColumnsType<T> = showIndex const sourceColumns: DataTableColumnsType<T> = showIndex
...@@ -181,6 +196,7 @@ export function DataTable<T extends object>({ ...@@ -181,6 +196,7 @@ export function DataTable<T extends object>({
] ]
: [...columns, ...(actionColumn ? [actionColumn] : [])]; : [...columns, ...(actionColumn ? [actionColumn] : [])];
const hasLineLimit = hasLineConfigured(sourceColumns); const hasLineLimit = hasLineConfigured(sourceColumns);
const minTableWidth = getMinimumTableWidth(sourceColumns);
const tableColumns = withLineLimit(sourceColumns); const tableColumns = withLineLimit(sourceColumns);
const TableComponent = fillHeight ? FillTable<T> : UTable<T>; const TableComponent = fillHeight ? FillTable<T> : UTable<T>;
return ( return (
...@@ -211,6 +227,11 @@ export function DataTable<T extends object>({ ...@@ -211,6 +227,11 @@ export function DataTable<T extends object>({
columns={tableColumns} columns={tableColumns}
tableLayout={hasLineLimit ? 'fixed' : undefined} tableLayout={hasLineLimit ? 'fixed' : undefined}
rowSelection={resolvedSelection} rowSelection={resolvedSelection}
scroll={{ ...props.scroll, x: props.scroll?.x ?? minTableWidth }}
styles={{
header: { cell: { paddingLeft: 20 } },
body: { cell: { paddingLeft: 20 } },
}}
pagination={ pagination={
resolvedPagination === false resolvedPagination === false
? false ? false
...@@ -247,6 +268,15 @@ function hasLineConfigured<T extends object>(columns: ColumnsType<T>): boolean { ...@@ -247,6 +268,15 @@ function hasLineConfigured<T extends object>(columns: ColumnsType<T>): boolean {
}); });
} }
function getMinimumTableWidth<T extends object>(columns: ColumnsType<T>): number {
return columns.reduce((width, column) => {
if ('children' in column && column.children) {
return width + getMinimumTableWidth(column.children);
}
return width + (typeof column.width === 'number' ? column.width : 120);
}, 0);
}
function withLineLimit<T extends object>(columns: DataTableColumnsType<T>): ColumnsType<T> { function withLineLimit<T extends object>(columns: DataTableColumnsType<T>): ColumnsType<T> {
return columns.map((column) => { return columns.map((column) => {
if ('children' in column && column.children) { if ('children' in column && column.children) {
...@@ -285,5 +315,7 @@ function lineStyle(line: number): CSSProperties { ...@@ -285,5 +315,7 @@ function lineStyle(line: number): CSSProperties {
overflow: 'hidden', overflow: 'hidden',
WebkitBoxOrient: 'vertical', WebkitBoxOrient: 'vertical',
WebkitLineClamp: line, WebkitLineClamp: line,
whiteSpace: 'pre-wrap',
overflowWrap: 'anywhere',
}; };
} }
...@@ -45,6 +45,7 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -45,6 +45,7 @@ export function SearchForm<T extends Record<string, unknown>>({
style={{ width }} style={{ width }}
options={field.options} options={field.options}
mode={field.type === 'selectMultiple' ? 'multiple' : undefined} mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
{...field.selectProps}
/> />
); );
if (field.type === 'cascader') if (field.type === 'cascader')
......
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
// 共五个状态覆盖全部生命周期,其中仅「已生效」可对外展示(门店列表只展示已生效数据)。 // 共五个状态覆盖全部生命周期,其中仅「已生效」可对外展示(门店列表只展示已生效数据)。
export type StoreStatus = 'PENDING' | 'APPROVED' | 'REJECTED' | 'REVOKED' | 'VOID'; export type StoreStatus = 'PENDING' | 'APPROVED' | 'REJECTED' | 'REVOKED' | 'VOID';
// 状态徽标配色规范(待审批黄 / 已生效绿 / 已打回红 / 已撤回灰 / 已作废灰) // 状态徽标配色规范(待审批黄 / 已生效蓝 / 已打回红 / 已撤回灰 / 已作废灰)
export const STORE_STATUS: Record<StoreStatus, { label: string; color: string }> = { export const STORE_STATUS: Record<StoreStatus, { label: string; color: string }> = {
PENDING: { label: '待审批', color: 'gold' }, PENDING: { label: '待审批', color: 'gold' },
APPROVED: { label: '已生效', color: 'green' }, APPROVED: { label: '已生效', color: 'blue' },
REJECTED: { label: '已打回', color: 'red' }, REJECTED: { label: '已打回', color: 'red' },
REVOKED: { label: '已撤回', color: '#8A94A6' }, REVOKED: { label: '已撤回', color: '#8A94A6' },
VOID: { label: '已作废', color: '#C9CED6' }, VOID: { label: '已作废', color: '#C9CED6' },
......
...@@ -32,7 +32,7 @@ interface FlowStage { ...@@ -32,7 +32,7 @@ interface FlowStage {
key: string; key: string;
title: string; title: string;
state: StageState; state: StageState;
number?: number; number: number;
actor?: string | null; actor?: string | null;
time?: string | null; time?: string | null;
caption?: string; caption?: string;
...@@ -101,10 +101,10 @@ function ApprovalStatus({ detail }: { detail: StoreListingDetail }) { ...@@ -101,10 +101,10 @@ function ApprovalStatus({ detail }: { detail: StoreListingDetail }) {
} }
function StageIcon({ state, number }: { state: StageState; number?: number }) { function StageIcon({ state, number }: { state: StageState; number?: number }) {
if (number !== undefined) return <>{number}</>;
if (state === 'rejected') return <CloseOutlined />; if (state === 'rejected') return <CloseOutlined />;
if (state === 'stopped') return <MinusOutlined />; if (state === 'stopped') return <MinusOutlined />;
if (state === 'done' || number === undefined) return <CheckOutlined />; return <CheckOutlined />;
return <>{number}</>;
} }
export function ApprovalDetailHeader({ export function ApprovalDetailHeader({
...@@ -174,6 +174,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) { ...@@ -174,6 +174,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
{ {
key: 'submit', key: 'submit',
title: '提交', title: '提交',
number: 1,
state: 'done', state: 'done',
actor: detail.submitUserName || EMPTY, actor: detail.submitUserName || EMPTY,
time: detail.submitTime, time: detail.submitTime,
...@@ -198,7 +199,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) { ...@@ -198,7 +199,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
return { return {
key: title, key: title,
title, title,
number: index + 1, number: index + 2,
state, state,
actor: done ? passedLog?.operatorName : undefined, actor: done ? passedLog?.operatorName : undefined,
time: done ? passedLog?.operateTime : undefined, time: done ? passedLog?.operateTime : undefined,
...@@ -215,6 +216,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) { ...@@ -215,6 +216,7 @@ export function ApprovalStages({ detail }: { detail: StoreListingDetail }) {
{ {
key: 'effective', key: 'effective',
title: '生效', title: '生效',
number: roles.length + 2,
state: approved ? 'done' : stopped ? 'stopped' : 'waiting', state: approved ? 'done' : stopped ? 'stopped' : 'waiting',
time: approved ? (detail.effectiveTime ?? detail.approveTime) : undefined, time: approved ? (detail.effectiveTime ?? detail.approveTime) : undefined,
caption: approved ? undefined : stopped || rejected ? '未生效' : '写入门店列表', caption: approved ? undefined : stopped || rejected ? '未生效' : '写入门店列表',
...@@ -276,7 +278,7 @@ export function ApprovalAuditTrail({ ...@@ -276,7 +278,7 @@ export function ApprovalAuditTrail({
const approved = detail.status === 'APPROVED'; const approved = detail.status === 'APPROVED';
const showHours = const showHours =
typeof pendingHours === 'number' && Number.isFinite(pendingHours) && pendingHours >= 0; typeof pendingHours === 'number' && Number.isFinite(pendingHours) && pendingHours >= 0;
const futureCaption = roles.length === 1 ? '通过后即可生效' : '全部审批节点通过后自动生效'; const futureCaption = level === roles.length ? '通过后即可生效' : '全部审批节点通过后自动生效';
return ( return (
<section className="approval-detail-audit" aria-label="审批留痕列表"> <section className="approval-detail-audit" aria-label="审批留痕列表">
...@@ -330,6 +332,22 @@ export function ApprovalAuditTrail({ ...@@ -330,6 +332,22 @@ export function ApprovalAuditTrail({
</div> </div>
</div> </div>
</article> </article>
{roles.slice(level).map((role, index) => (
<article key={role} className="approval-detail-chaincard" aria-label="后续审批节点">
<span
className="approval-detail-chaincard__icon approval-detail-chaincard__icon--waiting"
aria-hidden="true"
>
{level + index + 1}
</span>
<div className="approval-detail-chaincard__content">
<div className="approval-detail-chaincard__title">
{role} · 第 {level + index + 1} 级审批节点(待流转)
</div>
<div className="approval-detail-chaincard__meta">待前序节点通过</div>
</div>
</article>
))}
<article className="approval-detail-chaincard" aria-label="待生效节点"> <article className="approval-detail-chaincard" aria-label="待生效节点">
<span <span
className="approval-detail-chaincard__icon approval-detail-chaincard__icon--waiting" className="approval-detail-chaincard__icon approval-detail-chaincard__icon--waiting"
......
...@@ -66,9 +66,11 @@ function ListingStatus({ detail }: { detail: StoreListingDetail }) { ...@@ -66,9 +66,11 @@ function ListingStatus({ detail }: { detail: StoreListingDetail }) {
export function ListingDetailHeader({ export function ListingDetailHeader({
detail, detail,
spec,
onClose, onClose,
}: { }: {
detail: StoreListingDetail; detail: StoreListingDetail;
spec?: StoreDictionaries;
onClose: () => void; onClose: () => void;
}) { }) {
return ( return (
...@@ -93,7 +95,7 @@ export function ListingDetailHeader({ ...@@ -93,7 +95,7 @@ export function ListingDetailHeader({
</div> </div>
<div> <div>
<dt>业务场景</dt> <dt>业务场景</dt>
<dd>{detail.businessScene?.trim() ? '1 个' : EMPTY}</dd> <dd>{dictionaryLabel(spec?.businessScenes, detail.businessScene?.trim())}</dd>
</div> </div>
<div> <div>
<dt>产品分类</dt> <dt>产品分类</dt>
......
...@@ -150,7 +150,7 @@ describe('store detail presentation', () => { ...@@ -150,7 +150,7 @@ describe('store detail presentation', () => {
}); });
const overview = within(screen.getByLabelText('门店概览')); const overview = within(screen.getByLabelText('门店概览'));
expect(overview.getByRole('heading', { name: '当前门店' })).toBeInTheDocument(); expect(overview.getByRole('heading', { name: '当前门店' })).toBeInTheDocument();
for (const text of ['SQ001', '1 个', '6 个', '2026-10-09', 'v3', '已生效']) { for (const text of ['SQ001', '售后会员权益升级', '6 个', '2026-10-09', 'v3', '已生效']) {
expect(overview.getByText(text)).toBeInTheDocument(); expect(overview.getByText(text)).toBeInTheDocument();
} }
expect(overview.queryByText('提交人')).not.toBeInTheDocument(); expect(overview.queryByText('提交人')).not.toBeInTheDocument();
...@@ -166,7 +166,7 @@ describe('store detail presentation', () => { ...@@ -166,7 +166,7 @@ describe('store detail presentation', () => {
expect(onClose).toHaveBeenCalledOnce(); expect(onClose).toHaveBeenCalledOnce();
}); });
it('does not invent a version or scene count when listing fields are missing', () => { it('does not invent a version or scene when listing fields are missing', () => {
show({ show({
mode: 'listing', mode: 'listing',
detail: { detail: {
...@@ -179,6 +179,7 @@ describe('store detail presentation', () => { ...@@ -179,6 +179,7 @@ describe('store detail presentation', () => {
}); });
const overview = within(screen.getByLabelText('门店概览')); const overview = within(screen.getByLabelText('门店概览'));
expect(overview.getByText('当前版本')).toBeInTheDocument(); expect(overview.getByText('当前版本')).toBeInTheDocument();
expect(overview.getByText('业务场景').nextElementSibling).toHaveTextContent('—');
expect(overview.queryByText(/^v\d/)).not.toBeInTheDocument(); expect(overview.queryByText(/^v\d/)).not.toBeInTheDocument();
expect(overview.queryByText('1 个')).not.toBeInTheDocument(); expect(overview.queryByText('1 个')).not.toBeInTheDocument();
expect(overview.queryByText('0 个')).not.toBeInTheDocument(); expect(overview.queryByText('0 个')).not.toBeInTheDocument();
...@@ -272,7 +273,46 @@ describe('store detail presentation', () => { ...@@ -272,7 +273,46 @@ describe('store detail presentation', () => {
const flow = within(screen.getByLabelText('审批流程')); const flow = within(screen.getByLabelText('审批流程'));
expect(flow.queryByText('优加商务经理')).not.toBeInTheDocument(); expect(flow.queryByText('优加商务经理')).not.toBeInTheDocument();
expect(flow.getByText('优加财务经理')).toBeInTheDocument(); expect(flow.getByText('优加财务经理')).toBeInTheDocument();
for (const [title, number] of [
['提交', '1'],
['优加财务经理', '2'],
['生效', '3'],
]) {
const stage = flow.getByText(title).closest('li')!;
expect(within(stage).getByText(number)).toBeInTheDocument();
}
});
it.each(['PENDING', 'APPROVED', 'REJECTED', 'REVOKED'] as const)(
'keeps all flow nodes continuously numbered after the flow advances to %s',
(status) => {
show({
detail: {
...detail,
status,
currentLevel: 2,
approvalLogs: [
{
action: 'PASS',
operatorRole: 'YJ_BUSINESS_MGR',
operatorName: '商务甲',
operateTime: '2026-10-09T11:00:00',
},
],
},
}); });
const flow = within(screen.getByLabelText('审批流程'));
for (const [title, number] of [
['提交', '1'],
['优加商务经理', '2'],
['优加财务经理', '3'],
['生效', '4'],
]) {
const stage = flow.getByText(title).closest('li')!;
expect(within(stage).getByText(number)).toBeInTheDocument();
}
},
);
it('does not describe a rejected record as awaiting approval and preserves the audit reason', () => { it('does not describe a rejected record as awaiting approval and preserves the audit reason', () => {
show({ detail: { ...detail, status: 'REJECTED', rejectReason: '请核对政策' } }); show({ detail: { ...detail, status: 'REJECTED', rejectReason: '请核对政策' } });
...@@ -285,6 +325,40 @@ describe('store detail presentation', () => { ...@@ -285,6 +325,40 @@ describe('store detail presentation', () => {
expect(screen.getByText(/192\.0\.2\.1/)).toBeInTheDocument(); expect(screen.getByText(/192\.0\.2\.1/)).toBeInTheDocument();
}); });
it('includes the future finance node between the current business node and activation', () => {
show({
initialTab: 'logs',
detail: {
...detail,
approvalLogs: [
{ action: 'SUBMIT', operatorName: '运营甲', operateTime: detail.submitTime },
],
},
});
const trail = within(screen.getByLabelText('审批留痕列表'));
const cards = trail.getAllByRole('article');
expect(cards).toHaveLength(4);
expect(cards[1]).toHaveTextContent('优加商务经理');
expect(cards[2]).toHaveTextContent('优加财务经理');
expect(cards[2]).toHaveTextContent('待前序节点通过');
expect(cards[2]).not.toHaveTextContent('当前节点');
expect(cards[3]).toHaveTextContent('生效 · 写入门店列表');
});
it.each([1, 2])(
'does not duplicate finance or imply more approval at final level %s',
(totalLevel) => {
show({
initialTab: 'logs',
detail: { ...detail, totalLevel, currentLevel: totalLevel, approvalLogs: [] },
});
const trail = within(screen.getByLabelText('审批留痕列表'));
expect(trail.getAllByText(/优加财务经理/)).toHaveLength(1);
expect(trail.queryByLabelText('后续审批节点')).not.toBeInTheDocument();
expect(trail.getByLabelText('当前审批节点')).toHaveTextContent('通过后即可生效');
},
);
it('opens listing history directly and shows newest changes first', () => { it('opens listing history directly and shows newest changes first', () => {
show({ mode: 'listing', initialTab: 'history', detail: { ...detail, status: 'APPROVED' } }); show({ mode: 'listing', initialTab: 'history', detail: { ...detail, status: 'APPROVED' } });
expect(screen.getByRole('tab', { name: '变更历史' })).toHaveAttribute('aria-selected', 'true'); expect(screen.getByRole('tab', { name: '变更历史' })).toHaveAttribute('aria-selected', 'true');
......
...@@ -200,7 +200,7 @@ export function StoreDetailDrawer({ ...@@ -200,7 +200,7 @@ export function StoreDetailDrawer({
title={ title={
showCustomHeader ? ( showCustomHeader ? (
mode === 'listing' ? ( mode === 'listing' ? (
<ListingDetailHeader detail={detail!} onClose={onClose} /> <ListingDetailHeader detail={detail!} spec={spec} onClose={onClose} />
) : ( ) : (
<ApprovalDetailHeader detail={detail!} spec={spec} onClose={onClose} /> <ApprovalDetailHeader detail={detail!} spec={spec} onClose={onClose} />
) )
......
...@@ -72,8 +72,8 @@ ...@@ -72,8 +72,8 @@
} }
.approval-detail-status--approved { .approval-detail-status--approved {
background: #e6f5ee; background: var(--ant-color-primary-bg, #eef3ff);
color: #087b54; color: var(--uj-primary, #2b5ce6);
} }
.approval-detail-status--rejected { .approval-detail-status--rejected {
...@@ -141,8 +141,8 @@ ...@@ -141,8 +141,8 @@
.approval-detail-flow__heading > span { .approval-detail-flow__heading > span {
padding: 1px 8px; padding: 1px 8px;
border-radius: 4px; border-radius: 4px;
background: #e4f5f4; background: var(--ant-color-primary-bg, #eef3ff);
color: #008f88; color: var(--uj-primary, #2b5ce6);
font-size: 13px; font-size: 13px;
line-height: 22px; line-height: 22px;
} }
...@@ -176,7 +176,7 @@ ...@@ -176,7 +176,7 @@
} }
.approval-detail-flow__node--done:not(:last-child)::after { .approval-detail-flow__node--done:not(:last-child)::after {
background: #0da370; background: var(--uj-primary, #2b5ce6);
} }
.approval-detail-flow__icon { .approval-detail-flow__icon {
...@@ -197,8 +197,8 @@ ...@@ -197,8 +197,8 @@
.approval-detail-flow__node--done .approval-detail-flow__icon, .approval-detail-flow__node--done .approval-detail-flow__icon,
.approval-detail-chaincard__icon--done { .approval-detail-chaincard__icon--done {
border-color: #0da370; border-color: var(--uj-primary, #2b5ce6);
background: #0da370; background: var(--uj-primary, #2b5ce6);
color: #fff; color: #fff;
} }
......
...@@ -47,8 +47,8 @@ ...@@ -47,8 +47,8 @@
max-width: 280px; max-width: 280px;
padding: 1px 7px; padding: 1px 7px;
border-radius: 4px; border-radius: 4px;
background: #e4f5f4; background: var(--ant-color-primary-bg, #eef3ff);
color: #07796f; color: var(--uj-primary, #2b5ce6);
font-size: 12px; font-size: 12px;
font-weight: 500; font-weight: 500;
line-height: 20px; line-height: 20px;
......
...@@ -12,9 +12,9 @@ const textOptions = (values: string[]): DictOption[] => ...@@ -12,9 +12,9 @@ const textOptions = (values: string[]): DictOption[] =>
values.map((value) => ({ value, label: value })); values.map((value) => ({ value, label: value }));
/** /**
* 门店筛选和详情共用的本地字典;查询接口接收中文业务值。 * 详情展示所用的本地映射和计算规则字典;未知业务名称原样回显。
* 来源:2026-10-09 导入模板的计算/是否取值、模板示例及已返回的门店记录。 * 来源:2026-10-09 导入模板的计算/是否取值、模板示例及已返回的门店记录。
* 模板未提供完整场景/分类目录;新增业务值在此维护,未知回显值仍原样展示。 * 场景/分类目录仅含历史示例,不用于筛选;筛选选项由分类查询接口提供。
*/ */
export const STORE_DICTIONARIES: StoreDictionaries = { export const STORE_DICTIONARIES: StoreDictionaries = {
businessScenes: textOptions(['售后众筹', '精品升级', '售后会员权益升级', '售前延保']), businessScenes: textOptions(['售后众筹', '精品升级', '售后会员权益升级', '售前延保']),
......
...@@ -93,8 +93,8 @@ ...@@ -93,8 +93,8 @@
} }
.listing-detail-status--approved { .listing-detail-status--approved {
background: #e6f5ee; background: var(--ant-color-primary-bg, #eef3ff);
color: #087b54; color: var(--uj-primary, #2b5ce6);
} }
.listing-detail-status--pending { .listing-detail-status--pending {
...@@ -198,8 +198,8 @@ ...@@ -198,8 +198,8 @@
max-width: 100%; max-width: 100%;
padding: 1px 8px; padding: 1px 8px;
border-radius: 4px; border-radius: 4px;
background: #e4f5f4; background: var(--ant-color-primary-bg, #eef3ff);
color: #008f88; color: var(--uj-primary, #2b5ce6);
font-size: 13px; font-size: 13px;
line-height: 22px; line-height: 22px;
} }
......
import type { PropsWithChildren } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
act,
cleanup,
fireEvent,
render,
renderHook,
screen,
waitFor,
} from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useStoreFilterOptions } from './useStoreFilterOptions';
const api = vi.hoisted(() => ({ listScenes: vi.fn(), listGoodsCategories: vi.fn() }));
vi.mock('@/api', () => ({ store: api }));
const clients: QueryClient[] = [];
function setup(enabled = true, includeProducts = true) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
clients.push(client);
const wrapper = ({ children }: PropsWithChildren) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
);
return renderHook(() => useStoreFilterOptions({ enabled, includeProducts }), { wrapper });
}
const bottomScroll = {
currentTarget: { scrollHeight: 320, scrollTop: 280, clientHeight: 40 },
} as React.UIEvent<HTMLDivElement>;
beforeEach(() => {
vi.resetAllMocks();
api.listScenes.mockResolvedValue([{ name: '接口新增场景' }]);
api.listGoodsCategories.mockResolvedValue({
records: [{ categoryName: '接口新增分类' }],
current: 1,
size: 20,
total: 1,
pages: 1,
});
});
afterEach(() => {
cleanup();
clients.forEach((client) => client.clear());
clients.length = 0;
});
describe('store remote filter options', () => {
it('loads only one page, appends on scroll, and stops at the last page', async () => {
api.listGoodsCategories.mockImplementation(async ({ current }) => ({
records:
current === 1
? [
{
categoryName: '车辆美容',
children: [
{
categoryName: '车辆美容2级',
children: [{ categoryName: '车辆美容3级(集采)' }],
},
],
},
]
: [{ categoryName: '车辆美容' }, { categoryName: '第二页分类' }],
current,
size: 20,
total: 21,
pages: 2,
}));
const { result } = setup();
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '车辆美容-车辆美容2级',
label: '车辆美容-车辆美容2级',
}),
);
expect(api.listGoodsCategories).toHaveBeenCalledTimes(1);
expect(api.listGoodsCategories).toHaveBeenCalledWith({
current: 1,
size: 20,
categoryName: undefined,
});
act(() => {
result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll);
result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll);
});
await waitFor(() =>
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'车辆美容',
'车辆美容-车辆美容2级',
'车辆美容-车辆美容2级-车辆美容3级(集采)',
'第二页分类',
]),
);
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
expect(api.listGoodsCategories).toHaveBeenCalledTimes(2);
});
it('debounces remote search, resets pagination, and ignores an older search response', async () => {
let resolveOld!: (value: unknown) => void;
const response = (name: string) => ({
records: [{ categoryName: name }],
current: 1,
size: 20,
total: 1,
pages: 1,
});
api.listGoodsCategories.mockImplementation(({ categoryName }) =>
categoryName === '旧搜索'
? new Promise((resolve) => {
resolveOld = resolve;
})
: Promise.resolve(response(categoryName || '初始分类')),
);
const { result } = setup();
await waitFor(() => expect(result.current.productCategory.options).toHaveLength(2));
const search = (text: string) => {
const config = result.current.productCategory.selectProps.showSearch;
if (typeof config === 'object') config.onSearch?.(text);
};
act(() => {
search('旧');
search('旧搜索');
});
expect(api.listGoodsCategories).toHaveBeenCalledTimes(1);
await waitFor(() =>
expect(api.listGoodsCategories).toHaveBeenCalledWith({
current: 1,
size: 20,
categoryName: '旧搜索',
}),
);
act(() => search('新搜索'));
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '新搜索',
label: '新搜索',
}),
);
await act(async () => resolveOld(response('旧搜索结果')));
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'新搜索',
]);
act(() => result.current.reset());
await waitFor(() =>
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'初始分类',
]),
);
});
it('uses scene names from the endpoint and skips product calls on the listing page', async () => {
const { result } = setup(true, false);
await waitFor(() =>
expect(result.current.businessScene.options).toContainEqual({
value: '接口新增场景',
label: '接口新增场景',
}),
);
expect(api.listGoodsCategories).not.toHaveBeenCalled();
});
it('can paginate a new keyword while an older keyword page is still loading', async () => {
let resolveOld!: (value: unknown) => void;
const page = (current: number, name: string) => ({
records: [{ categoryName: name }],
current,
size: 20,
total: 21,
pages: 2,
});
api.listGoodsCategories.mockImplementation(({ current, categoryName }) =>
!categoryName && current === 2
? new Promise((resolve) => {
resolveOld = resolve;
})
: Promise.resolve(page(current, `${categoryName || '初始'}${current}`)),
);
const { result } = setup();
await waitFor(() => expect(result.current.productCategory.options).toHaveLength(2));
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
act(() => {
const config = result.current.productCategory.selectProps.showSearch;
if (typeof config === 'object') config.onSearch?.('新词');
});
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '新词1',
label: '新词1',
}),
);
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
await waitFor(() =>
expect(result.current.productCategory.options).toContainEqual({
value: '新词2',
label: '新词2',
}),
);
await act(async () => resolveOld(page(2, '旧页')));
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'新词1',
'新词2',
]);
});
it('preserves loaded options when loading more fails and retries the same page', async () => {
api.listGoodsCategories
.mockResolvedValueOnce({
records: [{ categoryName: '第一页' }],
current: 1,
size: 20,
total: 21,
pages: 2,
})
.mockRejectedValueOnce(new Error('网络异常'))
.mockResolvedValueOnce({
records: [{ categoryName: '第二页' }],
current: 2,
size: 20,
total: 21,
pages: 2,
});
const { result } = setup();
await waitFor(() => expect(result.current.productCategory.options).toHaveLength(2));
act(() => result.current.productCategory.selectProps.onPopupScroll?.(bottomScroll));
await waitFor(() => expect(api.listGoodsCategories).toHaveBeenCalledTimes(2));
await waitFor(() => expect(result.current.productCategory.selectProps.loading).toBe(false));
expect(result.current.productCategory.options[1].value).toBe('第一页');
render(<>{result.current.productCategory.selectProps.popupRender?.(<div />)}</>);
fireEvent.click(screen.getByRole('button', { name: '加载失败,点击重试' }));
await waitFor(() =>
expect(result.current.productCategory.options.map((option) => option.value)).toEqual([
'',
'第一页',
'第二页',
]),
);
expect(api.listGoodsCategories).toHaveBeenLastCalledWith({
current: 2,
size: 20,
categoryName: undefined,
});
});
it('does not load dictionaries without view permission', async () => {
setup(false);
await act(async () => {});
expect(api.listScenes).not.toHaveBeenCalled();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
});
});
import { useEffect, useRef, useState } from 'react';
import { useInfiniteQuery } from '@tanstack/react-query';
import type { SelectProps } from 'antd';
import { UButton } from '@uj/ui';
import { store, type StoreGoodsCategory } from '@/api';
import type { FieldOption } from '@/components/formSchema';
const PAGE_SIZE = 20;
const ALL: FieldOption = { value: '', label: '全部' };
type OptionKind = 'scenes' | 'goods';
interface OptionPage {
options: FieldOption[];
next?: number;
}
function nameOptions(names: (string | null | undefined)[]): FieldOption[] {
return [
...new Set(names.map((name) => name?.trim()).filter((name): name is string => !!name)),
].map((name) => ({ value: name, label: name }));
}
function categoryNames(categories: StoreGoodsCategory[], ancestors: string[] = []): string[] {
return categories.flatMap((category) => {
const name = category.categoryName?.trim();
const path = name ? [...ancestors, name] : ancestors;
// 门店导入/审批记录存的是以“-”连接的完整分类路径,而字典 children 是分层名称。
return [...(name ? [path.join('-')] : []), ...categoryNames(category.children ?? [], path)];
});
}
/** 筛选接口仍接收名称;字典 ID 只属于字典接口,不能代替查询值。 */
async function loadOptions(
kind: OptionKind,
current: number,
keyword: string,
): Promise<OptionPage> {
if (kind === 'goods') {
const page = await store.listGoodsCategories({
current,
size: PAGE_SIZE,
categoryName: keyword || undefined,
});
return {
options: nameOptions(categoryNames(page.records ?? [])),
next: page.records?.length && page.current < page.pages ? page.current + 1 : undefined,
};
}
const scenes = await store.listScenes({ current, size: PAGE_SIZE, name: keyword || undefined });
return {
options: nameOptions((scenes ?? []).map((scene) => scene.name)),
// 场景接口返回数组,没有 total/pages;不足一页表示已加载完。
next: scenes?.length >= PAGE_SIZE ? current + 1 : undefined,
};
}
function useRemoteOptions(kind: OptionKind, enabled: boolean) {
const [search, setSearch] = useState('');
const [keyword, setKeyword] = useState('');
const fetchingNext = useRef<string | undefined>(undefined);
useEffect(() => {
const timer = window.setTimeout(() => setKeyword(search.trim()), 300);
return () => window.clearTimeout(timer);
}, [search]);
const query = useInfiniteQuery({
queryKey: ['store', 'filter-options', kind, keyword],
queryFn: ({ pageParam }) => loadOptions(kind, pageParam, keyword),
initialPageParam: 1,
getNextPageParam: (last, pages) => {
if (kind === 'scenes' && pages.length > 1) {
const previous = new Set(
pages.slice(0, -1).flatMap((page) => page.options.map((option) => option.value)),
);
// 兼容返回全量数组的场景服务,避免一直请求相同数据。
if (last.options.every((option) => previous.has(option.value))) return undefined;
}
return last.next;
},
enabled,
staleTime: 5 * 60_000,
retry: false,
});
const searching = search.trim() !== keyword;
const options = [ALL];
const seen = new Set<string | number>(['']);
for (const page of searching ? [] : (query.data?.pages ?? [])) {
for (const option of page.options) {
if (!seen.has(option.value)) {
seen.add(option.value);
options.push(option);
}
}
}
const reset = () => {
setSearch('');
setKeyword('');
};
const loadMore = () => {
if (
!enabled ||
searching ||
!query.hasNextPage ||
query.isFetching ||
fetchingNext.current === keyword
)
return;
fetchingNext.current = keyword;
void query.fetchNextPage({ cancelRefetch: false }).finally(() => {
if (fetchingNext.current === keyword) fetchingNext.current = undefined;
});
};
const loading = enabled && (searching || query.isFetching);
const selectProps: SelectProps = {
showSearch: { searchValue: search, onSearch: setSearch, filterOption: false },
loading,
onChange: reset,
onOpenChange: (open) => {
if (!open) reset();
},
onPopupScroll: (event) => {
const target = event.currentTarget;
if (target.scrollHeight - target.scrollTop - target.clientHeight < 32) loadMore();
},
popupRender: (menu) => (
<>
{menu}
<div
style={{ padding: '6px 12px', color: 'var(--uj-text-3)', fontSize: 12 }}
aria-live="polite"
>
{loading ? (
'加载中…'
) : query.isError ? (
<UButton
type="link"
size="small"
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
if (query.isFetchNextPageError) loadMore();
else void query.refetch();
}}
>
加载失败,点击重试
</UButton>
) : options.length === 1 ? (
'暂无匹配选项'
) : query.hasNextPage ? (
'向下滚动加载更多'
) : (
'已加载全部'
)}
</div>
</>
),
};
return { options, selectProps, reset };
}
export function useStoreFilterOptions({
enabled,
includeProducts = false,
}: {
enabled: boolean;
includeProducts?: boolean;
}) {
const productCategory = useRemoteOptions('goods', enabled && includeProducts);
const businessScene = useRemoteOptions('scenes', enabled);
return {
productCategory,
businessScene,
reset: () => {
productCategory.reset();
businessScene.reset();
},
};
}
...@@ -123,28 +123,33 @@ export default function AccountManage() { ...@@ -123,28 +123,33 @@ export default function AccountManage() {
{ {
title: '账号', title: '账号',
dataIndex: 'account', dataIndex: 'account',
width: 180, width: 160,
line: 1,
render: (value) => ( render: (value) => (
<UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{value}</UText> <UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{value}</UText>
), ),
}, },
{ title: '姓名', dataIndex: 'name', width: 110 }, { title: '姓名', dataIndex: 'name', width: 130, line: 1 },
{ title: '手机号', dataIndex: 'mobile', width: 120 }, { title: '手机号', dataIndex: 'mobile', width: 120 },
{ title: '所属组织', dataIndex: 'orgPath', width: 260, line: 1 }, { title: '所属组织', dataIndex: 'orgPath', width: 230, line: 1 },
{ {
title: '角色', title: '角色',
dataIndex: 'roleNames', dataIndex: 'roleNames',
width: 220, width: 290,
render: (names: string[]) => render: (names: string[]) =>
names.length names.length
? names.map((name) => ( ? names.map((name, index) => (
<UTag key={name} color="blue"> <UTag
key={name}
color="blue"
style={index < names.length - 1 ? { marginRight: 4 } : undefined}
>
{name} {name}
</UTag> </UTag>
)) ))
: '—', : '—',
}, },
{ title: '数据域', dataIndex: 'dataScopeLabel', width: 140 }, { title: '数据域', dataIndex: 'dataScopeLabel' },
{ {
title: '状态', title: '状态',
width: 90, width: 90,
......
...@@ -34,7 +34,7 @@ export function RoleModal({ open, roleItem, onCancel, onSuccess }: RoleModalProp ...@@ -34,7 +34,7 @@ export function RoleModal({ open, roleItem, onCancel, onSuccess }: RoleModalProp
mutationFn: (values: RoleFormValues) => { mutationFn: (values: RoleFormValues) => {
const payload = { const payload = {
roleName: values.roleName.trim(), roleName: values.roleName.trim(),
defaultDataScope: Number(values.defaultDataScope), defaultDataScope: Number(1),
sort: Number(values.sort), sort: Number(values.sort),
status: Number(values.status), status: Number(values.status),
description: values.description?.trim() || undefined, description: values.description?.trim() || undefined,
...@@ -58,7 +58,7 @@ export function RoleModal({ open, roleItem, onCancel, onSuccess }: RoleModalProp ...@@ -58,7 +58,7 @@ export function RoleModal({ open, roleItem, onCancel, onSuccess }: RoleModalProp
sort: String(roleItem?.sort ?? 10), sort: String(roleItem?.sort ?? 10),
status: roleItem?.status ?? 1, status: roleItem?.status ?? 1,
description: roleItem?.description ?? '', description: roleItem?.description ?? '',
defaultDataScope: roleItem?.defaultDataScope, defaultDataScope: Number(roleItem?.defaultDataScope ?? 1),
}); });
}, [form, open, roleItem]); }, [form, open, roleItem]);
...@@ -117,6 +117,7 @@ export function RoleModal({ open, roleItem, onCancel, onSuccess }: RoleModalProp ...@@ -117,6 +117,7 @@ export function RoleModal({ open, roleItem, onCancel, onSuccess }: RoleModalProp
name: 'defaultDataScope', name: 'defaultDataScope',
label: '默认数据域', label: '默认数据域',
type: 'select', type: 'select',
disabled: true,
section: '数据域', section: '数据域',
options: dataScopeOptions, options: dataScopeOptions,
rules: [{ required: true, message: '请选择默认数据域' }], rules: [{ required: true, message: '请选择默认数据域' }],
......
...@@ -14,7 +14,6 @@ import { ...@@ -14,7 +14,6 @@ import {
} from '@/components'; } from '@/components';
import { P, PermButton } from '@/access'; import { P, PermButton } from '@/access';
import { role, type RolePageItem, type RolePageParams } from '@/api'; import { role, type RolePageItem, type RolePageParams } from '@/api';
import { getDataScopeLabel } from '@/constants/dataScope';
import { RoleModal } from './components/RoleModal'; import { RoleModal } from './components/RoleModal';
import { RoleDetailDrawer } from './components/RoleDetailDrawer'; import { RoleDetailDrawer } from './components/RoleDetailDrawer';
import { getBaseList } from './tools/constants'; import { getBaseList } from './tools/constants';
...@@ -23,7 +22,6 @@ interface Row { ...@@ -23,7 +22,6 @@ interface Row {
id: number; id: number;
name: string; name: string;
code: string; code: string;
scope: string;
userCount: number; userCount: number;
description: string; description: string;
type: string; type: string;
...@@ -41,8 +39,6 @@ function createRolePageParams( ...@@ -41,8 +39,6 @@ function createRolePageParams(
keyword: values.keyword as string | undefined, keyword: values.keyword as string | undefined,
isBuiltin: values.type === '' || values.type === undefined ? undefined : Number(values.type), isBuiltin: values.type === '' || values.type === undefined ? undefined : Number(values.type),
status: values.status === '' || values.status === undefined ? undefined : Number(values.status), status: values.status === '' || values.status === undefined ? undefined : Number(values.status),
defaultDataScope:
values.scope === '' || values.scope === undefined ? undefined : Number(values.scope),
}; };
} }
...@@ -52,7 +48,6 @@ export default function RoleManage() { ...@@ -52,7 +48,6 @@ export default function RoleManage() {
size: DEFAULT_PAGE_SIZE, size: DEFAULT_PAGE_SIZE,
isBuiltin: undefined, isBuiltin: undefined,
status: undefined, status: undefined,
defaultDataScope: undefined,
}); });
const [queryVersion, setQueryVersion] = useState(0); const [queryVersion, setQueryVersion] = useState(0);
const [roleModalOpen, setRoleModalOpen] = useState(false); const [roleModalOpen, setRoleModalOpen] = useState(false);
...@@ -79,7 +74,6 @@ export default function RoleManage() { ...@@ -79,7 +74,6 @@ export default function RoleManage() {
id: item.roleId, id: item.roleId,
name: item.roleName, name: item.roleName,
code: item.roleCode, code: item.roleCode,
scope: getDataScopeLabel(item.defaultDataScope),
userCount: item.userCount, userCount: item.userCount,
description: item.description ?? '—', description: item.description ?? '—',
type: item.isBuiltin === 1 ? '内置' : '自定义', type: item.isBuiltin === 1 ? '内置' : '自定义',
...@@ -102,33 +96,25 @@ export default function RoleManage() { ...@@ -102,33 +96,25 @@ export default function RoleManage() {
type: 'select', type: 'select',
options: getBaseList('roleStatus'), options: getBaseList('roleStatus'),
}, },
{
name: 'scope',
label: '默认数据域',
type: 'select',
options: getBaseList('dataScope'),
},
]; ];
const columns: DataTableColumnsType<Row> = [ const columns: DataTableColumnsType<Row> = [
{ title: '角色名称', dataIndex: 'name', width: 200 }, { title: '角色名称', dataIndex: 'name', width: 220, line: 1 },
{ {
title: '角色编码', title: '角色编码',
dataIndex: 'code', dataIndex: 'code',
width: 150, width: 220,
line: 1,
render: (v) => <UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{v}</UText>, render: (v) => <UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{v}</UText>,
}, },
{ title: '默认数据域', dataIndex: 'scope', width: 130 }, { title: '账号数', dataIndex: 'userCount' },
{ title: '账号数', dataIndex: 'userCount', width: 90 }, { title: '角色描述', dataIndex: 'description', width: 450, line: 1 },
{ title: '角色描述', dataIndex: 'description', width: 320, line: 1 },
{ {
title: '类型', title: '类型',
dataIndex: 'type', dataIndex: 'type',
width: 90,
render: (v) => <UTag color={v === '内置' ? 'geekblue' : 'default'}>{v}</UTag>, render: (v) => <UTag color={v === '内置' ? 'geekblue' : 'default'}>{v}</UTag>,
}, },
{ {
title: '状态', title: '状态',
width: 90,
render: (_, r) => ( render: (_, r) => (
<UTag color={r.status === 1 ? 'green' : 'default'}> <UTag color={r.status === 1 ? 'green' : 'default'}>
● {r.status === 1 ? '启用' : '停用'} ● {r.status === 1 ? '启用' : '停用'}
...@@ -181,7 +167,7 @@ export default function RoleManage() { ...@@ -181,7 +167,7 @@ export default function RoleManage() {
<UCard size="small"> <UCard size="small">
<SearchForm <SearchForm
fields={fields} fields={fields}
initialValues={{ type: '', status: '', scope: '' }} initialValues={{ type: '', status: '' }}
onSearch={(values, pagination) => { onSearch={(values, pagination) => {
setParams(createRolePageParams(values, pagination)); setParams(createRolePageParams(values, pagination));
setQueryVersion((version) => version + 1); setQueryVersion((version) => version + 1);
......
...@@ -7,6 +7,8 @@ import type { ApprovalRow } from '@/api'; ...@@ -7,6 +7,8 @@ import type { ApprovalRow } from '@/api';
import StoreApprove from '../index'; import StoreApprove from '../index';
const api = vi.hoisted(() => ({ const api = vi.hoisted(() => ({
listScenes: vi.fn(),
listGoodsCategories: vi.fn(),
listApprovals: vi.fn(), listApprovals: vi.fn(),
getApproval: vi.fn(), getApproval: vi.fn(),
passApproval: vi.fn(), passApproval: vi.fn(),
...@@ -50,6 +52,14 @@ let detail = { ...@@ -50,6 +52,14 @@ let detail = {
beforeEach(() => { beforeEach(() => {
vi.resetAllMocks(); vi.resetAllMocks();
api.listScenes.mockResolvedValue([]);
api.listGoodsCategories.mockResolvedValue({
records: [],
total: 0,
current: 1,
size: 20,
pages: 0,
});
pending = [{ ...row }]; pending = [{ ...row }];
mine = [ mine = [
{ ...row, listingId: '202', status: 'REJECTED', statusLabel: '已打回', actionable: false }, { ...row, listingId: '202', status: 'REJECTED', statusLabel: '已打回', actionable: false },
...@@ -100,6 +110,28 @@ function actionDialog(confirmLabel: string) { ...@@ -100,6 +110,28 @@ function actionDialog(confirmLabel: string) {
} }
describe('门店审批页面', () => { describe('门店审批页面', () => {
it.each(['handleOpinion', 'rejectReason'] as const)(
'我已办的长意见支持换行省略和悬停查看全文(%s)',
async (source) => {
const opinion = '请核对政策。\n' + '产品分类与业务场景需要逐项确认。'.repeat(12) + 'END-OF-OPINION';
api.listApprovals.mockResolvedValue({
records: [{ ...row, [source]: opinion }],
total: 1,
current: 1,
size: 10,
pages: 1,
});
mount();
fireEvent.click(screen.getByRole('tab', { name: /我已办/ }));
const text = await screen.findByText(opinion, { exact: true, normalizer: (value) => value });
fireEvent.mouseOver(text);
const tooltip = await screen.findByRole('tooltip');
expect(tooltip).toHaveTextContent('END-OF-OPINION');
expect(tooltip).toHaveTextContent('产品分类与业务场景需要逐项确认。');
expect(text).toHaveStyle({ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' });
},
);
it('按原型展示分类摘要、无币种前缀的权威成本、提交时间和停留时长', async () => { it('按原型展示分类摘要、无币种前缀的权威成本、提交时间和停留时长', async () => {
pending = [ pending = [
{ {
...@@ -121,22 +153,42 @@ describe('门店审批页面', () => { ...@@ -121,22 +153,42 @@ describe('门店审批页面', () => {
expect(screen.getByText('49 小时')).toBeInTheDocument(); expect(screen.getByText('49 小时')).toBeInTheDocument();
}); });
it('使用本地字典按实际中文业务场景和产品分类筛选', async () => { it('使用接口新增的业务场景和产品分类选项,查询提交中文名称', async () => {
api.listScenes.mockResolvedValue([{ id: 11, name: '新能源车交付' }]);
api.listGoodsCategories.mockImplementation(async ({ categoryName }) => ({
records:
categoryName === '汽车精品'
? [{ id: 91, categoryType: 91, categoryName: '汽车精品专属服务', children: [] }]
: [],
total: categoryName === '汽车精品' ? 1 : 0,
current: 1,
size: 20,
pages: categoryName === '汽车精品' ? 1 : 0,
}));
mount(); mount();
await screen.findByText('测试门店'); await screen.findByText('测试门店');
fireEvent.mouseDown(screen.getByLabelText('业务场景')); fireEvent.mouseDown(screen.getByLabelText('业务场景'));
fireEvent.click( fireEvent.click(
await screen.findByText('精品升级', { selector: '.ant-select-item-option-content' }), await screen.findByText('新能源车交付', { selector: '.ant-select-item-option-content' }),
); );
fireEvent.mouseDown(screen.getByLabelText('产品分类')); fireEvent.mouseDown(screen.getByLabelText('产品分类'));
fireEvent.change(screen.getByLabelText('产品分类'), { target: { value: '汽车精品' } });
fireEvent.click( fireEvent.click(
await screen.findByText('车辆美容', { selector: '.ant-select-item-option-content' }), await screen.findByText('汽车精品专属服务', { selector: '.ant-select-item-option-content' }),
); );
expect(api.listGoodsCategories).toHaveBeenCalledWith({
current: 1,
size: 20,
categoryName: '汽车精品',
});
fireEvent.click(screen.getByRole('button', { name: '查询' })); fireEvent.click(screen.getByRole('button', { name: '查询' }));
await waitFor(() => await waitFor(() =>
expect(api.listApprovals).toHaveBeenCalledWith( expect(api.listApprovals).toHaveBeenCalledWith(
'todo', 'todo',
expect.objectContaining({ businessScene: '精品升级', productCategory: '车辆美容' }), expect.objectContaining({
businessScene: '新能源车交付',
productCategory: '汽车精品专属服务',
}),
), ),
); );
expect(screen.queryByText('筛选字典加载失败')).not.toBeInTheDocument(); expect(screen.queryByText('筛选字典加载失败')).not.toBeInTheDocument();
...@@ -325,6 +377,8 @@ describe('门店审批页面', () => { ...@@ -325,6 +377,8 @@ describe('门店审批页面', () => {
mount([]); mount([]);
expect(screen.getByText('无门店审批访问权限')).toBeInTheDocument(); expect(screen.getByText('无门店审批访问权限')).toBeInTheDocument();
expect(api.listApprovals).not.toHaveBeenCalled(); expect(api.listApprovals).not.toHaveBeenCalled();
expect(api.listScenes).not.toHaveBeenCalled();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
}); });
it('仅有通过权限不能替代页面查看权限,也不加载审批详情', () => { it('仅有通过权限不能替代页面查看权限,也不加载审批详情', () => {
......
.store-approve-table-card {
/* 保留表格自然高度,由页面内容区滚动,避免 flex 收缩后裁掉底部行和分页。 */
flex-shrink: 0;
}
.store-approve-table.ant-table-wrapper .ant-table .ant-table-thead > tr > th { .store-approve-table.ant-table-wrapper .ant-table .ant-table-thead > tr > th {
height: 38px; height: 38px;
padding: 0 12px; padding: 0 12px;
...@@ -37,14 +42,31 @@ ...@@ -37,14 +42,31 @@
white-space: nowrap; white-space: nowrap;
} }
.store-approve-categories[tabindex] {
cursor: help;
}
.store-approve-category-list {
max-height: 320px;
margin: 0;
padding: 0 0 0 18px;
overflow-y: auto;
overflow-wrap: anywhere;
white-space: normal;
}
.store-approve-category-list > li + li {
margin-top: 4px;
}
.store-approve-tag { .store-approve-tag {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
height: 20px; height: 20px;
padding: 0 7px; padding: 0 7px;
border-radius: 4px; border-radius: 4px;
background: #e6f7f5; background: var(--ant-color-primary-bg, #eef3ff);
color: #07796f; color: var(--uj-primary, #2b5ce6);
font-size: 11px; font-size: 11px;
font-weight: 500; font-weight: 500;
white-space: nowrap; white-space: nowrap;
...@@ -89,8 +111,8 @@ ...@@ -89,8 +111,8 @@
} }
.store-approve-stay--normal { .store-approve-stay--normal {
background: #e8f7f0; background: var(--ant-color-primary-bg, #eef3ff);
color: #0b6b47; color: var(--uj-primary, #2b5ce6);
} }
.store-approve-stay--warning { .store-approve-stay--warning {
......
import { render, screen, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { ApprovalRow } from '@/api';
import { ApprovalActionModal, type ApprovalActionType } from './ApprovalActionModal';
function renderAction(
levels: Array<Pick<ApprovalRow, 'currentLevel' | 'totalLevel'>>,
type: ApprovalActionType = 'pass',
) {
const records: ApprovalRow[] = levels.map((level, index) => ({
listingId: String(index + 1),
storeName: `门店${index + 1}`,
merchantNo: `SQ00${index + 1}`,
businessScene: '精品升级',
status: 'PENDING',
...level,
}));
render(
<ApprovalActionModal
action={{ type, records }}
pending={false}
confirmed={false}
reason=""
onConfirmed={vi.fn()}
onReason={vi.fn()}
onCancel={vi.fn()}
onConfirm={vi.fn()}
/>,
);
return within(screen.getByRole('dialog')).getByRole('alert');
}
describe('通过确认的审批结果提示', () => {
it.each([
{ currentLevel: 2, totalLevel: 2 },
{ currentLevel: 1, totalLevel: 1 },
{ currentLevel: 3, totalLevel: 3 },
])('第 $currentLevel / $totalLevel 级终审通过后提示生效,不提示还有后续审批', (level) => {
const alert = renderAction([level]);
expect(alert).toHaveTextContent('通过当前审批节点后,记录将立即生效并进入门店列表。');
expect(alert).not.toHaveTextContent('后续审批');
});
it('中间审批节点提示仍需后续审批', () => {
const alert = renderAction([{ currentLevel: 1, totalLevel: 2 }]);
expect(alert).toHaveTextContent('记录将继续后续审批');
expect(alert).not.toHaveTextContent('立即生效');
});
it('批量全部终审时提示生效,不受终审总层级差异影响', () => {
const alert = renderAction(
[
{ currentLevel: 1, totalLevel: 1 },
{ currentLevel: 2, totalLevel: 2 },
],
'batch',
);
expect(alert).toHaveTextContent('记录将立即生效并进入门店列表');
expect(alert).not.toHaveTextContent('后续审批');
});
it('批量包含不同审批阶段时分别说明终审生效和继续后续审批', () => {
const alert = renderAction(
[
{ currentLevel: 2, totalLevel: 2 },
{ currentLevel: 1, totalLevel: 2 },
],
'batch',
);
expect(alert).toHaveTextContent('终审记录通过后将立即生效并进入门店列表');
expect(alert).toHaveTextContent('其余记录将继续后续审批');
});
it.each([
{},
{ currentLevel: null, totalLevel: null },
{ currentLevel: 0, totalLevel: 0 },
{ currentLevel: 3, totalLevel: 2 },
])('缺少或非法审批层级不承诺立即生效,也不假定还有后续审批:%j', (level) => {
const alert = renderAction([level]);
expect(alert).toHaveTextContent('系统将按记录的审批进度处理');
expect(alert).not.toHaveTextContent('立即生效');
expect(alert).not.toHaveTextContent('继续后续审批');
});
it('批量存在未知层级时不会将已知终审结果套用到全部记录', () => {
const alert = renderAction([{ currentLevel: 2, totalLevel: 2 }, {}], 'batch');
expect(alert).toHaveTextContent('系统将按记录的审批进度处理');
expect(alert).not.toHaveTextContent('立即生效');
});
});
...@@ -21,6 +21,30 @@ const buttons: Record<ApprovalActionType, string> = { ...@@ -21,6 +21,30 @@ const buttons: Record<ApprovalActionType, string> = {
batch: '确认批量通过', batch: '确认批量通过',
revoke: '确认撤回', revoke: '确认撤回',
}; };
function approvalResultMessage(records: ApprovalRow[]) {
const hasUnknownLevel = records.some(
({ currentLevel, totalLevel }) =>
typeof currentLevel !== 'number' ||
typeof totalLevel !== 'number' ||
!Number.isInteger(currentLevel) ||
!Number.isInteger(totalLevel) ||
currentLevel < 1 ||
totalLevel < currentLevel,
);
if (!records.length || hasUnknownLevel) {
return '通过当前审批节点后,系统将按记录的审批进度处理;完成全部审批节点后生效并进入门店列表。';
}
const finalCount = records.filter((row) => row.currentLevel === row.totalLevel).length;
if (finalCount === records.length) {
return '通过当前审批节点后,记录将立即生效并进入门店列表。';
}
if (finalCount > 0) {
return '本次审批包含不同审批阶段的记录:终审记录通过后将立即生效并进入门店列表;其余记录将继续后续审批,全部节点通过后生效。';
}
return '通过当前审批节点后,记录将继续后续审批;全部节点通过后才会生效并进入门店列表。';
}
interface Props { interface Props {
action?: ApprovalAction; action?: ApprovalAction;
spec?: StoreDictionaries; spec?: StoreDictionaries;
...@@ -71,7 +95,7 @@ export function ApprovalActionModal({ ...@@ -71,7 +95,7 @@ export function ApprovalActionModal({
type="info" type="info"
showIcon showIcon
title="审批范围为门店+业务场景下的全部产品分类" title="审批范围为门店+业务场景下的全部产品分类"
description="通过当前审批节点后,记录将继续后续审批;全部节点通过后才会生效并进入门店列表。" description={approvalResultMessage(action?.records ?? [])}
/> />
) : type === 'revoke' ? ( ) : type === 'revoke' ? (
<UAlert type="warning" showIcon title="撤回后记录将退出当前审批流程。" /> <UAlert type="warning" showIcon title="撤回后记录将退出当前审批流程。" />
......
...@@ -19,6 +19,7 @@ import { ...@@ -19,6 +19,7 @@ import {
} from '@/api'; } from '@/api';
import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer'; import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer';
import { STORE_DICTIONARIES } from '@/features/store/dictionaries'; import { STORE_DICTIONARIES } from '@/features/store/dictionaries';
import { useStoreFilterOptions } from '@/features/store/useStoreFilterOptions';
import { buildApproveColumns } from './tools/columns'; import { buildApproveColumns } from './tools/columns';
import { ApprovalActionModal, type ApprovalAction } from './components/ApprovalActionModal'; import { ApprovalActionModal, type ApprovalAction } from './components/ApprovalActionModal';
import { errorMessage, tabDefs } from './tools/consts'; import { errorMessage, tabDefs } from './tools/consts';
...@@ -35,6 +36,7 @@ const cleanText = (value: unknown) => ...@@ -35,6 +36,7 @@ const cleanText = (value: unknown) =>
export default function StoreApprove() { export default function StoreApprove() {
const { canPoint } = useAccess(); const { canPoint } = useAccess();
const allowed = canPoint(P.STORE_APPROVE_VIEW); const allowed = canPoint(P.STORE_APPROVE_VIEW);
const filterOptions = useStoreFilterOptions({ enabled: allowed, includeProducts: true });
const canPass = canPoint(P.STORE_APPROVE_AUDIT); const canPass = canPoint(P.STORE_APPROVE_AUDIT);
const canReject = canPoint(P.STORE_APPROVE_REJECT); const canReject = canPoint(P.STORE_APPROVE_REJECT);
const canRevoke = canPoint(P.STORE_APPROVE_REVOKE); const canRevoke = canPoint(P.STORE_APPROVE_REVOKE);
...@@ -186,14 +188,16 @@ export default function StoreApprove() { ...@@ -186,14 +188,16 @@ export default function StoreApprove() {
label: '产品分类', label: '产品分类',
type: 'select', type: 'select',
width: '100%', width: '100%',
options: [{ value: '', label: '全部' }, ...STORE_DICTIONARIES.productCategories], options: filterOptions.productCategory.options,
selectProps: filterOptions.productCategory.selectProps,
}, },
{ {
name: 'businessScene', name: 'businessScene',
label: '业务场景', label: '业务场景',
type: 'select', type: 'select',
width: '100%', width: '100%',
options: [{ value: '', label: '全部' }, ...STORE_DICTIONARIES.businessScenes], options: filterOptions.businessScene.options,
selectProps: filterOptions.businessScene.selectProps,
}, },
{ {
name: 'submitUserName', name: 'submitUserName',
...@@ -288,7 +292,10 @@ export default function StoreApprove() { ...@@ -288,7 +292,10 @@ export default function StoreApprove() {
submitUserName: '', submitUserName: '',
}} }}
onSearch={changeQuery} onSearch={changeQuery}
onReset={() => changeQuery({})} onReset={() => {
filterOptions.reset();
changeQuery({});
}}
/> />
</UCard> </UCard>
{list.isError ? ( {list.isError ? (
...@@ -306,7 +313,7 @@ export default function StoreApprove() { ...@@ -306,7 +313,7 @@ export default function StoreApprove() {
) : list.isPending ? ( ) : list.isPending ? (
<Skeleton variant="table" /> <Skeleton variant="table" />
) : ( ) : (
<div className="store-table-card"> <div className="store-table-card store-approve-table-card">
<DataTable<ApprovalRow> <DataTable<ApprovalRow>
className="store-approve-table" className="store-approve-table"
columns={buildApproveColumns(tab, STORE_DICTIONARIES)} columns={buildApproveColumns(tab, STORE_DICTIONARIES)}
......
import type { ColumnsType } from 'antd/es/table'; import type { DataTableColumnsType } from '@/components/DataTable';
import { UTag } from '@uj/ui'; import { UTag, UTooltip } from '@uj/ui';
import { StatusTag } from '@/components/StatusTag'; import { StatusTag } from '@/components/StatusTag';
import type { ApprovalRow, ApproveTab } from '@/api'; import type { ApprovalRow, ApproveTab } from '@/api';
import type { StoreDictionaries } from '@/features/store/dictionaries'; import type { StoreDictionaries } from '@/features/store/dictionaries';
...@@ -16,8 +16,8 @@ function formatSubmitTime(value?: string | null): string { ...@@ -16,8 +16,8 @@ function formatSubmitTime(value?: string | null): string {
export function buildApproveColumns( export function buildApproveColumns(
tab: ApproveTab, tab: ApproveTab,
spec?: StoreDictionaries, spec?: StoreDictionaries,
): ColumnsType<ApprovalRow> { ): DataTableColumnsType<ApprovalRow> {
const columns: ColumnsType<ApprovalRow> = [ const columns: DataTableColumnsType<ApprovalRow> = [
{ {
title: '门店名称', title: '门店名称',
dataIndex: 'storeName', dataIndex: 'storeName',
...@@ -38,17 +38,34 @@ export function buildApproveColumns( ...@@ -38,17 +38,34 @@ export function buildApproveColumns(
render: (_, row) => { render: (_, row) => {
const categories = row.productCategories ?? []; const categories = row.productCategories ?? [];
const count = row.categoryCount ?? categories.length; const count = row.categoryCount ?? categories.length;
const categoryNames = categories
.filter((category) => category.trim())
.map((category) => dictionaryLabel(spec?.productCategories, category));
return ( return (
<span className="store-approve-categories"> <UTooltip
{categories[0] ? ( trigger={['hover', 'focus']}
<span className="store-approve-tag"> title={
{dictionaryLabel(spec?.productCategories, categories[0])} categoryNames.length ? (
</span> <ul className="store-approve-category-list" aria-label="全部产品分类">
{categoryNames.map((name, index) => (
<li key={`${name}-${index}`}>{name}</li>
))}
</ul>
) : undefined
}
>
<span
className="store-approve-categories"
tabIndex={categoryNames.length ? 0 : undefined}
>
{categoryNames[0] ? (
<span className="store-approve-tag">{categoryNames[0]}</span>
) : ( ) : (
'—' '—'
)} )}
{count > 1 && <span className="store-approve-category-count">等 {count} 个分类</span>} {count > 1 && <span className="store-approve-category-count">等 {count} 个分类</span>}
</span> </span>
</UTooltip>
); );
}, },
}, },
...@@ -113,9 +130,7 @@ export function buildApproveColumns( ...@@ -113,9 +130,7 @@ export function buildApproveColumns(
width: 110, width: 110,
render: (_, row) => ( render: (_, row) => (
<UTag <UTag
color={ color={row.myAction === 'PASS' ? 'blue' : row.myAction === 'REJECT' ? 'red' : undefined}
row.myAction === 'PASS' ? 'green' : row.myAction === 'REJECT' ? 'red' : undefined
}
> >
{row.myActionLabel || {row.myActionLabel ||
({ PASS: '通过', REJECT: '打回' }[row.myAction ?? ''] ?? row.myAction ?? '—')} ({ PASS: '通过', REJECT: '打回' }[row.myAction ?? ''] ?? row.myAction ?? '—')}
...@@ -125,7 +140,9 @@ export function buildApproveColumns( ...@@ -125,7 +140,9 @@ export function buildApproveColumns(
{ title: '处理时间', dataIndex: 'handleTime', width: 150, render: formatDateTime }, { title: '处理时间', dataIndex: 'handleTime', width: 150, render: formatDateTime },
{ {
title: '处理意见', title: '处理意见',
key: 'handleOpinion',
width: 220, width: 220,
line: 2,
render: (_, row) => row.handleOpinion || row.rejectReason || '—', render: (_, row) => row.handleOpinion || row.rejectReason || '—',
}, },
{ title: '记录状态', width: 100, render: (_, row) => <StatusTag status={row.status} /> }, { title: '记录状态', width: 100, render: (_, row) => <StatusTag status={row.status} /> },
......
...@@ -7,6 +7,8 @@ import { AccessTestProvider } from '@/test/AccessTestProvider'; ...@@ -7,6 +7,8 @@ import { AccessTestProvider } from '@/test/AccessTestProvider';
import StoreListing from './index'; import StoreListing from './index';
const api = vi.hoisted(() => ({ const api = vi.hoisted(() => ({
listScenes: vi.fn(),
listGoodsCategories: vi.fn(),
listStores: vi.fn(), listStores: vi.fn(),
getStore: vi.fn(), getStore: vi.fn(),
getChanges: vi.fn(), getChanges: vi.fn(),
...@@ -60,6 +62,14 @@ function renderPage(permissions = ['store:list:view', 'store:list:export']) { ...@@ -60,6 +62,14 @@ function renderPage(permissions = ['store:list:view', 'store:list:export']) {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
api.listScenes.mockResolvedValue([]);
api.listGoodsCategories.mockResolvedValue({
records: [],
total: 0,
current: 1,
size: 20,
pages: 0,
});
api.listStores.mockImplementation(async (params) => ({ api.listStores.mockImplementation(async (params) => ({
records: rows, records: rows,
total: 42, total: 42,
...@@ -99,16 +109,17 @@ afterEach(() => { ...@@ -99,16 +109,17 @@ afterEach(() => {
}); });
describe('门店列表', () => { describe('门店列表', () => {
it('本地业务场景可筛选且导出沿用同一实际中文值', async () => { it('接口新增的业务场景可筛选且导出沿用同一实际中文值', async () => {
api.listScenes.mockResolvedValue([{ id: 11, name: '新能源车交付' }]);
renderPage(); renderPage();
fireEvent.mouseDown(await screen.findByLabelText('业务场景')); fireEvent.mouseDown(await screen.findByLabelText('业务场景'));
fireEvent.click( fireEvent.click(
await screen.findByText('售后众筹', { selector: '.ant-select-item-option-content' }), await screen.findByText('新能源车交付', { selector: '.ant-select-item-option-content' }),
); );
fireEvent.click(screen.getByRole('button', { name: /查\s*询/ })); fireEvent.click(screen.getByRole('button', { name: /查\s*询/ }));
await waitFor(() => await waitFor(() =>
expect(api.listStores).toHaveBeenLastCalledWith( expect(api.listStores).toHaveBeenLastCalledWith(
expect.objectContaining({ businessScene: '售后众筹', current: 1 }), expect.objectContaining({ businessScene: '新能源车交付', current: 1 }),
), ),
); );
const exportButton = screen.getByRole('button', { name: /导\s*出/ }); const exportButton = screen.getByRole('button', { name: /导\s*出/ });
...@@ -116,10 +127,11 @@ describe('门店列表', () => { ...@@ -116,10 +127,11 @@ describe('门店列表', () => {
fireEvent.click(exportButton); fireEvent.click(exportButton);
await waitFor(() => await waitFor(() =>
expect(api.exportStores).toHaveBeenCalledWith( expect(api.exportStores).toHaveBeenCalledWith(
expect.objectContaining({ businessScene: '售后众筹' }), expect.objectContaining({ businessScene: '新能源车交付' }),
), ),
); );
expect(screen.queryByText('业务场景加载失败')).not.toBeInTheDocument(); expect(screen.queryByText('业务场景加载失败')).not.toBeInTheDocument();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
}); });
it('提交真实筛选参数,翻页保留筛选,重置同时清空表单与请求', async () => { it('提交真实筛选参数,翻页保留筛选,重置同时清空表单与请求', async () => {
...@@ -379,6 +391,8 @@ describe('门店列表', () => { ...@@ -379,6 +391,8 @@ describe('门店列表', () => {
expect(api.listStores).not.toHaveBeenCalled(); expect(api.listStores).not.toHaveBeenCalled();
expect(api.getColumnConfig).not.toHaveBeenCalled(); expect(api.getColumnConfig).not.toHaveBeenCalled();
expect(api.getStore).not.toHaveBeenCalled(); expect(api.getStore).not.toHaveBeenCalled();
expect(api.listScenes).not.toHaveBeenCalled();
expect(api.listGoodsCategories).not.toHaveBeenCalled();
}); });
it('仅有导出权限不能替代列表查看权限,也不显示导出操作', async () => { it('仅有导出权限不能替代列表查看权限,也不显示导出操作', async () => {
......
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
} from '@/components'; } from '@/components';
import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer'; import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer';
import { STORE_DICTIONARIES } from '@/features/store/dictionaries'; import { STORE_DICTIONARIES } from '@/features/store/dictionaries';
import { useStoreFilterOptions } from '@/features/store/useStoreFilterOptions';
import { buildColumns } from './components/columns'; import { buildColumns } from './components/columns';
import { ColumnConfigModal } from './components/ColumnConfigModal'; import { ColumnConfigModal } from './components/ColumnConfigModal';
import { import {
...@@ -34,6 +35,7 @@ export default function StoreListing() { ...@@ -34,6 +35,7 @@ export default function StoreListing() {
const { message } = App.useApp(); const { message } = App.useApp();
const { canPoint } = useAccess(); const { canPoint } = useAccess();
const allowed = canPoint(P.STORE_LISTING_VIEW); const allowed = canPoint(P.STORE_LISTING_VIEW);
const filterOptions = useStoreFilterOptions({ enabled: allowed, includeProducts: false });
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [params, setParams] = useState<ListingPageParams>(INITIAL_PARAMS); const [params, setParams] = useState<ListingPageParams>(INITIAL_PARAMS);
const [queryVersion, setQueryVersion] = useState(0); const [queryVersion, setQueryVersion] = useState(0);
...@@ -103,7 +105,8 @@ export default function StoreListing() { ...@@ -103,7 +105,8 @@ export default function StoreListing() {
label: '业务场景', label: '业务场景',
type: 'select', type: 'select',
width: '100%', width: '100%',
options: [{ value: '', label: '全部' }, ...STORE_DICTIONARIES.businessScenes], options: filterOptions.businessScene.options,
selectProps: filterOptions.businessScene.selectProps,
}, },
{ name: 'effectiveRange', label: '上架时间', type: 'dateRange', width: '100%' }, { name: 'effectiveRange', label: '上架时间', type: 'dateRange', width: '100%' },
]; ];
...@@ -186,6 +189,7 @@ export default function StoreListing() { ...@@ -186,6 +189,7 @@ export default function StoreListing() {
if (!exportFile.isPending) exportFile.reset(); if (!exportFile.isPending) exportFile.reset();
}} }}
onReset={() => { onReset={() => {
filterOptions.reset();
setParams({ ...INITIAL_PARAMS, size: params.size }); setParams({ ...INITIAL_PARAMS, size: params.size });
setQueryVersion((version) => version + 1); setQueryVersion((version) => version + 1);
if (!exportFile.isPending) exportFile.reset(); if (!exportFile.isPending) exportFile.reset();
...@@ -234,8 +238,8 @@ export default function StoreListing() { ...@@ -234,8 +238,8 @@ export default function StoreListing() {
total, total,
showSizeChanger: false, showSizeChanger: false,
pageSizeOptions: [10, 20, 50, 100], pageSizeOptions: [10, 20, 50, 100],
showTotal: (count, range) => showTotal: (count) =>
`共 ${count.toLocaleString('zh-CN')} 条记录 · 每页 ${params.size ?? DEFAULT_PAGE_SIZE} 条 · 当前 ${range[0]}–${range[1]} 条`, `共 ${count.toLocaleString('zh-CN')} 条记录 · 每页 ${params.size ?? DEFAULT_PAGE_SIZE} 条`,
onChange: (current, size) => onChange: (current, size) =>
setParams((previous) => ({ setParams((previous) => ({
...previous, ...previous,
......
...@@ -96,8 +96,8 @@ ...@@ -96,8 +96,8 @@
padding: 0 7px; padding: 0 7px;
border: 0; border: 0;
border-radius: 4px; border-radius: 4px;
background: #e6f7f5; background: var(--ant-color-primary-bg, #eef3ff);
color: #07796f; color: var(--uj-primary, #2b5ce6);
font-size: 11px; font-size: 11px;
font-weight: 500; font-weight: 500;
line-height: 1.57; line-height: 1.57;
......
import { InfoCircleFilled, CheckCircleFilled } from '@ant-design/icons'; import { InfoCircleFilled, CheckCircleFilled } from '@ant-design/icons';
import { UCard, UTag } from '@uj/ui'; import { UCard } from '@uj/ui';
import { useAppStore } from '@/store/useAppStore'; import { useAppStore } from '@/store/useAppStore';
export type ChainNodeStatus = 'done' | 'active' | 'pending'; export type ChainNodeStatus = 'done' | 'active' | 'pending';
...@@ -80,16 +80,17 @@ function NodeIcon({ status, index }: NodeIconProps) { ...@@ -80,16 +80,17 @@ function NodeIcon({ status, index }: NodeIconProps) {
); );
} }
const lineColor = (status: ChainNodeStatus) => (status === 'done' ? '#16A34A' : '#E5E7EB');
function NodeLine({ status }: { status: ChainNodeStatus }) { function NodeLine({ status }: { status: ChainNodeStatus }) {
const bg = status === 'done' ? '#16A34A' : '#E5E7EB';
return ( return (
<div <div
style={{ style={{
flex: 1, flex: 1,
height: 2, height: 2,
background: bg, background: lineColor(status),
alignSelf: 'center', alignSelf: 'flex-start',
marginTop: -16, marginTop: 15,
}} }}
/> />
); );
...@@ -97,7 +98,6 @@ function NodeLine({ status }: { status: ChainNodeStatus }) { ...@@ -97,7 +98,6 @@ function NodeLine({ status }: { status: ChainNodeStatus }) {
export interface ApprovalChainPreviewProps { export interface ApprovalChainPreviewProps {
nodes?: ChainNode[]; nodes?: ChainNode[];
chainType?: string;
/** (可选)覆盖默认的提交人名称。不传则取当前登录用户名 */ /** (可选)覆盖默认的提交人名称。不传则取当前登录用户名 */
submitterName?: string; submitterName?: string;
/** (可选)覆盖默认的提交时间,格式 YYYY-MM-DD HH:mm */ /** (可选)覆盖默认的提交时间,格式 YYYY-MM-DD HH:mm */
...@@ -105,10 +105,11 @@ export interface ApprovalChainPreviewProps { ...@@ -105,10 +105,11 @@ export interface ApprovalChainPreviewProps {
} }
/** /**
* 生成默认 3 节点审批链: * 生成默认 4 节点审批链:
* - 第 1 个节点「提交」:副标题 = 当前登录用户名(外部 prop 覆盖优先);时间 = submitTime 或 DEFAULT_SUBMIT_TIME * - 第 1 个节点「提交」:副标题 = 当前登录用户名(外部 prop 覆盖优先);时间 = submitTime 或 DEFAULT_SUBMIT_TIME
* - 第 2 个节点「优加财务经理」:唯一审批节点 * - 第 2 个节点「优加商务经理」:当前审批节点(active)
* - 第 3 个节点「生效」:写入门店列表 * - 第 3 个节点「优加财务经理」:下一审批节点(pending)
* - 第 4 个节点「生效」:写入门店列表
*/ */
function buildDefaultNodes(submitter: string, time: string): ChainNode[] { function buildDefaultNodes(submitter: string, time: string): ChainNode[] {
return [ return [
...@@ -120,8 +121,13 @@ function buildDefaultNodes(submitter: string, time: string): ChainNode[] { ...@@ -120,8 +121,13 @@ function buildDefaultNodes(submitter: string, time: string): ChainNode[] {
}, },
{ {
status: 'active', status: 'active',
title: '优加商务经理',
subtitle: '当前审批节点',
},
{
status: 'pending',
title: '优加财务经理', title: '优加财务经理',
subtitle: '唯一审批节点', subtitle: '下一审批节点',
}, },
{ {
status: 'pending', status: 'pending',
...@@ -133,7 +139,6 @@ function buildDefaultNodes(submitter: string, time: string): ChainNode[] { ...@@ -133,7 +139,6 @@ function buildDefaultNodes(submitter: string, time: string): ChainNode[] {
export function ApprovalChainPreview({ export function ApprovalChainPreview({
nodes, nodes,
chainType = '单级审批',
submitterName, submitterName,
submitTime, submitTime,
}: ApprovalChainPreviewProps) { }: ApprovalChainPreviewProps) {
...@@ -153,17 +158,29 @@ export function ApprovalChainPreview({ ...@@ -153,17 +158,29 @@ export function ApprovalChainPreview({
<span style={{ fontSize: 15, fontWeight: 600 }}>审批链预览</span> <span style={{ fontSize: 15, fontWeight: 600 }}>审批链预览</span>
</div> </div>
} }
extra={
<UTag color="default" bordered style={{ fontSize: 12 }}>
{chainType}
</UTag>
}
> >
<div style={{ display: 'flex', padding: '20px 8px 8px' }}> <div style={{ display: 'flex', padding: '20px 8px 8px' }}>
{finalNodes.map((n, i) => ( {finalNodes.map((n, i) => {
<div key={i} style={{ flex: 1, display: 'flex', position: 'relative' }}> const prev = finalNodes[i - 1];
const hasLeft = i > 0;
const hasRight = i < finalNodes.length - 1;
return (
<div
key={i}
style={{
flex: 1,
display: 'flex',
alignItems: 'flex-start',
}}
>
<div style={{ flex: 1 }}>{hasLeft && <NodeLine status={prev.status} />}</div>
<div <div
style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1 }} style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
flex: 'none',
}}
> >
<NodeIcon status={n.status} index={i} /> <NodeIcon status={n.status} index={i} />
<div <div
...@@ -172,7 +189,11 @@ export function ApprovalChainPreview({ ...@@ -172,7 +189,11 @@ export function ApprovalChainPreview({
fontSize: 14, fontSize: 14,
fontWeight: 600, fontWeight: 600,
color: color:
n.status === 'active' ? '#2B5CE6' : n.status === 'done' ? '#16A34A' : '#6B7280', n.status === 'active'
? '#2B5CE6'
: n.status === 'done'
? '#16A34A'
: '#6B7280',
textAlign: 'center', textAlign: 'center',
}} }}
> >
...@@ -201,9 +222,10 @@ export function ApprovalChainPreview({ ...@@ -201,9 +222,10 @@ export function ApprovalChainPreview({
</div> </div>
)} )}
</div> </div>
{i < finalNodes.length - 1 && <NodeLine status={finalNodes[i].status} />} <div style={{ flex: 1 }}>{hasRight && <NodeLine status={n.status} />}</div>
</div> </div>
))} );
})}
</div> </div>
</UCard> </UCard>
); );
......
...@@ -7,7 +7,7 @@ export interface ConfirmActionBarProps { ...@@ -7,7 +7,7 @@ export interface ConfirmActionBarProps {
onSubmit?: () => void; onSubmit?: () => void;
} }
export function ConfirmActionBar({ passCount = 12, onBack, onSubmit }: ConfirmActionBarProps) { export function ConfirmActionBar({ onBack, onSubmit }: ConfirmActionBarProps) {
return ( return (
<div <div
style={{ style={{
...@@ -27,7 +27,7 @@ export function ConfirmActionBar({ passCount = 12, onBack, onSubmit }: ConfirmAc ...@@ -27,7 +27,7 @@ export function ConfirmActionBar({ passCount = 12, onBack, onSubmit }: ConfirmAc
icon={<ArrowRightOutlined />} icon={<ArrowRightOutlined />}
onClick={onSubmit ?? (() => console.log('下一步:提交审批'))} onClick={onSubmit ?? (() => console.log('下一步:提交审批'))}
> >
下一步:提交审批({passCount}) 下一步:提交审批
</UButton> </UButton>
</div> </div>
</div> </div>
......
import { useMemo } from 'react'; import { useMemo } from 'react';
import { InfoCircleFilled, UploadOutlined, DownloadOutlined } from '@ant-design/icons'; import { InfoCircleFilled, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { UCard, UButton, UTag } from '@uj/ui'; import { UCard, UButton } from '@uj/ui';
import type { StoreImportFailVO, StoreImportCheckVO } from '@/api/modules/store'; import type { StoreImportFailVO, StoreImportCheckVO } from '@/api/modules/store';
export interface FailDetailCardProps { export interface FailDetailCardProps {
checkResult?: StoreImportCheckVO; checkResult?: StoreImportCheckVO;
/** 上传文件的字节数(兜底:后端可能不返回 fileSize,用 File 对象的 size 字段) */
fileSize?: number;
/** 点击「重新上传」时触发(通常回到 Step 0 并清空文件) */ /** 点击「重新上传」时触发(通常回到 Step 0 并清空文件) */
onReUpload?: () => void; onReUpload?: () => void;
} }
...@@ -13,7 +15,6 @@ const FAIL_COL_LABELS = [ ...@@ -13,7 +15,6 @@ const FAIL_COL_LABELS = [
{ key: 'rowIndex' as const, label: '行号', width: 92 }, { key: 'rowIndex' as const, label: '行号', width: 92 },
{ key: 'storeName' as const, label: '门店名称', width: 300 }, { key: 'storeName' as const, label: '门店名称', width: 300 },
{ key: 'merchantNo' as const, label: '门店商户号', width: 160 }, { key: 'merchantNo' as const, label: '门店商户号', width: 160 },
{ key: 'levelLabel' as const, label: '校验层级', width: 130 },
{ key: 'reason' as const, label: '失败原因', width: undefined }, { key: 'reason' as const, label: '失败原因', width: undefined },
] as const; ] as const;
...@@ -33,7 +34,7 @@ function triggerDownloadFailFile(url: string) { ...@@ -33,7 +34,7 @@ function triggerDownloadFailFile(url: string) {
} }
} }
export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) { export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetailCardProps) {
const failRows = (checkResult?.failRows ?? 0) as number; const failRows = (checkResult?.failRows ?? 0) as number;
const failFileUrl = checkResult?.failFileUrl ?? null; const failFileUrl = checkResult?.failFileUrl ?? null;
const failures = (checkResult?.failures ?? []) as StoreImportFailVO[]; const failures = (checkResult?.failures ?? []) as StoreImportFailVO[];
...@@ -49,11 +50,13 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) ...@@ -49,11 +50,13 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
* 底部 L1 / L2 通过校验文字(复用 checkResult 的字段,无则从 failures.length 推断) * 底部 L1 / L2 通过校验文字(复用 checkResult 的字段,无则从 failures.length 推断)
*/ */
const l1 = useMemo(() => { const l1 = useMemo(() => {
// 文件大小:优先后端 fileSize,兜底用传入的 File.size(字节)
const rawSize = typeof checkResult?.fileSize === 'number' ? checkResult.fileSize : fileSize;
const size = const size =
typeof checkResult?.fileSize === 'number' typeof rawSize === 'number'
? checkResult.fileSize === 0 ? rawSize === 0
? '0' ? '0'
: `${Math.max(1, Math.round(checkResult.fileSize / 1024))}KB` : `${Math.max(1, Math.round(rawSize / 1024))}KB`
: ''; : '';
const total = typeof checkResult?.totalRows === 'number' ? `${checkResult.totalRows} 行` : ''; const total = typeof checkResult?.totalRows === 'number' ? `${checkResult.totalRows} 行` : '';
const version = checkResult?.templateVersion ? `模板版本${checkResult.templateVersion}` : ''; const version = checkResult?.templateVersion ? `模板版本${checkResult.templateVersion}` : '';
...@@ -63,7 +66,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) ...@@ -63,7 +66,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
: `格式 .xlsx / ${size}${total ? ' / ' + total : ''}${version ? ' / ' + version : ''}`, : `格式 .xlsx / ${size}${total ? ' / ' + total : ''}${version ? ' / ' + version : ''}`,
]; ];
return parts.filter(Boolean).join(' · '); return parts.filter(Boolean).join(' · ');
}, [checkResult]); }, [checkResult, fileSize]);
const l2 = useMemo(() => { const l2 = useMemo(() => {
const template = checkResult?.templateVersion const template = checkResult?.templateVersion
...@@ -127,7 +130,9 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) ...@@ -127,7 +130,9 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
<div <div
style={{ style={{
width: '100%', width: '100%',
maxHeight: 360,
overflowX: 'auto', overflowX: 'auto',
overflowY: 'auto',
marginBottom: 14, marginBottom: 14,
}} }}
> >
...@@ -146,7 +151,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) ...@@ -146,7 +151,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
))} ))}
</colgroup> </colgroup>
<thead> <thead>
<tr> <tr style={{ position: 'sticky', top: 0, zIndex: 1 }}>
{FAIL_COL_LABELS.map((c) => ( {FAIL_COL_LABELS.map((c) => (
<th <th
key={c.key} key={c.key}
...@@ -158,6 +163,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) ...@@ -158,6 +163,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
padding: '10px 8px', padding: '10px 8px',
borderBottom: '1px solid #F3F4F6', borderBottom: '1px solid #F3F4F6',
whiteSpace: 'nowrap', whiteSpace: 'nowrap',
background: '#fff',
}} }}
> >
{c.label} {c.label}
...@@ -167,7 +173,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) ...@@ -167,7 +173,7 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
</thead> </thead>
<tbody> <tbody>
{hasFailures ? ( {hasFailures ? (
failures.slice(0, 3).map((f, i) => ( failures.map((f, i) => (
<tr key={`${f.rowIndex ?? i}-${f.levelCode ?? ''}-${f.productCategory ?? ''}`}> <tr key={`${f.rowIndex ?? i}-${f.levelCode ?? ''}-${f.productCategory ?? ''}`}>
{/* 行号(蓝 #2563EB) */} {/* 行号(蓝 #2563EB) */}
<td <td
...@@ -208,29 +214,6 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps) ...@@ -208,29 +214,6 @@ export function FailDetailCard({ checkResult, onReUpload }: FailDetailCardProps)
> >
{f.merchantNo ?? '-'} {f.merchantNo ?? '-'}
</td> </td>
{/* 校验层级(浅黄 Tag,与截图 L4 业务级 一致) */}
<td
style={{
padding: '14px 8px',
borderBottom: '1px solid #F3F4F6',
whiteSpace: 'nowrap',
}}
>
<UTag
color="default"
bordered={false}
style={{
background: '#FEF3C7',
color: '#92400E',
padding: '3px 10px',
borderRadius: 6,
fontSize: 13,
lineHeight: 1.4,
}}
>
{f.levelLabel ?? `L${f.levelCode ?? '?'} 校验级`}
</UTag>
</td>
{/* 失败原因(红 #991B1B) */} {/* 失败原因(红 #991B1B) */}
<td <td
style={{ style={{
......
...@@ -6,9 +6,9 @@ import type { USelectProps } from '@uj/ui'; ...@@ -6,9 +6,9 @@ import type { USelectProps } from '@uj/ui';
import type { StoreImportCheckVO } from '@/api/modules/store'; import type { StoreImportCheckVO } from '@/api/modules/store';
export interface ImportInfoValues { export interface ImportInfoValues {
org: string; org?: string;
scene: string; scene?: string;
categories: string[]; categories?: string[];
remark?: string; remark?: string;
} }
......
...@@ -3,7 +3,6 @@ import { UCard } from '@uj/ui'; ...@@ -3,7 +3,6 @@ import { UCard } from '@uj/ui';
const rules = [ const rules = [
'主服务商切换:主服务商由「深圳嘀加」变更为「深圳优加」;凡在优加系统中完成上架的门店,嘀加系统中对应门店的主服务商必须同步更新为「深圳优加」。', '主服务商切换:主服务商由「深圳嘀加」变更为「深圳优加」;凡在优加系统中完成上架的门店,嘀加系统中对应门店的主服务商必须同步更新为「深圳优加」。',
'北森同步:需考虑北森同步处理,优加进入同步配置,组织与人员账号同步范围扩展至优加主体。',
'商品上架利润率测算:非优加门店的测算逻辑保持不变;优加门店不需要重复计算一次,避免毛利被重复扣减出现「负毛利」。', '商品上架利润率测算:非优加门店的测算逻辑保持不变;优加门店不需要重复计算一次,避免毛利被重复扣减出现「负毛利」。',
'上架规则回补:把优加上架规则内容回补到嘀加上架模板中,方便对账数据计算——以优加上架表中对应的内容为准,回填到嘀加系统。', '上架规则回补:把优加上架规则内容回补到嘀加上架模板中,方便对账数据计算——以优加上架表中对应的内容为准,回填到嘀加系统。',
'上架时序建议:建议嘀加系统先上架、优加系统后上架,且两者上架的时间间隔在同一天内完成。', '上架时序建议:建议嘀加系统先上架、优加系统后上架,且两者上架的时间间隔在同一天内完成。',
...@@ -65,8 +64,8 @@ export function NoticeSection() { ...@@ -65,8 +64,8 @@ export function NoticeSection() {
<span <span
style={{ style={{
flex: 'none', flex: 'none',
width: 18, width: 22,
height: 18, height: 22,
borderRadius: '50%', borderRadius: '50%',
background: '#E0E7FF', background: '#E0E7FF',
color: '#2B5CE6', color: '#2B5CE6',
......
...@@ -3,8 +3,8 @@ import type { TableProps } from 'antd'; ...@@ -3,8 +3,8 @@ import type { TableProps } from 'antd';
import type { PolicyConfirmRow } from '../../tools/policyTableData'; import type { PolicyConfirmRow } from '../../tools/policyTableData';
const storeInfoHeaderStyle: React.CSSProperties = { const storeInfoHeaderStyle: React.CSSProperties = {
background: '#EEF2FF', background: '#EFF4FF',
color: '#3730A3', color: '#2B5CE6',
fontWeight: 600, fontWeight: 600,
fontSize: 13, fontSize: 13,
}; };
...@@ -51,7 +51,7 @@ function SceneTag({ text }: { text: string }) { ...@@ -51,7 +51,7 @@ function SceneTag({ text }: { text: string }) {
function CategoryTag({ text }: { text: string }) { function CategoryTag({ text }: { text: string }) {
return ( return (
<UTag <UTag
color="success" color="processing"
bordered={false} bordered={false}
title={text} title={text}
style={{ style={{
...@@ -77,7 +77,27 @@ function FeeValueCell({ value }: { value: string }) { ...@@ -77,7 +77,27 @@ function FeeValueCell({ value }: { value: string }) {
return <span style={{ fontWeight: 600, color: '#1F2937' }}>{value}</span>; return <span style={{ fontWeight: 600, color: '#1F2937' }}>{value}</span>;
} }
export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { export function buildPolicyColumns(
rows: PolicyConfirmRow[] = [],
): TableProps<PolicyConfirmRow>['columns'] {
/**
* 计算当前行某列的 rowSpan(同门店 / 同业务场景合并单元格):
* - keyFn:对每行提取分组 key(如门店名、或「门店名|业务场景」复合键)
* - 当前行与上一行 key 相同 → rowSpan = 0(被合并)
* - 否则向下统计连续相同 key 的行数作为 rowSpan
*/
const getRowSpan = (index: number, keyFn: (r: PolicyConfirmRow) => string): number => {
if (index < 0 || index >= rows.length) return 1;
const cur = keyFn(rows[index]);
if (index > 0 && keyFn(rows[index - 1]) === cur) return 0;
let span = 1;
for (let i = index + 1; i < rows.length; i++) {
if (keyFn(rows[i]) === cur) span++;
else break;
}
return span;
};
return [ return [
// ------------- 第一组:门店信息(4 列) ------------- // ------------- 第一组:门店信息(4 列) -------------
{ {
...@@ -90,7 +110,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -90,7 +110,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
key: 'storeName', key: 'storeName',
width: 200, width: 200,
onHeaderCell: () => ({ style: storeInfoHeaderStyle }), onHeaderCell: () => ({ style: storeInfoHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
rowSpan: getRowSpan(index ?? 0, (r) => r.storeName),
style: cellStyle,
}),
render: (v) => <span style={{ color: '#1A202C', fontWeight: 500 }}>{v}</span>, render: (v) => <span style={{ color: '#1A202C', fontWeight: 500 }}>{v}</span>,
}, },
{ {
...@@ -100,7 +123,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -100,7 +123,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 130, width: 130,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: storeInfoHeaderStyle }), onHeaderCell: () => ({ style: storeInfoHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
// 同门店的商户号必然相同,按「门店名 + 商户号」复合键合并
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.storeMerchantNo}`),
style: cellStyle,
}),
render: (v) => <a style={{ color: '#2563EB', fontSize: 12.5 }}>{v}</a>, render: (v) => <a style={{ color: '#2563EB', fontSize: 12.5 }}>{v}</a>,
}, },
{ {
...@@ -110,16 +137,27 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -110,16 +137,27 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 130, width: 130,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: storeInfoHeaderStyle }), onHeaderCell: () => ({ style: storeInfoHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
// 同门店下相同业务场景才合并(不同门店同名场景不合并)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v: string) => <SceneTag text={v} />, render: (v: string) => <SceneTag text={v} />,
}, },
],
},
// ------------- 第二组:商务政策(14 列) -------------
{
title: '商务政策',
align: 'center',
children: [
{ {
title: '产品分类', title: '产品分类',
dataIndex: 'productCategory', dataIndex: 'productCategory',
key: 'productCategory', key: 'productCategory',
width: 280, width: 280,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: storeInfoHeaderStyle }), onHeaderCell: () => ({ style: bizPolicyHeaderStyle }),
onCell: () => ({ onCell: () => ({
style: { style: {
...cellStyle, ...cellStyle,
...@@ -130,13 +168,6 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -130,13 +168,6 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
}), }),
render: (v: string) => <CategoryTag text={v} />, render: (v: string) => <CategoryTag text={v} />,
}, },
],
},
// ------------- 第二组:商务政策(14 列) -------------
{
title: '商务政策',
align: 'center',
children: [
// 管理层市场费 1 // 管理层市场费 1
{ {
title: '管理层市场费1计算模式', title: '管理层市场费1计算模式',
...@@ -203,7 +234,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -203,7 +234,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 170, width: 170,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: bizPolicyHeaderStyle }), onHeaderCell: () => ({ style: bizPolicyHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
// 同门店同业务场景合并(与「业务场景」列合并粒度一致)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
}, },
{ {
title: '一线阳光计算模式', title: '一线阳光计算模式',
...@@ -241,7 +276,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -241,7 +276,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 180, width: 180,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: bizPolicyHeaderStyle }), onHeaderCell: () => ({ style: bizPolicyHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
// 同门店同业务场景合并(与「业务场景」列合并粒度一致)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
}, },
{ {
title: '一线阳光2计算模式', title: '一线阳光2计算模式',
...@@ -285,7 +324,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -285,7 +324,11 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 160, width: 160,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: costHeaderStyle }), onHeaderCell: () => ({ style: costHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
// 运营成本按「门店 + 业务场景」维度合并(同一门店下不同业务场景的运营成本不同)
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v) => <MoneyCell value={v as string} />, render: (v) => <MoneyCell value={v as string} />,
}, },
{ {
...@@ -295,7 +338,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -295,7 +338,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 220, width: 220,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: costHeaderStyle }), onHeaderCell: () => ({ style: costHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v) => <MoneyCell value={v as string} />, render: (v) => <MoneyCell value={v as string} />,
}, },
{ {
...@@ -305,7 +351,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] { ...@@ -305,7 +351,10 @@ export function buildPolicyColumns(): TableProps<PolicyConfirmRow>['columns'] {
width: 140, width: 140,
align: 'center', align: 'center',
onHeaderCell: () => ({ style: costHeaderStyle }), onHeaderCell: () => ({ style: costHeaderStyle }),
onCell: () => ({ style: cellStyle }), onCell: (_r, index) => ({
rowSpan: getRowSpan(index ?? 0, (r) => `${r.storeName}|${r.businessScene}`),
style: cellStyle,
}),
render: (v) => <MoneyCell value={v as string} />, render: (v) => <MoneyCell value={v as string} />,
}, },
], ],
......
...@@ -24,7 +24,21 @@ export function PolicyConfirmTable({ ...@@ -24,7 +24,21 @@ export function PolicyConfirmTable({
ruleCategoryCount, ruleCategoryCount,
ruleTotalRows, ruleTotalRows,
}: PolicyConfirmTableProps) { }: PolicyConfirmTableProps) {
const columns = useMemo(() => buildPolicyColumns() as any[], []); /**
* 数据源优先级:previewRows(接口真实数据) > dataSource > mock 兜底
* 放在 columns 之前,因为 buildPolicyColumns 需要 rows 来计算同门店 / 同场景的合并单元格 rowSpan
*/
const rows: PolicyConfirmRow[] = useMemo(() => {
if (Array.isArray(previewRows) && previewRows.length > 0) {
return convertPreviewRows(previewRows);
}
if (Array.isArray(dataSource) && dataSource.length > 0) {
return dataSource;
}
return mockPolicyRows;
}, [dataSource, previewRows]);
const columns = useMemo(() => buildPolicyColumns(rows) as any[], [rows]);
/** /**
* 动态拼接 footer 文字:优先用外部传入的通过行统计, * 动态拼接 footer 文字:优先用外部传入的通过行统计,
...@@ -71,17 +85,6 @@ export function PolicyConfirmTable({ ...@@ -71,17 +85,6 @@ export function PolicyConfirmTable({
return colWidths.reduce((a, b) => a + b, 0) + 40; // 加 40px 冗余 return colWidths.reduce((a, b) => a + b, 0) + 40; // 加 40px 冗余
}, [columns]); }, [columns]);
const rows: PolicyConfirmRow[] = useMemo(() => {
// 优先级:previewRows(接口真实数据) > dataSource > mock 兜底
if (Array.isArray(previewRows) && previewRows.length > 0) {
return convertPreviewRows(previewRows);
}
if (Array.isArray(dataSource) && dataSource.length > 0) {
return dataSource;
}
return mockPolicyRows;
}, [dataSource, previewRows]);
// 显式标注 TableProps:否则 pagination:false 会被推断成 boolean,赋给 UTable 时类型不兼容 // 显式标注 TableProps:否则 pagination:false 会被推断成 boolean,赋给 UTable 时类型不兼容
const tableProps: TableProps<PolicyConfirmRow> = { const tableProps: TableProps<PolicyConfirmRow> = {
rowKey: (r: PolicyConfirmRow) => `${r.storeMerchantNo}-${r.businessScene}-${r.productCategory}`, rowKey: (r: PolicyConfirmRow) => `${r.storeMerchantNo}-${r.businessScene}-${r.productCategory}`,
......
...@@ -10,7 +10,6 @@ export interface SubmitActionBarProps { ...@@ -10,7 +10,6 @@ export interface SubmitActionBarProps {
} }
export function SubmitActionBar({ export function SubmitActionBar({
totalRows = 12,
loading = false, loading = false,
disabled = false, disabled = false,
onBack, onBack,
...@@ -40,7 +39,7 @@ export function SubmitActionBar({ ...@@ -40,7 +39,7 @@ export function SubmitActionBar({
disabled={disabled || loading} disabled={disabled || loading}
onClick={onSubmit ?? (() => console.log('确认提交并推送审批'))} onClick={onSubmit ?? (() => console.log('确认提交并推送审批'))}
> >
确认提交并推送审批({totalRows}) 确认提交并推送审批
</UButton> </UButton>
</div> </div>
); );
......
...@@ -44,19 +44,18 @@ function buildInfoFromCheckResult(vo: StoreImportCheckVO): SubmitConfirmInfo { ...@@ -44,19 +44,18 @@ function buildInfoFromCheckResult(vo: StoreImportCheckVO): SubmitConfirmInfo {
const monthly = Math.round(first?.costMonthly ?? 0); const monthly = Math.round(first?.costMonthly ?? 0);
const labor = Math.round(first?.costLabor ?? 0); const labor = Math.round(first?.costLabor ?? 0);
const total = deco + monthly + labor; const total = deco + monthly + labor;
const approvalRole = vo.nextRoleName ?? '优加财务经理'; const approvalRole = vo.nextRoleName ?? '-';
return { return {
storeName: vo.storeName ?? '巴州强冠东风汽车销售服务有限公司', storeName: vo.storeName ?? '-',
storeMerchantNo: vo.merchantNo ?? 'SQ20240115', storeMerchantNo: vo.merchantNo ?? '-',
categoryCount: vo.distinctProductCategoryCount ?? 6, categoryCount: vo.distinctProductCategoryCount ?? 6,
sceneCount: vo.distinctBusinessSceneCount ?? 2, sceneCount: vo.distinctBusinessSceneCount ?? 2,
totalRows: vo.productCategoryRowCount ?? vo.totalRows ?? 12, totalRows: vo.productCategoryRowCount ?? vo.totalRows ?? 12,
operatingCost: total > 0 ? `¥ ${total.toLocaleString('en-US')}` : '¥ 1,500.00', operatingCost: total > 0 ? `¥ ${total.toLocaleString('en-US')}` : '-',
operatingCostDetail: `门店维度字段(装修设备 ${deco} + 当月产生 ${monthly} + 人工成本 ${labor})`, operatingCostDetail: `门店维度字段(装修设备 ${deco} + 当月产生 ${monthly} + 人工成本 ${labor})`,
approvalChain: approvalRole, approvalChain: approvalRole,
approvalChainTag: '单级审批', approvalChainTag: '两级审批',
approvalChainDesc: '提交后直接进入单级审批,无中间节点', approvalChainDesc: '提交后直接进入两级审批,无中间节点',
// 预计审批人 = 当前提交人(登录用户名) + (审批角色)
expectedApprover: `${approvalRole}`, expectedApprover: `${approvalRole}`,
}; };
} }
......
import { useState, useCallback, useEffect } from 'react'; import { useState, useCallback, useEffect, useRef } from 'react';
import { App } from 'antd'; import { App } from 'antd';
import { import {
InfoCircleFilled, InfoCircleFilled,
...@@ -40,6 +40,10 @@ export function UploadCard({ ...@@ -40,6 +40,10 @@ export function UploadCard({
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const [downloading, setDownloading] = useState(false); const [downloading, setDownloading] = useState(false);
const [fileList, setFileList] = useState<UploadFile[]>([]); const [fileList, setFileList] = useState<UploadFile[]>([]);
// antd Upload 实例,用于编程式打开文件选择框
const uploadRef = useRef<any>(null);
// 记录上一次已处理的 reUploadTrigger,防止 effect 因其它依赖变化而重复触发
const processedTriggerRef = useRef(0);
/** 从 checkResult + 文件名推导要显示的统计文案:共 N 行(X 家门店 × Y 场景 × Z 分类)· 模板版本 vX.X.X */ /** 从 checkResult + 文件名推导要显示的统计文案:共 N 行(X 家门店 × Y 场景 × Z 分类)· 模板版本 vX.X.X */
const statLineText = (() => { const statLineText = (() => {
...@@ -100,18 +104,6 @@ export function UploadCard({ ...@@ -100,18 +104,6 @@ export function UploadCard({
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [file]); }, [file]);
/**
* Step 2 → 点击失败明细里的【重新上传】:
* 父组件 handleReUpload = 切 Step0 + 清空 checkResult + reUploadCounter++
* 本 useEffect 监听 reUploadTrigger(>0 表示被触发过)+ 有 file + 非 uploading → 自动 runUpload
*/
useEffect(() => {
if (reUploadTrigger > 0 && file && !uploading) {
void runUpload(file);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reUploadTrigger]);
const clearFileState = useCallback(() => { const clearFileState = useCallback(() => {
setFileList([]); setFileList([]);
onFileChange?.(null); onFileChange?.(null);
...@@ -191,6 +183,38 @@ export function UploadCard({ ...@@ -191,6 +183,38 @@ export function UploadCard({
fileList, fileList,
}; };
/**
* Step 2 → 点击失败明细里的【重新上传】:
* 父组件 handleReUpload = 切 Step0 + 清空 checkResult + reUploadCounter++
* 本 effect 监听 reUploadTrigger 变化,清空已选文件并编程式打开文件选择对话框,
* 让用户重新选择文件(选完文件后走正常 customRequest → runUpload → check 接口链路)。
* 注意:不再自动用原文件调用 check 接口,必须由用户重新选文件。
*/
useEffect(() => {
if (reUploadTrigger <= 0) return;
if (reUploadTrigger === processedTriggerRef.current) return;
processedTriggerRef.current = reUploadTrigger;
// 清空文件状态
setFileList([]);
onFileChange?.(null);
// 等 DOM 更新后再打开文件选择框:兼容 antd Upload ref 可能不暴露 upload() 的情况,
// 优先用 ref.upload(),兜底通过 DOM 查找隐藏的 input[type=file] 触发 click
setTimeout(() => {
const inst = uploadRef.current;
if (inst && typeof inst.upload === 'function') {
inst.upload();
return;
}
const input = document.querySelector<HTMLInputElement>(
'.uj-upload-dragger input[type="file"], .ant-upload input[type="file"]',
);
if (input) {
input.value = '';
input.click();
}
}, 0);
}, [reUploadTrigger, onFileChange]);
return ( return (
<UCard <UCard
styles={{ body: { padding: 20 } }} styles={{ body: { padding: 20 } }}
...@@ -209,7 +233,7 @@ export function UploadCard({ ...@@ -209,7 +233,7 @@ export function UploadCard({
} }
> >
<div style={{ position: 'relative' }}> <div style={{ position: 'relative' }}>
<UUpload.Dragger {...uploadProps}> <UUpload.Dragger ref={uploadRef} {...uploadProps}>
<div style={{ padding: '30px 0' }}> <div style={{ padding: '30px 0' }}>
<div <div
style={{ style={{
......
...@@ -82,22 +82,10 @@ export interface ValidationStatsProps { ...@@ -82,22 +82,10 @@ export interface ValidationStatsProps {
checkResult?: StoreImportCheckVO; checkResult?: StoreImportCheckVO;
} }
function calcOperatingCost(vo: StoreImportCheckVO): number {
const rows = vo.previewRows ?? [];
if (rows.length === 0) return 0;
const first = rows[0];
return (
Math.round(first.costDecoration ?? 0) +
Math.round(first.costMonthly ?? 0) +
Math.round(first.costLabor ?? 0)
);
}
function buildStatsFromCheckResult(vo: StoreImportCheckVO): StatItem[] { function buildStatsFromCheckResult(vo: StoreImportCheckVO): StatItem[] {
const rows = vo.productCategoryRowCount ?? vo.totalRows; const rows = vo.productCategoryRowCount ?? vo.totalRows;
const storeCount = 1; const storeCount = 1;
const sceneCount = vo.distinctBusinessSceneCount; const sceneCount = vo.distinctBusinessSceneCount;
const operating = calcOperatingCost(vo);
const items: StatItem[] = [ const items: StatItem[] = [
{ {
...@@ -123,13 +111,6 @@ function buildStatsFromCheckResult(vo: StoreImportCheckVO): StatItem[] { ...@@ -123,13 +111,6 @@ function buildStatsFromCheckResult(vo: StoreImportCheckVO): StatItem[] {
}); });
} }
items.push({
label: '运营成本合计',
value: operating > 0 ? `¥ ${operating.toLocaleString('en-US')}` : '-',
desc: '门店维度(装修设备 + 当月产生 + 人工成本)',
tone: 'default',
});
return items; return items;
} }
...@@ -151,11 +132,13 @@ const defaultStats: StatItem[] = [ ...@@ -151,11 +132,13 @@ const defaultStats: StatItem[] = [
export function ValidationStats({ stats, checkResult }: ValidationStatsProps) { export function ValidationStats({ stats, checkResult }: ValidationStatsProps) {
const finalStats: StatItem[] = const finalStats: StatItem[] =
stats ?? (checkResult ? buildStatsFromCheckResult(checkResult) : defaultStats); stats ?? (checkResult ? buildStatsFromCheckResult(checkResult) : defaultStats);
// 按实际卡片数量平分整行宽度
const colCount = Math.max(1, finalStats.length);
return ( return (
<div <div
style={{ style={{
display: 'grid', display: 'grid',
gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gridTemplateColumns: `repeat(${colCount}, minmax(0, 1fr))`,
gap: 16, gap: 16,
marginBottom: 20, marginBottom: 20,
}} }}
......
...@@ -45,12 +45,13 @@ export default function TemplateImport() { ...@@ -45,12 +45,13 @@ export default function TemplateImport() {
const handleFileChange = (f: File | null) => { const handleFileChange = (f: File | null) => {
setSelectedFile(f); setSelectedFile(f);
// 移除文件时,同步清空校验结果 + 导入信息里的 3 个回显字段(保留 remark) // 移除文件时,同步清空校验结果 + 导入信息里的 3 个回显字段(保留 remark)
// 注意:org/scene 用 undefined 而非 '',否则 antd Select 会把 '' 当成选中值,placeholder 不显示
if (f === null) { if (f === null) {
setCheckResult(null); setCheckResult(null);
setImportInfo((prev) => ({ setImportInfo((prev) => ({
org: prev?.org ?? '', org: undefined,
scene: prev?.scene ?? '', scene: undefined,
categories: prev?.categories ?? [], categories: [],
remark: prev?.remark, remark: prev?.remark,
})); }));
} }
...@@ -76,7 +77,9 @@ export default function TemplateImport() { ...@@ -76,7 +77,9 @@ export default function TemplateImport() {
}; };
const handleReUpload = () => { const handleReUpload = () => {
// Step 2 重新上传:不清空文件,回到 Step0 后由 UploadCard.useEffect 监听 trigger 自动重跑上传 // Step 2 重新上传:清空文件 + checkResult,回到 Step0 后由 UploadCard 打开文件选择对话框,
// 用户重新选择文件后走正常 customRequest → runUpload → check 接口链路
setSelectedFile(null);
setCheckResult(null); setCheckResult(null);
setSubmitChecked(true); setSubmitChecked(true);
setCurrentStep(0); setCurrentStep(0);
...@@ -96,14 +99,14 @@ export default function TemplateImport() { ...@@ -96,14 +99,14 @@ export default function TemplateImport() {
setCheckResult(result); setCheckResult(result);
modal.success({ modal.success({
title: '提交审批成功', title: '提交审批成功',
content: `已提交 ${result.passRows ?? 0} 行 / 涉及 ${listingIds.length} 条上架记录,请在「门店审批」中跟踪进度。`, content: `涉及 ${listingIds.length} 条上架记录,请在「门店审批」中跟踪进度。`,
okText: '前往门店审批', okText: '前往门店审批',
okButtonProps: { type: 'primary' }, okButtonProps: { type: 'primary' },
cancelText: '知道了', cancelText: '知道了',
// 非阻塞(不强制跳转):「知道了」留在当前页 // 非阻塞(不强制跳转):「知道了」留在当前页
onOk: () => { onOk: () => {
// 跳转门店审批页(对应路由:/store/approve) // 跳转门店审批页,tab=mine 默认定位到「我发起的」页签
window.location.href = '/store/approve'; window.location.href = '/store/approval?tab=mine';
}, },
}); });
} catch (e) { } catch (e) {
...@@ -143,7 +146,11 @@ export default function TemplateImport() { ...@@ -143,7 +146,11 @@ export default function TemplateImport() {
{currentStep === 1 && ( {currentStep === 1 && (
<> <>
<ValidationStats checkResult={checkResult ?? undefined} /> <ValidationStats checkResult={checkResult ?? undefined} />
<FailDetailCard checkResult={checkResult ?? undefined} onReUpload={handleReUpload} /> <FailDetailCard
checkResult={checkResult ?? undefined}
fileSize={selectedFile?.size}
onReUpload={handleReUpload}
/>
<ValidationActionBar nextDisabled={failCount > 0} onBack={goPrev} onNextStep={goNext} /> <ValidationActionBar nextDisabled={failCount > 0} onBack={goPrev} onNextStep={goNext} />
</> </>
)} )}
......
import { lazy, StrictMode, Suspense } from 'react';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { createMemoryRouter, RouterProvider } from 'react-router-dom';
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { router as initialRouter } from './index';
const reload = vi.fn();
const routers: ReturnType<typeof createMemoryRouter>[] = [];
afterAll(() => initialRouter.dispose());
async function renderFailedRoute(error: unknown) {
// 使用真实路由注册的错误页,漏配 errorElement 也必须让测试失败。
const { router } = await import('./index');
const rootRoute = router.routes.find((route) => route.path === '/');
router.dispose();
const BrokenPage = lazy(async () => {
throw error;
});
const memoryRouter = createMemoryRouter(
[
{
path: '/',
errorElement: rootRoute?.errorElement,
children: [
{
path: 'store/import',
element: (
<Suspense fallback="加载中">
<BrokenPage />
</Suspense>
),
},
],
},
],
{ initialEntries: ['/store/import?tab=pending#upload'] },
);
routers.push(memoryRouter);
render(
<StrictMode>
<RouterProvider router={memoryRouter} />
</StrictMode>,
);
}
beforeEach(() => {
sessionStorage.clear();
reload.mockReset();
vi.stubGlobal('location', { ...window.location, reload });
// 这些用例故意让路由组件抛错,React 会输出已由边界处理的错误。
vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
cleanup();
routers.splice(0).forEach((router) => router.dispose());
vi.restoreAllMocks();
vi.unstubAllGlobals();
sessionStorage.clear();
});
describe('路由资源加载失败恢复', () => {
it.each([
new TypeError(
'Failed to fetch dynamically imported module: https://youjia.test.glsx.com.cn/assets/index-DAYbQRtY.js',
),
new TypeError('error loading dynamically imported module: https://example.com/assets/page.js'),
new TypeError('Importing a module script failed.'),
new Error('Unable to preload CSS for /assets/page-abc.css'),
])('首次资源加载失败只刷新一次(含 StrictMode):%s', async (error) => {
await renderFailedRoute(error);
await waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
expect(screen.getByText('页面资源加载失败')).toBeInTheDocument();
expect(screen.getByRole('button', { name: '刷新页面' })).toBeInTheDocument();
});
it('重新加载应用后仍失败只显示手动刷新入口,手动刷新也不重置自动刷新次数', async () => {
const error = new TypeError('Failed to fetch dynamically imported module: /assets/old.js');
await renderFailedRoute(error);
await waitFor(() => expect(reload).toHaveBeenCalledTimes(1));
cleanup();
// 模拟整页刷新丢弃 JS 内存,保留该标签页的 sessionStorage。
vi.resetModules();
await renderFailedRoute(
new TypeError('Failed to fetch dynamically imported module: /assets/another.js'),
);
const button = await screen.findByRole('button', { name: '刷新页面' });
expect(reload).toHaveBeenCalledTimes(1);
fireEvent.click(button);
expect(reload).toHaveBeenCalledTimes(2);
cleanup();
vi.resetModules();
await renderFailedRoute(error);
await screen.findByRole('button', { name: '刷新页面' });
expect(reload).toHaveBeenCalledTimes(2);
});
it.each([
new Error('审批提交失败'),
new TypeError('Failed to fetch'),
new TypeError("Cannot read properties of undefined (reading 'name')"),
new SyntaxError('Unexpected token'),
new Error('Failed to fetch dynamically imported module: 业务错误信息'),
'Failed to fetch dynamically imported module: 字符串业务错误',
])('普通业务或运行时异常不自动刷新:%s', async (error) => {
await renderFailedRoute(error);
expect(await screen.findByText('页面发生错误')).toBeInTheDocument();
expect(reload).not.toHaveBeenCalled();
expect(sessionStorage.length).toBe(0);
});
it.each(['getItem', 'setItem'] as const)(
'sessionStorage.%s 不可用时保守提供手动刷新,避免循环',
async (method) => {
vi.spyOn(Storage.prototype, method).mockImplementation(() => {
throw new DOMException('Storage unavailable', 'SecurityError');
});
await renderFailedRoute(
new TypeError('Failed to fetch dynamically imported module: /assets/page.js'),
);
const button = await screen.findByRole('button', { name: '刷新页面' });
expect(reload).not.toHaveBeenCalled();
fireEvent.click(button);
expect(reload).toHaveBeenCalledTimes(1);
},
);
});
import { useEffect } from 'react';
import { useRouteError } from 'react-router-dom';
import { UButton, UResult } from '@uj/ui';
const RELOAD_KEY = 'uj-store:chunk-reload-attempted';
function isResourceLoadError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return (
(error.name === 'TypeError' &&
/^(Failed to fetch dynamically imported module:|error loading dynamically imported module:|Importing a module script failed\.?$)/i.test(
error.message,
)) ||
/^Unable to preload CSS for /.test(error.message)
);
}
export default function RouteErrorBoundary() {
const error = useRouteError();
const resourceLoadFailed = isResourceLoadError(error);
useEffect(() => {
if (!resourceLoadFailed) return;
try {
if (sessionStorage.getItem(RELOAD_KEY) !== null) return;
// 必须先持久化再刷新;整个标签页会话只自动尝试一次,手动刷新也不清除此标记。
sessionStorage.setItem(RELOAD_KEY, '1');
} catch {
// 无法跨刷新保存次数时,仅提供手动恢复,避免无限刷新。
return;
}
window.location.reload();
}, [resourceLoadFailed]);
return (
<UResult
status="error"
title={resourceLoadFailed ? '页面资源加载失败' : '页面发生错误'}
subTitle={
resourceLoadFailed
? '请检查网络后刷新页面。如果仍无法打开,请联系管理员。'
: '请刷新页面重试。如果问题持续出现,请联系管理员。'
}
extra={<UButton onClick={() => window.location.reload()}>刷新页面</UButton>}
/>
);
}
...@@ -12,6 +12,7 @@ import BasicLayout from '@/layouts/BasicLayout'; ...@@ -12,6 +12,7 @@ import BasicLayout from '@/layouts/BasicLayout';
import Login from '@/pages/Login'; import Login from '@/pages/Login';
import NotFound from '@/pages/NotFound'; import NotFound from '@/pages/NotFound';
import { useAppStore } from '@/store/useAppStore'; import { useAppStore } from '@/store/useAppStore';
import RouteErrorBoundary from './RouteErrorBoundary';
// 路由级代码分割:首屏仅加载 Login/NotFound,其余页面按需懒加载 // 路由级代码分割:首屏仅加载 Login/NotFound,其余页面按需懒加载
const Dashboard = lazy(() => import('@/pages/Dashboard')); const Dashboard = lazy(() => import('@/pages/Dashboard'));
...@@ -36,6 +37,7 @@ export const router = createBrowserRouter([ ...@@ -36,6 +37,7 @@ export const router = createBrowserRouter([
{ path: '/login', element: <Login /> }, { path: '/login', element: <Login /> },
{ {
path: '/', path: '/',
errorElement: <RouteErrorBoundary />,
element: ( element: (
<RequireAuth> <RequireAuth>
<BasicLayout /> <BasicLayout />
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!