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 1074 additions and 576 deletions
......@@ -92,12 +92,14 @@ scripts/
`apps/mp` 下四个原生小程序(points / sales / store / usedcar)同仓,但它们**不进 pnpm 的构建链**(没有 build 任务),在微信开发者工具里编译,第三方依赖靠「构建 npm」落到 `miniprogram_npm/`。
先跑一次工作区安装(只认 pnpm,不要用 npm install):
克隆之后**一条命令**,四件事按依赖顺序自己补齐,不需要事先单独 `pnpm install`:
```bash
pnpm install
pnpm build:npm # 装依赖 → api-core 产物 → 子包依赖 → 构建 npm → 体检
```
只认 pnpm,不要用 npm install(唯一例外是 `packageUsedCar`,脚本内部自己调 npm)。
### 只做你改的那个小程序
每个小程序根目录都有自己的入口 `mp-npm.mjs`,**只管自己**,不会碰其他三个:
......@@ -111,27 +113,29 @@ cd apps/mp/store && node mp-npm.mjs --check # 同样效果
(`mp-npm.mjs` 已写进各 lane 的 `packOptions.ignore`,不会被打进小程序包体。)
它做三步,用不上的步骤不会出现(非 usedcar 不会打印子包依赖那一段):
它按顺序做四步,用不上的步骤不会出现(非 usedcar 不打印子包依赖那一段):
1. `pnpm --filter @uj/api-core build` → `miniprogram_dist/`——「构建 npm」的唯一输入,gitignore 的产物,漏了就是白屏;
2. 本 lane 有内嵌子包时(目前只有 usedcar 的 `packageUsedCar`)缺依赖就跑 `setup:deps`(内部 `npm install`);
3. 服务端口 9420 可达时调 `cli.bat build-npm` 自动构建;然后按工具自己的判定规则校验 `miniprogram_npm/`,缺哪个包点哪个名。
1. 工作区依赖:`node_modules/.modules.yaml` 不存在就跑 `pnpm install`(`--check` 只报不装);`pnpm-lock.yaml` 比它新会提示依赖可能过期;
2. `pnpm --filter @uj/api-core build` → `miniprogram_dist/`——「构建 npm」的唯一输入,gitignore 的产物,漏了就是白屏;
3. 本 lane 有内嵌子包时(目前只有 usedcar 的 `packageUsedCar`)缺依赖就跑 `setup:deps`(内部 `npm install`);
4. 服务端口 9420 可达时调 `cli.bat build-npm` 自动构建;然后按工具自己的判定规则校验 `miniprogram_npm/`,缺哪个包点哪个名。
### 一次准备全仓(新环境 / CI)
```bash
pnpm mp # 遍历 apps/mp/manifest.json 里所有 lane
pnpm build:npm # 等价于 pnpm mp,遍历 apps/mp/manifest.json 里所有 lane
pnpm mp:check # 只体检
pnpm mp --lane usedcar,store # 指定几个(等价于分别进目录跑)
```
退出码:全绿 0,有缺口 1,可直接挂钩子。
退出码:全绿 0;有缺口、或前置(依赖 / api-core / 子包)没完成 1,可直接挂钩子。
想让第 3 步免人工:开发者工具 → **设置 → 安全设置 → 打开「服务端口」**,之后脚本会自己调 cli 构建;没开会打印精确到项目目录的人工清单。
想让第 4 步免人工:开发者工具 → **设置 → 安全设置 → 打开「服务端口」**,之后脚本会自己调 cli 构建;没开会打印精确到项目目录的人工清单。
脚本坏了才需要的手工等价步骤:
```bash
pnpm install # 工作区依赖
pnpm --filter @uj/api-core build # api-core 产物
pnpm --filter @uj/mp-usedcar run setup:deps # 仅 usedcar
# 然后在开发者工具里打开 apps/mp/<lane> → 工具 → 构建 npm
......
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
createSigner,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
......@@ -17,7 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 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();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
......@@ -28,7 +30,7 @@ export const demoGateway: GatewayStrategy = {
router: 'rop-scrm-demo/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'demo-sha1' }),
signer: createSigner({ kind: 'rop', id: 'demo-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
node_modules/
/miniprogram_npm/
miniprogram_npm
/miniprogram_npm
*.log
.DS_Store
*.tmp
\ No newline at end of file
*.tmp
......@@ -11,7 +11,10 @@ let index = 2
4预发布
*/
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(accountInfo.miniProgram.envVersion)
//手动控制体验版环境的请求 true就依据下面index false就默认为2
......
/**
* points 请求层:@uj/api-core 的客户端工厂。
*
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL 拼装 / 签名 /
* 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL 拼装 / 签名 /
* 拦截器(业务码归一 / 登录跳转 / loading / toast)由 api-core 负责。
*
* public API 与旧壳一致:get/post/request(RequestMethods, params, returnAll)、
......@@ -15,7 +15,7 @@
* · sentry 上报 → events.error + onTransportError
*/
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core'
import { createClient } from '@uj/api-core'
import {
defaultMerchantId,
secretKey,
......@@ -29,7 +29,8 @@ const DEFAULT_CRED = {
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
}
const client = createRopClient({
const client = createClient({
kind: 'rop',
hosts: { scrm: domain },
pathEnum,
secretKey,
......
......@@ -34,39 +34,45 @@ Component({
},
init() {
/**
* 获取自定义导航栏信息
* 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → wx.getWindowInfo()
* fontSizeSetting → wx.getAppBaseInfo()
* 新接口均为同步返回,去掉原来的 .then 异步时序。
*/
wx.getSystemInfo().then(res => {
let {
fontSizeSetting,
statusBarHeight,
screenWidth
} = res
const {
height,
right,
width,
top
} = wx.getMenuButtonBoundingClientRect(),
currentPages = getCurrentPages(), {
showBack
} = this.data
if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true
})
let navigationBarHeight = height + ((top - statusBarHeight) * 2)
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width * 2)
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
const windowInfo = wx.getWindowInfo() || {}
const appBaseInfo = wx.getAppBaseInfo() || {}
let {
fontSizeSetting,
statusBarHeight,
screenWidth,
} = {
...windowInfo,
fontSizeSetting: appBaseInfo.fontSizeSetting,
}
const {
height,
right,
width,
top,
} = wx.getMenuButtonBoundingClientRect()
const currentPages = getCurrentPages()
const { showBack } = this.data
if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true
})
let navigationBarHeight = height + ((top - statusBarHeight) * 2)
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width * 2)
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
},
emit({
......
......@@ -15,7 +15,7 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let system = wx.getSystemInfoSync()
let system = wx.getWindowInfo()
this.getAllMerchantList()
this.setData({
cHeight: system.windowHeight
......
......@@ -61,7 +61,7 @@ Page({
},
onLoad(options) {
let system = wx.getSystemInfoSync()
let system = wx.getWindowInfo()
const { merchantId } = wx.p.storage.get('merchant_info')
this.toGetFreeCardDay(merchantId)
this.setData({
......
......@@ -16,12 +16,16 @@
"uglifyFileName": false,
"uploadWithSourceMap": true,
"useIsolateContext": false,
"nodeModules": false,
"enhance": true,
"useMultiFrameRuntime": true,
"showShadowRootInWxmlPanel": true,
"packNpmManually": false,
"packNpmRelationList": [],
"packNpmManually": true,
"packNpmRelationList": [
{
"packageJsonPath": "./package.json",
"miniprogramNpmDistDir": "./"
}
],
"minifyWXSS": true,
"disableUseStrict": false,
"ignoreUploadUnusedFiles": true,
......@@ -37,7 +41,11 @@
"useCompilerPlugins": [
"sass"
],
"condition": true
"condition": true,
"compileWorklet": false,
"localPlugins": false,
"swc": false,
"disableSWC": true
},
"compileType": "miniprogram",
"simulatorType": "wechat",
......@@ -62,5 +70,6 @@
],
"include": []
},
"appid": "wx7ce755e425603084"
"appid": "wx7ce755e425603084",
"libVersion": "3.9.0"
}
\ No newline at end of file
{
"libVersion": "3.9.0",
"projectname": "points-mall",
"projectname": "points",
"setting": {
"urlCheck": false,
"coverView": true,
......@@ -9,97 +9,16 @@
"preloadBackgroundData": false,
"autoAudits": false,
"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",
"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
}
]
}
}
"condition": {}
}
\ No newline at end of file
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
createSigner,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
......@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
......@@ -29,7 +30,7 @@ export const pointsGateway: GatewayStrategy = {
router: 'rop-scrm-points/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'points-sha1' }),
signer: createSigner({ kind: 'rop', id: 'points-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
......@@ -47,13 +47,14 @@ export function getNavigationBarTitleText() {
/** 存储设备信息 */
export function setSystem_info(that) {
let info = storage.get('system_info')
!info &&
wx.getSystemInfo({
success(res) {
// console.log(res)
storage.set('system_info', res)
}
})
if (!info) {
// 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆到新接口后合并存储,
// 保证 utils/track/Track.js 读取的 brand/model/system/SDKVersion/version 等字段仍可用。
const windowInfo = wx.getWindowInfo() || {}
const appBaseInfo = wx.getAppBaseInfo() || {}
const deviceInfo = wx.getDeviceInfo() || {}
storage.set('system_info', { ...deviceInfo, ...appBaseInfo, ...windowInfo })
}
}
export default{
......
......@@ -200,7 +200,7 @@ reportParamError('霈W”撘虜嚗erchantId, channelSource, phone 餈
productId: 'prod_456',
quantity: 2,
operation: 'add_to_cart',
userAgent: wx.getSystemInfoSync(),
userAgent: wx.getDeviceInfo(),
timestamp: Date.now()
};
......@@ -212,7 +212,7 @@ reportSentryError('韐剔頧行仃韐', cartParams, {
user_type: 'premium'
},
contexts: {
device_info: wx.getSystemInfoSync(),
device_info: { ...wx.getDeviceInfo(), ...wx.getWindowInfo(), ...wx.getAppBaseInfo() },
app_version: '1.2.3'
}
});*/
......@@ -58,14 +58,18 @@ const showToast = val => {
/**获取设备信息 */
const getSystemInfo = callBack => {
wx.getSystemInfo({
success(res) {
callBack(res)
},
fail(err) {
callBack(err)
}
})
try {
// 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆到新接口后合并返回,
// 保持与原 getSystemInfo 一致的字段集合,避免调用方逐个改造。
const windowInfo = wx.getWindowInfo() || {}
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)
}
}
/**拨打电话 */
......
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
import { getSystemInfoSync } from '~/utils/systemInfo'
Component({
/**
* 组件的属性列表
......@@ -34,39 +36,35 @@ Component({
},
init() {
/**
* 获取自定义导航栏信息
* 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → getWindowInfo
* fontSizeSetting → getAppBaseInfo
*/
wx.getSystemInfo().then(res => {
let {
fontSizeSetting,
statusBarHeight,
screenWidth
} = res
const {
height,
right,
width,
top
} = wx.getMenuButtonBoundingClientRect(),
currentPages = getCurrentPages(), {
showBack
} = this.data
if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true
})
let navigationBarHeight = height + ((top - statusBarHeight) * 2)
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width * 2)
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
const { fontSizeSetting, statusBarHeight, screenWidth } = getSystemInfoSync()
const {
height,
right,
width,
top,
} = wx.getMenuButtonBoundingClientRect()
const currentPages = getCurrentPages()
const { showBack } = this.data
if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true
})
let navigationBarHeight = height + ((top - statusBarHeight) * 2)
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width * 2)
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
},
emit({
......
// packageEquity/pages/active/active.js
import { equityApi } from '~/api/api'
import USER from '~/api/usersApi/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({
/**
* 页面的初始数据
......@@ -109,7 +110,7 @@ Page({
},
onLoad: function (options) {
this.login()
let system = wx.getSystemInfoSync()
let system = getSystemInfoSync()
this.setData({
cHeight: system.windowHeight
})
......
import { equityApi } from '~/api/api'
import { isMember } from '~/utils/cache/storageApi'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({
/**
* 页面的初始数据
......@@ -16,7 +17,7 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let system = wx.getSystemInfoSync()
let system = getSystemInfoSync()
this.getAllMerchantList()
this.setData(
{
......
import { couponsApi, shopmallApi, ssoApi } from '~/api/api'
import USER from '~/api/usersApi/index'
import { defaultMerchantId } from '~/utils/request/environment'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({
data: {
freeDay: 0,
......@@ -110,7 +111,7 @@ Page({
})
},
onLoad(options) {
let system = wx.getSystemInfoSync()
let system = getSystemInfoSync()
const merchantId = wx.$storage.get('srcm_shopmall_merchant_id')
let newMerchantId = merchantId || defaultMerchantId
......
import { commonApi, equityApi } from '~/api/api'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({
data: {
tempFilePath: '',
......@@ -34,7 +35,7 @@ Page({
let query = wx.createSelectorQuery().in(this); //获取自定义组件的SelectQuery对象
this.canvasCtx = wx.createCanvasContext('signature', that)
// 设置线的样式
let { windowWidth, windowHeight } = wx.getSystemInfoSync()
let { windowWidth, windowHeight } = getSystemInfoSync()
this.canvasCtx.setFillStyle("white");
this.canvasCtx.fillRect(0, 0, windowWidth, windowHeight);
this.canvasCtx.setLineCap("round");
......
// components/navigationBar/navigationBar.js
import { getSystemInfoSync } from '~/utils/systemInfo'
Component({
/**
* 组件的属性列表
......@@ -33,24 +35,25 @@ Component({
},
init() {
/**
* 获取自定义导航栏信息
* 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → getWindowInfo
* fontSizeSetting → getAppBaseInfo
*/
wx.getSystemInfo().then(res => {
let { fontSizeSetting, statusBarHeight, screenWidth } = res
const { height, right, width, top } = wx.getMenuButtonBoundingClientRect()
let navigationBarHeight = height + (top - statusBarHeight) * 2 + 4 // 4
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width) - width
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
const { fontSizeSetting, statusBarHeight, screenWidth } = getSystemInfoSync()
const { height, right, width, top } = wx.getMenuButtonBoundingClientRect()
let navigationBarHeight = height + (top - statusBarHeight) * 2 + 4 // 4
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width) - width
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
},
emit({ navigationBarHeight, statusBarHeight }) {
......
......@@ -2,6 +2,7 @@
import { imgUrlMixin } from '~/mixins/index'
import index_const from '~/pages/tab/storeAssistant/pages/index/index_const'
import Draw from '~/utils/Draw'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({
/**
* 组件的属性列表
......@@ -20,7 +21,7 @@ Component({
wx.$api.showLoading('处理中')
val.boxImageHeight = 66
// 计算弹窗图片区域最大高度
let windowHeight = wx.getSystemInfoSync().windowHeight
let windowHeight = getSystemInfoSync().windowHeight
let res = {
height: windowHeight - 150
}
......
//index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from './u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
var uChartsInstance = {};
Component({
properties: {
......@@ -19,9 +20,9 @@ Component({
methods: {
setLine() {
//这里的第一个 750 对应 css .charts 的 width
const cWidth = 640 / 750 * wx.getSystemInfoSync().windowWidth;
const cWidth = 640 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height
const cHeight = 300 / 750 * wx.getSystemInfoSync().windowWidth;
const cHeight = 300 / 750 * getSystemInfoSync().windowWidth;
this.setData({
cWidth,
cHeight
......
// packageStoreAssistant/packageActivity/pages/pay/pay.js
import ActivityApi from '~/api/activityApi/index'
import wxqrcode from '~/utils/lib/wxqrcode'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
import {
centsToyuan,
accAdd
......@@ -234,7 +235,7 @@ Page({
// console.log(text)
let size = 0
try {
const info = wx.getSystemInfoSync()
const info = getSystemInfoSync()
let scale = info.windowWidth / 750 //不同屏幕下QRcode的适配比例;设计稿是750宽
let width = 300 * scale
size = width
......
// packageStoreAssistant/packageEquityClaims/components/picture/picture.js
import { commonApi } from '~/api/api'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
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'});
// if(e) return
const {count} = this.data.configOptions
let sysInfo = wx.getSystemInfoSync()
let sysInfo = getSystemInfoSync()
let maxNum = sysInfo?.environment ? 9 : 20 // 企微打开的话最大是9张。如果count大于9 会无法上传有异常
let aleadyLength = 0
if (batchFlag) {
......
import MineApi from '~/api/mineApi/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Page({
/**
* 页面的初始数据
......@@ -70,7 +71,7 @@ Page({
pageSize,
merchantId
}).then(res => {
let windowWidth = wx.getSystemInfoSync().windowWidth
let windowWidth = getSystemInfoSync().windowWidth
let activityTitleViewWidth = windowWidth - ((windowWidth / 375) * (46 + 48 + 160 + 24)) / 2 // 活动title区域宽度
res.list &&
res.list.forEach((val, index) => {
......
import { IMG_URL } from "~/utils/constantData";
import { discoveryApi,shopmallApi } from "~/api/api";
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({
/**
* 组件的属性列表
......@@ -95,7 +96,7 @@ Component({
}
});
const systemInfo = wx.getSystemInfoSync()
const systemInfo = getSystemInfoSync()
this.setData({
channelStyle,
list,
......
// pages/tab/storeAssistant/pages/index/components/clueManage/clueManage.js
import { imgUrlMixin } from '~/mixins/index'
import activityApi from '~/api/activityApi/index';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({
behaviors: [imgUrlMixin],
......@@ -49,7 +50,7 @@ Component({
methods: {
computeBottom() {
try {
wx.getSystemInfo({
getSystemInfo({
success: (res) => {
const ratio = res.screenWidth / 750
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
// import * as echarts from '../ec-canvas/echarts';
var uChartsInstance = {};
......@@ -33,9 +34,9 @@ Component({
methods: {
onReady() {
//这里的第一个 750 对应 css .charts 的 width
const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth;
const cWidth = 750 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height
const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
const cHeight = 500 / 750 * getSystemInfoSync().windowWidth;
this.setData({
cWidth: 320,
cHeight: 140
......
import { imgUrlMixin } from '~/mixins/index'
import USERAPI from "~/api/usersApi/index";
import activityApi from '~/api/activityApi/index';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
Component({
behaviors: [imgUrlMixin],
properties: {
......@@ -38,7 +39,7 @@ Component({
methods: {
computeBottom() {
try {
wx.getSystemInfo({
getSystemInfo({
success: (res) => {
const ratio = res.screenWidth / 750
const safeInsetBottom = res.safeArea ? (res.screenHeight - res.safeArea.bottom) : 0
......
......@@ -41,7 +41,11 @@
"ignoreDevUnusedFiles": false,
"condition": false,
"useApiHook": false,
"useApiHostProcess": false
"useApiHostProcess": false,
"compileWorklet": false,
"localPlugins": false,
"swc": false,
"disableSWC": true
},
"compileType": "miniprogram",
"simulatorType": "wechat",
......
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
createSigner,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
......@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
......@@ -29,7 +30,7 @@ export const salesGateway: GatewayStrategy = {
router: 'rop-scrm-sales/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'sales-sha1' }),
signer: createSigner({ kind: 'rop', id: 'sales-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
import {
equityApi
} from '~/api/api'
......@@ -48,7 +49,7 @@ export function getNavigationBarTitleText() {
/** 存储设备信息 */
export function setSystem_info(that) {
let info = $Storage.get('system_info')
!info && wx.getSystemInfo({
!info && getSystemInfo({
success(res) {
// console.log(res)
$Storage.set('system_info', res)
......
/**
* @file ROP 请求签名;序列化依赖 lib/qs(indices / allowDots / encodeValuesOnly)。
* 签名算法与 store/usedcar/points 同源,收敛到 @uj/api-core 的 createSha1Signer;
* 签名算法与 store/usedcar/points 同源,收敛到 @uj/api-core 的 createSigner;
* 签完仍返回摊平后的对象,它同时是 wx.request 的请求体(与原实现逐字节一致)。
*/
import qs from '../lib/qs'
import { createSha1Signer } from '@uj/api-core'
import { createSigner } from '@uj/api-core'
import environment from './environment.js'
const salesSigner = createSha1Signer({ id: 'sales-sha1' })
const salesSigner = createSigner({ kind: 'rop', id: 'sales-sha1' })
const flatten = params => {
const objStr = qs.stringify(params, {
......
/**
* sales 请求层:@uj/api-core 的客户端工厂。
*
* 一个 createRopClient({配置}) 直接拿到 client;平台(wx)、URL 拼装、签名、
* 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台(wx)、URL 拼装、签名、
* 拦截器(业务码归一 / 登录重放 / loading / toast)全在 api-core 里,本文件只传环境参数。
* public API 与旧壳逐签名一致:get/post/request(params, returnAll, isShowLoading, hostType)、
* reportTrack(params)、getMock(),453 处调用点零改动。
*/
// 小程序走主入口具名导出(构建 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 { login } from '~/utils/appFn/index'
const client = createRopClient({
const client = createClient({
kind: 'rop',
hosts: { scrm: domain, dj: djDomain, merchant: merchantDomain },
pathEnum,
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 {
Storage
} from '~/utils/cache/storage'
import sopApi from '~/api/sopApi'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const $Storage = new Storage()
/**
* 日期格式化
......@@ -31,7 +32,7 @@ const isEmptyObj = (obj) => {
};
const setNavigationBarTitle = (title) => {
wx.getSystemInfo({
getSystemInfo({
success: (res) => {
// console.log('++++++++++++++', res);
// console.log('title length',title.length)
......
import $router from '../router/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/**
* 微信校验通知类工具封装
......@@ -98,7 +99,7 @@ const wxShowToast = (name, params) => {
/**获取设备信息 */
const getSystemInfo = callBack => {
wx.getSystemInfo({
getSystemInfo({
success(res) {
callBack(res)
},
......@@ -131,7 +132,7 @@ const isFullSucreen = isComponents => {
let {
navigationStyle
} = __wxConfig.page[key].window
wx.getSystemInfo({
getSystemInfo({
success(res) {
if (res.platform != 'android') {
let {
......
......@@ -3,6 +3,7 @@ project.private.config.json
sitemap.json
miniprogram_npm
/miniprogram_npm
/miniprogram_npm.bak
node_modules
/node_modules
# local env files
......
// components/navigationBar/navigationBar.js
import { getSystemInfoSync } from '~/utils/systemInfo'
Component({
/**
* 组件的属性列表
......@@ -34,39 +36,35 @@ Component({
},
init() {
/**
* 获取自定义导航栏信息
* 获取自定义导航栏信息。
* 基础库 2.20.1+ 起 getSystemInfo 已废弃,按字段拆分到新接口:
* statusBarHeight / screenWidth → getWindowInfo
* fontSizeSetting → getAppBaseInfo
*/
wx.getSystemInfo().then(res => {
let {
fontSizeSetting,
statusBarHeight,
screenWidth
} = res
const {
height,
right,
width,
top
} = wx.getMenuButtonBoundingClientRect(),
currentPages = getCurrentPages(), {
showBack
} = this.data
if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true
})
let navigationBarHeight = height + ((top - statusBarHeight) * 2) + 4 // 4
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width) - width
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
const { fontSizeSetting, statusBarHeight, screenWidth } = getSystemInfoSync()
const {
height,
right,
width,
top,
} = wx.getMenuButtonBoundingClientRect()
const currentPages = getCurrentPages()
const { showBack } = this.data
if (showBack && currentPages.length > 1) this.setData({
SHOWBACK: true
})
let navigationBarHeight = height + ((top - statusBarHeight) * 2) + 4 // 4
let navigationBarPadding = screenWidth - right
let navigationBarWidth = screenWidth - (navigationBarPadding * 2 + width) - width
this.setData({
statusBarHeight,
navigationBarHeight,
navigationBarStyle: `font-size:${fontSizeSetting}px;`,
navigationBarTextWidth: `width:${navigationBarWidth}px;padding:0 ${navigationBarPadding}px;`
})
this.emit({
navigationBarHeight,
statusBarHeight
})
},
emit({
......
import WxCanvas from './wx-canvas';
import * as echarts from './echarts';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
let ctx;
......@@ -78,7 +79,7 @@ Component({
methods: {
init: function (callback) {
const version = wx.getSystemInfoSync().SDKVersion
const version = getSystemInfoSync().SDKVersion
const canUseNewCanvas = compareVersion(version, '2.9.0') >= 0;
const forceUseOldCanvas = this.data.forceUseOldCanvas;
......@@ -115,7 +116,7 @@ console.log(this.data.isUseNewCanvas)
echarts.setCanvasCreator(() => {
return canvas;
});
// const canvasDpr = wx.getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
// const canvasDpr = getSystemInfoSync().pixelRatio // 微信旧的canvas不能传入dpr
const canvasDpr = 1
var query = wx.createSelectorQuery().in(this);
query.select('.ec-canvas').boundingClientRect(res => {
......@@ -146,7 +147,7 @@ console.log(this.data.isUseNewCanvas)
const canvasNode = res[0].node
this.canvasNode = canvasNode
const canvasDpr = wx.getSystemInfoSync().pixelRatio
const canvasDpr = getSystemInfoSync().pixelRatio
const canvasWidth = res[0].width
const canvasHeight = res[0].height
......
//index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from '../../../../../utils/u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
var uChartsInstance = {};
Component({
properties: {
......@@ -33,10 +34,10 @@ Component({
isLabel
} = this.data
//这里的第一个 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
const cHeight = width / 750 * wx.getSystemInfoSync().windowWidth;
const pixelRatio = wx.getSystemInfoSync().pixelRatio;
const cHeight = width / 750 * getSystemInfoSync().windowWidth;
const pixelRatio = getSystemInfoSync().pixelRatio;
this.setData({
cWidth,
cHeight,
......
//index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from '../../../../../utils/u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const view = require('../view.js')
var uChartsInstance = {};
......@@ -16,10 +17,10 @@ Component({
methods: {
getRatio() {
//这里的第一个 750 对应 css .charts 的 width
const cWidth = 700 / 750 * wx.getSystemInfoSync().windowWidth;
const cWidth = 700 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height
const cHeight = 480 / 750 * wx.getSystemInfoSync().windowWidth;
const pixelRatio = wx.getSystemInfoSync().pixelRatio;
const cHeight = 480 / 750 * getSystemInfoSync().windowWidth;
const pixelRatio = getSystemInfoSync().pixelRatio;
this.setData({
cWidth,
cHeight,
......
//index.js
//注意!基础库【2.9.0】起支持 2d 模式,如不显示请检查基础库版本!
import uCharts from '../../../../../utils/u-charts/u-charts.js';
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const view = require('../view.js')
var uChartsInstance = {};
Component({
......@@ -14,9 +15,9 @@ Component({
methods: {
getRatio() {
//这里的第一个 750 对应 css .charts 的 width
const cWidth = 750 / 750 * wx.getSystemInfoSync().windowWidth;
const cWidth = 750 / 750 * getSystemInfoSync().windowWidth;
//这里的 500 对应 css .charts 的 height
const cHeight = 500 / 750 * wx.getSystemInfoSync().windowWidth;
const cHeight = 500 / 750 * getSystemInfoSync().windowWidth;
this.setData({
cWidth,
cHeight
......
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
createSigner,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
......@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
......@@ -29,7 +30,7 @@ export const storeGateway: GatewayStrategy = {
router: 'rop-scrm-store/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'store-sha1' }),
signer: createSigner({ kind: 'rop', id: 'store-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
// 实例化对象存储
import { Storage } from './storage'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const $Storage = new Storage()
// console.log($Storage)
/** */
......@@ -54,7 +55,7 @@ export function getNavigationBarTitleText() {
export function setSystem_info(that) {
let info = $Storage.get('system_info')
!info &&
wx.getSystemInfo({
getSystemInfo({
success(res) {
// console.log(res)
$Storage.set('system_info', res)
......
import { preReleaseAppId } from '~/config'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
const target = ['ip', 'dev', 'uat', 'prod', 'preRelease']
const mockObj = {
test: 'https://oss-config.dev.glsx.com.cn/mock/63fd6c2034c4d918e2f4df4d/config',
......@@ -15,7 +16,7 @@ const mockObj = {
// const index = 1
const accountInfo = wx.getAccountInfoSync()
const systemInfo = wx.getSystemInfoSync()
const systemInfo = getSystemInfoSync()
// console.log(systemInfo);
// console.log(accountInfo.miniProgram.envVersion)
//手动控制体验版环境的请求 true就依据下面index false就默认为2
......
import qs from '../lib/qs'
import { createSha1Signer } from '@uj/api-core'
import { createSigner } from '@uj/api-core'
import environment from './environment.js'
// 签名算法统一收口到 @uj/api-core 的 SHA1 预设;本文件只保留 mp 侧的「参数摊平」规则。
// 迁移时用脚本对老 sign() 逐字节验证过:扁平 / 中文与特殊字符 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined-数字-布尔 / dj 后端形状 共 8 类用例全部一致。
const storeSigner = createSha1Signer({ id: 'store-sha1' })
const storeSigner = createSigner({ kind: 'rop', id: 'store-sha1' })
/**
* 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
......
/**
* store 请求层:@uj/api-core 的客户端工厂。
*
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责,
* 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责,
* 本文件只传域名、凭据、会话与登录回调。
* public API 与旧壳一致:get/post/request(params, returnAll, requestPath),
* params 含 method,requestPath 对应 hostType(scrm/dj,缺省 scrm)。
*/
// 小程序走主入口具名导出(构建 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 { getSessionId } from '~/utils/cache/storageApi'
import network from '~/utils/network'
const client = createRopClient({
const client = createClient({
kind: 'rop',
hosts: { scrm: domain.scrm, dj: domain.dj, merchant: domain.merchant },
pathEnum,
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";
// equityApi
// } from '../api/api'
import $router from "../router/index";
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/**
* 日期格式化
......@@ -69,7 +70,7 @@ const isFullSucreen = (isComponents) => {
let val = false;
if (__wxConfig && __wxConfig.page && __wxConfig.page[key]) {
let { navigationStyle } = __wxConfig.page[key].window;
wx.getSystemInfo({
getSystemInfo({
success(res) {
if (res.platform != "android") {
let { statusBarHeight, screenHeight, windowHeight } = res;
......@@ -242,7 +243,7 @@ const deepClone = (target) => {
//设置标题
const setNavigationBarTitle = (title) =>{
wx.getSystemInfo({
getSystemInfo({
success: (res) => {
// console.log('++++++++++++++', res);
// console.log('title length',title.length)
......
import wxqrcode from '~/utils/lib/wxqrcode.js'
import $router from '../router/index'
import { getSystemInfoSync, getSystemInfo } from '~/utils/systemInfo'
/**
* 微信校验通知类工具封装
*/
......@@ -94,7 +95,7 @@ const wxShowToast = (name, params) => {
/**获取设备信息 */
const getSystemInfo = callBack => {
wx.getSystemInfo({
getSystemInfo({
success(res) {
callBack(res)
},
......@@ -179,7 +180,7 @@ const isFullSucreen = isComponents => {
let {
navigationStyle
} = __wxConfig.page[key].window
wx.getSystemInfo({
getSystemInfo({
success(res) {
if (res.platform != 'android') {
let {
......
import {
createRpcDispatcher,
createWxSender,
createSha1Signer,
createSigner,
registerGateway,
type GatewayStrategy,
type GatewayCredential,
......@@ -17,8 +17,9 @@ import {
* - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。
*
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同
* 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
*
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
......@@ -29,7 +30,7 @@ export const usedcarGateway: GatewayStrategy = {
router: 'rop-scrm-usedcar/router',
tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'usedcar-sha1' }),
signer: createSigner({ kind: 'rop', id: 'usedcar-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
......@@ -13,7 +13,7 @@ const require = createRequire(import.meta.url)
const rootDir = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..')
const qs = require(path.join(rootDir, 'utils/lib/qs.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]) */
function flatten(params) {
......@@ -54,7 +54,7 @@ function legacySign(params, secret, noSignAttr = []) {
return realObj
}
const signer = createSha1Signer({ id: 'usedcar-sha1' })
const signer = createSigner({ kind: 'rop', id: 'usedcar-sha1' })
/** 迁移后的加签路径:与 utils/request/http.js sign 同源 */
async function sign(params, secret, noSignAttr = []) {
......
......@@ -65,8 +65,8 @@ async function loadProjectHttpModule(environment) {
// http.js 的摘要已收口到 @uj/api-core;data: URL 模块解析不了裸包名,按同一路子注入。
source = replaceRequired(
source,
/import\s+\{\s*createSha1Signer\s*\}\s*from\s+['"]@uj\/api-core['"];?/,
`const { createSha1Signer } = globalThis[${JSON.stringify(contextKey)}].apiCore`,
/import\s+\{\s*createSigner\s*\}\s*from\s+['"]@uj\/api-core['"];?/,
`const { createSigner } = globalThis[${JSON.stringify(contextKey)}].apiCore`,
'api-core signer import'
)
source = replaceRequired(
......
......@@ -5,13 +5,13 @@
*/
import environment from './environment.js'
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'
// 与老 sign 的摘要算法字节级一致(迁移时用脚本验过:扁平 / 中文 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined / merchants 域名形状 全部通过)。
const usedcarSigner = createSha1Signer({ id: 'usedcar-sha1' })
const usedcarSigner = createSigner({ kind: 'rop', id: 'usedcar-sha1' })
/**
* 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
......
/**
* 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)、
* getMock()、getApiFoxMock(),46 处调用点零改动。
*
......@@ -11,7 +11,7 @@
* · 网络失败 / 超时提示改写 → beforeRequest / onTransportError
*/
// 小程序走主入口具名导出(构建 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 util from '~/utils/util.js'
import { envIndex } from '~/config'
......@@ -73,10 +73,15 @@ const ropOptions = {
}
// 常规请求: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,
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 { Suspense, useEffect, useState } from 'react';
import { Suspense, useEffect, useMemo, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
DashboardOutlined,
......@@ -10,12 +12,20 @@ import {
TeamOutlined,
AuditOutlined,
AppstoreOutlined,
FolderOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
GiftOutlined,
FileSyncOutlined,
FundOutlined,
TransactionOutlined,
SolutionOutlined,
HomeOutlined,
SettingOutlined,
} from '@ant-design/icons';
import { useAccess, buildMenus, type MenuGroupDef } from '@/access';
import { useAppStore } from '@/store/useAppStore';
import { menu as menuApi } from '@/api';
import { menu as menuApi, cancelRequests } from '@/api';
import { logoutEverything } from '../subapp-lifecycle';
import { Logo } from '@/components/Logo';
import { Skeleton } from '@uj/ui';
......@@ -57,25 +67,37 @@ const iconMap: Record<string, React.ReactNode> = {
TeamOutlined: <TeamOutlined />,
AuditOutlined: <AuditOutlined />,
UserOutlined: <UserOutlined />,
GiftOutlined: <GiftOutlined />,
FileSyncOutlined: <FileSyncOutlined />,
FundOutlined: <FundOutlined />,
TransactionOutlined: <TransactionOutlined />,
SolutionOutlined: <SolutionOutlined />,
HomeOutlined: <HomeOutlined />,
SettingOutlined: <SettingOutlined />,
};
/** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */
const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />;
/** 一级分组既无自身图标、也无子项可借时的兜底图标:折叠成图标栏时也有可点的入口 */
const GROUP_DEFAULT_ICON: React.ReactNode = <FolderOutlined />;
// 后端下发的 icon 是「antd 图标名字符串」,这里查表换成 React 节点。
// 未登记的图标名会静默回落默认图标 —— 这正是之前「菜单全是同一个图标」排查起来很痛苦的原因,
// 未登记的图标名会静默回落兜底图标 —— 这正是之前「菜单全是同一个图标」排查起来很痛苦的原因,
// 故开发环境对未知图标名告警一次(同名只报一次,避免菜单每项刷屏)。
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;
if (hit) return hit;
if (name && import.meta.env.DEV && !warnedIcons.has(name)) {
warnedIcons.add(name);
console.warn(
`[menu] 图标「${name}」未在 src/layouts/BasicLayout.tsx 的 iconMap 中登记,已回落默认图标。` +
`[menu] 图标「${name}」未在 src/layouts/BasicLayout.tsx 的 iconMap 中登记,已回落兜底图标。` +
`请在 iconMap 补一行,或让后端改发已支持的值。`,
);
}
return DEFAULT_MENU_ICON;
return fallback;
}
// 兜底菜单:接口失败/尚未返回时使用(与 src/config/menu.json 对应)
......@@ -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() {
const navigate = useNavigate();
const location = useLocation();
......@@ -123,14 +150,18 @@ export default function BasicLayout() {
};
}, [loggedIn, points]);
// 后端树为空(接口未就绪或该账号无任何菜单)时走兜底,避免侧边栏整组消失
const groups: MenuGroupDef[] = remoteGroups?.length
? [...FRONTEND_ONLY_GROUPS, ...remoteGroups]
: fallbackGroups;
// 后端树为空(接口未就绪或该账号无任何菜单)时走兜底,避免侧边栏整组消失。
// useMemo 固定引用:下面的 openKeys 校准 effect 依赖 groups,若每次渲染都生成新数组会导致 effect 反复执行。
const groups: MenuGroupDef[] = useMemo(
() => (remoteGroups?.length ? [...FRONTEND_ONLY_GROUPS, ...remoteGroups] : fallbackGroups),
[remoteGroups],
);
// -> antd Menu items(后端树已在 buildMenus 内与 permCodes 取过交集;兜底菜单按权限过滤)
// hideTitle 的分组不生成 type:'group',改由 children 平铺到当前层级——
// 这样是真没有标题节点,而不是用 CSS 把标题藏起来(藏起来会留下一行空白占位)。
// 普通分组渲染成【可折叠的 SubMenu】:点一级标题即可收起/展开其下的二级菜单项,
// 取代原先 type:'group' 标题组(inline 模式下永远展开、点不动)。菜单变多后靠折叠控制侧边栏长度。
// hideTitle 分组仍是平铺到顶层的普通菜单项(如「工作台」单入口),保持一点即达。
// SubMenu key 统一加 'group:' 前缀,与页面 path 区分开,避免 key 撞车。
const items: MenuItemType[] = groups.flatMap<MenuItemType>((g) => {
const children = g.children
.filter((m) => !m.resource || can(m.resource))
......@@ -139,7 +170,18 @@ export default function BasicLayout() {
icon: resolveIcon(m.icon),
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);
......@@ -158,6 +200,33 @@ export default function BasicLayout() {
const current = flat.find((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 登记的页题。
const crumbTitles = [
......@@ -186,7 +255,7 @@ export default function BasicLayout() {
<Sider
collapsed={collapsed}
trigger={null}
width={232}
width={216}
collapsedWidth={68}
className="uj-sider"
>
......@@ -208,8 +277,19 @@ export default function BasicLayout() {
mode="inline"
className="uj-menu"
selectedKeys={selectedKey ? [selectedKey] : []}
openKeys={openKeys}
onOpenChange={(keys) => setOpenKeys(keys.map(String))}
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>
</Sider>
......@@ -303,7 +383,7 @@ export default function BasicLayout() {
minHeight: 0,
overflow: 'auto',
background: 'var(--uj-bg)',
padding: 24,
padding: 12,
display: 'flex',
flexDirection: 'column',
}}
......
......@@ -25,7 +25,7 @@ export function Donut() {
return el;
});
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">
<circle cx={66} cy={66} r={r} fill="none" stroke="#F0F2F7" strokeWidth="14" />
{circles}
......
......@@ -52,6 +52,7 @@ export function LoginForm() {
dataScope: res.dataScope,
roleCodes: res.roleCodes ?? [],
permCodes: res.permCodes ?? [],
loginToken: res.loginToken,
});
// 菜单树与用户信息都按角色/账号下发:登录即视为账号切换点,旧缓存必须作废
menuApi.clearCache();
......
# 积分域老网关联调配置模板
# 用法:复制为 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=
......@@ -8,15 +8,15 @@
## 1. 静态闸门(本机实测,2026-11-06)
| 闸门 | 命令 | 结果 |
| ------ | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| 类型 | `npx tsc --noEmit` | 0 错 |
| Lint | `npx eslint . --max-warnings=0` | 0 错 0 警 |
| 格式 | `npx prettier --check`(本子应用全量) | 通过 |
| 构建 | `npx vite build` | 通过,3310 模块 / 1505.86 kB(gzip 480.88 kB) |
| 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1(store 既有 CSS,与本次无关);扫描 3 个子应用,points 在内 |
| 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 |
| 签名器 | `node --experimental-strip-types temp/md5-check.mjs` | 自写 MD5 与 `node:crypto` 217 组逐字节一致(RFC 1321 向量 + UTF-8 多字节 + 任意长度)。脚本已删 |
| 闸门 | 命令 | 结果 |
| ------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| 类型 | `npx tsc --noEmit` | 0 错 |
| Lint | `npx eslint . --max-warnings=0` | 0 错 0 警 |
| 格式 | `npx prettier --check`(本子应用全量) | 通过 |
| 构建 | `npx vite build` | 通过,3310 模块 / 1505.86 kB(gzip 480.88 kB) |
| 边界 | `node scripts/check-boundaries.mjs` | 错误 0,告警 1(store 既有 CSS,与本次无关);扫描 3 个子应用,points 在内 |
| 一致性 | `node scripts/reconcile.mjs` | 问题 0 —— 但它不检查 points,见第 6.1 |
| 签名 | `pnpm --filter @uj/api-core test`(`test/glsxSign.test.mjs`) | 真实抓包 11 字段复算 → `689F62277A050D6285B1E38BB2C3DA8D8E518EC9` 精确命中;MD5(32 位)明确不符,已固化成防回归闸门 |
浏览器里逐个页面的验收没做 —— 按约定静态闸门到此为止,视觉与交互由你点。第 9 节是可以照着点的清单。
......@@ -108,7 +108,7 @@
接口方法名、入参字段、返回结构一个字没改;改的是「怎么发出去、怎么读回来」。适配层在 [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`,页面与业务模块不需要知道对方是谁。
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 引用传给主壳,序列化不了它,所以主壳代码一行不用改。
请求仍然全部经 `requestViaHost()` → `window.$wujie.props.request(config)`,铁律「请求层绝不下放」没有被破坏([ARCHITECTURE.md §2](file:///D:/work/uj-admin/ARCHITECTURE.md))。
......@@ -196,4 +196,4 @@ points 里绕过去的地方都在本子应用内,没有 bypass 规范。欠
4. 第二个 tab:查看 → 付款审批(三层级联、税点重算总额、验证码倒计时)→ 编辑进批次(解散 / 移除)→ 到账明细(受理失败行再次打款)→ 行导出。
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';
/**
......@@ -19,11 +27,12 @@ const UJ_SUCCESS_CODE = 200;
const UJ_UNAUTHORIZED_CODE = 10002;
/**
* glsx 的 MD5 加签:secret 前后包裹、按 key 升序拼接 k+v、sign 大写。
* 现在由 api-core 的 createMd5Signer 生成——其默认配置(glsx 风格序列化 + both 包裹 + 大写)
* 与原手写实现字节级一致,这里只声明 id。换网关改 createMd5Signer 的配置即可,不再手写。
* glsx 的 SHA1 加签:secret 前后包裹、按 key 升序拼接 k+v、sign 40 位大写、timestamp 进原文。
* 依据 glsx-common/src/util.js#createSign 的默认 way='sha1',并经真实抓包 golden 值复算命中:
* 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 为验签保留原始响应串,所以字符串响应要先解析成对象。 */
function parseRawBody(raw: unknown): unknown {
......@@ -70,8 +79,11 @@ interface GlsxGatewayDef {
export function createGlsxGateway(def: GlsxGatewayDef): GatewayStrategy {
return {
...def,
signer: glxsrMd5Signer,
signer: glsxSha1Signer,
normalize: normalizeGlsxEnvelope,
// 老网关每次请求固定携带、且参与加签的渠道参数:与老系统 / 真实抓包一致用 'scrm-home'。
// 改这个值会直接改变签名原文,联调前不要随意换渠道名。
fixedParams: { source: 'scrm-home' },
};
}
......
......@@ -10,7 +10,7 @@ registerGateway(djSmartcarlifeGateway);
export {
createGlsxGateway,
djSmartcarlifeGateway,
glxsrMd5Signer,
glsxSha1Signer,
normalizeGlsxEnvelope,
scrmCarlifeGateway,
scrmShopmallGateway,
......
......@@ -13,7 +13,7 @@ export { registerGateway, resolveGateway } from '@uj/api-core';
export {
createGlsxGateway,
djSmartcarlifeGateway,
glxsrMd5Signer,
glsxSha1Signer,
normalizeGlsxEnvelope,
scrmCarlifeGateway,
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 { getLoginSession } from '@/access';
// 显式 import(而非依赖 barrel 的 re-export 副作用):保证任何调用路径下网关策略都已登记,
// 否则 resolveGateway 会抛「网关尚未接入」。
import './gateways';
......@@ -12,7 +21,7 @@ const LEGACY_TIMEOUT = 180000;
/**
* web 侧与四个原生小程序共用同一个 `@uj/api-core` 门面。
*
* 一个 createRpcGatewayClient({配置}) 拿到 client;方案(rpcGateway)、fixedParams 合并、
* createClient({配置}) 不传 kind 即最新版方案(rpcGateway);fixedParams 合并、
* 加签、router 落点、令牌头、信封归一全部由 registerGateway 登记的 GatewayStrategy 决定,
* 与小程序 createRpcDispatcher 共用 prepareRpcCall,字节同源。
* 平台差异只由 transport 一处表达:web 子应用走主壳注入的 axios(hostSend),
......@@ -24,13 +33,20 @@ const LEGACY_TIMEOUT = 180000;
* · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等),
* 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。
*/
export const request = createRpcGatewayClient({
export const request = createClient({
transport: 'host',
hostSend: requestViaHost(),
timeout: LEGACY_TIMEOUT,
contentType: false,
gatewayCredential: (id) => getGatewayCredential(id as GatewayId),
gatewayToken: getGatewayToken,
// sessionId 取自登录接口的 data.loginToken(老网关会话标识);facade 的 resolveSession 会在
// 签名前把它并入请求体并参与 SHA1 加签(与老系统请求体一致)。source 作为网关级固定参数已登记在
// 网关策略(glsx.ts 的 GatewayStrategy.fixedParams)里,这里无需重复配置。
session: {
sessionId: () => getLoginSession()?.loginToken ?? '',
paramName: 'sessionId',
},
errorHandler: (err) => {
throw err.cause ?? err;
},
......
......@@ -10,6 +10,21 @@ import type { GatewayId } from '@/adapter';
* @/adapter/rpc.ts 的 Request → 主壳 props.request,边界由 check-boundaries.mjs 复查。
*/
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>(
gateway: GatewayId,
method: string,
......
......@@ -20,7 +20,7 @@
.uj-points-detail-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 4px 16px;
gap: 4px 12px;
}
.uj-points-detail-item {
display: flex;
......@@ -41,28 +41,28 @@
white-space: nowrap;
}
/* 累计结算金额条:一排等宽浅灰平铺块,对齐老系统的 .statistics / .content-item。
老系统是 flex:1 的平铺灰块、无描边、无圆角,这里用 #f7f9fa 一致底色。 */
老系统是 flex:1 的平铺灰块、无描边、无圆角,这里用 surface-2 一致底色。 */
.uj-points-statistics {
display: flex;
flex-wrap: wrap;
gap: 12px;
gap: var(--uj-space-2, 8px);
/* 列表页里统计条只占自己那一行,剩余高度全给表格。 */
flex: none;
}
.uj-points-statistics-item {
flex: 1 1 200px;
min-width: 200px;
background: #f7f9fa;
border-radius: 8px;
padding: 16px;
flex: 1 1 180px;
min-width: 180px;
background: var(--uj-surface-2);
border-radius: 6px;
padding: 12px;
}
.uj-points-statistics-label {
color: var(--uj-text-3);
font-size: 14px;
margin-bottom: 12px;
font-size: 13px;
margin-bottom: 8px;
}
.uj-points-statistics-value {
font-size: 26px;
font-size: 22px;
font-weight: 700;
color: var(--uj-text-1);
}
......@@ -86,15 +86,15 @@
/* 统计条容器与标题行:对齐老系统 .statistics(无外框)与 .title(16px 粗体)。 */
.uj-points-statistics-card {
flex: none;
margin-bottom: 12px;
margin-bottom: var(--uj-space-module, 10px);
}
.uj-points-statistics-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
font-size: 16px;
gap: 8px;
margin-bottom: 8px;
font-size: 15px;
font-weight: 700;
color: var(--uj-text-1);
}
......@@ -149,7 +149,7 @@
display: block;
width: 100%;
border: 1px solid var(--uj-border);
border-radius: 8px;
border-radius: 6px;
}
.uj-points-idcard-empty {
display: flex;
......@@ -157,7 +157,7 @@
justify-content: center;
height: 96px;
border: 1px dashed var(--uj-border);
border-radius: 8px;
border-radius: 6px;
color: var(--uj-text-3);
}
/* 免责协议指向第三方域名,不写尺寸就会被 iframe 默认高度压成一条。 */
......@@ -166,7 +166,7 @@
width: 100%;
height: 60vh;
border: 1px solid var(--uj-border);
border-radius: 8px;
border-radius: 6px;
background: var(--uj-surface);
}
.uj-points-detail > .uj-points-detail-grid {
......@@ -180,7 +180,7 @@
margin-bottom: 12px;
padding: 6px 10px;
border: 1px solid var(--uj-border);
border-radius: 8px;
border-radius: 6px;
background: var(--uj-surface-2, var(--uj-surface));
font-size: 13px;
}
......@@ -208,7 +208,7 @@
}
.uj-points-tag-list {
margin: 0;
padding: 0 0 0 20px;
padding: 0 0 0 12px;
list-style: none;
}
.uj-points-tag-panel > .uj-points-tag-list {
......@@ -249,13 +249,13 @@
把页面整体收一档。共享令牌(圆角档、阴影、字号档、配色)保持不变。
改动只落在 points 目录的 page.css,packages 一行没动。 */
/* 页面骨架:整页与各区块之间的 gap,16 → 12。 */
/* 页面骨架:整页与各区块之间的 gap,统一到模块间距令牌(≤10px)。 */
.uj-points-app .uj-page {
gap: 12px;
gap: var(--uj-space-module, 10px);
}
/* 页头:标题块与右上角动作之间的 gap,20 → 12;标题降一档字号、收窄下边距。 */
/* 页头:标题块与右上角动作之间的 gap,收紧到 8px。 */
.uj-points-app .uj-page__header {
gap: 12px;
gap: 8px;
}
.uj-points-app .uj-page__title {
margin-bottom: 4px;
......@@ -288,21 +288,21 @@
padding: 8px 12px;
}
/* 工具条与分页:padding 12/20 → 8/16,内部 gap 12 → 8。 */
/* 工具条与分页:padding 8/12,内部 gap 8。 */
.uj-points-app .uj-table-toolbar {
gap: 8px;
padding: 8px 16px;
padding: 8px 12px;
}
.uj-points-app .uj-table .ant-table-pagination.ant-pagination {
padding: 8px 16px;
padding: 8px 12px;
}
/* 卡片圆角 12 → 8:在密集数据页里更利落、更精致(仅 points)。 */
.uj-points-app .uj-card {
border-radius: 8px;
border-radius: 6px;
}
/* 弹窗/抽屉里的表单项默认 24px,收到 16px;页面筛选区已内联 marginBottom:0 不受影响。 */
.uj-points-app .ant-form-item {
margin-bottom: 16px;
margin-bottom: var(--uj-space-module, 10px);
}
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 { pointsApi, type StaffScoreRow } from '@/api';
import { PP } from '@/permissions/codes';
......@@ -135,7 +135,6 @@ export default function ScoreUsers() {
}
>
<UTabs
className="uj-page__tabs"
activeKey={tab}
onChange={(key) => {
setTab(String(key));
......@@ -143,12 +142,9 @@ export default function ScoreUsers() {
}}
items={lists.map((item) => ({
key: item.key,
label: (
<>
{SCORE_TABS.find((tabItem) => tabItem.key === item.key)?.label}{' '}
<span className="uj-code">{item.query.isFetching ? '…' : item.total}</span>
</>
),
label: tabLabel(SCORE_TABS.find((tabItem) => tabItem.key === item.key)?.label, {
count: item.query.isFetching ? '…' : item.total,
}),
}))}
/>
<UCard className="uj-filter-card" size="small">
......
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { DownOutlined } from '@ant-design/icons';
import { UAlert, UButton, UCard, UDropdown, UResult, useUMessage } from '@uj/ui';
import {
ConfirmModal,
......@@ -42,6 +43,15 @@ import { TransferDetailDialog } from './components/TransferDetailDialog';
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 签约中)。 */
const REJECTABLE = new Set(['0', '1', '6', '8']);
......@@ -74,6 +84,9 @@ export default function WithdrawList() {
const [audit, setAudit] = useState<AuditAsk>();
const [pay, setPay] = useState<PayAsk>();
const [pendingPay, setPendingPay] = useState<PayAsk>();
// 两个下拉的展开态只用于箭头翻转指示。
const [batchMenuOpen, setBatchMenuOpen] = useState(false);
const [allMenuOpen, setAllMenuOpen] = useState(false);
const [batch, setBatch] = useState<BatchAsk>();
const [detailId, setDetailId] = useState<string>();
const [idCardRow, setIdCardRow] = useState<WithdrawRow>();
......@@ -379,6 +392,8 @@ export default function WithdrawList() {
) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY, PP.WITHDRAW_REJECT, PP.WITHDRAW_BATCH]) ? (
<UDropdown
open={batchMenuOpen}
onOpenChange={setBatchMenuOpen}
menu={{
items: [
{ key: '0', label: '批量审核' },
......@@ -389,11 +404,15 @@ export default function WithdrawList() {
onClick: ({ key }) => void runAction(Number(key) as 0 | 1 | 2 | 3, 'batch'),
}}
>
<UButton>批量操作</UButton>
<UButton icon={menuArrowIcon(batchMenuOpen)} iconPlacement="end">
批量操作
</UButton>
</UDropdown>
) : null}
{can([PP.WITHDRAW_APPROVE, PP.WITHDRAW_PAY]) ? (
<UDropdown
open={allMenuOpen}
onOpenChange={setAllMenuOpen}
menu={{
items: [
{ key: '0', label: '一键审核' },
......@@ -402,7 +421,9 @@ export default function WithdrawList() {
onClick: ({ key }) => void runAction(Number(key) as 0 | 1, 'all'),
}}
>
<UButton>一键操作</UButton>
<UButton icon={menuArrowIcon(allMenuOpen)} iconPlacement="end">
一键操作
</UButton>
</UDropdown>
) : null}
{can(PP.WITHDRAW_TAG) ? (
......
......@@ -26,7 +26,6 @@ export default function WithdrawManage() {
description="提现单从这里审核、付款、生成批次;批次再走 OA 付款审批,到账情况逐条可查。"
>
<UTabs
className="uj-page__tabs"
activeKey={active.key}
onChange={(key) => setTab(String(key))}
items={TABS.map((item) => ({ key: item.key, label: item.label }))}
......
import type { ReactNode } from 'react';
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 { StoreDictionaries } from './dictionaries';
import { dictionaryLabel, formatPolicyValue } from './formatters';
......@@ -81,14 +81,7 @@ function DetailContent({
const approvalTabs = [
{
key: 'market',
label: (
<span>
管理层市场费{' '}
<span className="approval-detail-tab-count" aria-hidden="true">
{detail.categoryCount ?? items.length}
</span>
</span>
),
label: tabLabel('管理层市场费', { count: detail.categoryCount ?? items.length }),
children: <ApprovalPolicyPanel detail={detail} spec={spec} kind="market" />,
},
{
......@@ -167,11 +160,12 @@ function DetailContent({
type="warning"
title="打回原因"
description={detail.rejectReason}
style={{ marginBottom: 16 }}
style={{ marginBottom: 'var(--uj-space-module, 10px)' }}
/>
)}
<UTabs
key={`${detail.listingId}:${mode}:${initialTab}:${open}`}
size="lg"
defaultActiveKey={selectedTab}
items={tabs}
/>
......@@ -211,7 +205,6 @@ export function StoreDetailDrawer({
)
}
closable={showCustomHeader ? false : undefined}
rootClassName={mode === 'listing' ? 'store-listing-detail' : 'store-approval-detail'}
styles={
mode === 'listing'
? { header: { padding: '16px 20px 20px' }, body: { padding: 20 } }
......
......@@ -35,7 +35,7 @@
min-width: 32px;
height: 32px;
padding: 0;
border-radius: 7px;
border-radius: 6px;
background: var(--uj-divider);
color: var(--uj-text-2);
font-size: 18px;
......@@ -120,7 +120,7 @@
}
.approval-detail-flow {
margin-bottom: 20px;
margin-bottom: var(--uj-space-module, 10px);
}
.approval-detail-flow__heading {
......@@ -249,49 +249,6 @@
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 {
display: flex;
flex-direction: column;
......@@ -304,7 +261,7 @@
gap: 12px;
padding: 14px 16px;
border: 1px solid var(--uj-border);
border-radius: 8px;
border-radius: 6px;
background: var(--uj-surface);
}
......@@ -391,11 +348,6 @@
flex-basis: 110px;
}
.store-approval-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.approval-detail-chaincard {
gap: 10px;
padding: 12px;
......
......@@ -5,7 +5,7 @@
.approval-policy-panel__table {
overflow: hidden;
border: 1px solid var(--uj-border);
border-radius: 8px;
border-radius: 6px;
background: var(--uj-surface);
}
......
......@@ -67,7 +67,7 @@ strong.listing-cost-panel__amount {
}
.listing-cost-panel__note {
margin: 22px 0 0;
margin: 10px 0 0;
line-height: 22px;
}
......
......@@ -7,7 +7,7 @@
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
gap: 10px;
}
.listing-detail-header__top h2 {
......@@ -32,7 +32,7 @@
min-width: 32px;
height: 32px;
padding: 0;
border-radius: 7px;
border-radius: 6px;
background: var(--uj-divider);
color: var(--uj-text-2);
font-size: 18px;
......@@ -46,7 +46,7 @@
.listing-detail-meta {
display: flex;
flex-wrap: wrap;
gap: 8px 20px;
gap: 8px 12px;
margin: 12px 0 0;
font-size: 14px;
font-weight: 400;
......@@ -112,34 +112,6 @@
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 {
color: var(--uj-text-1);
font-size: 14px;
......@@ -227,11 +199,6 @@
gap: 6px 14px;
}
.store-listing-detail .ant-tabs-tab {
padding: 10px 8px;
font-size: 14px;
}
.listing-store-info__fields > div {
grid-template-columns: 110px minmax(0, 1fr);
}
......
......@@ -29,12 +29,12 @@
display: grid;
grid-template-columns: 110px minmax(0, 1fr);
gap: 12px;
padding: 16px 0;
padding: 12px 0;
border-bottom: 1px solid var(--uj-divider);
}
.listing-change-history__version:first-of-type {
padding-top: 24px;
padding-top: 12px;
}
.listing-change-history__version-meta {
......@@ -106,7 +106,7 @@
}
.listing-change-history__empty {
margin: 16px 0;
margin: 10px 0;
}
@media (max-width: 600px) {
......
......@@ -5,12 +5,12 @@
.store-confirm-records {
max-height: 320px;
overflow: auto;
margin: var(--uj-space-4, 16px) 0;
margin: var(--uj-space-module, 10px) 0;
border: 1px solid var(--uj-border);
border-radius: var(--uj-radius-md, 8px);
border-radius: var(--uj-radius-md, 6px);
}
.store-confirm-record {
padding: var(--uj-space-3, 12px) var(--uj-space-4, 16px);
padding: 10px 14px;
border-bottom: 1px solid var(--uj-divider);
}
.store-confirm-record:last-child {
......
......@@ -30,7 +30,7 @@
align-items: center;
height: 22px;
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);
color: var(--uj-primary);
font-size: var(--uj-font-xs, 12px);
......@@ -50,7 +50,7 @@
gap: 5px;
height: 22px;
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-weight: 500;
font-variant-numeric: var(--uj-num, tabular-nums);
......
import { useEffect, useRef, useState } from 'react';
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 {
DataTable,
......@@ -265,7 +265,6 @@ export default function StoreApprove() {
description="按门店+业务场景审核上架数据,商务经理、财务经理依次审批;全部节点通过后生效。"
>
<UTabs
className="uj-page__tabs"
activeKey={tab}
onChange={(key) => {
setTab(key as ApproveTab);
......@@ -274,11 +273,7 @@ export default function StoreApprove() {
}}
items={tabDefs.map(({ key, label }, index) => ({
key,
label: (
<>
{label} <span className="uj-num">{lists[index].data?.total ?? '—'}</span>
</>
),
label: tabLabel(label, { count: lists[index].data?.total ?? '—' }),
}))}
/>
<UCard className="uj-filter-card" size="small">
......
......@@ -7,7 +7,7 @@
align-items: center;
height: 22px;
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);
color: var(--uj-primary);
font-size: var(--uj-font-xs, 12px);
......@@ -19,7 +19,7 @@
display: flex;
flex-direction: column;
gap: var(--uj-space-2, 8px);
margin-block: var(--uj-space-5, 20px);
margin-block: var(--uj-space-module, 10px);
}
.store-column-option {
......@@ -29,5 +29,5 @@
gap: var(--uj-space-3, 12px);
padding: var(--uj-space-2, 8px) var(--uj-space-3, 12px);
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 }) {
height: 2,
background: lineColor(status),
alignSelf: 'flex-start',
marginTop: 15,
marginTop: 10,
}}
/>
);
......@@ -151,8 +151,8 @@ export function ApprovalChainPreview({
return (
<UCard
styles={{ body: { padding: '20px 24px 24px' } }}
style={{ marginBottom: 20, border: '1px solid var(--uj-border)', borderRadius: 10 }}
styles={{ body: { padding: '14px 16px' } }}
style={{ marginBottom: 'var(--uj-space-module, 10px)', border: '1px solid var(--uj-border)', borderRadius: 10 }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
......@@ -160,7 +160,7 @@ export function ApprovalChainPreview({
</div>
}
>
<div style={{ display: 'flex', padding: '20px 8px 8px' }}>
<div style={{ display: 'flex', padding: '12px 8px 8px' }}>
{finalNodes.map((n, i) => {
const prev = finalNodes[i - 1];
const hasLeft = i > 0;
......@@ -186,7 +186,7 @@ export function ApprovalChainPreview({
<NodeIcon status={n.status} index={i} />
<div
style={{
marginTop: 14,
marginTop: 10,
fontSize: 14,
fontWeight: 600,
color:
......
......@@ -88,10 +88,10 @@ export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetail
return (
<UCard
styles={{ body: { padding: '18px 20px 14px' } }}
styles={{ body: { padding: '14px 16px 12px' } }}
style={{
border: '1px solid var(--uj-border)',
marginBottom: 20,
marginBottom: 'var(--uj-space-module, 10px)',
borderRadius: 12,
background: 'var(--uj-surface)',
overflow: 'hidden',
......@@ -140,7 +140,7 @@ export function FailDetailCard({ checkResult, fileSize, onReUpload }: FailDetail
maxHeight: 360,
overflowX: 'auto',
overflowY: 'auto',
marginBottom: 14,
marginBottom: 10,
}}
>
<table
......
......@@ -12,7 +12,7 @@ export interface ImportInfoValues {
}
const formItemLayout = {
style: { marginBottom: 18 },
style: { marginBottom: 'var(--uj-space-module, 10px)' },
};
export interface ImportInfoCardProps {
......@@ -94,8 +94,8 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
return (
<UCard
styles={{ body: { padding: 20 } }}
style={{ marginBottom: 20, border: '1px solid var(--uj-border)' }}
styles={{ body: { padding: 14 } }}
style={{ marginBottom: 'var(--uj-space-module, 10px)', border: '1px solid var(--uj-border)' }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
......@@ -115,7 +115,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gap: 20,
gap: 10,
}}
>
<UFormItem
......@@ -164,7 +164,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gap: 20,
gap: 10,
marginTop: 4,
}}
>
......@@ -180,7 +180,7 @@ export function ImportInfoCard({ values, checkResult, onChange }: ImportInfoCard
</div>
<UFormItem
label={<span style={{ marginTop: 18, display: 'inline-block' }}>备注</span>}
label={<span style={{ marginTop: 10, display: 'inline-block' }}>备注</span>}
name="remark"
style={{ marginBottom: 8 }}
>
......
......@@ -12,10 +12,10 @@ export function NoticeSection() {
return (
<UCard
styles={{
body: { padding: '16px 20px' },
body: { padding: '12px 14px' },
}}
style={{
marginBottom: 20,
marginBottom: 'var(--uj-space-module, 10px)',
border: '1px solid var(--uj-info-border)',
background: 'var(--uj-primary-soft)',
}}
......@@ -25,7 +25,7 @@ export function NoticeSection() {
display: 'flex',
alignItems: 'center',
gap: 10,
marginBottom: 14,
marginBottom: 10,
}}
>
<span
......
......@@ -33,7 +33,7 @@ export function PageHeader() {
];
return (
<div className="uj-page__header" style={{ marginBottom: 20 }}>
<div className="uj-page__header" style={{ marginBottom: 'var(--uj-space-module, 10px)' }}>
<div>
<h2 className="uj-page__title">导入门店信息</h2>
<p className="uj-page__desc">
......
......@@ -108,10 +108,10 @@ export function PolicyConfirmTable({
return (
<UCard
styles={{ body: { padding: '16px 16px 12px' } }}
styles={{ body: { padding: '14px 14px 10px' } }}
style={{
border: '1px solid var(--uj-border)',
marginBottom: 20,
marginBottom: 'var(--uj-space-module, 10px)',
borderRadius: 10,
overflow: 'hidden',
}}
......@@ -122,7 +122,7 @@ export function PolicyConfirmTable({
</div>
<div
style={{
marginTop: 12,
marginTop: 10,
padding: '10px 12px',
background: 'var(--uj-surface-2)',
borderRadius: 6,
......
......@@ -29,8 +29,8 @@ export function StepsBar({ current = 0 }: StepsBarProps) {
style={{
background: 'var(--uj-surface)',
borderRadius: 10,
padding: '20px 32px 12px',
marginBottom: 20,
padding: '14px 20px 8px',
marginBottom: 'var(--uj-space-module, 10px)',
border: '1px solid var(--uj-border)',
}}
>
......
......@@ -139,8 +139,8 @@ export function SubmitConfirmCard({
return (
<UCard
styles={{ body: { padding: '20px 24px' } }}
style={{ marginBottom: 20, border: '1px solid var(--uj-border)', borderRadius: 10 }}
styles={{ body: { padding: '14px 16px' } }}
style={{ marginBottom: 'var(--uj-space-module, 10px)', border: '1px solid var(--uj-border)', borderRadius: 8 }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
......@@ -158,7 +158,7 @@ export function SubmitConfirmCard({
display: 'flex',
alignItems: 'flex-start',
gap: 8,
marginBottom: 16,
marginBottom: 10,
}}
>
<ExclamationCircleOutlined
......@@ -182,7 +182,7 @@ export function SubmitConfirmCard({
padding: '14px 16px',
background: 'var(--uj-surface-2)',
borderRadius: 8,
marginBottom: 18,
marginBottom: 12,
}}
>
<UCheckbox
......@@ -199,7 +199,7 @@ export function SubmitConfirmCard({
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{infoRows.map((r) => (
<div key={r.label} style={{ display: 'flex', alignItems: 'flex-start' }}>
<span style={labelStyle}>{r.label}</span>
......
......@@ -214,8 +214,8 @@ export function UploadCard({
return (
<UCard
styles={{ body: { padding: 20 } }}
style={{ border: '1px solid var(--uj-border)', marginBottom: 20 }}
styles={{ body: { padding: 14 } }}
style={{ border: '1px solid var(--uj-border)', marginBottom: 'var(--uj-space-module, 10px)' }}
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<InfoCircleFilled style={{ color: 'var(--uj-primary)', fontSize: 14 }} />
......@@ -231,7 +231,7 @@ export function UploadCard({
>
<div style={{ position: 'relative' }}>
<UUpload.Dragger ref={uploadRef} {...uploadProps}>
<div style={{ padding: '30px 0' }}>
<div style={{ padding: '20px 0' }}>
<div
style={{
width: 48,
......@@ -241,7 +241,7 @@ export function UploadCard({
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 16,
marginBottom: 12,
}}
>
{uploading ? (
......@@ -306,7 +306,7 @@ export function UploadCard({
{fileList[0] && (
<div
style={{
marginTop: 16,
marginTop: 12,
display: 'flex',
alignItems: 'center',
padding: '14px 16px',
......@@ -324,7 +324,7 @@ export function UploadCard({
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
marginRight: 12,
marginRight: 8,
flex: 'none',
}}
>
......
......@@ -35,7 +35,7 @@ function StatCard({ item }: StatCardProps) {
const tone = toneMap[item.tone];
return (
<UCard
styles={{ body: { padding: '18px 20px' } }}
styles={{ body: { padding: '14px 16px' } }}
style={{
borderLeft: `3px solid ${tone.accent}`,
border: tone.border,
......@@ -139,8 +139,8 @@ export function ValidationStats({ stats, checkResult }: ValidationStatsProps) {
style={{
display: 'grid',
gridTemplateColumns: `repeat(${colCount}, minmax(0, 1fr))`,
gap: 16,
marginBottom: 20,
gap: 10,
marginBottom: 'var(--uj-space-module, 10px)',
}}
>
{finalStats.map((s) => (
......
......@@ -157,7 +157,7 @@ export function AccountFormDrawer({
onClose={onClose}
footer={
<div style={footerStyle}>
<UButton onClick={onClose}>取消</UButton>
<UButton type="default" onClick={onClose}>取消</UButton>
<UButton type="primary" loading={saveMutation.isPending} onClick={() => form.submit()}>
保存
</UButton>
......
......@@ -36,7 +36,7 @@ export function RoleDetailDrawer({ open, roleId, onClose }: RoleDetailDrawerProp
title={detail ? `角色详情 · ${detail.roleName}` : '角色详情'}
onClose={onClose}
footer={
<UButton style={{ float: 'right' }} onClick={onClose}>
<UButton type="default" style={{ float: 'right' }} onClick={onClose}>
关闭
</UButton>
}
......@@ -282,7 +282,7 @@ const summaryStyle = {
flexWrap: 'wrap' as const,
fontSize: 13,
gap: '8px 16px',
marginBottom: 18,
marginBottom: 'var(--uj-space-module, 10px)',
};
const sectionTitleStyle = {
alignItems: 'center',
......@@ -358,7 +358,7 @@ const legendStyle = {
display: 'flex',
flexWrap: 'wrap' as const,
fontSize: 12,
gap: 18,
gap: 10,
marginTop: 12,
};
const legendItemStyle = { alignItems: 'center', display: 'inline-flex', gap: 6 };
......@@ -132,7 +132,7 @@ export function RoleFormDrawer({ open, roleItem, onClose, onSuccess }: RoleFormD
onClose={onClose}
footer={
<div style={footerStyle}>
<UButton onClick={onClose}>取消</UButton>
<UButton type="default" onClick={onClose}>取消</UButton>
<UButton type="primary" loading={saveMutation.isPending} onClick={() => form.submit()}>
保存
</UButton>
......
......@@ -14,6 +14,9 @@ export default [
// 工具链只查各 lane 的 src/,lane 自己的 node --test 门禁在 lane 内跑。
ignores: [
'**/dist/**',
// api-core 的 tsup 还会产出 miniprogram_dist/index.js(小程序「构建 npm」用的
// 单文件 bundle),同样是生成物且已被 .gitignore 忽略,不能进 lint 口径。
'**/miniprogram_dist/**',
'**/node_modules/**',
'**/.turbo/**',
'**/coverage/**',
......
......@@ -19,6 +19,12 @@
"import": "./dist/index.js",
"require": "./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": [
......@@ -29,7 +35,7 @@
"build": "tsup",
"dev": "tsup --watch",
"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"
},
"devDependencies": {
......
......@@ -9,7 +9,7 @@
*
* 适用范围:web(Vite)/ Node 支持 package.json exports 子路径;
* 原生微信小程序的「构建 npm」不保证解析 exports,四个 mp app 统一走主入口具名导出
* `import { createRopClient } from '@uj/api-core'`,拿到的是同一个门面、同一份策略表。
* `import { createClient } from '@uj/api-core'`,拿到的是同一个门面、同一份策略表。
*/
export {
Request,
......@@ -17,16 +17,9 @@ export {
Defaults,
InterceptorManager,
RequestError,
strategies,
ropPreset,
gscPreset,
webHostPreset,
restPreset,
createRopClient,
createWebHostClient,
createRpcGatewayClient,
createRestClient,
createGscRestClient,
createSigner,
createStrategy,
createClient,
Request as default,
} from './index';
export type {
......
import { Request } from './facade';
import { Request } from '../core/facade';
import {
createStrategy,
ropPreset,
gscPreset,
webHostPreset,
restPreset,
rpcGatewayPreset,
} from './strategies';
import type { RopPresetOptions, RpcGatewayPresetOptions } from './strategies';
import type { RequestConfig } from './facade';
} from '../gateway/strategies';
import type {
CreateStrategyOptions,
RopPresetOptions,
RpcGatewayPresetOptions,
StrategyKind,
} from '../gateway/strategies';
import type { RequestConfig } from '../core/facade';
/**
* 客户端工厂:消费层的默认入口,与 `createGscClient` 同构 ——
......@@ -58,3 +64,29 @@ export function createRestClient(options: RequestConfig = {}): Request {
export function createGscRestClient(options: RequestConfig = {}): Request {
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;
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!