Commit c36c0477 by liimin

Merge branch 'v1.0.0' of http://192.168.3.233:8090/ujia/uj-store into v1.0.0

2 parents 726bc2f6 ac56d4c1
Showing 96 changed files with 4357 additions and 246 deletions
...@@ -15,3 +15,5 @@ _* ...@@ -15,3 +15,5 @@ _*
*.pem *.pem
keys/ keys/
src/api/core/keys/ src/api/core/keys/
# Local browser self-test screenshots, responses, reports and logs
/artifacts/store-ui-selftest-*/
...@@ -5,7 +5,7 @@ stages: ...@@ -5,7 +5,7 @@ stages:
lint: lint:
stage: verify stage: verify
image: node:20 image: node:22.22.2
cache: cache:
key: key:
files: files:
......
22.22.2
...@@ -69,19 +69,28 @@ src/ ...@@ -69,19 +69,28 @@ src/
## 首次运行 ## 首次运行
依赖通过 **pnpm** 管理(见 `package.json` 的 `packageManager` 与 `.npmrc`)。本机需先装好 [pnpm](https://pnpm.io/)(Node 18.18+)。 依赖通过 **pnpm 10.8.1** 管理(见 `package.json` 的 `packageManager` 与 `.npmrc`)。使用 **Node 22.22.2**(已固定在 `.nvmrc` 与 CI)。
```bash ```bash
pnpm install # 安装依赖,生成 node_modules 与 pnpm-lock.yaml nvm install 22.22.2
nvm use 22.22.2
pnpm install --frozen-lockfile
pnpm dev # 启动开发服务器:http://localhost:5173 pnpm dev # 启动开发服务器:http://localhost:5173
pnpm test # API 契约、金额展示、审批及列表交互测试
pnpm build # 类型检查(tsc --noEmit)+ 生产构建到 dist/ pnpm build # 类型检查(tsc --noEmit)+ 生产构建到 dist/
pnpm preview # 本地预览构建产物 pnpm preview # 本地预览构建产物
``` ```
Windows 下若 `nvm use` 提示系统链接访问被拒绝,可在管理员终端切换;也可仅在当前 PowerShell 会话设置 `$env:Path = "$env:NVM_HOME/v22.22.2;$env:Path"` 后执行上述 pnpm 命令。
> 若某包因镜像源偶发抽取失败(如 `@ant-design/icons` 在 npmmirror 上曾损坏),重试一次,或临时切换官方源: > 若某包因镜像源偶发抽取失败(如 `@ant-design/icons` 在 npmmirror 上曾损坏),重试一次,或临时切换官方源:
> `pnpm install --registry=https://registry.npmjs.org/` > `pnpm install --registry=https://registry.npmjs.org/`
> 编辑器仍报“找不到模块 antd”等红线时,确认 `node_modules/antd` 已存在,并执行 > 编辑器仍报“找不到模块 antd”等红线时,确认 `node_modules/antd` 已存在,并执行
> `TypeScript: Restart TS Server`(VS Code `Ctrl+Shift+P`)刷新类型缓存。 > `TypeScript: Restart TS Server`(VS Code `Ctrl+Shift+P`)刷新类型缓存。
后端约定(需自行实现):`POST /api/store-import`(multipart,含 `file` 与 `templateVersion=V1.0.1`)。 开发代理:`/api` → `http://192.168.3.197:8788`,配置位于 `vite.config.ts`。需处于可访问后端的内网;生产环境应配置对应网关代理。
门店审批与门店列表已连接 `/store/approval/*`、`/store/listing/*`。筛选和详情共用 `src/features/store/dictionaries.ts` 本地字典,查询提交中文业务值,未知回显值原样展示;新增业务场景或产品分类在此维护。查看权限及按钮权限取登录接口的 `permCodes`;审批状态和层级以后端返回为准。详情按一条「门店+业务场景」记录展示,批量审批使用后端批量接口,重新提交入口及对接已屏蔽,导出直接下载当前筛选结果。
审批和列表接口通过 `lossless-json` 保留长 ID、金额及比例原文;运营成本合计直接展示 `costTotal`,不从已格式化单价或分类明细重新计算。真实页面联调记录位于 `artifacts/store-ui-selftest-2026-10-09/`。
# 门店审批与门店列表实施记录
用户已批准计划,当前分支 v1.0.0 原地实施。依据 Downloads 中的 PRD 与高保真原型,用户确认优先于原型演示代码。
## 已确认口径
- 两级审批:商务经理 → 财务经理,展示兼容后端层级;状态始终以后端为准。
- 详情限定当前 listingId 对应的门店和业务场景,无编辑。按 2026-10-09 用户最新要求,重新提交功能暂时屏蔽,不做接口对接和开发;保留既有 RESUBMIT 审批历史的只读展示。
- 导出直接下载;批量调用 batch-pass,仅展示整体返回,不猜测部分成功。
- 比例 5 = 5%,金额元,costTotal 为权威值,不按分类或场景重复累加。
- 优先复用 DataTable 的 rowActions/actions.permission 和 @uj/ui。
- 按用户确认使用 store:approve:view/pass/reject 与 store:list:view/export。
## 任务与验证
1. 环境:nvm 安装 Node 22.22.2、pnpm frozen install、Vite 启动,再开发。
2. API:真实分页、审批、详情、字典、历史、列配置和带鉴权文件下载,边界测试。
3. 公共详情:两种只读抽屉、精确金额/单位展示、动态流程与留痕,组件测试。
4. 审批:三页签、统一筛选、数量、分页、受控多选、单次和批量确认、打回校验、撤回;重新提交暂不纳入当前范围,测试权限与刷新。
5. 列表:四项筛选、服务端分页排序、六列、按用户列配置、当前筛选导出、详情历史;页面测试。
6. 整体:全量测试、类型检查、构建、权限 lint、修改文件格式检查和独立审查。
## 进展与裁定
- 2026-10-09 用户追加要求:重新提交功能先屏蔽,不做对接和开发。移除列表入口、确认弹窗分支、页面 mutation 调用及 Store API 方法,并同步撤回提示;下方完成与验收记录保留为本次范围调整前的历史记录。
- 2026-10-09:nvm 安装 22.22.2 成功;nvm use 因系统链接权限失败。所有工程命令通过进程 PATH 使用 nvm 的 v22.22.2,不覆盖系统链接。
- pnpm install --frozen-lockfile 完成;Vite http://127.0.0.1:5173 启动成功。
- 基线 2/2 测试通过;基线 build 因 http.ts 中禁用的响应验签遗留未使用变量失败,纳入最小清理,保持既有验签行为。
- 浏览器工具访问 localhost 被权限机制拒绝;不绕过,改用自动化组件/契约测试。真实视觉验收待用户允许访问。
- 实时接口列表均为空;两级后端流转暂无法凭真实记录验证,夹具不冒充真实业务数据。
- 依赖接口:API 类型与方法由 api_contract 提供;StoreDetailDrawer/formatters 由 requirements 提供;StoreListing 由 repo_reuse 提供;主代理负责公共组件、审批、集成及复核。
## 完成与验收记录
- 两页已替换模拟数据:审批三页签、筛选计数、单条/批量通过、打回原因、撤回与原记录重提;列表筛选、分页排序、列配置、导出、场景详情及变更历史。
- 复用现有 DataTable/SearchForm/PermButton 与 @uj/ui;新增 UDrawer。修复筛选重置和无权限按钮禁用被覆盖,并兼容后端菜单 `/store/approval` 地址。
- 仅审批/列表响应接入 lossless-json,保留长 ID 与金额原文。金额展示不重算、不舍入权威合计;解析、详情及提交均有回归覆盖。
- 独立审查已完成;发现的门店名称冻结列缺口已修复。补充登录/退出清理查询缓存,避免切换账号复用列表及列配置。
- 最终验证(Node v22.22.2 / pnpm 10.8.1):`pnpm test` 10 个文件、94 项全部通过;`pnpm build`(含类型检查)通过;`pnpm lint`(当前项目范围 src/access)、修改文件 Prettier 检查与 `git diff --check` 通过。生产构建仍提示主包超过 500 kB,不阻断构建。
- 验收边界:实时登录与查询接口可用,但列表无业务记录;未进行真实审批写入或真实两级流转。浏览器访问未获许可,视觉验收未完成。测试中的业务记录均为明确夹具。
- 代码留在当前分支,未提交、未推送、未部署。
# 可配置业务组件设计
## 目标
在 `src/components` 提供三类可复用的业务组件:搜索、表格分页、表单与详情。页面通过配置描述字段、列和按钮,减少重复界面代码。所有基础界面元素复用 `@uj/ui`,不直接使用等价的 antd 组件。
本次只新增组件与使用说明,不替换现有页面。
## 组件与职责
### SearchForm
- 接收字段配置、初始值、查询和重置回调。
- 支持文本、下拉、多选、日期和日期范围。
- 自动渲染查询、重置按钮;也允许调用方提供额外操作区。
- 查询时返回当前字段值,重置时恢复配置的初始值。
### DataTable
- 接收列、数据、分页、加载状态和行唯一标识。
- 可选显示序号、行勾选与顶部操作区。
- 分页变化通过回调交给页面请求下一页数据;组件不自行请求接口。
- 列内容以 antd 兼容的列定义为基础,以便调用方提供自定义单元格内容。
### CombiForm
- `mode="form"` 时按字段配置生成可编辑表单,暴露表单实例和提交回调。
- `mode="detail"` 时使用同一份字段配置只读展示数据。
- 支持文本、下拉、多选、日期、日期范围、单选、开关和文本域。
- 字段可依据当前值动态隐藏或禁用,也可提供自定义渲染内容。
## 统一配置约定
字段配置包含:字段名、标题、控件类型、提示语、选项、默认值、是否必填、是否隐藏、是否禁用、宽度和变化回调。动态隐藏与禁用接收当前表单值。
按钮配置包含:文字、点击回调、显示类型、危险状态、加载状态及可选权限点。配置了权限点的按钮使用现有的 `PermButton`;无权限默认隐藏,也可配置为显示不可点击状态并显示提示。
复杂控件或特殊显示不纳入第一版的固定类型;通过自定义渲染入口扩展,避免把旧项目中大量仅被少数页面使用的逻辑带入新项目。
## 文件组织
```
src/components/
├── SearchForm/
│ ├── index.tsx
│ └── types.ts
├── DataTable/
│ ├── index.tsx
│ └── types.ts
├── CombiForm/
│ ├── index.tsx
│ └── types.ts
└── index.ts
```
每个组件只负责界面生成与事件转交,不保存接口数据,也不写角色判断。权限统一使用 `@/access` 导出的能力。
## 使用方式
页面维护字段、列和按钮配置,并把数据及回调传给组件。搜索条件和分页状态仍归页面所有,便于与现有请求逻辑和缓存机制协作。编辑表单由页面负责保存接口;详情组件只接收展示数据。
## 异常与边界
- 缺少下拉选项时显示为空选项,不自行发起请求。
- 隐藏字段不参与界面展示;表单校验规则仅用于可见字段。
- 没有数据时使用统一表格的空状态。
- `DataTable` 的分页可关闭,供一次性列表使用。
- 权限点缺失时不做猜测,按按钮配置的默认规则处理。
## 验收与验证
- 为三类组件的配置转换与关键交互补充自动检查:搜索重置、分页回调、字段隐藏、详情展示及权限按钮配置。
- 先确认新增检查能因组件缺失而失败,再实现最小功能使其通过。
- 运行项目的类型检查、格式检查和生产构建。
- 新增一份可复制的使用示例,覆盖搜索、表格分页、编辑表单与详情展示。
## 不包含的内容
- 不迁移旧项目的图片上传、富文本、远程搜索、表头筛选、树状表格等专用能力。
- 不修改 `packages/ui` 中的基础组件,也不直接引入等价 antd 控件。
- 不修改现有业务页面或接口。
...@@ -5,10 +5,11 @@ ...@@ -5,10 +5,11 @@
"type": "module", "type": "module",
"packageManager": "pnpm@10.8.1", "packageManager": "pnpm@10.8.1",
"engines": { "engines": {
"node": ">=18.18.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"test": "vitest run",
"build": "tsc --noEmit && vite build", "build": "tsc --noEmit && vite build",
"preview": "vite preview", "preview": "vite preview",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
...@@ -24,12 +25,16 @@ ...@@ -24,12 +25,16 @@
"antd": "^6.6.5", "antd": "^6.6.5",
"axios": "^1.20.0", "axios": "^1.20.0",
"jsrsasign": "^11.1.5", "jsrsasign": "^11.1.5",
"lossless-json": "^4.3.1",
"react": "^19.3.0", "react": "^19.3.0",
"react-dom": "^19.3.0", "react-dom": "^19.3.0",
"react-router-dom": "^7.18.4", "react-router-dom": "^7.18.4",
"zustand": "^5.0.0" "zustand": "^5.0.0"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.7",
"@types/jsrsasign": "^10.5.15", "@types/jsrsasign": "^10.5.15",
"@types/node": "^26.6.5", "@types/node": "^26.6.5",
"@types/react": "^19.0.0", "@types/react": "^19.0.0",
...@@ -39,10 +44,12 @@ ...@@ -39,10 +44,12 @@
"eslint": "^9", "eslint": "^9",
"eslint-config-prettier": "^9", "eslint-config-prettier": "^9",
"husky": "^9", "husky": "^9",
"jsdom": "^30.1.1",
"lint-staged": "^15", "lint-staged": "^15",
"prettier": "^3", "prettier": "^3",
"typescript": "^5.6.3", "typescript": "^5.6.3",
"vite": "^6.0.0" "vite": "^6.0.0",
"vitest": "^5.0.2"
}, },
"lint-staged": { "lint-staged": {
"src/access/**/*.{ts,tsx}": [ "src/access/**/*.{ts,tsx}": [
......
import { Cascader, type CascaderProps } from 'antd';
import type { DefaultOptionType } from 'antd/es/cascader';
export type UCascaderProps = CascaderProps<DefaultOptionType, keyof DefaultOptionType, false>;
/** 项目统一级联选择。 */
export function UCascader(props: UCascaderProps) {
return <Cascader {...props} />;
}
import { DatePicker, type DatePickerProps } from 'antd';
export type UDatePickerProps = DatePickerProps;
export const UDatePicker = Object.assign((props: UDatePickerProps) => <DatePicker {...props} />, {
RangePicker: DatePicker.RangePicker,
});
import { Descriptions, type DescriptionsProps } from 'antd';
export type UDescriptionsProps = DescriptionsProps;
export const UDescriptions = Object.assign(
(props: UDescriptionsProps) => <Descriptions {...props} />,
{
Item: Descriptions.Item,
},
);
import { Drawer, type DrawerProps } from 'antd';
export type UDrawerProps = DrawerProps;
/** Unified detail drawer; responsive width and lifecycle defaults remain overridable. */
export function UDrawer({ size = 760, destroyOnHidden = true, styles, ...props }: UDrawerProps) {
return (
<Drawer
size={size}
destroyOnHidden={destroyOnHidden}
styles={(info) => {
const custom = typeof styles === 'function' ? styles(info) : styles;
return { ...custom, wrapper: { maxWidth: '94vw', ...custom?.wrapper } };
}}
{...props}
/>
);
}
...@@ -5,11 +5,20 @@ import { Modal, type ModalProps } from 'antd'; ...@@ -5,11 +5,20 @@ import { Modal, type ModalProps } from 'antd';
* 若需 Modal.confirm 等静态方法,后续可在此封装 UModal.confirm 包装器。 * 若需 Modal.confirm 等静态方法,后续可在此封装 UModal.confirm 包装器。
*/ */
export function UModal(props: ModalProps) { export function UModal(props: ModalProps) {
const { centered = true, destroyOnClose = true, okButtonProps, ...rest } = props; const {
centered = true,
destroyOnClose,
destroyOnHidden = destroyOnClose ?? true,
maskClosable,
mask,
okButtonProps,
...rest
} = props;
return ( return (
<Modal <Modal
centered={centered} centered={centered}
destroyOnClose={destroyOnClose} destroyOnHidden={destroyOnHidden}
mask={mask ?? (maskClosable === undefined ? undefined : { closable: maskClosable })}
okButtonProps={{ type: 'primary', ...okButtonProps }} okButtonProps={{ type: 'primary', ...okButtonProps }}
{...rest} {...rest}
/> />
......
import { Radio, type RadioGroupProps, type RadioProps } from 'antd';
export type URadioProps = RadioProps;
export type URadioGroupProps = RadioGroupProps;
export const URadio = Object.assign((props: URadioProps) => <Radio {...props} />, {
Group: Radio.Group,
});
import { Switch, type SwitchProps } from 'antd';
export type USwitchProps = SwitchProps;
export const USwitch = (props: USwitchProps) => <Switch {...props} />;
...@@ -12,6 +12,9 @@ export type { UInputProps } from './components/Input'; ...@@ -12,6 +12,9 @@ export type { UInputProps } from './components/Input';
export { USelect } from './components/Select'; export { USelect } from './components/Select';
export type { USelectProps } from './components/Select'; export type { USelectProps } from './components/Select';
export { UCascader } from './components/Cascader';
export type { UCascaderProps } from './components/Cascader';
export { UForm, UFormItem } from './components/Form'; export { UForm, UFormItem } from './components/Form';
export { UTypography, UTitle, UText, UParagraph } from './components/Typography'; export { UTypography, UTitle, UText, UParagraph } from './components/Typography';
...@@ -20,6 +23,8 @@ export { UCard } from './components/Card'; ...@@ -20,6 +23,8 @@ export { UCard } from './components/Card';
export { UTag } from './components/Tag'; export { UTag } from './components/Tag';
export { UAlert } from './components/Alert'; export { UAlert } from './components/Alert';
export { UModal } from './components/Modal'; export { UModal } from './components/Modal';
export { UDrawer } from './components/Drawer';
export type { UDrawerProps } from './components/Drawer';
export { UTable } from './components/Table'; export { UTable } from './components/Table';
export { FillTable } from './components/FillTable'; export { FillTable } from './components/FillTable';
export { UUpload } from './components/Upload'; export { UUpload } from './components/Upload';
...@@ -31,3 +36,12 @@ export { UCheckbox } from './components/Checkbox'; ...@@ -31,3 +36,12 @@ export { UCheckbox } from './components/Checkbox';
export { UList } from './components/List'; export { UList } from './components/List';
export { UTooltip } from './components/Tooltip'; export { UTooltip } from './components/Tooltip';
export { UResult } from './components/Result'; export { UResult } from './components/Result';
export { UDatePicker } from './components/DatePicker';
export type { UDatePickerProps } from './components/DatePicker';
export { URadio } from './components/Radio';
export type { URadioProps, URadioGroupProps } from './components/Radio';
export { USwitch } from './components/Switch';
export type { USwitchProps } from './components/Switch';
export { UDescriptions } from './components/Descriptions';
export type { UDescriptionsProps } from './components/Descriptions';
...@@ -20,3 +20,14 @@ export { AccessProvider, useAccess } from './runtime/AccessProvider'; ...@@ -20,3 +20,14 @@ export { AccessProvider, useAccess } from './runtime/AccessProvider';
// 权限 UI 组件:与权限点配套 // 权限 UI 组件:与权限点配套
export { PermButton } from './ui/PermButton'; export { PermButton } from './ui/PermButton';
export { Perm } from './ui/Perm'; export { Perm } from './ui/Perm';
export {
clearLoginSession,
getAuthorization,
getLoginSession,
getUserInfo,
getUserPermCodes,
saveLoginSession,
saveUserInfo,
} from './session';
export type { LoginSession } from './session';
...@@ -9,17 +9,25 @@ export type PermissionPoint = string; ...@@ -9,17 +9,25 @@ export type PermissionPoint = string;
export const P = { export const P = {
// 门店审批 // 门店审批
STORE_APPROVE: 'store:approve', STORE_APPROVE: 'store:approve:view',
STORE_APPROVE_VIEW: 'store:approve:view', STORE_APPROVE_VIEW: 'store:approve:view',
STORE_APPROVE_MANAGE: 'store:approve:manage', STORE_APPROVE_MANAGE: 'store.approve:manage',
// 审核按钮:后端审批动作为 pass/reject,无 audit 动作码,暂挂 audit,待定 STORE_APPROVE_AUDIT: 'store:approve:pass',
STORE_APPROVE_AUDIT: 'store:approve:audit',
STORE_APPROVE_REJECT: 'store:approve:reject', STORE_APPROVE_REJECT: 'store:approve:reject',
// 门店列表 // 门店列表
STORE_LISTING: 'store:list', STORE_LISTING: 'store:list:view',
STORE_LISTING_VIEW: 'store:list:view',
STORE_LISTING_EXPORT: 'store:list:export', STORE_LISTING_EXPORT: 'store:list:export',
// 删除按钮:后端列表无 delete 动作码,暂挂 delete,待定 STORE_LISTING_DELETE: 'store.listing:delete',
STORE_LISTING_DELETE: 'store:list:delete', /** 角色管理
* system:role:view - 查看角色详情
* system:role:save - 新增/编辑/删除角色
*/
SYSTEM_ROLE_VIEW: 'system:role:view',
SYSTEM_ROLE_SAVE: 'system:role:save',
/** 账号管理 */
SYSTEM_USER_VIEW: 'system:user:view',
SYSTEM_USER_SAVE: 'system:user:save',
// 复用片段 // 复用片段
VIEW: ':view', VIEW: ':view',
MANAGE: ':manage', MANAGE: ':manage',
......
/** 登录会话:令牌、用户信息和权限均属于访问控制范围。 */
export interface LoginSession {
token: string;
tokenType: 'Bearer' | string;
expireAt: string;
userId: number;
account: string;
name: string;
orgId: number;
dataScope: number;
roleCodes: string[];
permCodes: string[];
}
const SESSION_KEY = 'session';
/** 用户信息及权限的统一本地存储键。 */
const USER_INFO_KEY = 'uj-auth-user-info';
export function saveLoginSession(session: LoginSession) {
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
}
export function getLoginSession(): LoginSession | undefined {
const raw = localStorage.getItem(SESSION_KEY);
if (!raw) return undefined;
try {
const session = JSON.parse(raw) as LoginSession;
if (
!session.token ||
(session.expireAt && new Date(session.expireAt).getTime() <= Date.now())
) {
localStorage.removeItem(SESSION_KEY);
return undefined;
}
return session;
} catch {
localStorage.removeItem(SESSION_KEY);
return undefined;
}
}
export function getAuthorization() {
const session = getLoginSession();
return session ? `${session.tokenType || 'Bearer'} ${session.token}` : undefined;
}
export function saveUserInfo(info: unknown, fallbackPermCodes: string[] = []) {
const userInfo =
info && typeof info === 'object' && !Array.isArray(info)
? (info as Record<string, unknown>)
: {};
const permCodes = Array.isArray(userInfo.permCodes)
? userInfo.permCodes.filter((code): code is string => typeof code === 'string')
: fallbackPermCodes;
localStorage.setItem(USER_INFO_KEY, JSON.stringify({ ...userInfo, permCodes }));
}
/** 获取本地用户信息,权限按钮以其中的 permCodes 为唯一依据。 */
export function getUserInfo(): Record<string, unknown> | undefined {
const raw = localStorage.getItem(USER_INFO_KEY);
if (!raw) return undefined;
try {
const userInfo = JSON.parse(raw);
return userInfo && typeof userInfo === 'object' && !Array.isArray(userInfo)
? (userInfo as Record<string, unknown>)
: undefined;
} catch {
localStorage.removeItem(USER_INFO_KEY);
return undefined;
}
}
export function getUserPermCodes(): string[] {
const permCodes = getUserInfo()?.permCodes;
return Array.isArray(permCodes)
? permCodes.filter((code): code is string => typeof code === 'string')
: [];
}
export function clearLoginSession() {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(USER_INFO_KEY);
}
...@@ -3,7 +3,7 @@ import { UButton, UTooltip, type UButtonProps } from '@uj/ui'; ...@@ -3,7 +3,7 @@ import { UButton, UTooltip, type UButtonProps } from '@uj/ui';
import { useAccess } from '../runtime/AccessProvider'; import { useAccess } from '../runtime/AccessProvider';
interface PermButtonProps extends UButtonProps { interface PermButtonProps extends UButtonProps {
/** 所需权限点,如 'store.approve:audit';无该权限时按 fallback 处理 */ /** 所需权限点,如 'store:approve:pass';无该权限时按 fallback 处理 */
permission: string; permission: string;
/** 无权限时的表现:'hide' 不渲染(默认)| 'disabled' 渲染禁用态 */ /** 无权限时的表现:'hide' 不渲染(默认)| 'disabled' 渲染禁用态 */
fallback?: 'hide' | 'disabled'; fallback?: 'hide' | 'disabled';
...@@ -22,7 +22,7 @@ export const PermButton = forwardRef<HTMLButtonElement, PermButtonProps>( ...@@ -22,7 +22,7 @@ export const PermButton = forwardRef<HTMLButtonElement, PermButtonProps>(
if (!ok && fallback === 'hide') return null; if (!ok && fallback === 'hide') return null;
const btn = <UButton ref={ref} disabled={!ok || rest.disabled} {...rest} />; const btn = <UButton ref={ref} {...rest} disabled={!ok || rest.disabled} />;
if (!ok && fallback === 'disabled' && unauthorizedTip) { if (!ok && fallback === 'disabled' && unauthorizedTip) {
return <UTooltip title={unauthorizedTip}>{btn}</UTooltip>; return <UTooltip title={unauthorizedTip}>{btn}</UTooltip>;
......
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { AxiosAdapter } from 'axios';
import { http } from '../http';
import { store } from '../../modules/store';
import { formatMoney, formatPolicyValue } from '@/features/store/formatters';
const originalAdapter = http.defaults.adapter;
function serveRaw(raw: string) {
const adapter: AxiosAdapter = async (config) => ({
config,
data: raw,
headers: { 'content-type': 'application/json' },
status: 200,
statusText: 'OK',
});
http.defaults.adapter = adapter;
}
async function request<T = Record<string, unknown>>(url: string): Promise<T> {
return http.get(url) as unknown as Promise<T>;
}
beforeEach(() => localStorage.clear());
afterEach(() => {
http.defaults.adapter = originalAdapter;
});
describe('store JSON precision at the HTTP boundary', () => {
it('preserves unquoted int64 IDs and monetary decimals through display and a later approval request', async () => {
serveRaw(
'{"code":200,"data":{"listingId":9223372036854775807,"storeName":"门店","merchantNo":"M1","businessScene":"AFTER_SALE_MEMBER","costTotal":9007199254740993.01,"currentLevel":1,"totalLevel":2,"items":[{"itemId":9223372036854775806,"marketFee1Value":5,"marketFee1Unit":"RATIO"}]}}',
);
const detail = await store.getApproval('9223372036854775807');
expect(detail.listingId).toBe('9223372036854775807');
expect(detail.costTotal).toBe('9007199254740993.01');
expect(formatMoney(detail.costTotal)).toBe('¥9,007,199,254,740,993.01');
expect(detail.items?.[0].itemId).toBe('9223372036854775806');
expect(formatPolicyValue(detail.items?.[0].marketFee1Value, 'RATIO')).toBe('5%');
let submittedBody = '';
http.defaults.adapter = async (config) => {
submittedBody = config.data;
return {
config,
data: '{"code":200,"data":null}',
headers: { 'content-type': 'application/json' },
status: 200,
statusText: 'OK',
};
};
await store.passApproval(detail.listingId);
expect(submittedBody).toBe('{"listingId":"9223372036854775807"}');
});
it.each([
'/store/approval/pending',
'/store/approval/done',
'/store/approval/mine',
'/store/listing/page',
'/api/store/listing/page?current=1',
'http://example.test/store/listing/page',
])('preserves record numbers but keeps pagination numeric for %s', async (url) => {
serveRaw(
'{"code":200,"timestamp":1791514515716,"success":true,"data":{"records":[{"listingId":21,"costTotal":0.00,"categoryCount":6,"currentLevel":1,"totalLevel":2,"pendingHours":24,"actionable":true,"items":[{"sunshine1OnlinePoint":0,"sunshine2OnlinePoint":1}]}],"total":1,"current":1,"size":20,"pages":1}}',
);
const body = await request<{
code: number;
timestamp: number;
success: boolean;
data: {
records: Record<string, unknown>[];
total: number;
current: number;
size: number;
pages: number;
};
}>(url);
expect(body.code).toBe(200);
expect(body.timestamp).toBe(1791514515716);
expect(body.success).toBe(true);
expect(body.data).toMatchObject({ total: 1, current: 1, size: 20, pages: 1 });
expect(body.data.records[0]).toEqual({
listingId: '21',
costTotal: '0.00',
categoryCount: 6,
currentLevel: 1,
totalLevel: 2,
pendingHours: 24,
actionable: true,
items: [{ sunshine1OnlinePoint: 0, sunshine2OnlinePoint: 1 }],
});
});
it('preserves all cost and policy values without changing missing or invalid input', async () => {
serveRaw(
'{"code":200,"data":{"costDecoration":null,"costMonthly":"","costLabor":"invalid","costTotal":-0.01,"marketFee1Value":0,"marketFee2Value":33.333333333333333333,"sunshine1Value":1e-18,"sunshine2Value":1.234567890123456789e+30}}',
);
const body = await request<{ data: Record<string, unknown> }>('/store/listing/21');
expect(body.data).toEqual({
costDecoration: null,
costMonthly: '',
costLabor: 'invalid',
costTotal: '-0.01',
marketFee1Value: '0',
marketFee2Value: '33.333333333333333333',
sunshine1Value: '1e-18',
sunshine2Value: '1.234567890123456789e+30',
});
expect(formatMoney(body.data.costTotal)).toBe('¥-0.01');
expect(formatMoney(body.data.costMonthly)).toBe('—');
expect(formatMoney(body.data.costLabor)).toBe('—');
expect(formatPolicyValue(body.data.sunshine1Value, 'RATIO')).toBe('0.000000000000000001%');
});
it('preserves IDs in approval and change history rather than truncating them', async () => {
serveRaw(
'{"code":200,"data":{"listingId":9223372036854775807,"approvalLogs":[{"logId":9223372036854775806,"operatorId":9223372036854775805}],"changeHistory":[{"changeId":9223372036854775804,"changeUserId":9223372036854775803,"versionNo":2}]}}',
);
const body = await request<{ data: unknown }>('/store/approval/9223372036854775807');
expect(body.data).toEqual({
listingId: '9223372036854775807',
approvalLogs: [{ logId: '9223372036854775806', operatorId: '9223372036854775805' }],
changeHistory: [
{ changeId: '9223372036854775804', changeUserId: '9223372036854775803', versionNo: 2 },
],
});
});
it('rejects unsafe nonfinancial counts instead of silently truncating them', async () => {
serveRaw(
'{"code":200,"data":{"records":[],"total":9007199254740993,"current":1,"size":20,"pages":1}}',
);
await expect(request('/store/listing/page')).rejects.toThrow();
});
it('preserves audit creator and updater IDs that do not use an Id suffix', async () => {
serveRaw(
'{"code":200,"data":{"items":[{"createBy":9223372036854775807,"updateBy":9223372036854775806}]}}',
);
const body = await request<{ data: unknown }>('/store/listing/21');
expect(body.data).toEqual({
items: [{ createBy: '9223372036854775807', updateBy: '9223372036854775806' }],
});
});
it.each(['/system/user/current', '/store/role/list', '/store/import/check'])(
'keeps existing ordinary JSON behavior outside the approval and listing endpoints: %s',
async (url) => {
serveRaw('{"code":200,"data":{"userId":21,"costTotal":5.20,"enabled":true}}');
expect(await request(url)).toEqual({
code: 200,
data: { userId: 21, costTotal: 5.2, enabled: true },
});
},
);
it('does not introduce conversion failures for the existing bare import submission ID', async () => {
serveRaw('{"code":200,"data":9223372036854775807}');
const body = await request<{ code: number; data: number }>('/store/import/submit');
expect(body.code).toBe(200);
expect(typeof body.data).toBe('number');
});
it('keeps numeric business error codes available to the common error handling', async () => {
serveRaw('{"code":10003,"message":"无审批权限","data":{"listingId":9223372036854775807}}');
await expect(store.getApproval('9223372036854775807')).rejects.toMatchObject({
code: 10003,
message: '无审批权限',
data: { listingId: '9223372036854775807' },
});
});
});
...@@ -3,6 +3,12 @@ ...@@ -3,6 +3,12 @@
// 规范见《优加门店上架系统 · 前后端 RSA 非对称加签对接说明》。 // 规范见《优加门店上架系统 · 前后端 RSA 非对称加签对接说明》。
import { http } from './http'; import { http } from './http';
import type { ApiResult } from './types'; import type { ApiResult } from './types';
import type { AxiosResponseHeaders } from 'axios';
export interface BlobResponse {
blob: Blob;
headers: Record<string, string> | AxiosResponseHeaders;
}
export class ApiClient { export class ApiClient {
/** 共享的 axios 实例(请求加签 / 响应验签在 ./http 拦截器中完成) */ /** 共享的 axios 实例(请求加签 / 响应验签在 ./http 拦截器中完成) */
...@@ -24,6 +30,22 @@ export class ApiClient { ...@@ -24,6 +30,22 @@ export class ApiClient {
return this.call<T>('DELETE', url, { params }); return this.call<T>('DELETE', url, { params });
} }
/** 下载二进制文件(不解包 data,直接返回原始 blob + response headers(含 content-disposition)) */
protected async getBlob(url: string, params?: Record<string, unknown>): Promise<BlobResponse> {
// 注意:经过 http.ts 响应拦截器后,非 JSON(文件流)分支会返回 {data: Blob, headers} 包装体(与原生 resp 形状一致)
// 详见 src/api/core/http.ts 响应拦截器「非 JSON 分支」
const resp = (await this.http.request({
method: 'GET',
url,
params,
responseType: 'blob',
})) as unknown as { data: Blob; headers: Record<string, string> };
return {
blob: resp.data,
headers: resp.headers ?? {},
};
}
/** 统一请求入口:调用共享 http,并把响应 body 解包为 data */ /** 统一请求入口:调用共享 http,并把响应 body 解包为 data */
private call<T>(method: string, url: string, extra: Record<string, unknown> = {}): Promise<T> { private call<T>(method: string, url: string, extra: Record<string, unknown> = {}): Promise<T> {
const config = { method, url, ...extra } as any; const config = { method, url, ...extra } as any;
......
...@@ -129,9 +129,12 @@ const STRICT_VERIFY = (import.meta.env as any).VITE_STRICT_VERIFY === 'true'; ...@@ -129,9 +129,12 @@ const STRICT_VERIFY = (import.meta.env as any).VITE_STRICT_VERIFY === 'true';
http.interceptors.response.use( http.interceptors.response.use(
(response: any) => { (response: any) => {
const ct = (response.headers['content-type'] || '') as string; const ct = (response.headers['content-type'] || '') as string;
// 二进制/文件流(模板下载、导出):服务端不签名,直接返回(§4.3) // 二进制/文件流(模板下载、导出):服务端不签名,直接返回带 headers 的包装体(§4.3)
if (!ct.includes('application/json')) { if (!ct.includes('application/json')) {
return response.data; return {
data: response.data,
headers: response.headers ?? {},
};
} }
// 启动引导接口(拉公钥)自身不参与验签,避免“为验签而先要公钥”的死循环 // 启动引导接口(拉公钥)自身不参与验签,避免“为验签而先要公钥”的死循环
...@@ -172,7 +175,7 @@ http.interceptors.response.use( ...@@ -172,7 +175,7 @@ http.interceptors.response.use(
if (body.code === 401) clearToken(); if (body.code === 401) clearToken();
const err: any = new Error(body.message || '请求失败'); const err: any = new Error(body.message || '请求失败');
err.code = body.code; err.code = body.code;
err.data = body.data; err.data = 'data' in body ? body.data : undefined;
return Promise.reject(err); return Promise.reject(err);
} }
return body; return body;
......
import { isLosslessNumber, parse, toSafeNumberOrThrow } from 'lossless-json';
const MONEY_FIELD =
/^(?:costDecoration|costMonthly|costLabor|costTotal|marketFee\d+Value|sunshine\d+Value)$/;
function isStoreEndpoint(url?: string) {
if (!url) return false;
try {
const path = new URL(url, 'http://store-api.local').pathname;
return /^\/(?:api\/)?store\/(?:approval|listing)(?:\/|$)/.test(path);
} catch {
return false;
}
}
/**
* 仅门店业务响应使用无损解析。ID 与金额保留服务端数字原文;
* 页码、状态码、层级和开关仍为经过安全转换的普通数值。
*/
export function parseStoreResponse(raw: string, url?: string): unknown {
if (!isStoreEndpoint(url)) return JSON.parse(raw) as unknown;
return parse(raw, (key, value) => {
if (!isLosslessNumber(value)) return value;
if (
key === 'id' ||
key.endsWith('Id') ||
key === 'createBy' ||
key === 'updateBy' ||
MONEY_FIELD.test(key)
)
return value.value;
return toSafeNumberOrThrow(value.value);
});
}
...@@ -12,3 +12,4 @@ export * from './modules/org'; ...@@ -12,3 +12,4 @@ export * from './modules/org';
export * from './modules/system'; export * from './modules/system';
export * from './modules/auth'; export * from './modules/auth';
export * from './modules/menu'; export * from './modules/menu';
export * from './modules/user';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { http } from '../../core/http';
import { store } from '../store';
const originalAdapter = http.defaults.adapter;
const approvalRecord = {
listingId: '9007199254740993',
storeName: '测试门店',
merchantNo: 'M-001',
productCategories: ['FILM_ORIGINAL'],
categoryCount: 1,
businessScene: 'AFTER_SALE_MEMBER',
costTotal: '90071992547409.91',
currentLevel: 1,
totalLevel: 2,
submitUserName: '运营人员',
submitTime: '2026-10-09T09:00:00',
pendingHours: 1,
timeoutLevel: 'NORMAL',
status: 'PENDING',
statusLabel: '待审批',
rejectReason: null,
myAction: null,
myActionLabel: null,
handleTime: null,
handleOpinion: null,
actionable: true,
};
const page = { records: [approvalRecord], total: 41, current: 2, size: 20, pages: 3 };
function serve(
handler: (config: InternalAxiosRequestConfig) => {
data: unknown;
headers?: Record<string, string>;
},
) {
const adapter: AxiosAdapter = async (config) => {
const result = handler(config);
return {
config,
data: result.data,
headers: result.headers ?? { 'content-type': 'application/json' },
status: 200,
statusText: 'OK',
};
};
http.defaults.adapter = adapter;
}
function result(data: unknown) {
return JSON.stringify({
code: 200,
message: '操作成功',
data,
timestamp: 1791514515716,
success: true,
});
}
beforeEach(() => {
localStorage.clear();
vi.spyOn(console, 'log').mockImplementation(() => undefined);
});
afterEach(() => {
http.defaults.adapter = originalAdapter;
vi.restoreAllMocks();
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe('store API contract', () => {
it.each([
['todo', '/store/approval/pending'],
['done', '/store/approval/done'],
['mine', '/store/approval/mine'],
] as const)('loads %s with server pagination and untouched monetary values', async (tab, url) => {
serve((config) => {
expect(config.method).toBe('get');
expect(config.url).toBe(url);
expect(config.params).toEqual({ current: 2, size: 20, keyword: 'M-001' });
return { data: result(page) };
});
expect(await store.listApprovals(tab, { current: 2, size: 20, keyword: 'M-001' })).toEqual(
page,
);
});
it('defaults approvals to the pending endpoint', async () => {
serve((config) => {
expect(config.url).toBe('/store/approval/pending');
return { data: result({ records: [], total: 0, current: 1, size: 20, pages: 0 }) };
});
expect((await store.listApprovals()).records).toEqual([]);
});
it('forwards listing filters and server sort keys without adding status or region', async () => {
const params = {
current: 3,
size: 10,
storeName: '门店',
merchantNo: 'M',
businessScene: 'AFTER_SALE_MEMBER',
startDate: '2026-10-01',
endDate: '2026-10-09',
sortField: 'effectiveDate' as const,
sortOrder: 'desc' as const,
};
serve((config) => {
expect(config.url).toBe('/store/listing/page');
expect(config.params).toEqual(params);
return { data: result({ records: [], total: 0, current: 3, size: 10, pages: 0 }) };
});
expect((await store.listStores(params)).current).toBe(3);
});
it('uses listing IDs for detail and history and unwraps column responses', async () => {
const responses: Record<string, unknown> = {
'/store/approval/9007199254740993': {
...approvalRecord,
items: [],
approvalLogs: [],
changeHistory: [],
},
'/store/listing/9007199254740993': {
...approvalRecord,
items: [],
approvalLogs: [],
changeHistory: [],
},
'/store/listing/9007199254740993/changes': [
{ changeId: 4, beforeValue: '0', afterValue: '5' },
],
'/store/listing/column-config': { columns: ['storeName', 'businessScene'] },
};
serve((config) => {
expect(config.method).toBe('get');
expect(responses).toHaveProperty(config.url!);
return { data: result(responses[config.url!]) };
});
expect((await store.getApproval('9007199254740993')).listingId).toBe('9007199254740993');
expect((await store.getStore('9007199254740993')).costTotal).toBe('90071992547409.91');
expect(await store.getChanges('9007199254740993')).toEqual([
{ changeId: '4', beforeValue: '0', afterValue: '5' },
]);
expect(await store.getColumnConfig()).toEqual({ columns: ['storeName', 'businessScene'] });
});
it('sends exact approval action bodies and revokes the record without a body', async () => {
const requests: { url: string; data: unknown }[] = [];
serve((config) => {
expect(config.method).toBe('post');
requests.push({ url: config.url!, data: config.data ? JSON.parse(config.data) : undefined });
return { data: result(null) };
});
await store.passApproval('9007199254740993');
await store.rejectApproval(21, '政策有误');
await store.batchPassApproval([21, 22]);
await store.revokeApproval(21);
await store.saveColumnConfig(['merchantNo', 'storeName']);
expect(requests).toEqual([
{ url: '/store/approval/pass', data: { listingId: '9007199254740993' } },
{ url: '/store/approval/reject', data: { listingId: 21, reason: '政策有误' } },
{ url: '/store/approval/batch-pass', data: { listingIds: [21, 22] } },
{ url: '/store/approval/21/revoke', data: undefined },
{ url: '/store/listing/column-config', data: { columns: ['merchantNo', 'storeName'] } },
]);
});
it('does not submit an empty batch and exposes backend business failures', async () => {
let calls = 0;
serve(() => {
calls += 1;
return { data: JSON.stringify({ code: 10003, message: '无审批权限', data: null }) };
});
await expect(store.batchPassApproval([])).rejects.toThrow();
expect(calls).toBe(0);
await expect(store.passApproval(21)).rejects.toMatchObject({
message: '无审批权限',
code: 10003,
});
});
it('retains existing import upload and submission behavior', async () => {
const file = new File(['example'], 'import.xlsx');
const payload = { taskId: 'task-1', storeName: '门店', businessScene: 'AFTER_SALE_MEMBER' };
serve((config) => {
if (config.url === '/store/import/check') {
expect(config.data.get('file')).toBe(file);
expect(config.data.get('templateVersion')).toBe('V1.0.1');
return { data: result({ taskId: 'task-1' }) };
}
expect(config.url).toBe('/store/import/submit');
expect(JSON.parse(config.data)).toEqual(payload);
return { data: result({ approveId: 'approval-1' }) };
});
expect(await store.uploadImport(file)).toEqual({ taskId: 'task-1' });
expect(await store.submitImport(payload)).toEqual({ approveId: 'approval-1' });
});
});
describe('direct store export', () => {
function watchDownloads() {
const createObjectURL = vi.fn((_blob: Blob) => 'blob:store-export');
const revokeObjectURL = vi.fn();
vi.stubGlobal(
'URL',
class extends URL {
static createObjectURL = createObjectURL;
static revokeObjectURL = revokeObjectURL;
},
);
const downloads: { filename: string; href: string }[] = [];
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
this: HTMLAnchorElement,
) {
downloads.push({ filename: this.download, href: this.href });
});
return { downloads, createObjectURL, revokeObjectURL };
}
it('downloads the binary response with authorization, filters and UTF-8 filename', async () => {
vi.useFakeTimers();
localStorage.setItem('session', JSON.stringify({ token: 'test-token', tokenType: 'Bearer' }));
const watched = watchDownloads();
serve((config) => {
expect(config.url).toBe('/store/listing/export');
expect(config.responseType).toBe('arraybuffer');
expect(config.headers.get('Authorization')).toBe('Bearer test-token');
expect(config.params).toEqual({
businessScene: 'AFTER_SALE_MEMBER',
startDate: '2026-10-01',
});
return {
data: new Uint8Array([80, 75, 3, 4]).buffer,
headers: {
'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'content-disposition':
"attachment; filename*=UTF-8''%E9%97%A8%E5%BA%97%E6%98%8E%E7%BB%86.xlsx",
},
};
});
await store.exportStores({ businessScene: 'AFTER_SALE_MEMBER', startDate: '2026-10-01' });
expect(watched.downloads).toEqual([{ filename: '门店明细.xlsx', href: 'blob:store-export' }]);
expect(watched.createObjectURL.mock.calls[0][0]).toBeInstanceOf(Blob);
expect(watched.createObjectURL.mock.calls[0][0].size).toBe(4);
expect(document.querySelector('a[download]')).toBeNull();
await vi.runAllTimersAsync();
expect(watched.revokeObjectURL).toHaveBeenCalledWith('blob:store-export');
});
it('rejects JSON business errors received as arraybuffer without downloading them', async () => {
const watched = watchDownloads();
serve(() => ({
data: new TextEncoder().encode(
JSON.stringify({ code: 10003, message: '无导出权限', data: null }),
).buffer,
headers: { 'content-type': 'application/json;charset=UTF-8' },
}));
await expect(store.exportStores({})).rejects.toMatchObject({
message: '无导出权限',
code: 10003,
});
expect(watched.downloads).toEqual([]);
expect(watched.createObjectURL).not.toHaveBeenCalled();
});
});
...@@ -3,8 +3,14 @@ ...@@ -3,8 +3,14 @@
import { ApiClient } from '../core/client'; import { ApiClient } from '../core/client';
export interface OrgNode { export interface OrgNode {
id: string; id: number;
name: string; parentId: number;
label: string;
permCode?: string;
nodeType: number;
product?: string;
sort: number;
status: number;
children?: OrgNode[]; children?: OrgNode[];
} }
......
...@@ -10,6 +10,36 @@ export interface RoleItem { ...@@ -10,6 +10,36 @@ export interface RoleItem {
remark?: string; remark?: string;
createTime?: string; createTime?: string;
} }
export interface RolePageParams {
current?: number;
size?: number;
keyword?: string;
isBuiltin?: number;
status?: number;
defaultDataScope?: number;
}
export interface RolePageItem {
roleId: number;
roleName: string;
roleCode: string;
defaultDataScope: number;
accountCount: number;
description?: string;
isBuiltin: number;
status: number;
}
export interface RolePageResult {
records: RolePageItem[];
total: number;
current: number;
size: number;
pages: number;
}
export interface RoleOption {
roleId: number;
roleName: string;
roleCode?: string;
}
export interface PermissionMatrix { export interface PermissionMatrix {
roleId: string; roleId: string;
...@@ -20,6 +50,12 @@ export interface PermissionMatrix { ...@@ -20,6 +50,12 @@ export interface PermissionMatrix {
} }
class Role extends ApiClient { class Role extends ApiClient {
options() {
return this.get<RoleOption[]>('/system/role/options');
}
page(payload: RolePageParams) {
return this.post<RolePageResult>('/system/role/page', payload as Record<string, unknown>);
}
list(params: Record<string, unknown> = {}) { list(params: Record<string, unknown> = {}) {
return this.get<PageResult<RoleItem>>('/store/role/list', params); return this.get<PageResult<RoleItem>>('/store/role/list', params);
} }
......
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* 回退到普通文件名。
}
}
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 payload: 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;
},
],
});
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;
}
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;
}
// 签名规范 / 公钥下发(免签接口,规范 §2/§6) // 签名规范 / 公钥下发(免签接口,规范 §2/§6)
// 继承 ApiClient,共享 http 与 RSA 加签/验签。 // 继承 ApiClient,共享 http 与 RSA 加签/验签。
// 注意:登录相关的 LoginParams / LoginResult / login() 已由 ./auth 统一定义,
// 本模块仅保留签名规范(SignSpec)及 info/spec,避免同名类型在 api 桶导出时歧义。
import { ApiClient } from '../core/client'; import { ApiClient } from '../core/client';
export interface SignSpec { export interface SignSpec {
...@@ -19,6 +21,10 @@ export interface SignSpec { ...@@ -19,6 +21,10 @@ export interface SignSpec {
} }
class System extends ApiClient { class System extends ApiClient {
info() {
return this.get<Record<string, unknown>>('/system/auth/info');
}
spec() { spec() {
return this.get<SignSpec>('/system/sign/spec'); return this.get<SignSpec>('/system/sign/spec');
} }
......
import { ApiClient } from '../core/client';
export interface UserPageParams {
current?: number;
size?: number;
keyword?: string;
mobile?: string;
orgId?: number;
roleId?: number;
status?: number;
}
export interface UserPageItem {
userId: number;
account: string;
name: string;
mobile: string;
email?: string;
orgId?: number;
orgPath?: string;
dataScope?: number;
dataScopeLabel?: string;
status: number;
lastLoginAt?: string;
roleNames?: string[];
roleCodes?: string[];
remark?: string;
}
export interface UserCreatePayload {
account: string;
name: string;
mobile: string;
email?: string;
orgId: number;
dataScope?: number;
status?: number;
roleIds?: number[];
remark?: string;
}
export interface UserUpdatePayload extends Omit<UserCreatePayload, 'account'> {
userId: number;
}
export interface UserPageResult {
records: UserPageItem[];
total: number;
current: number;
size: number;
pages: number;
}
class User extends ApiClient {
page(params: UserPageParams) {
return this.post<UserPageResult>('/system/user/page', params);
}
create(payload: UserCreatePayload) {
return this.post<null>('/system/user/create', payload);
}
update(payload: UserUpdatePayload) {
return this.post<null>('/system/user/update', payload);
}
resetPassword(userId: number, payload: { password: string }) {
return this.post<null>(`/system/user/${userId}/reset-password`, payload);
}
updateStatus(userId: number, payload: { status: number }) {
return this.post<null>(`/system/user/${userId}/status`, payload);
}
}
export const user = new User();
import type { CSSProperties, ReactNode } from 'react';
import type { FormInstance, FormProps } from 'antd';
import { UCascader, UDescriptions, UForm, UFormItem, UInput, USelect, USwitch } from '@uj/ui';
import type { FieldSchema } from '../formSchema';
export interface CombiFormProps<T extends Record<string, unknown>> {
mode: 'form' | 'detail';
fields: FieldSchema<T>[];
form?: FormInstance<T>;
initialValues?: Partial<T>;
onSubmit?: (values: T) => void;
layout?: FormProps['layout'];
formStyle?: CSSProperties;
sectionContentStyle?: CSSProperties;
renderSectionTitle?: (title: string) => ReactNode;
renderControl?: (
field: FieldSchema<T>,
form: FormInstance<T>,
values: T,
) => ReactNode | undefined;
}
export function CombiForm<T extends Record<string, unknown>>({
mode,
fields,
form: externalForm,
initialValues,
onSubmit,
layout,
formStyle,
sectionContentStyle,
renderSectionTitle,
renderControl,
}: CombiFormProps<T>) {
const [innerForm] = UForm.useForm<T>();
const form = externalForm ?? innerForm;
const values = UForm.useWatch([], form) as T | undefined;
const data = (values ?? initialValues ?? {}) as T;
const visible = fields.filter(
(field) => !(typeof field.hidden === 'function' ? field.hidden(data) : field.hidden),
);
if (mode === 'detail')
return (
<UDescriptions
column={1}
items={visible.map((field) => ({
key: field.name,
label: field.label,
children: field.render
? field.render(data[field.name], data)
: String(data[field.name] ?? '—'),
}))}
/>
);
const sections = visible.reduce<{ title?: string; fields: FieldSchema<T>[] }[]>(
(groups, field) => {
const last = groups.at(-1);
if (last && last.title === field.section) last.fields.push(field);
else groups.push({ title: field.section, fields: [field] });
return groups;
},
[],
);
const defaultControl = (field: FieldSchema<T>) => {
if (field.type === 'cascader')
return <UCascader options={field.options} style={{ width: '100%' }} />;
if (field.type === 'select' || field.type === 'selectMultiple')
return (
<USelect
options={field.options}
mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
style={{ width: '100%' }}
/>
);
if (field.type === 'switch') return <USwitch />;
if (field.type === 'textarea') return <UInput.TextArea />;
return <UInput />;
};
return (
<UForm
form={form}
initialValues={initialValues}
layout={layout}
style={formStyle}
onFinish={(next) => onSubmit?.(next as T)}
>
{sections.map((section, sectionIndex) => (
<section key={`${section.title ?? 'default'}-${sectionIndex}`}>
{section.title ? renderSectionTitle?.(section.title) : null}
<div style={sectionContentStyle}>
{section.fields.map((field) => (
<UFormItem
key={field.name}
name={field.name as string}
label={field.label}
rules={field.rules}
style={field.itemStyle}
>
{renderControl?.(field, form, data) ?? defaultControl(field)}
</UFormItem>
))}
</div>
</section>
))}
</UForm>
);
}
import type { ReactNode } from 'react';
import { UModal } from '@uj/ui';
export interface ConfirmModalProps {
open: boolean;
content: ReactNode;
title?: ReactNode;
width?: number;
okText?: string;
cancelText?: string;
confirmLoading?: boolean;
onCancel: () => void;
onConfirm: () => void;
}
/** 通用二次确认弹窗,业务页面负责传入提示内容和确认动作。 */
export function ConfirmModal({
open,
content,
title = '提示',
width = 420,
okText = '确定',
cancelText = '取消',
confirmLoading,
onCancel,
onConfirm,
}: ConfirmModalProps) {
return (
<UModal
open={open}
title={title}
width={width}
okText={okText}
cancelText={cancelText}
confirmLoading={confirmLoading}
onCancel={onCancel}
onOk={onConfirm}
>
<div style={{ padding: '8px 0 24px' }}>{content}</div>
</UModal>
);
}
import type { ReactNode } from 'react';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { UButton, UTable, FillTable } from '@uj/ui';
import { PermButton } from '@/access';
import type { ActionSchema } from '../formSchema';
/** 列表分页统一默认每页条数。 */
export const DEFAULT_PAGE_SIZE = 10;
/** 列表行操作配置;配置 permission 时自动使用权限按钮。 */
export interface RowActionSchema<T> extends Omit<ActionSchema, 'danger' | 'label' | 'onClick'> {
/** 可按当前行动态生成操作文案。 */
label: ReactNode | ((record: T) => ReactNode);
/** 可按当前行动态决定是否使用警示颜色。 */
danger?: boolean | ((record: T) => boolean);
onClick: (record: T) => void;
visible?: (record: T) => boolean;
}
export interface DataTableProps<T> extends Pick<
TableProps<T>,
| 'dataSource'
| 'loading'
| 'rowKey'
| 'rowSelection'
| 'onChange'
| 'scroll'
| 'size'
| 'locale'
| 'className'
> {
columns: ColumnsType<T>;
showIndex?: boolean;
pagination?:
| {
current: number;
/** 每页条数,默认 10。 */
pageSize?: number;
total: number;
onChange: (page: number, pageSize: number) => void;
/** 是否展示每页条数选择,默认展示。 */
showSizeChanger?: boolean;
/** 每页条数选择项,默认 10 / 20 / 50 / 100。 */
pageSizeOptions?: (string | number)[];
/** 默认展示总数;false 隐藏,也可传入自定义文案。 */
showTotal?: boolean | ((total: number, range: [number, number]) => ReactNode);
}
| false;
actions?: ActionSchema[];
/** 行内操作。配置 permission 时自动按权限显示,未配置则使用普通按钮。 */
rowActions?: RowActionSchema<T>[];
/** 行内操作列标题,默认“操作”。 */
actionColumnTitle?: ReactNode;
/** 行内操作列宽度。 */
actionColumnWidth?: number;
actionColumnFixed?: 'left' | 'right';
toolbarClassName?: string;
toolbarTitle?: ReactNode;
fillHeight?: boolean;
/** 接口返回的分页对象;传入后自动从 recordsKey 读取列表数据。 */
pageData?: Record<string, unknown>;
/** 分页对象中的列表字段名,默认 records。 */
recordsKey?: string;
/** 分页对象中的总数、页码和每页条数字段名。 */
totalKey?: string;
currentKey?: string;
sizeKey?: string;
}
export function DataTable<T extends object>({
columns,
showIndex,
pagination,
actions,
rowActions,
actionColumnTitle = '操作',
actionColumnWidth,
actionColumnFixed,
toolbarClassName,
toolbarTitle,
fillHeight = false,
pageData,
recordsKey = 'records',
totalKey = 'total',
currentKey = 'current',
sizeKey = 'size',
...props
}: DataTableProps<T>) {
const records = pageData?.[recordsKey];
const dataSource = Array.isArray(records) ? (records as T[]) : props.dataSource;
const resolvedPagination = pagination
? {
...pagination,
current: Number(pageData?.[currentKey] ?? pagination.current),
pageSize: Number(pageData?.[sizeKey] ?? pagination.pageSize ?? DEFAULT_PAGE_SIZE),
total: Number(pageData?.[totalKey] ?? pagination.total),
}
: pagination;
const page = resolvedPagination || undefined;
const renderActionButton = (
action: Omit<ActionSchema, 'onClick'>,
onClick: () => void,
key: string,
isRowAction = false,
) => {
const buttonProps = {
danger: action.danger,
disabled: action.disabled,
onClick,
type: action.type ?? (isRowAction ? ('link' as const) : undefined),
};
return action.permission ? (
<PermButton key={key} permission={action.permission} {...buttonProps}>
{action.label}
</PermButton>
) : (
<UButton key={key} {...buttonProps}>
{action.label}
</UButton>
);
};
const actionColumn: ColumnsType<T>[number] | undefined = rowActions?.length
? {
title: actionColumnTitle,
key: '__actions',
width: actionColumnWidth,
fixed: actionColumnFixed,
render: (_: unknown, record: T) =>
rowActions
.filter((action) => action.visible?.(record) ?? true)
.map((action, index) => {
const label =
typeof action.label === 'function' ? action.label(record) : action.label;
const danger =
typeof action.danger === 'function' ? action.danger(record) : action.danger;
return renderActionButton(
{ ...action, danger, label },
() => action.onClick(record),
`row-action-${index}`,
true,
);
}),
}
: undefined;
const tableColumns = showIndex
? [
{
title: '序号',
key: '__index',
width: 72,
render: (_: unknown, _row: T, index: number) =>
((page?.current ?? 1) - 1) * (page?.pageSize ?? 0) + index + 1,
},
...columns,
...(actionColumn ? [actionColumn] : []),
]
: [...columns, ...(actionColumn ? [actionColumn] : [])];
const TableComponent = fillHeight ? FillTable<T> : UTable<T>;
return (
<>
{toolbarTitle || actions?.length ? (
<div
className={toolbarClassName}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
flexWrap: 'wrap',
gap: 12,
padding: 16,
}}
>
<div>{toolbarTitle}</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
{actions?.map((action, index) =>
renderActionButton(action, action.onClick, `toolbar-action-${index}`),
)}
</div>
</div>
) : null}
<TableComponent
{...props}
dataSource={dataSource}
columns={tableColumns}
pagination={
resolvedPagination === false
? false
: resolvedPagination && {
...resolvedPagination,
current: resolvedPagination.current,
pageSize: resolvedPagination.pageSize,
total: resolvedPagination.total,
onChange: resolvedPagination.onChange,
showSizeChanger: resolvedPagination.showSizeChanger ?? true,
pageSizeOptions: resolvedPagination.pageSizeOptions ?? [10, 20, 50, 100],
showTotal:
typeof resolvedPagination.showTotal === 'function'
? resolvedPagination.showTotal
: resolvedPagination.showTotal === false
? undefined
: (total: number) => `共 ${total} 条`,
}
}
/>
</>
);
}
import { UCascader, UButton, UDatePicker, UForm, UFormItem, UInput, URadio, USelect } from '@uj/ui';
import type { FieldSchema } from '../formSchema';
import { DEFAULT_PAGE_SIZE } from '../DataTable';
export interface SearchPagination {
current: number;
size: number;
}
export interface SearchFormProps<T extends Record<string, unknown>> {
fields: FieldSchema<T>[];
initialValues?: Partial<T>;
/** 查询或重置时传出的分页参数,默认第 1 页、每页 10 条。 */
pagination?: Partial<SearchPagination>;
onSearch: (values: T, pagination: SearchPagination) => void;
onReset?: (values: Partial<T>, pagination: SearchPagination) => void;
layout?: 'inline' | 'vertical';
className?: string;
}
export function SearchForm<T extends Record<string, unknown>>({
fields,
initialValues,
pagination,
onSearch,
onReset,
layout = 'vertical',
className,
}: SearchFormProps<T>) {
const [form] = UForm.useForm();
const searchPagination: SearchPagination = {
current: pagination?.current ?? 1,
size: pagination?.size ?? DEFAULT_PAGE_SIZE,
};
const control = (field: FieldSchema<T>) => {
const common = {
disabled: typeof field.disabled === 'boolean' ? field.disabled : false,
placeholder: field.placeholder,
size: 'small' as const,
};
const width = field.width ?? '100%';
if (field.type === 'select' || field.type === 'selectMultiple')
return (
<USelect
{...common}
allowClear={false}
style={{ width }}
options={field.options}
mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
/>
);
if (field.type === 'cascader')
return <UCascader {...common} style={{ width }} options={field.options} allowClear={false} />;
if (field.type === 'date') return <UDatePicker {...common} style={{ width }} />;
if (field.type === 'dateRange')
return (
<UDatePicker.RangePicker disabled={common.disabled} size={common.size} style={{ width }} />
);
if (field.type === 'radio') return <URadio.Group {...common} options={field.options} />;
return field.type === 'textarea' ? (
<UInput.TextArea {...common} style={{ width }} />
) : (
<UInput {...common} style={{ width }} />
);
};
return (
<UForm
form={form}
initialValues={initialValues}
layout={layout === 'inline' ? 'vertical' : layout}
className={className}
style={searchFormStyle}
onFinish={(values) => onSearch(values as T, searchPagination)}
>
{fields.map((field) => (
<UFormItem
key={field.name}
name={field.name as string}
label={field.label}
style={{ marginBottom: 0, minWidth: 0 }}
>
{control(field)}
</UFormItem>
))}
<UFormItem style={searchActionsStyle}>
<UButton
type="default"
size="small"
onClick={() => {
const resetValues = fields.reduce<Record<string, unknown>>((values, field) => {
const initialValue = initialValues?.[field.name];
values[field.name] =
initialValue ??
(field.type === 'input' || field.type === 'textarea' ? '' : undefined);
return values;
}, {});
form.setFieldsValue(resetValues);
onReset?.(initialValues ?? {}, searchPagination);
}}
>
重置
</UButton>
<UButton htmlType="submit" size="small" style={{ marginLeft: 8 }}>
查询
</UButton>
</UFormItem>
</UForm>
);
}
const searchFormStyle = {
columnGap: 16,
display: 'grid',
gridTemplateColumns: 'repeat(4, minmax(0, 1fr))',
rowGap: 12,
};
const searchActionsStyle = {
display: 'flex',
gridColumn: '1 / -1',
justifyContent: 'flex-end',
marginBottom: 0,
};
...@@ -2,8 +2,8 @@ import { UTag } from '@uj/ui'; ...@@ -2,8 +2,8 @@ import { UTag } from '@uj/ui';
import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus'; import { STORE_STATUS, type StoreStatus } from '@/config/storeStatus';
/** 门店状态徽标(对应 PRD §4.2 状态规范) */ /** 门店状态徽标(对应 PRD §4.2 状态规范) */
export function StatusTag({ status }: { status: StoreStatus }) { export function StatusTag({ status }: { status?: StoreStatus | string | null }) {
const meta = STORE_STATUS[status]; const meta = STORE_STATUS[status as StoreStatus] ?? { label: status || '—', color: 'default' };
return ( return (
<UTag color={meta.color} style={{ marginInlineEnd: 0, borderRadius: 6 }}> <UTag color={meta.color} style={{ marginInlineEnd: 0, borderRadius: 6 }}>
{meta.label} {meta.label}
......
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { SearchForm } from '../SearchForm';
describe('SearchForm', () => {
it('重置清空未提供初始值的查询字段', () => {
render(
<SearchForm
fields={[{ name: 'keyword', label: '关键词', type: 'input' }]}
initialValues={{}}
onSearch={vi.fn()}
/>,
);
const input = screen.getByLabelText('关键词');
fireEvent.change(input, { target: { value: '旧关键词' } });
fireEvent.click(screen.getByRole('button', { name: /重\s*置/ }));
expect(screen.getByLabelText('关键词')).toHaveValue('');
});
it('重置后恢复初始值并通知页面', () => {
const onReset = vi.fn();
render(
<SearchForm
fields={[{ name: 'name', label: '名称', type: 'input' }]}
initialValues={{ name: '初始值' }}
onSearch={vi.fn()}
onReset={onReset}
/>,
);
const input = screen.getByLabelText('名称');
fireEvent.change(input, { target: { value: '已修改' } });
fireEvent.click(screen.getByRole('button', { name: /重\s*置/ }));
expect(screen.getByLabelText('名称')).toHaveValue('初始值');
expect(onReset).toHaveBeenCalledWith({ name: '初始值' }, { current: 1, size: 10 });
});
it('查询时传出页面配置的分页参数', async () => {
const onSearch = vi.fn();
const { container } = render(
<SearchForm
fields={[{ name: 'keyword', label: '关键字', type: 'input' }]}
initialValues={{}}
pagination={{ current: 1, size: 50 }}
onSearch={onSearch}
/>,
);
fireEvent.click(within(container).getByRole('button', { name: /查\s*询/ }));
await waitFor(() => {
expect(onSearch).toHaveBeenCalledWith({ keyword: undefined }, { current: 1, size: 50 });
});
});
});
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { AccessProvider, PermButton, P, saveUserInfo, useAccess } from '@/access';
import { DataTable } from '../DataTable';
describe('门店操作权限', () => {
it('表格沿用后端权限码显示审核与导出,无打回权限不显示打回', () => {
saveUserInfo({ permCodes: ['store:approve:pass', 'store:list:export'] });
render(
<AccessProvider>
<DataTable
columns={[{ title: '门店', dataIndex: 'name' }]}
rowKey="id"
dataSource={[{ id: '1', name: '门店A' }]}
actions={[{ label: '导出', permission: P.STORE_LISTING_EXPORT, onClick: vi.fn() }]}
rowActions={[
{ label: '审核', permission: P.STORE_APPROVE_AUDIT, onClick: vi.fn() },
{ label: '打回', permission: P.STORE_APPROVE_REJECT, onClick: vi.fn() },
]}
/>
</AccessProvider>,
);
expect(screen.getByRole('button', { name: '审核' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /导\s*出/ })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '打回' })).not.toBeInTheDocument();
});
it('业务 disabled=false 不能覆盖无权限禁用', () => {
const action = vi.fn();
render(
<AccessProvider>
<PermButton
permission="store:approve:pass"
fallback="disabled"
disabled={false}
onClick={action}
>
审批通过
</PermButton>
</AccessProvider>,
);
const button = screen.getByRole('button', { name: '审批通过' });
expect(button).toBeDisabled();
fireEvent.click(button);
expect(action).not.toHaveBeenCalled();
});
it('门店菜单以真实权限为准,刷新后不自动放大成管理员权限', () => {
saveUserInfo({ permCodes: ['store:approve:view'] });
function Probe() {
const { can } = useAccess();
return (
<>
{can('store.approve') && <span>审批菜单</span>}
{can('store.listing') && <span>门店菜单</span>}
</>
);
}
render(
<AccessProvider>
<Probe />
</AccessProvider>,
);
expect(screen.getByText('审批菜单')).toBeInTheDocument();
expect(screen.queryByText('门店菜单')).not.toBeInTheDocument();
});
});
import { render, screen } from '@testing-library/react';
import { UDatePicker, UDescriptions, URadio, USwitch } from '@uj/ui';
import { describe, expect, it } from 'vitest';
describe('统一表单控件', () => {
it('提供日期、单选、开关与详情展示控件', () => {
render(
<>
<label htmlFor="date">日期</label>
<UDatePicker id="date" />
<URadio.Group aria-label="状态" options={[{ label: '启用', value: 'enabled' }]} />
<USwitch aria-label="开关" />
<UDescriptions items={[{ key: 'name', label: '名称', children: '门店 A' }]} />
</>,
);
expect(screen.getByLabelText('日期')).toBeInTheDocument();
expect(screen.getByLabelText('状态')).toBeInTheDocument();
expect(screen.getByLabelText('开关')).toBeInTheDocument();
expect(screen.getByText('门店 A')).toBeInTheDocument();
});
});
import type { CSSProperties, ReactNode } from 'react';
import type { ButtonProps } from 'antd';
import type { Rule } from 'antd/es/form';
export type FieldType =
| 'input'
| 'textarea'
| 'select'
| 'selectMultiple'
| 'cascader'
| 'date'
| 'dateRange'
| 'radio'
| 'switch';
export interface FieldOption {
label: string;
value: string | number;
children?: FieldOption[];
}
export interface FieldSchema<T extends Record<string, unknown> = Record<string, unknown>> {
name: keyof T & string;
label: ReactNode;
type: FieldType;
placeholder?: string;
width?: number | string;
options?: FieldOption[];
rules?: Rule[];
section?: string;
itemStyle?: CSSProperties;
hidden?: boolean | ((values: T) => boolean);
disabled?: boolean | ((values: T) => boolean);
render?: (value: unknown, values: T) => ReactNode;
}
export interface ActionSchema {
label: ReactNode;
type?: ButtonProps['type'];
onClick: () => void;
permission?: string;
danger?: boolean;
disabled?: boolean;
}
export { Logo } from './Logo'; export { Logo } from './Logo';
export { StatusTag } from './StatusTag'; export { StatusTag } from './StatusTag';
export { default as PagePlaceholder } from './PagePlaceholder'; export { default as PagePlaceholder } from './PagePlaceholder';
export { SearchForm } from './SearchForm';
export type { SearchFormProps, SearchPagination } from './SearchForm';
export type { ActionSchema, FieldOption, FieldSchema, FieldType } from './formSchema';
export { DataTable, DEFAULT_PAGE_SIZE } from './DataTable';
export type { DataTableProps, RowActionSchema } from './DataTable';
export { ConfirmModal } from './ConfirmModal';
export type { ConfirmModalProps } from './ConfirmModal';
export { CombiForm } from './CombiForm';
export type { CombiFormProps } from './CombiForm';
import type { FieldOption } from '@/components';
/** 系统通用的数据域选项与展示文案。 */
export const dataScopeOptions = [
{ label: '全部数据', value: 1 },
{ label: '本部门及下级', value: 2 },
{ label: '本部门', value: 3 },
{ label: '仅本人', value: 4 },
] satisfies FieldOption[];
const dataScopeLabels: Record<number, string> = Object.fromEntries(
dataScopeOptions.map((item) => [item.value, item.label]),
);
export function getDataScopeLabel(scope: number | undefined, fallback = '—'): string {
return scope === undefined ? fallback : (dataScopeLabels[scope] ?? fallback);
}
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { StoreListingDetail } from '@/api';
import { STORE_DICTIONARIES, type StoreDictionaries } from './dictionaries';
import { StoreDetailDrawer } from './StoreDetailDrawer';
afterEach(cleanup);
// Swagger-shaped fixtures: live endpoints contain no records, so these are not real money samples.
const spec: StoreDictionaries = {
businessScenes: [
{ value: 'AFTER_SALES', label: '售后会员权益升级' },
{ value: 'PRE_SALES', label: '售前延保' },
],
productCategories: [
{ value: 'FILM', label: '太阳膜-原厂' },
{ value: 'WRAP', label: '车衣-原厂' },
],
calcModes: [{ value: 'CATEGORY', label: '按品类计算' }],
calcWays: [
{ value: 'INCOME', label: '收入' },
{ value: 'FIXED', label: '固定' },
],
onlinePointFlags: [
{ value: '1', label: '是' },
{ value: '0', label: '否' },
],
};
const detail: StoreListingDetail = {
listingId: '9007199254740993',
storeName: '当前门店',
merchantNo: 'SQ001',
businessScene: 'AFTER_SALES',
status: 'PENDING',
currentLevel: 1,
totalLevel: 2,
submitUserName: '运营甲',
submitTime: '2026-10-09T10:00:00',
costDecoration: '500',
costMonthly: '500',
costLabor: '500',
costTotal: '90071992547409.91',
items: [
{
itemId: '1',
productCategory: 'FILM',
marketFee1CalcMode: 'CATEGORY',
marketFee1CalcWay: 'INCOME',
marketFee1Value: '5',
marketFee1Unit: 'RATIO',
sunshine1OnlinePoint: 0,
sunshine1Value: '0',
sunshine1Unit: 'RATIO',
},
{
itemId: '2',
productCategory: 'WRAP',
marketFee1CalcMode: 'CATEGORY',
marketFee1CalcWay: 'FIXED',
marketFee1Value: '123.45',
marketFee1Unit: 'AMOUNT',
},
...Array.from({ length: 9 }, (_, index) => ({
itemId: `extra-${index}`,
productCategory: `分类${index}`,
})),
],
approvalLogs: [
{
logId: '1',
action: 'REJECT',
operatorName: '商务甲',
operatorRole: 'YJ_BUSINESS_MGR',
preStatus: 'PENDING',
postStatus: 'REJECTED',
reason: '请核对政策',
operateTime: '2026-10-09T11:00:00',
operateIp: '192.0.2.1',
},
],
changeHistory: [
{
changeId: 'old',
versionNo: 1,
changeField: '运营成本',
beforeValue: '0',
afterValue: '100',
changeUserName: '运营甲',
effectiveTime: '2026-09-01T10:00:00',
},
{
changeId: 'new',
versionNo: 2,
changeField: '管理层市场费',
beforeValue: '3%',
afterValue: '5%',
changeUserName: '运营乙',
effectiveTime: '2026-10-01T10:00:00',
},
],
};
function show(overrides: Partial<React.ComponentProps<typeof StoreDetailDrawer>> = {}) {
return render(
<StoreDetailDrawer
open
mode="approval"
detail={detail}
spec={spec}
onClose={() => undefined}
{...overrides}
/>,
);
}
describe('store detail presentation', () => {
it('uses local dictionaries for real Chinese policy values and numeric point flags', () => {
show({
spec: STORE_DICTIONARIES,
detail: {
...detail,
businessScene: '精品升级',
items: [
{
productCategory: '车辆美容',
sunshine1CalcMode: '按品类计算',
sunshine1CalcWay: '收入',
sunshine1OnlinePoint: 1,
sunshine2CalcMode: '按整单计算',
sunshine2CalcWay: '毛利',
sunshine2OnlinePoint: 0,
},
{ productCategory: '后续新增分类' },
],
},
});
expect(screen.getByText('精品升级')).toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: '一线阳光激励' }));
const panel = within(screen.getByRole('tabpanel', { name: '一线阳光激励' }));
for (const label of [
'车辆美容',
'后续新增分类',
'按品类计算',
'按整单计算',
'收入',
'毛利',
'是',
'否',
]) {
expect(panel.getByText(label)).toBeInTheDocument();
}
});
it('shows only the current scene, every category and the policy value unit', () => {
show();
expect(screen.getByText('当前门店')).toBeInTheDocument();
expect(screen.getByText('售后会员权益升级')).toBeInTheDocument();
expect(screen.queryByText('售前延保')).not.toBeInTheDocument();
expect(screen.getByText('分类8')).toBeInTheDocument();
expect(screen.getByText('5%')).toBeInTheDocument();
expect(screen.getByText('¥123.45')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: '通过' })).not.toBeInTheDocument();
});
it('displays the authoritative total even when the cost components differ', () => {
show();
fireEvent.click(screen.getByRole('tab', { name: '运营成本' }));
expect(screen.getAllByText('¥90,071,992,547,409.91').length).toBeGreaterThan(0);
expect(screen.queryByText('¥1,500.00')).not.toBeInTheDocument();
expect(screen.getAllByText('¥500.00')).toHaveLength(3);
});
it('renders zero point flags and zero policy values without treating them as missing', () => {
show();
fireEvent.click(screen.getByRole('tab', { name: '一线阳光激励' }));
expect(screen.getByText('否')).toBeInTheDocument();
expect(screen.getByText('0%')).toBeInTheDocument();
});
it('shows two approval stages by default and the returned single finance stage', () => {
const view = show({ detail: { ...detail, totalLevel: undefined } });
expect(within(screen.getByLabelText('审批流程')).getByText('优加商务经理')).toBeInTheDocument();
view.rerender(
<StoreDetailDrawer
open
mode="approval"
detail={{ ...detail, totalLevel: 1 }}
onClose={() => undefined}
/>,
);
const flow = within(screen.getByLabelText('审批流程'));
expect(flow.queryByText('优加商务经理')).not.toBeInTheDocument();
expect(flow.getByText('优加财务经理')).toBeInTheDocument();
});
it('does not describe a rejected record as awaiting approval and preserves the audit reason', () => {
show({ detail: { ...detail, status: 'REJECTED', rejectReason: '请核对政策' } });
expect(
within(screen.getByLabelText('审批流程')).queryByText('当前审批节点'),
).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: '审批留痕' }));
expect(screen.getByText('商务甲')).toBeInTheDocument();
expect(screen.getAllByText('请核对政策').length).toBeGreaterThan(0);
expect(screen.getByText(/192\.0\.2\.1/)).toBeInTheDocument();
});
it('opens listing history directly and shows newest changes first', () => {
show({ mode: 'listing', initialTab: 'history', detail: { ...detail, status: 'APPROVED' } });
expect(screen.getByRole('tab', { name: '变更历史' })).toHaveAttribute('aria-selected', 'true');
const panel = screen.getByRole('tabpanel');
expect(panel.textContent?.indexOf('管理层市场费')).toBeLessThan(
panel.textContent?.indexOf('运营成本') ?? -1,
);
expect(within(panel).getByText('3% → 5%')).toBeInTheDocument();
expect(screen.queryByRole('tab', { name: '审批留痕' })).not.toBeInTheDocument();
});
it('renders the batch-pass audit action as a readable business action', () => {
show({ detail: { ...detail, approvalLogs: [{ logId: 'batch', action: 'BATCH_PASS' }] } });
fireEvent.click(screen.getByRole('tab', { name: '审批留痕' }));
expect(screen.getByText('批量通过')).toBeInTheDocument();
expect(screen.queryByText('BATCH_PASS')).not.toBeInTheDocument();
});
it.each(['approval', 'listing'] as const)(
'uses approveTime for the %s effective date when effectiveTime is absent',
(mode) => {
show({ mode, detail: { ...detail, status: 'APPROVED', approveTime: '2026-10-09T12:30:45' } });
expect(screen.getByText('2026-10-09 12:30:45')).toBeInTheDocument();
},
);
it('keeps effectiveTime authoritative when both timestamp fields are present', () => {
show({
mode: 'listing',
detail: {
...detail,
status: 'APPROVED',
effectiveTime: '2026-10-09T12:45:00',
approveTime: '2026-10-09T12:30:45',
},
});
expect(screen.getByText('2026-10-09 12:45:00')).toBeInTheDocument();
expect(screen.queryByText('2026-10-09 12:30:45')).not.toBeInTheDocument();
});
it('replaces stale detail with a retryable error', () => {
const retry = vi.fn();
show({ error: new Error('请求失败'), onRetry: retry });
expect(screen.queryByText('太阳膜-原厂')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /重\s*试/ }));
expect(retry).toHaveBeenCalledOnce();
});
});
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 { describe, expect, it } from 'vitest';
import { dictionaryLabel, formatDateTime, formatMoney, formatPolicyValue } from './formatters';
// Contract fixtures, not production amount samples: the API currently has no store records.
describe('store numeric display', () => {
it.each([
[0, '¥0.00'],
['0.00', '¥0.00'],
['-12.5', '¥-12.50'],
['12345678901234567890.123456', '¥12,345,678,901,234,567,890.123456'],
['1,234.50', '¥1,234.50'],
['1.234567890123456789e5', '¥123,456.7890123456789'],
['1e-7', '¥0.0000001'],
['1.2300e2', '¥123.00'],
['-0', '¥0.00'],
])('preserves exact amount %s instead of rounding or coercing it', (value, expected) => {
expect(formatMoney(value)).toBe(expected);
});
it.each([
undefined,
null,
'',
' ',
'abc',
'1,23',
'NaN',
'Infinity',
Infinity,
NaN,
{},
'1e999999999',
])('does not turn missing or invalid %s into zero', (value) => {
expect(formatMoney(value)).toBe('—');
});
it('uses the authoritative policy unit, preserving zero and unknown units', () => {
expect(formatPolicyValue('5', 'RATIO')).toBe('5%');
expect(formatPolicyValue('0', 'RATIO')).toBe('0%');
expect(formatPolicyValue('12.34', 'AMOUNT')).toBe('¥12.34');
expect(formatPolicyValue('5', 'FUTURE_UNIT')).toBe('5');
expect(formatPolicyValue('0.333333333333333333', 'RATIO')).toBe('0.333333333333333333%');
expect(formatPolicyValue('', 'RATIO')).toBe('—');
});
});
describe('store labels', () => {
it('resolves known dictionaries without hiding unknown or zero values', () => {
expect(dictionaryLabel([{ value: '0', label: '关闭' }], 0)).toBe('关闭');
expect(dictionaryLabel([], 'NEW_SCENE')).toBe('NEW_SCENE');
expect(dictionaryLabel(undefined, '')).toBe('—');
});
it('formats server date strings without changing their timezone', () => {
expect(formatDateTime('2026-10-09T12:30:45')).toBe('2026-10-09 12:30:45');
expect(formatDateTime('2026-10-09 12:30:45')).toBe('2026-10-09 12:30:45');
expect(formatDateTime(null)).toBe('—');
});
});
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;
}
.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;
}
}
...@@ -37,19 +37,7 @@ body { ...@@ -37,19 +37,7 @@ body {
sans-serif; sans-serif;
} }
/* 彻底关掉 antd Table 内层容器的横向滚动条(亚像素/列宽导致)。 /* 横向滚动交由表格的 scroll 属性控制,避免窄屏裁掉政策明细与操作列。 */
必须用 !important 覆盖 antd 运行时(CSS-in-JS)注入的 overflow-x:auto。 */
.ant-table,
.ant-table-container,
.ant-table-content {
overflow-x: hidden !important;
}
/* 表体纵向滚动条只在内容超出时出现(覆盖 antd 默认的 overflow-y:scroll 常驻滚动条) */
.ant-table-body {
overflow-x: hidden !important;
overflow-y: auto !important;
}
/* Sider 锁定溢出,避免菜单 hover 背景/折叠 tooltip 产生横向滚动条 */ /* Sider 锁定溢出,避免菜单 hover 背景/折叠 tooltip 产生横向滚动条 */
.ant-layout-sider { .ant-layout-sider {
......
...@@ -19,7 +19,6 @@ import { ...@@ -19,7 +19,6 @@ import {
import { useAccess, buildMenus, type MenuGroupDef } from '@/access'; import { useAccess, buildMenus, type MenuGroupDef } from '@/access';
import { useAppStore } from '@/store/useAppStore'; import { useAppStore } from '@/store/useAppStore';
import { auth, menu as menuApi } from '@/api'; import { auth, menu as menuApi } from '@/api';
import { brandGradient } from '@/theme/themeConfig';
import { Logo } from '@/components/Logo'; import { Logo } from '@/components/Logo';
import { Skeleton } from '@uj/ui'; import { Skeleton } from '@uj/ui';
import menuJson from '@/config/menu.json'; import menuJson from '@/config/menu.json';
...@@ -166,7 +165,6 @@ export default function BasicLayout() { ...@@ -166,7 +165,6 @@ export default function BasicLayout() {
width={232} width={232}
collapsedWidth={68} collapsedWidth={68}
className="uj-sider" className="uj-sider"
style={{ background: brandGradient }}
> >
{/* 品牌区 */} {/* 品牌区 */}
<div className={`uj-sider-brand${collapsed ? ' is-collapsed' : ''}`}> <div className={`uj-sider-brand${collapsed ? ' is-collapsed' : ''}`}>
......
import { useEffect } from 'react';
import { message } from 'antd';
import { useMutation } from '@tanstack/react-query';
import { UButton, UCascader, UForm, UInput, UModal, USelect } from '@uj/ui';
import { user, type OrgNode, type RoleOption, type UserPageItem } from '@/api';
import { CombiForm, type FieldSchema } from '@/components';
import { dataScopeOptions } from '@/constants/dataScope';
import { findOrgPath, toOrgCascaderOptions } from '../tools/account';
interface AccountFormValues extends Record<string, unknown> {
account: string;
name: string;
mobile: string;
email?: string;
orgPath: number[];
dataScope?: number | '';
roleIds: number[];
}
export interface AccountModalProps {
open: boolean;
account?: UserPageItem;
orgTree: OrgNode[];
roleOptions: RoleOption[];
onCancel: () => void;
onSuccess: () => void;
}
export function AccountModal({
open,
account,
orgTree,
roleOptions,
onCancel,
onSuccess,
}: AccountModalProps) {
const [form] = UForm.useForm<AccountFormValues>();
const selectedRoleIds = UForm.useWatch('roleIds', form) ?? [];
const isEdit = Boolean(account);
const saveMutation = useMutation({
mutationFn: (values: AccountFormValues) => {
const orgId = values.orgPath.at(-1);
const payload = {
name: values.name.trim(),
mobile: values.mobile,
email: values.email?.trim() || undefined,
orgId: orgId as number,
dataScope: values.dataScope === '' ? undefined : values.dataScope,
roleIds: values.roleIds,
status: account?.status ?? 1,
};
return account
? user.update({ ...payload, userId: account.userId })
: user.create({ ...payload, account: values.account.trim() });
},
onSuccess: () => {
void message.success(isEdit ? '账号已保存' : '账号已创建');
onSuccess();
},
onError: (error: Error) => {
void message.error(error.message || '保存失败,请稍后重试');
},
});
useEffect(() => {
if (!open) return;
const selectedRoleIds = account?.roleCodes?.length
? roleOptions
.filter((item) => item.roleCode && account.roleCodes?.includes(item.roleCode))
.map((item) => item.roleId)
: [];
form.setFieldsValue({
account: account?.account ?? '',
name: account?.name ?? '',
mobile: account?.mobile ?? '',
email: account?.email ?? '',
orgPath: findOrgPath(orgTree, account?.orgId),
dataScope: account?.dataScope ?? '',
roleIds: selectedRoleIds,
});
}, [account, form, open, orgTree, roleOptions]);
const fields: FieldSchema<AccountFormValues>[] = [
{
name: 'account',
label: '账号',
type: 'input',
section: '基本信息',
rules: [
{ required: true, message: '请输入账号' },
{ min: 1, max: 20, message: '账号长度为 1-20 个字符' },
],
},
{
name: 'name',
label: '姓名',
type: 'input',
section: '基本信息',
rules: [
{ required: true, message: '请输入姓名' },
{ min: 1, max: 20, message: '姓名长度为 1-20 个字符' },
],
},
{
name: 'mobile',
label: '手机号',
type: 'input',
section: '基本信息',
rules: [
{ required: true, message: '请输入手机号' },
{ pattern: /^1\d{10}$/, message: '请输入正确的 11 位手机号' },
],
},
{
name: 'email',
label: '邮箱',
type: 'input',
section: '基本信息',
rules: [{ type: 'email', message: '请输入正确的邮箱地址' }],
},
{
name: 'orgPath',
label: '所属组织',
type: 'cascader',
section: '组织归属',
rules: [{ required: true, message: '请选择所属组织' }],
},
{
name: 'dataScope',
label: '数据域',
type: 'select',
section: '组织归属',
options: dataScopeOptions,
},
{
name: 'roleIds',
label: '角色分配',
type: 'selectMultiple',
section: '角色分配',
itemStyle: { gridColumn: '1 / -1' },
rules: [{ required: true, message: '请至少选择一个角色' }],
},
];
return (
<UModal
open={open}
title={isEdit ? '编辑账号' : '新增账号'}
width={520}
okText="保存"
cancelText="取消"
confirmLoading={saveMutation.isPending}
onCancel={onCancel}
onOk={() => form.submit()}
styles={{ body: { maxHeight: '65vh', overflowY: 'auto', paddingTop: 8 } }}
>
<CombiForm<AccountFormValues>
mode="form"
form={form}
layout="vertical"
onSubmit={(values) => saveMutation.mutate(values)}
initialValues={{ roleIds: [] }}
fields={fields}
sectionContentStyle={twoColumnStyle}
renderSectionTitle={(title) => <SectionTitle>{title}</SectionTitle>}
renderControl={(field) => {
if (field.name === 'account')
return (
<UInput disabled={isEdit} maxLength={20} placeholder="请输入登录账号" size="small" />
);
if (field.name === 'name')
return <UInput maxLength={20} placeholder="请输入姓名" size="small" />;
if (field.name === 'mobile')
return (
<UInput
inputMode="numeric"
maxLength={11}
placeholder="请输入手机号"
size="small"
onChange={(event) =>
form.setFieldValue('mobile', event.target.value.replace(/\D/g, ''))
}
/>
);
if (field.name === 'email') return <UInput placeholder="选填" size="small" />;
if (field.name === 'orgPath')
return (
<UCascader
options={toOrgCascaderOptions(orgTree)}
changeOnSelect
placeholder="请选择所属组织"
showSearch
size="small"
style={{ width: '100%' }}
/>
);
if (field.name === 'dataScope')
return (
<USelect
options={dataScopeOptions}
placeholder="请选择数据域"
size="small"
style={{ width: '100%' }}
/>
);
if (field.name === 'roleIds')
return (
<div style={roleListStyle}>
{roleOptions.map((item) => (
<UButton
key={item.roleId}
type={selectedRoleIds.includes(item.roleId) ? 'primary' : 'default'}
size="small"
style={roleOptionStyle}
onClick={() => {
const nextRoleIds = selectedRoleIds.includes(item.roleId)
? selectedRoleIds.filter((id) => id !== item.roleId)
: [...selectedRoleIds, item.roleId];
form.setFields([{ name: 'roleIds', value: nextRoleIds, errors: [] }]);
}}
>
{item.roleName}
</UButton>
))}
</div>
);
return undefined;
}}
/>
</UModal>
);
}
const twoColumnStyle = { display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 12 };
function SectionTitle({ children }: { children: string }) {
return (
<h3 style={sectionTitleStyle}>
<span style={sectionMarkerStyle} />
{children}
</h3>
);
}
const sectionTitleStyle = {
borderBottom: '1px solid #eef0f4',
alignItems: 'center',
display: 'flex',
gap: 6,
fontSize: 14,
lineHeight: '16px',
margin: '0 0 12px',
padding: '0 0 8px',
};
const sectionMarkerStyle = { backgroundColor: '#315ce8', borderRadius: 2, height: 10, width: 3 };
const roleListStyle = { display: 'flex', flexWrap: 'wrap', gap: 8 } as const;
const roleOptionStyle = {
alignItems: 'center',
display: 'flex',
height: 30,
margin: 0,
padding: '0 10px',
};
import PagePlaceholder from '@/components/PagePlaceholder'; import { useMemo, useState } from 'react';
import { Skeleton } from '@uj/ui'; import { message } from 'antd';
import { useMutation, useQuery } from '@tanstack/react-query';
import type { ColumnsType } from 'antd/es/table';
import { UCard, UTag, UText, UTitle } from '@uj/ui';
import {
DataTable,
DEFAULT_PAGE_SIZE,
ConfirmModal,
SearchForm,
type FieldSchema,
type RowActionSchema,
type SearchPagination,
} from '@/components';
import { P, PermButton } from '@/access';
import { org, role, user, type UserPageItem, type UserPageParams } from '@/api';
import { AccountModal } from './components/AccountModal';
import { createAccountPageParams, toOrgCascaderOptions, withAllOption } from './tools/account';
const accountStatusOptions = [
{ label: '启用', value: 1 },
{ label: '停用', value: 0 },
];
interface AccountRow {
id: number;
account: string;
name: string;
mobile: string;
orgPath: string;
roleNames: string[];
dataScopeLabel: string;
status: number;
lastLoginAt: string;
source: UserPageItem;
}
function toParams(values: Record<string, unknown>, pagination: SearchPagination): UserPageParams {
return createAccountPageParams(values, pagination);
}
export default function AccountManage() { export default function AccountManage() {
const loading = false; const [params, setParams] = useState<UserPageParams>({ current: 1, size: DEFAULT_PAGE_SIZE });
if (loading) return <Skeleton variant="default" />; const [queryVersion, setQueryVersion] = useState(0);
return <PagePlaceholder title="账号管理" description="账号开通、禁用与角色绑定(建设中)" />; const [accountModalOpen, setAccountModalOpen] = useState(false);
const [editingAccount, setEditingAccount] = useState<UserPageItem>();
const [resettingAccount, setResettingAccount] = useState<UserPageItem>();
const [changingStatusAccount, setChangingStatusAccount] = useState<UserPageItem>();
const resetPasswordMutation = useMutation({
mutationFn: (account: UserPageItem) => user.resetPassword(account.userId, { password: '' }),
onSuccess: () => {
void message.success('密码已重置');
setResettingAccount(undefined);
},
onError: (error: Error) => void message.error(error.message || '重置失败,请稍后重试'),
});
const statusMutation = useMutation({
mutationFn: async (account: UserPageItem) => {
const status = account.status === 1 ? 0 : 1;
await user.updateStatus(account.userId, { status });
return status;
},
onSuccess: (status) => {
void message.success(`账号已${status === 1 ? '启用' : '停用'}`);
setChangingStatusAccount(undefined);
setQueryVersion((version) => version + 1);
},
onError: (error: Error) => void message.error(error.message || '操作失败,请稍后重试'),
});
const {
data: result,
isLoading,
isFetching,
} = useQuery({
queryKey: ['user-page', params, queryVersion],
queryFn: () => user.page(params),
});
const { data: roleOptions = [] } = useQuery({
queryKey: ['role-options'],
queryFn: () => role.options(),
});
const { data: orgTree = [] } = useQuery({ queryKey: ['org-tree'], queryFn: () => org.tree() });
const data = useMemo<AccountRow[]>(
() =>
result?.records.map((item) => ({
id: item.userId,
account: item.account,
name: item.name,
mobile: item.mobile,
orgPath: item.orgPath ?? '—',
roleNames: item.roleNames ?? [],
dataScopeLabel: item.dataScopeLabel ?? '—',
status: item.status,
lastLoginAt: item.lastLoginAt ?? '—',
source: item,
})) ?? [],
[result],
);
const fields: FieldSchema<Record<string, unknown>>[] = [
{ name: 'keyword', label: '账号 / 姓名', type: 'input', placeholder: '模糊搜索' },
{
name: 'orgId',
label: '所属组织',
type: 'cascader',
options: withAllOption(toOrgCascaderOptions(orgTree)),
},
{
name: 'roleId',
label: '角色',
type: 'select',
options: withAllOption(
roleOptions.map((item) => ({ label: item.roleName, value: item.roleId })),
),
},
{
name: 'status',
label: '状态',
type: 'select',
options: withAllOption(accountStatusOptions),
},
];
const columns: ColumnsType<AccountRow> = [
{
title: '账号',
dataIndex: 'account',
width: 140,
render: (value) => (
<UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{value}</UText>
),
},
{ title: '姓名', dataIndex: 'name', width: 110 },
{ title: '手机号', dataIndex: 'mobile', width: 140 },
{ title: '所属组织', dataIndex: 'orgPath', width: 260 },
{
title: '角色',
dataIndex: 'roleNames',
width: 220,
render: (names: string[]) =>
names.length
? names.map((name) => (
<UTag key={name} color="blue">
{name}
</UTag>
))
: '—',
},
{ title: '数据域', dataIndex: 'dataScopeLabel', width: 140 },
{
title: '状态',
width: 90,
render: (_, row) => (row.status === 1 ? '启用' : '停用'),
},
{ title: '最后登录', dataIndex: 'lastLoginAt', width: 170 },
];
const rowActions: RowActionSchema<AccountRow>[] = [
{
label: '编辑',
permission: P.SYSTEM_USER_SAVE,
onClick: (row) => {
setEditingAccount(row.source);
setAccountModalOpen(true);
},
},
{
label: '重置密码',
permission: P.SYSTEM_USER_SAVE,
onClick: (row) => setResettingAccount(row.source),
},
{
label: (row) => (row.status === 1 ? '停用' : '启用'),
permission: P.SYSTEM_USER_SAVE,
danger: (row) => row.status === 1,
onClick: (row) => setChangingStatusAccount(row.source),
},
];
return (
<div style={{ padding: 10, display: 'flex', flexDirection: 'column', gap: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div>
<UTitle level={3} style={{ margin: 0 }}>
账号管理
</UTitle>
<UText type="secondary">维护系统用户账号,分配角色与组织归属。</UText>
</div>
<PermButton
permission={P.SYSTEM_USER_SAVE}
onClick={() => {
setEditingAccount(undefined);
setAccountModalOpen(true);
}}
>
新增账号
</PermButton>
</div>
<UCard size="small">
<SearchForm
fields={fields}
initialValues={{ orgId: [''], roleId: '', status: '' }}
onSearch={(values, pagination) => {
setParams(toParams(values, pagination));
setQueryVersion((version) => version + 1);
}}
onReset={(values, pagination) => {
setParams(toParams(values, pagination));
setQueryVersion((version) => version + 1);
}}
/>
</UCard>
<UCard size="small" styles={{ body: { padding: 0 } }}>
<DataTable<AccountRow>
rowKey="id"
columns={columns}
rowActions={rowActions}
actionColumnWidth={220}
loading={isLoading || isFetching}
pageData={result ? { ...result, records: data } : undefined}
pagination={{
current: params.current ?? 1,
pageSize: params.size,
total: result?.total ?? 0,
onChange: (current, size) => {
setParams((previous) => ({ ...previous, current, size }));
setQueryVersion((version) => version + 1);
},
}}
/>
</UCard>
<AccountModal
open={accountModalOpen}
account={editingAccount}
orgTree={orgTree}
roleOptions={roleOptions}
onCancel={() => setAccountModalOpen(false)}
onSuccess={() => {
setAccountModalOpen(false);
setQueryVersion((version) => version + 1);
}}
/>
<ConfirmModal
open={Boolean(resettingAccount)}
content="是否重置该用户密码"
confirmLoading={resetPasswordMutation.isPending}
onCancel={() => setResettingAccount(undefined)}
onConfirm={() => {
if (resettingAccount) resetPasswordMutation.mutate(resettingAccount);
}}
/>
<ConfirmModal
open={Boolean(changingStatusAccount)}
content={`是否${changingStatusAccount?.status === 1 ? '停用' : '启用'}用户${
changingStatusAccount ? `“${changingStatusAccount.account}”` : ''
}`}
confirmLoading={statusMutation.isPending}
onCancel={() => setChangingStatusAccount(undefined)}
onConfirm={() => {
if (changingStatusAccount) statusMutation.mutate(changingStatusAccount);
}}
/>
</div>
);
} }
import type { OrgNode, UserPageParams } from '@/api';
import type { SearchPagination } from '@/components';
import type { FieldOption } from '@/components/formSchema';
export function toOrgCascaderOptions(nodes: OrgNode[]): FieldOption[] {
return nodes.map((node) => ({
value: node.id,
label: node.label,
children: node.children?.length ? toOrgCascaderOptions(node.children) : undefined,
}));
}
/** 根据组织 ID 反查级联选择器所需的完整路径。 */
export function findOrgPath(nodes: OrgNode[], targetId: number | undefined): number[] {
if (targetId === undefined) return [];
for (const node of nodes) {
if (node.id === targetId) return [node.id];
const childPath = findOrgPath(node.children ?? [], targetId);
if (childPath.length) return [node.id, ...childPath];
}
return [];
}
/** 为模块内的下拉选项统一补充“全部”。 */
export function withAllOption(options: FieldOption[]): FieldOption[] {
return [{ label: '全部', value: '' }, ...options];
}
export function createAccountPageParams(
values: Record<string, unknown>,
pagination: SearchPagination,
): UserPageParams {
const orgPath = values.orgId;
const orgId = Array.isArray(orgPath) ? orgPath.at(-1) : undefined;
return {
current: pagination.current,
size: pagination.size,
keyword: values.keyword as string | undefined,
mobile: values.mobile as string | undefined,
// “全部”对应空值,不附加组织筛选条件。
orgId: typeof orgId === 'number' ? orgId : undefined,
roleId: values.roleId === '' || values.roleId === undefined ? undefined : Number(values.roleId),
status: values.status === '' || values.status === undefined ? undefined : Number(values.status),
};
}
import PagePlaceholder from '@/components/PagePlaceholder'; import { useMemo, useState } from 'react';
import { Skeleton } from '@uj/ui'; import { useQuery } from '@tanstack/react-query';
import type { ColumnsType } from 'antd/es/table';
import { UCard, UTag, UText, UTitle } from '@uj/ui';
import {
DataTable,
DEFAULT_PAGE_SIZE,
SearchForm,
type FieldSchema,
type RowActionSchema,
type SearchPagination,
} from '@/components';
import { P, PermButton } from '@/access';
import { role, type RolePageParams } from '@/api';
import { getDataScopeLabel } from '@/constants/dataScope';
import { getBaseList } from './tools/constants';
interface Row {
id: number;
name: string;
code: string;
scope: string;
accounts: number;
description: string;
type: string;
status?: number;
}
function createRolePageParams(
values: Record<string, unknown>,
pagination: SearchPagination,
): RolePageParams {
return {
current: pagination.current,
size: pagination.size,
keyword: values.keyword as string | undefined,
isBuiltin: values.type === '' || values.type === undefined ? undefined : Number(values.type),
status: values.status === '' || values.status === undefined ? undefined : Number(values.status),
defaultDataScope:
values.scope === '' || values.scope === undefined ? undefined : Number(values.scope),
};
}
export default function RoleManage() { export default function RoleManage() {
const loading = false; const [params, setParams] = useState<RolePageParams>({
if (loading) return <Skeleton variant="default" />; current: 1,
return <PagePlaceholder title="角色管理" description="角色定义与权限分配(建设中)" />; size: DEFAULT_PAGE_SIZE,
isBuiltin: undefined,
status: undefined,
defaultDataScope: undefined,
});
const [queryVersion, setQueryVersion] = useState(0);
const {
data: result,
isLoading,
isFetching,
} = useQuery({ queryKey: ['role-page', params, queryVersion], queryFn: () => role.page(params) });
const data = useMemo(
() =>
result?.records?.map((item) => ({
id: item.roleId,
name: item.roleName,
code: item.roleCode,
scope: getDataScopeLabel(item.defaultDataScope),
accounts: item.accountCount,
description: item.description ?? '—',
type: item.isBuiltin === 1 ? '内置' : '自定义',
status: item.status,
})) ?? [],
[result],
);
const fields: FieldSchema<Record<string, unknown>>[] = [
{ name: 'keyword', label: '角色名称 / 编码', type: 'input', placeholder: '模糊搜索' },
{
name: 'type',
label: '类型',
type: 'select',
options: getBaseList('roleType'),
},
{
name: 'status',
label: '状态',
type: 'select',
options: getBaseList('roleStatus'),
},
{
name: 'scope',
label: '默认数据域',
type: 'select',
options: getBaseList('dataScope'),
},
];
const columns: ColumnsType<Row> = [
{ title: '角色名称', dataIndex: 'name', width: 150 },
{
title: '角色编码',
dataIndex: 'code',
width: 150,
render: (v) => <UText style={{ color: '#315ce8', fontFamily: 'monospace' }}>{v}</UText>,
},
{ title: '默认数据域', dataIndex: 'scope', width: 130 },
{ title: '账号数', dataIndex: 'accounts', width: 90, align: 'right' },
{ title: '角色描述', dataIndex: 'description' },
{
title: '类型',
dataIndex: 'type',
width: 90,
render: (v) => <UTag color={v === '内置' ? 'geekblue' : 'default'}>{v}</UTag>,
},
{
title: '状态',
width: 90,
render: (_, r) => (
<UTag color={r.status === 1 ? 'green' : 'default'}>
● {r.status === 1 ? '启用' : '停用'}
</UTag>
),
},
];
const rowActions: RowActionSchema<Row>[] = [
{ label: '查看详情', permission: P.SYSTEM_ROLE_VIEW, onClick: () => undefined },
{ label: '编辑', permission: P.SYSTEM_ROLE_SAVE, onClick: () => undefined },
{
label: '删除',
permission: P.SYSTEM_ROLE_SAVE,
danger: true,
onClick: () => undefined,
},
];
return (
<div style={{ padding: 10, display: 'flex', flexDirection: 'column', gap: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<div>
<UTitle level={3} style={{ margin: 0 }}>
角色管理
</UTitle>
<UText type="secondary">
维护角色清单与基本信息,支持按关键字筛选;角色的菜单可见范围在「查看详情」中配置。
</UText>
</div>
<PermButton permission={P.SYSTEM_ROLE_SAVE}>新增角色</PermButton>
</div>
<UCard size="small">
<SearchForm
fields={fields}
initialValues={{ type: '', status: '', scope: '' }}
onSearch={(values, pagination) => {
setParams(createRolePageParams(values, pagination));
setQueryVersion((version) => version + 1);
}}
onReset={(values, pagination) => {
setParams(createRolePageParams(values, pagination));
setQueryVersion((version) => version + 1);
}}
/>
</UCard>
<UCard size="small" styles={{ body: { padding: 0 } }}>
<DataTable<Row>
rowKey="id"
columns={columns}
rowActions={rowActions}
actionColumnWidth={280}
loading={isLoading || isFetching}
pageData={result ? { ...result, records: data } : undefined}
recordsKey="records"
pagination={{
current: params.current ?? 1,
pageSize: params.size,
total: result?.total ?? 0,
onChange: (current, size) => {
setParams((prev) => ({ ...prev, current, size }));
setQueryVersion((version) => version + 1);
},
}}
/>
</UCard>
</div>
);
} }
import type { FieldOption } from '@/components';
import { dataScopeOptions } from '@/constants/dataScope';
/** 角色管理页专用的下拉选项。 */
export const baseList = {
roleType: [
{ label: '内置', value: 1 },
{ label: '自定义', value: 0 },
],
roleStatus: [
{ label: '启用', value: 1 },
{ label: '停用', value: 0 },
],
dataScope: dataScopeOptions,
} satisfies Record<string, FieldOption[]>;
export function getBaseList(key: keyof typeof baseList, includeAll = true): FieldOption[] {
return includeAll ? [{ label: '全部', value: '' }, ...baseList[key]] : baseList[key];
}
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: '确认撤回',
};
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="通过当前审批节点后,记录将继续后续审批;全部节点通过后才会生效并进入门店列表。"
/>
) : 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 { useMemo } from 'react';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { FillTable, UCheckbox, UTag } from '@uj/ui'; import { UTag } from '@uj/ui';
import { Perm, PermButton, P } from '@/access'; import { DataTable, type RowActionSchema } from '@/components';
import type { ApproveRow } from '../tools/consts'; import type { DataTableProps } from '@/components/DataTable';
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';
export function ApproveTable({ tab, data }: { tab: string; data: ApproveRow[] }) { interface Props extends Omit<DataTableProps<ApprovalRow>, 'columns'> {
const baseColumns: ColumnsType<ApproveRow> = [ tab: ApproveTab;
{ title: '门店名称', dataIndex: 'storeName', width: 220 }, spec?: StoreDictionaries;
rowActions: RowActionSchema<ApprovalRow>[];
}
export function ApproveTable({ tab, spec, ...props }: Props) {
const columns: ColumnsType<ApprovalRow> = [
{
title: '门店名称',
dataIndex: 'storeName',
width: 220,
fixed: 'left',
render: (value) => <strong>{value}</strong>,
},
{ {
title: '门店商户号', title: '门店商户号',
dataIndex: 'merchantNo', dataIndex: 'merchantNo',
width: 110, width: 140,
render: (v: string) => <span style={{ fontFamily: 'monospace' }}>{v}</span>, render: (value) => <span className="store-code">{value}</span>,
}, },
{ {
title: '产品分类', title: '产品分类',
dataIndex: 'categories', key: 'categories',
width: 170, width: 180,
render: (cs: string[]) => ( render: (_, row) => {
<> const categories = row.productCategories ?? [];
<UTag>{cs[0]}</UTag> const count = row.categoryCount ?? categories.length;
{cs.length > 1 && <span style={{ color: '#8A94A6' }}>等 {cs.length} 个分类</span>} return (
</> <>
), {categories[0] ? (
<UTag>{dictionaryLabel(spec?.productCategories, categories[0])}</UTag>
) : (
'—'
)}
{count > 1 && <span className="store-subtext">等 {count} 个分类</span>}
</>
);
},
}, },
{ {
title: '业务场景', title: '业务场景',
dataIndex: 'scene', dataIndex: 'businessScene',
width: 200, width: 200,
render: (s: string) => <UTag color="blue">{s}</UTag>, render: (value) => <UTag color="blue">{dictionaryLabel(spec?.businessScenes, value)}</UTag>,
},
{
title: '运营成本合计',
dataIndex: 'cost',
width: 120,
align: 'right',
render: (v: number | null) => (v == null ? '—' : `¥${v.toLocaleString()}`),
},
{
title: '提交人 / 提交时间',
dataIndex: 'submitter',
width: 160,
render: (_: unknown, r: ApproveRow) => (
<>
{r.submitter}
<br />
<span style={{ color: '#8A94A6' }}>{r.submittedAt}</span>
</>
),
},
{
title: '停留时长',
dataIndex: 'stayHours',
width: 90,
render: (h: number) => (
<span style={{ color: h > 48 ? '#E5484D' : h > 24 ? '#D97706' : 'inherit' }}>{h}h</span>
),
},
{
title: '操作',
key: 'op',
width: 140,
fixed: 'right',
render: () => (
<>
<PermButton permission={P.STORE_APPROVE_AUDIT} type="link" unauthorizedTip="无审批权限">
审核
</PermButton>
<Perm permission={P.STORE_APPROVE_VIEW}>
<a style={{ marginLeft: 12 }}>查看</a>
</Perm>
</>
),
}, },
]; ];
if (tab === 'todo')
const columns = useMemo(() => { columns.push(
if (tab === 'todo') { {
return [ title: '运营成本合计',
{ title: '', key: 'select', width: 40, render: () => <UCheckbox /> }, dataIndex: 'costTotal',
...baseColumns, width: 150,
] as ColumnsType<ApproveRow>; align: 'right',
} render: formatMoney,
return baseColumns; },
}, [tab]); {
title: '提交人 / 提交时间',
width: 180,
render: (_, row) => (
<>
{row.submitUserName || '—'}
<span className="store-subtext">{formatDateTime(row.submitTime)}</span>
</>
),
},
{
title: '停留时长',
width: 110,
render: (_, row) => {
const level =
row.timeoutLevel ??
(row.pendingHours != null && row.pendingHours > 48
? 'DANGER'
: row.pendingHours != null && row.pendingHours > 24
? 'WARNING'
: 'NORMAL');
return (
<span
style={{
color:
level === 'DANGER'
? 'var(--uj-error)'
: level === 'WARNING'
? 'var(--uj-warning)'
: undefined,
}}
>
{row.pendingHours == null ? '—' : `${row.pendingHours} 小时`}
</span>
);
},
},
);
if (tab === 'done')
columns.push(
{
title: '我的动作',
width: 100,
render: (_, row) => (
<UTag
color={
row.myAction === 'PASS' ? 'green' : row.myAction === 'REJECT' ? 'red' : undefined
}
>
{row.myActionLabel ||
({ PASS: '通过', REJECT: '打回' }[row.myAction ?? ''] ?? row.myAction ?? '—')}
</UTag>
),
},
{ title: '处理时间', dataIndex: 'handleTime', width: 180, render: formatDateTime },
{
title: '处理意见',
width: 220,
render: (_, row) => row.handleOpinion || row.rejectReason || '—',
},
{ title: '记录状态', width: 110, render: (_, row) => <StatusTag status={row.status} /> },
);
if (tab === 'mine')
columns.push(
{ title: '状态', width: 110, render: (_, row) => <StatusTag status={row.status} /> },
{
title: '审批进度',
width: 170,
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: 180, render: formatDateTime },
);
return ( return (
<FillTable<ApproveRow> <DataTable<ApprovalRow>
rowKey="id" {...props}
columns={columns} columns={columns}
dataSource={data} rowKey="listingId"
pagination={{ pageSize: 10 }} scroll={{ x: tab === 'done' ? 1500 : 1410 }}
actionColumnWidth={200}
actionColumnFixed="right"
/> />
); );
} }
// PRD §5.2 业务场景枚举(单选):售后会员权益升级 / 售前延保 import type { ApproveTab } from '@/api';
export const SCENES = ['售后会员权益升级', '售前延保']; export const tabDefs: { key: ApproveTab; label: string }[] = [
// PRD §6.1 产品分类枚举(6 值)
export const CATEGORIES = [
'太阳膜-原厂',
'车衣-原厂',
'精品-小桌板',
'精品-脚垫',
'踏板',
'车衣-副厂',
];
export interface ApproveRow {
id: string;
storeName: string;
merchantNo: string;
categories: string[];
scene: string;
cost: number | null;
submitter: string;
submittedAt: string;
stayHours: number;
}
export const tabDefs = [
{ key: 'todo', label: '待我审批' }, { key: 'todo', label: '待我审批' },
{ key: 'done', label: '我已办' }, { key: 'done', label: '我已办' },
{ key: 'mine', label: '我发起的' }, { key: 'mine', label: '我发起的' },
]; ];
export const rejectReasons = ['数据有误', '政策不合理', '缺少附件', '其他'];
// 占位数据:真实接入 /api/approvals?tab=todo|done|mine export function errorMessage(error: unknown): string {
export const EMPTY: ApproveRow[] = []; return error instanceof Error ? error.message : '操作失败,请稍后重试';
}
import { useEffect, useState } from 'react';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';
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 [order, setOrder] = useState<ListingColumn[]>(DEFAULT_COLUMNS);
const [selected, setSelected] = useState<ListingColumn[]>(props.columns);
useEffect(() => {
if (props.open) {
setOrder([
...props.columns,
...DEFAULT_COLUMNS.filter((column) => !props.columns.includes(column)),
]);
setSelected(props.columns);
}
}, [props.open, props.columns]);
function move(index: number, offset: number) {
setOrder((current) => {
const next = [...current];
[next[index], next[index + offset]] = [next[index + offset], next[index]];
return next;
});
}
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(order.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">
{order.map((column, index) => (
<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>
<UButton
type="text"
icon={<ArrowUpOutlined />}
aria-label={`上移${COLUMN_LABELS[column]}`}
disabled={index < 2 || props.loading || Boolean(props.error) || props.saving}
onClick={() => move(index, -1)}
/>
<UButton
type="text"
icon={<ArrowDownOutlined />}
aria-label={`下移${COLUMN_LABELS[column]}`}
disabled={
index === 0 ||
index === order.length - 1 ||
props.loading ||
Boolean(props.error) ||
props.saving
}
onClick={() => move(index, 1)}
/>
</div>
</div>
))}
</div>
{props.saveError ? (
<UAlert
type="error"
showIcon
title={errorText(props.saveError, '列配置保存失败,请重试')}
/>
) : null}
</UModal>
);
}
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { StatusTag } from '@/components/StatusTag'; import { UButton, UTag } from '@uj/ui';
import { PermButton, P } from '@/access'; import { P, Perm } from '@/access';
import type { StoreStatus } from '@/config/storeStatus'; import type { ListingPageParams, StoreListingRow } from '@/api';
import type { StoreRow } from '../tools/fetchStores'; 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(): ColumnsType<StoreRow> { export function buildColumns({
return [ visible,
{ title: '门店ID', dataIndex: 'id' }, params,
{ title: '门店名称', dataIndex: 'name' }, spec,
{ title: '城市', dataIndex: 'city' }, onDetail,
{ title: '业务场景', dataIndex: 'scene' }, onHistory,
{ }: {
title: '状态', visible: ListingColumn[];
dataIndex: 'status', params: ListingPageParams;
render: (s: StoreStatus) => <StatusTag status={s} />, spec?: StoreDictionaries;
onDetail: (row: StoreListingRow) => void;
onHistory: (row: StoreListingRow) => void;
}): ColumnsType<StoreListingRow> {
const sortOrder = params.sortOrder === 'asc' ? 'ascend' : 'descend';
const definitions: Record<ListingColumn, ColumnsType<StoreListingRow>[number]> = {
storeName: {
title: COLUMN_LABELS.storeName,
dataIndex: 'storeName',
key: 'storeName',
width: 230,
fixed: 'left',
render: (value: string, row) => (
<UButton type="link" className="store-listing-name" onClick={() => onDetail(row)}>
{value || '—'}
</UButton>
),
},
merchantNo: {
title: COLUMN_LABELS.merchantNo,
dataIndex: 'merchantNo',
key: 'merchantNo',
width: 170,
render: (value: string) => <span className="store-code">{value || '—'}</span>,
},
businessScene: {
title: COLUMN_LABELS.businessScene,
dataIndex: 'businessScene',
key: 'businessScene',
width: 210,
render: (value: string) => (
<UTag color="blue">{dictionaryLabel(spec?.businessScenes, value)}</UTag>
),
},
effectiveTime: {
title: COLUMN_LABELS.effectiveTime,
dataIndex: 'effectiveTime',
key: 'effectiveTime',
width: 150,
sorter: true,
sortOrder: params.sortField === 'effectiveDate' ? sortOrder : null,
render: (value: string | null) => formatDateTime(value).split(' ')[0],
}, },
{ title: '负责人', dataIndex: 'owner' }, changeCount: {
{ title: COLUMN_LABELS.changeCount,
title: '操作', dataIndex: 'changeCount',
key: 'op', key: 'changeCount',
width: 120, width: 120,
fixed: 'right', align: 'right',
render: () => ( sorter: true,
<PermButton sortOrder: params.sortField === 'changeCount' ? sortOrder : null,
permission={P.STORE_LISTING_DELETE} render: (value: number | null | undefined, row) => (
type="link" <Perm permission={P.STORE_LISTING_VIEW} fallback={value ?? '—'}>
danger <UButton
unauthorizedTip="无删除权限" type="link"
> aria-label={`查看${row.storeName}变更历史`}
删除 onClick={() => onHistory(row)}
</PermButton> >
{value ?? '—'}
</UButton>
</Perm>
), ),
}, },
]; };
return visible.map((column) => definitions[column]);
} }
.store-listing-toolbar {
padding: 16px 20px;
}
.store-listing-name {
padding: 0;
height: auto;
white-space: normal;
text-align: left;
font-weight: 600;
}
.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 { store, type StoreListingRow } from '@/api';
import type { StoreStatus } from '@/config/storeStatus';
export type StoreRow = StoreListingRow & { status: StoreStatus };
// 真实接入后端 /store/listing/page(仅返回「已生效」门店,PRD §5.3)
export async function fetchStores(): Promise<StoreRow[]> {
const page = await store.listStores({ pageNum: 1, pageSize: 10 });
return page.list.map((s) => ({ ...s, status: (s.status as StoreStatus) ?? 'ACTIVE' }));
}
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 = Object.keys(COLUMN_LABELS) as ListingColumn[];
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
? ['storeName', ...new Set(valid.filter((column) => column !== 'storeName'))]
: [...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, UTag } 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: '#4F46E5',
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>
);
}
function NodeLine({ status }: { status: ChainNodeStatus }) {
const bg = status === 'done' ? '#16A34A' : '#E5E7EB';
return (
<div
style={{
flex: 1,
height: 2,
background: bg,
alignSelf: 'center',
marginTop: -16,
}}
/>
);
}
export interface ApprovalChainPreviewProps {
nodes?: ChainNode[];
chainType?: string;
/** (可选)覆盖默认的提交人名称。不传则取当前登录用户名 */
submitterName?: string;
/** (可选)覆盖默认的提交时间,格式 YYYY-MM-DD HH:mm */
submitTime?: string;
}
/**
* 生成默认 3 节点审批链:
* - 第 1 个节点「提交」:副标题 = 当前登录用户名(外部 prop 覆盖优先);时间 = submitTime 或 DEFAULT_SUBMIT_TIME
* - 第 2 个节点「优加财务经理」:唯一审批节点
* - 第 3 个节点「生效」:写入门店列表
*/
function buildDefaultNodes(submitter: string, time: string): ChainNode[] {
return [
{
status: 'done',
title: '提交',
subtitle: submitter,
time,
},
{
status: 'active',
title: '优加财务经理',
subtitle: '唯一审批节点',
},
{
status: 'pending',
title: '生效',
subtitle: '写入门店列表',
},
];
}
export function ApprovalChainPreview({
nodes,
chainType = '单级审批',
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: '#4F46E5', fontSize: 14 }} />
<span style={{ fontSize: 15, fontWeight: 600 }}>审批链预览</span>
</div>
}
extra={
<UTag color="default" bordered style={{ fontSize: 12 }}>
{chainType}
</UTag>
}
>
<div style={{ display: 'flex', padding: '20px 8px 8px' }}>
{finalNodes.map((n, i) => (
<div key={i} style={{ flex: 1, display: 'flex', position: 'relative' }}>
<div
style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: 1 }}
>
<NodeIcon status={n.status} index={i} />
<div
style={{
marginTop: 14,
fontSize: 14,
fontWeight: 600,
color:
n.status === 'active' ? '#4F46E5' : 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>
{i < finalNodes.length - 1 && <NodeLine status={finalNodes[i].status} />}
</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({ passCount = 12, 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('下一步:提交审批'))}
>
下一步:提交审批({passCount})
</UButton>
</div>
</div>
);
}
import { useEffect, useMemo } from 'react';
import { InfoCircleFilled } from '@ant-design/icons';
import { App } from 'antd';
import { UCard, UForm, UFormItem, USelect, UInput } from '@uj/ui';
import type { USelectProps } from '@uj/ui';
import type { StoreImportCheckVO } from '@/api/modules/store';
export interface ImportInfoValues {
org: string;
scene: string;
categories: string[];
remark?: string;
}
const formItemLayout = {
style: { marginBottom: 18 },
};
export interface ImportInfoCardProps {
values?: Partial<ImportInfoValues>;
/** check 接口返回结果(用于动态生成 3 个下拉的 options) */
checkResult?: StoreImportCheckVO | null;
onChange?: (values: ImportInfoValues) => void;
}
export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCardProps) {
const { message } = App.useApp();
const [form] = UForm.useForm<ImportInfoValues>();
/**
* 3 个下拉 options 完全由接口返回决定(不再硬编码):
* - orgPath / businessScene 都是单值(名字里可能带 "/",是层级/组合名,不拆分)
* - productCategories 是多值,用 "/" 分隔成多选数组
*/
const orgOptions: USelectProps['options'] = useMemo(() => {
if (!checkResult?.orgPath) return [];
return [{ label: checkResult.orgPath, value: checkResult.orgPath }];
}, [checkResult?.orgPath]);
const sceneOptions: USelectProps['options'] = useMemo(() => {
if (!checkResult?.businessScene) return [];
return [{ label: checkResult.businessScene, value: checkResult.businessScene }];
}, [checkResult?.businessScene]);
const categoryOptions: USelectProps['options'] = useMemo(() => {
if (!checkResult?.productCategories) return [];
return checkResult.productCategories
.split('/')
.map((s) => s.trim())
.filter(Boolean)
.map((v) => ({ label: v, value: v }));
}, [checkResult?.productCategories]);
// 「只读」标记:只要任一3个下拉从接口回填过,即被锁定,禁止改动
const readOnly = useMemo(
() =>
Boolean(
values &&
(values.org || values.scene || (values.categories && values.categories.length > 0)),
),
[values],
);
// 受控回填:外部 values 变化时,把导入结果同步到表单
useEffect(() => {
if (values) {
form.setFieldsValue(values);
}
}, [values, form]);
const handleValuesChange = (changed: Partial<ImportInfoValues>, all: ImportInfoValues) => {
// 只读模式下:所属组织/业务场景/产品分类一旦由接口回填确定,不允许再修改
if (readOnly) {
const lockedKeys: (keyof ImportInfoValues)[] = ['org', 'scene', 'categories'];
const touched = lockedKeys.filter((k) => Object.prototype.hasOwnProperty.call(changed, k));
if (touched.length > 0) {
message.warning('该字段由模板解析结果自动回填,不可手动修改');
// 立刻恢复原值(只读语义:展示原值恢复不改)
form.setFieldsValue({
org: values?.org ?? all.org,
scene: values?.scene ?? all.scene,
categories: values?.categories ?? all.categories,
});
// 回退 touched keys 恢复后,不向上游广播 change(只传 remark 的变化允许)
const next: ImportInfoValues = { ...all };
if (values?.org != null) next.org = values.org;
if (values?.scene != null) next.scene = values.scene;
if (values?.categories != null) next.categories = values.categories;
onChange?.(next);
return;
}
}
onChange?.(all);
};
return (
<UCard
styles={{ body: { padding: 20 } }}
style={{ marginBottom: 20, border: '1px solid #E5E7EB' }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: '#4F46E5', fontSize: 14 }} />
<span style={{ fontSize: 15, fontWeight: 600 }}>导入信息</span>
</div>
}
>
<UForm
form={form}
layout="vertical"
onValuesChange={handleValuesChange}
onFinish={() => {
onChange?.(form.getFieldsValue());
}}
>
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gap: 20,
}}
>
<UFormItem
label={
<span>
所属组织<span style={{ color: '#E5484D', marginLeft: 2 }}>*</span>
</span>
}
name="org"
{...formItemLayout}
>
<USelect options={orgOptions} placeholder="请选择所属组织" />
</UFormItem>
<UFormItem
label={
<span>
业务场景<span style={{ color: '#E5484D', marginLeft: 2 }}>*</span>
</span>
}
name="scene"
{...formItemLayout}
>
<USelect options={sceneOptions} placeholder="请选择业务场景" />
</UFormItem>
<UFormItem
label={
<span>
产品分类<span style={{ color: '#E5484D', marginLeft: 2 }}>*</span>
</span>
}
name="categories"
{...formItemLayout}
>
<USelect
mode="multiple"
options={categoryOptions}
placeholder="请选择产品分类"
maxTagCount="responsive"
/>
</UFormItem>
</div>
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gap: 20,
marginTop: 4,
}}
>
<div style={{ fontSize: 12, color: '#8A94A6', lineHeight: 1.6 }}>
决定本次导入数据的数据可见范围
</div>
<div style={{ fontSize: 12, color: '#8A94A6', lineHeight: 1.6 }}>
同一门店有多个业务场景时需拆分为独立行导入
</div>
<div style={{ fontSize: 12, color: '#8A94A6', lineHeight: 1.6 }}>
决定模板中「产品分类」列的枚举范围
</div>
</div>
<UFormItem
label={<span style={{ marginTop: 18, display: 'inline-block' }}>备注</span>}
name="remark"
style={{ marginBottom: 8 }}
>
<UInput.TextArea
rows={2}
maxLength={200}
showCount
placeholder="选填,≤ 200 字,将在审批详情中展示给审批人"
/>
</UFormItem>
</UForm>
</UCard>
);
}
import { useState } from 'react';
import { App } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { store } from '@/api';
import { UAlert, UUpload, UParagraph } from '@uj/ui';
export function ImportUploader() {
const { message } = App.useApp();
const [uploading, setUploading] = useState(false);
const props: UploadProps = {
name: 'file',
multiple: false,
accept: '.xlsx,.xls',
showUploadList: true,
beforeUpload: async (file) => {
setUploading(true);
try {
await store.uploadImport(file as File);
message.success('模板已提交,后端解析中');
} catch (e) {
message.error((e as Error).message);
} finally {
setUploading(false);
}
// 返回 false 阻止 antd 自动上传,由我们手动走后端
return false;
},
};
return (
<>
<UAlert
type="info"
showIcon
style={{ marginBottom: 16 }}
message="Excel 由后端解析"
description="上传《【优加】门店上架模版-V1.0.1.xlsx》,前端仅做文件提交;模板版本一致性校验在后端完成。"
/>
<UParagraph type="secondary">
前端不引入 Excel 解析库,文件经 /api/store-import 提交,由后端完成解析与校验。
</UParagraph>
<UUpload.Dragger {...props} disabled={uploading}>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text">点击或拖拽门店上架模版到此处</p>
<p className="ant-upload-hint">支持 .xlsx / .xls,单文件</p>
</UUpload.Dragger>
</>
);
}
import { BulbFilled } from '@ant-design/icons';
import { UCard } from '@uj/ui';
const rules = [
'主服务商切换:主服务商由「深圳嘀加」变更为「深圳优加」;凡在优加系统中完成上架的门店,嘀加系统中对应门店的主服务商必须同步更新为「深圳优加」。',
'北森同步:需考虑北森同步处理,优加进入同步配置,组织与人员账号同步范围扩展至优加主体。',
'商品上架利润率测算:非优加门店的测算逻辑保持不变;优加门店不需要重复计算一次,避免毛利被重复扣减出现「负毛利」。',
'上架规则回补:把优加上架规则内容回补到嘀加上架模板中,方便对账数据计算——以优加上架表中对应的内容为准,回填到嘀加系统。',
'上架时序建议:建议嘀加系统先上架、优加系统后上架,且两者上架的时间间隔在同一天内完成。',
];
export function NoticeSection() {
return (
<UCard
styles={{
body: { padding: '16px 20px' },
}}
style={{
marginBottom: 20,
border: '1px solid #C7D2FE',
background: 'linear-gradient(90deg, #EEF2FF 0%, #F5F3FF 100%)',
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
marginBottom: 14,
}}
>
<span
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 6,
padding: '2px 10px',
borderRadius: 10,
background: '#4F46E5',
color: '#fff',
fontSize: 12,
fontWeight: 500,
}}
>
<BulbFilled style={{ fontSize: 12 }} />
上架联动规则
</span>
<span style={{ fontSize: 14, fontWeight: 600, color: '#3730A3' }}>
主服务商切换与外部系统联动要点
</span>
</div>
<ol style={{ margin: 0, paddingLeft: 0, listStyle: 'none' }}>
{rules.map((r, i) => (
<li
key={i}
style={{
display: 'flex',
gap: 10,
fontSize: 13,
color: '#4B5563',
lineHeight: 1.7,
marginBottom: i === rules.length - 1 ? 0 : 6,
}}
>
<span
style={{
flex: 'none',
width: 18,
height: 18,
borderRadius: '50%',
background: '#E0E7FF',
color: '#4338CA',
fontSize: 11,
fontWeight: 600,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
{i + 1}
</span>
<span style={{ flex: 1 }}>{r}</span>
</li>
))}
</ol>
</UCard>
);
}
import { useState } from 'react';
import { App } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { UButton } from '@uj/ui';
import { store } from '@/api';
const DEFAULT_TEMPLATE = '【优加】门店上架模版-V1.0.1.xlsx';
export function PageHeader() {
const { message } = App.useApp();
const [downloading, setDownloading] = useState(false);
const handleDownload = async () => {
if (downloading) return;
setDownloading(true);
try {
await store.downloadImportTemplate(DEFAULT_TEMPLATE);
message.success('模板下载成功');
} catch (e) {
message.error((e as Error).message ?? '模板下载失败');
} finally {
setDownloading(false);
}
};
const actions = [
{
key: 'download',
label: '下载模板',
icon: <DownloadOutlined />,
loading: downloading,
onClick: handleDownload,
},
{
key: 'spec',
label: '查看导入规范',
icon: null as React.ReactNode,
loading: false,
onClick: () => {
console.log('查看导入规范');
},
},
];
return (
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'flex-start',
marginBottom: 20,
}}
>
<div>
<h1
style={{
fontSize: 20,
fontWeight: 600,
margin: 0,
color: '#1A202C',
}}
>
导入门店信息
</h1>
<p
style={{
fontSize: 13,
color: '#6B7280',
margin: '8px 0 0',
lineHeight: 1.6,
}}
>
按《{DEFAULT_TEMPLATE}》导入单个门店的商务政策(一行 = 一个产品分类),
校验通过并提交审批,审批通过后门店方可对外展示。
</p>
</div>
<div style={{ display: 'flex', gap: 12 }}>
{actions.map((a) => (
<UButton key={a.key} icon={a.icon ?? undefined} loading={a.loading} onClick={a.onClick}>
{a.label}
</UButton>
))}
</div>
</div>
);
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!