Commit 80185a58 by chenwq

Merge branch 'master' of http://192.168.3.233:8090/ujia/uj-admin

2 parents 33e7a2d3 12ee1475
Pipeline #392 for 80185a58 failed in 0 seconds
Showing 49 changed files with 2218 additions and 272 deletions
import $router from '../router/index' import $router from '../router/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/** /**
* 微信校验通知类工具封装 * 微信校验通知类工具封装
...@@ -97,16 +96,30 @@ const wxShowToast = (name, params) => { ...@@ -97,16 +96,30 @@ const wxShowToast = (name, params) => {
} }
} }
/**获取设备信息 */ /**获取设备信息
const getSystemInfo = callBack => { * 兼容两种调用约定,对齐原生 wx.getSystemInfo:
getSystemInfo({ * - 对象形式 getSystemInfo({ success, fail, complete })
success(res) { * - 函数形式 getSystemInfo(callBack) —— 成功/失败以同一 callBack 回调
callBack(res) * 基础库 2.20.1+ 起 wx.getSystemInfo 已废弃,内部改用新接口合并返回。
}, */
fail(err) { const getSystemInfo = options => {
callBack(err) const callBack = typeof options === 'function' ? options : null
const onSuccess = callBack || (options && options.success)
const onFail = callBack || (options && options.fail)
const onComplete = options && options.complete
try {
const windowInfo = wx.getWindowInfo() || {}
const appBaseInfo = wx.getAppBaseInfo() || {}
const deviceInfo = wx.getDeviceInfo() || {}
const systemSetting = wx.getSystemSetting() || {}
const appAuthorizeSetting = wx.getAppAuthorizeSetting() || {}
const res = { ...deviceInfo, ...appBaseInfo, ...windowInfo, ...systemSetting, ...appAuthorizeSetting }
onSuccess && onSuccess(res)
} catch (err) {
onFail && onFail(err)
} finally {
onComplete && onComplete()
} }
})
} }
/**拨打电话 */ /**拨打电话 */
......
import wxqrcode from '~/utils/lib/wxqrcode.js' import wxqrcode from '~/utils/lib/wxqrcode.js'
import $router from '../router/index' import $router from '../router/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/** /**
* 微信校验通知类工具封装 * 微信校验通知类工具封装
*/ */
...@@ -93,16 +93,30 @@ const wxShowToast = (name, params) => { ...@@ -93,16 +93,30 @@ const wxShowToast = (name, params) => {
} }
} }
/**获取设备信息 */ /**获取设备信息
const getSystemInfo = callBack => { * 兼容两种调用约定,对齐原生 wx.getSystemInfo:
getSystemInfo({ * - 对象形式 getSystemInfo({ success, fail, complete })
success(res) { * - 函数形式 getSystemInfo(callBack) —— 成功/失败以同一 callBack 回调
callBack(res) * 基础库 2.20.1+ 起 wx.getSystemInfo 已废弃,内部改用新接口合并返回。
}, */
fail(err) { const getSystemInfo = options => {
callBack(err) const callBack = typeof options === 'function' ? options : null
const onSuccess = callBack || (options && options.success)
const onFail = callBack || (options && options.fail)
const onComplete = options && options.complete
try {
const windowInfo = wx.getWindowInfo() || {}
const appBaseInfo = wx.getAppBaseInfo() || {}
const deviceInfo = wx.getDeviceInfo() || {}
const systemSetting = wx.getSystemSetting() || {}
const appAuthorizeSetting = wx.getAppAuthorizeSetting() || {}
const res = { ...deviceInfo, ...appBaseInfo, ...windowInfo, ...systemSetting, ...appAuthorizeSetting }
onSuccess && onSuccess(res)
} catch (err) {
onFail && onFail(err)
} finally {
onComplete && onComplete()
} }
})
} }
/**拨打电话 */ /**拨打电话 */
......
...@@ -22,6 +22,19 @@ import { ...@@ -22,6 +22,19 @@ import {
SolutionOutlined, SolutionOutlined,
HomeOutlined, HomeOutlined,
SettingOutlined, SettingOutlined,
CarOutlined,
FundProjectionScreenOutlined,
AimOutlined,
ExperimentOutlined,
ControlOutlined,
ToolOutlined,
SendOutlined,
ReconciliationOutlined,
UserSwitchOutlined,
FileTextOutlined,
SafetyCertificateOutlined,
WechatOutlined,
PayCircleOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { useAccess, buildMenus, type MenuGroupDef } from '@/access'; import { useAccess, buildMenus, type MenuGroupDef } from '@/access';
import { useAppStore } from '@/store/useAppStore'; import { useAppStore } from '@/store/useAppStore';
...@@ -59,7 +72,9 @@ const EXTRA_TITLES: Record<string, string> = { ...@@ -59,7 +72,9 @@ const EXTRA_TITLES: Record<string, string> = {
'/profile': '个人资料', '/profile': '个人资料',
}; };
// 图标注册表:菜单数据只存图标名,渲染时查表(新增图标在这里登记即可) // 图标注册表:菜单数据(后端 sys_menu.icon / 兜底 menu.json)只存图标名,渲染时查表。
// 这里刻意用字面量而不是 `import * as antdIcons` 动态取:后者会把 894 个图标全打进首屏。
// 代价是后端新增菜单图标必须在这里同步登记一行,漏了会在 dev 控制台点名(见 resolveIcon)。
const iconMap: Record<string, React.ReactNode> = { const iconMap: Record<string, React.ReactNode> = {
DashboardOutlined: <DashboardOutlined />, DashboardOutlined: <DashboardOutlined />,
ShopOutlined: <ShopOutlined />, ShopOutlined: <ShopOutlined />,
...@@ -74,6 +89,20 @@ const iconMap: Record<string, React.ReactNode> = { ...@@ -74,6 +89,20 @@ const iconMap: Record<string, React.ReactNode> = {
SolutionOutlined: <SolutionOutlined />, SolutionOutlined: <SolutionOutlined />,
HomeOutlined: <HomeOutlined />, HomeOutlined: <HomeOutlined />,
SettingOutlined: <SettingOutlined />, SettingOutlined: <SettingOutlined />,
// 二手车管理(scripts/usedcar-menu-complete.sql)
CarOutlined: <CarOutlined />,
FundProjectionScreenOutlined: <FundProjectionScreenOutlined />,
AimOutlined: <AimOutlined />,
ExperimentOutlined: <ExperimentOutlined />,
ControlOutlined: <ControlOutlined />,
ToolOutlined: <ToolOutlined />,
SendOutlined: <SendOutlined />,
ReconciliationOutlined: <ReconciliationOutlined />,
UserSwitchOutlined: <UserSwitchOutlined />,
FileTextOutlined: <FileTextOutlined />,
SafetyCertificateOutlined: <SafetyCertificateOutlined />,
WechatOutlined: <WechatOutlined />,
PayCircleOutlined: <PayCircleOutlined />,
}; };
/** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */ /** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */
const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />; const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />;
......
...@@ -8,10 +8,24 @@ ...@@ -8,10 +8,24 @@
# - secret = 老系统 secret(glsx SHA1 加签私钥,sign 为 40 位大写) # - secret = 老系统 secret(glsx SHA1 加签私钥,sign 为 40 位大写)
# - version = 老系统 sign.v(默认 1.0.0) # - version = 老系统 sign.v(默认 1.0.0)
# - format = 老系统 sign.format(默认 json) # - format = 老系统 sign.format(默认 json)
#
# origin 协议:内网 IP / localhost 可用 http;公网域名一律 https。
# 公网 http 会被 nginx 301 到 https,而浏览器跟随 301 时把 POST 降成 GET 并丢掉请求体,
# 表现是「状态 200、响应没数据」,网关侧报「缺少 appKey 参数」(body 没了)。
#
# origin 环境:scrm 与 dj 两行必须取自同一行环境(下表),换环境时一起换。
# 老网关的 sessionId 是分环境签发的,不是全局通行证:同一个 scrm-base-*-rop 在 scrm.dev 实测
# code 0 出数据,在 scrm.test 实测 code 21 无效的sessionId。所以域名一旦和「主壳后端签发
# loginToken 的那个环境」不一致,每个接口都会被判死,看起来像登录失效,实际是配置错环境。
# 这张对照表由 out/.temp/wire-check.mjs ⑬⑭ 从 apps/mp/usedcar/utils/request/environment.js 现读现核。
# 必填:scrm-shopmall 网关地址 # 必填:scrm-shopmall 网关地址(下面三行是同一环境的成对写法,取哪一组都要和 dj 那行同环境)
VITE_POINTS_GATEWAY_ORIGIN=http://192.168.1.158:8788/ # dev(开发内网,主壳后端默认签发的就是它)
# VITE_POINTS_GATEWAY_ORIGIN=http://scrm.test.glsx.com.cn/ VITE_POINTS_GATEWAY_ORIGIN=https://scrm.dev.glsx.com.cn/
# uat(测试域)
# VITE_POINTS_GATEWAY_ORIGIN=https://scrm.test.glsx.com.cn/
# 本机起的老服务
# VITE_POINTS_GATEWAY_ORIGIN=http://192.168.1.158:8788/
# 必填:加签凭据 # 必填:加签凭据
VITE_POINTS_GATEWAY_APP_KEY=your-app-key VITE_POINTS_GATEWAY_APP_KEY=your-app-key
...@@ -21,5 +35,9 @@ VITE_POINTS_GATEWAY_SECRET=your-secret ...@@ -21,5 +35,9 @@ VITE_POINTS_GATEWAY_SECRET=your-secret
VITE_POINTS_GATEWAY_VERSION=1.0.0 VITE_POINTS_GATEWAY_VERSION=1.0.0
VITE_POINTS_GATEWAY_FORMAT=json VITE_POINTS_GATEWAY_FORMAT=json
# 选填:dj-smartcarlife 网关独立 origin(默认与 scrm-shopmall 同域;独立域名请改) # 必填:dj 网关独立 origin(老系统与二手车小程序的环境表里 dj 与 scrm 从来是两个域名)。
VITE_POINTS_DJ_GATEWAY_ORIGIN= # 留空不会退回 scrm 域名:dj 路由挂在 scrm 域名上是 nginx 405 Not Allowed,
# 因此 credentials.ts 按网关查表取地址,缺了当场报「未配置 dj-smartcarlife 网关地址」。
# 换环境时和上面的 scrm 行一起换(协议按 ⑪ 的规则:公网写 https,哪怕小程序环境表里那行是 http)。
# dev uat prod 分别是 dj.dev / dj.test / dj.glsx.com.cn
VITE_POINTS_DJ_GATEWAY_ORIGIN=https://dj.dev.glsx.com.cn/
...@@ -6,17 +6,18 @@ ...@@ -6,17 +6,18 @@
--- ---
## 1. 静态闸门(本机实测,2026-11-06) ## 1. 静态闸门(本机实测,2026-11-06 首测 / 2026-11-10 复测)
| 闸门 | 命令 | 结果 | | 闸门 | 命令 | 结果 |
| ------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | ------ | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 类型 | `npx tsc --noEmit` | 0 错 | | 类型 | `npx tsc --noEmit` | 0 错 |
| Lint | `npx eslint . --max-warnings=0` | 0 错 0 警 | | Lint | `npx eslint . --max-warnings=0` | 0 错 0 警 |
| 格式 | `npx prettier --check`(本子应用全量) | 通过 | | 格式 | `npx prettier --check`(本子应用全量) | 通过 |
| 构建 | `npx vite build` | 通过,3310 模块 / 1505.86 kB(gzip 480.88 kB) | | 构建 | `npx vite build` | 通过,3332 模块 / 1546.60 kB(gzip 495.51 kB)(2026-11-10 复测) |
| 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1(store 既有 CSS,与本次无关);扫描 3 个子应用,points 在内 | | 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1:`src/features/shared/page.css` 含裸 `.ant-*` 选择器(既有视觉收口,非本次新增;确认没覆盖组件内部几何属性即可);扫描 3 个子应用、5 个小程序,points 在内 |
| 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 | | 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 |
| 签名 | `pnpm --filter @uj/api-core test`(`test/glsxSign.test.mjs`) | 真实抓包 11 字段复算 → `689F62277A050D6285B1E38BB2C3DA8D8E518EC9` 精确命中;MD5(32 位)明确不符,已固化成防回归闸门 | | 签名 | `pnpm --filter @uj/api-core test`(`test/glsxSign.test.mjs`) | 真实抓包 11 字段复算 → `689F62277A050D6285B1E38BB2C3DA8D8E518EC9` 精确命中;MD5(32 位)明确不符,已固化成防回归闸门。整套 111 个(2026-11-10 新增 005/006 钉出口摊平、FT-REALM-001 钉跨 realm 文案) |
| 出口 | `node out/.temp/wire-check.mjs` | 17 组全离线断言,逐条见 §4;2026-11-10 起 ⑯ 管摊平、⑰ 管错误文案 |
浏览器里逐个页面的验收没做 —— 按约定静态闸门到此为止,视觉与交互由你点。第 9 节是可以照着点的清单。 浏览器里逐个页面的验收没做 —— 按约定静态闸门到此为止,视觉与交互由你点。第 9 节是可以照着点的清单。
...@@ -29,12 +30,12 @@ ...@@ -29,12 +30,12 @@
主壳菜单只需要配三个入口,其余五条是页面内部跳转(`goTo()`),菜单不用配也不该配。 主壳菜单只需要配三个入口,其余五条是页面内部跳转(`goTo()`),菜单不用配也不该配。
| 菜单 | 地址栏 | 页面 | | 菜单 | 地址栏 | 页面 |
| ------------------------------------------ | --------------------------------------------------- | ---------------------------------- | | ---------------------------------------- | --------------------------------------------------- | ---------------------------------------------- |
| 积分核销订单 | `/points/list` | `pages/OrderList` | | 积分核销订单 | `/points/list` | `pages/OrderList` |
| ↳ 查看 | `/points/order/<id>` | `pages/OrderDetail` | | ↳ 查看(抽屉) | 列表内抽屉,不跳路由 | `pages/OrderList/components/OrderDetailDrawer` |
| 用户积分明细 | `/points/users` | `pages/ScoreUsers` | | 用户积分明细 | `/points/users` | `pages/ScoreUsers` |
| ↳ 积分详情(续保/阳光激励,按门店+手机号) | `/points/user/<channelSource>/<merchantId>/<phone>` | `pages/UserScoreDetail` | | ↳ 积分详情(阳光激励,按员工号) | `/points/user/<channelSource>/<staffId>` | `pages/UserScoreDetail` |
| ↳ 积分详情(管理层,按员工号) | `/points/user/<channelSource>/<staffId>` | `pages/UserScoreDetail` | | ↳ 积分详情(续保/管理层,按门店+手机号) | `/points/user/<channelSource>/<merchantId>/<phone>` | `pages/UserScoreDetail` |
| 积分提现管理 | `/points/withdraw` | `pages/WithdrawManage`(两个 tab) | | 积分提现管理 | `/points/withdraw` | `pages/WithdrawManage`(两个 tab) |
| ↳ 编辑批次 | `/points/batch/<id>` | `pages/WithdrawBatch` | | ↳ 编辑批次 | `/points/batch/<id>` | `pages/WithdrawBatch` |
| ↳ 到账明细 | `/points/arrival/<id>` | `pages/WithdrawArrival` | | ↳ 到账明细 | `/points/arrival/<id>` | `pages/WithdrawArrival` |
...@@ -105,18 +106,40 @@ ...@@ -105,18 +106,40 @@
## 4. 接口不变,加一层适配 ## 4. 接口不变,加一层适配
接口方法名、入参字段、返回结构一个字没改;改的是「怎么发出去、怎么读回来」。适配层在 [src/adapter/](file:///D:/work/uj-admin/apps/web/subapps/points/src/adapter/index.ts),回答三件事,每件事只有一种答法: 接口方法名、入参字段、返回结构一个字没改;改的是「怎么发出去、怎么读回来」。适配层在 [src/adapter/](file:///D:/work/uj-admin/apps/web/subapps/points/src/adapter/index.ts),回答下面几件事,每件事只有一种答法:
1. **一个系统一套策略。** `GatewayId = 'scrm-shopmall' | 'scrm-carlife' | 'dj-smartcarlife'`,各自带 `router` 路径、令牌放哪个头(前两个 `token`,dj 是 `TGT`)、用哪个签名器。第三个系统再接进来时新增一个 `GatewayStrategy`,页面与业务模块不需要知道对方是谁。 1. **一个系统一套策略。** `GatewayId = 'scrm-shopmall' | 'scrm-carlife' | 'dj-smartcarlife'`,各自带 `router` 路径、令牌放哪个头(前两个 `token`,dj 是 `TGT`)、用哪个签名器。第三个系统再接进来时新增一个 `GatewayStrategy`,页面与业务模块不需要知道对方是谁。
2. **签名是可替换的策略,不是散在页面里的代码。** glsx 系用 **SHA1**:`secret + 按 key 升序拼接的 k+v + secret` 取 SHA1,**40 位大写**(不是 MD5,MD5 只有 32 位,曾误用导致验签必挂);timestamp 进签名原文,非字符串参数按 JSON 原文参与拼接。唯一实现是 api-core 的 `createSigner()` 不传参默认值(`gateways/glsx.ts` 只声明它),依据是 `glsx-common/src/util.js#createSign` 的默认 `way='sha1'`;真实抓包 golden 值固化在 `packages/api-core/test/glsxSign.test.mjs`。老系统的 `noSignAttr` 换成 `unsignedKeys`。 方法名里的 `dj.` / `scrm.` 前缀**不**代表落点域名:老系统里只有 `dj.smartcarlife.api.shopMerchant.list` 与 `dj.api.smartcarlife.merchant.score.deduct.order.page` 真打 dj 路由,`dj.api.shopmall.staff.score.*` 走的是 scrm-shopmall router。这条对照从 `temp/scrm-micro-points` 现读,不靠人记(见下文 ⑬)。
2. **签名是可替换的策略,不是散在页面里的代码。** glsx 系用 **SHA1**:`secret + 按 key 升序拼接的 k+v + secret` 取 SHA1,**40 位大写**(不是 MD5,MD5 只有 32 位,曾误用导致验签必挂);timestamp 进签名原文;数组与嵌套对象在加签**之前**摊平成 `ids[0]` / `a.b` 这样的标量键(第 6 条),不存在「非字符串参数按 JSON 原文拼接」这种形态。唯一实现是 api-core 的 `createSigner()` 不传参默认值(`gateways/glsx.ts` 只声明它),依据是 `glsx-common/src/util.js#createSign` 的默认 `way='sha1'`;真实抓包 golden 值固化在 `packages/api-core/test/glsxSign.test.mjs`。老系统的 `noSignAttr` 换成 `unsignedKeys`。
3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。 3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。
4. **请求体一律 `application/x-www-form-urlencoded`。** 这个头写在 `@uj/api-core` 的 `prepareRpcCall`(web 与小程序共用同一份组装),不在子应用装配层重复声明,也不由传输层默认值决定。少了它,axios 会把同一个对象按 JSON 发出去,而 glsx rop 网关只按 form 解析请求体,于是返回 HTTP 200 + `<error code="22">缺少appKey参数</error>`:状态正常、响应里没数据,看不出是编码问题。
5. **`usedCarFlag=1` 是这个系统的数据身份,不是筛选条件。** 后端把它加在 13 个接口的请求体上(`StaffScoreRopRequest` / `IntegralOrderPageRequest` / `IntegralTransferOutPageRequest` 三组,同组的导出、金额合计、一键操作校验各自复用),传 `1` = 只返回二手车展业门店数据、不传 = 原逻辑查全部。本系统只服务二手车,所以口径定成**一律传 1**:字段名与取值只在 [api/core/usedCarScope.ts](file:///D:/work/uj-admin/apps/web/subapps/points/src/api/core/usedCarScope.ts) 定义一次,由唯一的请求出口 [api/core/rpc-client.ts](file:///D:/work/uj-admin/apps/web/subapps/points/src/api/core/rpc-client.ts) 在 `rpc()` 里注入并覆盖。带来的三个后果都是刻意的:
- 页面上没有「门店范围」下拉了 —— 一个改了也不改变结果的控件比没有控件更坏;三屏的字段表与表单初值里都不再出现这个字段。
- 详情地址少一段:`/points/user/<channelSource>/<staffId>` 与 `/points/user/<channelSource>/<merchantId>/<phone>`。范围不再随地址流动,因为它不随任何人变。
- 覆盖范围按出口算,不按清单算:`wire-check.mjs` ⑩ 逐个复算 **53 个已登记方法**(需求点名的 13 个只是其中的子集),新接一个接口不需要登记条件就一定带 —— 漏不掉,也不需要谁记得。
将来若真要同域共存第二套部署(非二手车),改的是这个常量与注入点,而不是往页面里加回控件。
6. **数组与嵌套对象在请求出口摊平,签名原文与请求体是同一份字节。** `ids: [214, 213, 212]` → `ids[0]=214&ids[1]=213&ids[2]=212`,嵌套对象 → `a.b`,`null` → 空串,`undefined` 和空数组连键都不出现。规则逐字对齐老系统 `glsx-common/src/util.js#createSign` 里的 `qs.stringify({ arrayFormat: 'indices', allowDots: true, encodeValuesOnly: true })`,实现只有一处:`packages/api-core/src/gateway/dispatcher.ts` 的 `flattenFormParams`,在 `prepareRpcCall` 合并完 `fixedParams` / 业务参数 / 会话号之后、加签之前跑一次。web 与小程序共用这条组装,所以 points、mp/points、mp/sales 的数组入参一起被修正。
为什么值得单独一条:摊平如果交给传输层决定,axios 默认按 `ids[]=214&ids[]=213` 发出去,而签名原文里拼的是 JSON 数组本体,两边字节不同,网关回 `code 25 无效签名`。2026-11-10 提现批量付款的抓包正是这个形态(`source / ids[0..2] / canApprove / usedCarFlag / sessionId / method / appKey / format / timestamp / v / sign`),现象是一句文案正确的 `25` 落在所有带 `ids` 的批量操作上(审核、驳回、付款、打标、生成批次、金额合计)—— 一次签名错,六个入口一起红。
判据两道:`wire-check.mjs` ⑯ 对 53 个出口逐个复算摊平结果,并用 `node:crypto` 独立重算一遍签名(不 import 生产签名器,防止两处一起错);`glsxSign.test.mjs` IT-GLSX-SIGN-005 用一次线上真实应答(固定 timestamp,`code 0`,`payAmount: 1200`)钉住键序与 golden。
请求仍然全部经 `requestViaHost()` → `window.$wujie.props.request(config)`,铁律「请求层绝不下放」没有被破坏([ARCHITECTURE.md §2](file:///D:/work/uj-admin/ARCHITECTURE.md))。 请求仍然全部经 `requestViaHost()` → `window.$wujie.props.request(config)`,铁律「请求层绝不下放」没有被破坏([ARCHITECTURE.md §2](file:///D:/work/uj-admin/ARCHITECTURE.md))。
- 免签接口 5 个:`checkTransferType`、`sumAllPayAmount`、`settleAmount`、`payChannels`、`balance`(对老系统逐个核过);`importXlsx` 提交文件但签名原文里排除 `file`。 - **这个网关没有免签接口。** 老系统里那 5 个方法(`checkTransferType`、`sumAllPayAmount`、`settleAmount`、`payChannels`、`balance`)看着像「不签」,实测逐个打过去只证明了三件事:不带 appKey → `code 22 缺少appKey参数`;带 appKey 不带 sign → `code 24 缺少签名参数`;两者齐全 → `code 0 调用服务成功`。早先按「免签」登记时,`signed:false` 把整个身份信封一起跳过了,于是累计结算金额那条永远是一排 `—`。现在接口层不允许 `signed:false`(`wire-check.mjs` ⑮ 直接把它判红);`importXlsx` 提交文件但签名原文里排除 `file`,这是唯一的例外,走 `unsignedKeys`。
- **后端的原话必须落到页面上。** 网关已经回了 `code 25` 和一句「签名无效,请按正确的算法…」,页面却仍旧显示「操作失败,请稍后重试」,原因是 realm:子应用的代码在 wujie 的 iframe realm 里,请求由主壳的 `props.request` 抛出,那个 Error 在子应用侧 `instanceof Error` 与 `instanceof RequestError` 全是 false,于是 message 和 `code` 一起被丢掉,业务失败被当成传输失败 —— 文案变笼统、多弹一个 toast、还白重试一次。修法是两处:api-core 用 `isRequestError()`(认对象自己写上去的标记,不认原型链)配合 `wrapError()` 原样保留文案与码(`core/errors.ts`、`core/facade.ts`),points 侧 `features/shared/format.ts#errorMessage` 只按字段取值、拿到纯数字码就缀上「(网关码 25)」,取不到任何文字才用兜底句。判据:`facade.test.mjs` FT-REALM-001 用 `node:vm` 造一个真·另一个 realm 的 Error,断言只发一次请求、不多弹 toast;`wire-check.mjs` ⑰ 核文案矩阵(有码 / 无码 / 字符串 / undefined 四种输入)。
- 超时对齐老系统 180 s(导入/导出这类慢接口不会被前端提前掐断)。 - 超时对齐老系统 180 s(导入/导出这类慢接口不会被前端提前掐断)。
- 唯一一处「老系统没有的出口」:`scrm.api.shopmall.integralorder.page` / `.export`(门店版,不带 `all.`,见 `api/modules/points.ts` 的 `pageStoreOrders` / `exportStoreOrders`)。后端让它与运营版共用同一份 `IntegralOrderPageRequest`,`usedCarFlag` 同样生效;老系统只登记了 `all.*`,这两个是给门店端复用而在此登记的,**当前没有 UI 调用点,别当死代码删**(删前确认门店端没在用它)。
**主机侧要给的配置**(缺了会明确报错,不会静默):`VITE_POINTS_GATEWAY_ORIGIN` / `_APP_KEY` / `_SECRET` / `_VERSION`(缺省 1.0.0)/ `_FORMAT`(缺省 json),dj 网关另给 `VITE_POINTS_DJ_GATEWAY_ORIGIN`。适配层不留任何密钥字面量。 **主机侧要给的配置**(缺了会明确报错,不会静默):`VITE_POINTS_GATEWAY_ORIGIN` / `_APP_KEY` / `_SECRET` / `_VERSION`(缺省 1.0.0)/ `_FORMAT`(缺省 json),以及 `VITE_POINTS_DJ_GATEWAY_ORIGIN`(用到门店列表就是必填)。适配层不留任何密钥字面量。
origin 与请求体有四处容易踩的坑,都固化成了 `wire-check.mjs` 的断言(⑪⑫⑬⑭),不靠人记住:
- **协议**:内网 IP / localhost 用 http,公网域名必须 https。`scrm.test.glsx.com.cn` 的 nginx 对 http 一律 301,而浏览器跟随 301 会把 POST 降成 GET 并丢掉请求体 —— 现象是「状态 200、响应空白」。⑪ 核 `.env` / `.env.example` 里每个 origin 的协议。
- **域名与网关配套**:dj 路由不在 scrm 域名上,`scrm.test.glsx.com.cn/rop-dj-smartcarlife/router` 的 POST 直接被 nginx 挡成 405 Not Allowed。因此 `credentials.ts` 改成按网关查表取地址、缺了当场报错,不再「读不到就退回 scrm 域名」(兜底的后果是门店列表静默无数据)。⑬ 用两份事实核对:方法→router 逐个对齐 `temp/scrm-micro-points`,router→域名对齐二手车小程序的环境表 `apps/mp/usedcar/utils/request/environment.js`。
- **线上字节**:⑫ 跑完整两跳(子应用 `prepareRpcCall` → 主壳 `web-host` 方案 → 主壳那台 axios 的 adapter),断言真正离开浏览器的 body 是 `source=…&usedCarFlag=1&…&sign=…` 的 form 串而不是 JSON。
- **会话分环境**:`sessionId`(主壳 `loginToken`)是**某个环境签发的会话**,不是全局通行证。实测同一个 `scrm-base-*-rop` 在 `scrm.dev.glsx.com.cn` 回 `code:'0'` 出数据,在 `scrm.test.glsx.com.cn` 回 `code:'21' 无效的sessionId`。所以 scrm 与 dj 两个 origin 必须取自环境表的**同一行**,换环境一起换 —— ⑭ 就是把 `.env` 的两行拿去和小程序环境表逐行对齐。
这条的连锁现象要认得:`21` 归一成 `10002` 触发统一登出、清掉 `loginToken`,同一屏里后发的那条请求因此连 `sessionId` 都带不上,网关回 `code:'20' 缺少sessionId参数`。两条错误码是同一个配置错的两次呼吸,不是两个 bug。
联调前跑 `node out/.temp/wire-check.mjs`(17 组,全离线,不需要登录态)。
--- ---
...@@ -162,7 +185,7 @@ points 摮瓷 bypass 閫 ...@@ -162,7 +185,7 @@ points 摮瓷 bypass 閫
--- ---
## 7. 与老系统的九处差异(每处是选择,不是漏) ## 7. 与老系统的十处差异(每处是选择,不是漏)
1. **批量结算导入放开**(老代码注释状态)——按需求清单第 ① 项。 1. **批量结算导入放开**(老代码注释状态)——按需求清单第 ① 项。
2. **三层渠道级联筛选 → 三个联动下拉**:候选来自老系统同三个接口,选完上一层才发下一层请求,提交字段仍是 `paymentSubjectId` / `paymentChannelId`(后者存代征主体 id,字段名是历史遗留),与老系统逐字节相同。付款审批**弹窗**里保留了真级联懒加载。 2. **三层渠道级联筛选 → 三个联动下拉**:候选来自老系统同三个接口,选完上一层才发下一层请求,提交字段仍是 `paymentSubjectId` / `paymentChannelId`(后者存代征主体 id,字段名是历史遗留),与老系统逐字节相同。付款审批**弹窗**里保留了真级联懒加载。
...@@ -173,6 +196,7 @@ points 摮瓷 bypass 閫 ...@@ -173,6 +196,7 @@ points 摮瓷 bypass 閫
7. **审批状态字典合一份**:老系统筛选用 `statusList`、列渲染用 `tableStatus`,两份文案一致 → 合并成一份 `APPROVAL_STATUS`;到账明细页复用 9 项的 `TRANSFER_STATUS`,0-6 项文案与老系统那 7 项逐字相同。 7. **审批状态字典合一份**:老系统筛选用 `statusList`、列渲染用 `tableStatus`,两份文案一致 → 合并成一份 `APPROVAL_STATUS`;到账明细页复用 9 项的 `TRANSFER_STATUS`,0-6 项文案与老系统那 7 项逐字相同。
8. **提现导入的表头校验交给后端**:老页面在前端解析 xlsx 比对 10 个固定列名(从 A9 起)。本子应用依赖里没有 xlsx,加它要改工作区外的 `pnpm-workspace.yaml`,属于 6.1 之外的越界;文件不合规时导入接口回 `errorUrl`,弹窗按失败态给可下载模版。要恢复前端预校验 = 允许装 `xlsx` 依赖。 8. **提现导入的表头校验交给后端**:老页面在前端解析 xlsx 比对 10 个固定列名(从 A9 起)。本子应用依赖里没有 xlsx,加它要改工作区外的 `pnpm-workspace.yaml`,属于 6.1 之外的越界;文件不合规时导入接口回 `errorUrl`,弹窗按失败态给可下载模版。要恢复前端预校验 = 允许装 `xlsx` 依赖。
9. **「受理失败」的颜色不按老系统照抄**:老系统把这一项涂成绿色,是那一行复制粘贴抄错了;现在按语义给红(`dictionaries.ts:78` 已注明)。 9. **「受理失败」的颜色不按老系统照抄**:老系统把这一项涂成绿色,是那一行复制粘贴抄错了;现在按语义给红(`dictionaries.ts:78` 已注明)。
10. **详情地址就是老系统那两段,不多一段**:`user/<channelSource>/<staffId>` 与 `user/<channelSource>/<merchantId>/<phone>`。中途曾经末尾补过一段 `all`/`1`(`usedCarFlag`),用来让流水与顶部四张卡跟着列表页的范围走;范围改成系统级恒定值之后,这一段没有任何信息量,已经删干净。留下的兼容性问题只有一种:改造期间发出去的旧链接(带末段)。它们的下场是「接不住」而不是「查错人」—— 四段形制会被读成「门店+手机号」那一类、因缺标识落到「缺少用户标识」提示,五段形制匹配不到任何路由(离线核对 ⑥⑦⑧ 三组断言钉住)。
--- ---
...@@ -195,5 +219,6 @@ points 摮瓷 bypass 閫 ...@@ -195,5 +219,6 @@ points 摮瓷 bypass 閫
3. `/points/withdraw`:累计结算金额条与弹窗 → 全部生成批次 → 勾几条做批量审核 / 付款 / 驳回 / 生成批次 → 不勾选做一键审核 / 一键付款 → 标签标注 → 自定义标签(增、改、删、三层)→ 提现导入 → 导出 → 行查看 / 审核 / 驳回 / 付款 → 身份证与协议两个单元格。 3. `/points/withdraw`:累计结算金额条与弹窗 → 全部生成批次 → 勾几条做批量审核 / 付款 / 驳回 / 生成批次 → 不勾选做一键审核 / 一键付款 → 标签标注 → 自定义标签(增、改、删、三层)→ 提现导入 → 导出 → 行查看 / 审核 / 驳回 / 付款 → 身份证与协议两个单元格。
4. 第二个 tab:查看 → 付款审批(三层级联、税点重算总额、验证码倒计时)→ 编辑进批次(解散 / 移除)→ 到账明细(受理失败行再次打款)→ 行导出。 4. 第二个 tab:查看 → 付款审批(三层级联、税点重算总额、验证码倒计时)→ 编辑进批次(解散 / 移除)→ 到账明细(受理失败行再次打款)→ 行导出。
5. 权限:让后端只下发一个 `points:*` 码,验证其余按钮会隐藏(三态闸门的第二态)。 5. 权限:让后端只下发一个 `points:*` 码,验证其余按钮会隐藏(三态闸门的第二态)。
6. 门店范围(`usedCarFlag`):口径是「一律带 1」,所以验的是**任何一条请求都带**,而不是某个控件选了才带。打开三屏(`/points/list`、`/points/users`、`/points/withdraw`)不做任何操作,Network 里首屏分页请求的 form 数据就应有 `usedCarFlag: 1`;导出、提现页的累计结算金额条、一键审核/付款的合计与限制门店校验同样带 1。三屏的筛选区不应再出现「门店范围」下拉,地址栏里也不应再出现 `all` 或末段的范围值。
签名原文与摘要算法已用 glsx-common 源码 + 2026-11-09 真实抓包复算钉死(SHA1 / 40 位大写,见 `test/glsxSign.test.mjs`),但还没跑过真实网关 —— 第一次联调的判据就是接口 200 且 `code:'0'`;失败不会静默,会带着方法名和返回码说人话。 签名原文与摘要算法已用 glsx-common 源码 + 2026-11-09 真实抓包复算钉死(SHA1 / 40 位大写,见 `test/glsxSign.test.mjs`),但还没跑过真实网关 —— 第一次联调的判据就是接口 200 且 `code:'0'`;失败不会静默,会带着方法名和返回码说人话。
/**
* 数组参数的线上字节钉值:固定 timestamp 后发一次真实请求,让网关自己认证这份 sign。
* 用法:node out/.temp/array-golden.mjs <sessionId>
* 只读金额合计接口,不写任何数据。
*/
import { readFileSync } from 'node:fs';
import { createServer, loadConfigFromFile } from 'vite';
const SID = process.argv[2];
if (!SID) {
console.log('用法:node out/.temp/array-golden.mjs <sessionId>');
process.exit(1);
}
const lines = readFileSync('.env', 'utf8')
.split('\n')
.filter((line) => /^[A-Z_]+=/.test(line))
.map((line) => line.split('='));
const val = (k) => lines.find(([key]) => key === k)?.[1]?.trim() ?? '';
const credential = {
origin: val('VITE_POINTS_GATEWAY_ORIGIN'),
appKey: val('VITE_POINTS_GATEWAY_APP_KEY'),
secret: val('VITE_POINTS_GATEWAY_SECRET'),
version: '1.0.0',
format: 'json',
};
const TIMESTAMP = 1794300000000;
const realNow = Date.now;
Date.now = () => TIMESTAMP;
const cfg = await loadConfigFromFile({ command: 'serve', mode: 'development' }, 'vite.config.ts');
const server = await createServer({
...cfg.config,
appType: 'custom',
optimizeDeps: { noDiscovery: true, include: [] },
server: { ...cfg.config.server, middlewareMode: true },
logLevel: 'error',
});
const apiCore = await server.ssrLoadModule('@uj/api-core');
await server.ssrLoadModule('/src/adapter/gateways/index.ts');
const raw = await apiCore.prepareRpcCall(
{
gateway: 'scrm-shopmall',
method: 'scrm.api.shopmall.integral.transfer.out.pay.amount',
params: { ids: ['214', '213', '212'], canApprove: false, usedCarFlag: '1' },
},
{
resolveCredential: () => credential,
resolveToken: () => SID,
session: { name: 'sessionId', value: SID },
timeout: 60000,
},
);
Date.now = realNow;
const body = raw.data;
const form = new URLSearchParams(
Object.entries(body).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)]),
).toString();
const reply = await fetch(raw.url, {
method: 'POST',
headers: { ...raw.headers, 'content-type': 'application/x-www-form-urlencoded' },
body: form,
}).then(async (r) => ({ http: r.status, t: await r.text() }));
console.log('url :', raw.url);
console.log('timestamp :', TIMESTAMP);
console.log('keys :', JSON.stringify(Object.keys(body)));
console.log('body :', form.replace(/(appKey=)[^&]+/, '$1…').replace(/(sign=)[^&]+/, '$1…'));
console.log('sign :', body.sign);
console.log('reply :', `HTTP ${reply.http}`, reply.t.slice(0, 220));
console.log('appKey :', credential.appKey);
await server.close();
/**
* 数组参数(ids[])为什么回 code 25:三种发法逐字节对比。
* 用法:node out/.temp/array-sign-probe.mjs <sessionId> [origin]
* 只读金额合计接口,不写任何数据。
*/
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { createServer, loadConfigFromFile } from 'vite';
const SID = process.argv[2];
if (!SID) {
console.log('用法:node out/.temp/array-sign-probe.mjs <sessionId> [origin]');
process.exit(1);
}
const lines = readFileSync('.env', 'utf8')
.split('\n')
.filter((line) => /^[A-Z_]+=/.test(line))
.map((line) => line.split('='));
const val = (k) => lines.find(([key]) => key === k)?.[1]?.trim() ?? '';
const credential = {
origin: process.argv[3] || val('VITE_POINTS_GATEWAY_ORIGIN'),
appKey: val('VITE_POINTS_GATEWAY_APP_KEY'),
secret: val('VITE_POINTS_GATEWAY_SECRET'),
version: '1.0.0',
format: 'json',
};
const cfg = await loadConfigFromFile({ command: 'serve', mode: 'development' }, 'vite.config.ts');
const server = await createServer({
...cfg.config,
appType: 'custom',
optimizeDeps: { noDiscovery: true, include: [] },
server: { ...cfg.config.server, middlewareMode: true },
logLevel: 'error',
});
const apiCore = await server.ssrLoadModule('@uj/api-core');
await server.ssrLoadModule('/src/adapter/gateways/index.ts');
const deps = {
resolveCredential: () => credential,
resolveToken: () => SID,
session: { name: 'sessionId', value: SID },
timeout: 60000,
};
const METHOD = 'scrm.api.shopmall.integral.transfer.out.pay.amount';
const IDS = [214, 213, 212];
const PARAMS = { ids: IDS, canApprove: false };
const send = async (url, headers, fields, label) => {
const body = new URLSearchParams(
Object.entries(fields).map(([k, v]) => [k, typeof v === 'string' ? v : String(v)]),
).toString();
const reply = await fetch(url, {
method: 'POST',
headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' },
body,
})
.then((r) => r.text().then((t) => ({ http: r.status, t })))
.catch((e) => ({ http: 0, t: String(e) }));
const code =
(reply.t.match(/"code"\s*:\s*"(\d+)"/) ?? reply.t.match(/code="(\d+)"/) ?? [])[1] ?? '?';
const message =
(reply.t.match(/"message"\s*:\s*"([^"]*)"/) ?? reply.t.match(/<message>([^<]*)</) ?? [])[1] ??
'';
const solution = (reply.t.match(/"solution"\s*:\s*"([^"]*)"/) ?? [])[1] ?? '';
console.log(`\n【${label}】`);
console.log(
` body : ${body.replace(/&sign=[^&]*/, '&sign=…').replace(/(appKey=)[^&]*/, '$1…')}`,
);
console.log(
` 回话 : HTTP ${reply.http} code=${code} ${message}${solution ? ` / ${solution.slice(0, 40)}` : ''}`,
);
};
// ① 现状:api-core 直接发嵌套数组,body 由传输层决定怎么编码(浏览器里是 ids[]=…)。
const asIs = await apiCore.prepareRpcCall(
{ gateway: 'scrm-shopmall', method: METHOD, params: { ...PARAMS, usedCarFlag: '1' } },
deps,
);
await send(asIs.url, asIs.headers, asIs.data, '① 现状:params 里放数组');
// ② 老系统:glsx-common/createSign 用 qs(arrayFormat:indices, allowDots) 摊平后再签名,
// body 也发摊平后的键(ids[0]=…)。这是网关认的那份字节。
const legacyRequire = createRequire('D:/work/npm/glsx-common/package.json');
const qs = legacyRequire('qs');
const sha1 = legacyRequire('sha1');
const legacyParams = {
...PARAMS,
usedCarFlag: '1',
source: 'uj-web-points',
sessionId: SID,
method: METHOD,
appKey: credential.appKey,
format: credential.format,
v: credential.version,
};
// 逐字照抄 glsx-common/src/util.js#createSign(先塞 timestamp,再 qs 摊平,摊平后的键名才拿去排序)
legacyParams.timestamp = Date.now();
const strQs = qs.stringify(legacyParams, {
arrayFormat: 'indices',
allowDots: true,
encodeValuesOnly: true,
});
const collect = strQs.split('&').reduce((acc, item) => {
const [key, value] = item.split('=');
acc[key] = decodeURIComponent(value ?? '');
return acc;
}, {});
const keys = Object.keys(collect).sort();
const str = keys.reduce(
(col, key) => (key === 'sign' ? col : (col.push(key, collect[key] ?? ''), col)),
[],
);
collect.sign = sha1(`${credential.secret}${str.join('')}${credential.secret}`).toUpperCase();
await send(asIs.url, { token: SID }, collect, '② 老系统:qs 摊平 ids[0]/ids[1]/ids[2] 后加签');
// ③ 修复预演:出口先把数组摊平成 ids[0]/ids[1]/ids[2] 再交给 prepareRpcCall,
// 签名与 body 因此同源,仍然全部走 api-core。
const flattened = {};
strQs.split('&').forEach((item) => {
const [key, value] = item.split('=');
if (key !== 'ids[0]' && key !== 'ids[1]' && key !== 'ids[2]') return;
flattened[key] = decodeURIComponent(value);
});
console.log(
`\n(摊平对照:qs 给出的键名 = ${Object.keys(collect)
.filter((k) => k.startsWith('ids'))
.join(', ')})`,
);
const simulated = await apiCore.prepareRpcCall(
{
gateway: 'scrm-shopmall',
method: METHOD,
params: { ...flattened, canApprove: false },
},
deps,
);
await send(
simulated.url,
simulated.headers,
simulated.data,
'③ 修复预演:出口先摊平,再签名、再发',
);
await server.close();
/**
* 用真签名直连网关,判定 sessionId 这一层到底错在哪:
* A 只放请求体 / B 只放 token 头 / C 两处都放 / D 都不放(对照)。
*/
import { readFileSync } from 'node:fs';
import { createServer, loadConfigFromFile } from 'vite';
const SID = process.argv[2] ?? 'scrm-base-a9846af8-0a90-48ce-93ea-99d852a905da-rop';
// 第三个参数可换域名试同一个 sessionId:判定「会话过期」还是「环境不匹配」
const ORIGIN = process.argv[3] ?? '';
const METHOD = 'scrm.api.shopmall.integralorder.all.page';
const env = readFileSync('.env', 'utf8');
const val = (k) => env.match(new RegExp(`^${k}=(\\S+)`, 'm'))?.[1] ?? '';
const credential = {
origin: val('VITE_POINTS_GATEWAY_ORIGIN'),
appKey: val('VITE_POINTS_GATEWAY_APP_KEY'),
secret: val('VITE_POINTS_GATEWAY_SECRET'),
version: '1.0.0',
format: 'json',
};
const cfg = await loadConfigFromFile({ command: 'serve', mode: 'development' }, 'vite.config.ts');
const server = await createServer({
...cfg.config,
appType: 'custom',
optimizeDeps: { noDiscovery: true, include: [] },
server: { ...cfg.config.server, middlewareMode: true },
logLevel: 'error',
});
const send = async (label, { bodySid, headerSid }) => {
const apiCore = await server.ssrLoadModule('@uj/api-core');
await server.ssrLoadModule('/src/adapter/gateways/index.ts');
const raw = await apiCore.prepareRpcCall(
{ gateway: 'scrm-shopmall', method: METHOD, params: { currentPage: 1, pageSize: 1 } },
{
resolveCredential: () => (ORIGIN ? { ...credential, origin: ORIGIN } : credential),
resolveToken: () => (headerSid ? SID : ''),
session: bodySid ? { name: 'sessionId', value: SID } : undefined,
timeout: 180000,
},
);
const form = new URLSearchParams(
Object.entries(raw.data).map(([k, v]) => [k, String(v)]),
).toString();
const res = await fetch(raw.url, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded', ...(raw.headers ?? {}) },
body: form,
});
const text = (await res.text()).replace(/\s+/g, ' ').slice(0, 160);
const sentSid = raw.data.sessionId ? '有' : '无';
console.log(
`${label} body.sessionId=${sentSid} token头=${headerSid ? '有' : '无'}\n → ${text}\n`,
);
};
try {
console.log('打到', ORIGIN || credential.origin);
await send('A 只放请求体 ', { bodySid: true, headerSid: false });
await send('B 只放 token 头 ', { bodySid: false, headerSid: true });
await send('C 两处都放 ', { bodySid: true, headerSid: true });
await send('D 都不放(对照) ', { bodySid: false, headerSid: false });
console.log('被试 sessionId =', SID);
} finally {
await server.close();
}
/**
* 直连网关复现「累计结算金额」这一条:完全照子应用的发法(同一个方法名、同样不加签)。
* 用法:node out/.temp/settle-probe.mjs <sessionId> [origin]
* 只读统计接口,不写任何数据。
*/
import { readFileSync } from 'node:fs';
import { createServer, loadConfigFromFile } from 'vite';
const SID = process.argv[2];
if (!SID) {
console.log('用法:node out/.temp/settle-probe.mjs <sessionId> [origin]');
process.exit(1);
}
const lines = readFileSync('.env', 'utf8')
.split('\n')
.filter((line) => /^[A-Z_]+=/.test(line))
.map((line) => line.split('='));
const val = (k) => lines.find(([key]) => key === k)?.[1]?.trim() ?? '';
const credential = {
origin: process.argv[3] || val('VITE_POINTS_GATEWAY_ORIGIN'),
appKey: val('VITE_POINTS_GATEWAY_APP_KEY'),
secret: val('VITE_POINTS_GATEWAY_SECRET'),
version: '1.0.0',
format: 'json',
};
const cfg = await loadConfigFromFile({ command: 'serve', mode: 'development' }, 'vite.config.ts');
const server = await createServer({
...cfg.config,
appType: 'custom',
optimizeDeps: { noDiscovery: true, include: [] },
server: { ...cfg.config.server, middlewareMode: true },
logLevel: 'error',
});
const apiCore = await server.ssrLoadModule('@uj/api-core');
await server.ssrLoadModule('/src/adapter/gateways/index.ts');
const deps = {
resolveCredential: () => credential,
resolveToken: () => SID,
session: { name: 'sessionId', value: SID },
timeout: 60000,
};
const METHOD = {
settleAmount: 'scrm.api.shopmall.integral.transfer.out.settle.amount.get',
sumAllPayAmount: 'scrm.api.shopmall.integral.transfer.out.all.pay.amount',
checkTransferType: 'scrm.api.shopmall.integral.transfer.out.check.records.transferType',
payChannels: 'scrm.api.shopmall.integral.transfer.out.getChannel',
balance: 'scrm.api.shopmall.integral.transfer.out.balance.get',
};
const ask = async (method, mode) => {
// 子应用的请求出口现在一律带 usedCarFlag=1,这里照搬,保证三种发法只差在签名上。
const raw = await apiCore.prepareRpcCall(
{ gateway: 'scrm-shopmall', method, params: { usedCarFlag: '1' }, signed: mode.signed },
deps,
);
const fields = { ...raw.data };
if (mode.dropSign) delete fields.sign;
const form = new URLSearchParams(
Object.entries(fields).map(([k, v]) => [k, typeof v === 'string' ? v : JSON.stringify(v)]),
).toString();
const reply = await fetch(raw.url, {
method: 'POST',
headers: { ...raw.headers, 'content-type': 'application/x-www-form-urlencoded' },
body: form,
})
.then((r) => r.text().then((t) => ({ http: r.status, t })))
.catch((e) => ({ http: 0, t: String(e) }));
const code =
(reply.t.match(/"code"\s*:\s*"(\d+)"/) ?? reply.t.match(/code="(\d+)"/) ?? [])[1] ?? '?';
const message =
(reply.t.match(/"message"\s*:\s*"([^"]*)"/) ?? reply.t.match(/<message>([^<]*)</) ?? [])[1] ??
'';
return `HTTP ${reply.http} code=${code} ${message.slice(0, 26)}`;
};
// 三种发法:照现在(signed:false,信封也不发)/ 信封齐但不带 sign / 信封齐且带 sign
for (const [name, method] of Object.entries(METHOD)) {
const asIs = await ask(method, { signed: false });
const noSign = await ask(method, { signed: true, dropSign: true });
const withSign = await ask(method, { signed: true });
console.log(`${name.padEnd(17)} 现状:${asIs} | 信封无sign:${noSign} | 带sign:${withSign}`);
}
await server.close();
/**
* usedCarFlag 上线前的线上传参核对(离线:不依赖登录态、不依赖真实网关)。
*
* 口径变了:后端把这个字段加在 13 个接口上,而这个系统只服务二手车展业门店,
* 所以它不是筛选条件,是数据身份 —— 一律带 usedCarFlag=1,没有「全部」这一档。
* 于是这里要核的不再是「选了对不对」,而是三件事:
* ① 契约只有一个值,且覆盖任何传入草稿;
* ② 全仓只有一处注入(请求出口),页面、字段表、地址栏都不再碰它;
* ③ 逐个复算登记的每一个出口(53 个),确认组装层不会把它丢掉。
* ④ - ⑧ 核地址:范围段已从路由里删掉,旧地址只会「接不住」,不会静默查错人。
* ⑨ - ⑭ 核落点与联调配置:方法→router→域名、origin 协议、form 请求体、两个网关同环境。
* ⑮ - ⑰ 核线上字节的三条硬规则:没有免签接口(少 sign 就是 code 24)、
* 数组与嵌套对象必须在出口摊平(否则签名原文与请求体两套字节,网关回 code 25)、
* 后端给的失败原因必须原样出现在页面上(跨 realm 的错误不是本域 Error 实例)。
*/
import { createServer, loadConfigFromFile } from 'vite';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync } from 'node:fs';
import { createRequire } from 'node:module';
import { join } from 'node:path';
const cfg = await loadConfigFromFile({ command: 'serve', mode: 'development' }, 'vite.config.ts');
const server = await createServer({
...cfg.config,
appType: 'custom',
optimizeDeps: { noDiscovery: true, include: [] },
server: { ...cfg.config.server, middlewareMode: true },
logLevel: 'error',
});
const load = (p) => server.ssrLoadModule(p);
// 环境表只回答「哪个域名属于哪一路、哪一行」,协议由 ⑪ 单独核,所以这里一律剥掉协议再比。
const host = (origin) => new URL(origin).host;
const groups = [];
const check = async (name, fn) => {
await fn();
groups.push(name);
};
const DOCUMENTED = [
'dj.api.shopmall.staff.score.page',
'dj.api.shopmall.staff.score.export',
'dj.api.shopmall.staff.score.detail.list',
'dj.api.shopmall.staff.score.detail.list.export',
'scrm.api.shopmall.integralorder.all.page',
'scrm.api.shopmall.integralorder.all.export',
'scrm.api.shopmall.integralorder.page',
'scrm.api.shopmall.integralorder.export',
'scrm.api.shopmall.integral.transfer.out.page',
'scrm.api.shopmall.integral.transfer.out.export',
'scrm.api.shopmall.integral.transfer.out.all.pay.limit.store.check',
'scrm.api.shopmall.integral.transfer.out.all.pay.amount',
'scrm.api.shopmall.integral.transfer.out.settle.amount.get',
];
try {
const scope = await load('/src/api/core/usedCarScope.ts');
const { matchRoute } = await load('/src/routes.ts');
const fmt = await load('/src/features/shared/format.ts');
const fields = await load('/src/pages/WithdrawManage/tools/fields.ts');
await check('① 契约只有一个值:字段名 usedCarFlag、取值 1,并覆盖调用方传进来的任何东西', () => {
assert.equal(scope.USED_CAR_FIELD_NAME, 'usedCarFlag');
assert.equal(scope.USED_CAR_FLAG, '1');
assert.deepEqual(scope.withUsedCarScope({ currentPage: 1 }), {
currentPage: 1,
usedCarFlag: '1',
});
// 表单草稿、旧地址段、别处传来的 0/空串一律无效:口径不接受第二处定义。
for (const draft of ['', '0', 'all', undefined, null]) {
assert.equal(scope.withUsedCarScope({ usedCarFlag: draft }).usedCarFlag, '1');
}
});
await check('② 注入点唯一:全仓只有请求出口写这个字段,页面与接口方法都不写', () => {
// 只看代码行:注释里提到这个字段名是给人讲原理,不算第二处口径。
const codeOf = (f) =>
readFileSync(f, 'utf8')
.split('\n')
.filter((line) => !/^\s*(\/\/|\*)/.test(line))
.join('\n');
const files = readdirSync('src', { recursive: true })
.filter((p) => /[\w.-]\.(ts|tsx)$/.test(String(p)))
.map((p) => join('src', String(p)))
.filter((f) => codeOf(f).includes('usedCarFlag'));
assert.deepEqual(
files,
[join('src', 'api', 'core', 'usedCarScope.ts')],
`usedCarFlag 又出现在别处(${files.join(', ')}):口径回到两处,「一律带」就变成「看哪处生效」`,
);
// 出口那一行必须在,而且是包一层而不是拼参数
const client = readFileSync(join('src', 'api', 'core', 'rpc-client.ts'), 'utf8');
assert.match(client, /params:\s*withUsedCarScope\(params\)/, '请求出口没有接上注入');
});
await check('③ 提现字段表里已经没有这个条件(它不再是表单字段)', () => {
const list = fields.buildTransferFields({
channels: [],
entities: [],
merchants: [],
brands: [],
provinces: [],
tags: [],
});
assert.equal(list.filter((f) => f.name === 'usedCarFlag').length, 0);
});
await check('④ 表单与地址栏都不再携带范围:三屏字段表 + 路由表逐个核', () => {
const pages = [
'src/pages/OrderList/index.tsx',
'src/pages/ScoreUsers/index.tsx',
'src/pages/UserScoreDetail/index.tsx',
'src/pages/WithdrawManage/tools/fields.ts',
'src/pages/WithdrawManage/WithdrawList.tsx',
'src/App.tsx',
];
for (const f of pages) {
const code = readFileSync(f, 'utf8')
.split('\n')
.filter((line) => !/^\s*(\/\/|\*)/.test(line))
.join('\n');
assert.ok(
!/usedCarFlag|USED_CAR|usedCarSegment|usedCarFlagFromSegment/.test(code),
`${f} 还在处理门店范围:范围条件已经上移到请求出口,页面留着只会造成「表单选了没用」的假控件`,
);
}
assert.deepEqual(fmt.compactParams({ usedCarFlag: '', status: '0' }), { status: '0' });
assert.deepEqual(fields.toTransferParams({ status: '' }), {});
});
const appSrc = readFileSync('src/App.tsx', 'utf8');
const ROUTES = [...appSrc.matchAll(/\{\s*path:\s*'([^']+)'/g)].map((m) => ({
path: m[1],
Page: () => null,
}));
await check('⑤ 路由表读到 7 条', () => {
assert.equal(ROUTES.length, 7);
});
await check('⑥ 每条路由只接自己的地址,且每个值落回自己的参数名', () => {
ROUTES.forEach((route, index) => {
const names = [];
const values = [];
const url = route.path
.split('/')
.map((segment, k) => {
if (!segment.startsWith(':')) return segment;
names.push(segment.slice(1));
values.push(`v${index}${k}`);
return values[values.length - 1];
})
.join('/');
const matched = matchRoute(ROUTES, url);
assert.ok(matched, `「${url}」(${route.path})匹配不到任何路由`);
assert.deepEqual(
Object.keys(matched.params).sort(),
[...names].sort(),
`「${url}」(${route.path})被另一种形状接走:${Object.keys(matched.params).join(',')}`,
);
names.forEach((name, k) => {
assert.equal(matched.params[name], values[k], `「${url}」的 ${name} 值错位`);
});
});
});
await check('⑦ 列表拼出的详情地址,详情页接得住,地址里只剩「哪一个人」', () => {
const usersSrc = readFileSync('src/pages/ScoreUsers/index.tsx', 'utf8');
assert.match(usersSrc, /`user\/1\/\$\{encodeURIComponent\(row\.staffId\)\}`/);
assert.match(
usersSrc,
/`user\/\$\{channelSource\}\/\$\{encodeURIComponent\(\s*row\.merchantId,?\s*\)\}\/\$\{encodeURIComponent\(\s*row\.staffPhone,?\s*\)\}`,?/,
);
const sunshine = matchRoute(ROUTES, 'user/1/9');
assert.equal(sunshine?.params.staffId, '9');
assert.equal(sunshine?.params.usedCarFlag, undefined, '地址里不该再有范围段');
const renewal = matchRoute(ROUTES, 'user/2/7001/13800000000');
assert.deepEqual(renewal?.params, {
channelSource: '2',
merchantId: '7001',
phone: '13800000000',
});
});
await check('⑧ 改造前的旧地址(带范围末段)只会「接不住」,不会静默查错人', () => {
// 旧四段 user/1/<staffId>/<scope> 如今会落到「门店+手机号」那条路由上:
// 阳光激励渠道要求 staffId 定位,缺了就查不出人,页面走「标识不全」而不是拿 9/1 当门店手机号去查别人。
const stale = matchRoute(ROUTES, 'user/1/9/1');
assert.equal(stale?.params.channelSource, '1');
assert.equal(stale?.params.staffId, undefined);
// 旧五段(续保/管理层 + 范围)没有对应路由:整条地址不命中,提示页而非查到错的人。
assert.equal(matchRoute(ROUTES, 'user/2/7001/13800000000/1'), undefined);
});
const apiSrc = ['src/api/modules/points.ts', 'src/api/modules/withdraw.ts']
.map((f) => readFileSync(f, 'utf8'))
.join('\n');
const endpoints = [
...apiSrc.matchAll(/['"]((?:scrm|dj)-[\w-]+)['"]\s*,\s*['"]([\w.]+)['"]/g),
].map(([, gateway, method]) => ({ gateway, method }));
await check('⑨ 需求里的 13 个接口全部在接口层有出口(含两个门店版)', () => {
for (const method of DOCUMENTED) {
assert.ok(
endpoints.some((e) => e.method === method),
`${method} 在 api/modules 里没有出口`,
);
}
assert.equal(DOCUMENTED.length, 13);
});
await load('/src/adapter/gateways/index.ts');
const apiCore = await load('@uj/api-core');
const deps = {
resolveCredential: () => ({
origin: 'https://gateway.test',
appKey: 'ak',
secret: 'sk',
version: '1.0.0',
format: 'json',
}),
resolveToken: () => 'tok',
session: { name: 'sessionId', value: 'sid' },
timeout: 180000,
};
await check(
'⑩ 逐个复算请求体:登记的每个出口都带 usedCarFlag=1,签名与落点不受影响',
async () => {
const seen = new Set();
for (const { gateway, method } of endpoints) {
if (seen.has(method)) continue;
seen.add(method);
// 页面只会交来表单与分页参数;范围由请求出口注入后到这里。
// 这一跳验的是「组装层既不会丢掉它,也不会把它当成多余字段处理掉」。
const raw = await apiCore.prepareRpcCall(
{ gateway, method, params: scope.withUsedCarScope({ currentPage: 1, pageSize: 10 }) },
deps,
);
assert.equal(raw.data.usedCarFlag, '1', `${method} 的 body 丢了 usedCarFlag`);
assert.equal(raw.data.method, method, `${method} 的落点方法名不对`);
// 渠道名 2026-11-10 起由本域自报 'uj-web-points'(老抓包里是老系统的 'scrm-home');
// 它进签名原文但不参与身份校验,线上实测 code 0。换名要连同 api-core 的钉值一起重取。
assert.equal(raw.data.source, 'uj-web-points', `${method} 丢了网关固定渠道参数`);
assert.match(raw.url, /\/rop-[\w-]+\/router$/, `${method} 落点算错:${raw.url}`);
if (DOCUMENTED.includes(method)) {
assert.equal(typeof raw.data.sign, 'string', `${method} 没产生签名字段`);
assert.equal(raw.data.sign.length, 40, `${method} 的签名不是 SHA1 40 位`);
}
}
for (const method of DOCUMENTED) {
assert.ok(seen.has(method), `${method} 没进逐个复算:接口层登记与需求清单脱节了`);
}
console.log(
` · 逐个复算覆盖 ${seen.size} 个出口,需求点名的 ${DOCUMENTED.length} 个全在其中`,
);
},
);
await check('⑪ .env 里的网关 origin 协议:公网必须 https(http 会被 301 掉请求体)', () => {
// 公网 http 会被 nginx 301 到 https,浏览器跟随 301 时把 POST 降成 GET 并丢掉 body:
// 现象是「200 但响应空白」。内网 IP / localhost 不受这条约束。
const isPrivate = (host) =>
/^localhost$/.test(host) ||
/^127\./.test(host) ||
/^10\./.test(host) ||
/^192\.168\./.test(host) ||
/^172\.(1[6-9]|2\d|3[01])\./.test(host);
const origins = ['.env', '.env.example']
.flatMap((f) =>
readFileSync(f, 'utf8')
.split('\n')
.filter((line) => /^#?\s*VITE_POINTS_\w*GATEWAY_ORIGIN=\S/.test(line)),
)
.map((line) =>
line
.replace(/^\s*#\s*/, '')
.split('=')
.slice(1)
.join('=')
.trim(),
);
assert.ok(origins.length >= 2, `.env / .env.example 里没读到网关 origin`);
for (const raw of origins) {
const { protocol, hostname } = new URL(raw);
if (protocol === 'https:') continue;
assert.ok(
isPrivate(hostname),
`${raw}:公网地址用 http,会被 301 转到 https 并丢掉 POST 请求体,改成 https://`,
);
}
});
await check('⑫ 线上字节:经主壳那一跳后,请求体真的是 form 串(网关只认这个)', async () => {
// 老网关按 form 解析请求体;一旦发成 JSON,网关读不到 appKey/method,
// 回的是 HTTP 200 + `<error code="22">缺少appKey参数</error>`——看着像没数据,其实是没解析。
// 这里跑完整两跳:子应用组装(prepareRpcCall)→ 主壳方案(web-host)→ 主壳那台 axios 的序列化。
// axios 只装在主壳:借同一份实例,验的正是它会怎么编码请求体。
const axios = createRequire(join(process.cwd(), '../../shell/package.json'))('axios');
let wire = null;
const ax = axios.create({
adapter: (config) => {
const h = config.headers;
wire = {
data: config.data,
ct: (h && h.get && h.get('content-type')) || h?.['content-type'],
};
return Promise.resolve({
data: '{"code":"0","data":[]}',
status: 200,
headers: {},
config,
});
},
});
const shell = apiCore.createClient({
kind: 'web-host',
sender: {
send: async (req) => {
const r = await ax.request({
url: req.url,
method: req.method,
data: req.data,
headers: req.headers,
});
return { status: 200, data: r.data, headers: {} };
},
},
});
for (const method of [
'scrm.api.shopmall.integralorder.all.page',
'dj.api.shopmall.staff.score.page',
]) {
const raw = await apiCore.prepareRpcCall(
{
gateway: 'scrm-shopmall',
method,
params: fmt.compactParams({ currentPage: 1, usedCarFlag: '1' }),
},
deps,
);
await shell
.request({ url: raw.url, method: 'POST', data: raw.data, headers: raw.headers })
.catch(() => {});
assert.equal(wire?.ct, 'application/x-www-form-urlencoded', `${method} 线上头是 ${wire?.ct}`);
assert.equal(typeof wire?.data, 'string', `${method} 的请求体没被序列化`);
assert.equal(wire.data.startsWith('{'), false, `${method} 仍按 JSON 发送`);
// 线上真的是「一个个平铺的表单字段」:网关按这个解析 appKey、method 与 usedCarFlag
const form = Object.fromEntries(new URLSearchParams(wire.data));
assert.equal(form.method, method, `${method} 的落点方法名不在 form 字段里`);
assert.equal(form.usedCarFlag, '1', `${method} 的 usedCarFlag 不在 form 字段里`);
assert.equal(form.appKey, 'ak', `${method} 的 appKey 不在 form 字段里`);
assert.equal(String(form.sign).length, 40, `${method} 的签名不在 form 字段里`);
}
});
await check('⑬ 落点与老系统逐项一致:方法→router、router→域名', () => {
// 老系统的 method→router 是唯一事实来源(temp/scrm-micro-points),小程序环境表是域名来源。
const oldDir = '../../../../temp/scrm-micro-points/src/api/modules';
const oldMap = new Map();
for (const f of readdirSync(oldDir)) {
const s = readFileSync(`${oldDir}/${f}`, 'utf8');
let pending = null;
for (const m of s.matchAll(
// 老系统里 method 有反引号也有单引号两种写法(如 checkRecordsTransferType),两种都收。
/params\.method = (?:`([^`]+)`|'([^']+)')|url: '(rop-[\w-]+)\/router'/g,
)) {
const name = m[1] ?? m[2];
if (name) pending = name;
else if (pending) {
oldMap.set(pending, m[3]);
pending = null;
}
}
}
assert.ok(oldMap.size > 40, `老系统只解析出 ${oldMap.size} 条 method→router,解析规则失效了`);
// 我们的 gateway id → 登记的 router(glsx.ts 一处真源)
const glsx = readFileSync('src/adapter/gateways/glsx.ts', 'utf8');
const routerOf = new Map(
[...glsx.matchAll(/id: '([\w-]+)',\s*router: '(rop-[\w-]+)\/router'/g)].map(([, id, r]) => [
id,
r,
]),
);
// 老系统没有的出口(门店版 2 个)必须在这里点名,不能靠「查不到就跳过」蒙过去
const NOT_IN_LEGACY = [
'scrm.api.shopmall.integralorder.page',
'scrm.api.shopmall.integralorder.export',
];
for (const { gateway, method } of endpoints) {
const legacy = oldMap.get(method);
if (!legacy) {
assert.ok(
NOT_IN_LEGACY.includes(method),
`${method} 既不在老系统映射里、也没登记为「老系统没有的出口」`,
);
continue;
}
assert.equal(
routerOf.get(gateway),
legacy,
`${method} 落点错:老系统走 ${legacy},我们走 ${routerOf.get(gateway)}(网关 id=${gateway})`,
);
}
// router 的前缀决定域名:dj 系挂 dj 域,scrm 系挂 scrm 域(小程序同一份环境表)。
// 环境表只回答「哪个域名属于哪一路」,协议归 ⑪ 管(小程序能用 http,浏览器不能用)。
const envTable = readFileSync('../../../mp/usedcar/utils/request/environment.js', 'utf8');
const hostsOf = (kind) =>
// 只认生效行:环境表里注释掉的开发者本机 IP 不算候选。
envTable
.split('\n')
.filter((line) => !/^\s*\/\//.test(line))
.flatMap((line) =>
[...line.matchAll(new RegExp(`\\b${kind}: '(https?://[^']+)'`, 'g'))].map((m) =>
host(m[1]),
),
);
const env = readFileSync('.env', 'utf8');
const originOf = (key) =>
(env.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? '').replace(/\/+$/, '');
const pairs = [
['rop-scrm-shopmall', originOf('VITE_POINTS_GATEWAY_ORIGIN'), hostsOf('scrm')],
['rop-dj-smartcarlife', originOf('VITE_POINTS_DJ_GATEWAY_ORIGIN'), hostsOf('dj')],
];
for (const [router, origin, allowed] of pairs) {
assert.ok(origin, `${router} 的网关地址没配在 .env 里`);
assert.ok(
allowed.includes(host(origin)),
`${router} 的域名 ${origin} 不在小程序环境表的候选里(${allowed.join(' / ')})—— 域名与方法不配套`,
);
}
// 「同一个域名挡 dj 路由成 405」只对分域环境成立;环境表里 cdptest 一行本来就两路共用同一个域名,
// 那种行由表自己解释,不用我们的配置去背这个锅。
const sharedHosts = new Set(hostsOf('scrm').filter((h) => hostsOf('dj').includes(h)));
if (!sharedHosts.has(host(pairs[0][1]))) {
assert.notEqual(
host(pairs[0][1]),
host(pairs[1][1]),
'scrm 与 dj 配成了同一个域名:dj 路由会被 nginx 挡成 405',
);
}
});
await check('⑭ 两个网关必须在同一个环境行(会话号分环境,混了必回 code 21)', () => {
// 老网关的 sessionId 是「某个环境签发的会话」,不是全局通行证:
// 同一个 scrm-base-*-rop 在 scrm.dev 实测 code 0 出数据,在 scrm.test 实测 code 21 判死。
// 所以 scrm 与 dj 必须落在小程序环境表的同一行里,不能一个 dev 一个 test。
// 比的是域名:环境表里 dj.dev 写的是 http(小程序能用 http),浏览器侧的协议由 ⑪ 单独管。
const envTable = readFileSync('../../../mp/usedcar/utils/request/environment.js', 'utf8');
const rows = new Map();
let current = null;
for (const line of envTable.split('\n')) {
if (/^\s*\/\//.test(line)) continue; // 注释掉的开发者本机 IP 不算候选
const block = line.match(/^\s{1,2}(\w+): \{/);
if (block) {
current = block[1];
rows.set(current, {});
continue;
}
const site = line.match(/\b(scrm|dj): '(https?:\/\/[^']+)'/);
if (site && current) rows.get(current)[site[1]] = new URL(site[2]).host;
}
const env = readFileSync('.env', 'utf8');
const originOf = (key) =>
(env.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? '').replace(/\/+$/, '');
const scrmOrigin = originOf('VITE_POINTS_GATEWAY_ORIGIN');
const djOrigin = originOf('VITE_POINTS_DJ_GATEWAY_ORIGIN');
assert.ok(scrmOrigin && djOrigin, '⑭ 需要 .env 里两个网关 origin 都配上,先看 ⑬ 的报错');
const scrm = host(scrmOrigin);
const dj = host(djOrigin);
const matched = [...rows].filter(
([, row]) => row.scrm === scrm && row.dj === dj && row.scrm && row.dj,
);
assert.ok(
matched.length > 0,
`scrm=${scrm} 与 dj=${dj} 不在环境表的同一行里:会话是分环境的,混用必回 code 21 无效的sessionId。` +
`可选行:${[...rows]
.filter(([, r]) => r.scrm && r.dj)
.map(([k, r]) => `${k}(${r.scrm} + ${r.dj})`)
.join(' / ')}`,
);
console.log(` · 两个网关同属环境「${matched[0][0]}」`);
});
await check('⑮ 本域没有免签出口:每个登记的 method 都带 appKey 与 40 位 sign', async () => {
// 线上实测(out/.temp/settle-probe.mjs,5 个原「免签」接口 × 3 种发法):
// 不发 appKey → code 22 缺少appKey参数;发 appKey 不发 sign → code 24 缺少签名参数;两者都发 → code 0。
// 老代码里的 sign:true 标记不是「免签开关」,抄过来就是把每条请求变成必定失败的请求。
const modules = ['src/api/modules/points.ts', 'src/api/modules/withdraw.ts']
.map((f) => readFileSync(f, 'utf8'))
.join('\n');
assert.ok(
!modules.includes('signed: false'),
'接口层又出现 signed:false:这个网关没有免签接口,少 sign 直接 code 24',
);
const seen = new Set();
for (const { gateway, method } of endpoints) {
if (seen.has(method)) continue;
seen.add(method);
const raw = await apiCore.prepareRpcCall(
{ gateway, method, params: scope.withUsedCarScope({}) },
deps,
);
assert.equal(
raw.data.appKey,
'ak',
`${method} 没带 appKey:网关回 code 22,请求根本不会被执行`,
);
assert.equal(
typeof raw.data.sign === 'string' && raw.data.sign.length === 40,
true,
`${method} 的签名缺失或不是 SHA1 40 位:网关回 code 24/25`,
);
}
console.log(` · ${seen.size} 个出口逐个核过身份信封与签名`);
});
await check('⑯ 数组与嵌套对象在出口摊平:签名原文与请求体是同一份字节', async () => {
// 线上症状:勾选 3 条做批量操作,全部回 code 25 无效签名。原因是签名原文里写的是
// `ids[214,213,212]`(JSON 串),而请求体里 `ids` 怎么摊开由传输层决定(浏览器发 ids[]=…);
// 网关只会按它真正收到的键名重算。老系统与二手车小程序都先摊平再加签,摊平点现在在请求出口。
const nested = {
ids: ['214', '213'],
tag: { path: { id: 7 } },
nil: null,
empty: [],
drop: undefined,
};
const seen = new Set();
for (const { gateway, method } of endpoints) {
if (seen.has(method)) continue;
seen.add(method);
const { data: body } = await apiCore.prepareRpcCall(
{ gateway, method, params: nested },
deps,
);
assert.ok(!('ids' in body), `${method} 还在发数组本体:编码规则一旦交给传输层就是两套字节`);
assert.equal(body['ids[0]'], '214', `${method} 的 ids 没摊平成 ids[0]`);
assert.equal(body['ids[1]'], '213', `${method} 的 ids 没摊平成 ids[1]`);
assert.equal(body['tag.path.id'], '7', `${method} 的嵌套对象没摊平成 a.b`);
assert.equal(body.nil, '', `${method} 的 null 应摊成空串键(与 qs 同规则)`);
assert.ok(!('empty' in body), `${method} 的空数组该整个键消失`);
assert.ok(!('drop' in body), `${method} 的 undefined 该整个键消失`);
for (const [key, value] of Object.entries(body)) {
assert.ok(
typeof value === 'string' || typeof value === 'number',
`${method} 的 ${key} 不是标量:${JSON.stringify(value)}`,
);
}
// 独立复算一遍:就用网关 solution 里那句算法(SHA1(<secret> 升序 k+v <secret>)),
// 只喂它收到后会看到的键值对,不借 api-core 的签名器。
const plain = Object.keys(body)
.filter((key) => key !== 'sign')
.sort()
.map((key) => `${key}${body[key]}`)
.join('');
assert.equal(
body.sign,
createHash('sha1').update(`sk${plain}sk`).digest('hex').toUpperCase(),
`${method} 的签名与「按请求体字节重算」的结果不一致:网关按请求体验签,不看我们心里怎么想`,
);
}
console.log(` · ${seen.size} 个出口逐个复算了摊平后的签名`);
});
await check('⑰ 后端的原话必须落到页面上:跨 realm 的错误不降级成笼统提示', () => {
// 请求由主壳代理,错误对象属于主壳那个 realm,在子应用里 `instanceof Error === false`。
// 判断写成 instanceof 时,「无效签名」这种明确原因会被吞成「操作失败,请稍后重试」——
// 这一组断言在修复前是红的,它就是防回归的地方。
assert.equal(fmt.errorMessage({ message: '无效签名', code: '25' }), '无效签名(网关码 25)');
assert.equal(
fmt.errorMessage(Object.assign(new Error('无效签名'), { code: 25 })),
'无效签名(网关码 25)',
'本域 Error 与跨 realm 的普通对象要走同一条判断',
);
assert.equal(
fmt.errorMessage({ message: '提现记录不存在' }),
'提现记录不存在',
'没有码就别硬凑括注',
);
assert.equal(fmt.errorMessage('网关无响应'), '网关无响应');
// 只有「什么都没说」时才允许那句兜底话。
assert.equal(fmt.errorMessage(undefined), '操作失败,请稍后重试');
assert.ok(
!fmt.errorMessage({ message: '无效签名', code: '25' }).includes('操作失败'),
'后端已经说了原因,页面不许再用兜底话盖掉',
);
});
console.log(`wire-check 通过:${groups.length} 组断言`);
groups.forEach((g) => console.log(` ${g}`));
} finally {
await server.close();
}
...@@ -2,7 +2,6 @@ import { useEffect, useMemo, useState } from 'react'; ...@@ -2,7 +2,6 @@ import { useEffect, useMemo, useState } from 'react';
import { busEvents } from '@uj/contracts'; import { busEvents } from '@uj/contracts';
import { SubAppProvider, readInitialPage, shortName, subappBus } from '@uj/platform-sdk'; import { SubAppProvider, readInitialPage, shortName, subappBus } from '@uj/platform-sdk';
import OrderList from './pages/OrderList'; import OrderList from './pages/OrderList';
import OrderDetail from './pages/OrderDetail';
import ScoreUsers from './pages/ScoreUsers'; import ScoreUsers from './pages/ScoreUsers';
import UserScoreDetail from './pages/UserScoreDetail'; import UserScoreDetail from './pages/UserScoreDetail';
import WithdrawManage from './pages/WithdrawManage'; import WithdrawManage from './pages/WithdrawManage';
...@@ -18,7 +17,6 @@ import { UEmpty } from '@uj/ui'; ...@@ -18,7 +17,6 @@ import { UEmpty } from '@uj/ui';
*/ */
const ROUTES: RouteDef[] = [ const ROUTES: RouteDef[] = [
{ path: 'list', Page: OrderList }, { path: 'list', Page: OrderList },
{ path: 'order/:id', Page: OrderDetail },
{ path: 'users', Page: ScoreUsers }, { path: 'users', Page: ScoreUsers },
{ path: 'user/:channelSource/:staffId', Page: UserScoreDetail }, { path: 'user/:channelSource/:staffId', Page: UserScoreDetail },
{ path: 'user/:channelSource/:merchantId/:phone', Page: UserScoreDetail }, { path: 'user/:channelSource/:merchantId/:phone', Page: UserScoreDetail },
......
...@@ -16,25 +16,34 @@ import type { GatewayId } from './types'; ...@@ -16,25 +16,34 @@ import type { GatewayId } from './types';
const env = import.meta.env as Record<string, string | undefined>; const env = import.meta.env as Record<string, string | undefined>;
const SHARED = { const SHARED = {
origin: (env.VITE_POINTS_GATEWAY_ORIGIN ?? '').trim(),
appKey: (env.VITE_POINTS_GATEWAY_APP_KEY ?? '').trim(), appKey: (env.VITE_POINTS_GATEWAY_APP_KEY ?? '').trim(),
secret: (env.VITE_POINTS_GATEWAY_SECRET ?? '').trim(), secret: (env.VITE_POINTS_GATEWAY_SECRET ?? '').trim(),
version: (env.VITE_POINTS_GATEWAY_VERSION ?? '1.0.0').trim(), version: (env.VITE_POINTS_GATEWAY_VERSION ?? '1.0.0').trim(),
format: (env.VITE_POINTS_GATEWAY_FORMAT ?? 'json').trim(), format: (env.VITE_POINTS_GATEWAY_FORMAT ?? 'json').trim(),
}; };
/** 个别网关(dj)在老系统里挂在另一个域名上,允许单独覆盖。 */ /**
const OVERRIDES: Partial<Record<GatewayId, string>> = { * 每个网关的地址来自哪个环境变量 —— 取值与报错文案共用这一张表。
'dj-smartcarlife': (env.VITE_POINTS_DJ_GATEWAY_ORIGIN ?? '').trim(), *
* dj 路由不在 scrm 域名上(那里对 dj 的 POST 直接 405 Not Allowed),老系统与二手车小程序
* 的环境表里 dj 与 scrm 从来是两个域名,所以不给「读不到就退回 scrm」的兜底:
* 兜底的后果是接口静默无数据,排查成本远高于少配一个变量时当场报错。
*/
const GATEWAY_ORIGIN_ENV: Record<GatewayId, string> = {
'scrm-shopmall': 'VITE_POINTS_GATEWAY_ORIGIN',
'scrm-carlife': 'VITE_POINTS_GATEWAY_ORIGIN',
'dj-smartcarlife': 'VITE_POINTS_DJ_GATEWAY_ORIGIN',
}; };
const envOrigin = (id: GatewayId): string => (env[GATEWAY_ORIGIN_ENV[id]] ?? '').trim();
const injected = new Map<GatewayId, GatewayCredential>(); const injected = new Map<GatewayId, GatewayCredential>();
/** 运行时注入(联调脚本、灰度环境或后端下发的配置中心)。 */ /** 运行时注入(联调脚本、灰度环境或后端下发的配置中心)。 */
export function setGatewayCredential(id: GatewayId, credential: Partial<GatewayCredential>): void { export function setGatewayCredential(id: GatewayId, credential: Partial<GatewayCredential>): void {
const previous = injected.get(id); const previous = injected.get(id);
injected.set(id, { injected.set(id, {
origin: credential.origin ?? previous?.origin ?? SHARED.origin, origin: credential.origin ?? previous?.origin ?? envOrigin(id),
appKey: credential.appKey ?? previous?.appKey ?? SHARED.appKey, appKey: credential.appKey ?? previous?.appKey ?? SHARED.appKey,
secret: credential.secret ?? previous?.secret ?? SHARED.secret, secret: credential.secret ?? previous?.secret ?? SHARED.secret,
version: credential.version ?? previous?.version ?? SHARED.version, version: credential.version ?? previous?.version ?? SHARED.version,
...@@ -43,14 +52,11 @@ export function setGatewayCredential(id: GatewayId, credential: Partial<GatewayC ...@@ -43,14 +52,11 @@ export function setGatewayCredential(id: GatewayId, credential: Partial<GatewayC
} }
export function getGatewayCredential(id: GatewayId): GatewayCredential { export function getGatewayCredential(id: GatewayId): GatewayCredential {
const credential = injected.get(id) ?? { const credential = injected.get(id) ?? { ...SHARED, origin: envOrigin(id) };
...SHARED,
origin: OVERRIDES[id] || SHARED.origin,
};
if (!credential.origin) { if (!credential.origin) {
throw new Error( throw new Error(
`未配置 ${id} 网关地址:请在 .env 设置 VITE_POINTS_GATEWAY_ORIGIN(或该网关的独立 origin),` + `未配置 ${id} 网关地址:请在 .env 设置 ${GATEWAY_ORIGIN_ENV[id]}。` +
'积分域的接口不会自动改走主壳后端。', '积分域的接口不会自动改走主壳后端,也不会退回其它网关的域名。',
); );
} }
return credential; return credential;
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: liimin 17653212@qq.com * @Author: liimin 17653212@qq.com
* @Date: 2026-11-06 15:45:47 * @Date: 2026-11-06 15:45:47
* @LastEditors: liimin 17653212@qq.com * @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2026-11-09 18:56:31 * @LastEditTime: 2026-11-10 16:02:45
* @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\gateways\glsx.ts * @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\gateways\glsx.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
...@@ -81,9 +81,10 @@ export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy { ...@@ -81,9 +81,10 @@ export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy {
...def, ...def,
signer: glsxSha1Signer, signer: glsxSha1Signer,
normalize: normalizeGlsxEnvelope, normalize: normalizeGlsxEnvelope,
// 老网关每次请求固定携带、且参与加签的渠道参数:与老系统 / 真实抓包一致用 'scrm-home'。 // 老网关每次请求固定携带、且参与加签的渠道参数。本域自报 'uj-web-points'(2026-11-10 起,
// 改这个值会直接改变签名原文,联调前不要随意换渠道名。 // 不再是抓包里的老系统渠道 'scrm-home'):网关不拿它校验身份,线上实测照常 code 0,
fixedParams: { source: 'scrm-home' }, // 钉值见 packages/api-core/test/glsxSign.test.mjs 的 IT-GLSX-SIGN-005。
fixedParams: { source: 'uj-web-points' },
}; };
} }
......
...@@ -29,15 +29,16 @@ const LEGACY_TIMEOUT = 180000; ...@@ -29,15 +29,16 @@ const LEGACY_TIMEOUT = 180000;
* *
* 装配层只给环境参数: * 装配层只给环境参数:
* · gatewayCredential / gatewayToken —— 本域 .env 凭据与会话令牌,包内不留密钥字面量; * · gatewayCredential / gatewayToken —— 本域 .env 凭据与会话令牌,包内不留密钥字面量;
* · contentType:false —— 不预置 Content-Type,否则会改变主壳加签的 canonical 原文;
* · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等), * · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等),
* 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。 * 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。
*
* 这里不设 contentType:RPC 请求体的编码属于网关事实(glsx rop 只读 form 体),
* 由 prepareRpcCall 随请求头一起给出;在这一层再写一次就是两个真源。
*/ */
export const request = createClient({ export const request = createClient({
transport: 'host', transport: 'host',
hostSend: requestViaHost(), hostSend: requestViaHost(),
timeout: LEGACY_TIMEOUT, timeout: LEGACY_TIMEOUT,
contentType: false,
gatewayCredential: (id) => getGatewayCredential(id as GatewayId), gatewayCredential: (id) => getGatewayCredential(id as GatewayId),
gatewayToken: getGatewayToken, gatewayToken: getGatewayToken,
// sessionId 取自登录接口的 data.loginToken(老网关会话标识);facade 的 resolveSession 会在 // sessionId 取自登录接口的 data.loginToken(老网关会话标识);facade 的 resolveSession 会在
......
import { rpcCall } from '@/adapter'; import { rpcCall } from '@/adapter';
import type { GatewayId } from '@/adapter'; import type { GatewayId } from '@/adapter';
import { withUsedCarScope } from './usedCarScope';
/** /**
* 积分域的接口不是 REST:一个 RPC 方法名 + 一层平铺参数。 * 积分域的接口不是 REST:一个 RPC 方法名 + 一层平铺参数。
...@@ -34,7 +35,9 @@ export class RpcApiClient { ...@@ -34,7 +35,9 @@ export class RpcApiClient {
return rpcCall<T>({ return rpcCall<T>({
gateway, gateway,
method, method,
params, // 本域唯一的请求出口,因此也是「一律带 usedCarFlag=1」唯一的落点:
// 分页、导出、金额合计、一键操作校验全部经过这里,新加的接口不用登记也不会漏。
params: withUsedCarScope(params),
signed: options.signed, signed: options.signed,
unsignedKeys: options.unsignedKeys, unsignedKeys: options.unsignedKeys,
}); });
......
/**
* 「二手车展业门店」是这个系统的数据身份,不是筛选条件。
*
* 后端把 usedCarFlag(Integer)加在三组分页请求体上(StaffScoreRopRequest /
* IntegralOrderPageRequest / IntegralTransferOutPageRequest),同组请求体又被各自的
* 导出、金额合计、一键操作校验复用。取值只有一个口径:`1` = 只返回二手车展业门店的数据。
*
* 因此这个字段不在任何页面表单里出现,也不写在任何接口方法上:它在请求出口一次性注入
* (见 `src/api/core/rpc-client.ts`),本域的每一个 RPC 都必然带上,
* 不会出现「列表筛了、导出不筛」「这页带了、那页漏了」的口径分叉。
* 将来要接「非二手车」的第二套部署,改这一个常量与注入点即可,页面代码不用动。
*/
export const USED_CAR_FIELD_NAME = 'usedCarFlag';
/** 后端只认这一个值:`1` = 二手车展业门店。 */
export const USED_CAR_FLAG = '1';
/**
* 注入并覆盖:调用方传什么都以这里为准。
* 「一律带」是系统级口径,不能被某个页面的表单值改写 —— 所以合并放在最后一步、只放这一处。
*/
export function withUsedCarScope(params: Record<string, unknown>): Record<string, unknown> {
return { ...params, [USED_CAR_FIELD_NAME]: USED_CAR_FLAG };
}
...@@ -38,6 +38,26 @@ class PointsApi extends RpcApiClient { ...@@ -38,6 +38,26 @@ class PointsApi extends RpcApiClient {
return this.rpc<string>('scrm-shopmall', 'scrm.api.shopmall.integralorder.all.export', params); return this.rpc<string>('scrm-shopmall', 'scrm.api.shopmall.integralorder.all.export', params);
} }
/**
* 积分核销订单分页(门店版)。
*
* 后端这两个不带 `all.` 的入口与上面那对共用同一份 `IntegralOrderPageRequest`,
* 因此 `usedCarFlag` 同样生效;老系统只登记了 `all.*`,门店版没有页面调它。
* 这里登记是为了让门店端接入积分订单时不必重新摸接口 —— 看到「无人调用」先别删。
*/
pageStoreOrders(params: Record<string, unknown>) {
return this.rpc<RpcListResult<WriteOffOrder>>(
'scrm-shopmall',
'scrm.api.shopmall.integralorder.page',
params,
);
}
/** 积分核销订单导出(门店版),入参与分页同一份 */
exportStoreOrders(params: Record<string, unknown>) {
return this.rpc<string>('scrm-shopmall', 'scrm.api.shopmall.integralorder.export', params);
}
/** 批量结算导入:file 形如 "<扩展名>@<base64>" */ /** 批量结算导入:file 形如 "<扩展名>@<base64>" */
importSettlement(file: string) { importSettlement(file: string) {
return this.rpc<unknown>('scrm-shopmall', 'scrm.api.shopmall.integralorder.settlement.import', { return this.rpc<unknown>('scrm-shopmall', 'scrm.api.shopmall.integralorder.settlement.import', {
......
...@@ -114,13 +114,12 @@ class WithdrawApi extends RpcApiClient { ...@@ -114,13 +114,12 @@ class WithdrawApi extends RpcApiClient {
); );
} }
/** 校验所选记录 / 查询结果是否为同一提现类型(老系统该接口不加签) */ /** 校验所选记录 / 查询结果是否为同一提现类型(实测该接口仍必须加签) */
checkTransferType(params: Record<string, unknown> = {}) { checkTransferType(params: Record<string, unknown> = {}) {
return this.rpc<TransferTypeCheck>( return this.rpc<TransferTypeCheck>(
'scrm-shopmall', 'scrm-shopmall',
'scrm.api.shopmall.integral.transfer.out.check.records.transferType', 'scrm.api.shopmall.integral.transfer.out.check.records.transferType',
params, params,
{ signed: false },
); );
} }
...@@ -142,23 +141,21 @@ class WithdrawApi extends RpcApiClient { ...@@ -142,23 +141,21 @@ class WithdrawApi extends RpcApiClient {
); );
} }
/** 提现金额合计(按查询条件,一键操作用;老系统该接口不加签) */ /** 提现金额合计(按查询条件,一键操作用;实测仍必须加签,少了 sign 回 code 24) */
sumAllPayAmount(params: Record<string, unknown> = {}) { sumAllPayAmount(params: Record<string, unknown> = {}) {
return this.rpc<PayAmountCheck>( return this.rpc<PayAmountCheck>(
'scrm-shopmall', 'scrm-shopmall',
'scrm.api.shopmall.integral.transfer.out.all.pay.amount', 'scrm.api.shopmall.integral.transfer.out.all.pay.amount',
params, params,
{ signed: false },
); );
} }
/** 累计结算金额统计(按统计项编码平铺;老系统该接口不加签) */ /** 累计结算金额统计(按统计项编码平铺;实测仍必须加签,少了 sign 回 code 24) */
settleAmount(params: Record<string, unknown> = {}) { settleAmount(params: Record<string, unknown> = {}) {
return this.rpc<SettleAmountMap>( return this.rpc<SettleAmountMap>(
'scrm-shopmall', 'scrm-shopmall',
'scrm.api.shopmall.integral.transfer.out.settle.amount.get', 'scrm.api.shopmall.integral.transfer.out.settle.amount.get',
params, params,
{ signed: false },
); );
} }
...@@ -171,13 +168,12 @@ class WithdrawApi extends RpcApiClient { ...@@ -171,13 +168,12 @@ class WithdrawApi extends RpcApiClient {
); );
} }
/** 按提现类型/方式取可付款的渠道列表(单选那一项;老系统该接口不加签) */ /** 按提现类型/方式取可付款的渠道列表(单选那一项;实测仍必须加签,少了 sign 回 code 24) */
payChannels(params: Record<string, unknown> = {}) { payChannels(params: Record<string, unknown> = {}) {
return this.rpc<PayChannelOption[]>( return this.rpc<PayChannelOption[]>(
'scrm-shopmall', 'scrm-shopmall',
'scrm.api.shopmall.integral.transfer.out.getChannel', 'scrm.api.shopmall.integral.transfer.out.getChannel',
params, params,
{ signed: false },
); );
} }
...@@ -235,13 +231,12 @@ class WithdrawApi extends RpcApiClient { ...@@ -235,13 +231,12 @@ class WithdrawApi extends RpcApiClient {
); );
} }
/** 第三方余额:接口直接回一个金额(元,不加签),无数据时为空 */ /** 第三方余额:接口直接回一个金额(元,一样必须加签),无数据时为空 */
balance(params: Record<string, unknown> = {}) { balance(params: Record<string, unknown> = {}) {
return this.rpc<number | string | undefined>( return this.rpc<number | string | undefined>(
'scrm-shopmall', 'scrm-shopmall',
'scrm.api.shopmall.integral.transfer.out.balance.get', 'scrm.api.shopmall.integral.transfer.out.balance.get',
params, params,
{ signed: false },
); );
} }
......
...@@ -91,7 +91,7 @@ export function buildApprovalTransferColumns( ...@@ -91,7 +91,7 @@ export function buildApprovalTransferColumns(
{ {
title: '收款手机号', title: '收款手机号',
dataIndex: 'mobile', dataIndex: 'mobile',
width: 130, width: 140,
render: (value) => <span className="uj-code">{textOr(value)}</span>, render: (value) => <span className="uj-code">{textOr(value)}</span>,
}, },
]; ];
......
...@@ -95,9 +95,23 @@ export function compactParams(values: Record<string, unknown>): Record<string, u ...@@ -95,9 +95,23 @@ export function compactParams(values: Record<string, unknown>): Record<string, u
return params; return params;
} }
/** 错误提示取后端 message;适配层抛出的 Error 已带人话文案。 */ /**
* 错误提示取后端信封里的原话。
*
* 判断不能写成 `error instanceof Error`:请求由主壳代理,抛出的错误属于主壳那个 realm,
* 在子应用里 instanceof 一律为 false,于是「无效签名」这种明确原因会被吞成
* 「操作失败,请稍后重试」——后端说了什么,页面就该说什么。
* 数字网关码一并带上,报障时可以直接对着网关日志,不用再猜是哪一层失败。
*/
export function errorMessage(error: unknown): string { export function errorMessage(error: unknown): string {
if (error instanceof Error && error.message) return error.message; const e = error as { message?: unknown; code?: unknown } | undefined;
if (typeof error === 'string' && error) return error; const text =
return '操作失败,请稍后重试'; typeof error === 'string'
? error.trim()
: typeof e?.message === 'string'
? e.message.trim()
: '';
if (!text) return '操作失败,请稍后重试';
const code = typeof e?.code === 'number' || typeof e?.code === 'string' ? String(e.code) : '';
return /^\d+$/.test(code) ? `${text}(网关码 ${code})` : text;
} }
...@@ -83,6 +83,18 @@ ...@@ -83,6 +83,18 @@
} }
} }
/* 抽屉内空间充足(宽 ≥600),明细固定两列一行,不再跟外层 viewport 媒体查询走三列/单列。
用 .ant-drawer-body 前缀把特异性抬到 (0,2,0),稳稳压过上面的单类选择器规则;
极窄抽屉(<480,多见于手机全屏抽屉)回退单列,避免标签被挤断。 */
.ant-drawer-body .uj-points-detail-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (max-width: 480px) {
.ant-drawer-body .uj-points-detail-grid {
grid-template-columns: minmax(0, 1fr);
}
}
/* 统计条容器与标题行:对齐老系统 .statistics(无外框)与 .title(16px 粗体)。 */ /* 统计条容器与标题行:对齐老系统 .statistics(无外框)与 .title(16px 粗体)。 */
.uj-points-statistics-card { .uj-points-statistics-card {
flex: none; flex: none;
...@@ -98,6 +110,18 @@ ...@@ -98,6 +110,18 @@
font-weight: 700; font-weight: 700;
color: var(--uj-text-1); color: var(--uj-text-1);
} }
/* 取数失败:整条替换成一行人话,用 error 三色把「没数据」和「没取到」区分开。 */
.uj-points-statistics-error {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
border: 1px solid var(--uj-error-border);
border-radius: 6px;
background: var(--uj-error-soft);
color: var(--uj-error);
font-size: 13px;
}
/* 弹窗里的分组小标题与提示:统一比正文小一号、取第三级文字色。 */ /* 弹窗里的分组小标题与提示:统一比正文小一号、取第三级文字色。 */
.uj-points-dialog-label { .uj-points-dialog-label {
display: block; display: block;
......
/* 子应用内样式只在 <wujie-app> 的 shadowRoot 内生效,不会污染主壳。 /* 子应用内样式只在 <wujie-app> 的 shadowRoot 内生效,不会污染主壳。
tokens.css 由 main.tsx 引入;根节点带 .uj-scope 让令牌在 shadowRoot 内有本地落点, tokens.css 由 main.tsx 引入;根节点带 .uj-scope 让令牌在 shadowRoot 内有本地落点,
不依赖「自定义属性恰好能穿透 shadow DOM」这个侥幸。 */ 不依赖「自定义属性恰好能穿透 shadow DOM」这个侥幸。 */
/* 根因修复:iframe 的 html/body 必须定高,否则下方 .uj-points-app 的 height:100%
会回退成「内容高度」,导致 body 实际溢出。
溢出后 antd 抽屉打开时,rc-util 的滚动锁(useScrollLocker)检测到 body 溢出,
会给 `html body` 注入 `width: calc(100% - 滚动条宽px)` 来补偿被隐藏的滚动条 ——
可本应用滚动收在 .uj-points-app(overflow:auto)里、body 本身并不滚动,
这条补偿只会把整页宽度收窄,造成「打开抽屉整页左移、关闭复原」的抖动。
定高后 body 不再溢出,滚动锁不再注入该宽度补偿,抖动从源头消失。 */
html,
body {
height: 100%;
}
/* 兜底:万一某些长页面仍让 body 溢出(极端内容/未走 .uj-points-app 的入口),
直接强制 body 满宽,彻底消除左移,且不影响 .uj-points-app 内部自身的滚动。 */
html body {
width: 100% !important;
}
.uj-points-app { .uj-points-app {
/* height(而非 min-height):列表页要靠这条定高链路把剩余空间量出来。 /* height(而非 min-height):列表页要靠这条定高链路把剩余空间量出来。
长页面由内部 .uj-page 撑高后在本容器里滚,不会把 iframe 撑破。 */ 长页面由内部 .uj-page 撑高后在本容器里滚,不会把 iframe 撑破。 */
......
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { Skeleton, UAlert, UButton, UCard, UResult, UTitle } from '@uj/ui'; import { Skeleton, UAlert, UButton, UDrawer, UTitle } from '@uj/ui';
import { pointsApi } from '@/api'; import { pointsApi, type WriteOffOrderDetail } from '@/api';
import { PP } from '@/permissions/codes';
import { usePointsAccess } from '@/features/shared/access';
import { SETTLE_STATUS, optionLabel } from '@/features/shared/dictionaries'; import { SETTLE_STATUS, optionLabel } from '@/features/shared/dictionaries';
import { numberOr, textOr } from '@/features/shared/format'; import { numberOr, textOr } from '@/features/shared/format';
import { PageShell } from '@/features/shared/PageShell';
import type { PageParams } from '@/routes';
/** 详情字段的展示修饰:number = 按数字显示,code = 等宽字体(长单号)。 */
interface DetailField {
label: string;
key: string;
number?: boolean;
code?: boolean;
}
/** 详情字段与顺序逐字对齐老系统的 orderDetail.vue;空值一律显示占位符,不再显示 undefined。 */ /** 详情字段与顺序逐字对齐老系统的 orderDetail.vue;空值一律显示占位符,不再显示 undefined。 */
const FIELDS: DetailField[] = [ const FIELDS: { label: string; key: string; number?: boolean; code?: boolean }[] = [
{ label: '项目名称', key: 'bizRelName' }, { label: '项目名称', key: 'bizRelName' },
{ label: '消费积分', key: 'integralValue', number: true }, { label: '消费积分', key: 'integralValue', number: true },
{ label: '客户昵称', key: 'customerWechatName' }, { label: '客户昵称', key: 'customerWechatName' },
...@@ -30,43 +18,32 @@ const FIELDS: DetailField[] = [ ...@@ -30,43 +18,32 @@ const FIELDS: DetailField[] = [
{ label: '商户名称', key: 'merchantName' }, { label: '商户名称', key: 'merchantName' },
]; ];
export default function OrderDetail({ params }: { params: PageParams }) { export interface OrderDetailDrawerProps {
const { can } = usePointsAccess(); open: boolean;
const allowed = can(PP.ORDER_VIEW); id: string;
const id = params.id ?? ''; onClose: () => void;
}
/**
* 核销订单详情:原是独立路由页(order/:id),改为抽屉后,
* 用户在列表点「查看」不必跳出列表上下文,看完关掉即可继续处理。
* 内容与旧页逐字一致(字段、文案、空值占位)。
*/
export function OrderDetailDrawer({ open, id, onClose }: OrderDetailDrawerProps) {
const detail = useQuery({ const detail = useQuery({
queryKey: ['points', 'order', id], queryKey: ['points', 'order', id],
queryFn: () => pointsApi.orderDetail(id), queryFn: () => pointsApi.orderDetail(id),
enabled: allowed && !!id, enabled: open && !!id,
}); });
if (!allowed) { const data = detail.data as WriteOffOrderDetail | undefined;
return (
<UResult status="403" title="无积分核销订单访问权限" subTitle="请联系管理员确认账号权限。" />
);
}
if (!id) {
return (
<UResult
status="warning"
title="缺少订单标识"
subTitle="请从积分核销订单列表点击进入查看。"
/>
);
}
const data = detail.data;
// 结算状态文案老系统在页面里由 settlementStatus 现算,这里同样不依赖接口的冗余字段。 // 结算状态文案老系统在页面里由 settlementStatus 现算,这里同样不依赖接口的冗余字段。
const values: Record<string, string> = { const values: Record<string, string> = {
settlementStatusTxt: optionLabel(SETTLE_STATUS, data?.settlementStatus), settlementStatusTxt: optionLabel(SETTLE_STATUS, data?.settlementStatus),
}; };
return ( return (
<PageShell <UDrawer title="核销订单详情" width={600} open={open} onClose={onClose}>
title="核销订单详情"
description="这一笔积分核销的项目、客户与结算信息;返回后可在列表继续处理。"
back="list"
>
{detail.isError ? ( {detail.isError ? (
<UAlert <UAlert
type="error" type="error"
...@@ -82,7 +59,8 @@ export default function OrderDetail({ params }: { params: PageParams }) { ...@@ -82,7 +59,8 @@ export default function OrderDetail({ params }: { params: PageParams }) {
) : detail.isPending ? ( ) : detail.isPending ? (
<Skeleton variant="detail" /> <Skeleton variant="detail" />
) : ( ) : (
<UCard size="small"> <>
{/* 抽屉面板本身就是容器,不再套带描边的卡片,避免双重边框。 */}
<UTitle level={5}>订单信息</UTitle> <UTitle level={5}>订单信息</UTitle>
<dl className="uj-points-detail-grid"> <dl className="uj-points-detail-grid">
{FIELDS.map((field) => { {FIELDS.map((field) => {
...@@ -99,8 +77,8 @@ export default function OrderDetail({ params }: { params: PageParams }) { ...@@ -99,8 +77,8 @@ export default function OrderDetail({ params }: { params: PageParams }) {
); );
})} })}
</dl> </dl>
</UCard> </>
)} )}
</PageShell> </UDrawer>
); );
} }
...@@ -10,9 +10,9 @@ import { compactParams, errorMessage, expandDateRanges } from '@/features/shared ...@@ -10,9 +10,9 @@ import { compactParams, errorMessage, expandDateRanges } from '@/features/shared
import { isExcel, readLegacyFile, sizeError } from '@/features/shared/files'; import { isExcel, readLegacyFile, sizeError } from '@/features/shared/files';
import { firstPage, useExport, useList, usePageClamp, useRefresh } from '@/features/shared/queries'; import { firstPage, useExport, useList, usePageClamp, useRefresh } from '@/features/shared/queries';
import { PageShell } from '@/features/shared/PageShell'; import { PageShell } from '@/features/shared/PageShell';
import { goTo } from '@/features/shared/navigate';
import { useConfirmAction } from '@/features/shared/useConfirmAction'; import { useConfirmAction } from '@/features/shared/useConfirmAction';
import { buildOrderColumns } from './tools/columns'; import { buildOrderColumns } from './tools/columns';
import { OrderDetailDrawer } from './components/OrderDetailDrawer';
const SCOPE = ['points', 'orders'] as const; const SCOPE = ['points', 'orders'] as const;
...@@ -28,6 +28,7 @@ const FIELDS: FieldSchema<Record<string, unknown>>[] = [ ...@@ -28,6 +28,7 @@ const FIELDS: FieldSchema<Record<string, unknown>>[] = [
type: 'input', type: 'input',
placeholder: '请输入项目名称', placeholder: '请输入项目名称',
inputProps: { maxLength: 100 }, inputProps: { maxLength: 100 },
essential: true,
}, },
{ {
name: 'merchantName', name: 'merchantName',
...@@ -35,8 +36,15 @@ const FIELDS: FieldSchema<Record<string, unknown>>[] = [ ...@@ -35,8 +36,15 @@ const FIELDS: FieldSchema<Record<string, unknown>>[] = [
type: 'input', type: 'input',
placeholder: '请输入商户名称', placeholder: '请输入商户名称',
inputProps: { maxLength: 100 }, inputProps: { maxLength: 100 },
essential: true,
},
{
name: 'settlementStatus',
label: '结算状态',
type: 'select',
options: withAll(SETTLE_STATUS),
essential: true,
}, },
{ name: 'settlementStatus', label: '结算状态', type: 'select', options: withAll(SETTLE_STATUS) },
{ name: 'verificationTimeStr', label: '核销日期', type: 'dateRange' }, { name: 'verificationTimeStr', label: '核销日期', type: 'dateRange' },
]; ];
...@@ -46,6 +54,7 @@ export default function OrderList() { ...@@ -46,6 +54,7 @@ export default function OrderList() {
const allowed = can(PP.ORDER_VIEW); const allowed = can(PP.ORDER_VIEW);
const [filters, setFilters] = useState<Record<string, unknown>>({}); const [filters, setFilters] = useState<Record<string, unknown>>({});
const [page, setPage] = useState(firstPage); const [page, setPage] = useState(firstPage);
const [detailId, setDetailId] = useState<string>();
const refresh = useRefresh([...SCOPE]); const refresh = useRefresh([...SCOPE]);
const list = useList<WriteOffOrder>({ const list = useList<WriteOffOrder>({
scope: [...SCOPE], scope: [...SCOPE],
...@@ -81,7 +90,7 @@ export default function OrderList() { ...@@ -81,7 +90,7 @@ export default function OrderList() {
const columns = buildOrderColumns(); const columns = buildOrderColumns();
const rowActions: RowActionSchema<WriteOffOrder>[] = [ const rowActions: RowActionSchema<WriteOffOrder>[] = [
{ label: '查看', onClick: (row) => goTo(`order/${row.id}`) }, { label: '查看', onClick: (row) => setDetailId(row.id) },
{ {
label: (row) => (Number(row.settlementStatus) === 1 ? '取消结算' : '去结算'), label: (row) => (Number(row.settlementStatus) === 1 ? '取消结算' : '去结算'),
visible: () => can(PP.ORDER_SETTLE), visible: () => can(PP.ORDER_SETTLE),
...@@ -133,7 +142,11 @@ export default function OrderList() { ...@@ -133,7 +142,11 @@ export default function OrderList() {
<UCard className="uj-filter-card" size="small"> <UCard className="uj-filter-card" size="small">
<SearchForm <SearchForm
fields={FIELDS} fields={FIELDS}
initialValues={{ bizRelName: '', merchantName: '', settlementStatus: '' }} initialValues={{
bizRelName: '',
merchantName: '',
settlementStatus: '',
}}
onSearch={(values) => { onSearch={(values) => {
setFilters(compactParams(expandDateRanges({ ...values }, DATE_RANGES))); setFilters(compactParams(expandDateRanges({ ...values }, DATE_RANGES)));
setPage(firstPage); setPage(firstPage);
...@@ -180,6 +193,11 @@ export default function OrderList() { ...@@ -180,6 +193,11 @@ export default function OrderList() {
/> />
</UCard> </UCard>
{settle.modal} {settle.modal}
<OrderDetailDrawer
open={!!detailId}
id={detailId ?? ''}
onClose={() => setDetailId(undefined)}
/>
</PageShell> </PageShell>
); );
} }
...@@ -26,13 +26,13 @@ export function buildOrderColumns(): DataTableColumnsType<WriteOffOrder> { ...@@ -26,13 +26,13 @@ export function buildOrderColumns(): DataTableColumnsType<WriteOffOrder> {
{ {
title: '手机号', title: '手机号',
dataIndex: 'customerPhone', dataIndex: 'customerPhone',
width: 120, width: 140,
render: (value) => <span className="uj-code">{textOr(value)}</span>, render: (value) => <span className="uj-code">{textOr(value)}</span>,
}, },
{ {
title: '核销员工', title: '核销员工',
dataIndex: 'verificationStaffName', dataIndex: 'verificationStaffName',
width: 110, width: 140,
render: (value) => textOr(value), render: (value) => textOr(value),
}, },
{ title: '商户名称', dataIndex: 'merchantName', width: 200, render: (value) => textOr(value) }, { title: '商户名称', dataIndex: 'merchantName', width: 200, render: (value) => textOr(value) },
......
...@@ -30,13 +30,16 @@ const DATE_RANGES = [ ...@@ -30,13 +30,16 @@ const DATE_RANGES = [
/** /**
* 详情子页面的身份参数走路径段:阳光激励按员工号定位,另外两个渠道按「门店 + 手机号」定位。 * 详情子页面的身份参数走路径段:阳光激励按员工号定位,另外两个渠道按「门店 + 手机号」定位。
* 缺任一段就拼不出安全的地址,此时不提供入口(老系统会带着 undefined 去查,结果是错的人的积分)。 * 缺任一段就拼不出安全的地址,此时不提供入口(老系统会带着 undefined 去查,结果是错的人的积分)。
* 门店范围不再进地址:它是系统级口径,由请求出口统一注入,地址只负责「哪一个人」。
*/ */
function detailPath(row: StaffScoreRow, channelSource: string): string | undefined { function detailPath(row: StaffScoreRow, channelSource: string): string | undefined {
if (channelSource === '1') { if (channelSource === '1') {
return row.staffId ? `user/1/${encodeURIComponent(row.staffId)}` : undefined; return row.staffId ? `user/1/${encodeURIComponent(row.staffId)}` : undefined;
} }
if (!row.merchantId || !row.staffPhone) return undefined; if (!row.merchantId || !row.staffPhone) return undefined;
return `user/${channelSource}/${encodeURIComponent(row.merchantId)}/${encodeURIComponent(row.staffPhone)}`; return `user/${channelSource}/${encodeURIComponent(row.merchantId)}/${encodeURIComponent(
row.staffPhone,
)}`;
} }
export default function ScoreUsers() { export default function ScoreUsers() {
...@@ -88,7 +91,7 @@ export default function ScoreUsers() { ...@@ -88,7 +91,7 @@ export default function ScoreUsers() {
options: withAll(merchants.options), options: withAll(merchants.options),
essential: true, essential: true,
}, },
{ name: 'rewardTime', label: '积分收益时间', type: 'dateRange', essential: true }, { name: 'rewardTime', label: '积分收益时间', type: 'dateRange' },
{ name: 'reviewTime', label: '积分付款时间', type: 'dateRange' }, { name: 'reviewTime', label: '积分付款时间', type: 'dateRange' },
{ name: 'successTime', label: '积分到账时间', type: 'dateRange' }, { name: 'successTime', label: '积分到账时间', type: 'dateRange' },
]; ];
......
...@@ -23,6 +23,8 @@ const DATE_RANGES = [ ...@@ -23,6 +23,8 @@ const DATE_RANGES = [
/** /**
* 定位「哪一个人」:阳光激励用员工号,续保客户与管理层用门店 + 手机号。 * 定位「哪一个人」:阳光激励用员工号,续保客户与管理层用门店 + 手机号。
* 这两组字段名就是老接口 detailList 详情按钮传过去的那几个,不做改名。 * 这两组字段名就是老接口 detailList 详情按钮传过去的那几个,不做改名。
* 门店范围不在这里:顶部累计卡(staff.score.page)与流水(detail.list)都由请求出口统一注入,
* 地址里少一段,就不会出现「列表一个口径、详情另一个口径」。
*/ */
function buildIdentity(params: PageParams): Record<string, unknown> | undefined { function buildIdentity(params: PageParams): Record<string, unknown> | undefined {
const channelSource = params.channelSource ?? ''; const channelSource = params.channelSource ?? '';
...@@ -31,7 +33,11 @@ function buildIdentity(params: PageParams): Record<string, unknown> | undefined ...@@ -31,7 +33,11 @@ function buildIdentity(params: PageParams): Record<string, unknown> | undefined
return params.staffId ? { channelSource, staffId: params.staffId } : undefined; return params.staffId ? { channelSource, staffId: params.staffId } : undefined;
} }
if (!params.merchantId || !params.phone) return undefined; if (!params.merchantId || !params.phone) return undefined;
return { channelSource, merchantId: params.merchantId, staffPhone: params.phone }; return {
channelSource,
merchantId: params.merchantId,
staffPhone: params.phone,
};
} }
export default function UserScoreDetail({ params }: { params: PageParams }) { export default function UserScoreDetail({ params }: { params: PageParams }) {
......
...@@ -330,8 +330,12 @@ export default function WithdrawList() { ...@@ -330,8 +330,12 @@ export default function WithdrawList() {
const selection: DataTableRowSelection<WithdrawRow> = { const selection: DataTableRowSelection<WithdrawRow> = {
selectedRowKeys: selectedIds, selectedRowKeys: selectedIds,
disabled: list.query.isFetching, disabled: list.query.isFetching,
// 后端 id 实际是 number(老系统自增主键),但本页把它当 string 用:
// 这里绝不能 keys.map(String) —— 那样 selectedRowKeys 会变成字符串、而 antd 用行 id(number)
// 比对,'123' === 123 永假,复选框就永远勾不上。统一交给 rowKey 返回 String(id) 来归一,
// 这里原样存 antd 给的 key 即可(它已基于 rowKey 的值,即 string 化后的 id)。
onChange: (keys, rows) => { onChange: (keys, rows) => {
setSelectedIds(keys.map(String)); setSelectedIds(keys as string[]);
setSelectedRows(rows); setSelectedRows(rows);
}, },
}; };
...@@ -369,7 +373,12 @@ export default function WithdrawList() { ...@@ -369,7 +373,12 @@ export default function WithdrawList() {
}} }}
/> />
</UCard> </UCard>
<SettleAmountStrip amounts={amounts.data} onOpenAll={() => setMoreAmounts(true)} /> <SettleAmountStrip
amounts={amounts.data}
error={amounts.isError ? amounts.error : undefined}
onRetry={() => void amounts.refetch()}
onOpenAll={() => setMoreAmounts(true)}
/>
{list.query.isError ? ( {list.query.isError ? (
<UAlert <UAlert
type="error" type="error"
...@@ -457,7 +466,9 @@ export default function WithdrawList() { ...@@ -457,7 +466,9 @@ export default function WithdrawList() {
</div> </div>
<DataTable<WithdrawRow> <DataTable<WithdrawRow>
columns={columns} columns={columns}
rowKey="id" // rowKey 归一为字符串:后端 id 实际是 number,统一 String(id) 后,选中键(也是基于 rowKey)
// 与行 id 同为 string,selectedRowKeys 才能命中;同时提交给后端的 ids 保持 string 不变。
rowKey={(row: WithdrawRow) => String(row.id)}
rowSelection={selection} rowSelection={selection}
fillHeight fillHeight
actionColumnWidth={180} actionColumnWidth={180}
......
import { UButton, UModal } from '@uj/ui'; import { UButton, UModal } from '@uj/ui';
import type { SettleAmountMap } from '@/api'; import type { SettleAmountMap } from '@/api';
import { SETTLE_STATISTICS, SETTLE_STATISTICS_PREVIEW } from '@/features/shared/dictionaries'; import { SETTLE_STATISTICS, SETTLE_STATISTICS_PREVIEW } from '@/features/shared/dictionaries';
import { EMPTY } from '@/features/shared/format'; import { EMPTY, errorMessage } from '@/features/shared/format';
/** /**
* 累计结算金额:老系统把 10 个统计项写死在 constants.statisticsTypeList, * 累计结算金额:老系统把 10 个统计项写死在 constants.statisticsTypeList,
...@@ -22,20 +22,38 @@ function itemsOf(amounts: SettleAmountMap | undefined) { ...@@ -22,20 +22,38 @@ function itemsOf(amounts: SettleAmountMap | undefined) {
export interface SettleAmountStripProps { export interface SettleAmountStripProps {
amounts: SettleAmountMap | undefined; amounts: SettleAmountMap | undefined;
/**
* 取数失败本身。没有这一项时,「接口挂了」与「这个渠道确实没有结算额」在页面上是同一个样子:
* 一排 `—`。数字缺席必须说得出为什么缺席。
*/
error?: unknown;
onRetry?: () => void;
/** 老系统只有「查看更多」一个动作,展开弹窗。 */ /** 老系统只有「查看更多」一个动作,展开弹窗。 */
onOpenAll: () => void; onOpenAll: () => void;
} }
export function SettleAmountStrip({ amounts, onOpenAll }: SettleAmountStripProps) { export function SettleAmountStrip({ amounts, error, onRetry, onOpenAll }: SettleAmountStripProps) {
const preview = itemsOf(amounts).slice(0, SETTLE_STATISTICS_PREVIEW); const preview = itemsOf(amounts).slice(0, SETTLE_STATISTICS_PREVIEW);
return ( return (
<div className="uj-points-statistics-card"> <div className="uj-points-statistics-card">
<div className="uj-points-statistics-head"> <div className="uj-points-statistics-head">
<span>累计结算金额</span> <span>累计结算金额</span>
{!error ? (
<UButton type="link" onClick={onOpenAll}> <UButton type="link" onClick={onOpenAll}>
查看更多 查看更多
</UButton> </UButton>
) : null}
</div>
{error ? (
<div className="uj-points-statistics-error">
<span>{`取数失败:${errorMessage(error)}`}</span>
{onRetry ? (
<UButton type="link" onClick={onRetry}>
重试
</UButton>
) : null}
</div> </div>
) : (
<div className="uj-points-statistics"> <div className="uj-points-statistics">
{preview.map((item) => ( {preview.map((item) => (
<div className="uj-points-statistics-item" key={item.key}> <div className="uj-points-statistics-item" key={item.key}>
...@@ -47,6 +65,7 @@ export function SettleAmountStrip({ amounts, onOpenAll }: SettleAmountStripProps ...@@ -47,6 +65,7 @@ export function SettleAmountStrip({ amounts, onOpenAll }: SettleAmountStripProps
</div> </div>
))} ))}
</div> </div>
)}
</div> </div>
); );
} }
......
...@@ -93,7 +93,7 @@ export function buildApprovalFields( ...@@ -93,7 +93,7 @@ export function buildApprovalFields(
options: withAll(statusOptions(APPROVAL_STATUS)), options: withAll(statusOptions(APPROVAL_STATUS)),
essential: true, essential: true,
}, },
{ name: 'approvalTime', label: '审批时间', type: 'dateRange', essential: true }, { name: 'approvalTime', label: '审批时间', type: 'dateRange' },
{ name: 'oaApprovalTime', label: 'OA审批时间', type: 'dateRange' }, { name: 'oaApprovalTime', label: 'OA审批时间', type: 'dateRange' },
{ name: 'userSettleTime', label: '付款时间', type: 'dateRange' }, { name: 'userSettleTime', label: '付款时间', type: 'dateRange' },
]; ];
......
...@@ -150,11 +150,12 @@ export function buildTransferColumns( ...@@ -150,11 +150,12 @@ export function buildTransferColumns(
width: 150, width: 150,
render: (value) => textOr(value), render: (value) => textOr(value),
}, },
{ title: '收款手机号', dataIndex: 'mobile', width: 130, render: (value) => textOr(value) }, { title: '收款手机号', dataIndex: 'mobile', width: 140, render: (value) => textOr(value) },
{ {
title: '微信openid', title: '微信openid',
dataIndex: 'customerOpenId', dataIndex: 'customerOpenId',
width: 130, line: 1,
width: 150,
render: (value) => textOr(value), render: (value) => textOr(value),
}, },
{ {
......
...@@ -84,7 +84,7 @@ export function buildTransferFields( ...@@ -84,7 +84,7 @@ export function buildTransferFields(
options: withAll(statusOptions(TRANSFER_STATUS)), options: withAll(statusOptions(TRANSFER_STATUS)),
essential: true, essential: true,
}, },
{ name: 'applyDateStr', label: '申请时间', type: 'dateRange', essential: true }, { name: 'applyDateStr', label: '申请时间', type: 'dateRange' },
{ name: 'payTimeStr', label: '付款时间', type: 'dateRange' }, { name: 'payTimeStr', label: '付款时间', type: 'dateRange' },
{ name: 'channel', label: '付款渠道', type: 'select', options: withAll(deps.channels) }, { name: 'channel', label: '付款渠道', type: 'select', options: withAll(deps.channels) },
{ {
......
...@@ -15,8 +15,8 @@ export interface MatchedRoute { ...@@ -15,8 +15,8 @@ export interface MatchedRoute {
} }
/** /**
* 按段匹配:`user/:channelSource/:merchantId/:phone` 只吃三段, * 按段匹配:段数不等的路径互不干扰(`user/:channelSource/:staffId` 三段、
* 段数不等直接跳过,因此同一前缀下的长短路径可以共存(user/1/9 与 user/2/8/13800000000)。 * `user/:channelSource/:merchantId/:phone` 四段),因此同一前缀下的长短路径可以共存。
* 参数值做 decodeURIComponent,手机号与门店编号里不会有需要转义的字符,但保持成对。 * 参数值做 decodeURIComponent,手机号与门店编号里不会有需要转义的字符,但保持成对。
*/ */
export function matchRoute(routes: RouteDef[], subPath: string): MatchedRoute | undefined { export function matchRoute(routes: RouteDef[], subPath: string): MatchedRoute | undefined {
......
...@@ -26,3 +26,15 @@ export class RequestError extends Error { ...@@ -26,3 +26,15 @@ export class RequestError extends Error {
if (init.cause !== undefined) this.cause = init.cause; if (init.cause !== undefined) this.cause = init.cause;
} }
} }
/**
* 「是不是 RequestError」只能靠标记字段,不能靠 instanceof。
*
* wujie 子应用跑在自己的 iframe realm 里:主壳 props.request 抛出的错误在子应用侧
* `instanceof Error === false`。用 instanceof 判定会把一条带了人话文案与业务码的失败
* 降级成 `String(err)`,顺带丢掉 code —— 于是业务错误被当成传输错误(多 toast、多重试),
* 页面提示退化成「操作失败,请稍后重试」。`isRequestError` 是实例自有字段,跨 realm 仍在。
*/
export function isRequestError(error: unknown): error is RequestError {
return Boolean(error) && (error as { isRequestError?: unknown }).isRequestError === true;
}
import { createAutoSender, createWxSender, createUniSender, createFetchSender, createHostSender } from '../transport/senders'; import { createAutoSender, createWxSender, createUniSender, createFetchSender, createHostSender } from '../transport/senders';
import { RequestError } from './errors'; import { RequestError, isRequestError } from './errors';
import './polyfill';
import { resolveRequestStrategy } from '../gateway/strategies'; import { resolveRequestStrategy } from '../gateway/strategies';
import type { PreparedRequest, RequestStrategy, SignatureStrategy } from '../gateway/strategies'; import type { PreparedRequest, RequestStrategy, SignatureStrategy } from '../gateway/strategies';
import type { import type {
...@@ -20,7 +21,7 @@ import { ...@@ -20,7 +21,7 @@ import {
requestKey, requestKey,
} from './cancellation'; } from './cancellation';
export { RequestError } from './errors'; export { RequestError, isRequestError } from './errors';
export { export {
cancelRequests, cancelRequests,
setActiveScope, setActiveScope,
...@@ -189,7 +190,7 @@ export interface RequestConfig { ...@@ -189,7 +190,7 @@ export interface RequestConfig {
gatewayCredential?: (id: string) => GatewayCredential; gatewayCredential?: (id: string) => GatewayCredential;
/** 会话令牌提供器(主壳登录态 / 网关侧令牌)。 */ /** 会话令牌提供器(主壳登录态 / 网关侧令牌)。 */
gatewayToken?: () => string; gatewayToken?: () => string;
/** 该次调用是否加签,缺省 true(对应老网关 `signed: false` 的免签接口)。 */ /** 该次调用是否加签,缺省 true。false 只去掉 sign 一个键,appKey 等身份信封照发。 */
signed?: boolean; signed?: boolean;
/** 参与请求但不进签名原文的参数名(老系统 noSignAttr,文件 Base64 这类大字段)。 */ /** 参与请求但不进签名原文的参数名(老系统 noSignAttr,文件 Base64 这类大字段)。 */
unsignedKeys?: string[]; unsignedKeys?: string[];
...@@ -426,6 +427,37 @@ function buildError(message: string, init: Partial<RequestError> = {}): RequestE ...@@ -426,6 +427,37 @@ function buildError(message: string, init: Partial<RequestError> = {}): RequestE
return new RequestError(message, init); return new RequestError(message, init);
} }
/** 取错误文案:跨 realm 抛来的错误不是本 realm 的 Error 实例,只能认 message 字段。 */
function messageOf(error: unknown): string {
const message = (error as { message?: unknown } | undefined)?.message;
if (typeof message === 'string' && message) return message;
return typeof error === 'string' ? error : String(error);
}
/** 外部(主壳 / 第三方)错误上已有的语义字段,包装时原样带过来,别让 code 在转换里丢掉。 */
function foreignInit(error: unknown): Partial<RequestError> {
const e = error as { code?: string | number; data?: unknown; response?: unknown } | undefined;
const init: Partial<RequestError> = {};
if (e && typeof e.code !== 'undefined' && typeof e.code !== 'object') init.code = e.code;
if (e && typeof e.data !== 'undefined') init.data = e.data;
if (e && typeof e.response !== 'undefined') init.response = e.response;
return init;
}
/**
* 把任意来源的失败归成一份 RequestError。
* 判定用 isRequestError 标记而非 instanceof(见 errors.ts),否则会连带丢掉 code ——
* code 没了,业务失败会被当成传输失败去 toast、去重试。
*/
function wrapError(error: unknown, config?: RequestConfig): RequestError {
if (isRequestError(error)) return error;
return buildError(messageOf(error), {
...foreignInit(error),
cause: error,
...(config ? { config } : {}),
});
}
// PreparedRequest 由 ./strategies 定义并以 import type 引入。 // PreparedRequest 由 ./strategies 定义并以 import type 引入。
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -483,7 +515,7 @@ export class Request { ...@@ -483,7 +515,7 @@ export class Request {
promise = promise.then(chain.shift(), chain.shift()); promise = promise.then(chain.shift(), chain.shift());
} }
return promise.catch((error: unknown) => { return promise.catch((error: unknown) => {
const err = error instanceof RequestError ? error : buildError(error instanceof Error ? error.message : String(error), { cause: error }); const err = wrapError(error);
safeEvent(() => merged.events?.error?.(err, merged)); safeEvent(() => merged.events?.error?.(err, merged));
if (merged.errorHandler) return merged.errorHandler(err, merged); if (merged.errorHandler) return merged.errorHandler(err, merged);
throw err; throw err;
...@@ -608,9 +640,7 @@ export class Request { ...@@ -608,9 +640,7 @@ export class Request {
throw buildError('请求已取消', { config, code: 'CANCELLED', cause: error }); throw buildError('请求已取消', { config, code: 'CANCELLED', cause: error });
} }
lastError = error; lastError = error;
const wrapped = error instanceof RequestError const wrapped = wrapError(error, config);
? error
: buildError(error instanceof Error ? error.message : String(error), { cause: error, config });
const isBusiness = wrapped.code !== undefined; const isBusiness = wrapped.code !== undefined;
const shouldRetry = Boolean(retry && attempt < maxAttempts - 1 && (retry.condition ? retry.condition(wrapped) : !isBusiness)); const shouldRetry = Boolean(retry && attempt < maxAttempts - 1 && (retry.condition ? retry.condition(wrapped) : !isBusiness));
if (!shouldRetry) { if (!shouldRetry) {
......
/**
* 环境能力补齐:原生小程序(微信 appservice / 老 webview)运行时没有全局
* `AbortController` / `AbortSignal`,而 api-core 的取消链路(facade 每次 dispatch、
* senders 的超时 / 合并)依赖它们。缺失会直接导致 `AbortController is not defined`,
* 每个请求都崩。这里仅在全局确实不存在时安装最小实现;web / 现代浏览器已有原生
* 实现时本模块为 no-op,绝不覆盖原生。
*
* 最小实现足以支撑 api-core 的全部用法:
* - new AbortController() / controller.signal / controller.abort(reason)
* - signal.aborted / signal.addEventListener('abort', cb) / signal.onabort
* - AbortSignal.timeout(ms)(setTimeout 到点自动 abort)
* - AbortSignal.any(list)(任一输入 abort 即 abort)
* 真·底层中断(fetch / wx.request abort)由各自传输层负责,这里只管 api-core
* 内部的取消状态机,不越界。
*/
function installAbortPolyfill(): void {
const g = globalThis as Record<string, unknown>;
const hasController = typeof g.AbortController !== 'undefined';
const hasSignal = typeof g.AbortSignal !== 'undefined';
if (hasController && hasSignal) return; // 原生齐全,不碰
type AbortListener = (event: unknown) => void;
class PolyAbortSignal {
aborted = false;
reason: unknown = undefined;
onabort: AbortListener | null = null;
private listeners: AbortListener[] = [];
addEventListener(type: 'abort', listener: AbortListener): void {
if (type === 'abort') this.listeners.push(listener);
}
removeEventListener(type: 'abort', listener: AbortListener): void {
if (type === 'abort') {
const i = this.listeners.indexOf(listener);
if (i >= 0) this.listeners.splice(i, 1);
}
}
dispatchEvent(): boolean {
return false;
}
throwIfAborted(): void {
if (this.aborted) {
const e = new Error('AbortError');
(e as Error).name = 'AbortError';
throw e;
}
}
/** @internal 仅由 controller 调用 */
_fire(reason?: unknown): void {
if (this.aborted) return;
this.aborted = true;
this.reason = reason;
const cb = this.onabort;
if (cb) cb({ type: 'abort' });
const list = this.listeners.slice();
this.listeners.length = 0;
for (const l of list) l({ type: 'abort' });
}
}
class PolyAbortController {
readonly signal: PolyAbortSignal;
constructor() {
this.signal = new PolyAbortSignal();
}
abort(reason?: unknown): void {
this.signal._fire(reason);
}
}
const SignalCtor = PolyAbortSignal as unknown as typeof AbortSignal;
// AbortSignal.timeout:到点自动 abort(小程序里 wx.request 自带超时,这里仅补状态机)。
const timeoutFn = function timeout(ms: number): AbortSignal {
const ctrl = new PolyAbortController();
setTimeout(
() => ctrl.abort({ name: 'TimeoutError', message: `signal timed out after ${ms}ms` }),
ms,
);
return ctrl.signal;
} as unknown as typeof AbortSignal.timeout;
// AbortSignal.any:任一输入 abort 即 abort。
const anyFn = function any(signals: AbortSignal[]): AbortSignal {
const ctrl = new PolyAbortController();
for (const s of signals) {
if (s.aborted) {
ctrl.abort(s.reason);
break;
}
s.addEventListener('abort', () => ctrl.abort(s.reason), { once: true } as EventListenerOptions);
}
return ctrl.signal;
} as unknown as typeof AbortSignal.any;
if (!hasController) g.AbortController = PolyAbortController;
if (!hasSignal) {
const S = SignalCtor as unknown as Record<string, unknown>;
S.timeout = timeoutFn;
S.any = anyFn;
g.AbortSignal = SignalCtor;
}
}
installAbortPolyfill();
...@@ -42,6 +42,40 @@ export interface RpcDispatcherDeps extends Omit<RpcPrepareDeps, 'resolveToken'> ...@@ -42,6 +42,40 @@ export interface RpcDispatcherDeps extends Omit<RpcPrepareDeps, 'resolveToken'>
} }
/** /**
* glsx 系网关只认「摊平后的 form 键值对」:数组是 `ids[0]`/`ids[1]`,嵌套对象是 `a.b`,值一律是字符串。
* 老系统、二手车小程序与本域三条链路在这一步同源(`glsx-common/src/util.js#createSign` 与
* `apps/mp/usedcar/utils/request/http.js#flatten` 都先摊平再加签)。
*
* 不摊平会同时错两处:签名原文里是 `ids[214,213,212]`(JSON 串),而请求体里的键名由传输层决定
* (浏览器 axios 发 `ids[]=…`)——网关按它真正收到的键名重算签名,于是 HTTP 200 + `code 25 无效签名`。
* 规则逐条对齐 qs 的 `{arrayFormat:'indices', allowDots:true, encodeValuesOnly:true}`:
* null 留空串键,undefined 与空数组整个键消失。
*/
export function flattenFormParams(params: Record<string, unknown>): Record<string, string> {
const out: Record<string, string> = {};
const walk = (value: unknown, key: string) => {
if (value === undefined) return;
if (value === null) {
out[key] = '';
return;
}
if (Array.isArray(value)) {
value.forEach((item, index) => walk(item, `${key}[${index}]`));
return;
}
if (typeof value === 'object') {
for (const [name, nested] of Object.entries(value as Record<string, unknown>)) {
walk(nested, key ? `${key}.${name}` : name);
}
return;
}
out[key] = String(value);
};
for (const [key, value] of Object.entries(params)) walk(value, key);
return out;
}
/**
* 把一次「业务语义」调用组装成原始传输请求(只组装,不发送)。 * 把一次「业务语义」调用组装成原始传输请求(只组装,不发送)。
* *
* `createRpcDispatcher`(小程序直连)与 `strategies.rpcGateway`(统一 Request 门面) * `createRpcDispatcher`(小程序直连)与 `strategies.rpcGateway`(统一 Request 门面)
...@@ -54,35 +88,37 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi ...@@ -54,35 +88,37 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi
const needsSign = call.signed !== false; const needsSign = call.signed !== false;
// 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;会话标识同样并入并参与签名。 // 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;会话标识同样并入并参与签名。
// effectiveParams 同时驱动请求体与加签原文(与 rop 策略一致:sessionId 既进 body 也进签名)。 // 摊平发生在签名之前:effectiveParams 同时驱动加签原文与请求体,二者因此不可能分叉。
const effectiveParams: Record<string, unknown> = { const effectiveParams = flattenFormParams({
...strategy.fixedParams, ...strategy.fixedParams,
...call.params, ...call.params,
...(deps.session && !call.params[deps.session.name] ...(deps.session && !call.params[deps.session.name]
? { [deps.session.name]: deps.session.value } ? { [deps.session.name]: deps.session.value }
: {}), : {}),
}; });
const body: Record<string, unknown> = { ...effectiveParams, method: call.method }; const body: Record<string, unknown> = { ...effectiveParams, method: call.method };
if (needsSign) { if (needsSign && !credential.secret) {
if (!credential.secret) {
throw new Error(`网关 ${call.gateway} 的接口需要加签,但未配置 appKey / secret。`); throw new Error(`网关 ${call.gateway} 的接口需要加签,但未配置 appKey / secret。`);
} }
Object.assign( // 签名策略同时产出「身份信封」(appKey / v / format / timestamp)与 sign:
body, // appKey 是网关路由到具体接入方的身份,少了它连方法都不会被执行(实测 HTTP 200 + code 22 缺少appKey参数)。
await Promise.resolve( // 所以 signed:false 只摘掉 sign 这一个键,信封照发 —— 否则「免签」会变成「必定失败的请求」。
// 真正无签名的策略(signer 不产出 appKey)在这里自然得到空信封,不受影响。
const envelope = await Promise.resolve(
strategy.signer.fields({ strategy.signer.fields({
method: call.method, method: call.method,
params: effectiveParams, params: effectiveParams,
timestamp: Date.now(), timestamp: Date.now(),
appKey: credential.appKey, appKey: credential.appKey,
secret: credential.secret, // 不加签时不需要私钥(HMAC 之类算法拿空 secret 派生密钥会直接抛错),传空串只为让信封成形。
secret: needsSign ? credential.secret : '',
version: credential.version, version: credential.version,
format: credential.format, format: credential.format,
exclude: call.unsignedKeys, exclude: call.unsignedKeys,
}), }),
),
); );
} if (!needsSign) delete envelope.sign;
Object.assign(body, envelope);
const token = deps.resolveToken?.() ?? ''; const token = deps.resolveToken?.() ?? '';
const origin = credential.origin.replace(/\/+$/, ''); const origin = credential.origin.replace(/\/+$/, '');
...@@ -90,7 +126,13 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi ...@@ -90,7 +126,13 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi
method: 'POST', method: 'POST',
url: `${origin}/${strategy.router.replace(/^\/+/, '')}`, url: `${origin}/${strategy.router.replace(/^\/+/, '')}`,
data: body, data: body,
headers: token ? { [strategy.tokenHeader]: token } : {}, // RPC 网关(glsx rop)只按 form 解析请求体:不带这个头时,传输层(axios)会按
// 默认 JSON 序列化,网关读不到 appKey/method,回 HTTP 200 + `<error code="22">缺少appKey参数</error>`。
// 头名与第一代 rop 客户端逐字一致,保证 web 与小程序两条链路同一份线上字节。
headers: {
'content-type': 'application/x-www-form-urlencoded',
...(token ? { [strategy.tokenHeader]: token } : {}),
},
timeout: deps.timeout, timeout: deps.timeout,
normalize: strategy.normalize, normalize: strategy.normalize,
}; };
...@@ -108,8 +150,6 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) { ...@@ -108,8 +150,6 @@ export function createRpcDispatcher(deps: RpcDispatcherDeps) {
return async function rpcCall<T = unknown>(call: RpcCall): Promise<T> { return async function rpcCall<T = unknown>(call: RpcCall): Promise<T> {
const req = await prepareRpcCall(call, { resolveCredential, resolveToken, timeout }); const req = await prepareRpcCall(call, { resolveCredential, resolveToken, timeout });
return sender return sender.send(req).then((res) => unwrapEnvelope(res.data as NormalizedEnvelope) as T);
.send(req)
.then((res) => unwrapEnvelope(res.data as NormalizedEnvelope) as T);
}; };
} }
/** /**
* 环境能力补齐必须在任何业务代码前执行:原生小程序运行时没有全局 AbortController /
* AbortSignal,缺失会令每次请求抛 `AbortController is not defined`。仅在全局确实缺失时
* 安装最小实现,web / 现代浏览器有原生实现时本模块为 no-op。
*/
import './core/polyfill';
/**
* @uj/api-core 主入口 —— 对外只有三个统一门面: * @uj/api-core 主入口 —— 对外只有三个统一门面:
* *
* createSigner(options?) 签名器,选型靠 kind / algorithm,不传即最新 glsx SHA1 * createSigner(options?) 签名器,选型靠 kind / algorithm,不传即最新 glsx SHA1
...@@ -24,7 +31,13 @@ export type { ...@@ -24,7 +31,13 @@ export type {
} from './core/types'; } from './core/types';
export { registerGateway, resolveGateway } from './gateway/registry'; export { registerGateway, resolveGateway } from './gateway/registry';
export { createRpcDispatcher, prepareRpcCall, unwrapEnvelope, RpcError } from './gateway/dispatcher'; export {
createRpcDispatcher,
flattenFormParams,
prepareRpcCall,
unwrapEnvelope,
RpcError,
} from './gateway/dispatcher';
export type { RpcDispatcherDeps, RpcPrepareDeps } from './gateway/dispatcher'; export type { RpcDispatcherDeps, RpcPrepareDeps } from './gateway/dispatcher';
// 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。 // 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。
...@@ -112,6 +125,7 @@ export { ...@@ -112,6 +125,7 @@ export {
Defaults, Defaults,
InterceptorManager, InterceptorManager,
RequestError, RequestError,
isRequestError,
cancelRequests, cancelRequests,
setActiveScope, setActiveScope,
getActiveScope, getActiveScope,
......
import type { HttpMethod } from '@uj/contracts'; import type { HttpMethod } from '@uj/contracts';
import type { RawRequest, RawResponse, RequestSender } from '../core/types'; import type { RawRequest, RawResponse, RequestSender } from '../core/types';
import '../core/polyfill';
/** /**
* 主壳请求函数的入参形状(props.request / requestViaHost 的 RemoteRequest 子集)。 * 主壳请求函数的入参形状(props.request / requestViaHost 的 RemoteRequest 子集)。
......
...@@ -74,10 +74,21 @@ test('FT-FAC-001 主入口只暴露三个统一入口,旧具名 API 只在 leg ...@@ -74,10 +74,21 @@ test('FT-FAC-001 主入口只暴露三个统一入口,旧具名 API 只在 leg
assert.equal(typeof core[name], 'function', `主入口应导出 ${name}`); assert.equal(typeof core[name], 'function', `主入口应导出 ${name}`);
} }
const oldNames = [ const oldNames = [
'createMd5Signer', 'createGlsxSha1Signer', 'createSha1Signer', 'createSdkSigner', 'createMd5Signer',
'createHmacSigner', 'createNoneSigner', 'strategies', 'ropPreset', 'rpcGatewayPreset', 'createGlsxSha1Signer',
'createRopClient', 'createWebHostClient', 'createRpcGatewayClient', 'createRestClient', 'createSha1Signer',
'createGscRestClient', 'defineSignatureStrategy', 'createSdkSigner',
'createHmacSigner',
'createNoneSigner',
'strategies',
'ropPreset',
'rpcGatewayPreset',
'createRopClient',
'createWebHostClient',
'createRpcGatewayClient',
'createRestClient',
'createGscRestClient',
'defineSignatureStrategy',
]; ];
for (const name of oldNames) { for (const name of oldNames) {
assert.ok(!(name in core), `主入口不应再导出旧名 ${name}`); assert.ok(!(name in core), `主入口不应再导出旧名 ${name}`);
...@@ -114,7 +125,10 @@ test('FT-FAC-002 createSigner() 不传参即最新 glsx SHA1,与旧预设逐 ...@@ -114,7 +125,10 @@ test('FT-FAC-002 createSigner() 不传参即最新 glsx SHA1,与旧预设逐
test('FT-FAC-003 显式传 algorithm 保留通用工厂语义(老代码不炸)', async () => { test('FT-FAC-003 显式传 algorithm 保留通用工厂语义(老代码不炸)', async () => {
const custom = createSigner({ algorithm: 'md5', secretWrap: 'both', uppercase: true }); const custom = createSigner({ algorithm: 'md5', secretWrap: 'both', uppercase: true });
assert.deepEqual(await custom.fields(SIGN_INPUT), await legacy.createMd5Signer().fields(SIGN_INPUT)); assert.deepEqual(
await custom.fields(SIGN_INPUT),
await legacy.createMd5Signer().fields(SIGN_INPUT),
);
assert.throws(() => createSigner({ kind: 'custom' }), /algorithm/); assert.throws(() => createSigner({ kind: 'custom' }), /algorithm/);
}); });
...@@ -127,7 +141,10 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind ...@@ -127,7 +141,10 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind
assert.equal(createStrategy().strategy, legacy.strategies.rpcGateway({}).strategy); assert.equal(createStrategy().strategy, legacy.strategies.rpcGateway({}).strategy);
assert.throws(() => createStrategy({ kind: 'nope' }), /未知的策略 kind/); assert.throws(() => createStrategy({ kind: 'nope' }), /未知的策略 kind/);
const client = createClient({ kind: 'rest', sender: { send: async () => ({ status: 200, data: {} }) } }); const client = createClient({
kind: 'rest',
sender: { send: async () => ({ status: 200, data: {} }) },
});
assert.equal(typeof client.post, 'function'); assert.equal(typeof client.post, 'function');
assert.equal(client.defaults.config.strategy, 'plain'); assert.equal(client.defaults.config.strategy, 'plain');
assert.equal(createClient().defaults.config.strategy, 'rpc-gateway'); assert.equal(createClient().defaults.config.strategy, 'rpc-gateway');
...@@ -143,7 +160,9 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind ...@@ -143,7 +160,9 @@ test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind
test('FT-CANCEL-001 相同请求 abort 前一个在途请求(后一个成功)', async () => { test('FT-CANCEL-001 相同请求 abort 前一个在途请求(后一个成功)', async () => {
const calls = []; const calls = [];
let markFirstStarted; let markFirstStarted;
const firstStarted = new Promise((resolve) => { markFirstStarted = resolve; }); const firstStarted = new Promise((resolve) => {
markFirstStarted = resolve;
});
const sender = { const sender = {
send(req) { send(req) {
calls.push(req); calls.push(req);
...@@ -251,7 +270,9 @@ test('FT-CANCEL-005 cancelRequests() 不传 scope 取消当前 realm 全部在 ...@@ -251,7 +270,9 @@ test('FT-CANCEL-005 cancelRequests() 不传 scope 取消当前 realm 全部在
test('FT-CANCEL-006 外部 signal(react-query queryFn)abort 会取消请求且不重试', async () => { test('FT-CANCEL-006 外部 signal(react-query queryFn)abort 会取消请求且不重试', async () => {
let attempts = 0; let attempts = 0;
let markStarted; let markStarted;
const started = new Promise((resolve) => { markStarted = resolve; }); const started = new Promise((resolve) => {
markStarted = resolve;
});
const sender = { const sender = {
send(req) { send(req) {
attempts += 1; attempts += 1;
...@@ -299,14 +320,17 @@ test('FT-SIGNAL-001 transport=host 时 signal 透到 props.request(主壳 axio ...@@ -299,14 +320,17 @@ test('FT-SIGNAL-001 transport=host 时 signal 透到 props.request(主壳 axio
test('FT-SIGNAL-002 host 链路取消时,主壳拿到的 signal 真的被 abort', async () => { test('FT-SIGNAL-002 host 链路取消时,主壳拿到的 signal 真的被 abort', async () => {
let hostSignal; let hostSignal;
let markStarted; let markStarted;
const started = new Promise((resolve) => { markStarted = resolve; }); const started = new Promise((resolve) => {
markStarted = resolve;
});
setActiveScope('host-page'); setActiveScope('host-page');
const client = createClient({ const client = createClient({
kind: 'rest', kind: 'rest',
transport: 'host', transport: 'host',
raw: true, raw: true,
baseURL: 'https://api.test', baseURL: 'https://api.test',
hostSend: (req) => new Promise((_resolve, reject) => { hostSend: (req) =>
new Promise((_resolve, reject) => {
hostSignal = req.signal; hostSignal = req.signal;
markStarted(); markStarted();
req.signal?.addEventListener( req.signal?.addEventListener(
...@@ -334,14 +358,21 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy ...@@ -334,14 +358,21 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy
let captured; let captured;
globalThis.fetch = async (_url, init) => { globalThis.fetch = async (_url, init) => {
captured = init; captured = init;
return { status: 200, headers: { get: () => 'application/json' }, json: async () => ({ ok: 1 }) }; return {
status: 200,
headers: { get: () => 'application/json' },
json: async () => ({ ok: 1 }),
};
}; };
try { try {
const sender = createFetchSender(); const sender = createFetchSender();
const ac = new AbortController(); const ac = new AbortController();
await sender.send({ await sender.send({
method: 'POST', url: 'https://api.test/x', data: { a: 1 }, method: 'POST',
signal: ac.signal, timeout: 5000, url: 'https://api.test/x',
data: { a: 1 },
signal: ac.signal,
timeout: 5000,
}); });
assert.ok(captured.signal, 'fetch 应收到合并后的 signal'); assert.ok(captured.signal, 'fetch 应收到合并后的 signal');
ac.abort(); ac.abort();
...@@ -350,3 +381,44 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy ...@@ -350,3 +381,44 @@ test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', asy
globalThis.fetch = originalFetch; globalThis.fetch = originalFetch;
} }
}); });
/**
* wujie 子应用里,主壳 props.request 抛来的错误属于**另一个 realm**:
* `instanceof Error` / `instanceof RequestError` 在本域一律为 false。
* 判定一旦写成 instanceof,错误文案会变成 `String(err)`、code 整个丢失,
* 于是业务失败被当成传输失败(多一次 toast、还会重试),页面提示退化成「操作失败,请稍后重试」。
* 这里用 vm 造一个真·跨 realm 的 Error 来钉住这条。
*/
test('FT-REALM-001 跨 realm 抛来的错误仍保留 message 与 code,且不当成传输错误重试', async () => {
const vm = await import('node:vm');
const foreign = vm.runInNewContext(
`(() => { const e = new Error('无效签名'); e.name = 'RequestError'; e.isRequestError = true; e.code = 25; return e; })()`,
);
assert.equal(foreign instanceof Error, false, '前提:跨 realm 的错误不是本域 Error 实例');
let sends = 0;
const toasts = [];
const api = new core.Request({
strategy: 'plain',
baseURL: 'https://x.test',
retry: 2,
sender: {
async send() {
sends += 1;
throw foreign;
},
},
ui: { toast: (text) => toasts.push(text) },
});
await assert.rejects(
() => api.request({ url: '/a', method: 'GET' }),
(error) => {
assert.equal(error.message, '无效签名', '后端原话必须原样带回来');
assert.equal(error.code, 25, '业务码不能在本域包装里丢掉');
return true;
},
);
assert.equal(sends, 1, '带业务码的失败不是传输错误,不该重试');
assert.deepEqual(toasts, [], '业务失败的提示由调用方决定,门面不重复 toast');
});
...@@ -22,6 +22,7 @@ const { ...@@ -22,6 +22,7 @@ const {
createSigner, createSigner,
registerGateway, registerGateway,
prepareRpcCall, prepareRpcCall,
flattenFormParams,
} = require('../dist/index.cjs'); } = require('../dist/index.cjs');
const HERE = path.dirname(fileURLToPath(import.meta.url)); const HERE = path.dirname(fileURLToPath(import.meta.url));
...@@ -99,15 +100,14 @@ test('IT-GLSX-SIGN-002 MD5 预设与 ROP SHA1 预设都不得命中(防误用 ...@@ -99,15 +100,14 @@ test('IT-GLSX-SIGN-002 MD5 预设与 ROP SHA1 预设都不得命中(防误用
}); });
test('IT-GLSX-SIGN-003 端到端 prepareRpcCall 请求体 = 抓包 11 字段(含 sign)', async () => { test('IT-GLSX-SIGN-003 端到端 prepareRpcCall 请求体 = 抓包 11 字段(含 sign)', async () => {
// source 参与签名,生产渠道值必须与抓包一致,否则整条 golden 就不成立 // 这一条复算的是 2026-11-09 那次抓包的字节,所以按抓包里的渠道名登记网关;
const source = productionSource(); // 生产渠道名另有钉值(见 004 与 005),它同样进签名原文,换名就要重新取一份 golden。
assert.equal(source, CAPTURE.source, '生产网关 fixedParams.source 应与抓包一致');
registerGateway({ registerGateway({
id: 'golden-shopmall', id: 'golden-shopmall',
router: 'rop-scrm-shopmall/router', router: 'rop-scrm-shopmall/router',
tokenHeader: 'token', tokenHeader: 'token',
signer: createSigner({ id: 'golden-shopmall-sha1' }), signer: createSigner({ id: 'golden-shopmall-sha1' }),
fixedParams: { source }, fixedParams: { source: CAPTURE.source },
normalize: (raw) => ({ data: raw }), normalize: (raw) => ({ data: raw }),
}); });
...@@ -158,9 +158,109 @@ test('IT-GLSX-SIGN-004 points 网关源码不得回退到 MD5 预设或改动渠 ...@@ -158,9 +158,109 @@ test('IT-GLSX-SIGN-004 points 网关源码不得回退到 MD5 预设或改动渠
const file = path.join(ROOT, rel); const file = path.join(ROOT, rel);
assert.ok(existsSync(file), `${rel} 应存在`); assert.ok(existsSync(file), `${rel} 应存在`);
const src = readFileSync(file, 'utf8'); const src = readFileSync(file, 'utf8');
assert.ok(/createSigner\(\s*\)/.test(src), `${rel} 必须用新版统一签名器且不传参(默认 glsx SHA1)`); assert.ok(
assert.equal(productionSource(), CAPTURE.source, '渠道值改动会让签名与老网关不一致'); /createSigner\(\s*\)/.test(src),
`${rel} 必须用新版统一签名器且不传参(默认 glsx SHA1)`,
);
// 渠道名是本域自报的(2026-11-10 从老系统的 'scrm-home' 换成 'uj-web-points')。
// 它进签名原文、但不参与身份校验,线上实测 code 0;换名要连同 005 的钉值一起重取。
assert.equal(productionSource(), 'uj-web-points', '渠道值改动会让签名与线上钉值不一致');
assert.ok(!src.includes('createMd5Signer'), `${rel} 不得再用 MD5 旧预设`); assert.ok(!src.includes('createMd5Signer'), `${rel} 不得再用 MD5 旧预设`);
assert.ok(!src.includes("kind: 'md5'"), `${rel} 不得把签名器配成 MD5`); assert.ok(!src.includes("kind: 'md5'"), `${rel} 不得把签名器配成 MD5`);
assert.ok(!src.includes('glxsrMd5Signer'), `${rel} 不得残留旧导出名`); assert.ok(!src.includes('glxsrMd5Signer'), `${rel} 不得残留旧导出名`);
}); });
/**
* 2026-11-10 线上取的一份「数组参数」字节,网关当场认证通过(HTTP 200、code:'0'、data.payAmount=1200)。
* 抓它是因为页面上的批量操作全部回 code 25 无效签名:签名原文里写的是 `ids[214,213,212]`
* (JSON 串),而请求体里 `ids` 这个键怎么摊开由传输层决定,网关按它收到的键名重算必然对不上。
* 老系统与二手车小程序都先摊平成 `ids[0]` 再加签,本域同一份实现见 dispatcher.flattenFormParams。
*/
const LIVE = {
method: 'scrm.api.shopmall.integral.transfer.out.pay.amount',
timestamp: 1794300000000,
sessionId: 'scrm-base-1c3b0d4d-366a-4bf2-b8f7-0572f25aa715-rop',
sign: 'CE6C23DEC362B3E3FBA0BF2793CA3128D80FA9A3',
};
test('IT-GLSX-SIGN-005 数组参数在出口摊平成 ids[0]/ids[1]/ids[2]:签名与请求体同一份字节(线上认证)', async () => {
registerGateway({
id: 'live-shopmall',
router: 'rop-scrm-shopmall/router',
tokenHeader: 'token',
signer: createSigner({ id: 'live-shopmall-sha1' }),
fixedParams: { source: productionSource() },
normalize: (raw) => ({ data: raw }),
});
const realNow = Date.now;
Date.now = () => LIVE.timestamp;
let raw;
try {
raw = await prepareRpcCall(
{
gateway: 'live-shopmall',
method: LIVE.method,
params: { ids: ['214', '213', '212'], canApprove: false, usedCarFlag: '1' },
},
{
resolveCredential: () => ({
origin: 'https://scrm.dev.glsx.com.cn',
appKey: APP_KEY,
secret: SECRET,
version: '1.0.0',
format: 'json',
}),
session: { name: 'sessionId', value: LIVE.sessionId },
},
);
} finally {
Date.now = realNow;
}
const body = raw.data;
assert.deepEqual(Object.keys(body), [
'source',
'ids[0]',
'ids[1]',
'ids[2]',
'canApprove',
'usedCarFlag',
'sessionId',
'method',
'appKey',
'format',
'timestamp',
'v',
'sign',
]);
assert.ok(!('ids' in body), '原始数组键必须已经被摊平掉,否则线上发的就是 ids[]');
assert.equal(body['ids[0]'], '214');
assert.equal(body.canApprove, 'false', '布尔摊平成字符串,与老系统 qs 的产物一致');
// 线上发出去的就是 form 串,值只能是标量;一旦还留着数组或对象,编码方式就归传输层说了算,
// 签名原文与请求体从此两套字节(就是这次 code 25 的成因)。
for (const [key, value] of Object.entries(body)) {
assert.ok(
typeof value === 'string' || typeof value === 'number',
`字段 ${key} 没摊平成标量:${JSON.stringify(value)}`,
);
}
// 这一串不是本地复算出来的:同一份字段集在线上跑通过,网关回 code 0 并给了 payAmount。
assert.equal(body.sign, LIVE.sign, '摊平顺序或值形态一变,网关重算的签名就对不上(code 25)');
});
test('IT-GLSX-SIGN-006 嵌套对象摊平成 a.b,null 留空键、undefined 与空数组整个键消失', () => {
const flat = flattenFormParams({
ids: [],
tag: { path: { id: 7 }, name: null },
drop: undefined,
list: [1, [2, 3]],
});
assert.deepEqual(flat, {
'tag.path.id': '7',
'tag.name': '',
'list[0]': '1',
'list[1][0]': '2',
'list[1][1]': '3',
});
});
...@@ -45,24 +45,28 @@ function makeSender(responder) { ...@@ -45,24 +45,28 @@ function makeSender(responder) {
test('ST-REG-001 内置方案与签名策略都已注册', () => { test('ST-REG-001 内置方案与签名策略都已注册', () => {
assert.deepEqual(createStrategy.list(), ['plain', 'rop', 'gsc', 'web-host', 'rpc-gateway']); assert.deepEqual(createStrategy.list(), ['plain', 'rop', 'gsc', 'web-host', 'rpc-gateway']);
assert.deepEqual(createStrategy.signature.list(), [ assert.deepEqual(createStrategy.signature.list(), [
'none', 'sha1', 'md5', 'sdk', 'hmac-sha256', 'gsc-hmac', 'rop-sha1', 'none',
'sha1',
'md5',
'sdk',
'hmac-sha256',
'gsc-hmac',
'rop-sha1',
]); ]);
}); });
test('ST-REG-002 未知策略名明确报错,不悄悄退化', () => { test('ST-REG-002 未知策略名明确报错,不悄悄退化', () => {
assert.throws( assert.throws(() => new Request({ strategy: 'not-exist' }), /未知的网关方案策略/);
() => new Request({ strategy: 'not-exist' }), assert.throws(() => createStrategy.signature.resolve('not-exist'), /未知的签名策略/);
/未知的网关方案策略/,
);
assert.throws(
() => createStrategy.signature.resolve('not-exist'),
/未知的签名策略/,
);
}); });
test('ST-REG-003 自定义方案策略:注册后按名字使用,门面只做委托', async () => { test('ST-REG-003 自定义方案策略:注册后按名字使用,门面只做委托', async () => {
const { calls, sender } = makeSender(() => ({ status: 200, data: { errcode: 0, data: { ok: 1 } } })); const { calls, sender } = makeSender(() => ({
createStrategy.register(createStrategy.define({ status: 200,
data: { errcode: 0, data: { ok: 1 } },
}));
createStrategy.register(
createStrategy.define({
id: 'custom-gateway', id: 'custom-gateway',
defaults: { response: { codeKey: 'errcode', successCodes: [0], dataMode: 'envelope' } }, defaults: { response: { codeKey: 'errcode', successCodes: [0], dataMode: 'envelope' } },
async prepare(config) { async prepare(config) {
...@@ -74,7 +78,8 @@ test('ST-REG-003 自定义方案策略:注册后按名字使用,门面只做 ...@@ -74,7 +78,8 @@ test('ST-REG-003 自定义方案策略:注册后按名字使用,门面只做
resource: String(config.url), resource: String(config.url),
}; };
}, },
})); }),
);
const api = createRequest({ strategy: 'custom-gateway', sender }); const api = createRequest({ strategy: 'custom-gateway', sender });
const res = await api.post('/hello', { a: 1 }); const res = await api.post('/hello', { a: 1 });
...@@ -91,16 +96,23 @@ test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名 ...@@ -91,16 +96,23 @@ test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名
bodySign: (params, secret) => ({ ...params, sign: `demo:${secret}` }), bodySign: (params, secret) => ({ ...params, sign: `demo:${secret}` }),
}); });
const api = new Request(createStrategy({ kind: 'rop', sender, const api = new Request(
createStrategy({
kind: 'rop',
sender,
hosts: { scrm: 'https://api.test' }, hosts: { scrm: 'https://api.test' },
defaultCredential: { appKey: 'k', secret: 's' }, defaultCredential: { appKey: 'k', secret: 's' },
signature: 'demo-sign', signature: 'demo-sign',
})); }),
);
await api.post('scrm.api.shopmall.order.list', { pageNo: 1 }); await api.post('scrm.api.shopmall.order.list', { pageNo: 1 });
assert.equal(calls[0].data.sign, 'demo:s'); assert.equal(calls[0].data.sign, 'demo:s');
assert.equal(calls[0].data.method, 'scrm.api.shopmall.order.list'); assert.equal(calls[0].data.method, 'scrm.api.shopmall.order.list');
assert.equal(calls[0].url, 'https://api.test/rop-scrm-shopmall/router?method=scrm.api.shopmall.order.list'); assert.equal(
calls[0].url,
'https://api.test/rop-scrm-shopmall/router?method=scrm.api.shopmall.order.list',
);
}); });
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -109,7 +121,9 @@ test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名 ...@@ -109,7 +121,9 @@ test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名
test('ST-PRESET-005 rop 预设:业务码 / 登出码 / transport 由策略内置', async () => { test('ST-PRESET-005 rop 预设:业务码 / 登出码 / transport 由策略内置', async () => {
const { sender } = makeSender(() => ({ status: 200, data: { code: '0', data: { id: 7 } } })); const { sender } = makeSender(() => ({ status: 200, data: { code: '0', data: { id: 7 } } }));
const config = createStrategy({ kind: 'rop', sender, const config = createStrategy({
kind: 'rop',
sender,
hosts: { scrm: 'https://api.test' }, hosts: { scrm: 'https://api.test' },
signature: 'none', signature: 'none',
loginReplay: true, loginReplay: true,
...@@ -137,7 +151,9 @@ test('ST-PRESET-006 legacyEnvelope:成功返回完整信封,其它业务码 ...@@ -137,7 +151,9 @@ test('ST-PRESET-006 legacyEnvelope:成功返回完整信封,其它业务码
status: 200, status: 200,
data: { code: '-1', message: '库存不足', data: { sku: 9 } }, data: { code: '-1', message: '库存不足', data: { sku: 9 } },
})); }));
const config = createStrategy({ kind: 'rop', sender, const config = createStrategy({
kind: 'rop',
sender,
hosts: { scrm: 'https://api.test' }, hosts: { scrm: 'https://api.test' },
legacyEnvelope: true, legacyEnvelope: true,
response: { toastOnOtherCodes: ['-1'] }, response: { toastOnOtherCodes: ['-1'] },
...@@ -158,14 +174,26 @@ test('ST-PRESET-007 webHost 预设:ApiResult 信封 / 401 登出 / 业务错 ...@@ -158,14 +174,26 @@ test('ST-PRESET-007 webHost 预设:ApiResult 信封 / 401 登出 / 业务错
const toasts = []; const toasts = [];
const { sender } = makeSender((req) => const { sender } = makeSender((req) =>
req.url.includes('/fail') req.url.includes('/fail')
? { status: 200, data: { code: 500, message: '库存不足', data: { sku: 9 } }, headers: { 'content-type': 'application/json' } } ? {
: { status: 200, data: { code: 200, message: 'ok', data: { list: [1, 2] } }, headers: { 'content-type': 'application/json' } }, status: 200,
data: { code: 500, message: '库存不足', data: { sku: 9 } },
headers: { 'content-type': 'application/json' },
}
: {
status: 200,
data: { code: 200, message: 'ok', data: { list: [1, 2] } },
headers: { 'content-type': 'application/json' },
},
); );
const api = new Request(createStrategy({ kind: 'web-host', sender, const api = new Request(
createStrategy({
kind: 'web-host',
sender,
baseURL: 'https://host.test', baseURL: 'https://host.test',
contextPath: '/youjia', contextPath: '/youjia',
ui: { toast: (m) => toasts.push(m) }, ui: { toast: (m) => toasts.push(m) },
})); }),
);
assert.deepEqual(api.defaults.config.response.successCodes, [200]); assert.deepEqual(api.defaults.config.response.successCodes, [200]);
assert.deepEqual(api.defaults.config.response.logoutCodes, [401, 10002]); assert.deepEqual(api.defaults.config.response.logoutCodes, [401, 10002]);
...@@ -232,8 +260,13 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致 ...@@ -232,8 +260,13 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致
const oldSigner = createSigner({ kind: 'rop', id: 'points-sha1' }); const oldSigner = createSigner({ kind: 'rop', id: 'points-sha1' });
const legacy = async (params, secret, noSignAttr = []) => { const legacy = async (params, secret, noSignAttr = []) => {
const signed = await oldSigner.fields({ const signed = await oldSigner.fields({
method: params.method, appKey: params.appKey, secret, method: params.method,
version: params.v, format: params.format, params, exclude: noSignAttr, appKey: params.appKey,
secret,
version: params.v,
format: params.format,
params,
exclude: noSignAttr,
}); });
return { ...params, sign: signed.sign }; return { ...params, sign: signed.sign };
}; };
...@@ -244,17 +277,27 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致 ...@@ -244,17 +277,27 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致
{ {
name: '普通请求', name: '普通请求',
params: { params: {
method: 'scrm.api.shopmall.pointswallet.get', userId: 'u1', pageNo: 1, method: 'scrm.api.shopmall.pointswallet.get',
v: '1.0.0', format: 'json', locale: 'zh_CN', source: 'dj-wechat', userId: 'u1',
appKey: APP_KEY, sessionId: 'sess-9', pageNo: 1,
v: '1.0.0',
format: 'json',
locale: 'zh_CN',
source: 'dj-wechat',
appKey: APP_KEY,
sessionId: 'sess-9',
}, },
exclude: [], exclude: [],
}, },
{ {
name: 'noSignAttr(file)', name: 'noSignAttr(file)',
params: { params: {
method: 'scrm.api.carlife.common.uploadImg', file: 'BASE64_DATA', method: 'scrm.api.carlife.common.uploadImg',
v: '1.0.0', format: 'json', appKey: APP_KEY, sessionId: 'sess-9', file: 'BASE64_DATA',
v: '1.0.0',
format: 'json',
appKey: APP_KEY,
sessionId: 'sess-9',
}, },
exclude: ['file'], exclude: ['file'],
}, },
...@@ -269,7 +312,12 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致 ...@@ -269,7 +312,12 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致
test('ST-COMPAT-012 旧 profile / sign 字段仍可用(向后兼容)', async () => { test('ST-COMPAT-012 旧 profile / sign 字段仍可用(向后兼容)', async () => {
const { calls, sender } = makeSender(); const { calls, sender } = makeSender();
const api = new Request({ sender, profile: 'rop', sign: 'none', hosts: { scrm: 'https://api.test' } }); const api = new Request({
sender,
profile: 'rop',
sign: 'none',
hosts: { scrm: 'https://api.test' },
});
await api.post('a.b.c', { p: 1 }); await api.post('a.b.c', { p: 1 });
assert.equal(calls[0].url, 'https://api.test/rop-scrm-c/router?method=a.b.c'); assert.equal(calls[0].url, 'https://api.test/rop-scrm-c/router?method=a.b.c');
assert.ok(!('sign' in calls[0].data)); assert.ok(!('sign' in calls[0].data));
...@@ -325,16 +373,27 @@ registerGateway({ ...@@ -325,16 +373,27 @@ registerGateway({
}); });
const rpcCredential = () => ({ const rpcCredential = () => ({
origin: 'https://rpc.test/', appKey: 'k', secret: 's', version: '1.0.0', format: 'json', origin: 'https://rpc.test/',
appKey: 'k',
secret: 's',
version: '1.0.0',
format: 'json',
}); });
const rpcToken = () => 'T-1'; const rpcToken = () => 'T-1';
const rpcDeps = { resolveCredential: rpcCredential, resolveToken: rpcToken, timeout: 180000 }; const rpcDeps = { resolveCredential: rpcCredential, resolveToken: rpcToken, timeout: 180000 };
function makeRpcApi(extra = {}) { function makeRpcApi(extra = {}) {
const { calls, sender } = makeEnvelopeSender(); const { calls, sender } = makeEnvelopeSender();
const api = new Request(createStrategy({ sender, gatewayCredential: rpcCredential, gatewayToken: rpcToken, const api = new Request(
timeout: 180000, contentType: false, ...extra, createStrategy({
})); sender,
gatewayCredential: rpcCredential,
gatewayToken: rpcToken,
timeout: 180000,
contentType: false,
...extra,
}),
);
return { calls, sender, api }; return { calls, sender, api };
} }
...@@ -353,10 +412,14 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/ ...@@ -353,10 +412,14 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/
const req = calls[0]; const req = calls[0];
assert.equal(req.url, 'https://rpc.test/rop-st/router'); assert.equal(req.url, 'https://rpc.test/rop-st/router');
assert.equal(req.method, 'POST'); assert.equal(req.method, 'POST');
// 值一律标量字符串:网关只按 form 解析请求体,编码细节不能留给传输层决定(见 dispatcher 摊平)。
assert.deepEqual(req.data, { assert.deepEqual(req.data, {
locale: 'zh_CN', source: 'st', pageNo: 1, locale: 'zh_CN',
source: 'st',
pageNo: '1',
method: 'scrm.api.st.order.page', method: 'scrm.api.st.order.page',
appKey: 'k', sign: 'scrm.api.st.order.page#s', appKey: 'k',
sign: 'scrm.api.st.order.page#s',
}); });
assert.equal(req.headers.token, 'T-1'); assert.equal(req.headers.token, 'T-1');
assert.equal(req.timeout, 180000); assert.equal(req.timeout, 180000);
...@@ -366,21 +429,28 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/ ...@@ -366,21 +429,28 @@ test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/
assert.equal(rpcSignInputs.length, 1); assert.equal(rpcSignInputs.length, 1);
assert.equal(rpcSignInputs[0].appKey, 'k'); assert.equal(rpcSignInputs[0].appKey, 'k');
assert.equal(rpcSignInputs[0].secret, 's'); assert.equal(rpcSignInputs[0].secret, 's');
assert.deepEqual(rpcSignInputs[0].params, { locale: 'zh_CN', source: 'st', pageNo: 1 }); assert.deepEqual(rpcSignInputs[0].params, { locale: 'zh_CN', source: 'st', pageNo: '1' });
}); });
test('ST-RPC-003 signed:false 免签;unsignedKeys 透传 exclude;业务参数可覆盖 fixedParams', async () => { test('ST-RPC-003 signed:false 只摘 sign、身份信封照发;unsignedKeys 透传 exclude;业务参数可覆盖 fixedParams', async () => {
const off = makeRpcApi(); const off = makeRpcApi();
await off.api.post('m.no.sign', { file: 'BASE64' }, { gateway: 'st-rpc', signed: false }); await off.api.post('m.no.sign', { file: 'BASE64' }, { gateway: 'st-rpc', signed: false });
assert.ok(!('sign' in off.calls[0].data)); assert.ok(!('sign' in off.calls[0].data), '免签的含义就是不发 sign 这一个键');
assert.ok(!('appKey' in off.calls[0].data)); // appKey / timestamp 属于「我是哪个接入方」的身份,不属于签名算法;
// 一并省掉的话网关直接 code 22 缺少appKey参数(线上实测),所以必须照发。
assert.equal(off.calls[0].data.appKey, 'k', '免签请求也必须带身份信封,否则请求根本不会被执行');
assert.equal(off.calls[0].data.file, 'BASE64'); assert.equal(off.calls[0].data.file, 'BASE64');
rpcSignInputs.length = 0; rpcSignInputs.length = 0;
const excluded = makeRpcApi(); const excluded = makeRpcApi();
await excluded.api.post('m.with.exclude', { locale: 'en_US', file: 'BASE64' }, { await excluded.api.post(
gateway: 'st-rpc', unsignedKeys: ['file'], 'm.with.exclude',
}); { locale: 'en_US', file: 'BASE64' },
{
gateway: 'st-rpc',
unsignedKeys: ['file'],
},
);
assert.equal(excluded.calls[0].data.locale, 'en_US'); assert.equal(excluded.calls[0].data.locale, 'en_US');
assert.deepEqual(rpcSignInputs[0].exclude, ['file']); assert.deepEqual(rpcSignInputs[0].exclude, ['file']);
assert.deepEqual(rpcSignInputs[0].params, { locale: 'en_US', source: 'st', file: 'BASE64' }); assert.deepEqual(rpcSignInputs[0].params, { locale: 'en_US', source: 'st', file: 'BASE64' });
...@@ -388,14 +458,17 @@ test('ST-RPC-003 signed:false 免签;unsignedKeys 透传 exclude;业务参 ...@@ -388,14 +458,17 @@ test('ST-RPC-003 signed:false 免签;unsignedKeys 透传 exclude;业务参
test('ST-RPC-004 与 prepareRpcCall / createRpcDispatcher 共用同一份组装实现(字节一致)', async () => { test('ST-RPC-004 与 prepareRpcCall / createRpcDispatcher 共用同一份组装实现(字节一致)', async () => {
const call = { const call = {
gateway: 'st-rpc', method: 'm.same', params: { a: 1, file: 'BASE64' }, gateway: 'st-rpc',
method: 'm.same',
params: { a: 1, file: 'BASE64' },
unsignedKeys: ['file'], unsignedKeys: ['file'],
}; };
const direct = await prepareRpcCall(call, rpcDeps); const direct = await prepareRpcCall(call, rpcDeps);
const { calls, api } = makeRpcApi(); const { calls, api } = makeRpcApi();
await api.post(call.method, call.params, { await api.post(call.method, call.params, {
gateway: call.gateway, unsignedKeys: call.unsignedKeys, gateway: call.gateway,
unsignedKeys: call.unsignedKeys,
}); });
for (const key of ['url', 'method', 'headers', 'timeout']) { for (const key of ['url', 'method', 'headers', 'timeout']) {
assert.deepEqual(calls[0][key], direct[key], `${key} 必须与 dispatcher 一致`); assert.deepEqual(calls[0][key], direct[key], `${key} 必须与 dispatcher 一致`);
...@@ -419,6 +492,18 @@ test('ST-RPC-004 与 prepareRpcCall / createRpcDispatcher 共用同一份组装 ...@@ -419,6 +492,18 @@ test('ST-RPC-004 与 prepareRpcCall / createRpcDispatcher 共用同一份组装
assert.deepEqual(dispatchCalls[0].headers, direct.headers); assert.deepEqual(dispatchCalls[0].headers, direct.headers);
}); });
test('ST-RPC-004b RPC 组装自带 form 请求头:网关只按 form 解析请求体', async () => {
// 少了这个头,传输层(axios / fetch)会按默认 JSON 发送,glsx rop 网关读不到 appKey/method,
// 回 HTTP 200 + `<error code="22">缺少appKey参数</error>`:状态正常、响应里没数据,极难归因到编码。
const direct = await prepareRpcCall(
{ gateway: 'st-rpc', method: 'm.form', params: { a: 1 } },
rpcDeps,
);
assert.equal(direct.headers['content-type'], 'application/x-www-form-urlencoded');
// 令牌头照旧并存,两者不是二选一
assert.equal(direct.headers.token, rpcDeps.resolveToken());
});
test('ST-RPC-005 网关 / 凭据缺失时明确报错,不静默发出请求', async () => { test('ST-RPC-005 网关 / 凭据缺失时明确报错,不静默发出请求', async () => {
const { api, calls } = makeRpcApi(); const { api, calls } = makeRpcApi();
await assert.rejects(() => api.post('m', {}, {}), /需要指定 gateway/); await assert.rejects(() => api.post('m', {}, {}), /需要指定 gateway/);
...@@ -440,30 +525,43 @@ test('ST-RPC-006 真实双层门面:rpcGateway → host sender → 主壳归 ...@@ -440,30 +525,43 @@ test('ST-RPC-006 真实双层门面:rpcGateway → host sender → 主壳归
for (const fn of cfg.transformResponse ?? []) body = fn(body, {}); for (const fn of cfg.transformResponse ?? []) body = fn(body, {});
return { data: body?.data, headers: {} }; return { data: body?.data, headers: {} };
}; };
const api = new Request(createStrategy({ transport: 'host', hostSend, const api = new Request(
gatewayCredential: rpcCredential, gatewayToken: rpcToken, createStrategy({
timeout: 180000, contentType: false, transport: 'host',
})); hostSend,
gatewayCredential: rpcCredential,
gatewayToken: rpcToken,
timeout: 180000,
contentType: false,
}),
);
const res = await api.post('m.double', {}, { gateway: 'st-rpc' }); const res = await api.post('m.double', {}, { gateway: 'st-rpc' });
assert.equal(hostCalls.length, 1); assert.equal(hostCalls.length, 1);
assert.equal(hostCalls[0].url, 'https://rpc.test/rop-st/router'); assert.equal(hostCalls[0].url, 'https://rpc.test/rop-st/router');
assert.equal(hostCalls[0].method, 'POST'); assert.equal(hostCalls[0].method, 'POST');
assert.equal(hostCalls[0].headers.token, 'T-1'); assert.equal(hostCalls[0].headers.token, 'T-1');
assert.equal(typeof hostCalls[0].transformResponse?.[0], 'function', assert.equal(
'网关的 normalize 必须挂到 transformResponse,先于主壳拦截器归一'); typeof hostCalls[0].transformResponse?.[0],
'function',
'网关的 normalize 必须挂到 transformResponse,先于主壳拦截器归一',
);
assert.deepEqual(res, { id: 9, ok: true }); assert.deepEqual(res, { id: 9, ok: true });
}); });
test('ST-RPC-007 失败信封经统一响应归一后,外部 errorHandler 仍能拿到业务码', async () => { test('ST-RPC-007 失败信封经统一响应归一后,外部 errorHandler 仍能拿到业务码', async () => {
const { calls, sender } = makeEnvelopeSender(() => ({ code: '21', message: '登录已失效' })); const { calls, sender } = makeEnvelopeSender(() => ({ code: '21', message: '登录已失效' }));
let seen; let seen;
const api = new Request(createStrategy({ sender, gatewayCredential: rpcCredential, const api = new Request(
createStrategy({
sender,
gatewayCredential: rpcCredential,
errorHandler: (err) => { errorHandler: (err) => {
seen = err; seen = err;
return { handled: true, code: err.code }; return { handled: true, code: err.code };
}, },
})); }),
);
const res = await api.post('m.fail', {}, { gateway: 'st-rpc' }); const res = await api.post('m.fail', {}, { gateway: 'st-rpc' });
assert.equal(calls.length, 1); assert.equal(calls.length, 1);
assert.equal(seen.code, 10002); assert.equal(seen.code, 10002);
......
...@@ -55,7 +55,7 @@ export interface DataTableProps<T> extends Pick< ...@@ -55,7 +55,7 @@ export interface DataTableProps<T> extends Pick<
rowActions?: RowActionSchema<T>[]; rowActions?: RowActionSchema<T>[];
/** 行内操作列标题,默认“操作”。 */ /** 行内操作列标题,默认“操作”。 */
actionColumnTitle?: ReactNode; actionColumnTitle?: ReactNode;
/** 行内操作列宽度。 */ /** 行内操作列宽度。可不传:未传时按按钮文案自动估算;传了但偏小时也会自动取较大值,避免按钮被列宽砍掉。 */
actionColumnWidth?: number; actionColumnWidth?: number;
actionColumnFixed?: 'left' | 'right'; actionColumnFixed?: 'left' | 'right';
toolbarClassName?: string; toolbarClassName?: string;
...@@ -156,11 +156,19 @@ export function DataTable<T extends object>({ ...@@ -156,11 +156,19 @@ export function DataTable<T extends object>({
</UButton> </UButton>
); );
}; };
// 操作列宽度:页面可显式给 actionColumnWidth,但多数页面估不准、给小了按钮就被列宽砍掉
// (.uj-row-actions 是 nowrap,不会换行、只会溢出)。这里按按钮文案自动算出所需宽度,
// 取「页面给的」与「算出来的」二者较大值——页面给大了尊重页面,给小了或没给就自动兜底。
// 列宽是 fixed 布局下的硬约束,算出来的宽度已包住整组按钮,保证一行放得下、不被砍。
const resolvedActionWidth =
actionColumnWidth != null
? Math.max(actionColumnWidth, estimateActionWidth(rowActions))
: estimateActionWidth(rowActions);
const actionColumn: ColumnsType<T>[number] | undefined = rowActions?.length const actionColumn: ColumnsType<T>[number] | undefined = rowActions?.length
? { ? {
title: actionColumnTitle, title: actionColumnTitle,
key: '__actions', key: '__actions',
width: actionColumnWidth, width: resolvedActionWidth,
fixed: actionColumnFixed, fixed: actionColumnFixed,
render: (_: unknown, record: T) => { render: (_: unknown, record: T) => {
const visibleActions = rowActions.filter((action) => action.visible?.(record) ?? true); const visibleActions = rowActions.filter((action) => action.visible?.(record) ?? true);
...@@ -271,6 +279,25 @@ function getMinimumTableWidth<T extends object>(columns: ColumnsType<T>): number ...@@ -271,6 +279,25 @@ function getMinimumTableWidth<T extends object>(columns: ColumnsType<T>): number
}, 0); }, 0);
} }
/**
* 估出操作列该给多宽:逐按钮量字面宽度(中文 ~14px / 其它 ~8px)+ 小号文字按钮左右内边距(各 7px)
* + 按钮间距(--uj-space-1=4px)+ 单元格左右内边距(各 16px)。
* 动态文案(函数型 label)按 4 个汉字保守估,宁可宽一点也不要把按钮挤掉。
*/
function estimateActionWidth<T extends object>(actions?: RowActionSchema<T>[]): number {
if (!actions?.length) return 0;
const buttonWidth = (action: RowActionSchema<T>): number => {
const raw = typeof action.label === 'function' ? '四个字' : action.label;
const text = typeof raw === 'string' ? raw : '四个字';
let textWidth = 0;
for (const char of text) textWidth += /[一-龥]/.test(char) ? 14 : 8;
return textWidth + 14; // 小号文字按钮左右内边距 7px × 2
};
const buttons = actions.reduce((sum, action) => sum + buttonWidth(action), 0);
const gaps = (actions.length - 1) * 4;
return Math.ceil(buttons + gaps + 32); // 32 = 单元格左右内边距 16px × 2
}
function withLineLimit<T extends object>(columns: DataTableColumnsType<T>): ColumnsType<T> { function withLineLimit<T extends object>(columns: DataTableColumnsType<T>): ColumnsType<T> {
return columns.map((column) => { return columns.map((column) => {
if ('children' in column && column.children) { if ('children' in column && column.children) {
......
...@@ -18,6 +18,11 @@ export interface SearchFormProps<T extends Record<string, unknown>> { ...@@ -18,6 +18,11 @@ export interface SearchFormProps<T extends Record<string, unknown>> {
* 真源就在字段定义那一行 —— 哪个条件重要是一个业务判断,只有写它的人知道; * 真源就在字段定义那一行 —— 哪个条件重要是一个业务判断,只有写它的人知道;
* 不在 SearchForm 上传 visibleCount,也不在别处维护第二份「常显字段」清单, * 不在 SearchForm 上传 visibleCount,也不在别处维护第二份「常显字段」清单,
* 那样改一次要改两处、还容易漏。 * 那样改一次要改两处、还容易漏。
*
* 时间区间(dateRange)的常显规则例外:它默认进「更多筛选」(区间控件要跨 2 列才完整),
* 但「轻量表单」(常显非日期字段 ≤2 且整页条件 ≤3,如积分详情只有积分类型 + 积分变化时间)
* 或显式标了 essential:true 的区间会直接常显,避免「就两三个条件」的页还要点开更多。
* 具体阈值见组件内的 dateInline 启发式。
*/ */
fields: FieldSchema<T>[]; fields: FieldSchema<T>[];
initialValues?: Partial<T>; initialValues?: Partial<T>;
...@@ -49,11 +54,32 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -49,11 +54,32 @@ export function SearchForm<T extends Record<string, unknown>>({
size: pagination?.size ?? DEFAULT_PAGE_SIZE, size: pagination?.size ?? DEFAULT_PAGE_SIZE,
}; };
// 一条 essential 都没有时保持原行为:全部常显、不出现「更多筛选」。 const hasAnyEssential = fields.some((field) => field.essential);
// 让页面可以逐批迁移,不会因为共享层升级就突然把条件藏起来。 // 常显的非日期字段:标了 essential 的,或「全都不标 essential」时全部常显(门店列表这类没有
const hasSplit = fields.some((field) => field.essential); // 重点字段的页,非日期字段仍作常显锚点,避免常显行空着只剩按钮)。
const primaryFields = hasSplit ? fields.filter((field) => field.essential) : fields; const primaryNonDate = fields.filter(
const extraFields = hasSplit ? fields.filter((field) => !field.essential) : []; (field) => field.type !== 'dateRange' && (field.essential === true || !hasAnyEssential),
);
const dateFields = fields.filter((field) => field.type === 'dateRange');
// 时间区间是否常显(不进「更多筛选」)的启发式:
// - 显式 essential:true 的日期区间强制常显(页面作者明确要它常显);
// - 否则只在「轻量表单」里常显 —— 常显的非日期字段很少(≤2)且整页条件总数也少(≤3),
// 即「就两三个查询条件」的页面(如积分详情:积分类型 + 积分变化时间),
// 区间直接常显更顺手,不必点开「更多筛选」;
// - 没有任何非日期常显字段时(纯日期区间表单),也常显,避免常显行空着却把日期收进更多;
// 其余(字段多 / 非日期常显已 ≥3)保持原行为:日期区间进「更多筛选」,
// 防止把常显行挤爆、把「查询 / 重置」挤到第二行。
// 区间控件要显示「开始 ~ 结束」,放进更多时会跨 2 列(见 renderField 的 span)才完整。
const lightForm = primaryNonDate.length <= 2 && fields.length <= 3;
const dateInline = dateFields.length > 0 && (primaryNonDate.length === 0 || lightForm);
const isPrimary = (field: FieldSchema<T>): boolean => {
if (field.type === 'dateRange') return field.essential === true || dateInline;
return field.essential === true || !hasAnyEssential;
};
const primaryFields = fields.filter(isPrimary);
const extraFields = fields.filter((field) => !isPrimary(field));
const activeExtraCount = extraFields.filter((field) => isSet(values?.[field.name])).length; const activeExtraCount = extraFields.filter((field) => isSet(values?.[field.name])).length;
const control = (field: FieldSchema<T>) => { const control = (field: FieldSchema<T>) => {
...@@ -86,16 +112,20 @@ export function SearchForm<T extends Record<string, unknown>>({ ...@@ -86,16 +112,20 @@ export function SearchForm<T extends Record<string, unknown>>({
); );
}; };
const renderField = (field: FieldSchema<T>) => ( const renderField = (field: FieldSchema<T>) => {
<UFormItem // 时间区间选择器默认跨 2 列(见 FieldSchema.span 注释);其余类型默认 1,
key={field.name} // 显式传 span 可覆盖。跨列只是「腾出空间」,再用 maxWidth 把控件卡在合理宽度:
name={field.name as string} // 既够显示「开始 ~ 结束」(约 236px 控件),又不会被宽屏的 auto-fit 撑到整行那么宽。
label={field.label} const span = field.span ?? (field.type === 'dateRange' ? 2 : 1);
style={{ marginBottom: 0, minWidth: 0 }} const style: React.CSSProperties = { marginBottom: 0, minWidth: 0 };
> if (span > 1) style.gridColumn = `span ${span}`;
if (field.type === 'dateRange') style.maxWidth = 340;
return (
<UFormItem key={field.name} name={field.name as string} label={field.label} style={style}>
{control(field)} {control(field)}
</UFormItem> </UFormItem>
); );
};
return ( return (
<UForm <UForm
......
...@@ -24,6 +24,11 @@ export interface FieldSchema<T extends Record<string, unknown> = Record<string, ...@@ -24,6 +24,11 @@ export interface FieldSchema<T extends Record<string, unknown> = Record<string,
type: FieldType; type: FieldType;
placeholder?: string; placeholder?: string;
width?: number | string; width?: number | string;
/**
* 在筛选栅格里跨几列(默认 1)。时间区间选择器(dateRange)要显示「开始 ~ 结束」,
* 单列的 ~136px 控件放不下,默认 2 列;其余类型如需更宽也可显式指定。
*/
span?: number;
options?: FieldOption[]; options?: FieldOption[];
rules?: Rule[]; rules?: Rule[];
section?: string; section?: string;
......
...@@ -247,9 +247,13 @@ body { ...@@ -247,9 +247,13 @@ body {
动作列用固定宽度而非 auto:常显区与收起区(.uj-filter-more)必须用同一列模板, 动作列用固定宽度而非 auto:常显区与收起区(.uj-filter-more)必须用同一列模板,
否则后者少了动作列、字段列会更宽,两排控件对不齐。--uj-filter-actions-col 即预留的动作列宽。 */ 否则后者少了动作列、字段列会更宽,两排控件对不齐。--uj-filter-actions-col 即预留的动作列宽。 */
.uj-filter-grid { .uj-filter-grid {
--uj-filter-actions-col: 240px; /* 列数由「筛选卡实时宽度」自动决定(auto-fit):能塞几列就几列,
空出来的轨道自动坍缩 —— 所以「5 个字段」绝不会被强行塞进 6 列而压窄,
多余的空列不存在,字段直接撑宽。字段列最小 240px(标签 104 + 控件 ≥136),
保证每个输入框都从容;窗口变窄时自动减列、字段换行,按钮始终钉在第一排。 */
--uj-filter-actions-col: 220px;
display: grid; display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr)) var(--uj-filter-actions-col); grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)) var(--uj-filter-actions-col);
column-gap: var(--uj-space-4, 16px); column-gap: var(--uj-space-4, 16px);
row-gap: var(--uj-space-3, 12px); row-gap: var(--uj-space-3, 12px);
align-items: center; align-items: center;
...@@ -273,7 +277,10 @@ body { ...@@ -273,7 +277,10 @@ body {
} }
/* 动作区:固定在栅格最后一列(动作列),与字段同一排、垂直居中。 */ /* 动作区:固定在栅格最后一列(动作列),与字段同一排、垂直居中。 */
.uj-filter-actions { .uj-filter-actions {
/* 钉在栅格第一行最后一列:无论字段有没有换行,按钮永远和首排字段同排,
不会被多出来的字段顶到第二排。 */
grid-column: -2 / -1; grid-column: -2 / -1;
grid-row: 1;
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
align-items: center; align-items: center;
...@@ -283,9 +290,10 @@ body { ...@@ -283,9 +290,10 @@ body {
/* 收起后的第二排:与第一排同栅格、同列模板(含等宽动作列预留,空着), /* 收起后的第二排:与第一排同栅格、同列模板(含等宽动作列预留,空着),
靠一条淡分隔线区隔,不另起一个卡片。字段列因此与常显区严格对齐。 */ 靠一条淡分隔线区隔,不另起一个卡片。字段列因此与常显区严格对齐。 */
.uj-filter-more { .uj-filter-more {
--uj-filter-actions-col: 240px; /* 与常显区同列模板(auto-fit + 等宽动作列预留),两排控件严格对齐。 */
--uj-filter-actions-col: 220px;
display: grid; display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr)) var(--uj-filter-actions-col); grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)) var(--uj-filter-actions-col);
column-gap: var(--uj-space-4, 16px); column-gap: var(--uj-space-4, 16px);
row-gap: var(--uj-space-3, 12px); row-gap: var(--uj-space-3, 12px);
align-items: center; align-items: center;
...@@ -322,32 +330,22 @@ body { ...@@ -322,32 +330,22 @@ body {
transform: rotate(180deg); transform: rotate(180deg);
} }
/* 标签移到左侧后每组字段多占 104px,列数按「控件至少约 170px」反推: /* 超窄屏:auto-fit 仍会保留右侧 220px 动作列、字段挤成单列,
1700 以下 3 列、1400 以下 2 列、1100 以下 1 列;动作列在窄屏退回整行。 */ 故在此让字段单列堆叠、按钮整行沉底,避免字段被压成 160px 以下的细条。 */
@media (max-width: 1700px) { @media (max-width: 640px) {
.uj-filter-grid { .uj-filter-grid,
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.uj-filter-grid .uj-filter-actions {
grid-column: 1 / -1;
}
.uj-filter-more { .uj-filter-more {
grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 1400px) {
.uj-filter-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
} }
.uj-filter-more { .uj-filter-grid .uj-filter-actions,
grid-template-columns: repeat(2, minmax(0, 1fr)); .uj-filter-more .uj-filter-actions {
grid-column: 1 / -1;
grid-row: auto;
} }
} }
/* 页面级标题行在窄屏改为纵向堆叠(视口级,与筛选卡无关)。 */
@media (max-width: 1100px) { @media (max-width: 1100px) {
.uj-filter-grid,
.uj-filter-more {
grid-template-columns: minmax(0, 1fr);
}
.uj-page__header { .uj-page__header {
flex-direction: column; flex-direction: column;
} }
......
...@@ -731,6 +731,9 @@ importers: ...@@ -731,6 +731,9 @@ importers:
'@tanstack/react-query': '@tanstack/react-query':
specifier: 'catalog:' specifier: 'catalog:'
version: 5.106.1(@types/react@19.3.0)(react@19.3.1) version: 5.106.1(@types/react@19.3.0)(react@19.3.1)
'@uj/api-core':
specifier: workspace:^0.0.0
version: link:../api-core
'@uj/contracts': '@uj/contracts':
specifier: workspace:* specifier: workspace:*
version: link:../contracts version: link:../contracts
......
-- =====================================================================
-- 二手车管理(usedcar)完整重建脚本的回滚
-- 对应 usedcar-menu-complete.sql:删除整棵「二手车管理」子树(menu_code 前缀 10026)。
--
-- 说明:
-- - 先用 dry-run 数一遍要删的行(判据:目录 1 / 页面 12 / 按钮 43 = 56),确认无误再 DELETE。
-- - 10026* 只属于二手车管理模块(门店/系统 10000~10024、积分 10025),不会误删其它模块。
-- - sys_role_menu 按 menu_id 记录关联:外键开启的库必须先清关联,否则删除报错。
-- 清理语句见下方注释,menu_code 前缀对齐后再执行。
-- =====================================================================
USE `yj_service`;
-- 1) dry-run:要删什么,先看数与清单
SELECT `menu_type`, COUNT(*) AS cnt
FROM `sys_menu`
WHERE `menu_code` LIKE '10026%'
GROUP BY `menu_type`;
SELECT `menu_id`, `menu_code`, `parent_code`, `menu_name`, `menu_type`, `perm_code`
FROM `sys_menu`
WHERE `menu_code` LIKE '10026%'
ORDER BY `menu_code`;
-- 2) 先解角色关联(按你库里的表名/字段确认后再放开注释执行)
-- DELETE rm FROM `sys_role_menu` rm
-- JOIN `sys_menu` m ON m.`menu_id` = rm.`menu_id`
-- WHERE m.`menu_code` LIKE '10026%';
-- 3) 删除整棵子树(幂等:跑第二次影响 0 行)
DELETE FROM `sys_menu` WHERE `menu_code` LIKE '10026%';
-- 4) 回查:判据 0 行
SELECT COUNT(*) AS remaining FROM `sys_menu` WHERE `menu_code` LIKE '10026%';
-- =====================================================================
-- 二手车管理(usedcar)菜单 / 权限码 完整重建脚本(自包含)
--
-- 来源:产品给的模块权限定义(12 个页面 + 各页权限按钮),
-- 结构与命名对齐 scripts/points-menu-complete.sql。
--
-- 编号与命名约定(沿用现系统):
-- - 目录 menu_code = 10026(积分 10025 之后顺延;门店/系统占 10000~10024)。
-- - 页面 = 目录码 + 2 位(1002601…1002612),按钮 = 页面码 + 2 位(100260101…)。
-- - perm_code 用 `资源:动作`,域前缀 usedcar:;页面挂 :view,动作各自一码。
-- - route 首段 usedcar 需与子应用 apps/web/subapps/usedcar/package.json 的 uj.route 一致,
-- 否则菜单点进去 404(构建期子应用注册表会先撞车报错,见 shell/src/subapps.ts)。
-- - 图标名必须同时满足两条,否则前端静默回落(dev 环境会告警一次):
-- 1) 是真实的 @ant-design/icons 名称;
-- 2) 已登记在 apps/web/shell/src/layouts/BasicLayout.tsx 的 iconMap。
-- 本脚本用到的 13 个图标已全部登记;一级的 icon 取目录节点自身(见 menu-product-icons.sql)。
--
-- tab 怎么落的:
-- 运营(合同/阳光激励)、车辆台账(车辆/财务)、一客一群(一客一群/4S店配置)
-- 在树上都是【一个页面节点】,tab 的差异体现在按钮的 perm_code 前缀上
-- (contract:/incentive:/ledger:export-finance/dealer:)。
-- 需要整页 tab 隐藏时才加 menu_type=2 且 route=NULL 的子节点(积分 1002504 就是这么用的:
-- 适配器会跳过无 route 的页面节点,于是它只当权限载体,不进侧边栏)。
--
-- 幂等:menu_code 唯一 + INSERT IGNORE,重复执行安全(已存在则跳过)。
-- 若想彻底清空后重建,先跑 preflight 确认范围,再执行:
-- DELETE FROM `sys_menu` WHERE `menu_code` LIKE '10026%';
-- 或直接跑 scripts/usedcar-menu-complete-rollback.sql。
-- 角色授权不在本脚本内(sys_role_menu 按 menu_id 记录,跑完第 4 步自行关联)。
-- =====================================================================
USE `yj_service`;
-- ---------------------------------------------------------------------
-- 0) 预检:三条都必须返回 0 行,否则编号已被占用,先停下来对一下
-- ---------------------------------------------------------------------
SELECT COUNT(*) AS hit_menu_code FROM `sys_menu` WHERE `menu_code` LIKE '10026%';
SELECT COUNT(*) AS hit_menu_id FROM `sys_menu` WHERE `menu_id` BETWEEN 45 AND 100;
SELECT COUNT(*) AS hit_perm_code FROM `sys_menu` WHERE `perm_code` LIKE 'usedcar:%';
-- ---------------------------------------------------------------------
-- 1) 建全:目录 + 12 个页面 + 43 个权限按钮
-- ---------------------------------------------------------------------
INSERT IGNORE INTO `sys_menu` (`menu_id`, `menu_code`, `parent_code`, `menu_name`, `menu_type`, `perm_code`, `product`, `route`, `icon`, `sort`, `visible`, `status`, `create_by`, `create_time`, `update_by`, `update_time`, `is_deleted`) VALUES
-- 一级(产品分组):图标取这一行的 icon
(45, '10026', NULL, '二手车管理', 1, NULL, '二手车管理', NULL, 'CarOutlined', 4, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 数据看板(搜索 + 数据展示/切换,无动作按钮,看数据即 :view)
(46, '1002601', '10026', '数据看板', 2, 'usedcar:dashboard:view', '二手车管理', '/usedcar/dashboard', 'FundProjectionScreenOutlined', 1, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 线索管理(5 个 tab 共用 lead:view;详情页含基础信息/跟进记录/操作日志)
(47, '1002602', '10026', '线索管理', 2, 'usedcar:lead:view', '二手车管理', '/usedcar/leads', 'AimOutlined', 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(48, '100260201', '1002602', '导出', 3, 'usedcar:lead:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(49, '100260202', '1002602', '线索详情', 3, 'usedcar:lead:detail', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 评估管理(详情/车辆评估/评估核价可共用一个页面,按码分闸门)
(50, '1002603', '10026', '评估管理', 2, 'usedcar:assess:view', '二手车管理', '/usedcar/assessment', 'ExperimentOutlined', 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(51, '100260301', '1002603', '导出', 3, 'usedcar:assess:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(52, '100260302', '1002603', '详情', 3, 'usedcar:assess:detail', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(53, '100260303', '1002603', '车辆评估', 3, 'usedcar:assess:evaluate', '二手车管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(54, '100260304', '1002603', '评估核价', 3, 'usedcar:assess:price-audit', '二手车管理', NULL, NULL, 4, 1, 1, NULL, NULL, NULL, NULL, 0),
(55, '100260305', '1002603', '图片下载', 3, 'usedcar:assess:image-download', '二手车管理', NULL, NULL, 5, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 运营管理|tab 合同管理
(56, '1002604', '10026', '运营管理', 2, 'usedcar:operation:view', '二手车管理', '/usedcar/operation', 'ControlOutlined', 4, 1, 1, NULL, NULL, NULL, NULL, 0),
(57, '100260401', '1002604', '合同导出', 3, 'usedcar:contract:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(58, '100260402', '1002604', '批量导入合同', 3, 'usedcar:contract:import', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(59, '100260403', '1002604', '合同详情', 3, 'usedcar:contract:detail', '二手车管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(60, '100260404', '1002604', '合同下载', 3, 'usedcar:contract:download', '二手车管理', NULL, NULL, 4, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 运营管理|tab 阳光激励
(61, '100260405', '1002604', '激励导出', 3, 'usedcar:incentive:export', '二手车管理', NULL, NULL, 5, 1, 1, NULL, NULL, NULL, NULL, 0),
(62, '100260406', '1002604', '新增激励', 3, 'usedcar:incentive:create', '二手车管理', NULL, NULL, 6, 1, 1, NULL, NULL, NULL, NULL, 0),
(63, '100260407', '1002604', '修改激励', 3, 'usedcar:incentive:update', '二手车管理', NULL, NULL, 7, 1, 1, NULL, NULL, NULL, NULL, 0),
(64, '100260408', '1002604', '激励详情', 3, 'usedcar:incentive:detail', '二手车管理', NULL, NULL, 8, 1, 1, NULL, NULL, NULL, NULL, 0),
(65, '100260409', '1002604', '删除激励', 3, 'usedcar:incentive:delete', '二手车管理', NULL, NULL, 9, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 车辆管理(状态变更=编辑车辆,与详情同页)
(66, '1002605', '10026', '车辆管理', 2, 'usedcar:vehicle:view', '二手车管理', '/usedcar/vehicles', 'ToolOutlined', 5, 1, 1, NULL, NULL, NULL, NULL, 0),
(67, '100260501', '1002605', '导出', 3, 'usedcar:vehicle:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(68, '100260502', '1002605', '详情', 3, 'usedcar:vehicle:detail', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(69, '100260503', '1002605', '状态变更', 3, 'usedcar:vehicle:status', '二手车管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(70, '100260504', '1002605', '图片下载', 3, 'usedcar:vehicle:image-download', '二手车管理', NULL, NULL, 4, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 交付单管理
(71, '1002606', '10026', '交付单管理', 2, 'usedcar:delivery:view', '二手车管理', '/usedcar/delivery', 'SendOutlined', 6, 1, 1, NULL, NULL, NULL, NULL, 0),
(72, '100260601', '1002606', '导出', 3, 'usedcar:delivery:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(73, '100260602', '1002606', '详情', 3, 'usedcar:delivery:detail', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 车辆台账|tab 车辆台账 / tab 财务台账(财务侧口径单独一码,便于只给车辆台账的角色挡住金额)
(74, '1002607', '10026', '车辆台账', 2, 'usedcar:ledger:view', '二手车管理', '/usedcar/ledger', 'ReconciliationOutlined', 7, 1, 1, NULL, NULL, NULL, NULL, 0),
(75, '100260701', '1002607', '车辆台账导出', 3, 'usedcar:ledger:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(76, '100260702', '1002607', '财务台账导出', 3, 'usedcar:ledger:export-finance', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 离职继承(新增人员交接为 3 步弹窗表单)
(77, '1002608', '10026', '离职继承', 2, 'usedcar:handover:view', '二手车管理', '/usedcar/handover', 'UserSwitchOutlined', 8, 1, 1, NULL, NULL, NULL, NULL, 0),
(78, '100260801', '1002608', '新增人员交接', 3, 'usedcar:handover:create', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(79, '100260802', '1002608', '交接详情', 3, 'usedcar:handover:detail', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 报告管理(详情跳转 H5)
(80, '1002609', '10026', '报告管理', 2, 'usedcar:report:view', '二手车管理', '/usedcar/reports', 'FileTextOutlined', 9, 1, 1, NULL, NULL, NULL, NULL, 0),
(81, '100260901', '1002609', '导出', 3, 'usedcar:report:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(82, '100260902', '1002609', '详情(H5)', 3, 'usedcar:report:detail', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 车况信息(编辑车况 → 一键生成评估单 / AI 收车报告)
(83, '1002610', '10026', '车况信息', 2, 'usedcar:condition:view', '二手车管理', '/usedcar/condition', 'SafetyCertificateOutlined', 10, 1, 1, NULL, NULL, NULL, NULL, 0),
(84, '100261001', '1002610', '详情/编辑', 3, 'usedcar:condition:edit', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(85, '100261002', '1002610', '一键生成评估单', 3, 'usedcar:condition:assess-order', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(86, '100261003', '1002610', 'AI收车报告(H5)', 3, 'usedcar:condition:ai-report', '二手车管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 一客一群(预生成)|tab 一客一群
(87, '1002611', '10026', '一客一群(预生成)', 2, 'usedcar:group:view', '二手车管理', '/usedcar/customer-group', 'WechatOutlined', 11, 1, 1, NULL, NULL, NULL, NULL, 0),
(88, '100261101', '1002611', '创建群活码', 3, 'usedcar:group:create', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(89, '100261102', '1002611', '批量删除', 3, 'usedcar:group:batch-delete', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(90, '100261103', '1002611', '下载', 3, 'usedcar:group:download', '二手车管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(91, '100261104', '1002611', '修改', 3, 'usedcar:group:update', '二手车管理', NULL, NULL, 4, 1, 1, NULL, NULL, NULL, NULL, 0),
(92, '100261105', '1002611', '删除', 3, 'usedcar:group:delete', '二手车管理', NULL, NULL, 5, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 一客一群(预生成)|tab 4S店配置
(93, '100261106', '1002611', '新增配置', 3, 'usedcar:dealer:create', '二手车管理', NULL, NULL, 6, 1, 1, NULL, NULL, NULL, NULL, 0),
(94, '100261107', '1002611', '修改配置', 3, 'usedcar:dealer:update', '二手车管理', NULL, NULL, 7, 1, 1, NULL, NULL, NULL, NULL, 0),
(95, '100261108', '1002611', '删除配置', 3, 'usedcar:dealer:delete', '二手车管理', NULL, NULL, 8, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 付款管理
(96, '1002612', '10026', '付款管理', 2, 'usedcar:payment:view', '二手车管理', '/usedcar/payment', 'PayCircleOutlined', 12, 1, 1, NULL, NULL, NULL, NULL, 0),
(97, '100261201', '1002612', '导出', 3, 'usedcar:payment:export', '二手车管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(98, '100261202', '1002612', '批量重推付款单', 3, 'usedcar:payment:batch-repay', '二手车管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(99, '100261203', '1002612', '详情', 3, 'usedcar:payment:detail', '二手车管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(100, '100261204', '1002612', '回单', 3, 'usedcar:payment:receipt', '二手车管理', NULL, NULL, 4, 1, 1, NULL, NULL, NULL, NULL, 0);
-- ---------------------------------------------------------------------
-- 2) 回查:判据 —— 目录 1 行 / 页面 12 行 / 按钮 43 行,且页面 icon 全部非空
-- ---------------------------------------------------------------------
SELECT `menu_type`, COUNT(*) AS cnt
FROM `sys_menu`
WHERE `menu_code` LIKE '10026%' AND `is_deleted` = 0
GROUP BY `menu_type`;
SELECT `menu_code`, `menu_name`, `perm_code`, `route`, `icon`
FROM `sys_menu`
WHERE `menu_type` = 2 AND `menu_code` LIKE '10026%' AND `is_deleted` = 0
ORDER BY `sort`;
-- ---------------------------------------------------------------------
-- 3) 孤儿检查:判据 0 行(父节点不在这棵树里 = 编号写错,菜单会整项不渲染)
-- ---------------------------------------------------------------------
SELECT c.`menu_code`, c.`parent_code`, c.`menu_name`
FROM `sys_menu` c
LEFT JOIN `sys_menu` p ON p.`menu_code` = c.`parent_code` AND p.`is_deleted` = 0
WHERE c.`menu_code` LIKE '10026%' AND c.`is_deleted` = 0
AND c.`parent_code` IS NOT NULL AND p.`menu_code` IS NULL;
-- ---------------------------------------------------------------------
-- 4) 授权:本脚本不猜角色。确认要给的 menu_id 区间后自行关联,例如超级管理员:
-- INSERT IGNORE INTO `sys_role_menu` (`role_id`, `menu_id`)
-- SELECT <role_id>, `menu_id` FROM `sys_menu` WHERE `menu_code` LIKE '10026%';
-- 不授权的话后端 /system/menu/tree/current 不会下发,侧边栏看不到(不是前端 bug)。
-- ---------------------------------------------------------------------
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!