Commit 33e7a2d3 by chenwq

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

2 parents f4f08371 ff73bae9
Pipeline #390 for 33e7a2d3 failed in 0 seconds
Showing 145 changed files with 2667 additions and 878 deletions
...@@ -92,12 +92,14 @@ scripts/ ...@@ -92,12 +92,14 @@ scripts/
`apps/mp` 下四个原生小程序(points / sales / store / usedcar)同仓,但它们**不进 pnpm 的构建链**(没有 build 任务),在微信开发者工具里编译,第三方依赖靠「构建 npm」落到 `miniprogram_npm/`。 `apps/mp` 下四个原生小程序(points / sales / store / usedcar)同仓,但它们**不进 pnpm 的构建链**(没有 build 任务),在微信开发者工具里编译,第三方依赖靠「构建 npm」落到 `miniprogram_npm/`。
先跑一次工作区安装(只认 pnpm,不要用 npm install): 克隆之后**一条命令**,四件事按依赖顺序自己补齐,不需要事先单独 `pnpm install`:
```bash ```bash
pnpm install pnpm build:npm # 装依赖 → api-core 产物 → 子包依赖 → 构建 npm → 体检
``` ```
只认 pnpm,不要用 npm install(唯一例外是 `packageUsedCar`,脚本内部自己调 npm)。
### 只做你改的那个小程序 ### 只做你改的那个小程序
每个小程序根目录都有自己的入口 `mp-npm.mjs`,**只管自己**,不会碰其他三个: 每个小程序根目录都有自己的入口 `mp-npm.mjs`,**只管自己**,不会碰其他三个:
...@@ -111,27 +113,29 @@ cd apps/mp/store && node mp-npm.mjs --check # 同样效果 ...@@ -111,27 +113,29 @@ cd apps/mp/store && node mp-npm.mjs --check # 同样效果
(`mp-npm.mjs` 已写进各 lane 的 `packOptions.ignore`,不会被打进小程序包体。) (`mp-npm.mjs` 已写进各 lane 的 `packOptions.ignore`,不会被打进小程序包体。)
它做三步,用不上的步骤不会出现(非 usedcar 不会打印子包依赖那一段): 它按顺序做四步,用不上的步骤不会出现(非 usedcar 不打印子包依赖那一段):
1. `pnpm --filter @uj/api-core build` → `miniprogram_dist/`——「构建 npm」的唯一输入,gitignore 的产物,漏了就是白屏; 1. 工作区依赖:`node_modules/.modules.yaml` 不存在就跑 `pnpm install`(`--check` 只报不装);`pnpm-lock.yaml` 比它新会提示依赖可能过期;
2. 本 lane 有内嵌子包时(目前只有 usedcar 的 `packageUsedCar`)缺依赖就跑 `setup:deps`(内部 `npm install`); 2. `pnpm --filter @uj/api-core build` → `miniprogram_dist/`——「构建 npm」的唯一输入,gitignore 的产物,漏了就是白屏;
3. 服务端口 9420 可达时调 `cli.bat build-npm` 自动构建;然后按工具自己的判定规则校验 `miniprogram_npm/`,缺哪个包点哪个名。 3. 本 lane 有内嵌子包时(目前只有 usedcar 的 `packageUsedCar`)缺依赖就跑 `setup:deps`(内部 `npm install`);
4. 服务端口 9420 可达时调 `cli.bat build-npm` 自动构建;然后按工具自己的判定规则校验 `miniprogram_npm/`,缺哪个包点哪个名。
### 一次准备全仓(新环境 / CI) ### 一次准备全仓(新环境 / CI)
```bash ```bash
pnpm mp # 遍历 apps/mp/manifest.json 里所有 lane pnpm build:npm # 等价于 pnpm mp,遍历 apps/mp/manifest.json 里所有 lane
pnpm mp:check # 只体检 pnpm mp:check # 只体检
pnpm mp --lane usedcar,store # 指定几个(等价于分别进目录跑) pnpm mp --lane usedcar,store # 指定几个(等价于分别进目录跑)
``` ```
退出码:全绿 0,有缺口 1,可直接挂钩子。 退出码:全绿 0;有缺口、或前置(依赖 / api-core / 子包)没完成 1,可直接挂钩子。
想让第 3 步免人工:开发者工具 → **设置 → 安全设置 → 打开「服务端口」**,之后脚本会自己调 cli 构建;没开会打印精确到项目目录的人工清单。 想让第 4 步免人工:开发者工具 → **设置 → 安全设置 → 打开「服务端口」**,之后脚本会自己调 cli 构建;没开会打印精确到项目目录的人工清单。
脚本坏了才需要的手工等价步骤: 脚本坏了才需要的手工等价步骤:
```bash ```bash
pnpm install # 工作区依赖
pnpm --filter @uj/api-core build # api-core 产物 pnpm --filter @uj/api-core build # api-core 产物
pnpm --filter @uj/mp-usedcar run setup:deps # 仅 usedcar pnpm --filter @uj/mp-usedcar run setup:deps # 仅 usedcar
# 然后在开发者工具里打开 apps/mp/<lane> → 工具 → 构建 npm # 然后在开发者工具里打开 apps/mp/<lane> → 工具 → 构建 npm
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -17,7 +17,9 @@ import { ...@@ -17,7 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。 * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同算法。 * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -28,7 +30,7 @@ export const demoGateway: GatewayStrategy = { ...@@ -28,7 +30,7 @@ export const demoGateway: GatewayStrategy = {
router: 'rop-scrm-demo/router', router: 'rop-scrm-demo/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'demo-sha1' }), signer: createSigner({ kind: 'rop', id: 'demo-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
node_modules/ node_modules/
/miniprogram_npm/ miniprogram_npm
/miniprogram_npm
*.log *.log
.DS_Store .DS_Store
*.tmp *.tmp
...@@ -11,7 +11,10 @@ let index = 2 ...@@ -11,7 +11,10 @@ let index = 2
4预发布 4预发布
*/ */
const accountInfo = wx.getAccountInfoSync() const accountInfo = wx.getAccountInfoSync()
const systemInfo = wx.getSystemInfoSync() // 基础库 2.20.1+ 起 getSystemInfoSync 已废弃,环境判定只用到 platform,
// 改用 getDeviceInfo;旧基础库(无该接口)回退到旧接口,避免无谓报错。
const systemInfo =
typeof wx.getDeviceInfo === 'function' ? wx.getDeviceInfo() : wx.getSystemInfoSync()
// console.log(systemInfo); // console.log(systemInfo);
// console.log(accountInfo.miniProgram.envVersion) // console.log(accountInfo.miniProgram.envVersion)
//手动控制体验版环境的请求 true就依据下面index false就默认为2 //手动控制体验版环境的请求 true就依据下面index false就默认为2
......
/** /**
* points 请求层:@uj/api-core 的客户端工厂。 * points 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL 拼装 / 签名 / * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL 拼装 / 签名 /
* 拦截器(业务码归一 / 登录跳转 / loading / toast)由 api-core 负责。 * 拦截器(业务码归一 / 登录跳转 / loading / toast)由 api-core 负责。
* *
* public API 与旧壳一致:get/post/request(RequestMethods, params, returnAll)、 * public API 与旧壳一致:get/post/request(RequestMethods, params, returnAll)、
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
* · sentry 上报 → events.error + onTransportError * · sentry 上报 → events.error + onTransportError
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { import {
defaultMerchantId, defaultMerchantId,
secretKey, secretKey,
...@@ -29,7 +29,8 @@ const DEFAULT_CRED = { ...@@ -29,7 +29,8 @@ const DEFAULT_CRED = {
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b', secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
} }
const client = createRopClient({ const client = createClient({
kind: 'rop',
hosts: { scrm: domain }, hosts: { scrm: domain },
pathEnum, pathEnum,
secretKey, secretKey,
......
...@@ -34,23 +34,30 @@ Component({ ...@@ -34,23 +34,30 @@ Component({
}, },
init() { init() {
/** /**
* 获取自定义导航栏信息 * 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → wx.getWindowInfo()
* fontSizeSetting → wx.getAppBaseInfo()
* 新接口均为同步返回,去掉原来的 .then 异步时序。
*/ */
wx.getSystemInfo().then(res => { const windowInfo = wx.getWindowInfo() || {}
const appBaseInfo = wx.getAppBaseInfo() || {}
let { let {
fontSizeSetting, fontSizeSetting,
statusBarHeight, statusBarHeight,
screenWidth screenWidth,
} = res } = {
...windowInfo,
fontSizeSetting: appBaseInfo.fontSizeSetting,
}
const { const {
height, height,
right, right,
width, width,
top top,
} = wx.getMenuButtonBoundingClientRect(), } = wx.getMenuButtonBoundingClientRect()
currentPages = getCurrentPages(), { const currentPages = getCurrentPages()
showBack const { showBack } = this.data
} = this.data
if (showBack && currentPages.length > 1) this.setData({ if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true SHOWBACK: true
}) })
...@@ -67,7 +74,6 @@ Component({ ...@@ -67,7 +74,6 @@ Component({
navigationBarHeight, navigationBarHeight,
statusBarHeight statusBarHeight
}) })
})
}, },
emit({ emit({
navigationBarHeight, navigationBarHeight,
......
...@@ -15,7 +15,7 @@ Page({ ...@@ -15,7 +15,7 @@ Page({
* 生命周期函数--监听页面加载 * 生命周期函数--监听页面加载
*/ */
onLoad: function (options) { onLoad: function (options) {
let system = wx.getSystemInfoSync() let system = wx.getWindowInfo()
this.getAllMerchantList() this.getAllMerchantList()
this.setData({ this.setData({
cHeight: system.windowHeight cHeight: system.windowHeight
......
...@@ -61,7 +61,7 @@ Page({ ...@@ -61,7 +61,7 @@ Page({
}, },
onLoad(options) { onLoad(options) {
let system = wx.getSystemInfoSync() let system = wx.getWindowInfo()
const { merchantId } = wx.p.storage.get('merchant_info') const { merchantId } = wx.p.storage.get('merchant_info')
this.toGetFreeCardDay(merchantId) this.toGetFreeCardDay(merchantId)
this.setData({ this.setData({
......
...@@ -16,12 +16,16 @@ ...@@ -16,12 +16,16 @@
"uglifyFileName": false, "uglifyFileName": false,
"uploadWithSourceMap": true, "uploadWithSourceMap": true,
"useIsolateContext": false, "useIsolateContext": false,
"nodeModules": false,
"enhance": true, "enhance": true,
"useMultiFrameRuntime": true, "useMultiFrameRuntime": true,
"showShadowRootInWxmlPanel": true, "showShadowRootInWxmlPanel": true,
"packNpmManually": false, "packNpmManually": true,
"packNpmRelationList": [], "packNpmRelationList": [
{
"packageJsonPath": "./package.json",
"miniprogramNpmDistDir": "./"
}
],
"minifyWXSS": true, "minifyWXSS": true,
"disableUseStrict": false, "disableUseStrict": false,
"ignoreUploadUnusedFiles": true, "ignoreUploadUnusedFiles": true,
...@@ -37,7 +41,11 @@ ...@@ -37,7 +41,11 @@
"useCompilerPlugins": [ "useCompilerPlugins": [
"sass" "sass"
], ],
"condition": true "condition": true,
"compileWorklet": false,
"localPlugins": false,
"swc": false,
"disableSWC": true
}, },
"compileType": "miniprogram", "compileType": "miniprogram",
"simulatorType": "wechat", "simulatorType": "wechat",
...@@ -62,5 +70,6 @@ ...@@ -62,5 +70,6 @@
], ],
"include": [] "include": []
}, },
"appid": "wx7ce755e425603084" "appid": "wx7ce755e425603084",
"libVersion": "3.9.0"
} }
\ No newline at end of file \ No newline at end of file
{ {
"libVersion": "3.9.0", "libVersion": "3.9.0",
"projectname": "points-mall", "projectname": "points",
"setting": { "setting": {
"urlCheck": false, "urlCheck": false,
"coverView": true, "coverView": true,
...@@ -9,97 +9,16 @@ ...@@ -9,97 +9,16 @@
"preloadBackgroundData": false, "preloadBackgroundData": false,
"autoAudits": false, "autoAudits": false,
"showShadowRootInWxmlPanel": true, "showShadowRootInWxmlPanel": true,
"compileHotReLoad": true "compileHotReLoad": true,
"useApiHook": true,
"useStaticServer": true,
"useLanDebug": false,
"showES6CompileOption": false,
"checkInvalidKey": true,
"ignoreDevUnusedFiles": true,
"bigPackageSizeSupport": false,
"useIsolateContext": false
}, },
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html", "description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
"condition": { "condition": {}
"miniprogram": {
"list": [
{
"name": "packageMine/pages/order/index/index",
"pathName": "packageMine/pages/order/index/index",
"query": "",
"scene": null,
"launchMode": "default"
},
{
"name": "pages/Login/Login",
"pathName": "pages/Login/Login",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "积分中心",
"pathName": "packageIndex/pages/integral/index/index",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "提现记录",
"pathName": "packageIndex/pages/integral/withdrawalNote/withdrawalNote",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "我要提现",
"pathName": "packageIndex/pages/integral/withdrawal/withdrawal",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "添加账户",
"pathName": "packageIndex/pages/bankAccount/add/add",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "收款账户",
"pathName": "packageIndex/pages/bankAccount/list/list",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "兑换成功",
"pathName": "packageIndex/pages/integral/withdrawalSuccess/withdrawalSuccess",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "",
"pathName": "packageIndex/pages/integral/withdrawalRules/withdrawalRules",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "购物车",
"pathName": "pages/tab/cart/index",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "我的页面",
"pathName": "pages/tab/mine/index",
"query": "",
"launchMode": "default",
"scene": null
},
{
"name": "设置",
"pathName": "packageMine/pages/setting/index",
"query": "",
"launchMode": "default",
"scene": null
}
]
}
}
} }
\ No newline at end of file \ No newline at end of file
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -17,8 +17,9 @@ import { ...@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。 * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同 * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const pointsGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const pointsGateway: GatewayStrategy = {
router: 'rop-scrm-points/router', router: 'rop-scrm-points/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'points-sha1' }), signer: createSigner({ kind: 'rop', id: 'points-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
...@@ -47,13 +47,14 @@ export function getNavigationBarTitleText() { ...@@ -47,13 +47,14 @@ export function getNavigationBarTitleText() {
/** 存储设备信息 */ /** 存储设备信息 */
export function setSystem_info(that) { export function setSystem_info(that) {
let info = storage.get('system_info') let info = storage.get('system_info')
!info && if (!info) {
wx.getSystemInfo({ // 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆到新接口后合并存储,
success(res) { // 保证 utils/track/Track.js 读取的 brand/model/system/SDKVersion/version 等字段仍可用。
// console.log(res) const windowInfo = wx.getWindowInfo() || {}
storage.set('system_info', res) const appBaseInfo = wx.getAppBaseInfo() || {}
const deviceInfo = wx.getDeviceInfo() || {}
storage.set('system_info', { ...deviceInfo, ...appBaseInfo, ...windowInfo })
} }
})
} }
export default{ export default{
......
...@@ -200,7 +200,7 @@ reportParamError('霈W”撘虜嚗erchantId, channelSource, phone 餈 ...@@ -200,7 +200,7 @@ reportParamError('霈W”撘虜嚗erchantId, channelSource, phone 餈
productId: 'prod_456', productId: 'prod_456',
quantity: 2, quantity: 2,
operation: 'add_to_cart', operation: 'add_to_cart',
userAgent: wx.getSystemInfoSync(), userAgent: wx.getDeviceInfo(),
timestamp: Date.now() timestamp: Date.now()
}; };
...@@ -212,7 +212,7 @@ reportSentryError('韐剔頧行仃韐', cartParams, { ...@@ -212,7 +212,7 @@ reportSentryError('韐剔頧行仃韐', cartParams, {
user_type: 'premium' user_type: 'premium'
}, },
contexts: { contexts: {
device_info: wx.getSystemInfoSync(), device_info: { ...wx.getDeviceInfo(), ...wx.getWindowInfo(), ...wx.getAppBaseInfo() },
app_version: '1.2.3' app_version: '1.2.3'
} }
});*/ });*/
...@@ -58,14 +58,18 @@ const showToast = val => { ...@@ -58,14 +58,18 @@ const showToast = val => {
/**获取设备信息 */ /**获取设备信息 */
const getSystemInfo = callBack => { const getSystemInfo = callBack => {
wx.getSystemInfo({ try {
success(res) { // 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆到新接口后合并返回,
callBack(res) // 保持与原 getSystemInfo 一致的字段集合,避免调用方逐个改造。
}, const windowInfo = wx.getWindowInfo() || {}
fail(err) { const appBaseInfo = wx.getAppBaseInfo() || {}
const deviceInfo = wx.getDeviceInfo() || {}
const systemSetting = wx.getSystemSetting() || {}
const appAuthorizeSetting = wx.getAppAuthorizeSetting() || {}
callBack({ ...deviceInfo, ...appBaseInfo, ...windowInfo, ...systemSetting, ...appAuthorizeSetting })
} catch (err) {
callBack(err) callBack(err)
} }
})
} }
/**拨打电话 */ /**拨打电话 */
......
project.config.json
project.private.config.json
sitemap.json
miniprogram_npm
/miniprogram_npm
node_modules
/node_modules
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*
// components/navigationBar/navigationBar.js // components/navigationBar/navigationBar.js
import { getSystemInfoSync } from '~/utils/systemInfo'
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
...@@ -34,23 +36,20 @@ Component({ ...@@ -34,23 +36,20 @@ Component({
}, },
init() { init() {
/** /**
* 获取自定义导航栏信息 * 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → getWindowInfo
* fontSizeSetting → getAppBaseInfo
*/ */
wx.getSystemInfo().then(res => { const { fontSizeSetting, statusBarHeight, screenWidth } = getSystemInfoSync()
let {
fontSizeSetting,
statusBarHeight,
screenWidth
} = res
const { const {
height, height,
right, right,
width, width,
top top,
} = wx.getMenuButtonBoundingClientRect(), } = wx.getMenuButtonBoundingClientRect()
currentPages = getCurrentPages(), { const currentPages = getCurrentPages()
showBack const { showBack } = this.data
} = this.data
if (showBack && currentPages.length > 1) this.setData({ if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true SHOWBACK: true
}) })
...@@ -67,7 +66,6 @@ Component({ ...@@ -67,7 +66,6 @@ Component({
navigationBarHeight, navigationBarHeight,
statusBarHeight statusBarHeight
}) })
})
}, },
emit({ emit({
navigationBarHeight, navigationBarHeight,
......
// packageEquity/pages/active/active.js // packageEquity/pages/active/active.js
import { equityApi } from '~/api/api' import { equityApi } from '~/api/api'
import USER from '~/api/usersApi/index' import USER from '~/api/usersApi/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({ Page({
/** /**
* 页面的初始数据 * 页面的初始数据
...@@ -109,7 +110,7 @@ Page({ ...@@ -109,7 +110,7 @@ Page({
}, },
onLoad: function (options) { onLoad: function (options) {
this.login() this.login()
let system = wx.getSystemInfoSync() let system = getSystemInfoSync()
this.setData({ this.setData({
cHeight: system.windowHeight cHeight: system.windowHeight
}) })
......
import { equityApi } from '~/api/api' import { equityApi } from '~/api/api'
import { isMember } from '~/utils/cache/storageApi' import { isMember } from '~/utils/cache/storageApi'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({ Page({
/** /**
* 页面的初始数据 * 页面的初始数据
...@@ -16,7 +17,7 @@ Page({ ...@@ -16,7 +17,7 @@ Page({
* 生命周期函数--监听页面加载 * 生命周期函数--监听页面加载
*/ */
onLoad: function (options) { onLoad: function (options) {
let system = wx.getSystemInfoSync() let system = getSystemInfoSync()
this.getAllMerchantList() this.getAllMerchantList()
this.setData( this.setData(
{ {
......
import { couponsApi, shopmallApi, ssoApi } from '~/api/api' import { couponsApi, shopmallApi, ssoApi } from '~/api/api'
import USER from '~/api/usersApi/index' import USER from '~/api/usersApi/index'
import { defaultMerchantId } from '~/utils/request/environment' import { defaultMerchantId } from '~/utils/request/environment'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({ Page({
data: { data: {
freeDay: 0, freeDay: 0,
...@@ -110,7 +111,7 @@ Page({ ...@@ -110,7 +111,7 @@ Page({
}) })
}, },
onLoad(options) { onLoad(options) {
let system = wx.getSystemInfoSync() let system = getSystemInfoSync()
const merchantId = wx.$storage.get('srcm_shopmall_merchant_id') const merchantId = wx.$storage.get('srcm_shopmall_merchant_id')
let newMerchantId = merchantId || defaultMerchantId let newMerchantId = merchantId || defaultMerchantId
......
import { commonApi, equityApi } from '~/api/api' import { commonApi, equityApi } from '~/api/api'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({ Page({
data: { data: {
tempFilePath: '', tempFilePath: '',
...@@ -34,7 +35,7 @@ Page({ ...@@ -34,7 +35,7 @@ Page({
let query = wx.createSelectorQuery().in(this); //获取自定义组件的SelectQuery对象 let query = wx.createSelectorQuery().in(this); //获取自定义组件的SelectQuery对象
this.canvasCtx = wx.createCanvasContext('signature', that) this.canvasCtx = wx.createCanvasContext('signature', that)
// 设置线的样式 // 设置线的样式
let { windowWidth, windowHeight } = wx.getSystemInfoSync() let { windowWidth, windowHeight } = getSystemInfoSync()
this.canvasCtx.setFillStyle("white"); this.canvasCtx.setFillStyle("white");
this.canvasCtx.fillRect(0, 0, windowWidth, windowHeight); this.canvasCtx.fillRect(0, 0, windowWidth, windowHeight);
this.canvasCtx.setLineCap("round"); this.canvasCtx.setLineCap("round");
......
// components/navigationBar/navigationBar.js // components/navigationBar/navigationBar.js
import { getSystemInfoSync } from '~/utils/systemInfo'
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
...@@ -33,10 +35,12 @@ Component({ ...@@ -33,10 +35,12 @@ Component({
}, },
init() { init() {
/** /**
* 获取自定义导航栏信息 * 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → getWindowInfo
* fontSizeSetting → getAppBaseInfo
*/ */
wx.getSystemInfo().then(res => { const { fontSizeSetting, statusBarHeight, screenWidth } = getSystemInfoSync()
let { fontSizeSetting, statusBarHeight, screenWidth } = res
const { height, right, width, top } = wx.getMenuButtonBoundingClientRect() const { height, right, width, top } = wx.getMenuButtonBoundingClientRect()
let navigationBarHeight = height + (top - statusBarHeight) * 2 + 4 // 4 let navigationBarHeight = height + (top - statusBarHeight) * 2 + 4 // 4
let navigationBarPadding = screenWidth - right let navigationBarPadding = screenWidth - right
...@@ -51,7 +55,6 @@ Component({ ...@@ -51,7 +55,6 @@ Component({
navigationBarHeight, navigationBarHeight,
statusBarHeight statusBarHeight
}) })
})
}, },
emit({ navigationBarHeight, statusBarHeight }) { emit({ navigationBarHeight, statusBarHeight }) {
let navHeight = navigationBarHeight + statusBarHeight let navHeight = navigationBarHeight + statusBarHeight
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import { imgUrlMixin } from '~/mixins/index' import { imgUrlMixin } from '~/mixins/index'
import index_const from '~/pages/tab/storeAssistant/pages/index/index_const' import index_const from '~/pages/tab/storeAssistant/pages/index/index_const'
import Draw from '~/utils/Draw' import Draw from '~/utils/Draw'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
...@@ -20,7 +21,7 @@ Component({ ...@@ -20,7 +21,7 @@ Component({
wx.$api.showLoading('处理中') wx.$api.showLoading('处理中')
val.boxImageHeight = 66 val.boxImageHeight = 66
// 计算弹窗图片区域最大高度 // 计算弹窗图片区域最大高度
let windowHeight = wx.getSystemInfoSync().windowHeight let windowHeight = getSystemInfoSync().windowHeight
let res = { let res = {
height: windowHeight - 150 height: windowHeight - 150
} }
......
//index.js //index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本! //注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from './u-charts/u-charts.js'; import uCharts from './u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
var uChartsInstance = {}; var uChartsInstance = {};
Component({ Component({
properties: { properties: {
...@@ -19,9 +20,9 @@ Component({ ...@@ -19,9 +20,9 @@ Component({
methods: { methods: {
setLine() { setLine() {
//这里的第一个 750 对应 css .charts 的 width //这里的第一个 750 对应 css .charts 的 width
const cWidth = 640 / 750 * wx.getSystemInfoSync().windowWidth; const cWidth = 640 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height //这里的 500 对应 css .charts 的 height
const cHeight = 300 / 750 * wx.getSystemInfoSync().windowWidth; const cHeight = 300 / 750 * getSystemInfoSync().windowWidth;
this.setData({ this.setData({
cWidth, cWidth,
cHeight cHeight
......
// packageStoreAssistant/packageActivity/pages/pay/pay.js // packageStoreAssistant/packageActivity/pages/pay/pay.js
import ActivityApi from '~/api/activityApi/index' import ActivityApi from '~/api/activityApi/index'
import wxqrcode from '~/utils/lib/wxqrcode' import wxqrcode from '~/utils/lib/wxqrcode'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
import { import {
centsToyuan, centsToyuan,
accAdd accAdd
...@@ -234,7 +235,7 @@ Page({ ...@@ -234,7 +235,7 @@ Page({
// console.log(text) // console.log(text)
let size = 0 let size = 0
try { try {
const info = wx.getSystemInfoSync() const info = getSystemInfoSync()
let scale = info.windowWidth / 750 //不同屏幕下QRcode的适配比例;设计稿是750宽 let scale = info.windowWidth / 750 //不同屏幕下QRcode的适配比例;设计稿是750宽
let width = 300 * scale let width = 300 * scale
size = width size = width
......
// packageStoreAssistant/packageEquityClaims/components/picture/picture.js // packageStoreAssistant/packageEquityClaims/components/picture/picture.js
import { commonApi } from '~/api/api' import { commonApi } from '~/api/api'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
...@@ -80,7 +81,7 @@ Component({ ...@@ -80,7 +81,7 @@ Component({
// this.triggerEvent('upload', {url: 'https://img02.glsx.com.cn/weapp/resource/saas/scrm/assets/glsx/logo_collapse_new_common.png',type : 'png'}); // this.triggerEvent('upload', {url: 'https://img02.glsx.com.cn/weapp/resource/saas/scrm/assets/glsx/logo_collapse_new_common.png',type : 'png'});
// if(e) return // if(e) return
const {count} = this.data.configOptions const {count} = this.data.configOptions
let sysInfo = wx.getSystemInfoSync() let sysInfo = getSystemInfoSync()
let maxNum = sysInfo?.environment ? 9 : 20 // 企微打开的话最大是9张。如果count大于9 会无法上传有异常 let maxNum = sysInfo?.environment ? 9 : 20 // 企微打开的话最大是9张。如果count大于9 会无法上传有异常
let aleadyLength = 0 let aleadyLength = 0
if (batchFlag) { if (batchFlag) {
......
import MineApi from '~/api/mineApi/index' import MineApi from '~/api/mineApi/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({ Page({
/** /**
* 页面的初始数据 * 页面的初始数据
...@@ -70,7 +71,7 @@ Page({ ...@@ -70,7 +71,7 @@ Page({
pageSize, pageSize,
merchantId merchantId
}).then(res => { }).then(res => {
let windowWidth = wx.getSystemInfoSync().windowWidth let windowWidth = getSystemInfoSync().windowWidth
let activityTitleViewWidth = windowWidth - ((windowWidth / 375) * (46 + 48 + 160 + 24)) / 2 // 活动title区域宽度 let activityTitleViewWidth = windowWidth - ((windowWidth / 375) * (46 + 48 + 160 + 24)) / 2 // 活动title区域宽度
res.list && res.list &&
res.list.forEach((val, index) => { res.list.forEach((val, index) => {
......
import { IMG_URL } from "~/utils/constantData"; import { IMG_URL } from "~/utils/constantData";
import { discoveryApi,shopmallApi } from "~/api/api"; import { discoveryApi,shopmallApi } from "~/api/api";
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
...@@ -95,7 +96,7 @@ Component({ ...@@ -95,7 +96,7 @@ Component({
} }
}); });
const systemInfo = wx.getSystemInfoSync() const systemInfo = getSystemInfoSync()
this.setData({ this.setData({
channelStyle, channelStyle,
list, list,
......
// pages/tab/storeAssistant/pages/index/components/clueManage/clueManage.js // pages/tab/storeAssistant/pages/index/components/clueManage/clueManage.js
import { imgUrlMixin } from '~/mixins/index' import { imgUrlMixin } from '~/mixins/index'
import activityApi from '~/api/activityApi/index'; import activityApi from '~/api/activityApi/index';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({ Component({
behaviors: [imgUrlMixin], behaviors: [imgUrlMixin],
...@@ -49,7 +50,7 @@ Component({ ...@@ -49,7 +50,7 @@ Component({
methods: { methods: {
computeBottom() { computeBottom() {
try { try {
wx.getSystemInfo({ getSystemInfo({
success: (res) => { success: (res) => {
const ratio = res.screenWidth / 750 const ratio = res.screenWidth / 750
const safeInsetBottom = res.safeArea ? (res.screenHeight - res.safeArea.bottom) : 0 const safeInsetBottom = res.safeArea ? (res.screenHeight - res.safeArea.bottom) : 0
......
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
// pages/tab/storeAssistant/pages/index/components/sopChart/sopChart.js // pages/tab/storeAssistant/pages/index/components/sopChart/sopChart.js
// import * as echarts from '../ec-canvas/echarts'; // import * as echarts from '../ec-canvas/echarts';
var uChartsInstance = {}; var uChartsInstance = {};
...@@ -33,9 +34,9 @@ Component({ ...@@ -33,9 +34,9 @@ Component({
methods: { methods: {
onReady() { onReady() {
//这里的第一个 750 对应 css .charts 的 width //这里的第一个 750 对应 css .charts 的 width
const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth; const cWidth = 750 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height //这里的 500 对应 css .charts 的 height
const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth; const cHeight = 500 / 750 * getSystemInfoSync().windowWidth;
this.setData({ this.setData({
cWidth: 320, cWidth: 320,
cHeight: 140 cHeight: 140
......
import { imgUrlMixin } from '~/mixins/index' import { imgUrlMixin } from '~/mixins/index'
import USERAPI from "~/api/usersApi/index"; import USERAPI from "~/api/usersApi/index";
import activityApi from '~/api/activityApi/index'; import activityApi from '~/api/activityApi/index';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({ Component({
behaviors: [imgUrlMixin], behaviors: [imgUrlMixin],
properties: { properties: {
...@@ -38,7 +39,7 @@ Component({ ...@@ -38,7 +39,7 @@ Component({
methods: { methods: {
computeBottom() { computeBottom() {
try { try {
wx.getSystemInfo({ getSystemInfo({
success: (res) => { success: (res) => {
const ratio = res.screenWidth / 750 const ratio = res.screenWidth / 750
const safeInsetBottom = res.safeArea ? (res.screenHeight - res.safeArea.bottom) : 0 const safeInsetBottom = res.safeArea ? (res.screenHeight - res.safeArea.bottom) : 0
......
...@@ -41,7 +41,11 @@ ...@@ -41,7 +41,11 @@
"ignoreDevUnusedFiles": false, "ignoreDevUnusedFiles": false,
"condition": false, "condition": false,
"useApiHook": false, "useApiHook": false,
"useApiHostProcess": false "useApiHostProcess": false,
"compileWorklet": false,
"localPlugins": false,
"swc": false,
"disableSWC": true
}, },
"compileType": "miniprogram", "compileType": "miniprogram",
"simulatorType": "wechat", "simulatorType": "wechat",
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -17,8 +17,9 @@ import { ...@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。 * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同 * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const salesGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const salesGateway: GatewayStrategy = {
router: 'rop-scrm-sales/router', router: 'rop-scrm-sales/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'sales-sha1' }), signer: createSigner({ kind: 'rop', id: 'sales-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
import { import {
equityApi equityApi
} from '~/api/api' } from '~/api/api'
...@@ -48,7 +49,7 @@ export function getNavigationBarTitleText() { ...@@ -48,7 +49,7 @@ export function getNavigationBarTitleText() {
/** 存储设备信息 */ /** 存储设备信息 */
export function setSystem_info(that) { export function setSystem_info(that) {
let info = $Storage.get('system_info') let info = $Storage.get('system_info')
!info && wx.getSystemInfo({ !info && getSystemInfo({
success(res) { success(res) {
// console.log(res) // console.log(res)
$Storage.set('system_info', res) $Storage.set('system_info', res)
......
/** /**
* @file ROP 请求签名;序列化依赖 lib/qs(indices / allowDots / encodeValuesOnly)。 * @file ROP 请求签名;序列化依赖 lib/qs(indices / allowDots / encodeValuesOnly)。
* 签名算法与 store/usedcar/points 同源,收敛到 @uj/api-core 的 createSha1Signer; * 签名算法与 store/usedcar/points 同源,收敛到 @uj/api-core 的 createSigner;
* 签完仍返回摊平后的对象,它同时是 wx.request 的请求体(与原实现逐字节一致)。 * 签完仍返回摊平后的对象,它同时是 wx.request 的请求体(与原实现逐字节一致)。
*/ */
import qs from '../lib/qs' import qs from '../lib/qs'
import { createSha1Signer } from '@uj/api-core' import { createSigner } from '@uj/api-core'
import environment from './environment.js' import environment from './environment.js'
const salesSigner = createSha1Signer({ id: 'sales-sha1' }) const salesSigner = createSigner({ kind: 'rop', id: 'sales-sha1' })
const flatten = params => { const flatten = params => {
const objStr = qs.stringify(params, { const objStr = qs.stringify(params, {
......
/** /**
* sales 请求层:@uj/api-core 的客户端工厂。 * sales 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台(wx)、URL 拼装、签名、 * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台(wx)、URL 拼装、签名、
* 拦截器(业务码归一 / 登录重放 / loading / toast)全在 api-core 里,本文件只传环境参数。 * 拦截器(业务码归一 / 登录重放 / loading / toast)全在 api-core 里,本文件只传环境参数。
* public API 与旧壳逐签名一致:get/post/request(params, returnAll, isShowLoading, hostType)、 * public API 与旧壳逐签名一致:get/post/request(params, returnAll, isShowLoading, hostType)、
* reportTrack(params)、getMock(),453 处调用点零改动。 * reportTrack(params)、getMock(),453 处调用点零改动。
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { sign, domain, djDomain, merchantDomain, pathEnum, secretKey, djSecretKey, index } from './http.js' import { sign, domain, djDomain, merchantDomain, pathEnum, secretKey, djSecretKey, index } from './http.js'
import { login } from '~/utils/appFn/index' import { login } from '~/utils/appFn/index'
const client = createRopClient({ const client = createClient({
kind: 'rop',
hosts: { scrm: domain, dj: djDomain, merchant: merchantDomain }, hosts: { scrm: domain, dj: djDomain, merchant: merchantDomain },
pathEnum, pathEnum,
secretKey, secretKey,
......
/**
* @file 系统信息兼容层:合并微信新 API,替代已废弃的 wx.getSystemInfoSync / wx.getSystemInfo。
* 纯函数模块,不调 setData、不访问页面实例。
* 与 usedcar 的 utils/systemInfo.js 保持一致的实现。
*/
/** 测试专用:重置 legacy environment 缓存 */
export function __resetLegacyEnvironmentCacheForTest() {
legacyEnvironmentResolved = false
legacyEnvironmentCache = LEGACY_ENV_UNSET
}
/** @type {string|undefined|symbol} */
let legacyEnvironmentCache
/** 是否已解析过 legacy environment(含「无需 sync」的结论) */
let legacyEnvironmentResolved = false
const LEGACY_ENV_UNSET = Symbol('legacyEnvironmentUnset')
/**
* 旧版企微判断:优先新 API,仅在必要时调用一次原生 wx.getSystemInfoSync().environment
* @returns {string|undefined}
*/
function getLegacyEnvironment() {
if (legacyEnvironmentResolved) {
return legacyEnvironmentCache === LEGACY_ENV_UNSET ? undefined : legacyEnvironmentCache
}
legacyEnvironmentResolved = true
try {
const appBase = wx.getAppBaseInfo?.()
const host = appBase?.host
const hostEnv = typeof host === 'string' ? host : host?.env
if (hostEnv === 'wxwork') {
legacyEnvironmentCache = 'wxwork'
return legacyEnvironmentCache
}
if (typeof wx.qy !== 'undefined') {
legacyEnvironmentCache = 'wxwork'
return legacyEnvironmentCache
}
const legacyEnv = wx.getSystemInfoSync?.()?.environment
legacyEnvironmentCache = legacyEnv || LEGACY_ENV_UNSET
return legacyEnv
} catch (_) {
legacyEnvironmentCache = LEGACY_ENV_UNSET
return undefined
}
}
/**
* 解析企微运行环境,对齐旧版 getSystemInfoSync().environment
* 优先 legacy / host.env、wx.qy 兜底
* @param {string|{ env?: string }} [host]
* @returns {string}
*/
function resolveEnvironment(host) {
const legacyEnv = getLegacyEnvironment()
if (legacyEnv) return legacyEnv
const hostEnv = typeof host === 'string' ? host : host?.env
if (hostEnv === 'wxwork') return 'wxwork'
if (typeof wx.qy !== 'undefined') return 'wxwork'
return ''
}
/**
* 同步获取与旧版 getSystemInfoSync 兼容的系统信息对象
* @returns {WechatMiniprogram.SystemInfo}
*/
export function getSystemInfoSync() {
const deviceInfo = wx.getDeviceInfo()
const windowInfo = wx.getWindowInfo()
const appBaseInfo = wx.getAppBaseInfo()
return {
...deviceInfo,
...windowInfo,
...appBaseInfo,
environment: resolveEnvironment(appBaseInfo.host),
}
}
/**
* 登录端标识,对齐 loginControlList 后端约定:1 企微,0 微信
* 与旧版 accountItems / wxLogin 一致:优先读原生 wx.getSystemInfoSync().environment
* @returns {0|1}
*/
export function getLoginEnvName() {
const legacyEnv = getLegacyEnvironment()
if (legacyEnv) return 1
return getSystemInfoSync().environment ? 1 : 0
}
/**
* 异步获取系统信息,行为对齐旧版 wx.getSystemInfo
* @param {WechatMiniprogram.GetSystemInfoOption} [options]
*/
export function getSystemInfo(options = {}) {
try {
const res = getSystemInfoSync()
options.success?.(res)
} catch (err) {
options.fail?.(err)
} finally {
options.complete?.()
}
}
...@@ -4,6 +4,7 @@ import { ...@@ -4,6 +4,7 @@ import {
Storage Storage
} from '~/utils/cache/storage' } from '~/utils/cache/storage'
import sopApi from '~/api/sopApi' import sopApi from '~/api/sopApi'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const $Storage = new Storage() const $Storage = new Storage()
/** /**
* 日期格式化 * 日期格式化
...@@ -31,7 +32,7 @@ const isEmptyObj = (obj) => { ...@@ -31,7 +32,7 @@ const isEmptyObj = (obj) => {
}; };
const setNavigationBarTitle = (title) => { const setNavigationBarTitle = (title) => {
wx.getSystemInfo({ getSystemInfo({
success: (res) => { success: (res) => {
// console.log('++++++++++++++', res); // console.log('++++++++++++++', res);
// console.log('title length',title.length) // console.log('title length',title.length)
......
import $router from '../router/index' import $router from '../router/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/** /**
* 微信校验通知类工具封装 * 微信校验通知类工具封装
...@@ -98,7 +99,7 @@ const wxShowToast = (name, params) => { ...@@ -98,7 +99,7 @@ const wxShowToast = (name, params) => {
/**获取设备信息 */ /**获取设备信息 */
const getSystemInfo = callBack => { const getSystemInfo = callBack => {
wx.getSystemInfo({ getSystemInfo({
success(res) { success(res) {
callBack(res) callBack(res)
}, },
...@@ -131,7 +132,7 @@ const isFullSucreen = isComponents => { ...@@ -131,7 +132,7 @@ const isFullSucreen = isComponents => {
let { let {
navigationStyle navigationStyle
} = __wxConfig.page[key].window } = __wxConfig.page[key].window
wx.getSystemInfo({ getSystemInfo({
success(res) { success(res) {
if (res.platform != 'android') { if (res.platform != 'android') {
let { let {
......
...@@ -3,6 +3,7 @@ project.private.config.json ...@@ -3,6 +3,7 @@ project.private.config.json
sitemap.json sitemap.json
miniprogram_npm miniprogram_npm
/miniprogram_npm /miniprogram_npm
/miniprogram_npm.bak
node_modules node_modules
/node_modules /node_modules
# local env files # local env files
......
// components/navigationBar/navigationBar.js // components/navigationBar/navigationBar.js
import { getSystemInfoSync } from '~/utils/systemInfo'
Component({ Component({
/** /**
* 组件的属性列表 * 组件的属性列表
...@@ -34,23 +36,20 @@ Component({ ...@@ -34,23 +36,20 @@ Component({
}, },
init() { init() {
/** /**
* 获取自定义导航栏信息 * 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → getWindowInfo
* fontSizeSetting → getAppBaseInfo
*/ */
wx.getSystemInfo().then(res => { const { fontSizeSetting, statusBarHeight, screenWidth } = getSystemInfoSync()
let {
fontSizeSetting,
statusBarHeight,
screenWidth
} = res
const { const {
height, height,
right, right,
width, width,
top top,
} = wx.getMenuButtonBoundingClientRect(), } = wx.getMenuButtonBoundingClientRect()
currentPages = getCurrentPages(), { const currentPages = getCurrentPages()
showBack const { showBack } = this.data
} = this.data
if (showBack && currentPages.length > 1) this.setData({ if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true SHOWBACK: true
}) })
...@@ -67,7 +66,6 @@ Component({ ...@@ -67,7 +66,6 @@ Component({
navigationBarHeight, navigationBarHeight,
statusBarHeight statusBarHeight
}) })
})
}, },
emit({ emit({
navigationBarHeight, navigationBarHeight,
......
import WxCanvas from './wx-canvas'; import WxCanvas from './wx-canvas';
import * as echarts from './echarts'; import * as echarts from './echarts';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
let ctx; let ctx;
...@@ -78,7 +79,7 @@ Component({ ...@@ -78,7 +79,7 @@ Component({
methods: { methods: {
init: function (callback) { init: function (callback) {
const version = wx.getSystemInfoSync().SDKVersion const version = getSystemInfoSync().SDKVersion
const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0; const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0;
const forceUseOldCanvas = this.data.forceUseOldCanvas; const forceUseOldCanvas = this.data.forceUseOldCanvas;
...@@ -115,7 +116,7 @@ console.log(this.data.isUseNewCanvas) ...@@ -115,7 +116,7 @@ console.log(this.data.isUseNewCanvas)
echarts.setCanvasCreator(() => { echarts.setCanvasCreator(() => {
return canvas; return canvas;
}); });
// const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr // const canvasDpr = getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
const canvasDpr = 1 const canvasDpr = 1
var query = wx.createSelectorQuery().in(this); var query = wx.createSelectorQuery().in(this);
query.select('.ec-canvas').boundingClientRect(res => { query.select('.ec-canvas').boundingClientRect(res => {
...@@ -146,7 +147,7 @@ console.log(this.data.isUseNewCanvas) ...@@ -146,7 +147,7 @@ console.log(this.data.isUseNewCanvas)
const canvasNode = res[0].node const canvasNode = res[0].node
this.canvasNode = canvasNode this.canvasNode = canvasNode
const canvasDpr = wx.getSystemInfoSync().pixelRatio const canvasDpr = getSystemInfoSync().pixelRatio
const canvasWidth = res[0].width const canvasWidth = res[0].width
const canvasHeight = res[0].height const canvasHeight = res[0].height
......
//index.js //index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本! //注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from '../../../../../utils/u-charts/u-charts.js'; import uCharts from '../../../../../utils/u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
var uChartsInstance = {}; var uChartsInstance = {};
Component({ Component({
properties: { properties: {
...@@ -33,10 +34,10 @@ Component({ ...@@ -33,10 +34,10 @@ Component({
isLabel isLabel
} = this.data } = this.data
//这里的第一个 750 对应 css .charts 的 width //这里的第一个 750 对应 css .charts 的 width
const cWidth = (isLabel?700:width) / 750 * wx.getSystemInfoSync().windowWidth; const cWidth = (isLabel?700:width) / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height //这里的 500 对应 css .charts 的 height
const cHeight = width / 750 * wx.getSystemInfoSync().windowWidth; const cHeight = width / 750 * getSystemInfoSync().windowWidth;
const pixelRatio = wx.getSystemInfoSync().pixelRatio; const pixelRatio = getSystemInfoSync().pixelRatio;
this.setData({ this.setData({
cWidth, cWidth,
cHeight, cHeight,
......
//index.js //index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本! //注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from '../../../../../utils/u-charts/u-charts.js'; import uCharts from '../../../../../utils/u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const view = require('../view.js') const view = require('../view.js')
var uChartsInstance = {}; var uChartsInstance = {};
...@@ -16,10 +17,10 @@ Component({ ...@@ -16,10 +17,10 @@ Component({
methods: { methods: {
getRatio() { getRatio() {
//这里的第一个 750 对应 css .charts 的 width //这里的第一个 750 对应 css .charts 的 width
const cWidth = 700 / 750 * wx.getSystemInfoSync().windowWidth; const cWidth = 700 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height //这里的 500 对应 css .charts 的 height
const cHeight = 480 / 750 * wx.getSystemInfoSync().windowWidth; const cHeight = 480 / 750 * getSystemInfoSync().windowWidth;
const pixelRatio = wx.getSystemInfoSync().pixelRatio; const pixelRatio = getSystemInfoSync().pixelRatio;
this.setData({ this.setData({
cWidth, cWidth,
cHeight, cHeight,
......
//index.js //index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本! //注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from '../../../../../utils/u-charts/u-charts.js'; import uCharts from '../../../../../utils/u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const view = require('../view.js') const view = require('../view.js')
var uChartsInstance = {}; var uChartsInstance = {};
Component({ Component({
...@@ -14,9 +15,9 @@ Component({ ...@@ -14,9 +15,9 @@ Component({
methods: { methods: {
getRatio() { getRatio() {
//这里的第一个 750 对应 css .charts 的 width //这里的第一个 750 对应 css .charts 的 width
const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth; const cWidth = 750 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height //这里的 500 对应 css .charts 的 height
const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth; const cHeight = 500 / 750 * getSystemInfoSync().windowWidth;
this.setData({ this.setData({
cWidth, cWidth,
cHeight cHeight
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -17,8 +17,9 @@ import { ...@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。 * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同 * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const storeGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const storeGateway: GatewayStrategy = {
router: 'rop-scrm-store/router', router: 'rop-scrm-store/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'store-sha1' }), signer: createSigner({ kind: 'rop', id: 'store-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
// 实例化对象存储 // 实例化对象存储
import { Storage } from './storage' import { Storage } from './storage'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const $Storage = new Storage() const $Storage = new Storage()
// console.log($Storage) // console.log($Storage)
/** */ /** */
...@@ -54,7 +55,7 @@ export function getNavigationBarTitleText() { ...@@ -54,7 +55,7 @@ export function getNavigationBarTitleText() {
export function setSystem_info(that) { export function setSystem_info(that) {
let info = $Storage.get('system_info') let info = $Storage.get('system_info')
!info && !info &&
wx.getSystemInfo({ getSystemInfo({
success(res) { success(res) {
// console.log(res) // console.log(res)
$Storage.set('system_info', res) $Storage.set('system_info', res)
......
import { preReleaseAppId } from '~/config' import { preReleaseAppId } from '~/config'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const target = ['ip', 'dev', 'uat', 'prod', 'preRelease'] const target = ['ip', 'dev', 'uat', 'prod', 'preRelease']
const mockObj = { const mockObj = {
test: 'https://oss-config.dev.glsx.com.cn/mock/63fd6c2034c4d918e2f4df4d/config', test: 'https://oss-config.dev.glsx.com.cn/mock/63fd6c2034c4d918e2f4df4d/config',
...@@ -15,7 +16,7 @@ const mockObj = { ...@@ -15,7 +16,7 @@ const mockObj = {
// const index = 1 // const index = 1
const accountInfo = wx.getAccountInfoSync() const accountInfo = wx.getAccountInfoSync()
const systemInfo = wx.getSystemInfoSync() const systemInfo = getSystemInfoSync()
// console.log(systemInfo); // console.log(systemInfo);
// console.log(accountInfo.miniProgram.envVersion) // console.log(accountInfo.miniProgram.envVersion)
//手动控制体验版环境的请求 true就依据下面index false就默认为2 //手动控制体验版环境的请求 true就依据下面index false就默认为2
......
import qs from '../lib/qs' import qs from '../lib/qs'
import { createSha1Signer } from '@uj/api-core' import { createSigner } from '@uj/api-core'
import environment from './environment.js' import environment from './environment.js'
// 签名算法统一收口到 @uj/api-core 的 SHA1 预设;本文件只保留 mp 侧的「参数摊平」规则。 // 签名算法统一收口到 @uj/api-core 的 SHA1 预设;本文件只保留 mp 侧的「参数摊平」规则。
// 迁移时用脚本对老 sign() 逐字节验证过:扁平 / 中文与特殊字符 / noSignAttr / 嵌套对象 / // 迁移时用脚本对老 sign() 逐字节验证过:扁平 / 中文与特殊字符 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined-数字-布尔 / dj 后端形状 共 8 类用例全部一致。 // 数组 / 数组套对象 / null-undefined-数字-布尔 / dj 后端形状 共 8 类用例全部一致。
const storeSigner = createSha1Signer({ id: 'store-sha1' }) const storeSigner = createSigner({ kind: 'rop', id: 'store-sha1' })
/** /**
* 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。 * 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
......
/** /**
* store 请求层:@uj/api-core 的客户端工厂。 * store 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责, * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责,
* 本文件只传域名、凭据、会话与登录回调。 * 本文件只传域名、凭据、会话与登录回调。
* public API 与旧壳一致:get/post/request(params, returnAll, requestPath), * public API 与旧壳一致:get/post/request(params, returnAll, requestPath),
* params 含 method,requestPath 对应 hostType(scrm/dj,缺省 scrm)。 * params 含 method,requestPath 对应 hostType(scrm/dj,缺省 scrm)。
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { sign, domain, djSecretKey, pathEnum, secretKey } from './http.js' import { sign, domain, djSecretKey, pathEnum, secretKey } from './http.js'
import { getSessionId } from '~/utils/cache/storageApi' import { getSessionId } from '~/utils/cache/storageApi'
import network from '~/utils/network' import network from '~/utils/network'
const client = createRopClient({ const client = createClient({
kind: 'rop',
hosts: { scrm: domain.scrm, dj: domain.dj, merchant: domain.merchant }, hosts: { scrm: domain.scrm, dj: domain.dj, merchant: domain.merchant },
pathEnum, pathEnum,
secretKey, secretKey,
......
/**
* @file 系统信息兼容层:合并微信新 API,替代已废弃的 wx.getSystemInfoSync / wx.getSystemInfo。
* 纯函数模块,不调 setData、不访问页面实例。
* 与 usedcar 的 utils/systemInfo.js 保持一致的实现。
*/
/** 测试专用:重置 legacy environment 缓存 */
export function __resetLegacyEnvironmentCacheForTest() {
legacyEnvironmentResolved = false
legacyEnvironmentCache = LEGACY_ENV_UNSET
}
/** @type {string|undefined|symbol} */
let legacyEnvironmentCache
/** 是否已解析过 legacy environment(含「无需 sync」的结论) */
let legacyEnvironmentResolved = false
const LEGACY_ENV_UNSET = Symbol('legacyEnvironmentUnset')
/**
* 旧版企微判断:优先新 API,仅在必要时调用一次原生 wx.getSystemInfoSync().environment
* @returns {string|undefined}
*/
function getLegacyEnvironment() {
if (legacyEnvironmentResolved) {
return legacyEnvironmentCache === LEGACY_ENV_UNSET ? undefined : legacyEnvironmentCache
}
legacyEnvironmentResolved = true
try {
const appBase = wx.getAppBaseInfo?.()
const host = appBase?.host
const hostEnv = typeof host === 'string' ? host : host?.env
if (hostEnv === 'wxwork') {
legacyEnvironmentCache = 'wxwork'
return legacyEnvironmentCache
}
if (typeof wx.qy !== 'undefined') {
legacyEnvironmentCache = 'wxwork'
return legacyEnvironmentCache
}
const legacyEnv = wx.getSystemInfoSync?.()?.environment
legacyEnvironmentCache = legacyEnv || LEGACY_ENV_UNSET
return legacyEnv
} catch (_) {
legacyEnvironmentCache = LEGACY_ENV_UNSET
return undefined
}
}
/**
* 解析企微运行环境,对齐旧版 getSystemInfoSync().environment
* 优先 legacy / host.env、wx.qy 兜底
* @param {string|{ env?: string }} [host]
* @returns {string}
*/
function resolveEnvironment(host) {
const legacyEnv = getLegacyEnvironment()
if (legacyEnv) return legacyEnv
const hostEnv = typeof host === 'string' ? host : host?.env
if (hostEnv === 'wxwork') return 'wxwork'
if (typeof wx.qy !== 'undefined') return 'wxwork'
return ''
}
/**
* 同步获取与旧版 getSystemInfoSync 兼容的系统信息对象
* @returns {WechatMiniprogram.SystemInfo}
*/
export function getSystemInfoSync() {
const deviceInfo = wx.getDeviceInfo()
const windowInfo = wx.getWindowInfo()
const appBaseInfo = wx.getAppBaseInfo()
return {
...deviceInfo,
...windowInfo,
...appBaseInfo,
environment: resolveEnvironment(appBaseInfo.host),
}
}
/**
* 登录端标识,对齐 loginControlList 后端约定:1 企微,0 微信
* 与旧版 accountItems / wxLogin 一致:优先读原生 wx.getSystemInfoSync().environment
* @returns {0|1}
*/
export function getLoginEnvName() {
const legacyEnv = getLegacyEnvironment()
if (legacyEnv) return 1
return getSystemInfoSync().environment ? 1 : 0
}
/**
* 异步获取系统信息,行为对齐旧版 wx.getSystemInfo
* @param {WechatMiniprogram.GetSystemInfoOption} [options]
*/
export function getSystemInfo(options = {}) {
try {
const res = getSystemInfoSync()
options.success?.(res)
} catch (err) {
options.fail?.(err)
} finally {
options.complete?.()
}
}
...@@ -7,6 +7,7 @@ import { commonApi, equityApi } from "../api/api"; ...@@ -7,6 +7,7 @@ import { commonApi, equityApi } from "../api/api";
// equityApi // equityApi
// } from '../api/api' // } from '../api/api'
import $router from "../router/index"; import $router from "../router/index";
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/** /**
* 日期格式化 * 日期格式化
...@@ -69,7 +70,7 @@ const isFullSucreen = (isComponents) => { ...@@ -69,7 +70,7 @@ const isFullSucreen = (isComponents) => {
let val = false; let val = false;
if (__wxConfig && __wxConfig.page && __wxConfig.page[key]) { if (__wxConfig && __wxConfig.page && __wxConfig.page[key]) {
let { navigationStyle } = __wxConfig.page[key].window; let { navigationStyle } = __wxConfig.page[key].window;
wx.getSystemInfo({ getSystemInfo({
success(res) { success(res) {
if (res.platform != "android") { if (res.platform != "android") {
let { statusBarHeight, screenHeight, windowHeight } = res; let { statusBarHeight, screenHeight, windowHeight } = res;
...@@ -242,7 +243,7 @@ const deepClone = (target) => { ...@@ -242,7 +243,7 @@ const deepClone = (target) => {
//设置标题 //设置标题
const setNavigationBarTitle = (title) =>{ const setNavigationBarTitle = (title) =>{
wx.getSystemInfo({ getSystemInfo({
success: (res) => { success: (res) => {
// console.log('++++++++++++++', res); // console.log('++++++++++++++', res);
// console.log('title length',title.length) // console.log('title length',title.length)
......
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'
/** /**
* 微信校验通知类工具封装 * 微信校验通知类工具封装
*/ */
...@@ -94,7 +95,7 @@ const wxShowToast = (name, params) => { ...@@ -94,7 +95,7 @@ const wxShowToast = (name, params) => {
/**获取设备信息 */ /**获取设备信息 */
const getSystemInfo = callBack => { const getSystemInfo = callBack => {
wx.getSystemInfo({ getSystemInfo({
success(res) { success(res) {
callBack(res) callBack(res)
}, },
...@@ -179,7 +180,7 @@ const isFullSucreen = isComponents => { ...@@ -179,7 +180,7 @@ const isFullSucreen = isComponents => {
let { let {
navigationStyle navigationStyle
} = __wxConfig.page[key].window } = __wxConfig.page[key].window
wx.getSystemInfo({ getSystemInfo({
success(res) { success(res) {
if (res.platform != 'android') { if (res.platform != 'android') {
let { let {
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -17,8 +17,9 @@ import { ...@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。 * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同 * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const usedcarGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const usedcarGateway: GatewayStrategy = {
router: 'rop-scrm-usedcar/router', router: 'rop-scrm-usedcar/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'usedcar-sha1' }), signer: createSigner({ kind: 'rop', id: 'usedcar-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
...@@ -13,7 +13,7 @@ const require = createRequire(import.meta.url) ...@@ -13,7 +13,7 @@ const require = createRequire(import.meta.url)
const rootDir = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..') const rootDir = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..')
const qs = require(path.join(rootDir, 'utils/lib/qs.js')) const qs = require(path.join(rootDir, 'utils/lib/qs.js'))
const sha1 = require(path.join(rootDir, 'utils/lib/sha1.js')) const sha1 = require(path.join(rootDir, 'utils/lib/sha1.js'))
const { createSha1Signer } = require('@uj/api-core') const { createSigner } = require('@uj/api-core')
/** 与 utils/request/http.js flatten 保持一致:qs 摊平成实际发送体(嵌套 a.b / 数组 a[0]) */ /** 与 utils/request/http.js flatten 保持一致:qs 摊平成实际发送体(嵌套 a.b / 数组 a[0]) */
function flatten(params) { function flatten(params) {
...@@ -54,7 +54,7 @@ function legacySign(params, secret, noSignAttr = []) { ...@@ -54,7 +54,7 @@ function legacySign(params, secret, noSignAttr = []) {
return realObj return realObj
} }
const signer = createSha1Signer({ id: 'usedcar-sha1' }) const signer = createSigner({ kind: 'rop', id: 'usedcar-sha1' })
/** 迁移后的加签路径:与 utils/request/http.js sign 同源 */ /** 迁移后的加签路径:与 utils/request/http.js sign 同源 */
async function sign(params, secret, noSignAttr = []) { async function sign(params, secret, noSignAttr = []) {
......
...@@ -65,8 +65,8 @@ async function loadProjectHttpModule(environment) { ...@@ -65,8 +65,8 @@ async function loadProjectHttpModule(environment) {
// http.js 的摘要已收口到 @uj/api-core;data: URL 模块解析不了裸包名,按同一路子注入。 // http.js 的摘要已收口到 @uj/api-core;data: URL 模块解析不了裸包名,按同一路子注入。
source = replaceRequired( source = replaceRequired(
source, source,
/import\s+\{\s*createSha1Signer\s*\}\s*from\s+['"]@uj\/api-core['"];?/, /import\s+\{\s*createSigner\s*\}\s*from\s+['"]@uj\/api-core['"];?/,
`const { createSha1Signer } = globalThis[${JSON.stringify(contextKey)}].apiCore`, `const { createSigner } = globalThis[${JSON.stringify(contextKey)}].apiCore`,
'api-core signer import' 'api-core signer import'
) )
source = replaceRequired( source = replaceRequired(
......
...@@ -5,13 +5,13 @@ ...@@ -5,13 +5,13 @@
*/ */
import environment from './environment.js' import environment from './environment.js'
import qs from '~/utils/lib/qs' import qs from '~/utils/lib/qs'
import { createSha1Signer } from '@uj/api-core' import { createSigner } from '@uj/api-core'
const path = '/rop-dj-car-boutique/router' const path = '/rop-dj-car-boutique/router'
// 与老 sign 的摘要算法字节级一致(迁移时用脚本验过:扁平 / 中文 / noSignAttr / 嵌套对象 / // 与老 sign 的摘要算法字节级一致(迁移时用脚本验过:扁平 / 中文 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined / merchants 域名形状 全部通过)。 // 数组 / 数组套对象 / null-undefined / merchants 域名形状 全部通过)。
const usedcarSigner = createSha1Signer({ id: 'usedcar-sha1' }) const usedcarSigner = createSigner({ kind: 'rop', id: 'usedcar-sha1' })
/** /**
* 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。 * 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
......
/** /**
* usedcar 请求层:@uj/api-core 的客户端工厂。 * usedcar 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器由 api-core 负责。 * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器由 api-core 负责。
* public API 与旧壳一致:get/post/request(method, data, noSignAttr, requestPath, domainName, failTips)、 * public API 与旧壳一致:get/post/request(method, data, noSignAttr, requestPath, domainName, failTips)、
* getMock()、getApiFoxMock(),46 处调用点零改动。 * getMock()、getApiFoxMock(),46 处调用点零改动。
* *
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
* · 网络失败 / 超时提示改写 → beforeRequest / onTransportError * · 网络失败 / 超时提示改写 → beforeRequest / onTransportError
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { sign, domain, path, secretKey } from './http.js' import { sign, domain, path, secretKey } from './http.js'
import util from '~/utils/util.js' import util from '~/utils/util.js'
import { envIndex } from '~/config' import { envIndex } from '~/config'
...@@ -73,10 +73,15 @@ const ropOptions = { ...@@ -73,10 +73,15 @@ const ropOptions = {
} }
// 常规请求:sessionId 可能正在换取(启动 / 登录后),等闸门放行再发。 // 常规请求:sessionId 可能正在换取(启动 / 登录后),等闸门放行再发。
const client = createRopClient({ ...ropOptions, session: { sessionId: () => util.waitSessionId() } }) const client = createClient({
kind: 'rop',
...ropOptions,
session: { sessionId: () => util.waitSessionId() },
})
// 换取会话本身的接口不能等闸门,否则自己把自己锁死。 // 换取会话本身的接口不能等闸门,否则自己把自己锁死。
const sessionFreeClient = createRopClient({ const sessionFreeClient = createClient({
kind: 'rop',
...ropOptions, ...ropOptions,
session: { sessionId: () => util.getSessionId() || '' }, session: { sessionId: () => util.getSessionId() || '' },
}) })
......
import { bus } from 'wujie';
import { PAGE_LEAVE_EVENT } from '@uj/contracts';
import { Layout, Menu, Avatar, Dropdown, Button, Breadcrumb } from 'antd'; import { Layout, Menu, Avatar, Dropdown, Button, Breadcrumb } from 'antd';
import { Suspense, useEffect, useState } from 'react'; import { Suspense, useEffect, useMemo, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom'; import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { import {
DashboardOutlined, DashboardOutlined,
...@@ -10,12 +12,20 @@ import { ...@@ -10,12 +12,20 @@ import {
TeamOutlined, TeamOutlined,
AuditOutlined, AuditOutlined,
AppstoreOutlined, AppstoreOutlined,
FolderOutlined,
MenuFoldOutlined, MenuFoldOutlined,
MenuUnfoldOutlined, MenuUnfoldOutlined,
GiftOutlined,
FileSyncOutlined,
FundOutlined,
TransactionOutlined,
SolutionOutlined,
HomeOutlined,
SettingOutlined,
} 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';
import { menu as menuApi } from '@/api'; import { menu as menuApi, cancelRequests } from '@/api';
import { logoutEverything } from '../subapp-lifecycle'; import { logoutEverything } from '../subapp-lifecycle';
import { Logo } from '@/components/Logo'; import { Logo } from '@/components/Logo';
import { Skeleton } from '@uj/ui'; import { Skeleton } from '@uj/ui';
...@@ -57,25 +67,37 @@ const iconMap: Record<string, React.ReactNode> = { ...@@ -57,25 +67,37 @@ const iconMap: Record<string, React.ReactNode> = {
TeamOutlined: <TeamOutlined />, TeamOutlined: <TeamOutlined />,
AuditOutlined: <AuditOutlined />, AuditOutlined: <AuditOutlined />,
UserOutlined: <UserOutlined />, UserOutlined: <UserOutlined />,
GiftOutlined: <GiftOutlined />,
FileSyncOutlined: <FileSyncOutlined />,
FundOutlined: <FundOutlined />,
TransactionOutlined: <TransactionOutlined />,
SolutionOutlined: <SolutionOutlined />,
HomeOutlined: <HomeOutlined />,
SettingOutlined: <SettingOutlined />,
}; };
/** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */ /** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */
const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />; const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />;
/** 一级分组既无自身图标、也无子项可借时的兜底图标:折叠成图标栏时也有可点的入口 */
const GROUP_DEFAULT_ICON: React.ReactNode = <FolderOutlined />;
// 后端下发的 icon 是「antd 图标名字符串」,这里查表换成 React 节点。 // 后端下发的 icon 是「antd 图标名字符串」,这里查表换成 React 节点。
// 未登记的图标名会静默回落默认图标 —— 这正是之前「菜单全是同一个图标」排查起来很痛苦的原因, // 未登记的图标名会静默回落兜底图标 —— 这正是之前「菜单全是同一个图标」排查起来很痛苦的原因,
// 故开发环境对未知图标名告警一次(同名只报一次,避免菜单每项刷屏)。 // 故开发环境对未知图标名告警一次(同名只报一次,避免菜单每项刷屏)。
const warnedIcons = new Set<string>(); const warnedIcons = new Set<string>();
function resolveIcon(name: string | null | undefined): React.ReactNode { function resolveIcon(
name: string | null | undefined,
fallback: React.ReactNode = DEFAULT_MENU_ICON,
): React.ReactNode {
const hit = name ? iconMap[name] : undefined; const hit = name ? iconMap[name] : undefined;
if (hit) return hit; if (hit) return hit;
if (name && import.meta.env.DEV && !warnedIcons.has(name)) { if (name && import.meta.env.DEV && !warnedIcons.has(name)) {
warnedIcons.add(name); warnedIcons.add(name);
console.warn( console.warn(
`[menu] 图标「${name}」未在 src/layouts/BasicLayout.tsx 的 iconMap 中登记,已回落默认图标。` + `[menu] 图标「${name}」未在 src/layouts/BasicLayout.tsx 的 iconMap 中登记,已回落兜底图标。` +
`请在 iconMap 补一行,或让后端改发已支持的值。`, `请在 iconMap 补一行,或让后端改发已支持的值。`,
); );
} }
return DEFAULT_MENU_ICON; return fallback;
} }
// 兜底菜单:接口失败/尚未返回时使用(与 src/config/menu.json 对应) // 兜底菜单:接口失败/尚未返回时使用(与 src/config/menu.json 对应)
...@@ -98,6 +120,11 @@ fallbackGroups.forEach((g) => ...@@ -98,6 +120,11 @@ fallbackGroups.forEach((g) =>
}), }),
); );
/** 一级分组的 SubMenu key 前缀:与页面 path 区分,onClick 据此挡掉非路由 key。
* 分组名需保持唯一(后端菜单树的既有约束)——同名分组本就是配置错误,不让前端悄悄掩盖。 */
const GROUP_KEY_PREFIX = 'group:';
const groupKey = (group: string) => `${GROUP_KEY_PREFIX}${group}`;
export default function BasicLayout() { export default function BasicLayout() {
const navigate = useNavigate(); const navigate = useNavigate();
const location = useLocation(); const location = useLocation();
...@@ -123,14 +150,18 @@ export default function BasicLayout() { ...@@ -123,14 +150,18 @@ export default function BasicLayout() {
}; };
}, [loggedIn, points]); }, [loggedIn, points]);
// 后端树为空(接口未就绪或该账号无任何菜单)时走兜底,避免侧边栏整组消失 // 后端树为空(接口未就绪或该账号无任何菜单)时走兜底,避免侧边栏整组消失。
const groups: MenuGroupDef[] = remoteGroups?.length // useMemo 固定引用:下面的 openKeys 校准 effect 依赖 groups,若每次渲染都生成新数组会导致 effect 反复执行。
? [...FRONTEND_ONLY_GROUPS, ...remoteGroups] const groups: MenuGroupDef[] = useMemo(
: fallbackGroups; () => (remoteGroups?.length ? [...FRONTEND_ONLY_GROUPS, ...remoteGroups] : fallbackGroups),
[remoteGroups],
);
// -> antd Menu items(后端树已在 buildMenus 内与 permCodes 取过交集;兜底菜单按权限过滤) // -> antd Menu items(后端树已在 buildMenus 内与 permCodes 取过交集;兜底菜单按权限过滤)
// hideTitle 的分组不生成 type:'group',改由 children 平铺到当前层级—— // 普通分组渲染成【可折叠的 SubMenu】:点一级标题即可收起/展开其下的二级菜单项,
// 这样是真没有标题节点,而不是用 CSS 把标题藏起来(藏起来会留下一行空白占位)。 // 取代原先 type:'group' 标题组(inline 模式下永远展开、点不动)。菜单变多后靠折叠控制侧边栏长度。
// hideTitle 分组仍是平铺到顶层的普通菜单项(如「工作台」单入口),保持一点即达。
// SubMenu key 统一加 'group:' 前缀,与页面 path 区分开,避免 key 撞车。
const items: MenuItemType[] = groups.flatMap<MenuItemType>((g) => { const items: MenuItemType[] = groups.flatMap<MenuItemType>((g) => {
const children = g.children const children = g.children
.filter((m) => !m.resource || can(m.resource)) .filter((m) => !m.resource || can(m.resource))
...@@ -139,7 +170,18 @@ export default function BasicLayout() { ...@@ -139,7 +170,18 @@ export default function BasicLayout() {
icon: resolveIcon(m.icon), icon: resolveIcon(m.icon),
label: m.label, label: m.label,
})); }));
return g.hideTitle ? children : [{ type: 'group' as const, label: g.group, children }]; if (!children.length) return []; // 权限过滤后的空组不渲染,避免出现点不开的空 SubMenu
if (g.hideTitle) return children;
return [
{
key: groupKey(g.group),
// 一级图标取后端产品分组节点自己的 icon;没登记才借首个子项,
// 再没有才落 FolderOutlined——借子项会让一级图标跟着二级的 sort 变,所以只当兜底。
icon: resolveIcon(g.icon, children[0]?.icon ?? GROUP_DEFAULT_ICON),
label: g.group,
children,
},
];
}); });
const flat = groups.flatMap((g) => g.children); const flat = groups.flatMap((g) => g.children);
...@@ -158,6 +200,33 @@ export default function BasicLayout() { ...@@ -158,6 +200,33 @@ export default function BasicLayout() {
const current = flat.find((m) => m.path === selectedKey); const current = flat.find((m) => m.path === selectedKey);
const currentGroup = groups.find((g) => g.children.some((m) => m.path === selectedKey)); const currentGroup = groups.find((g) => g.children.some((m) => m.path === selectedKey));
// 当前页所属的可折叠分组:默认展开这一组,让用户一进来就能看到自己所在的位置。
// hideTitle 组(工作台)是平铺的普通项,没有 SubMenu,返回 null 不参与展开。
const activeGroupKey =
currentGroup && !currentGroup.hideTitle ? groupKey(currentGroup.group) : null;
// 一级菜单展开状态(受控):
// - 惰性初始化为首帧就只展开当前分组、其余收起,既避免「先全收起再弹开」的闪烁,
// 也是「菜单多了」之后控制侧边栏长度的关键。
// - 用户点一级标题只增删自己那一组(onOpenChange 全量回写),不做手风琴式强制收起;
// effect 依赖刻意不含 openKeys,否则收起当前分组后会被立刻弹回、永远关不上。
// - 路由 / 菜单数据 / Sider 折叠态变化时清掉失效分组 key、补上当前分组,保证选中项始终可见。
// collapsed 必加:@rc-component/menu 进入 inlineCollapsed 会触发 onOpenChange([]),
// 受控 openKeys 下它恢复展开时写不回缓存(Menu.js 的 setMergedOpenKeys 对受控无效),
// 不重新校准会让「收起侧栏再展开」把所有分组连同当前位置一起收起。
// - 内容未变返回原引用避免多余渲染;依赖都是稳定值(groups 已 useMemo)。
const [openKeys, setOpenKeys] = useState<string[]>(() =>
activeGroupKey ? [activeGroupKey] : [],
);
useEffect(() => {
const valid = new Set(groups.filter((g) => !g.hideTitle).map((g) => groupKey(g.group)));
setOpenKeys((prev) => {
const next = prev.filter((k) => valid.has(k));
if (activeGroupKey && !next.includes(activeGroupKey)) next.push(activeGroupKey);
return next.length === prev.length && next.every((k, i) => k === prev[i]) ? prev : next;
});
}, [groups, activeGroupKey, collapsed]);
// 面包屑:分组 > 当前页;分组名与页题同名(如「工作台」)时只留一级,避免重复。 // 面包屑:分组 > 当前页;分组名与页题同名(如「工作台」)时只留一级,避免重复。
// 非菜单页(/profile)无分组,只显示 EXTRA_TITLES 登记的页题。 // 非菜单页(/profile)无分组,只显示 EXTRA_TITLES 登记的页题。
const crumbTitles = [ const crumbTitles = [
...@@ -186,7 +255,7 @@ export default function BasicLayout() { ...@@ -186,7 +255,7 @@ export default function BasicLayout() {
<Sider <Sider
collapsed={collapsed} collapsed={collapsed}
trigger={null} trigger={null}
width={232} width={216}
collapsedWidth={68} collapsedWidth={68}
className="uj-sider" className="uj-sider"
> >
...@@ -208,8 +277,19 @@ export default function BasicLayout() { ...@@ -208,8 +277,19 @@ export default function BasicLayout() {
mode="inline" mode="inline"
className="uj-menu" className="uj-menu"
selectedKeys={selectedKey ? [selectedKey] : []} selectedKeys={selectedKey ? [selectedKey] : []}
openKeys={openKeys}
onOpenChange={(keys) => setOpenKeys(keys.map(String))}
items={items} items={items}
onClick={({ key }) => navigate(key)} onClick={({ key }) => {
// 一级标题点击走 onOpenChange、不产生 onClick;这里仍按「分组 key 不导航」兜底,
// 防止分组 key 被误当作路由跳进 404。
if (key.startsWith(GROUP_KEY_PREFIX)) return;
// 切菜单先中断上一页的在途请求:alive 保活的子应用不会卸载,旧响应回来会写脏 state。
// 广播给所有保活子应用(各自 cancelRequests),主壳自己的在途请求在这里一并取消。
bus.$emit(PAGE_LEAVE_EVENT);
cancelRequests();
navigate(key);
}}
/> />
</div> </div>
</Sider> </Sider>
...@@ -303,7 +383,7 @@ export default function BasicLayout() { ...@@ -303,7 +383,7 @@ export default function BasicLayout() {
minHeight: 0, minHeight: 0,
overflow: 'auto', overflow: 'auto',
background: 'var(--uj-bg)', background: 'var(--uj-bg)',
padding: 24, padding: 12,
display: 'flex', display: 'flex',
flexDirection: 'column', flexDirection: 'column',
}} }}
......
...@@ -25,7 +25,7 @@ export function Donut() { ...@@ -25,7 +25,7 @@ export function Donut() {
return el; return el;
}); });
return ( return (
<div style={{ display: 'flex', alignItems: 'center', gap: 20 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
<svg width={132} height={132} viewBox="0 0 132 132"> <svg width={132} height={132} viewBox="0 0 132 132">
<circle cx={66} cy={66} r={r} fill="none" stroke="#F0F2F7" strokeWidth="14" /> <circle cx={66} cy={66} r={r} fill="none" stroke="#F0F2F7" strokeWidth="14" />
{circles} {circles}
......
...@@ -52,6 +52,7 @@ export function LoginForm() { ...@@ -52,6 +52,7 @@ export function LoginForm() {
dataScope: res.dataScope, dataScope: res.dataScope,
roleCodes: res.roleCodes ?? [], roleCodes: res.roleCodes ?? [],
permCodes: res.permCodes ?? [], permCodes: res.permCodes ?? [],
loginToken: res.loginToken,
}); });
// 菜单树与用户信息都按角色/账号下发:登录即视为账号切换点,旧缓存必须作废 // 菜单树与用户信息都按角色/账号下发:登录即视为账号切换点,旧缓存必须作废
menuApi.clearCache(); menuApi.clearCache();
......
...@@ -30,10 +30,11 @@ ...@@ -30,10 +30,11 @@
background: linear-gradient(160deg, #0b1437 0%, #16245a 100%); background: linear-gradient(160deg, #0b1437 0%, #16245a 100%);
} }
/* Sider 菜单:胶囊态选中 + 隐藏默认右侧指示条 */ /* Sider 菜单:胶囊态选中 + 隐藏默认右侧指示条。
圆角/高度全部由 themeConfig 的 Menu token 下发(itemBorderRadius: 6 / itemHeight: 40),
这里不再写死几何量,避免和 token 打架。 */
.uj-sider .ant-menu-inline .ant-menu-item { .uj-sider .ant-menu-inline .ant-menu-item {
border-radius: 8px; margin-top: 2px;
margin-top: 4px;
} }
.uj-sider .ant-menu-inline .ant-menu-item-selected::after { .uj-sider .ant-menu-inline .ant-menu-item-selected::after {
display: none; display: none;
...@@ -97,7 +98,7 @@ ...@@ -97,7 +98,7 @@
.uj-login-brand { .uj-login-brand {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: var(--uj-space-module, 10px);
font-size: 16px; font-size: 16px;
font-weight: 600; font-weight: 600;
letter-spacing: 2px; letter-spacing: 2px;
...@@ -294,7 +295,7 @@ ...@@ -294,7 +295,7 @@
padding: 0; padding: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 16px; gap: 12px;
max-width: 210px; max-width: 210px;
} }
.uj-login-feats li { .uj-login-feats li {
...@@ -374,10 +375,10 @@ ...@@ -374,10 +375,10 @@
width: 440px; width: 440px;
max-width: 100%; max-width: 100%;
background: #fff; background: #fff;
border-radius: 18px; border-radius: var(--uj-radius-lg, 8px);
padding: 48px 44px; padding: 44px 40px;
box-shadow: var(--uj-shadow-pop); box-shadow: var(--uj-shadow-pop);
border: 1px solid #eef1f6; border: 1px solid var(--uj-border, #e6ebf2);
} }
/* 浏览器「记住密码」自动填充后,输入框出现默认淡色背景(淡蓝/淡黄),与白色卡片不搭。 /* 浏览器「记住密码」自动填充后,输入框出现默认淡色背景(淡蓝/淡黄),与白色卡片不搭。
autofill 的淡色必须用 inset 阴影盖——普通 background 改不掉它。 autofill 的淡色必须用 inset 阴影盖——普通 background 改不掉它。
...@@ -410,34 +411,35 @@ ...@@ -410,34 +411,35 @@
position: relative; position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
/* 垂直、低饱和、matte 深蓝:比原 160° 对角渐变更稳重、更有层次但不「动」。 */ /* 垂直 matte 深蓝,色值全部取品牌深色系(#0B1437 同族):
background: linear-gradient(180deg, #0e1736 0%, #111b3d 55%, #0e1631 100%); 顶部与登录页左栏 (#0B1437) 同一色,中段 #14204E 同时是折叠弹出层 (darkPopupBg) 的底色,
box-shadow: 4px 0 24px -12px rgba(6, 12, 38, 0.55); 保证「主题深色 = 菜单深色 = 弹层深色」三者同源,不再各写一套蓝。 */
background: linear-gradient(180deg, #0b1437 0%, #14204e 55%, #0a1230 100%);
box-shadow: 4px 0 20px -14px rgba(6, 12, 38, 0.5);
/* 侧边菜单不再有 CSS 旋钮:高度 / 左右留白 / 圆角 / 图标尺寸 / 折叠宽度 /* 侧边菜单不再有 CSS 旋钮:高度 / 左右留白 / 圆角 / 图标尺寸 / 折叠宽度
全部写在 themeConfig.ts 的 components.Menu token 里,由组件自身参与计算。 */ 全部写在 themeConfig.ts 的 components.Menu token 里,由组件自身参与计算。 */
} }
/* 左侧菜单栏「地脚线 / 地面」:与登录页时钟底部同源一面墙、同一片地面的视觉延伸, /* 左侧菜单栏「地脚线 / 地面」:与登录页时钟底部同一套墙地语言,但整体收细 ——
让登录页与内部系统形成关联。2px 受光交界亮线 + 墙根投影带(AO) + 向前(下)渐沉的 12px 高(原 20px),交界亮线 1px(原 2px),AO 带压缩到 1–8px,光晕减弱。
地面主调 + 地面反光光晕,与 .uj-login-foot::before 同一套语言; 保留呼应、去掉抢眼的粗线条。 */
height:20px 与登录页地面等高,强化「同一片地面」的呼应。 */
.uj-sider::after { .uj-sider::after {
content: ''; content: '';
position: absolute; position: absolute;
left: 0; left: 0;
right: 0; right: 0;
bottom: 0; bottom: 0;
height: 20px; height: 12px;
z-index: 1; z-index: 1;
pointer-events: none; pointer-events: none;
background: background:
/* 1. 墙地交界受光亮线 */ /* 1. 墙地交界受光亮线:1px,弱化到不抢 */
linear-gradient(180deg, rgba(198, 220, 255, 0.5) 0 2px, transparent 2px), linear-gradient(180deg, rgba(198, 220, 255, 0.34) 0 1px, transparent 1px),
/* 2. 墙根投影(AO):2–13px 渐虚,模拟墙在地面落影 */ /* 2. 墙根投影(AO):1–8px 渐虚,比原版收窄一半 */
linear-gradient(180deg, transparent 2px, rgba(2, 6, 18, 0.62) 7px, rgba(2, 6, 18, 0) 13px), linear-gradient(180deg, transparent 1px, rgba(2, 6, 18, 0.5) 4px, rgba(2, 6, 18, 0) 8px),
/* 3. 地面主调:近墙受光略亮、向前(下)渐沉 */ /* 3. 地面主调:近墙受光略亮、向前(下)渐沉 */
linear-gradient(180deg, rgba(26, 40, 82, 0.94) 0%, rgba(6, 10, 28, 0.98) 100%), linear-gradient(180deg, rgba(26, 40, 82, 0.92) 0%, rgba(6, 10, 28, 0.97) 100%),
/* 4. 地面反光光晕(延续登录页氛围,居中受光) */ /* 4. 地面反光光晕:减弱,只留一点呼吸 */
radial-gradient(82% 240% at 50% 0%, rgba(120, 160, 255, 0.18), rgba(120, 160, 255, 0) 65%); radial-gradient(82% 240% at 50% 0%, rgba(120, 160, 255, 0.12), rgba(120, 160, 255, 0) 60%);
} }
.uj-sider > .ant-layout-sider-children { .uj-sider > .ant-layout-sider-children {
display: flex; display: flex;
...@@ -447,11 +449,11 @@ ...@@ -447,11 +449,11 @@
/* 品牌区 */ /* 品牌区 */
.uj-sider-brand { .uj-sider-brand {
height: 64px; height: 56px;
flex: none; flex: none;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 12px; gap: var(--uj-space-module, 10px);
padding: 0 18px; padding: 0 18px;
border-bottom: 1px solid rgba(255, 255, 255, 0.07); border-bottom: 1px solid rgba(255, 255, 255, 0.07);
} }
...@@ -488,7 +490,7 @@ ...@@ -488,7 +490,7 @@
min-height: 0; min-height: 0;
overflow-y: auto; overflow-y: auto;
/* 底部预留地脚线(地面)高度,避免菜单最后一项被 .uj-sider::after 的地面带遮挡 */ /* 底部预留地脚线(地面)高度,避免菜单最后一项被 .uj-sider::after 的地面带遮挡 */
padding-block: 12px 24px; padding-block: 10px 16px;
padding-inline: 0; padding-inline: 0;
scrollbar-gutter: stable both-edges; scrollbar-gutter: stable both-edges;
scrollbar-width: none; scrollbar-width: none;
...@@ -507,36 +509,36 @@ ...@@ -507,36 +509,36 @@
.uj-menu.ant-menu-dark { .uj-menu.ant-menu-dark {
background: transparent; background: transparent;
} }
/* 分组标题:只有字重/字距/大小写没有对应 token,故保留这三项; /* 一级菜单(SubMenu)标题:沿用原先分组标题的字重/字距/大小写;
字号与颜色已移到 themeConfig 的 groupTitleFontSize / darkGroupTitleColor。 字号与颜色仍由 themeConfig 的 token 下发。间距一律不写——antd 自身会让标题与菜单项对齐,
间距一律不写——antd 自身会让标题与菜单项对齐,手动设 padding 反而容易错位。 */ 手动设 padding 反而容易错位(折叠态图标居中尤其敏感)。 */
.uj-menu.ant-menu-dark .ant-menu-item-group-title { .uj-menu.ant-menu-dark .ant-menu-submenu-title {
font-weight: 600; font-weight: 600;
letter-spacing: 2px; letter-spacing: 2px;
text-transform: uppercase; text-transform: uppercase;
} }
/* 选中态左侧指示条:用 inset 阴影画,不占盒模型空间, /* 选中态左侧指示条:用 inset 阴影画,不占盒模型空间,
因此不会改变组件的宽高,也不会干扰折叠态的居中计算。 */ 因此不会改变组件的宽高,也不会干扰折叠态的居中计算。
颜色取 --uj-brand-light(品牌亮色档),与登录页点缀、选中底 (primary 的 alpha) 同族。 */
.uj-menu.ant-menu-dark .ant-menu-item-selected { .uj-menu.ant-menu-dark .ant-menu-item-selected {
box-shadow: inset 3px 0 0 0 #5b8def; box-shadow: inset 3px 0 0 0 var(--uj-brand-light, #5b8def);
}
/* 收起态隐藏分组标题 —— 这是本区块唯一一处非颜色覆盖:
antd 折叠时并不隐藏分组标题,只做 text-overflow 省略(会留下比如「门…」这样的小字),
企业后台通常选择直接隐藏。若你想要组件原生行为,删掉这三条即可。 */
.uj-menu.ant-menu-inline-collapsed .ant-menu-item-group-title {
display: none;
} }
/* 折叠态(Sider 收起成图标栏)不再隐藏标题:
antd 自身会把 SubMenu 标题文字收起、只留图标,hover 弹出子菜单浮层。
若照旧对标题容器 display:none,会把折叠态下唯一的图标入口一起干掉,菜单就点不动了。
折叠态的展开/收起由 antd 浮层接管,openKeys 只作用于展开态。 */
/* ============ 应用骨架:Header ============ */ /* ============ 应用骨架:Header ============ */
/* 实底白 + 1px 实线:去掉毛玻璃(半透明 + blur 是「柔」的主要来源之一),
企业后台的头部要「压得住」页面,而不是飘在内容上。 */
.uj-header { .uj-header {
height: 64px; height: 56px;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 16px; gap: 12px;
padding-inline: 20px !important; padding-inline: 20px !important;
background: rgba(255, 255, 255, 0.86) !important; background: #fff !important;
backdrop-filter: blur(8px); border-bottom: 1px solid var(--uj-border, #e6ebf2);
border-bottom: 1px solid #eef1f6;
} }
.uj-header-left { .uj-header-left {
display: flex; display: flex;
...@@ -567,7 +569,7 @@ ...@@ -567,7 +569,7 @@
color: #1d2533; color: #1d2533;
} }
/* 全局搜索:胶囊态,聚焦浮现品牌色描边 */ /* 全局搜索:矩形输入框 + 实描边,与控件体系同一套圆角(不再用 999px 胶囊) */
.uj-header-search { .uj-header-search {
position: relative; position: relative;
flex: 1; flex: 1;
...@@ -575,13 +577,13 @@ ...@@ -575,13 +577,13 @@
margin-inline: auto; margin-inline: auto;
} }
.uj-header-search .ant-input-affix-wrapper { .uj-header-search .ant-input-affix-wrapper {
height: 38px; height: 34px;
background: #f2f4f9; background: #fff;
border-radius: 999px; border-radius: var(--uj-radius-md, 6px);
padding: 0 14px; padding: 0 12px;
display: flex; display: flex;
align-items: center; align-items: center;
transition: all 0.25s ease; transition: all 0.2s ease;
} }
.uj-header-search .ant-input-affix-wrapper .ant-input { .uj-header-search .ant-input-affix-wrapper .ant-input {
height: auto; height: auto;
...@@ -601,7 +603,7 @@ ...@@ -601,7 +603,7 @@
color: #8a94a6; color: #8a94a6;
background: #fff; background: #fff;
border: 1px solid #e2e7ef; border: 1px solid #e2e7ef;
border-radius: 6px; border-radius: var(--uj-radius-sm, 4px);
padding: 3px 7px; padding: 3px 7px;
pointer-events: none; pointer-events: none;
} }
...@@ -619,7 +621,7 @@ ...@@ -619,7 +621,7 @@
height: 34px; height: 34px;
padding: 0; padding: 0;
border: none; border: none;
border-radius: 10px; border-radius: var(--uj-radius-md, 6px);
background: transparent !important; background: transparent !important;
color: #4a5568; color: #4a5568;
font-size: 16px; font-size: 16px;
...@@ -645,7 +647,7 @@ ...@@ -645,7 +647,7 @@
background: transparent; background: transparent;
cursor: pointer; cursor: pointer;
padding: 4px 8px 4px 4px; padding: 4px 8px 4px 4px;
border-radius: 999px; border-radius: var(--uj-radius-md, 6px);
transition: background 0.2s ease; transition: background 0.2s ease;
} }
.uj-header-user:hover { .uj-header-user:hover {
...@@ -671,36 +673,24 @@ ...@@ -671,36 +673,24 @@
.uj-dash { .uj-dash {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 18px; gap: var(--uj-space-module, 10px);
} }
/* 品牌欢迎条:浅色卡片 + 品牌色点睛。 /* 品牌欢迎条:白卡 + 1px 实描边 + 干脆短影。
旧版用 brandGradient(#0B1437→#16245A) 整条铺底,明度过低显得压抑; 旧版的浅蓝渐变底 + 右上角柔光圆斑是「柔、肉」的主要来源,全部去掉;
现改为高明度底色,品牌感交给「小面积渐变方块 + 右上角柔光」承载。 */ 品牌感交给「小面积渐变方块」一个点睛位承载。 */
.uj-dash-hero { .uj-dash-hero {
position: relative; position: relative;
overflow: hidden; overflow: hidden;
border-radius: 16px; border-radius: var(--uj-radius-card, 10px);
padding: 26px 30px; padding: 14px 16px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 20px; gap: 12px;
background: linear-gradient(120deg, #ffffff 0%, #f5f7ff 100%); background: #fff;
border: 1px solid rgba(43, 92, 230, 0.1); border: 1px solid var(--uj-border, #e6ebf2);
box-shadow: 0 2px 10px rgba(16, 24, 64, 0.04); box-shadow: var(--uj-shadow-card);
}
/* 右上角品牌柔光:给浅底加层次,不占大面积 */
.uj-dash-hero::after {
content: '';
position: absolute;
right: -60px;
top: -80px;
width: 260px;
height: 260px;
border-radius: 50%;
background: radial-gradient(circle, rgba(43, 92, 230, 0.1) 0%, rgba(43, 92, 230, 0) 70%);
pointer-events: none;
} }
.uj-dash-hero-id { .uj-dash-hero-id {
position: relative; position: relative;
...@@ -719,17 +709,17 @@ ...@@ -719,17 +709,17 @@
.uj-dash-hero-mark { .uj-dash-hero-mark {
width: 16px; width: 16px;
height: 16px; height: 16px;
border-radius: 5px; border-radius: var(--uj-radius-sm, 4px);
flex: none; flex: none;
background: linear-gradient(135deg, #2b5ce6, #5b8def); background: linear-gradient(135deg, #2b5ce6, #5b8def);
box-shadow: 0 4px 10px rgba(43, 92, 230, 0.3); box-shadow: 0 2px 6px rgba(43, 92, 230, 0.3);
} }
.uj-dash-hero-title { .uj-dash-hero-title {
font-size: 24px; font-size: 20px;
font-weight: 700; font-weight: 700;
color: #1d2533; color: #1d2533;
line-height: 1.25; line-height: 1.25;
margin: 12px 0 6px; margin: 10px 0 4px;
} }
.uj-dash-hero-sub { .uj-dash-hero-sub {
font-size: 13px; font-size: 13px;
...@@ -748,8 +738,8 @@ ...@@ -748,8 +738,8 @@
flex-direction: column; flex-direction: column;
gap: 3px; gap: 3px;
min-width: 132px; min-width: 132px;
padding: 10px 14px; padding: 8px 12px;
border-radius: 10px; border-radius: var(--uj-radius-md, 6px);
background: rgba(43, 92, 230, 0.05); background: rgba(43, 92, 230, 0.05);
border: 1px solid rgba(43, 92, 230, 0.08); border: 1px solid rgba(43, 92, 230, 0.08);
} }
...@@ -768,27 +758,28 @@ ...@@ -768,27 +758,28 @@
.uj-dash-kpis { .uj-dash-kpis {
display: grid; display: grid;
grid-template-columns: repeat(4, 1fr); grid-template-columns: repeat(4, 1fr);
gap: 16px; gap: var(--uj-space-module, 10px);
} }
.uj-kpi { .uj-kpi {
position: relative; position: relative;
overflow: hidden; overflow: hidden;
border-radius: 14px; border-radius: var(--uj-radius-card, 10px);
transition: transition:
transform 0.2s ease, transform 0.2s ease,
box-shadow 0.2s ease; box-shadow 0.2s ease;
} }
.uj-kpi:hover { .uj-kpi:hover {
transform: translateY(-3px); /* 只抬 1px:hover 反馈保留,但不再「飘」 */
box-shadow: 0 16px 30px -18px rgba(16, 24, 40, 0.28); transform: translateY(-1px);
box-shadow: var(--uj-shadow-raise);
} }
.uj-kpi-bar { .uj-kpi-bar {
position: absolute; position: absolute;
left: 0; left: 0;
top: 0; top: 0;
bottom: 0; bottom: 0;
width: 4px; width: 3px;
border-radius: 4px 0 0 4px; border-radius: 3px 0 0 3px;
} }
.uj-kpi-head { .uj-kpi-head {
display: flex; display: flex;
...@@ -796,28 +787,28 @@ ...@@ -796,28 +787,28 @@
justify-content: space-between; justify-content: space-between;
} }
.uj-kpi-icon { .uj-kpi-icon {
width: 40px; width: 36px;
height: 40px; height: 36px;
border-radius: 11px; border-radius: var(--uj-radius-md, 6px);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-size: 19px; font-size: 18px;
} }
.uj-kpi-label { .uj-kpi-label {
margin-top: 14px; margin-top: 10px;
font-size: 13px; font-size: 13px;
color: #8a94a6; color: #8a94a6;
} }
.uj-kpi-value { .uj-kpi-value {
font-size: 30px; font-size: 26px;
font-weight: 700; font-weight: 700;
color: #1d2533; color: #1d2533;
line-height: 1.2; line-height: 1.2;
margin-top: 2px; margin-top: 2px;
} }
.uj-kpi-delta { .uj-kpi-delta {
margin-top: 8px; margin-top: 6px;
font-size: 12px; font-size: 12px;
font-weight: 600; font-weight: 600;
display: flex; display: flex;
...@@ -828,35 +819,35 @@ ...@@ -828,35 +819,35 @@
.uj-dash-main { .uj-dash-main {
display: grid; display: grid;
grid-template-columns: 2fr 1fr; grid-template-columns: 2fr 1fr;
gap: 16px; gap: var(--uj-space-module, 10px);
align-items: stretch; align-items: stretch;
} }
.uj-dash-trend { .uj-dash-trend {
border-radius: 14px; border-radius: var(--uj-radius-card, 10px);
} }
.uj-dash-side { .uj-dash-side {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 16px; gap: var(--uj-space-module, 10px);
} }
.uj-dash-side .ant-card { .uj-dash-side .ant-card {
border-radius: 14px; border-radius: var(--uj-radius-card, 10px);
} }
/* 底部快捷 */ /* 底部快捷 */
.uj-dash-foot { .uj-dash-foot {
display: grid; display: grid;
grid-template-columns: repeat(4, 1fr); grid-template-columns: repeat(4, 1fr);
gap: 16px; gap: var(--uj-space-module, 10px);
} }
.uj-dash-foot-item { .uj-dash-foot-item {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
background: #fff; background: #fff;
border: 1px solid #eef1f6; border: 1px solid var(--uj-border, #e6ebf2);
border-radius: 12px; border-radius: var(--uj-radius-card, 10px);
padding: 16px 18px; padding: 12px 14px;
font-size: 14px; font-size: 14px;
color: #1d2533; color: #1d2533;
cursor: pointer; cursor: pointer;
...@@ -864,7 +855,7 @@ ...@@ -864,7 +855,7 @@
} }
.uj-dash-foot-item:hover { .uj-dash-foot-item:hover {
border-color: rgba(43, 92, 230, 0.4); border-color: rgba(43, 92, 230, 0.4);
box-shadow: 0 10px 22px -16px rgba(43, 92, 230, 0.6); box-shadow: 0 4px 12px -8px rgba(43, 92, 230, 0.5);
} }
/* ============ 工作台 · 欢迎页 ============ */ /* ============ 工作台 · 欢迎页 ============ */
...@@ -872,34 +863,34 @@ ...@@ -872,34 +863,34 @@
font-size: 14px; font-size: 14px;
font-weight: 600; font-weight: 600;
color: #1d2533; color: #1d2533;
margin-bottom: 12px; margin-bottom: 10px;
} }
.uj-welcome-quick { .uj-welcome-quick {
display: grid; display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 16px; gap: var(--uj-space-module, 10px);
} }
.uj-quick-card { .uj-quick-card {
border-radius: 14px; border-radius: var(--uj-radius-card, 10px);
transition: transition:
transform 0.2s ease, transform 0.2s ease,
box-shadow 0.2s ease; box-shadow 0.2s ease;
} }
.uj-quick-card:hover { .uj-quick-card:hover {
transform: translateY(-3px); transform: translateY(-1px);
box-shadow: 0 16px 30px -18px rgba(16, 24, 40, 0.28); box-shadow: var(--uj-shadow-raise);
} }
.uj-quick-icon { .uj-quick-icon {
width: 38px; width: 34px;
height: 38px; height: 34px;
border-radius: 10px; border-radius: var(--uj-radius-md, 6px);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-size: 18px; font-size: 17px;
background: #eef3ff; background: #eef3ff;
color: #2b5ce6; color: #2b5ce6;
margin-bottom: 12px; margin-bottom: 10px;
} }
.uj-quick-label { .uj-quick-label {
font-size: 14px; font-size: 14px;
...@@ -924,14 +915,14 @@ ...@@ -924,14 +915,14 @@
gap: 14px; gap: 14px;
} }
.uj-welcome-sec-icon { .uj-welcome-sec-icon {
width: 36px; width: 32px;
height: 36px; height: 32px;
border-radius: 10px; border-radius: var(--uj-radius-md, 6px);
flex: none; flex: none;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
font-size: 17px; font-size: 16px;
background: #fff7e6; background: #fff7e6;
color: #ba7517; color: #ba7517;
} }
...@@ -940,7 +931,7 @@ ...@@ -940,7 +931,7 @@
.uj-profile { .uj-profile {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 16px; gap: var(--uj-space-module, 10px);
} }
/* 顶部身份横幅 */ /* 顶部身份横幅 */
...@@ -949,17 +940,17 @@ ...@@ -949,17 +940,17 @@
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
flex-wrap: wrap; flex-wrap: wrap;
gap: 20px 24px; gap: 12px 16px;
padding: 22px 24px; padding: 12px 14px;
} }
.uj-profile-hero-id { .uj-profile-hero-id {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 16px; gap: 12px;
} }
.uj-profile-avatar { .uj-profile-avatar {
background: linear-gradient(135deg, #2b5ce6, #5b8def); background: linear-gradient(135deg, #2b5ce6, #5b8def);
box-shadow: 0 6px 16px rgba(43, 92, 230, 0.28); box-shadow: 0 3px 10px rgba(43, 92, 230, 0.28);
flex: none; flex: none;
} }
.uj-profile-name { .uj-profile-name {
...@@ -974,7 +965,7 @@ ...@@ -974,7 +965,7 @@
.uj-profile-hero-meta { .uj-profile-hero-meta {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 14px 36px; gap: 12px 20px;
} }
.uj-profile-chip { .uj-profile-chip {
display: flex; display: flex;
...@@ -996,7 +987,7 @@ ...@@ -996,7 +987,7 @@
.uj-profile-grid { .uj-profile-grid {
display: grid; display: grid;
grid-template-columns: minmax(300px, 1fr) minmax(300px, 1fr); grid-template-columns: minmax(300px, 1fr) minmax(300px, 1fr);
gap: 16px; gap: var(--uj-space-module, 10px);
align-items: stretch; align-items: stretch;
} }
.uj-profile-info, .uj-profile-info,
...@@ -1023,8 +1014,8 @@ ...@@ -1023,8 +1014,8 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 12px;
padding: 12px 0; padding: 10px 0;
border-bottom: 1px dashed #f0f3f8; border-bottom: 1px dashed #f0f3f8;
font-size: 13px; font-size: 13px;
} }
...@@ -1060,7 +1051,7 @@ ...@@ -1060,7 +1051,7 @@
.uj-dash-hero { .uj-dash-hero {
flex-direction: column; flex-direction: column;
align-items: flex-start; align-items: flex-start;
padding: 22px 20px; padding: 16px;
} }
.uj-dash-hero-meta { .uj-dash-hero-meta {
width: 100%; width: 100%;
......
# 积分域老网关联调配置模板
# 用法:复制为 apps/web/subapps/points/.env 后填入真实值(.env 已被 gitignore,不会入库)。
# 凭据含义见 DELIVERY.md §4 与 src/adapter/credentials.ts。
#
# 取值来源:老系统 temp/scrm-micro-points/src/config/env.*.js
# - origin = 老系统 request.baseURL(开发内网 / 生产测试域二选一)
# - appKey = 老系统 sign.appKey
# - secret = 老系统 secret(glsx SHA1 加签私钥,sign 为 40 位大写)
# - version = 老系统 sign.v(默认 1.0.0)
# - format = 老系统 sign.format(默认 json)
# 必填:scrm-shopmall 网关地址
VITE_POINTS_GATEWAY_ORIGIN=http://192.168.1.158:8788/
# VITE_POINTS_GATEWAY_ORIGIN=http://scrm.test.glsx.com.cn/
# 必填:加签凭据
VITE_POINTS_GATEWAY_APP_KEY=your-app-key
VITE_POINTS_GATEWAY_SECRET=your-secret
# 选填
VITE_POINTS_GATEWAY_VERSION=1.0.0
VITE_POINTS_GATEWAY_FORMAT=json
# 选填:dj-smartcarlife 网关独立 origin(默认与 scrm-shopmall 同域;独立域名请改)
VITE_POINTS_DJ_GATEWAY_ORIGIN=
...@@ -9,14 +9,14 @@ ...@@ -9,14 +9,14 @@
## 1. 静态闸门(本机实测,2026-11-06) ## 1. 静态闸门(本机实测,2026-11-06)
| 闸门 | 命令 | 结果 | | 闸门 | 命令 | 结果 |
| ------ | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | ------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| 类型 | `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` | 通过,3310 模块 / 1505.86 kB(gzip 480.88 kB) |
| 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1(store 既有 CSS,与本次无关);扫描 3 个子应用,points 在内 | | 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1(store 既有 CSS,与本次无关);扫描 3 个子应用,points 在内 |
| 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 | | 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 |
| 签名器 | `node --experimental-strip-types temp/md5-check.mjs` | 自写 MD5 与 `node:crypto` 217 组逐字节一致(RFC 1321 向量 + UTF-8 多字节 + 任意长度)。脚本已删 | | 签名 | `pnpm --filter @uj/api-core test`(`test/glsxSign.test.mjs`) | 真实抓包 11 字段复算 → `689F62277A050D6285B1E38BB2C3DA8D8E518EC9` 精确命中;MD5(32 位)明确不符,已固化成防回归闸门 |
浏览器里逐个页面的验收没做 —— 按约定静态闸门到此为止,视觉与交互由你点。第 9 节是可以照着点的清单。 浏览器里逐个页面的验收没做 —— 按约定静态闸门到此为止,视觉与交互由你点。第 9 节是可以照着点的清单。
...@@ -108,7 +108,7 @@ ...@@ -108,7 +108,7 @@
接口方法名、入参字段、返回结构一个字没改;改的是「怎么发出去、怎么读回来」。适配层在 [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 系用 MD5:`secret + 按 key 升序拼接的 k+v + secret`,32 位大写;非字符串参数按 JSON 原文参与拼接(这是签名原文怎么拼的唯一答案,在 `gateways/glsx.ts:25`)。老系统的 `noSignAttr` 换成 `unsignedKeys`。 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`。
3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。 3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。
请求仍然全部经 `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))。
...@@ -196,4 +196,4 @@ points 里绕过去的地方都在本子应用内,没有 bypass 规范。欠 ...@@ -196,4 +196,4 @@ points 里绕过去的地方都在本子应用内,没有 bypass 规范。欠
4. 第二个 tab:查看 → 付款审批(三层级联、税点重算总额、验证码倒计时)→ 编辑进批次(解散 / 移除)→ 到账明细(受理失败行再次打款)→ 行导出。 4. 第二个 tab:查看 → 付款审批(三层级联、税点重算总额、验证码倒计时)→ 编辑进批次(解散 / 移除)→ 到账明细(受理失败行再次打款)→ 行导出。
5. 权限:让后端只下发一个 `points:*` 码,验证其余按钮会隐藏(三态闸门的第二态)。 5. 权限:让后端只下发一个 `points:*` 码,验证其余按钮会隐藏(三态闸门的第二态)。
签名原文是按老系统源码推出的,还没跑过真实网关 —— 第一次联调的判据就是接口 200 且 `code:'0'`;失败不会静默,会带着方法名和返回码说人话。 签名原文与摘要算法已用 glsx-common 源码 + 2026-11-09 真实抓包复算钉死(SHA1 / 40 位大写,见 `test/glsxSign.test.mjs`),但还没跑过真实网关 —— 第一次联调的判据就是接口 200 且 `code:'0'`;失败不会静默,会带着方法名和返回码说人话。
import { createMd5Signer } from '@uj/api-core'; /*
* @Author: liimin 17653212@qq.com
* @Date: 2026-11-06 15:45:47
* @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2026-11-09 18:56:31
* @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
*/
import { createSigner } from '@uj/api-core';
import type { GatewayId, GatewayStrategy, NormalizedEnvelope, Signer } from '../types'; import type { GatewayId, GatewayStrategy, NormalizedEnvelope, Signer } from '../types';
/** /**
...@@ -19,11 +27,12 @@ const UJ_SUCCESS_CODE = 200; ...@@ -19,11 +27,12 @@ const UJ_SUCCESS_CODE = 200;
const UJ_UNAUTHORIZED_CODE = 10002; const UJ_UNAUTHORIZED_CODE = 10002;
/** /**
* glsx 的 MD5 加签:secret 前后包裹、按 key 升序拼接 k+v、sign 大写。 * glsx 的 SHA1 加签:secret 前后包裹、按 key 升序拼接 k+v、sign 40 位大写、timestamp 进原文。
* 现在由 api-core 的 createMd5Signer 生成——其默认配置(glsx 风格序列化 + both 包裹 + 大写) * 依据 glsx-common/src/util.js#createSign 的默认 way='sha1',并经真实抓包 golden 值复算命中:
* 与原手写实现字节级一致,这里只声明 id。换网关改 createMd5Signer 的配置即可,不再手写。 * sign=689F62277A050D6285B1E38BB2C3DA8D8E518EC9(见 api-core/test/glsxSign.test.mjs)。
* 这里只用 api-core 的语义化预设 createSigner,不再手写,也不再用 MD5(32 位,验签必挂)。
*/ */
export const glxsrMd5Signer: Signer = createMd5Signer({ id: 'glsx-md5' }); export const glsxSha1Signer: Signer = createSigner();
/** 主壳 transport 为验签保留原始响应串,所以字符串响应要先解析成对象。 */ /** 主壳 transport 为验签保留原始响应串,所以字符串响应要先解析成对象。 */
function parseRawBody(raw: unknown): unknown { function parseRawBody(raw: unknown): unknown {
...@@ -70,8 +79,11 @@ interface GlsxGatewayDef { ...@@ -70,8 +79,11 @@ interface GlsxGatewayDef {
export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy { export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy {
return { return {
...def, ...def,
signer: glxsrMd5Signer, signer: glsxSha1Signer,
normalize: normalizeGlsxEnvelope, normalize: normalizeGlsxEnvelope,
// 老网关每次请求固定携带、且参与加签的渠道参数:与老系统 / 真实抓包一致用 'scrm-home'。
// 改这个值会直接改变签名原文,联调前不要随意换渠道名。
fixedParams: { source: 'scrm-home' },
}; };
} }
......
...@@ -10,7 +10,7 @@ registerGateway(djSmartcarlifeGateway); ...@@ -10,7 +10,7 @@ registerGateway(djSmartcarlifeGateway);
export { export {
createGlsxGateway, createGlsxGateway,
djSmartcarlifeGateway, djSmartcarlifeGateway,
glxsrMd5Signer, glsxSha1Signer,
normalizeGlsxEnvelope, normalizeGlsxEnvelope,
scrmCarlifeGateway, scrmCarlifeGateway,
scrmShopmallGateway, scrmShopmallGateway,
......
...@@ -13,7 +13,7 @@ export { registerGateway, resolveGateway } from '@uj/api-core'; ...@@ -13,7 +13,7 @@ export { registerGateway, resolveGateway } from '@uj/api-core';
export { export {
createGlsxGateway, createGlsxGateway,
djSmartcarlifeGateway, djSmartcarlifeGateway,
glxsrMd5Signer, glsxSha1Signer,
normalizeGlsxEnvelope, normalizeGlsxEnvelope,
scrmCarlifeGateway, scrmCarlifeGateway,
scrmShopmallGateway, scrmShopmallGateway,
......
import { createRpcGatewayClient } from '@uj/api-core/Request'; /*
* @Author: liimin 17653212@qq.com
* @Date: 2026-11-06 17:31:14
* @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2026-11-09 18:47:44
* @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\rpc.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import { createClient } from '@uj/api-core';
import { requestViaHost } from '@uj/platform-sdk'; import { requestViaHost } from '@uj/platform-sdk';
import { getLoginSession } from '@/access';
// 显式 import(而非依赖 barrel 的 re-export 副作用):保证任何调用路径下网关策略都已登记, // 显式 import(而非依赖 barrel 的 re-export 副作用):保证任何调用路径下网关策略都已登记,
// 否则 resolveGateway 会抛「网关尚未接入」。 // 否则 resolveGateway 会抛「网关尚未接入」。
import './gateways'; import './gateways';
...@@ -12,7 +21,7 @@ const LEGACY_TIMEOUT = 180000; ...@@ -12,7 +21,7 @@ const LEGACY_TIMEOUT = 180000;
/** /**
* web 侧与四个原生小程序共用同一个 `@uj/api-core` 门面。 * web 侧与四个原生小程序共用同一个 `@uj/api-core` 门面。
* *
* 一个 createRpcGatewayClient({配置}) 拿到 client;方案(rpcGateway)、fixedParams 合并、 * createClient({配置}) 不传 kind 即最新版方案(rpcGateway);fixedParams 合并、
* 加签、router 落点、令牌头、信封归一全部由 registerGateway 登记的 GatewayStrategy 决定, * 加签、router 落点、令牌头、信封归一全部由 registerGateway 登记的 GatewayStrategy 决定,
* 与小程序 createRpcDispatcher 共用 prepareRpcCall,字节同源。 * 与小程序 createRpcDispatcher 共用 prepareRpcCall,字节同源。
* 平台差异只由 transport 一处表达:web 子应用走主壳注入的 axios(hostSend), * 平台差异只由 transport 一处表达:web 子应用走主壳注入的 axios(hostSend),
...@@ -24,13 +33,20 @@ const LEGACY_TIMEOUT = 180000; ...@@ -24,13 +33,20 @@ const LEGACY_TIMEOUT = 180000;
* · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等), * · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等),
* 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。 * 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。
*/ */
export const request = createRpcGatewayClient({ export const request = createClient({
transport: 'host', transport: 'host',
hostSend: requestViaHost(), hostSend: requestViaHost(),
timeout: LEGACY_TIMEOUT, timeout: LEGACY_TIMEOUT,
contentType: false, contentType: false,
gatewayCredential: (id) => getGatewayCredential(id as GatewayId), gatewayCredential: (id) => getGatewayCredential(id as GatewayId),
gatewayToken: getGatewayToken, gatewayToken: getGatewayToken,
// sessionId 取自登录接口的 data.loginToken(老网关会话标识);facade 的 resolveSession 会在
// 签名前把它并入请求体并参与 SHA1 加签(与老系统请求体一致)。source 作为网关级固定参数已登记在
// 网关策略(glsx.ts 的 GatewayStrategy.fixedParams)里,这里无需重复配置。
session: {
sessionId: () => getLoginSession()?.loginToken ?? '',
paramName: 'sessionId',
},
errorHandler: (err) => { errorHandler: (err) => {
throw err.cause ?? err; throw err.cause ?? err;
}, },
......
...@@ -10,6 +10,21 @@ import type { GatewayId } from '@/adapter'; ...@@ -10,6 +10,21 @@ import type { GatewayId } from '@/adapter';
* @/adapter/rpc.ts 的 Request → 主壳 props.request,边界由 check-boundaries.mjs 复查。 * @/adapter/rpc.ts 的 Request → 主壳 props.request,边界由 check-boundaries.mjs 复查。
*/ */
export class RpcApiClient { export class RpcApiClient {
constructor() {
// 业务模块常把 `pointsApi.pageOrders` 之类的方法引用直接传给 react-query 的
// fetcher / useExport,若不在构造期绑定 this,调用时 this 指向 undefined,
// 进而 `this.rpc is not a function`。这里把实例方法统一绑定到自身,
// 不论以「方法引用」还是「实例调用」形式使用都安全。
const proto = Object.getPrototypeOf(this);
for (const name of Object.getOwnPropertyNames(proto)) {
if (name === 'constructor') continue;
const value = (this as unknown as Record<string, unknown>)[name];
if (typeof value === 'function') {
(this as unknown as Record<string, unknown>)[name] = value.bind(this);
}
}
}
protected rpc<T>( protected rpc<T>(
gateway: GatewayId, gateway: GatewayId,
method: string, method: string,
......
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
.uj-points-detail-grid { .uj-points-detail-grid {
display: grid; display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 4px 16px; gap: 4px 12px;
} }
.uj-points-detail-item { .uj-points-detail-item {
display: flex; display: flex;
...@@ -41,28 +41,28 @@ ...@@ -41,28 +41,28 @@
white-space: nowrap; white-space: nowrap;
} }
/* 累计结算金额条:一排等宽浅灰平铺块,对齐老系统的 .statistics / .content-item。 /* 累计结算金额条:一排等宽浅灰平铺块,对齐老系统的 .statistics / .content-item。
老系统是 flex:1 的平铺灰块、无描边、无圆角,这里用 #f7f9fa 一致底色。 */ 老系统是 flex:1 的平铺灰块、无描边、无圆角,这里用 surface-2 一致底色。 */
.uj-points-statistics { .uj-points-statistics {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 12px; gap: var(--uj-space-2, 8px);
/* 列表页里统计条只占自己那一行,剩余高度全给表格。 */ /* 列表页里统计条只占自己那一行,剩余高度全给表格。 */
flex: none; flex: none;
} }
.uj-points-statistics-item { .uj-points-statistics-item {
flex: 1 1 200px; flex: 1 1 180px;
min-width: 200px; min-width: 180px;
background: #f7f9fa; background: var(--uj-surface-2);
border-radius: 8px; border-radius: 6px;
padding: 16px; padding: 12px;
} }
.uj-points-statistics-label { .uj-points-statistics-label {
color: var(--uj-text-3); color: var(--uj-text-3);
font-size: 14px; font-size: 13px;
margin-bottom: 12px; margin-bottom: 8px;
} }
.uj-points-statistics-value { .uj-points-statistics-value {
font-size: 26px; font-size: 22px;
font-weight: 700; font-weight: 700;
color: var(--uj-text-1); color: var(--uj-text-1);
} }
...@@ -86,15 +86,15 @@ ...@@ -86,15 +86,15 @@
/* 统计条容器与标题行:对齐老系统 .statistics(无外框)与 .title(16px 粗体)。 */ /* 统计条容器与标题行:对齐老系统 .statistics(无外框)与 .title(16px 粗体)。 */
.uj-points-statistics-card { .uj-points-statistics-card {
flex: none; flex: none;
margin-bottom: 12px; margin-bottom: var(--uj-space-module, 10px);
} }
.uj-points-statistics-head { .uj-points-statistics-head {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 12px; gap: 8px;
margin-bottom: 12px; margin-bottom: 8px;
font-size: 16px; font-size: 15px;
font-weight: 700; font-weight: 700;
color: var(--uj-text-1); color: var(--uj-text-1);
} }
...@@ -149,7 +149,7 @@ ...@@ -149,7 +149,7 @@
display: block; display: block;
width: 100%; width: 100%;
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: 8px; border-radius: 6px;
} }
.uj-points-idcard-empty { .uj-points-idcard-empty {
display: flex; display: flex;
...@@ -157,7 +157,7 @@ ...@@ -157,7 +157,7 @@
justify-content: center; justify-content: center;
height: 96px; height: 96px;
border: 1px dashed var(--uj-border); border: 1px dashed var(--uj-border);
border-radius: 8px; border-radius: 6px;
color: var(--uj-text-3); color: var(--uj-text-3);
} }
/* 免责协议指向第三方域名,不写尺寸就会被 iframe 默认高度压成一条。 */ /* 免责协议指向第三方域名,不写尺寸就会被 iframe 默认高度压成一条。 */
...@@ -166,7 +166,7 @@ ...@@ -166,7 +166,7 @@
width: 100%; width: 100%;
height: 60vh; height: 60vh;
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: 8px; border-radius: 6px;
background: var(--uj-surface); background: var(--uj-surface);
} }
.uj-points-detail > .uj-points-detail-grid { .uj-points-detail > .uj-points-detail-grid {
...@@ -180,7 +180,7 @@ ...@@ -180,7 +180,7 @@
margin-bottom: 12px; margin-bottom: 12px;
padding: 6px 10px; padding: 6px 10px;
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: 8px; border-radius: 6px;
background: var(--uj-surface-2, var(--uj-surface)); background: var(--uj-surface-2, var(--uj-surface));
font-size: 13px; font-size: 13px;
} }
...@@ -208,7 +208,7 @@ ...@@ -208,7 +208,7 @@
} }
.uj-points-tag-list { .uj-points-tag-list {
margin: 0; margin: 0;
padding: 0 0 0 20px; padding: 0 0 0 12px;
list-style: none; list-style: none;
} }
.uj-points-tag-panel > .uj-points-tag-list { .uj-points-tag-panel > .uj-points-tag-list {
...@@ -249,13 +249,13 @@ ...@@ -249,13 +249,13 @@
把页面整体收一档。共享令牌(圆角档、阴影、字号档、配色)保持不变。 把页面整体收一档。共享令牌(圆角档、阴影、字号档、配色)保持不变。
改动只落在 points 目录的 page.css,packages 一行没动。 */ 改动只落在 points 目录的 page.css,packages 一行没动。 */
/* 页面骨架:整页与各区块之间的 gap,16 → 12。 */ /* 页面骨架:整页与各区块之间的 gap,统一到模块间距令牌(≤10px)。 */
.uj-points-app .uj-page { .uj-points-app .uj-page {
gap: 12px; gap: var(--uj-space-module, 10px);
} }
/* 页头:标题块与右上角动作之间的 gap,20 → 12;标题降一档字号、收窄下边距。 */ /* 页头:标题块与右上角动作之间的 gap,收紧到 8px。 */
.uj-points-app .uj-page__header { .uj-points-app .uj-page__header {
gap: 12px; gap: 8px;
} }
.uj-points-app .uj-page__title { .uj-points-app .uj-page__title {
margin-bottom: 4px; margin-bottom: 4px;
...@@ -288,21 +288,21 @@ ...@@ -288,21 +288,21 @@
padding: 8px 12px; padding: 8px 12px;
} }
/* 工具条与分页:padding 12/20 → 8/16,内部 gap 12 → 8。 */ /* 工具条与分页:padding 8/12,内部 gap 8。 */
.uj-points-app .uj-table-toolbar { .uj-points-app .uj-table-toolbar {
gap: 8px; gap: 8px;
padding: 8px 16px; padding: 8px 12px;
} }
.uj-points-app .uj-table .ant-table-pagination.ant-pagination { .uj-points-app .uj-table .ant-table-pagination.ant-pagination {
padding: 8px 16px; padding: 8px 12px;
} }
/* 卡片圆角 12 → 8:在密集数据页里更利落、更精致(仅 points)。 */ /* 卡片圆角 12 → 8:在密集数据页里更利落、更精致(仅 points)。 */
.uj-points-app .uj-card { .uj-points-app .uj-card {
border-radius: 8px; border-radius: 6px;
} }
/* 弹窗/抽屉里的表单项默认 24px,收到 16px;页面筛选区已内联 marginBottom:0 不受影响。 */ /* 弹窗/抽屉里的表单项默认 24px,收到 16px;页面筛选区已内联 marginBottom:0 不受影响。 */
.uj-points-app .ant-form-item { .uj-points-app .ant-form-item {
margin-bottom: 16px; margin-bottom: var(--uj-space-module, 10px);
} }
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { UAlert, UButton, UCard, UResult, UTabs } from '@uj/ui'; import { UAlert, UButton, UCard, UResult, UTabs, tabLabel } from '@uj/ui';
import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@/components'; import { DataTable, SearchForm, type FieldSchema, type RowActionSchema } from '@/components';
import { pointsApi, type StaffScoreRow } from '@/api'; import { pointsApi, type StaffScoreRow } from '@/api';
import { PP } from '@/permissions/codes'; import { PP } from '@/permissions/codes';
...@@ -135,7 +135,6 @@ export default function ScoreUsers() { ...@@ -135,7 +135,6 @@ export default function ScoreUsers() {
} }
> >
<UTabs <UTabs
className="uj-page__tabs"
activeKey={tab} activeKey={tab}
onChange={(key) => { onChange={(key) => {
setTab(String(key)); setTab(String(key));
...@@ -143,12 +142,9 @@ export default function ScoreUsers() { ...@@ -143,12 +142,9 @@ export default function ScoreUsers() {
}} }}
items={lists.map((item) => ({ items={lists.map((item) => ({
key: item.key, key: item.key,
label: ( label: tabLabel(SCORE_TABS.find((tabItem) => tabItem.key === item.key)?.label, {
<> count: item.query.isFetching ? '…' : item.total,
{SCORE_TABS.find((tabItem) => tabItem.key === item.key)?.label}{' '} }),
<span className="uj-code">{item.query.isFetching ? '…' : item.total}</span>
</>
),
}))} }))}
/> />
<UCard className="uj-filter-card" size="small"> <UCard className="uj-filter-card" size="small">
......
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { DownOutlined } from '@ant-design/icons';
import { UAlert, UButton, UCard, UDropdown, UResult, useUMessage } from '@uj/ui'; import { UAlert, UButton, UCard, UDropdown, UResult, useUMessage } from '@uj/ui';
import { import {
ConfirmModal, ConfirmModal,
...@@ -42,6 +43,15 @@ import { TransferDetailDialog } from './components/TransferDetailDialog'; ...@@ -42,6 +43,15 @@ import { TransferDetailDialog } from './components/TransferDetailDialog';
const SCOPE = ['points', 'transfers'] as const; const SCOPE = ['points', 'transfers'] as const;
/** 下拉触发按钮的箭头:悬浮展开时向下→向上翻转,收起还原。 */
function menuArrowIcon(open: boolean) {
return (
<DownOutlined
style={{ transform: open ? 'rotate(180deg)' : undefined, transition: 'transform 0.2s ease' }}
/>
);
}
/** 老系统只有这几个状态的提现单可以驳回(0 待审核、1 已审核、6 受理失败、8 签约中)。 */ /** 老系统只有这几个状态的提现单可以驳回(0 待审核、1 已审核、6 受理失败、8 签约中)。 */
const REJECTABLE = new Set(['0', '1', '6', '8']); const REJECTABLE = new Set(['0', '1', '6', '8']);
...@@ -74,6 +84,9 @@ export default function WithdrawList() { ...@@ -74,6 +84,9 @@ export default function WithdrawList() {
const [audit, setAudit] = useState<AuditAsk>(); const [audit, setAudit] = useState<AuditAsk>();
const [pay, setPay] = useState<PayAsk>(); const [pay, setPay] = useState<PayAsk>();
const [pendingPay, setPendingPay] = useState<PayAsk>(); const [pendingPay, setPendingPay] = useState<PayAsk>();
// 两个下拉的展开态只用于箭头翻转指示。
const [batchMenuOpen, setBatchMenuOpen] = useState(false);
const [allMenuOpen, setAllMenuOpen] = useState(false);
const [batch, setBatch] = useState<BatchAsk>(); const [batch, setBatch] = useState<BatchAsk>();
const [detailId, setDetailId] = useState<string>(); const [detailId, setDetailId] = useState<string>();
const [idCardRow, setIdCardRow] = useState<WithdrawRow>(); const [idCardRow, setIdCardRow] = useState<WithdrawRow>();
...@@ -379,6 +392,8 @@ export default function WithdrawList() { ...@@ -379,6 +392,8 @@ export default function WithdrawList() {
) : null} ) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY, PP.WITHDRAW_REJECT, PP.WITHDRAW_BATCH]) ? ( {can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY, PP.WITHDRAW_REJECT, PP.WITHDRAW_BATCH]) ? (
<UDropdown <UDropdown
open={batchMenuOpen}
onOpenChange={setBatchMenuOpen}
menu={{ menu={{
items: [ items: [
{ key: '0', label: '批量审核' }, { key: '0', label: '批量审核' },
...@@ -389,11 +404,15 @@ export default function WithdrawList() { ...@@ -389,11 +404,15 @@ export default function WithdrawList() {
onClick: ({ key }) => void runAction(Number(key) as 0 | 1 | 2 | 3, 'batch'), onClick: ({ key }) => void runAction(Number(key) as 0 | 1 | 2 | 3, 'batch'),
}} }}
> >
<UButton>批量操作</UButton> <UButton icon={menuArrowIcon(batchMenuOpen)} iconPlacement="end">
批量操作
</UButton>
</UDropdown> </UDropdown>
) : null} ) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY]) ? ( {can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY]) ? (
<UDropdown <UDropdown
open={allMenuOpen}
onOpenChange={setAllMenuOpen}
menu={{ menu={{
items: [ items: [
{ key: '0', label: '一键审核' }, { key: '0', label: '一键审核' },
...@@ -402,7 +421,9 @@ export default function WithdrawList() { ...@@ -402,7 +421,9 @@ export default function WithdrawList() {
onClick: ({ key }) => void runAction(Number(key) as 0 | 1, 'all'), onClick: ({ key }) => void runAction(Number(key) as 0 | 1, 'all'),
}} }}
> >
<UButton>一键操作</UButton> <UButton icon={menuArrowIcon(allMenuOpen)} iconPlacement="end">
一键操作
</UButton>
</UDropdown> </UDropdown>
) : null} ) : null}
{can(PP.WITHDRAW_TAG) ? ( {can(PP.WITHDRAW_TAG) ? (
......
...@@ -26,7 +26,6 @@ export default function WithdrawManage() { ...@@ -26,7 +26,6 @@ export default function WithdrawManage() {
description="提现单从这里审核、付款、生成批次;批次再走 OA 付款审批,到账情况逐条可查。" description="提现单从这里审核、付款、生成批次;批次再走 OA 付款审批,到账情况逐条可查。"
> >
<UTabs <UTabs
className="uj-page__tabs"
activeKey={active.key} activeKey={active.key}
onChange={(key) => setTab(String(key))} onChange={(key) => setTab(String(key))}
items={TABS.map((item) => ({ key: item.key, label: item.label }))} items={TABS.map((item) => ({ key: item.key, label: item.label }))}
......
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
import type { TableColumnsType } from 'antd'; import type { TableColumnsType } from 'antd';
import { Skeleton, UAlert, UButton, UDrawer, UResult, UTable, UTabs, UTag, UText } from '@uj/ui'; import { Skeleton, UAlert, UButton, UDrawer, UResult, UTable, UTabs, UTag, UText, tabLabel } from '@uj/ui';
import type { StoreListingDetail, StoreListingItem } from '@/api'; import type { StoreListingDetail, StoreListingItem } from '@/api';
import type { StoreDictionaries } from './dictionaries'; import type { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatPolicyValue } from './formatters'; import { dictionaryLabel, formatPolicyValue } from './formatters';
...@@ -81,14 +81,7 @@ function DetailContent({ ...@@ -81,14 +81,7 @@ function DetailContent({
const approvalTabs = [ const approvalTabs = [
{ {
key: 'market', key: 'market',
label: ( label: tabLabel('管理层市场费', { count: detail.categoryCount ?? items.length }),
<span>
管理层市场费{' '}
<span className="approval-detail-tab-count" aria-hidden="true">
{detail.categoryCount ?? items.length}
</span>
</span>
),
children: <ApprovalPolicyPanel detail={detail} spec={spec} kind="market" />, children: <ApprovalPolicyPanel detail={detail} spec={spec} kind="market" />,
}, },
{ {
...@@ -167,11 +160,12 @@ function DetailContent({ ...@@ -167,11 +160,12 @@ function DetailContent({
type="warning" type="warning"
title="打回原因" title="打回原因"
description={detail.rejectReason} description={detail.rejectReason}
style={{ marginBottom: 16 }} style={{ marginBottom: 'var(--uj-space-module, 10px)' }}
/> />
)} )}
<UTabs <UTabs
key={`${detail.listingId}:${mode}:${initialTab}:${open}`} key={`${detail.listingId}:${mode}:${initialTab}:${open}`}
size="lg"
defaultActiveKey={selectedTab} defaultActiveKey={selectedTab}
items={tabs} items={tabs}
/> />
...@@ -211,7 +205,6 @@ export function StoreDetailDrawer({ ...@@ -211,7 +205,6 @@ export function StoreDetailDrawer({
) )
} }
closable={showCustomHeader ? false : undefined} closable={showCustomHeader ? false : undefined}
rootClassName={mode === 'listing' ? 'store-listing-detail' : 'store-approval-detail'}
styles={ styles={
mode === 'listing' mode === 'listing'
? { header: { padding: '16px 20px 20px' }, body: { padding: 20 } } ? { header: { padding: '16px 20px 20px' }, body: { padding: 20 } }
......
...@@ -35,7 +35,7 @@ ...@@ -35,7 +35,7 @@
min-width: 32px; min-width: 32px;
height: 32px; height: 32px;
padding: 0; padding: 0;
border-radius: 7px; border-radius: 6px;
background: var(--uj-divider); background: var(--uj-divider);
color: var(--uj-text-2); color: var(--uj-text-2);
font-size: 18px; font-size: 18px;
...@@ -120,7 +120,7 @@ ...@@ -120,7 +120,7 @@
} }
.approval-detail-flow { .approval-detail-flow {
margin-bottom: 20px; margin-bottom: var(--uj-space-module, 10px);
} }
.approval-detail-flow__heading { .approval-detail-flow__heading {
...@@ -249,49 +249,6 @@ ...@@ -249,49 +249,6 @@
margin-top: 3px; margin-top: 3px;
} }
.store-approval-detail .ant-tabs > .ant-tabs-nav {
margin-bottom: 20px;
}
.store-approval-detail .ant-tabs > .ant-tabs-nav::before {
border-bottom-color: var(--uj-border);
}
.store-approval-detail .ant-tabs-tab {
padding: 12px 16px;
color: var(--uj-text-3);
font-size: 16px;
line-height: 24px;
}
.store-approval-detail .ant-tabs-tab + .ant-tabs-tab {
margin-left: 4px;
}
.store-approval-detail .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: var(--uj-primary);
font-weight: 600;
}
.store-approval-detail .ant-tabs-ink-bar {
background: var(--uj-primary);
}
.approval-detail-tab-count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
margin-left: 6px;
padding: 0 5px;
border-radius: 10px;
background: var(--uj-divider);
color: var(--uj-text-2);
font-size: 12px;
font-weight: 400;
}
.approval-detail-audit { .approval-detail-audit {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
...@@ -304,7 +261,7 @@ ...@@ -304,7 +261,7 @@
gap: 12px; gap: 12px;
padding: 14px 16px; padding: 14px 16px;
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: 8px; border-radius: 6px;
background: var(--uj-surface); background: var(--uj-surface);
} }
...@@ -391,11 +348,6 @@ ...@@ -391,11 +348,6 @@
flex-basis: 110px; flex-basis: 110px;
} }
.store-approval-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.approval-detail-chaincard { .approval-detail-chaincard {
gap: 10px; gap: 10px;
padding: 12px; padding: 12px;
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
.approval-policy-panel__table { .approval-policy-panel__table {
overflow: hidden; overflow: hidden;
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: 8px; border-radius: 6px;
background: var(--uj-surface); background: var(--uj-surface);
} }
......
...@@ -67,7 +67,7 @@ strong.listing-cost-panel__amount { ...@@ -67,7 +67,7 @@ strong.listing-cost-panel__amount {
} }
.listing-cost-panel__note { .listing-cost-panel__note {
margin: 22px 0 0; margin: 10px 0 0;
line-height: 22px; line-height: 22px;
} }
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 10px;
} }
.listing-detail-header__top h2 { .listing-detail-header__top h2 {
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
min-width: 32px; min-width: 32px;
height: 32px; height: 32px;
padding: 0; padding: 0;
border-radius: 7px; border-radius: 6px;
background: var(--uj-divider); background: var(--uj-divider);
color: var(--uj-text-2); color: var(--uj-text-2);
font-size: 18px; font-size: 18px;
...@@ -46,7 +46,7 @@ ...@@ -46,7 +46,7 @@
.listing-detail-meta { .listing-detail-meta {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 8px 20px; gap: 8px 12px;
margin: 12px 0 0; margin: 12px 0 0;
font-size: 14px; font-size: 14px;
font-weight: 400; font-weight: 400;
...@@ -112,34 +112,6 @@ ...@@ -112,34 +112,6 @@
color: var(--uj-text-3); color: var(--uj-text-3);
} }
.store-listing-detail .ant-tabs > .ant-tabs-nav {
margin-bottom: 22px;
}
.store-listing-detail .ant-tabs > .ant-tabs-nav::before {
border-bottom-color: var(--uj-border);
}
.store-listing-detail .ant-tabs-tab {
padding: 12px 18px;
color: var(--uj-text-3);
font-size: 16px;
line-height: 24px;
}
.store-listing-detail .ant-tabs-tab + .ant-tabs-tab {
margin-left: 4px;
}
.store-listing-detail .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
color: var(--uj-primary);
font-weight: 600;
}
.store-listing-detail .ant-tabs-ink-bar {
background: var(--uj-primary);
}
.listing-store-info { .listing-store-info {
color: var(--uj-text-1); color: var(--uj-text-1);
font-size: 14px; font-size: 14px;
...@@ -227,11 +199,6 @@ ...@@ -227,11 +199,6 @@
gap: 6px 14px; gap: 6px 14px;
} }
.store-listing-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.listing-store-info__fields > div { .listing-store-info__fields > div {
grid-template-columns: 110px minmax(0, 1fr); grid-template-columns: 110px minmax(0, 1fr);
} }
......
...@@ -29,12 +29,12 @@ ...@@ -29,12 +29,12 @@
display: grid; display: grid;
grid-template-columns: 110px minmax(0, 1fr); grid-template-columns: 110px minmax(0, 1fr);
gap: 12px; gap: 12px;
padding: 16px 0; padding: 12px 0;
border-bottom: 1px solid var(--uj-divider); border-bottom: 1px solid var(--uj-divider);
} }
.listing-change-history__version:first-of-type { .listing-change-history__version:first-of-type {
padding-top: 24px; padding-top: 12px;
} }
.listing-change-history__version-meta { .listing-change-history__version-meta {
...@@ -106,7 +106,7 @@ ...@@ -106,7 +106,7 @@
} }
.listing-change-history__empty { .listing-change-history__empty {
margin: 16px 0; margin: 10px 0;
} }
@media (max-width: 600px) { @media (max-width: 600px) {
......
...@@ -5,12 +5,12 @@ ...@@ -5,12 +5,12 @@
.store-confirm-records { .store-confirm-records {
max-height: 320px; max-height: 320px;
overflow: auto; overflow: auto;
margin: var(--uj-space-4, 16px) 0; margin: var(--uj-space-module, 10px) 0;
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: var(--uj-radius-md, 8px); border-radius: var(--uj-radius-md, 6px);
} }
.store-confirm-record { .store-confirm-record {
padding: var(--uj-space-3, 12px) var(--uj-space-4, 16px); padding: 10px 14px;
border-bottom: 1px solid var(--uj-divider); border-bottom: 1px solid var(--uj-divider);
} }
.store-confirm-record:last-child { .store-confirm-record:last-child {
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
align-items: center; align-items: center;
height: 22px; height: 22px;
padding: 0 var(--uj-space-2, 8px); padding: 0 var(--uj-space-2, 8px);
border-radius: var(--uj-radius-xs, 4px); border-radius: var(--uj-radius-xs, 3px);
background: var(--uj-primary-soft); background: var(--uj-primary-soft);
color: var(--uj-primary); color: var(--uj-primary);
font-size: var(--uj-font-xs, 12px); font-size: var(--uj-font-xs, 12px);
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
gap: 5px; gap: 5px;
height: 22px; height: 22px;
padding: 0 var(--uj-space-2, 8px); padding: 0 var(--uj-space-2, 8px);
border-radius: var(--uj-radius-xs, 4px); border-radius: var(--uj-radius-xs, 3px);
font-size: var(--uj-font-xs, 12px); font-size: var(--uj-font-xs, 12px);
font-weight: 500; font-weight: 500;
font-variant-numeric: var(--uj-num, tabular-nums); font-variant-numeric: var(--uj-num, tabular-nums);
......
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query'; import { useMutation, useQueries, useQuery, useQueryClient } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UResult, UTabs, useUMessage } from '@uj/ui'; import { UAlert, UButton, UCard, UResult, UTabs, tabLabel, useUMessage } from '@uj/ui';
import { P, PermButton, useAccess } from '@/access'; import { P, PermButton, useAccess } from '@/access';
import { import {
DataTable, DataTable,
...@@ -265,7 +265,6 @@ export default function StoreApprove() { ...@@ -265,7 +265,6 @@ export default function StoreApprove() {
description="按门店+业务场景审核上架数据,商务经理、财务经理依次审批;全部节点通过后生效。" description="按门店+业务场景审核上架数据,商务经理、财务经理依次审批;全部节点通过后生效。"
> >
<UTabs <UTabs
className="uj-page__tabs"
activeKey={tab} activeKey={tab}
onChange={(key) => { onChange={(key) => {
setTab(key as ApproveTab); setTab(key as ApproveTab);
...@@ -274,11 +273,7 @@ export default function StoreApprove() { ...@@ -274,11 +273,7 @@ export default function StoreApprove() {
}} }}
items={tabDefs.map(({ key, label }, index) => ({ items={tabDefs.map(({ key, label }, index) => ({
key, key,
label: ( label: tabLabel(label, { count: lists[index].data?.total ?? '—' }),
<>
{label} <span className="uj-num">{lists[index].data?.total ?? '—'}</span>
</>
),
}))} }))}
/> />
<UCard className="uj-filter-card" size="small"> <UCard className="uj-filter-card" size="small">
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
align-items: center; align-items: center;
height: 22px; height: 22px;
padding: 0 var(--uj-space-2, 8px); padding: 0 var(--uj-space-2, 8px);
border-radius: var(--uj-radius-xs, 4px); border-radius: var(--uj-radius-xs, 3px);
background: var(--uj-primary-soft); background: var(--uj-primary-soft);
color: var(--uj-primary); color: var(--uj-primary);
font-size: var(--uj-font-xs, 12px); font-size: var(--uj-font-xs, 12px);
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: var(--uj-space-2, 8px); gap: var(--uj-space-2, 8px);
margin-block: var(--uj-space-5, 20px); margin-block: var(--uj-space-module, 10px);
} }
.store-column-option { .store-column-option {
...@@ -29,5 +29,5 @@ ...@@ -29,5 +29,5 @@
gap: var(--uj-space-3, 12px); gap: var(--uj-space-3, 12px);
padding: var(--uj-space-2, 8px) var(--uj-space-3, 12px); padding: var(--uj-space-2, 8px) var(--uj-space-3, 12px);
border: 1px solid var(--uj-border); border: 1px solid var(--uj-border);
border-radius: var(--uj-radius-md, 8px); border-radius: var(--uj-radius-md, 6px);
} }
...@@ -91,7 +91,7 @@ function NodeLine({ status }: { status: ChainNodeStatus }) { ...@@ -91,7 +91,7 @@ function NodeLine({ status }: { status: ChainNodeStatus }) {
height: 2, height: 2,
background: lineColor(status), background: lineColor(status),
alignSelf: 'flex-start', alignSelf: 'flex-start',
marginTop: 15, marginTop: 10,
}} }}
/> />
); );
...@@ -151,8 +151,8 @@ export function ApprovalChainPreview({ ...@@ -151,8 +151,8 @@ export function ApprovalChainPreview({
return ( return (
<UCard <UCard
styles={{ body: { padding: '20px 24px 24px' } }} styles={{ body: { padding: '14px 16px' } }}
style={{ marginBottom: 20, border: '1px solid var(--uj-border)', borderRadius: 10 }} style={{ marginBottom: 'var(--uj-space-module, 10px)', border: '1px solid var(--uj-border)', borderRadius: 10 }}
title={ title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} /> <InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
...@@ -160,7 +160,7 @@ export function ApprovalChainPreview({ ...@@ -160,7 +160,7 @@ export function ApprovalChainPreview({
</div> </div>
} }
> >
<div style={{ display: 'flex', padding: '20px 8px 8px' }}> <div style={{ display: 'flex', padding: '12px 8px 8px' }}>
{finalNodes.map((n, i) => { {finalNodes.map((n, i) => {
const prev = finalNodes[i - 1]; const prev = finalNodes[i - 1];
const hasLeft = i > 0; const hasLeft = i > 0;
...@@ -186,7 +186,7 @@ export function ApprovalChainPreview({ ...@@ -186,7 +186,7 @@ export function ApprovalChainPreview({
<NodeIcon status={n.status} index={i} /> <NodeIcon status={n.status} index={i} />
<div <div
style={{ style={{
marginTop: 14, marginTop: 10,
fontSize: 14, fontSize: 14,
fontWeight: 600, fontWeight: 600,
color: color:
......
...@@ -88,10 +88,10 @@ export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetail ...@@ -88,10 +88,10 @@ export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetail
return ( return (
<UCard <UCard
styles={{ body: { padding: '18px 20px 14px' } }} styles={{ body: { padding: '14px 16px 12px' } }}
style={{ style={{
border: '1px solid var(--uj-border)', border: '1px solid var(--uj-border)',
marginBottom: 20, marginBottom: 'var(--uj-space-module, 10px)',
borderRadius: 12, borderRadius: 12,
background: 'var(--uj-surface)', background: 'var(--uj-surface)',
overflow: 'hidden', overflow: 'hidden',
...@@ -140,7 +140,7 @@ export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetail ...@@ -140,7 +140,7 @@ export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetail
maxHeight: 360, maxHeight: 360,
overflowX: 'auto', overflowX: 'auto',
overflowY: 'auto', overflowY: 'auto',
marginBottom: 14, marginBottom: 10,
}} }}
> >
<table <table
......
...@@ -12,7 +12,7 @@ export interface ImportInfoValues { ...@@ -12,7 +12,7 @@ export interface ImportInfoValues {
} }
const formItemLayout = { const formItemLayout = {
style: { marginBottom: 18 }, style: { marginBottom: 'var(--uj-space-module, 10px)' },
}; };
export interface ImportInfoCardProps { export interface ImportInfoCardProps {
...@@ -94,8 +94,8 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard ...@@ -94,8 +94,8 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
return ( return (
<UCard <UCard
styles={{ body: { padding: 20 } }} styles={{ body: { padding: 14 } }}
style={{ marginBottom: 20, border: '1px solid var(--uj-border)' }} style={{ marginBottom: 'var(--uj-space-module, 10px)', border: '1px solid var(--uj-border)' }}
title={ title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} /> <InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
...@@ -115,7 +115,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard ...@@ -115,7 +115,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
style={{ style={{
display: 'grid', display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr', gridTemplateColumns: '1fr 1fr 1fr',
gap: 20, gap: 10,
}} }}
> >
<UFormItem <UFormItem
...@@ -164,7 +164,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard ...@@ -164,7 +164,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
style={{ style={{
display: 'grid', display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr', gridTemplateColumns: '1fr 1fr 1fr',
gap: 20, gap: 10,
marginTop: 4, marginTop: 4,
}} }}
> >
...@@ -180,7 +180,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard ...@@ -180,7 +180,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
</div> </div>
<UFormItem <UFormItem
label={<span style={{ marginTop: 18, display: 'inline-block' }}>备注</span>} label={<span style={{ marginTop: 10, display: 'inline-block' }}>备注</span>}
name="remark" name="remark"
style={{ marginBottom: 8 }} style={{ marginBottom: 8 }}
> >
......
...@@ -12,10 +12,10 @@ export function NoticeSection() { ...@@ -12,10 +12,10 @@ export function NoticeSection() {
return ( return (
<UCard <UCard
styles={{ styles={{
body: { padding: '16px 20px' }, body: { padding: '12px 14px' },
}} }}
style={{ style={{
marginBottom: 20, marginBottom: 'var(--uj-space-module, 10px)',
border: '1px solid var(--uj-info-border)', border: '1px solid var(--uj-info-border)',
background: 'var(--uj-primary-soft)', background: 'var(--uj-primary-soft)',
}} }}
...@@ -25,7 +25,7 @@ export function NoticeSection() { ...@@ -25,7 +25,7 @@ export function NoticeSection() {
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
gap: 10, gap: 10,
marginBottom: 14, marginBottom: 10,
}} }}
> >
<span <span
......
...@@ -33,7 +33,7 @@ export function PageHeader() { ...@@ -33,7 +33,7 @@ export function PageHeader() {
]; ];
return ( return (
<div className="uj-page__header" style={{ marginBottom: 20 }}> <div className="uj-page__header" style={{ marginBottom: 'var(--uj-space-module, 10px)' }}>
<div> <div>
<h2 className="uj-page__title">导入门店信息</h2> <h2 className="uj-page__title">导入门店信息</h2>
<p className="uj-page__desc"> <p className="uj-page__desc">
......
...@@ -108,10 +108,10 @@ export function PolicyConfirmTable({ ...@@ -108,10 +108,10 @@ export function PolicyConfirmTable({
return ( return (
<UCard <UCard
styles={{ body: { padding: '16px 16px 12px' } }} styles={{ body: { padding: '14px 14px 10px' } }}
style={{ style={{
border: '1px solid var(--uj-border)', border: '1px solid var(--uj-border)',
marginBottom: 20, marginBottom: 'var(--uj-space-module, 10px)',
borderRadius: 10, borderRadius: 10,
overflow: 'hidden', overflow: 'hidden',
}} }}
...@@ -122,7 +122,7 @@ export function PolicyConfirmTable({ ...@@ -122,7 +122,7 @@ export function PolicyConfirmTable({
</div> </div>
<div <div
style={{ style={{
marginTop: 12, marginTop: 10,
padding: '10px 12px', padding: '10px 12px',
background: 'var(--uj-surface-2)', background: 'var(--uj-surface-2)',
borderRadius: 6, borderRadius: 6,
......
...@@ -29,8 +29,8 @@ export function StepsBar({ current = 0 }: StepsBarProps) { ...@@ -29,8 +29,8 @@ export function StepsBar({ current = 0 }: StepsBarProps) {
style={{ style={{
background: 'var(--uj-surface)', background: 'var(--uj-surface)',
borderRadius: 10, borderRadius: 10,
padding: '20px 32px 12px', padding: '14px 20px 8px',
marginBottom: 20, marginBottom: 'var(--uj-space-module, 10px)',
border: '1px solid var(--uj-border)', border: '1px solid var(--uj-border)',
}} }}
> >
......
...@@ -139,8 +139,8 @@ export function SubmitConfirmCard({ ...@@ -139,8 +139,8 @@ export function SubmitConfirmCard({
return ( return (
<UCard <UCard
styles={{ body: { padding: '20px 24px' } }} styles={{ body: { padding: '14px 16px' } }}
style={{ marginBottom: 20, border: '1px solid var(--uj-border)', borderRadius: 10 }} style={{ marginBottom: 'var(--uj-space-module, 10px)', border: '1px solid var(--uj-border)', borderRadius: 8 }}
title={ title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} /> <InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
...@@ -158,7 +158,7 @@ export function SubmitConfirmCard({ ...@@ -158,7 +158,7 @@ export function SubmitConfirmCard({
display: 'flex', display: 'flex',
alignItems: 'flex-start', alignItems: 'flex-start',
gap: 8, gap: 8,
marginBottom: 16, marginBottom: 10,
}} }}
> >
<ExclamationCircleOutlined <ExclamationCircleOutlined
...@@ -182,7 +182,7 @@ export function SubmitConfirmCard({ ...@@ -182,7 +182,7 @@ export function SubmitConfirmCard({
padding: '14px 16px', padding: '14px 16px',
background: 'var(--uj-surface-2)', background: 'var(--uj-surface-2)',
borderRadius: 8, borderRadius: 8,
marginBottom: 18, marginBottom: 12,
}} }}
> >
<UCheckbox <UCheckbox
...@@ -199,7 +199,7 @@ export function SubmitConfirmCard({ ...@@ -199,7 +199,7 @@ export function SubmitConfirmCard({
</div> </div>
</div> </div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{infoRows.map((r) => ( {infoRows.map((r) => (
<div key={r.label} style={{ display: 'flex', alignItems: 'flex-start' }}> <div key={r.label} style={{ display: 'flex', alignItems: 'flex-start' }}>
<span style={labelStyle}>{r.label}</span> <span style={labelStyle}>{r.label}</span>
......
...@@ -214,8 +214,8 @@ export function UploadCard({ ...@@ -214,8 +214,8 @@ export function UploadCard({
return ( return (
<UCard <UCard
styles={{ body: { padding: 20 } }} styles={{ body: { padding: 14 } }}
style={{ border: '1px solid var(--uj-border)', marginBottom: 20 }} style={{ border: '1px solid var(--uj-border)', marginBottom: 'var(--uj-space-module, 10px)' }}
title={ title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} /> <InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
...@@ -231,7 +231,7 @@ export function UploadCard({ ...@@ -231,7 +231,7 @@ export function UploadCard({
> >
<div style={{ position: 'relative' }}> <div style={{ position: 'relative' }}>
<UUpload.Dragger ref={uploadRef} {...uploadProps}> <UUpload.Dragger ref={uploadRef} {...uploadProps}>
<div style={{ padding: '30px 0' }}> <div style={{ padding: '20px 0' }}>
<div <div
style={{ style={{
width: 48, width: 48,
...@@ -241,7 +241,7 @@ export function UploadCard({ ...@@ -241,7 +241,7 @@ export function UploadCard({
display: 'inline-flex', display: 'inline-flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'center', justifyContent: 'center',
marginBottom: 16, marginBottom: 12,
}} }}
> >
{uploading ? ( {uploading ? (
...@@ -306,7 +306,7 @@ export function UploadCard({ ...@@ -306,7 +306,7 @@ export function UploadCard({
{fileList[0] && ( {fileList[0] && (
<div <div
style={{ style={{
marginTop: 16, marginTop: 12,
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
padding: '14px 16px', padding: '14px 16px',
...@@ -324,7 +324,7 @@ export function UploadCard({ ...@@ -324,7 +324,7 @@ export function UploadCard({
display: 'inline-flex', display: 'inline-flex',
alignItems: 'center', alignItems: 'center',
justifyContent: 'center', justifyContent: 'center',
marginRight: 12, marginRight: 8,
flex: 'none', flex: 'none',
}} }}
> >
......
...@@ -35,7 +35,7 @@ function StatCard({ item }: StatCardProps) { ...@@ -35,7 +35,7 @@ function StatCard({ item }: StatCardProps) {
const tone = toneMap[item.tone]; const tone = toneMap[item.tone];
return ( return (
<UCard <UCard
styles={{ body: { padding: '18px 20px' } }} styles={{ body: { padding: '14px 16px' } }}
style={{ style={{
borderLeft: `3px solid ${tone.accent}`, borderLeft: `3px solid ${tone.accent}`,
border: tone.border, border: tone.border,
...@@ -139,8 +139,8 @@ export function ValidationStats({ stats, checkResult }: ValidationStatsProps) { ...@@ -139,8 +139,8 @@ export function ValidationStats({ stats, checkResult }: ValidationStatsProps) {
style={{ style={{
display: 'grid', display: 'grid',
gridTemplateColumns: `repeat(${colCount}, minmax(0, 1fr))`, gridTemplateColumns: `repeat(${colCount}, minmax(0, 1fr))`,
gap: 16, gap: 10,
marginBottom: 20, marginBottom: 'var(--uj-space-module, 10px)',
}} }}
> >
{finalStats.map((s) => ( {finalStats.map((s) => (
......
...@@ -157,7 +157,7 @@ export function AccountFormDrawer({ ...@@ -157,7 +157,7 @@ export function AccountFormDrawer({
onClose={onClose} onClose={onClose}
footer={ footer={
<div style={footerStyle}> <div style={footerStyle}>
<UButton onClick={onClose}>取消</UButton> <UButton type="default" onClick={onClose}>取消</UButton>
<UButton type="primary" loading={saveMutation.isPending} onClick={() => form.submit()}> <UButton type="primary" loading={saveMutation.isPending} onClick={() => form.submit()}>
保存 保存
</UButton> </UButton>
......
...@@ -36,7 +36,7 @@ export function RoleDetailDrawer({ open, roleId, onClose }: RoleDetailDrawerProp ...@@ -36,7 +36,7 @@ export function RoleDetailDrawer({ open, roleId, onClose }: RoleDetailDrawerProp
title={detail ? `角色详情 · ${detail.roleName}` : '角色详情'} title={detail ? `角色详情 · ${detail.roleName}` : '角色详情'}
onClose={onClose} onClose={onClose}
footer={ footer={
<UButton style={{ float: 'right' }} onClick={onClose}> <UButton type="default" style={{ float: 'right' }} onClick={onClose}>
关闭 关闭
</UButton> </UButton>
} }
...@@ -282,7 +282,7 @@ const summaryStyle = { ...@@ -282,7 +282,7 @@ const summaryStyle = {
flexWrap: 'wrap' as const, flexWrap: 'wrap' as const,
fontSize: 13, fontSize: 13,
gap: '8px 16px', gap: '8px 16px',
marginBottom: 18, marginBottom: 'var(--uj-space-module, 10px)',
}; };
const sectionTitleStyle = { const sectionTitleStyle = {
alignItems: 'center', alignItems: 'center',
...@@ -358,7 +358,7 @@ const legendStyle = { ...@@ -358,7 +358,7 @@ const legendStyle = {
display: 'flex', display: 'flex',
flexWrap: 'wrap' as const, flexWrap: 'wrap' as const,
fontSize: 12, fontSize: 12,
gap: 18, gap: 10,
marginTop: 12, marginTop: 12,
}; };
const legendItemStyle = { alignItems: 'center', display: 'inline-flex', gap: 6 }; const legendItemStyle = { alignItems: 'center', display: 'inline-flex', gap: 6 };
...@@ -132,7 +132,7 @@ export function RoleFormDrawer({ open, roleItem, onClose, onSuccess }: RoleFormD ...@@ -132,7 +132,7 @@ export function RoleFormDrawer({ open, roleItem, onClose, onSuccess }: RoleFormD
onClose={onClose} onClose={onClose}
footer={ footer={
<div style={footerStyle}> <div style={footerStyle}>
<UButton onClick={onClose}>取消</UButton> <UButton type="default" onClick={onClose}>取消</UButton>
<UButton type="primary" loading={saveMutation.isPending} onClick={() => form.submit()}> <UButton type="primary" loading={saveMutation.isPending} onClick={() => form.submit()}>
保存 保存
</UButton> </UButton>
......
...@@ -14,6 +14,9 @@ export default [ ...@@ -14,6 +14,9 @@ export default [
// 工具链只查各 lane 的 src/,lane 自己的 node --test 门禁在 lane 内跑。 // 工具链只查各 lane 的 src/,lane 自己的 node --test 门禁在 lane 内跑。
ignores: [ ignores: [
'**/dist/**', '**/dist/**',
// api-core 的 tsup 还会产出 miniprogram_dist/index.js(小程序「构建 npm」用的
// 单文件 bundle),同样是生成物且已被 .gitignore 忽略,不能进 lint 口径。
'**/miniprogram_dist/**',
'**/node_modules/**', '**/node_modules/**',
'**/.turbo/**', '**/.turbo/**',
'**/coverage/**', '**/coverage/**',
......
...@@ -19,6 +19,12 @@ ...@@ -19,6 +19,12 @@
"import": "./dist/index.js", "import": "./dist/index.js",
"require": "./dist/index.cjs", "require": "./dist/index.cjs",
"default": "./dist/index.cjs" "default": "./dist/index.cjs"
},
"./legacy": {
"types": "./dist/legacy.d.ts",
"import": "./dist/legacy.js",
"require": "./dist/legacy.cjs",
"default": "./dist/legacy.cjs"
} }
}, },
"files": [ "files": [
...@@ -29,7 +35,7 @@ ...@@ -29,7 +35,7 @@
"build": "tsup", "build": "tsup",
"dev": "tsup --watch", "dev": "tsup --watch",
"lint": "eslint . --max-warnings=0", "lint": "eslint . --max-warnings=0",
"test": "pnpm build && node --test test/sdkSign.test.mjs test/gsc.test.mjs test/rop.test.mjs test/request.test.mjs test/strategy.test.mjs test/clients.test.mjs", "test": "pnpm build && node --test test/sdkSign.test.mjs test/gsc.test.mjs test/rop.test.mjs test/request.test.mjs test/strategy.test.mjs test/clients.test.mjs test/glsxSign.test.mjs test/facade.test.mjs",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"devDependencies": { "devDependencies": {
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
* *
* 适用范围:web(Vite)/ Node 支持 package.json exports 子路径; * 适用范围:web(Vite)/ Node 支持 package.json exports 子路径;
* 原生微信小程序的「构建 npm」不保证解析 exports,四个 mp app 统一走主入口具名导出 * 原生微信小程序的「构建 npm」不保证解析 exports,四个 mp app 统一走主入口具名导出
* `import { createRopClient } from '@uj/api-core'`,拿到的是同一个门面、同一份策略表。 * `import { createClient } from '@uj/api-core'`,拿到的是同一个门面、同一份策略表。
*/ */
export { export {
Request, Request,
...@@ -17,16 +17,9 @@ export { ...@@ -17,16 +17,9 @@ export {
Defaults, Defaults,
InterceptorManager, InterceptorManager,
RequestError, RequestError,
strategies, createSigner,
ropPreset, createStrategy,
gscPreset, createClient,
webHostPreset,
restPreset,
createRopClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
Request as default, Request as default,
} from './index'; } from './index';
export type { export type {
......
import { Request } from './facade'; import { Request } from '../core/facade';
import { import {
createStrategy,
ropPreset, ropPreset,
gscPreset, gscPreset,
webHostPreset, webHostPreset,
restPreset, restPreset,
rpcGatewayPreset, rpcGatewayPreset,
} from './strategies'; } from '../gateway/strategies';
import type { RopPresetOptions, RpcGatewayPresetOptions } from './strategies'; import type {
import type { RequestConfig } from './facade'; CreateStrategyOptions,
RopPresetOptions,
RpcGatewayPresetOptions,
StrategyKind,
} from '../gateway/strategies';
import type { RequestConfig } from '../core/facade';
/** /**
* 客户端工厂:消费层的默认入口,与 `createGscClient` 同构 —— * 客户端工厂:消费层的默认入口,与 `createGscClient` 同构 ——
...@@ -58,3 +64,29 @@ export function createRestClient(options: RequestConfig = {}): Request { ...@@ -58,3 +64,29 @@ export function createRestClient(options: RequestConfig = {}): Request {
export function createGscRestClient(options: RequestConfig = {}): Request { export function createGscRestClient(options: RequestConfig = {}): Request {
return new Request(gscPreset(options)); return new Request(gscPreset(options));
} }
// ---------------------------------------------------------------------------
// 新版统一客户端入口
// ---------------------------------------------------------------------------
export type ClientKind = StrategyKind;
export type CreateClientOptions = CreateStrategyOptions;
/**
* 【新版统一客户端入口】一个函数 + 一份配置,选型靠 `kind`,其余参数原样透给门面。
*
* ```ts
* createClient() // 最新:rpc-gateway 方案
* createClient({ kind: 'rpc-gateway', gatewayCredential, hostSend })
* createClient({ kind: 'rop', hosts, pathEnum, secretKey, signature })
* createClient({ kind: 'web-host', sender, signature: createStrategy.signature.define(...) })
* ```
*
* 不传 kind 即最新版方案;老系统必须显式指定。`rpc-gateway` 发请求前需要
* `gatewayCredential`(构造期不强制,缺了会在真正请求时报错)。
*
* 与 createStrategy 共用同一套 kind 映射:这里只多做一步 `new Request(config)`。
*/
export function createClient(options: CreateClientOptions = {}): Request {
return new Request(createStrategy(options));
}
/**
* 在途请求取消注册表。
*
* 参考 glsk-fetch 的 AbortSignal 透传 / CANCEL_ERROR 语义,但补上它缺失的两点:
* 1. 它只用一个 Set<string> 存 url,做「相同 url 进行中 → 拒绝后一个」;这里用
* Map<key, AbortController> 真正 **abort 前一个未完成的相同请求**。
* 2. 它没有任何页面/scope 分组,只能靠业务方共享外部 signal;这里按 scope 建索引,
* 菜单/页面切换时一次 cancelRequests(scope) 就能批量中断该页所有在途请求。
*
* key = METHOD:resource:稳定参数哈希(而非只有 url),避免不同筛选条件/分页的
* 并发查询被误判成「相同请求」。
*
* 注册表挂在 globalThis 的 Symbol.for 上:微前端里主壳与每个 iframe 各有自己的
* api-core bundle 副本,各自 realm 独立,正好各管各的在途请求;同一 realm 内即便
* 加载了两份 bundle(主入口 + legacy)也共用一份注册表,取消不会漏。
*/
export interface CancellationReason {
code: 'CANCELLED';
detail: string;
}
export function cancellationError(detail: string): CancellationReason {
return { code: 'CANCELLED', detail };
}
interface Registry {
byKey: Map<string, AbortController>;
byScope: Map<string, Set<AbortController>>;
activeScope?: string;
}
const REGISTRY_KEY = Symbol.for('uj.api-core.cancellation');
function registry(): Registry {
const g = globalThis as unknown as Record<symbol, Registry | undefined>;
if (!g[REGISTRY_KEY]) {
g[REGISTRY_KEY] = { byKey: new Map(), byScope: new Map() };
}
return g[REGISTRY_KEY]!;
}
/** 当前页面 scope:请求未显式带 scope 时自动归到这里。 */
export function setActiveScope(scope?: string): void {
registry().activeScope = scope || undefined;
}
export function getActiveScope(): string | undefined {
return registry().activeScope;
}
/** 稳定序列化:对象按 key 排序,保证参数相同则 key 相同。循环引用降级成字符串。 */
function stable(value: unknown, seen = new WeakSet<object>()): string {
if (value === null || value === undefined) return '';
if (typeof value !== 'object') return String(value);
if (seen.has(value)) return '[Circular]';
seen.add(value);
if (Array.isArray(value)) return `[${value.map((v) => stable(v, seen)).join(',')}]`;
return `{${Object.keys(value)
.sort()
.map((k) => `${k}:${stable((value as Record<string, unknown>)[k], seen)}`)
.join(',')}}`;
}
/** 相同请求判定用的 key:方法 + 资源 + 参数(data 优先,其次 params)。 */
export function requestKey(method: string, resource: string, payload?: unknown): string {
return `${method.toUpperCase()}:${resource}:${stable(payload)}`;
}
export interface RegisterCancellableOptions {
key: string;
controller: AbortController;
scope?: string;
/** 是否取消同 key 的前一个未完成请求(默认 true)。 */
cancelPrevious?: boolean;
/** 传给前一个请求 abort() 的原因。 */
reason?: unknown;
}
/**
* 登记一次在途请求,返回注销函数(必须在 finally 里调用)。
* 若同 key 已有未完成请求且 cancelPrevious 为真,先 abort 它再登记新的。
*/
export function registerCancellable(options: RegisterCancellableOptions): () => void {
const reg = registry();
const { key, controller, scope, cancelPrevious = true, reason } = options;
if (cancelPrevious) {
const previous = reg.byKey.get(key);
if (previous && previous !== controller && !previous.signal.aborted) {
previous.abort(reason ?? cancellationError('被后续相同请求取代'));
}
}
reg.byKey.set(key, controller);
if (scope) {
let set = reg.byScope.get(scope);
if (!set) {
set = new Set();
reg.byScope.set(scope, set);
}
set.add(controller);
}
return () => {
if (reg.byKey.get(key) === controller) reg.byKey.delete(key);
const set = scope ? reg.byScope.get(scope) : undefined;
if (set && scope) {
set.delete(controller);
if (!set.size) reg.byScope.delete(scope);
}
};
}
/**
* 批量取消在途请求。
* - 传 scope:只取消该页面/分组的请求;
* - 不传:取消当前 realm 内所有在途请求(菜单切换、登出用这个)。
* 返回实际被 abort 的请求数。
*/
export function cancelRequests(scope?: string): number {
const reg = registry();
const reason = cancellationError('页面切换,取消在途请求');
const targets = new Set<AbortController>();
if (scope === undefined) {
for (const controller of reg.byKey.values()) targets.add(controller);
for (const set of reg.byScope.values()) for (const controller of set) targets.add(controller);
} else {
for (const controller of reg.byScope.get(scope) ?? []) targets.add(controller);
}
let count = 0;
for (const controller of targets) {
if (controller.signal.aborted) continue;
controller.abort(reason);
count += 1;
}
return count;
}
/** 调试 / 测试用:当前在途请求数。 */
export function activeRequestCount(scope?: string): number {
const reg = registry();
if (scope !== undefined) return reg.byScope.get(scope)?.size ?? 0;
return reg.byKey.size;
}
/**
* 合并外部 signal 与自有 controller:外部 abort 时也联动自有 controller。
* 自有 controller 的 signal 才是往下传给传输层的那一个。
*/
export function linkAbortSignal(controller: AbortController, external?: AbortSignal): AbortSignal {
if (!external) return controller.signal;
if (external.aborted) {
controller.abort(external.reason ?? cancellationError('外部 signal 已中止'));
return controller.signal;
}
external.addEventListener('abort', () => controller.abort(external.reason), { once: true });
return controller.signal;
}
import { createAutoSender, createWxSender, createUniSender, createFetchSender, createHostSender } from './senders'; import { createAutoSender, createWxSender, createUniSender, createFetchSender, createHostSender } from '../transport/senders';
import { RequestError } from './errors'; import { RequestError } from './errors';
import { resolveRequestStrategy } from './strategies'; import { resolveRequestStrategy } from '../gateway/strategies';
import type { PreparedRequest, RequestStrategy, SignatureStrategy } from './strategies'; import type { PreparedRequest, RequestStrategy, SignatureStrategy } from '../gateway/strategies';
import type { import type {
GatewayCredential, GatewayCredential,
HeaderSigner, HeaderSigner,
...@@ -11,9 +11,23 @@ import type { ...@@ -11,9 +11,23 @@ import type {
ResponseVerifier, ResponseVerifier,
Signer, Signer,
} from './types'; } from './types';
import type { HostSendFn } from './senders'; import type { HostSendFn } from '../transport/senders';
import {
cancellationError,
getActiveScope,
linkAbortSignal,
registerCancellable,
requestKey,
} from './cancellation';
export { RequestError } from './errors'; export { RequestError } from './errors';
export {
cancelRequests,
setActiveScope,
getActiveScope,
activeRequestCount,
requestKey,
} from './cancellation';
export type { export type {
PreparedRequest, PreparedRequest,
RequestStrategy, RequestStrategy,
...@@ -22,7 +36,7 @@ export type { ...@@ -22,7 +36,7 @@ export type {
RequestStrategySpec, RequestStrategySpec,
SessionValue, SessionValue,
RopPresetOptions, RopPresetOptions,
} from './strategies'; } from '../gateway/strategies';
/** /**
* 统一请求门面:工厂层(clients.ts)在此之上,消费层默认不必直接 `new Request`。 * 统一请求门面:工厂层(clients.ts)在此之上,消费层默认不必直接 `new Request`。
...@@ -254,7 +268,22 @@ export interface RequestConfig { ...@@ -254,7 +268,22 @@ export interface RequestConfig {
*/ */
contentType?: string | false; contentType?: string | false;
timeout?: number; timeout?: number;
/** 防重复提交(同 method+resource 进行中再次调用直接 reject)。 */ /**
* 外部中止信号(react-query 的 queryFn signal / 手动 AbortController)。
* 门面会把它与自有 controller 联动,最终 signal 一路透到传输层(axios / fetch)。
*/
signal?: AbortSignal;
/**
* 页面 scope:缺省取 setActiveScope() 设的当前页。切页 / 登出时调用
* cancelRequests(scope) 可批量中断该页所有在途请求。
*/
scope?: string;
/**
* 相同请求(同 method + resource + 参数)进行中时,abort 掉前一个未完成的请求,默认 true。
* 想保留旧「拒绝后一个」语义请显式开 duplicatePrevention(两者互斥,后者优先)。
*/
cancelPrevious?: boolean;
/** 防重复提交(同 method+resource 进行中再次调用直接 reject)。开启时不再自动取消前一个。 */
duplicatePrevention?: boolean; duplicatePrevention?: boolean;
/** 重试:数字或详细配置。 */ /** 重试:数字或详细配置。 */
retry?: number | RetryOptions; retry?: number | RetryOptions;
...@@ -491,11 +520,12 @@ export class Request { ...@@ -491,11 +520,12 @@ export class Request {
private async dispatch<T>(config: RequestConfig): Promise<T> { private async dispatch<T>(config: RequestConfig): Promise<T> {
const resource = String(config.url ?? ''); const resource = String(config.url ?? '');
const method = String(config.method ?? 'GET').toUpperCase();
const retry: RetryOptions | undefined = const retry: RetryOptions | undefined =
typeof config.retry === 'number' ? { retries: config.retry } : config.retry; typeof config.retry === 'number' ? { retries: config.retry } : config.retry;
const maxAttempts = retry ? retry.retries + 1 : 1; const maxAttempts = retry ? retry.retries + 1 : 1;
const key = `${String(config.method ?? 'GET').toUpperCase()}:${resource}`; const key = `${method}:${resource}`;
if (config.duplicatePrevention) { if (config.duplicatePrevention) {
if (this.activeKeys.has(key)) { if (this.activeKeys.has(key)) {
safeEvent(() => config.events?.duplicate?.(resource, config)); safeEvent(() => config.events?.duplicate?.(resource, config));
...@@ -504,10 +534,27 @@ export class Request { ...@@ -504,10 +534,27 @@ export class Request {
this.activeKeys.add(key); this.activeKeys.add(key);
} }
// —— 在途请求取消注册 ——
// controller 由门面持有,signal 通过 config 传给 prepare → PreparedRequest → RawRequest
// → host/fetch sender → 主壳 axios,取消能真正中断底层 HTTP。
const controller = new AbortController();
const signal = linkAbortSignal(controller, config.signal as AbortSignal | undefined);
config.signal = signal;
const scope = config.scope ?? getActiveScope();
const unregister = registerCancellable({
key: requestKey(method, resource, config.data ?? config.params),
controller,
scope,
// 旧 duplicatePrevention 语义是「拒绝后一个」,与「取消前一个」互斥,以后者为准。
cancelPrevious: config.cancelPrevious !== false && !config.duplicatePrevention,
reason: cancellationError('被后续相同请求取代'),
});
// 前置拦截(网络检查等) // 前置拦截(网络检查等)
if (config.beforeRequest) { if (config.beforeRequest) {
const pre = await config.beforeRequest({ resource, config }); const pre = await config.beforeRequest({ resource, config });
if (pre && typeof pre === 'object' && (pre as { abort?: boolean }).abort) { if (pre && typeof pre === 'object' && (pre as { abort?: boolean }).abort) {
unregister();
return (pre as { value?: unknown }).value as T; return (pre as { value?: unknown }).value as T;
} }
} }
...@@ -526,9 +573,13 @@ export class Request { ...@@ -526,9 +573,13 @@ export class Request {
} }
for (let attempt = 0; attempt < maxAttempts; attempt++) { for (let attempt = 0; attempt < maxAttempts; attempt++) {
try { try {
if (signal.aborted) throw buildError('请求已取消', { config, code: 'CANCELLED' });
const prepared = await this.prepare(config, session); const prepared = await this.prepare(config, session);
if (signal.aborted) throw buildError('请求已取消', { config, code: 'CANCELLED' });
const sender = this.getSender(); const sender = this.getSender();
let raw: RawResponse = await sender.send(prepared as unknown as RawRequest); let raw: RawResponse = await sender.send(prepared as unknown as RawRequest);
// 传输层即使忽略 signal(自定义 sender / 老适配器),取消也不能让响应静默落地。
if (signal.aborted) throw buildError('请求已取消', { config, code: 'CANCELLED' });
// transformResponse 统一在门面执行(不交给传输层): // transformResponse 统一在门面执行(不交给传输层):
// 老 web 壳靠它把 ArrayBuffer 解回文本、从 content-disposition 取文件名,门面接管后 // 老 web 壳靠它把 ArrayBuffer 解回文本、从 content-disposition 取文件名,门面接管后
// host / wx / fetch 三条链路行为一致,也避免 axios 层再跑一次导致重复处理。 // host / wx / fetch 三条链路行为一致,也避免 axios 层再跑一次导致重复处理。
...@@ -552,6 +603,10 @@ export class Request { ...@@ -552,6 +603,10 @@ export class Request {
safeEvent(() => config.events?.complete?.({ resource, ok })); safeEvent(() => config.events?.complete?.({ resource, ok }));
return result as T; return result as T;
} catch (error) { } catch (error) {
if (signal.aborted) {
// 取消不是业务失败:不重试、不 toast、不触发 onTransportError。
throw buildError('请求已取消', { config, code: 'CANCELLED', cause: error });
}
lastError = error; lastError = error;
const wrapped = error instanceof RequestError const wrapped = error instanceof RequestError
? error ? error
...@@ -580,6 +635,7 @@ export class Request { ...@@ -580,6 +635,7 @@ export class Request {
} }
safeUI(() => ui.hideNavigationBarLoading()); safeUI(() => ui.hideNavigationBarLoading());
safeUI(() => ui.stopPullDownRefresh()); safeUI(() => ui.stopPullDownRefresh());
unregister();
if (config.duplicatePrevention) this.activeKeys.delete(key); if (config.duplicatePrevention) this.activeKeys.delete(key);
if (!ok) safeEvent(() => config.events?.complete?.({ resource, ok })); if (!ok) safeEvent(() => config.events?.complete?.({ resource, ok }));
} }
...@@ -599,9 +655,13 @@ export class Request { ...@@ -599,9 +655,13 @@ export class Request {
return { name: sc.paramName ?? 'sessionId', value }; return { name: sc.paramName ?? 'sessionId', value };
} }
/** 方案拼装委托给注册表里的 RequestStrategy;门面只负责之后的统一响应归一。 */ /**
* 方案拼装委托给注册表里的 RequestStrategy;门面只负责之后的统一响应归一。
* signal 在这里统一并入(所有方案一视同仁),随后经 RawRequest 透给传输层。
*/
private async prepare(config: RequestConfig, session?: { name: string; value: string }): Promise<PreparedRequest> { private async prepare(config: RequestConfig, session?: { name: string; value: string }): Promise<PreparedRequest> {
return resolveRequestStrategy(config).prepare(config, session); const prepared = await resolveRequestStrategy(config).prepare(config, session);
return config.signal ? { ...prepared, signal: config.signal } : prepared;
} }
// —— 统一响应归一(抹平拦截器:所有 profile 同一套语义) —— // —— 统一响应归一(抹平拦截器:所有 profile 同一套语义) ——
......
...@@ -130,6 +130,8 @@ export interface RawRequest { ...@@ -130,6 +130,8 @@ export interface RawRequest {
transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>; transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>;
/** 传输层在拿到响应后、交给业务层前,先把对方信封归一成 NormalizedEnvelope。 */ /** 传输层在拿到响应后、交给业务层前,先把对方信封归一成 NormalizedEnvelope。 */
normalize?: (raw: unknown) => NormalizedEnvelope; normalize?: (raw: unknown) => NormalizedEnvelope;
/** 中止信号:由门面创建,一路透到 axios / fetch;页面切换或相同请求取代时触发。 */
signal?: AbortSignal;
} }
/** /**
......
...@@ -4,7 +4,7 @@ import type { ...@@ -4,7 +4,7 @@ import type {
RawRequest, RawRequest,
RpcCall, RpcCall,
RequestSender, RequestSender,
} from './types'; } from '../core/types';
import { resolveGateway } from './registry'; import { resolveGateway } from './registry';
/** 网关归一后的失败:携带后端语义码,便于上层按 10002 等做登出 / 提示。 */ /** 网关归一后的失败:携带后端语义码,便于上层按 10002 等做登出 / 提示。 */
...@@ -30,6 +30,8 @@ export interface RpcPrepareDeps { ...@@ -30,6 +30,8 @@ export interface RpcPrepareDeps {
resolveToken?: () => string; resolveToken?: () => string;
/** 默认超时(毫秒);老系统 RPC 网关一般 180000。 */ /** 默认超时(毫秒);老系统 RPC 网关一般 180000。 */
timeout?: number; timeout?: number;
/** 会话标识(如老网关 sessionId):在签名前并入请求体并参与加签;由 facade 的 resolveSession 解析后传入。 */
session?: { name: string; value: string };
} }
export interface RpcDispatcherDeps extends Omit<RpcPrepareDeps, 'resolveToken'> { export interface RpcDispatcherDeps extends Omit<RpcPrepareDeps, 'resolveToken'> {
...@@ -51,10 +53,14 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi ...@@ -51,10 +53,14 @@ export async function prepareRpcCall(call: RpcCall, deps: RpcPrepareDeps): Promi
const credential = deps.resolveCredential(call.gateway); const credential = deps.resolveCredential(call.gateway);
const needsSign = call.signed !== false; const needsSign = call.signed !== false;
// 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;签名与请求体都基于这份有效参数。 // 网关级常量参数(locale / source 等)先并入,业务参数可覆盖;会话标识同样并入并参与签名。
// effectiveParams 同时驱动请求体与加签原文(与 rop 策略一致:sessionId 既进 body 也进签名)。
const effectiveParams: Record<string, unknown> = { const effectiveParams: Record<string, unknown> = {
...strategy.fixedParams, ...strategy.fixedParams,
...call.params, ...call.params,
...(deps.session && !call.params[deps.session.name]
? { [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) {
......
import { hmacSha256Sync } from './crypto'; import { hmacSha256Sync } from '../signing/crypto';
import { createAutoSender } from './senders'; import { createAutoSender } from '../transport/senders';
import type { HeaderSigner, RawRequest, RawResponse, RequestSender } from './types'; import type { HeaderSigner, RawRequest, RawResponse, RequestSender } from '../core/types';
/** /**
* GSC / glsk 网关适配:REST 落点 + 查询串参数 + HMAC-SHA256 头部签名。 * GSC / glsk 网关适配:REST 落点 + 查询串参数 + HMAC-SHA256 头部签名。
......
import type { GatewayStrategy } from './types'; import type { GatewayStrategy } from '../core/types';
/** /**
* 网关注册表:接入一个新系统 = 登记一个 GatewayStrategy。 * 网关注册表:接入一个新系统 = 登记一个 GatewayStrategy。
......
import { createWxSender } from './senders'; import { createWxSender } from '../transport/senders';
import type { RequestSender } from './types'; import type { RequestSender } from '../core/types';
/** /**
* ROP-router 网关客户端:把各 mp 小程序里手写的那层 `utils/request/request.js` * ROP-router 网关客户端:把各 mp 小程序里手写的那层 `utils/request/request.js`
......
import { createMd5Signer, createSha1Signer, createHmacSigner, createSdkSigner } from './signers'; import { createSigner } from '../signing/signers';
import { createGscHeaderSigner, buildGscQuery, processGscSignParams } from './gsc'; import { createGscHeaderSigner, buildGscQuery, processGscSignParams } from './gsc';
import { prepareRpcCall } from './dispatcher'; import { prepareRpcCall } from './dispatcher';
import { RequestError } from './errors'; import { RequestError } from '../core/errors';
import type { GatewayCredential, HeaderSigner, RawRequest, Signer } from './types'; import type { GatewayCredential, HeaderSigner, RawRequest, Signer } from '../core/types';
import type { BodySignFn, RequestConfig, ResponseOptions, SignaturePreset } from './facade'; import type { BodySignFn, RequestConfig, ResponseOptions, SignaturePreset } from '../core/facade';
/** /**
* 请求方案 / 签名两套正交策略。 * 请求方案 / 签名两套正交策略。
...@@ -46,6 +46,8 @@ export interface PreparedRequest { ...@@ -46,6 +46,8 @@ export interface PreparedRequest {
normalize?: (raw: unknown) => unknown; normalize?: (raw: unknown) => unknown;
/** 透传给传输层的附加项(web 主壳需要 withCredentials / responseType)。 */ /** 透传给传输层的附加项(web 主壳需要 withCredentials / responseType)。 */
withCredentials?: boolean; withCredentials?: boolean;
/** 中止信号:由门面在 prepare 之后统一并入,透传到 RawRequest / axios。 */
signal?: AbortSignal;
} }
/** 一个网关方案策略:自带默认配置 + 请求拼装。 */ /** 一个网关方案策略:自带默认配置 + 请求拼装。 */
...@@ -261,11 +263,11 @@ function headerSignerOf(config: RequestConfig): HeaderSigner | undefined { ...@@ -261,11 +263,11 @@ function headerSignerOf(config: RequestConfig): HeaderSigner | undefined {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
registerSignatureStrategy('none', {}); registerSignatureStrategy('none', {});
registerSignatureStrategy('sha1', () => ({ id: 'sha1', bodySign: bodySignFromSigner(createSha1Signer()) })); registerSignatureStrategy('sha1', () => ({ id: 'sha1', bodySign: bodySignFromSigner(createSigner({ kind: 'rop' })) }));
registerSignatureStrategy('md5', () => ({ id: 'md5', bodySign: bodySignFromSigner(createMd5Signer()) })); registerSignatureStrategy('md5', () => ({ id: 'md5', bodySign: bodySignFromSigner(createSigner({ kind: 'md5' })) }));
registerSignatureStrategy('sdk', () => ({ id: 'sdk', bodySign: bodySignFromSigner(createSdkSigner()) })); registerSignatureStrategy('sdk', () => ({ id: 'sdk', bodySign: bodySignFromSigner(createSigner({ kind: 'sdk' })) }));
registerSignatureStrategy('hmac-sha256', () => { registerSignatureStrategy('hmac-sha256', () => {
const inner = createHmacSigner(); const inner = createSigner({ kind: 'hmac' });
return { return {
id: 'hmac-sha256', id: 'hmac-sha256',
bodySign: bodySignFromSigner(inner), bodySign: bodySignFromSigner(inner),
...@@ -298,7 +300,7 @@ registerSignatureStrategy('gsc-hmac', () => ({ id: 'gsc-hmac', headerSigner: cre ...@@ -298,7 +300,7 @@ registerSignatureStrategy('gsc-hmac', () => ({ id: 'gsc-hmac', headerSigner: cre
* 不摊平、只取回 sign 字段,与 bodySignFromSigner 的摊平版是两种不同策略。 * 不摊平、只取回 sign 字段,与 bodySignFromSigner 的摊平版是两种不同策略。
*/ */
registerSignatureStrategy('rop-sha1', () => { registerSignatureStrategy('rop-sha1', () => {
const signer = createSha1Signer({ id: 'rop-sha1' }); const signer = createSigner({ kind: 'rop', id: 'rop-sha1' });
return { return {
id: 'rop-sha1', id: 'rop-sha1',
bodySign: async (params, secret, noSignAttr = []) => { bodySign: async (params, secret, noSignAttr = []) => {
...@@ -578,7 +580,7 @@ const webHostStrategy: RequestStrategy = defineRequestStrategy({ ...@@ -578,7 +580,7 @@ const webHostStrategy: RequestStrategy = defineRequestStrategy({
*/ */
const rpcGatewayStrategy: RequestStrategy = defineRequestStrategy({ const rpcGatewayStrategy: RequestStrategy = defineRequestStrategy({
id: 'rpc-gateway', id: 'rpc-gateway',
async prepare(config) { async prepare(config, session) {
const gateway = String(config.gateway ?? ''); const gateway = String(config.gateway ?? '');
if (!gateway) { if (!gateway) {
throw new RequestError( throw new RequestError(
...@@ -607,6 +609,7 @@ const rpcGatewayStrategy: RequestStrategy = defineRequestStrategy({ ...@@ -607,6 +609,7 @@ const rpcGatewayStrategy: RequestStrategy = defineRequestStrategy({
resolveCredential, resolveCredential,
resolveToken: config.gatewayToken, resolveToken: config.gatewayToken,
timeout: config.timeout, timeout: config.timeout,
session,
}, },
); );
...@@ -728,3 +731,72 @@ export const strategies = { ...@@ -728,3 +731,72 @@ export const strategies = {
list: listSignatureStrategies, list: listSignatureStrategies,
}, },
}; };
// ---------------------------------------------------------------------------
// 新版统一策略入口:createStrategy / createClient 共用这一套 kind 映射
// ---------------------------------------------------------------------------
/** 方案种类 —— 不传即最新版 'rpc-gateway';其余都是老系统,必须显式传。 */
export type StrategyKind = 'rpc-gateway' | 'rop' | 'gsc' | 'web-host' | 'rest';
/** createStrategy / createClient 的公共入参:选型靠 kind,其余就是普通的 RequestConfig。 */
export interface CreateStrategyOptions extends RequestConfig {
/** 方案种类,默认 'rpc-gateway'。 */
kind?: StrategyKind;
/** kind='rop':小程序老壳的登录重发语义。 */
loginReplay?: boolean;
/** kind='rop':usedcar 老壳的完整信封语义。 */
legacyEnvelope?: boolean;
/** kind='rpc-gateway':运行时凭据注入(请求时才真正需要)。 */
gatewayCredential?: (id: string) => GatewayCredential;
/** kind='rpc-gateway':会话令牌提供器。 */
gatewayToken?: () => string;
/** kind='rpc-gateway':单网关应用可固定默认 gateway。 */
gateway?: string;
}
function strategyConfig(options: CreateStrategyOptions): RequestConfig {
const { kind = 'rpc-gateway', loginReplay, legacyEnvelope, ...env } = options;
switch (kind) {
case 'rpc-gateway':
return rpcGatewayPreset(env as RpcGatewayPresetOptions);
case 'rop':
return ropPreset({ ...env, loginReplay, legacyEnvelope } as RopPresetOptions);
case 'gsc':
return gscPreset(env);
case 'web-host':
return webHostPreset(env);
case 'rest':
return restPreset(env);
default:
throw new RequestError(`未知的策略 kind: ${String(kind)}`, { code: 'UNKNOWN_STRATEGY' });
}
}
/**
* 【新版统一策略入口】生成一份 RequestConfig;常规消费直接用 createClient,不需要碰这里。
*
* ```ts
* createStrategy() // 最新:rpc-gateway
* createStrategy({ kind: 'rop', hosts, secretKey }) // 老系统:ROP-router
* createStrategy({ kind: 'web-host', sender }) // 老系统:web 主壳
* ```
*
* 注册自定义方案 / 覆盖内置实现的高级能力挂在同名静态属性上:
* `createStrategy.define/register/resolve/list`、`createStrategy.signature.*`。
*/
export const createStrategy = Object.assign(
(options: CreateStrategyOptions = {}): RequestConfig => strategyConfig(options),
{
define: defineRequestStrategy,
register: registerRequestStrategy,
resolve: resolveRequestStrategy,
list: listRequestStrategies,
signature: {
define: defineSignatureStrategy,
register: registerSignatureStrategy,
resolve: resolveSignatureStrategy,
list: listSignatureStrategies,
},
},
);
/**
* @uj/api-core 主入口 —— 对外只有三个统一门面:
*
* createSigner(options?) 签名器,选型靠 kind / algorithm,不传即最新 glsx SHA1
* createStrategy(options?) 请求方案配置,选型靠 kind,不传即最新 rpc-gateway
* createClient(options?) 客户端实例,选型靠 kind,不传即最新 rpc-gateway
*
* 老系统显式传参(kind:'rop' / 'md5' / 'gsc' / 'web-host' / 'rest' 等)。
* 旧版那些具名预设全部降级到 `@uj/api-core/legacy`,不再从主入口导出。
*/
export type { export type {
GatewayCredential, GatewayCredential,
GatewayStrategy, GatewayStrategy,
...@@ -11,11 +21,11 @@ export type { ...@@ -11,11 +21,11 @@ export type {
RpcCall, RpcCall,
Signer, Signer,
SignInput, SignInput,
} from './types'; } from './core/types';
export { registerGateway, resolveGateway } from './registry'; export { registerGateway, resolveGateway } from './gateway/registry';
export { createRpcDispatcher, prepareRpcCall, unwrapEnvelope, RpcError } from './dispatcher'; export { createRpcDispatcher, prepareRpcCall, unwrapEnvelope, RpcError } from './gateway/dispatcher';
export type { RpcDispatcherDeps, RpcPrepareDeps } from './dispatcher'; export type { RpcDispatcherDeps, RpcPrepareDeps } from './gateway/dispatcher';
// 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。 // 传输层适配:每种 transport 一个 RequestSender 构造器,由 dispatcher 的 sender 注入。
export { export {
...@@ -24,32 +34,45 @@ export { ...@@ -24,32 +34,45 @@ export {
createUniSender, createUniSender,
createFetchSender, createFetchSender,
createAutoSender, createAutoSender,
} from './senders'; } from './transport/senders';
export type { HostRequestConfig, HostSendFn } from './senders'; export type { HostRequestConfig, HostSendFn } from './transport/senders';
// 签名策略适配:通用工厂 + MD5 / SHA1 / HMAC / SDK / none 五种预设,算法可注入。 // 【统一门面 1/3】签名器:所有算法 / 预设都通过参数确定。
export { export { createSigner } from './signing/signers';
createSigner,
createMd5Signer,
createSha1Signer,
createHmacSigner,
createSdkSigner,
createNoneSigner,
} from './signers';
export type { export type {
SignAlgorithm, SignAlgorithm,
Canonicalizer, Canonicalizer,
SignFieldNames, SignFieldNames,
SignerOptions, SignerOptions,
CreateSignerOptions,
SignerKind,
HmacSignerOptions, HmacSignerOptions,
HmacHeaderNames, HmacHeaderNames,
SdkSignerOptions, SdkSignerOptions,
} from './signers'; } from './signing/signers';
// 【统一门面 2/3】请求方案:createStrategy 上挂 define/register/resolve/list 与 signature.*。
export { createStrategy } from './gateway/strategies';
export type {
StrategyKind,
CreateStrategyOptions,
RequestStrategy,
RequestStrategySpec,
SignatureStrategy,
SignatureSpec,
PreparedRequest,
SessionValue,
} from './gateway/strategies';
// 【统一门面 3/3】客户端实例:new Request(createStrategy(options))。
export { createClient } from './client/clients';
export type { ClientKind, CreateClientOptions } from './client/clients';
// 摘要 / MAC 算法 helper(供自定义 Signer 注入;hmacSha256Sync 为同步纯实现,原生小程序可用)。 // 摘要 / MAC 算法 helper(供自定义 Signer 注入;hmacSha256Sync 为同步纯实现,原生小程序可用)。
export { md5, sha1, sha256, hmacSha256, hmacSha256Sync } from './crypto'; export { md5, sha1, sha256, hmacSha256, hmacSha256Sync } from './signing/crypto';
// GSC / glsk 网关:HMAC 头部签名 + REST 客户端(查询串参数、JSON body、业务码归一)。 // 两个独立老适配器:mp 的 newRequest.js / 离线钉值测试仍在用,且小程序「构建 npm」
// 不保证解析 exports 子路径,故保留在主入口(它们不是新门面的预设,形态与 Request 不同)。
export { export {
createGscClient, createGscClient,
createGscHeaderSigner, createGscHeaderSigner,
...@@ -57,7 +80,7 @@ export { ...@@ -57,7 +80,7 @@ export {
flattenGscParams, flattenGscParams,
buildGscQuery, buildGscQuery,
generateGscNonce, generateGscNonce,
} from './gsc'; } from './gateway/gsc';
export type { export type {
GscClient, GscClient,
GscClientOptions, GscClientOptions,
...@@ -67,11 +90,8 @@ export type { ...@@ -67,11 +90,8 @@ export type {
GscResponseConfig, GscResponseConfig,
GscResponseData, GscResponseData,
GscSessionConfig, GscSessionConfig,
} from './gsc'; } from './gateway/gsc';
export { createLegacyRopClient } from './gateway/rop';
// 第一代 ROP 客户端:独立于统一门面,仅保留给离线钉值测试与旧 `request(opts)` 形状的脚本。
// 新代码请用下方「客户端工厂」里的 createRopClient(走统一 Request 门面 + rop 方案策略)。
export { createLegacyRopClient } from './rop';
export type { export type {
RopClient, RopClient,
RopClientOptions, RopClientOptions,
...@@ -82,20 +102,9 @@ export type { ...@@ -82,20 +102,9 @@ export type {
RopRequestOptions, RopRequestOptions,
RopUiAdapter, RopUiAdapter,
RopLoadingAdapter, RopLoadingAdapter,
} from './rop'; } from './gateway/rop';
// 客户端工厂:消费层默认入口,一个 createXxxClient({配置}) 直接拿 client。
// 与 createGscClient 同构,但底层委托的仍是下面这套统一门面 + 策略注册表。
export {
createRopClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
} from './clients';
// 统一请求门面:抹平平台(auto/wx/uni/fetch/host)、签名、拦截器。 // 统一请求门面:抹平平台(auto/wx/uni/fetch/host)、签名、拦截器。
// 方案与签名都是注册表里的策略;注册自定义策略 / 覆盖内置实现时才需要直接碰它们。
// 同时提供 '@uj/api-core/Request' 子路径入口(src/Request.ts)。 // 同时提供 '@uj/api-core/Request' 子路径入口(src/Request.ts)。
export { export {
Request, Request,
...@@ -103,36 +112,15 @@ export { ...@@ -103,36 +112,15 @@ export {
Defaults, Defaults,
InterceptorManager, InterceptorManager,
RequestError, RequestError,
} from './facade'; cancelRequests,
setActiveScope,
getActiveScope,
activeRequestCount,
requestKey,
} from './core/facade';
// 子路径 `@uj/api-core/Request` 别名到本 bundle,需在此提供默认导出。 // 子路径 `@uj/api-core/Request` 别名到本 bundle,需在此提供默认导出。
export { Request as default } from './facade'; export { Request as default } from './core/facade';
export {
defineRequestStrategy,
defineSignatureStrategy,
registerRequestStrategy,
registerSignatureStrategy,
resolveRequestStrategy,
resolveSignatureStrategy,
listRequestStrategies,
listSignatureStrategies,
strategies,
ropPreset,
gscPreset,
webHostPreset,
restPreset,
rpcGatewayPreset,
} from './strategies';
export type {
RequestStrategy,
RequestStrategySpec,
SignatureStrategy,
SignatureSpec,
PreparedRequest,
SessionValue,
RopPresetOptions,
RpcGatewayPresetOptions,
} from './strategies';
export type { export type {
RequestConfig, RequestConfig,
RequestTransport, RequestTransport,
...@@ -146,4 +134,4 @@ export type { ...@@ -146,4 +134,4 @@ export type {
RetryOptions, RetryOptions,
ErrorHandler, ErrorHandler,
Interceptor, Interceptor,
} from './facade'; } from './core/facade';
/**
* @deprecated 兼容入口:`@uj/api-core/legacy`
*
* 这里集中放老版本那些「一个系统一个函数」的具名 API。新代码请只用主入口的三个统一入口:
*
* ```ts
* import { createSigner, createStrategy, createClient } from '@uj/api-core'
*
* createSigner() // 取代 createGlsxSha1Signer()
* createSigner({ kind: 'rop' }) // 取代 createSha1Signer()
* createSigner({ kind: 'md5' }) // 取代 createMd5Signer()
* createStrategy({ kind: 'rop' }) // 取代 strategies.rop() / ropPreset()
* createClient({ kind: 'rop', ... }) // 取代 createRopClient()
* ```
*
* 选型与算法全部通过参数表达;不传参数即最新版(glsx SHA1 签名 + rpc-gateway 方案),
* 老系统显式传 `kind` / `algorithm`。
*
* 注意:本文件是**独立打包的兼容 bundle**(CJS / ESM 都关掉了跨入口 chunk 共享),
* 内部的策略注册表与主入口不是同一份实例。请整套从本入口取用,不要与主入口的
* createClient / registerGateway 混着注册。例外是「在途请求取消注册表」——它挂在
* globalThis 的 Symbol.for 上,跨 bundle 仍是同一份,取消不会漏。
* 原生微信小程序的「构建 npm」不保证解析 exports 子路径,四个 mp app 一律走主入口。
*/
// 旧签名器预设
export {
createMd5Signer,
createGlsxSha1Signer,
createSha1Signer,
createHmacSigner,
createSdkSigner,
createNoneSigner,
} from './signing/signers';
export type {
HmacSignerOptions,
HmacHeaderNames,
SdkSignerOptions,
} from './signing/signers';
// 旧策略 preset 与注册表操作
export {
strategies,
defineRequestStrategy,
defineSignatureStrategy,
registerRequestStrategy,
registerSignatureStrategy,
resolveRequestStrategy,
resolveSignatureStrategy,
listRequestStrategies,
listSignatureStrategies,
ropPreset,
gscPreset,
webHostPreset,
restPreset,
rpcGatewayPreset,
} from './gateway/strategies';
export type { RopPresetOptions, RpcGatewayPresetOptions } from './gateway/strategies';
// 旧客户端工厂
export {
createRopClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
} from './client/clients';
...@@ -10,8 +10,9 @@ ...@@ -10,8 +10,9 @@
/** /**
* MD5(RFC 1321)。 * MD5(RFC 1321)。
* *
* 老系统的 RPC 网关用 MD5 加签,而这里不引第三方包:catalog 里只有 RSA 链路用到 jsrsasign, * 部分老链路用 MD5 加签(注意:glsx 系 RPC 网关实际是 SHA1,见 signers.ts),这里不引第三方包:
* 为一个摘要算法再加一份依赖不值当。实现按 32 位有符号整数走,输出小端 16 进制, * catalog 里只有 RSA 链路用到 jsrsasign,为一个摘要算法再加一份依赖不值当。
* 实现按 32 位有符号整数走,输出小端 16 进制,
* 已用 RFC 1321 的测试向量核对。 * 已用 RFC 1321 的测试向量核对。
*/ */
const SHIFT = [ const SHIFT = [
...@@ -160,10 +161,10 @@ export async function hmacSha256(message: string, secret: string): Promise<strin ...@@ -160,10 +161,10 @@ export async function hmacSha256(message: string, secret: string): Promise<strin
/** /**
* SHA1(RFC 3174)。 * SHA1(RFC 3174)。
* *
* 原生小程序(points-mall / store-assistant / business-assistant / scrm-carlife)的 RPC 网关 * 原生小程序(points-mall / store-assistant / business-assistant / scrm-carlife)与 web points
* 走 SHA1 加签(`sha1(secret + 拼接原文 + secret).toUpperCase()`),与 web points 子应用的 * 子应用的 glsx RPC 网关**都走 SHA1 加签**(`sha1(secret + 拼接原文 + secret).toUpperCase()`),
* MD5 网关是**两套不同算法**——同一网关家族、不同端用不同摘要。为不让 mp 重新造轮子,这里 * 差别只在 web 侧 timestamp 也进签名原文。为不让 mp 重新造轮子,这里提供零依赖纯实现,
* 提供零依赖纯实现,与 MD5 共用 `toUtf8Bytes`,并已用 RFC 3174 测试向量核对。 * 与 MD5 共用 `toUtf8Bytes`,并已用 RFC 3174 测试向量及真实抓包 golden 值核对。
*/ */
function leftRotate32(value: number, amount: number): number { function leftRotate32(value: number, amount: number): number {
return ((value << amount) | (value >>> (32 - amount))) >>> 0; return ((value << amount) | (value >>> (32 - amount))) >>> 0;
......
import { hmacSha256, md5, sha1 } from './crypto'; import { hmacSha256, md5, sha1 } from './crypto';
import type { Signer, SignInput } from './types'; import type { Signer, SignInput } from '../core/types';
/** /**
* 签名算法:把「签名原文串 + 密钥」算成签名值。可同步(MD5)或异步(Web Crypto HMAC)。 * 签名算法:把「签名原文串 + 密钥」算成签名值。可同步(MD5)或异步(Web Crypto HMAC)。
...@@ -30,12 +30,37 @@ export interface SignerOptions { ...@@ -30,12 +30,37 @@ export interface SignerOptions {
fieldNames?: SignFieldNames; fieldNames?: SignFieldNames;
/** 值序列化(默认 glsx 风格:字符串原样、数/布尔 String、其它 JSON.stringify)。 */ /** 值序列化(默认 glsx 风格:字符串原样、数/布尔 String、其它 JSON.stringify)。 */
canonicalize?: Canonicalizer; canonicalize?: Canonicalizer;
/** sign 值是否大写(MD5 老系统要 true)。默认 false。 */ /** sign 值是否大写(glsx 系老系统要 true)。默认 false。 */
uppercase?: boolean; uppercase?: boolean;
/** 是否把 params 全部并进(排除 unsignedKeys)。默认 true。 */ /** 是否把 params 全部并进(排除 unsignedKeys)。默认 true。 */
includeParams?: boolean; includeParams?: boolean;
} }
/**
* 签名方案种类 —— 新版统一门面 createSigner 的唯一「选型参数」。
*
* - 'glsx'(默认,最新版):glsx 系 RPC 网关 SHA1,40 位大写、secret 前后包裹、timestamp 进原文。
* 依据 glsx-common/src/util.js#createSign 默认 way='sha1',并经真实抓包 golden 值复算命中。
* - 其余都是**老系统**,必须显式传:'rop'(mp ROP SHA1,不带 timestamp)、'md5'(确实要求
* MD5 的老系统)、'sdk'(glsx-common-sdk)、'hmac'(glsk REST)、'none'(免签)、
* 'custom'(通用参数化工厂,需给 algorithm)。
*/
export type SignerKind = 'glsx' | 'rop' | 'md5' | 'sdk' | 'hmac' | 'none' | 'custom';
/** createSigner 的入参:所有选型与微调都靠参数,不再为每个系统单开一个函数。 */
export interface CreateSignerOptions extends Omit<SignerOptions, 'algorithm'> {
/** 方案种类。不传时:给了 algorithm 就按 'custom',否则按最新的 'glsx'。 */
kind?: SignerKind;
/** 摘要 / MAC 算法(kind='custom' 时必填;其余 kind 由预设给定,可显式覆盖)。 */
algorithm?: SignerOptions['algorithm'];
/** kind='sdk':摘要算法,对应 glsx-common-sdk 的 way 参数,默认 'sha1'。 */
way?: 'sha1' | 'md5';
/** kind='hmac':输出头名映射。 */
headerNames?: HmacHeaderNames;
/** kind='hmac':是否把 method 并进签名原文,默认 true。 */
appendMethod?: boolean;
}
/** 默认 glsx 风格序列化:与老 SCRM 网关的签名原文规则一致。 */ /** 默认 glsx 风格序列化:与老 SCRM 网关的签名原文规则一致。 */
const DEFAULT_CANONICALIZE: Canonicalizer = (value) => { const DEFAULT_CANONICALIZE: Canonicalizer = (value) => {
if (value === null || value === undefined) return ''; if (value === null || value === undefined) return '';
...@@ -78,13 +103,15 @@ function wrapSecret( ...@@ -78,13 +103,15 @@ function wrapSecret(
} }
/** /**
* 通用签名策略工厂:把「签名原文怎么拼 + 用什么算法 + secret 怎么裹 + 输出哪些字段」参数化, * 通用签名策略实现:把「签名原文怎么拼 + 用什么算法 + secret 怎么裹 + 输出哪些字段」参数化,
* 避免每个系统手写 MD5 / HMAC 样板。具体算法可注入,覆盖 mp 无 Web Crypto 的情况。 * 避免每个系统手写 MD5 / HMAC 样板。具体算法可注入,覆盖 mp 无 Web Crypto 的情况。
* *
* 这是 createSigner(kind:'custom') / 各预设的**内部实现**,对外只暴露 createSigner。
*
* 返回的 Signer.fields 是 async(即便算法同步也会包成 Promise)——dispatcher 已对签名 await, * 返回的 Signer.fields 是 async(即便算法同步也会包成 Promise)——dispatcher 已对签名 await,
* 这样 HMAC(Web Crypto 异步)与 MD5(同步)走同一套契约,且不引入同步重依赖。 * 这样 HMAC(Web Crypto 异步)与 MD5(同步)走同一套契约,且不引入同步重依赖。
*/ */
export function createSigner(options: SignerOptions): Signer { function buildGenericSigner(options: SignerOptions): Signer {
const { const {
id = 'custom', id = 'custom',
algorithm, algorithm,
...@@ -143,13 +170,81 @@ export function createSigner(options: SignerOptions): Signer { ...@@ -143,13 +170,81 @@ export function createSigner(options: SignerOptions): Signer {
}; };
} }
/** 走通用实现的三种摘要方案默认配置(新版默认 'glsx')。 */
const SIGNER_DEFAULTS = {
glsx: {
id: 'glsx-rpc-sha1',
algorithm: 'sha1',
secretWrap: 'both',
includeDefaults: true,
uppercase: true,
},
rop: {
id: 'glsx-sha1',
algorithm: 'sha1',
secretWrap: 'both',
includeDefaults: true,
excludeDefaults: ['timestamp'],
uppercase: true,
},
md5: {
id: 'md5',
algorithm: 'md5',
secretWrap: 'both',
includeDefaults: true,
uppercase: true,
},
} satisfies Record<'glsx' | 'rop' | 'md5', SignerOptions>;
/** /**
* MD5 加签预设(老 SCRM / glsx 系风格):secret 前后包裹、字段名 appKey/format/method/timestamp/v、 * 【新版统一签名器入口】所有签名方案都通过参数确定,不再为每个系统单开一个函数。
* 输出 sign 大写。默认即与 points 子系统原来的 glxsrMd5Signer 字节级一致。 *
* ```ts
* createSigner() // 最新:glsx SHA1(40 位大写、含 timestamp)
* createSigner({ kind: 'rop' }) // 老系统:mp ROP SHA1(不带 timestamp)
* createSigner({ kind: 'md5' }) // 老系统:MD5
* createSigner({ kind: 'hmac' }) // 老系统:glsk HMAC 头签名
* createSigner({ kind: 'custom', algorithm: myHash, secretWrap: 'both' })
* ```
*
* 兼容规则:显式传 `algorithm` 且未传 `kind` 时按 'custom' 处理,保留原通用工厂语义;
* 其余参数(id / uppercase / fieldNames / canonicalize / excludeDefaults ...)可覆盖预设默认值。
*
* 具名的 createMd5Signer / createGlsxSha1Signer / ... 已降级为兼容别名(@uj/api-core/legacy)。
*/
export function createSigner(options: CreateSignerOptions = {}): Signer {
const { kind = options.algorithm ? 'custom' : 'glsx', ...rest } = options;
switch (kind) {
case 'glsx':
case 'rop':
case 'md5':
return buildGenericSigner({ ...SIGNER_DEFAULTS[kind], ...rest } as SignerOptions);
case 'sdk':
return createSdkSigner(rest);
case 'hmac':
return createHmacSigner(rest);
case 'none':
return createNoneSigner(rest.id);
case 'custom':
if (!rest.algorithm) {
throw new Error("createSigner({ kind: 'custom' }) 需要提供 algorithm");
}
return buildGenericSigner(rest as SignerOptions);
default:
throw new Error(`未知的 signer kind: ${String(kind)}`);
}
}
/**
* MD5 加签预设:secret 前后包裹、字段名 appKey/format/method/timestamp/v、输出 sign 大写(32 位)。
*
* 注意:glsx 系(老 SCRM)RPC 网关实际用的是 **SHA1**(40 位大写),见 createGlsxSha1Signer。
* 历史上 web points 曾误用本预设,导致验签失败;本预设仅保留给确实要求 MD5 的系统与内置
* 'md5' 签名策略使用,**不要用于 glsx 网关**。
*/ */
export function createMd5Signer(options: { id?: string; uppercase?: boolean } = {}): Signer { export function createMd5Signer(options: { id?: string; uppercase?: boolean } = {}): Signer {
return createSigner({ return createSigner({
id: options.id ?? 'glsx-md5', id: options.id ?? 'md5',
algorithm: 'md5', algorithm: 'md5',
secretWrap: 'both', secretWrap: 'both',
includeDefaults: true, includeDefaults: true,
...@@ -158,13 +253,35 @@ export function createMd5Signer(options: { id?: string; uppercase?: boolean } = ...@@ -158,13 +253,35 @@ export function createMd5Signer(options: { id?: string; uppercase?: boolean } =
} }
/** /**
* glsx 系(老 SCRM)RPC 网关的 SHA1 加签预设:secret 前后包裹、按 key 升序拼 k+v、
* 系统字段 appKey/format/method/timestamp/v 全进原文、输出 sign 大写(**40 位**)。
*
* 依据:glsx-common/src/util.js#createSign 的默认 way='sha1'(src/http.js 未覆盖),
* 且 2026-11-09 真实抓包(method=scrm.api.shopmall.integralorder.all.page、
* sign=689F62277A050D6285B1E38BB2C3DA8D8E518EC9)已复算命中,见 test/glsxSign.test.mjs。
*
* 与小程序 ROP 的 createSha1Signer 区别只在一处:本预设 **timestamp 进签名原文**(web RPC
* 网关带时间戳),mp ROP 不带 timestamp。两者都属 SHA1、都用 glsx 风格序列化,别混用。
*/
export function createGlsxSha1Signer(options: { id?: string; uppercase?: boolean } = {}): Signer {
return createSigner({
id: options.id ?? 'glsx-rpc-sha1',
algorithm: 'sha1',
secretWrap: 'both',
includeDefaults: true,
uppercase: options.uppercase ?? true,
});
}
/**
* SHA1 加签预设(原生小程序 ROP 方案):secret 前后包裹、`appKey/format/method/v` 进原文 + * SHA1 加签预设(原生小程序 ROP 方案):secret 前后包裹、`appKey/format/method/v` 进原文 +
* params 全签(mp 会把 locale / source / sessionId 放进 params,一并参与签名)、不挂 timestamp * params 全签(mp 会把 locale / source / sessionId 放进 params,一并参与签名)、不挂 timestamp
* (mp 用 v 而非时间戳)、输出 sign 大写。 * (mp 用 v 而非时间戳)、输出 sign 大写。
* *
* 与 web points 子应用的 MD5 网关同属一个后端家族,但**算法是 SHA1**——两套不同摘要并存, * web points 子应用的 glsx RPC 网关同属一个后端家族、同样用 SHA1(见 createGlsxSha1Signer),
* 故这里独立预设,不让 mp 复用 web 的 MD5 signer。原文拼接使用默认 glsx 风格(扁平参数下与 * 差别仅在 timestamp 是否进原文;故两个预设独立存在,不让 mp 复用 web 的含时间戳版本。
* mp 的 qs 拼接等价;仅当参数含嵌套对象 / 数组时才可能分叉,那种情况可改用 qs 或自定义 canonicalize)。 * 原文拼接使用默认 glsx 风格(扁平参数下与 mp 的 qs 拼接等价;仅当参数含嵌套对象 / 数组时
* 才可能分叉,那种情况可改用 qs 或自定义 canonicalize)。
*/ */
export function createSha1Signer(options: { id?: string; uppercase?: boolean } = {}): Signer { export function createSha1Signer(options: { id?: string; uppercase?: boolean } = {}): Signer {
return createSigner({ return createSigner({
......
import type { HttpMethod } from '@uj/contracts'; import type { HttpMethod } from '@uj/contracts';
import type { RawRequest, RawResponse, RequestSender } from './types'; import type { RawRequest, RawResponse, RequestSender } from '../core/types';
/** /**
* 主壳请求函数的入参形状(props.request / requestViaHost 的 RemoteRequest 子集)。 * 主壳请求函数的入参形状(props.request / requestViaHost 的 RemoteRequest 子集)。
...@@ -16,11 +16,31 @@ export interface HostRequestConfig { ...@@ -16,11 +16,31 @@ export interface HostRequestConfig {
transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>; transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>;
responseType?: 'json' | 'blob' | 'arraybuffer' | 'text'; responseType?: 'json' | 'blob' | 'arraybuffer' | 'text';
withCredentials?: boolean; withCredentials?: boolean;
/** 中止信号:跨 props.request 引用传递(wujie 同源 srcdoc 不做序列化),主壳 axios 直接吃它。 */
signal?: AbortSignal;
[key: string]: unknown; [key: string]: unknown;
} }
export type HostSendFn = (req: HostRequestConfig) => Promise<unknown>; export type HostSendFn = (req: HostRequestConfig) => Promise<unknown>;
/** 合并多个 signal(外部取消 + 超时取消);无 AbortSignal.any 的环境手动联动。 */
function mergeSignal(...signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
const list = signals.filter(Boolean) as AbortSignal[];
if (!list.length) return undefined;
if (list.length === 1) return list[0];
const anyFn = (AbortSignal as unknown as { any?: (s: AbortSignal[]) => AbortSignal }).any;
if (typeof anyFn === 'function') return anyFn(list);
const controller = new AbortController();
for (const s of list) {
if (s.aborted) {
controller.abort(s.reason);
break;
}
s.addEventListener('abort', () => controller.abort(s.reason), { once: true });
}
return controller.signal;
}
/** /**
* 把主壳请求函数包成 RequestSender。 * 把主壳请求函数包成 RequestSender。
* *
...@@ -42,6 +62,7 @@ export function createHostSender(send: HostSendFn): RequestSender { ...@@ -42,6 +62,7 @@ export function createHostSender(send: HostSendFn): RequestSender {
timeout: req.timeout, timeout: req.timeout,
withCredentials: true, withCredentials: true,
responseType: req.responseType, responseType: req.responseType,
signal: req.signal,
transformResponse: req.transformResponse transformResponse: req.transformResponse
?? (req.normalize ?? (req.normalize
? [req.normalize as (raw: unknown, headers: Record<string, string>) => unknown] ? [req.normalize as (raw: unknown, headers: Record<string, string>) => unknown]
...@@ -140,12 +161,18 @@ export function createFetchSender(init?: RequestInit): RequestSender { ...@@ -140,12 +161,18 @@ export function createFetchSender(init?: RequestInit): RequestSender {
: typeof req.data === 'string' : typeof req.data === 'string'
? req.data ? req.data
: JSON.stringify(req.data); : JSON.stringify(req.data);
const mergedSignal = mergeSignal(
req.signal,
req.timeout ? AbortSignal.timeout(req.timeout) : undefined,
);
const response = await fetch(req.url, { const response = await fetch(req.url, {
method: req.method, method: req.method,
headers: req.headers, headers: req.headers,
body, body,
signal: req.timeout ? AbortSignal.timeout(req.timeout) : undefined, signal: mergedSignal,
...init, ...init,
// init 自带 signal 时仍要保住门面的取消链路。
...(init?.signal ? { signal: mergeSignal(mergedSignal, init.signal) } : {}),
}); });
const raw = response.headers.get('content-type')?.includes('application/json') const raw = response.headers.get('content-type')?.includes('application/json')
? await response.json() ? await response.json()
......
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
* 客户端工厂层钉值测试。 * 客户端工厂层钉值测试。
* *
* 关注两件事: * 关注两件事:
* 1. createXxxClient({配置}) 与 new Request(strategies.xxx({...})) 逐字节等价 —— * 1. createXxxClient({配置}) 与 new Request(createStrategy.xxx({...})) 逐字节等价 ——
* 工厂只是装配形态,不是另一套请求实现; * 工厂只是装配形态,不是另一套请求实现;
* 2. 消费层装配点(四个小程序 + web 主壳 + web points)必须保持工厂形态, * 2. 消费层装配点(四个小程序 + web 主壳 + web points)必须保持工厂形态,
* 不得再出现 new Request / strategies.* / 全局注册签名。 * 不得再出现 new Request / createStrategy.* / 全局注册签名。
*/ */
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { createRequire } from 'node:module'; import { createRequire } from 'node:module';
...@@ -19,15 +19,10 @@ const core = require('../dist/index.cjs'); ...@@ -19,15 +19,10 @@ const core = require('../dist/index.cjs');
const { const {
Request, Request,
createRequest, createRequest,
strategies, createStrategy,
defineSignatureStrategy,
registerGateway, registerGateway,
createLegacyRopClient, createLegacyRopClient,
createRopClient, createClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
} = core; } = core;
const HERE = path.dirname(fileURLToPath(import.meta.url)); const HERE = path.dirname(fileURLToPath(import.meta.url));
...@@ -68,7 +63,7 @@ const inlineSign = async (params, secret) => ({ ...params, sign: `inline#${secre ...@@ -68,7 +63,7 @@ const inlineSign = async (params, secret) => ({ ...params, sign: `inline#${secre
// 1. 工厂 == 策略装配 // 1. 工厂 == 策略装配
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
test('CT-FAC-001 createRopClient 与 strategies.rop 装配逐字节等价', async () => { test('CT-FAC-001 createClient 与 createStrategy.rop 装配逐字节等价', async () => {
const a = makeSender(); const a = makeSender();
const b = makeSender(); const b = makeSender();
const options = { const options = {
...@@ -79,8 +74,8 @@ test('CT-FAC-001 createRopClient 与 strategies.rop 装配逐字节等价', asyn ...@@ -79,8 +74,8 @@ test('CT-FAC-001 createRopClient 与 strategies.rop 装配逐字节等价', asyn
session: { sessionId: () => 'sess-1' }, session: { sessionId: () => 'sess-1' },
}; };
const viaFactory = createRopClient({ ...options, sender: a.sender }); const viaFactory = createClient({ kind: 'rop', ...options, sender: a.sender });
const viaStrategies = createRequest(strategies.rop({ ...options, sender: b.sender })); const viaStrategies = createRequest(createStrategy({ kind: 'rop', ...options, sender: b.sender }));
assert.ok(viaFactory instanceof Request); assert.ok(viaFactory instanceof Request);
assert.ok(viaStrategies instanceof Request); assert.ok(viaStrategies instanceof Request);
...@@ -98,9 +93,9 @@ test('CT-FAC-001 createRopClient 与 strategies.rop 装配逐字节等价', asyn ...@@ -98,9 +93,9 @@ test('CT-FAC-001 createRopClient 与 strategies.rop 装配逐字节等价', asyn
assert.equal(a.calls[0].data.sign, 'inline#sk'); assert.equal(a.calls[0].data.sign, 'inline#sk');
}); });
test('CT-FAC-002 signature 直接给函数即可生效,无需 strategies.signature.register', async () => { test('CT-FAC-002 signature 直接给函数即可生效,无需 createStrategy.signature.register', async () => {
const { calls, sender } = makeSender(); const { calls, sender } = makeSender();
const api = createRopClient({ hosts: HOSTS, defaultCredential: CRED, signature: inlineSign, sender }); const api = createClient({ kind: 'rop', hosts: HOSTS, defaultCredential: CRED, signature: inlineSign, sender });
await api.post('scrm.api.shopmall.order.list', { p: 1 }); await api.post('scrm.api.shopmall.order.list', { p: 1 });
assert.equal(calls[0].data.sign, 'inline#sk'); assert.equal(calls[0].data.sign, 'inline#sk');
assert.ok(calls[0].url.includes('router?method=scrm.api.shopmall.order.list')); assert.ok(calls[0].url.includes('router?method=scrm.api.shopmall.order.list'));
...@@ -108,16 +103,16 @@ test('CT-FAC-002 signature 直接给函数即可生效,无需 strategies.signa ...@@ -108,16 +103,16 @@ test('CT-FAC-002 signature 直接给函数即可生效,无需 strategies.signa
test('CT-FAC-003 内置签名名 / 签名策略实例同样可用', async () => { test('CT-FAC-003 内置签名名 / 签名策略实例同样可用', async () => {
const byName = makeSender(); const byName = makeSender();
const named = createRopClient({ const named = createClient({
hosts: HOSTS, defaultCredential: CRED, signature: 'rop-sha1', sender: byName.sender, kind: 'rop', hosts: HOSTS, defaultCredential: CRED, signature: 'rop-sha1', sender: byName.sender,
}); });
await named.post('scrm.api.shopmall.order.list', { p: 1 }); await named.post('scrm.api.shopmall.order.list', { p: 1 });
assert.ok(byName.calls[0].data.sign, '内置 rop-sha1 必须产出 sign'); assert.ok(byName.calls[0].data.sign, '内置 rop-sha1 必须产出 sign');
const byInstance = makeSender(); const byInstance = makeSender();
const custom = defineSignatureStrategy('ct-inline', { bodySign: inlineSign }); const custom = createStrategy.signature.define('ct-inline', { bodySign: inlineSign });
const api = createRopClient({ const api = createClient({
hosts: HOSTS, defaultCredential: CRED, signature: custom, sender: byInstance.sender, kind: 'rop', hosts: HOSTS, defaultCredential: CRED, signature: custom, sender: byInstance.sender,
}); });
await api.post('scrm.api.shopmall.order.list', { p: 1 }); await api.post('scrm.api.shopmall.order.list', { p: 1 });
assert.equal(byInstance.calls[0].data.sign, 'inline#sk'); assert.equal(byInstance.calls[0].data.sign, 'inline#sk');
...@@ -125,11 +120,11 @@ test('CT-FAC-003 内置签名名 / 签名策略实例同样可用', async () => ...@@ -125,11 +120,11 @@ test('CT-FAC-003 内置签名名 / 签名策略实例同样可用', async () =>
test('CT-FAC-004 五个工厂都返回同一个 Request 类', () => { test('CT-FAC-004 五个工厂都返回同一个 Request 类', () => {
const clients = [ const clients = [
createRopClient({ hosts: HOSTS }), createClient({ kind: 'rop', hosts: HOSTS }),
createWebHostClient({}), createClient({ kind: 'web-host' }),
createRestClient({}), createClient({ kind: 'rest' }),
createGscRestClient({}), createClient({ kind: 'gsc' }),
createRpcGatewayClient({ createClient({
gatewayCredential: () => ({ origin: 'https://gw.test', appKey: 'ak', secret: 'sk' }), gatewayCredential: () => ({ origin: 'https://gw.test', appKey: 'ak', secret: 'sk' }),
}), }),
]; ];
...@@ -140,13 +135,13 @@ test('CT-FAC-004 五个工厂都返回同一个 Request 类', () => { ...@@ -140,13 +135,13 @@ test('CT-FAC-004 五个工厂都返回同一个 Request 类', () => {
} }
}); });
test('CT-FAC-005 createWebHostClient 与 strategies.webHost 装配等价(自带信封语义)', async () => { test('CT-FAC-005 createClient 与 createStrategy.webHost 装配等价(自带信封语义)', async () => {
const responder = { status: 200, data: { code: 200, data: { id: 7 } } }; const responder = { status: 200, data: { code: 200, data: { id: 7 } } };
const a = makeSender(responder); const a = makeSender(responder);
const b = makeSender(responder); const b = makeSender(responder);
const options = { baseURL: 'https://api.test', contentType: false }; const options = { baseURL: 'https://api.test', contentType: false };
const viaFactory = createWebHostClient({ ...options, sender: a.sender }); const viaFactory = createClient({ kind: 'web-host', ...options, sender: a.sender });
const viaStrategies = createRequest(strategies.webHost({ ...options, sender: b.sender })); const viaStrategies = createRequest(createStrategy({ kind: 'web-host', ...options, sender: b.sender }));
const x = await viaFactory.post('/x', { a: 1 }); const x = await viaFactory.post('/x', { a: 1 });
const y = await viaStrategies.post('/x', { a: 1 }); const y = await viaStrategies.post('/x', { a: 1 });
...@@ -156,7 +151,7 @@ test('CT-FAC-005 createWebHostClient 与 strategies.webHost 装配等价(自 ...@@ -156,7 +151,7 @@ test('CT-FAC-005 createWebHostClient 与 strategies.webHost 装配等价(自
assert.deepEqual(x.data.data, { id: 7 }); assert.deepEqual(x.data.data, { id: 7 });
}); });
test('CT-FAC-006 createRpcGatewayClient 业务侧只传 gateway', async () => { test('CT-FAC-006 createClient 业务侧只传 gateway', async () => {
registerGateway({ registerGateway({
id: 'ct-rpc', id: 'ct-rpc',
router: 'rop-ct/router', router: 'rop-ct/router',
...@@ -169,7 +164,7 @@ test('CT-FAC-006 createRpcGatewayClient 业务侧只传 gateway', async () => { ...@@ -169,7 +164,7 @@ test('CT-FAC-006 createRpcGatewayClient 业务侧只传 gateway', async () => {
normalize: (raw) => (String(raw.code) === '0' ? { data: raw.data } : { code: 500, message: 'bad' }), normalize: (raw) => (String(raw.code) === '0' ? { data: raw.data } : { code: 500, message: 'bad' }),
}); });
const { calls, sender } = makeEnvelopeSender(); const { calls, sender } = makeEnvelopeSender();
const api = createRpcGatewayClient({ const api = createClient({
sender, sender,
gatewayCredential: () => ({ origin: 'https://gw.test', appKey: 'ak', secret: 'sk' }), gatewayCredential: () => ({ origin: 'https://gw.test', appKey: 'ak', secret: 'sk' }),
gatewayToken: () => 'tk-1', gatewayToken: () => 'tk-1',
...@@ -184,11 +179,11 @@ test('CT-FAC-006 createRpcGatewayClient 业务侧只传 gateway', async () => { ...@@ -184,11 +179,11 @@ test('CT-FAC-006 createRpcGatewayClient 业务侧只传 gateway', async () => {
test('CT-FAC-007 第一代 ROP 客户端与工厂分离,且子路径导出同一批工厂', () => { test('CT-FAC-007 第一代 ROP 客户端与工厂分离,且子路径导出同一批工厂', () => {
assert.equal(typeof createLegacyRopClient, 'function'); assert.equal(typeof createLegacyRopClient, 'function');
assert.notEqual(core.createRopClient, createLegacyRopClient); assert.notEqual(core.createClient, createLegacyRopClient);
// './Request' 别名到同一 bundle,工厂因此也只有一个实例。 // './Request' 别名到同一 bundle,工厂因此也只有一个实例。
const pkg = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8')); const pkg = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8'));
assert.equal(pkg.exports['./Request'].require, './dist/index.cjs'); assert.equal(pkg.exports['./Request'].require, './dist/index.cjs');
assert.equal(typeof core.createRpcGatewayClient, 'function'); assert.equal(typeof core.createClient, 'function');
}); });
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -207,12 +202,16 @@ const ASSEMBLY_POINTS = [ ...@@ -207,12 +202,16 @@ const ASSEMBLY_POINTS = [
'apps/mp/usedcar/packageUsedCar/newRequest.js', 'apps/mp/usedcar/packageUsedCar/newRequest.js',
]; ];
test('CT-FAC-008 所有装配点只用工厂,不再出现 new Request / strategies / 注册签名', () => { test('CT-FAC-008 所有装配点只用工厂,不再出现 new Request / createStrategy / 注册签名', () => {
for (const rel of ASSEMBLY_POINTS) { for (const rel of ASSEMBLY_POINTS) {
const src = readFileSync(path.join(ROOT, rel), 'utf8'); const src = readFileSync(path.join(ROOT, rel), 'utf8');
assert.ok(!src.includes('new Request('), `${rel} 不应再直接 new Request`); assert.ok(!src.includes('new Request('), `${rel} 不应再直接 new Request`);
assert.ok(!/strategies\.(rop|gsc|webHost|rest|rpcGateway)\(/.test(src), `${rel} 不应再选策略`); assert.ok(!/createStrategy\.(rop|gsc|webHost|rest|rpcGateway)\(/.test(src), `${rel} 不应再选策略`);
assert.ok(!src.includes('signature.register('), `${rel} 不应再全局注册签名`); assert.ok(!src.includes('signature.register('), `${rel} 不应再全局注册签名`);
assert.ok(/create\w+Client\(\s*\{/.test(src), `${rel} 必须用一个 createXxxClient({配置}) 装配`); assert.ok(/create\w*Client\(\s*\{/.test(src), `${rel} 必须用统一 createClient({配置}) 装配(老 GSC 适配器为 createGscClient)`);
assert.ok(
!/create(?:Rop|WebHost|RpcGateway|Rest|GscRest)Client\(/.test(src),
`${rel} 不得再用旧具名工厂(已降级到 @uj/api-core/legacy)`,
);
} }
}); });
/**
* @file 新版统一门面 + 请求取消的钉值测试。
*
* 覆盖三件事:
* 1. 对外只有 createSigner / createStrategy / createClient;不传参即最新版,
* 旧具名 API 只在 @uj/api-core/legacy 里;
* 2. 相同请求(同 method+resource+参数)abort 前一个、按 scope 批量取消,
* 取消统一转 CANCELLED 且不重试;
* 3. AbortSignal 一路透到传输层(host / fetch),能真正中断底层请求。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import test from 'node:test';
const require = createRequire(import.meta.url);
const core = require('../dist/index.cjs');
const legacy = require('../dist/legacy.cjs');
const {
createSigner,
createStrategy,
createClient,
cancelRequests,
setActiveScope,
getActiveScope,
activeRequestCount,
requestKey,
} = core;
/** pending 型 sender:只有 resolve() 或 signal abort 才会落地,便于观察取消。 */
function pendingSender(delay = 20) {
const calls = [];
const sender = {
send(req) {
calls.push(req);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve({ status: 200, data: 'ok' }), delay);
req.signal?.addEventListener(
'abort',
() => {
clearTimeout(timer);
reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
},
{ once: true },
);
});
},
};
return { calls, sender };
}
function restClient(sender, extra = {}) {
return createClient({ kind: 'rest', sender, raw: true, baseURL: 'https://api.test', ...extra });
}
/** 门面的 dispatch 在 Promise 链里执行,让出一次事件循环等它完成注册。 */
const tick = () => new Promise((r) => setTimeout(r, 0));
const SIGN_INPUT = {
method: 'scrm.api.x',
params: { a: 1, settlementStatus: '' },
timestamp: 1794222639246,
appKey: '48e5',
secret: 'c246',
version: '1.0.0',
format: 'json',
};
// ---------------------------------------------------------------------------
// 1. 新门面
// ---------------------------------------------------------------------------
test('FT-FAC-001 主入口只暴露三个统一入口,旧具名 API 只在 legacy 子路径', () => {
for (const name of ['createSigner', 'createStrategy', 'createClient']) {
assert.equal(typeof core[name], 'function', `主入口应导出 ${name}`);
}
const oldNames = [
'createMd5Signer', 'createGlsxSha1Signer', 'createSha1Signer', 'createSdkSigner',
'createHmacSigner', 'createNoneSigner', 'strategies', 'ropPreset', 'rpcGatewayPreset',
'createRopClient', 'createWebHostClient', 'createRpcGatewayClient', 'createRestClient',
'createGscRestClient', 'defineSignatureStrategy',
];
for (const name of oldNames) {
assert.ok(!(name in core), `主入口不应再导出旧名 ${name}`);
assert.ok(name in legacy, `legacy 子路径应保留 ${name}`);
}
});
test('FT-FAC-002 createSigner() 不传参即最新 glsx SHA1,与旧预设逐字节一致', async () => {
const fresh = await createSigner().fields(SIGN_INPUT);
const old = await legacy.createGlsxSha1Signer().fields(SIGN_INPUT);
assert.deepEqual(fresh, old);
assert.equal(fresh.sign.length, 40, 'glsx SHA1 是 40 位大写');
assert.equal(fresh.sign, fresh.sign.toUpperCase());
// 老系统必须显式传 kind
assert.deepEqual(
await createSigner({ kind: 'rop' }).fields(SIGN_INPUT),
await legacy.createSha1Signer().fields(SIGN_INPUT),
);
assert.deepEqual(
await createSigner({ kind: 'md5' }).fields(SIGN_INPUT),
await legacy.createMd5Signer().fields(SIGN_INPUT),
);
assert.equal((await createSigner({ kind: 'md5' }).fields(SIGN_INPUT)).sign.length, 32);
assert.deepEqual(
await createSigner({ kind: 'sdk' }).fields(SIGN_INPUT),
await legacy.createSdkSigner().fields(SIGN_INPUT),
);
// HMAC 每次生成随机 nonce,不做逐字节比对,只确认能产出签名头。
const hmac = await createSigner({ kind: 'hmac' }).fields(SIGN_INPUT);
assert.equal(typeof hmac['X-Sign'], 'string');
assert.deepEqual(createSigner({ kind: 'none' }).fields(SIGN_INPUT), {});
});
test('FT-FAC-003 显式传 algorithm 保留通用工厂语义(老代码不炸)', async () => {
const custom = createSigner({ algorithm: 'md5', secretWrap: 'both', uppercase: true });
assert.deepEqual(await custom.fields(SIGN_INPUT), await legacy.createMd5Signer().fields(SIGN_INPUT));
assert.throws(() => createSigner({ kind: 'custom' }), /algorithm/);
});
test('FT-FAC-004 createStrategy/createClient 默认最新版,老系统按 kind 选', () => {
assert.equal(createStrategy().strategy, 'rpc-gateway');
assert.equal(createStrategy({ kind: 'rop' }).strategy, 'rop');
assert.equal(createStrategy({ kind: 'gsc' }).strategy, 'gsc');
assert.equal(createStrategy({ kind: 'web-host' }).strategy, 'web-host');
assert.equal(createStrategy({ kind: 'rest' }).strategy, 'plain');
assert.equal(createStrategy().strategy, legacy.strategies.rpcGateway({}).strategy);
assert.throws(() => createStrategy({ kind: 'nope' }), /未知的策略 kind/);
const client = createClient({ kind: 'rest', sender: { send: async () => ({ status: 200, data: {} }) } });
assert.equal(typeof client.post, 'function');
assert.equal(client.defaults.config.strategy, 'plain');
assert.equal(createClient().defaults.config.strategy, 'rpc-gateway');
// 高级注册能力挂在 createStrategy 上,不用再从主入口导出一堆 define/register
assert.equal(typeof createStrategy.signature.define, 'function');
assert.ok(createStrategy.list().includes('rpc-gateway'));
});
// ---------------------------------------------------------------------------
// 2. 相同请求取消前一个
// ---------------------------------------------------------------------------
test('FT-CANCEL-001 相同请求 abort 前一个在途请求(后一个成功)', async () => {
const calls = [];
let markFirstStarted;
const firstStarted = new Promise((resolve) => { markFirstStarted = resolve; });
const sender = {
send(req) {
calls.push(req);
if (calls.length === 1) markFirstStarted();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve({ status: 200, data: 'ok' }), 15);
req.signal?.addEventListener(
'abort',
() => {
clearTimeout(timer);
reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
},
{ once: true },
);
});
},
};
const client = restClient(sender);
const first = client.post('/same', { page: 1 });
// 立刻挂上 rejection handler:取消发生在微任务里,晚挂会被 Node 判成 unhandledRejection。
const firstAssert = assert.rejects(first, (e) => e.code === 'CANCELLED', '第一个应被取消');
await firstStarted; // 等第一个真的进了传输层,才是「在途」场景
const second = client.post('/same', { page: 1 });
const secondResult = second.then((v) => v);
await firstAssert;
assert.equal((await secondResult).data, 'ok');
assert.equal(calls.length, 2, '两个都真的发出去了');
assert.ok(calls[0].signal.aborted, '第一个 signal 应已中止');
assert.ok(!calls[1].signal.aborted, '第二个不应被中止');
});
test('FT-CANCEL-001B 背靠背相同请求:前一个尚未发出即被取消,不浪费一次 HTTP', async () => {
const { calls, sender } = pendingSender(15);
const client = restClient(sender);
const first = client.post('/back-to-back', { page: 1 });
const firstAssert = assert.rejects(first, (e) => e.code === 'CANCELLED');
const second = client.post('/back-to-back', { page: 1 });
assert.equal((await second).data, 'ok');
await firstAssert;
assert.equal(calls.length, 1, '前一个在进入传输层前就被取消,只发一次');
});
test('FT-CANCEL-002 参数不同不算相同请求,两个都正常完成', async () => {
const { calls, sender } = pendingSender(10);
const client = restClient(sender);
const [a, b] = await Promise.all([
client.post('/same', { page: 1 }),
client.post('/same', { page: 2 }),
]);
assert.equal(a.data, 'ok');
assert.equal(b.data, 'ok');
assert.equal(calls.length, 2);
assert.notEqual(
requestKey('POST', '/same', { page: 1 }),
requestKey('POST', '/same', { page: 2 }),
);
});
test('FT-CANCEL-003 cancelPrevious:false 可关闭同请求取消', async () => {
const { sender } = pendingSender(10);
const client = restClient(sender, { cancelPrevious: false });
const [a, b] = await Promise.all([client.post('/x', { v: 1 }), client.post('/x', { v: 1 })]);
assert.equal(a.data, 'ok');
assert.equal(b.data, 'ok');
});
// ---------------------------------------------------------------------------
// 3. scope 批量取消 + 外部 signal
// ---------------------------------------------------------------------------
test('FT-CANCEL-004 setActiveScope 自动打标,cancelRequests(scope) 批量中断', async () => {
const { sender } = pendingSender(50);
const client = restClient(sender);
setActiveScope('page-a');
try {
assert.equal(getActiveScope(), 'page-a');
const a = client.post('/a', { x: 1 });
const b = client.post('/b', { x: 2 });
await tick();
assert.equal(activeRequestCount('page-a'), 2, '两个请求都应归到当前页 scope');
assert.equal(cancelRequests('page-a'), 2);
await assert.rejects(a, (e) => e.code === 'CANCELLED');
await assert.rejects(b, (e) => e.code === 'CANCELLED');
assert.equal(activeRequestCount('page-a'), 0);
} finally {
setActiveScope(undefined);
}
});
test('FT-CANCEL-005 cancelRequests() 不传 scope 取消当前 realm 全部在途请求', async () => {
const { sender } = pendingSender(50);
const client = restClient(sender);
setActiveScope('page-b');
try {
const p = client.post('/c', { x: 3 });
await tick();
assert.equal(activeRequestCount(), 1);
assert.equal(cancelRequests(), 1);
await assert.rejects(p, (e) => e.code === 'CANCELLED');
} finally {
setActiveScope(undefined);
}
});
test('FT-CANCEL-006 外部 signal(react-query queryFn)abort 会取消请求且不重试', async () => {
let attempts = 0;
let markStarted;
const started = new Promise((resolve) => { markStarted = resolve; });
const sender = {
send(req) {
attempts += 1;
markStarted();
return new Promise((_resolve, reject) => {
req.signal.addEventListener(
'abort',
() => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
{ once: true },
);
});
},
};
const client = restClient(sender, { retry: 3 });
const ac = new AbortController();
const p = client.post('/external', { q: 1 }, { signal: ac.signal });
// 等请求真的进了传输层再 abort,才是在模拟 queryFn signal 取消「在途」请求。
await started;
ac.abort();
await assert.rejects(p, (e) => e.code === 'CANCELLED');
assert.equal(attempts, 1, '取消不得触发重试');
});
// ---------------------------------------------------------------------------
// 4. signal 透传到传输层
// ---------------------------------------------------------------------------
test('FT-SIGNAL-001 transport=host 时 signal 透到 props.request(主壳 axios 入口)', async () => {
const seen = [];
const client = createClient({
kind: 'rest',
transport: 'host',
raw: true,
baseURL: 'https://api.test',
hostSend: async (req) => {
seen.push(req);
return { status: 200, data: 'ok' };
},
});
assert.equal((await client.post('/host', { a: 1 })).data, 'ok');
assert.ok(seen[0].signal, 'hostSend 必须收到 signal');
assert.equal(typeof seen[0].signal.addEventListener, 'function');
});
test('FT-SIGNAL-002 host 链路取消时,主壳拿到的 signal 真的被 abort', async () => {
let hostSignal;
let markStarted;
const started = new Promise((resolve) => { markStarted = resolve; });
setActiveScope('host-page');
const client = createClient({
kind: 'rest',
transport: 'host',
raw: true,
baseURL: 'https://api.test',
hostSend: (req) => new Promise((_resolve, reject) => {
hostSignal = req.signal;
markStarted();
req.signal?.addEventListener(
'abort',
() => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
{ once: true },
);
}),
});
const p = client.post('/host-abort', { a: 1 });
try {
await started;
assert.ok(hostSignal, '主壳应收到 signal');
cancelRequests('host-page');
assert.equal(hostSignal.aborted, true, 'signal 必须真的中止,axios 才会断连');
await assert.rejects(p, (e) => e.code === 'CANCELLED');
} finally {
setActiveScope(undefined);
}
});
test('FT-SIGNAL-003 createFetchSender 合并外部 signal 与超时 signal', async () => {
const { createFetchSender } = core;
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (_url, init) => {
captured = init;
return { status: 200, headers: { get: () => 'application/json' }, json: async () => ({ ok: 1 }) };
};
try {
const sender = createFetchSender();
const ac = new AbortController();
await sender.send({
method: 'POST', url: 'https://api.test/x', data: { a: 1 },
signal: ac.signal, timeout: 5000,
});
assert.ok(captured.signal, 'fetch 应收到合并后的 signal');
ac.abort();
assert.equal(captured.signal.aborted, true, '外部 abort 应联动到 fetch signal');
} finally {
globalThis.fetch = originalFetch;
}
});
/**
* @file glsx 系(老 SCRM)RPC 网关签名的真实抓包 golden 钉值测试。
*
* 2026-11-09 抓到的一次请求(method=scrm.api.shopmall.integralorder.all.page),
* 固定 timestamp 后可离线复算:sign=689F62277A050D6285B1E38BB2C3DA8D8E518EC9。
* 40 位 ⇒ SHA1(glsx-common/src/util.js#createSign 默认 way='sha1');此前 web points
* 误用 createSigner(MD5 只有 32 位)导致验签必挂。这份测试就是防回归闸门:
* 既钉死算法,也钉死「签名原文怎么拼」和端到端请求体。
*
* 凭据取自 temp/scrm-micro-points/src/config/env.development.js(与 strategy.test.mjs
* 同源,非新增密钥);抓包中的 sessionId 是一次性会话标识,仅作复算输入。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import test from 'node:test';
const require = createRequire(import.meta.url);
const {
createSigner,
registerGateway,
prepareRpcCall,
} = require('../dist/index.cjs');
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(HERE, '../../..');
const APP_KEY = '48e5e13229b82c1b4e6e8c96151f0637';
const SECRET = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b';
const TIMESTAMP = 1794222639246;
const GOLDEN_SIGN = '689F62277A050D6285B1E38BB2C3DA8D8E518EC9';
const SESSION_ID = 'scrm-base-8293b9c7-3a37-4074-a055-e383076d5aa2-rop';
const METHOD = 'scrm.api.shopmall.integralorder.all.page';
/** 抓包请求体中除 sign 外的 10 个字段(空串 settlementStatus 也参与签名)。 */
const CAPTURE = {
appKey: APP_KEY,
v: '1.0.0',
format: 'json',
source: 'scrm-home',
pageSize: 10,
currentPage: 1,
settlementStatus: '',
method: METHOD,
sessionId: SESSION_ID,
timestamp: TIMESTAMP,
};
/**
* 老系统的 createSign 收的是「整个请求体」;这里按同样形状把全量字段塞进 params,
* 系统字段再单独给一遍(同名覆盖为同值,签名原文不会重复拼接)。
*/
function signInput(params = { ...CAPTURE }) {
return {
method: METHOD,
params,
timestamp: TIMESTAMP,
appKey: APP_KEY,
secret: SECRET,
version: CAPTURE.v,
format: CAPTURE.format,
};
}
/** 从生产网关源码读出 fixedParams.source,保证测试用的渠道值与实际发出的一致。 */
function productionSource() {
const rel = 'apps/web/subapps/points/src/adapter/gateways/glsx.ts';
const src = readFileSync(path.join(ROOT, rel), 'utf8');
const matched = src.match(/fixedParams:\s*\{\s*source:\s*'([^']+)'\s*\}/);
assert.ok(matched, `${rel} 应显式声明 fixedParams.source`);
return matched[1];
}
test('IT-GLSX-SIGN-001 真实抓包复算命中 SHA1 golden(40 位大写)', async () => {
const fields = await createSigner().fields(signInput());
assert.equal(fields.sign, GOLDEN_SIGN, 'glsx 网关必须是 SHA1,不是 MD5');
assert.match(fields.sign, /^[0-9A-F]{40}$/, 'sign 必须是 40 位大写十六进制');
// 系统字段也回吐给 prepareRpcCall 并进请求体
assert.equal(fields.appKey, APP_KEY);
assert.equal(fields.format, CAPTURE.format);
assert.equal(fields.method, METHOD);
assert.equal(fields.timestamp, TIMESTAMP);
assert.equal(fields.v, CAPTURE.v);
});
test('IT-GLSX-SIGN-002 MD5 预设与 ROP SHA1 预设都不得命中(防误用回归)', async () => {
const md5 = await createSigner({ kind: 'md5' }).fields(signInput());
assert.match(md5.sign, /^[0-9A-F]{32}$/, 'MD5 只有 32 位');
assert.notEqual(md5.sign, GOLDEN_SIGN);
// mp ROP 的 createSigner 排除系统 timestamp;真实 mp 请求体里也没有 timestamp
// (老系统复刻用的 signInput 把 CAPTURE 全量塞进 params,这里要按 mp 的真实形状剔掉它)。
const mpParams = { ...CAPTURE };
delete mpParams.timestamp;
const rop = await createSigner({ kind: 'rop' }).fields(signInput(mpParams));
assert.notEqual(rop.sign, GOLDEN_SIGN, 'mp ROP 预设不含 timestamp,不能复用');
});
test('IT-GLSX-SIGN-003 端到端 prepareRpcCall 请求体 = 抓包 11 字段(含 sign)', async () => {
// source 参与签名,生产渠道值必须与抓包一致,否则整条 golden 就不成立
const source = productionSource();
assert.equal(source, CAPTURE.source, '生产网关 fixedParams.source 应与抓包一致');
registerGateway({
id: 'golden-shopmall',
router: 'rop-scrm-shopmall/router',
tokenHeader: 'token',
signer: createSigner({ id: 'golden-shopmall-sha1' }),
fixedParams: { source },
normalize: (raw) => ({ data: raw }),
});
const realNow = Date.now;
Date.now = () => TIMESTAMP;
try {
const raw = await prepareRpcCall(
{
gateway: 'golden-shopmall',
method: METHOD,
params: {
pageSize: CAPTURE.pageSize,
currentPage: CAPTURE.currentPage,
settlementStatus: CAPTURE.settlementStatus,
},
},
{
resolveCredential: () => ({
origin: 'http://gateway.test/',
appKey: APP_KEY,
secret: SECRET,
version: CAPTURE.v,
format: CAPTURE.format,
}),
// 会话标识由 facade.resolveSession 注入,签名前进请求体
session: { name: 'sessionId', value: SESSION_ID },
},
);
assert.equal(raw.url, 'http://gateway.test/rop-scrm-shopmall/router');
const body = raw.data;
const expected = { ...CAPTURE, sign: GOLDEN_SIGN };
assert.deepEqual(
Object.keys(body).sort(),
Object.keys(expected).sort(),
'请求体字段集应完全一致',
);
for (const [key, value] of Object.entries(expected)) {
assert.equal(String(body[key]), String(value), `字段 ${key} 应与抓包一致`);
}
} finally {
Date.now = realNow;
}
});
test('IT-GLSX-SIGN-004 points 网关源码不得回退到 MD5 预设或改动渠道值', () => {
const rel = 'apps/web/subapps/points/src/adapter/gateways/glsx.ts';
const file = path.join(ROOT, rel);
assert.ok(existsSync(file), `${rel} 应存在`);
const src = readFileSync(file, 'utf8');
assert.ok(/createSigner\(\s*\)/.test(src), `${rel} 必须用新版统一签名器且不传参(默认 glsx SHA1)`);
assert.equal(productionSource(), CAPTURE.source, '渠道值改动会让签名与老网关不一致');
assert.ok(!src.includes('createMd5Signer'), `${rel} 不得再用 MD5 旧预设`);
assert.ok(!src.includes("kind: 'md5'"), `${rel} 不得把签名器配成 MD5`);
assert.ok(!src.includes('glxsrMd5Signer'), `${rel} 不得残留旧导出名`);
});
...@@ -9,7 +9,7 @@ import { createRequire } from 'node:module'; ...@@ -9,7 +9,7 @@ import { createRequire } from 'node:module';
import test from 'node:test'; import test from 'node:test';
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
const { createLegacyRopClient, createSha1Signer } = require('../dist/index.cjs'); const { createLegacyRopClient, createSigner } = require('../dist/index.cjs');
const HOSTS = { scrm: 'https://scrm.test.glsx.com.cn', dj: 'https://dj.test.glsx.com.cn' }; const HOSTS = { scrm: 'https://scrm.test.glsx.com.cn', dj: 'https://dj.test.glsx.com.cn' };
const PATH_ENUM = { shopmall: '/rop-scrm-shopmall/' }; const PATH_ENUM = { shopmall: '/rop-scrm-shopmall/' };
...@@ -17,7 +17,7 @@ const DEFAULT_CRED = { appKey: '48e5e13229b82c1b4e6e8c96151f0637', secret: 'c246 ...@@ -17,7 +17,7 @@ const DEFAULT_CRED = { appKey: '48e5e13229b82c1b4e6e8c96151f0637', secret: 'c246
const DJ_CRED = { appKey: 'dj-appkey', secret: 'dj-secret' }; const DJ_CRED = { appKey: 'dj-appkey', secret: 'dj-secret' };
const SCrm_SHOPMALL_CRED = { appKey: 'shopmall-appkey', secret: 'shopmall-secret' }; const SCrm_SHOPMALL_CRED = { appKey: 'shopmall-appkey', secret: 'shopmall-secret' };
const signer = createSha1Signer({ id: 'test-sha1' }); const signer = createSigner({ kind: 'rop', id: 'test-sha1' });
const flatten = (obj) => { const flatten = (obj) => {
const out = {}; const out = {};
for (const [k, v] of Object.entries(obj)) { for (const [k, v] of Object.entries(obj)) {
......
/** /**
* @file createSdkSigner 与 glsx-common-sdk `request/helper.js#createSign` 的钉值对照。 * @file createSigner 与 glsx-common-sdk `request/helper.js#createSign` 的钉值对照。
* 输入是已摊平参数(SDK 内部用 qs 摊平,摊平发生在签名前),timestamp 固定以便复算。 * 输入是已摊平参数(SDK 内部用 qs 摊平,摊平发生在签名前),timestamp 固定以便复算。
*/ */
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
...@@ -7,7 +7,7 @@ import { createRequire } from 'node:module'; ...@@ -7,7 +7,7 @@ import { createRequire } from 'node:module';
import test from 'node:test'; import test from 'node:test';
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
const { createSdkSigner } = require('../dist/index.cjs'); const { createSigner } = require('../dist/index.cjs');
const TS = 1700000000000; const TS = 1700000000000;
const SECRET = 'test-secret'; const SECRET = 'test-secret';
...@@ -47,7 +47,7 @@ const expected = { ...@@ -47,7 +47,7 @@ const expected = {
for (const way of ['sha1', 'md5']) { for (const way of ['sha1', 'md5']) {
test(`IT-SDK-SIGN-${way.toUpperCase()} 与 SDK createSign 逐字节一致`, () => { test(`IT-SDK-SIGN-${way.toUpperCase()} 与 SDK createSign 逐字节一致`, () => {
const signer = createSdkSigner({ way }); const signer = createSigner({ kind: 'sdk', way });
vectors.forEach(([name, exclude, params], i) => { vectors.forEach(([name, exclude, params], i) => {
const fields = signer.fields(input(params, exclude)); const fields = signer.fields(input(params, exclude));
assert.equal(fields.timestamp, String(TS), `${name}: timestamp 进请求体且为字符串`); assert.equal(fields.timestamp, String(TS), `${name}: timestamp 进请求体且为字符串`);
...@@ -57,13 +57,13 @@ for (const way of ['sha1', 'md5']) { ...@@ -57,13 +57,13 @@ for (const way of ['sha1', 'md5']) {
} }
test('IT-SDK-SIGN-003 sign 键被剔除,timestamp 不参与 noSignAttr', () => { test('IT-SDK-SIGN-003 sign 键被剔除,timestamp 不参与 noSignAttr', () => {
const signer = createSdkSigner(); const signer = createSigner({ kind: 'sdk' });
const withSign = signer.fields(input({ method: 'x', sign: 'stale', appKey: 'k' })); const withSign = signer.fields(input({ method: 'x', sign: 'stale', appKey: 'k' }));
const withoutSign = signer.fields(input({ method: 'x', appKey: 'k' })); const withoutSign = signer.fields(input({ method: 'x', appKey: 'k' }));
assert.equal(withSign.sign, withoutSign.sign); assert.equal(withSign.sign, withoutSign.sign);
}); });
test('IT-SDK-SIGN-004 输出仅含 timestamp 与 sign(其余参数由请求体自带)', () => { test('IT-SDK-SIGN-004 输出仅含 timestamp 与 sign(其余参数由请求体自带)', () => {
const fields = createSdkSigner().fields(input({ method: 'x', appKey: 'k' })); const fields = createSigner({ kind: 'sdk' }).fields(input({ method: 'x', appKey: 'k' }));
assert.deepEqual(Object.keys(fields).sort(), ['sign', 'timestamp']); assert.deepEqual(Object.keys(fields).sort(), ['sign', 'timestamp']);
}); });
/** /**
* 方案策略 / 签名策略注册表的钉值测试。 * 方案策略 / 签名策略注册表的钉值测试。
* *
* 关注点:门面只做委托,策略自带默认语义;消费层用 strategies.xxx({...}) 只传环境参数。 * 关注点:门面只做委托,策略自带默认语义;消费层用 createStrategy.xxx({...}) 只传环境参数。
* 同时守住「逐字节兼容」:内置 rop-sha1 必须与 points 旧 getData 的签名完全一致。 * 同时守住「逐字节兼容」:内置 rop-sha1 必须与 points 旧 getData 的签名完全一致。
*/ */
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
...@@ -16,8 +16,8 @@ const core = require('../dist/index.cjs'); ...@@ -16,8 +16,8 @@ const core = require('../dist/index.cjs');
const { const {
Request, Request,
createRequest, createRequest,
strategies, createStrategy,
createSha1Signer, createSigner,
RequestError, RequestError,
registerGateway, registerGateway,
prepareRpcCall, prepareRpcCall,
...@@ -43,8 +43,8 @@ function makeSender(responder) { ...@@ -43,8 +43,8 @@ function makeSender(responder) {
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
test('ST-REG-001 内置方案与签名策略都已注册', () => { test('ST-REG-001 内置方案与签名策略都已注册', () => {
assert.deepEqual(strategies.request.list(), ['plain', 'rop', 'gsc', 'web-host', 'rpc-gateway']); assert.deepEqual(createStrategy.list(), ['plain', 'rop', 'gsc', 'web-host', 'rpc-gateway']);
assert.deepEqual(strategies.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',
]); ]);
}); });
...@@ -55,14 +55,14 @@ test('ST-REG-002 未知策略名明确报错,不悄悄退化', () => { ...@@ -55,14 +55,14 @@ test('ST-REG-002 未知策略名明确报错,不悄悄退化', () => {
/未知的网关方案策略/, /未知的网关方案策略/,
); );
assert.throws( assert.throws(
() => strategies.signature.resolve('not-exist'), () => 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(() => ({ status: 200, data: { errcode: 0, data: { ok: 1 } } }));
strategies.request.register(strategies.request.define({ 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) {
...@@ -87,12 +87,11 @@ test('ST-REG-003 自定义方案策略:注册后按名字使用,门面只做 ...@@ -87,12 +87,11 @@ test('ST-REG-003 自定义方案策略:注册后按名字使用,门面只做
test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名字', async () => { test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名字', async () => {
const { calls, sender } = makeSender(); const { calls, sender } = makeSender();
strategies.signature.register('demo-sign', { createStrategy.signature.register('demo-sign', {
bodySign: (params, secret) => ({ ...params, sign: `demo:${secret}` }), bodySign: (params, secret) => ({ ...params, sign: `demo:${secret}` }),
}); });
const api = new Request(strategies.rop({ const api = new Request(createStrategy({ kind: 'rop', sender,
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',
...@@ -110,8 +109,7 @@ test('ST-REG-004 自定义签名策略:实现注册一次,装配层只写名 ...@@ -110,8 +109,7 @@ 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 = strategies.rop({ const config = createStrategy({ kind: 'rop', sender,
sender,
hosts: { scrm: 'https://api.test' }, hosts: { scrm: 'https://api.test' },
signature: 'none', signature: 'none',
loginReplay: true, loginReplay: true,
...@@ -139,8 +137,7 @@ test('ST-PRESET-006 legacyEnvelope:成功返回完整信封,其它业务码 ...@@ -139,8 +137,7 @@ 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 = strategies.rop({ const config = createStrategy({ kind: 'rop', sender,
sender,
hosts: { scrm: 'https://api.test' }, hosts: { scrm: 'https://api.test' },
legacyEnvelope: true, legacyEnvelope: true,
response: { toastOnOtherCodes: ['-1'] }, response: { toastOnOtherCodes: ['-1'] },
...@@ -164,8 +161,7 @@ test('ST-PRESET-007 webHost 预设:ApiResult 信封 / 401 登出 / 业务错 ...@@ -164,8 +161,7 @@ test('ST-PRESET-007 webHost 预设:ApiResult 信封 / 401 登出 / 业务错
? { status: 200, data: { code: 500, message: '库存不足', data: { sku: 9 } }, 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' } }, : { status: 200, data: { code: 200, message: 'ok', data: { list: [1, 2] } }, headers: { 'content-type': 'application/json' } },
); );
const api = new Request(strategies.webHost({ const api = new Request(createStrategy({ kind: 'web-host', sender,
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) },
...@@ -193,7 +189,7 @@ test('ST-PRESET-007 webHost 预设:ApiResult 信封 / 401 登出 / 业务错 ...@@ -193,7 +189,7 @@ test('ST-PRESET-007 webHost 预设:ApiResult 信封 / 401 登出 / 业务错
test('ST-PRESET-008 rest 预设极简:只选 plain,其余走门面默认', async () => { test('ST-PRESET-008 rest 预设极简:只选 plain,其余走门面默认', async () => {
const { calls, sender } = makeSender(() => ({ status: 200, data: { id: 3 } })); const { calls, sender } = makeSender(() => ({ status: 200, data: { id: 3 } }));
const config = strategies.rest({ sender, baseURL: 'https://api.test' }); const config = createStrategy({ kind: 'rest', sender, baseURL: 'https://api.test' });
assert.equal(config.strategy, 'plain'); assert.equal(config.strategy, 'plain');
const res = await new Request(config).get('/users/3'); const res = await new Request(config).get('/users/3');
...@@ -217,9 +213,9 @@ test('ST-PRESET-009 显式 strategy 覆盖自动推断', async () => { ...@@ -217,9 +213,9 @@ test('ST-PRESET-009 显式 strategy 覆盖自动推断', async () => {
test('ST-PRESET-010 三种方案共用同一条响应归一 pipeline', async () => { test('ST-PRESET-010 三种方案共用同一条响应归一 pipeline', async () => {
const { sender } = makeSender(() => ({ status: 200, data: { code: '0', data: { same: true } } })); const { sender } = makeSender(() => ({ status: 200, data: { code: '0', data: { same: true } } }));
for (const [name, config] of [ for (const [name, config] of [
['rop', strategies.rop({ sender, hosts: { scrm: 'https://api.test' } })], ['rop', createStrategy({ kind: 'rop', sender, hosts: { scrm: 'https://api.test' } })],
['gsc', strategies.gsc({ sender, baseURL: 'https://api.test' })], ['gsc', createStrategy({ kind: 'gsc', sender, baseURL: 'https://api.test' })],
['plain', strategies.rest({ sender, baseURL: 'https://api.test' })], ['plain', createStrategy({ kind: 'rest', sender, baseURL: 'https://api.test' })],
]) { ]) {
const res = await new Request(config).post('/x', {}); const res = await new Request(config).post('/x', {});
assert.deepEqual(res, { same: true }, `${name} 应同样剔包`); assert.deepEqual(res, { same: true }, `${name} 应同样剔包`);
...@@ -233,7 +229,7 @@ test('ST-PRESET-010 三种方案共用同一条响应归一 pipeline', async () ...@@ -233,7 +229,7 @@ test('ST-PRESET-010 三种方案共用同一条响应归一 pipeline', async ()
test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致', async () => { test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致', async () => {
const APP_KEY = '48e5e13229b82c1b4e6e8c96151f0637'; const APP_KEY = '48e5e13229b82c1b4e6e8c96151f0637';
const SECRET = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b'; const SECRET = 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b';
const oldSigner = createSha1Signer({ 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, appKey: params.appKey, secret,
...@@ -241,7 +237,7 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致 ...@@ -241,7 +237,7 @@ test('ST-COMPAT-011 内置 rop-sha1 与 points 旧 getData 签名逐字节一致
}); });
return { ...params, sign: signed.sign }; return { ...params, sign: signed.sign };
}; };
const builtin = strategies.signature.resolve('rop-sha1'); const builtin = createStrategy.signature.resolve('rop-sha1');
assert.equal(builtin.id, 'rop-sha1'); assert.equal(builtin.id, 'rop-sha1');
const cases = [ const cases = [
...@@ -285,7 +281,7 @@ test('ST-COMPAT-013 @uj/api-core/Request 子路径与主入口是同一个 bundl ...@@ -285,7 +281,7 @@ test('ST-COMPAT-013 @uj/api-core/Request 子路径与主入口是同一个 bundl
assert.equal(sub.import, './dist/index.js'); assert.equal(sub.import, './dist/index.js');
assert.equal(sub.require, './dist/index.cjs'); assert.equal(sub.require, './dist/index.cjs');
assert.equal(core.default, Request); assert.equal(core.default, Request);
assert.equal(typeof core.strategies.rop, 'function'); assert.equal(typeof core.createStrategy, 'function');
}); });
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
...@@ -336,17 +332,17 @@ const rpcDeps = { resolveCredential: rpcCredential, resolveToken: rpcToken, time ...@@ -336,17 +332,17 @@ const rpcDeps = { resolveCredential: rpcCredential, resolveToken: rpcToken, time
function makeRpcApi(extra = {}) { function makeRpcApi(extra = {}) {
const { calls, sender } = makeEnvelopeSender(); const { calls, sender } = makeEnvelopeSender();
const api = new Request(strategies.rpcGateway({ const api = new Request(createStrategy({ sender, gatewayCredential: rpcCredential, gatewayToken: rpcToken,
sender, gatewayCredential: rpcCredential, gatewayToken: rpcToken,
timeout: 180000, contentType: false, ...extra, timeout: 180000, contentType: false, ...extra,
})); }));
return { calls, sender, api }; return { calls, sender, api };
} }
test('ST-RPC-001 strategies.rpcGateway 是可直接使用的内置方案预设', () => { test('ST-RPC-001 createStrategy 不传参即默认最新版 rpc-gateway 方案', () => {
assert.equal(typeof strategies.rpcGateway, 'function'); assert.equal(typeof createStrategy, 'function');
assert.ok(strategies.request.list().includes('rpc-gateway')); assert.equal(typeof core.createStrategy, 'function');
assert.equal(typeof core.rpcGatewayPreset, 'function'); assert.equal(createStrategy().strategy, 'rpc-gateway');
assert.ok(createStrategy.list().includes('rpc-gateway'));
}); });
test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/令牌/信封全由网关策略决定', async () => { test('ST-RPC-002 消费层只传 gateway + 方法名 + 参数:落点/加签/令牌/信封全由网关策略决定', async () => {
...@@ -444,8 +440,7 @@ test('ST-RPC-006 真实双层门面:rpcGateway → host sender → 主壳归 ...@@ -444,8 +440,7 @@ 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(strategies.rpcGateway({ const api = new Request(createStrategy({ transport: 'host', hostSend,
transport: 'host', hostSend,
gatewayCredential: rpcCredential, gatewayToken: rpcToken, gatewayCredential: rpcCredential, gatewayToken: rpcToken,
timeout: 180000, contentType: false, timeout: 180000, contentType: false,
})); }));
...@@ -463,8 +458,7 @@ test('ST-RPC-006 真实双层门面:rpcGateway → host sender → 主壳归 ...@@ -463,8 +458,7 @@ test('ST-RPC-006 真实双层门面:rpcGateway → host sender → 主壳归
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(strategies.rpcGateway({ const api = new Request(createStrategy({ sender, gatewayCredential: rpcCredential,
sender, gatewayCredential: rpcCredential,
errorHandler: (err) => { errorHandler: (err) => {
seen = err; seen = err;
return { handled: true, code: err.code }; return { handled: true, code: err.code };
......
...@@ -39,12 +39,18 @@ const shared = { ...@@ -39,12 +39,18 @@ const shared = {
export default defineConfig([ export default defineConfig([
{ {
...shared, ...shared,
// 只打一个自包含 bundle:子路径 `@uj/api-core/Request` 在 package.json 里别名到同一产物, // 主入口 + legacy 兼容入口。子路径 `@uj/api-core/Request` 仍别名到 index 产物,
// 保证 Request 类全局唯一(多入口会各自内联一份,导致 instanceof / 引用比较失效)。 // 保证主链路的 Request 类全局唯一;legacy 是独立 bundle,仅服务仓外旧代码,
// 不与主入口混用注册表(见 src/legacy.ts 注释)。
entry: ['src/index.ts', 'src/legacy.ts'],
format: ['cjs', 'esm'], format: ['cjs', 'esm'],
dts: true, dts: true,
clean: true, clean: true,
sourcemap: true, sourcemap: true,
// 关掉 ESM 的跨入口 chunk 共享:否则 legacy 在 CJS 下自成一份注册表、在 ESM 下
// 却与主入口共用同一份,「能不能混着注册」会随导入格式变。统一成各自独立、
// 与 src/legacy.ts 的注释一致;取消注册表走 globalThis Symbol.for,不受影响。
splitting: false,
outDir: 'dist', outDir: 'dist',
}, },
{ {
......
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
}, },
{ {
"group": "门店上架", "group": "门店上架",
"icon": "HomeOutlined",
"children": [ "children": [
{ {
"path": "/store/import", "path": "/store/import",
...@@ -37,6 +38,7 @@ ...@@ -37,6 +38,7 @@
}, },
{ {
"group": "系统设置", "group": "系统设置",
"icon": "SettingOutlined",
"children": [ "children": [
{ {
"path": "/system/role", "path": "/system/role",
......
...@@ -20,3 +20,10 @@ export function busEvents(shortName: string) { ...@@ -20,3 +20,10 @@ export function busEvents(shortName: string) {
} }
export type BusEvents = ReturnType<typeof busEvents>; export type BusEvents = ReturnType<typeof busEvents>;
/**
* 全局「离开当前页面」广播(不带 shortName 前缀):主壳切菜单时发出,
* 所有 alive 保活的子应用都要取消自己上一页的在途请求。
* 子应用内部换页仍走各 name 的 events.navigate,由 SubAppLifecycle 单独处理。
*/
export const PAGE_LEAVE_EVENT = 'uj:page-leave';
...@@ -16,6 +16,8 @@ export interface RemoteRequest { ...@@ -16,6 +16,8 @@ export interface RemoteRequest {
responseType?: 'json' | 'blob' | 'arraybuffer' | 'text'; responseType?: 'json' | 'blob' | 'arraybuffer' | 'text';
transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>; transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>;
_noVerify?: boolean; _noVerify?: boolean;
/** 中止信号:wujie props 是同源引用传递,可原样跨到主壳 axios(不走 postMessage 序列化)。 */
signal?: AbortSignal;
[key: string]: unknown; [key: string]: unknown;
} }
......
...@@ -17,6 +17,8 @@ export const palette = { ...@@ -17,6 +17,8 @@ export const palette = {
primarySoft: '#EEF3FF', primarySoft: '#EEF3FF',
deep1: '#0B1437', deep1: '#0B1437',
deep2: '#16245A', deep2: '#16245A',
/** 品牌亮色:深色底(Sider / 登录左栏)上的品牌点缀,primary 的同族提亮档 */
light: '#5B8DEF',
}, },
/** 表面四层:页面底 / 卡片 / 表头 / hover。卡片之间的层级差主要来自这里,不靠加边框。 */ /** 表面四层:页面底 / 卡片 / 表头 / hover。卡片之间的层级差主要来自这里,不靠加边框。 */
surface: { surface: {
...@@ -64,11 +66,11 @@ export const palette = { ...@@ -64,11 +66,11 @@ export const palette = {
} as const; } as const;
export const radius = { export const radius = {
xs: 4, xs: 3,
sm: 6, sm: 4,
md: 8, md: 6,
lg: 10, lg: 8,
card: 12, card: 10,
pill: 999, pill: 999,
} as const; } as const;
...@@ -81,8 +83,9 @@ export const control = { ...@@ -81,8 +83,9 @@ export const control = {
} as const; } as const;
export const shadow = { export const shadow = {
/** 与 tokens.css 的 --uj-shadow-* 同值,对账脚本会校验。 */ /** 与 tokens.css 的 --uj-shadow-* 同值,对账脚本会校验。
card: '0 1px 2px rgba(16, 24, 40, 0.04), 0 8px 24px -10px rgba(16, 24, 40, 0.12)', * 收干脆:短投射 + 低扩散,卡片「贴」在页面上而不是「漂」在页面上。 */
raise: '0 2px 4px rgba(16, 24, 40, 0.05), 0 16px 32px -14px rgba(16, 24, 40, 0.2)', card: '0 1px 2px rgba(16, 24, 40, 0.05), 0 2px 6px -2px rgba(16, 24, 40, 0.08)',
pop: '0 12px 40px -12px rgba(16, 24, 40, 0.2)', raise: '0 2px 4px rgba(16, 24, 40, 0.06), 0 8px 20px -12px rgba(16, 24, 40, 0.18)',
pop: '0 8px 28px -10px rgba(16, 24, 40, 0.24)',
} as const; } as const;
...@@ -86,7 +86,7 @@ export const themeConfig: ThemeConfig = { ...@@ -86,7 +86,7 @@ export const themeConfig: ThemeConfig = {
components: { components: {
Layout: { Layout: {
headerBg: '#FFFFFF', headerBg: '#FFFFFF',
headerHeight: 60, headerHeight: 56,
headerPadding: '0 20px', headerPadding: '0 20px',
siderBg: 'transparent', siderBg: 'transparent',
bodyBg: palette.surface.page, bodyBg: palette.surface.page,
...@@ -102,13 +102,13 @@ export const themeConfig: ThemeConfig = { ...@@ -102,13 +102,13 @@ export const themeConfig: ThemeConfig = {
darkItemSelectedColor: '#FFFFFF', darkItemSelectedColor: '#FFFFFF',
darkGroupTitleColor: 'rgba(255,255,255,.32)', darkGroupTitleColor: 'rgba(255,255,255,.32)',
// 折叠态弹出的子菜单底:与 .uj-sider 中段色一致,避免弹出层露出 antd 默认的深蓝黑 // 折叠态弹出的子菜单底:与 .uj-sider 中段色一致,避免弹出层露出 antd 默认的深蓝黑
darkPopupBg: '#111B3D', darkPopupBg: '#14204E',
// —— 几何:全部走 token,不在 design.css 里用 CSS 覆盖组件内部盒模型 —— // —— 几何:全部走 token,不在 design.css 里用 CSS 覆盖组件内部盒模型 ——
// antd 会用 itemMarginInline 参与折叠态居中计算(paddingInline: calc(50% - 图标宽/2 - itemMarginInline)), // antd 会用 itemMarginInline 参与折叠态居中计算(paddingInline: calc(50% - 图标宽/2 - itemMarginInline)),
// 所以「胶囊左右留白」必须由这个 token 给,不能用 CSS margin 顶替。 // 所以「胶囊左右留白」必须由这个 token 给,不能用 CSS margin 顶替。
itemMarginInline: 10, itemMarginInline: 8,
itemBorderRadius: 10, itemBorderRadius: 6,
itemHeight: 44, itemHeight: 40,
iconSize: 15, iconSize: 15,
groupTitleFontSize: 10.5, groupTitleFontSize: 10.5,
// 必须与 <Sider collapsedWidth={68}> 保持一致:Menu 折叠态有自己的 collapsedWidth, // 必须与 <Sider collapsedWidth={68}> 保持一致:Menu 折叠态有自己的 collapsedWidth,
...@@ -117,17 +117,18 @@ export const themeConfig: ThemeConfig = { ...@@ -117,17 +117,18 @@ export const themeConfig: ThemeConfig = {
}, },
Card: { Card: {
borderRadiusLG: radius.card, borderRadiusLG: radius.card,
// 卡片靠「浅底 + 无描边 + 柔影」成立;再叠一圈 #e2e8f0 的实描边是原来越来越「硬」的根因。 // 卡片描边取 border(不是 divider):1px 实线勾边 + 干脆短影,边界「立得住」,
colorBorderSecondary: palette.line.divider, // 这是「质感」的来源 —— 全靠柔影分层会显得又软又飘。
colorBorderSecondary: palette.line.border,
headerBg: 'transparent', headerBg: 'transparent',
headerHeight: 48, headerHeight: 44,
headerHeightSM: 40, headerHeightSM: 40,
headerPadding: 14, headerPadding: 12,
headerPaddingSM: 10, headerPaddingSM: 10,
headerFontSize: 15, headerFontSize: 15,
headerFontSizeSM: 14, headerFontSizeSM: 14,
bodyPadding: 20, bodyPadding: 16,
bodyPaddingSM: 16, bodyPaddingSM: 14,
actionsBg: palette.surface.raised, actionsBg: palette.surface.raised,
}, },
Button: { Button: {
...@@ -160,7 +161,7 @@ export const themeConfig: ThemeConfig = { ...@@ -160,7 +161,7 @@ export const themeConfig: ThemeConfig = {
rowHoverBg: palette.surface.raised, rowHoverBg: palette.surface.raised,
rowSelectedBg: palette.soft.info, rowSelectedBg: palette.soft.info,
rowSelectedHoverBg: '#E4ECFD', rowSelectedHoverBg: '#E4ECFD',
cellPaddingBlockMD: 11, cellPaddingBlockMD: 10,
// 左右留白取 antd 的 middle 默认值 16,不再追「与卡片 20px 对齐」: // 左右留白取 antd 的 middle 默认值 16,不再追「与卡片 20px 对齐」:
// 20px 会把 90~110px 的窄列挤到内容宽不足 4 个汉字, // 20px 会把 90~110px 的窄列挤到内容宽不足 4 个汉字,
// 表头「变更次数」这类四字标题就换行,整行表头被撑成两倍高。 // 表头「变更次数」这类四字标题就换行,整行表头被撑成两倍高。
...@@ -192,7 +193,7 @@ export const themeConfig: ThemeConfig = { ...@@ -192,7 +193,7 @@ export const themeConfig: ThemeConfig = {
fontSize: 13, fontSize: 13,
}, },
Form: { Form: {
itemMarginBottom: 18, itemMarginBottom: 16,
verticalLabelPadding: '0 0 6px', verticalLabelPadding: '0 0 6px',
labelColor: palette.text.secondary, labelColor: palette.text.secondary,
labelFontSize: 13, labelFontSize: 13,
...@@ -234,11 +235,12 @@ export const themeConfig: ThemeConfig = { ...@@ -234,11 +235,12 @@ export const themeConfig: ThemeConfig = {
colorBgElevated: palette.surface.base, colorBgElevated: palette.surface.base,
}, },
Tabs: { Tabs: {
horizontalItemPadding: '10px 16px', horizontalItemPadding: '7px 16px',
horizontalMargin: '0 0 16px', horizontalMargin: '0',
itemColor: palette.text.secondary, itemColor: palette.text.secondary,
itemSelectedColor: palette.brand.primary, // 滑动药丸风格:激活标签落在主色滑块上,文字反白;hover 只是加深,不走主色。
itemHoverColor: palette.brand.primary, itemSelectedColor: palette.surface.onPrimary,
itemHoverColor: palette.text.primary,
inkBarColor: palette.brand.primary, inkBarColor: palette.brand.primary,
titleFontSize: 14, titleFontSize: 14,
cardBg: palette.surface.raised, cardBg: palette.surface.raised,
......
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
--uj-primary-soft: #eef3ff; /* 选中底、图标容器这类「品牌色但要淡」 */ --uj-primary-soft: #eef3ff; /* 选中底、图标容器这类「品牌色但要淡」 */
--uj-brand-1: #0b1437; --uj-brand-1: #0b1437;
--uj-brand-2: #16245a; --uj-brand-2: #16245a;
--uj-brand-light: #5b8def; /* 深色底(Sider / 登录左栏)上的品牌点缀 */
/* ---- 表面:四层递进,卡片不再靠「加个边框」区分自己 ---- */ /* ---- 表面:四层递进,卡片不再靠「加个边框」区分自己 ---- */
--uj-bg: #f4f6fa; /* 页面底 */ --uj-bg: #f4f6fa; /* 页面底 */
...@@ -61,10 +62,10 @@ ...@@ -61,10 +62,10 @@
--uj-neutral-soft: #f2f4f8; --uj-neutral-soft: #f2f4f8;
--uj-neutral-border: #e4e8ef; --uj-neutral-border: #e4e8ef;
/* ---- 高度:两级静置 + 一级抬起(hover)+ 浮层 ---- */ /* ---- 高度:两级静置 + 一级抬起(hover)+ 浮层。短投射、低扩散,干脆不飘 ---- */
--uj-shadow-card: 0 1px 2px rgba(16, 24, 40, 0.04), 0 8px 24px -10px rgba(16, 24, 40, 0.12); --uj-shadow-card: 0 1px 2px rgba(16, 24, 40, 0.05), 0 2px 6px -2px rgba(16, 24, 40, 0.08);
--uj-shadow-raise: 0 2px 4px rgba(16, 24, 40, 0.05), 0 16px 32px -14px rgba(16, 24, 40, 0.2); --uj-shadow-raise: 0 2px 4px rgba(16, 24, 40, 0.06), 0 8px 20px -12px rgba(16, 24, 40, 0.18);
--uj-shadow-pop: 0 12px 40px -12px rgba(16, 24, 40, 0.2); --uj-shadow-pop: 0 8px 28px -10px rgba(16, 24, 40, 0.24);
/* 聚焦环:控件 focus 一律用它,不要各自写 box-shadow 调 alpha */ /* 聚焦环:控件 focus 一律用它,不要各自写 box-shadow 调 alpha */
--uj-ring: 0 0 0 3px rgba(43, 92, 230, 0.14); --uj-ring: 0 0 0 3px rgba(43, 92, 230, 0.14);
...@@ -77,13 +78,18 @@ ...@@ -77,13 +78,18 @@
--uj-space-6: 24px; --uj-space-6: 24px;
--uj-space-8: 32px; --uj-space-8: 32px;
/* ---- 圆角:卡片走 lg、控件走 md、标签走 sm;pill 只给胶囊态控件 ---- */ /* ---- 模块间距(统一值):页面里「卡片 ↔ 卡片」「区块 ↔ 区块」的纵向间隔。
--uj-radius-xs: 4px; 整站模块间距一律用它,不再出现 16/18/20/22/24 各写各的;上限就是 10px。 ---- */
--uj-radius-sm: 6px; --uj-space-module: 10px;
--uj-radius-md: 8px;
--uj-radius-lg: 10px; /* ---- 圆角:整体收紧一档(企业级要「利落」不要「圆润」)。
--uj-radius-card: 12px; 卡片走 card、控件走 md、标签走 sm;pill 只给胶囊态控件 ---- */
--uj-radius-pill: 999px; --uj-radius-xs: 3px;
--uj-radius-sm: 4px;
--uj-radius-md: 6px;
--uj-radius-lg: 8px;
--uj-radius-card: 10px;
--uj-radius-pill: 6px;
/* ---- 字号:正文 14 是基准,向下只留 13/12 两级说明,不出现 12.5 这种值 ---- */ /* ---- 字号:正文 14 是基准,向下只留 13/12 两级说明,不出现 12.5 这种值 ---- */
--uj-font-xs: 12px; --uj-font-xs: 12px;
......
...@@ -33,6 +33,12 @@ export interface MenuGroupDef { ...@@ -33,6 +33,12 @@ export interface MenuGroupDef {
group: string; group: string;
children: MenuItemDef[]; children: MenuItemDef[];
/** /**
* 一级菜单(产品分组节点)自己的图标名,取自后端 nodeType=1 的 node.icon。
* 为 null/未登记时由渲染层回落「首个子项图标」——那会让一级图标跟着二级排序变,
* 所以给一级菜单定图标请在后端节点上登记,别指望子项。
*/
icon?: string | null;
/**
* true:不渲染分组标题,children 直接平铺为该层级的菜单项。 * true:不渲染分组标题,children 直接平铺为该层级的菜单项。
* 用于「工作台」这类只有一个入口的分组——挂一个独占一行的标题纯属噪音。 * 用于「工作台」这类只有一个入口的分组——挂一个独占一行的标题纯属噪音。
* 后端菜单树不会下发该字段,仅由前端固定组与兜底 menu.json 标注意图。 * 后端菜单树不会下发该字段,仅由前端固定组与兜底 menu.json 标注意图。
...@@ -53,6 +59,7 @@ export interface MenuGroupDef { ...@@ -53,6 +59,7 @@ export interface MenuGroupDef {
* - 只取 nodeType 1(分组)下的 nodeType 2(页面);nodeType 3 是按钮操作点,不进菜单。 * - 只取 nodeType 1(分组)下的 nodeType 2(页面);nodeType 3 是按钮操作点,不进菜单。
* - status !== 1(停用)的节点丢弃。 * - status !== 1(停用)的节点丢弃。
* - path 与 icon 直接取自后端下发的 node.route / node.icon,前端不再做映射。 * - path 与 icon 直接取自后端下发的 node.route / node.icon,前端不再做映射。
* 一级(分组)图标取 nodeType=1 节点自己的 icon,与二级同用一套图标名。
* - permCode 与当前账号持有的权限点取交集(/current 后端已按角色过滤,这里作双保险再过滤一次)。 * - permCode 与当前账号持有的权限点取交集(/current 后端已按角色过滤,这里作双保险再过滤一次)。
* - node.route 缺失 → 跳过并告警(点了会 404,不应渲染)。 * - node.route 缺失 → 跳过并告警(点了会 404,不应渲染)。
* - 分组/页面均按 sort 升序。 * - 分组/页面均按 sort 升序。
...@@ -115,7 +122,7 @@ export function buildMenus( ...@@ -115,7 +122,7 @@ export function buildMenus(
} }
children.push({ path, label: n.label, icon: n.icon ?? null, resource }); children.push({ path, label: n.label, icon: n.icon ?? null, resource });
}); });
if (children.length) groups.push({ group: g.label, children }); if (children.length) groups.push({ group: g.label, icon: g.icon ?? null, children });
}); });
return groups; return groups;
......
...@@ -10,6 +10,12 @@ export interface LoginSession { ...@@ -10,6 +10,12 @@ export interface LoginSession {
dataScope: number; dataScope: number;
roleCodes: string[]; roleCodes: string[];
permCodes: string[]; permCodes: string[];
/**
* 老网关会话标识(形如 scrm-base-<uuid>-rop)。
* 优加主壳后端不用它,但积分核销等老 RPC 网关(glsx/scrm)把它作为 sessionId 放进请求体并参与加签。
* 登录接口返回后由登录流程写入此处,子应用通过 getLoginSession() 读取。
*/
loginToken?: string;
} }
const SESSION_KEY = 'session'; const SESSION_KEY = 'session';
......
// 统一 HTTP 客户端(web 主壳唯一出口) // 统一 HTTP 客户端(web 主壳唯一出口)
// //
// 这里是 **@uj/api-core 客户端工厂** 的装配点:一个 createWebHostClient({配置}) 拿到 client, // 这里是 **@uj/api-core 客户端工厂** 的装配点:一个 createClient({ kind: 'web-host', 配置}) 拿到 client,
// 只传环境参数 → sender(axios) / baseURL / contextPath / RSA 签名器 / 验签器 / 无损解析器 / 登出回调。 // 只传环境参数 → sender(axios) / baseURL / contextPath / RSA 签名器 / 验签器 / 无损解析器 / 登出回调。
// 方案(webHost)与签名(rsa)由工厂在 api-core 内选好,平台、URL 拼装、业务码归一、 // 方案(webHost)与签名(rsa)由工厂在 api-core 内选好,平台、URL 拼装、业务码归一、
// 错误处理的实现都不在这里,与四个小程序完全同一套门面与策略注册表。 // 错误处理的实现都不在这里,与四个小程序完全同一套门面与策略注册表。
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'; import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';
import { message } from 'antd'; import { message } from 'antd';
import { createWebHostClient, defineSignatureStrategy } from '@uj/api-core'; import { createClient, createStrategy } from '@uj/api-core';
import type { import type {
HeaderSignInput, HeaderSignInput,
HeaderSigner, HeaderSigner,
...@@ -66,6 +66,8 @@ const sender: RequestSender = { ...@@ -66,6 +66,8 @@ const sender: RequestSender = {
timeout: req.timeout, timeout: req.timeout,
responseType: req.responseType as AxiosRequestConfig['responseType'], responseType: req.responseType as AxiosRequestConfig['responseType'],
withCredentials: req.withCredentials === true, withCredentials: req.withCredentials === true,
// 子应用门面创建的 signal 经 props.request 原样传到这里,axios 收到 abort 会真正中断连接。
signal: req.signal,
// transformResponse 由门面统一执行(验签需要原始串),传输层保持恒等。 // transformResponse 由门面统一执行(验签需要原始串),传输层保持恒等。
transformResponse: [(raw: unknown) => raw], transformResponse: [(raw: unknown) => raw],
}); });
...@@ -111,7 +113,7 @@ const signer: HeaderSigner = { ...@@ -111,7 +113,7 @@ const signer: HeaderSigner = {
}; };
// RSA 与小程序 sha1 签名器地位对等:作为一份签名策略直接传给工厂,不需要全局注册名字。 // RSA 与小程序 sha1 签名器地位对等:作为一份签名策略直接传给工厂,不需要全局注册名字。
const rsaSignature = defineSignatureStrategy('rsa', { headerSigner: signer }); const rsaSignature = createStrategy.signature.define('rsa', { headerSigner: signer });
// ---------- 令牌失效(401)的上层处理回调 ---------- // ---------- 令牌失效(401)的上层处理回调 ----------
// http 属于基础设施层,不应反向依赖 store / 路由。 // http 属于基础设施层,不应反向依赖 store / 路由。
...@@ -132,7 +134,8 @@ export function setUnauthorizedHandler(fn: UnauthorizedHandler) { ...@@ -132,7 +134,8 @@ export function setUnauthorizedHandler(fn: UnauthorizedHandler) {
// 工厂装配:全项目唯一一份 web 请求引擎 // 工厂装配:全项目唯一一份 web 请求引擎
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
const client = createWebHostClient({ const client = createClient({
kind: 'web-host',
sender, sender,
baseURL: SIGN_CONFIG.BASE_URL, baseURL: SIGN_CONFIG.BASE_URL,
// 后端统一 context-path:同时进线上 URL 与 canonical 第 2 行,二者因此永远一致。 // 后端统一 context-path:同时进线上 URL 与 canonical 第 2 行,二者因此永远一致。
...@@ -178,8 +181,13 @@ interface HostRequestConfig extends Record<string, unknown> { ...@@ -178,8 +181,13 @@ interface HostRequestConfig extends Record<string, unknown> {
_noVerify?: boolean; _noVerify?: boolean;
timeout?: number; timeout?: number;
withCredentials?: boolean; withCredentials?: boolean;
/** 子应用侧请求的中止信号(由 api-core 门面创建,跨 props.request 引用传递)。 */
signal?: AbortSignal;
} }
/** 主壳侧也暴露统一取消 API:切菜单 / 登出时由 shell 调用。 */
export { cancelRequests, setActiveScope, getActiveScope, activeRequestCount } from '@uj/api-core';
async function request<T = unknown>(config: HostRequestConfig): Promise<T> { async function request<T = unknown>(config: HostRequestConfig): Promise<T> {
const token = getToken(); const token = getToken();
const headers: Record<string, string> = { ...(config.headers ?? {}) }; const headers: Record<string, string> = { ...(config.headers ?? {}) };
......
...@@ -29,6 +29,12 @@ export interface LoginResult { ...@@ -29,6 +29,12 @@ export interface LoginResult {
permCodes: string[]; permCodes: string[];
/** 是否需强制改密:true-本次使用的是初始/重置密码,前端应引导改密后才能正常使用 */ /** 是否需强制改密:true-本次使用的是初始/重置密码,前端应引导改密后才能正常使用 */
needChangePassword: boolean; needChangePassword: boolean;
/**
* 老网关会话标识(形如 scrm-base-<uuid>-rop)。
* 优加主壳后端不用它,但积分核销等老 RPC 网关(glsx/scrm)把它作为 sessionId 放进请求体并参与加签。
* 登录接口已返回,这里补上字段,由登录流程落库到本地会话,子应用通过 getLoginSession() 读取。
*/
loginToken?: string;
} }
/** 当前登录用户信息(角色 + 权限码 + 数据域) */ /** 当前登录用户信息(角色 + 权限码 + 数据域) */
......
...@@ -21,7 +21,10 @@ export interface MenuNode { ...@@ -21,7 +21,10 @@ export interface MenuNode {
status: number; status: number;
/** 路由 path(nodeType=2 页面菜单由后端下发,如 /store/import) */ /** 路由 path(nodeType=2 页面菜单由后端下发,如 /store/import) */
route?: string | null; route?: string | null;
/** 图标名(如 ShopOutlined);为 null 时由渲染层兜底默认图标 */ /**
* 图标名(如 ShopOutlined):nodeType=1 是一级菜单的图标,nodeType=2 是页面菜单的图标。
* 为 null 时由渲染层兜底(一级借首个子项、子项落默认图标),故一级想要稳定图标须在这里登记。
*/
icon?: string | null; icon?: string | null;
children: MenuNode[]; children: MenuNode[];
} }
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@uj/api-core": "workspace:^0.0.0",
"@uj/contracts": "workspace:*", "@uj/contracts": "workspace:*",
"@uj/design-tokens": "workspace:*", "@uj/design-tokens": "workspace:*",
"@uj/ui": "workspace:*", "@uj/ui": "workspace:*",
......
import { useEffect } from 'react'; import { useEffect } from 'react';
import { busEvents } from '@uj/contracts'; import { busEvents, PAGE_LEAVE_EVENT } from '@uj/contracts';
import { cancelRequests, setActiveScope } from '@uj/api-core';
import { queryClient } from './compat/queryClient'; import { queryClient } from './compat/queryClient';
import { shortName, subappBus } from './subapp'; import { shortName, subappBus } from './subapp';
/** /**
* 订阅主壳广播,维护子应用内的会话派生状态。 * 订阅主壳广播,维护子应用内的会话派生状态与请求生命周期。
* *
* 三条必须做的清理: * 必须做的清理:
* - logout / session 变更时清空 QueryClient 缓存,否则换账号后会短暂看到上一个账号的数据; * - logout / session 变更时清空 QueryClient 缓存,否则换账号后会短暂看到上一个账号的数据;
* - 切菜单 / 换页时 abort 掉上一页所有在途请求(alive 保活的子应用不会卸载,
* 旧请求回来仍会 resolve 并写脏 state),并让 react-query 取消对应查询;
* - 不自己清 uj_token / session(那是 host 的真源),子应用只跟随; * - 不自己清 uj_token / session(那是 host 的真源),子应用只跟随;
* - 不在这里发 `$emit(ready)`:握手由各子应用的 App 在订阅建立后发,顺序不能乱。 * - 不在这里发 `$emit(ready)`:握手由各子应用的 App 在订阅建立后发,顺序不能乱。
*
* scope 由 navigate 携带的子路径维护,请求未显式带 scope 时会自动归到当前页;
* 但批量取消一律用 cancelRequests() 无参形式,避免首屏 / 未打标请求漏网。
*/ */
export function SubAppLifecycle() { export function SubAppLifecycle() {
useEffect(() => { useEffect(() => {
...@@ -18,22 +24,46 @@ export function SubAppLifecycle() { ...@@ -18,22 +24,46 @@ export function SubAppLifecycle() {
if (!bus || !name) return; if (!bus || !name) return;
const events = busEvents(name); const events = busEvents(name);
let currentScope: string | undefined;
const onSessionChange = () => { const onSessionChange = () => {
queryClient.clear(); queryClient.clear();
window.dispatchEvent(new CustomEvent('uj:session-changed')); window.dispatchEvent(new CustomEvent('uj:session-changed'));
}; };
const onLogout = () => { const onLogout = () => {
cancelRequests();
queryClient.clear(); queryClient.clear();
}; };
/** 主壳切菜单:所有保活子应用一起取消上一页在途请求。 */
const onPageLeave = () => {
cancelRequests();
void queryClient.cancelQueries();
};
/** 子应用内部换页:主壳 MicroApp 会在 subPath 变化时发这个事件。 */
const onNavigate = (...args: unknown[]) => {
const next = String(args[0] ?? '');
// 首屏握手时主壳会补发一次 navigate,此时没有「上一页」,不要误取消首屏请求。
if (currentScope !== undefined && currentScope !== next) {
cancelRequests();
void queryClient.cancelQueries();
}
currentScope = next;
setActiveScope(next || undefined);
};
bus.$on(events.session, onSessionChange); bus.$on(events.session, onSessionChange);
bus.$on(events.logout, onLogout); bus.$on(events.logout, onLogout);
bus.$on(events.navigate, onNavigate);
bus.$on(PAGE_LEAVE_EVENT, onPageLeave);
// 这里不能同时监听 uj:session-changed:onSessionChange 自己会 dispatch 它, // 这里不能同时监听 uj:session-changed:onSessionChange 自己会 dispatch 它,
// 两个订阅会形成无限回环。自定义事件只给 AccessProvider 刷新权限用。 // 两个订阅会形成无限回环。自定义事件只给 AccessProvider 刷新权限用。
return () => { return () => {
bus.$off(events.session, onSessionChange); bus.$off(events.session, onSessionChange);
bus.$off(events.logout, onLogout); bus.$off(events.logout, onLogout);
bus.$off(events.navigate, onNavigate);
bus.$off(PAGE_LEAVE_EVENT, onPageLeave);
setActiveScope(undefined);
}; };
}, []); }, []);
......
...@@ -10,6 +10,12 @@ export interface LoginSession { ...@@ -10,6 +10,12 @@ export interface LoginSession {
dataScope: number; dataScope: number;
roleCodes: string[]; roleCodes: string[];
permCodes: string[]; permCodes: string[];
/**
* 老网关会话标识(形如 scrm-base-<uuid>-rop)。
* 优加主壳后端不用它,但积分核销等老 RPC 网关(glsx/scrm)把它作为 sessionId 放进请求体并参与加签。
* 登录接口返回后由登录流程写入此处,子应用通过 getLoginSession() 读取。
*/
loginToken?: string;
} }
const SESSION_KEY = 'session'; const SESSION_KEY = 'session';
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
"extends": "../typescript-config/react-lib.json", "extends": "../typescript-config/react-lib.json",
"compilerOptions": { "compilerOptions": {
"paths": { "paths": {
"@uj/api-core": ["../api-core/src/index.ts"],
"@uj/contracts": ["../contracts/src/index.ts"], "@uj/contracts": ["../contracts/src/index.ts"],
"@uj/design-tokens": ["../design-tokens/src/index.ts"], "@uj/design-tokens": ["../design-tokens/src/index.ts"],
"@uj/ui": ["../ui/src/index.ts"] "@uj/ui": ["../ui/src/index.ts"]
......
...@@ -2,7 +2,11 @@ import { Drawer, type DrawerProps } from 'antd'; ...@@ -2,7 +2,11 @@ import { Drawer, type DrawerProps } from 'antd';
export type UDrawerProps = DrawerProps; export type UDrawerProps = DrawerProps;
/** Unified detail drawer; responsive width and lifecycle defaults remain overridable. */ /**
* Unified detail drawer; responsive width and lifecycle defaults remain overridable.
* 约定:footer 里的取消/关闭按钮一律 type="default"(UButton 默认 primary,
* 不显式写就是主色)—— antd v6 的 Drawer 已无内置 footer 按钮,约定只能落在调用点。
*/
export function UDrawer({ size = 760, destroyOnHidden = true, styles, ...props }: UDrawerProps) { export function UDrawer({ size = 760, destroyOnHidden = true, styles, ...props }: UDrawerProps) {
return ( return (
<Drawer <Drawer
......
...@@ -2,6 +2,7 @@ import { Modal, type ModalProps } from 'antd'; ...@@ -2,6 +2,7 @@ import { Modal, type ModalProps } from 'antd';
/** /**
* 项目统一弹窗。约定默认居中、关闭时销毁内容、确认按钮为主色。 * 项目统一弹窗。约定默认居中、关闭时销毁内容、确认按钮为主色。
* 取消按钮一律普通按钮(default),不随调用方默认样式漂移;
* 若需 Modal.confirm 等静态方法,后续可在此封装 UModal.confirm 包装器。 * 若需 Modal.confirm 等静态方法,后续可在此封装 UModal.confirm 包装器。
*/ */
export function UModal(props: ModalProps) { export function UModal(props: ModalProps) {
...@@ -12,6 +13,7 @@ export function UModal(props: ModalProps) { ...@@ -12,6 +13,7 @@ export function UModal(props: ModalProps) {
maskClosable, maskClosable,
mask, mask,
okButtonProps, okButtonProps,
cancelButtonProps,
...rest ...rest
} = props; } = props;
return ( return (
...@@ -20,6 +22,7 @@ export function UModal(props: ModalProps) { ...@@ -20,6 +22,7 @@ export function UModal(props: ModalProps) {
destroyOnHidden={destroyOnHidden} destroyOnHidden={destroyOnHidden}
mask={mask ?? (maskClosable === undefined ? { closable: false } : { closable: maskClosable })} mask={mask ?? (maskClosable === undefined ? { closable: false } : { closable: maskClosable })}
okButtonProps={{ type: 'primary', ...okButtonProps }} okButtonProps={{ type: 'primary', ...okButtonProps }}
cancelButtonProps={{ type: 'default', ...cancelButtonProps }}
{...rest} {...rest}
/> />
); );
......
import type { ElementRef, ReactNode } from 'react';
import { forwardRef } from 'react';
import { Tabs } from 'antd'; import { Tabs } from 'antd';
import type { TabsProps } from 'antd';
/** 项目统一标签页,透传 antd Tabs。 */ export type UTabsSize = 'md' | 'lg';
export const UTabs = Tabs;
// antd Tabs 自带 size(SizeType),语义是控件尺寸,与我们「页面级 / 抽屉放大版」不同,
// 这里剔除后自定义 size,避免两套 size 含义打架。
export interface UTabsProps extends Omit<TabsProps, 'size'> {
/** 尺寸:md 页面级(默认,14px);lg 抽屉/详情内的放大版(16px)。 */
size?: UTabsSize;
}
/**
* 系统级分段导航(Tabs)。在 antd Tabs 之上统一三件事:
* 1. 自动带 .uj-page__tabs,页面不必再手写 className;
* 2. 统一的字号、配色、激活态、聚焦环(见 ui.css 的 .uj-page__tabs 规则);
* 3. size 区分页面级与抽屉内放大版,避免各页面各写一套作用域 CSS。
*
* 计角标请用配套 tabLabel(),替代各页面手搓的 uj-num / approval-detail-tab-count。
*/
export const UTabs = forwardRef<ElementRef<typeof Tabs>, UTabsProps>(
({ className, size = 'md', ...rest }, ref) => {
const base = size === 'lg' ? 'uj-page__tabs uj-page__tabs--lg' : 'uj-page__tabs';
return <Tabs ref={ref} {...rest} className={className ? `${base} ${className}` : base} />;
},
);
UTabs.displayName = 'UTabs';
export default UTabs; export default UTabs;
export interface TabLabelOptions {
/** 角标数字/文案;传 null / undefined / '' 则不渲染角标。 */
count?: ReactNode;
/** 角标色调:neutral 灰底(默认),primary 主色底强调。 */
tone?: 'neutral' | 'primary';
/** 角标无障碍标签;不传则隐藏(aria-hidden)。 */
countLabel?: string;
}
/**
* 生成带计数角标的 tab 文案,统一替代各页面手搓的 uj-num / approval-detail-tab-count。
*
* label: tabLabel('待我审批', { count: total }) // 灰底角标
* label: tabLabel('待我审批', { count: total, tone: 'primary' }) // 主色强调角标
* label: tabLabel('管理层市场费', { count: n, countLabel: `共 ${n} 项` }) // 带朗读
*/
export function tabLabel(text: ReactNode, options?: TabLabelOptions): ReactNode {
const count = options?.count;
const visible = count !== null && count !== undefined && count !== '';
return (
<span className="uj-tabs__label">
{text}
{visible ? (
<span
className={'uj-tabs__count' + (options?.tone === 'primary' ? ' uj-tabs__count--primary' : '')}
aria-hidden={options?.countLabel ? undefined : true}
aria-label={options?.countLabel}
>
{count}
</span>
) : null}
</span>
);
}
...@@ -45,7 +45,8 @@ export { UUpload } from './components/Upload'; ...@@ -45,7 +45,8 @@ export { UUpload } from './components/Upload';
export { Skeleton } from './components/Skeleton'; export { Skeleton } from './components/Skeleton';
export type { SkeletonVariant } from './components/Skeleton'; export type { SkeletonVariant } from './components/Skeleton';
export { UTabs } from './components/Tabs'; export { UTabs, tabLabel } from './components/Tabs';
export type { UTabsProps, UTabsSize, TabLabelOptions } from './components/Tabs';
export { UCheckbox } from './components/Checkbox'; export { UCheckbox } from './components/Checkbox';
export { UList } from './components/List'; export { UList } from './components/List';
export { UTooltip } from './components/Tooltip'; export { UTooltip } from './components/Tooltip';
......
...@@ -42,7 +42,7 @@ body { ...@@ -42,7 +42,7 @@ body {
.uj-page { .uj-page {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: var(--uj-space-4, 16px); gap: var(--uj-space-module, 10px);
min-width: 0; min-width: 0;
min-height: 100%; min-height: 100%;
} }
...@@ -83,15 +83,121 @@ body { ...@@ -83,15 +83,121 @@ body {
gap: var(--uj-space-2, 8px); gap: var(--uj-space-2, 8px);
} }
/* 页内分段导航(Tabs):不参与伸缩,间距交给页面 gap,避免 antd 默认 margin 叠成两层。 */ /* 页内分段导航(Tabs / 系统组件 · 滑动药丸风格):
浅灰圆角轨道 + 主色填充滑块,切换时滑块平滑滑动;选中态文字反色(on-primary),
计数角标反转成主色字。size=md 页面级(14px);size=lg 抽屉/详情内放大版(16px)。
优先级:antd v6 的 cssinjs 规则与本文件同注 shadowRoot 且顺序在后,同特异性时 antd 获胜
(实测:激活文字色 / hover 色 / horizontalItemPadding 都曾被 antd 盖掉)——
所以这里全部走子选择器链 .uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap
> .ant-tabs-nav-list > ... 提到 (0,8,0),保证压过 antd;themeConfig 的 Tabs token 同值兜底。 */
.uj-page__tabs { .uj-page__tabs {
flex: none; flex: none;
} }
.uj-page__tabs .ant-tabs-nav { .uj-page__tabs.ant-tabs > .ant-tabs-nav {
margin-bottom: 0; margin-bottom: 0;
} }
.uj-page__tabs .ant-tabs-nav::before { /* 轨道自带边界,antd 默认的整条底边框去掉。 */
border-bottom-color: var(--uj-divider); .uj-page__tabs.ant-tabs > .ant-tabs-nav::before {
display: none;
}
/* 轨道:收缩到内容宽的浅灰胶囊容器,滑块与标签都落在里面;
内描边用 inset box-shadow(不占布局)勾出边界。 */
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list {
position: relative;
display: inline-flex;
width: fit-content;
gap: 2px;
padding: 3px;
background: var(--uj-surface-3);
box-shadow: inset 0 0 0 1px var(--uj-divider);
border-radius: var(--uj-radius-pill, 999px);
}
/* 标签:透明底浮在轨道上,层级高于滑块,文字才不会被盖住。
hover 先浮出一层白色底,激活后由主色滑块接管(激活项不响应 hover)。 */
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab {
position: relative;
z-index: 1;
margin: 0;
padding: 5px 12px;
border-radius: var(--uj-radius-pill, 999px);
color: var(--uj-text-2);
font-size: var(--uj-font-md, 14px);
transition: color 0.2s ease, background-color 0.2s ease;
}
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab:hover:not(.ant-tabs-tab-active) {
background: var(--uj-surface);
}
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab:hover > .ant-tabs-tab-btn {
color: var(--uj-text-1);
}
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab.ant-tabs-tab-active > .ant-tabs-tab-btn {
color: var(--uj-on-primary);
font-weight: 600;
}
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab.ant-tabs-tab-disabled {
color: var(--uj-text-4);
}
/* 滑块:复用 antd ink-bar,从「底部下划线」改为「撑满标签高度的圆角主色背景」,
随选中项平滑滑动(z-index 低于标签,文字浮在其上)。 */
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-ink-bar {
top: 3px;
bottom: 3px;
height: auto;
background: var(--uj-primary);
border-radius: var(--uj-radius-pill, 999px);
z-index: 0;
/* rc-tabs 默认用 inline left/width 定位滑块(indicator.align 非 center/end 时不走
transform),动画必须同时覆盖 left/right/width 才跟手。 */
transition: left 0.28s cubic-bezier(0.4, 0, 0.2, 1), right 0.28s cubic-bezier(0.4, 0, 0.2, 1),
width 0.28s cubic-bezier(0.4, 0, 0.2, 1);
}
/* 键盘聚焦可见:胶囊形聚焦环。 */
.uj-page__tabs.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab > .ant-tabs-tab-btn:focus-visible {
outline: none;
box-shadow: var(--uj-ring);
border-radius: var(--uj-radius-pill, 999px);
}
/* lg:抽屉/详情内放大版(16px,轨道与滑块同步放大)。 */
.uj-page__tabs--lg.ant-tabs > .ant-tabs-nav {
margin-bottom: var(--uj-space-4, 16px);
}
.uj-page__tabs--lg.ant-tabs > .ant-tabs-nav > .ant-tabs-nav-wrap > .ant-tabs-nav-list > .ant-tabs-tab {
padding: 6px 16px;
font-size: var(--uj-font-xl, 16px);
line-height: 24px;
}
/* Tab 文案与计数角标:替代各页面手搓的 uj-num / approval-detail-tab-count。
角标底色取 border-strong(比轨道的 surface-3 深一档,在轨道上才看得见)。 */
.uj-tabs__label {
display: inline-flex;
align-items: center;
gap: 6px;
}
.uj-tabs__count {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 18px;
height: 18px;
padding: 0 5px;
border-radius: var(--uj-radius-pill, 999px);
background: var(--uj-border-strong);
color: var(--uj-text-2);
font-size: 11px;
font-weight: 600;
line-height: 1;
font-variant-numeric: var(--uj-num, tabular-nums);
transition: background-color 0.2s ease, color 0.2s ease;
}
.uj-tabs__count--primary {
background: var(--uj-primary);
color: var(--uj-on-primary);
}
/* 选中态:主色胶囊上角标整体反转(反色底 + 主色字),任何主题下都成立。 */
.uj-page__tabs.ant-tabs .ant-tabs-nav .ant-tabs-tab-active .uj-tabs__count,
.uj-page__tabs.ant-tabs .ant-tabs-nav .ant-tabs-tab-active .uj-tabs__count--primary {
background: var(--uj-on-primary);
color: var(--uj-primary);
} }
/* 列表页里表头与表体之间只有一层卡片间距,不再额外叠 gap。 */ /* 列表页里表头与表体之间只有一层卡片间距,不再额外叠 gap。 */
.uj-page--fill > .uj-page__body { .uj-page--fill > .uj-page__body {
...@@ -99,15 +205,16 @@ body { ...@@ -99,15 +205,16 @@ body {
min-height: 0; min-height: 0;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: var(--uj-space-4, 16px); gap: var(--uj-space-module, 10px);
} }
/* ============ 卡片 ============ */ /* ============ 卡片 ============ */
/* 卡片靠浅底 + 柔影分层,不靠描边。阴影取令牌,两级:静置 / hover 抬起。 */ /* 卡片 = 1px 实描边 + 干脆短影:描边立边界,影子给层次。
全靠柔影分层会软;实描边是企业级「质感」的最低成本来源。 */
.uj-card { .uj-card {
border: 1px solid transparent; border: 1px solid var(--uj-border, #e6ebf2);
border-radius: var(--uj-radius-card, 12px); border-radius: var(--uj-radius-card, 10px);
background: var(--uj-surface, #fff); background: var(--uj-surface, #fff);
box-shadow: var(--uj-shadow-card); box-shadow: var(--uj-shadow-card);
} }
...@@ -136,10 +243,13 @@ body { ...@@ -136,10 +243,13 @@ body {
padding: 12px 16px; padding: 12px 16px;
} }
/* 筛选字段栅格:桌面 4 列 + 动作列,动作与字段同排、垂直居中; /* 筛选字段栅格:桌面 4 列 + 动作列,动作与字段同排、垂直居中;
标签在控件左侧,控件左缘因此落在同一条竖线上(标签列宽由 SearchForm 的 labelCol 给出)。 */ 标签在控件左侧,控件左缘因此落在同一条竖线上(标签列宽由 SearchForm 的 labelCol 给出)。
动作列用固定宽度而非 auto:常显区与收起区(.uj-filter-more)必须用同一列模板,
否则后者少了动作列、字段列会更宽,两排控件对不齐。--uj-filter-actions-col 即预留的动作列宽。 */
.uj-filter-grid { .uj-filter-grid {
--uj-filter-actions-col: 240px;
display: grid; display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr)) auto; grid-template-columns: repeat(4, minmax(0, 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;
...@@ -170,10 +280,12 @@ body { ...@@ -170,10 +280,12 @@ body {
gap: var(--uj-space-2, 8px); gap: var(--uj-space-2, 8px);
white-space: nowrap; white-space: nowrap;
} }
/* 收起后的第二排:与第一排同栅格,靠一条淡分隔线区隔,不另起一个卡片。 */ /* 收起后的第二排:与第一排同栅格、同列模板(含等宽动作列预留,空着),
靠一条淡分隔线区隔,不另起一个卡片。字段列因此与常显区严格对齐。 */
.uj-filter-more { .uj-filter-more {
--uj-filter-actions-col: 240px;
display: grid; display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr)); grid-template-columns: repeat(4, minmax(0, 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;
......
-- =====================================================================
-- 三个一级菜单(产品分组节点)的图标
--
-- 为什么需要这份:一级的图标取的是后端 nodeType=1(sys_menu.menu_type=1 目录)
-- 节点自己的 icon。该列为 NULL 时前端只能借「首个子项」的图标,
-- 于是二级改个 sort,一级的图标就跟着变——这是配置缺项,不是设计。
--
-- 图标名必须同时满足两条,否则前端会回落并(dev)告警:
-- 1) 是真实存在的 @ant-design/icons 名称;
-- 2) 已登记在 apps/web/shell/src/layouts/BasicLayout.tsx 的 iconMap 里。
-- 本脚本用到的 GiftOutlined / HomeOutlined / SettingOutlined 两条都已满足。
--
-- 幂等:UPDATE 按 menu_name + menu_type=1 定位,重复执行结果一致;
-- 执行前先看第 1 步的现状,确认这三行确实存在且唯一。
-- =====================================================================
USE `yj_service`;
-- 1) 现状:一级菜单(目录)有哪些、各自 icon 是什么
-- 判据:下面每个 menu_name 应恰好 1 行;出现 0 行或 >1 行先别往下跑。
SELECT `menu_id`, `menu_code`, `parent_code`, `menu_name`, `icon`, `sort`
FROM `sys_menu`
WHERE `menu_type` = 1 AND `is_deleted` = 0
ORDER BY `sort`, `menu_code`;
-- 2) 落图标
UPDATE `sys_menu` SET `icon` = 'GiftOutlined'
WHERE `menu_type` = 1 AND `is_deleted` = 0 AND `menu_name` = '积分管理';
UPDATE `sys_menu` SET `icon` = 'HomeOutlined'
WHERE `menu_type` = 1 AND `is_deleted` = 0 AND `menu_name` = '门店上架';
UPDATE `sys_menu` SET `icon` = 'SettingOutlined'
WHERE `menu_type` = 1 AND `is_deleted` = 0 AND `menu_name` = '系统设置';
-- 3) 回查:判据是三行、icon 分别是 GiftOutlined / HomeOutlined / SettingOutlined
SELECT `menu_name`, `icon`
FROM `sys_menu`
WHERE `menu_type` = 1 AND `is_deleted` = 0
AND `menu_name` IN ('积分管理', '门店上架', '系统设置');
-- ---------------------------------------------------------------------
-- 回滚(把三个一级恢复成「未登记,借首个子项」的旧行为)
-- ---------------------------------------------------------------------
-- UPDATE `sys_menu` SET `icon` = NULL
-- WHERE `menu_type` = 1 AND `menu_name` IN ('积分管理', '门店上架', '系统设置');
...@@ -297,6 +297,19 @@ function collectRelations(laneDir, projectConfig) { ...@@ -297,6 +297,19 @@ function collectRelations(laneDir, projectConfig) {
return [{ pkgJsonPath: join(laneDir, 'package.json'), distDir: laneDir }]; return [{ pkgJsonPath: join(laneDir, 'package.json'), distDir: laneDir }];
} }
/**
* 「构建 npm」会把 miniprogram_dist/index.js 原样拷进 miniprogram_npm/@uj/api-core/index.js。
* 只看「文件存在」会把旧 bundle 也判成就位 —— 主入口导出面一变(如新增 createClient),
* 旧包在运行时就是 undefined。按内容比对(换行归一)识别过期,给中性提示而非报错。
*/
function apiCoreBundleFresh(target) {
const src = join(API_CORE_DIR, 'miniprogram_dist', 'index.js');
const dst = join(target, '@uj/api-core', 'index.js');
if (!existsSync(src) || !existsSync(dst)) return undefined;
const norm = (p) => readFileSync(p, 'utf8').replace(/\r\n/g, '\n');
return norm(src) === norm(dst);
}
function checkRelation(rel) { function checkRelation(rel) {
const pkg = readJson(rel.pkgJsonPath); const pkg = readJson(rel.pkgJsonPath);
if (!pkg) return { error: `读不到 ${rel.pkgJsonPath}`, deps: [], missing: [], broken: [] }; if (!pkg) return { error: `读不到 ${rel.pkgJsonPath}`, deps: [], missing: [], broken: [] };
...@@ -309,7 +322,11 @@ function checkRelation(rel) { ...@@ -309,7 +322,11 @@ function checkRelation(rel) {
if (deps.includes('@uj/api-core') && !existsSync(join(target, '@uj/api-core', 'index.js'))) { if (deps.includes('@uj/api-core') && !existsSync(join(target, '@uj/api-core', 'index.js'))) {
if (!missing.includes('@uj/api-core')) broken.push('@uj/api-core 缺 index.js'); if (!missing.includes('@uj/api-core')) broken.push('@uj/api-core 缺 index.js');
} }
return { deps, missing, broken, target, pkgPath: rel.pkgJsonPath }; const stale = [];
if (deps.includes('@uj/api-core') && apiCoreBundleFresh(target) === false) {
stale.push('@uj/api-core 产物不是最新(主入口已更新)');
}
return { deps, missing, broken, stale, target, pkgPath: rel.pkgJsonPath };
} }
export function inspectLane(lane) { export function inspectLane(lane) {
...@@ -323,14 +340,16 @@ export function inspectLane(lane) { ...@@ -323,14 +340,16 @@ export function inspectLane(lane) {
return { label, ...checkRelation(rel) }; return { label, ...checkRelation(rel) };
}); });
const gap = rows.flatMap((r) => [...(r.missing || []), ...(r.broken || [])]); const gap = rows.flatMap((r) => [...(r.missing || []), ...(r.broken || [])]);
const stale = rows.flatMap((r) => r.stale || []);
const hasTarget = rows.some((r) => r.target && existsSync(r.target)); const hasTarget = rows.some((r) => r.target && existsSync(r.target));
return { return {
lane, lane,
laneDir, laneDir,
rows, rows,
gap, gap,
stale,
hasTarget, hasTarget,
built: hasTarget && gap.length === 0, built: hasTarget && gap.length === 0 && stale.length === 0,
autoMode: config?.setting?.packNpmManually !== true, autoMode: config?.setting?.packNpmManually !== true,
nodeModulesOff: config?.setting?.nodeModules === false, nodeModulesOff: config?.setting?.nodeModules === false,
}; };
...@@ -358,6 +377,7 @@ function printLaneReport(r) { ...@@ -358,6 +377,7 @@ function printLaneReport(r) {
} else { } else {
bad(`${row.label}: ${total - row.missing.length}/${total} 包就位,缺 ${gap.join(', ')}`); bad(`${row.label}: ${total - row.missing.length}/${total} 包就位,缺 ${gap.join(', ')}`);
} }
if (row.stale?.length) warn(`${row.label}: ${row.stale.join('、')}`);
} }
if (r.nodeModulesOff) { if (r.nodeModulesOff) {
warn('project.config.json 里 nodeModules: false(旧开关),工具可能不启用 npm 模块'); warn('project.config.json 里 nodeModules: false(旧开关),工具可能不启用 npm 模块');
...@@ -416,13 +436,30 @@ export async function runLanes(lanes, opts = parseArgs()) { ...@@ -416,13 +436,30 @@ export async function runLanes(lanes, opts = parseArgs()) {
const pending = report.filter((r) => !r.built); const pending = report.filter((r) => !r.built);
const ready = report.filter((r) => r.built); const ready = report.filter((r) => r.built);
const staleLanes = report.filter((r) => r.stale?.length);
const build = res.build || { mode: 'skipped' }; const build = res.build || { mode: 'skipped' };
console.log(`\n${paint('── 结果 ──', C.bold)}`); console.log(`\n${paint('── 结果 ──', C.bold)}`);
if (ready.length) if (ready.length)
console.log(` ${paint('可用', C.green)}: ${ready.map((r) => r.lane).join(', ')}`); console.log(` ${paint('可用', C.green)}: ${ready.map((r) => r.lane).join(', ')}`);
if (pending.length) if (pending.length) {
console.log(` ${paint('白屏风险', C.red)}: ${pending.map((r) => r.lane).join(', ')}`); if (build.mode === 'manual') {
// 「工具 → 构建 npm」是微信小程序的默认手工动作,不是异常,不必报警为白屏风险
console.log(` ${paint('待手动构建 npm', C.yellow)}: ${pending.map((r) => r.lane).join(', ')}`);
} else {
// 缺包 vs 产物过期分开列:前者要装依赖,后者只需工具重跑一次「构建 npm」。
const needBuild = pending.filter((r) => r.gap.length);
const needManual = pending.filter((r) => !r.gap.length);
if (needBuild.length) {
console.log(` ${paint('待构建', C.yellow)}: ${needBuild.map((r) => r.lane).join(', ')}`);
}
if (needManual.length) {
console.log(
` ${paint('待手动构建 npm', C.yellow)}: ${needManual.map((r) => r.lane).join(', ')} (api-core 产物已更新)`,
);
}
}
}
if (!pending.length) { if (!pending.length) {
console.log(`\n${paint('全部就位,可以直接编译。', C.green)}`); console.log(`\n${paint('全部就位,可以直接编译。', C.green)}`);
...@@ -437,10 +474,12 @@ export async function runLanes(lanes, opts = parseArgs()) { ...@@ -437,10 +474,12 @@ export async function runLanes(lanes, opts = parseArgs()) {
if (!sub || res[`sub:${p.lane}`] !== false) continue; if (!sub || res[`sub:${p.lane}`] !== false) continue;
console.log(` ${p.lane} 子包依赖缺失:${paint(sub.fixHint, C.cyan)}`); console.log(` ${p.lane} 子包依赖缺失:${paint(sub.fixHint, C.cyan)}`);
} }
if (build.mode === 'manual') { if (build.mode === 'manual' || staleLanes.length) {
console.log(`\n ${paint('构建 npm 需要开发者工具:', C.yellow)}${build.reason}`); const reason = build.reason ?? 'api-core 产物已更新,本地 miniprogram_npm 仍是旧 bundle';
console.log(`\n ${paint('构建 npm 需要开发者工具:', C.yellow)}${reason}`);
console.log(' 打开对应项目后执行「工具 → 构建 npm」,再重跑本命令校验:'); console.log(' 打开对应项目后执行「工具 → 构建 npm」,再重跑本命令校验:');
for (const p of pending) { const needBuild = build.mode === 'manual' ? pending : staleLanes;
for (const p of needBuild) {
const label = targets.length === 1 ? p.laneDir : `${p.lane} (${p.laneDir})`; const label = targets.length === 1 ? p.laneDir : `${p.lane} (${p.laneDir})`;
console.log(` - ${label}`); console.log(` - ${label}`);
} }
......
-- =====================================================================
-- 积分管理(points)完整重建脚本的回滚
-- 对应 points-menu-complete.sql:删除整棵「积分管理」子树(menu_code 前缀 10025)。
--
-- 说明:
-- - 用前缀匹配一次性删掉全部积分管理条目(目录 + 页面 + 按钮),幂等安全。
-- - 10025* 仅属于积分管理模块(门店 10000~10024、系统 10013~10024 不在此区间),
-- 不会误删其它模块。
-- - 若已把这些菜单分配给角色(sys_role_menu 等按 menu_id 记录),
-- 删除前请先清理角色-菜单关联,否则外键约束(生产库通常开启)会导致删除失败。
-- =====================================================================
USE `yj_service`;
DELETE FROM `sys_menu` WHERE `menu_code` LIKE '10025%';
-- =====================================================================
-- 积分管理(points)菜单 / 权限码 完整重建脚本(自包含)
--
-- 适用场景:原「积分管理」整棵菜单已被删除,需要一份从零建全的 SQL。
-- 与 points-menu-sync.sql(改旧码 + 插新项)不同,本脚本是纯 INSERT,
-- 一次性把积分管理目录 + 全部页面 + 全部按钮权限 + 图标建齐。
--
-- 说明:
-- - 复用原 menu_id 25~28(目录 / 核销订单菜单 / 批量结算导入 / 导出),
-- 以便角色-菜单关联(通常按 menu_id 记录)能自动续上,无需重新授权。
-- - 权限码一律用前端 codes.ts 的真实值(points:order:* 等),不再用旧的错误码 list:*。
-- - INSERT 用 IGNORE:menu_code 唯一,重复执行安全(已存在则跳过)。
-- - 若想彻底清空后重建,可先执行:
-- DELETE FROM `sys_menu` WHERE `menu_code` LIKE '10025%';
-- 再跑本脚本。
--
-- 菜单树(menu_type: 1-目录 2-菜单 3-按钮):
-- 积分管理(10025, 目录, GiftOutlined)
-- ├─ 积分核销订单(1002501, 菜单, order:view, FileSyncOutlined) /points/list
-- │ ├─ 去结算/取消结算(100250103, 按钮, order:settle)
-- │ ├─ 批量结算导入(100250101, 按钮, order:import)
-- │ └─ 导出(100250102, 按钮, order:export)
-- ├─ 用户积分明细(1002502, 菜单, score:view, FundOutlined) /points/users
-- │ └─ 导出(100250201, 按钮, score:export)
-- └─ 积分提现管理(1002503, 菜单, withdraw:view, TransactionOutlined) /points/withdraw
-- ├─ 审批通过(100250301, 按钮, withdraw:approve)
-- ├─ 审批打回(100250302, 按钮, withdraw:reject)
-- ├─ 去付款(100250303, 按钮, withdraw:pay)
-- ├─ 生成批次(100250304, 按钮, withdraw:batch)
-- ├─ 打标签(100250305, 按钮, withdraw:tag)
-- ├─ 批量导入(100250306, 按钮, withdraw:import)
-- ├─ 导出(100250307, 按钮, withdraw:export)
-- └─ 积分提现审批(1002504, 子菜单, approval:view, SolutionOutlined)
-- ├─ 付款审核(100250401, 按钮, approval:pay-audit)
-- ├─ 解散批次(100250402, 按钮, approval:disband)
-- ├─ 移除提现(100250403, 按钮, approval:remove)
-- └─ 再次打款(100250404, 按钮, arrival:pay-again)
-- =====================================================================
USE `yj_service`;
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
-- 目录
(25, '10025', NULL, '积分管理', 1, NULL, '积分管理', NULL, 'GiftOutlined', 3, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 积分核销订单(路由 /points/list;核销订单列表与详情共用 order:view)
(26, '1002501', '10025', '积分核销订单', 2, 'points:order:view', '积分管理', '/points/list', 'FileSyncOutlined', 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(27, '100250101', '1002501', '批量结算导入', 3, 'points:order:import', '积分管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(28, '100250102', '1002501', '导出', 3, 'points:order:export', '积分管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(29, '100250103', '1002501', '去结算/取消结算', 3, 'points:order:settle', '积分管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 用户积分明细(路由 /points/users;列表与详情共用 score:view)
(30, '1002502', '10025', '用户积分明细', 2, 'points:score:view', '积分管理', '/points/users', 'FundOutlined', 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(31, '100250201', '1002502', '导出', 3, 'points:score:export', '积分管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 积分提现管理(路由 /points/withdraw;列表 Tab 用 withdraw:view)
(32, '1002503', '10025', '积分提现管理', 2, 'points:withdraw:view', '积分管理', '/points/withdraw','TransactionOutlined', 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(33, '100250301', '1002503', '审批通过', 3, 'points:withdraw:approve','积分管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(34, '100250302', '1002503', '审批打回', 3, 'points:withdraw:reject', '积分管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(35, '100250303', '1002503', '去付款', 3, 'points:withdraw:pay', '积分管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(36, '100250304', '1002503', '生成批次', 3, 'points:withdraw:batch', '积分管理', NULL, NULL, 4, 1, 1, NULL, NULL, NULL, NULL, 0),
(37, '100250305', '1002503', '打标签', 3, 'points:withdraw:tag', '积分管理', NULL, NULL, 5, 1, 1, NULL, NULL, NULL, NULL, 0),
(38, '100250306', '1002503', '批量导入', 3, 'points:withdraw:import', '积分管理', NULL, NULL, 6, 1, 1, NULL, NULL, NULL, NULL, 0),
(39, '100250307', '1002503', '导出', 3, 'points:withdraw:export', '积分管理', NULL, NULL, 7, 1, 1, NULL, NULL, NULL, NULL, 0),
-- 积分提现审批(审核 Tab 的查看权限 approval:view;WithdrawApprove/Batch/Arrival 共用)
(40, '1002504', '1002503', '积分提现审批', 2, 'points:approval:view', '积分管理', NULL, 'SolutionOutlined', 8, 1, 1, NULL, NULL, NULL, NULL, 0),
(41, '100250401', '1002504', '付款审核', 3, 'points:approval:pay-audit','积分管理', NULL, NULL, 1, 1, 1, NULL, NULL, NULL, NULL, 0),
(42, '100250402', '1002504', '解散批次', 3, 'points:approval:disband','积分管理', NULL, NULL, 2, 1, 1, NULL, NULL, NULL, NULL, 0),
(43, '100250403', '1002504', '移除提现', 3, 'points:approval:remove', '积分管理', NULL, NULL, 3, 1, 1, NULL, NULL, NULL, NULL, 0),
(44, '100250404', '1002504', '再次打款', 3, 'points:arrival:pay-again','积分管理',NULL, NULL, 4, 1, 1, NULL, NULL, NULL, NULL, 0);
...@@ -87,7 +87,7 @@ function templateIndexTs(dir, displayName) { ...@@ -87,7 +87,7 @@ function templateIndexTs(dir, displayName) {
L.push("import {"); L.push("import {");
L.push(" createRpcDispatcher,"); L.push(" createRpcDispatcher,");
L.push(" createWxSender,"); L.push(" createWxSender,");
L.push(" createSha1Signer,"); L.push(" createSigner,");
L.push(" registerGateway,"); L.push(" registerGateway,");
L.push(" type GatewayStrategy,"); L.push(" type GatewayStrategy,");
L.push(" type GatewayCredential,"); L.push(" type GatewayCredential,");
...@@ -103,8 +103,9 @@ function templateIndexTs(dir, displayName) { ...@@ -103,8 +103,9 @@ function templateIndexTs(dir, displayName) {
L.push(' * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。'); L.push(' * - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。');
L.push(' *'); L.push(' *');
L.push(' * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、'); L.push(' * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、');
L.push(' * appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同'); L.push(' * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx');
L.push(' * 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。'); L.push(' * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);');
L.push(" * 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。");
L.push(' *'); L.push(' *');
L.push(' * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();'); L.push(' * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();');
L.push(' * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。'); L.push(' * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。');
...@@ -115,7 +116,7 @@ function templateIndexTs(dir, displayName) { ...@@ -115,7 +116,7 @@ function templateIndexTs(dir, displayName) {
L.push(` router: 'rop-scrm-${dir}/router',`); L.push(` router: 'rop-scrm-${dir}/router',`);
L.push(" tokenHeader: 'token',"); L.push(" tokenHeader: 'token',");
L.push(` // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。`); L.push(` // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。`);
L.push(` signer: createSha1Signer({ id: '${signerId}' }),`); L.push(` signer: createSigner({ kind: 'rop', id: '${signerId}' }),`);
L.push(" // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。"); L.push(" // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。");
L.push(" fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },"); L.push(" fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },");
L.push(' // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。'); L.push(' // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。');
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!