feat(inbox): 新增开门/到货/进场/离场车牌登记与 extend_props 持久化

- functions 新增 openDoor/registerLicensePlate/enter/departure(规则表+权限分组)
- 到货登记表 wms_inbox_arrival_register(含消费字段,离场闭环,货主收货群优先推送)
- 回执 extend_props 持久化落库与定时补发送下发(重推兜底回读)
- 车牌提取正则兼容异体字(粤/粵)
- 售后类型/关键字/函数/回复 v2 模型与迁移
- INBOX V2 HTTP 测试报告与指南
This commit is contained in:
liufumingren 2026-09-17 02:41:43 +08:00
parent a667f1401e
commit c2a761ca26
49 changed files with 6162 additions and 65 deletions

View File

@ -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
<!-- SERVICE_METHOD_INVENTORY:BEGIN -->
自动生成时间: 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

View File

@ -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`)。

327
INBOX_V2_TEST_GUIDE.md Normal file
View File

@ -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 幂等写库<br/>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 引擎<br/>模块接管]|
I --> K[callFunction 代码越权校验]
K --> L[writeOutboundReply 出站回执]
L -->|POST notify.reply| M[回调 URL<br/>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&timestamp={秒级时间戳}&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&timestamp={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&timestamp={秒}&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` 指向生产库,禁止裸跑)。

14
app.js
View File

@ -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);

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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;
};

View File

@ -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,

View File

@ -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,

View File

@ -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;
};

View File

@ -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 = '抱歉,暂时无法处理您的请求';
}

View File

@ -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 };
}
/**

View File

@ -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;
}

View File

@ -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<void>} 无返回值,推送结果回写到消息记录(push_status 2/3)。
* @param {Object} [extendProps=null] 回执携带的扩展指令(如开门 openDoor / 车牌登记 registerLicensePlate),
* 非空时透传到 notify.reply 的 data.extend_props。
* @return {Promise<boolean>} 推送是否成功(回调 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<boolean>} 是否仓库群。
*/
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<Set<string>>} 屏蔽用户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<boolean>} 是否已屏蔽。
*/
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;

View File

@ -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__' },

View File

@ -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<Object>} 配置对象。
*/
async load(warehouseId) {
const { app } = this;
const wid = Number(warehouseId) || 0;
const key = CACHE_KEY_PREFIX + wid;
if (typeof app.getCacheAsync === 'function') {
const cached = await app.getCacheAsync(key);
if (cached && cached._v === CACHE_VERSION) return cached;
}
const cfg = await this.build(wid);
if (typeof app.setCacheAsync === 'function') {
await app.setCacheAsync(key, cfg, CACHE_TTL);
}
return cfg;
}
/**
* 失效仓库配置缓存(管理接口增删改配置后调用)。
* @param {number} warehouseId 仓库ID。
* @return {Promise<void>} 无返回值。
*/
async invalidate(warehouseId) {
const { app } = this;
const wid = Number(warehouseId) || 0;
if (typeof app.delCacheAsync === 'function') {
await app.delCacheAsync(CACHE_KEY_PREFIX + wid);
}
}
/**
* 从 DB 拼装配置(全量小表查询 + 内存关联)。
* @param {number} wid 仓库ID(0=未绑定仓库,只加载系统级)。
* @return {Promise<Object>} 配置对象。
*/
async build(wid) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const wh = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: wid }] };
// 1. 子类型(启用)
const subTypes = await ctx.model.AfterSaleSubType.findAll({
where: { ...wh, is_enabled: 1 },
raw: true,
});
const subTypeMap = {};
const validSubTypeIds = new Set();
for (const s of subTypes) {
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,
};
validSubTypeIds.add(s.id);
}
// 2. 关键词(启用)
const keywords = await ctx.model.AfterSaleKeyword.findAll({
where: { ...wh, is_enabled: 1 },
attributes: [ 'keyword', 'sub_type_id', 'sort_order' ],
raw: true,
});
const kwList = keywords
.filter(k => validSubTypeIds.has(k.sub_type_id))
.sort((a, b) => (a.sort_order - b.sort_order) || String(a.keyword).length - String(b.keyword).length);
// 3. 群类型白名单(全局表)
const groupRows = await ctx.model.AfterSaleSubTypeGroup.findAll({
attributes: [ 'sub_type_id', 'group_type', 'sub_group' ],
raw: true,
});
const groupWhitelist = {};
for (const g of groupRows) {
if (!validSubTypeIds.has(g.sub_type_id)) continue;
if (!groupWhitelist[g.sub_type_id]) groupWhitelist[g.sub_type_id] = [];
groupWhitelist[g.sub_type_id].push({
group_type: String(g.group_type || '').trim(),
sub_group: String(g.sub_group || '').trim(),
});
}
// 4. 子类型-函数关系(全局表)
const funcRelRows = await ctx.model.AfterSaleSubTypeFunction.findAll({
attributes: [ 'sub_type_id', 'function_id', 'sort_order' ],
raw: true,
});
const funcRows = await ctx.model.AfterSaleFunction.findAll({
attributes: [ 'id', 'function_code', 'is_enabled' ],
raw: true,
});
const funcIdMap = {};
const functionEnabled = {};
for (const f of funcRows) {
funcIdMap[f.id] = f.function_code;
if (Number(f.is_enabled) === 1) functionEnabled[f.function_code] = true;
}
const subTypeFunctions = {};
for (const r of funcRelRows) {
const code = funcIdMap[r.function_id];
if (!code || !validSubTypeIds.has(r.sub_type_id)) continue;
if (!subTypeFunctions[r.sub_type_id]) subTypeFunctions[r.sub_type_id] = [];
subTypeFunctions[r.sub_type_id].push({ function_code: code, sort_order: r.sort_order });
}
for (const key of Object.keys(subTypeFunctions)) {
subTypeFunctions[key].sort((a, b) => a.sort_order - b.sort_order);
}
// 5. 子类型-取号规则关系(全局表)+ 取号规则本体
const ruleRelRows = await ctx.model.AfterSaleSubTypeRule.findAll({
attributes: [ 'sub_type_id', 'number_rule_id', 'sort_order' ],
raw: true,
});
const ruleRows = await ctx.model.InboxNumberRule.findAll({
attributes: [ 'id', 'target', 'regexp', 'sort_order' ],
raw: true,
});
const ruleIdMap = {};
for (const n of ruleRows) ruleIdMap[n.id] = n;
const subTypeRules = {};
for (const r of ruleRelRows) {
const rule = ruleIdMap[r.number_rule_id];
if (!rule || !validSubTypeIds.has(r.sub_type_id)) continue;
if (!subTypeRules[r.sub_type_id]) subTypeRules[r.sub_type_id] = [];
subTypeRules[r.sub_type_id].push({
target: String(rule.target || '').trim(),
regexp: String(rule.regexp || ''),
sort_order: r.sort_order || rule.sort_order || 0,
});
}
for (const key of Object.keys(subTypeRules)) {
subTypeRules[key].sort((a, b) => a.sort_order - b.sort_order);
}
// 6. 回复表:仓库级覆盖系统级(同子类型取 warehouse_id 非空者优先)
const replyRows = await ctx.model.AfterSaleReply.findAll({
where: { ...wh, is_enabled: 1 },
attributes: [ 'warehouse_id', 'sub_type_id', 'reply', 'is_reply', 'no_number_hint' ],
raw: true,
});
const replies = {};
for (const r of replyRows) {
if (!validSubTypeIds.has(r.sub_type_id)) continue;
const isWh = r.warehouse_id !== null && r.warehouse_id !== undefined;
const existing = replies[r.sub_type_id];
if (!existing || (isWh && existing.warehouse_id === null)) {
replies[r.sub_type_id] = {
reply: String(r.reply || ''),
is_reply: Number(r.is_reply) === 1 ? 1 : 0,
no_number_hint: r.no_number_hint ? String(r.no_number_hint) : '',
warehouse_id: isWh ? r.warehouse_id : null,
};
}
}
return {
_v: CACHE_VERSION,
subTypes: subTypeMap,
keywords: kwList,
groupWhitelist,
subTypeFunctions,
functionEnabled,
subTypeRules,
replies,
};
}
}
module.exports = InboxV2ConfigService;

View File

@ -0,0 +1,84 @@
'use strict';
const Service = require('egg').Service;
/**
* 售后函数表同步服务(v2 仓库可配置回信引擎)。
*
* 职责:启动时把 inbox functions 注册表(代码权威源)幂等 upsert 到
* wms_after_sale_function,供管理界面展示与开关控制。
*
* 原则:
* - 只增改、不删:代码中已删除的函数保留 DB 行(避免关联行悬空,管理端可见并可停用);
* - 不覆盖管理端字段:is_enabled / sort_order 由管理端维护,同步仅刷新 name/description;
* - 失败仅告警:本服务不影响任何消息处理链路,运行时执行始终以代码注册表为准。
*/
class InboxV2FunctionSyncService extends Service {
/**
* 同步注册表到售后函数表(幂等,可重复执行)。
* @return {Promise<{ok:boolean, created:number, updated:number, total:number, skipped?:boolean, error?:string}>} 同步统计结果,skipped 表示未执行同步(模型缺失/注册表为空)。
*/
async sync() {
const { ctx } = this;
const stats = { ok: false, created: 0, updated: 0, total: 0 };
// 模型缺失场景(如部分单测):直接跳过,不报错。
if (!ctx.model || !ctx.model.AfterSaleFunction) {
return { ...stats, ok: true, skipped: true };
}
let registry;
try {
const functionsSvc = ctx.service.inbox.functions;
registry = functionsSvc && functionsSvc.registry;
} catch (e) {
ctx.logger.warn(`[inbox v2] 函数服务不可用,跳过函数表同步: ${e.message}`);
return { ...stats, ok: true, skipped: true };
}
if (!(registry instanceof Map) || registry.size === 0) {
return { ...stats, ok: true, skipped: true };
}
// 收集待同步行(function_code 即注册名)。
const rows = [];
const seen = new Set();
for (const [ code, def ] of registry) {
if (!code || seen.has(code)) continue;
seen.add(code);
rows.push({
function_code: code,
name: code,
description: (typeof def.description === 'string' ? def.description : '').slice(0, 500) || null,
});
}
stats.total = rows.length;
try {
// 同步前查现有集合,用于统计新增/更新。
const existing = await ctx.model.AfterSaleFunction.findAll({
attributes: [ 'function_code' ],
raw: true,
});
const existingSet = new Set(existing.map(r => r.function_code));
stats.created = rows.filter(r => !existingSet.has(r.function_code)).length;
stats.updated = rows.length - stats.created;
// bulkCreate + updateOnDuplicate:新行插入(is_enabled 默认 1、sort_order 默认 0),
// 已有行仅刷新 name/description,不覆盖管理端维护的 is_enabled / sort_order。
await ctx.model.AfterSaleFunction.bulkCreate(rows, {
updateOnDuplicate: [ 'name', 'description' ],
});
stats.ok = true;
return stats;
} catch (error) {
ctx.logger.warn(
`[inbox v2] 售后函数表同步失败(不影响启动): ${error && error.message ? error.message : error}`
);
return { ...stats, error: error && error.message ? error.message : String(error) };
}
}
}
module.exports = InboxV2FunctionSyncService;

View File

@ -0,0 +1,411 @@
'use strict';
/* eslint-disable no-use-before-define */
const Service = require('egg').Service;
/**
* 取号 target → 函数入参键映射。
* keyword 类(运单号/订单号/平台单号/收货单/入库单/出库单)合并为一个逗号分隔字符串;
* express_name 取第一个匹配值。
* 注意:只保留有真实消费者的映射;plate_no 当前无函数消费 params.plate_no
* (车牌函数自行从原消息提取),不入映射,避免悬空。
*/
const TARGET_PARAM_MAP = {
waybill_no: 'keyword',
order_no: 'keyword',
source_order_codes: 'keyword',
receiving_no: 'keyword',
entry_order_no: 'keyword',
stockout_no: 'keyword',
express_name: 'express',
};
/**
* 函数按子类型补充 issue_type 入参(函数入参语义由代码定义,引擎按子类型转译)。
*/
const FN_ISSUE_TYPE_MAP = {
handleStoreFeedback: {
damage: 'damaged', missing_item: 'missing', mis_shipment: 'wrong', extra_item: 'multiple',
},
changeAddr: {
change_address: 'addr', rejected: 'return', urge: 'urge',
},
};
/** 取号失败默认引导语(回复表未配置 no_number_hint 时使用)。 */
const DEFAULT_NO_NUMBER_HINT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)';
/** 单值类 target 缺参引导语。 */
const TARGET_HINT_MAP = {
express_name: '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)',
};
/**
* v2 仓库可配置回信引擎(规则驱动,替代 v1 硬编码规则表)。
*
* 链路:关键词命中(长词优先)→ 群类型白名单过滤 → 关系表取处理函数 →
* 取号规则提取对象数组 → 入参组装 → callFunction(代码 groups 越权校验兜底)→ 回复表决策。
*
* 出参与 v1 rules.handle 同构:
* - { handled: false }:未命中;
* - { handled: true, silent: true }:命中但静默(回复表 is_reply=0);
* - { handled: true, reply, fn, params, result, matchedKey, thoughts }:已执行。
*
* 安全三件套(取号正则):保存时校验(管理接口)+ 长度上限(DB 列 500)+
* 每次 new RegExp(绝不缓存编译对象,避免状态污染与 ReDoS 复用),非法正则跳过并告警。
*/
class InboxV2RulesService extends Service {
/**
* v2 引擎主入口。
* @param {string} content 消息正文。
* @return {Promise<Object>} 处理结果(与 v1 rules.handle 同构)。
*/
async handle(content) {
const { ctx } = this;
const text = String(content || '').trim();
if (!text) return { handled: false };
const groupType = String(ctx.inboxContext?.group_type || '').trim();
if (!groupType) return { handled: false };
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
const groupSubType = String(ctx.inboxContext?.sub_type || '').trim();
const cfg = await ctx.service.inbox.v2.config.load(warehouseId);
// 1. 关键词命中:长词优先;同长按 sort_order;同长同子类型只保留一次。
const candidates = this._matchKeywords(text, cfg);
if (candidates.length === 0) {
ctx.logger.info(`[inbox v2] 未命中关键词 group=${groupType} text=${text.slice(0, 50)}`);
return { handled: false };
}
const groupsSvc = ctx.service.inbox.groups;
const funcSvc = ctx.service.inbox.functions;
const activeGroups = groupsSvc.resolveActiveGroups();
// 2. 候选子类型逐个尝试:白名单过滤 → 取函数 → 取号 → 执行。
for (const cand of candidates) {
const subType = cfg.subTypes[cand.sub_type_id];
if (!subType) continue;
// 2.1 群类型白名单过滤(sub_group 维度;群 sub_type 为空时只按主类型)
if (!this._groupAllowed(cfg, cand.sub_type_id, groupType, groupSubType)) {
ctx.logger.info(
`[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 不在群 ${groupType}:${groupSubType || '-'} 白名单,跳过`
);
continue;
}
// 2.2 取关联函数(启用且代码已注册且群权限可用)
const fns = (cfg.subTypeFunctions[cand.sub_type_id] || []).filter(f =>
cfg.functionEnabled[f.function_code]
);
if (fns.length === 0) {
ctx.logger.info(`[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 无可用函数,跳过`);
continue;
}
// 2.3 取号规则提取(对象数组:{target, values[]})
const extracted = this._extractNumbers(text, cfg, cand.sub_type_id);
if (extracted === null) {
// 关联了取号规则但未提取到值 → 引导提示
const reply = this._noNumberHint(cfg, cand.sub_type_id);
const thoughts = [{
round: 0,
action: 'rule',
function: fns[0].function_code,
params: {},
reason: `v2 关键词命中: ${cand.keyword},取号失败-引导提示`,
functionResult: null,
}];
return {
handled: true,
reply,
fn: fns[0].function_code,
params: {},
result: null,
matchedKey: cand.keyword,
thoughts,
};
}
// 2.4 逐函数执行(按 sort_order;任一失败立即以失败出参返回)
const results = [];
let lastFn = null;
let lastParams = null;
let executed = false;
for (const f of fns) {
const def = funcSvc.registry.get(f.function_code);
if (!def || !groupsSvc.isFunctionAvailable(def, activeGroups)) {
ctx.logger.info(
`[inbox v2] 函数 ${f.function_code} 当前群不可用,跳过 ` +
`groups=${def ? def.groups.join(',') : '-'} active=${activeGroups.join(',')}`
);
continue;
}
const params = this._buildParams(f.function_code, subType, extracted);
const result = await funcSvc.callFunction(f.function_code, params);
lastFn = f.function_code;
lastParams = params;
executed = true;
ctx.logger.info(
`[inbox v2] 执行 fn=${f.function_code} sub=${subType.type}:${subType.sub_type} ` +
`params=${JSON.stringify(params)} success=${!!result.success}`
);
if (!result.success) {
const thoughts = [{
round: 0,
action: 'rule',
function: f.function_code,
params,
reason: `v2 关键词命中: ${cand.keyword}`,
functionResult: result,
}];
return {
handled: true,
reply: String(result.error || '操作失败,请联系客服处理'),
fn: f.function_code,
params,
result,
matchedKey: cand.keyword,
thoughts,
};
}
results.push({ fn: f.function_code, params, result });
}
if (!executed) continue;
// 2.5 回复决策:回复表(仓库级覆盖系统级)→ 函数返回值兜底
return this._buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text);
}
return { handled: false };
}
/**
* 关键词匹配:收集文本包含的所有关键词,按长度降序、sort_order 升序排序,
* 取最长命中词集合(同长多子类型均候选)。
* @param {string} text 消息正文。
* @param {Object} cfg v2 配置。
* @return {Array<{keyword:string, sub_type_id:number}>} 候选列表。
*/
_matchKeywords(text, cfg) {
const hits = [];
for (const k of cfg.keywords || []) {
if (k.keyword && text.includes(k.keyword)) hits.push({ keyword: k.keyword, sub_type_id: k.sub_type_id });
}
if (hits.length === 0) return [];
hits.sort((a, b) => b.keyword.length - a.keyword.length);
const maxLen = hits[0].keyword.length;
const top = hits.filter(h => h.keyword.length === maxLen);
const seen = new Set();
return top.filter(h => {
const key = h.sub_type_id;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/**
* 群类型白名单过滤。
* @param {Object} cfg v2 配置。
* @param {number} subTypeId 子类型ID。
* @param {string} groupType 群主类型。
* @param {string} groupSubType 群子类型(可为空)。
* @return {boolean} 是否允许。
*/
_groupAllowed(cfg, subTypeId, groupType, groupSubType) {
const rows = (cfg.groupWhitelist || {})[subTypeId];
if (!Array.isArray(rows) || rows.length === 0) return false;
return rows.some(r => {
if (r.group_type !== groupType) return false;
if (!groupSubType) return true; // 群未绑子类型:只按主类型放行
return r.sub_group === groupSubType;
});
}
/**
* 取号规则提取(安全三件套:每次 new RegExp + try/catch + 长度上限)。
* @param {string} text 消息正文。
* @param {Object} cfg v2 配置。
* @param {number} subTypeId 子类型ID。
* @return {Array|null} 提取结果数组 [{target, values[]}];未提取到任何值返回 null。
*/
_extractNumbers(text, cfg, subTypeId) {
const rules = (cfg.subTypeRules || {})[subTypeId];
if (!Array.isArray(rules) || rules.length === 0) return [];
const out = [];
let anyHit = false;
for (const rule of rules) {
if (!rule.regexp) continue;
if (rule.regexp.length > 500) {
this.ctx.logger.warn(`[inbox v2] 取号正则超长跳过 sub_type_id=${subTypeId} target=${rule.target}`);
continue;
}
let re;
try {
re = new RegExp(rule.regexp, 'g'); // 每次新建,绝不缓存编译对象
} catch (e) {
this.ctx.logger.warn(
`[inbox v2] 取号正则非法跳过 sub_type_id=${subTypeId} target=${rule.target}: ${e.message}`
);
continue;
}
const values = [];
try {
for (const m of text.matchAll(re)) {
const v = String(m[0]).trim();
if (v && !values.includes(v)) values.push(v);
}
} catch (e) {
this.ctx.logger.warn(`[inbox v2] 取号正则执行异常 target=${rule.target}: ${e.message}`);
}
out.push({ target: rule.target, values });
if (values.length > 0) anyHit = true;
}
return anyHit ? out : null;
}
/**
* 入参组装:取号结果对象数组 → 函数 params。
* keyword 类 target 合并去重后 join(',');express/plate_no 取第一个值;
* 按函数补充 issue_type。
* @param {string} fn 函数名。
* @param {Object} subType 子类型记录。
* @param {Array} extracted 提取结果。
* @return {Object} 函数入参。
*/
_buildParams(fn, subType, extracted) {
const params = {};
const keywordValues = [];
for (const item of extracted) {
const paramKey = TARGET_PARAM_MAP[item.target];
if (!paramKey || item.values.length === 0) continue;
if (paramKey === 'keyword') {
for (const v of item.values) {
if (!keywordValues.includes(v)) keywordValues.push(v);
}
} else if (!params[paramKey]) {
params[paramKey] = item.values[0];
}
}
if (keywordValues.length > 0) params.keyword = keywordValues.join(',');
// 子类型 → issue_type 转译
const map = FN_ISSUE_TYPE_MAP[fn];
if (map && map[subType.sub_type]) params.issue_type = map[subType.sub_type];
return params;
}
/**
* 取号失败引导语:回复表 no_number_hint → target 专属 → 默认。
* @param {Object} cfg v2 配置。
* @param {number} subTypeId 子类型ID。
* @return {string} 引导语。
*/
_noNumberHint(cfg, subTypeId) {
const replyCfg = (cfg.replies || {})[subTypeId];
if (replyCfg && replyCfg.no_number_hint) return replyCfg.no_number_hint;
const rules = (cfg.subTypeRules || {})[subTypeId] || [];
for (const r of rules) {
if (TARGET_HINT_MAP[r.target]) return TARGET_HINT_MAP[r.target];
}
return DEFAULT_NO_NUMBER_HINT;
}
/**
* 出参构建:回复表决策(仓库级覆盖系统级)→ 函数返回值兜底。
* @param {Object} cfg v2 配置。
* @param {Object} cand 命中候选。
* @param {Object} subType 子类型记录。
* @param {Array} results 函数执行结果数组。
* @param {string} lastFn 最后执行的函数名。
* @param {Object} lastParams 最后执行的函数入参。
* @param {string} text 消息正文。
* @return {Object} 与 v1 rules.handle 同构的出参。
*/
_buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text) {
const last = results[results.length - 1];
const replyCfg = (cfg.replies || {})[cand.sub_type_id];
// 回复表显式配置:is_reply=0 静默;is_reply=1 用自定义文案(占位符替换)
if (replyCfg && replyCfg.is_reply === 0) {
return { handled: true, silent: true };
}
let reply;
if (replyCfg && replyCfg.reply) {
reply = this._renderReply(replyCfg.reply, subType, results, text);
} else {
// 无回复配置:函数返回值兜底(与 v1 buildReply 同构语义)
reply = this._buildReplyFromResult(results);
}
const thoughts = results.map((r, idx) => ({
round: idx,
action: 'rule',
function: r.fn,
params: r.params,
reason: `v2 关键词命中: ${cand.keyword}`,
functionResult: r.result,
}));
return {
handled: true,
reply,
fn: lastFn || last.fn,
params: lastParams || last.params,
result: last.result,
matchedKey: cand.keyword,
thoughts,
};
}
/**
* 回复文案占位符渲染:{sub_type_name}/{keyword}/{express}。
* @param {string} tpl 模板文案。
* @param {Object} subType 子类型记录。
* @param {Array} results 函数执行结果。
* @param {string} text 消息正文。
* @return {string} 渲染后的文案。
*/
_renderReply(tpl, subType, results, text) {
const last = results[results.length - 1];
const params = (last && last.params) || {};
return String(tpl)
.replace(/\{sub_type_name\}/g, subType.name || '')
.replace(/\{keyword\}/g, String(params.keyword || ''))
.replace(/\{express\}/g, String(params.express || ''))
.replace(/\{text\}/g, text.slice(0, 200));
}
/**
* 无回复配置时,从函数返回值兜底构建回复(direct_reply.messages → data.message → error)。
* @param {Array} results 函数执行结果数组。
* @return {string|string[]|null} 回复文本。
*/
_buildReplyFromResult(results) {
const replies = [];
for (const r of results) {
const result = r.result;
if (!result || typeof result !== 'object') continue;
if (result.success === false) {
replies.push(String(result.error || '操作失败,请联系客服处理'));
continue;
}
const data = result.data || {};
if (data.direct_reply === true && Array.isArray(data.messages) && data.messages.length > 0) {
replies.push(...data.messages.map(m => String(m)));
} else if (data.message) {
replies.push(String(data.message));
}
}
if (replies.length === 0) return null;
return replies.length === 1 ? replies[0] : replies;
}
}
module.exports = InboxV2RulesService;

View File

@ -30,9 +30,9 @@ class AfterSaleMethodService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount';
const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress,workCount';
const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount';
const _noNeedRight = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount,typeList,typeCreate,typeUpdate,typeDelete,subTypeList,subTypeCreate,subTypeUpdate,subTypeDelete';
const _noNeedLog = 'workList,auditList,detail,export,exportTaskProgress,workCount,typeList,subTypeList';
const _noNeedAuth = 'workList,auditList,detail,create,transfer,handleWorkOrder,batchSetPendingFeedback,batchClose,registerClaim,export,exportTaskProgress,workCount,typeList,typeCreate,typeUpdate,typeDelete,subTypeList,subTypeCreate,subTypeUpdate,subTypeDelete';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -1010,6 +1010,210 @@ class AfterSaleMethodService extends MainService {
}
}
// ===========================
// 售后类型/子类型自定义配置
// ===========================
/**
* 售后类型列表:返回系统级(warehouse_id IS NULL)+ 当前仓库自定义的合并列表。
* 默认按 sort_order 升序、id 升序;支持分页、where 条件({operator, value} 规范)与排序。
*
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {number} [data.pagination.page=1] 页码
* @param {number} [data.pagination.pageSize=20] 每页数量(上限500)
* @param {Object} [data.where] 筛选条件,支持字段 id/type/name/is_system/is_enabled/sort_order/created_at/updated_at
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder },不传时默认 sort_order ASC, id ASC
* @return {Promise<Object>} 统一 success 包装,data 为 { list, pagination }
*/
async typeList(data = {}) {
const { ctx, service } = this;
const { pagination, sort } = data || {};
const { where } = this.prepareWhereContext(data);
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const result = await service.systems.afterSale.getTypeList({ warehouseId, where, pagination, sort });
return this.success('ok', result);
}
/**
* 创建仓库自定义售后类型。warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
*
* @param {Object} data 请求体
* @param {string} data.type 类型编码(仅小写字母/数字/下划线,不可与系统级编码重复)
* @param {string} data.name 类型名称(长度≤50)
* @param {number} [data.sort_order=0] 排序值
* @param {number} [data.is_enabled=1] 是否启用(0/1)
* @return {Promise<Object>} 成功返回 success 包装及新记录;失败返回 fail 包装(含业务码)
*/
async typeCreate(data = {}) {
const { ctx, service } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const {
type,
name,
sort_order: sortOrder,
is_enabled: isEnabled,
} = data || {};
try {
const result = await service.systems.afterSale.createType({ warehouseId, type, name, sortOrder, isEnabled });
return this.success('售后类型创建成功', result);
} catch (e) {
return this.fail(e.message, { code: Number(e.code) || 400 });
}
}
/**
* 更新仓库自定义售后类型。仅允许修改 name/is_enabled/sort_order,type 编码不可变。
*
* @param {Object} data 请求体
* @param {number} data.id 类型主键ID
* @param {string} [data.name] 类型名称(长度≤50)
* @param {number} [data.is_enabled] 是否启用(0/1)
* @param {number} [data.sort_order] 排序值
* @return {Promise<Object>} 成功返回 success 包装及更新后记录;失败返回 fail 包装(含业务码)
*/
async typeUpdate(data = {}) {
const { ctx, service } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const {
id,
name,
sort_order: sortOrder,
is_enabled: isEnabled,
} = data || {};
try {
const result = await service.systems.afterSale.updateType({ warehouseId, id, name, sortOrder, isEnabled });
return this.success('售后类型更新成功', result);
} catch (e) {
return this.fail(e.message, { code: Number(e.code) || 400 });
}
}
/**
* 删除仓库自定义售后类型。系统级类型禁止删除;
* 删除前检查该类型下是否存在当前仓库的自定义子类型,存在则拒绝(需先删除子类型)。
*
* @param {Object} data 请求体
* @param {number} data.id 类型主键ID
* @return {Promise<Object>} 成功返回 success 包装;失败返回 fail 包装(含业务码)
*/
async typeDelete(data = {}) {
const { ctx, service } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const { id } = data || {};
try {
const result = await service.systems.afterSale.deleteType({ warehouseId, id });
return this.success('售后类型删除成功', { data: result });
} catch (e) {
return this.fail(e.message, { code: Number(e.code) || 400 });
}
}
/**
* 售后子类型列表:返回系统级 + 当前仓库自定义的合并列表,支持按 type 过滤与按 type 分组返回。
* 默认按 sort_order 升序、id 升序。
*
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数
* @param {number} [data.pagination.page=1] 页码
* @param {number} [data.pagination.pageSize=20] 每页数量(上限500)
* @param {Object} [data.where] 筛选条件,支持字段 id/type/sub_type/name/is_system/is_enabled/sort_order/created_at/updated_at
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder },不传时默认 sort_order ASC, id ASC
* @param {boolean} [data.group] 是否按 type 分组返回 groups(true 时额外返回 groups 数组)
* @return {Promise<Object>} 统一 success 包装,data 为 { list, pagination, groups? }
*/
async subTypeList(data = {}) {
const { ctx, service } = this;
const { pagination, sort, group } = data || {};
const { where } = this.prepareWhereContext(data);
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const result = await service.systems.afterSale.getSubTypeList({ warehouseId, where, pagination, sort, group });
return this.success('ok', result);
}
/**
* 创建仓库自定义售后子类型。warehouse_id 由服务端从当前上下文自动注入,前端无需传递。
* 所属类型必须存在(系统级或当前仓库自定义)且处于启用状态。
*
* @param {Object} data 请求体
* @param {string} data.type 所属类型编码(必须已存在且启用)
* @param {string} data.sub_type 子类型编码(仅小写字母/数字/下划线,不可与系统级同 type 下编码重复)
* @param {string} data.name 子类型名称(长度≤50)
* @param {number} [data.sort_order=0] 排序值
* @param {number} [data.is_enabled=1] 是否启用(0/1)
* @return {Promise<Object>} 成功返回 success 包装及新记录;失败返回 fail 包装(含业务码)
*/
async subTypeCreate(data = {}) {
const { ctx, service } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const {
type,
sub_type: subType,
name,
sort_order: sortOrder,
is_enabled: isEnabled,
} = data || {};
try {
const result = await service.systems.afterSale.createSubType({ warehouseId, type, subType, name, sortOrder, isEnabled });
return this.success('售后子类型创建成功', result);
} catch (e) {
return this.fail(e.message, { code: Number(e.code) || 400 });
}
}
/**
* 更新仓库自定义售后子类型。仅允许修改 name/is_enabled/sort_order,type 与 sub_type 编码不可变。
*
* @param {Object} data 请求体
* @param {number} data.id 子类型主键ID
* @param {string} [data.name] 子类型名称(长度≤50)
* @param {number} [data.is_enabled] 是否启用(0/1)
* @param {number} [data.sort_order] 排序值
* @return {Promise<Object>} 成功返回 success 包装及更新后记录;失败返回 fail 包装(含业务码)
*/
async subTypeUpdate(data = {}) {
const { ctx, service } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const {
id,
name,
sort_order: sortOrder,
is_enabled: isEnabled,
} = data || {};
try {
const result = await service.systems.afterSale.updateSubType({ warehouseId, id, name, sortOrder, isEnabled });
return this.success('售后子类型更新成功', result);
} catch (e) {
return this.fail(e.message, { code: Number(e.code) || 400 });
}
}
/**
* 删除仓库自定义售后子类型。系统级子类型禁止删除;
* 若该子类型已被当前仓库的售后单使用(wms_after_sale 存在引用),拒绝删除。
*
* @param {Object} data 请求体
* @param {number} data.id 子类型主键ID
* @return {Promise<Object>} 成功返回 success 包装;失败返回 fail 包装(含业务码)
*/
async subTypeDelete(data = {}) {
const { ctx, service } = this;
const warehouseId = ctx.user && ctx.user.store_id ? Number(ctx.user.store_id) : 0;
const { id } = data || {};
try {
const result = await service.systems.afterSale.deleteSubType({ warehouseId, id });
return this.success('售后子类型删除成功', { data: result });
} catch (e) {
return this.fail(e.message, { code: Number(e.code) || 400 });
}
}
}
module.exports = AfterSaleMethodService;

View File

@ -2215,6 +2215,685 @@ class AfterSaleService extends Service {
};
return labels[channel] || channel || '';
}
// ===========================
// 售后类型/子类型自定义配置
// ===========================
/**
* 构造售后类型配置业务错误(携带业务码,供方法层包装为统一失败响应)。
* @param {string} message 错误提示信息
* @param {number} [code=400] 业务错误码
* @return {Error} 携带业务码的错误对象
*/
_createAfterSaleTypeConfigError(message, code = 400) {
const error = new Error(message);
error.code = code;
return error;
}
/**
* 校验售后类型/子类型编码:非空且仅允许小写字母、数字、下划线。
* @param {string} code 编码值
* @param {string} fieldLabel 字段中文名(用于错误提示)
* @return {string} 去空格后的编码
* @throws {Error} 编码为空或格式不合法时抛出(业务码 400)
*/
_validateAfterSaleTypeCode(code, fieldLabel) {
const trimmed = typeof code === 'string' ? code.trim() : '';
if (!trimmed) {
throw this._createAfterSaleTypeConfigError(`${fieldLabel}不能为空`, 400);
}
if (!/^[a-z0-9_]+$/.test(trimmed)) {
throw this._createAfterSaleTypeConfigError(`${fieldLabel}只能包含小写字母、数字和下划线`, 400);
}
return trimmed;
}
/**
* 归一化售后类型/子类型的 sort_order 入参。
* @param {*} value 原始排序值
* @return {number} 归一化后的整数排序值(非法值按 0 处理)
*/
_normalizeAfterSaleTypeSortOrder(value) {
const num = Number(value);
if (!Number.isFinite(num)) return 0;
return Math.floor(num);
}
/**
* 归一化 is_enabled 入参。
* @param {*} value 原始值(0/1/布尔/字符串)
* @param {number} [defaultValue=1] 缺省值
* @return {number} 0 或 1
*/
_normalizeAfterSaleTypeEnabled(value, defaultValue = 1) {
if (value === undefined || value === null || value === '') return defaultValue;
return value === 0 || value === '0' || value === false || value === 'false' ? 0 : 1;
}
/**
* 格式化售后类型/子类型配置行:数值字段归一化、时间字段格式化。
* @param {Object} row 原始行数据
* @return {Object} 格式化后的行数据
*/
_formatAfterSaleTypeConfigRow(row) {
if (!row) return row;
const { app } = this;
return {
...row,
warehouse_id: row.warehouse_id === null || row.warehouse_id === undefined ? null : Number(row.warehouse_id),
is_system: Number(row.is_system),
is_enabled: Number(row.is_enabled),
sort_order: Number(row.sort_order),
created_at: row.created_at ? app.formatDate(row.created_at) : null,
updated_at: row.updated_at ? app.formatDate(row.updated_at) : null,
};
}
/**
* 构建售后类型列表的 where 条件(字段白名单,仓库维度由作用域条件统一控制)。
* @param {Object} where 标准化 where 条件对象
* @param {Object} Op Sequelize Op 对象
* @return {Object} Sequelize where 条件
*/
_buildAfterSaleTypeListWhere(where = {}, Op) {
const queryWhere = {};
const directFields = [
'id', 'type', 'name', 'is_system', 'is_enabled',
'sort_order', 'created_at', 'updated_at',
];
for (const field of directFields) {
if (where[field] !== undefined && where[field] !== null) {
queryWhere[field] = this._resolveConditionValue(where[field], Op);
}
}
return queryWhere;
}
/**
* 构建售后类型列表的排序参数(字段白名单)。
* @param {Object} sort 排序参数
* @param {string} [sort.sortField] 排序字段
* @param {string} [sort.sortOrder] 排序顺序(asc/desc)
* @return {Array<Array<string>>} Sequelize order 数组
*/
_buildAfterSaleTypeListOrder(sort = {}) {
const sortField = sort.sortField || sort.sort_field;
const allowedSortFields = new Set([
'id', 'type', 'name', 'is_enabled', 'sort_order', 'created_at', 'updated_at',
]);
if (sortField && allowedSortFields.has(sortField)) {
const sortOrderRaw = String(sort.sortOrder || sort.sort_order || 'asc').toLowerCase();
const sortOrder = sortOrderRaw === 'desc' ? 'DESC' : 'ASC';
return [[ sortField, sortOrder ], [ 'id', 'ASC' ]];
}
return [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]];
}
/**
* 构建售后子类型列表的 where 条件(字段白名单,仓库维度由作用域条件统一控制)。
* @param {Object} where 标准化 where 条件对象
* @param {Object} Op Sequelize Op 对象
* @return {Object} Sequelize where 条件
*/
_buildAfterSaleSubTypeListWhere(where = {}, Op) {
const queryWhere = {};
const directFields = [
'id', 'type', 'sub_type', 'name', 'is_system', 'is_enabled',
'sort_order', 'created_at', 'updated_at',
];
for (const field of directFields) {
if (where[field] !== undefined && where[field] !== null) {
queryWhere[field] = this._resolveConditionValue(where[field], Op);
}
}
return queryWhere;
}
/**
* 构建售后子类型列表的排序参数(字段白名单)。
* @param {Object} sort 排序参数
* @param {string} [sort.sortField] 排序字段
* @param {string} [sort.sortOrder] 排序顺序(asc/desc)
* @return {Array<Array<string>>} Sequelize order 数组
*/
_buildAfterSaleSubTypeListOrder(sort = {}) {
const sortField = sort.sortField || sort.sort_field;
const allowedSortFields = new Set([
'id', 'type', 'sub_type', 'name', 'is_enabled', 'sort_order', 'created_at', 'updated_at',
]);
if (sortField && allowedSortFields.has(sortField)) {
const sortOrderRaw = String(sort.sortOrder || sort.sort_order || 'asc').toLowerCase();
const sortOrder = sortOrderRaw === 'desc' ? 'DESC' : 'ASC';
return [[ sortField, sortOrder ], [ 'id', 'ASC' ]];
}
return [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]];
}
/**
* 售后类型列表:系统级(warehouse_id IS NULL)+ 当前仓库自定义合并,支持分页/where/sort。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID(0 表示无仓库上下文,仅返回系统级数据)
* @param {Object} [params.where] 标准化 where 条件
* @param {Object} [params.pagination] 分页参数 {page, pageSize}
* @param {Object} [params.sort] 排序参数 {sortField, sortOrder}
* @return {Promise<Object>} { list: Array, pagination: Object }
*/
async getTypeList(params = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const { warehouseId = 0, where = {}, pagination = {}, sort = {} } = params;
const page = Math.max(1, parseInt(pagination.page) || 1);
const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20));
const scopeWhere = warehouseId
? { [Op.or]: [{ warehouse_id: null }, { warehouse_id: warehouseId }] }
: { warehouse_id: null };
const fieldWhere = this._buildAfterSaleTypeListWhere(where, Op);
const queryWhere = { ...scopeWhere, ...fieldWhere };
const order = this._buildAfterSaleTypeListOrder(sort);
const { count, rows } = await ctx.model.AfterSaleType.findAndCountAll({
where: queryWhere,
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
attributes: [
'id', 'type', 'name', 'warehouse_id', 'is_system',
'is_enabled', 'sort_order', 'created_at', 'updated_at',
],
});
const totalPages = Math.ceil(count / pageSize);
return {
list: rows.map(row => this._formatAfterSaleTypeConfigRow(row)),
pagination: {
page,
pageSize,
total: count,
totalPages,
hasPrevious: page > 1,
hasNext: page * pageSize < count,
},
};
}
/**
* 创建仓库自定义售后类型。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID
* @param {string} params.type 类型编码
* @param {string} params.name 类型名称
* @param {*} [params.sortOrder] 排序值
* @param {*} [params.isEnabled] 是否启用(0/1)
* @return {Promise<Object>} 新创建的售后类型记录
* @throws {Error} 参数不合法、编码重复时抛出(携带业务码)
*/
async createType(params = {}) {
const { ctx } = this;
const { warehouseId = 0, type, name, sortOrder, isEnabled } = params;
if (!warehouseId) {
throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能创建售后类型', 400);
}
const typeCode = this._validateAfterSaleTypeCode(type, '类型编码');
if (typeCode.length > 20) {
throw this._createAfterSaleTypeConfigError('类型编码长度不能超过20个字符', 400);
}
const typeName = typeof name === 'string' ? name.trim() : '';
if (!typeName) {
throw this._createAfterSaleTypeConfigError('类型名称不能为空', 400);
}
if (typeName.length > 50) {
throw this._createAfterSaleTypeConfigError('类型名称长度不能超过50个字符', 400);
}
const sortOrderValue = this._normalizeAfterSaleTypeSortOrder(sortOrder);
const isEnabledValue = this._normalizeAfterSaleTypeEnabled(isEnabled);
// 不能与系统级类型编码重复
const systemType = await ctx.model.AfterSaleType.findOne({
where: { type: typeCode, warehouse_id: null },
attributes: [ 'id' ],
raw: true,
});
if (systemType) {
throw this._createAfterSaleTypeConfigError('该类型编码与系统预设类型重复,不允许使用', 409);
}
// 同仓库内唯一(唯一索引兜底)
const existType = await ctx.model.AfterSaleType.findOne({
where: { type: typeCode, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
if (existType) {
throw this._createAfterSaleTypeConfigError('该类型编码在当前仓库已存在', 409);
}
try {
const record = await ctx.model.AfterSaleType.create({
warehouse_id: warehouseId,
type: typeCode,
name: typeName,
is_system: 0,
is_enabled: isEnabledValue,
sort_order: sortOrderValue,
});
return this._formatAfterSaleTypeConfigRow(record && record.toJSON ? record.toJSON() : record);
} catch (error) {
if (error && error.name === 'SequelizeUniqueConstraintError') {
throw this._createAfterSaleTypeConfigError('该类型编码在当前仓库已存在', 409);
}
throw error;
}
}
/**
* 更新仓库自定义售后类型(仅 name/is_enabled/sort_order 可改,type 编码不可变)。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID
* @param {number} params.id 类型主键ID
* @param {string} [params.name] 类型名称
* @param {*} [params.isEnabled] 是否启用(0/1)
* @param {*} [params.sortOrder] 排序值
* @return {Promise<Object>} 更新后的售后类型记录
* @throws {Error} 记录不存在/为系统预设或参数不合法时抛出(携带业务码)
*/
async updateType(params = {}) {
const { ctx } = this;
const { warehouseId = 0, id, name, sortOrder, isEnabled } = params;
if (!warehouseId) {
throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能修改售后类型', 400);
}
const typeId = Number(id);
if (!Number.isFinite(typeId) || typeId <= 0) {
throw this._createAfterSaleTypeConfigError('售后类型ID不合法', 400);
}
const record = await ctx.model.AfterSaleType.findOne({
where: { id: typeId, warehouse_id: warehouseId, is_system: 0 },
});
if (!record) {
throw this._createAfterSaleTypeConfigError('售后类型不存在、无权操作或为系统预设类型', 404);
}
const updateData = {};
if (name !== undefined) {
const typeName = typeof name === 'string' ? name.trim() : '';
if (!typeName) {
throw this._createAfterSaleTypeConfigError('类型名称不能为空', 400);
}
if (typeName.length > 50) {
throw this._createAfterSaleTypeConfigError('类型名称长度不能超过50个字符', 400);
}
updateData.name = typeName;
}
if (isEnabled !== undefined) {
updateData.is_enabled = this._normalizeAfterSaleTypeEnabled(isEnabled);
}
if (sortOrder !== undefined) {
updateData.sort_order = this._normalizeAfterSaleTypeSortOrder(sortOrder);
}
if (Object.keys(updateData).length === 0) {
throw this._createAfterSaleTypeConfigError('没有需要更新的字段', 400);
}
await record.update(updateData);
return this._formatAfterSaleTypeConfigRow(record.toJSON());
}
/**
* 删除仓库自定义售后类型(系统级禁止删除;存在当前仓库自定义子类型时拒绝删除)。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID
* @param {number} params.id 类型主键ID
* @return {Promise<Object>} { id, deleted: true }
* @throws {Error} 记录不存在/为系统预设或存在自定义子类型时抛出(携带业务码)
*/
async deleteType(params = {}) {
const { ctx } = this;
const { warehouseId = 0, id } = params;
if (!warehouseId) {
throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能删除售后类型', 400);
}
const typeId = Number(id);
if (!Number.isFinite(typeId) || typeId <= 0) {
throw this._createAfterSaleTypeConfigError('售后类型ID不合法', 400);
}
const record = await ctx.model.AfterSaleType.findOne({
where: { id: typeId, warehouse_id: warehouseId, is_system: 0 },
attributes: [ 'id', 'type' ],
raw: true,
});
if (!record) {
throw this._createAfterSaleTypeConfigError('售后类型不存在、无权操作或为系统预设类型', 404);
}
// 删除前检查该类型下是否存在当前仓库的自定义子类型,存在则拒绝(不做级联删除,避免误删数据)
const subTypeCount = await ctx.model.AfterSaleSubType.count({
where: { type: record.type, warehouse_id: warehouseId, is_system: 0 },
});
if (subTypeCount > 0) {
throw this._createAfterSaleTypeConfigError('该类型下存在当前仓库的自定义子类型,请先删除子类型', 409);
}
await ctx.model.AfterSaleType.destroy({
where: { id: typeId, warehouse_id: warehouseId, is_system: 0 },
});
return { id: typeId, deleted: true };
}
/**
* 售后子类型列表:系统级 + 当前仓库自定义合并,支持 type 过滤与按 type 分组返回。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID(0 表示无仓库上下文,仅返回系统级数据)
* @param {Object} [params.where] 标准化 where 条件
* @param {Object} [params.pagination] 分页参数 {page, pageSize}
* @param {Object} [params.sort] 排序参数 {sortField, sortOrder}
* @param {boolean} [params.group=false] 是否按 type 分组返回 groups
* @return {Promise<Object>} { list: Array, pagination: Object, groups?: Array }
*/
async getSubTypeList(params = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const {
warehouseId = 0,
where = {},
pagination = {},
sort = {},
group = false,
} = params;
const page = Math.max(1, parseInt(pagination.page) || 1);
const pageSize = Math.min(500, Math.max(1, parseInt(pagination.pageSize) || 20));
const scopeWhere = warehouseId
? { [Op.or]: [{ warehouse_id: null }, { warehouse_id: warehouseId }] }
: { warehouse_id: null };
const fieldWhere = this._buildAfterSaleSubTypeListWhere(where, Op);
const queryWhere = { ...scopeWhere, ...fieldWhere };
const order = this._buildAfterSaleSubTypeListOrder(sort);
const attributes = [
'id', 'type', 'sub_type', 'name', 'warehouse_id', 'is_system',
'is_enabled', 'sort_order', 'created_at', 'updated_at',
];
const { count, rows } = await ctx.model.AfterSaleSubType.findAndCountAll({
where: queryWhere,
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
attributes,
});
const totalPages = Math.ceil(count / pageSize);
const result = {
list: rows.map(row => this._formatAfterSaleTypeConfigRow(row)),
pagination: {
page,
pageSize,
total: count,
totalPages,
hasPrevious: page > 1,
hasNext: page * pageSize < count,
},
};
// 按 type 分组:基于全量过滤结果(不受分页影响)构建分组结构
if (group) {
const typeRows = await ctx.model.AfterSaleType.findAll({
where: scopeWhere,
attributes: [ 'type', 'name' ],
raw: true,
});
const typeNameMap = {};
for (const row of typeRows) {
typeNameMap[row.type] = row.name;
}
const allRows = await ctx.model.AfterSaleSubType.findAll({
where: queryWhere,
order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
attributes,
});
const groups = [];
const groupIndexMap = new Map();
for (const row of allRows) {
if (!groupIndexMap.has(row.type)) {
groupIndexMap.set(row.type, groups.length);
groups.push({
type: row.type,
name: typeNameMap[row.type] || row.type,
items: [],
});
}
groups[groupIndexMap.get(row.type)].items.push(this._formatAfterSaleTypeConfigRow(row));
}
result.groups = groups;
}
return result;
}
/**
* 创建仓库自定义售后子类型。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID
* @param {string} params.type 所属类型编码(必须已存在且启用)
* @param {string} params.subType 子类型编码
* @param {string} params.name 子类型名称
* @param {*} [params.sortOrder] 排序值
* @param {*} [params.isEnabled] 是否启用(0/1)
* @return {Promise<Object>} 新创建的售后子类型记录
* @throws {Error} 参数不合法、类型不存在/停用、编码重复时抛出(携带业务码)
*/
async createSubType(params = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const { warehouseId = 0, type, subType, name, sortOrder, isEnabled } = params;
if (!warehouseId) {
throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能创建售后子类型', 400);
}
const typeCode = this._validateAfterSaleTypeCode(type, '类型编码');
if (typeCode.length > 20) {
throw this._createAfterSaleTypeConfigError('类型编码长度不能超过20个字符', 400);
}
const subTypeCode = this._validateAfterSaleTypeCode(subType, '子类型编码');
if (subTypeCode.length > 50) {
throw this._createAfterSaleTypeConfigError('子类型编码长度不能超过50个字符', 400);
}
const subTypeName = typeof name === 'string' ? name.trim() : '';
if (!subTypeName) {
throw this._createAfterSaleTypeConfigError('子类型名称不能为空', 400);
}
if (subTypeName.length > 50) {
throw this._createAfterSaleTypeConfigError('子类型名称长度不能超过50个字符', 400);
}
// 所属类型必须存在(系统级或当前仓库自定义)且启用
const typeRecord = await ctx.model.AfterSaleType.findOne({
where: {
[Op.or]: [
{ type: typeCode, warehouse_id: null },
{ type: typeCode, warehouse_id: warehouseId },
],
},
attributes: [ 'id', 'is_enabled' ],
raw: true,
});
if (!typeRecord) {
throw this._createAfterSaleTypeConfigError('售后类型不存在', 400);
}
if (Number(typeRecord.is_enabled) !== 1) {
throw this._createAfterSaleTypeConfigError('售后类型已停用,不能添加子类型', 400);
}
// 不能与系统级同 type 下的子类型编码重复
const systemSubType = await ctx.model.AfterSaleSubType.findOne({
where: { type: typeCode, sub_type: subTypeCode, warehouse_id: null },
attributes: [ 'id' ],
raw: true,
});
if (systemSubType) {
throw this._createAfterSaleTypeConfigError('该子类型编码与系统预设重复,不允许使用', 409);
}
// 同类型同仓库内唯一(唯一索引兜底)
const existSubType = await ctx.model.AfterSaleSubType.findOne({
where: { type: typeCode, sub_type: subTypeCode, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
if (existSubType) {
throw this._createAfterSaleTypeConfigError('该子类型编码在当前仓库已存在', 409);
}
const sortOrderValue = this._normalizeAfterSaleTypeSortOrder(sortOrder);
const isEnabledValue = this._normalizeAfterSaleTypeEnabled(isEnabled);
try {
const record = await ctx.model.AfterSaleSubType.create({
warehouse_id: warehouseId,
type: typeCode,
sub_type: subTypeCode,
name: subTypeName,
is_system: 0,
is_enabled: isEnabledValue,
sort_order: sortOrderValue,
});
return this._formatAfterSaleTypeConfigRow(record && record.toJSON ? record.toJSON() : record);
} catch (error) {
if (error && error.name === 'SequelizeUniqueConstraintError') {
throw this._createAfterSaleTypeConfigError('该子类型编码在当前仓库已存在', 409);
}
throw error;
}
}
/**
* 更新仓库自定义售后子类型(仅 name/is_enabled/sort_order 可改,type 与 sub_type 编码不可变)。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID
* @param {number} params.id 子类型主键ID
* @param {string} [params.name] 子类型名称
* @param {*} [params.isEnabled] 是否启用(0/1)
* @param {*} [params.sortOrder] 排序值
* @return {Promise<Object>} 更新后的售后子类型记录
* @throws {Error} 记录不存在/为系统预设或参数不合法时抛出(携带业务码)
*/
async updateSubType(params = {}) {
const { ctx } = this;
const { warehouseId = 0, id, name, sortOrder, isEnabled } = params;
if (!warehouseId) {
throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能修改售后子类型', 400);
}
const subTypeId = Number(id);
if (!Number.isFinite(subTypeId) || subTypeId <= 0) {
throw this._createAfterSaleTypeConfigError('售后子类型ID不合法', 400);
}
const record = await ctx.model.AfterSaleSubType.findOne({
where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 },
});
if (!record) {
throw this._createAfterSaleTypeConfigError('售后子类型不存在、无权操作或为系统预设类型', 404);
}
const updateData = {};
if (name !== undefined) {
const subTypeName = typeof name === 'string' ? name.trim() : '';
if (!subTypeName) {
throw this._createAfterSaleTypeConfigError('子类型名称不能为空', 400);
}
if (subTypeName.length > 50) {
throw this._createAfterSaleTypeConfigError('子类型名称长度不能超过50个字符', 400);
}
updateData.name = subTypeName;
}
if (isEnabled !== undefined) {
updateData.is_enabled = this._normalizeAfterSaleTypeEnabled(isEnabled);
}
if (sortOrder !== undefined) {
updateData.sort_order = this._normalizeAfterSaleTypeSortOrder(sortOrder);
}
if (Object.keys(updateData).length === 0) {
throw this._createAfterSaleTypeConfigError('没有需要更新的字段', 400);
}
await record.update(updateData);
return this._formatAfterSaleTypeConfigRow(record.toJSON());
}
/**
* 删除仓库自定义售后子类型(系统级禁止删除;已被售后单使用时拒绝删除)。
* @param {Object} params 参数对象
* @param {number} params.warehouseId 当前仓库ID
* @param {number} params.id 子类型主键ID
* @return {Promise<Object>} { id, deleted: true }
* @throws {Error} 记录不存在/为系统预设或已被售后单使用时抛出(携带业务码)
*/
async deleteSubType(params = {}) {
const { ctx } = this;
const { warehouseId = 0, id } = params;
if (!warehouseId) {
throw this._createAfterSaleTypeConfigError('无法获取当前仓库上下文,不能删除售后子类型', 400);
}
const subTypeId = Number(id);
if (!Number.isFinite(subTypeId) || subTypeId <= 0) {
throw this._createAfterSaleTypeConfigError('售后子类型ID不合法', 400);
}
const record = await ctx.model.AfterSaleSubType.findOne({
where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 },
attributes: [ 'id', 'type', 'sub_type' ],
raw: true,
});
if (!record) {
throw this._createAfterSaleTypeConfigError('售后子类型不存在、无权操作或为系统预设类型', 404);
}
// 检查 wms_after_sale 引用(命中 idx_type_subtype 索引,成本可控),被使用时拒绝删除
const usedCount = await ctx.model.AfterSale.count({
where: {
warehouse_id: warehouseId,
type: record.type,
sub_type: record.sub_type,
deleted_at: null,
},
});
if (usedCount > 0) {
throw this._createAfterSaleTypeConfigError('该子类型已被售后单使用,无法删除', 409);
}
await ctx.model.AfterSaleSubType.destroy({
where: { id: subTypeId, warehouse_id: warehouseId, is_system: 0 },
});
return { id: subTypeId, deleted: true };
}
}
module.exports = AfterSaleService;

View File

@ -731,6 +731,56 @@ class InboxGroupService extends Service {
return rows;
}
/**
* 按货主ID列表查询指定子类型的货主群(如收货群 receiving / 售后群 after_sales)。
*
* 匹配规则:
* 1. group_type = 'store'
* 2. sub_type 在传入子类型列表中
* 3. store_id 在传入列表中
* 4. is_blocked = 0
*
* @param {Object} params 查询参数。
* @param {number[]} params.storeIds 货主ID列表。
* @param {number} params.warehouseId 仓库ID。
* @param {string[]} params.subTypes 货主群子类型列表(如 [ 'receiving' ])。
* @return {Promise<Array>} 货主群列表 [{group_id, group_name, store_id, sub_type, ext_data}]。
*/
async findStoreGroups({ storeIds, warehouseId, subTypes }) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const ids = (Array.isArray(storeIds) ? storeIds : [ storeIds ])
.map(id => Number(id))
.filter(id => Number.isFinite(id) && id > 0);
const subs = (Array.isArray(subTypes) ? subTypes : [ subTypes ])
.map(s => String(s || '').trim())
.filter(Boolean);
if (ids.length === 0 || subs.length === 0) {
return [];
}
const rows = await ctx.model.InboxGroup.findAll({
attributes: [ 'id', 'group_name', 'group_id', 'store_id', 'sub_type', 'ext_data' ],
where: {
warehouse_id: Number(warehouseId),
group_type: 'store',
sub_type: { [Op.in]: subs },
store_id: { [Op.in]: ids },
is_blocked: 0,
},
raw: true,
});
ctx.logger.info(
`[inbox group] 查货主群 warehouse=${warehouseId} ` +
`stores=[${ids.join(',')}] subTypes=[${subs.join(',')}] found=${rows.length}`
);
return rows;
}
}
module.exports = InboxGroupService;

View File

@ -0,0 +1,303 @@
'use strict';
/**
* 创建售后类型/子类型自定义表,支持以仓库为维度做隔离。
*
* 表结构:
* 1. wms_after_sale_type:售后类型表
* 2. wms_after_sale_sub_type:售后子类型表(type 编码关联类型表)
*
* 隔离语义:
* - warehouse_id = NULL 且 is_system = 1:系统级类型,全部仓库可读(不允许编辑/删除)。
* - warehouse_id = 仓库ID 且 is_system = 0:仓库自定义类型,仅该仓库可见。
*
* 数据播种:
* 将当前 wms_after_sale 已有的售后类型/子类型枚举(order/receiving/entry/stockout
* 及其全部子类型)作为系统级(warehouse_id=NULL, is_system=1)写入两表。
* 由于 MySQL 唯一索引对 NULL 不生效,播种采用"先查后插"保证幂等。
*/
const TYPE_TABLE = 'wms_after_sale_type';
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
/**
* 现有售后类型 + 子类型枚举(与 app/model/after_sale.js 的 AFTER_SALE_TYPES 保持一致)。
* @type {Array<{type: string, name: string, subTypes: Array<{sub_type: string, name: string}>}>}
*/
const SYSTEM_AFTER_SALE_TYPES = [
{
type: 'order',
name: '订单',
subTypes: [
{ sub_type: 'damage', name: '破损' },
{ sub_type: 'missing_item', name: '少发' },
{ sub_type: 'mis_shipment', name: '错发' },
{ sub_type: 'wrong_sku', name: '错品' },
{ sub_type: 'quality_issue', name: '质量问题' },
{ sub_type: 'delivery_delay', name: '发货延迟' },
{ sub_type: 'logistics_issue', name: '物流异常' },
{ sub_type: 'rejected', name: '客户拒收' },
{ sub_type: 'intercept', name: '拦截' },
{ sub_type: 'verify_delivery', name: '核实签收' },
{ sub_type: 'urge', name: '催件' },
{ sub_type: 'extra_item', name: '多发' },
{ sub_type: 'change_address', name: '改地址' },
{ sub_type: 'change_carrier', name: '换快递' },
{ sub_type: 'pickup', name: '揽收' },
{ sub_type: 'weight_issue', name: '重量异常' },
{ sub_type: 'freight_issue', name: '运费争议' },
{ sub_type: 'other', name: '其他' },
],
},
{
type: 'receiving',
name: '收货单',
subTypes: [
{ sub_type: 'shortage', name: '少货' },
{ sub_type: 'damage', name: '破损' },
{ sub_type: 'wrong_sku', name: '错品' },
{ sub_type: 'quality_issue', name: '质量问题' },
{ sub_type: 'other', name: '其他' },
],
},
{
type: 'entry',
name: '入库单',
subTypes: [
{ sub_type: 'shortage', name: '少货' },
{ sub_type: 'damage', name: '破损' },
{ sub_type: 'wrong_sku', name: '错品' },
{ sub_type: 'quality_issue', name: '质量问题' },
{ sub_type: 'other', name: '其他' },
],
},
{
type: 'stockout',
name: '出库单',
subTypes: [
{ sub_type: 'return_issue', name: '退货异常' },
{ sub_type: 'wrong_outbound', name: '错发' },
{ sub_type: 'shortage', name: '少发' },
{ sub_type: 'other', name: '其他' },
],
},
];
/**
* 查询系统级类型/子类型是否已存在(warehouse_id IS NULL 的行)。
* @param {object} queryInterface Sequelize QueryInterface 实例
* @param {string} table 表名
* @param {string} where 额外 where 条件(可含 :name 占位符)
* @param {object} replacements 占位符替换值
* @return {Promise<boolean>} 已存在返回 true
*/
async function findSystemIds(queryInterface, table, where, replacements) {
const rows = await queryInterface.sequelize.query(
`SELECT id FROM \`${table}\` WHERE ${where} AND warehouse_id IS NULL AND is_system = 1 LIMIT 1`,
{ replacements, type: queryInterface.sequelize.QueryTypes.SELECT }
);
return rows.length > 0;
}
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
// ─── 1. 售后类型表 ─────────────────────────────────────────
if (!exists(TYPE_TABLE)) {
await queryInterface.createTable(TYPE_TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)',
},
type: {
type: Sequelize.STRING(20),
allowNull: false,
comment: '售后类型编码:order/receiving/entry/stockout,仓库自定义可自定义编码',
},
name: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '售后类型名称',
},
is_system: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义',
},
is_enabled: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:1=启用,0=停用',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '排序值,越小越靠前',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
// 仓库内类型编码唯一(系统级 warehouse_id=NULL 不参与唯一约束,系统编码唯一性由应用层保证)
await queryInterface.addIndex(TYPE_TABLE, [ 'type', 'warehouse_id' ], {
unique: true,
name: 'uk_type_warehouse',
});
await queryInterface.addIndex(TYPE_TABLE, [ 'warehouse_id' ], {
name: 'idx_warehouse_id',
});
await queryInterface.addIndex(TYPE_TABLE, [ 'is_system' ], {
name: 'idx_is_system',
});
}
// ─── 2. 售后子类型表 ───────────────────────────────────────
if (!exists(SUB_TYPE_TABLE)) {
await queryInterface.createTable(SUB_TYPE_TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)',
},
type: {
type: Sequelize.STRING(20),
allowNull: false,
comment: '所属售后类型编码(对应 wms_after_sale_type.type)',
},
sub_type: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '售后子类型编码,与 type 组成二级分类(与 wms_after_sale.sub_type 对应)',
},
name: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '售后子类型名称',
},
is_system: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义',
},
is_enabled: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:1=启用,0=停用',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '排序值,越小越靠前',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
// 同一类型下仓库内子类型编码唯一
await queryInterface.addIndex(SUB_TYPE_TABLE, [ 'type', 'sub_type', 'warehouse_id' ], {
unique: true,
name: 'uk_type_subtype_warehouse',
});
await queryInterface.addIndex(SUB_TYPE_TABLE, [ 'warehouse_id' ], {
name: 'idx_warehouse_id',
});
await queryInterface.addIndex(SUB_TYPE_TABLE, [ 'is_system' ], {
name: 'idx_is_system',
});
}
// ─── 3. 播种现有类型为系统级(先查后插,幂等) ───────────────
const now = new Date();
for (const [ typeIndex, item ] of SYSTEM_AFTER_SALE_TYPES.entries()) {
const typeExists = await findSystemIds(queryInterface, TYPE_TABLE, '`type` = :type', { type: item.type });
if (!typeExists) {
await queryInterface.bulkInsert(TYPE_TABLE, [{
warehouse_id: null,
type: item.type,
name: item.name,
is_system: 1,
is_enabled: 1,
sort_order: typeIndex + 1,
created_at: now,
updated_at: now,
}]);
}
const subTypeRows = [];
for (const [ subIndex, sub ] of item.subTypes.entries()) {
const subExists = await findSystemIds(
queryInterface,
SUB_TYPE_TABLE,
'`type` = :type AND `sub_type` = :subType',
{ type: item.type, subType: sub.sub_type }
);
if (!subExists) {
subTypeRows.push({
warehouse_id: null,
type: item.type,
sub_type: sub.sub_type,
name: sub.name,
is_system: 1,
is_enabled: 1,
sort_order: subIndex + 1,
created_at: now,
updated_at: now,
});
}
}
if (subTypeRows.length > 0) {
await queryInterface.bulkInsert(SUB_TYPE_TABLE, subTypeRows);
}
}
},
down: async queryInterface => {
await queryInterface.dropTable(SUB_TYPE_TABLE);
await queryInterface.dropTable(TYPE_TABLE);
},
};

View File

@ -0,0 +1,162 @@
'use strict';
/**
* 创建售后关键词表 wms_after_sale_keyword:关键词 → 售后子类型 映射。
*
* 语义:
* - 多个关键词可对应同一个售后子类型(1:N),一个关键词在同一仓库内唯一(只映射一个子类型)。
* - 仓库维度隔离:warehouse_id=NULL + is_system=1 为系统级关键词,全部仓库可见;
* warehouse_id=仓库ID + is_system=0 为仓库自定义关键词,仅该仓库可见。
* - 匹配优先级:sort_order 小者优先(AI 按关键词推断子类型时,先取仓库自定义+系统级合并列表,
* 按关键词长度降序、sort_order 升序匹配)。
*
* 数据播种:将 app/service/inbox/rules.js 中硬编码的 EXPRESS_SUB_TYPE_RULES
* (快递反馈→订单售后子类型 8 组关键词)作为系统级写入本表。
* 由于 MySQL 唯一索引对 NULL 不生效,播种采用"先查后插"保证幂等。
*/
const TABLE = 'wms_after_sale_keyword';
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
/**
* 系统级预设关键词(来源:inbox/rules.js EXPRESS_SUB_TYPE_RULES,type=order)。
* @type {Array<{sub_type: string, keywords: string[]}>}
*/
const SYSTEM_KEYWORD_RULES = [
{ sub_type: 'verify_delivery', keywords: [ '核实签收', '签收核实', '已签收', '签收' ] },
{ sub_type: 'damage', keywords: [ '破损', '坏了', '破损件' ] },
{ sub_type: 'missing_item', keywords: [ '少发', '漏发', '发少' ] },
{ sub_type: 'change_address', keywords: [ '改地址', '地址更改', '改址' ] },
{ sub_type: 'change_carrier', keywords: [ '换快递', '改快递' ] },
{ sub_type: 'urge', keywords: [ '催件', '催派', '催促' ] },
{ sub_type: 'delivery_delay', keywords: [ '发货延迟', '延迟发货', '催发货' ] },
{ sub_type: 'rejected', keywords: [ '拒收' ] },
];
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
// ─── 建表 ─────────────────────────────────────────────────
if (!exists) {
await queryInterface.createTable(TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)',
},
sub_type_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
},
keyword: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '关键词,命中即映射到对应售后子类型',
},
is_system: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义',
},
is_enabled: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:1=启用,0=停用',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '匹配优先级,数值小者优先(同长度命中时生效)',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
// 同一仓库内关键词唯一(系统级 warehouse_id=NULL 不参与唯一约束,由应用层保证)
await queryInterface.addIndex(TABLE, [ 'keyword', 'warehouse_id' ], {
unique: true,
name: 'uk_keyword_warehouse',
});
await queryInterface.addIndex(TABLE, [ 'sub_type_id' ], {
name: 'idx_sub_type_id',
});
await queryInterface.addIndex(TABLE, [ 'warehouse_id' ], {
name: 'idx_warehouse_id',
});
await queryInterface.addIndex(TABLE, [ 'is_system' ], {
name: 'idx_is_system',
});
}
// ─── 播种系统级关键词(先查后插,幂等) ────────────────────
const { sequelize } = queryInterface;
const now = new Date();
for (const [ ruleIndex, rule ] of SYSTEM_KEYWORD_RULES.entries()) {
// 定位系统级订单子类型(warehouse_id IS NULL)
const subRows = await sequelize.query(
`SELECT id FROM \`${SUB_TYPE_TABLE}\`
WHERE type = 'order' AND sub_type = :subType AND warehouse_id IS NULL AND is_system = 1
LIMIT 1`,
{ replacements: { subType: rule.sub_type }, type: sequelize.QueryTypes.SELECT }
);
if (subRows.length === 0) {
console.warn(`[MIGRATION] 跳过播种:未找到系统级子类型 order.${rule.sub_type}`);
continue;
}
const subTypeId = subRows[0].id;
const rows = [];
for (const [ kwIndex, kw ] of rule.keywords.entries()) {
const existsRows = await sequelize.query(
`SELECT id FROM \`${TABLE}\`
WHERE keyword = :kw AND warehouse_id IS NULL AND is_system = 1
LIMIT 1`,
{ replacements: { kw }, type: sequelize.QueryTypes.SELECT }
);
if (existsRows.length === 0) {
rows.push({
warehouse_id: null,
sub_type_id: subTypeId,
keyword: kw,
is_system: 1,
is_enabled: 1,
sort_order: ruleIndex * 100 + kwIndex,
created_at: now,
updated_at: now,
});
}
}
if (rows.length > 0) {
await queryInterface.bulkInsert(TABLE, rows);
}
}
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE);
},
};

View File

@ -0,0 +1,91 @@
'use strict';
/**
* 创建取号规则表 wms_inbox_number_rule。
*
* 语义:从接收到的消息中,关键词命中售后子类型后,按该子类型关联的取号规则
* 用正则从消息文本中提取符合规则的单据号,用于替代硬编码的下一步处理。
* 子类型与规则的关联见 20260916162000-create-sub-type-number-rule-relation.js(多对多)。
*
* 提取目标类型(target)枚举:
* - waybill_no 运单号
* - receiving_no 收货单号
* - entry_order_no 入库单号
* - stockout_no 出库单号
* - order_no 订单编号
* - source_order_codes 交易平台订单编号(多个合成)
* - express_name 快递名称
* - plate_no 车牌号
*/
const RULE_TABLE = 'wms_inbox_number_rule';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
// ─── 1. 建取号规则表 ───────────────────────────────────────
if (!exists(RULE_TABLE)) {
await queryInterface.createTable(RULE_TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '规则名称,如:运单号提取/收货单号提取/平台订单号提取',
},
target: {
type: Sequelize.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: Sequelize.STRING(500),
allowNull: false,
comment: '取号正则(JS 正则源字符串,不含首尾斜杠,支持全局匹配)',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '规则尝试顺序,数值小者优先',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
await queryInterface.addIndex(RULE_TABLE, [ 'name' ], {
unique: true,
name: 'uk_name',
});
await queryInterface.addIndex(RULE_TABLE, [ 'target' ], {
name: 'idx_target',
});
}
},
down: async queryInterface => {
const tables = await queryInterface.showAllTables();
const ruleExists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === RULE_TABLE);
if (ruleExists) {
await queryInterface.dropTable(RULE_TABLE);
}
},
};

View File

@ -0,0 +1,36 @@
'use strict';
/**
* 清理旧命名的取号规则表 wms_number_rule(已改名为 wms_inbox_number_rule)。
*
* 背景:20260916160000 迁移最初以表名 wms_number_rule 在开发库执行过,
* 后与 wms_number_sequence 存在语义混淆风险,改名为 wms_inbox_number_rule。
* 本迁移仅负责开发库旧表清理与旧 SequelizeMeta 记录清理;生产库从未执行旧表名,
* up 中幂等跳过。
*/
const LEGACY_TABLE = 'wms_number_rule';
const LEGACY_MIGRATION_NAME = '20260916160000-create-wms-number-rule-and-link-sub-type.js';
module.exports = {
up: async queryInterface => {
const { sequelize } = queryInterface;
const tables = await queryInterface.showAllTables();
const legacyExists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === LEGACY_TABLE);
// 旧表清理(仅开发库存在;旧表无数据,直接删除)
if (legacyExists) {
await queryInterface.dropTable(LEGACY_TABLE);
}
// 旧迁移记录清理(仅开发库有该记录)
await sequelize.query(
'DELETE FROM SequelizeMeta WHERE name = :name',
{ replacements: { name: LEGACY_MIGRATION_NAME } }
);
},
down: async () => {
// 旧表不重建(改名后不可逆回旧命名)
},
};

View File

@ -0,0 +1,92 @@
'use strict';
/**
* 创建售后子类型与取号规则的多对多中间表 wms_after_sale_sub_type_rule,
* 并清理旧单列设计(number_rule_id,仅开发库存在)。
*
* 语义:一个售后子类型可关联多个取号规则(如"改快递"需同时取运单号与平台订单号),
* 一个取号规则可被多个子类型复用。sort_order 表示同一子类型下规则的提取顺序。
*/
const RELATION_TABLE = 'wms_after_sale_sub_type_rule';
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
// ─── 1. 建中间表 ───────────────────────────────────────────
if (!exists(RELATION_TABLE)) {
await queryInterface.createTable(RELATION_TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
sub_type_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
},
number_rule_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '取号规则ID(关联 wms_inbox_number_rule.id)',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '同一子类型下规则的提取顺序,数值小者优先',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
await queryInterface.addIndex(RELATION_TABLE, [ 'sub_type_id', 'number_rule_id' ], {
unique: true,
name: 'uk_sub_type_rule',
});
await queryInterface.addIndex(RELATION_TABLE, [ 'number_rule_id' ], {
name: 'idx_number_rule_id',
});
}
// ─── 2. 清理旧单列设计(仅开发库存在,生产幂等跳过) ─────────
if (exists(SUB_TYPE_TABLE)) {
const subTypeColumns = await queryInterface.describeTable(SUB_TYPE_TABLE);
if (subTypeColumns.number_rule_id) {
const indexes = await queryInterface.showIndex(SUB_TYPE_TABLE);
const legacyIndex = indexes.find(
i => (typeof i === 'string' ? i : i.name) === 'idx_number_rule_id'
);
if (legacyIndex) {
await queryInterface.removeIndex(SUB_TYPE_TABLE, 'idx_number_rule_id');
}
await queryInterface.removeColumn(SUB_TYPE_TABLE, 'number_rule_id');
}
}
},
down: async queryInterface => {
const tables = await queryInterface.showAllTables();
const relationExists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === RELATION_TABLE);
if (relationExists) {
await queryInterface.dropTable(RELATION_TABLE);
}
// 旧单列不恢复(已被多对多中间表取代)
},
};

View File

@ -0,0 +1,79 @@
'use strict';
/**
* 播种取号规则数据:把 app/service/inbox/rules.js 现有硬编码的提取方法
* (extractWaybills / extractOrders / EXPRESS_NAMES)落库为 wms_inbox_number_rule 规则。
*
* 幂等设计:基于唯一索引 uk_name 做 INSERT IGNORE,不会重复插入。
*
* 说明:现有提取逻辑中正则之外的部分(运单号过滤:手机号/座机/日期戳/售后单号;
* 订单号兜底取纯数字)仍由代码兜底处理,正则列只存核心匹配源串。
*/
const TABLE = 'wms_inbox_number_rule';
const SEED_RULES = [
{
name: '运单号提取',
target: 'waybill_no',
// 对应 extractWaybills 的核心匹配:[A-Za-z0-9_-]{10,24}(过滤逻辑由代码兜底)
regexp: '[A-Za-z0-9_-]{10,24}',
sort_order: 1,
},
{
name: '订单编号提取',
target: 'order_no',
// 对应 extractOrders 优先规则:SYS/SO/DD 前缀及字母数字混合号
regexp: '(?<![A-Za-z0-9])SYS\\d{4,}|(?<![A-Za-z0-9])SO[A-Za-z0-9-]{4,}|(?<![A-Za-z0-9])DD[A-Za-z0-9-]{4,}|(?<![A-Za-z0-9])[A-Z]{2,8}-?\\d{4,}',
sort_order: 2,
},
{
name: '平台订单号提取',
target: 'source_order_codes',
// 对应 extractOrders 兜底规则:12~20 位纯数字(多个合成,代码侧去重)
regexp: '(?<!\\d)\\d{12,20}(?!\\d)',
sort_order: 3,
},
{
name: '快递名称提取',
target: 'express_name',
// 对应 EXPRESS_NAMES 列表(长名在前,避免短名截断)
regexp: '中通快运|中通快递|极兔速递|京东快递|圆通快递|申通快递|顺丰速运|韵达快递|邮政小包|圆通|中通|申通|顺丰|韵达|极兔|邮政|EMS|京东|德邦',
sort_order: 4,
},
];
module.exports = {
up: async queryInterface => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
if (!exists) {
throw new Error(`表 ${TABLE} 不存在,请先执行 20260916160000-create-wms-inbox-number-rule-and-link-sub-type.js`);
}
const { sequelize } = queryInterface;
for (const rule of SEED_RULES) {
await sequelize.query(
'INSERT IGNORE INTO `' + TABLE + '` (name, target, `regexp`, sort_order, created_at, updated_at) '
+ 'VALUES (:name, :target, :regexp, :sortOrder, NOW(), NOW())',
{
replacements: {
name: rule.name,
target: rule.target,
regexp: rule.regexp,
sortOrder: rule.sort_order,
},
type: sequelize.QueryTypes.INSERT,
}
);
}
},
down: async queryInterface => {
const names = SEED_RULES.map(r => r.name);
await queryInterface.sequelize.query(
'DELETE FROM `' + TABLE + '` WHERE name IN (:names)',
{ replacements: { names } }
);
},
};

View File

@ -0,0 +1,106 @@
'use strict';
/**
* 播种系统级售后子类型与取号规则的关联数据(多对多中间表)。
*
* 映射来源:order 类型系统子类型的消息处理需求——
* - 改地址/换快递:需运单号 + 平台订单号(改快递操作需要对应平台单号)
* - 其余子类型:目前仅需运单号
*
* 幂等设计:基于唯一索引 uk_sub_type_rule(sub_type_id, number_rule_id) 做 INSERT IGNORE,
* 不会重复插入已存在的关联。子类型按(type=order + warehouse_id IS NULL)定位,
* 规则按 name 定位。
*/
const RELATION_TABLE = 'wms_after_sale_sub_type_rule';
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
const RULE_TABLE = 'wms_inbox_number_rule';
/** 子类型编码 → 规则名称列表(按 sort_order 顺序) */
const SUB_TYPE_RULE_MAP = [
{ sub_type: 'verify_delivery', rules: [ '运单号提取' ] },
{ sub_type: 'damage', rules: [ '运单号提取' ] },
{ sub_type: 'missing_item', rules: [ '运单号提取' ] },
{ sub_type: 'change_address', rules: [ '运单号提取', '平台订单号提取' ] },
{ sub_type: 'change_carrier', rules: [ '运单号提取', '平台订单号提取' ] },
{ sub_type: 'urge', rules: [ '运单号提取' ] },
{ sub_type: 'delivery_delay', rules: [ '运单号提取' ] },
{ sub_type: 'rejected', rules: [ '运单号提取' ] },
];
module.exports = {
up: async queryInterface => {
const { sequelize } = queryInterface;
for (const item of SUB_TYPE_RULE_MAP) {
// 定位系统级 order 子类型
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: item.sub_type },
type: sequelize.QueryTypes.SELECT,
}
);
if (subRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${item.sub_type}`);
continue;
}
const subTypeId = subRows[0].id;
for (const [ ruleIndex, ruleName ] of item.rules.entries()) {
const ruleRows = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE name = :name LIMIT 1',
{ replacements: { name: ruleName }, type: sequelize.QueryTypes.SELECT }
);
if (ruleRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到取号规则 ${ruleName}`);
continue;
}
const ruleId = ruleRows[0].id;
await sequelize.query(
'INSERT IGNORE INTO `' + RELATION_TABLE + '` '
+ '(sub_type_id, number_rule_id, sort_order, created_at, updated_at) '
+ 'VALUES (:subTypeId, :ruleId, :sortOrder, NOW(), NOW())',
{
replacements: { subTypeId, ruleId, sortOrder: ruleIndex + 1 },
type: sequelize.QueryTypes.INSERT,
}
);
}
}
},
down: async queryInterface => {
const { sequelize } = queryInterface;
for (const item of SUB_TYPE_RULE_MAP) {
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: item.sub_type },
type: sequelize.QueryTypes.SELECT,
}
);
if (subRows.length === 0) continue;
const subTypeId = subRows[0].id;
const ruleRows = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE name IN (:names)',
{
replacements: { names: item.rules },
type: sequelize.QueryTypes.SELECT,
}
);
if (ruleRows.length === 0) continue;
const ruleIds = ruleRows.map(r => r.id);
await sequelize.query(
'DELETE FROM `' + RELATION_TABLE + '` '
+ 'WHERE sub_type_id = :subTypeId AND number_rule_id IN (:ruleIds)',
{ replacements: { subTypeId, ruleIds } }
);
}
},
};

View File

@ -0,0 +1,94 @@
'use strict';
/**
* 创建售后自定义回复表 wms_after_sale_reply。
*
* 语义:消息关键词命中售后子类型并完成处理后,按子类型返回自定义回复文案。
* - 系统级(warehouse_id=NULL):全部仓库可读的默认回复。
* - 仓库级(warehouse_id=仓库ID):该仓库自定义回复,设置了自动覆盖系统级
* (读取时优先仓库级,无仓库级再回退系统级)。
* - 每个仓库每种子类型只允许一条仓库级回复(唯一索引 uk_warehouse_sub_type 保证);
* 系统级每种子类型只允许一条,由应用层校验(MySQL 唯一索引对 NULL 不生效)。
*/
const TABLE = 'wms_after_sale_reply';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
if (exists) return;
await queryInterface.createTable(TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
defaultValue: null,
comment: '仓库ID(NULL=系统级默认回复;非NULL=仓库级自定义回复,覆盖系统级)',
},
sub_type_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
},
reply: {
type: Sequelize.TEXT,
allowNull: false,
comment: '自定义回复文案(支持换行,可含占位符)',
},
is_reply: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否回复:1=命中后回复,0=静默不回复',
},
no_number_hint: {
type: Sequelize.STRING(500),
allowNull: true,
defaultValue: null,
comment: '未取到单据号时的引导语(如:请提供运单号;为空则用默认引导语)',
},
is_enabled: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:1=启用,0=停用(停用视为未设置,回退系统级)',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
// 仓库级:每仓库每子类型唯一(系统级 warehouse_id=NULL 由应用层保证唯一)
await queryInterface.addIndex(TABLE, [ 'warehouse_id', 'sub_type_id' ], {
unique: true,
name: 'uk_warehouse_sub_type',
});
await queryInterface.addIndex(TABLE, [ 'sub_type_id' ], {
name: 'idx_sub_type_id',
});
await queryInterface.addIndex(TABLE, [ 'is_enabled' ], {
name: 'idx_is_enabled',
});
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE);
},
};

View File

@ -0,0 +1,54 @@
'use strict';
/**
* 给 wms_after_sale_reply 补两列(开发库补丁,生产幂等跳过)。
*
* 背景:20260916190000 建表迁移在开发库执行后补充了两个字段设计——
* - is_reply:是否回复(1=命中后回复,0=静默不回复)
* - no_number_hint:未取到单据号时的引导语
* 原迁移文件已同步更新,生产执行时会直接带两列,本迁移在生产幂等跳过。
*/
const TABLE = 'wms_after_sale_reply';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
if (!exists) return;
const columns = await queryInterface.describeTable(TABLE);
if (!columns.is_reply) {
await queryInterface.addColumn(TABLE, 'is_reply', {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否回复:1=命中后回复,0=静默不回复',
after: 'reply',
});
}
if (!columns.no_number_hint) {
await queryInterface.addColumn(TABLE, 'no_number_hint', {
type: Sequelize.STRING(500),
allowNull: true,
defaultValue: null,
comment: '未取到单据号时的引导语(如:请提供运单号;为空则用默认引导语)',
after: 'is_reply',
});
}
},
down: async queryInterface => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
if (!exists) return;
const columns = await queryInterface.describeTable(TABLE);
if (columns.no_number_hint) {
await queryInterface.removeColumn(TABLE, 'no_number_hint');
}
if (columns.is_reply) {
await queryInterface.removeColumn(TABLE, 'is_reply');
}
},
};

View File

@ -0,0 +1,53 @@
'use strict';
/**
* 播种"车牌提取"取号规则到 wms_inbox_number_rule。
*
* 正则说明:中国车牌(含传统蓝牌/黄牌与新能源绿牌,兼容"·"分隔点):
* - 省简称 + 发牌机关字母 + 5 位号码(传统)
* - 省简称 + 字母 + D/F 开头 6 位号码(新能源)
* - 末位兼容 挂/学/警/港/澳 等特殊字符
*
* 幂等设计:基于唯一索引 uk_name 做 INSERT IGNORE。
*/
const TABLE = 'wms_inbox_number_rule';
const SEED_RULE = {
name: '车牌提取',
target: 'plate_no',
regexp: '[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])',
sort_order: 5,
};
module.exports = {
up: async queryInterface => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
if (!exists) {
throw new Error(`表 ${TABLE} 不存在,请先执行 20260916160000-create-wms-inbox-number-rule-and-link-sub-type.js`);
}
const { sequelize } = queryInterface;
await sequelize.query(
'INSERT IGNORE INTO `' + TABLE + '` (name, target, `regexp`, sort_order, created_at, updated_at) '
+ 'VALUES (:name, :target, :regexp, :sortOrder, NOW(), NOW())',
{
replacements: {
name: SEED_RULE.name,
target: SEED_RULE.target,
regexp: SEED_RULE.regexp,
sortOrder: SEED_RULE.sort_order,
},
type: sequelize.QueryTypes.INSERT,
}
);
},
down: async queryInterface => {
await queryInterface.sequelize.query(
'DELETE FROM `' + TABLE + '` WHERE name = :name',
{ replacements: { name: SEED_RULE.name } }
);
},
};

View File

@ -0,0 +1,27 @@
'use strict';
/**
* 修正"车牌提取"规则正则(开发库已插入旧正则,生产幂等)。
*
* 问题:旧正则 alternation 顺序导致新能源 6 位尾号被截断
* ("粤BD12345" 匹配成 "粤BD1234")。
* 修正:新能源分支 [DF][A-HJ-NP-Z0-9]{5} 前置优先,传统 5 位尾号分支靠后。
*/
const TABLE = 'wms_inbox_number_rule';
const FIXED_REGEXP = '[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])';
module.exports = {
up: async queryInterface => {
await queryInterface.sequelize.query(
'UPDATE `' + TABLE + '` SET `regexp` = :regexp, updated_at = NOW() WHERE name = :name',
{ replacements: { name: '车牌提取', regexp: FIXED_REGEXP } }
);
},
// eslint-disable-next-line no-unused-vars
down: async queryInterface => {
// 回滚不做(旧正则有截断缺陷,不回退)
},
};

View File

@ -0,0 +1,53 @@
'use strict';
/**
* 创建到货登记表 wms_inbox_arrival_register。
*
* 用途:货主/仓库群发送"到货+车牌号"时,AI 提取车牌号并登记,
* 记录货主ID、仓库ID、登记时间(created_at)、车牌号。
*
* 索引:
* idx_warehouse_plate(仓库+车牌查询某车牌在该仓库的登记记录)
* idx_store_id(按货主查询)
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, DATE } = Sequelize;
await queryInterface.createTable('wms_inbox_arrival_register', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(数据隔离维度)',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID(仓库群登记时无货主,允许为空)',
},
license_plate: {
type: STRING(20),
allowNull: false,
comment: '车牌号',
},
created_at: { type: DATE, allowNull: false, comment: '登记时间' },
updated_at: { type: DATE, allowNull: false, comment: '更新时间' },
});
await queryInterface.addIndex('wms_inbox_arrival_register', [ 'warehouse_id', 'license_plate' ], { name: 'idx_warehouse_plate' });
await queryInterface.addIndex('wms_inbox_arrival_register', [ 'store_id' ], { name: 'idx_store_id' });
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('wms_inbox_arrival_register');
},
};

View File

@ -0,0 +1,27 @@
'use strict';
/**
* 修复"车牌提取"规则正则:省份简称兼容异体字。
*
* 问题:用户输入"粵BEH9852到货"(粵 U+7CB5 为"粤 U+7CA4"的异体写法),
* 旧正则只含简体"粤",无法匹配导致"未识别到车牌号"。
* 修正:省份字符类中"粤"后补充异体"粵"。
*/
const TABLE = 'wms_inbox_number_rule';
const FIXED_REGEXP = '[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤粵青藏川宁琼使领][A-HJ-NP-Z][·.]?(?:[DF][A-HJ-NP-Z0-9]{5}|[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])';
module.exports = {
up: async queryInterface => {
await queryInterface.sequelize.query(
'UPDATE `' + TABLE + '` SET `regexp` = :regexp, updated_at = NOW() WHERE name = :name',
{ replacements: { name: '车牌提取', regexp: FIXED_REGEXP } }
);
},
// eslint-disable-next-line no-unused-vars
down: async queryInterface => {
// 回滚不做(旧正则有异体字漏匹配缺陷,不回退)
},
};

View File

@ -0,0 +1,32 @@
'use strict';
/**
* 到货登记表增加消费字段(离场登记)。
*
* 用途:离场方法(departure)命中 6 小时内未消费的登记后,
* 标记 consumed=1 并记录 consumed_at,防止重复离场。
*/
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { TINYINT, DATE } = Sequelize;
await queryInterface.addColumn('wms_inbox_arrival_register', 'consumed', {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否已消费(离场登记)0=未消费 1=已消费',
});
await queryInterface.addColumn('wms_inbox_arrival_register', 'consumed_at', {
type: DATE,
allowNull: true,
comment: '消费时间(离场时间)',
});
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.removeColumn('wms_inbox_arrival_register', 'consumed_at');
await queryInterface.removeColumn('wms_inbox_arrival_register', 'consumed');
},
};

View File

@ -0,0 +1,30 @@
'use strict';
/**
* wms_inbox_group 增加「是否模板消息回复」开关列。
* 与 ai_enabled(是否AI回复)并列:ai_enabled 控制是否启用 AI 处理,
* template_reply_enabled 控制命中处理后是否以模板消息形式回复(关闭则走普通文本回复)。
*/
const TABLE_NAME = 'wms_inbox_group';
module.exports = {
up: async (queryInterface, Sequelize) => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (columns.template_reply_enabled) return;
await queryInterface.addColumn(TABLE_NAME, 'template_reply_enabled', {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)',
after: 'ai_enabled',
});
},
down: async queryInterface => {
const columns = await queryInterface.describeTable(TABLE_NAME);
if (!columns.template_reply_enabled) return;
await queryInterface.removeColumn(TABLE_NAME, 'template_reply_enabled');
},
};

View File

@ -0,0 +1,227 @@
'use strict';
/**
* 创建售后处理函数表 wms_after_sale_function 与 子类型-函数关系表
* wms_after_sale_sub_type_function,并播种系统预设数据。
*
* 语义(新消息处理链路):
* 消息命中售后子类型 → 查关系表取该子类型的处理方法(function_code)
* → 从 inbox functions registry 按 function_code 调用 handler。
* - 系统预设子类型:固定关联(本迁移 seed,不可改)。
* - 仓库自定义子类型:可自行选择处理方法(增删关系)。
* 处理函数在代码注册(registry)时同步 upsert 到函数表;本迁移先播种
* 现有 register 的售后处理类函数,保证表不空。
*
* 注:queryOrder/queryReturn/queryPackVideo/queryWeight 等查询类函数
* 走规则引擎关键词路由,不属于售后子类型处理链路,不入此表。
*/
const FUNCTION_TABLE = 'wms_after_sale_function';
const RELATION_TABLE = 'wms_after_sale_sub_type_function';
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
/** 系统预设处理函数(function_code 与 inbox/functions.js register 名一致) */
const SYSTEM_FUNCTIONS = [
{ function_code: 'interceptWaybill', name: '拦截处理', description: '批量创建拦截售后工单,设置订单/运单拦截状态并通知快递售后群' },
{ function_code: 'requestPickup', name: '揽收处理', description: '创建揽收售后工单,原文转发快递揽收群(无揽收群回退售后群)' },
{ function_code: 'cancelIntercept', name: '取消拦截处理', description: '取消拦截:已有工单追加记录,无工单按拦截规则创建并通知快递群' },
{ function_code: 'handleStoreFeedback', name: '货主问题反馈', description: '错发/破损/多发/少发类反馈建工单(货主售后群,不转发快递群)' },
{ function_code: 'changeAddr', name: '改地址/催退回/催件', description: '改地址/催退回/催件诉求建工单并原文转发快递售后群' },
{ function_code: 'weishoudao', name: '核实签收', description: '核实签收诉求建工单并转发快递售后群核实' },
{ function_code: 'changeExpress', name: '改快递', description: '未分配快递的待处理订单修改目标快递' },
{ function_code: 'createPostnum', name: '出单/分配快递号', description: '已审核未取号订单提交分配快递号并回传平台' },
{ function_code: 'handleExpressFeedback', name: '快递群通用反馈', description: '快递群反馈:已有工单追加记录,无工单按运单自动建单(AI 传入 type/sub_type)' },
];
/** 系统预设子类型 → 处理函数(固定关联) */
const SYSTEM_SUB_TYPE_FUNCTIONS = [
{ sub_type: 'intercept', functions: [ 'interceptWaybill' ] },
{ sub_type: 'pickup', functions: [ 'requestPickup' ] },
{ sub_type: 'damage', functions: [ 'handleStoreFeedback' ] },
{ sub_type: 'missing_item', functions: [ 'handleStoreFeedback' ] },
{ sub_type: 'mis_shipment', functions: [ 'handleStoreFeedback' ] },
{ sub_type: 'extra_item', functions: [ 'handleStoreFeedback' ] },
{ sub_type: 'change_address', functions: [ 'changeAddr' ] },
{ sub_type: 'rejected', functions: [ 'changeAddr' ] },
{ sub_type: 'urge', functions: [ 'changeAddr' ] },
{ sub_type: 'verify_delivery', functions: [ 'weishoudao' ] },
{ sub_type: 'change_carrier', functions: [ 'changeExpress' ] },
{ sub_type: 'delivery_delay', functions: [ 'createPostnum' ] },
];
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
const { sequelize } = queryInterface;
// ─── 1. 函数表 ─────────────────────────────────────────────
if (!exists(FUNCTION_TABLE)) {
await queryInterface.createTable(FUNCTION_TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
function_code: {
type: Sequelize.STRING(50),
allowNull: false,
comment: '处理函数编码(与 inbox functions registry 注册名一致)',
},
name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '处理函数名称',
},
description: {
type: Sequelize.STRING(500),
allowNull: true,
defaultValue: null,
comment: '处理函数说明',
},
is_enabled: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 1,
comment: '是否启用:1=启用,0=停用',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '排序值,越小越靠前',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
await queryInterface.addIndex(FUNCTION_TABLE, [ 'function_code' ], {
unique: true,
name: 'uk_function_code',
});
}
// ─── 2. 关系表 ─────────────────────────────────────────────
if (!exists(RELATION_TABLE)) {
await queryInterface.createTable(RELATION_TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
sub_type_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
},
function_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '处理函数ID(关联 wms_after_sale_function.id)',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '同子类型下处理函数执行顺序,数值小者优先',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
await queryInterface.addIndex(RELATION_TABLE, [ 'sub_type_id', 'function_id' ], {
unique: true,
name: 'uk_sub_type_function',
});
await queryInterface.addIndex(RELATION_TABLE, [ 'function_id' ], {
name: 'idx_function_id',
});
}
// ─── 3. 播种系统预设函数(INSERT IGNORE 基于 uk_function_code) ──
for (const [ idx, fn ] of SYSTEM_FUNCTIONS.entries()) {
await sequelize.query(
'INSERT IGNORE INTO `' + FUNCTION_TABLE + '` '
+ '(function_code, name, description, is_enabled, sort_order, created_at, updated_at) '
+ 'VALUES (:code, :name, :description, 1, :sortOrder, NOW(), NOW())',
{
replacements: {
code: fn.function_code,
name: fn.name,
description: fn.description,
sortOrder: idx + 1,
},
type: sequelize.QueryTypes.INSERT,
}
);
}
// ─── 4. 播种系统预设子类型 → 函数固定关联 ────────────────────
for (const item of SYSTEM_SUB_TYPE_FUNCTIONS) {
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: item.sub_type },
type: sequelize.QueryTypes.SELECT,
}
);
if (subRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${item.sub_type}`);
continue;
}
const subTypeId = subRows[0].id;
for (const [ fnIndex, code ] of item.functions.entries()) {
const fnRows = await sequelize.query(
'SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :code LIMIT 1',
{ replacements: { code }, type: sequelize.QueryTypes.SELECT }
);
if (fnRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到处理函数 ${code}`);
continue;
}
const functionId = fnRows[0].id;
await sequelize.query(
'INSERT IGNORE INTO `' + RELATION_TABLE + '` '
+ '(sub_type_id, function_id, sort_order, created_at, updated_at) '
+ 'VALUES (:subTypeId, :functionId, :sortOrder, NOW(), NOW())',
{
replacements: { subTypeId, functionId, sortOrder: fnIndex + 1 },
type: sequelize.QueryTypes.INSERT,
}
);
}
}
},
down: async queryInterface => {
await queryInterface.dropTable(RELATION_TABLE);
await queryInterface.dropTable(FUNCTION_TABLE);
},
};

View File

@ -0,0 +1,134 @@
'use strict';
/**
* 创建 群类型 ↔ 售后子类型 关联表 wms_after_sale_sub_type_group。
*
* 语义:多个群类型可对应同一个售后子类型(多对多),表示该子类型的
* 售后诉求可以在哪些类型的群中发起/处理。群粒度精确到子类型:
* group_type=store/warehouse/express,sub_group=群子类型
* (store: after_sales/finance/receiving;warehouse: customer_service/...;express: pickup/after_sales)。
* - is_system=1:系统预设关联(系统级子类型的默认分配),锁定不可更改。
* - is_system=0:自定义关联(仓库自定义子类型可自行选择群类型)。
*/
const TABLE = 'wms_after_sale_sub_type_group';
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
/** 系统预设:order 类型系统级子类型 → 群类型+群子类型(依据现有函数 groups 声明) */
const SYSTEM_SUB_TYPE_GROUPS = [
// 货主售后群(bound:store:after_sales)
{ sub_type: 'intercept', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'warehouse', sub_group: 'customer_service' }] },
{ sub_type: 'pickup', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'warehouse', sub_group: 'customer_service' }] },
{ sub_type: 'damage', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'missing_item', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'mis_shipment', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'extra_item', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'change_address', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'rejected', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'urge', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'verify_delivery', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'change_carrier', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'delivery_delay', groups: [{ group_type: 'store', sub_group: 'after_sales' }, { group_type: 'express', sub_group: 'after_sales' }] },
{ sub_type: 'logistics_issue', groups: [{ group_type: 'express', sub_group: 'after_sales' }] },
];
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
const { sequelize } = queryInterface;
// ─── 建表 ─────────────────────────────────────────────────
if (!exists(TABLE)) {
await queryInterface.createTable(TABLE, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
sub_type_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
},
group_type: {
type: Sequelize.STRING(20),
allowNull: false,
comment: '群类型:store=货主群 / warehouse=仓库群 / express=快递群',
},
sub_group: {
type: Sequelize.STRING(20),
allowNull: false,
comment: '群子类型:store(after_sales/finance/receiving)、warehouse(customer_service/...)、express(pickup/after_sales)',
},
is_system: {
type: Sequelize.TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否系统预设关联:1=系统级子类型默认分配(锁定不可改),0=自定义',
},
sort_order: {
type: Sequelize.INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '排序值,越小越靠前',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
});
await queryInterface.addIndex(TABLE, [ 'sub_type_id', 'group_type', 'sub_group' ], {
unique: true,
name: 'uk_sub_type_group',
});
await queryInterface.addIndex(TABLE, [ 'group_type', 'sub_group' ], {
name: 'idx_group_type',
});
}
// ─── 播种系统预设关联(INSERT IGNORE 基于 uk_sub_type_group) ──
for (const item of SYSTEM_SUB_TYPE_GROUPS) {
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: item.sub_type },
type: sequelize.QueryTypes.SELECT,
}
);
if (subRows.length === 0) {
console.warn(`[MIGRATION] 跳过:未找到系统级子类型 order.${item.sub_type}`);
continue;
}
const subTypeId = subRows[0].id;
for (const [ idx, g ] of item.groups.entries()) {
await sequelize.query(
'INSERT IGNORE INTO `' + TABLE + '` '
+ '(sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) '
+ 'VALUES (:subTypeId, :groupType, :subGroup, 1, :sortOrder, NOW(), NOW())',
{
replacements: { subTypeId, groupType: g.group_type, subGroup: g.sub_group, sortOrder: idx + 1 },
type: sequelize.QueryTypes.INSERT,
}
);
}
}
},
down: async queryInterface => {
await queryInterface.dropTable(TABLE);
},
};

View File

@ -0,0 +1,68 @@
'use strict';
/**
* 群类型-子类型关联表补充群子类型维度(开发库补丁,生产幂等跳过)。
*
* 背景:20260917120000 建表时关联粒度只有主群类型,后补充 sub_group
* (群子类型)维度。原迁移已改为最终版(生产执行直接含 sub_group),
* 本迁移仅开发库:加列 + 按主类型回填子类型 + 重建唯一索引。
* 回填规则与最终版 seed 一致:store/express→after_sales,warehouse→customer_service。
*/
const TABLE = 'wms_after_sale_sub_type_group';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
if (!exists) return;
const columns = await queryInterface.describeTable(TABLE);
// 生产已含 sub_group(17120000 最终版)→ 跳过
if (columns.sub_group) return;
const { sequelize } = queryInterface;
// 1. 加列
await queryInterface.addColumn(TABLE, 'sub_group', {
type: Sequelize.STRING(20),
allowNull: false,
defaultValue: '',
comment: '群子类型:store(after_sales/finance/receiving)、warehouse(customer_service/...)、express(pickup/after_sales)',
after: 'group_type',
});
// 2. 按主类型回填(与最终版 seed 一致)
await sequelize.query(
'UPDATE `' + TABLE + '` SET sub_group = :afterSales WHERE group_type IN (:store, :express)',
{ replacements: { afterSales: 'after_sales', store: 'store', express: 'express' } }
);
await sequelize.query(
'UPDATE `' + TABLE + '` SET sub_group = :customerService WHERE group_type = :warehouse',
{ replacements: { customerService: 'customer_service', warehouse: 'warehouse' } }
);
// 3. 重建索引(旧 uk_sub_type_group 为 (sub_type_id, group_type),升级为含 sub_group)
const indexes = await queryInterface.showIndex(TABLE);
const legacyIndex = indexes.find(i => (typeof i === 'string' ? i : i.name) === 'uk_sub_type_group');
if (legacyIndex) {
await queryInterface.removeIndex(TABLE, 'uk_sub_type_group');
}
await queryInterface.addIndex(TABLE, [ 'sub_type_id', 'group_type', 'sub_group' ], {
unique: true,
name: 'uk_sub_type_group',
});
const legacyIdx = indexes.find(i => (typeof i === 'string' ? i : i.name) === 'idx_group_type');
if (legacyIdx) {
await queryInterface.removeIndex(TABLE, 'idx_group_type');
}
await queryInterface.addIndex(TABLE, [ 'group_type', 'sub_group' ], {
name: 'idx_group_type',
});
},
down: async () => {
// 不回退(生产最终版即含 sub_group)
},
};

View File

@ -0,0 +1,85 @@
'use strict';
/**
* 修复 v2 回信引擎配置链数据缺口(幂等,先查后插)。
*
* 1. change_carrier(换快递)子类型关联"快递名称提取"取号规则:
* 换快递函数 changeExpress 需要目标快递(express 入参),
* 原种子只关联了运单号 + 平台单号,缺 express_name。
* 2. 关键词表补充 intercept(拦截)/ pickup(揽收)子类型关键词:
* 原 22 个关键词仅覆盖 8 个子类型,拦截/揽收在 v2 引擎命中不了。
*/
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
const RULE_TABLE = 'wms_inbox_number_rule';
const RELATION_TABLE = 'wms_after_sale_sub_type_rule';
const KEYWORD_TABLE = 'wms_after_sale_keyword';
/** 补充关键词(与 v1 函数 keywords 语义一致)。 */
const MISSING_KEYWORDS = [
{ sub_type: 'intercept', keywords: [ '拦截', '退回', '召回', '追回', '取消快递' ] },
{ sub_type: 'pickup', 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(RULE_TABLE)) return;
// ─── 1. change_carrier 关联 express_name 规则 ─────────────────
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: 'change_carrier' } }
);
const [ ruleRows ] = await sequelize.query(
'SELECT id FROM `' + RULE_TABLE + '` WHERE target = :target AND name = :name LIMIT 1',
{ replacements: { target: 'express_name', name: '快递名称提取' } }
);
if (subRows.length > 0 && ruleRows.length > 0 && exists(RELATION_TABLE)) {
const subTypeId = subRows[0].id;
const ruleId = ruleRows[0].id;
const [ relRows ] = await sequelize.query(
'SELECT id FROM `' + RELATION_TABLE + '` WHERE sub_type_id = :sid AND number_rule_id = :rid LIMIT 1',
{ replacements: { sid: subTypeId, rid: ruleId } }
);
if (relRows.length === 0) {
await sequelize.query(
'INSERT INTO `' + RELATION_TABLE + '` (sub_type_id, number_rule_id, sort_order, created_at, updated_at) VALUES (:sid, :rid, 3, NOW(), NOW())',
{ replacements: { sid: subTypeId, rid: ruleId } }
);
}
}
// ─── 2. 关键词补充(先查后插,MySQL 唯一索引对 NULL warehouse 不生效) ───
if (exists(KEYWORD_TABLE)) {
for (const rule of MISSING_KEYWORDS) {
const [ subRows2 ] = 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: rule.sub_type } }
);
if (subRows2.length === 0) continue;
const subTypeId = subRows2[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 } }
);
}
sortOrder += 1;
}
}
}
},
down: async () => {
// 不回退(种子类数据)
},
};

View File

@ -0,0 +1,36 @@
'use strict';
/**
* wms_inbox_message 增加 extend_props 列(回执扩展属性持久化,幂等)。
*
* 背景:出站回执 notify.reply 的 extend_props(如开门指令等空文案回执的驱动属性)
* 此前只在首推时随报文发出,不落库。手动/定时重推时无法恢复 extend_props,
* 且 content 为空的 extend_props 回执被重推扫描直接跳过。加列后:
* - 首推写库持久化;重推从记录原样带回;
* - 空文案但含 extend_props 的出站记录可被重推。
*/
const TABLE = 'wms_inbox_message';
module.exports = {
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE);
if (!exists) return;
const columns = await queryInterface.describeTable(TABLE);
if (columns.extend_props) return;
await queryInterface.addColumn(TABLE, 'extend_props', {
type: Sequelize.JSON,
allowNull: true,
defaultValue: null,
comment: '回执扩展属性(notify.reply 的 extend_props),重推时原样带回',
after: 'ext_data',
});
},
down: async () => {
// 不回退(新列无副作用)
},
};

View File

@ -1,4 +1,52 @@
[
{
"version": "2026.09.16-inbox-push-retry-warehouse-setting",
"date": "2026-09-16",
"type": "updated",
"summary": "仓库设置新增「站内信推送失败自动重发」配置(嵌套结构 subject_config.inbox_push_retry,同「收货未入库提醒」):enabled(flag,默认 0=关闭,需显式开启)、window_minutes(重发时间范围,分钟,1-1440,默认 30)。开启后站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline 的 503)由定时任务每 3 分钟自动重发,仅重发失败时间在 window_minutes 内的消息,超出范围不再补发。",
"methods": [
"setting.warehouse.getSettings",
"setting.warehouse.saveSettings"
],
"notes": [
"字段落位:wms_store.subject_config.inbox_push_retry(与 receiving_pending_inbound_notice 同表的嵌套 JSON 配置)",
"默认值口径:未配置(或配置缺失/非法结构)时 enabled=false、window_minutes=30,即**默认关闭不重发**,需在仓库设置中显式开启",
"代码依据:app/model/store.js#normalizeInboxPushRetry(enabled 走 normalizeBooleanFlag;window_minutes 限 1-1440 整数,越界抛「subject_config.inbox_push_retry.window_minutes 必须是 1-1440 的整数(分钟)」);app/service/systems/setting/warehouse.js#WAREHOUSE_SETTING_FIELDS(key=inbox_push_retry,type=object,item_keys 为 enabled/window_minutes)",
"消费方:app/service/inbox/message.js#retryFailedByWarehouse(定时任务 app/schedule/retry_inbox_push.js,每 3 分钟;逐仓读设置 → 仅重发该仓窗口内 push_status=3 的出站消息,单仓单轮上限 config.inbox.pushRetryLimit,默认 20)",
"全局应急开关:config.inbox.pushRetryEnabled(默认 true),置 false 后所有仓库都不再自动重发;config.inbox.pushRetryWindowMs 仅在仓库未配置/配置非法时兜底(默认 30 分钟)",
"getFieldMeta 为通用结构(list + children,不逐字段枚举),本次未改动其文档",
"文档版本 0.3.132 -> 0.3.133,updatedAt 2026-09-16"
]
},
{
"version": "2026.09.16-after-sale-type-subtype-crud",
"date": "2026-09-16",
"type": "added",
"summary": "售后模块新增售后类型/子类型自定义配置 8 个接口:afterSale.typeList / typeCreate / typeUpdate / typeDelete / subTypeList / subTypeCreate / subTypeUpdate / subTypeDelete。列表返回系统级(warehouse_id=null、is_system=1)+ 当前仓库自定义(is_system=0)合并;创建仅允许仓库自定义;改/删仅命中 id + 当前仓库 + is_system=0;系统级不允许编辑/删除(未命中统一 404);编码仅允许小写字母/数字/下划线(type≤20、sub_type≤50、name≤50)且创建时校验不与系统级重复、同仓库内唯一(409);update 编码不可变;删除不做级联(类型下存在自定义子类型或子类型已被售后单引用时 409 拒绝)。",
"methods": [
"afterSale.typeList",
"afterSale.typeCreate",
"afterSale.typeUpdate",
"afterSale.typeDelete",
"afterSale.subTypeList",
"afterSale.subTypeCreate",
"afterSale.subTypeUpdate",
"afterSale.subTypeDelete"
],
"notes": [
"接口口径:全部挂 afterSale 模块(POST /system?method=afterSale.xxx);方法层 app/service/systemMethods/afterSale.js(typeList/typeCreate/typeUpdate/typeDelete/subTypeList/subTypeCreate/subTypeUpdate/subTypeDelete)→ 业务层 app/service/systems/afterSale.js(getTypeList/createType/updateType/deleteType/getSubTypeList/createSubType/updateSubType/deleteSubType)",
"权限口径(afterSale.js#systemInit):8 个方法全部免权限(_noNeedRight)、免仓库有效期校验(_noNeedAuth)、需登录(不在 _noNeedLogin);typeList/subTypeList 免日志(_noNeedLog),其余 6 个写系统日志",
"仓库维度隔离:列表按 [warehouse_id IS NULL OR warehouse_id=当前仓库] 合并;创建/改/删均以 ctx.user.store_id 为 warehouseId(无仓库上下文报 400),改/删仅命中 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 兜底",
"编码不可变:typeUpdate 仅允许 name/is_enabled/sort_order,type 不可改;subTypeUpdate 仅允许 name/is_enabled/sort_order,type 与 sub_type 均不可改",
"删除策略(拒绝,不做级联):typeDelete 在该类型下存在当前仓库自定义子类型时拒绝(409);subTypeDelete 在 wms_after_sale 存在该 type/sub_type 引用(deleted_at 为空)时拒绝(409「已被售后单使用」)",
"错误码口径:400(参数/编码格式/无仓库上下文)、404(不存在/无权/系统预设)、409(编码重复/存在自定义子类型/已被售后单使用)",
"数据模型:wms_after_sale_type / wms_after_sale_sub_type(app/model/after_sale_type.js、after_sale_sub_type.js;迁移 database/migrations/20260916100000-create-wms-after-sale-type-tables.js)",
"AI_METHOD_ROUTING.md 新增 5.8 节(8 个方法的 method→文件→函数→登录→鉴权口径速查表)并刷新第 6 节自动清单(systemMethods/afterSale.js 22→30,systems/afterSale.js 29→46)",
"文档版本 0.3.131 -> 0.3.132,updatedAt 2026-09-16;写入通过 script/update-api-doc.cjs(先 --dry-run)"
]
},
{
"version": "2026.09.15-warehouse-pending-receiving-notice-template",
"date": "2026-09-15",

View File

@ -1,8 +1,8 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.3.131",
"updatedAt": "2026-09-15",
"version": "0.3.133",
"updatedAt": "2026-09-16",
"headers": [
{
"name": "platform",
@ -14483,6 +14483,24 @@
"type": "string",
"required": false,
"description": "通知短语(消息第一行,货主群)。变量同 notice_template,留空使用默认短语"
},
{
"name": "subject_config.inbox_push_retry",
"type": "object",
"required": false,
"description": "站内信推送失败自动重发配置(同「收货未入库提醒」的嵌套结构):开启后站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline)由定时任务每 3 分钟自动重发一次"
},
{
"name": "subject_config.inbox_push_retry.enabled",
"type": "number",
"required": false,
"description": "是否开启站内信推送失败自动重发(flag:0=关闭,1=开启;默认 0=关闭,需显式开启)"
},
{
"name": "subject_config.inbox_push_retry.window_minutes",
"type": "number",
"required": false,
"description": "重发时间范围(分钟,1-1440,默认 30):仅自动重发「失败时间在该范围内」的消息,超出范围不再补发;仅在 enabled 开启时生效"
}
],
"errors": [
@ -14831,6 +14849,27 @@
"required": false,
"source": "body.subject_config",
"description": "通知短语(消息第一行,货主群)。变量同 notice_template,留空使用默认短语;最长 500 字符,超长报 400"
},
{
"name": "subject_config.inbox_push_retry",
"type": "object",
"required": false,
"description": "站内信推送失败自动重发配置(同「收货未入库提醒」的嵌套结构):开启后站内信回信/系统通知推送失败(如桥接离线返回 wx offline / qiwe offline)由定时任务每 3 分钟自动重发一次",
"source": "body.subject_config"
},
{
"name": "subject_config.inbox_push_retry.enabled",
"type": "number",
"required": false,
"description": "是否开启站内信推送失败自动重发(flag:0=关闭,1=开启;默认 0=关闭,需显式开启)",
"source": "body.subject_config"
},
{
"name": "subject_config.inbox_push_retry.window_minutes",
"type": "number",
"required": false,
"description": "重发时间范围(分钟,1-1440,默认 30):仅自动重发「失败时间在该范围内」的消息,超出范围不再补发;仅在 enabled 开启时生效",
"source": "body.subject_config"
}
],
"response": [
@ -40618,6 +40657,708 @@
}
],
"errors": []
},
{
"method": "afterSale.typeList",
"description": "售后类型列表:返回系统级(warehouse_id=null、is_system=1,全部仓库可见)与当前仓库自定义(is_system=0)类型的合并列表,默认按 sort_order 升序、id 升序,pageSize 上限 500。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "分页 { page: 1, pageSize: 20 },pageSize 上限 500"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "可选筛选字段: id/type/name/is_system/is_enabled/sort_order/created_at/updated_at"
},
{
"name": "sort",
"type": "object",
"required": false,
"source": "body",
"description": "排序 { sortField, sortOrder },支持 id/type/name/is_enabled/sort_order/created_at/updated_at;不传默认 sort_order ASC, id ASC"
}
],
"response": [
{
"name": "list",
"type": "array",
"required": true,
"description": "售后类型列表,每条含 { id, warehouse_id, type, name, is_system, is_enabled, sort_order, created_at, updated_at };系统级 warehouse_id=null、is_system=1"
},
{
"name": "pagination",
"type": "object",
"required": true,
"description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }"
}
],
"errors": []
},
{
"method": "afterSale.typeCreate",
"description": "创建仓库自定义售后类型(is_system=0):warehouse_id 由服务端从当前仓库上下文自动注入,前端无需传递。type 编码仅允许小写字母/数字/下划线且长度≤20,不可与系统级编码重复,同仓库内唯一(MySQL 唯一索引 uk_type_warehouse 兜底)。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "type",
"type": "string",
"required": true,
"source": "body",
"description": "类型编码,仅允许 /^[a-z0-9_]+$/(小写字母/数字/下划线),长度≤20,不可与系统级编码重复"
},
{
"name": "name",
"type": "string",
"required": true,
"source": "body",
"description": "类型名称,长度≤50"
},
{
"name": "sort_order",
"type": "number",
"required": false,
"source": "body",
"description": "排序值,越小越靠前,默认 0(非法值按 0 处理)"
},
{
"name": "is_enabled",
"type": "integer",
"required": false,
"source": "body",
"description": "是否启用:1=启用(默认 1),0=停用"
}
],
"response": [
{
"name": "id",
"type": "integer",
"required": true,
"description": "新类型主键ID"
},
{
"name": "warehouse_id",
"type": "integer",
"required": true,
"description": "仓库ID(当前仓库自定义)"
},
{
"name": "type",
"type": "string",
"required": true,
"description": "类型编码"
},
{
"name": "name",
"type": "string",
"required": true,
"description": "类型名称"
},
{
"name": "is_system",
"type": "integer",
"required": true,
"description": "是否系统级,固定 0(仓库自定义)"
},
{
"name": "is_enabled",
"type": "integer",
"required": true,
"description": "是否启用:1=启用,0=停用"
},
{
"name": "sort_order",
"type": "number",
"required": true,
"description": "排序值"
},
{
"name": "created_at",
"type": "string",
"required": false,
"description": "创建时间(格式化字符串)"
},
{
"name": "updated_at",
"type": "string",
"required": false,
"description": "更新时间(格式化字符串)"
}
],
"errors": [
{
"code": 400,
"message": "无法获取当前仓库上下文,不能创建售后类型"
},
{
"code": 400,
"message": "类型编码不能为空 / 只能包含小写字母、数字和下划线 / 长度不能超过20个字符"
},
{
"code": 400,
"message": "类型名称不能为空 / 长度不能超过50个字符"
},
{
"code": 409,
"message": "该类型编码与系统预设类型重复,不允许使用"
},
{
"code": 409,
"message": "该类型编码在当前仓库已存在"
}
]
},
{
"method": "afterSale.typeUpdate",
"description": "更新仓库自定义售后类型:仅命中 id + 当前仓库 + is_system=0 的记录,系统级类型不允许修改(未命中统一返回 404)。仅允许修改 name/is_enabled/sort_order,type 编码不可变。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "id",
"type": "integer",
"required": true,
"source": "body",
"description": "类型主键ID"
},
{
"name": "name",
"type": "string",
"required": false,
"source": "body",
"description": "类型名称,长度≤50"
},
{
"name": "is_enabled",
"type": "integer",
"required": false,
"source": "body",
"description": "是否启用:1=启用,0=停用"
},
{
"name": "sort_order",
"type": "number",
"required": false,
"source": "body",
"description": "排序值,越小越靠前"
}
],
"response": [
{
"name": "id",
"type": "integer",
"required": true,
"description": "类型主键ID"
},
{
"name": "warehouse_id",
"type": "integer",
"required": true,
"description": "仓库ID"
},
{
"name": "type",
"type": "string",
"required": true,
"description": "类型编码(不可变)"
},
{
"name": "name",
"type": "string",
"required": true,
"description": "类型名称"
},
{
"name": "is_system",
"type": "integer",
"required": true,
"description": "是否系统级,固定 0(仓库自定义)"
},
{
"name": "is_enabled",
"type": "integer",
"required": true,
"description": "是否启用:1=启用,0=停用"
},
{
"name": "sort_order",
"type": "number",
"required": true,
"description": "排序值"
},
{
"name": "created_at",
"type": "string",
"required": false,
"description": "创建时间(格式化字符串)"
},
{
"name": "updated_at",
"type": "string",
"required": false,
"description": "更新时间(格式化字符串)"
}
],
"errors": [
{
"code": 400,
"message": "无法获取当前仓库上下文,不能修改售后类型"
},
{
"code": 400,
"message": "售后类型ID不合法"
},
{
"code": 400,
"message": "类型名称不能为空 / 长度不能超过50个字符"
},
{
"code": 400,
"message": "没有需要更新的字段"
},
{
"code": 404,
"message": "售后类型不存在、无权操作或为系统预设类型"
}
]
},
{
"method": "afterSale.typeDelete",
"description": "删除仓库自定义售后类型(不做级联删除):系统级类型禁止删除;删除前检查该类型下是否存在当前仓库自定义子类型,存在则拒绝(需先删除子类型)。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "id",
"type": "integer",
"required": true,
"source": "body",
"description": "类型主键ID"
}
],
"response": [
{
"name": "data",
"type": "object",
"required": true,
"description": "删除结果对象"
},
{
"name": "data.id",
"type": "integer",
"required": true,
"description": "被删除的类型ID"
},
{
"name": "data.deleted",
"type": "boolean",
"required": true,
"description": "固定 true"
}
],
"errors": [
{
"code": 400,
"message": "无法获取当前仓库上下文,不能删除售后类型"
},
{
"code": 400,
"message": "售后类型ID不合法"
},
{
"code": 404,
"message": "售后类型不存在、无权操作或为系统预设类型"
},
{
"code": 409,
"message": "该类型下存在当前仓库的自定义子类型,请先删除子类型"
}
]
},
{
"method": "afterSale.subTypeList",
"description": "售后子类型列表:返回系统级(warehouse_id=null、is_system=1)+ 当前仓库自定义(is_system=0)子类型的合并列表,默认按 sort_order 升序、id 升序;group=true 时额外按 type 分组返回 groups(基于全量过滤结果、不受分页影响,组内 sort_order 升序)。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "分页 { page: 1, pageSize: 20 },pageSize 上限 500"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "可选筛选字段: id/type/sub_type/name/is_system/is_enabled/sort_order/created_at/updated_at"
},
{
"name": "sort",
"type": "object",
"required": false,
"source": "body",
"description": "排序 { sortField, sortOrder },支持 id/type/sub_type/name/is_enabled/sort_order/created_at/updated_at;不传默认 sort_order ASC, id ASC"
},
{
"name": "group",
"type": "boolean",
"required": false,
"source": "body",
"description": "是否按 type 分组返回 groups(true 时额外返回 groups 数组)"
}
],
"response": [
{
"name": "list",
"type": "array",
"required": true,
"description": "售后子类型列表,每条含 { id, warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at }"
},
{
"name": "pagination",
"type": "object",
"required": true,
"description": "分页信息 { page, pageSize, total, totalPages, hasPrevious, hasNext }"
},
{
"name": "groups",
"type": "array",
"required": false,
"description": "group=true 时返回:按 type 分组,每组 { type, name, items: [...] },组内按 sort_order 升序、id 升序"
}
],
"errors": []
},
{
"method": "afterSale.subTypeCreate",
"description": "创建仓库自定义售后子类型(is_system=0):所属 type 必须已存在(系统级或当前仓库自定义)且处于启用状态(is_enabled=1)。sub_type 编码仅允许小写字母/数字/下划线且长度≤50,不可与系统级同 type 下编码重复,同仓库同 type 下唯一(MySQL 唯一索引 uk_type_subtype_warehouse 兜底)。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "type",
"type": "string",
"required": true,
"source": "body",
"description": "所属类型编码,必须已存在且启用(is_enabled=1)"
},
{
"name": "sub_type",
"type": "string",
"required": true,
"source": "body",
"description": "子类型编码,仅允许 /^[a-z0-9_]+$/(小写字母/数字/下划线),长度≤50,不可与系统级同 type 下编码重复"
},
{
"name": "name",
"type": "string",
"required": true,
"source": "body",
"description": "子类型名称,长度≤50"
},
{
"name": "sort_order",
"type": "number",
"required": false,
"source": "body",
"description": "排序值,越小越靠前,默认 0(非法值按 0 处理)"
},
{
"name": "is_enabled",
"type": "integer",
"required": false,
"source": "body",
"description": "是否启用:1=启用(默认 1),0=停用"
}
],
"response": [
{
"name": "id",
"type": "integer",
"required": true,
"description": "新子类型主键ID"
},
{
"name": "warehouse_id",
"type": "integer",
"required": true,
"description": "仓库ID(当前仓库自定义)"
},
{
"name": "type",
"type": "string",
"required": true,
"description": "所属类型编码"
},
{
"name": "sub_type",
"type": "string",
"required": true,
"description": "子类型编码"
},
{
"name": "name",
"type": "string",
"required": true,
"description": "子类型名称"
},
{
"name": "is_system",
"type": "integer",
"required": true,
"description": "是否系统级,固定 0(仓库自定义)"
},
{
"name": "is_enabled",
"type": "integer",
"required": true,
"description": "是否启用:1=启用,0=停用"
},
{
"name": "sort_order",
"type": "number",
"required": true,
"description": "排序值"
},
{
"name": "created_at",
"type": "string",
"required": false,
"description": "创建时间(格式化字符串)"
},
{
"name": "updated_at",
"type": "string",
"required": false,
"description": "更新时间(格式化字符串)"
}
],
"errors": [
{
"code": 400,
"message": "无法获取当前仓库上下文,不能创建售后子类型"
},
{
"code": 400,
"message": "类型编码不能为空 / 只能包含小写字母、数字和下划线 / 长度不能超过20个字符"
},
{
"code": 400,
"message": "子类型编码不能为空 / 只能包含小写字母、数字和下划线 / 长度不能超过50个字符"
},
{
"code": 400,
"message": "子类型名称不能为空 / 长度不能超过50个字符"
},
{
"code": 400,
"message": "售后类型不存在"
},
{
"code": 400,
"message": "售后类型已停用,不能添加子类型"
},
{
"code": 409,
"message": "该子类型编码与系统预设重复,不允许使用"
},
{
"code": 409,
"message": "该子类型编码在当前仓库已存在"
}
]
},
{
"method": "afterSale.subTypeUpdate",
"description": "更新仓库自定义售后子类型:仅命中 id + 当前仓库 + is_system=0 的记录,系统级子类型不允许修改。仅允许修改 name/is_enabled/sort_order,type 与 sub_type 编码均不可变。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "id",
"type": "integer",
"required": true,
"source": "body",
"description": "子类型主键ID"
},
{
"name": "name",
"type": "string",
"required": false,
"source": "body",
"description": "子类型名称,长度≤50"
},
{
"name": "is_enabled",
"type": "integer",
"required": false,
"source": "body",
"description": "是否启用:1=启用,0=停用"
},
{
"name": "sort_order",
"type": "number",
"required": false,
"source": "body",
"description": "排序值,越小越靠前"
}
],
"response": [
{
"name": "id",
"type": "integer",
"required": true,
"description": "子类型主键ID"
},
{
"name": "warehouse_id",
"type": "integer",
"required": true,
"description": "仓库ID"
},
{
"name": "type",
"type": "string",
"required": true,
"description": "所属类型编码(不可变)"
},
{
"name": "sub_type",
"type": "string",
"required": true,
"description": "子类型编码(不可变)"
},
{
"name": "name",
"type": "string",
"required": true,
"description": "子类型名称"
},
{
"name": "is_system",
"type": "integer",
"required": true,
"description": "是否系统级,固定 0(仓库自定义)"
},
{
"name": "is_enabled",
"type": "integer",
"required": true,
"description": "是否启用:1=启用,0=停用"
},
{
"name": "sort_order",
"type": "number",
"required": true,
"description": "排序值"
},
{
"name": "created_at",
"type": "string",
"required": false,
"description": "创建时间(格式化字符串)"
},
{
"name": "updated_at",
"type": "string",
"required": false,
"description": "更新时间(格式化字符串)"
}
],
"errors": [
{
"code": 400,
"message": "无法获取当前仓库上下文,不能修改售后子类型"
},
{
"code": 400,
"message": "售后子类型ID不合法"
},
{
"code": 400,
"message": "子类型名称不能为空 / 长度不能超过50个字符"
},
{
"code": 400,
"message": "没有需要更新的字段"
},
{
"code": 404,
"message": "售后子类型不存在、无权操作或为系统预设类型"
}
]
},
{
"method": "afterSale.subTypeDelete",
"description": "删除仓库自定义售后子类型(不做级联):系统级子类型禁止删除;若该子类型已被当前仓库售后单使用(wms_after_sale 存在该 type/sub_type 引用),拒绝删除。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [],
"params": [
{
"name": "id",
"type": "integer",
"required": true,
"source": "body",
"description": "子类型主键ID"
}
],
"response": [
{
"name": "data",
"type": "object",
"required": true,
"description": "删除结果对象"
},
{
"name": "data.id",
"type": "integer",
"required": true,
"description": "被删除的子类型ID"
},
{
"name": "data.deleted",
"type": "boolean",
"required": true,
"description": "固定 true"
}
],
"errors": [
{
"code": 400,
"message": "无法获取当前仓库上下文,不能删除售后子类型"
},
{
"code": 400,
"message": "售后子类型ID不合法"
},
{
"code": 404,
"message": "售后子类型不存在、无权操作或为系统预设类型"
},
{
"code": 409,
"message": "该子类型已被售后单使用,无法删除"
}
]
}
]
},