Commit 37ad326c by liimin

feat: 初始化 uj-console wujie 微前端 monorepo

单体 uj-store 重构为 wujie 微前端:shell(host) + micro-apps(system/store) + packages。

核心约定:
- 请求层不下放,全项目仅 shell 经 props.request 发 HTTP,baseURL 只解析一次。
- 后端地址按访问连接推导:VITE_API_TARGET 留空→同源(生产访问什么域名打什么域名,
  如 http://ujia.glsx.com.cn/youjia/...,由 nginx 转发,零配置无需 CORS);
  内网调试填 VITE_API_TARGET 即浏览器直连固定后端,不区分测试/生产多套配置。
- 移除 proxy/direct 二元模式与 /api 前缀代理;context-path(/youjia) 由拦截器补并计入签名。

含 alias 单源、PEM 虚拟模块、签名链路、定向发版 release.mjs、lint/format 全量清偿、
边界静态校验 check-boundaries,以及 tsconfig/eslint/vite 配置脚手架。
1 parent 8bab2fc6
Showing 263 changed files with 5115 additions and 0 deletions
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
# ---------------------------------------------------------------------------
# 只有 shell 需要这份配置。子应用不读任何 VITE_* 密钥,也不注入 PEM 虚拟模块。
# 复制为 apps/web/shell/.env 后按需改 VITE_API_TARGET(指向你本机/测试可达的后端)。
# ---------------------------------------------------------------------------
# 内网调试:固定后端地址(浏览器直连,需后端对当前来源开放 CORS)。
# 留空 → 同源:生产访问什么域名就打什么域名(如 http://ujia.glsx.com.cn/youjia/...),无需改配置。
VITE_API_TARGET=http://192.168.3.197:8788
# 后端 context-path,会同时出现在实际请求路径与签名 canonical 第 2 行,必须与后端严格一致
VITE_API_CONTEXT_PATH=/youjia
# 签名开关:开发期可临时置 false 借后端宽松模式放行;生产务必 true
VITE_SIGN_ENABLED=true
VITE_SIGN_DEBUG=false
VITE_STRICT_VERIFY=false
# 生产可选:CI 注入 PEM(Base64 公钥体 / 完整私钥 PEM),用于无法放文件时的兜底
# VITE_SERVER_PUBLIC_KEY=
# VITE_CLIENT_PRIVATE_KEY=
# 运行时子应用清单(独立部署用)。
# ⚠ 生产必填:uj.entry 写的是 localhost 开发机地址,生产环境 entryOf() 会拒绝回落到它,
# 没清单时子应用会显示「未找到子应用入口」。该 URL 必须响应 Cache-Control: no-cache。
# VITE_MANIFEST_URL=/mfe/manifest.json
node_modules/
dist/
.turbo/
.tmp/
coverage/
# 发版脚本产出的待上传目录(版本化产物 + manifest.json)
.release/
*.log
# 环境变量(可含密钥兜底值)
.env
.env.local
.env.*.local
# 签名密钥材料:绝不入库。从旧仓手工拷贝到 apps/web/shell/keys/
**/keys/*.pem
*.pem
# 编辑器 / 系统
.vscode/*
!.vscode/settings.json
.idea/
.DS_Store
Thumbs.db
# WorkBuddy 内部状态(项目记忆/工具数据,非源码)
.workbuddy/
# ---------------------------------------------------------------------------
# 流水线:verify → 受影响应用独立构建 → 手动发布单个子应用
#
# 发一个子应用不需要重建主壳:build:* 只打该 app 的 dist,deploy:* 只上传该
# 版本目录并增量改 manifest.json。见 docs/DEPLOY.md 与 scripts/release.mjs。
#
# 仍需按实际基础设施接线的两处(不臆造制品库):
# MFE_PUBLIC_BASE 产物对外根地址,留空 = 同源 /mfe/...;跨域 CDN 填完整域名
# MFE_UPLOAD_CMD 上传钩子模板,{dir}=本地待上传目录 {remote}=远端相对路径
# 以及「用 build 产物起静态服务逐路由冒烟」这一关(dev/prod 链路不同,不能只信 dev)
# ---------------------------------------------------------------------------
stages:
- verify
- build
- deploy
variables:
PNPM_VERSION: 10.32.1
# 留空时 release.mjs 只产出 .release/ 待上传目录,由下游流水线/人工上传
MFE_PUBLIC_BASE: ''
MFE_UPLOAD_CMD: ''
.pnpm:
image: node:22
before_script:
- corepack enable
- corepack prepare pnpm@${PNPM_VERSION} --activate
- pnpm install --frozen-lockfile
cache:
key:
files:
- pnpm-lock.yaml
paths:
- .pnpm-store
verify:
extends: .pnpm
stage: verify
script:
# boundaries + reconcile + typecheck + lint + format:check
- pnpm verify
# ---- 独立构建:只发一个模块 ----
# 版本号:打 tag 用 tag,否则用短 sha。产物目录不可变,同一次提交重复发会被拒绝。
# SUBAPP_BASE 让产物资源路径对齐 /mfe/<app>/<version>/,否则部署后 404 白屏;
# 它已列入 turbo.json 的 globalEnv,换版本重建不会被缓存命中。
build:shell:
extends: .pnpm
stage: build
script:
- pnpm build:shell
artifacts:
paths: [apps/web/shell/dist/]
rules:
- changes:
- apps/web/shell/**/*
- packages/platform-core/**/*
- packages/contracts/**/*
- packages/design-tokens/**/*
- packages/vite-config/**/*
- packages/typescript-config/**/*
- packages/eslint-config/**/*
- pnpm-workspace.yaml
- pnpm-lock.yaml
- turbo.json
- tsconfig.base.json
build:system:
extends: .pnpm
stage: build
script:
- export MFE_VERSION="${CI_COMMIT_TAG:-$CI_COMMIT_SHORT_SHA}"
- export SUBAPP_BASE="${MFE_PUBLIC_BASE}/mfe/system/${MFE_VERSION}/"
- pnpm build:system
artifacts:
paths: [apps/web/micro-apps/system/dist/]
rules:
- changes:
- apps/web/micro-apps/system/**/*
- packages/platform-sdk/**/*
- packages/ui/**/*
- packages/biz/**/*
- packages/design-tokens/**/*
- packages/contracts/**/*
- packages/vite-config/**/*
- packages/typescript-config/**/*
- packages/eslint-config/**/*
- pnpm-workspace.yaml
- pnpm-lock.yaml
- turbo.json
- tsconfig.base.json
build:store:
extends: .pnpm
stage: build
script:
- export MFE_VERSION="${CI_COMMIT_TAG:-$CI_COMMIT_SHORT_SHA}"
- export SUBAPP_BASE="${MFE_PUBLIC_BASE}/mfe/store/${MFE_VERSION}/"
- pnpm build:store
artifacts:
paths: [apps/web/micro-apps/store/dist/]
rules:
- changes:
- apps/web/micro-apps/store/**/*
- packages/platform-sdk/**/*
- packages/ui/**/*
- packages/biz/**/*
- packages/design-tokens/**/*
- packages/contracts/**/*
- packages/vite-config/**/*
- packages/typescript-config/**/*
- packages/eslint-config/**/*
- pnpm-workspace.yaml
- pnpm-lock.yaml
- turbo.json
- tsconfig.base.json
# ---- 发布单个子应用:只上传该版本目录 + 改 manifest,host 不重建 ----
# when: manual 是刻意留的:清单一旦切过去,所有在线用户整页刷新后就会用新版本。
deploy:system:
extends: .pnpm
stage: deploy
needs: [build:system]
script:
- export MFE_VERSION="${CI_COMMIT_TAG:-$CI_COMMIT_SHORT_SHA}"
- node scripts/release.mjs --app system --version "$MFE_VERSION" --skip-build
artifacts:
paths: [.release/]
rules:
- changes:
- apps/web/micro-apps/system/**/*
- packages/platform-sdk/**/*
- packages/ui/**/*
- packages/biz/**/*
- packages/design-tokens/**/*
- packages/contracts/**/*
- packages/vite-config/**/*
- pnpm-workspace.yaml
- pnpm-lock.yaml
when: manual
deploy:store:
extends: .pnpm
stage: deploy
needs: [build:store]
script:
- export MFE_VERSION="${CI_COMMIT_TAG:-$CI_COMMIT_SHORT_SHA}"
- node scripts/release.mjs --app store --version "$MFE_VERSION" --skip-build
artifacts:
paths: [.release/]
rules:
- changes:
- apps/web/micro-apps/store/**/*
- packages/platform-sdk/**/*
- packages/ui/**/*
- packages/biz/**/*
- packages/design-tokens/**/*
- packages/contracts/**/*
- packages/vite-config/**/*
- pnpm-workspace.yaml
- pnpm-lock.yaml
when: manual
# 回滚不需要构建:只把清单指回旧版本目录。填 ROLLBACK_VERSION 后手动触发。
rollback:
stage: deploy
image: node:22
variables:
ROLLBACK_APP: system
script:
- node scripts/release.mjs --app "$ROLLBACK_APP" --version "$ROLLBACK_VERSION" --switch-only
artifacts:
paths: [.release/]
rules:
- if: '$ROLLBACK_VERSION'
when: manual
# 主壳变更必须整站重新部署(它承载 index.html 与 VITE_MANIFEST_URL),
# 不走版本化子应用目录。上传命令按实际站点部署方式接线。
deploy:shell:
stage: deploy
image: node:22
needs: [build:shell]
script:
- echo "TODO: 把 apps/web/shell/dist/ 部署到站点根;确认 VITE_MANIFEST_URL 指向 /mfe/manifest.json"
- echo "注意 manifest.json 必须响应 Cache-Control: no-cache"
rules:
- changes:
- apps/web/shell/**/*
- packages/platform-core/**/*
when: manual
# ---------------------------------------------------------------------------
# pnpm workspace 行为约定(沿用 atlas)
# ---------------------------------------------------------------------------
# 内部包一律软链到 workspace,禁止从远端拉同名包
link-workspace-packages=true
prefer-workspace-packages=true
save-workspace-protocol=false
# 自动安装 peer 依赖并去重,避免 react 多实例
auto-install-peers=true
dedupe-peer-dependents=true
strict-peer-dependencies=false
# 严格 node_modules 结构,杜绝幽灵依赖
node-linker=isolated
# lockfile 记录精确版本,方便审计
save-exact=false
resolution-mode=highest
# 关闭「跑脚本前校验依赖是否过期」:该检查并发读写
# node_modules/.pnpm-workspace-state-v1.json,turbo 并行调度多个 pnpm run 时
# 会互相读到半截文件导致 JSON.parse 硬失败。依赖是否过期由 pnpm install 保证。
verify-deps-before-run=false
# 生成物 / 依赖锁由工具链自己维护,格式化后会被重新生成覆盖回去
node_modules/
**/dist/
.turbo/
.release/
coverage/
pnpm-lock.yaml
# 私钥材料不入库,也不参与格式化
**/keys/*.pem
{
"singleQuote": true,
"semi": true,
"printWidth": 100,
"trailingComma": "all",
"arrowParens": "always",
"endOfLine": "lf",
"overrides": [
{
"files": "*.md",
"options": { "proseWrap": "preserve" }
}
]
}
# uj-console
优加门店上架系统的 **wujie(无界)微前端版**,从 `D:\work\uj-store` 单体重构而来。旧仓全程只读,未做任何改动。
- 主壳:`@uj/web-shell`(登录 / 布局 / 菜单 / 路由分发 / RSA 签名链路 / 子应用挂载)
- 子应用:`@uj/web-system`(系统管理域)、`@uj/web-store`(门店业务域)
- 共享包:`contracts`(type-only 契约)、`platform-core`(host 独占运行时)、`platform-sdk`(子应用 SDK)、`ui`、`biz`、`design-tokens`、`vite-config`、`typescript-config`、`eslint-config`
- 工程规范借鉴 `D:\work\demo\atlas`(catalog / turbo / 共享 vite 工厂 / wujie 握手实证)与 `D:\work\demo\genesis`(catalog 收录标准、dev 自动发现、CI 闸门)
## 当前状态(务必先读)
**这是一份可继续推进的架构骨架,不是已验收可上线的系统。** 已完成的与未完成的分开列:
| 已完成 | 证据 |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| 从旧仓同步 149 个业务源码文件,旧仓只读 | `pnpm sync -- --write`;16 个测试/PEM 被规则排除 |
| 全量 TS/TSX 语法检查 180 个文件 0 错误 | TypeScript parser `parseDiagnostics` |
| **8 个包 `tsc --noEmit` 全量类型检查 0 错误** | `pnpm typecheck`(turbo 8/8 successful,实测) |
| **三个应用 `vite build` 全部成功** | `pnpm build`(turbo 3/3 successful,实测) |
| **`pnpm verify` 全绿** | boundaries → reconcile → typecheck → lint → lint:all → format:check,退出码 0 |
| **lint / format 历史债全量清偿(B 方案)** | 39 条 error + 9 条 warning 归零,175 个文件完成 prettier 格式化 |
| 架构边界闸门 0 错误(1 条 CSS 告警) | `node scripts/check-boundaries.mjs` |
| 工程结构对账 0 问题(13 个包 / 29 个 catalog 条目 / 3 个端口) | `node scripts/reconcile.mjs` |
| 签名密钥本地就位(`*.pem` 已被 .gitignore 排除) | 从旧仓 `src/api/core/keys/` 只读拷贝到 `apps/web/shell/keys/` |
| wujie 握手、alive 保活、props.request 代理、运行时 manifest、统一登出 | `apps/web/shell/src/*`、`packages/platform-sdk/src/*` |
| 单模块发版(版本化产物 + base 校验 + 清单增量更新 + 回滚),11 条自测断言全过 | `scripts/release.mjs`;用法见 `docs/DEPLOY.md` |
| 未完成 | 原因 |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| 四项 wujie PoC 实测 | 必须真实浏览器验证,见 ARCHITECTURE.md §7 |
| 测试文件重写 | 16 个 `*.test.*` 被排除,需按新 alias 重写并补 jsdom 配置 |
| 制品上传与冒烟关 | CI 的 build/deploy 已接上 `release.mjs`,但 `MFE_UPLOAD_CMD` / `MFE_PUBLIC_BASE` 与「用 build 产物逐路由冒烟」需按实际制品库补齐 |
> **全量清偿记录(B 方案,2026-11-05)**:新仓源码从现在起独立演进,不再与旧仓逐字对应。
>
> - **格式**:`prettier --write .` 处理 175 个文件;新增 `.prettierignore` 排除 `pnpm-lock.yaml` / `dist` 等生成物,避免被工具链重写后出现假性不合规。
> - **lint error 39 条**:`no-explicit-any` 全部换成具体类型(`import.meta.env` 收口为 `Record<string, string | undefined>`、axios 拦截器改用 `InternalAxiosRequestConfig` / `AxiosResponse` + 结构守卫);`@ts-ignore` 换成 shell tsconfig 正式纳入的 ambient 声明;`react-hooks/rules-of-hooks` 的**条件调用 `useMemo` 是真 bug**,把 `FailDetailCard` 的 early return 移到所有 Hook 之后。
> - **warning 9 条(`--max-warnings=0` 同样卡闸门)**:`router.tsx` 的路由守卫、`columns.tsx` 的 4 个展示组件分别拆成 `RequireAuth.tsx` / `cells.tsx`;分页 effect 改为依赖原始值;`setRole` / `loadPermissions` 用 `useCallback` 固定引用;删掉一条失效的 `eslint-disable`。
> - **闸门覆盖补全**:`platform-core` / `platform-sdk` 等 8 个包原本没有 `lint` 脚本,turbo 根本没扫到它们。新增根级 `pnpm lint:all`(`eslint . --max-warnings=0`)并纳入 `verify`,与逐包 `lint` 双口径都要求零 warning。
> - **防止刷回**:`sync-from-uj-store.mjs` 已冻结 `--force`,误跑会把今天的格式与修复全部覆盖回旧仓原样;仅历史对账时显式 `--unfreeze --force` 放行。
## 快速开始
```bash
# 1. 安装依赖(首次)
pnpm install
# 2. 环境变量:只有主壳读 .env
cp .env.example apps/web/shell/.env
# 3. 签名密钥:本仓已就位(*.pem 已被 .gitignore 排除)。换机器时重新执行:
# mkdir -p apps/web/shell/keys
# cp "D:/work/uj-store/src/api/core/keys/client_private.pem" apps/web/shell/keys/
# cp "D:/work/uj-store/src/api/core/keys/server_public.pem" apps/web/shell/keys/
# 4. 一条命令起全站(主壳 5173 + system 5174 + store 5175)
pnpm dev
```
浏览器只访问 **http://localhost:5173**。wujie 的子应用需要各自的 dev server 才有 HMR,进程数变多,但入口仍是一个命令、一个地址。服务启停由你控制,脚本不常驻。
## 目录结构
```
apps/web/
shell/ @uj/web-shell :5173 主壳
keys/ PEM(gitignore)
src/MicroApp.tsx wujie core 直调 / 握手 / alive 保活 / 失败自愈
src/subapps.ts 目录推导注册清单(import.meta.glob)
src/subapp-props.ts props.request 唯一构造点
src/subapp-lifecycle.ts 统一登出:广播 + destroyApp
src/runtime-manifest.ts 运行时清单(独立部署)
micro-apps/
system/ @uj/web-system :5174 角色管理 / 账号管理
store/ @uj/web-store :5175 导入 / 审批 / 列表 + features/store
packages/
contracts/ type-only:SubAppProps / RemoteRequest / SubAppManifest / busEvents
platform-core/ host 独占:axios + 签名 + PEM + AccessProvider + queryClient + zustand
platform-sdk/ 子应用:RemoteApiClient / SubAppProvider / compat 兼容层
ui/ biz/ design-tokens/ 纯组件 / 跨域常量 / 主题(各自打进产物)
vite-config/ alias 单一真源 + shell/子应用两套 Vite 工厂
typescript-config/ eslint-config/
scripts/
sync-from-uj-store.mjs 旧仓 -> 新仓源码同步(默认 dry-run,只读旧仓)
gen-tsconfig.mjs 从 alias 表生成各 app 的 tsconfig.paths
check-boundaries.mjs 架构边界闸门
reconcile.mjs 工程结构对账
dev.mjs 一条命令起全站
```
## 常用命令
| 命令 | 说明 |
| ---------------------- | ------------------------------------------------------------------- |
| `pnpm dev` | 并行起 shell + 两个子应用(`--scope=shell` 可只起一个) |
| `pnpm build` | turbo 构建全部;也可 `pnpm build:store` 只构建一个子应用 |
| `pnpm boundaries` | 边界闸门:子应用不许 import platform-core / PEM / axios 运行时 |
| `pnpm reconcile` | 结构对账:workspace 引用、catalog、alias 目标、端口冲突 |
| `pnpm gen:tsconfig` | 从 alias 表重生成三份 tsconfig(新增子应用后必跑) |
| `pnpm sync -- --write` | 重新同步旧仓源码(不覆盖已有文件;`--force` 已冻结) |
| `pnpm lint:all` | 根级全仓 eslint,覆盖没有 lint 脚本的共享包,`--max-warnings=0` |
| `pnpm verify` | boundaries → reconcile → typecheck → lint → lint:all → format:check |
| `pnpm ci` | verify + build |
## 三条不可动摇的约束
1. **请求层绝不下放。** 子应用不打包 `axios`、PEM 虚拟模块、5 个 `VITE_*` 签名配置,所有请求经 `props.request` 由主壳那份带 RSA 加签/验签/401 统一登出的 axios 实例代理。理由见 ARCHITECTURE.md §2。
2. **`@/xxx` 的 alias 表是单一真源。** `packages/vite-config/src/aliases.mjs` 同时驱动 Vite `resolve.alias` 与 tsconfig `paths`,业务源码的 import 路径不用改(全量清偿后部分文件已按新规范调整,但映射契约不变)。手抄两份必然出现「dev 能跑、tsc 报找不到模块」。
3. **跨应用共享只有显式契约。** `@uj/contracts` 只放 type 与无副作用常量;任何 `createContext` / axios 实例 / `QueryClient` 都不许放进共享包。
延伸阅读:[ARCHITECTURE.md](./ARCHITECTURE.md) · [docs/MIGRATION.md](./docs/MIGRATION.md) · [docs/DEPLOY.md](./docs/DEPLOY.md)
import { app } from '@uj/eslint-config';
export default app({ noRestrictedImports: true });
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>门店业务 · 子应用</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
{
"name": "@uj/web-store",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint . --max-warnings=0",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@uj/biz": "workspace:*",
"@uj/contracts": "workspace:*",
"@uj/design-tokens": "workspace:*",
"@uj/platform-sdk": "workspace:*",
"@uj/ui": "workspace:*",
"@ant-design/icons": "catalog:",
"@tanstack/react-query": "catalog:",
"antd": "catalog:",
"dayjs": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"react-router-dom": "catalog:",
"zustand": "catalog:"
},
"devDependencies": {
"@types/node": "catalog:",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@uj/eslint-config": "workspace:*",
"@uj/typescript-config": "workspace:*",
"@uj/vite-config": "workspace:*",
"axios": "catalog:",
"eslint": "catalog:",
"typescript": "catalog:",
"vite": "catalog:"
},
"uj": {
"route": "store",
"entry": "http://localhost:5175/"
}
}
import { useEffect, useState } from 'react';
import { Empty } from 'antd';
import { busEvents } from '@uj/contracts';
import { SubAppProvider, readInitialPage, shortName, subappBus } from '@uj/platform-sdk';
import TemplateImport from './pages/TemplateImport';
import StoreApprove from './pages/StoreApprove';
import StoreListing from './pages/StoreListing';
/**
* 页名 -> 页面组件。页名来自后端菜单 route 的末段:
* /store/import -> import
* /store/approval -> approval
* /store/listing -> listing
*/
const PAGES = {
import: TemplateImport,
approval: StoreApprove,
listing: StoreListing,
} as const;
function renderPage(page: string) {
const Page = PAGES[page as keyof typeof PAGES];
return Page ? (
<Page />
) : (
<Empty description={`没有名为「${page}」的页面`} image={Empty.PRESENTED_IMAGE_SIMPLE} />
);
}
function StoreApp() {
const [page, setPage] = useState<string>(readInitialPage);
useEffect(() => {
const bus = subappBus();
if (!bus) return;
const events = busEvents(shortName());
const onNavigate = (...args: unknown[]) => setPage(String(args[0] ?? ''));
const onLogout = () => setPage('');
bus.$on(events.navigate, onNavigate);
bus.$on(events.logout, onLogout);
bus.$emit(events.ready);
return () => {
bus.$off(events.navigate, onNavigate);
bus.$off(events.logout, onLogout);
};
}, []);
return renderPage(page);
}
export function App() {
return (
<SubAppProvider>
<div className="uj-scope uj-store-app">{StoreApp()}</div>
</SubAppProvider>
);
}
/** 业务模块的 `../core/client` 桥接:继承目标换成 props.request 代理。 */
export { RemoteApiClient as ApiClient } from '@uj/platform-sdk';
export type { BlobResponse } from '@uj/platform-sdk';
// 后端统一响应包装(规范 §五:code === 200 视为成功,否则拦截器抛错)
export interface ApiResult<T> {
code: number;
message: string;
data: T;
}
// 分页结果(门店列表 / 审批列表等)
export interface PageResult<T> {
list: T[];
total: number;
pageNum: number;
pageSize: number;
}
/** 门店域的 `@/api` 出口。store.ts 已 export * from './storeTypes'。 */
export * from './modules/store';
export * from './modules/storeTypes';
export * from './core/types';
// 门店上架业务接口,路径与 DTO 对齐后端 OpenAPI。
import { ApiClient } from '../core/client';
import { downloadStoreExport } from './storeDownload';
import type {
ApprovalPageParams,
ApprovalRow,
ApproveTab,
ListingPageParams,
StoreChangeLog,
StoreColumnConfig,
StoreGoodsCategory,
StoreGoodsCategoryQuery,
StoreId,
StoreListingDetail,
StoreListingRow,
StorePage,
StoreScene,
StoreSceneQuery,
} from './storeTypes';
export * from './storeTypes';
// ---------- 门店导入(PRD §5.1 四步:下载→校验→确认→提交审批) ----------
/** 模板下载(免签,浏览器直链 / 网关暴露,§4.3) */
export const STORE_IMPORT_TEMPLATE_URL = '/store/import/template';
export interface ImportSubmitPayload {
taskId: string;
storeName: string;
businessScene: string;
[key: string]: unknown;
}
/** 校验失败明细行 */
export interface StoreImportFailVO {
rowIndex?: number;
storeName: string;
merchantNo: string;
productCategory: string;
/** 校验层级编码:L3-单元格级 L4-业务级 L5-重复上架级 */
levelCode: string;
/** 校验层级文案:如「L4 业务级」 */
levelLabel: string;
/** 失败原因 */
reason: string;
}
/** 导入行(产品分类明细) */
export interface StoreImportRowDTO {
/** 门店名称(营业执照全称) */
storeName: string;
merchantNo: string;
/** 业务场景(展示用 label,落库为 baseSceneCode) */
businessScene: string;
/** 业务场景编码(D+ baseSceneCode,如 110102) */
businessSceneCode: string;
/** 产品分类(系统字典标准名,可多级以「-」分隔) */
productCategory: string;
/** 产品分类 ID(D+ dj_car_life_goods_category_configuration.category_type) */
productCategoryId: number;
/** 产品分类层级(D+ dj_car_life_goods_category_configuration.level,1 起) */
productCategoryLevel: number;
marketFee1CalcMode: string;
marketFee1CalcWay: string;
marketFee1Value: number;
/** 数值单位:RATIO-比例 AMOUNT-金额(由计算方式推导) */
marketFee1Unit: string;
marketFee2CalcMode: string;
marketFee2CalcWay: string;
marketFee2Value: number;
marketFee2Unit: string;
/** 一线阳光是否开启线上积分:1-是 0-否 */
sunshine1OnlinePoint: number;
sunshine1CalcMode: string;
sunshine1CalcWay: string;
sunshine1Value: number;
sunshine1Unit: string;
sunshine2OnlinePoint: number;
sunshine2CalcMode: string;
sunshine2CalcWay: string;
sunshine2Value: number;
sunshine2Unit: string;
/** 装修、设备总投入 */
costDecoration: number;
/** 当月产生(房租、水电、耗材等) */
costMonthly: number;
/** 人工成本 */
costLabor: number;
}
/** POST /store/import/check 响应 data */
export interface StoreImportCheckVO {
templateVersion: string;
/** 解析总行数 */
totalRows: number;
/** 校验通过行数 */
passRows: number;
/** 校验失败行数 */
failRows: number;
storeName: string;
merchantNo: string;
/** 所属组织(完整层级路径 label,例如「优加主体 / 线上运营部」) */
orgPath: string;
/** 业务场景(多个以「/」分隔,label,例如「售后会员权益升级 / 售前延保」) */
businessScene: string;
/** 产品分类(去重后的 label,多个以「/」分隔,例如「太阳膜-原厂/车衣-原厂/精品-小桌板」) */
productCategories: string;
/** 校验失败明细 */
failures: StoreImportFailVO[];
/** 导入行(产品分类明细) */
previewRows: StoreImportRowDTO[];
/** 导入失败明细文件下载地址(全部成功时为 null) */
failFileUrl: string | null;
/** 下一个待审批角色名称,如「优加商务经理」 */
nextRoleName: string;
/** 去重后的产品分类数,例如 6(2 个业务场景 × 6 个分类 → 6) */
distinctProductCategoryCount: number;
/** 去重后的业务场景数,例如 2 */
distinctBusinessSceneCount: number;
/** 产品分类总行数,例如 12 */
productCategoryRowCount: number;
/** 本次落库 / 提交的上架记录 ID(按业务场景拆分,一条 = 一个场景) */
listingIds: number[];
/** 是否已落库(导入成功为 true;仅校验失败为 false) */
submitted: boolean;
/** 导入文件名(校验结果展示用,可选) */
fileName?: string;
/** 导入文件大小(字节,可选) */
fileSize?: number;
/** L1 格式 / 模板版本校验是否通过(false 表示格式不正确或模板版本不一致) */
failL1Passed?: boolean;
/** L2 列结构校验是否通过(false 表示存在缺失列或多余列) */
failL2Passed?: boolean;
}
/** POST /store/import/check 请求参数(FormData) */
export interface StoreImportCheckParams {
file: File;
/** 备注(可选,≤ 200 字) */
remark?: string;
}
/** POST /store/import/submit 请求体:把草稿记录提交为待审批(不重新解析文件) */
export interface StoreImportCommitDTO {
/** 导入返回的上架记录 ID 列表(同一门店的多个业务场景) */
listingIds: number[];
}
const APPROVAL_PATHS: Record<ApproveTab, string> = {
todo: '/store/approval/pending',
done: '/store/approval/done',
mine: '/store/approval/mine',
};
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 = {}) {
return this.get<StorePage<StoreListingRow>>(
'/store/listing/page',
params as Record<string, unknown>,
);
}
/** 下载门店上架导入模板(V1.0.1,21 列,输出 .xlsx 文件) */
async downloadImportTemplate(
defaultFilename = '【优加】门店上架模版-V1.0.1.xlsx',
): Promise<void> {
const { blob, headers } = await this.getBlob(STORE_IMPORT_TEMPLATE_URL);
// 防御:如果后端网关 / 鉴权拦截返回 JSON(比如 code!=200 的错误),blob 的 type 会是 application/json。
if (/application\/json/i.test(blob.type) || blob.size < 200) {
try {
const text = await blob.text();
const err = JSON.parse(text);
throw Object.assign(new Error(err?.message ?? '模板下载失败:返回不是文件流'), {
code: err?.code,
data: err?.data,
});
} catch (e) {
if (e instanceof Error && /^模板下载失败/.test(e.message)) throw e;
throw new Error('模板下载失败:响应不是 .xlsx 文件流');
}
}
const disposition = (headers['content-disposition'] ?? '') as string;
let filename = defaultFilename;
if (disposition) {
const matched = disposition.match(/filename\*=UTF-8''([^;]+)/i);
const simple = disposition.match(/filename="?([^";]+)"?/i);
filename = decodeURIComponent(matched?.[1] ?? simple?.[1] ?? defaultFilename);
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
/** 上传模板文件做五级校验 + 落库草稿(失败时返回失败明细文件 URL,不落库) */
uploadImport(params: StoreImportCheckParams) {
const form = new FormData();
form.append('file', params.file);
if (params.remark !== undefined && params.remark !== null) {
form.append('remark', String(params.remark));
}
return this.post<StoreImportCheckVO>('/store/import/check', form);
}
/** 提交:把草稿记录提交为待审批(不重新解析文件,响应 data 类型同 check) */
submitImport(payload: StoreImportCommitDTO) {
return this.post<StoreImportCheckVO>('/store/import/submit', payload);
}
listApprovals(tab: ApproveTab = 'todo', params: ApprovalPageParams = {}) {
return this.get<StorePage<ApprovalRow>>(APPROVAL_PATHS[tab], params as Record<string, unknown>);
}
getApproval(id: StoreId) {
return this.get<StoreListingDetail>(`/store/approval/${encodeURIComponent(id)}`);
}
passApproval(id: StoreId, reason?: string) {
return this.post<void>('/store/approval/pass', { listingId: id, reason });
}
rejectApproval(id: StoreId, reason: string) {
return this.post<void>('/store/approval/reject', { listingId: id, reason });
}
batchPassApproval(ids: StoreId[]): Promise<void> {
if (ids.length === 0) return Promise.reject(new Error('请先选择待审批记录'));
return this.post<void>('/store/approval/batch-pass', { listingIds: ids });
}
revokeApproval(id: StoreId) {
return this.post<void>(`/store/approval/${encodeURIComponent(id)}/revoke`);
}
getStore(id: StoreId) {
return this.get<StoreListingDetail>(`/store/listing/${encodeURIComponent(id)}`);
}
getChanges(id: StoreId) {
return this.get<StoreChangeLog[]>(`/store/listing/${encodeURIComponent(id)}/changes`);
}
exportStores(params: ListingPageParams = {}): Promise<void> {
return downloadStoreExport(this.http, params);
}
getColumnConfig() {
return this.get<StoreColumnConfig>('/store/listing/column-config');
}
saveColumnConfig(columns: string[]) {
return this.post<void>('/store/listing/column-config', { columns });
}
approve(id: StoreId, action: 'pass' | 'reject', comment?: string) {
return action === 'pass'
? this.passApproval(id, comment)
: this.rejectApproval(id, comment ?? '');
}
}
export const store = new Store();
import type { AxiosInstance } from 'axios';
import type { ListingPageParams } from './storeTypes';
const DEFAULT_FILENAME = '门店列表.xlsx';
function exportFilename(disposition: string) {
const encoded = /filename\*\s*=\s*(?:"([^"]*)"|([^;]*))/i.exec(disposition);
const plain = /(?:^|;)\s*filename\s*=\s*(?:"([^"]*)"|([^;]*))/i.exec(disposition);
let filename = plain?.[1] ?? plain?.[2]?.trim() ?? DEFAULT_FILENAME;
if (encoded) {
try {
const value = (encoded[1] ?? encoded[2]).trim().replace(/^[^']*'[^']*'/, '');
filename = decodeURIComponent(value);
} catch {
// 不合法的 filename* 回退到普通文件名。
}
}
// 文件名清洗必须覆盖 C0 控制字符(NUL / 换行等),否则响应头里的恶意值会破坏本地文件名。
// eslint-disable-next-line no-control-regex -- 有意匹配 U+0000~U+001F,不是误写
return filename.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').trim() || DEFAULT_FILENAME;
}
function invalidDownload(payload: unknown): Error {
let body = payload;
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch {
body = null;
}
}
if (body && typeof body === 'object' && 'message' in body && typeof body.message === 'string') {
return Object.assign(new Error(body.message), {
code: 'code' in body ? body.code : undefined,
data: 'data' in body ? body.data : undefined,
});
}
return new Error('导出响应不是可下载的文件');
}
/** 复用鉴权/签名拦截器,同时保留文件响应和 JSON 业务错误的不同处理。 */
export async function downloadStoreExport(http: AxiosInstance, params: ListingPageParams) {
let filename = DEFAULT_FILENAME;
let mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
const response: unknown = await http.request({
method: 'GET',
url: '/store/listing/export',
params,
responseType: 'arraybuffer',
transformResponse: [
(raw: ArrayBuffer | string, headers) => {
filename = exportFilename(String(headers['content-disposition'] ?? ''));
mime = String(headers['content-type'] ?? mime);
// http 的 JSON 错误拦截需要原始文本,不能把 ArrayBuffer stringify 成 {}。
return /\bjson\b/i.test(mime) && typeof raw !== 'string'
? new TextDecoder().decode(raw)
: raw;
},
],
});
// 非 JSON 响应由共享拦截器包装为 { data, headers },先取出文件内容。
const payload =
response && typeof response === 'object' && 'headers' in response && 'data' in response
? response.data
: response;
if (!(payload instanceof ArrayBuffer)) throw invalidDownload(payload);
const blob = new Blob([payload], { type: mime });
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = filename;
link.hidden = true;
document.body.appendChild(link);
try {
link.click();
} finally {
link.remove();
// 让浏览器先消费下载链接,再释放其内存。
setTimeout(() => URL.revokeObjectURL(objectUrl), 0);
}
}
/** 门店上架接口原始契约;ID 和金额字符串不做 Number 转换。 */
export type StoreId = number | string;
export type StoreDecimal = number | string | null;
export type ApproveTab = 'todo' | 'done' | 'mine';
export interface StorePage<T> {
records: T[];
total: number;
current: number;
size: 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 {
current?: number;
size?: number;
keyword?: string;
productCategory?: string;
businessScene?: string;
submitUserName?: string;
}
export interface ListingPageParams {
current?: number;
size?: number;
storeName?: string;
merchantNo?: string;
businessScene?: string;
startDate?: string;
endDate?: string;
sortField?: 'effectiveDate' | 'changeCount';
sortOrder?: 'asc' | 'desc';
}
export interface ApprovalRow {
listingId: StoreId;
storeName: string;
merchantNo: string;
productCategories?: string[] | null;
categoryCount?: number | null;
businessScene: string;
costTotal?: StoreDecimal;
currentLevel?: number | null;
totalLevel?: number | null;
submitUserName?: string | null;
submitTime?: string | null;
pendingHours?: number | null;
timeoutLevel?: 'NORMAL' | 'WARNING' | 'DANGER' | string | null;
status?: string | null;
statusLabel?: string | null;
rejectReason?: string | null;
myAction?: 'PASS' | 'REJECT' | string | null;
myActionLabel?: string | null;
handleTime?: string | null;
handleOpinion?: string | null;
actionable?: boolean | null;
}
export type ApproveRow = ApprovalRow;
export interface StoreListingRow {
listingId: StoreId;
storeName: string;
merchantNo: string;
businessScene: string;
effectiveTime?: string | null;
changeCount?: number | null;
costTotal?: StoreDecimal;
}
interface StoreAuditFields {
createBy?: StoreId | null;
createTime?: string | null;
updateBy?: StoreId | null;
updateTime?: string | null;
}
export interface StoreListingItem extends StoreAuditFields {
itemId?: StoreId;
listingId?: StoreId;
productCategory?: string | null;
marketFee1CalcMode?: string | null;
marketFee1CalcWay?: string | null;
marketFee1Value?: StoreDecimal;
marketFee1Unit?: string | null;
marketFee2CalcMode?: string | null;
marketFee2CalcWay?: string | null;
marketFee2Value?: StoreDecimal;
marketFee2Unit?: string | null;
sunshine1OnlinePoint?: number | null;
sunshine1CalcMode?: string | null;
sunshine1CalcWay?: string | null;
sunshine1Value?: StoreDecimal;
sunshine1Unit?: string | null;
sunshine2OnlinePoint?: number | null;
sunshine2CalcMode?: string | null;
sunshine2CalcWay?: string | null;
sunshine2Value?: StoreDecimal;
sunshine2Unit?: string | null;
}
export interface StoreApprovalLog extends StoreAuditFields {
logId?: StoreId;
listingId?: StoreId;
action?: string | null;
operatorId?: StoreId | null;
operatorName?: string | null;
operatorRole?: string | null;
preStatus?: string | null;
postStatus?: string | null;
reason?: string | null;
operateTime?: string | null;
operateIp?: string | null;
}
export interface StoreChangeLog extends StoreAuditFields {
changeId?: StoreId;
listingId?: StoreId;
versionNo?: number | null;
changeField?: string | null;
beforeValue?: string | null;
afterValue?: string | null;
changeUserId?: StoreId | null;
changeUserName?: string | null;
effectiveTime?: string | null;
}
/** listingId 对应单个门店、单个业务场景,成本合计以 costTotal 为准。 */
export interface StoreListingDetail {
listingId: StoreId;
storeName: string;
merchantNo: string;
businessScene: string;
categoryCount?: number | null;
status?: string | null;
statusLabel?: string | null;
currentLevel?: number | null;
totalLevel?: number | null;
levelRoleCode?: string | null;
effectiveTime?: string | null;
submitTime?: string | null;
submitUserName?: string | null;
approveTime?: string | null;
approveUserName?: string | null;
rejectReason?: string | null;
costDecoration?: StoreDecimal;
costMonthly?: StoreDecimal;
costLabor?: StoreDecimal;
costTotal?: StoreDecimal;
items?: StoreListingItem[] | null;
changeHistory?: StoreChangeLog[] | null;
approvalLogs?: StoreApprovalLog[] | null;
}
export interface DictOption {
value: string;
label: string;
extra?: string | null;
}
export interface StoreColumnConfig {
columns?: string[] | null;
}
import type { TableColumnsType } from 'antd';
import { UTable } from '@uj/ui';
import type { StoreListingDetail, StoreListingItem } from '@/api';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatMoney, formatPolicyValue } from './formatters';
import './approvalPolicy.css';
interface PanelProps {
detail: StoreListingDetail;
spec?: StoreDictionaries;
}
type PolicyPrefix = 'marketFee1' | 'marketFee2' | 'sunshine1' | 'sunshine2';
type PolicyRow = StoreListingItem & { displayKey: string };
function categoryCount(detail: StoreListingDetail): number | undefined {
if (
typeof detail.categoryCount === 'number' &&
Number.isSafeInteger(detail.categoryCount) &&
detail.categoryCount >= 0
) {
return detail.categoryCount;
}
if (!detail.items) return undefined;
return new Set(detail.items.map((item) => item.productCategory?.trim()).filter(Boolean)).size;
}
export function ApprovalPolicyPanel({
detail,
spec,
kind,
}: PanelProps & { kind: 'market' | 'sunshine' }) {
const market = kind === 'market';
const name = market ? '管理层市场费' : '一线阳光激励';
const prefixes: PolicyPrefix[] = market
? ['marketFee1', 'marketFee2']
: ['sunshine1', 'sunshine2'];
const columns: TableColumnsType<PolicyRow> = [
{
title: '产品分类',
key: 'category',
width: market ? 120 : 110,
fixed: 'left',
render: (_, item) => (
<span className="approval-policy-panel__category">
{dictionaryLabel(spec?.productCategories, item.productCategory)}
</span>
),
},
...prefixes.flatMap((prefix, index): TableColumnsType<PolicyRow> => [
...(prefix === 'sunshine1' || prefix === 'sunshine2'
? [
{
title: '开启线上积分',
key: `${prefix}OnlinePoint`,
width: 100,
render: (_: unknown, item: PolicyRow) =>
dictionaryLabel(spec?.onlinePointFlags, item[`${prefix}OnlinePoint`]),
},
]
: []),
{
title: `${market ? '市场费' : '激励'}${index + 1}计算模式`,
key: `${prefix}CalcMode`,
width: market ? 110 : 100,
render: (_, item) => dictionaryLabel(spec?.calcModes, item[`${prefix}CalcMode`]),
},
{
title: '计算方式',
key: `${prefix}CalcWay`,
width: market ? 90 : 80,
render: (_, item) => dictionaryLabel(spec?.calcWays, item[`${prefix}CalcWay`]),
},
{
title: `${market ? '市场费' : '激励费'}${index + 1}`,
key: `${prefix}Value`,
width: 80,
align: 'right',
render: (_, item) => (
<span className="approval-policy-panel__value">
{formatPolicyValue(item[`${prefix}Value`], item[`${prefix}Unit`] ?? undefined)}
</span>
),
},
]),
];
const rows = (detail.items || []).map((item, index) => ({
...item,
displayKey: `${item.itemId ?? 'item'}-${index}`,
}));
const count = categoryCount(detail);
return (
<section className="approval-policy-panel" aria-label={`${name}政策`}>
<div className="approval-policy-panel__table">
<UTable<PolicyRow>
rowKey="displayKey"
size="small"
pagination={false}
columns={columns}
dataSource={rows}
scroll={{ x: 'max-content' }}
/>
</div>
<p className="approval-policy-panel__note">
本页签展示本审批记录({detail.storeName || '—'} ·{' '}
{dictionaryLabel(spec?.businessScenes, detail.businessScene)})下
{count === undefined ? '的产品分类' : ` ${count} 个产品分类`}的{name}
政策,仅展示,不参与逐项勾选。
</p>
{!market && (
<p className="approval-policy-panel__note">
「开启线上积分」按记录中的是否值展示,激励费按各项政策的计算方式与单位展示。
</p>
)}
</section>
);
}
interface CostRow {
key: string;
name: string;
value: string;
description: string;
total?: boolean;
}
export function ApprovalCostPanel({ detail, spec }: PanelProps) {
// The heading supplies the currency unit. All digits still come from the shared formatter.
const amount = (value: StoreListingDetail['costTotal']) => formatMoney(value).replace(/^¥/, '');
const rows: CostRow[] = [
{
key: 'decoration',
name: '装修、设备总投入',
value: amount(detail.costDecoration),
description: '门店装修与设备投入',
},
{
key: 'monthly',
name: '当月产生(房租、水电、耗材等)',
value: amount(detail.costMonthly),
description: '门店当月房租、水电、耗材等费用',
},
{
key: 'labor',
name: '人工成本',
value: amount(detail.costLabor),
description: '门店人工成本',
},
{
key: 'total',
name: '运营成本合计',
value: amount(detail.costTotal),
description: '门店维度的运营成本合计',
total: true,
},
{
key: 'categories',
name: '本场景产品分类行数',
value: String(categoryCount(detail) ?? '—'),
description: dictionaryLabel(spec?.businessScenes, detail.businessScene),
},
];
const columns: TableColumnsType<CostRow> = [
{
title: '项目',
dataIndex: 'name',
key: 'name',
width: 240,
render: (value: string) => <span className="approval-cost-panel__name">{value}</span>,
},
{
title: '金额(元)',
dataIndex: 'value',
key: 'value',
width: 130,
align: 'right',
render: (value: string, row) =>
row.total ? <strong className="approval-cost-panel__total">{value}</strong> : value,
},
{
title: '说明',
dataIndex: 'description',
key: 'description',
className: 'approval-cost-panel__description',
},
];
return (
<section className="approval-policy-panel approval-cost-panel" aria-label="运营成本明细">
<div className="approval-policy-panel__table">
<UTable<CostRow>
rowKey="key"
size="small"
pagination={false}
columns={columns}
dataSource={rows}
scroll={{ x: 'max-content' }}
/>
</div>
<p className="approval-policy-panel__note">
运营成本为门店维度,不随产品分类数或业务场景数重复累计。
</p>
</section>
);
}
import type { StoreChangeLog } from '@/api';
import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatMoney } from './formatters';
import './listingHistory.css';
const EMPTY = '—';
const FIELD_LABELS: Record<string, string> = {
storeName: '门店名称',
merchantNo: '门店商户号',
status: '上架状态',
businessScene: '业务场景',
productCategory: '产品分类',
productCategories: '产品分类',
categoryCount: '产品分类数',
costDecoration: '装修、设备总投入',
costMonthly: '当月产生费用',
costLabor: '人工成本',
costTotal: '运营成本合计',
};
const COST_FIELDS = new Set(['costDecoration', 'costMonthly', 'costLabor', 'costTotal']);
const COST_LABELS = new Set([
'运营成本',
'装修、设备总投入',
'当月产生费用',
'人工成本',
'运营成本合计',
]);
const POLICY_LABELS: Record<string, string> = {
marketFee1: '管理层市场费 1',
marketFee2: '管理层市场费 2',
sunshine1: '一线阳光激励费 1',
sunshine2: '一线阳光激励费 2',
};
const POLICY_SUFFIX_LABELS: Record<string, string> = {
CalcMode: '计算模式',
CalcWay: '计算方式',
Value: '数值',
Unit: '单位',
OnlinePoint: '开启线上积分',
};
interface HistoryGroup {
key: string;
version?: number;
changes: StoreChangeLog[];
effectiveTime?: string;
}
function policyField(field: string) {
return field.match(/^(marketFee[12]|sunshine[12])(CalcMode|CalcWay|Value|Unit|OnlinePoint)$/);
}
function fieldLabel(field: string): string {
if (Object.hasOwn(FIELD_LABELS, field)) return FIELD_LABELS[field];
const policy = policyField(field);
if (policy) return `${POLICY_LABELS[policy[1]]} ${POLICY_SUFFIX_LABELS[policy[2]]}`;
return field || '变更字段未提供';
}
function changeCategory(field: string): string {
if (COST_FIELDS.has(field) || COST_LABELS.has(field)) return '运营成本';
if (policyField(field) || /市场费|阳光激励|激励计算|激励政策/.test(field)) return '激励政策';
if (field === 'businessScene' || field === '业务场景') return '业务场景';
if (
['productCategory', 'productCategories', 'categoryCount', '产品分类', '产品分类数'].includes(
field,
)
) {
return '产品分类';
}
return fieldLabel(field);
}
function isFirstListing(group: HistoryGroup): boolean {
return (
group.version === 1 &&
group.changes.some(
(change) =>
change.changeField === 'status' &&
change.afterValue === 'APPROVED' &&
change.beforeValue !== 'APPROVED',
)
);
}
function groupTitle(group: HistoryGroup): string {
if (isFirstListing(group)) return '首次上架';
const categories = [
...new Set(group.changes.map((change) => changeCategory(change.changeField || ''))),
];
if (
categories.length === 2 &&
categories.includes('激励政策') &&
categories.includes('运营成本')
) {
return '激励政策与运营成本调整';
}
if (
categories.length === 2 &&
categories.includes('业务场景') &&
categories.includes('产品分类')
) {
return '业务场景与产品分类调整';
}
if (categories.every((category) => category === '变更字段未提供')) return '门店信息变更';
return `${categories.join('与')}调整`;
}
function dateText(value?: string, includeTime = false): string {
const match = value?.trim().match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}))?/);
if (!match) return EMPTY;
return includeTime && match[2] ? `${match[1]} ${match[2]}` : match[1];
}
function groupHistory(history: StoreChangeLog[]): HistoryGroup[] {
const groups: HistoryGroup[] = [];
const versions = new Map<number, HistoryGroup>();
history.forEach((change, index) => {
const version =
typeof change.versionNo === 'number' &&
Number.isSafeInteger(change.versionNo) &&
change.versionNo > 0
? change.versionNo
: undefined;
let group = version === undefined ? undefined : versions.get(version);
if (!group) {
group = {
key: version === undefined ? `unknown-${index}` : `version-${version}`,
version,
changes: [],
};
groups.push(group);
if (version !== undefined) versions.set(version, group);
}
group.changes.push(change);
const effectiveTime = change.effectiveTime?.trim();
if (
effectiveTime &&
dateText(effectiveTime) !== EMPTY &&
(!group.effectiveTime ||
effectiveTime.replace('T', ' ') > group.effectiveTime.replace('T', ' '))
) {
group.effectiveTime = effectiveTime;
}
});
return groups.sort((a, b) => {
if (a.version !== undefined && b.version !== undefined) return a.version > b.version ? -1 : 1;
if (a.version !== undefined) return -1;
if (b.version !== undefined) return 1;
return (b.effectiveTime || '').localeCompare(a.effectiveTime || '');
});
}
function categoryValue(value: string, spec?: StoreDictionaries): string {
// Multi-category audit values may be serialized arrays; preserve other API text verbatim.
if (value.trim().startsWith('[')) {
try {
const categories: unknown = JSON.parse(value);
if (
Array.isArray(categories) &&
categories.every((category) => typeof category === 'string')
) {
return categories.length
? categories
.map((category) => dictionaryLabel(spec?.productCategories, category))
.join(' / ')
: EMPTY;
}
} catch {
return value;
}
}
return dictionaryLabel(spec?.productCategories, value);
}
function changeValue(field: string, value: unknown, spec?: StoreDictionaries): string {
if (value === null || value === undefined || String(value).trim() === '') return EMPTY;
const text = String(value);
if (COST_FIELDS.has(field)) {
const formatted = formatMoney(value);
return formatted === EMPTY ? text : formatted;
}
if (field === 'status') {
return Object.hasOwn(STORE_STATUS, text) ? STORE_STATUS[text as StoreStatus].label : text;
}
if (field === 'businessScene') return dictionaryLabel(spec?.businessScenes, text);
if (field === 'productCategory' || field === 'productCategories')
return categoryValue(text, spec);
const policy = policyField(field);
if (policy?.[2] === 'CalcMode') return dictionaryLabel(spec?.calcModes, text);
if (policy?.[2] === 'CalcWay') return dictionaryLabel(spec?.calcWays, text);
if (policy?.[2] === 'OnlinePoint') return dictionaryLabel(spec?.onlinePointFlags, text);
if (policy?.[2] === 'Unit') return text === 'AMOUNT' ? '金额' : text === 'RATIO' ? '比例' : text;
// Policy values carry no unit in the audit DTO; do not infer money or percentages.
return text;
}
export function ListingChangeHistory({
history,
spec,
}: {
history: StoreChangeLog[] | null | undefined;
spec?: StoreDictionaries;
}) {
const groups = groupHistory(history || []);
return (
<section className="listing-change-history" aria-label="变更历史(只读)">
<h3 className="listing-change-history__heading">变更历史(只读)</h3>
{groups.length ? (
groups.map((group) => {
const versionLabel = group.version === undefined ? '版本未提供' : `v${group.version}`;
const users = [
...new Set(
group.changes.map((change) => change.changeUserName?.trim()).filter(Boolean),
),
];
return (
<article
key={group.key}
className="listing-change-history__version"
aria-label={group.version === undefined ? versionLabel : `版本 ${versionLabel}`}
>
<div className="listing-change-history__version-meta">
<strong>{versionLabel}</strong>
<span>{dateText(group.effectiveTime)}</span>
</div>
<div className="listing-change-history__content">
<h4>{groupTitle(group)}</h4>
{isFirstListing(group) && (
<p className="listing-change-history__description">
门店在系统中完成首次上架并生效。
</p>
)}
<dl className="listing-change-history__changes">
{group.changes.map((change, index) => {
const field = change.changeField?.trim() || '';
return (
<div key={`${change.changeId ?? 'change'}-${index}`}>
<dt>{fieldLabel(field)}</dt>
<dd>
{changeValue(field, change.beforeValue, spec)} →{' '}
{changeValue(field, change.afterValue, spec)}
</dd>
</div>
);
})}
</dl>
<p className="listing-change-history__audit">
变更人:{users.join('、') || EMPTY} · 生效时间{' '}
{dateText(group.effectiveTime, true)}
</p>
</div>
</article>
);
})
) : (
<p className="listing-change-history__empty">暂无变更历史</p>
)}
</section>
);
}
import type { StoreListingDetail } from '@/api';
import { formatMoney } from './formatters';
import './listingCost.css';
export function ListingCostPanel({ detail }: { detail: StoreListingDetail }) {
return (
<section className="listing-cost-panel" aria-label="运营成本(门店维度)">
<h3 className="listing-cost-panel__title">运营成本(门店维度)</h3>
<dl className="listing-cost-panel__fields">
<div>
<dt>装修、设备总投入</dt>
<dd>
<span className="listing-cost-panel__amount">{formatMoney(detail.costDecoration)}</span>
</dd>
</div>
<div>
<dt>当月产生费用</dt>
<dd>
<span className="listing-cost-panel__amount">{formatMoney(detail.costMonthly)}</span>
<span className="listing-cost-panel__hint">房租、水电、耗材等</span>
</dd>
</div>
<div>
<dt>人工成本</dt>
<dd>
<span className="listing-cost-panel__amount">{formatMoney(detail.costLabor)}</span>
<span className="listing-cost-panel__hint">按人力成本维度合并填写</span>
</dd>
</div>
<div>
<dt>运营成本合计</dt>
<dd>
<strong className="listing-cost-panel__amount">{formatMoney(detail.costTotal)}</strong>
</dd>
</div>
</dl>
<p className="listing-cost-panel__note">
运营成本为门店维度字段,同一门店的各业务场景记录需保持一致,系统在上传时校验一致性。
</p>
</section>
);
}
import { CloseOutlined } from '@ant-design/icons';
import { UButton } from '@uj/ui';
import type { StoreListingDetail } from '@/api';
import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel } from './formatters';
import './listingDetail.css';
const EMPTY = '—';
function categoryCount(detail: StoreListingDetail): string {
if (
typeof detail.categoryCount === 'number' &&
Number.isSafeInteger(detail.categoryCount) &&
detail.categoryCount >= 0
) {
return `${detail.categoryCount} 个`;
}
if (!detail.items) return EMPTY;
const categories = detail.items
.map((item) => item.productCategory?.trim())
.filter((category): category is string => !!category);
return `${new Set(categories).size} 个`;
}
function currentVersion(detail: StoreListingDetail): string {
const versions = (detail.changeHistory || [])
.map((change) => change.versionNo)
.filter(
(version): version is number =>
typeof version === 'number' && Number.isSafeInteger(version) && version > 0,
);
return versions.length
? `v${versions.reduce((latest, version) => Math.max(latest, version))}`
: EMPTY;
}
/** Format the API's calendar fields as text, preserving its original time zone. */
function effectiveDate(detail: StoreListingDetail, includeTime = false): string {
const value = detail.effectiveTime?.trim() || detail.approveTime?.trim();
const match = value?.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}))?/);
if (!match) return EMPTY;
return includeTime && match[2] ? `${match[1]} ${match[2]}` : match[1];
}
function ListingStatus({ detail }: { detail: StoreListingDetail }) {
const knownStatus = Object.hasOwn(STORE_STATUS, detail.status || '')
? STORE_STATUS[detail.status as StoreStatus]
: undefined;
const tone =
detail.status === 'APPROVED'
? 'approved'
: detail.status === 'PENDING'
? 'pending'
: detail.status === 'REJECTED'
? 'rejected'
: 'neutral';
return (
<span className={`listing-detail-status listing-detail-status--${tone}`}>
<span className="listing-detail-status__dot" aria-hidden="true" />
{detail.statusLabel?.trim() || knownStatus?.label || EMPTY}
</span>
);
}
export function ListingDetailHeader({
detail,
spec,
onClose,
}: {
detail: StoreListingDetail;
spec?: StoreDictionaries;
onClose: () => void;
}) {
return (
<section className="listing-detail-header" aria-label="门店概览">
<div className="listing-detail-header__top">
<h2>{detail.storeName?.trim() || EMPTY}</h2>
<div className="listing-detail-header__actions">
<ListingStatus detail={detail} />
<UButton
type="text"
className="listing-detail-header__close"
aria-label="关闭"
icon={<CloseOutlined />}
onClick={onClose}
/>
</div>
</div>
<dl className="listing-detail-meta">
<div>
<dt>商户号</dt>
<dd>{detail.merchantNo?.trim() || EMPTY}</dd>
</div>
<div>
<dt>业务场景</dt>
<dd>{dictionaryLabel(spec?.businessScenes, detail.businessScene?.trim())}</dd>
</div>
<div>
<dt>产品分类</dt>
<dd>{categoryCount(detail)}</dd>
</div>
<div>
<dt>上架时间</dt>
<dd>{effectiveDate(detail)}</dd>
</div>
<div>
<dt>当前版本</dt>
<dd>{currentVersion(detail)}</dd>
</div>
</dl>
</section>
);
}
export function ListingStoreInfo({
detail,
spec,
}: {
detail: StoreListingDetail;
spec?: StoreDictionaries;
}) {
const scene = detail.businessScene?.trim();
return (
<section className="listing-store-info" aria-label="门店信息">
<h3 className="listing-store-info__title">门店信息</h3>
<dl className="listing-store-info__fields">
<div>
<dt>门店名称</dt>
<dd>{detail.storeName?.trim() || EMPTY}</dd>
</div>
<div>
<dt>门店商户号</dt>
<dd>{detail.merchantNo?.trim() || EMPTY}</dd>
</div>
<div>
<dt>业务场景</dt>
<dd>
{scene ? (
<span className="listing-store-info__scene">
{dictionaryLabel(spec?.businessScenes, scene)}
</span>
) : (
EMPTY
)}
<span className="listing-store-info__hint">
同一门店的每个业务场景均覆盖全部产品分类
</span>
</dd>
</div>
<div>
<dt>产品分类数</dt>
<dd>
<span>{categoryCount(detail)}</span>
<span className="listing-store-info__hint">完整清单见「产品与场景」页签</span>
</dd>
</div>
<div>
<dt>上架状态</dt>
<dd>
<ListingStatus detail={detail} />
</dd>
</div>
<div>
<dt>生效时间</dt>
<dd>{effectiveDate(detail, true)}</dd>
</div>
</dl>
</section>
);
}
import type { ReactNode } from 'react';
import type { TableColumnsType } from 'antd';
import { Skeleton, UAlert, UButton, UDrawer, UResult, UTable, UTabs, UTag, UText } from '@uj/ui';
import type { StoreListingDetail, StoreListingItem } from '@/api';
import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatPolicyValue } from './formatters';
import { ListingDetailHeader, ListingStoreInfo } from './ListingDetailOverview';
import { ListingChangeHistory } from './ListingChangeHistory';
import { ListingCostPanel } from './ListingCostPanel';
import { ApprovalPolicyPanel, ApprovalCostPanel } from './ApprovalPolicyPanels';
import {
ApprovalDetailHeader,
ApprovalStages,
ApprovalAuditTrail,
} from './ApprovalDetailPresentation';
export interface StoreDetailDrawerProps {
open: boolean;
detail?: StoreListingDetail;
spec?: StoreDictionaries;
loading?: boolean;
error?: unknown;
mode: 'approval' | 'listing';
initialTab?: string;
pendingHours?: number | null;
onClose: () => void;
onRetry?: () => void;
footer?: ReactNode;
}
type PolicyPrefix = 'marketFee1' | 'marketFee2' | 'sunshine1' | 'sunshine2';
function DetailContent({
detail,
spec,
mode,
initialTab,
open,
pendingHours,
}: Pick<StoreDetailDrawerProps, 'spec' | 'mode' | 'initialTab' | 'open' | 'pendingHours'> & {
detail: StoreListingDetail;
}) {
const items = (detail.items || []).map((item, index) => ({
...item,
displayKey: String(item.itemId ?? index),
}));
const scene = dictionaryLabel(spec?.businessScenes, detail.businessScene);
const categoryColumn: TableColumnsType<StoreListingItem>[number] = {
title: '产品分类',
key: 'category',
width: 150,
fixed: 'left',
render: (_, item) => (
<UTag>{dictionaryLabel(spec?.productCategories, item.productCategory)}</UTag>
),
};
const policyTable = (columns: TableColumnsType<StoreListingItem>) => (
<UTable<StoreListingItem>
rowKey="displayKey"
size="small"
pagination={false}
columns={columns}
dataSource={items}
scroll={{ x: 'max-content' }}
/>
);
const compactPolicy = (item: StoreListingItem, prefix: PolicyPrefix) => (
<div>
{dictionaryLabel(spec?.calcModes, item[`${prefix}CalcMode`])} /{' '}
{dictionaryLabel(spec?.calcWays, item[`${prefix}CalcWay`])} /{' '}
{formatPolicyValue(item[`${prefix}Value`], item[`${prefix}Unit`] ?? undefined)}
{(prefix === 'sunshine1' || prefix === 'sunshine2') && (
<div>
<UText type="secondary">
开启线上积分:{dictionaryLabel(spec?.onlinePointFlags, item[`${prefix}OnlinePoint`])}
</UText>
</div>
)}
</div>
);
const approvalTabs = [
{
key: 'market',
label: (
<span>
管理层市场费{' '}
<span className="approval-detail-tab-count" aria-hidden="true">
{detail.categoryCount ?? items.length}
</span>
</span>
),
children: <ApprovalPolicyPanel detail={detail} spec={spec} kind="market" />,
},
{
key: 'sunshine',
label: '一线阳光激励',
children: <ApprovalPolicyPanel detail={detail} spec={spec} kind="sunshine" />,
},
{
key: 'costs',
label: '运营成本',
children: <ApprovalCostPanel detail={detail} spec={spec} />,
},
{
key: 'logs',
label: '审批留痕',
children: <ApprovalAuditTrail detail={detail} spec={spec} pendingHours={pendingHours} />,
},
];
const listingTabs = [
{
key: 'info',
label: '门店信息',
children: <ListingStoreInfo detail={detail} spec={spec} />,
},
{
key: 'products',
label: '产品与场景',
children: policyTable([
categoryColumn,
{ title: '业务场景', key: 'scene', width: 200, render: () => scene },
{
title: '阳光激励 1 计算模式',
key: 'mode1',
width: 160,
render: (_, item) => dictionaryLabel(spec?.calcModes, item.sunshine1CalcMode),
},
{
title: '阳光激励 2 计算模式',
key: 'mode2',
width: 160,
render: (_, item) => dictionaryLabel(spec?.calcModes, item.sunshine2CalcMode),
},
]),
},
{
key: 'policies',
label: '市场与激励',
children: policyTable([
categoryColumn,
...(['marketFee1', 'marketFee2', 'sunshine1', 'sunshine2'] as const).map(
(prefix, index) => ({
title: ['管理层市场费 1', '管理层市场费 2', '一线阳光激励费 1', '一线阳光激励费 2'][
index
],
key: prefix,
width: 240,
render: (_: unknown, item: StoreListingItem) => compactPolicy(item, prefix),
}),
),
]),
},
{ key: 'costs', label: '运营成本', children: <ListingCostPanel detail={detail} /> },
{
key: 'history',
label: '变更历史',
children: <ListingChangeHistory history={detail.changeHistory} spec={spec} />,
},
];
const tabs = mode === 'approval' ? approvalTabs : listingTabs;
const selectedTab = tabs.some((tab) => tab.key === initialTab) ? initialTab : tabs[0].key;
return (
<>
{mode === 'approval' && <ApprovalStages detail={detail} />}
{detail.rejectReason && (
<UAlert
type="warning"
title="打回原因"
description={detail.rejectReason}
style={{ marginBottom: 16 }}
/>
)}
<UTabs
key={`${detail.listingId}:${mode}:${initialTab}:${open}`}
defaultActiveKey={selectedTab}
items={tabs}
/>
</>
);
}
export function StoreDetailDrawer({
open,
detail,
spec,
loading,
error,
mode,
initialTab,
pendingHours,
onClose,
onRetry,
footer,
}: StoreDetailDrawerProps) {
const showCustomHeader = !!detail && !loading && !error;
return (
<UDrawer
open={open}
onClose={onClose}
title={
showCustomHeader ? (
mode === 'listing' ? (
<ListingDetailHeader detail={detail!} spec={spec} onClose={onClose} />
) : (
<ApprovalDetailHeader detail={detail!} spec={spec} onClose={onClose} />
)
) : mode === 'approval' ? (
'门店审批详情'
) : (
'门店详情'
)
}
closable={showCustomHeader ? false : undefined}
rootClassName={mode === 'listing' ? 'store-listing-detail' : 'store-approval-detail'}
styles={
mode === 'listing'
? { header: { padding: '16px 20px 20px' }, body: { padding: 20 } }
: { header: { padding: '18px 22px' }, body: { padding: '20px 22px' } }
}
footer={footer}
>
{loading ? (
<Skeleton variant="detail" />
) : error ? (
<UResult
status="error"
title="详情加载失败"
subTitle={error instanceof Error ? error.message : '请稍后重试'}
extra={onRetry && <UButton onClick={onRetry}>重试</UButton>}
/>
) : detail ? (
<DetailContent
open={open}
detail={detail}
spec={spec}
mode={mode}
initialTab={initialTab}
pendingHours={pendingHours}
/>
) : (
<UResult status="info" title="暂无门店详情" />
)}
</UDrawer>
);
}
.approval-detail-header {
color: #202733;
font-weight: 400;
}
.approval-detail-header__top,
.approval-detail-header__identity {
display: flex;
align-items: flex-start;
gap: 12px;
}
.approval-detail-header__top {
justify-content: space-between;
}
.approval-detail-header__identity {
min-width: 0;
align-items: baseline;
}
.approval-detail-header__identity h2 {
min-width: 0;
margin: 0;
color: #151b24;
font-size: 20px;
font-weight: 600;
line-height: 32px;
overflow-wrap: anywhere;
}
.approval-detail-header__close.ant-btn {
flex: none;
width: 32px;
min-width: 32px;
height: 32px;
padding: 0;
border-radius: 7px;
background: #eef1f6;
color: #596579;
font-size: 18px;
}
.approval-detail-header__close.ant-btn:hover {
background: #e2e7f0;
color: #202733;
}
.approval-detail-status {
display: inline-flex;
flex: none;
align-items: center;
gap: 6px;
padding: 2px 9px;
border-radius: 6px;
font-size: 14px;
font-weight: 400;
line-height: 23px;
white-space: nowrap;
}
.approval-detail-status__dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.approval-detail-status--pending {
background: #fff6e5;
color: #a86808;
}
.approval-detail-status--approved {
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
}
.approval-detail-status--rejected {
background: #fff0ee;
color: #c43c3c;
}
.approval-detail-status--neutral {
background: #f0f2f5;
color: #758195;
}
.approval-detail-meta {
display: flex;
flex-wrap: wrap;
gap: 10px 18px;
margin: 12px 0 0;
font-size: 14px;
line-height: 24px;
}
.approval-detail-meta > div {
display: flex;
align-items: baseline;
gap: 5px;
min-width: 0;
}
.approval-detail-meta dt {
flex: none;
color: #758195;
}
.approval-detail-meta dd {
min-width: 0;
margin: 0;
font-weight: 600;
overflow-wrap: anywhere;
}
.approval-detail-meta__time {
color: #758195;
font-weight: 400;
}
.approval-detail-flow {
margin-bottom: 20px;
}
.approval-detail-flow__heading {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
.approval-detail-flow__heading h3 {
margin: 0;
color: #28313f;
font-size: 14px;
font-weight: 600;
line-height: 24px;
}
.approval-detail-flow__heading > span {
padding: 1px 8px;
border-radius: 4px;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 13px;
line-height: 22px;
}
.approval-detail-flow__nodes {
display: flex;
margin: 0;
padding: 6px 0 14px;
overflow-x: auto;
list-style: none;
}
.approval-detail-flow__node {
position: relative;
display: flex;
flex: 1 0 120px;
flex-direction: column;
align-items: center;
padding: 0 5px;
text-align: center;
}
.approval-detail-flow__node:not(:last-child)::after {
position: absolute;
top: 14px;
right: calc(-50% + 24px);
left: calc(50% + 24px);
height: 2px;
background: #e2e6ed;
content: '';
}
.approval-detail-flow__node--done:not(:last-child)::after {
background: var(--uj-primary, #2b5ce6);
}
.approval-detail-flow__icon {
position: relative;
z-index: 1;
display: grid;
place-items: center;
width: 30px;
height: 30px;
margin-bottom: 10px;
border: 1.5px solid #cbd3df;
border-radius: 50%;
background: #fff;
color: #758195;
font-size: 15px;
font-weight: 600;
}
.approval-detail-flow__node--done .approval-detail-flow__icon,
.approval-detail-chaincard__icon--done {
border-color: var(--uj-primary, #2b5ce6);
background: var(--uj-primary, #2b5ce6);
color: #fff;
}
.approval-detail-flow__node--current .approval-detail-flow__icon,
.approval-detail-chaincard__icon--current {
border-color: #315efb;
background: #315efb;
color: #fff;
}
.approval-detail-flow__node--current .approval-detail-flow__icon {
box-shadow: 0 0 0 4px #e0e8ff;
}
.approval-detail-flow__node--rejected .approval-detail-flow__icon,
.approval-detail-chaincard__icon--rejected {
border-color: #d64a49;
background: #d64a49;
color: #fff;
}
.approval-detail-flow__node > strong {
color: #465164;
font-size: 14px;
font-weight: 500;
line-height: 22px;
}
.approval-detail-flow__node--current > strong {
color: #315efb;
font-weight: 600;
}
.approval-detail-flow__node--rejected > strong {
color: #c43c3c;
}
.approval-detail-flow__caption,
.approval-detail-flow__time {
max-width: 100%;
color: #97a3b7;
font-size: 12px;
line-height: 18px;
overflow-wrap: anywhere;
}
.approval-detail-flow__caption {
margin-top: 3px;
}
.store-approval-detail .ant-tabs > .ant-tabs-nav {
margin-bottom: 20px;
}
.store-approval-detail .ant-tabs > .ant-tabs-nav::before {
border-bottom-color: #e2e6ed;
}
.store-approval-detail .ant-tabs-tab {
padding: 12px 16px;
color: #758195;
font-size: 16px;
line-height: 24px;
}
.store-approval-detail .ant-tabs-tab + .ant-tabs-tab {
margin-left: 4px;
}
.store-approval-detail .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: #315efb;
font-weight: 600;
}
.store-approval-detail .ant-tabs-ink-bar {
background: #315efb;
}
.approval-detail-tab-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
margin-left: 6px;
padding: 0 5px;
border-radius: 10px;
background: #eef1f6;
color: #596579;
font-size: 12px;
font-weight: 400;
}
.approval-detail-audit {
display: flex;
flex-direction: column;
gap: 12px;
}
.approval-detail-chaincard {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px 16px;
border: 1px solid #e0e6ef;
border-radius: 8px;
background: #fff;
}
.approval-detail-chaincard__icon {
display: grid;
flex: 0 0 30px;
place-items: center;
width: 30px;
height: 30px;
margin-top: 3px;
border-radius: 50%;
font-size: 15px;
font-weight: 600;
}
.approval-detail-chaincard__icon--waiting,
.approval-detail-chaincard__icon--stopped {
background: #eef1f6;
color: #758195;
}
.approval-detail-chaincard__content {
flex: 1;
min-width: 0;
overflow-wrap: anywhere;
}
.approval-detail-chaincard__title {
color: #28313f;
font-size: 14px;
font-weight: 500;
line-height: 24px;
}
.approval-detail-chaincard__title strong {
font-weight: inherit;
}
.approval-detail-chaincard__meta {
display: flex;
flex-wrap: wrap;
gap: 0 8px;
margin-top: 2px;
color: #758195;
font-size: 13px;
line-height: 22px;
}
.approval-detail-chaincard__meta > span + span::before {
margin-right: 8px;
content: '·';
}
.approval-detail-chaincard__reason {
margin: 6px 0 0;
color: #596579;
font-size: 13px;
line-height: 22px;
white-space: pre-wrap;
}
.approval-detail-audit__empty {
margin: 0;
color: #97a3b7;
font-size: 13px;
}
@media (max-width: 600px) {
.approval-detail-header__identity {
flex-wrap: wrap;
gap: 6px 10px;
}
.approval-detail-header__identity h2 {
font-size: 18px;
line-height: 28px;
}
.approval-detail-meta {
gap: 6px 14px;
}
.approval-detail-flow__node {
flex-basis: 110px;
}
.store-approval-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.approval-detail-chaincard {
gap: 10px;
padding: 12px;
}
}
.approval-policy-panel {
min-width: 0;
}
.approval-policy-panel__table {
overflow: hidden;
border: 1px solid #e0e6ef;
border-radius: 8px;
background: #fff;
}
.approval-policy-panel .ant-table {
color: #465164;
font-size: 13px;
}
.approval-policy-panel .ant-table-thead > tr > th {
height: 38px;
padding: 9px 12px;
border-bottom-color: #e0e6ef;
background: #fafbfc;
color: #758195;
font-size: 12px;
font-weight: 500;
line-height: 20px;
white-space: nowrap;
}
.approval-policy-panel .ant-table-tbody > tr > td {
height: 44px;
padding: 8px 12px;
border-bottom-color: #eef1f6;
font-variant-numeric: tabular-nums;
line-height: 22px;
}
.approval-policy-panel .ant-table-tbody > tr:last-child > td {
border-bottom: 0;
}
.approval-policy-panel .ant-table-tbody > tr.ant-table-row:hover > td {
background: #fafbfc;
}
.approval-policy-panel__category {
display: inline-block;
max-width: 280px;
padding: 1px 7px;
border-radius: 4px;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 12px;
font-weight: 500;
line-height: 20px;
overflow-wrap: anywhere;
}
.approval-policy-panel__value {
color: #465164;
font-variant-numeric: tabular-nums;
}
.approval-policy-panel__note {
margin: 10px 0 0;
color: #97a3b7;
font-size: 12px;
line-height: 20px;
overflow-wrap: anywhere;
}
.approval-cost-panel__name {
color: #28313f;
font-weight: 500;
}
.approval-cost-panel__total {
color: #28313f;
font-weight: 600;
}
.approval-cost-panel .ant-table-tbody .approval-cost-panel__description {
color: #97a3b7;
}
@media (max-width: 600px) {
.approval-policy-panel .ant-table-thead > tr > th,
.approval-policy-panel .ant-table-tbody > tr > td {
padding-right: 10px;
padding-left: 10px;
}
}
import type { DictOption } from '@/api';
export interface StoreDictionaries {
businessScenes: DictOption[];
productCategories: DictOption[];
calcModes: DictOption[];
calcWays: DictOption[];
onlinePointFlags: DictOption[];
}
const textOptions = (values: string[]): DictOption[] =>
values.map((value) => ({ value, label: value }));
/**
* 详情展示所用的本地映射和计算规则字典;未知业务名称原样回显。
* 来源:2026-10-09 导入模板的计算/是否取值、模板示例及已返回的门店记录。
* 场景/分类目录仅含历史示例,不用于筛选;筛选选项由分类查询接口提供。
*/
export const STORE_DICTIONARIES: StoreDictionaries = {
businessScenes: textOptions(['售后众筹', '精品升级', '售后会员权益升级', '售前延保']),
productCategories: textOptions([
'车辆美容',
'车辆美容-车辆美容2级',
'车辆美容-车辆美容2级-车辆美容3级(集采)',
'工时费',
'其他(众筹)',
'改色膜(原厂)',
'精品(集采)',
'记录仪',
'电子烟(集采)',
'太阳膜()',
'太阳膜-原厂',
'车衣-原厂',
'精品-小桌板',
'精品-脚垫',
'踏板',
'车衣-副厂',
]),
calcModes: textOptions(['按品类计算', '按整单计算']),
calcWays: textOptions([
'收入',
'毛利',
'固定',
'固定*购买金额',
'园区店总金额',
'园区店毛利(不扣除产品成本)',
'园区店毛利',
'收入-其他费用',
'收入-自定义其他费用',
]),
onlinePointFlags: [
{ value: '1', label: '是' },
{ value: '0', label: '否' },
],
};
import type { DictOption } from '@/api';
const EMPTY = '—';
/** Display only: move decimal digits as text, never round or recalculate API amounts. */
function decimalParts(
value: unknown,
): { sign: string; integer: string; fraction: string } | undefined {
if (typeof value !== 'string' && typeof value !== 'number') return;
let text = String(value).trim();
if (text.includes(',')) {
if (!/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?$/.test(text)) return;
text = text.replaceAll(',', '');
}
const match = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i.exec(text);
if (!match) return;
let [integer, fraction = ''] = match[2].split('.');
let exponent = BigInt(match[3] || '0');
// Prevent unbounded exponent expansion; ordinary and large fixed-point strings retain all digits.
if (exponent > 10000n || exponent < -10000n) return;
while (exponent > 0n) {
integer += fraction[0] || '0';
fraction = fraction.slice(1);
exponent -= 1n;
}
while (exponent < 0n) {
fraction = (integer.slice(-1) || '0') + fraction;
integer = integer.slice(0, -1);
exponent += 1n;
}
integer = integer.replace(/^0+(?=\d)/, '') || '0';
const sign = match[1] === '-' && /[1-9]/.test(integer + fraction) ? '-' : '';
return { sign, integer, fraction };
}
export function formatMoney(value: unknown): string {
const parts = decimalParts(value);
if (!parts) return EMPTY;
const integer = parts.integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return `¥${parts.sign}${integer}.${parts.fraction.padEnd(2, '0')}`;
}
export function formatPolicyValue(value: unknown, unit?: string): string {
if (unit === 'AMOUNT') return formatMoney(value);
const parts = decimalParts(value);
if (!parts) return EMPTY;
const decimal = `${parts.sign}${parts.integer}${parts.fraction ? `.${parts.fraction}` : ''}`;
return unit === 'RATIO' ? `${decimal}%` : decimal;
}
export function formatDateTime(value?: string | null): string {
return value?.trim().replace('T', ' ') || EMPTY;
}
export function dictionaryLabel(options: DictOption[] | undefined, value: unknown): string {
if (value === null || value === undefined || value === '') return EMPTY;
const key = String(value);
return options?.find((option) => String(option.value) === key)?.label || key;
}
.listing-cost-panel {
color: #28313f;
font-size: 14px;
line-height: 22px;
}
.listing-cost-panel__title {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
padding-bottom: 12px;
border-bottom: 1px solid #e9edf3;
font-size: 14px;
font-weight: 600;
line-height: 22px;
}
.listing-cost-panel__title::before {
flex: none;
width: 3px;
height: 14px;
border-radius: 2px;
background: #315efb;
content: '';
}
.listing-cost-panel__fields {
margin: 10px 0 0;
}
.listing-cost-panel__fields > div {
display: grid;
grid-template-columns: 144px minmax(0, 1fr);
align-items: start;
min-height: 36px;
padding: 6px 0;
}
.listing-cost-panel__fields dt {
padding-right: 12px;
color: #758195;
}
.listing-cost-panel__fields dd {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 14px;
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.listing-cost-panel__amount {
font-variant-numeric: tabular-nums;
}
strong.listing-cost-panel__amount {
font-weight: 600;
}
.listing-cost-panel__hint,
.listing-cost-panel__note {
color: #97a3b7;
font-size: 13px;
}
.listing-cost-panel__note {
margin: 22px 0 0;
line-height: 22px;
}
@media (max-width: 600px) {
.listing-cost-panel__fields > div {
grid-template-columns: 132px minmax(0, 1fr);
}
}
.listing-detail-header {
color: #202733;
font-weight: 400;
}
.listing-detail-header__top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
}
.listing-detail-header__top h2 {
min-width: 0;
margin: 0;
color: #151b24;
font-size: 20px;
font-weight: 600;
line-height: 32px;
overflow-wrap: anywhere;
}
.listing-detail-header__actions {
display: flex;
flex: none;
align-items: center;
gap: 10px;
}
.listing-detail-header__close.ant-btn {
width: 32px;
min-width: 32px;
height: 32px;
padding: 0;
border-radius: 7px;
background: #eef1f6;
color: #596579;
font-size: 18px;
}
.listing-detail-header__close.ant-btn:hover {
background: #e2e7f0;
color: #202733;
}
.listing-detail-meta {
display: flex;
flex-wrap: wrap;
gap: 8px 20px;
margin: 12px 0 0;
font-size: 14px;
font-weight: 400;
line-height: 22px;
}
.listing-detail-meta > div {
display: flex;
align-items: baseline;
gap: 5px;
min-width: 0;
}
.listing-detail-meta dt {
flex: none;
color: #758195;
}
.listing-detail-meta dd {
margin: 0;
font-weight: 600;
overflow-wrap: anywhere;
}
.listing-detail-status {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 25px;
padding: 2px 9px;
border-radius: 6px;
font-size: 14px;
font-weight: 400;
line-height: 21px;
white-space: nowrap;
}
.listing-detail-status__dot {
flex: none;
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
.listing-detail-status--approved {
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
}
.listing-detail-status--pending {
background: #fff8e2;
color: #ad7c00;
}
.listing-detail-status--rejected {
background: #fff0ee;
color: #c43c3c;
}
.listing-detail-status--neutral {
background: #f0f2f5;
color: #758195;
}
.store-listing-detail .ant-tabs > .ant-tabs-nav {
margin-bottom: 22px;
}
.store-listing-detail .ant-tabs > .ant-tabs-nav::before {
border-bottom-color: #e2e6ed;
}
.store-listing-detail .ant-tabs-tab {
padding: 12px 18px;
color: #758195;
font-size: 16px;
line-height: 24px;
}
.store-listing-detail .ant-tabs-tab + .ant-tabs-tab {
margin-left: 4px;
}
.store-listing-detail .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: #315efb;
font-weight: 600;
}
.store-listing-detail .ant-tabs-ink-bar {
background: #315efb;
}
.listing-store-info {
color: #28313f;
font-size: 14px;
line-height: 22px;
}
.listing-store-info__title {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
padding-bottom: 12px;
border-bottom: 1px solid #e9edf3;
font-size: 14px;
font-weight: 600;
line-height: 22px;
}
.listing-store-info__title::before {
flex: none;
width: 3px;
height: 14px;
border-radius: 2px;
background: #315efb;
content: '';
}
.listing-store-info__fields {
margin: 10px 0 0;
}
.listing-store-info__fields > div {
display: grid;
grid-template-columns: 144px minmax(0, 1fr);
align-items: start;
min-height: 36px;
padding: 6px 0;
}
.listing-store-info__fields dt {
color: #758195;
}
.listing-store-info__fields dd {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 9px;
min-width: 0;
margin: 0;
overflow-wrap: anywhere;
}
.listing-store-info__scene {
display: inline-block;
max-width: 100%;
padding: 1px 8px;
border-radius: 4px;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 13px;
line-height: 22px;
}
.listing-store-info__hint {
color: #97a3b7;
font-size: 13px;
}
@media (max-width: 600px) {
.listing-detail-header__top {
gap: 10px;
}
.listing-detail-header__top h2 {
font-size: 18px;
line-height: 28px;
}
.listing-detail-header__actions {
gap: 6px;
}
.listing-detail-meta {
gap: 6px 14px;
}
.store-listing-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.listing-store-info__fields > div {
grid-template-columns: 110px minmax(0, 1fr);
}
}
.listing-change-history {
color: #28313f;
font-size: 14px;
line-height: 24px;
}
.listing-change-history__heading {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
padding-bottom: 12px;
border-bottom: 1px solid #e9edf3;
font-size: 14px;
font-weight: 600;
line-height: 22px;
}
.listing-change-history__heading::before {
flex: none;
width: 3px;
height: 14px;
border-radius: 2px;
background: #315efb;
content: '';
}
.listing-change-history__version {
display: grid;
grid-template-columns: 110px minmax(0, 1fr);
gap: 12px;
padding: 16px 0;
border-bottom: 1px solid #e9edf3;
}
.listing-change-history__version:first-of-type {
padding-top: 24px;
}
.listing-change-history__version-meta {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
min-width: 0;
overflow-wrap: anywhere;
}
.listing-change-history__version-meta strong {
color: #315efb;
font-size: 13px;
font-weight: 600;
}
.listing-change-history__version-meta span,
.listing-change-history__audit,
.listing-change-history__empty {
color: #97a3b7;
font-size: 13px;
}
.listing-change-history__content {
min-width: 0;
overflow-wrap: anywhere;
}
.listing-change-history__content h4 {
margin: 0 0 8px;
color: #28313f;
font-size: 14px;
font-weight: 400;
line-height: 24px;
}
.listing-change-history__description {
margin: 0 0 4px;
color: #596579;
}
.listing-change-history__changes {
margin: 0;
color: #596579;
}
.listing-change-history__changes > div {
display: flex;
flex-wrap: wrap;
align-items: baseline;
column-gap: 12px;
margin-top: 2px;
}
.listing-change-history__changes dt {
max-width: 100%;
}
.listing-change-history__changes dd {
min-width: 0;
margin: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.listing-change-history__audit {
margin: 8px 0 0;
}
.listing-change-history__empty {
margin: 16px 0;
}
@media (max-width: 600px) {
.listing-change-history__version {
grid-template-columns: 80px minmax(0, 1fr);
gap: 10px;
}
}
.store-page {
display: flex;
flex-direction: column;
gap: 16px;
min-width: 0;
min-height: 100%;
}
.store-page-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
}
.store-page-header h3,
.store-page-header h4 {
margin: 0 0 6px;
}
.store-page-header .ant-typography-secondary {
font-size: 13px;
line-height: 1.8;
}
.store-filter-card {
border: 1px solid var(--uj-border);
box-shadow: var(--uj-shadow-card);
}
.store-search-form {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px 20px;
}
.store-search-form > :last-child {
grid-column: 1 / -1;
justify-self: end;
margin-bottom: 0;
}
.store-search-form > :last-child button + button {
margin-left: 8px;
}
.store-table-card {
min-width: 0;
border: 1px solid var(--uj-border);
border-radius: 10px;
background: var(--uj-surface);
overflow: hidden;
box-shadow: var(--uj-shadow-card);
}
.store-code {
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
font-size: 12px;
}
.store-subtext {
display: block;
color: var(--uj-text-3);
font-size: 12px;
margin-top: 3px;
}
.store-row-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.store-confirm-records {
max-height: 320px;
overflow: auto;
margin: 16px 0;
border: 1px solid var(--uj-border);
border-radius: 8px;
}
.store-confirm-record {
padding: 12px 16px;
border-bottom: 1px solid var(--uj-divider);
}
.store-confirm-record:last-child {
border-bottom: 0;
}
@media (max-width: 1100px) {
.store-search-form {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 640px) {
.store-search-form {
grid-template-columns: minmax(0, 1fr);
}
.store-page-header {
flex-direction: column;
}
}
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();
},
};
}
/* 子应用内样式只在 shadowRoot 内生效。
业务 CSS(features/store 与各页面目录下的 .css)由各页面自行 import,
它们的裸类名不会穿透到主壳 —— 这正是 wujie 相对联邦省下的样式边界工作。
注意:注释里不要写 glob 路径,星号紧跟斜杠的写法会提前终止 CSS 注释。 */
.uj-store-app {
min-height: 100%;
width: 100%;
color: var(--uj-color-text-primary);
}
import { StrictMode } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { App } from './App';
import '@uj/design-tokens/tokens.css';
import './index.css';
let root: Root | null = null;
function render(): void {
const el = document.getElementById('root');
if (!el) throw new Error('Root container #root not found');
root?.unmount();
root = createRoot(el);
root.render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
);
}
if (window.__POWERED_BY_WUJIE__) {
window.__WUJIE_MOUNT = () => render();
window.__WUJIE_UNMOUNT = () => {
root?.unmount();
root = null;
};
} else {
render();
}
.store-approve-table-card {
/* 保留表格自然高度,由页面内容区滚动,避免 flex 收缩后裁掉底部行和分页。 */
flex-shrink: 0;
}
.store-approve-table.ant-table-wrapper .ant-table .ant-table-thead > tr > th {
height: 38px;
padding: 0 12px;
background: #fbfcfd;
color: #6b7686;
font-size: 12px;
font-weight: 500;
white-space: nowrap;
}
.store-approve-table.ant-table-wrapper .ant-table .ant-table-tbody > tr > td {
height: 44px;
padding: 8px 12px;
color: #333c4a;
font-size: 13px;
line-height: 20px;
vertical-align: middle;
white-space: nowrap;
}
.store-approve-table .ant-table-tbody .ant-btn-link {
height: 28px;
padding: 0 8px;
font-size: 13px;
}
.store-approve-merchant {
color: #2b5ce6;
font-family: 'JetBrains Mono', 'SFMono-Regular', Consolas, monospace;
font-size: 12px;
}
.store-approve-categories {
display: inline-flex;
align-items: center;
gap: 4px;
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 {
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 7px;
border-radius: 4px;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 11px;
font-weight: 500;
white-space: nowrap;
}
.store-approve-category-count {
color: #333c4a;
font-size: 13px;
}
.store-approve-money {
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.store-approve-submit-time {
display: block;
color: #9aa5b5;
font-size: 12px;
white-space: nowrap;
}
.store-approve-stay {
display: inline-flex;
align-items: center;
gap: 5px;
height: 22px;
padding: 0 8px;
border-radius: 5px;
font-size: 11.5px;
font-weight: 500;
white-space: nowrap;
}
.store-approve-stay::before {
width: 5px;
height: 5px;
flex: 0 0 5px;
border-radius: 50%;
background: currentColor;
content: '';
}
.store-approve-stay--normal {
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
}
.store-approve-stay--warning {
background: #fdf4e3;
color: #9a5f08;
}
.store-approve-stay--danger {
background: #fdecec;
color: #a3262c;
}
import { UAlert, UButton, UCheckbox, UForm, UFormItem, UInput, UModal, UTag } from '@uj/ui';
import type { ApprovalRow } from '@/api';
import type { StoreDictionaries } from '@/features/store/dictionaries';
import { dictionaryLabel, formatMoney } from '@/features/store/formatters';
import { rejectReasons } from '../tools/consts';
export type ApprovalActionType = 'pass' | 'reject' | 'batch' | 'revoke';
export interface ApprovalAction {
type: ApprovalActionType;
records: ApprovalRow[];
}
const titles: Record<ApprovalActionType, string> = {
pass: '确认通过',
reject: '打回审批',
batch: '批量审批确认',
revoke: '确认撤回',
};
const buttons: Record<ApprovalActionType, string> = {
pass: '确认通过',
reject: '确认打回',
batch: '确认批量通过',
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 {
action?: ApprovalAction;
spec?: StoreDictionaries;
pending: boolean;
confirmed: boolean;
reason: string;
error?: string;
onConfirmed: (value: boolean) => void;
onReason: (value: string) => void;
onCancel: () => void;
onConfirm: () => void;
}
export function ApprovalActionModal({
action,
spec,
pending,
confirmed,
reason,
error,
onConfirmed,
onReason,
onCancel,
onConfirm,
}: Props) {
const type = action?.type ?? 'pass';
const needsConfirmation = type === 'pass' || type === 'batch';
return (
<UModal
open={!!action}
title={titles[type]}
width={600}
okText={buttons[type]}
cancelText="取消"
onCancel={onCancel}
onOk={onConfirm}
confirmLoading={pending}
closable={!pending}
maskClosable={!pending}
keyboard={!pending}
cancelButtonProps={{ disabled: pending }}
okButtonProps={{
disabled: needsConfirmation && !confirmed,
danger: type === 'reject' || type === 'revoke',
}}
>
{type === 'pass' || type === 'batch' ? (
<UAlert
type="info"
showIcon
title="审批范围为门店+业务场景下的全部产品分类"
description={approvalResultMessage(action?.records ?? [])}
/>
) : type === 'revoke' ? (
<UAlert type="warning" showIcon title="撤回后记录将退出当前审批流程。" />
) : null}
<div className="store-confirm-records">
{action?.records.map((row) => (
<div className="store-confirm-record" key={row.listingId}>
<strong>{row.storeName}</strong>
<span className="store-subtext">商户号:{row.merchantNo}</span>
<div style={{ marginTop: 8 }}>
<UTag color="blue">{dictionaryLabel(spec?.businessScenes, row.businessScene)}</UTag>
<span>{row.categoryCount ?? row.productCategories?.length ?? 0} 个产品分类</span>
</div>
{needsConfirmation && (
<>
<div style={{ marginTop: 8 }}>运营成本合计:{formatMoney(row.costTotal)}</div>
<span className="store-subtext">
{row.productCategories
?.map((category) => dictionaryLabel(spec?.productCategories, category))
.join('、')}
</span>
</>
)}
</div>
))}
</div>
{type === 'reject' && (
<UForm layout="vertical">
<UFormItem label="打回原因" required>
<UInput.TextArea
aria-label="打回原因"
value={reason}
onChange={(event) => onReason(event.target.value)}
maxLength={200}
showCount
rows={4}
placeholder="请填写打回原因(最多 200 字)"
disabled={pending}
/>
</UFormItem>
<div className="store-row-actions">
{rejectReasons.map((value) => (
<UButton
key={value}
type="default"
size="small"
disabled={pending}
onClick={() => onReason(value)}
>
{value}
</UButton>
))}
</div>
</UForm>
)}
{needsConfirmation && (
<UCheckbox
checked={confirmed}
disabled={pending}
onChange={(event) => onConfirmed(event.target.checked)}
>
我已核对以上记录和数据,确认通过当前审批节点
</UCheckbox>
)}
{error && <UAlert style={{ marginTop: 12 }} type="error" showIcon title={error} />}
</UModal>
);
}
import type { DataTableColumnsType } from '@/components/DataTable';
import { UTag, UTooltip } from '@uj/ui';
import { StatusTag } from '@/components/StatusTag';
import type { ApprovalRow, ApproveTab } from '@/api';
import type { StoreDictionaries } from '@/features/store/dictionaries';
import { dictionaryLabel, formatDateTime, formatMoney } from '@/features/store/formatters';
import '../approveTable.css';
function formatSubmitTime(value?: string | null): string {
const text = formatDateTime(value);
const match =
/^\d{4}-(\d{2}-\d{2}) (\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(text);
return match ? `${match[1]} ${match[2]}` : text;
}
export function buildApproveColumns(
tab: ApproveTab,
spec?: StoreDictionaries,
): DataTableColumnsType<ApprovalRow> {
const columns: DataTableColumnsType<ApprovalRow> = [
{
title: '门店名称',
dataIndex: 'storeName',
width: tab === 'mine' ? 230 : 220,
fixed: 'left',
render: (value) => <strong>{value}</strong>,
},
{
title: '门店商户号',
dataIndex: 'merchantNo',
width: tab === 'mine' ? 120 : 110,
render: (value) => <span className="store-approve-merchant">{value || '—'}</span>,
},
{
title: '产品分类',
key: 'categories',
width: tab === 'todo' ? 170 : 200,
render: (_, row) => {
const categories = row.productCategories ?? [];
const count = row.categoryCount ?? categories.length;
const categoryNames = categories
.filter((category) => category.trim())
.map((category) => dictionaryLabel(spec?.productCategories, category));
return (
<UTooltip
trigger={['hover', 'focus']}
title={
categoryNames.length ? (
<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>}
</span>
</UTooltip>
);
},
},
{
title: '业务场景',
dataIndex: 'businessScene',
width: tab === 'todo' ? 200 : tab === 'done' ? 150 : 160,
render: (value) => (
<span className="store-approve-tag">{dictionaryLabel(spec?.businessScenes, value)}</span>
),
},
];
if (tab === 'todo')
columns.push(
{
title: '运营成本合计',
dataIndex: 'costTotal',
width: 110,
align: 'right',
render: (value) => (
<span className="store-approve-money">
{formatMoney(value).replace(/^¥/, '').replace(/\.00$/, '')}
</span>
),
},
{
title: '提交人 / 时间',
width: 150,
render: (_, row) => (
<>
{row.submitUserName || '—'}
<span className="store-approve-submit-time">{formatSubmitTime(row.submitTime)}</span>
</>
),
},
{
title: '停留时长',
width: 86,
render: (_, row) => {
const hours = row.pendingHours;
if (typeof hours !== 'number' || !Number.isFinite(hours) || hours < 0) return '—';
const level =
row.timeoutLevel ?? (hours > 48 ? 'DANGER' : hours > 24 ? 'WARNING' : 'NORMAL');
const tone =
level === 'DANGER'
? 'danger'
: level === 'WARNING'
? 'warning'
: level === 'NORMAL'
? 'normal'
: 'unknown';
return (
<span className={`store-approve-stay store-approve-stay--${tone}`}>{hours} 小时</span>
);
},
},
);
if (tab === 'done')
columns.push(
{
title: '我的动作',
width: 110,
render: (_, row) => (
<UTag
color={row.myAction === 'PASS' ? 'blue' : row.myAction === 'REJECT' ? 'red' : undefined}
>
{row.myActionLabel ||
({ PASS: '通过', REJECT: '打回' }[row.myAction ?? ''] ?? row.myAction ?? '—')}
</UTag>
),
},
{ title: '处理时间', dataIndex: 'handleTime', width: 150, render: formatDateTime },
{
title: '处理意见',
key: 'handleOpinion',
width: 220,
line: 2,
render: (_, row) => row.handleOpinion || row.rejectReason || '—',
},
{ title: '记录状态', width: 100, render: (_, row) => <StatusTag status={row.status} /> },
);
if (tab === 'mine')
columns.push(
{ title: '状态', width: 130, render: (_, row) => <StatusTag status={row.status} /> },
{
title: '审批进度',
width: 150,
render: (_, row) =>
row.status === 'PENDING'
? (row.totalLevel ?? 2) === 1 || row.currentLevel === 2
? '待优加财务经理审批'
: '待优加商务经理审批'
: row.status === 'REJECTED'
? '退回发起人'
: row.status === 'REVOKED'
? '发起人已撤回'
: row.status === 'APPROVED'
? '已完成'
: '—',
},
{ title: '提交时间', dataIndex: 'submitTime', width: 170, render: formatDateTime },
);
return columns;
}
import type { ApproveTab } from '@/api';
export const tabDefs: { key: ApproveTab; label: string }[] = [
{ key: 'todo', label: '待我审批' },
{ key: 'done', label: '我已办' },
{ key: 'mine', label: '我发起的' },
];
export const rejectReasons = ['数据有误', '政策不合理', '缺少附件', '其他'];
export function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : '操作失败,请稍后重试';
}
import { useEffect, useState } from 'react';
import { UAlert, UButton, UCheckbox, UModal, UText } from '@uj/ui';
import { COLUMN_LABELS, DEFAULT_COLUMNS, errorText, type ListingColumn } from '../tools/listing';
interface Props {
open: boolean;
columns: ListingColumn[];
loading: boolean;
error: unknown;
saving: boolean;
saveError: unknown;
onClose: () => void;
onRetry: () => void;
onSave: (columns: ListingColumn[]) => void;
}
export function ColumnConfigModal(props: Props) {
const [selected, setSelected] = useState<ListingColumn[]>(props.columns);
useEffect(() => {
if (props.open) {
setSelected(props.columns);
}
}, [props.open, props.columns]);
return (
<UModal
title="列配置"
open={props.open}
onCancel={props.saving ? undefined : props.onClose}
okText="保存"
cancelText="取消"
confirmLoading={props.saving}
okButtonProps={{ disabled: props.loading || Boolean(props.error) || props.saving }}
cancelButtonProps={{ disabled: props.saving }}
onOk={() => props.onSave(DEFAULT_COLUMNS.filter((column) => selected.includes(column)))}
>
<UText type="secondary">门店名称和操作列始终显示,其余列可勾选显示,字段顺序固定。</UText>
{props.error ? (
<UAlert
type="error"
showIcon
title={errorText(props.error, '列配置加载失败')}
action={
<UButton type="link" onClick={props.onRetry} loading={props.loading}>
重新加载列配置
</UButton>
}
/>
) : null}
{props.loading && <p role="status">正在加载列配置…</p>}
<div className="store-column-options">
{DEFAULT_COLUMNS.map((column) => (
<div className="store-column-option" key={column}>
<UCheckbox
checked={selected.includes(column)}
disabled={
column === 'storeName' || props.loading || Boolean(props.error) || props.saving
}
onChange={(event) =>
setSelected((current) =>
event.target.checked
? [...current, column]
: current.filter((key) => key !== column),
)
}
>
{COLUMN_LABELS[column]}
</UCheckbox>
</div>
))}
</div>
{props.saveError ? (
<UAlert
type="error"
showIcon
title={errorText(props.saveError, '列配置保存失败,请重试')}
/>
) : null}
</UModal>
);
}
import type { ColumnsType } from 'antd/es/table';
import type { StoreListingRow } from '@/api';
import type { StoreDictionaries } from '@/features/store/dictionaries';
import { dictionaryLabel, formatDateTime } from '@/features/store/formatters';
import { COLUMN_LABELS, type ListingColumn } from '../tools/listing';
export function buildColumns({
visible,
spec,
}: {
visible: ListingColumn[];
spec?: StoreDictionaries;
}): ColumnsType<StoreListingRow> {
const definitions: Record<ListingColumn, ColumnsType<StoreListingRow>[number]> = {
storeName: {
title: COLUMN_LABELS.storeName,
dataIndex: 'storeName',
key: 'storeName',
width: 230,
render: (value: string) => <span className="store-listing-name">{value || '—'}</span>,
},
merchantNo: {
title: COLUMN_LABELS.merchantNo,
dataIndex: 'merchantNo',
key: 'merchantNo',
width: 120,
render: (value: string) => <span className="store-code">{value || '—'}</span>,
},
businessScene: {
title: COLUMN_LABELS.businessScene,
dataIndex: 'businessScene',
key: 'businessScene',
width: 230,
render: (value: string) => (
<span className="store-listing-scene">{dictionaryLabel(spec?.businessScenes, value)}</span>
),
},
effectiveTime: {
title: COLUMN_LABELS.effectiveTime,
dataIndex: 'effectiveTime',
key: 'effectiveTime',
width: 130,
render: (value: string | null) => formatDateTime(value).split(' ')[0],
},
changeCount: {
title: COLUMN_LABELS.changeCount,
dataIndex: 'changeCount',
key: 'changeCount',
width: 90,
align: 'right',
render: (value: number | null | undefined) => value ?? '—',
},
};
return visible.map((column) => definitions[column]);
}
import { useEffect, useMemo, useState } from 'react';
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { App } from 'antd';
import { DownloadOutlined, SettingOutlined } from '@ant-design/icons';
import { Skeleton, UAlert, UButton, UCard, UResult, UText, UTitle } from '@uj/ui';
import { P, useAccess } from '@/access';
import { store, type ListingPageParams, type StoreId, type StoreListingRow } from '@/api';
import {
DataTable,
DEFAULT_PAGE_SIZE,
SearchForm,
type ActionSchema,
type FieldSchema,
type RowActionSchema,
} from '@/components';
import { StoreDetailDrawer } from '@/features/store/StoreDetailDrawer';
import { STORE_DICTIONARIES } from '@/features/store/dictionaries';
import { useStoreFilterOptions } from '@/features/store/useStoreFilterOptions';
import { buildColumns } from './components/columns';
import { ColumnConfigModal } from './components/ColumnConfigModal';
import {
errorText,
exportParams,
filterParams,
INITIAL_PARAMS,
normalizeColumns,
type ListingFilters,
} from './tools/listing';
import '@/features/store/store.css';
import './listing.css';
const CONFIG_KEY = ['store', 'listing', 'columns'] as const;
export default function StoreListing() {
const { message } = App.useApp();
const { canPoint } = useAccess();
const allowed = canPoint(P.STORE_LISTING_VIEW);
const filterOptions = useStoreFilterOptions({ enabled: allowed, includeProducts: false });
const queryClient = useQueryClient();
const [params, setParams] = useState<ListingPageParams>(INITIAL_PARAMS);
const [queryVersion, setQueryVersion] = useState(0);
const [selected, setSelected] = useState<{ id: StoreId; tab: string } | null>(null);
const [configOpen, setConfigOpen] = useState(false);
const listing = useQuery({
queryKey: ['store', 'listing', 'page', params, queryVersion],
queryFn: () => store.listStores(params),
placeholderData: keepPreviousData,
enabled: allowed,
});
const config = useQuery({
queryKey: CONFIG_KEY,
queryFn: () => store.getColumnConfig(),
enabled: allowed,
});
const configuredColumns = useMemo(() => normalizeColumns(config.data?.columns), [config.data]);
const detail = useQuery({
queryKey: ['store', 'listing', 'detail', selected?.id],
enabled: allowed && selected !== null,
queryFn: async () => {
const id = selected!.id;
const [data, changes] = await Promise.all([store.getStore(id), store.getChanges(id)]);
return { ...data, changeHistory: changes };
},
});
// 同上:把分页参数取成原始值再进依赖,避免对 params 对象的引用依赖。
const currentPage = params.current ?? 1;
const pageSize = params.size ?? 20;
useEffect(() => {
if (!allowed || !listing.data || listing.isPlaceholderData) return;
const lastPage = Math.max(1, Math.ceil(listing.data.total / pageSize));
if (currentPage > lastPage) {
setParams((previous) => ({ ...previous, current: lastPage }));
setQueryVersion((version) => version + 1);
}
}, [allowed, listing.data, listing.isPlaceholderData, currentPage, pageSize]);
const saveConfig = useMutation({
mutationFn: async (columns: string[]) => {
await store.saveColumnConfig(columns);
return store.getColumnConfig();
},
onSuccess: (result) => {
queryClient.setQueryData(CONFIG_KEY, result);
setConfigOpen(false);
message.success('列配置已保存');
},
});
const exportFile = useMutation({
mutationFn: () => store.exportStores(exportParams(params)),
onSuccess: () => {
message.success('导出文件已下载');
},
});
const total = listing.data?.total ?? 0;
const overExportLimit = total > 50_000;
const openDetail = (row: StoreListingRow, tab = 'info') =>
setSelected({ id: row.listingId, tab });
const fields: FieldSchema<ListingFilters>[] = [
{ name: 'storeName', label: '门店名称', type: 'input', placeholder: '模糊搜索', width: '100%' },
{
name: 'merchantNo',
label: '门店商户号',
type: 'input',
placeholder: '模糊搜索',
width: '100%',
},
{
name: 'businessScene',
label: '业务场景',
type: 'select',
width: '100%',
options: filterOptions.businessScene.options,
selectProps: filterOptions.businessScene.selectProps,
},
{ name: 'effectiveRange', label: '上架时间', type: 'dateRange', width: '100%' },
];
const columns = buildColumns({
visible: configuredColumns,
spec: STORE_DICTIONARIES,
});
const rowActions: RowActionSchema<StoreListingRow>[] = [
{ label: '查看详情', permission: P.STORE_LISTING_VIEW, onClick: (row) => openDetail(row) },
{
label: '变更历史',
permission: P.STORE_LISTING_VIEW,
onClick: (row) => openDetail(row, 'history'),
},
];
const actions: ActionSchema[] = [
{
label: (
<>
<SettingOutlined aria-hidden /> 列配置
</>
),
type: 'default',
permission: P.STORE_LISTING_VIEW,
onClick: () => {
saveConfig.reset();
setConfigOpen(true);
},
},
{
label: (
<>
<DownloadOutlined aria-hidden /> {exportFile.isPending ? '正在导出…' : '导出'}
</>
),
type: 'default',
permission: P.STORE_LISTING_EXPORT,
disabled:
overExportLimit || listing.isFetching || Boolean(listing.error) || exportFile.isPending,
onClick: () => {
if (!overExportLimit && !exportFile.isPending) exportFile.mutate();
},
},
];
if (!allowed)
return (
<UResult status="403" title="无门店列表访问权限" subTitle="请联系管理员开通访问权限。" />
);
if (listing.isPending) return <Skeleton variant="table" />;
return (
<div className="store-page">
<div className="store-page-header">
<div>
<UTitle level={3} style={{ margin: 0 }}>
门店列表
</UTitle>
<UText type="secondary">
仅展示审批通过的数据。一行对应一个门店与一个业务场景,门店名称相同、业务场景不同的记录分别展示。
</UText>
</div>
</div>
<UCard className="store-filter-card" size="small">
<SearchForm<ListingFilters>
fields={fields}
layout="vertical"
className="store-search-form"
initialValues={{ businessScene: '' }}
onSearch={(values) => {
const next = {
...filterParams(values),
current: 1,
size: params.size,
sortField: params.sortField,
sortOrder: params.sortOrder,
};
setParams(next);
setQueryVersion((version) => version + 1);
if (!exportFile.isPending) exportFile.reset();
}}
onReset={() => {
filterOptions.reset();
setParams({ ...INITIAL_PARAMS, size: params.size });
setQueryVersion((version) => version + 1);
if (!exportFile.isPending) exportFile.reset();
}}
/>
</UCard>
{listing.error ? (
<UAlert
type="error"
showIcon
title={errorText(listing.error, '门店列表加载失败')}
action={
<UButton type="link" onClick={() => void listing.refetch()}>
重新加载列表
</UButton>
}
/>
) : null}
{exportFile.error ? (
<UAlert type="error" showIcon title={errorText(exportFile.error, '导出失败,请重试')} />
) : null}
{overExportLimit ? (
<UAlert type="warning" showIcon title="筛选结果超过 50,000 条,请缩小范围后导出。" />
) : null}
<div className="store-listing-section">
<DataTable<StoreListingRow>
className="store-listing-table"
rowKey="listingId"
columns={columns}
rowActions={rowActions}
actionColumnWidth={150}
actionColumnFixed="right"
toolbarTitle={
<UText strong>
已生效门店 <UText type="secondary">{total} 条</UText>
</UText>
}
toolbarClassName="store-listing-toolbar"
actions={actions}
dataSource={listing.data?.records ?? []}
loading={listing.isFetching}
scroll={{ x: 950 }}
pagination={{
current: params.current ?? 1,
pageSize: params.size ?? DEFAULT_PAGE_SIZE,
total,
showSizeChanger: false,
pageSizeOptions: [10, 20, 50, 100],
showTotal: (count) =>
`共 ${count.toLocaleString('zh-CN')} 条记录 · 每页 ${params.size ?? DEFAULT_PAGE_SIZE} 条`,
onChange: (current, size) =>
setParams((previous) => ({
...previous,
current: size !== previous.size ? 1 : current,
size,
})),
}}
/>
</div>
<ColumnConfigModal
open={configOpen}
columns={configuredColumns}
loading={config.isFetching}
error={config.error}
saving={saveConfig.isPending}
saveError={saveConfig.error}
onClose={() => setConfigOpen(false)}
onRetry={() => void config.refetch()}
onSave={(next) => {
if (!config.isFetching && !config.error && !saveConfig.isPending) saveConfig.mutate(next);
}}
/>
<StoreDetailDrawer
key={selected ? `${selected.id}:${selected.tab}` : 'closed'}
open={selected !== null}
detail={detail.data}
spec={STORE_DICTIONARIES}
loading={detail.isPending && selected !== null}
error={detail.error}
mode="listing"
initialTab={selected?.tab}
onClose={() => setSelected(null)}
onRetry={() => void detail.refetch()}
/>
</div>
);
}
.store-listing-section {
min-width: 0;
}
.store-listing-toolbar {
padding: 16px 20px;
}
.store-listing-table.ant-table-wrapper {
min-width: 0;
overflow: hidden;
border: 1px solid #e1e6ed;
border-radius: 10px;
background: #fff;
box-shadow: none;
}
.store-listing-table .ant-table:is(.ant-table-middle, .ant-table-medium) {
color: #333c4a;
font-size: 13px;
line-height: 1.57;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-thead
> tr
> th {
height: 38px;
padding: 0 12px;
border-bottom: 1px solid #e1e6ed;
background: #fbfcfd;
color: #6b7686;
font-size: 12px;
font-weight: 500;
line-height: 1.57;
white-space: nowrap;
}
.store-listing-table .ant-table-thead > tr > th::before {
display: none;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr
> td {
height: 44px;
padding: 8px 12px;
border-bottom: 1px solid #edf0f5;
color: #333c4a;
font-size: 13px;
line-height: 1.57;
vertical-align: middle;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr:last-child
> td {
border-bottom: 0;
}
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr:hover
> td,
.store-listing-table
.ant-table:is(.ant-table-middle, .ant-table-medium)
.ant-table-tbody
> tr
> td.ant-table-cell-row-hover {
background: #fbfcfd;
}
.store-listing-table .store-listing-name {
color: #121821;
font-weight: 500;
}
.store-listing-table .store-code {
color: #2b5ce6;
font-family: 'JetBrains Mono', 'SFMono-Regular', Consolas, monospace;
font-size: 12px;
}
.store-listing-table .store-listing-scene {
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 7px;
border: 0;
border-radius: 4px;
background: var(--ant-color-primary-bg, #eef3ff);
color: var(--uj-primary, #2b5ce6);
font-size: 11px;
font-weight: 500;
line-height: 1.57;
white-space: nowrap;
}
.store-listing-table .ant-table-tbody > tr > td:last-child .ant-btn-link {
display: inline-flex;
height: auto;
min-width: 0;
padding: 0;
border: 0;
border-radius: 0;
background: transparent;
color: #2b5ce6;
font-size: 13px;
font-weight: 400;
line-height: 1.57;
vertical-align: middle;
box-shadow: none;
}
.store-listing-table .ant-table-tbody > tr > td:last-child .ant-btn-link + .ant-btn-link {
margin-inline-start: 12px;
}
.store-listing-table .ant-table-tbody > tr > td:last-child .ant-btn-link:hover {
color: #2b5ce6;
text-decoration: underline;
}
.store-listing-table.ant-table-wrapper .ant-table-pagination.ant-pagination {
display: flex;
align-items: center;
justify-content: flex-end;
margin: 0;
padding: 13px 20px;
border-top: 1px solid #e1e6ed;
background: #fff;
color: #6b7686;
font-size: 12px;
}
.store-listing-table .ant-pagination .ant-pagination-total-text {
margin-inline-end: auto;
padding-inline-end: 12px;
}
.store-listing-table .ant-pagination .ant-pagination-item,
.store-listing-table .ant-pagination .ant-pagination-prev,
.store-listing-table .ant-pagination .ant-pagination-next {
min-width: 28px;
height: 28px;
margin-inline-end: 5px;
border-radius: 5px;
font-size: 12px;
line-height: 26px;
}
.store-listing-table .ant-pagination .ant-pagination-item-active {
border-color: #2b5ce6;
background: #2b5ce6;
font-weight: 500;
}
.store-listing-table .ant-pagination .ant-pagination-item-active a {
color: #fff;
}
.store-column-options {
display: flex;
flex-direction: column;
gap: 8px;
margin-block: 20px;
}
.store-column-option {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 8px 12px;
border: 1px solid var(--ant-color-border-secondary, #e8ecf3);
border-radius: var(--ant-border-radius, 8px);
}
import type { ListingPageParams } from '@/api';
import { DEFAULT_PAGE_SIZE } from '@/components';
export const COLUMN_LABELS = {
storeName: '门店名称',
merchantNo: '门店商户号',
businessScene: '业务场景',
effectiveTime: '上架时间',
changeCount: '变更次数',
} as const;
export type ListingColumn = keyof typeof COLUMN_LABELS;
export const DEFAULT_COLUMNS: ListingColumn[] = [
'storeName',
'merchantNo',
'businessScene',
'effectiveTime',
'changeCount',
];
export const INITIAL_PARAMS: ListingPageParams = {
current: 1,
size: DEFAULT_PAGE_SIZE,
sortField: 'effectiveDate',
sortOrder: 'desc',
};
export function normalizeColumns(columns?: string[] | null): ListingColumn[] {
const valid = (columns ?? []).filter((column): column is ListingColumn =>
Object.hasOwn(COLUMN_LABELS, column),
);
// 保存的配置只决定显隐,字段顺序始终与原型一致。
return valid.length
? DEFAULT_COLUMNS.filter((column) => column === 'storeName' || valid.includes(column))
: [...DEFAULT_COLUMNS];
}
export type ListingFilters = Record<string, unknown> & {
storeName?: string;
merchantNo?: string;
businessScene?: string;
effectiveRange?: [
{ format: (pattern: string) => string },
{ format: (pattern: string) => string },
];
};
export function filterParams(values: ListingFilters): ListingPageParams {
const result: ListingPageParams = {};
for (const key of ['storeName', 'merchantNo', 'businessScene'] as const) {
const value = values[key]?.trim();
if (value) result[key] = value;
}
if (values.effectiveRange?.[0] && values.effectiveRange[1]) {
result.startDate = values.effectiveRange[0].format('YYYY-MM-DD');
result.endDate = values.effectiveRange[1].format('YYYY-MM-DD');
}
return result;
}
export function exportParams({ current: _current, size: _size, ...params }: ListingPageParams) {
return params;
}
export function errorText(error: unknown, fallback: string) {
return error instanceof Error && error.message ? error.message : fallback;
}
import { InfoCircleFilled, CheckCircleFilled } from '@ant-design/icons';
import { UCard } from '@uj/ui';
import { useAppStore } from '@/store/useAppStore';
export type ChainNodeStatus = 'done' | 'active' | 'pending';
export interface ChainNode {
status: ChainNodeStatus;
title: string;
subtitle: string;
time?: string;
}
const DEFAULT_SUBMIT_TIME = '2026-09-20 15:12';
interface NodeIconProps {
status: ChainNodeStatus;
index: number;
}
function NodeIcon({ status, index }: NodeIconProps) {
if (status === 'done') {
return (
<div
style={{
width: 32,
height: 32,
borderRadius: '50%',
background: '#16A34A',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
flex: 'none',
}}
>
<CheckCircleFilled style={{ fontSize: 18 }} />
</div>
);
}
if (status === 'active') {
return (
<div
style={{
width: 32,
height: 32,
borderRadius: '50%',
background: '#2B5CE6',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
color: '#fff',
fontWeight: 600,
fontSize: 13,
flex: 'none',
boxShadow: '0 0 0 4px #EEF2FF',
}}
>
{index + 1}
</div>
);
}
return (
<div
style={{
width: 32,
height: 32,
borderRadius: '50%',
background: '#fff',
border: '2px solid #D1D5DB',
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
color: '#9CA3AF',
flex: 'none',
}}
>
<CheckCircleFilled style={{ fontSize: 16 }} />
</div>
);
}
const lineColor = (status: ChainNodeStatus) => (status === 'done' ? '#16A34A' : '#E5E7EB');
function NodeLine({ status }: { status: ChainNodeStatus }) {
return (
<div
style={{
flex: 1,
height: 2,
background: lineColor(status),
alignSelf: 'flex-start',
marginTop: 15,
}}
/>
);
}
export interface ApprovalChainPreviewProps {
nodes?: ChainNode[];
/** (可选)覆盖默认的提交人名称。不传则取当前登录用户名 */
submitterName?: string;
/** (可选)覆盖默认的提交时间,格式 YYYY-MM-DD HH:mm */
submitTime?: string;
}
/**
* 生成默认 4 节点审批链:
* - 第 1 个节点「提交」:副标题 = 当前登录用户名(外部 prop 覆盖优先);时间 = submitTime 或 DEFAULT_SUBMIT_TIME
* - 第 2 个节点「优加商务经理」:当前审批节点(active)
* - 第 3 个节点「优加财务经理」:下一审批节点(pending)
* - 第 4 个节点「生效」:写入门店列表
*/
function buildDefaultNodes(submitter: string, time: string): ChainNode[] {
return [
{
status: 'done',
title: '提交',
subtitle: submitter,
time,
},
{
status: 'active',
title: '优加商务经理',
subtitle: '当前审批节点',
},
{
status: 'pending',
title: '优加财务经理',
subtitle: '下一审批节点',
},
{
status: 'pending',
title: '生效',
subtitle: '写入门店列表',
},
];
}
export function ApprovalChainPreview({
nodes,
submitterName,
submitTime,
}: ApprovalChainPreviewProps) {
const { currentUser } = useAppStore();
const finalSubmitter = submitterName ?? currentUser.name ?? '管理员';
const finalTime = submitTime ?? DEFAULT_SUBMIT_TIME;
const finalNodes: ChainNode[] = nodes ?? buildDefaultNodes(finalSubmitter, finalTime);
return (
<UCard
styles={{ body: { padding: '20px 24px 24px' } }}
style={{ marginBottom: 20, border: '1px solid #E5E7EB', borderRadius: 10 }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: '#2B5CE6', fontSize: 14 }} />
<span style={{ fontSize: 15, fontWeight: 600 }}>审批链预览</span>
</div>
}
>
<div style={{ display: 'flex', padding: '20px 8px 8px' }}>
{finalNodes.map((n, i) => {
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
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
flex: 'none',
}}
>
<NodeIcon status={n.status} index={i} />
<div
style={{
marginTop: 14,
fontSize: 14,
fontWeight: 600,
color:
n.status === 'active'
? '#2B5CE6'
: n.status === 'done'
? '#16A34A'
: '#6B7280',
textAlign: 'center',
}}
>
{n.title}
</div>
<div
style={{
marginTop: 4,
fontSize: 12,
color: '#9CA3AF',
textAlign: 'center',
}}
>
{n.subtitle}
</div>
{n.time && (
<div
style={{
marginTop: 4,
fontSize: 11,
color: '#C7CDD6',
textAlign: 'center',
}}
>
{n.time}
</div>
)}
</div>
<div style={{ flex: 1 }}>{hasRight && <NodeLine status={n.status} />}</div>
</div>
);
})}
</div>
</UCard>
);
}
import { ArrowLeftOutlined, ArrowRightOutlined } from '@ant-design/icons';
import { UButton } from '@uj/ui';
export interface ConfirmActionBarProps {
passCount?: number;
onBack?: () => void;
onSubmit?: () => void;
}
export function ConfirmActionBar({ onBack, onSubmit }: ConfirmActionBarProps) {
return (
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
paddingTop: 4,
}}
>
<UButton icon={<ArrowLeftOutlined />} onClick={onBack ?? (() => console.log('返回上一步'))}>
返回上一步
</UButton>
<div style={{ display: 'flex', gap: 12 }}>
<UButton
type="primary"
icon={<ArrowRightOutlined />}
onClick={onSubmit ?? (() => console.log('下一步:提交审批'))}
>
下一步:提交审批
</UButton>
</div>
</div>
);
}
import { useMemo } from 'react';
import { InfoCircleFilled, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { UCard, UButton } from '@uj/ui';
import type { StoreImportFailVO, StoreImportCheckVO } from '@/api/modules/store';
export interface FailDetailCardProps {
checkResult?: StoreImportCheckVO;
/** 上传文件的字节数(兜底:后端可能不返回 fileSize,用 File 对象的 size 字段) */
fileSize?: number;
/** 点击「重新上传」时触发(通常回到 Step 0 并清空文件) */
onReUpload?: () => void;
}
const FAIL_COL_LABELS = [
{ key: 'rowIndex' as const, label: '行号', width: 92 },
{ key: 'storeName' as const, label: '门店名称', width: 300 },
{ key: 'merchantNo' as const, label: '门店商户号', width: 160 },
{ key: 'reason' as const, label: '失败原因', width: undefined },
] as const;
/** 触发下载失败明细文件(直接使用后端 failFileUrl) */
function triggerDownloadFailFile(url: string) {
try {
const a = document.createElement('a');
a.href = url;
a.target = '_blank';
a.rel = 'noopener noreferrer';
a.download = '失败明细.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} catch {
window.open(url, '_blank', 'noopener noreferrer');
}
}
export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetailCardProps) {
const failRows = (checkResult?.failRows ?? 0) as number;
const failFileUrl = checkResult?.failFileUrl ?? null;
const failures = (checkResult?.failures ?? []) as StoreImportFailVO[];
const hasFailures = Array.isArray(failures) && failures.length > 0;
const hasFailFile = !!failFileUrl;
// 失败明细为空也允许渲染(显示 0 条失败 + 底部通过说明)。
// early return 必须放在下面所有 Hook 之后:shouldRender 变化时若少调两个 useMemo,
// React 会抛 "Rendered fewer hooks than expected" 并整页崩溃。
const shouldRender = failRows > 0 || hasFailures || hasFailFile;
/**
* 底部 L1 / L2 通过校验文字(复用 checkResult 的字段,无则从 failures.length 推断)
*/
const l1 = useMemo(() => {
// 文件大小:优先后端 fileSize,兜底用传入的 File.size(字节)
const rawSize = typeof checkResult?.fileSize === 'number' ? checkResult.fileSize : fileSize;
const size =
typeof rawSize === 'number'
? rawSize === 0
? '0'
: `${Math.max(1, Math.round(rawSize / 1024))}KB`
: '';
const total = typeof checkResult?.totalRows === 'number' ? `${checkResult.totalRows} 行` : '';
const version = checkResult?.templateVersion ? `模板版本${checkResult.templateVersion}` : '';
const parts = [
checkResult?.failL1Passed === false
? '格式不正确 / 模板版本不一致,校验失败'
: `格式 .xlsx / ${size}${total ? ' / ' + total : ''}${version ? ' / ' + version : ''}`,
];
return parts.filter(Boolean).join(' · ');
}, [checkResult, fileSize]);
const l2 = useMemo(() => {
const template = checkResult?.templateVersion
? `《模板${checkResult.templateVersion}》`
: '《【优加】门店上架模版》';
if (checkResult?.failL2Passed === false) {
return `${template}(21 列) 存在缺失列或多余列,请重新下载模板填写`;
}
return `${template}(21 列) 全部列匹配,无缺失列、无多余列`;
}, [checkResult]);
if (!shouldRender) return null;
const handleDownload = () => {
if (!failFileUrl) return;
triggerDownloadFailFile(failFileUrl);
};
return (
<UCard
styles={{ body: { padding: '18px 20px 14px' } }}
style={{
border: '1px solid #E5E7EB',
marginBottom: 20,
borderRadius: 12,
background: '#fff',
overflow: 'hidden',
}}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<span
style={{
width: 8,
height: 8,
borderRadius: '50%',
background: '#2563EB',
flex: 'none',
}}
/>
<span style={{ fontSize: 17, fontWeight: 700, color: '#111827' }}>校验失败明细</span>
{failRows > 0 && (
<span style={{ fontSize: 13, color: '#9CA3AF', marginLeft: 4 }}>共 {failRows} 条</span>
)}
</div>
}
extra={
<div style={{ display: 'flex', gap: 10 }}>
<UButton icon={<DownloadOutlined />} onClick={handleDownload} disabled={!hasFailFile}>
下载失败明细
</UButton>
<UButton
icon={<UploadOutlined />}
type="link"
onClick={onReUpload}
style={{ color: '#111827' }}
>
重新上传
</UButton>
</div>
}
>
{/* 失败明细表头 + 明细行(原生 table,样式与截图一致) */}
<div
style={{
width: '100%',
maxHeight: 360,
overflowX: 'auto',
overflowY: 'auto',
marginBottom: 14,
}}
>
<table
style={{
width: '100%',
borderCollapse: 'separate',
borderSpacing: 0,
tableLayout: 'fixed',
fontSize: 13,
}}
>
<colgroup>
{FAIL_COL_LABELS.map((c) => (
<col key={c.key} style={{ width: c.width ?? 'auto' }} />
))}
</colgroup>
<thead>
<tr style={{ position: 'sticky', top: 0, zIndex: 1 }}>
{FAIL_COL_LABELS.map((c) => (
<th
key={c.key}
style={{
textAlign: 'left',
color: '#6B7280',
fontWeight: 400,
fontSize: 13,
padding: '10px 8px',
borderBottom: '1px solid #F3F4F6',
whiteSpace: 'nowrap',
background: '#fff',
}}
>
{c.label}
</th>
))}
</tr>
</thead>
<tbody>
{hasFailures ? (
failures.map((f, i) => (
<tr key={`${f.rowIndex ?? i}-${f.levelCode ?? ''}-${f.productCategory ?? ''}`}>
{/* 行号(蓝 #2563EB) */}
<td
style={{
padding: '14px 8px',
borderBottom: '1px solid #F3F4F6',
color: '#2563EB',
fontWeight: 500,
whiteSpace: 'nowrap',
}}
>
{String(f.rowIndex ?? i + 1).padStart(2, '0')}
</td>
{/* 门店名称(深灰 普通字) */}
<td
style={{
padding: '14px 8px',
borderBottom: '1px solid #F3F4F6',
color: '#111827',
fontWeight: 500,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
title={f.storeName}
>
{f.storeName ?? '-'}
</td>
{/* 门店商户号(蓝 #2563EB) */}
<td
style={{
padding: '14px 8px',
borderBottom: '1px solid #F3F4F6',
color: '#2563EB',
fontWeight: 500,
whiteSpace: 'nowrap',
}}
>
{f.merchantNo ?? '-'}
</td>
{/* 失败原因(红 #991B1B) */}
<td
style={{
padding: '14px 8px',
borderBottom: '1px solid #F3F4F6',
color: '#991B1B',
fontWeight: 500,
lineHeight: 1.5,
wordBreak: 'break-all',
}}
title={f.reason}
>
{f.reason ?? '-'}
</td>
</tr>
))
) : (
<tr>
<td
colSpan={FAIL_COL_LABELS.length}
style={{
padding: '18px 8px',
color: '#6B7280',
fontSize: 13,
textAlign: 'center',
borderBottom: '1px solid #F3F4F6',
}}
>
<InfoCircleFilled style={{ color: '#9CA3AF', marginRight: 6 }} />
明细已生成失败文件,请点击右上角「下载失败明细」查看完整失败原因
</td>
</tr>
)}
</tbody>
</table>
</div>
{/* 底部 L1 / L2 校验说明(截图 2 行灰字) */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 6 }}>
<div style={{ fontSize: 13, color: '#6B7280', lineHeight: 1.6 }}>
<span>表头级(L2)校验:</span>
<span
style={{
color: '#047857',
fontWeight: 600,
margin: '0 6px',
}}
>
通过
</span>
<span>—— {l2}</span>
</div>
<div style={{ fontSize: 13, color: '#6B7280', lineHeight: 1.6 }}>
<span>文件级(L1)校验:</span>
<span
style={{
color: '#047857',
fontWeight: 600,
margin: '0 6px',
}}
>
通过
</span>
<span>—— {l1}</span>
</div>
</div>
</UCard>
);
}
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!