Compare commits

...

12 Commits

Author SHA1 Message Date
liufumingren
a5a6ea4a93 chore(frp): 新增 frpc 隧道安装/启动脚本与配置,忽略本地 frpc.exe 二进制 2026-09-23 02:46:44 +08:00
liufumingren
fa112891a9 docs(api): 同步微信模块 system.json 接口文档与变更记录(wechat.* 系列方法) 2026-09-23 02:46:39 +08:00
liufumingren
68a7e1b17d feat(wechat): 新增 wms_user_oauth / wms_wechat_app 表迁移及登录码、模板、审核、授权信息等字段 2026-09-23 02:46:34 +08:00
liufumingren
258232f98d feat(wechat): 微信开放平台第三方平台接入:授权事件回调、加解密、OpenAPI 客户端、oauth 登录态中间层与工牌扫码 2026-09-23 02:46:28 +08:00
liufumingren
b6baece8ad feat(workbench): 打包扫描单响应补充拣货人 picker_id/picker_name(波次关联拣货任务) 2026-09-23 02:46:22 +08:00
liufumingren
a078d74122 feat(order): parseAddress 改为内置省市字典本地解析,新增 parseAddressLocal,移除 DeepSeek AI 解析依赖 2026-09-23 02:46:16 +08:00
liufumingren
01acf106ae refactor(order): 自动出库当天订单开关改排除语义,allow_same_day_outbound 更名为 exclude_same_day_outbound(默认排除) 2026-09-23 02:46:11 +08:00
liufumingren
ec632cf3e5 feat(after-sale): 新增取消拦截子类型,补齐拦截/揽收/错发/多发运单号取号规则与关键词迁移 2026-09-23 02:46:06 +08:00
liufumingren
dde026d7dd feat(inbox): help 清单按群类型白名单过滤并按 sort_order 排序,回复占位符 back_text 回退 message 2026-09-23 02:46:00 +08:00
liufumingren
e8526e2bef feat: 自动出库规则支持当天订单限制配置
- 新增 allow_same_day_outbound(出库当天订单,默认否)
- 新增 same_day_outbound_deadline_time(允许当天出库最后时间,默认 06:00;复核时间早于该时间的订单不受关闭影响)
- 新增 same_day_outbound_release_time(当天放开时间,默认 22:00;当天到达该时间后放开当天复核订单)
- 保存校验:允许当天出库最后时间不能大于当天放开时间
- 出库扫描按 recheck_time 过滤:到达放开时间前,当天最后时间之后复核的订单不自动出库(北京时间边界,UTC 存储换算)
2026-09-23 02:22:23 +08:00
liufumingren
bf4920475d docs(api): 同步 business 打包分支 users 恢复说明与变更记录 2026-09-21 19:25:26 +08:00
liufumingren
df0c1735c8 fix(workbench): business 打包分支恢复 users 上报打包人,token+key 新链路保持工作台成员回填 2026-09-21 19:25:22 +08:00
47 changed files with 6979 additions and 440 deletions

3
.gitignore vendored
View File

@ -44,3 +44,6 @@ script/debug-*.cjs
.ssl/
nginx_config/
nginx-upstream-local.conf
# frpc binary (installed on demand by script/frp/frp-install.ps1)
script/frp/*.exe

View File

@ -186,9 +186,9 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 成员副表:`wms_workbench_member`(工作台成员/用户登录,user_id 可空兼容非系统账号用户、user_name 名称快照、软删除);`workbench.bindMember` 免登录免鉴权(入参 userId 可空 + userName 姓名必填 + 工作台 token)新增成员行;`workbench.removeMember` 免登录免鉴权(入参行 ids + 工作台 token)按 token 解析工作台后仅软删除归属该工作台的成员行,移除后该工作台已无任何成员时自动结束其所有未结束打包任务(wms_pack_task status<2 置 2 并写 end_time,同步回写订单打包状态与补确认打印状态、写完成操作日志、复位摄像头 OSD、失效 token 缓存,与 finishPack 语义一致,响应附 auto_finished_pack{finished,task_ids},2026-09-21 补充)
- 401/403 口径:/system 网关不支持方法内设置 HTTP 状态码,按现有惯例返回 `flag=failure、code=XXX` 业务失败(与 stock/warehouse.js 同款);公共 token 校验方法 `resolveWorkbenchContext(token)`(app/service/systems/workbench.js):无 token 统一返回 code=401(消息「工作台 token 不能为空」,2026-09-06 由 400 调整)、token 无效/工作台不存在(含软删除)返回 403(保持原口径),解析成功后写入 ctx.workbenchToken/ctx.workbenchId/ctx.workbenchWarehouseId 供后续方法使用(仓库限定,禁止跨仓库);`workbench.getWorkbenchInfo`/`workbench.bindMember`/`workbench.removeMember` 均统一走该校验(无 token 返回 401,bindMember/removeMember token 优先校验)
- 打包/称重三接口(2026-09-06 新增):`workbench.packOrder`(打包上报,推荐 key 模式:前端先扫码 `workbench.queryOrder` 拿 key(20 分钟有效),打包只传 token + key(除 token、key 外不再接收任何订单相关信息,body 其它字段一律忽略,防篡改;不传 key 时旧参数模式过渡兼容,后续版本移除),参数由后端从 Redis 缓存 workbench:packctx:{key} 拉取(含订单号/波次号/运单号),跨仓/跨台消费他人 key 返回 403、缺 key 或过期返回 400;响应 task_id/order_id/delivery_order_code/wave_no/isSandan/pack_mode/status,团购附 batch)、`workbench.finishPack`(打包完成,入参 token,响应 workbench_id/finished/task_id/order_id/end_time,无未结束任务 finished=false)、`workbench.sendWeight`(称重上报,入参 token/barcode/weight(单位克),散单响应 barcode/waybill_code/order_id/weighing_weight/items_weight/mode=single,团购波次响应另附 wave_id/wave_no/total_weight/order_count/mode=wave)均免登录/免权限/免鉴权,靠工作台 token 自校验;仓库与工作台均由服务端从 token 解析注入,body 传入 warehouse_id/workbench_id 一律忽略(禁止前端传值);三接口保留系统日志(systemInit 未声明免日志)
- 打包运单维度(2026-09-21 修复一单多号):`workbench.packOrder` 传运单号时按「订单+运单号」维度写入 wms_pack_task.waybill_code 并散单去重(同时清理同订单历史 waybill_code 为空的旧流水),主单号/子单号流水互不覆盖,未传保持订单维度(兼容旧设备端);团购为波次维度不使用运单号;打包人一律由服务端取该工作台绑定成员回填(wms_workbench_member,users 入参已移除,旧设备端传 users 被忽略,2026-09-21)
- 打包运单维度(2026-09-21 修复一单多号):`workbench.packOrder` 传运单号时按「订单+运单号」维度写入 wms_pack_task.waybill_code 并散单去重(同时清理同订单历史 waybill_code 为空的旧流水),主单号/子单号流水互不覆盖,未传保持订单维度(兼容旧设备端);团购为波次维度不使用运单号;打包人一律由服务端取该工作台绑定成员回填(wms_workbench_member,users 入参已移除、旧设备端传 users 被忽略,2026-09-21);business 旧链路(workbench.business 的 packOrder 分支)支持传入 users 上报打包人(未上报回填成员,2026-09-21 恢复)
- 条码查单接口(2026-09-06 新增):`workbench.queryOrder`(条码查订单,入参 token/barcode,响应 barcode/waybill_code/isSandan/store_remark/express/order/items/source_table,散单 order 附 intercept_flag/pack_flag 0/1 标志、团购附 batch 波次总量信息;items 逐项合并 stock 详情含 need_recheck 是否需要复核(Y=需要 N=不需要(免验),2026-09-19 补充);pack_flag 按运单维度判定(该运单号已有打包流水 wms_pack_task.waybill_code 命中或历史订单级流水 waybill_code 为空兜底时为 1,否则 0,主单号/子单号互不影响,流水查询异常降级订单级 pack_status 判定,2026-09-21 调整);查询成功时响应另附 key(打包上下文 key,wpck 前缀 + 随机段,Redis 缓存 workbench:packctx:{key} TTL 20 分钟,内容含订单号/波次号/运单号/归属仓库与工作台,供 workbench.packOrder 消费防篡改,2026-09-21 新增))免登录/免权限/免鉴权,靠工作台 token 自校验;仓库与工作台均由服务端从 token 解析注入,body 传入 warehouse_id/workbench_id 一律忽略(禁止前端传值);只读查询不涉及缓存失效;保留系统日志(systemInit 未声明免日志)
- 接口文档:`methods/system.json` 分组「工作台模块」(module=workbench)与「基础模块」(module=index),变更记录见 `methods/changes/system.json` 版本 `2026.09.03-workbench-login-code-token`、`2026.09.03-workbench-member-remove`、`2026.09.03-workbench-member-bind`、`2026.09.06-workbench-getWorkbenchInfo-members`、`2026.09.06-workbench-getWorkbenchInfo-current-packing`、`2026.09.06-workbench-getWorkbenchInfo-wave-items-total`、`2026.09.06-workbench-pack-order-finish-pack-send-weight`、`2026.09.06-workbench-queryOrder`、`2026.09.19-workbench-getWorkbenchInfo-order-items`、`2026.09.19-workbench-order-items-need-recheck`、`2026.09.19-workbench-getWorkbenchInfo-wave-items-summary`、`2026.09.21-workbench.packOrder-waybill-dimension`、`2026.09.21-workbench.removeMember-auto-finish-pack`、`2026.09.21-workbench.packOrder-remove-users-param`、`2026.09.21-workbench.packOrder-key-mode`、`2026.09.21-workbench.packOrder-key-only`、`2026.09.21-workbench.packOrder-legacy-compat`、`2026.09.21-workbench.packOrder-key-forward-fix`、`2026.09.21-workbench.getWorkbenchInfo-order-fields`
- 接口文档:`methods/system.json` 分组「工作台模块」(module=workbench)与「基础模块」(module=index),变更记录见 `methods/changes/system.json` 版本 `2026.09.03-workbench-login-code-token`、`2026.09.03-workbench-member-remove`、`2026.09.03-workbench-member-bind`、`2026.09.06-workbench-getWorkbenchInfo-members`、`2026.09.06-workbench-getWorkbenchInfo-current-packing`、`2026.09.06-workbench-getWorkbenchInfo-wave-items-total`、`2026.09.06-workbench-pack-order-finish-pack-send-weight`、`2026.09.06-workbench-queryOrder`、`2026.09.19-workbench-getWorkbenchInfo-order-items`、`2026.09.19-workbench-order-items-need-recheck`、`2026.09.19-workbench-getWorkbenchInfo-wave-items-summary`、`2026.09.21-workbench.packOrder-waybill-dimension`、`2026.09.21-workbench.removeMember-auto-finish-pack`、`2026.09.21-workbench.packOrder-remove-users-param`、`2026.09.21-workbench.packOrder-key-mode`、`2026.09.21-workbench.packOrder-key-only`、`2026.09.21-workbench.packOrder-legacy-compat`、`2026.09.21-workbench.packOrder-key-forward-fix`、`2026.09.21-workbench.getWorkbenchInfo-order-fields`、`2026.09.21-workbench.packOrder-business-users-restore`
- 当前打包信息:`workbench.getWorkbenchInfo` 响应 data 另含 `current_wave`(当前正在打包的团购波次,来自 wms_pack_task 最新一条 pack_mode=2 未结束任务,无则为空对象;含 order_count 波次订单数与 items_total 波次商品总件数,均按 current+dispatch 分表实时统计、15s 短缓存兜底)与 `current_orders`(未结束打包任务对应订单数组,逐单按 current→dispatch 分表补发货单号/order_type/store_id/items_count/items_total,另附任务表 item_quantity/sku_count/waybill_code,散单任务(pack_mode=1)附 items 商品明细数组(复用 _fetchOrderItemsDetail 公共方法,与 workbench.queryOrder 的 items 同源,含条码/图片/包装要求/need_recheck 是否需要复核),另补货主备注 store_remark 与运单信息 express(物流公司/称重重量/包材名称,与 queryOrder 口径一致,2026-09-21 补充),团购任务(pack_mode=2)items 为波次商品 SKU 聚合汇总(_fetchWaveItemsSummary,波次内全部未拦截订单按 SKU 聚合计划数量并合并 stock 详情,15s 短缓存兜底,元素另附 is_wave_summary=true),无则为空数组);打包信息随 `workbench:token:{token}` 缓存(TTL 300s)一并缓存,packOrder/finishPack 状态变更后主动失效缓存,查询异常降级为空对象/空数组(单笔商品明细异常仅 items 降级为空数组)
- 迁移:`database/migrations/20260903100000-add-login-code-token-to-wms-workbench.js`(幂等 up/down,已在开发库执行;生产库待发布时按标准流程执行)
@ -432,8 +432,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- list, manualOutboundOrder
- app/service/systemMethods/order/packing.js (11)
- list, get, setEndTime, forceRecord, export, exportTaskProgress, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/order/pendingOrder.js (41)
- list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, _parseAddressBatchOneShot, _parseSingleAddress, catch
- app/service/systemMethods/order/pendingOrder.js (40)
- list, detail, reverseReviewOrder, assertOrdersWithoutWaybill, syncWavesAfterReverseReview, allocateStorage, allocateStorageProgress, normalizeAllocateStorageTaskProgress, normalizeAllocateStorageTaskCount, normalizeAllocateStorageTaskCounts, normalizeAllocateStorageRequestId, getAllocateStorageTaskCacheKey, setAllocateStorageTaskProgress, getAllocateStorageTaskProgress, getAllocateExpressTaskCacheKey, normalizeAllocateExpressTaskId, setAllocateExpressTaskProgress, getAllocateExpressTaskProgress, getSyncOrderIdsTaskCacheKey, normalizeSyncOrderIdsRequestId, setSyncOrderIdsTaskProgress, getSyncOrderIdsTaskProgress, cancelAllocateStorage, syncOrderIds, syncOrderIdsProgress, allocateExpressCode, allocateExpressCodeTaskProgress, markPendingOutboundOrder, cancelOrder, normalizePendingOutboundOrderIds, normalizePendingCancelOrderIds, isCancelablePendingOrder, updateOrderPlatform, updateOrderExpress, updateAddress, updateRemark, cloneOrder, parseAddress, parseAddressLocal, catch
- app/service/systemMethods/order/print.js (4)
- getWavePlatformPrintData, getOrderPrintData, getPrintDataByWaybillCodes, unlockWavePlatformPrintDataByGroup
- app/service/systemMethods/order/recheckOrder.js (60)

View File

@ -0,0 +1,338 @@
'use strict';
const Controller = require('egg').Controller;
const wechatOpenCrypt = require('../lib/wechat_open_crypt');
const WechatOpenClient = require('../lib/wechat_open_client');
/**
* 微信开放平台第三方平台回调 Controller。
* 接收微信服务器推送的授权事件(组件票据/授权成功/授权更新/取消授权),
* 对应路由 GET|POST /Authorization。
*/
class WechatOpenController extends Controller {
/**
* 读取原始请求体(微信推送为 text/xml,bodyParser 默认不解析)。
* @return {Promise<string>} 原始请求体字符串。
*/
async readRawBody() {
const { ctx } = this;
if (ctx.request.rawBody) {
return String(ctx.request.rawBody);
}
return await new Promise((resolve, reject) => {
let data = '';
ctx.req.on('data', chunk => {
data += chunk;
});
ctx.req.on('end', () => resolve(data));
ctx.req.on('error', reject);
});
}
/**
* 授权事件接收入口(GET=URL 验证,POST=事件推送)。
* @return {Promise<void>}
*/
async authorization() {
const { ctx, app } = this;
const config = (app.config && app.config.wechatOpen) || {};
const signature = String(ctx.query.signature || '');
const timestamp = String(ctx.query.timestamp || '');
const nonce = String(ctx.query.nonce || '');
const echostr = String(ctx.query.echostr || '');
const msgSignature = String(ctx.query.msg_signature || '');
const state = String(ctx.query.state || '');
const authCode = String(ctx.query.auth_code || '');
// ─── URL 有效性验证(首次配置服务器地址时) ───────────────
if (echostr) {
const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce);
ctx.logger.info(`[wechatOpen] URL 验证 ${valid ? '通过' : '失败'}`);
ctx.body = valid ? echostr : '签名验证失败';
return;
}
// ─── 授权回跳(微信授权完成后重定向 GET,带 state/auth_code;state 缺失同样走 view 提示) ───
if (ctx.method === 'GET') {
await this.handleAuthCallback(state, authCode);
return;
}
try {
const rawBody = await this.readRawBody();
if (!rawBody || !rawBody.trim()) {
ctx.logger.error('[wechatOpen] 接收到的推送体为空');
ctx.body = 'fail';
return;
}
const decryptResult = wechatOpenCrypt.decryptMsg({
token: config.token,
encodingAesKey: config.encoding_aes_key,
componentAppid: config.component_appid,
msgSignature,
timestamp,
nonce,
encryptedXml: rawBody,
});
if (decryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
ctx.logger.error(`[wechatOpen] 消息解密失败 code=${decryptResult.code} msg=${decryptResult.msg}`);
ctx.body = 'fail';
return;
}
const msgObj = wechatOpenCrypt.parseXml(decryptResult.msg);
const infoType = String(msgObj.InfoType || '');
const event = String(msgObj.Event || '');
ctx.logger.info(`[wechatOpen] 收到推送 InfoType=${infoType} Event=${event}`);
// 小程序事件(如审核结果)用 Event 字段分发,组件事件用 InfoType 分发
await this.handleEvent(event || infoType, msgObj);
// 微信要求回显 success 表示处理成功
ctx.body = 'success';
} catch (e) {
ctx.logger.error(`[wechatOpen] 处理异常: ${e.message}`, e);
ctx.body = 'fail';
}
}
/**
* 授权回跳处理:凭 state 取回仓库信息,用 auth_code 换取令牌并落库绑定仓库。
* @param {string} state 发起授权时缓存的随机 state。
* @param {string} authCode 微信回跳携带的授权码。
* @return {Promise<void>}
*/
async handleAuthCallback(state, authCode) {
const { ctx, app } = this;
const client = new WechatOpenClient(ctx);
const render = viewData => ctx.render('wechat_auth_callback.html', viewData);
if (!state) {
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 state 参数,请从系统重新发起授权' });
}
const stateInfo = await client.getAuthState(state);
if (!stateInfo) {
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '授权链接已过期或不存在,请重新发起授权' });
}
if (!authCode) {
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 auth_code 参数' });
}
try {
// 用授权码换取授权方令牌(不依赖 authorized 事件时序)
const authorizationInfo = await client.queryAuth(authCode);
const authorizerAppid = authorizationInfo.authorizer_appid;
if (!authorizerAppid) throw new Error('授权信息缺少 authorizer_appid');
const nowSec = Math.floor(Date.now() / 1000);
const fields = {
warehouse_id: stateInfo.warehouse_id || null,
authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null,
auth_time: nowSec,
func_info: JSON.stringify(authorizationInfo.func_info || []),
is_enabled: 1,
};
// 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断
try {
const detail = await client.getAuthorizerDetail(authorizerAppid);
if (detail) {
Object.assign(
fields,
ctx.service.systems.wechat.buildAuthorizerPatch(
detail.authorizer_info,
detail.authorization_info || {}
)
);
}
} catch (e) {
ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`);
}
const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } });
if (existing) {
await existing.update(fields);
} else {
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
}
// 令牌写入 Redis 缓存(不落库)
await client.cacheSet(
`App:${authorizerAppid}:AuthorizerAccessToken`,
authorizationInfo.authorizer_access_token,
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
);
await client.cacheSet(
`App:${authorizerAppid}:authorizer_refresh_token`,
authorizationInfo.authorizer_refresh_token,
30 * 24 * 3600
);
// state 一次性消费
await client.clearAuthState(state);
ctx.logger.info(`[wechatOpen] 授权回调成功 appid=${authorizerAppid} warehouse_id=${fields.warehouse_id}`);
return render({
title: '微信授权结果',
resultLevel: 'success',
resultText: '授权成功,小程序已绑定仓库',
appid: authorizerAppid,
nickname: fields.nickname || '',
warehouseId: fields.warehouse_id || null,
});
} catch (e) {
ctx.logger.error(`[wechatOpen] 授权回调处理失败: ${e.message}`, e);
return render({
title: '微信授权结果',
resultLevel: 'error',
resultText: `授权处理失败:${e.message}`,
appid: '',
nickname: '',
warehouseId: null,
});
}
}
/**
* 按 InfoType 分发处理授权事件。
* @param {string} infoType 事件类型。
* @param {object} msgObj 解密后的消息对象。
* @return {Promise<void>}
*/
async handleEvent(infoType, msgObj) {
const { ctx, app } = this;
const client = new WechatOpenClient(ctx);
switch (infoType) {
case 'component_verify_ticket': {
// 组件票据:每 10 分钟推送一次,缓存后用于换取 component_access_token
const ticket = String(msgObj.ComponentVerifyTicket || '');
if (!ticket) {
ctx.logger.error('[wechatOpen] component_verify_ticket 事件缺少 ComponentVerifyTicket');
return;
}
await client.saveComponentVerifyTicket(ticket);
ctx.logger.info(`[wechatOpen] 已保存 ComponentVerifyTicket(AppId: ${msgObj.AppId})`);
break;
}
case 'authorized':
case 'updateauthorized': {
const authorizerAppid = String(msgObj.AuthorizerAppid || '');
const authorizationCode = String(msgObj.AuthorizationCode || '');
if (!authorizerAppid || !authorizationCode) {
ctx.logger.error(`[wechatOpen] ${infoType} 事件缺少 AuthorizerAppid/AuthorizationCode`);
return;
}
// 暂存授权码(供后续换取令牌使用)
await client.saveAuthorizationCode(authorizerAppid, authorizationCode);
// 用授权码换取授权方令牌与权限集合
const authorizationInfo = await client.queryAuth(authorizationCode);
const nowSec = Math.floor(Date.now() / 1000);
const fields = {
authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null,
auth_time: nowSec,
func_info: JSON.stringify(authorizationInfo.func_info || []),
is_enabled: 1,
};
// authorizer_access_token 存入 Redis 缓存(自动过期),不落库
await client.cacheSet(
`App:${authorizerAppid}:AuthorizerAccessToken`,
authorizationInfo.authorizer_access_token,
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
);
await client.cacheSet(
`App:${authorizerAppid}:authorizer_refresh_token`,
authorizationInfo.authorizer_refresh_token,
30 * 24 * 3600
);
// 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断
try {
const detail = await client.getAuthorizerDetail(authorizerAppid);
if (detail) {
Object.assign(
fields,
ctx.service.systems.wechat.buildAuthorizerPatch(
detail.authorizer_info,
detail.authorization_info || {}
)
);
}
} catch (e) {
ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`);
}
const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } });
if (existing) {
await existing.update(fields);
ctx.logger.info(`[wechatOpen] 已更新授权记录 appid=${authorizerAppid}`);
} else {
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
ctx.logger.info(`[wechatOpen] 已新增授权记录 appid=${authorizerAppid}`);
}
break;
}
case 'unauthorized': {
const authorizerAppid = String(msgObj.AuthorizerAppid || '');
if (!authorizerAppid) {
ctx.logger.error('[wechatOpen] unauthorized 事件缺少 AuthorizerAppid');
return;
}
// 清理令牌缓存
await client.clearAuthorizerCache(authorizerAppid);
// 停用授权记录(保留记录供追溯)
await app.model.WechatApp.update(
{ is_enabled: 0 },
{ where: { appid: authorizerAppid } }
);
ctx.logger.info(`[wechatOpen] 已停用授权记录 appid=${authorizerAppid}`);
break;
}
case 'weapp_audit_success': {
// 代码审核通过:按小程序原始ID(ToUserName=gh_xxx)定位记录,状态置 2
const originalId = String(msgObj.ToUserName || '').trim();
if (!originalId) {
ctx.logger.error('[wechatOpen] weapp_audit_success 缺少 ToUserName');
return;
}
await app.model.WechatApp.update(
{ audit_status: 2, audit_reason: '' },
{ where: { user_name: originalId } }
);
ctx.logger.info(`[wechatOpen] 审核通过 originalId=${originalId}`);
break;
}
case 'weapp_audit_fail': {
// 代码审核驳回:状态置 3 并记录驳回原因
const originalId = String(msgObj.ToUserName || '').trim();
if (!originalId) {
ctx.logger.error('[wechatOpen] weapp_audit_fail 缺少 ToUserName');
return;
}
await app.model.WechatApp.update(
{ audit_status: 3, audit_reason: String(msgObj.Reason || '') },
{ where: { user_name: originalId } }
);
ctx.logger.info(`[wechatOpen] 审核驳回 originalId=${originalId} reason=${msgObj.Reason || ''}`);
break;
}
default:
ctx.logger.info(`[wechatOpen] 未处理的 InfoType: ${infoType}`);
break;
}
}
}
module.exports = WechatOpenController;

View File

@ -0,0 +1,677 @@
'use strict';
/**
* 微信开放平台第三方平台 API 客户端。
* 封装组件级接口调用与 token 管理(Redis 缓存,Key 与参考实现一致):
* - component_access_token:调用授权方接口的组件凭证(约 2 小时)。
* - App:{appid}:authorization_code:授权码(authorized 事件推送后暂存)。
* - App:{appid}:authorizer_refresh_token:授权方刷新令牌(长期)。
* - App:{appid}:AuthorizerAccessToken:授权方接口调用凭证(约 2 小时)。
*
* 配置读取 app.config.wechatOpen:
* - component_appid / component_secret / token / encoding_aes_key / api_base
*/
const DEFAULT_API_BASE = 'https://api.weixin.qq.com';
/** 缓存预留提前量(秒):token 在过期前提前失效,避免临界调用失败。 */
const EXPIRE_MARGIN = 300;
class WechatOpenClient {
/**
* @param {object} ctx Egg 上下文。
*/
constructor(ctx) {
this.ctx = ctx;
this.app = ctx.app;
this.config = (this.app && this.app.config && this.app.config.wechatOpen) || {};
}
/**
* 获取 Redis 客户端(cache 库),不可用时返回 null。
* @return {object|null} ioredis 客户端。
*/
redis() {
return this.app && this.app.redis && typeof this.app.redis.get === 'function'
? this.app.redis.get('cache')
: null;
}
/**
* 读取缓存。
* @param {string} key Redis key。
* @return {Promise<string|null>} 缓存值。
*/
async cacheGet(key) {
const redis = this.redis();
if (!redis) return null;
return redis.get(key);
}
/**
* 写入缓存。
* @param {string} key Redis key。
* @param {string} value 值。
* @param {number} ttl 过期秒数。
* @return {Promise<void>}
*/
async cacheSet(key, value, ttl) {
const redis = this.redis();
if (!redis) return;
await redis.set(key, value, 'EX', ttl);
}
/**
* 删除缓存。
* @param {...string} keys Redis keys。
* @return {Promise<void>}
*/
async cacheDel(...keys) {
const redis = this.redis();
if (!redis || keys.length === 0) return;
await redis.del(...keys);
}
/**
* 发起微信 API POST 请求(JSON)。
* @param {string} path API 路径(不含 base)。
* @param {object} body 请求体。
* @param {string} [token] component_access_token(作为 URL query 拼接)。
* @return {Promise<object>} 响应 JSON。
*/
async apiPost(path, body, token) {
const base = this.config.api_base || DEFAULT_API_BASE;
let url = base.replace(/\/$/, '') + path;
if (token) {
url += `${url.includes('?') ? '&' : '?'}component_access_token=${encodeURIComponent(token)}`;
}
const response = await this.ctx.curl(url, {
method: 'POST',
dataType: 'json',
timeout: 30000,
headers: { 'Content-Type': 'application/json' },
data: body,
});
return response && response.data !== undefined ? response.data : response;
}
/**
* 携带 component_access_token 发起 POST 请求;遇 40001(invalid credential,token 被别处刷新顶掉)
* 时自动清除缓存 token、重取后重试一次。
*
* @param {string} path API 路径(不含 base)。
* @param {object} body 请求体。
* @return {Promise<object>} 响应 JSON(必要时重试后)。
*/
async apiPostWithComponentToken(path, body) {
let result = await this.apiPost(path, body, await this.getComponentAccessToken());
if (result && Number(result.errcode) === 40001) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn(`[wechatOpen] component_access_token 失效(40001),清除缓存重试: ${path}`);
}
await this.cacheDel('component_access_token');
result = await this.apiPost(path, body, await this.getComponentAccessToken());
}
return result;
}
/**
* 保存 ComponentVerifyTicket(component_verify_ticket 事件推送后调用)。
* @param {string} ticket 推送的 Ticket。
* @return {Promise<void>}
*/
async saveComponentVerifyTicket(ticket) {
// 微信每 10 分钟推送一次,ticket 有效期 12 小时。
// 缓存 12 小时:异常未及时收到推送时,继续用上一次可用 ticket 换取 component_access_token(官方建议)。
await this.cacheSet('ComponentVerifyTicket', ticket, 12 * 3600);
}
/**
* 获取组件接口调用凭证 component_access_token(缓存优先)。
* @return {Promise<string>} component_access_token。
*/
async getComponentAccessToken() {
const cached = await this.cacheGet('component_access_token');
if (cached) return cached;
const ticket = await this.cacheGet('ComponentVerifyTicket');
if (!ticket) {
throw new Error('ComponentVerifyTicket 不存在,请等待微信推送后重试');
}
const result = await this.apiPost('/cgi-bin/component/api_component_token', {
component_appid: this.config.component_appid,
component_appsecret: this.config.component_secret,
component_verify_ticket: ticket,
});
if (result && result.component_access_token) {
const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN;
await this.cacheSet('component_access_token', result.component_access_token, Math.max(ttl, 60));
return result.component_access_token;
}
throw new Error(`获取 component_access_token 失败: ${JSON.stringify(result)}`);
}
/**
* 保存授权码(authorized/updateauthorized 事件推送后调用)。
* @param {string} authorizerAppid 授权方小程序 AppID。
* @param {string} authorizationCode 授权码。
* @return {Promise<void>}
*/
async saveAuthorizationCode(authorizerAppid, authorizationCode) {
// 授权码有效期 1 小时
await this.cacheSet(`App:${authorizerAppid}:authorization_code`, authorizationCode, 3600);
}
/**
* 使用授权码换取授权方令牌(api_query_auth)。
* @param {string} authorizationCode 授权码。
* @return {Promise<object>} authorization_info(含 authorizer_refresh_token/
* authorizer_access_token/expires_in/func_info 等)。
*/
async queryAuth(authorizationCode) {
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_query_auth', {
component_appid: this.config.component_appid,
authorization_code: authorizationCode,
});
if (result && result.authorization_info) {
return result.authorization_info;
}
throw new Error(`获取 authorizer_refresh_token 失败: ${JSON.stringify(result)}`);
}
/**
* 获取/刷新授权方接口调用凭证 authorizer_access_token(缓存优先)。
* @param {string} appid 授权方小程序 AppID。
* @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取)。
* @return {Promise<object>} { authorizerAccessToken, authorizerRefreshToken }。
*/
async getAuthorizerAccessToken(appid, refreshToken) {
const tokenKey = `App:${appid}:AuthorizerAccessToken`;
const cached = await this.cacheGet(tokenKey);
if (cached) {
return { authorizerAccessToken: cached, authorizerRefreshToken: refreshToken || null };
}
let token = refreshToken || (await this.cacheGet(`App:${appid}:authorizer_refresh_token`));
if (!token) {
throw new Error(`App:${appid} 的 authorizer_refresh_token 不存在`);
}
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_authorizer_token', {
component_appid: this.config.component_appid,
authorizer_appid: appid,
authorizer_refresh_token: token,
});
if (result && result.authorizer_access_token) {
const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN;
await this.cacheSet(tokenKey, result.authorizer_access_token, Math.max(ttl, 60));
if (result.authorizer_refresh_token) {
token = result.authorizer_refresh_token;
await this.cacheSet(`App:${appid}:authorizer_refresh_token`, token, 30 * 24 * 3600);
}
return { authorizerAccessToken: result.authorizer_access_token, authorizerRefreshToken: token };
}
throw new Error(`获取 authorizer_access_token 失败: ${JSON.stringify(result)}`);
}
/**
* 获取授权方基本信息(api_get_authorizer_info:昵称/头像/原始ID)。
* @param {string} appid 授权方小程序 AppID。
* @return {Promise<object>} authorizer_info。
*/
async getAuthorizerInfo(appid) {
const detail = await this.getAuthorizerDetail(appid);
if (detail && detail.authorizer_info) {
return detail.authorizer_info;
}
throw new Error(`获取授权方信息失败: ${JSON.stringify(detail)}`);
}
/**
* 获取授权账号详情(api_get_authorizer_info 完整返回:authorizer_info + authorization_info)。
* @param {string} appid 授权方小程序 AppID。
* @return {Promise<object>} { authorizer_info, authorization_info }。
*/
async getAuthorizerDetail(appid) {
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_get_authorizer_info', {
component_appid: this.config.component_appid,
authorizer_appid: appid,
});
if (result && (result.authorizer_info || result.authorization_info)) {
return result;
}
throw new Error(`获取授权账号详情失败: ${JSON.stringify(result)}`);
}
/**
* 创建预授权码(用于生成授权链接)。
* @return {Promise<string>} pre_auth_code。
*/
async createPreAuthCode() {
const cached = await this.cacheGet('preauthcode');
if (cached) return cached;
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_create_preauthcode', {
component_appid: this.config.component_appid,
});
if (result && result.pre_auth_code) {
await this.cacheSet('preauthcode', result.pre_auth_code, result.expires_in || 1800);
return result.pre_auth_code;
}
throw new Error(`创建预授权码失败: ${JSON.stringify(result)}`);
}
/**
* 查询小程序认证进度(POST wxa/sec/queryauth,使用 authorizer_access_token 代商家调用,权限集 18)。
*
* @param {string} appid 小程序 AppID。
* @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取,Redis 丢失可用 DB 值兜底)。
* @param {string} taskid 认证任务 id(发起认证接口返回)。
* @return {Promise<object>} 微信原始响应(errcode/errmsg/task_status/apply_status/orderid/auth_url 等)。
*/
async queryMiniProgramAuth(appid, refreshToken, taskid) {
const request = async () => {
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/wxa/sec/queryauth`
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
const response = await this.ctx.curl(url, {
method: 'POST',
dataType: 'json',
timeout: 30000,
headers: { 'Content-Type': 'application/json' },
data: { taskid },
});
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn(`[wechatOpen] wxa/sec/queryauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
}
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
result = await request();
}
return result;
}
/**
* 发起小程序认证(wxa/sec/wxaapi/wxaauth,使用 authorizer_access_token 代商家调用,权限集 18)。
*
* 材料图片由前端上传换取 media_id 后一步提交;请求体字段白名单由业务层透传。
*
* @param {string} appid 小程序 AppID。
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
* @param {object} body 认证请求体(contact_type/contact_name/各 media_id 材料等)。
* @return {Promise<object>} 微信原始响应(errcode/errmsg/taskid/auth_url/apply_status)。
*/
async wxaauth(appid, refreshToken, body) {
const request = async () => {
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/wxa/sec/wxaapi/wxaauth`
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
const response = await this.ctx.curl(url, {
method: 'POST',
dataType: 'json',
timeout: 60000,
headers: { 'Content-Type': 'application/json' },
data: body,
});
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn(`[wechatOpen] wxa/sec/wxaapi/wxaauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
}
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
result = await request();
}
return result;
}
/**
* 上传认证材料图片到微信换取 media_id(wxa/sec/wxaapi/uploadmedia,
* authorizer_access_token 代商家调用,权限集 18)。
*
* 采用 multipart/form-data:media=图片文件(写入临时文件后按路径上传,保证文件名带扩展名)、
* media_type=image;成功后返回 media_id(3 天内有效,供 wxaauth 提交)。
*
* @param {string} appid 小程序 AppID。
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
* @param {Buffer} buffer 图片内容。
* @param {string} filename 文件名(含扩展名,如 idcard.jpg)。
* @return {Promise<object>} 微信原始响应(errcode/errmsg/media_id/media_md5)。
*/
async uploadAuthMedia(appid, refreshToken, buffer, filename) {
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const tmpFile = path.join(
os.tmpdir(),
`wxauth-${Date.now()}-${Math.random().toString(36).slice(2, 10)}-${path.basename(filename || 'image.jpg')}`
);
await fs.promises.writeFile(tmpFile, buffer);
const request = async () => {
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/wxa/sec/wxaapi/uploadmedia`
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
const response = await this.ctx.curl(url, {
method: 'POST',
dataType: 'json',
timeout: 60000,
data: { media_type: 'image' },
files: { media: tmpFile },
});
return response && response.data !== undefined ? response.data : response;
};
try {
let result = await request();
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn(`[wechatOpen] wxa/sec/wxaapi/uploadmedia token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
}
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
result = await request();
}
return result;
} finally {
await fs.promises.unlink(tmpFile).catch(() => {});
}
}
/**
* 获取小程序模板列表(wxa/gettemplatelist,仅支持 component_access_token,GET 请求)。
*
* @param {number} [templateType] 0=普通模板、1=标准模板,不传返回全部。
* @return {Promise<object>} 微信原始响应(errcode/errmsg/template_list)。
*/
async getTemplateList(templateType) {
const request = async () => {
const componentAccessToken = await this.getComponentAccessToken();
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/wxa/gettemplatelist`;
const response = await this.ctx.curl(url, {
method: 'GET',
dataType: 'json',
timeout: 30000,
data: {
access_token: componentAccessToken,
...(templateType !== undefined && templateType !== null ? { template_type: templateType } : {}),
},
});
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
if (result && Number(result.errcode) === 40001) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn('[wechatOpen] gettemplatelist 40001 component_access_token 失效,清除缓存重试');
}
await this.cacheDel('component_access_token');
result = await request();
}
return result;
}
/**
* 提交代码审核(wxa/submit_audit,使用 authorizer_access_token 代商家调用,权限集 18)。
*
* @param {string} appid 小程序 AppID。
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
* @param {object} body 请求体(item_list/version_desc 等,均为可选)。
* @return {Promise<object>} 微信原始响应(errcode/errmsg/auditid)。
*/
async submitAudit(appid, refreshToken, body) {
const request = async () => {
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/wxa/submit_audit`
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
const response = await this.ctx.curl(url, {
method: 'POST',
dataType: 'json',
timeout: 60000,
headers: { 'Content-Type': 'application/json' },
data: body,
});
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn(`[wechatOpen] wxa/submit_audit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
}
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
result = await request();
}
return result;
}
/**
* 获取体验版二维码(wxa/get_qrcode,使用 authorizer_access_token 代商家调用,权限集 18/86)。
*
* 成功返回图片二进制(contentType=image/jpeg),失败返回微信 JSON(errcode/errmsg)。
*
* @param {string} appid 小程序 AppID。
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
* @param {string} [path] 二维码扫码进入的页面路径(可选,自动 urlencode)。
* @return {Promise<object>} { errcode, errmsg } 或 { errcode: 0, contentType, buffer }。
*/
async getTrialQRCode(appid, refreshToken, path) {
const request = async () => {
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
const base = this.config.api_base || DEFAULT_API_BASE;
let url = `${base.replace(/\/$/, '')}/wxa/get_qrcode`
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
if (path) {
url += `&path=${encodeURIComponent(path)}`;
}
const response = await this.ctx.curl(url, {
method: 'GET',
timeout: 30000,
});
const contentType = String((response.headers && response.headers['content-type']) || '');
if (contentType.includes('image')) {
return { errcode: 0, errmsg: 'ok', contentType, buffer: response.data };
}
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn(`[wechatOpen] wxa/get_qrcode token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
}
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
result = await request();
}
return result;
}
/**
* 上传代码并生成体验版(wxa/commit,使用 authorizer_access_token 代商家调用,权限集 18)。
*
* @param {string} appid 小程序 AppID。
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
* @param {object} body { template_id, ext_json, user_version, user_desc }。
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
*/
async commitTemplate(appid, refreshToken, body) {
const request = async () => {
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/wxa/commit`
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
const response = await this.ctx.curl(url, {
method: 'POST',
dataType: 'json',
timeout: 60000,
headers: { 'Content-Type': 'application/json' },
data: body,
});
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn(`[wechatOpen] wxa/commit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
}
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
result = await request();
}
return result;
}
/**
* 快速注册企业小程序(fastregisterweapp,仅支持第三方平台 component_access_token)。
*
* @param {string} action create=创建小程序 / search=查询创建任务状态。
* @param {object} body 请求体。
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
*/
async fastRegisterWeapp(action, body) {
const request = async () => {
const componentAccessToken = await this.getComponentAccessToken();
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/cgi-bin/component/fastregisterweapp`
+ `?action=${encodeURIComponent(action)}`
+ `&component_access_token=${encodeURIComponent(componentAccessToken)}`;
const response = await this.ctx.curl(url, {
method: 'POST',
dataType: 'json',
timeout: 30000,
headers: { 'Content-Type': 'application/json' },
data: body,
});
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
if (result && Number(result.errcode) === 40001) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn('[wechatOpen] fastregisterweapp 40001 component_access_token 失效,清除缓存重试');
}
await this.cacheDel('component_access_token');
result = await request();
}
return result;
}
/**
* 小程序登录凭证校验(jscode2session):第三方平台代小程序实现登录。
* @param {string} appid 小程序 AppID。
* @param {string} jsCode wx.login 获取的 code。
* @return {Promise<object>} { openid, session_key, unionid }。
*/
async jscode2session(appid, jsCode) {
const request = async () => {
const componentAccessToken = await this.getComponentAccessToken();
const base = this.config.api_base || DEFAULT_API_BASE;
const url = `${base.replace(/\/$/, '')}/sns/component/jscode2session`
+ `?appid=${encodeURIComponent(appid)}`
+ '&grant_type=authorization_code'
+ `&component_appid=${encodeURIComponent(this.config.component_appid)}`
+ `&component_access_token=${encodeURIComponent(componentAccessToken)}`
+ `&js_code=${encodeURIComponent(jsCode)}`;
const response = await this.ctx.curl(url, {
method: 'GET',
dataType: 'json',
timeout: 30000,
});
return response && response.data !== undefined ? response.data : response;
};
let result = await request();
// 40001:component_access_token 被别处刷新顶掉(not latest),清除缓存重取后重试一次
if (result && Number(result.errcode) === 40001) {
if (this.ctx && this.ctx.logger) {
this.ctx.logger.warn('[wechatOpen] jscode2session 40001 component_access_token 失效,清除缓存重试');
}
await this.cacheDel('component_access_token');
result = await request();
}
// 调试:打印微信原始返回报文(仅 openid/session_key/unionid,无昵称头像)
if (this.ctx && this.ctx.logger) {
this.ctx.logger.info(`[wechatOpen] jscode2session appid=${appid} 返回: ${JSON.stringify(result)}`);
}
if (result && result.openid) {
return result;
}
throw new Error(`jscode2session 失败: ${JSON.stringify(result)}`);
}
/**
* 清理授权方相关缓存(unauthorized 取消授权事件后调用)。
* @param {string} appid 授权方小程序 AppID。
* @return {Promise<void>}
*/
async clearAuthorizerCache(appid) {
await this.cacheDel(
`App:${appid}:authorization_code`,
`App:${appid}:authorizer_refresh_token`,
`App:${appid}:AuthorizerAccessToken`
);
}
/**
* 保存授权 state(发起授权时缓存仓库信息,回跳时凭 state 取回)。
* @param {string} state 随机 state。
* @param {number|string} warehouseId 仓库ID。
* @param {number} [ttl=600] 过期秒数。
* @return {Promise<void>}
*/
async saveAuthState(state, warehouseId, ttl = 600) {
await this.cacheSet(
`wechat_auth_state:${state}`,
JSON.stringify({ warehouse_id: warehouseId, created_at: Math.floor(Date.now() / 1000) }),
ttl
);
}
/**
* 读取授权 state 对应的仓库信息。
* @param {string} state 随机 state。
* @return {Promise<object|null>} { warehouse_id, created_at },不存在/过期返回 null。
*/
async getAuthState(state) {
const cached = await this.cacheGet(`wechat_auth_state:${state}`);
if (!cached) return null;
try {
return JSON.parse(cached);
} catch (e) {
return null;
}
}
/**
* 删除授权 state 缓存(回调消费后调用,保证一次性)。
* @param {string} state 随机 state。
* @return {Promise<void>}
*/
async clearAuthState(state) {
await this.cacheDel(`wechat_auth_state:${state}`);
}
}
module.exports = WechatOpenClient;

View File

@ -0,0 +1,223 @@
'use strict';
const crypto = require('node:crypto');
const { XMLParser } = require('fast-xml-parser');
/**
* 微信开放平台第三方平台消息加解密工具(Node 版 WXBizMsgCrypt)。
* 对应微信官方示例(PHP WXBizMsgCrypt)能力:
* - URL 有效性验证(首次配置服务器地址时的 echostr 校验)
* - 事件推送消息解密(AES-256-CBC + PKCS#7,密文格式:
* 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid)
*
* 错误码沿用微信官方定义:
* -40001 签名验证错误 / -40004 encodingAesKey 非法 / -40005 appid 校验错误 /
* -40007 AES 解密失败 / -40008 解密后 buffer 非法 / -40010 base64 解码失败。
*/
const ERROR_CODES = {
OK: 0,
VALIDATE_SIGNATURE_ERROR: -40001,
ILLEGAL_AES_KEY: -40004,
VALIDATE_APPID_ERROR: -40005,
DECRYPT_AES_ERROR: -40007,
ILLEGAL_BUFFER: -40008,
DECODE_BASE64_ERROR: -40010,
};
/**
* 计算 SHA1(hex)。
* @param {string} input 输入字符串。
* @return {string} SHA1 摘要。
*/
function sha1(input) {
return crypto.createHash('sha1').update(input, 'utf8').digest('hex');
}
/**
* 生成消息签名:sha1(sort(token, timestamp, nonce, encrypt))。
* @param {string} token 第三方平台消息校验 Token。
* @param {string} timestamp 时间戳。
* @param {string} nonce 随机串。
* @param {string} [encrypt=''] 加密内容(URL 验证时为空)。
* @return {string} 签名。
*/
function getSignature(token, timestamp, nonce, encrypt = '') {
const arr = [ token, String(timestamp), String(nonce), String(encrypt || '') ].sort();
return sha1(arr.join(''));
}
/**
* 校验 URL 有效性签名:signature === sha1(sort(token, timestamp, nonce))。
* @param {string} token 第三方平台消息校验 Token。
* @param {string} signature 微信回传的 signature。
* @param {string} timestamp 时间戳。
* @param {string} nonce 随机串。
* @return {boolean} 是否通过。
*/
function verifyUrlSignature(token, signature, timestamp, nonce) {
if (!token || !signature || timestamp === undefined || timestamp === null || nonce === undefined || nonce === null) {
return false;
}
const expected = getSignature(token, timestamp, nonce);
return expected === String(signature);
}
/**
* 解析加密推送 XML,提取 <Encrypt> 内容。
* @param {string} encryptedXml 微信推送的加密 XML。
* @return {string} Encrypt 密文(base64 字符串)。
*/
function extractEncrypt(encryptedXml) {
if (!encryptedXml) return '';
const parser = new XMLParser({
ignoreAttributes: false,
parseTagValue: false,
parseAttributeValue: false,
trimValues: false,
});
let parsed;
try {
parsed = parser.parse(encryptedXml.trim());
} catch (e) {
return '';
}
return (parsed && parsed.xml && parsed.xml.Encrypt) || '';
}
/**
* PKCS#7 去除填充。
* @param {Buffer} buf 解密后的带填充 buffer。
* @return {Buffer} 去填充后的 buffer。
*/
function pkcs7Decode(buf) {
const pad = buf[buf.length - 1];
if (pad >= 1 && pad <= 32) {
return buf.subarray(0, buf.length - pad);
}
return buf;
}
/**
* AES-256-CBC 解密微信密文。
* @param {string} encrypted base64 密文。
* @param {Buffer} aesKey 32 字节 AES Key。
* @return {{ code: number, buf: Buffer }} 解密结果(失败时 buf 为空 Buffer)。
*/
function aesDecrypt(encrypted, aesKey) {
const encryptedBuf = Buffer.from(String(encrypted), 'base64');
if (!encryptedBuf.length) {
return { code: ERROR_CODES.DECODE_BASE64_ERROR, buf: Buffer.alloc(0) };
}
try {
const iv = aesKey.subarray(0, 16);
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv);
decipher.setAutoPadding(false);
const decoded = pkcs7Decode(Buffer.concat([ decipher.update(encryptedBuf), decipher.final() ]));
return { code: ERROR_CODES.OK, buf: decoded };
} catch (e) {
return { code: ERROR_CODES.DECRYPT_AES_ERROR, buf: Buffer.alloc(0) };
}
}
/**
* 解密事件推送消息(完整流程:签名校验 → base64/AES 解密 → 报文解析 → appid 校验)。
* @param {object} opts 参数。
* @param {string} opts.token 第三方平台消息校验 Token。
* @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。
* @param {string} opts.componentAppid 第三方平台 AppID。
* @param {string} opts.msgSignature 消息签名 msg_signature。
* @param {string|number} opts.timestamp 时间戳。
* @param {string} opts.nonce 随机串。
* @param {string} opts.encryptedXml 微信推送的加密 XML。
* @return {{ code: number, msg: string }} code=0 时 msg 为解密后的明文 XML。
*/
function decryptMsg(opts) {
const {
token,
encodingAesKey,
componentAppid,
msgSignature,
timestamp,
nonce,
encryptedXml,
} = opts || {};
const encrypt = extractEncrypt(encryptedXml);
if (!encrypt) {
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '加密 XML 中未找到 Encrypt 内容' };
}
// 1. 校验消息签名
const expectedSignature = getSignature(token, timestamp, nonce, encrypt);
if (expectedSignature !== String(msgSignature)) {
return { code: ERROR_CODES.VALIDATE_SIGNATURE_ERROR, msg: '消息签名校验失败' };
}
// 2. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节)
let aesKey;
try {
aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64');
} catch (e) {
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 非法' };
}
if (aesKey.length !== 32) {
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 解码后长度不是 32 字节' };
}
// 3. AES 解密
const decrypted = aesDecrypt(encrypt, aesKey);
if (decrypted.code !== ERROR_CODES.OK) {
return { code: decrypted.code, msg: 'AES 解密失败' };
}
// 4. 解析明文(二进制 buffer):16 字节随机串 + 4 字节大端长度 + 消息体 + appid
const content = decrypted.buf;
if (content.length < 20) {
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后 buffer 长度非法' };
}
const msgLen = content.readUInt32BE(16);
if (20 + msgLen > content.length) {
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后消息长度非法' };
}
const xmlContent = content.subarray(20, 20 + msgLen).toString('utf8');
const fromAppid = content.subarray(20 + msgLen).toString('utf8');
// 5. 校验 appid
if (fromAppid !== String(componentAppid)) {
return { code: ERROR_CODES.VALIDATE_APPID_ERROR, msg: `appid 校验失败: ${fromAppid}` };
}
return { code: ERROR_CODES.OK, msg: xmlContent };
}
/**
* 解析明文 XML 为对象({ AppId, InfoType, ... })。
* @param {string} xml 明文 XML。
* @return {object} 解析后的对象(失败返回空对象)。
*/
function parseXml(xml) {
if (!xml) return {};
const parser = new XMLParser({
ignoreAttributes: false,
parseTagValue: false,
parseAttributeValue: false,
trimValues: false,
});
try {
const parsed = parser.parse(xml.trim());
return (parsed && parsed.xml) || {};
} catch (e) {
return {};
}
}
module.exports = {
ERROR_CODES,
sha1,
getSignature,
verifyUrlSignature,
extractEncrypt,
decryptMsg,
parseXml,
};

View File

@ -30,6 +30,7 @@ module.exports = app => {
{ name: '物流异常', value: 'logistics_issue' },
{ name: '客户拒收', value: 'rejected' },
{ name: '拦截', value: 'intercept' },
{ name: '取消拦截', value: 'cancel_intercept' },
{ name: '核实签收', value: 'verify_delivery' },
{ name: '催件', value: 'urge' },
{ name: '多发', value: 'extra_item' },

View File

@ -28,6 +28,9 @@ module.exports = app => {
*/
const getDefaultInventoryWarningRules = () => DEFAULT_INVENTORY_WARNING_RULES.map(rule => ({ ...rule }));
const DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME = '06:00';
const DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME = '22:00';
const DEFAULT_AUTO_OUTBOUND_RULES = Object.freeze({
enabled: false,
require_recheck: true,
@ -36,6 +39,9 @@ module.exports = app => {
require_sync: true,
require_print: true,
require_pick: true,
exclude_same_day_outbound: true,
same_day_outbound_deadline_time: '06:00',
same_day_outbound_release_time: '22:00',
});
const DEFAULT_CUTOFF_ORDER_TIME = '18:00';
@ -176,6 +182,52 @@ module.exports = app => {
});
};
/**
* 规范化 HH:mm 时间文本。
* 缺省或格式非法时回退指定默认值。
*
* @param {string|undefined|null} value 原始时间文本。
* @param {string} defaultValue 默认 HH:mm。
* @return {string} 规范化后的 HH:mm 文本。
*/
const normalizeHourMinuteTime = (value, defaultValue) => {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const text = String(value).trim();
return /^([01]\d|2[0-3]):[0-5]\d$/.test(text) ? text : defaultValue;
};
/**
* 将 HH:mm 文本解析为总分钟数(用于时间先后比较)。
*
* @param {string} timeText HH:mm 文本。
* @return {number} 总分钟数。
*/
const parseHourMinuteToMinutes = timeText => {
const match = /^(\d{2}):(\d{2})$/.exec(String(timeText || '').trim());
if (!match) return 0;
return Number(match[1]) * 60 + Number(match[2]);
};
/**
* 规范化「允许当天出库最后时间」配置(HH:mm)。
* 缺省或格式非法时回退默认 06:00。
*
* @param {string|undefined|null} value 原始时间文本。
* @return {string} 规范化后的 HH:mm 文本。
*/
const normalizeSameDayOutboundDeadlineTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_DEADLINE_TIME);
/**
* 规范化「当天放开时间」配置(HH:mm)。
* 缺省或格式非法时回退默认 22:00。
*
* @param {string|undefined|null} value 原始时间文本。
* @return {string} 规范化后的 HH:mm 文本。
*/
const normalizeSameDayOutboundReleaseTime = value => normalizeHourMinuteTime(value, DEFAULT_SAME_DAY_OUTBOUND_RELEASE_TIME);
/**
* 规范化自动化出库规则配置。
* 确保 enabled/require_recheck/require_pack/require_weigh/require_sync/require_print/require_pick 等字段存在且类型正确。
@ -201,6 +253,14 @@ module.exports = app => {
return { ...DEFAULT_AUTO_OUTBOUND_RULES };
}
const sameDayOutboundDeadlineTime = normalizeSameDayOutboundDeadlineTime(parsed.same_day_outbound_deadline_time);
const sameDayOutboundReleaseTime = normalizeSameDayOutboundReleaseTime(parsed.same_day_outbound_release_time);
// 保存时校验:允许当天出库最后时间不能大于当天放开时间
if (parseHourMinuteToMinutes(sameDayOutboundDeadlineTime) > parseHourMinuteToMinutes(sameDayOutboundReleaseTime)) {
throw new Error('自动出库规则:允许当天出库最后时间不能大于当天放开时间');
}
return {
enabled: normalizeBooleanFlag(parsed.enabled, 'auto_outbound_rules.enabled') === true,
require_recheck: parsed.require_recheck !== false,
@ -209,6 +269,9 @@ module.exports = app => {
require_sync: parsed.require_sync !== false,
require_print: parsed.require_print !== false,
require_pick: parsed.require_pick !== false,
exclude_same_day_outbound: normalizeBooleanFlag(parsed.exclude_same_day_outbound, 'auto_outbound_rules.exclude_same_day_outbound') !== false,
same_day_outbound_deadline_time: sameDayOutboundDeadlineTime,
same_day_outbound_release_time: sameDayOutboundReleaseTime,
};
};

156
app/model/user_oauth.js Normal file
View File

@ -0,0 +1,156 @@
'use strict';
/**
* 用户第三方授权表模型。
* 保存用户通过第三方厂商(微信等)OAuth 登录后的授权信息与令牌信息。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, TINYINT, DATE } = app.Sequelize;
const UserOauth = app.model.define('userOauth', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
user_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '用户ID(关联 account.id)',
},
app_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '微信应用ID(关联 wms_wechat_app.id),用于取对应应用 token 处理',
},
provider: {
type: STRING(50),
allowNull: false,
comment: '厂商,如 wechat/mini_program',
},
platform: {
type: STRING(50),
allowNull: true,
comment: '平台,如 h5/app/mp',
},
unionid: {
type: STRING(50),
allowNull: true,
comment: '厂商统一ID(同一厂商跨应用唯一,部分平台无)',
},
openid: {
type: STRING(50),
allowNull: false,
comment: '平台内唯一ID',
},
nickname: {
type: STRING(255),
allowNull: true,
comment: '昵称',
},
sex: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '性别:0=未知,1=男,2=女',
},
country: {
type: STRING(50),
allowNull: true,
comment: '国家',
},
province: {
type: STRING(50),
allowNull: true,
comment: '省',
},
city: {
type: STRING(50),
allowNull: true,
comment: '市',
},
headimgurl: {
type: STRING(500),
allowNull: true,
comment: '头像URL',
},
login_time: {
type: INTEGER(11),
allowNull: true,
comment: '最近登录时间(unix秒级时间戳)',
},
login_count: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '累计登录次数',
},
expire_in: {
type: INTEGER(11),
allowNull: true,
comment: '令牌过期周期(秒)',
},
expire_time: {
type: INTEGER(11),
allowNull: true,
comment: '令牌过期时间(unix秒级时间戳)',
},
session_key: {
type: STRING(45),
allowNull: true,
comment: '会话密钥(微信小程序登录态)',
},
refresh_token: {
type: STRING(110),
allowNull: true,
comment: '刷新令牌',
},
access_token: {
type: STRING(110),
allowNull: true,
comment: '访问令牌',
},
login_code: {
type: STRING(128),
allowNull: true,
comment: '登录码({uuid,id_6} JSON 的 base64,一次性消费)',
},
created_at: {
type: DATE,
comment: '创建时间',
},
updated_at: {
type: DATE,
comment: '更新时间',
},
}, {
tableName: 'wms_user_oauth',
underscored: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
comment: '用户第三方授权表',
indexes: [
{
unique: true,
fields: [ 'app_id', 'provider', 'openid' ],
name: 'uk_app_provider_openid',
},
{
unique: true,
fields: [ 'login_code' ],
name: 'uk_login_code',
},
{
fields: [ 'user_id' ],
name: 'idx_user_id',
},
],
});
return UserOauth;
};

203
app/model/wechat_app.js Normal file
View File

@ -0,0 +1,203 @@
'use strict';
/**
* 微信开放平台授权小程序表模型。
* 记录仓库(主体)授权的小程序信息与令牌,供业务按小程序维度调用微信接口。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, TINYINT, TEXT, DATE } = app.Sequelize;
const WechatApp = app.model.define('wechatApp', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '仓库ID(绑定关系,NULL=已授权待绑定仓库)',
},
appid: {
type: STRING(64),
allowNull: false,
comment: '小程序AppID',
},
nickname: {
type: STRING(100),
allowNull: true,
comment: '小程序名称',
},
user_name: {
type: STRING(100),
allowNull: true,
comment: '小程序原始ID(gh_xxx)',
},
head_img: {
type: STRING(500),
allowNull: true,
comment: '小程序头像URL',
},
authorizer_refresh_token: {
type: STRING(255),
allowNull: true,
comment: '授权方刷新令牌(长期有效,防 Redis 丢失)',
},
auth_time: {
type: INTEGER(11),
allowNull: true,
comment: '授权时间(unix秒级时间戳)',
},
func_info: {
type: TEXT,
allowNull: true,
comment: '授权权限集合(JSON 字符串,来自 api_query_auth)',
},
template_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '当前上传的代码模板ID(wxa/commit 成功后记录)',
},
user_version: {
type: STRING(64),
allowNull: true,
defaultValue: null,
comment: '当前上传的代码版本号(wxa/commit 成功后记录)',
},
audit_status: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '代码审核状态:0=未提交,1=审核中,2=审核通过,3=审核驳回',
},
audit_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '微信审核单ID(wxa/submit_audit 返回的 auditid)',
},
audit_reason: {
type: STRING(500),
allowNull: true,
defaultValue: null,
comment: '代码审核驳回原因',
},
principal_name: {
type: STRING(100),
allowNull: true,
defaultValue: null,
comment: '主体名称',
},
signature: {
type: STRING(500),
allowNull: true,
defaultValue: null,
comment: '小程序账号介绍',
},
alias: {
type: STRING(100),
allowNull: true,
defaultValue: null,
comment: '微信号(可能为空)',
},
qrcode_url: {
type: STRING(500),
allowNull: true,
defaultValue: null,
comment: '二维码图片URL',
},
service_type_id: {
type: TINYINT,
allowNull: true,
defaultValue: null,
comment: '账号类型id(0 普通小程序等)',
},
verify_type_id: {
type: TINYINT,
allowNull: true,
defaultValue: null,
comment: '认证类型id(-1 未认证,0 微信认证,1 新浪微博认证,3 资质通过未名称认证,4 同3+微博)',
},
account_status: {
type: TINYINT,
allowNull: true,
defaultValue: null,
comment: '账号状态(1 正常,14 已注销,16 已封禁,18 已告警,19 已冻结)',
},
register_type: {
type: TINYINT,
allowNull: true,
defaultValue: null,
comment: '小程序注册方式(0 普通,6 法人扫脸创建企业小程序等)',
},
business_info: {
type: STRING(500),
allowNull: true,
defaultValue: null,
comment: '功能开通状况 JSON',
},
mini_program_info: {
type: TEXT,
allowNull: true,
defaultValue: null,
comment: '小程序配置信息 JSON(network/categories/visit_status)',
},
auth_task_id: {
type: STRING(64),
allowNull: true,
defaultValue: null,
comment: '微信认证任务ID(发起认证接口返回)',
},
auth_task_status: {
type: TINYINT,
allowNull: true,
defaultValue: null,
comment: '认证任务流程状态(task_status 0-15)',
},
auth_apply_status: {
type: TINYINT,
allowNull: true,
defaultValue: null,
comment: '认证审核单状态(apply_status 0-5)',
},
is_enabled: {
type: TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:1=启用,0=停用',
},
created_at: {
type: DATE,
comment: '创建时间',
},
updated_at: {
type: DATE,
comment: '更新时间',
},
}, {
tableName: 'wms_wechat_app',
underscored: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
comment: '微信开放平台授权小程序表(仓库绑定)',
indexes: [
{
unique: true,
fields: [ 'appid' ],
name: 'uk_appid',
},
{
fields: [ 'warehouse_id' ],
name: 'idx_warehouse_id',
},
],
});
return WechatApp;
};

View File

@ -8,6 +8,10 @@ module.exports = app => {
router.get('/auth/platformOauthBind', controller.home.platformOauthBind);
router.get('/query/pddCode/:code', controller.home.queryPddCode);
// 微信开放平台第三方平台授权事件接收(GET=URL验证,POST=事件推送)
router.get('/Authorization', controller.wechatOpen.authorization);
router.post('/Authorization', controller.wechatOpen.authorization);
// 内部网关接口
router.post('/internal/v1/gateway', controller.gateway.internal);

View File

@ -14,6 +14,12 @@
* 6. 已拣货:pick_status = 'fin'
*
* 各条件是否必须可由仓库配置独立控制。
*
* 当天订单限制(exclude_same_day_outbound,默认 true):
* 开启时,在当天放开时间(same_day_outbound_release_time,默认北京时间 22:00)前,
* 北京时间当天「允许当天出库最后时间」(same_day_outbound_deadline_time,默认 06:00)
* 起复核(recheck_time)的订单不自动出库;
* 到达放开时间后当天复核订单恢复自动出库。关闭则全程不受限制。
*/
module.exports = {
schedule: {

View File

@ -52,7 +52,7 @@ class InboxFunctionsService extends Service {
*/
registerBuiltinFunctions() {
this.register('help', {
description: '帮助指令:枚举当前仓库可见的售后类型与子类型(含关键词),返回可用指令清单(back_text),供回复模板 {back_text} 占位符渲染',
description: '帮助指令:枚举当前仓库当前群可见(按群类型白名单过滤)的售后类型与子类型(含关键词),返回可用指令清单(back_text),供回复模板 {back_text} 占位符渲染',
params: {},
groups: [ GROUP.COMMON ],
weight: 0,
@ -69,12 +69,17 @@ class InboxFunctionsService extends Service {
ctx.logger.warn(`[inbox functions] help 加载 v2 配置失败: ${e.message}`);
}
// 类型名映射
// 类型名映射(含排序,帮助清单按类型 sort_order 分组输出)
let typeNameMap = {};
let typeOrderMap = {};
try {
const types = await ctx.model.AfterSaleType.findAll({ attributes: [ 'type', 'name' ], raw: true });
const types = await ctx.model.AfterSaleType.findAll({ attributes: [ 'type', 'name', 'sort_order' ], raw: true });
typeNameMap = {};
for (const t of types) typeNameMap[t.type] = t.name;
typeOrderMap = {};
for (const t of types) {
typeNameMap[t.type] = t.name;
typeOrderMap[t.type] = Number(t.sort_order) || 0;
}
} catch (e) { /* ignore */ }
// 关键词按子类型聚合(可见配置)
@ -88,10 +93,28 @@ class InboxFunctionsService extends Service {
const lines = [];
const subTypes = (cfg && cfg.subTypes) ? Object.values(cfg.subTypes) : [];
for (const st of subTypes) {
// 群类型白名单过滤:仅展示当前群可见的子类型(复用 v2 规则引擎的白名单语义;
// 无群上下文时不过滤,兼容 AI 直调 help 的场景)
const groupType = String(ctx.inboxContext?.group_type || '').trim();
const groupSubType = String(ctx.inboxContext?.sub_type || '').trim();
const visibleSubTypes = groupType && cfg
? subTypes.filter(st => ctx.service.inbox.v2.rules._groupAllowed(cfg, st.id, groupType, groupSubType))
: subTypes;
// 按类型 sort_order → 子类型 sort_order → id 排序,保证清单顺序稳定
visibleSubTypes.sort((a, b) => (
(typeOrderMap[a.type] || 0) - (typeOrderMap[b.type] || 0)
|| (Number(a.sort_order) || 0) - (Number(b.sort_order) || 0)
|| (Number(a.id) || 0) - (Number(b.id) || 0)
));
let lastType = null;
for (const st of visibleSubTypes) {
const tName = typeNameMap[st.type] || st.type;
const kws = kwBySubType[st.id] || [];
lines.push(`${tName}:`);
// 类型表头仅在该类型首次出现时输出一次
if (tName !== lastType) {
lines.push(`${tName}:`);
lastType = tName;
}
lines.push(` ${st.name}:关键词:${kws.length > 0 ? kws.join(',') : '(未配置)'}`);
}
const backText = lines.length > 0 ? lines.join('\n') : '(当前仓库未配置可用指令)';

View File

@ -7,7 +7,7 @@ const CACHE_KEY_PREFIX = 'inbox:v2:cfg:';
/** 配置缓存 TTL(秒)。 */
const CACHE_TTL = 300;
/** 缓存结构版本号,结构变更时递增,避免读到旧结构。 */
const CACHE_VERSION = 1;
const CACHE_VERSION = 2;
/**
* v2 仓库可配置回信引擎 —— 配置加载服务。
@ -20,7 +20,7 @@ const CACHE_VERSION = 1;
* 配置结构(纯对象,可安全进缓存/Redis 序列化,不含 Map/Set/RegExp 实例):
* {
* _v: 1,
* subTypes: { [id]: {id, type, sub_type, name, is_system, is_enabled} },
* subTypes: { [id]: {id, type, sub_type, name, is_system, is_enabled, sort_order} },
* keywords: [ {keyword, sub_type_id, sort_order} ],
* groupWhitelist: { [sub_type_id]: [ {group_type, sub_group} ] },
* subTypeFunctions: { [sub_type_id]: [ {function_code, sort_order} ] },
@ -86,6 +86,7 @@ class InboxV2ConfigService extends Service {
subTypeMap[s.id] = {
id: s.id, type: s.type, sub_type: s.sub_type, name: s.name,
is_system: s.is_system, is_enabled: s.is_enabled,
sort_order: Number(s.sort_order) || 0,
};
validSubTypeIds.add(s.id);
}

View File

@ -393,7 +393,9 @@ class InboxV2RulesService extends Service {
/**
* 回复文案占位符渲染:{sub_type_name}/{keyword}/{express}/{back_text}。
* {back_text} 取自函数返回的 data.back_text(如 help 函数生成的指令清单)。
* {back_text} 优先取函数返回的 data.back_text(如 help 函数生成的指令清单);
* 函数未返回 back_text 时回退到 data.message(对齐 v1 rules.buildReply 口径,
* 否则 interceptWaybill 等只返回 message 的函数渲染恒为空 → 静默不回信)。
* @param {string} tpl 模板文案。
* @param {Object} subType 子类型记录。
* @param {Array} results 函数执行结果。
@ -404,9 +406,10 @@ class InboxV2RulesService extends Service {
_renderReply(tpl, subType, results, text, fallbackParams) {
const last = results.length > 0 ? results[results.length - 1] : null;
const params = (last && last.params) || fallbackParams || {};
const backText = (last && last.result && last.result.data && last.result.data.back_text)
? String(last.result.data.back_text)
: '';
const lastData = (last && last.result && last.result.data) || {};
const backText = lastData.back_text
? String(lastData.back_text)
: (typeof lastData.message === 'string' ? String(lastData.message) : '');
return String(tpl)
.replace(/\{sub_type_name\}/g, subType.name || '')
.replace(/\{keyword\}/g, String(params.keyword || ''))

View File

@ -16,6 +16,7 @@ class MainService extends Service {
this._noNeedLogin = null;
this._noNeedRight = null;
this._noNeedAuth = null;
this._noNeedBind = null;
this.user = null;
this.userId = null;
}
@ -307,6 +308,7 @@ class MainService extends Service {
const _noNeedRight = (this._noNeedRight || '').split(',');
const _noNeedAuth = (this._noNeedAuth || '').split(',');
const _noNeedLog = (this._noNeedLog || '').split(',');
const _noNeedBind = (this._noNeedBind || '').split(',');
const api_path = `${servicePath}.${actionName}`;
const result = {
status: 401,
@ -358,6 +360,51 @@ class MainService extends Service {
// 设置新的 token 到响应头
ctx.set('Authorization', `Bearer ${newToken}`);
}
// 3.5 中间层:白名单内的接口优先按真实用户放行(正常登录 token 或已绑定 oauth token),
// 未绑定真实用户的微信登录态(oauth_id + user_id=0)作为兜底放行,业务方法经 ctx.oauth 取微信身份。
if (_noNeedBind.indexOf('*') > -1 || _noNeedBind.indexOf(actionName) > -1) {
let oauth = null;
const oauthId = Number(decoded.oauth_id || 0);
if (Number.isInteger(oauthId) && oauthId > 0) {
oauth = await ctx.model.UserOauth.findByPk(oauthId, { raw: true });
if (oauth) {
ctx.oauth = oauth;
ctx.oauthId = oauth.id;
}
}
// 1. 有真实用户(oauth.user_id 或 token id)→ 按正常用户上下文放行
const userId = oauth ? Number(oauth.user_id || 0) : Number(decoded.id || decoded.userId || 0);
if (userId > 0) {
const bindUser = await ctx.service.systems.auth.user.findById(userId);
if (bindUser) {
if (bindUser.status !== 1) {
result.status = 403;
result.message = '账号已被禁用';
return result;
}
this.setUserContext(ctx, bindUser, decoded);
result.status = 200;
result.message = 'ok';
result.user = bindUser;
return result;
}
}
// 2. 未绑定真实用户的微信登录态 → 兜底放行(ctx.oauth 可用)
if (oauth) {
result.status = 200;
result.message = 'ok';
return result;
}
// 3. 既无用户也无微信登录态 → 401
result.status = 401;
result.message = '未提供有效的微信登录态';
return result;
}
// 4. 获取用户信息
const user = await ctx.service.systems.auth.user.findById(decoded.id || decoded.userId);
@ -619,11 +666,12 @@ class MainService extends Service {
ctx.jwtPayload = decoded;
}
systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*') {
systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*', _noNeedBind = '') {
this._noNeedLogin = _noNeedLogin;
this._noNeedRight = _noNeedRight;
this._noNeedLog = _noNeedLog;
this._noNeedAuth = _noNeedAuth;
this._noNeedBind = _noNeedBind;
}
}

View File

@ -3399,11 +3399,18 @@ class indexService extends MainService {
}
/**
* 根据 token(ye4s 登录临时码 tmp_code)查询用户信息。
* 根据 token 查询用户信息(免登录、免鉴权,工作台工牌扫码用)。
*
* 支持两种 token:
* 1. 微信工牌码(登录码):base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'},
* 按 uuid 前缀取 wms_user_oauth.id → 返回 nickname / user_id;
* 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name),
* 未绑定时直接返回 wms_user_oauth.nickname。
* 2. ye4s 登录临时码:对应 ye4s_user.tmp_code(旧流程兜底)。
*
* @param {Object} data 请求参数
* @param {string} data.token ye4s 登录临时码(对应 ye4s_user.tmp_code)
* @return {Promise<Object>} 统一响应结构;命中时返回 real_name 与 wms_account_id,未命中时返回失败响应(code=404)
* @param {string} data.token 微信工牌码(base64)或 ye4s 登录临时码
* @return {Promise<Object>} 统一响应结构;命中时返回 real_name 与 user_id/wms_account_id,未命中时返回失败响应(code=404)
*/
async queryUserByToken(data = {}) {
const { ctx } = this;
@ -3413,11 +3420,24 @@ class indexService extends MainService {
return this.fail('token 不能为空', { code: 400 });
}
const rawToken = String(token).trim();
// 微信工牌码(base64 + uuid + wechat 来源):走 wms_user_oauth 查询
const wechatBadge = this.parseWechatBadgeCode(rawToken);
if (wechatBadge) {
try {
return await this.queryUserByWechatBadge(wechatBadge.oauthId);
} catch (error) {
ctx.logger.error('工牌查询用户失败:', error);
return this.fail(error.message || '查询用户失败', { code: 500 });
}
}
try {
const ye4sClient = ctx.app.mysql.get('ye4s');
const rows = await ye4sClient.select('ye4s_user', {
where: {
tmp_code: String(token).trim(),
tmp_code: rawToken,
},
columns: [ 'real_name', 'wms_account_id' ],
limit: 1,
@ -3438,5 +3458,84 @@ class indexService extends MainService {
return this.fail(error.message || '查询用户失败', { code: 500 });
}
}
/**
* 解析微信工牌码:base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'}
* - 解码为 JSON 且来源为 wechat 时返回 { oauthId }(wms_user_oauth.id)
* - 其他内容(ye4s 临时码等)返回 null,由调用方走旧逻辑
*
* @param {string} token 工牌码原文
* @return {{oauthId: number}|null} 解析结果
*/
parseWechatBadgeCode(token) {
try {
const text = String(token || '').trim();
// 快速预判:长度与字符集需符合 base64,避免每条码都走解码
if (!text || text.length < 16 || !/^[A-Za-z0-9+/=_-]+$/.test(text)) {
return null;
}
const b64 = text.replace(/-/g, '+').replace(/_/g, '/');
const decoded = Buffer.from(b64, 'base64').toString('utf8');
if (!decoded || !decoded.trim().startsWith('{')) {
return null;
}
const payload = JSON.parse(decoded);
if (!payload || typeof payload !== 'object') {
return null;
}
const form = payload.form || payload.source || '';
const uuid = payload.uuid || '';
if (String(form) !== 'wechat' || !uuid) {
return null;
}
// uuid 形如 {oauth_id}_{6位随机},取前缀作为 wms_user_oauth.id
const oauthId = Number(String(uuid).split('_')[0]);
if (!Number.isInteger(oauthId) || oauthId <= 0) {
return null;
}
return { oauthId };
} catch (error) {
return null;
}
}
/**
* 微信工牌查询用户:按 wms_user_oauth.id 取 nickname/user_id;
* 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name),
* 未绑定/无工号记录时直接返回 wms_user_oauth.nickname。
*
* @param {number} oauthId wms_user_oauth.id
* @return {Promise<Object>} 统一响应结构
*/
async queryUserByWechatBadge(oauthId) {
const { ctx } = this;
const oauth = await ctx.model.UserOauth.findByPk(oauthId);
if (!oauth) {
return this.fail('用户不存在', { code: 404 });
}
const userId = Number(oauth.user_id) || 0;
let realName = oauth.nickname || '';
// 已绑定账号:拉取 wms_account_store_employee 工号名称(real_name,status=1)
if (userId > 0) {
const employee = await ctx.model.AccountStoreEmployee.findOne({
where: { account_id: userId, status: 1 },
order: [[ 'id', 'ASC' ]],
});
if (employee && employee.real_name) {
realName = employee.real_name;
}
}
return this.success('查询成功', {
real_name: realName,
user_id: userId > 0 ? userId : null,
wms_account_id: userId > 0 ? userId : null,
nickname: oauth.nickname || '',
code: 200,
});
}
}
module.exports = indexService;

View File

@ -410,6 +410,71 @@ const PROVINCE_LIST = [
'香港特别行政区', '澳门特别行政区',
];
/**
* 本地地址解析副接口内置的"省 → 地级市"地址字典数据。
*
* 覆盖全国 34 个省级行政区下的地级市/自治州/地区/盟(约 340 条),
* 供 parseAddressLocal 遍历匹配识别省市区,不依赖 AI 接口。
* 直辖市(北京/天津/上海/重庆)的 city 与 province 同名;港澳台无地级市条目,
* 仅靠 PROVINCE_LIST 识别省份。
*/
const LOCAL_CITY_DICT = Object.freeze(
[
[ '北京市', [ '北京市' ]],
[ '天津市', [ '天津市' ]],
[ '上海市', [ '上海市' ]],
[ '重庆市', [ '重庆市' ]],
[ '河北省', [ '石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市' ]],
[ '山西省', [ '太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市' ]],
[ '内蒙古自治区', [ '呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市', '兴安盟', '锡林郭勒盟', '阿拉善盟' ]],
[ '辽宁省', [ '沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市' ]],
[ '吉林省', [ '长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市', '延边朝鲜族自治州' ]],
[ '黑龙江省', [ '哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市', '大兴安岭地区' ]],
[ '江苏省', [ '南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市' ]],
[ '浙江省', [ '杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市' ]],
[ '安徽省', [ '合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '六安市', '亳州市', '池州市', '宣城市' ]],
[ '福建省', [ '福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市' ]],
[ '江西省', [ '南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市' ]],
[ '山东省', [ '济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '临沂市', '德州市', '聊城市', '滨州市', '菏泽市' ]],
[ '河南省', [ '郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市' ]],
[ '湖北省', [ '武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市', '恩施土家族苗族自治州' ]],
[ '湖南省', [ '长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市', '湘西土家族苗族自治州' ]],
[ '广东省', [ '广州市', '韶关市', '深圳市', '珠海市', '汕头市', '佛山市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市' ]],
[ '广西壮族自治区', [ '南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市' ]],
[ '海南省', [ '海口市', '三亚市', '三沙市', '儋州市' ]],
[ '四川省', [ '成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市', '阿坝藏族羌族自治州', '甘孜藏族自治州', '凉山彝族自治州' ]],
[ '贵州省', [ '贵阳市', '六盘水市', '遵义市', '安顺市', '毕节市', '铜仁市', '黔西南布依族苗族自治州', '黔东南苗族侗族自治州', '黔南布依族苗族自治州' ]],
[ '云南省', [ '昆明市', '曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '普洱市', '临沧市', '楚雄彝族自治州', '红河哈尼族彝族自治州', '文山壮族苗族自治州', '西双版纳傣族自治州', '大理白族自治州', '德宏傣族景颇族自治州', '怒江傈僳族自治州', '迪庆藏族自治州' ]],
[ '西藏自治区', [ '拉萨市', '日喀则市', '昌都市', '林芝市', '山南市', '那曲市', '阿里地区' ]],
[ '陕西省', [ '西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市' ]],
[ '甘肃省', [ '兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市', '临夏回族自治州', '甘南藏族自治州' ]],
[ '青海省', [ '西宁市', '海东市', '海北藏族自治州', '黄南藏族自治州', '海南藏族自治州', '果洛藏族自治州', '玉树藏族自治州', '海西蒙古族藏族自治州' ]],
[ '宁夏回族自治区', [ '银川市', '石嘴山市', '吴忠市', '固原市', '中卫市' ]],
[ '新疆维吾尔自治区', [ '乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市', '昌吉回族自治州', '博尔塔拉蒙古自治州', '巴音郭楞蒙古自治州', '克孜勒苏柯尔克孜自治州', '伊犁哈萨克自治州', '阿克苏地区', '喀什地区', '和田地区', '塔城地区', '阿勒泰地区' ]],
].reduce((map, [ province, cities ]) => {
for (const city of cities) map[city] = province;
return map;
}, {})
);
/**
* parseAddressLocal 内置的示例地址数据。
*
* 请求未传 address/addresses 时,接口直接遍历识别这批地址并返回结果,
* 便于验证本地字典遍历识别效果,覆盖直辖市、普通省市区、县级市、不设区地级市、
* 自治区、仅有城市名、仅有县级市名等典型场景。
*/
const LOCAL_SAMPLE_ADDRESSES = Object.freeze([
'张三 13800138000 北京市朝阳区建国路88号',
'李四 13900139000 广东省广州市天河区体育西路100号',
'江苏省苏州市昆山市花桥镇光明路8号',
'广东省东莞市南城街道宏图路100号',
'新疆维吾尔自治区乌鲁木齐市天山区中山路1号',
'苏州市姑苏区干将西路100号',
'昆山市玉山镇前进西路100号',
'四川省成都市武侯区人民南路四段10号',
]);
/**
* 根据已解析的地址字段,利用中国行政区划知识进行反向推断,补全缺失的 province/city/area。
*
@ -535,92 +600,7 @@ function reverseInferAddress(parsed) {
}
/**
* 从模型返回的文本中截取 JSON 片段(对象或数组),并清理 markdown 代码块标记。
* 对象取第一个 { 到最后一个 },数组取第一个 [ 到最后一个 ],自动忽略前后多余文本。
*
* @param {string} text 模型原始返回文本。
* @return {string} 截取后的 JSON 字符串;无有效片段时返回原文 trim。
*/
function extractJsonBlock(text) {
if (!text) return '';
let s = String(text).trim();
s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '');
const firstBrace = s.indexOf('{');
const firstBracket = s.indexOf('[');
let start = -1;
if (firstBrace === -1) {
start = firstBracket;
} else if (firstBracket === -1) {
start = firstBrace;
} else {
start = Math.min(firstBrace, firstBracket);
}
const end = Math.max(s.lastIndexOf('}'), s.lastIndexOf(']'));
if (start === -1 || end === -1 || end <= start) {
return s;
}
return s.slice(start, end + 1);
}
const ADDRESS_PARSE_FIELDS = [
'province', 'city', 'area', 'town', 'detailAddress', 'name', 'mobile',
];
/**
* 从任意文本(如思维链模型的 reasoning_content)中提取地址解析字段,
* 支持 "province":"xx"、province=xx、province:xx 等常见写法。
*
* @param {string} text 原始文本。
* @return {Object|null} 提取到的字段对象;一个字段都没提取到则返回 null。
*/
function salvageFieldsFromText(text) {
if (!text) return null;
const src = String(text);
const out = {};
let foundAny = false;
for (const field of ADDRESS_PARSE_FIELDS) {
const patterns = [
new RegExp(`["']?${field}["']?\\s*[::=]\\s*["']([^"']{0,80})["']`, 'i'),
new RegExp(`["']?${field}["']?\\s*[::=]\\s*([^\\s,,;;\\n"']{0,80})`, 'i'),
];
for (const re of patterns) {
const m = src.match(re);
if (m && m[1] && m[1].trim()) {
out[field] = m[1].trim();
foundAny = true;
break;
}
}
}
return foundAny ? out : null;
}
/**
* 清洗手机号:仅保留合法 11 位大陆手机号;兜底提取的脏数据(如整段地址)置空。
*
* @param {*} mobile 原始手机号字段。
* @return {string} 合法手机号或空字符串。
*/
function sanitizeMobile(mobile) {
const m = String(mobile || '').trim();
return /^1[3-9]\d{9}$/.test(m) ? m : '';
}
/**
* 清洗收件人姓名:过滤过长的字符串与明显混入地址信息的脏数据。
*
* @param {*} name 原始姓名字段。
* @return {string} 合法姓名或空字符串。
*/
function sanitizeName(name) {
const n = String(name || '').trim();
if (!n || n.length > 20) return '';
if (/[省市县区镇街道路号村组栋座楼室单元乡]/.test(n)) return '';
return n;
}
/**
* 地址解析最终兜底:AI 解析与行政区划映射表均失败时,用正则按"省-市-区-镇"顺序
* 地址解析最终兜底:本地字典遍历与行政区划映射表均失败时,用正则按"省-市-区-镇"顺序
* 从原始地址字符串中提取行政区划。支持省份全称与简称(如"广东"、"内蒙古")。
*
* @param {string} text 原始地址字符串。
@ -667,6 +647,210 @@ function extractAddressByRegex(text) {
return result;
}
/**
* 本地地址解析副接口核心逻辑:不调用 AI,直接遍历内置的省市区地址字典数据,
* 对地址字符串做包含匹配,识别出省/市/区(及乡镇、详细地址、手机号)。
*
* 遍历识别顺序:
* 1. 提取并剥离手机号
* 2. 遍历 LOCAL_CITY_DICT 找最先出现的地级市 → city + province
* 3. 无城市命中时,遍历 CHINA_ADMIN_DIVISION_MAP 找特殊行政区 → area + 反查省/市
* 4. 仍未识别省份时,遍历 PROVINCE_LIST 全称/简称匹配
* 5. 有省无市时,在省名之后正则提取市
* 6. 直辖市补全:province 与 city 同名
* 7. 有市无区时,在市名之后遍历特殊行政区 + 正则提取区/县
* 8. 复用 reverseInferAddress 统一补全缺失的省/市/区
* 9. 正则提取乡镇/街道,剩余部分作为详细地址
*
* @param {*} rawAddress 原始地址字符串。
* @return {Object} { address, ok, message, fields };fields 为
* { province, city, area, town, detailAddress, name, mobile } 或 null。
*/
function parseAddressByLocalDict(rawAddress) {
const address = String(rawAddress || '').trim();
if (!address) {
return { address, ok: false, message: '地址字符串不能为空', fields: null };
}
// 1. 提取并剥离手机号
let working = address;
let mobile = '';
const mobileMatch = working.match(/1[3-9]\d{9}/);
if (mobileMatch) {
mobile = mobileMatch[0];
working = working.replace(mobile, '');
}
let province = '';
let city = '';
let area = '';
// 2. 遍历地级市字典,取地址中最先出现的城市
let cityIdx = -1;
for (const [ cityName, provinceName ] of Object.entries(LOCAL_CITY_DICT)) {
const idx = working.indexOf(cityName);
if (idx >= 0 && (cityIdx === -1 || idx < cityIdx)) {
cityIdx = idx;
city = cityName;
province = provinceName;
}
}
// 3. 无城市命中时,遍历特殊行政区映射(省直辖县级市/不设区地级市/代管县级市)
if (!city) {
let areaIdx = -1;
for (const [ key, entry ] of Object.entries(CHINA_ADMIN_DIVISION_MAP)) {
const idx = working.indexOf(key);
if (idx >= 0 && (areaIdx === -1 || idx < areaIdx)) {
areaIdx = idx;
area = key;
province = entry.province;
city = entry.city;
}
}
}
// 4. 仍未识别省份时,遍历省份全称/简称
if (!province) {
for (const p of PROVINCE_LIST) {
if (working.includes(p)) {
province = p;
break;
}
const short = p.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, '');
if (short !== p && working.includes(short)) {
province = p;
break;
}
}
}
// 5. 有省无市:在省名之后正则提取市
if (province && !city) {
const short = province.replace(/(壮族自治区|回族自治区|维吾尔自治区|特别行政区|自治区|省|市)$/, '');
const fullIdx = working.indexOf(province);
const shortIdx = working.indexOf(short);
const idx = Math.max(fullIdx, shortIdx);
const skipLen = fullIdx >= 0 ? province.length : short.length;
const rest = idx >= 0 ? working.slice(idx + skipLen) : working;
const cityMatch = rest.match(/([\u4e00-\u9fa5]{2,10}?(?:自治州|地区|盟|市))/);
if (cityMatch) {
city = cityMatch[1];
}
}
// 6. 直辖市补全:province 与 city 同名
if (!province && MUNICIPALITY_SET.has(city)) {
province = city;
}
if (province && !city && MUNICIPALITY_SET.has(province)) {
city = province;
}
// 7. 有市无区:在市名之后遍历特殊行政区 + 正则提取区/县
if (city && !area) {
const cityPos = working.indexOf(city);
const rest = cityPos >= 0 ? working.slice(cityPos + city.length) : working;
for (const key of Object.keys(CHINA_ADMIN_DIVISION_MAP)) {
if (rest.includes(key)) {
area = key;
break;
}
}
if (!area) {
const areaMatch = rest.match(/([\u4e00-\u9fa5]{1,10}?(?:自治县|自治旗|旗|区|县|市))/);
if (areaMatch) {
area = areaMatch[1];
}
// "市辖区"不是真实行政区(东莞/中山等不设区地级市的历史遗留写法),
// 从原文剥离并置空 area,交由 reverseInferAddress 对不设区地级市将 area 补为 city;
// 剥离可避免后续 town/detailAddress 提取把"市辖区"误并入街道名
if (area === '市辖区') {
working = working.replace('市辖区', '');
area = '';
}
}
}
// 8. 复用反向推断补全缺失的省/市/区(含不设区地级市 area 补 city 等规则)
let town = '';
const inferred = reverseInferAddress({
province,
city,
area,
town,
detailAddress: working,
name: '',
mobile,
});
province = inferred.province;
city = inferred.city;
area = inferred.area;
// 9. 提取乡镇/街道:限定在已识别行政区(city/area)之后的余串开头匹配,
// 避免正则从地址开头扫描时把省市区前缀吞进镇名(如"苏省苏州市昆山市花桥镇")
town = '';
let restTail = working;
{
const areaPos = area ? working.indexOf(area) : -1;
const cityPos = city ? working.indexOf(city) : -1;
const areaEnd = areaPos >= 0 ? areaPos + area.length : -1;
const cityEnd = cityPos >= 0 ? cityPos + city.length : -1;
if (Math.max(areaEnd, cityEnd) >= 0) {
restTail = working.slice(Math.max(areaEnd, cityEnd));
}
}
const townMatch = restTail.match(/^[\s,,、]*([\u4e00-\u9fa5]{2,10}?(?:街道|办事处|镇|乡))/);
if (townMatch) {
town = townMatch[1];
}
let cutEnd = -1;
for (const part of [ province, city, area, town ]) {
if (!part) continue;
const idx = working.indexOf(part);
if (idx >= 0 && idx + part.length > cutEnd) {
cutEnd = idx + part.length;
}
}
let detailAddress = cutEnd >= 0 ? working.slice(cutEnd) : working;
detailAddress = detailAddress.replace(/^[\s,,、-]+/, '').trim();
// 10. 正则最终兜底:字典遍历无法识别时,用正则从原文提取省市区
if (!province && !city && !area) {
const regexResult = extractAddressByRegex(working);
if (regexResult.province) {
province = regexResult.province;
city = city || regexResult.city;
area = area || regexResult.area;
if (!town) {
town = regexResult.town;
}
// 重算详细地址
cutEnd = -1;
for (const part of [ province, city, area, town ]) {
if (!part) continue;
const idx = working.indexOf(part);
if (idx >= 0 && idx + part.length > cutEnd) {
cutEnd = idx + part.length;
}
}
detailAddress = cutEnd >= 0 ? working.slice(cutEnd) : working;
detailAddress = detailAddress.replace(/^[\s,,、-]+/, '').trim();
}
}
if (!province && !city && !area) {
return { address, ok: false, message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
}
return {
address,
ok: true,
message: 'ok',
fields: { province, city, area, town, detailAddress, name: '', mobile },
};
}
class PendingOrderService extends OrderBaseService {
/**
* 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。
@ -676,9 +860,9 @@ class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateExpressCodeTaskProgress,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,syncOrderIdsProgress,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,parseAddressLocal,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill,allocateSubOrderNumber,allocateSubOrderNumberProgress,batchMarkPrinted';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -3653,25 +3837,26 @@ class PendingOrderService extends OrderBaseService {
}
/**
* 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。
* 智能地址解析:使用本地省市区字典遍历方式将地址字符串解析为结构化地址。
*
* 原 DeepSeek AI 解析方式已弃用,现改为本地字典遍历识别(与 parseAddressLocal 同源):
* - 遍历 LOCAL_CITY_DICT(约 340 个地级市)识别 province/city
* - 遍历 CHINA_ADMIN_DIVISION_MAP(省直辖县级市/不设区地级市/代管县级市)识别特殊区县
* - 遍历 PROVINCE_LIST 全称/简称兜底识别省份
* - 复用 reverseInferAddress 补全省/市/区,extractAddressByRegex 正则最终兜底
*
* 支持单条解析与数组批量解析两种模式:
* - 单条:data.address 传字符串,返回单条解析结果(与原行为一致)
* - 批量:data.addresses(或 data.address)传字符串数组,按数组顺序返回 data.list,
* 每条元素含 address/flag/message 与解析字段,失败条目不影响其他条目
*
* 采用"AI 解析 + 反向识别兜底"双层策略:
* 1. 先由 DeepSeek AI 进行语义级地址解析
* 2. 若 AI 返回的省/市/区字段缺失,通过内置的中国行政区划映射表反向补全
* 3. 仅在两层策略均无法确定 province 时才判定失败
*
* @param {Object} data 请求数据。
* @param {string|string[]} data.address 原始地址字符串或字符串数组(必填)。
* @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。
* @return {Promise<Object>} 解析结果;批量模式返回 data.list 数组。
*/
async parseAddress(data = {}) {
// 批量模式:addresses 数组优先,其次 address 数组
// 批量模式:addresses 数组优先,其次 address 数组;均走本地字典遍历解析
const rawAddresses = Array.isArray(data.addresses)
? data.addresses
: (Array.isArray(data.address) ? data.address : null);
@ -3683,334 +3868,87 @@ class PendingOrderService extends OrderBaseService {
if (rawAddresses.length > 50) {
return this.fail('单次批量解析最多支持 50 条地址');
}
// 批量提速:每 10 条合并为一次 DeepSeek 请求(实测 10 条约 18s、无截断),
// 所有块异步并行发出,全部完成后按输入顺序聚合返回;失败/缺失条目逐条回退单条解析。
const CHUNK_SIZE = 10;
const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' };
const toListItem = r => ({
address: r.address,
flag: r.flag,
flag: r.ok ? 'success' : 'failure',
message: r.message,
...(r.fields || EMPTY_FIELDS),
});
const chunks = [];
for (let i = 0; i < rawAddresses.length; i += CHUNK_SIZE) {
chunks.push(rawAddresses.slice(i, i + CHUNK_SIZE));
}
const chunkResults = await Promise.all(chunks.map(chunk => this._parseAddressBatchOneShot(chunk)));
const results = await Promise.all(rawAddresses.map((item, idx) => {
const r = chunkResults[Math.floor(idx / CHUNK_SIZE)];
const inChunk = r && r[idx % CHUNK_SIZE];
return inChunk && inChunk.ok ? inChunk : this._parseSingleAddress(item);
}));
const results = rawAddresses.map(item => parseAddressByLocalDict(item));
return this.success('地址解析成功', { list: results.map(toListItem) });
}
// 单条模式(向后兼容)
const single = await this._parseSingleAddress(data.address);
const single = parseAddressByLocalDict(data.address);
if (!single.ok) {
return this.fail(single.message);
}
return this.success('地址解析成功', single.fields);
}
/**
* 块内一次性解析:把一组地址(建议 10 条)合并为一次 DeepSeek 请求,
* 让模型按编号返回 JSON 数组,省去逐条请求的网络开销。
*
* @param {string[]} addressList 地址字符串数组。
* @return {Promise<Array|null>} 与入参顺序对齐的逐条结果数组;
* 请求失败/JSON 解析失败/被截断时返回 null,由调用方逐条回退单条解析。
*/
async _parseAddressBatchOneShot(addressList) {
const apiKey = this.config.deepseek.apiKey;
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
if (!apiKey) return null;
const numbered = addressList.map((a, i) => `${i + 1}. ${a}`).join('\n');
const prompt = `你是一个专业的中文地址解析助手。请一次性解析以下 ${addressList.length} 条地址,按编号顺序返回JSON数组,每条为:
{"index":编号,"province":"省","city":"市","area":"区/县","town":"乡镇/街道","detailAddress":"详细地址","name":"收件人","mobile":"手机号"}
规则:
1. 地址重复拼接时先智能去重再解析
2. 直辖市:province与city都填直辖市名,area填市辖区名
3. 无法识别的字段填空字符串
4. 只返回JSON数组,不含解释或markdown
地址列表:
${numbered}`;
try {
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
headers: {
Authorization: `Bearer ${apiKey}`,
},
data: {
model: 'deepseek-v4-flash',
messages: [
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
{ role: 'user', content: prompt },
],
temperature: 0,
max_tokens: 32000,
},
timeout: 120000,
});
if (result.status !== 200 || !result.data) {
return null;
}
const choice = result.data.choices?.[0] || {};
// 被截断时整体回退,避免残缺数组造成大量错位
if ((choice.finish_reason || '') === 'length') {
return null;
}
const content = String(choice.message?.content || '').trim();
const arr = JSON.parse(extractJsonBlock(content));
if (!Array.isArray(arr)) {
return null;
}
this.ctx.logger.info('[parseAddress] 批量块请求完成:入参 %d 条,finish_reason=%s,返回 %d 条', addressList.length, choice.finish_reason, arr.length);
return addressList.map((address, idx) => {
if (!String(address || '').trim()) {
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
}
const item = arr.find(x => x && Number(x.index) === idx + 1);
if (!item) {
return { address, ok: false, flag: 'failure', message: '批量解析未返回该条结果', fields: null };
}
let province = String(item.province || '').trim();
let city = String(item.city || '').trim();
let area = String(item.area || '').trim();
let town = String(item.town || '').trim();
const detailAddress = String(item.detailAddress || '').trim();
const name = sanitizeName(item.name);
const mobile = sanitizeMobile(item.mobile);
// 反向识别兜底 + 正则兜底,与单条解析保持一致
const inferred = reverseInferAddress({ province, city, area, town, detailAddress, name, mobile });
province = inferred.province;
city = inferred.city;
area = inferred.area;
if (!province) {
const regexResult = extractAddressByRegex(address);
if (regexResult.province) {
province = regexResult.province;
city = city || regexResult.city;
area = area || regexResult.area;
town = town || regexResult.town;
}
}
if (!province || province === '暂未识别' || province === '其他') {
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
}
return {
address,
ok: true,
flag: 'success',
message: 'ok',
fields: { province, city, area, town, detailAddress, name, mobile },
};
});
} catch (error) {
this.ctx.logger.warn('[parseAddress] 批量一次性解析失败,将逐条回退: %s', error.message);
return null;
}
}
/**
* 解析单条地址(parseAddress 单条/批量模式共用)。
* 本地地址解析接口:不调用 AI,直接内置省市区地址字典数据,遍历识别省市区。
*
* @param {*} item 原始地址。
* @return {Promise<Object>} { address, ok, flag, message, fields };fields 为解析字段对象或 null。
* 与 parseAddress 使用同一套本地字典遍历解析逻辑,两者解析结果等价;
* - 单条:data.address 传字符串,返回单条解析结果(与 parseAddress 单条结构一致)
* - 批量:data.addresses(或 data.address)传字符串数组,返回 data.list,
* 每条含 address/flag/message 与解析字段,失败条目不影响其他条目
* - 演示:address 与 addresses 均不传时,直接使用接口内置的示例地址数据
* 遍历识别并返回 data.list(data.source=sample)
*
* 识别范围:province/city/area/town/detailAddress/mobile(name 本地不识别,返回空字符串)。
*
* @param {Object} data 请求数据。
* @param {string|string[]} [data.address] 原始地址字符串或字符串数组。
* @param {string[]} [data.addresses] 批量地址字符串数组(与 address 数组二选一)。
* @return {Promise<Object>} 解析结果;批量/演示模式返回 data.list 数组。
*/
async _parseSingleAddress(item) {
const address = String(item || '').trim();
if (!address) {
return { address, ok: false, flag: 'failure', message: '地址字符串不能为空', fields: null };
async parseAddressLocal(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
// 确定输入地址:addresses 数组 > address 数组 > address 字符串 > 内置示例地址数据
let addresses;
let useSample = false;
if (Array.isArray(requestData.addresses)) {
addresses = requestData.addresses;
} else if (Array.isArray(requestData.address)) {
addresses = requestData.address;
} else if (String(requestData.address || '').trim()) {
addresses = [ String(requestData.address).trim() ];
} else {
addresses = LOCAL_SAMPLE_ADDRESSES.slice();
useSample = true;
}
const apiKey = this.config.deepseek.apiKey;
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
if (!apiKey) {
return { address, ok: false, flag: 'failure', message: 'DeepSeek API Key 未配置', fields: null };
if (!addresses.length) {
return this.fail('地址数组不能为空');
}
if (!useSample && addresses.length > 50) {
return this.fail('单次批量解析最多支持 50 条地址');
}
try {
// 仅在 parseAddress 使用 v4-flash(速度优先,适合批量解析),不改全局配置
const model = 'deepseek-v4-flash';
const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。
const EMPTY_FIELDS = { province: '', city: '', area: '', town: '', detailAddress: '', name: '', mobile: '' };
const toListItem = r => ({
address: r.address,
flag: r.ok ? 'success' : 'failure',
message: r.message,
...(r.ok && r.fields ? r.fields : EMPTY_FIELDS),
});
规则:
1. 提取字段:province(省)、city(市)、area(区/县)、town(乡镇/街道)、detailAddress(详细地址)、name(收件人)、mobile(手机号)
2. **中国行政区划特殊规则(非常重要)**:
- 四大直辖市(北京、天津、上海、重庆):province填直辖市名,city填直辖市名,area填市辖区名(如"朝阳区")
- 省直辖县级市(如湖北仙桃/潜江/天门、河南济源、海南五指山/琼海/文昌/万宁/东方、新疆石河子等):province填省名,city填省名或留空,area填县级市名
- 不设区的地级市(如东莞、中山、嘉峪关、儋州、三沙):province填省名,city填地级市名,area填地级市名或留空
- 普通地级市代管的县级市(如苏州代管昆山、无锡代管江阴、潍坊代管寿光等):province填省名,city填地级市名,area填县级市名
3. **利用你的中国地理知识**:如果地址缺少省份或城市信息,请检索你的知识库反向推断。例如:
- "仙桃市xxx路" → province=湖北省, city=湖北省, area=仙桃市(省直辖县级市)
- "昆山市xxx镇" → province=江苏省, city=苏州市, area=昆山市(苏州代管县级市)
- "广东省东莞市xxx镇" → province=广东省, city=东莞市, area=东莞市(不设区的地级市)
- "浙江省xxx村" → 根据村名命名习惯和方言特征推测所属城市
4. 如果实在无法确定,province填"",city和area同理填"",收件人和name同理填"",mobile同理填""。
5. detailAddress去除省市区部分,只保留街道/村/门牌号
6. 地址字符串若出现重复拼接(如"陕西省延安市志丹县"出现两次),先智能去重再解析,合并保留重复部分中的街道/村信息
7. 只返回纯JSON,不含解释或markdown
地址字符串: "${address}"
请返回JSON:`;
const requestDeepSeek = async maxTokens => {
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
headers: {
Authorization: `Bearer ${apiKey}`,
},
data: {
model,
messages: [
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
{ role: 'user', content: prompt },
],
temperature: 0,
max_tokens: maxTokens,
},
timeout: 60000,
});
if (result.status !== 200 || !result.data) {
return null;
}
const choice = result.data.choices?.[0] || {};
return {
content: String(choice.message?.content || '').trim(),
reasoningContent: String(choice.message?.reasoning_content || '').trim(),
finishReason: choice.finish_reason || '',
};
};
// deepseek-v4-flash 为思维链模型,max_tokens 过小时推理会耗尽全部配额,
// 导致 content 为空且 finish_reason=length。首次给足 3000 tokens,
// 仍被截断且无法从 reasoning_content 兜底时,加大到 8000 重试一次。
let response = await requestDeepSeek(3000);
if (
response
&& response.finishReason === 'length'
&& !response.content
&& !salvageFieldsFromText(response.reasoningContent)
) {
this.ctx.logger.warn('[parseAddress] 首次调用被截断(finish_reason=length),以 max_tokens=8000 重试');
response = await requestDeepSeek(8000);
// 单条模式(向后兼容 parseAddress 单条返回结构)
if (!useSample && addresses.length === 1) {
const single = parseAddressByLocalDict(addresses[0]);
if (!single.ok) {
return this.fail(single.message);
}
if (!response) {
return { address, ok: false, flag: 'failure', message: '地址解析服务请求失败', fields: null };
}
const { content, reasoningContent, finishReason } = response;
this.ctx.logger.info('[parseAddress] DeepSeek原始返回 finish_reason=%s content: %s', finishReason, content || '(空)');
const tryParseJson = raw => {
try {
return JSON.parse(raw);
} catch (parseError) {
return null;
}
};
// 清理 markdown 代码块标记,并截取第一个 { 到最后一个 } 之间的 JSON 片段
let parsed = tryParseJson(extractJsonBlock(content));
if (!parsed) {
// 轻量修复:去除对象/数组内的尾随逗号后重试
parsed = tryParseJson(extractJsonBlock(content).replace(/,\s*([}\]])/g, '$1'));
}
// JSON 解析失败时,尝试从 content 或 reasoning_content 文本中做字段级提取兜底
if (!parsed) {
parsed = salvageFieldsFromText(content || reasoningContent);
if (parsed) {
this.ctx.logger.warn('[parseAddress] 正文字段提取兜底结果: %j', parsed);
}
}
if (!parsed) {
this.ctx.logger.warn('[parseAddress] JSON解析失败,finish_reason=%s,原始返回: %s', finishReason, content || reasoningContent);
if (finishReason === 'length') {
return { address, ok: false, flag: 'failure', message: '地址解析超时,请重试', fields: null };
}
return { address, ok: false, flag: 'failure', message: '地址解析结果格式异常,请重试', fields: null };
}
let province = String(parsed.province || '').trim();
let city = String(parsed.city || '').trim();
let area = String(parsed.area || '').trim();
let town = String(parsed.town || '').trim();
const detailAddress = String(parsed.detailAddress || '').trim();
const name = sanitizeName(parsed.name);
const mobile = sanitizeMobile(parsed.mobile);
// --- 反向识别兜底:使用内置行政区划映射表补全缺失字段 ---
const inferred = reverseInferAddress({
province,
city,
area,
town,
detailAddress,
name,
mobile,
});
province = inferred.province;
city = inferred.city;
area = inferred.area;
// --- 最终兜底:AI 与映射表均失败时,用正则从原始地址提取省市区 ---
if (!province) {
const regexResult = extractAddressByRegex(address);
if (regexResult.province) {
province = regexResult.province;
city = city || regexResult.city;
area = area || regexResult.area;
if (!town) {
town = regexResult.town;
}
this.ctx.logger.warn('[parseAddress] 正则兜底解析结果: %j', regexResult);
}
}
// 反向识别后仍无 province 才判定失败
if (!province || province === '暂未识别' || province === '其他') {
return { address, ok: false, flag: 'failure', message: '地址解析失败:省市区无法识别,请补充更多地址信息后重试', fields: null };
}
return {
address,
ok: true,
flag: 'success',
message: 'ok',
fields: {
province,
city,
area,
town,
detailAddress,
name,
mobile,
},
};
} catch (error) {
this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message);
return { address, ok: false, flag: 'failure', message: `地址解析失败: ${error.message}`, fields: null };
return this.success('地址解析成功', single.fields);
}
const list = addresses.map(item => toListItem(parseAddressByLocalDict(item)));
const message = useSample ? '内置示例地址遍历识别成功' : '地址解析成功';
return this.success(message, useSample ? { list, source: 'sample' } : { list });
}
/**

View File

@ -6,9 +6,9 @@ class SettingWarehouseMethodsService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert,getweChatApp';
const _noNeedLog = '*';
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert,getweChatApp';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -183,6 +183,31 @@ class SettingWarehouseMethodsService extends MainService {
});
}
}
/**
* 获取当前仓库启用的微信小程序授权配置(wms_wechat_app)。
*
* 仅返回一条启用(is_enabled=1)记录,配置统一封装在响应 data 字段中,
* data 为对象而非数组;无可用记录时 data 为 null。
*
* @return {Promise<Object>} 统一响应结果。
*/
async getweChatApp() {
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
if (!targetService || typeof targetService.getWechatApp !== 'function') {
return this.fail('获取微信小程序配置失败', { code: 500 });
}
try {
const result = await targetService.getWechatApp();
return this.success('ok', { data: result });
} catch (error) {
return this.fail(error.message || '获取微信小程序配置失败', {
code: Number(error.code) || 500,
});
}
}
}
module.exports = SettingWarehouseMethodsService;

View File

@ -9,7 +9,9 @@ class userService extends MainService {
const _noNeedRight = '*';
const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode';
const _noNeedAuth = '*';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
// info:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问
const _noNeedBind = 'info';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth, _noNeedBind);
}
async login(data) {
const { service } = this;

View File

@ -0,0 +1,322 @@
'use strict';
const MainService = require('../main');
/**
* 微信开放平台 method 层(system.json module: wechat)。
*/
class WechatService extends MainService {
constructor(ctx) {
super(ctx);
// getAuthUrl:需登录、免权限、不记系统日志;loginByCode:免登录、免权限、免鉴权;
// pushLoginCode/queryauth/registerMiniprogram/getTemplateList/commit/getTrialQRCode/submitAudit/userList:需登录、免权限(PC 已登录用户操作);
// bindUser/updateInfo/uploadHeadimg/getMyLoginCode:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问
this.systemInit('loginByCode', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo', '*', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode');
}
/**
* 获取当前微信登录用户的登录码(至少微信登录):无则生成写入,有则直接返回。
*
* @return {Promise<Object>} 统一响应结果。
*/
async getMyLoginCode() {
try {
const result = await this.service.systems.wechat.getMyLoginCode();
if (result && result.success === true) {
return this.success(result.message || '获取成功', result.data);
}
return this.fail((result && result.message) || '获取失败');
} catch (e) {
return this.fail('获取登录码失败:' + e.message);
}
}
async getAuthUrl(data) {
try {
const result = await this.service.systems.wechat.getAuthUrl(data || {});
return this.success('获取成功', result);
} catch (e) {
return this.fail(e.message);
}
}
/**
* 小程序登录码登录(免登录):入参 code + app_id,返回 token + user(参考 auth.login)。
*
* @param {Object} data 请求参数。
* @return {Promise<Object>} 统一响应结果。
*/
async loginByCode(data) {
try {
const result = await this.service.systems.wechat.loginByCode(data || {});
if (result.code) {
return this.success('登录成功', result);
}
return this.fail('登录失败:' + result.message, result);
} catch (e) {
return this.fail('登录失败:' + e.message);
}
}
/**
* 绑定用户(微信登录态中间层):用户名密码一致则绑定并签发新 token。
*
* @param {Object} data 请求参数(username/password)。
* @return {Promise<Object>} 统一响应结果。
*/
async bindUser(data) {
try {
const result = await this.service.systems.wechat.bindUser(data || {});
if (result.code) {
return this.success('绑定成功', result);
}
return this.fail('绑定失败:' + result.message, result);
} catch (e) {
return this.fail('绑定失败:' + e.message);
}
}
/**
* 确认登录码(需登录,PC 已登录用户确认小程序登录)。
*
* @param {Object} data 请求参数(code)。
* @return {Promise<Object>} 统一响应结果。
*/
async pushLoginCode(data) {
try {
const result = await this.service.systems.wechat.pushLoginCode(data || {});
if (result.code) {
return this.success(result.message || '操作成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('确认登录失败:' + e.message);
}
}
/**
* 查询当前仓库小程序认证状态(需登录)。
*
* @param {Object} data 请求参数(taskid)。
* @return {Promise<Object>} 统一响应结果。
*/
async queryauth(data) {
try {
const result = await this.service.systems.wechat.queryauth(data || {});
if (result.code) {
return this.success(result.message || '查询成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('查询认证状态失败:' + e.message);
}
}
/**
* 发起小程序认证(需登录):前端上传材料换取 media_id 后一步提交。
*
* @param {Object} data 请求参数(contact_type/contact_name 必填,其余白名单字段透传)。
* @return {Promise<Object>} 统一响应结果。
*/
async wxaauth(data) {
try {
const result = await this.service.systems.wechat.wxaauth(data || {});
if (result.code) {
return this.success(result.message || '认证已发起', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('发起认证失败:' + e.message);
}
}
/**
* 获取并同步当前仓库小程序基础信息(需登录)。
*
* 调微信 api_get_authorizer_info 拉取授权账号详情(authorizer_info + authorization_info),
* 将基础信息/认证类型/权限集等落库 wms_wechat_app 后返回完整数据。
*
* @param {Object} data 请求参数(无)。
* @return {Promise<Object>} 统一响应结果。
*/
async getAuthorizerInfo(data) {
try {
const result = await this.service.systems.wechat.getAuthorizerInfo(data || {});
if (result.code) {
return this.success(result.message || '获取成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('获取小程序基础信息失败:' + e.message);
}
}
/**
* 快速注册企业小程序(需登录)。
*
* @param {Object} data 请求参数(name/code/code_type/legal_persona_wechat/legal_persona_name/component_phone)。
* @return {Promise<Object>} 统一响应结果。
*/
async registerMiniprogram(data) {
try {
const result = await this.service.systems.wechat.registerMiniprogram(data || {});
if (result.code) {
return this.success(result.message || '操作成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('注册小程序失败:' + e.message);
}
}
/**
* 更新微信账号资料(微信登录态中间层,仅未绑定用户)。
*
* @param {Object} data 请求参数(nickname/headimgurl)。
* @return {Promise<Object>} 统一响应结果。
*/
async updateInfo(data) {
try {
const result = await this.service.systems.wechat.updateInfo(data || {});
if (result.code) {
return this.success(result.message || '更新成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('更新失败:' + e.message);
}
}
/**
* 上传微信账号头像(微信登录态中间层,至少微信登录即可)。
*
* @param {Object} data 请求参数(image: 裁剪后的 PNG base64)。
* @return {Promise<Object>} 统一响应结果。
*/
async uploadHeadimg(data) {
try {
const result = await this.service.systems.wechat.uploadHeadimg(data || {});
if (result.code) {
return this.success(result.message || '上传成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('上传头像失败:' + e.message);
}
}
/**
* 获取小程序模板库列表(需登录,Redis 缓存 24h)。
*
* @return {Promise<Object>} 统一响应结果。
*/
async getTemplateList() {
try {
const result = await this.service.systems.wechat.getTemplateList();
if (result.code) {
return this.success(result.message || '获取成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('获取模板列表失败:' + e.message);
}
}
/**
* 上传代码并生成体验版(需登录)。
*
* @param {Object} data 请求参数(template_id/ext_json/user_version/user_desc)。
* @return {Promise<Object>} 统一响应结果。
*/
async commit(data) {
try {
const result = await this.service.systems.wechat.commit(data || {});
if (result.code) {
return this.success(result.message || '上传成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('上传代码失败:' + e.message);
}
}
/**
* 获取体验版二维码(需登录)。
*
* @param {Object} data 请求参数(可选 path)。
* @return {Promise<Object>} 统一响应结果。
*/
async getTrialQRCode(data) {
try {
const result = await this.service.systems.wechat.getTrialQRCode(data || {});
if (result.code) {
return this.success(result.message || '获取成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('获取体验版二维码失败:' + e.message);
}
}
/**
* 提交代码审核(需登录)。
*
* @param {Object} data 请求参数(item_list/version_desc 等,均为可选)。
* @return {Promise<Object>} 统一响应结果。
*/
async submitAudit(data) {
try {
const result = await this.service.systems.wechat.submitAudit(data || {});
if (result.code) {
return this.success(result.message || '提交成功', result);
}
return this.fail(result.message, result);
} catch (e) {
return this.fail('提交代码审核失败:' + e.message);
}
}
/**
* 拉取当前仓库小程序的用户列表(需登录,支持 where/pagination/sort)。
*
* @param {Object} data 请求参数(可选 app_id/where/pagination/sort)。
* @return {Promise<Object>} 统一响应结果。
*/
async userList(data = {}) {
try {
// where 字段白名单:仅允许按用户表常规字段过滤,禁止探测敏感列
const allowedWhereFields = new Set([
'id',
'user_id',
'app_id',
'openid',
'unionid',
'nickname',
'sex',
'login_time',
'login_count',
'created_at',
'updated_at',
]);
const rawWhere = data.where && typeof data.where === 'object' ? data.where : {};
const filteredWhere = {};
for (const key of Object.keys(rawWhere)) {
if (allowedWhereFields.has(key)) {
filteredWhere[key] = rawWhere[key];
}
}
data.where = filteredWhere;
this.prepareWhereContext(data);
const result = await this.service.systems.wechat.userList(data);
if (result.code) {
return this.success(result.message || '获取成功', result.data);
}
return this.fail(result.message);
} catch (e) {
return this.fail('获取用户列表失败:' + e.message);
}
}
}
module.exports = WechatService;

View File

@ -305,6 +305,38 @@ class UserService extends Service {
}
}
/**
* 发布微信登录事件(唤醒 user.getLoginWechatCode 打开的长轮询)。
*
* @param {string} clientCode 客户端编码。
* @param {object} [payload={}] 附加事件数据(如 ye4s_user_id)。
* @return {Promise<void>} 无返回值。
*/
async publishWechatLoginEvent(clientCode, payload = {}) {
const { app } = this;
if (!clientCode) {
return;
}
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
if (!cacheRedis) {
return;
}
const channel = this.getWechatLoginEventChannel(clientCode);
const eventData = {
client_code: clientCode,
event_at: new Date().toISOString(),
...payload,
};
try {
await cacheRedis.publish(channel, JSON.stringify(eventData));
} catch (error) {
app.coreLogger.warn(`发布微信登录事件失败: ${error.message}`);
}
}
async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
const { app } = this;
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
@ -1629,14 +1661,62 @@ class UserService extends Service {
/**
* 获取用户信息(重构版)
* @return {Object} 用户信息
* @param {Object} [data={}] 入参。
* @param {string} [data.wechat_appId] 小程序 AppID:传入时按该小程序归属仓库过滤工号列表,
* 仅保留非仓库工号(货主)与该仓库工号;未传入/查不到仓库时保持原逻辑。
* @return {Object} 用户信息
*/
async info() {
async info(data = {}) {
const { ctx } = this;
try {
// 微信登录态中间层:未绑定真实用户时返回微信层信息(不 401)
if (!ctx.userId && !ctx.user && ctx.oauth) {
const oauth = ctx.oauth;
return {
success: true,
data: {
id: Number(oauth.user_id) || 0,
is_bound: Number(oauth.user_id) > 0,
oauth_id: oauth.id,
user_id: Number(oauth.user_id) || 0,
openid: oauth.openid,
unionid: oauth.unionid || '',
nickname: oauth.nickname || '',
headimgurl: oauth.headimgurl || '',
login_time: oauth.login_time,
login_count: oauth.login_count,
},
code: 200,
};
}
const userId = ctx.userId || (ctx.user && ctx.user.id);
const user = await this.findById(userId);
if (!user) {
return {
success: false,
data: null,
code: 401,
};
}
// 可选:传入 wechat_appId 时按小程序归属仓库过滤工号列表
// (只保留非仓库工号(货主)与仅该仓库工号)
const appId = typeof data.wechat_appId === 'string' ? data.wechat_appId.trim() : '';
if (appId) {
const wechatApp = await ctx.model.WechatApp.findOne({
where: { appid: appId, is_enabled: 1 },
attributes: [ 'id', 'appid', 'warehouse_id' ],
});
const warehouseId = Number(wechatApp && wechatApp.warehouse_id);
if (wechatApp && Number.isInteger(warehouseId) && warehouseId > 0 && Array.isArray(user.employees)) {
user.employees = user.employees.filter(
employee => String(employee.role_type) !== 'warehouse' || Number(employee.store_id) === warehouseId
);
}
}
return {
success: true,
data: user,

View File

@ -117,6 +117,15 @@ class OrderAutoOutboundService extends MainService {
* - {boolean} [rules.require_sync] 是否要求已同步(sync_status='fin')
* - {boolean} [rules.require_print] 是否要求已打印(print_status='fin')
* - {boolean} [rules.require_pick] 是否要求已拣货(pick_status='fin')
* - {boolean} [rules.exclude_same_day_outbound] 是否不出库当天复核订单(默认 true);
* 为 true 时,在到达当天放开时间(same_day_outbound_release_time,默认北京时间 22:00)前,
* 北京时间当天「允许当天出库最后时间」(same_day_outbound_deadline_time,默认 06:00)起复核(recheck_time)的订单当天不参与自动出库;
* recheck_time 早于该最后时间或为 null 的订单不受影响;
* 到达放开时间后当天复核订单恢复自动出库。
* - {string} [rules.same_day_outbound_deadline_time] 允许当天出库最后时间(HH:mm,默认 '06:00'),
* 复核时间早于该时间的订单不受「不出库当天订单」开启的影响。
* - {string} [rules.same_day_outbound_release_time] 当天放开时间(HH:mm,默认 '22:00'),
* 仅在 exclude_same_day_outbound 为 true 时生效。
* @return {Object} Sequelize where 条件对象。
*/
buildAutoOutboundWhere(rules) {
@ -132,6 +141,24 @@ class OrderAutoOutboundService extends MainService {
where.recheck_status = 'fin';
}
// 开启「不出库当天订单」(默认开启)时:当天到达放开时间(默认北京时间 22:00)前,
// 排除当天「允许当天出库最后时间」(默认 06:00)起复核的订单(recheck_time 为 null 不排除);
// 到达放开时间后不再限制当天复核订单,当天即可出库。
// 注意:应用按 UTC 读写 DATETIME,recheck_time 存储为 UTC 时刻,边界需按北京时间(UTC+8)换算。
if (rules.exclude_same_day_outbound !== false) {
const now = new Date();
const releaseUtc = this.buildSameDayReleaseUtc(now, rules.same_day_outbound_release_time);
if (now.getTime() < releaseUtc.getTime()) {
const sameDayCutoffUtc = this.buildSameDayOutboundCutoffUtc(now, rules.same_day_outbound_deadline_time);
where.recheck_time = {
[Op.or]: [
{ [Op.lt]: sameDayCutoffUtc },
{ [Op.is]: null },
],
};
}
}
if (rules.require_pack) {
where.pack_status = 'fin';
}
@ -192,6 +219,77 @@ class OrderAutoOutboundService extends MainService {
return orders;
}
/**
* 计算「允许当天出库最后时间」边界(UTC 时刻)。
*
* 边界为北京时间当天配置时刻(默认 06:00,UTC+8):
* - recheck_time(UTC 存储)早于该边界 → 不受「不出库当天订单」开启影响,当天允许自动出库;
* - recheck_time 晚于或等于该边界 → 在到达当天放开时间前不自动出库,
* 到达放开时间(默认 22:00)后放开。
*
* 用 UTC 显式换算,不依赖 Node 进程时区(生产服务器 TZ 可能与北京时间不一致)。
*
* @param {Date} [now] 当前时刻(用于计算“今天”,默认 new Date())。
* @param {string} [timeText] 允许当天出库最后时间(HH:mm,默认 '06:00')。
* @return {Date} 北京时间当天该时刻对应的 UTC Date。
*/
buildSameDayOutboundCutoffUtc(now = new Date(), timeText) {
const DAY_MS = 24 * 3600 * 1000;
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
const { hour, minute } = this.resolveSameDayTime(timeText, 6, 0);
// 当前时刻换算为北京时刻后,取北京当天 0 点的毫秒基准
const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS;
const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS;
return new Date(beijingMidnightMs + hour * 3600 * 1000 + minute * 60 * 1000 - BEIJING_OFFSET_MS);
}
/**
* 解析 HH:mm 时间配置为小时/分钟,缺省或格式非法时回退指定默认值。
*
* @param {string} [timeText] 时间文本,如 '22:00'。
* @param {number} defaultHour 默认小时。
* @param {number} defaultMinute 默认分钟。
* @return {{hour: number, minute: number}} 小时与分钟。
*/
resolveSameDayTime(timeText, defaultHour, defaultMinute) {
const text = typeof timeText === 'string' ? timeText.trim() : '';
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(text);
if (!match) {
return { hour: defaultHour, minute: defaultMinute };
}
return { hour: Number(match[1]), minute: Number(match[2]) };
}
/**
* 解析「当天放开时间」配置为小时/分钟(HH:mm)。
* 缺省或格式非法时回退默认 22:00。
*
* @param {string} [timeText] 时间文本,如 '22:00'。
* @return {{hour: number, minute: number}} 小时与分钟。
*/
resolveSameDayReleaseTime(timeText) {
return this.resolveSameDayTime(timeText, 22, 0);
}
/**
* 计算北京时间当天「放开时间」对应的 UTC Date。
*
* 仅在开启「不出库当天订单」时使用:当前时刻早于该边界时,
* 当天最后时间之后复核的订单不自动出库;晚于或等于该边界时放开。
*
* @param {Date} [now] 当前时刻(默认 new Date())。
* @param {string} [timeText] 放开时间(HH:mm,默认 22:00)。
* @return {Date} 北京时间当天放开时间对应的 UTC Date。
*/
buildSameDayReleaseUtc(now = new Date(), timeText) {
const DAY_MS = 24 * 3600 * 1000;
const BEIJING_OFFSET_MS = 8 * 3600 * 1000;
const { hour, minute } = this.resolveSameDayReleaseTime(timeText);
const beijingNowMs = now.getTime() + BEIJING_OFFSET_MS;
const beijingMidnightMs = Math.floor(beijingNowMs / DAY_MS) * DAY_MS;
return new Date(beijingMidnightMs + hour * 3600 * 1000 + minute * 60 * 1000 - BEIJING_OFFSET_MS);
}
/**
* 查找有称重记录的订单ID列表。
*

View File

@ -226,7 +226,7 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
key: 'auto_outbound_rules',
name: '自动出库规则',
type: 'object',
default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true, require_print: true, require_pick: true }),
default: Object.freeze({ enabled: false, require_recheck: true, require_pack: true, require_weigh: true, require_sync: true, require_print: true, require_pick: true, exclude_same_day_outbound: true, same_day_outbound_deadline_time: '06:00', same_day_outbound_release_time: '22:00' }),
required: false,
description: '满足条件自动标记出库。全部条件满足时自动标记待出库',
item_keys: Object.freeze([
@ -237,6 +237,9 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
Object.freeze({ key: 'require_sync', name: '需已同步', type: 'flag', required: false, description: '是否要求 sync_status=fin' }),
Object.freeze({ key: 'require_print', name: '需已打印', type: 'flag', required: false, description: '是否要求 print_status=fin' }),
Object.freeze({ key: 'require_pick', name: '需已拣货', type: 'flag', required: false, description: '是否要求 pick_status=fin' }),
Object.freeze({ key: 'exclude_same_day_outbound', name: '不出库当天订单', type: 'flag', required: false, default: true, description: '开启后,在当天放开时间前,「允许当天出库最后时间」之后复核的订单不自动出库,到达当天放开时间后恢复' }),
Object.freeze({ key: 'same_day_outbound_deadline_time', name: '允许当天出库最后时间', type: 'string', required: false, default: '06:00', maxLength: 5, min: '00:00', max: '23:59', description: '复核时间早于该时间的订单不受「不出库当天订单」开启的影响,格式 HH:mm,不能大于当天放开时间' }),
Object.freeze({ key: 'same_day_outbound_release_time', name: '当天放开时间', type: 'string', required: false, default: '22:00', maxLength: 5, min: '00:00', max: '23:59', description: '开启「不出库当天订单」时,当天到达该时间后不再限制当天复核订单的自动出库,格式 HH:mm' }),
]),
}),
Object.freeze({
@ -977,6 +980,52 @@ class SettingWarehouseService extends Service {
return this.buildFrontConfigOutput(record, warehouseId);
}
/**
* 获取当前仓库启用的微信小程序授权配置(wms_wechat_app)。
*
* 只拉取一条启用记录(is_enabled=1,按 id 升序取第一条),返回值为对象;
* 无可用记录时返回 null(接口 data 为空)。
* 出于安全考虑不返回 authorizer_refresh_token 长期令牌。
*
* @return {Promise<Object|null>} 微信小程序配置对象;无可用记录时 null。
* @throws {Error} 未识别到当前仓库时抛出,状态码 400。
*/
async getWechatApp() {
const warehouseId = this.getCurrentWarehouseId();
const wechatAppModel = this.ctx.model && this.ctx.model.WechatApp;
if (!wechatAppModel || typeof wechatAppModel.findOne !== 'function') {
throw this.createError('WechatApp model 不可用', 500);
}
const record = await wechatAppModel.findOne({
where: {
warehouse_id: warehouseId,
is_enabled: 1,
},
order: [[ 'id', 'ASC' ]],
});
if (!record) {
return null;
}
const plain = record.get ? record.get({ plain: true }) : record;
return {
id: plain.id,
warehouse_id: plain.warehouse_id,
appid: plain.appid,
nickname: plain.nickname,
user_name: plain.user_name,
head_img: plain.head_img,
auth_time: plain.auth_time,
func_info: plain.func_info,
is_enabled: plain.is_enabled,
created_at: plain.created_at,
updated_at: plain.updated_at,
};
}
/**
* 构建前端配置公共拉取接口的缓存键(按域名)。
*

View File

@ -403,6 +403,48 @@ class UploadService extends Service {
}
}
/**
* 服务器端上传 Buffer(小文件直传,如前端裁剪后的头像)。
*
* @param {Buffer} buffer 文件内容 Buffer。
* @param {Object} options 上传选项(key 必传或由 generateFileName 生成;
* maxSizeBytes 覆盖大小上限;mimetype 限定后缀)。
* @return {Promise<Object>} 上传结果(fileName/url/cdnUrl/cosUrl/etag 等)。
*/
async uploadBuffer(buffer, options = {}) {
const { bucket, region, uploadurl, cdnurl } = this.getCosConfig();
if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
throw new Error('上传内容为空');
}
const filename = options.filename || 'image.png';
this.validateFile({ filename, fileSize: buffer.length }, options);
const fileName = options.key || this.generateFileName(
filename,
options.mimeType || 'image/png',
options.category
);
const result = await this.cos.putObject({
Bucket: bucket,
Region: region,
Key: fileName,
Body: buffer,
ContentLength: buffer.length,
});
return {
fileName,
cosUrl: `${uploadurl}/${fileName}`,
cdnUrl: `${cdnurl}/${fileName}`,
url: `${cdnurl}/${fileName}`,
etag: result.ETag,
location: result.Location,
uploadAt: new Date().toISOString(),
};
}
/**
* 验证文件
* @param {Object} fileStream 文件流对象

File diff suppressed because it is too large Load Diff

View File

@ -778,8 +778,8 @@ class WorkbenchService extends Service {
* 打包任务写入:根据发货单号查询订单并创建/更新打包任务记录。
* 兼容一单多号(主单号/子单号):传入 waybill_code 时按「订单 + 运单号」维度
* 记录打包流水与去重,主/子单号流水互不覆盖;未传时保持订单维度(兼容旧设备端)。
* 打包人一律取该工作台绑定成员(wms_workbench_member),不再接收 users 入参。
* @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time, waybill_code }
* 打包人:上报了 users(business 旧链路)以上报为准,未上报(token+key 新链路)自动回填工作台绑定成员。
* @param {Object} params - { delivery_order_code, wave_no, warehouse_id, workbench_id, status, pack_time, waybill_code, users }
* @param {string} [params.waybill_code] 扫描打包的运单号(可选,用于运单维度记录流水)
* @returns {Promise<Object>}
*/
@ -791,7 +791,8 @@ class WorkbenchService extends Service {
wave_total_orders: waveTotalOrders,
items_count: itemsCount,
items_total: itemsTotal,
waybill_code: waybillCodeParam } = params;
waybill_code: waybillCodeParam,
users: usersParam } = params;
if (!deliveryOrderCode) throw new Error('发货单号不能为空');
if (!inputWarehouseId) throw new Error('仓库ID不能为空');
@ -1100,10 +1101,10 @@ class WorkbenchService extends Service {
});
// 步骤7:写入打包人员信息
// 打包人一律取该工作台绑定成员(成员登入/登出链路 bindMember/removeMember 已持久化到
// wms_workbench_member,数据源单一,前端不再上报 users 入参)。
let users = [];
if (validWorkbenchId) {
// 上报了 users(business 旧链路)时以上报为准;未上报(token+key 新链路)时
// 自动回填该工作台绑定成员(成员登入/登出链路 bindMember/removeMember 已持久化到 wms_workbench_member)。
let users = Array.isArray(usersParam) && usersParam.length > 0 ? usersParam : [];
if (users.length === 0 && validWorkbenchId) {
try {
const members = await this.listWorkbenchMembers(validWorkbenchId);
users = members.map(m => ({
@ -2040,6 +2041,8 @@ class WorkbenchService extends Service {
* 散单(isSandan=1)时在响应 order 对象中额外返回 intercept_flag / pack_flag 两个 0/1 标志:
* 拦截状态(intercept_status)不等于 none 时 intercept_flag=1,否则 0;
* pack_flag 按运单维度判定(该运单号已有打包流水为 1,主/子单号互不影响)。
* order 对象始终包含 picker_id / picker_name:通过 wave_id 关联拣货任务取拣货人,
* 散单无波次或未分配拣货人时为 null / 空串。
* 查询成功时生成一次性打包上下文 key(20 分钟有效)写入 Redis,
* 响应附 key 供 workbench.packOrder 消费,打包参数由后端维护防篡改。
* @param {Object} params - { barcode, warehouseId, workbenchId }
@ -2212,6 +2215,37 @@ class WorkbenchService extends Service {
}
}
// 步骤6.5:查询拣货人(通过波次关联拣货任务;散单无波次时为 null/空串)
let pickerId = null;
let pickerName = '';
if (waveId && Number(waveId) > 0) {
try {
const pickerRows = await ctx.model.query(
`
SELECT t.pick_user_id, t.pick_user_name
FROM wms_wave_pick_task_wave tw
INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id
WHERE tw.wave_id = :waveId
AND tw.warehouse_id = :warehouseId
AND t.pick_user_id IS NOT NULL
ORDER BY t.create_time DESC
LIMIT 1
`,
{
replacements: { waveId: Number(waveId), warehouseId },
type: ctx.model.QueryTypes.SELECT,
}
);
const pickerRow = Array.isArray(pickerRows) && pickerRows.length > 0 ? pickerRows[0] : null;
if (pickerRow && pickerRow.pick_user_id != null) {
pickerId = Number(pickerRow.pick_user_id);
pickerName = String(pickerRow.pick_user_name || '').trim();
}
} catch (pickerErr) {
ctx.logger.warn('[Workbench._queryOrder] 查询拣货人失败 waveId=%d: %s', waveId, pickerErr.message);
}
}
const result = {
barcode: normalizedBarcode,
waybill_code: waybillCode,
@ -2243,6 +2277,8 @@ class WorkbenchService extends Service {
items_weight: orderRow.items_weight,
source_platform_code: orderRow.source_platform_code,
logistics_name: orderRow.logistics_name,
picker_id: pickerId,
picker_name: pickerName,
create_at: orderRow.create_at,
updated_at: orderRow.updated_at,
},
@ -3633,7 +3669,9 @@ class WorkbenchService extends Service {
*/
async packOrderByToken(data = {}) {
const { ctx } = this;
const { token, key, ...legacyParams } = data || {};
// 新链路(token+key / 旧参数过渡)一律不接收 users:打包人由 _packOrder 自动回填工作台绑定成员。
// 仅 business(packOrder) 旧链路支持上报 users。
const { token, key, users: _ignoredUsers, ...legacyParams } = data || {};
const resolved = await this.resolveWorkbenchContext(token);
if (!resolved.success) return resolved;

View File

@ -0,0 +1,104 @@
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= title %></title>
<style>
body {
margin: 0;
padding: 24px;
background: #f5f7fb;
color: #1f2937;
font-family: "Microsoft YaHei", sans-serif;
}
.card {
max-width: 560px;
margin: 40px auto;
background: #ffffff;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
overflow: hidden;
}
.header {
padding: 20px 24px;
border-bottom: 1px solid #e5e7eb;
}
.header h1 {
margin: 0;
font-size: 20px;
}
.summary {
margin: 16px 24px 0;
padding: 16px;
border-radius: 10px;
font-size: 16px;
font-weight: 600;
}
.summary.success { background: #ecfdf3; color: #027a48; }
.summary.error { background: #fef3f2; color: #b42318; }
.content {
padding: 16px 24px 24px;
}
.row {
display: flex;
padding: 8px 0;
border-bottom: 1px dashed #e5e7eb;
font-size: 14px;
}
.row:last-child { border-bottom: none; }
.label {
width: 120px;
color: #6b7280;
flex-shrink: 0;
}
.value {
word-break: break-all;
color: #111827;
}
.hint {
margin-top: 12px;
font-size: 13px;
color: #9ca3af;
}
</style>
</head>
<body>
<div class="card">
<div class="header">
<h1><%= title %></h1>
</div>
<div class="summary <%= resultLevel %>"><%= resultText %></div>
<div class="content">
<% if (resultLevel === 'success') { %>
<div class="row">
<div class="label">小程序AppID</div>
<div class="value"><%= appid %></div>
</div>
<div class="row">
<div class="label">小程序名称</div>
<div class="value"><%= nickname || '-' %></div>
</div>
<div class="row">
<div class="label">绑定仓库ID</div>
<div class="value"><%= warehouseId === null || warehouseId === undefined ? '-' : warehouseId %></div>
</div>
<div class="hint">授权信息已保存,可返回系统查看小程序列表。</div>
<% } else { %>
<div class="hint">请返回系统重新发起授权。</div>
<% } %>
</div>
</div>
</body>
</html>

View File

@ -48,6 +48,18 @@ module.exports = appInfo => {
appKey: 23535631,
security: 'd0cbd3935e3afa2b42b5dc600c08a795',
};
// 微信开放平台第三方平台(组件)配置:接收授权事件推送与调用授权方接口。
// 值可被 config.local.js / config.prod.js 覆盖。
config.wechatOpen = {
component_appid: 'wx6e91ec813bcb7eec',
component_secret: '8e76ea205dcc1d3e506ce6c102375bdd',
token: 'lujS6QH8jUkabwOwMuAqe9odz7',
encoding_aes_key: 'lujS6QH8jUkabwOwMuAqe9odz7jmKEnT37XMahpSmrU',
api_base: 'https://api.weixin.qq.com',
// 授权完成后的回跳地址(微信开放平台授权链接 redirect_uri,须为系统 /Authorization 路由;
// 域名须在微信开放平台登记为授权回调域名,前端 nginx 已将 /Authorization 代理到本系统)
redirect_uri: 'https://wms.wms.gztbyc.com/Authorization',
};
config.deepseek = {
apiKey: process.env.DEEPSEEK_API_KEY || '',
baseUrl: 'https://api.deepseek.com',

View File

@ -0,0 +1,111 @@
'use strict';
/**
* 修复拦截/揽收子类型缺少「运单号提取」取号规则关联的问题。
*
* 背景:
* - 20260917130000 为 intercept(拦截)/ pickup(揽收)补充了关键词,使其能被 v2 引擎命中;
* - 但未关联取号规则。v2 规则引擎 _extractNumbers 在该子类型无规则时返回 [](非 null),
* 不会进入「取号失败」分支,而是直接执行 interceptWaybill / requestPickup,
* 函数因缺运单号返回硬编码错误「请提供运单号」,绕过了回复表配置的取号失败引导语;
* - 20260918150000 又因这两个子类型无取号规则而清空了其系统级 no_number_hint。
*
* 本次修复(幂等):
* 1. 为系统级 intercept / pickup 子类型关联「运单号提取」取号规则(依赖唯一索引
* uk_sub_type_rule 做 INSERT IGNORE);
* 2. 将系统级回复行空的 no_number_hint 补为默认运单号引导语(只填空值行)。
*
* 修复后链路:消息「拦截」→ 命中关键词 → 关联规则存在但未提取到运单号 → extracted=null
* → 返回取号失败引导语(回复表 no_number_hint → 代码默认值兜底)。
*/
const REL_TABLE = 'wms_after_sale_sub_type_rule';
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
const RULE_TABLE = 'wms_inbox_number_rule';
const REPLY_TABLE = 'wms_after_sale_reply';
const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)';
const RULE_NAME = '运单号提取';
const SUB_TYPES = [ 'intercept', 'pickup' ];
module.exports = {
up: async queryInterface => {
const { sequelize } = queryInterface;
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
if (!exists(REL_TABLE) || !exists(SUB_TYPE_TABLE) || !exists(RULE_TABLE)) return;
const [ ruleRows ] = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1',
{ replacements: { name: RULE_NAME } }
);
if (ruleRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`);
return;
}
const ruleId = ruleRows[0].id;
let inserted = 0;
for (const subType of SUB_TYPES) {
const [ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1',
{ replacements: { type: 'order', subType } }
);
if (subRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${subType}`);
continue;
}
await sequelize.query(
'INSERT IGNORE INTO `' + REL_TABLE + '` '
+ '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) '
+ 'VALUES (:sid, :rid, 1, NOW(), NOW())',
{ replacements: { sid: subRows[0].id, rid: ruleId } }
);
inserted += 1;
}
console.log(`[MIGRATION] 取号规则关联插入 ${inserted} 条`);
// 补充系统级回复行的取号失败引导语(只填空值行)
if (exists(REPLY_TABLE)) {
const [ replyRows ] = await sequelize.query(
'SELECT r.id FROM `' + REPLY_TABLE + '` r '
+ 'JOIN `' + SUB_TYPE_TABLE + '` st ON st.id = r.sub_type_id '
+ 'WHERE r.warehouse_id IS NULL AND st.type = :type AND st.sub_type IN (:subTypes) '
+ 'AND (r.no_number_hint IS NULL OR r.no_number_hint = :empty)',
{ replacements: { type: 'order', subTypes: SUB_TYPES, empty: '' } }
);
for (const row of replyRows) {
await sequelize.query(
'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id',
{ replacements: { hint: HINT_DEFAULT, id: row.id } }
);
}
console.log(`[MIGRATION] 补充取号失败引导语 ${replyRows.length} 行`);
}
},
down: async queryInterface => {
const { sequelize } = queryInterface;
const [ ruleRows ] = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1',
{ replacements: { name: RULE_NAME } }
);
if (ruleRows.length === 0) return;
for (const subType of SUB_TYPES) {
const [ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1',
{ replacements: { type: 'order', subType } }
);
if (subRows.length === 0) continue;
await sequelize.query(
'DELETE FROM `' + REL_TABLE + '` WHERE sub_type_id = :sid AND number_rule_id = :rid',
{ replacements: { sid: subRows[0].id, rid: ruleRows[0].id } }
);
}
// 引导语不回退(数据修正,与既有种子迁移 down 语义一致)
},
};

View File

@ -0,0 +1,147 @@
'use strict';
/**
* 错发(mis_shipment)/ 多发(extra_item)子类型配置补齐:关键词 + 运单号取号规则 + 引导语。
*
* 背景:
* - v1 引擎(inbox/rules.js STORE_RULES)中错发/多发分别有关键词且 waybill:true:
* 错发:错发、发错(fn=handleStoreFeedback, issueType=wrong)
* 多发:多发、发多(fn=handleStoreFeedback, issueType=multiple)
* - v2 关键词表 wms_after_sale_keyword 中这两个子类型无任何关键词,无法命中;
* 且无「运单号提取」取号规则关联 → v2 引擎 _extractNumbers 返回 [],
* 直接执行 handleStoreFeedback,缺单号时返回函数硬编码错误「请提供运单号」,
* 取号失败引导语分支不可达(与拦截/揽收同款问题)。
*
* 本次修复(幂等):
* 1. 将 v1 既有关键词作为系统级默认关键词写入(先查后插,NULL 仓库不参与唯一约束);
* 2. 为系统级错发/多发子类型关联「运单号提取」取号规则(INSERT IGNORE 依赖唯一索引 uk_sub_type_rule);
* 3. 将系统级回复行空的 no_number_hint 补为默认运单号引导语(只填空值行,仓库级行不动)。
*/
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
const KEYWORD_TABLE = 'wms_after_sale_keyword';
const REL_TABLE = 'wms_after_sale_sub_type_rule';
const RULE_TABLE = 'wms_inbox_number_rule';
const REPLY_TABLE = 'wms_after_sale_reply';
const RULE_NAME = '运单号提取';
const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)';
/** 子类型编码 → 默认关键词(与 v1 STORE_RULES 一致) */
const SUB_TYPE_KEYWORDS = [
{ sub_type: 'mis_shipment', keywords: [ '错发', '发错' ] },
{ sub_type: 'extra_item', keywords: [ '多发', '发多' ] },
];
module.exports = {
up: async queryInterface => {
const { sequelize } = queryInterface;
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
if (!exists(SUB_TYPE_TABLE) || !exists(KEYWORD_TABLE)) return;
// ─── 1. 默认关键词(先查后插,NULL 仓库不参与唯一约束) ─────────
let inserted = 0;
for (const rule of SUB_TYPE_KEYWORDS) {
const [ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1',
{ replacements: { type: 'order', subType: rule.sub_type } }
);
if (subRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${rule.sub_type}`);
continue;
}
const subTypeId = subRows[0].id;
let sortOrder = 0;
for (const kw of rule.keywords) {
const [ kwRows ] = await sequelize.query(
'SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :kw AND warehouse_id IS NULL LIMIT 1',
{ replacements: { kw } }
);
if (kwRows.length === 0) {
await sequelize.query(
'INSERT INTO `' + KEYWORD_TABLE + '` '
+ '(warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) '
+ 'VALUES (NULL, :sid, :kw, 1, 1, :so, NOW(), NOW())',
{ replacements: { sid: subTypeId, kw, so: sortOrder } }
);
inserted += 1;
}
sortOrder += 1;
}
}
console.log(`[MIGRATION] 默认关键词插入 ${inserted} 条`);
// ─── 2. 运单号取号规则关联(INSERT IGNORE,依赖 uk_sub_type_rule) ──
if (exists(REL_TABLE) && exists(RULE_TABLE)) {
const [ ruleRows ] = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1',
{ replacements: { name: RULE_NAME } }
);
if (ruleRows.length > 0) {
const ruleId = ruleRows[0].id;
let relInserted = 0;
for (const rule of SUB_TYPE_KEYWORDS) {
const [ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1',
{ replacements: { type: 'order', subType: rule.sub_type } }
);
if (subRows.length === 0) continue;
await sequelize.query(
'INSERT IGNORE INTO `' + REL_TABLE + '` '
+ '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) '
+ 'VALUES (:sid, :rid, 1, NOW(), NOW())',
{ replacements: { sid: subRows[0].id, rid: ruleId } }
);
relInserted += 1;
}
console.log(`[MIGRATION] 取号规则关联插入 ${relInserted} 条`);
} else {
console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`);
}
}
// ─── 3. 系统级空引导语回填(只填空值行) ─────────────────────
if (exists(REPLY_TABLE)) {
const [ replyRows ] = await sequelize.query(
'SELECT r.id FROM `' + REPLY_TABLE + '` r '
+ 'JOIN `' + SUB_TYPE_TABLE + '` st ON st.id = r.sub_type_id '
+ 'WHERE r.warehouse_id IS NULL AND st.type = :type AND st.sub_type IN (:subTypes) '
+ 'AND (r.no_number_hint IS NULL OR r.no_number_hint = :empty)',
{ replacements: { type: 'order', subTypes: SUB_TYPE_KEYWORDS.map(x => x.sub_type), empty: '' } }
);
for (const row of replyRows) {
await sequelize.query(
'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id',
{ replacements: { hint: HINT_DEFAULT, id: row.id } }
);
}
console.log(`[MIGRATION] 补充取号失败引导语 ${replyRows.length} 行`);
}
},
down: async queryInterface => {
const { sequelize } = queryInterface;
// 回滚取号规则关联;关键词与引导语不回退(种子类数据,与既有迁移 down 语义一致)
const [ ruleRows ] = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1',
{ replacements: { name: RULE_NAME } }
);
if (ruleRows.length === 0) return;
for (const rule of SUB_TYPE_KEYWORDS) {
const [ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1 LIMIT 1',
{ replacements: { type: 'order', subType: rule.sub_type } }
);
if (subRows.length === 0) continue;
await sequelize.query(
'DELETE FROM `' + REL_TABLE + '` WHERE sub_type_id = :sid AND number_rule_id = :rid',
{ replacements: { sid: subRows[0].id, rid: ruleRows[0].id } }
);
}
},
};

View File

@ -0,0 +1,203 @@
'use strict';
/**
* 订单类型新增系统级子类型「取消拦截」(cancel_intercept),并补齐 v2 配置链。
*
* 背景:
* - v1 引擎(inbox/rules.js STORE_RULES)与代码函数表均有 cancelIntercept
* (关键词:取消拦截/撤销拦截/解除拦截/不拦截/不用拦截,waybill:true);
* - v2 的售后子类型表 wms_after_sale_sub_type 中没有该子类型,导致 v2 引擎
* 无法把「取消拦截」类消息路由到 cancelIntercept 函数(帮助清单缺项)。
*
* 本次修复(幂等,先查后插;INSERT IGNORE 依赖既有唯一索引):
* 1. 插入系统级子类型 cancel_intercept(sort_order=10,紧跟拦截之后),
* 并将原 sort_order>=10 的系统级 order 子类型顺延 +1;
* 2. 关键词 5 条:取消拦截/撤销拦截/解除拦截/不拦截/不用拦截;
* 3. 群类型白名单:store:after_sales + warehouse:customer_service(与函数 groups 一致);
* 4. 子类型-函数关系:cancelIntercept;
* 5. 取号规则关联:运单号提取(waybill);
* 6. 系统级回复行:reply={back_text}、is_reply=1、create_work_order=1、
* no_number_hint=默认运单号引导语、is_enabled=1。
*/
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
const KEYWORD_TABLE = 'wms_after_sale_keyword';
const GROUP_REL_TABLE = 'wms_after_sale_sub_type_group';
const FUNCTION_TABLE = 'wms_after_sale_function';
const FUNC_REL_TABLE = 'wms_after_sale_sub_type_function';
const RULE_TABLE = 'wms_inbox_number_rule';
const RULE_REL_TABLE = 'wms_after_sale_sub_type_rule';
const REPLY_TABLE = 'wms_after_sale_reply';
const SUB_TYPE_CODE = 'cancel_intercept';
const SUB_TYPE_NAME = '取消拦截';
const SUB_TYPE_SORT = 10; // 紧跟拦截(9)之后
const KEYWORDS = [ '取消拦截', '撤销拦截', '解除拦截', '不拦截', '不用拦截' ];
const GROUP_WHITELIST = [
{ group_type: 'store', sub_group: 'after_sales' },
{ group_type: 'warehouse', sub_group: 'customer_service' },
];
const FUNCTION_CODE = 'cancelIntercept';
const RULE_NAME = '运单号提取';
const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)';
module.exports = {
up: async queryInterface => {
const { sequelize } = queryInterface;
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
if (!exists(SUB_TYPE_TABLE)) return;
// ─── 1. 子类型(先查;不存在则顺延 sort_order 并插入) ─────────
let [ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1',
{ replacements: { type: 'order', subType: SUB_TYPE_CODE } }
);
if (subRows.length === 0) {
await sequelize.query(
'UPDATE `' + SUB_TYPE_TABLE + '` SET sort_order = sort_order + 1 '
+ 'WHERE type = :type AND warehouse_id IS NULL AND sort_order >= :sort',
{ replacements: { type: 'order', sort: SUB_TYPE_SORT } }
);
await sequelize.query(
'INSERT INTO `' + SUB_TYPE_TABLE + '` '
+ '(warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at) '
+ 'VALUES (NULL, :type, :subType, :name, 1, 1, :sort, NOW(), NOW())',
{ replacements: { type: 'order', subType: SUB_TYPE_CODE, name: SUB_TYPE_NAME, sort: SUB_TYPE_SORT } }
);
[ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1',
{ replacements: { type: 'order', subType: SUB_TYPE_CODE } }
);
console.log(`[MIGRATION] 子类型插入 order.${SUB_TYPE_CODE},原 sort_order>=${SUB_TYPE_SORT} 已顺延`);
}
if (subRows.length === 0) {
console.warn(`[MIGRATION] 跳过:子类型 order.${SUB_TYPE_CODE} 缺失且插入失败`);
return;
}
const subTypeId = subRows[0].id;
// ─── 2. 关键词(先查后插,NULL 仓库不参与唯一约束) ─────────
if (exists(KEYWORD_TABLE)) {
let kwInserted = 0;
for (const [ idx, kw ] of KEYWORDS.entries()) {
const [ kwRows ] = await sequelize.query(
'SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :kw AND warehouse_id IS NULL LIMIT 1',
{ replacements: { kw } }
);
if (kwRows.length === 0) {
await sequelize.query(
'INSERT INTO `' + KEYWORD_TABLE + '` '
+ '(warehouse_id, sub_type_id, keyword, is_system, is_enabled, sort_order, created_at, updated_at) '
+ 'VALUES (NULL, :sid, :kw, 1, 1, :so, NOW(), NOW())',
{ replacements: { sid: subTypeId, kw, so: idx } }
);
kwInserted += 1;
}
}
console.log(`[MIGRATION] 关键词插入 ${kwInserted} 条`);
}
// ─── 3. 群类型白名单(INSERT IGNORE,依赖 uk_sub_type_group) ──
if (exists(GROUP_REL_TABLE)) {
let grpInserted = 0;
for (const [ idx, g ] of GROUP_WHITELIST.entries()) {
await sequelize.query(
'INSERT IGNORE INTO `' + GROUP_REL_TABLE + '` '
+ '(sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) '
+ 'VALUES (:sid, :groupType, :subGroup, 1, :so, NOW(), NOW())',
{ replacements: { sid: subTypeId, groupType: g.group_type, subGroup: g.sub_group, so: idx + 1 } }
);
grpInserted += 1;
}
console.log(`[MIGRATION] 群白名单插入 ${grpInserted} 条`);
}
// ─── 4. 子类型-函数关系(INSERT IGNORE,依赖 uk_sub_type_function) ──
if (exists(FUNC_REL_TABLE) && exists(FUNCTION_TABLE)) {
const [ fnRows ] = await sequelize.query(
'SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :code LIMIT 1',
{ replacements: { code: FUNCTION_CODE } }
);
if (fnRows.length > 0) {
await sequelize.query(
'INSERT IGNORE INTO `' + FUNC_REL_TABLE + '` '
+ '(sub_type_id, function_id, sort_order, created_at, updated_at) '
+ 'VALUES (:sid, :fid, 1, NOW(), NOW())',
{ replacements: { sid: subTypeId, fid: fnRows[0].id } }
);
console.log(`[MIGRATION] 函数关系插入 ${FUNCTION_CODE}`);
} else {
console.warn(`[MIGRATION] 跳过:未找到处理函数 ${FUNCTION_CODE}`);
}
}
// ─── 5. 运单号取号规则关联(INSERT IGNORE,依赖 uk_sub_type_rule) ──
if (exists(RULE_REL_TABLE) && exists(RULE_TABLE)) {
const [ ruleRows ] = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1',
{ replacements: { name: RULE_NAME } }
);
if (ruleRows.length > 0) {
await sequelize.query(
'INSERT IGNORE INTO `' + RULE_REL_TABLE + '` '
+ '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) '
+ 'VALUES (:sid, :rid, 1, NOW(), NOW())',
{ replacements: { sid: subTypeId, rid: ruleRows[0].id } }
);
console.log(`[MIGRATION] 取号规则关联插入 ${RULE_NAME}`);
} else {
console.warn(`[MIGRATION] 跳过:未找到取号规则 ${RULE_NAME}`);
}
}
// ─── 6. 系统级回复行(先查后插) ─────────────────────────────
if (exists(REPLY_TABLE)) {
const [ replyRows ] = await sequelize.query(
'SELECT id FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL LIMIT 1',
{ replacements: { sid: subTypeId } }
);
if (replyRows.length === 0) {
await sequelize.query(
'INSERT INTO `' + REPLY_TABLE + '` '
+ '(warehouse_id, sub_type_id, reply, is_reply, create_work_order, no_number_hint, is_enabled, created_at, updated_at) '
+ 'VALUES (NULL, :sid, :reply, 1, 1, :hint, 1, NOW(), NOW())',
{ replacements: { sid: subTypeId, reply: '{back_text}', hint: HINT_DEFAULT } }
);
console.log('[MIGRATION] 系统级回复行插入 1 行');
}
}
},
down: async queryInterface => {
const { sequelize } = queryInterface;
const [ subRows ] = await sequelize.query(
'SELECT id FROM `' + SUB_TYPE_TABLE + '` '
+ 'WHERE type = :type AND sub_type = :subType AND warehouse_id IS NULL LIMIT 1',
{ replacements: { type: 'order', subType: SUB_TYPE_CODE } }
);
if (subRows.length === 0) return;
const subTypeId = subRows[0].id;
// 回滚关联与配置(关键词/回复行/白名单/函数/取号规则)
await sequelize.query('DELETE FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } });
await sequelize.query('DELETE FROM `' + KEYWORD_TABLE + '` WHERE sub_type_id = :sid AND warehouse_id IS NULL', { replacements: { sid: subTypeId } });
await sequelize.query('DELETE FROM `' + GROUP_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } });
await sequelize.query('DELETE FROM `' + FUNC_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } });
await sequelize.query('DELETE FROM `' + RULE_REL_TABLE + '` WHERE sub_type_id = :sid', { replacements: { sid: subTypeId } });
// 删除子类型并恢复 sort_order 顺延
await sequelize.query(
'DELETE FROM `' + SUB_TYPE_TABLE + '` WHERE id = :sid',
{ replacements: { sid: subTypeId } }
);
await sequelize.query(
'UPDATE `' + SUB_TYPE_TABLE + '` SET sort_order = sort_order - 1 '
+ 'WHERE type = :type AND warehouse_id IS NULL AND sort_order > :sort',
{ replacements: { type: 'order', sort: SUB_TYPE_SORT } }
);
},
};

View File

@ -0,0 +1,139 @@
'use strict';
/**
* 创建用户第三方授权表 wms_user_oauth。
*
* 用途:保存用户通过第三方厂商(如微信、小程序)OAuth 登录后的授权信息,
* 包括用户画像(昵称/头像/地区)、平台凭证(openid/unionid)与令牌信息
* (session_key/access_token/refresh_token 及过期时间)。
*
* 索引:
* - uk_provider_openid:厂商 + 平台ID 唯一,同一用户在同一厂商/平台下仅一条绑定。
* - idx_user_id:按用户查询其全部授权绑定。
*/
const TABLE_NAME = 'wms_user_oauth';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, INTEGER, TINYINT, DATE } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
user_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '用户ID(关联 account.id)',
},
provider: {
type: STRING(50),
allowNull: false,
comment: '厂商,如 wechat/mini_program',
},
platform: {
type: STRING(50),
allowNull: true,
comment: '平台,如 h5/app/mp',
},
unionid: {
type: STRING(50),
allowNull: true,
comment: '厂商统一ID(同一厂商跨应用唯一,部分平台无)',
},
openid: {
type: STRING(50),
allowNull: false,
comment: '平台内唯一ID',
},
nickname: {
type: STRING(255),
allowNull: true,
comment: '昵称',
},
sex: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '性别:0=未知,1=男,2=女',
},
country: {
type: STRING(50),
allowNull: true,
comment: '国家',
},
province: {
type: STRING(50),
allowNull: true,
comment: '省',
},
city: {
type: STRING(50),
allowNull: true,
comment: '市',
},
headimgurl: {
type: STRING(500),
allowNull: true,
comment: '头像URL',
},
login_time: {
type: INTEGER(11),
allowNull: true,
comment: '最近登录时间(unix秒级时间戳)',
},
login_count: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '累计登录次数',
},
expire_in: {
type: INTEGER(11),
allowNull: true,
comment: '令牌过期周期(秒)',
},
expire_time: {
type: INTEGER(11),
allowNull: true,
comment: '令牌过期时间(unix秒级时间戳)',
},
session_key: {
type: STRING(45),
allowNull: true,
comment: '会话密钥(微信小程序登录态)',
},
refresh_token: {
type: STRING(110),
allowNull: true,
comment: '刷新令牌',
},
access_token: {
type: STRING(110),
allowNull: true,
comment: '访问令牌',
},
created_at: { type: DATE, allowNull: false, comment: '创建时间' },
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
});
await queryInterface.addIndex(TABLE_NAME, [ 'provider', 'openid' ], {
unique: true,
name: 'uk_provider_openid',
});
await queryInterface.addIndex(TABLE_NAME, [ 'user_id' ], {
name: 'idx_user_id',
});
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,108 @@
'use strict';
/**
* 创建微信开放平台授权小程序表 wms_wechat_app。
*
* 用途:仓库(主体)在微信开放平台将自己主体下的小程序授权给本系统提供服务,
* 记录小程序授权信息(appid/名称/授权令牌)与仓库的绑定关系(warehouse_id)。
* 小程序归属仓库主体,1 个仓库可授权多个小程序。
*
* 令牌说明:
* - authorizer_refresh_token:授权方刷新令牌,长期有效,用于刷新接口调用凭证。
* - authorizer_access_token:授权方接口调用凭证,约 2 小时有效,过期后用
* refresh_token 刷新并回写本表。
*
* 索引:
* - uk_appid:appid 唯一(同一小程序只允许授权一次)。
* - idx_warehouse_id:按仓库查询其已授权小程序列表。
*/
const TABLE_NAME = 'wms_wechat_app';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, INTEGER, TINYINT, DATE } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(小程序归属主体,绑定关系)',
},
appid: {
type: STRING(64),
allowNull: false,
comment: '小程序AppID',
},
nickname: {
type: STRING(100),
allowNull: true,
comment: '小程序名称',
},
user_name: {
type: STRING(100),
allowNull: true,
comment: '小程序原始ID(gh_xxx)',
},
head_img: {
type: STRING(500),
allowNull: true,
comment: '小程序头像URL',
},
app_secret: {
type: STRING(64),
allowNull: true,
comment: '小程序密钥(按需配置)',
},
authorizer_refresh_token: {
type: STRING(255),
allowNull: true,
comment: '授权方刷新令牌(长期有效)',
},
authorizer_access_token: {
type: STRING(512),
allowNull: true,
comment: '授权方接口调用凭证(约2小时有效)',
},
access_token_expire_time: {
type: INTEGER(11),
allowNull: true,
comment: '接口调用凭证过期时间(unix秒级时间戳)',
},
auth_time: {
type: INTEGER(11),
allowNull: true,
comment: '授权时间(unix秒级时间戳)',
},
is_enabled: {
type: TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:1=启用,0=停用',
},
created_at: { type: DATE, allowNull: false, comment: '创建时间' },
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
});
await queryInterface.addIndex(TABLE_NAME, [ 'appid' ], {
unique: true,
name: 'uk_appid',
});
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id' ], {
name: 'idx_warehouse_id',
});
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,44 @@
'use strict';
/**
* wms_user_oauth 增加应用映射字段 app_id。
*
* 背景:微信 openid 是「小程序 appid」维度唯一,同一用户在不同小程序下
* openid 不同。为使用户授权记录能定位到对应小程序应用(wms_wechat_app),
* 以便取该应用自己的 access_token 处理,新增 app_id 关联字段。
*
* 索引调整:
* - 删除 uk_provider_openid(provider + openid),
* 改为 uk_app_provider_openid(app_id + provider + openid)。
* - 注意:MySQL 唯一索引对 NULL 不生效,app_id 为 NULL 的记录(非小程序
* 厂商场景)不参与唯一约束,写入时需业务侧先查后插保证幂等。
*/
const TABLE_NAME = 'wms_user_oauth';
module.exports = {
async up(queryInterface, Sequelize) {
const { BIGINT } = Sequelize;
await queryInterface.addColumn(TABLE_NAME, 'app_id', {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '微信应用ID(关联 wms_wechat_app.id),用于取对应应用 token 处理',
});
await queryInterface.removeIndex(TABLE_NAME, 'uk_provider_openid');
await queryInterface.addIndex(TABLE_NAME, [ 'app_id', 'provider', 'openid' ], {
unique: true,
name: 'uk_app_provider_openid',
});
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.removeIndex(TABLE_NAME, 'uk_app_provider_openid');
await queryInterface.addIndex(TABLE_NAME, [ 'provider', 'openid' ], {
unique: true,
name: 'uk_provider_openid',
});
await queryInterface.removeColumn(TABLE_NAME, 'app_id');
},
};

View File

@ -0,0 +1,43 @@
'use strict';
/**
* wms_wechat_app 表结构微调,适配微信开放平台授权事件推送。
*
* 1. warehouse_id 改为可空:
* 授权事件(authorized/updateauthorized)由微信开放平台推送,推送时
* 仓库绑定关系尚未确定(参考流程为授权后由回跳页面再绑定仓库),
* 因此授权阶段允许 warehouse_id 为 NULL(NULL=待绑定)。
* 2. 新增 func_info(TEXT):
* 保存授权方授权给第三方平台的权限集合(api_query_auth 返回的
* authorization_info.func_info JSON 字符串)。
*/
const TABLE_NAME = 'wms_wechat_app';
module.exports = {
async up(queryInterface, Sequelize) {
const { TEXT } = Sequelize;
await queryInterface.changeColumn(TABLE_NAME, 'warehouse_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '仓库ID(绑定关系,NULL=已授权待绑定仓库)',
});
await queryInterface.addColumn(TABLE_NAME, 'func_info', {
type: TEXT,
allowNull: true,
comment: '授权权限集合(JSON 字符串,来自 api_query_auth)',
});
},
async down(queryInterface, Sequelize) {
await queryInterface.removeColumn(TABLE_NAME, 'func_info');
await queryInterface.changeColumn(TABLE_NAME, 'warehouse_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(小程序归属主体,绑定关系)',
});
},
};

View File

@ -0,0 +1,44 @@
'use strict';
/**
* 精简 wms_wechat_app 表字段。
*
* 背景:令牌类字段改为由 Redis 管理(与参考实现一致),DB 只保留
* 授权状态、绑定关系与长期凭证:
* - authorizer_access_token:约 2 小时过期、高频变化,Redis 缓存 + TTL 管理,
* 落库无意义,移除。
* - access_token_expire_time:配合 access_token 的过期时间,随 access_token
* 一起由 Redis TTL 管理,移除。
* - app_secret:第三方平台模式下调用授权方接口使用 component_access_token /
* authorizer_access_token,无需小程序密钥,移除。
* - authorizer_refresh_token 保留落库:长期凭证,防 Redis 清空后需重新授权。
*/
const TABLE_NAME = 'wms_wechat_app';
module.exports = {
async up(queryInterface) {
await queryInterface.removeColumn(TABLE_NAME, 'authorizer_access_token');
await queryInterface.removeColumn(TABLE_NAME, 'access_token_expire_time');
await queryInterface.removeColumn(TABLE_NAME, 'app_secret');
},
async down(queryInterface, Sequelize) {
const { STRING, INTEGER } = Sequelize;
await queryInterface.addColumn(TABLE_NAME, 'app_secret', {
type: STRING(64),
allowNull: true,
comment: '小程序密钥(按需配置)',
});
await queryInterface.addColumn(TABLE_NAME, 'access_token_expire_time', {
type: INTEGER(11),
allowNull: true,
comment: '接口调用凭证过期时间(unix秒级时间戳)',
});
await queryInterface.addColumn(TABLE_NAME, 'authorizer_access_token', {
type: STRING(512),
allowNull: true,
comment: '授权方接口调用凭证(约2小时有效)',
});
},
};

View File

@ -0,0 +1,32 @@
'use strict';
/**
* wms_user_oauth 增加 login_code 字段。
*
* 用途:扫码登录码(小程序授权/扫码登录场景),生成方式与
* wms_workbench.login_code 保持一致(前缀 + 随机,64 位,全局唯一,
* 登录码为一次性凭证,消费后作废)。
*/
const TABLE_NAME = 'wms_user_oauth';
module.exports = {
async up(queryInterface, Sequelize) {
const { STRING } = Sequelize;
await queryInterface.addColumn(TABLE_NAME, 'login_code', {
type: STRING(64),
allowNull: true,
comment: '登录码(前缀+随机,64位,全局唯一)',
});
await queryInterface.addIndex(TABLE_NAME, [ 'login_code' ], {
unique: true,
name: 'uk_login_code',
});
},
async down(queryInterface) {
await queryInterface.removeIndex(TABLE_NAME, 'uk_login_code');
await queryInterface.removeColumn(TABLE_NAME, 'login_code');
},
};

View File

@ -0,0 +1,30 @@
'use strict';
/**
* 扩展 wms_user_oauth.login_code 长度:64 → 128。
*
* 原因:login_code 为 {uuid, id_6} JSON 的 base64,长度约 96 字符,
* 原 VARCHAR(64) 写入时报 Data too long。
*/
const TABLE_NAME = 'wms_user_oauth';
module.exports = {
async up(queryInterface, Sequelize) {
const { STRING } = Sequelize;
await queryInterface.changeColumn(TABLE_NAME, 'login_code', {
type: STRING(128),
allowNull: true,
comment: '登录码({uuid,id_6} JSON 的 base64,一次性消费)',
});
},
async down(queryInterface, Sequelize) {
const { STRING } = Sequelize;
await queryInterface.changeColumn(TABLE_NAME, 'login_code', {
type: STRING(64),
allowNull: true,
comment: '登录码(前缀+随机,64位,全局唯一)',
});
},
};

View File

@ -0,0 +1,24 @@
'use strict';
/**
* wms_wechat_app 增加「当前上传的代码模板ID」字段 template_id。
*
* 用于记录第三方平台代开发小程序最近一次 wxa/commit 上传代码使用的模板 ID。
*/
const TABLE_NAME = 'wms_wechat_app';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn(TABLE_NAME, 'template_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '当前上传的代码模板ID(wxa/commit 成功后记录)',
});
},
async down(queryInterface) {
await queryInterface.removeColumn(TABLE_NAME, 'template_id');
},
};

View File

@ -0,0 +1,47 @@
'use strict';
/**
* wms_wechat_app 增加代码审核相关字段:
* - user_version:当前上传的代码版本号(wxa/commit 成功后记录)
* - audit_status:代码审核状态 0=未提交 1=审核中 2=审核通过 3=审核驳回
* - audit_id:微信审核单 ID(auditid)
* - audit_reason:审核驳回原因
*/
const TABLE_NAME = 'wms_wechat_app';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn(TABLE_NAME, 'user_version', {
type: Sequelize.STRING(64),
allowNull: true,
defaultValue: null,
comment: '当前上传的代码版本号(wxa/commit 成功后记录)',
});
await queryInterface.addColumn(TABLE_NAME, 'audit_status', {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '代码审核状态:0=未提交,1=审核中,2=审核通过,3=审核驳回',
});
await queryInterface.addColumn(TABLE_NAME, 'audit_id', {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '微信审核单ID(wxa/submit_audit 返回的 auditid)',
});
await queryInterface.addColumn(TABLE_NAME, 'audit_reason', {
type: Sequelize.STRING(500),
allowNull: true,
defaultValue: null,
comment: '代码审核驳回原因',
});
},
async down(queryInterface) {
await queryInterface.removeColumn(TABLE_NAME, 'user_version');
await queryInterface.removeColumn(TABLE_NAME, 'audit_status');
await queryInterface.removeColumn(TABLE_NAME, 'audit_id');
await queryInterface.removeColumn(TABLE_NAME, 'audit_reason');
},
};

View File

@ -0,0 +1,64 @@
'use strict';
/**
* wms_wechat_app 补充授权账号基础信息与认证相关字段:
* - 基础信息(api_get_authorizer_info):principal_name/signature/alias/qrcode_url/
* service_type_id/verify_type_id/account_status/register_type/business_info/mini_program_info
* - 认证任务与状态(wxa/sec/queryauth):auth_task_id/auth_task_status/auth_apply_status
*/
const TABLE_NAME = 'wms_wechat_app';
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.addColumn(TABLE_NAME, 'principal_name', {
type: Sequelize.STRING(100), allowNull: true, defaultValue: null, comment: '主体名称',
});
await queryInterface.addColumn(TABLE_NAME, 'signature', {
type: Sequelize.STRING(500), allowNull: true, defaultValue: null, comment: '小程序账号介绍',
});
await queryInterface.addColumn(TABLE_NAME, 'alias', {
type: Sequelize.STRING(100), allowNull: true, defaultValue: null, comment: '微信号(可能为空)',
});
await queryInterface.addColumn(TABLE_NAME, 'qrcode_url', {
type: Sequelize.STRING(500), allowNull: true, defaultValue: null, comment: '二维码图片URL',
});
await queryInterface.addColumn(TABLE_NAME, 'service_type_id', {
type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '账号类型id(0 普通小程序等)',
});
await queryInterface.addColumn(TABLE_NAME, 'verify_type_id', {
type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '认证类型id(-1 未认证,0 微信认证,1 新浪微博认证,3 资质通过未名称认证,4 同3+微博)',
});
await queryInterface.addColumn(TABLE_NAME, 'account_status', {
type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '账号状态(1 正常,14 已注销,16 已封禁,18 已告警,19 已冻结)',
});
await queryInterface.addColumn(TABLE_NAME, 'register_type', {
type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '小程序注册方式(0 普通,6 法人扫脸创建企业小程序等)',
});
await queryInterface.addColumn(TABLE_NAME, 'business_info', {
type: Sequelize.STRING(500), allowNull: true, defaultValue: null, comment: '功能开通状况 JSON(open_pay/open_shake/open_scan/open_card/open_store)',
});
await queryInterface.addColumn(TABLE_NAME, 'mini_program_info', {
type: Sequelize.TEXT, allowNull: true, defaultValue: null, comment: '小程序配置信息 JSON(network/categories/visit_status)',
});
await queryInterface.addColumn(TABLE_NAME, 'auth_task_id', {
type: Sequelize.STRING(64), allowNull: true, defaultValue: null, comment: '微信认证任务ID(发起认证接口 wxa/sec/wxaapi/wxaauth 返回)',
});
await queryInterface.addColumn(TABLE_NAME, 'auth_task_status', {
type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '认证任务流程状态(wxa/sec/queryauth task_status 0-15)',
});
await queryInterface.addColumn(TABLE_NAME, 'auth_apply_status', {
type: Sequelize.TINYINT, allowNull: true, defaultValue: null, comment: '认证审核单状态(wxa/sec/queryauth apply_status 0-5)',
});
},
async down(queryInterface) {
for (const col of [
'principal_name', 'signature', 'alias', 'qrcode_url', 'service_type_id',
'verify_type_id', 'account_status', 'register_type', 'business_info',
'mini_program_info', 'auth_task_id', 'auth_task_status', 'auth_apply_status',
]) {
await queryInterface.removeColumn(TABLE_NAME, col);
}
},
};

17
frpc.toml Normal file
View File

@ -0,0 +1,17 @@
# frpc 客户端配置(frp v0.70.1,复用本机 printServer 的 frpc.exe;生产 frps 为 v0.61.1)
# 用途:将本地 WMS 开发服务(http://127.0.0.1:6060)通过生产环境 frps
# 暴露为 http://test.wms.o.gztbyc.com(frps subDomainHost=o.gztbyc.com)。
# 启动:npm run frpc:start(首次自动从 D:\printServer 复制 frpc.exe 到 script/frp/)
serverAddr = "112.124.21.102"
serverPort = 6005
auth.token = "frpPrintToken2024"
# 测试域名:test_wms.o.gztbyc.com
# (subdomain + 生产 frps 的 subDomainHost 泛域名拼接,经 vhostHTTPPort 18080 对外)
[[proxies]]
name = "wms-test"
type = "http"
localIP = "127.0.0.1"
localPort = 6060
subdomain = "test_wms"

View File

@ -1,4 +1,392 @@
[
{
"version": "2026.09.22-wechat.wxaauth-cos-url",
"date": "2026-09-22",
"type": "updated",
"summary": "wechat.wxaauth 改为后端分步:图片字段传 COS 文件 URL,后端下载 → uploadmedia 换 media_id → wxaauth 提交",
"methods": [
"wechat.wxaauth"
],
"notes": [
"后端分步:① 图片字段值为 http/https(COS URL)时,后端 GET 下载 Buffer → POST /wxa/sec/wxaapi/uploadmedia(multipart/form-data,media_type=image,media=临时文件)换 media_id;② 替换请求体后调 /wxa/sec/wxaapi/wxaauth 提交。非 URL 值视为已传 media_id 原样透传。",
"支持自动换 media_id 的图片字段:顶层 contact_cert_photo/business_license_copy/legal_persona_idcard_copy/legal_persona_media;pic_list 项的 pic_url;qualification_list 项 licence_list/certificate_list 的 value;statement_list 项的 value。",
"uploadmedia 实现细节:Buffer 写临时文件(文件名带 jpg/jpeg/png 扩展名,从 URL path 提取,默认 image.jpg)后按路径传 files:{media}(urllib 2.44 files 支持 Buffer 但文件名固定 bufferfileN 无扩展名,故落临时文件保证扩展名),finally 删除临时文件;40001/40014 清 authorizer token 重试一次。media_id 3 天内有效。",
"代码变更:app/lib/wechat_open_client.js 新增 uploadAuthMedia;app/service/systems/wechat.js 新增 resolveBodyMedia/resolveMediaValue/downloadFromUrl/resolveMediaFilename 并在 wxaauth 中调用。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.wxaauth",
"date": "2026-09-22",
"type": "added",
"summary": "新增 wechat.wxaauth 发起小程序认证(一步提交):前端上传材料换 media_id 后传入,后端调 wxa/sec/wxaapi/wxaauth,成功回写 auth_task_id/auth_apply_status",
"methods": [
"wechat.wxaauth"
],
"notes": [
"新增接口 wechat.wxaauth(需登录免权限,权限集 18):前端负责上传材料换取 media_id 后一步提交;入参白名单透传(contact_type/contact_name 必填,其余 contact_*/business_license_*/legal_persona_*/pic_list 等 33 字段白名单)。",
"成功回写 wms_wechat_app.auth_task_id=taskid、auth_apply_status(auth_task_status 置空),返回 taskid/auth_url/apply_status;taskid 供 wechat.queryauth 查询进度(taskid 可选,库中 auth_task_id 兜底)。",
"已认证(verify_type_id>=0)拒绝重复发起;未授权权限集 18 拒绝。lib#wxaauth 40001/40014 清 authorizer token 重试一次。不拆表:认证状态继续复用 wms_wechat_app 现有字段,无迁移。",
"代码变更:app/lib/wechat_open_client.js 新增 wxaauth;app/service/systems/wechat.js 新增 wxaauth;systemMethods/wechat.js 白名单与出口同步。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.queryauth-verified-first",
"date": "2026-09-22",
"type": "updated",
"summary": "wechat.queryauth 改为先判已认证再查进度:已认证直接返回认证信息;未认证且有 taskid 才调微信查进度;taskid 可选(库中 auth_task_id 兜底);认证通过回写 verify_type_id=0",
"methods": [
"wechat.queryauth"
],
"notes": [
"判定顺序:① 本地 wms_wechat_app.verify_type_id>=0(已认证)→ 直接返回本地认证信息(is_verified=true/verify_type_id/principal_name/signature/service_type_id/account_status),不调微信;② 未认证(null/-1)→ taskid(入参优先,其次库中 auth_task_id)调 wxa/sec/queryauth 查进度;③ 未认证且无 taskid → 返回 code 200「尚未认证且无认证任务」(is_verified=false)。",
"落库:查询成功回写 auth_task_id/auth_task_status/auth_apply_status;apply_status=4(认证通过)时同时回写 verify_type_id=0(微信认证),后续 queryauth 直接走已认证分支。",
"文档:system.json wechat.queryauth 条目 params(taskid 改可选)/response(新增 is_verified/verify_type_id/principal_name 等)同步。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.getAuthorizerInfo-db-fields",
"date": "2026-09-22",
"type": "added",
"summary": "新增 wechat.getAuthorizerInfo 基础信息接口;wms_wechat_app 补充授权账号基础信息与认证状态字段(13列);认证 taskid/状态随 queryauth 成功落库",
"methods": [
"wechat.getAuthorizerInfo",
"wechat.queryauth"
],
"notes": [
"新增接口 wechat.getAuthorizerInfo(需登录免权限):调微信 POST /cgi-bin/component/api_get_authorizer_info(component_access_token)拉取 authorizer_info + authorization_info,将基础信息/认证类型/权限集落库 wms_wechat_app 后返回完整数据。",
"迁移 20260922180000-add-authorizer-info-fields-to-wms-wechat-app:wms_wechat_app 新增 principal_name/signature/alias/qrcode_url/service_type_id/verify_type_id/account_status/register_type/business_info/mini_program_info/auth_task_id/auth_task_status/auth_apply_status,开发+生产均已执行。",
"verify_type_info.id 语义:-1 未认证、0 微信认证、1 新浪微博认证、3 资质通过未名称认证、4 同3+微博;account_status:1 正常、14 已注销、16 已封禁、18 已告警、19 已冻结。",
"认证任务落库口径:taskid 由发起认证接口(wxa/sec/wxaapi/wxaauth,暂未接入)返回,queryauth 查询成功后回写 auth_task_id/auth_task_status/auth_apply_status。",
"代码变更:app/lib/wechat_open_client.js 新增 getAuthorizerDetail(完整返回);app/service/systems/wechat.js 新增 buildAuthorizerPatch/getAuthorizerInfo、queryauth 增加状态落库;app/controller/wechatOpen.js 授权回调/authorized/updateauthorized 事件改用 getAuthorizerDetail 全量字段落库;app/model/wechat_app.js、systemMethods/wechat.js 同步。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.getAuthUrl-scope",
"date": "2026-09-22",
"type": "updated",
"summary": "wechat.getAuthUrl 授权链接限定授权范围:auth_type=2(仅小程序)+ category_id_list=18|86(代码管理、体验版二维码)",
"methods": [
"wechat.getAuthUrl"
],
"notes": [
"修正认知:auth_type 是授权账号类型(1公众号/2小程序/3公众号+小程序),不是权限范围;权限范围由 category_id_list(权限集 id 列表,竖线分隔)或商家在授权页自定义勾选控制。业务所需权限集:18=小程序代码管理(commit/submit_audit/queryauth/get_qrcode)、86=体验版二维码;getTemplateList/jscode2session/快速注册不需要商家权限集。",
"代码变更:app/service/systems/wechat.js#getAuthUrl 授权链接增加 category_id_list=18|86、auth_type 改为 2。前提:18/86 需在微信开放平台后台「权限集」配置并全网发布,否则商家授权页看不到;已授权商家需重新扫码授权才能获得 18/86。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.commit-ext-json-default",
"date": "2026-09-22",
"type": "updated",
"summary": "wechat.commit 的 ext_json 改为后端默认生成(仅 extEnable+extAppid),不再由前端传入",
"methods": [
"wechat.commit"
],
"notes": [
"入参仅剩 template_id;ext_json 由后端生成 JSON.stringify({extEnable:true, extAppid: 当前小程序appid}),前端传值被忽略;响应新增 ext_json 回显。",
"代码变更:app/service/systems/wechat.js#commit;文档 system.json wechat.commit 条目 params/response 同步。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.commit-desc-from-template",
"date": "2026-09-22",
"type": "updated",
"summary": "wechat.commit 代码描述也改为从模板取:user_version 与 user_desc 均不再由外部传入",
"methods": [
"wechat.commit"
],
"notes": [
"入参进一步瘦身:user_desc 也移除(外部传入被忽略);commit 流程:getTemplateList(0) → 按 template_id 找模板 → 取模板 user_version(≤64)与 user_desc 作为上传版本号/代码描述(缺失分别报「模板缺少合法版本号/缺少代码描述」)→ wxa/commit 成功后回写 wms_wechat_app.template_id/user_version;响应新增 user_desc。",
"代码变更:app/service/systems/wechat.js#commit;文档 system.json wechat.commit 条目 params/response 同步。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.userList",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.userList(需登录):拉取当前仓库小程序的用户列表(wms_user_oauth),支持 where/pagination/sort",
"methods": [
"wechat.userList"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.userList(isNeedLogin=true、isNeedAuth=false、Authorization 头):按 ctx.user.store_id 取仓库启用小程序(wms_wechat_app,is_enabled=1;可选 app_id 指定单个,须属于当前仓库),查询 wms_user_oauth(provider=wechat,app_id IN 命中应用);入参 where(字段白名单 id/user_id/app_id/openid/unionid/nickname/sex/login_time/login_count/created_at/updated_at,operator 结构,经 prepareWhereContext 解析)、pagination(page/pageSize)、sort(sortField 白名单同上,默认 updated_at DESC)。",
"代码变更:app/service/systems/wechat.js#userList(findAndCountAll,attributes 排除 session_key/refresh_token/access_token/expire_in/expire_time/login_code 敏感字段,raw+is_bound);app/service/systemMethods/wechat.js 出口 + where 字段白名单过滤 + _noNeedRight/_noNeedLog/_noNeedAuth 白名单加入 userList。",
"无数据库变更(纯只读查询)。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.queryauth-fix",
"date": "2026-09-22",
"type": "updated",
"summary": "修复 wechat.queryauth:接口路径改为 wxa/sec/queryauth 并新增必填入参 taskid,响应改为 task_status/apply_status",
"methods": [
"wechat.queryauth"
],
"notes": [
"根因:此前实现误用 /wxa/sec/wxaapi/queryauth 且未传 taskid,微信返回 40066 invalid url;官方接口为 POST /wxa/sec/queryauth?access_token=authorizer_access_token,请求体必填 taskid(发起认证接口 wxa/sec/wxaapi/wxaauth 返回)。",
"修复:lib#queryMiniProgramAuth 改路径并传 { taskid },40001/40014 清 authorizer token 重试;systems#queryauth 新增 taskid 必填校验,响应返回 task_status/apply_status/orderid/auth_url 等并附中文文案;文档 system.json queryauth 条目同步更新。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.submitAudit",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.submitAudit(需登录):提交代码审核,wms_wechat_app 新增审核状态字段(开发+生产已迁移)",
"methods": [
"wechat.submitAudit"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.submitAudit(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参白名单 item_list/feedback_info/feedback_stuff/preview_info/version_desc/privacy_api_not_use/order_info/ugc_declare;校验权限集 18;仅 audit_status!=1 时允许提交;POST wxa/submit_audit(authorizer_access_token,40001/40014 清缓存重试)成功后回写 audit_status=1、audit_id。",
"数据库:迁移 20260922170000-add-audit-fields-to-wms-wechat-app.js(user_version/audit_status/audit_id/audit_reason),开发与生产均已执行;commit 同步回写 user_version;审核结果事件 weapp_audit_success→audit_status=2、weapp_audit_fail→audit_status=3+audit_reason(按 ToUserName=user_name 定位)。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.getTrialQRCode",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.getTrialQRCode(需登录):获取体验版二维码(转存 COS 返回 URL)",
"methods": [
"wechat.getTrialQRCode"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.getTrialQRCode(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参 path(可选);按 ctx.user.store_id 取仓库启用小程序,hasFuncScope 校验权限集 18 或 86;GET wxa/get_qrcode(authorizer_access_token,path 自动 urlencode,40001/40014 清 authorizer token 缓存重试)返回 jpeg 图片,经 upload.uploadBuffer 转存 COS(key=qrcode/wechat/{warehouseId}/{yyyymmdd}/{ts}{rand}.jpg)后返回 URL。",
"代码变更:app/lib/wechat_open_client.js#getTrialQRCode;app/service/systems/wechat.js#getTrialQRCode/#buildTrialQrCodeKey;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.commit",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.commit(需登录):上传代码并生成体验版,wms_wechat_app 新增 template_id 字段(开发+生产已迁移)",
"methods": [
"wechat.commit"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.commit(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参 template_id/ext_json/user_version(≤64)/user_desc;按 ctx.user.store_id 取仓库启用小程序,hasFuncScope(func_info, 18) 校验代码管理权限集,getTemplateList(0) 校验模板存在(微信 85014 兜底),POST wxa/commit(authorizer_access_token,40001/40014 清 authorizer token 缓存重试)成功后回写 wms_wechat_app.template_id。",
"数据库:迁移 20260922160000-add-template-id-to-wms-wechat-app.js(wms_wechat_app.template_id bigint unsigned nullable),已在开发(127.0.0.1:3307)与生产(112.124.21.102)执行并验证;app/model/wechat_app.js 同步 template_id 字段。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.getTemplateList",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.getTemplateList(需登录):获取普通模板库列表,Redis 缓存 24h",
"methods": [
"wechat.getTemplateList"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.getTemplateList(isNeedLogin=true、isNeedAuth=false、Authorization 头):只拉普通模板(template_type=0,GET wxa/gettemplatelist + component_access_token,40001 自愈);Redis key wechat:template:list:normal 缓存 24h,有缓存直接返回(from_cache=true),无缓存拉取后写缓存。",
"代码变更:app/lib/wechat_open_client.js#getTemplateList(GET 请求封装);app/service/systems/wechat.js#getTemplateList;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.getMyLoginCode",
"date": "2026-09-22",
"type": "added",
"summary": "新增 wechat.getMyLoginCode:获取当前微信登录用户的登录码(至少微信登录),无则生成写入、有则直接返回",
"methods": [
"wechat.getMyLoginCode"
],
"notes": [
"systemMethods/wechat.js 白名单:_noNeedBind 新增 getMyLoginCode(微信登录态中间层,未绑定真实用户也可访问,业务层校验 ctx.oauth);systems/wechat.js 新增 getMyLoginCode:ctx.oauth 定位 wms_user_oauth,login_code 为空时 buildLoginCode(id) 生成(uuid={id}_{6位随机}、form=wechat 的 JSON base64)并回写,已有直接返回;system.json 微信模块新增该 method"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.uploadHeadimg",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.uploadHeadimg(微信登录态中间层):上传裁剪后的 PNG 头像(<500K)并回写 headimgurl",
"methods": [
"wechat.uploadHeadimg"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.uploadHeadimg(中间层鉴权,至少微信登录即可,未绑定也可):入参 image(PNG base64,支持 data URL 前缀);校验大小 <500K 与 PNG 文件头魔数后经 upload.uploadBuffer 上传 COS(key=headimg/wechat/{yyyymmdd}/{timestamp}{random}.png,不依赖仓库上下文),回写 wms_user_oauth.headimgurl 并返回 URL。",
"代码变更:app/service/systems/upload.js#uploadBuffer(Buffer 直传 COS);app/service/systems/wechat.js#uploadHeadimg/#buildHeadimgKey;app/service/systemMethods/wechat.js 出口 + _noNeedBind 白名单。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.updateInfo",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.updateInfo(微信登录态中间层):未绑定用户更新自己的昵称/头像",
"methods": [
"wechat.updateInfo"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.updateInfo(中间层鉴权,需有效微信登录态 token):仅未绑定真实用户(wms_user_oauth.user_id=0)可更新 nickname(≤255)/headimgurl(≤500),可部分更新,至少一个字段;已绑定账号返回「账号已绑定,不支持修改微信资料」。",
"代码变更:app/service/systems/wechat.js#updateInfo;app/service/systemMethods/wechat.js 出口 + _noNeedBind 白名单加入 updateInfo。"
],
"module": "wechat"
},
{
"version": "2026.09.22-user.info-wechat-appId-filter",
"date": "2026-09-22",
"type": "updated",
"summary": "user.info 新增可选入参 wechat_appId:传入时按小程序归属仓库过滤工号列表(仅保留非仓库工号(货主)+ 该仓库工号)",
"methods": [
"user.info"
],
"notes": [
"user.info 新增可选入参 wechat_appId:按 wms_wechat_app.appid(is_enabled=1)反查归属 warehouse_id,有仓库时过滤返回的 user.employees —— 保留 role_type!=warehouse(货主工号)或 store_id=该仓库 的工号;未传或查不到仓库保持原逻辑。",
"代码变更:app/service/systems/auth/user.js#info 增加 data.wechat_appId 处理(method 层 user.info 已透传 data)。"
],
"module": "user"
},
{
"version": "2026.09.22-wechat.registerMiniprogram",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.registerMiniprogram(需登录):快速注册企业小程序",
"methods": [
"wechat.registerMiniprogram"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.registerMiniprogram(isNeedLogin=true、isNeedAuth=false、Authorization 头):入参 name/code/code_type/legal_persona_wechat/legal_persona_name(必填)+ component_phone(选填),校验后调微信 fastregisterweapp?action=create(component_access_token,40001 自愈重试);注册任务创建后法人微信收到模板消息做人脸核身,审核结果通过 notify_third_fasteregister 事件推送到授权事件接收 URL(后续需在 handleEvent 中处理该事件绑定仓库)。",
"代码变更:app/lib/wechat_open_client.js#fastRegisterWeapp(create/search 通用封装 + 40001 自愈);app/service/systems/wechat.js#registerMiniprogram;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单。"
],
"module": "wechat"
},
{
"version": "2026.09.22-wechat.queryauth",
"date": "2026-09-22",
"type": "added",
"summary": "新增微信模块 wechat.queryauth(需登录):查询当前仓库小程序的认证状态",
"methods": [
"wechat.queryauth"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.queryauth(isNeedLogin=true、isNeedAuth=false、Authorization 头):按 ctx.user.store_id 取仓库启用小程序(wms_wechat_app,is_enabled=1,id ASC 取第一条),用 authorizer_access_token 调微信 wxa/sec/wxaapi/queryauth 返回 auth_state(0 未认证/1 认证中/2 认证通过/3 认证失败)并附 auth_state_text 中文文案。",
"代码变更:app/lib/wechat_open_client.js#queryMiniProgramAuth(authorizer_access_token 调 wxa/sec/wxaapi/queryauth,支持 DB 落库的 authorizer_refresh_token 兜底 Redis 丢失);app/service/systems/wechat.js#queryauth;app/service/systemMethods/wechat.js 出口 + _noNeedRight/_noNeedAuth 白名单加入 queryauth。"
],
"module": "wechat"
},
{
"version": "2026.09.21-wechat.pushLoginCode-legacy-code",
"date": "2026-09-21",
"type": "updated",
"summary": "弃用 wechat.getLoginWechatCode,wechat.pushLoginCode 改为复用旧 user.getLoginWechatCode 生成的登录码",
"methods": [
"wechat.pushLoginCode"
],
"notes": [
"弃用新增的 wechat.getLoginWechatCode(移除 systems/method 层与文档);小程序端继续使用旧 user.getLoginWechatCode 生成/轮询 6 位字母+数字登录码(user:wechat:login:code:* / client key,TTL 60s)。",
"wechat.pushLoginCode(需登录免权限)改造:读旧码缓存(getWechatLoginCodeCacheKey)取 client_code,经 findYe4sBindingByAccountId 反查当前账号 ye4s_user,将 ye4s_user_id 双写旧登录码缓存(code key + client key,TTL 按剩余有效期),旧轮询方读到 ye4s_user_id 即走 loginByYe4sUserId 直登返回正常 WMS token。"
],
"module": "wechat"
},
{
"version": "2026.09.21-wechat.loginCode-flow",
"date": "2026-09-21",
"type": "added",
"summary": "新增微信模块 wechat.getLoginWechatCode / wechat.pushLoginCode:小程序端生成 6 位登录码轮询,PC 已登录用户确认后小程序端返回登录成功并绑定账号",
"methods": [
"wechat.getLoginWechatCode",
"wechat.pushLoginCode"
],
"notes": [
"getLoginWechatCode(微信登录态中间层 _noNeedBind):不传 code 生成 6 位数字登录码写 Redis(key wechat:login:code:{code},TTL 300s,记录 oauth_id);传 code 轮询状态 pending/expired/success;success 时校验归属 oauth_id、一次性消费登录码、绑定 wms_user_oauth.user_id=确认账号(防换绑)并签发登录 token(id=账号ID、oauth_id 保留)。",
"pushLoginCode(需登录、免权限):PC/Web 已登录用户传 code,将对应缓存态置 success 并写入 account_id(TTL 120s 等待小程序领取);登录码归属校验防止他人码窃取登录。",
"代码变更:app/service/systems/wechat.js#getLoginWechatCode/#pushLoginCode/#createLoginCode/#getLoginCodeCacheKey、app/service/systemMethods/wechat.js(出口 + _noNeedBind 白名单 + _noNeedRight 加入 pushLoginCode)。"
],
"module": "wechat"
},
{
"version": "2026.09.21-wechat.loginByCode-appid-string",
"date": "2026-09-21",
"type": "updated",
"summary": "wechat.loginByCode 应用标识兼容字符串 appid:新增 appid(微信 AppID 字符串)入参按 uk_appid 反查,app_id(整数主键)保留向后兼容",
"methods": [
"wechat.loginByCode"
],
"notes": [
"微信 AppID 是字符串(如 wx6e91ec813bcb7eec),小程序端应传 appid 字符串(模板小程序运行时取 wx.getAccountInfoSync().miniProgram.appId)而非数据库主键。",
"代码变更:app/service/systems/wechat.js 新增 resolveWechatApp(优先 app_id 主键,其次 appid 按 uk_appid 反查并过滤 is_enabled=1);loginByCode 经 resolveWechatApp 解析应用记录,wms_user_oauth.app_id 仍存 wms_wechat_app.id(整数外键)。文档 system.json loginByCode 入参补充 appid 字段说明。"
],
"module": "wechat"
},
{
"version": "2026.09.21-user.info-oauth-middle",
"date": "2026-09-21",
"type": "updated",
"summary": "user.info 支持微信登录态中间层:微信登录未绑定时返回微信层信息(is_bound=false),不 401",
"methods": [
"user.info"
],
"notes": [
"systemMethods/user.js 构造器新增 _noNeedBind='info'(systemInit 第 5 参),微信登录态 token 可调用 user.info;auth.user.info 增加分支:未绑定真实用户(ctx.oauth 存在且无 ctx.user)时返回微信层信息(id=0/is_bound=false/oauth_id/openid/unionid/nickname/headimgurl/login_time/login_count,code 200),不 401;绑定/正常登录仍返回 findById 完整信息。",
"代码变更:app/service/systems/auth/user.js#info、app/service/systemMethods/user.js;撤销前版 wechat.getUserInfo(用户要求 getUserInfo 为公用接口,不收在 wechat 模块)。"
],
"module": "user"
},
{
"version": "2026.09.21-wechat.bindUser",
"date": "2026-09-21",
"type": "added",
"summary": "新增微信模块 wechat.bindUser(微信登录态中间层):用户名密码一致则绑定 wms_user_oauth.user_id 并签发绑定后的新 token",
"methods": [
"wechat.bindUser"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.bindUser(中间层鉴权:需有效微信登录态 token,未绑定真实用户也可调用):入参 username(用户名/手机号/邮箱)+ password;复用 auth.user 的 findUserByIdentifier/checkUserStatus/verifyPassword 校验;一致则 wms_user_oauth.user_id 绑定账号并签发新 token(payload id=账号ID、oauth_id 保留);已绑定时仅允许本人凭据幂等调用,不允许换绑。",
"鉴权机制:app/service/main.js checkAuth 新增中间层白名单 _noNeedBind(systemInit 第 5 参),oauth token 有效即通过(user_id=0 也可),ctx.oauth/ctx.oauthId 注入微信身份,不查 API 权限;代码变更:app/service/systemMethods/wechat.js(bindUser 出口 + _noNeedBind 白名单)、app/service/systems/wechat.js#bindUser/#buildBindResult。"
],
"module": "wechat"
},
{
"version": "2026.09.21-wechat.loginByCode",
"date": "2026-09-21",
"type": "added",
"summary": "新增微信模块 wechat.loginByCode(免登录):小程序 wx.login code 换 openid/session_key 并查/建 wms_user_oauth,返回 token+user",
"methods": [
"wechat.loginByCode"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.loginByCode(免登录 isNeedLogin=false):入参 code(wx.login 获取)+ app_id(wms_wechat_app.id);jscode2session(GET /sns/component/jscode2session)换 openid/session_key/unionid;wms_user_oauth 有记录则刷新 login_time/login_count/session_key,无记录则创建且 user_id=0(未绑定);JWT payload 记录 oauth_id(wms_user_oauth.id),区别于正常登录的用户 id 字段。",
"代码变更:app/lib/wechat_open_client.js#jscode2session(GET 请求封装);app/service/systems/wechat.js#loginByCode;app/service/systemMethods/wechat.js 免登录白名单加入 loginByCode。"
],
"module": "wechat"
},
{
"version": "2026.09.21-workbench.packOrder-business-users-restore",
"date": "2026-09-21",
"type": "updated",
"summary": "workbench.business 的 packOrder 分支恢复支持传入 users 上报打包人(未上报时回填工作台成员);token+key 新链路保持剥离 users",
"methods": [
"workbench.business"
],
"notes": [
"业务旧链路(workbench.business 的 packOrder 分支)恢复 users 上报生效:上报时以上报为准,未上报时自动回填该工作台绑定成员(wms_workbench_member);token+key 新链路(workbench.packOrder)保持剥离 users、一律取工作台绑定成员。",
"代码变更:app/service/systems/workbench.js#_packOrder 恢复 users 入参(上报优先、未报回填)、#packOrderByToken 解构剥离 users;回归测试 test/workbench_pack_waybill_dimension.test.cjs(26 用例)。"
],
"module": "workbench"
},
{
"version": "2026.09.21-wechat.getAuthUrl",
"date": "2026-09-21",
"type": "added",
"summary": "新增微信模块 wechat.getAuthUrl:生成微信开放平台小程序授权链接(PC版),state 缓存仓库信息用于回跳绑定",
"methods": [
"wechat.getAuthUrl"
],
"notes": [
"system.json 新增 module=wechat 方法 wechat.getAuthUrl(需登录);app/service/systems/wechat.js + app/service/systemMethods/wechat.js 生成授权链接;state=随机串,缓存 key wechat_auth_state:{state}(TTL 600s)存仓库信息;GET /Authorization 回跳凭 state 绑定仓库并落库 wms_wechat_app;state 缺失/过期展示错误页 app/view/wechat_auth_callback.html;配置 wechatOpen.redirect_uri"
],
"module": "wechat"
},
{
"version": "2026.09.21-workbench.getWorkbenchInfo-order-fields",
"date": "2026-09-21",

File diff suppressed because it is too large Load Diff

View File

@ -43,6 +43,8 @@
"start": "egg-scripts start ",
"stop": "node ./app/lib/stop_current_egg.js",
"dev": "egg-bin dev --port=6060",
"frpc:install": "powershell -ExecutionPolicy Bypass -File ./script/frp/frp-install.ps1",
"frpc:start": "powershell -ExecutionPolicy Bypass -File ./script/frp/frp-start.ps1",
"file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs",
"debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs",
"debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs",

View File

@ -0,0 +1,42 @@
# Put frpc.exe into script/frp/ (same dir as this script).
# Priority: 1) reuse local D:\printServer\frpc\frpc.exe 2) download from GitHub.
# ASCII only, avoids ANSI encoding issues with Chinese paths.
$ErrorActionPreference = 'Stop'
$FrpDir = $PSScriptRoot
$Exe = Join-Path $FrpDir 'frpc.exe'
if (Test-Path $Exe) {
Write-Output "frpc.exe already exists: $Exe"
exit 0
}
New-Item -ItemType Directory -Force -Path $FrpDir | Out-Null
# 1) reuse frpc from local printServer project
$LocalFrpc = 'D:\printServer\frpc\frpc.exe'
if (Test-Path $LocalFrpc) {
Copy-Item -Force $LocalFrpc $Exe
Write-Output "frpc.exe copied from $LocalFrpc -> $Exe"
exit 0
}
# 2) download (fallback)
$Version = '0.61.1'
$ZipName = "frp_${Version}_windows_amd64.zip"
$Url = "https://github.com/fatedier/frp/releases/download/v$Version/$ZipName"
$TmpZip = Join-Path $FrpDir $ZipName
$ExtractDir = Join-Path $FrpDir "frp_${Version}_windows_amd64"
Write-Output "Downloading $Url ..."
Invoke-WebRequest -Uri $Url -OutFile $TmpZip -UseBasicParsing
Write-Output "Extracting ..."
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory($TmpZip, $FrpDir)
Move-Item -Force (Join-Path $ExtractDir 'frpc.exe') $Exe
Remove-Item -Recurse -Force $ExtractDir
Remove-Item -Force $TmpZip
Write-Output "frpc.exe installed: $Exe"

18
script/frp/frp-start.ps1 Normal file
View File

@ -0,0 +1,18 @@
# Start frpc with the project frpc.toml (copy frpc.exe first if missing).
# ASCII only, avoids ANSI encoding issues with Chinese paths.
$ErrorActionPreference = 'Stop'
$FrpDir = $PSScriptRoot
$Exe = Join-Path $FrpDir 'frpc.exe'
if (-not (Test-Path $Exe)) {
Write-Output 'frpc.exe not found, installing ...'
& (Join-Path $PSScriptRoot 'frp-install.ps1')
}
$ProjectRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$Config = Join-Path $ProjectRoot 'frpc.toml'
$Config = (Resolve-Path $Config).Path
Write-Output "Starting frpc with config: $Config"
& $Exe -c $Config