diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md
index 1e75eff..ed9fbfb 100644
--- a/AI_METHOD_ROUTING.md
+++ b/AI_METHOD_ROUTING.md
@@ -271,6 +271,28 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 失败口径:参数非法 → 400(`摄像头ID不能为空`/`云台方向不合法,仅支持:…`/`云台转速需为 1-7 的整数`/`预置点编号…`);摄像头不存在或跨仓库 → 404;打印服务 HTTP 非 2xx 或回包 `status=fail`/`success=false` → 500 `打印服务请求失败: …`
- 接口文档:`methods/system.json` 分组「摄像头模块」(module=camera),变更记录见 `methods/changes/system.json` 版本 `2026.09.15-camera-ptz-control`(首次登记)、`2026.09.15-camera-ptz-wms-endpoint`(改独立端点)、`2026.09.15-camera-ptz-preset-set`(新增存点)、`2026.09.15-camera-ptz-camera-id`(请求体带 cameraId)
+## 5.8 afterSale(售后类型/子类型配置 CRUD)能力速查
+
+| method | 实现文件 | 函数 | 登录 | 鉴权/权限 |
+|---|---|---|---|---|
+| afterSale.typeList | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeList / getTypeList | 需登录 | 免权限、免仓库有效期校验、免日志 |
+| afterSale.typeCreate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeCreate / createType | 需登录 | 免权限、免仓库有效期校验、记日志 |
+| afterSale.typeUpdate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeUpdate / updateType | 需登录 | 免权限、免仓库有效期校验、记日志 |
+| afterSale.typeDelete | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | typeDelete / deleteType | 需登录 | 免权限、免仓库有效期校验、记日志 |
+| afterSale.subTypeList | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeList / getSubTypeList | 需登录 | 免权限、免仓库有效期校验、免日志 |
+| afterSale.subTypeCreate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeCreate / createSubType | 需登录 | 免权限、免仓库有效期校验、记日志 |
+| afterSale.subTypeUpdate | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeUpdate / updateSubType | 需登录 | 免权限、免仓库有效期校验、记日志 |
+| afterSale.subTypeDelete | app/service/systemMethods/afterSale.js → app/service/systems/afterSale.js | subTypeDelete / deleteSubType | 需登录 | 免权限、免仓库有效期校验、记日志 |
+
+- 仓库维度隔离:列表返回系统级(warehouse_id=null、is_system=1,全部仓库可读)+ 当前仓库自定义(is_system=0)合并;创建仅允许仓库自定义;改/删仅命中 `id + warehouse_id=当前仓库 + is_system=0`
+- 系统级保护:is_system=1 的类型/子类型不允许编辑/删除,未命中统一 404「不存在、无权操作或为系统预设类型」
+- 编码规则:type/sub_type 仅允许 `/^[a-z0-9_]+$/`(小写字母/数字/下划线);type≤20 字符、sub_type≤50、name≤50;创建时校验编码不与系统级重复、同仓库内唯一(409),MySQL 唯一索引 `uk_type_warehouse` / `uk_type_subtype_warehouse` 兜底
+- 编码不可变:update 仅允许 name/is_enabled/sort_order,不允许改 type/sub_type 编码
+- 删除策略(拒绝,不做级联):typeDelete 在该类型下存在本仓库自定义子类型时拒绝(409);subTypeDelete 在 wms_after_sale 存在该 type/sub_type 引用时拒绝(409「已被售后单使用」)
+- 错误码:400(参数/编码格式错误)、404(不存在/无权/系统预设)、409(编码重复/存在子类型/被引用)
+- 数据表:wms_after_sale_type / wms_after_sale_sub_type(app/model/after_sale_type.js、after_sale_sub_type.js)
+- 接口文档:methods/system.json 分组「售后模块」(module=afterSale),变更记录见 methods/changes/system.json 版本 2026.09.16-after-sale-type-subtype-crud
+
## method结束
## 6. 全量 Service Method 能力清单(自动扫描)
@@ -282,7 +304,7 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 临时清单输出:temp/tmp-service-method-inventory.md
-自动生成时间: 2026-09-15T15:22:29.464Z
+自动生成时间: 2026-09-15T16:36:08.605Z
扫描范围: app/service/**/*.js
文件数: 212
@@ -307,8 +329,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- resolveActiveGroups, isFunctionAvailable, getFunctionList, buildFunctionListText
- app/service/inbox/index.js (5)
- list, detail, thread, reply, stats
-- app/service/inbox/message.js (9)
- - list, _normalizeIds, _normalizeStrings, detail, thread, stats, retry, _repush, retryFailed
+- app/service/inbox/message.js (10)
+ - list, _normalizeIds, _normalizeStrings, detail, thread, stats, retry, _repush, retryFailed, retryFailedByWarehouse
- app/service/inbox/processor.js (15)
- _loadGroupInfo, isStaleMessage, process, handleApiMessage, tryBindGroup, writeOutboundReply, isBlocked, invalidateBlockCache, getApiAppCallbackConfig, getApiAppCallbackUrl, pushSystemNotification, extractWarehouseId, extractStoreId, getWarehouseIdFromContext, getStoreIdFromContext
- app/service/inbox/receiver.js (1)
@@ -365,8 +387,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- heartbeat
- app/service/system.js (4)
- callMethod, validateParams, validateRequestContext, saveLog
-- app/service/systemMethods/afterSale.js (22)
- - workList, _resolveAfterSaleBlockRoleGroups, workCount, auditList, detail, create, _resolveRedundantFields, transfer, handleWorkOrder, batchSetPendingFeedback, batchClose, registerClaim, export, exportTaskProgress, generateAfterSaleNo, _getCurrentDatePart, _buildOperatorSnapshot, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
+- app/service/systemMethods/afterSale.js (30)
+ - workList, _resolveAfterSaleBlockRoleGroups, workCount, auditList, detail, create, _resolveRedundantFields, transfer, handleWorkOrder, batchSetPendingFeedback, batchClose, registerClaim, export, exportTaskProgress, generateAfterSaleNo, _getCurrentDatePart, _buildOperatorSnapshot, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress, typeList, typeCreate, typeUpdate, typeDelete, subTypeList, subTypeCreate, subTypeUpdate, subTypeDelete
- app/service/systemMethods/apiApp.js (6)
- list, detail, create, update, delete, regenerateSecret
- app/service/systemMethods/camera.js (10)
@@ -513,8 +535,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- list, detail, create, update, delete, business, bindCamera, bind, getWorkbenchInfo, resetLoginCode, removeMember, bindMember, packOrder, finishPack, sendWeight, queryOrder
- app/service/systems/account_platform.js (11)
- getActiveInclude, getPrimaryRoleBinding, formatActiveContext, switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
-- app/service/systems/afterSale.js (29)
- - list, countPending, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder, getDetail, _enrichAfterSaleDetail, _resolveOrderDetail, _resolveStoreContractNote, _resolveWaybillDetail, _enrichStepsWithAttachments, create, _enrichListStoreNames, update, _formatAfterSaleRow, addStep, bindAttachments, transfer, handleWorkOrder, createInterceptWorkOrdersAndNotify, _resolveFollowupHours, _tryParseHours, batchSetPendingFeedback, batchClose, registerClaim, exportAfterSales, _generateAndUploadExcel, _getCreateChannelLabel
+- app/service/systems/afterSale.js (46)
+ - list, countPending, _buildListWhere, _resolveConditionValue, _extractConditionValue, _buildListOrder, getDetail, _enrichAfterSaleDetail, _resolveOrderDetail, _resolveStoreContractNote, _resolveWaybillDetail, _enrichStepsWithAttachments, create, _enrichListStoreNames, update, _formatAfterSaleRow, addStep, bindAttachments, transfer, handleWorkOrder, createInterceptWorkOrdersAndNotify, _resolveFollowupHours, _tryParseHours, batchSetPendingFeedback, batchClose, registerClaim, exportAfterSales, _generateAndUploadExcel, _getCreateChannelLabel, _createAfterSaleTypeConfigError, _validateAfterSaleTypeCode, _normalizeAfterSaleTypeSortOrder, _normalizeAfterSaleTypeEnabled, _formatAfterSaleTypeConfigRow, _buildAfterSaleTypeListWhere, _buildAfterSaleTypeListOrder, _buildAfterSaleSubTypeListWhere, _buildAfterSaleSubTypeListOrder, getTypeList, createType, updateType, deleteType, getSubTypeList, createSubType, updateSubType, deleteSubType
- app/service/systems/api_sign.js (4)
- getApiAppCacheKey, getApiAppConfigByAppKey, getApiAppSecretByAppKey, verifyRequestSignByAppKey
- app/service/systems/apiApp.js (8)
@@ -751,6 +773,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
+
+
diff --git a/INBOX_V2_HTTP_TEST_REPORT.md b/INBOX_V2_HTTP_TEST_REPORT.md
new file mode 100644
index 0000000..cbece71
--- /dev/null
+++ b/INBOX_V2_HTTP_TEST_REPORT.md
@@ -0,0 +1,349 @@
+# 站内信 v2 可配置回信引擎 —— HTTP 覆盖测试报告
+
+> 生成时间:2026-09-16T18:11:52.145Z | 执行方式:真实 HTTP 链路(POST /warehouse?method=inbox.push)
+
+## 1. 测试环境
+
+| 项 | 值 |
+|---|---|
+| 服务 | http://127.0.0.1:6060(本地 egg 服务,运行中) |
+| 回调接收服务 | http://127.0.0.1:9001/ack(本地 ack 服务,返回 {code:200}) |
+| 数据库 | 127.0.0.1:3307/wms(本地库) |
+| API 应用 | wms_api_app id=3,app_key=APP2025011514315678,warehouse_id=100000 |
+| 原 callback_url | `http://localhost:6061/push` → 测试期间改为本地 ack 服务(**未自动恢复**) |
+| 新 v2 测试群 | `httpv2:1789582312145`(首推自动登记后开启 store/after_sales + ai_enabled=1 + template_reply_enabled=1) |
+| 新 express 测试群 | `httpv2expr:1789582312145`(express/after_sales,开启 v2) |
+| 存量 v1 对照群 | `test-enter-store-aftersales`(template_reply_enabled=0) |
+| 存量 ai_enabled=0 群 | `g_st_finance_debug` |
+
+## 2. 链路
+
+```mermaid
+flowchart LR
+ A[测试脚本] -->|POST /warehouse inbox.push 验签| B[warehouseMethods/inbox.push]
+ B --> C[receiver.receive 幂等写库 + 自动登记群]
+ C -->|source_type=api setImmediate| D[processor.handleApiMessage]
+ D --> E{群校验 ai_enabled / group_type / 历史消息}
+ E -->|template_reply_enabled=1| F[inbox.v2.rules 可配置引擎]
+ F --> G[关键词→白名单→取号→callFunction→回复表]
+ G --> H[writeOutboundReply]
+ H -->|POST notify.reply| I[本地 ack 服务 9001]
+ I --> J[push_status=2]
+```
+
+## 3. 用例结果总览
+
+- 总计:**12** 用例,通过:**12**,失败:**0**
+
+| # | 用例 | 内容 | 结果 |
+|---|---|---|---|
+| TC01 | 破损建单(新 v2 群) | `破损 SF1234567890123` | ✅ PASS |
+| TC02 | 改地址 | `改地址 SF1234567890123` | ✅ PASS |
+| TC03 | 换快递(express 取号) | `改快递 SF1234567890123 圆通` | ✅ PASS |
+| TC04 | 拦截 | `拦截 SF1234567890123` | ✅ PASS |
+| TC05 | 揽收(上门取件) | `上门取件 SF1234567890123` | ✅ PASS |
+| TC06 | 取号失败引导语 | `破损` | ✅ PASS |
+| TC07 | v2 未命中静默(模块接管) | `今天天气怎么样` | ✅ PASS |
+| TC08 | 历史消息静默跳过 | `破损 SF1234567890123` | ✅ PASS |
+| TC09 | 幂等(同 requestId 两次推送) | `破损 SF9999999999999` | ✅ PASS |
+| TC10 | express 群白名单放行但函数越权拦截(静默) | `破损 SF1234567890123` | ✅ PASS |
+| TC11 | v1 分叉确认(template_reply_enabled=0 群) | `破损 SF1234567890123` | ✅ PASS |
+| TC12 | ai_enabled=0 群跳过 | `破损 SF1234567890123` | ✅ PASS |
+
+## 4. 用例明细
+
+### TC01 破损建单(新 v2 群) ✅ PASS
+
+- 消息:`破损 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-01-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 入站消息入库 | ✅ | id=2016 |
+| v2 命中轨迹写入 ai_thoughts(function=handleStoreFeedback) | ✅ | [object Object] |
+| 出站回执存在(sys:ack) | ✅ | sys:ack:api:APP2025011514315678:httpv2-01-1789582314626 |
+| 出站 push_status=2(回调 200) | ✅ | push_status=2 |
+| 本地 ack 服务收到 notify.reply(type=ai) | ✅ | type=ai |
+| 出站日志 wms_warehouse_log 记录 notify.reply | ✅ | http_status=200 |
+| 无工单时函数返回可见(出站文案非空) | ✅ | 本地无该运单,函数返回文案: 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 |
+
+- 入站消息 id=2016,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-01-1789582314626` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC02 改地址 ✅ PASS
+
+- 消息:`改地址 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-02-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| v2 命中 changeAddr | ✅ | |
+| 出站回执存在 | ✅ | push_status=2 |
+| 函数已执行(工单或错误文案) | ✅ | \| 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 |
+
+- 入站消息 id=2018,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-02-1789582314626` | 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC03 换快递(express 取号) ✅ PASS
+
+- 消息:`改快递 SF1234567890123 圆通`
+- ext_id:`api:APP2025011514315678:httpv2-03-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| v2 命中 changeExpress | ✅ | |
+| 取号含 express=圆通 | ✅ | thoughts 含 express 字段 |
+| 出站回执存在 | ✅ | 未找到订单:SF1234567890123、1234567890123 |
+
+- 入站消息 id=2020,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-03-1789582314626` | 未找到订单:SF1234567890123、1234567890123 | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC04 拦截 ✅ PASS
+
+- 消息:`拦截 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-04-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| v2 命中 interceptWaybill | ✅ | |
+| 出站回执存在 | ✅ | 请提供运单号 |
+
+- 入站消息 id=2022,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-04-1789582314626` | 请提供运单号 | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC05 揽收(上门取件) ✅ PASS
+
+- 消息:`上门取件 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-05-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| v2 命中 requestPickup | ✅ | |
+| 出站回执存在 | ✅ | 请提供运单号 |
+
+- 入站消息 id=2024,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-05-1789582314626` | 请提供运单号 | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC06 取号失败引导语 ✅ PASS
+
+- 消息:`破损`
+- ext_id:`api:APP2025011514315678:httpv2-06-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 出站回执为取号引导语 | ✅ | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) |
+| 未建工单(取号失败不调用函数) | ✅ | |
+
+- 入站消息 id=2026,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-06-1789582314626` | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC07 v2 未命中静默(模块接管) ✅ PASS
+
+- 消息:`今天天气怎么样`
+- ext_id:`api:APP2025011514315678:httpv2-07-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 无出站回执(静默) | ✅ | |
+| 无 ai_thoughts 轨迹 | ✅ | 空 |
+| 无新工单 | ✅ | 0 条 |
+
+- 入站消息 id=2028,ai_thoughts:
+
+```json
+null
+```
+
+### TC08 历史消息静默跳过 ✅ PASS
+
+- 消息:`破损 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-08-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 入站仍入库 | ✅ | id=2029 |
+| 无出站回执(静默跳过) | ✅ | |
+| 无新工单 | ✅ | 0 条 |
+
+- 入站消息 id=2029,ai_thoughts:
+
+```json
+null
+```
+
+### TC09 幂等(同 requestId 两次推送) ✅ PASS
+
+- 消息:`破损 SF9999999999999`
+- ext_id:`api:APP2025011514315678:httpv2-09-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 两次推送均返回成功(flag=success) | ✅ | 第一次 flag=success,第二次 flag=success |
+| 入站仅 1 条 | ✅ | 1 -> 1 |
+| 出站仅 1 条(不重复处理) | ✅ | 出站条数 1 -> 1 |
+
+- 入站消息 id=2030,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-09-1789582314626` | 未找到当前货主在仓库中的运单「SF9999999999999」,请核实单号后重试 | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC10 express 群白名单放行但函数越权拦截(静默) ✅ PASS
+
+- 消息:`破损 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-10-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 入站消息入库 | ✅ | id=2032 |
+| 无出站回执(静默) | ✅ | |
+| 白名单行存在(express/after_sales 允许 damage 子类型) | ✅ | 行数=1 |
+| 函数越权拦截(handleStoreFeedback 仅 store 群可用 → 无轨迹) | ✅ | 无轨迹 |
+
+- 入站消息 id=2032,ai_thoughts:
+
+```json
+null
+```
+
+### TC11 v1 分叉确认(template_reply_enabled=0 群) ✅ PASS
+
+- 消息:`破损 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-11-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 未走 v2 引擎(thoughts 无 v2 轨迹特征) | ✅ | [{"round":0,"action":"rule","params":{"keyword":"SF1234567890123","issue_type":"damaged"},"reason":"关键词规则命中: 破损","function":"handleStoreFeedback","functionResult":{"error":"未找到当前货主在仓库中的运单「SF1234567890 |
+| 群配置 template_reply_enabled=0 已确认 | ✅ | |
+
+- 入站消息 id=2033,ai_thoughts:
+
+```json
+[object Object]
+```
+
+- 出站回执:
+
+| ext_id | content | push_status |
+|---|---|---|
+| `sys:ack:api:APP2025011514315678:httpv2-11-1789582314626` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 |
+
+- 本地 ack 服务收到 notify.reply:type=ai
+
+- wms_warehouse_log notify.reply 日志:http_status=200
+
+### TC12 ai_enabled=0 群跳过 ✅ PASS
+
+- 消息:`破损 SF1234567890123`
+- ext_id:`api:APP2025011514315678:httpv2-12-1789582314626`
+
+| 校验项 | 结果 | 详情 |
+|---|---|---|
+| 无出站回执 | ✅ | |
+| 无新工单 | ✅ | 0 条 |
+
+- 入站消息 id=2035,ai_thoughts:
+
+```json
+null
+```
+
+## 5. 说明与后续
+
+1. 测试产生的入站/出站消息、工单等数据**已保留**(未自动清理),可直接在库中核对。
+2. `wms_api_app` id=3 的 callback_url 测试期间被改为本地 ack 服务,如需恢复:
+
+```sql
+UPDATE wms_api_app SET callback_url = 'http://localhost:6061/push' WHERE id = 3;
+```
+
+3. 测试脚本与明细数据位于 `temp/inbox_v2_http_test/`(`run_http_test.js`、`ack_server.js`、`report.json`)。
+
diff --git a/INBOX_V2_TEST_GUIDE.md b/INBOX_V2_TEST_GUIDE.md
new file mode 100644
index 0000000..21bc144
--- /dev/null
+++ b/INBOX_V2_TEST_GUIDE.md
@@ -0,0 +1,327 @@
+# 站内信 v2 可配置回信引擎 —— 端到端测试流程指南
+
+> 适用对象:开发/测试人员。覆盖消息 HTTP 推送进入、群类型创建、回传数据接收、
+> 校验准则、涉及表的状态变化与特殊流程边界。
+> 所有示例基于本地环境(服务 `127.0.0.1:6060`,MySQL `127.0.0.1:3307/wms`),
+> 生产环境仅做只读核对,禁止写操作。
+
+## 测试范围(重要)
+
+- **只测 v2 链路**:`template_reply_enabled=1` 的群走 `inbox.v2.rules` 可配置引擎;
+- **v1 链路不需要测试**:processor 分叉为 `else` 分支原样保留,v1 规则表
+ (`inbox/rules.js` 静态规则)与 AI 兜底逻辑零改动,无需回归;
+- 自动化验证已覆盖:`test/inbox/v2_rules_engine.test.js`(引擎 9 用例)、
+ `test/inbox/v2_processor_fork.test.js`(分叉 3 用例)、
+ `test/inbox/v2_function_sync.test.js`(函数同步 4 用例)。
+
+---
+
+## 0. 总体链路
+
+```mermaid
+flowchart LR
+ A[外部适配器] -->|POST /warehouse inbox.push 验签| B[warehouseMethods/inbox.push]
+ B --> C[receiver.receive 幂等写库
wms_inbox_message inbound]
+ C -->|自动登记群| D[wms_inbox_group]
+ C -->|source_type=api 异步| E[processor.handleApiMessage]
+ E --> F{群校验: group_type / ai_enabled}
+ F -->|未通过| G[静默跳过]
+ F -->|通过| H{规则引擎}
+ H -->|v1| I[rules.handle]
+ H -->|template_reply_enabled=1| J[inbox.v2.rules 引擎
模块接管]|
+ I --> K[callFunction 代码越权校验]
+ K --> L[writeOutboundReply 出站回执]
+ L -->|POST notify.reply| M[回调 URL
wms_api_app.callback_url]
+ L --> N[wms_inbox_message outbound + wms_warehouse_log]
+```
+
+---
+
+## 1. 消息 HTTP 推送进入(inbox.push)
+
+### 1.1 入口
+
+```
+POST http://127.0.0.1:6060/warehouse?method=inbox.push&v=1.0×tamp={秒级时间戳}&app_key={appKey}&sign={sign}
+Content-Type: application/json
+```
+
+- `warehouse_id` 由验签后的 `wms_api_app` 上下文注入,**禁止外部传入**;
+- `ext_id` 由服务端组合:`api:{appKey}:{requestId}`,用于幂等去重。
+
+### 1.2 签名算法(app/lib/api_sign.js)
+
+```
+bodySign = md5(stableStringify(body)) // 对象键按字母序排序后序列化
+canonical = query 参数按 key 字母序拼接 "k=v&k2=v2"(排除 sign/signature)
+sign = md5(canonical + self_app_secret + bodySign)
+```
+
+- `self_app_secret` 来自 `wms_api_app.self_app_secret`(按 `app_key` 查询);
+- `app_key` 对应仓库的 API 应用需存在且已启用。
+
+### 1.3 请求体字段
+
+| 字段 | 必填 | 说明 |
+|---|---|---|
+| `requestId` | ✅ | 来源请求唯一 ID,与 appKey 组成 `ext_id` |
+| `content` | - | 消息正文(触发规则引擎的输入) |
+| `groupId` | - | 外部群 ID,用于关联群与货主路由 |
+| `groupName` | - | 群名称(首次推送会自动登记群) |
+| `userId` / `userName` | - | 外部用户 ID / 名称 |
+| `parentId` | - | 关联消息 ID(回信时形成对话链) |
+| `targetType` | - | `im` / `api` / `webhook`,默认 `im` |
+| `extData` | - | 透传 JSON,WMS 不解析,回信原样带回 |
+| `sendTime` | - | 消息原始发送时间(毫秒/秒/ISO),用于历史消息过滤 |
+| `flags` | - | `{skipAi:true}` 显式跳过 AI;`{send_time:ms}` 等价 sendTime |
+
+### 1.4 响应与幂等
+
+- 成功:`{code:0, message:'ok', data:{ok:true, id, ext_id}}`;
+- 相同 `ext_id` 重复推送:直接返回已存在记录,**不重复入库、不重复触发处理**。
+
+---
+
+## 2. 创建特定群类型
+
+### 2.1 自动登记(首次推送即建群)
+
+首次推送含 `groupName` 的消息时,`receiver.receive` 自动在 `wms_inbox_group`
+创建群记录(按 `group_id + warehouse_id` 唯一):
+- `ai_enabled=0`、`group_type/sub_type=NULL`、`store_id` 取自绑定的货主;
+- 群名变化只更新名称,不重复建群。
+
+### 2.2 配置群类型(管理接口)
+
+```
+POST http://127.0.0.1:6060/system?method=inbox.group.update&v=1.0×tamp={ts}
+Authorization: Bearer {登录 token}
+Content-Type: application/json
+
+{ "id": {群记录ID}, "groupType": "store", "subType": "after_sales",
+ "storeId": 1000000, "aiEnabled": 1 }
+```
+
+- `groupType`:`store`(货主)/ `warehouse`(仓库)/ `express`(快递);
+- `subType`(群子类型):
+ - store:`after_sales` / `finance` / `receiving`
+ - warehouse:`receiving` / `production` / `stockout` / `finance` / `all` / `customer_service` / `exception`
+ - express:`pickup` / `after_sales`
+- `aiEnabled=1` 才会进入规则引擎(第 5 步开关);
+- `inbox.group.reset`:清空群类型配置并重置 AI 开关。
+
+### 2.3 v2 回信开关(开启即接管链路)
+
+v2 引擎开关 `template_reply_enabled`(管理接口未上线前用 SQL 设置):
+
+```sql
+UPDATE wms_inbox_group SET template_reply_enabled = 1
+WHERE group_id = '{测试群ID}' AND warehouse_id = {仓库ID};
+```
+
+- `template_reply_enabled=1` 的群在第 6 步自动走 `inbox.v2.rules.handle`(已接入);
+- **模块接管模式**:v2 开启群的未命中消息直接静默,不走 v1 规则、不走 AI 兜底;
+- 群信息每条消息实时查库(`_loadGroupInfo` 不缓存),SQL 改动对下一条消息立即生效;
+- v2 配置数据(关键词/白名单/函数/取号/回复)有 300s 缓存,改动后需
+ `ctx.service.inbox.v2.config.invalidate(warehouseId)` 或等 TTL 过期。
+
+---
+
+## 3. 接收回传数据
+
+### 3.1 出站回执方向(WMS → 外部)
+
+规则处理完成后,`processor.writeOutboundReply` 向 `wms_api_app.callback_url`
+POST 回执(`notify.reply`):
+
+```
+POST {callback_url}?app_key={k}&method=notify.reply×tamp={秒}&sign={md5(appSecret + timestamp + bodyJson)}
+```
+
+回执 body 关键字段:
+- `data.type`:`ai`(规则/AI 自动回复)、`system`、`bind`、`balance`、`error`;
+- `data.content`:回复内容;`data.ext_data`:入站 `extData` 原样带回;
+- `data.ext_id`:出站消息记录 ID;`data.group_id` / `user_id` / `user_name`:目标群与用户。
+
+### 3.2 测试接收方法
+
+方式 A(推荐):临时把本地库 `wms_api_app.callback_url` 指向本地 HTTP 接收服务,
+观察收到的 `notify.reply` 报文并返回 `{code:200}`:
+
+```sql
+UPDATE wms_api_app SET callback_url = 'http://127.0.0.1:9001/ack'
+WHERE app_key = '{测试app_key}';
+```
+
+方式 B(不落回执服务):直接核对库表:
+- `wms_inbox_message`:`direction='outbound'`、`ext_id='sys:ack:{入站ext_id}'`;
+- `wms_warehouse_log`:`method='notify.reply'` 的出站通知日志(含 http_status/body/result)。
+
+### 3.3 推送状态核对
+
+| push_status | 含义 |
+|---|---|
+| 0/1 | 未推送 / 待推送 |
+| 2 | 回调返回 HTTP 200 且 `code=200` → 推送成功 |
+| 3 | 回调非 200 / 无回调地址 / 异常 → 推送失败(可 `inbox.message.retry` 重推) |
+
+---
+
+## 4. 校验准则
+
+| # | 校验项 | 准则 |
+|---|---|---|
+| 1 | 幂等 | 相同 `ext_id` 只入库一次、只处理一次 |
+| 2 | 群类型 | `group_type` 为空 → 跳过处理(未绑定任务类型) |
+| 3 | AI 开关 | `ai_enabled != 1` → 跳过(快递群默认 0,需手动开) |
+| 4 | 历史消息 | `send_time` 距今 > 10 分钟(`config.inbox.historyMessageMaxAgeMs` 可调)→ 跳过,不回复不建工单 |
+| 5 | 屏蔽 | 屏蔽用户/群 → 跳过处理(`blockUser` 函数 / `wms_inbox_block`) |
+| 6 | 关键词命中 | 长词优先;命中后先过防误判守卫(如"拦截" vs "查物流") |
+| 7 | 函数越权 | `callFunction` 按群活跃分组校验,越权返回错误(DB 配置只做可见性,代码是最终权威) |
+| 8 | 取号失败 | 子类型关联了取号规则但未提取到值 → 回复引导语(`no_number_hint` → target 专属 → 默认),**不调用函数** |
+| 9 | 回复决策 | 回复表 `is_reply=1` → 自定义文案;`is_reply=0` → 静默(函数仍执行);无配置 → 函数返回值兜底 |
+| 10 | 快递群 | express 群仅执行函数,**不回信** |
+| 11 | 出站回执 | 回执 `ext_id='sys:ack:{入站ext_id}'` 唯一,重复处理不重复出站 |
+| 12 | 缓存 | v2 配置缓存 `inbox:v2:cfg:{warehouseId}` TTL 300s;配置变更后必须 `invalidate`,否则 5 分钟内不生效 |
+
+---
+
+## 5. 涉及表的状态变化
+
+### 5.1 消息链路表
+
+| 表 | 变化 |
+|---|---|
+| `wms_inbox_message` | 入站:`direction='inbound'`、`push_status=0`;规则命中后写 `ai_thoughts`(轨迹 JSON)。出站:`direction='outbound'`、`ext_id='sys:ack:{ext_id}'`、`parent_id=入站ID`;推送后 `push_status=2/3`、`push_response`、`pushed_at` |
+| `wms_inbox_group` | 首次推送自动登记(`ai_enabled=0`);`group.update` 写 `group_type/sub_type/store_id/ai_enabled`;群名变化只更新名称 |
+| `wms_warehouse_log` | 每次出站 `notify.reply` 写一条(`method/url/http_status/body/result/use_time`) |
+
+### 5.2 业务函数表(v1 与 v2 共用函数)
+
+| 表 | 变化(以函数为准) |
+|---|---|
+| `wms_after_sale` | `interceptWaybill`(type=order, sub_type=intercept, status=pending)、`changeAddr`(change_address/rejected/urge)、`handleStoreFeedback`(mis_shipment/damage/extra_item/missing_item)、`weishoudao`(verify_delivery)、`requestPickup`(pickup)等创建售后工单 |
+| `wms_order_express` | 拦截成功后写 `intercept_status='requested'` 与 `intercept_time`(值域见 `intercept-status-values` 约定) |
+| `wms_order_delivery_{warehouseId}` | `createPostnum` 分配运单号后写 `logistics_*`/`post_status`;`changeExpress` 修改快递分配 |
+
+### 5.3 v2 配置表(全部只读,引擎启动时一次性同步函数表)
+
+| 表 | 变化 |
+|---|---|
+| `wms_after_sale_function` | 启动时 `functionSync.sync()` 幂等 upsert(只增改不删、不覆盖 `is_enabled/sort_order`) |
+| `wms_after_sale_type` / `wms_after_sale_sub_type` | 系统级 + 仓库级(`warehouse_id NULL` 全局可见) |
+| `wms_after_sale_keyword` | 关键词 → 子类型映射(长词优先、`sort_order` 同长时生效) |
+| `wms_after_sale_sub_type_group` | 子类型 × 群类型 × 群子类型白名单(`uk(sub_type_id, group_type, sub_group)`) |
+| `wms_after_sale_sub_type_function` | 子类型 → 处理函数(`function_id` + `sort_order`) |
+| `wms_after_sale_sub_type_rule` + `wms_inbox_number_rule` | 子类型 → 取号规则(`target/regexp/sort_order`) |
+| `wms_after_sale_reply` | 仓库级(`warehouse_id` 非空)覆盖系统级;`is_reply=0` 静默、`no_number_hint` 引导语 |
+
+---
+
+## 6. 特殊流程边界
+
+### 6.1 开关与分叉边界
+
+- **AI 开关**:`ai_enabled != 1` 一律跳过(安全默认,快递群默认关闭);
+- **群未绑定**:`group_type` 为空跳过;`store` 群无 `store_id` 归属时主分组不激活(`resolveActiveGroups`);
+- **v1/v2 分叉**(已接入):`template_reply_enabled=1` 走 `inbox.v2.rules.handle`,
+ 否则走 `inbox.rules.handle`(v1 分支原逻辑零改动);
+- **模块接管**:v2 开启群的未命中消息直接静默 return,不回落到 v1 规则与 AI 兜底。
+
+### 6.2 v2 引擎边界(已接入 processor)
+
+- **关键词命中**:长词优先;同长多个子类型均按序尝试;
+- **白名单过滤**:`(group_type, sub_group)` 双维度;群 `sub_type` 为空时**只按主类型放行**
+ (随后由 `callFunction` groups 校验兜底收紧);
+- **取号正则安全三件套**:保存时校验 + 长度 ≤ 500 + 每次 `new RegExp`(非法正则跳过并告警);
+- **入参组装**:`waybill_no/order_no/source_order_codes/receiving_no/entry_order_no/stockout_no`
+ 合并去重 join 逗号 → `keyword`;`express_name→express`;
+ 子类型转译 `issue_type`(damage→damaged、change_address→addr、rejected→return、urge→urge 等);
+- **多函数子类型**:按 `sort_order` 依次执行,任一失败立即返回失败文案;
+- **回复优先级**:回复表(仓库级 > 系统级)> 函数返回值(`direct_reply.messages` > `data.message` > `error`);
+- **缓存失效**:管理接口增删改配置后必须调用 `ctx.service.inbox.v2.config.invalidate(warehouseId)`;
+ 启动时**不清** v2 缓存(防雪崩)。
+
+### 6.3 消息边界
+
+- **历史/补推消息**:`sendTime` 超阈值 → 静默跳过(不回复、不建工单);
+- **屏蔽**:屏蔽用户(`wms_inbox_block`)/ 屏蔽群(`is_blocked=1`)→ 跳过处理;
+- **express 群**:函数照常执行(如 `handleExpressFeedback`),但**不回信**;
+- **幂等回执**:`sys:ack:{ext_id}` 保证同一入站消息只产生一条出站回执;
+- **多条回复**:引擎返回数组时逐条出站,`ext_id` 追加 `:r0/:r1` 避免唯一键冲突;
+- **渠道校正**:回执 `ext_data.source` 按群 ID 格式校正(`@chatroom→wx`、纯数字→qiwe),防止投递到错误渠道。
+
+### 6.4 数据层已知状态(2026-09-17 已修复)
+
+1. ✅ `change_carrier`(换快递)已补 `express_name` 取号规则关联(迁移 `20260917130000`),
+ "改快递 {单号} 圆通" 可完整组装 `keyword + express`;
+2. ✅ 关键词表已补 `intercept`(拦截/退回/召回/追回/取消快递)与 `pickup`(揽收/上门取件/取件/退货取件)共 9 条;
+3. ⚠️ `wrong_sku`/`quality_issue` 无群白名单关联行(预期内,引擎白名单过滤后跳过)。
+
+---
+
+## 7. v2 链路测试步骤(本地)
+
+> v1 链路不需要测试(分叉 else 分支原样保留)。以下步骤专测 v2。
+
+### 7.1 前置:准备好一个 v2 开启的测试群
+
+```sql
+-- 1) 确保群存在(可由首次推送自动登记,或手动插入)
+-- 2) 配置群类型 + 开关(管理接口未上线前用 SQL)
+UPDATE wms_inbox_group
+SET group_type='store', sub_type='after_sales',
+ store_id={货主ID}, ai_enabled=1, template_reply_enabled=1
+WHERE group_id='{测试群ID}' AND warehouse_id={仓库ID};
+```
+
+v2 链路的四个开关缺一不可:`group_type` 非空 → `ai_enabled=1` → `template_reply_enabled=1`
+→ 消息内容命中 v2 关键词。
+
+### 7.2 推送消息并核对(HTTP 入口)
+
+```powershell
+# 1) 推送入站消息:POST /warehouse?method=inbox.push(签名见 1.2)
+# body: {"requestId":"v2-001","content":"破损 SF1234567890123",
+# "groupId":"{测试群ID}","groupName":"{群名}",
+# "userId":"u1","userName":"测试用户"}
+# 2) 核对入站:
+# SELECT id, direction, ai_thoughts FROM wms_inbox_message
+# WHERE ext_id='api:{appKey}:v2-001';
+# → direction='inbound',ai_thoughts 含 v2 轨迹(action=rule、function=handleStoreFeedback)
+# 3) 核对出站回执:
+# SELECT id, ext_id, direction, content, push_status FROM wms_inbox_message
+# WHERE ext_id='sys:ack:api:{appKey}:v2-001';
+# → direction='outbound'、push_status=2(回调可用时)/3(未配置回调)
+# 4) 核对工单:
+# SELECT after_sale_no, type, sub_type, status FROM wms_after_sale
+# WHERE warehouse_id={仓库ID} ORDER BY id DESC LIMIT 5;
+# → sub_type='damage'、status='pending'
+# 5) 核对出站日志:
+# SELECT method, http_status, result FROM wms_warehouse_log
+# WHERE warehouse_id={仓库ID} AND method='notify.reply' ORDER BY id DESC LIMIT 5;
+```
+
+### 7.3 推荐用例集(全部走 v2 群)
+
+| 用例 | 消息 | 预期 |
+|---|---|---|
+| 破损建单 | `破损 SF1234567890123` | `handleStoreFeedback(issue_type=damaged)` + damage 工单 + 回执 |
+| 改地址 | `改地址 SF1234567890123` | `changeAddr(issue_type=addr)` + change_address 工单 |
+| 换快递 | `改快递 SF1234567890123 圆通` | `changeExpress(keyword=..., express=圆通)` |
+| 拦截 | `拦截 SF1234567890123` | `interceptWaybill` + intercept 工单(`wms_order_express.intercept_status='requested'`) |
+| 揽收 | `上门取件 SF1234567890123` | `requestPickup` + pickup 工单 |
+| 取号失败 | `破损` | 回复引导语,**不建工单** |
+| v2 未命中 | `今天天气怎么样` | 模块接管静默:无函数调用、无回执记录 |
+| 历史消息 | 同破损内容 + `sendTime` 为 30 分钟前 | 静默跳过:无回执、无工单 |
+| 群开关关闭 | 同破损内容 + `template_reply_enabled=0` | 走 v1(不属 v2 测试范围,仅确认分叉生效) |
+
+### 7.4 边界补充
+
+- 快递群(express)命中 v2:函数照常执行,但**不回信**(复用现有回执逻辑);
+- 相同 `requestId` 重复推送:幂等,只处理一次;
+- 回复表 `is_reply=0`:函数执行但静默(可临时插行验证,见 `wms_after_sale_reply`)。
+
+> 补充:egg 测试环境运行 DB 相关测试必须
+> `$env:DISPATCH_FACTORY_TEST_MYSQL='1'; $env:EGG_SERVER_ENV='local'; npx egg-bin test {文件}`
+> (默认 unittest 环境禁用 sequelize 且 `config.default.js` 指向生产库,禁止裸跑)。
diff --git a/app.js b/app.js
index 0223c5a..d45750e 100644
--- a/app.js
+++ b/app.js
@@ -50,6 +50,20 @@ module.exports = app => {
}
});
+ // 售后函数表启动同步(v2 可配置回信引擎):
+ // 把 inbox functions 代码注册表幂等 upsert 到 wms_after_sale_function,
+ // 只增改不删、不覆盖管理端 is_enabled/sort_order;失败仅告警,不影响启动。
+ try {
+ const ctx = app.createAnonymousContext();
+ if (ctx && ctx.service && ctx.service.inbox
+ && ctx.service.inbox.v2 && ctx.service.inbox.v2.functionSync) {
+ const stats = await ctx.service.inbox.v2.functionSync.sync();
+ app.logger.info(`✅ 售后函数表同步完成: ${JSON.stringify(stats)}`);
+ }
+ } catch (error) {
+ app.logger.warn(`⚠️ 售后函数表同步失败(不影响启动): ${error && error.message ? error.message : error}`);
+ }
+
// 验证缓存方法
if (typeof app.setCacheAsync === 'function') {
await app.setCacheAsync('system', 'wms', 10);
diff --git a/app/model/after_sale_function.js b/app/model/after_sale_function.js
new file mode 100644
index 0000000..61bacec
--- /dev/null
+++ b/app/model/after_sale_function.js
@@ -0,0 +1,67 @@
+'use strict';
+
+module.exports = app => {
+ const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
+
+ const AfterSaleFunction = app.model.define('afterSaleFunction', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ function_code: {
+ type: STRING(50),
+ allowNull: false,
+ comment: '处理函数编码(与 inbox functions registry 注册名一致)',
+ },
+ name: {
+ type: STRING(100),
+ allowNull: false,
+ comment: '处理函数名称',
+ },
+ description: {
+ type: STRING(500),
+ allowNull: true,
+ defaultValue: null,
+ comment: '处理函数说明',
+ },
+ is_enabled: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 1,
+ comment: '是否启用:1=启用,0=停用',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '排序值,越小越靠前',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_function',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '售后处理函数表(子类型处理链路)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'function_code' ],
+ name: 'uk_function_code',
+ },
+ ],
+ });
+
+ return AfterSaleFunction;
+};
diff --git a/app/model/after_sale_keyword.js b/app/model/after_sale_keyword.js
new file mode 100644
index 0000000..e0dbbd7
--- /dev/null
+++ b/app/model/after_sale_keyword.js
@@ -0,0 +1,81 @@
+'use strict';
+
+module.exports = app => {
+ const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
+
+ const AfterSaleKeyword = app.model.define('afterSaleKeyword', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ warehouse_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: true,
+ defaultValue: null,
+ comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)',
+ },
+ sub_type_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: false,
+ comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
+ },
+ keyword: {
+ type: STRING(100),
+ allowNull: false,
+ comment: '关键词,命中即映射到对应售后子类型',
+ },
+ is_system: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义',
+ },
+ is_enabled: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 1,
+ comment: '是否启用:1=启用,0=停用',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '匹配优先级,数值小者优先(同长度命中时生效)',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_keyword',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '售后关键词表(关键词 → 售后子类型映射)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'keyword', 'warehouse_id' ],
+ name: 'uk_keyword_warehouse',
+ },
+ {
+ fields: [ 'sub_type_id' ],
+ name: 'idx_sub_type_id',
+ },
+ {
+ fields: [ 'warehouse_id' ],
+ name: 'idx_warehouse_id',
+ },
+ ],
+ });
+
+ return AfterSaleKeyword;
+};
diff --git a/app/model/after_sale_reply.js b/app/model/after_sale_reply.js
new file mode 100644
index 0000000..80ce96d
--- /dev/null
+++ b/app/model/after_sale_reply.js
@@ -0,0 +1,81 @@
+'use strict';
+
+module.exports = app => {
+ const { STRING, BIGINT, TINYINT, TEXT, DATE } = app.Sequelize;
+
+ const AfterSaleReply = app.model.define('afterSaleReply', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ warehouse_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: true,
+ defaultValue: null,
+ comment: '仓库ID(NULL=系统级默认回复;非NULL=仓库级自定义回复,覆盖系统级)',
+ },
+ sub_type_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: false,
+ comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
+ },
+ reply: {
+ type: TEXT,
+ allowNull: false,
+ comment: '自定义回复文案(支持换行,可含占位符)',
+ },
+ is_reply: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 1,
+ comment: '是否回复:1=命中后回复,0=静默不回复',
+ },
+ no_number_hint: {
+ type: STRING(500),
+ allowNull: true,
+ defaultValue: null,
+ comment: '未取到单据号时的引导语(如:请提供运单号;为空则用默认引导语)',
+ },
+ is_enabled: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 1,
+ comment: '是否启用:1=启用,0=停用(停用视为未设置,回退系统级)',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_reply',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '售后自定义回复表(仓库级覆盖系统级)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'warehouse_id', 'sub_type_id' ],
+ name: 'uk_warehouse_sub_type',
+ },
+ {
+ fields: [ 'sub_type_id' ],
+ name: 'idx_sub_type_id',
+ },
+ {
+ fields: [ 'is_enabled' ],
+ name: 'idx_is_enabled',
+ },
+ ],
+ });
+
+ return AfterSaleReply;
+};
diff --git a/app/model/after_sale_sub_type.js b/app/model/after_sale_sub_type.js
new file mode 100644
index 0000000..407c75d
--- /dev/null
+++ b/app/model/after_sale_sub_type.js
@@ -0,0 +1,86 @@
+'use strict';
+
+module.exports = app => {
+ const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
+
+ const AfterSaleSubType = app.model.define('afterSaleSubType', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ warehouse_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: true,
+ defaultValue: null,
+ comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义)',
+ },
+ type: {
+ type: STRING(20),
+ allowNull: false,
+ comment: '所属售后类型编码(对应 wms_after_sale_type.type)',
+ },
+ sub_type: {
+ type: STRING(50),
+ allowNull: false,
+ comment: '售后子类型编码(与 wms_after_sale.sub_type 对应)',
+ },
+ name: {
+ type: STRING(50),
+ allowNull: false,
+ comment: '售后子类型名称',
+ },
+ is_system: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '是否系统级:1=系统级(不可编辑/删除),0=仓库自定义',
+ },
+ is_enabled: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 1,
+ comment: '是否启用:1=启用,0=停用',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '排序值,越小越靠前',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_sub_type',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '售后子类型表(系统级 + 仓库自定义)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'type', 'sub_type', 'warehouse_id' ],
+ name: 'uk_type_subtype_warehouse',
+ },
+ {
+ fields: [ 'warehouse_id' ],
+ name: 'idx_warehouse_id',
+ },
+ {
+ fields: [ 'is_system' ],
+ name: 'idx_is_system',
+ },
+ ],
+ });
+
+ return AfterSaleSubType;
+};
diff --git a/app/model/after_sale_sub_type_function.js b/app/model/after_sale_sub_type_function.js
new file mode 100644
index 0000000..5c33ec1
--- /dev/null
+++ b/app/model/after_sale_sub_type_function.js
@@ -0,0 +1,59 @@
+'use strict';
+
+module.exports = app => {
+ const { BIGINT, INTEGER, DATE } = app.Sequelize;
+
+ const AfterSaleSubTypeFunction = app.model.define('afterSaleSubTypeFunction', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ sub_type_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: false,
+ comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
+ },
+ function_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: false,
+ comment: '处理函数ID(关联 wms_after_sale_function.id)',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '同子类型下处理函数执行顺序,数值小者优先',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_sub_type_function',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '售后子类型-处理函数关联表(多对多)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'sub_type_id', 'function_id' ],
+ name: 'uk_sub_type_function',
+ },
+ {
+ fields: [ 'function_id' ],
+ name: 'idx_function_id',
+ },
+ ],
+ });
+
+ return AfterSaleSubTypeFunction;
+};
diff --git a/app/model/after_sale_sub_type_group.js b/app/model/after_sale_sub_type_group.js
new file mode 100644
index 0000000..909f1a9
--- /dev/null
+++ b/app/model/after_sale_sub_type_group.js
@@ -0,0 +1,70 @@
+'use strict';
+
+module.exports = app => {
+ const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
+
+ const AfterSaleSubTypeGroup = app.model.define('afterSaleSubTypeGroup', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ sub_type_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: false,
+ comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
+ },
+ group_type: {
+ type: STRING(20),
+ allowNull: false,
+ comment: '群类型:store=货主群 / warehouse=仓库群 / express=快递群',
+ },
+ sub_group: {
+ type: STRING(20),
+ allowNull: false,
+ comment: '群子类型:store(after_sales/finance/receiving)、warehouse(customer_service/...)、express(pickup/after_sales)',
+ },
+ is_system: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '是否系统预设关联:1=系统级子类型默认分配(锁定不可改),0=自定义',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '排序值,越小越靠前',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_sub_type_group',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '群类型-售后子类型关联表(多对多)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'sub_type_id', 'group_type', 'sub_group' ],
+ name: 'uk_sub_type_group',
+ },
+ {
+ fields: [ 'group_type', 'sub_group' ],
+ name: 'idx_group_type',
+ },
+ ],
+ });
+
+ return AfterSaleSubTypeGroup;
+};
diff --git a/app/model/after_sale_sub_type_rule.js b/app/model/after_sale_sub_type_rule.js
new file mode 100644
index 0000000..067e59d
--- /dev/null
+++ b/app/model/after_sale_sub_type_rule.js
@@ -0,0 +1,59 @@
+'use strict';
+
+module.exports = app => {
+ const { BIGINT, INTEGER, DATE } = app.Sequelize;
+
+ const AfterSaleSubTypeRule = app.model.define('afterSaleSubTypeRule', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ sub_type_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: false,
+ comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
+ },
+ number_rule_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: false,
+ comment: '取号规则ID(关联 wms_inbox_number_rule.id)',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '同一子类型下规则的提取顺序,数值小者优先',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_sub_type_rule',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '售后子类型-取号规则关联表(多对多)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'sub_type_id', 'number_rule_id' ],
+ name: 'uk_sub_type_rule',
+ },
+ {
+ fields: [ 'number_rule_id' ],
+ name: 'idx_number_rule_id',
+ },
+ ],
+ });
+
+ return AfterSaleSubTypeRule;
+};
diff --git a/app/model/after_sale_type.js b/app/model/after_sale_type.js
new file mode 100644
index 0000000..5dae9d5
--- /dev/null
+++ b/app/model/after_sale_type.js
@@ -0,0 +1,81 @@
+'use strict';
+
+module.exports = app => {
+ const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
+
+ const AfterSaleType = app.model.define('afterSaleType', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ warehouse_id: {
+ type: BIGINT(20).UNSIGNED,
+ allowNull: true,
+ defaultValue: null,
+ comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义)',
+ },
+ type: {
+ type: STRING(20),
+ allowNull: false,
+ comment: '售后类型编码:order/receiving/entry/stockout,仓库自定义可自定义编码',
+ },
+ name: {
+ type: STRING(50),
+ allowNull: false,
+ comment: '售后类型名称',
+ },
+ is_system: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '是否系统级:1=系统级(不可编辑/删除),0=仓库自定义',
+ },
+ is_enabled: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 1,
+ comment: '是否启用:1=启用,0=停用',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '排序值,越小越靠前',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_after_sale_type',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '售后类型表(系统级 + 仓库自定义)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'type', 'warehouse_id' ],
+ name: 'uk_type_warehouse',
+ },
+ {
+ fields: [ 'warehouse_id' ],
+ name: 'idx_warehouse_id',
+ },
+ {
+ fields: [ 'is_system' ],
+ name: 'idx_is_system',
+ },
+ ],
+ });
+
+ return AfterSaleType;
+};
diff --git a/app/model/inbox_arrival_register.js b/app/model/inbox_arrival_register.js
new file mode 100644
index 0000000..2fef56a
--- /dev/null
+++ b/app/model/inbox_arrival_register.js
@@ -0,0 +1,71 @@
+'use strict';
+
+/**
+ * 到货登记 Model。
+ * 货主/仓库群发送"到货+车牌号"时,AI 提取车牌号并登记,
+ * 记录货主ID、仓库ID、登记时间(created_at)、车牌号。
+ * @param {Object} app Egg.js Application 实例。
+ * @return {Object} Sequelize Model 定义。
+ */
+module.exports = app => {
+ const { BIGINT, STRING } = app.Sequelize;
+
+ const InboxArrivalRegister = app.model.define('inbox_arrival_register', {
+ id: {
+ type: BIGINT.UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ allowNull: false,
+ comment: '主键ID',
+ },
+ warehouse_id: {
+ type: BIGINT.UNSIGNED,
+ allowNull: false,
+ comment: '仓库ID(数据隔离维度)',
+ },
+ store_id: {
+ type: BIGINT.UNSIGNED,
+ allowNull: true,
+ comment: '货主ID(仓库群登记时无货主,允许为空)',
+ },
+ license_plate: {
+ type: STRING(20),
+ allowNull: false,
+ comment: '车牌号',
+ },
+ consumed: {
+ type: app.Sequelize.TINYINT(1),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '是否已消费(离场登记)0=未消费 1=已消费',
+ },
+ consumed_at: {
+ type: app.Sequelize.DATE,
+ allowNull: true,
+ comment: '消费时间(离场时间)',
+ },
+ created_at: {
+ type: app.Sequelize.DATE,
+ allowNull: false,
+ defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
+ comment: '登记时间',
+ },
+ updated_at: {
+ type: app.Sequelize.DATE,
+ allowNull: false,
+ defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_inbox_arrival_register',
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ // 表无 deleted_at 列,必须显式关闭全局 define 的 paranoid 默认值,
+ // 否则 findAll/findOne 会拼出 deleted_at 字段导致 Unknown column 报错
+ paranoid: false,
+ comment: '到货登记表(货主ID、仓库ID、登记时间、车牌号)',
+ });
+
+ return InboxArrivalRegister;
+};
diff --git a/app/model/inbox_group.js b/app/model/inbox_group.js
index 63e6cd3..2381ab5 100644
--- a/app/model/inbox_group.js
+++ b/app/model/inbox_group.js
@@ -70,6 +70,12 @@ module.exports = app => {
defaultValue: 0,
comment: '是否启用AI自动回复: 0=关闭 1=开启',
},
+ template_reply_enabled: {
+ type: TINYINT(1),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)',
+ },
express_interfaces: {
type: STRING(500),
allowNull: true,
diff --git a/app/model/inbox_message.js b/app/model/inbox_message.js
index 73873b5..151a3b4 100644
--- a/app/model/inbox_message.js
+++ b/app/model/inbox_message.js
@@ -107,6 +107,11 @@ module.exports = app => {
allowNull: true,
comment: '外部透传数据,外部传入任意JSON,WMS不解析,回信时原样返回',
},
+ extend_props: {
+ type: JSON_TYPE,
+ allowNull: true,
+ comment: '回执扩展属性(notify.reply 的 extend_props),重推时原样带回',
+ },
flags: {
type: JSON_TYPE,
allowNull: true,
diff --git a/app/model/inbox_number_rule.js b/app/model/inbox_number_rule.js
new file mode 100644
index 0000000..d7b244a
--- /dev/null
+++ b/app/model/inbox_number_rule.js
@@ -0,0 +1,64 @@
+'use strict';
+
+module.exports = app => {
+ const { STRING, INTEGER, BIGINT, DATE } = app.Sequelize;
+
+ const InboxNumberRule = app.model.define('inboxNumberRule', {
+ id: {
+ type: BIGINT(20).UNSIGNED,
+ primaryKey: true,
+ autoIncrement: true,
+ comment: '主键',
+ },
+ name: {
+ type: STRING(100),
+ allowNull: false,
+ comment: '规则名称,如:运单号提取/收货单号提取/平台订单号提取',
+ },
+ target: {
+ type: STRING(50),
+ allowNull: false,
+ comment: '提取目标类型:waybill_no/receiving_no/entry_order_no/stockout_no/order_no/source_order_codes/express_name/plate_no',
+ },
+ regexp: {
+ type: STRING(500),
+ allowNull: false,
+ comment: '取号正则(JS 正则源字符串,不含首尾斜杠,支持全局匹配)',
+ },
+ sort_order: {
+ type: INTEGER(11),
+ allowNull: false,
+ defaultValue: 0,
+ comment: '规则尝试顺序,数值小者优先',
+ },
+ created_at: {
+ type: DATE,
+ comment: '创建时间',
+ },
+ updated_at: {
+ type: DATE,
+ comment: '更新时间',
+ },
+ }, {
+ tableName: 'wms_inbox_number_rule',
+ underscored: true,
+ timestamps: true,
+ createdAt: 'created_at',
+ updatedAt: 'updated_at',
+ paranoid: false,
+ comment: '取号规则表(站内信消息中正则提取单据号)',
+ indexes: [
+ {
+ unique: true,
+ fields: [ 'name' ],
+ name: 'uk_name',
+ },
+ {
+ fields: [ 'target' ],
+ name: 'idx_target',
+ },
+ ],
+ });
+
+ return InboxNumberRule;
+};
diff --git a/app/service/inbox/ai.js b/app/service/inbox/ai.js
index 7c34508..b68c235 100644
--- a/app/service/inbox/ai.js
+++ b/app/service/inbox/ai.js
@@ -359,13 +359,14 @@ ${historyContext}
ctx.logger.info(`[inbox ai] 执行 ${fnName}: ${JSON.stringify(lastFunctionResult)}`);
// 函数携带模板消息(direct_reply=true)→ 直接作为最终回复,不再交由 AI 改写
- const directReply = lastFunctionResult
+ // 允许 message 为空字符串(如开门:靠 extend_props 指令驱动,文案为空)
+ const hasDirectReply = !!(lastFunctionResult
&& lastFunctionResult.data
- && lastFunctionResult.data.direct_reply === true
- && lastFunctionResult.data.message
- ? String(lastFunctionResult.data.message)
+ && lastFunctionResult.data.direct_reply === true);
+ const directReply = hasDirectReply
+ ? String(lastFunctionResult.data.message || '')
: '';
- if (directReply) {
+ if (hasDirectReply) {
ctx.logger.info(`[inbox ai] 函数 ${fnName} 返回模板消息,直接回复 (length=${directReply.length})`);
finalReply = directReply;
break;
@@ -406,13 +407,13 @@ ${historyContext}
}
}
- // 无回复的兜底
- if (!finalReply && lastFunctionResult) {
+ // 无回复的兜底(finalReply 为空串时保留,不覆盖——开门等指令允许空文案回执)
+ if ((finalReply === null || finalReply === undefined) && lastFunctionResult) {
finalReply = lastFunctionResult?.data?.message
|| lastFunctionResult?.data?.greeting
|| (lastFunctionResult?.success !== false ? '操作已完成' : lastFunctionResult?.error || '处理完成');
}
- if (!finalReply) {
+ if (finalReply === null || finalReply === undefined) {
finalReply = '抱歉,暂时无法处理您的请求';
}
diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js
index e8d1115..e39cee8 100644
--- a/app/service/inbox/functions.js
+++ b/app/service/inbox/functions.js
@@ -6,6 +6,20 @@ const Service = require('egg').Service;
const { GROUP } = require('./groups');
const { pickNoticeTimeOrderIds } = require('../../lib/intercept_time');
+/**
+ * 提取车牌号(与 wms_inbox_number_rule 车牌取号规则同版:支持蓝/黄牌、新能源绿牌、
+ * 挂车、警/学/港澳牌及 ·/· 分隔符)。
+ * 省份简称兼容简体与异体写法(如 粤/粵)。
+ * 只取第一个匹配,无匹配返回空字符串。
+ * @param {string} text 消息正文。
+ * @return {string} 车牌号。
+ */
+function extractLicensePlate(text) {
+ const raw = String(text || '');
+ const m = raw.match(/[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤粵青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])/);
+ return m ? m[0] : '';
+}
+
/**
* 站内信函数注册表。
* 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。
@@ -4014,6 +4028,309 @@ class InboxFunctionsService extends Service {
}
},
});
+
+ this.register('openDoor', {
+ description: '开门:仓库群收到"开门"指令时调用,触发大门开启动作。回复内容为空,由 extend_props 指令驱动开门',
+ params: {},
+ groups: [ GROUP.BOUND_WAREHOUSE ],
+ weight: 90,
+ keywords: [ '开门' ],
+ handler: async (params = {}) => {
+ const { ctx } = this;
+ void params;
+ ctx.logger.info('[inbox functions] 执行开门指令');
+ return {
+ success: true,
+ data: {
+ message: '',
+ direct_reply: true,
+ extend_props: { do: 'openDoor' },
+ },
+ };
+ },
+ });
+
+ this.register('registerLicensePlate', {
+ description: '到货登记:从当前消息中提取车牌号并登记。货主/仓库群发送"到货+车牌号"时调用',
+ params: {},
+ groups: [ GROUP.BOUND_STORE, GROUP.BOUND_WAREHOUSE ],
+ weight: 90,
+ keywords: [ '到货' ],
+ handler: async (params = {}) => {
+ const { ctx } = this;
+ void params;
+
+ // 读取原消息内容提取车牌号
+ let originalText = '';
+ try {
+ const mid = ctx.inboxContext?.inbound_message_id;
+ if (mid) {
+ const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true });
+ if (m && m.content) originalText = String(m.content);
+ }
+ } catch (e) { /* ignore */ }
+
+ const carnum = extractLicensePlate(originalText);
+ if (!carnum) {
+ return {
+ success: false,
+ error: '未识别到车牌号,请发送:到货+车牌号\n例:到货 粤A12345',
+ };
+ }
+
+ // 写库登记(失败不阻塞回执,仅告警)
+ try {
+ await ctx.model.InboxArrivalRegister.create({
+ warehouse_id: Number(ctx.inboxContext?.warehouse_id) || 0,
+ store_id: Number(ctx.inboxContext?.store_id) || null,
+ license_plate: carnum,
+ });
+ } catch (e) {
+ ctx.logger.warn(`[inbox functions] 到货登记写库失败: ${e.message}`);
+ }
+
+ ctx.logger.info(`[inbox functions] 到货登记车牌: ${carnum}`);
+ return {
+ success: true,
+ data: {
+ message: `车牌${carnum}已登记,请在6小时内入场,超时请重新登记`,
+ direct_reply: true,
+ carnum,
+ extend_props: { do: 'registerLicensePlate', value: carnum },
+ },
+ };
+ },
+ });
+
+ this.register('departure', {
+ description: '离场登记:消息含"离场"时调用,提取车牌号,查6小时内未消费的到货登记,标记消费并通知对应货主(优先收货群,其次售后群,发送失败换下一个群);当前消息不回执',
+ params: {},
+ groups: [ GROUP.BOUND_WAREHOUSE ],
+ weight: 90,
+ keywords: [ '离场' ],
+ handler: async (params = {}) => {
+ const { ctx } = this;
+ void params;
+
+ // 读取原消息内容提取车牌号
+ let originalText = '';
+ try {
+ const mid = ctx.inboxContext?.inbound_message_id;
+ if (mid) {
+ const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true });
+ if (m && m.content) originalText = String(m.content);
+ }
+ } catch (e) { /* ignore */ }
+
+ const carnum = extractLicensePlate(originalText);
+ if (!carnum) {
+ return {
+ success: false,
+ error: '未识别到车牌号,请发送:车牌号+离场\n例:粤A12345离场',
+ };
+ }
+
+ const warehouseId = Number(ctx.inboxContext?.warehouse_id) || 0;
+ if (!warehouseId) {
+ return { success: false, error: '无法获取仓库信息' };
+ }
+
+ const { Op } = ctx.app.Sequelize;
+
+ // 第一步:查6小时内未消费的到货登记
+ const record = await ctx.model.InboxArrivalRegister.findOne({
+ attributes: [ 'id', 'store_id', 'license_plate' ],
+ where: {
+ warehouse_id: warehouseId,
+ license_plate: carnum,
+ consumed: 0,
+ created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') },
+ },
+ order: [[ 'created_at', 'DESC' ]],
+ raw: true,
+ });
+ if (!record) {
+ // 区分提示:6小时内已消费过 → 重复离场;否则无有效登记
+ const consumedRecord = await ctx.model.InboxArrivalRegister.findOne({
+ attributes: [ 'id' ],
+ where: {
+ warehouse_id: warehouseId,
+ license_plate: carnum,
+ consumed: 1,
+ created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') },
+ },
+ raw: true,
+ });
+ if (consumedRecord) {
+ // 已离过场:静默处理,不回执不通知
+ ctx.logger.info(`[inbox functions] 离场登记: 车牌=${carnum} 已离过场,静默忽略`);
+ return {
+ success: true,
+ data: { carnum, consumed: false, duplicate: true },
+ };
+ }
+ return {
+ success: false,
+ error: `未查询到车牌 ${carnum} 6小时内的有效登记,离场失败`,
+ };
+ }
+
+ // 第二步:乐观标记消费(防并发重复离场)
+ const [ affected ] = await ctx.model.InboxArrivalRegister.update(
+ { consumed: 1, consumed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP') },
+ { where: { id: record.id, consumed: 0 } }
+ );
+ if (affected !== 1) {
+ // 并发重复离场:静默处理,不回执不通知
+ ctx.logger.info(`[inbox functions] 离场登记: 车牌=${carnum} 并发重复离场,静默忽略`);
+ return {
+ success: true,
+ data: { carnum, consumed: false, duplicate: true },
+ };
+ }
+
+ // 第三步:通知对应货主(优先收货群,其次售后群,发送失败换下一个群)
+ const notifyResult = await this.notifyStoreReceiving(
+ warehouseId, record.store_id,
+ `${carnum}已卸货离场,本次收货完成,在清点中,请耐心等待清点结果,天豹云仓竭诚为您服务。`
+ );
+ const pushed = notifyResult.pushed;
+ const pushedGroup = notifyResult.pushedGroup;
+
+ ctx.logger.info(
+ `[inbox functions] 离场登记: 车牌=${carnum} 消费成功 ` +
+ `store_id=${record.store_id || '-'} pushed=${pushed} group=${pushedGroup || '-'}`
+ );
+
+ // 当前消息不回执(data 不含 message/extend_props → 规则引擎无回复)
+ return {
+ success: true,
+ data: { carnum, consumed: true, pushed, pushed_group: pushedGroup },
+ };
+ },
+ });
+
+ this.register('enter', {
+ description: '进场登记:消息含"进场"时调用,提取车牌号,查6小时内未消费的到货登记,通知对应货主收货群"车辆已入场,等待卸货"(优先收货群,其次售后群,发送失败换下一个群);当前消息不回执',
+ params: {},
+ groups: [ GROUP.BOUND_WAREHOUSE ],
+ weight: 90,
+ keywords: [ '进场' ],
+ handler: async (params = {}) => {
+ const { ctx } = this;
+ void params;
+
+ // 读取原消息内容提取车牌号
+ let originalText = '';
+ try {
+ const mid = ctx.inboxContext?.inbound_message_id;
+ if (mid) {
+ const m = await ctx.model.InboxMessage.findByPk(mid, { attributes: [ 'content' ], raw: true });
+ if (m && m.content) originalText = String(m.content);
+ }
+ } catch (e) { /* ignore */ }
+
+ const carnum = extractLicensePlate(originalText);
+ if (!carnum) {
+ return {
+ success: false,
+ error: '未识别到车牌号,请发送:车牌号+进场\n例:粤A12345进场',
+ };
+ }
+
+ const warehouseId = Number(ctx.inboxContext?.warehouse_id) || 0;
+ if (!warehouseId) {
+ return { success: false, error: '无法获取仓库信息' };
+ }
+
+ const { Op } = ctx.app.Sequelize;
+
+ // 查6小时内未消费的到货登记(进场不改消费状态,离场时才消费)
+ const record = await ctx.model.InboxArrivalRegister.findOne({
+ attributes: [ 'id', 'store_id', 'license_plate' ],
+ where: {
+ warehouse_id: warehouseId,
+ license_plate: carnum,
+ consumed: 0,
+ created_at: { [Op.gte]: ctx.app.Sequelize.literal('DATE_SUB(NOW(), INTERVAL 6 HOUR)') },
+ },
+ order: [[ 'created_at', 'DESC' ]],
+ raw: true,
+ });
+ if (!record) {
+ return {
+ success: false,
+ error: `未查询到车牌 ${carnum} 6小时内的有效登记,请先登记到货`,
+ };
+ }
+
+ // 通知对应货主(优先收货群,其次售后群,发送失败换下一个群)
+ const notifyResult = await this.notifyStoreReceiving(
+ warehouseId, record.store_id,
+ `车辆${carnum}已入场,等待卸货`
+ );
+ const pushed = notifyResult.pushed;
+ const pushedGroup = notifyResult.pushedGroup;
+
+ ctx.logger.info(
+ `[inbox functions] 进场登记: 车牌=${carnum} ` +
+ `store_id=${record.store_id || '-'} pushed=${pushed} group=${pushedGroup || '-'}`
+ );
+
+ // 当前消息不回执(data 不含 message/extend_props → 规则引擎无回复)
+ return {
+ success: true,
+ data: { carnum, entered: true, pushed, pushed_group: pushedGroup },
+ };
+ },
+ });
+ }
+
+ /**
+ * 通知货主(优先收货群 receiving,其次售后群 after_sales,发送失败换下一个群)。
+ * @param {number} warehouseId 仓库ID。
+ * @param {number|null} storeId 货主ID(为空时直接返回未推送)。
+ * @param {string} content 通知内容。
+ * @return {Promise<{pushed: boolean, pushedGroup: string}>} 推送结果。
+ */
+ async notifyStoreReceiving(warehouseId, storeId, content) {
+ const { ctx } = this;
+ let pushed = false;
+ let pushedGroup = '';
+ if (!storeId) return { pushed, pushedGroup };
+
+ try {
+ const groupSvc = ctx.service.systems.inbox.group;
+ const [ receivingGroups, afterSalesGroups ] = await Promise.all([
+ groupSvc.findStoreGroups({ storeIds: [ storeId ], warehouseId, subTypes: [ 'receiving' ] }),
+ groupSvc.findStoreGroups({ storeIds: [ storeId ], warehouseId, subTypes: [ 'after_sales' ] }),
+ ]);
+ const candidates = [ ...receivingGroups, ...afterSalesGroups ];
+ for (const g of candidates) {
+ if (!g.group_id) continue;
+ const ok = await ctx.service.inbox.processor.writeOutboundReply({
+ warehouse_id: warehouseId,
+ ext_id: `sys:store-notify:${warehouseId}:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`,
+ parent_id: null,
+ ext_data: g.ext_data || null,
+ group_id: g.group_id,
+ user_id: '',
+ group_name: g.group_name || '',
+ user_name: '',
+ store_id: g.store_id || null,
+ }, content, 'system');
+ if (ok) {
+ pushed = true;
+ pushedGroup = g.group_name || g.group_id;
+ break;
+ }
+ ctx.logger.warn(`[inbox functions] 通知货主群 ${g.group_name || g.group_id} 推送失败,尝试下一个`);
+ }
+ } catch (e) {
+ ctx.logger.warn(`[inbox functions] 通知货主失败: ${e.message}`);
+ }
+
+ return { pushed, pushedGroup };
}
/**
diff --git a/app/service/inbox/message.js b/app/service/inbox/message.js
index 0565488..8703ae8 100644
--- a/app/service/inbox/message.js
+++ b/app/service/inbox/message.js
@@ -552,7 +552,7 @@ class InboxMessageService extends Service {
user_name: record.user_name || '',
ext_data: record.ext_data || null,
reuse_message_id: Number(record.id) || 0,
- }, record.content || '', hasUser ? 'ai_reply' : 'system');
+ }, record.content || '', hasUser ? 'ai_reply' : 'system', record.extend_props || null);
}
/**
@@ -603,7 +603,7 @@ class InboxMessageService extends Service {
attributes: [
'id', 'warehouse_id', 'ext_id', 'parent_id',
'group_id', 'group_name', 'user_id', 'user_name',
- 'ext_data', 'content',
+ 'ext_data', 'content', 'extend_props',
],
order: [[ 'created_at', 'ASC' ], [ 'id', 'ASC' ]],
limit,
@@ -613,9 +613,11 @@ class InboxMessageService extends Service {
const summary = { scanned: rows.length, retried: 0, succeeded: 0, failed: 0, skipped: 0 };
for (const row of rows) {
- if (!(Number(row.warehouse_id) > 0) || !row.group_id || !row.group_name || !row.content) {
+ // 空文案但含 extend_props 的回执(如开门指令)可重放;两者皆空才跳过
+ if (!(Number(row.warehouse_id) > 0) || !row.group_id || !row.group_name
+ || (!row.content && !row.extend_props)) {
summary.skipped++;
- ctx.logger.warn(`[inbox] 自动重推跳过消息 id=${row.id}(缺少 warehouse_id/group_id/group_name/content,无法重放)`);
+ ctx.logger.warn(`[inbox] 自动重推跳过消息 id=${row.id}(缺少 warehouse_id/group_id/group_name/content+extend_props,无法重放)`);
continue;
}
diff --git a/app/service/inbox/processor.js b/app/service/inbox/processor.js
index 76f19df..7a18b75 100644
--- a/app/service/inbox/processor.js
+++ b/app/service/inbox/processor.js
@@ -23,7 +23,7 @@ class InboxProcessorService extends Service {
* @param {string} groupId 外部群ID
* @param {number} warehouseId 仓库ID
* @param {Object|null} msgExtData 入站消息的 ext_data
- * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, ext_data: Object|null}>} 群类型/子类型/AI开关/扩展数据
+ * @return {Promise<{group_type: string, sub_type: string, ai_enabled: number, template_reply_enabled: number, ext_data: Object|null}>} 群类型/子类型/AI开关/模板回信开关/扩展数据
*/
async _loadGroupInfo(groupId, warehouseId, msgExtData) {
const { ctx } = this;
@@ -31,7 +31,7 @@ class InboxProcessorService extends Service {
let group = null;
try {
group = await ctx.model.InboxGroup.findOne({
- attributes: [ 'group_type', 'sub_type', 'ai_enabled', 'ext_data' ],
+ attributes: [ 'group_type', 'sub_type', 'ai_enabled', 'template_reply_enabled', 'ext_data' ],
where: { group_id: groupId, warehouse_id: warehouseId },
raw: true,
});
@@ -43,6 +43,7 @@ class InboxProcessorService extends Service {
group_type: (group && group.group_type) || '',
sub_type: (group && group.sub_type) || '',
ai_enabled: group ? group.ai_enabled : 0,
+ template_reply_enabled: group ? group.template_reply_enabled : 0,
ext_data: (group && group.ext_data) || null,
};
@@ -196,6 +197,7 @@ class InboxProcessorService extends Service {
ctx.inboxContext.group_type = info.group_type;
ctx.inboxContext.sub_type = info.sub_type;
ctx.inboxContext.ai_enabled = info.ai_enabled;
+ ctx.inboxContext.template_reply_enabled = info.template_reply_enabled;
ctx.inboxContext.group_ext_data = info.ext_data;
} else {
ctx.inboxContext.ai_enabled = 0;
@@ -219,16 +221,9 @@ class InboxProcessorService extends Service {
// 5.1 加载屏蔽用户列表,注入上下文供 AI 判断真人接管
if (!ctx.inboxContext._blockedUserIds) {
try {
- const { InboxBlock } = ctx.model;
- const rows = await InboxBlock.findAll({
- attributes: [ 'user_id' ],
- where: { warehouse_id: warehouseId },
- raw: true,
- });
- ctx.inboxContext._blockedUserIds = new Set(
- rows.map(r => String(r.user_id || '').trim()).filter(Boolean)
- );
+ ctx.inboxContext._blockedUserIds = await this.loadBlockedUserIds(warehouseId);
} catch (e) {
+ ctx.logger.warn(`[inbox processor] 加载屏蔽用户列表失败: ${e.message}`);
ctx.inboxContext._blockedUserIds = new Set();
}
}
@@ -237,7 +232,13 @@ class InboxProcessorService extends Service {
ctx.inboxContext.inbound_message_id = parentId || null;
// 6. 关键词规则引擎(主回复路径,不走 AI,节省推理费用)
- const ruleResult = await ctx.service.inbox.rules.handle(String(data.content || '').trim());
+ // v2 分叉:群开启模板回信引擎(template_reply_enabled=1)时走 v2 可配置引擎,
+ // 模块接管模式——v2 未命中直接静默返回,不再走 v1 规则与 AI 兜底。
+ const text = String(data.content || '').trim();
+ const v2Enabled = ctx.inboxContext.template_reply_enabled === 1;
+ const ruleResult = v2Enabled
+ ? await ctx.service.inbox.v2.rules.handle(text)
+ : await ctx.service.inbox.rules.handle(text);
if (ruleResult.handled) {
// 记录规则命中轨迹到入站消息,便于排查
if (ruleResult.thoughts && ruleResult.thoughts.length > 0) {
@@ -256,9 +257,11 @@ class InboxProcessorService extends Service {
return;
}
- if (ruleResult.reply) {
- // 支持多条回复(如查退回多单号):逐条独立回信
- const replies = Array.isArray(ruleResult.reply) ? ruleResult.reply : [ ruleResult.reply ];
+ if (ruleResult.reply || (ruleResult.result && ruleResult.result.data && ruleResult.result.data.extend_props)) {
+ // 支持多条回复(如查退回多单号):逐条独立回信;
+ // 也支持空文案回执(如开门:content 为空,仅靠 extend_props 指令驱动)
+ const ruleExtendProps = ruleResult.result && ruleResult.result.data && ruleResult.result.data.extend_props;
+ const replies = Array.isArray(ruleResult.reply) ? ruleResult.reply : [ ruleResult.reply || '' ];
ctx.logger.info(
`[inbox processor] 规则引擎处理完成 ext_id=${extId} ` +
`fn=${ruleResult.fn || '-'} key=${ruleResult.matchedKey || '-'} replies=${replies.length}`
@@ -281,7 +284,7 @@ class InboxProcessorService extends Service {
user_id: ctx.inboxContext?.user_id || data.user_id || null,
group_name: ctx.inboxContext?.group_name || data.group_name || null,
user_name: ctx.inboxContext?.user_name || data.user_name || null,
- }, replyContent, 'rule_reply');
+ }, replyContent, 'rule_reply', ruleExtendProps);
}
} else {
ctx.logger.info(`[inbox processor] 规则已执行但无回复内容 ext_id=${extId} fn=${ruleResult.fn || '-'}`);
@@ -289,6 +292,15 @@ class InboxProcessorService extends Service {
return;
}
+ // 6.1 v2 模块接管:开启模板回信引擎的群,未命中后直接静默,不走 v1 规则与 AI 兜底
+ if (v2Enabled) {
+ ctx.logger.info(
+ `[inbox processor] v2 引擎未命中,静默(模板回信群不走 v1/AI) ext_id=${extId} ` +
+ `content=${text.slice(0, 80)}`
+ );
+ return;
+ }
+
// 6.5 AI 兜底(默认关闭,config.inbox.aiFallback=true 时启用)
const aiFallback = !!(this.app.config.inbox && this.app.config.inbox.aiFallback);
if (!aiFallback) {
@@ -324,7 +336,9 @@ class InboxProcessorService extends Service {
return;
}
- const replyContent = aiResult.reply || '已处理完成';
+ const replyContent = typeof aiResult.reply === 'string' ? aiResult.reply : '已处理完成';
+ const aiExtendProps = aiResult.functionResult
+ && aiResult.functionResult.data && aiResult.functionResult.data.extend_props;
ctx.logger.info(
`[inbox processor] AI 处理完成 ext_id=${extId} ` +
`function=${aiResult.functionName || 'direct'} reply_length=${replyContent.length}`
@@ -358,7 +372,7 @@ class InboxProcessorService extends Service {
user_id: ctx.inboxContext?.user_id || data.user_id || null,
group_name: ctx.inboxContext?.group_name || data.group_name || null,
user_name: ctx.inboxContext?.user_name || data.user_name || null,
- }, replyContent);
+ }, replyContent, 'ai_reply', aiExtendProps);
} catch (error) {
ctx.logger.warn(`[inbox processor] API 回执失败 ext_id=${extId}: ${error.message}`);
}
@@ -471,9 +485,11 @@ class InboxProcessorService extends Service {
* @param {string} replyContent 回复内容。
* @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error / system。
* system 类型不要求 user_id/user_name。
- * @return {Promise} 无返回值,推送结果回写到消息记录(push_status 2/3)。
+ * @param {Object} [extendProps=null] 回执携带的扩展指令(如开门 openDoor / 车牌登记 registerLicensePlate),
+ * 非空时透传到 notify.reply 的 data.extend_props。
+ * @return {Promise} 推送是否成功(回调 HTTP 200 且返回 code=200)。
*/
- async writeOutboundReply(data, replyContent, source = 'ai_reply') {
+ async writeOutboundReply(data, replyContent, source = 'ai_reply', extendProps = null) {
const { ctx } = this;
const { InboxMessage } = ctx.model;
@@ -533,12 +549,33 @@ class InboxProcessorService extends Service {
group_name: groupName,
user_name: isSystem ? null : userName,
content: replyContent,
- ext_data: outboundExtData, flags: {},
+ ext_data: outboundExtData,
+ extend_props: extendProps || null,
+ flags: {},
});
outboundId = created.id;
}
}
+ // 重推兜底:复用已有记录(定时补发送/手动重推)时,若调用方未传 extend_props,
+ // 从原记录回读,保证定时补发送报文一定带 extend_props(如开门指令等空文案回执)
+ let finalExtendProps = extendProps && typeof extendProps === 'object' && !Array.isArray(extendProps)
+ ? extendProps
+ : null;
+ if (!finalExtendProps && outboundId > 0) {
+ try {
+ const existed = await InboxMessage.findOne({
+ where: { id: outboundId }, attributes: [ 'extend_props' ], raw: true,
+ });
+ if (existed && existed.extend_props
+ && typeof existed.extend_props === 'object' && !Array.isArray(existed.extend_props)) {
+ finalExtendProps = existed.extend_props;
+ }
+ } catch (e) {
+ ctx.logger.warn(`[inbox processor] 回读 extend_props 失败: ${e.message}`);
+ }
+ }
+
const callbackUrl = callbackConfig.url;
if (callbackUrl) {
const crypto = require('crypto');
@@ -546,9 +583,13 @@ class InboxProcessorService extends Service {
const notifyBody = {
code: 200,
data: {
- type: isSystem ? 'system' : source === 'ai_reply' ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error',
+ // rule_reply(关键词规则引擎回执)与 ai_reply 同属机器人自动回复,映射为 ai 类型
+ type: isSystem ? 'system' : (source === 'ai_reply' || source === 'rule_reply') ? 'ai' : source === 'bind_confirm' ? 'bind' : source === 'balance' ? 'balance' : 'error',
content: replyContent,
ext_data: outboundExtData,
+ ...(finalExtendProps
+ ? { extend_props: finalExtendProps }
+ : {}),
ext_id: String(outboundId),
group_id: groupId,
...(isSystem ? {} : { user_id: userId, user_name: userName }),
@@ -618,31 +659,32 @@ class InboxProcessorService extends Service {
{ where: { id: parentId } }
);
}
- } else {
- // 推送失败:回写状态和原因
- await InboxMessage.update(
- {
- push_status: 3,
- push_response: {
- http_status: curlResult ? curlResult.status : null,
- body: curlResult ? (curlResult.data || null) : null,
- error: curlResult ? '回调返回非200或code非200' : '回调无响应',
- },
- },
- { where: { id: outboundId } }
- );
+ return true;
}
- } else {
- // 未配置回调地址:回写状态
+ // 推送失败:回写状态和原因
await InboxMessage.update(
{
push_status: 3,
- push_response: { error: '未配置回调地址(wms_api_app.callback_url为空)' },
+ push_response: {
+ http_status: curlResult ? curlResult.status : null,
+ body: curlResult ? (curlResult.data || null) : null,
+ error: curlResult ? '回调返回非200或code非200' : '回调无响应',
+ },
},
{ where: { id: outboundId } }
);
- ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,回写失败状态 ext_id=${extId}`);
+ return false;
}
+ // 未配置回调地址:回写状态
+ await InboxMessage.update(
+ {
+ push_status: 3,
+ push_response: { error: '未配置回调地址(wms_api_app.callback_url为空)' },
+ },
+ { where: { id: outboundId } }
+ );
+ ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,回写失败状态 ext_id=${extId}`);
+ return false;
} catch (error) {
ctx.logger.warn(`[inbox processor] 回执写入失败: ${error.message}`);
@@ -670,12 +712,77 @@ class InboxProcessorService extends Service {
} catch (logErr) {
ctx.logger.error('[notify-log] 失败日志写入异常: ' + logErr.message);
}
+ return false;
}
}
+ /**
+ * 判断当前消息所在群是否为仓库内部群(wms_inbox_group.group_type='warehouse')。
+ * 优先使用已加载的群信息(ctx.inboxContext.group_type),避免重复查库;
+ * 未加载时按 (group_id, warehouse_id) 查库,查库异常按「非仓库群」处理(屏蔽照常生效,安全默认)。
+ *
+ * @param {string} groupId 外部群ID。
+ * @param {number} warehouseId 仓库ID。
+ * @return {Promise} 是否仓库群。
+ */
+ async isWarehouseGroup(groupId, warehouseId) {
+ const { ctx } = this;
+
+ const cachedGroupType = String(ctx.inboxContext?.group_type || '').trim();
+ if (cachedGroupType) return cachedGroupType === 'warehouse';
+
+ if (!groupId) return false;
+
+ try {
+ const group = await ctx.model.InboxGroup.findOne({
+ attributes: [ 'group_type' ],
+ where: { group_id: groupId, warehouse_id: warehouseId },
+ raw: true,
+ });
+ return String((group && group.group_type) || '').trim() === 'warehouse';
+ } catch (error) {
+ ctx.logger.warn(`[inbox processor] 查询群类型失败: ${error.message}`);
+ return false;
+ }
+ }
+
+ /**
+ * 加载当前仓库的屏蔽用户ID集合(供 AI 判断真人接管)。
+ * 口径与 isBlocked() 一致:仓库群忽略不带群ID的屏蔽记录(仅带 group_id 的记录才算命中),
+ * 避免货主群/快递群等场景的用户级屏蔽连带把仓库群用户标记为「已屏蔽」。
+ *
+ * @param {number} warehouseId 仓库ID。
+ * @return {Promise>} 屏蔽用户ID集合。
+ */
+ async loadBlockedUserIds(warehouseId) {
+ const { ctx } = this;
+ const isWarehouseGroup = String(ctx.inboxContext?.group_type || '').trim() === 'warehouse';
+
+ const { InboxBlock } = ctx.model;
+ const rows = await InboxBlock.findAll({
+ attributes: [ 'group_id', 'user_id' ],
+ where: { warehouse_id: warehouseId },
+ raw: true,
+ });
+
+ return new Set(
+ rows
+ .filter(r => !(isWarehouseGroup && !String(r.group_id || '').trim()))
+ .map(r => String(r.user_id || '').trim())
+ .filter(Boolean)
+ );
+ }
+
/**
* 检查当前消息的群/用户是否在屏蔽列表中。
*
+ * 口径:
+ * - 带群ID的屏蔽记录(`群:用户` / `群:*`)在对应群内始终生效;
+ * - 仅带 user_id 的全局用户屏蔽(`*:用户`)在仓库群内不生效——仓库群是内部群,
+ * 此类屏蔽多来自货主群/快递群等外部场景,不应连带跳过仓库群消息;
+ * 仓库群内由机器人发起的屏蔽([屏蔽] 指令)会写入当前群 group_id,故仍按带群ID记录生效。
+ * - 无群ID的消息(如私聊)不受此例外影响。
+ *
* @return {Promise} 是否已屏蔽。
*/
async isBlocked() {
@@ -717,7 +824,14 @@ class InboxProcessorService extends Service {
// 3. 检查当前消息是否命中屏蔽规则
if (groupId && userId && blockedSet.has(`${groupId}:${userId}`)) return true;
if (groupId && blockedSet.has(`${groupId}:*`)) return true;
- if (userId && blockedSet.has(`*:${userId}`)) return true;
+ if (userId && blockedSet.has(`*:${userId}`)) {
+ // 仓库群忽略不带群ID的用户级屏蔽(见方法注释)
+ if (groupId && await this.isWarehouseGroup(groupId, warehouseId)) {
+ ctx.logger.info(`[inbox processor] 仓库群忽略不带群ID的用户屏蔽 group_id=${groupId} user_id=${userId}`);
+ return false;
+ }
+ return true;
+ }
return false;
} catch (error) {
@@ -745,7 +859,7 @@ class InboxProcessorService extends Service {
* 获取仓库 ApiApp 回调配置(URL + 签名凭证)。
*
* @param {number} warehouseId 仓库ID。
- * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>}
+ * @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调地址与签名凭证,未配置/异常时各字段为 null。
*/
async getApiAppCallbackConfig(warehouseId) {
const { ctx } = this;
diff --git a/app/service/inbox/rules.js b/app/service/inbox/rules.js
index a965c6f..8ae33b4 100644
--- a/app/service/inbox/rules.js
+++ b/app/service/inbox/rules.js
@@ -413,6 +413,8 @@ const STORE_RULES = [
{ keys: [ '改京东' ], fn: 'changeExpress', express: '京东', order: true,
tip: '如需改快递,发送:改京东+订单号' },
{ keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' },
+ { keys: [ '到货' ], fn: 'registerLicensePlate',
+ tip: '如需到货登记,发送:到货+车牌号\n例:到货 粤A12345' },
{ keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true,
tip: '如需查询打包视频,发送:打包视频+运单号\n例:打包视频 SF123' },
{ keys: [ '查库存' ], fn: 'searchStock', stockSearch: true,
@@ -435,6 +437,13 @@ const WAREHOUSE_RULES = [
{ keys: [ '打包视频', '装箱视频' ], fn: 'queryPackVideo', waybill: true,
tip: '如需查询打包视频,发送:打包视频+运单号' },
{ keys: [ '仓库地址', '退货地址', '退件地址', '寄回地址', '收货地址' ], fn: 'queryWarehouseAddress' },
+ { keys: [ '开门' ], fn: 'openDoor' },
+ { keys: [ '到货' ], fn: 'registerLicensePlate',
+ tip: '如需到货登记,发送:到货+车牌号\n例:到货 粤A12345' },
+ { keys: [ '离场' ], fn: 'departure',
+ tip: '如需离场登记,发送:车牌号+离场\n例:粤A12345离场' },
+ { keys: [ '进场' ], fn: 'enter',
+ tip: '如需进场登记,发送:车牌号+进场\n例:粤A12345进场' },
{ keys: [ '查库存' ], fn: 'searchWarehouseStock', stockSearch: true,
tip: '如需查库存,发送:查库存+商品名称/编码/条码' },
{ keys: [ 'help', '指令', '帮助' ], fn: '__help__' },
diff --git a/app/service/inbox/v2/config.js b/app/service/inbox/v2/config.js
new file mode 100644
index 0000000..f06e16f
--- /dev/null
+++ b/app/service/inbox/v2/config.js
@@ -0,0 +1,204 @@
+'use strict';
+
+const Service = require('egg').Service;
+
+/** v2 配置缓存键前缀(单仓库一份配置,TTL 300s)。 */
+const CACHE_KEY_PREFIX = 'inbox:v2:cfg:';
+/** 配置缓存 TTL(秒)。 */
+const CACHE_TTL = 300;
+/** 缓存结构版本号,结构变更时递增,避免读到旧结构。 */
+const CACHE_VERSION = 1;
+
+/**
+ * v2 仓库可配置回信引擎 —— 配置加载服务。
+ *
+ * 职责:
+ * - load(warehouseId):加载"系统级(warehouse_id IS NULL) + 仓库级(warehouse_id=当前仓库)"合并后的配置,
+ * 缓存于单 key inbox:v2:cfg:{warehouseId}(TTL 300s),缓存 miss 时从 DB 拼装;
+ * - invalidate(warehouseId):删除指定仓库配置缓存(仅管理接口调用,启动不清缓存防雪崩)。
+ *
+ * 配置结构(纯对象,可安全进缓存/Redis 序列化,不含 Map/Set/RegExp 实例):
+ * {
+ * _v: 1,
+ * subTypes: { [id]: {id, type, sub_type, name, is_system, is_enabled} },
+ * keywords: [ {keyword, sub_type_id, sort_order} ],
+ * groupWhitelist: { [sub_type_id]: [ {group_type, sub_group} ] },
+ * subTypeFunctions: { [sub_type_id]: [ {function_code, sort_order} ] },
+ * functionEnabled: { [function_code]: true },
+ * subTypeRules: { [sub_type_id]: [ {target, regexp, sort_order} ] },
+ * replies: { [sub_type_id]: {reply, is_reply, no_number_hint, warehouse_id} } // 仓库级覆盖系统级
+ * }
+ */
+class InboxV2ConfigService extends Service {
+ /**
+ * 加载仓库配置(缓存优先)。
+ * @param {number} warehouseId 仓库ID。
+ * @return {Promise