Compare commits
8 Commits
c2a761ca26
...
c6224b471e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6224b471e | ||
|
|
dc9f83a2d7 | ||
|
|
1771b5c6c9 | ||
|
|
17f7e3d87b | ||
|
|
a3ec20098f | ||
|
|
e8f9ccad95 | ||
|
|
388809fc9f | ||
|
|
806e739267 |
File diff suppressed because one or more lines are too long
@ -1,6 +1,6 @@
|
||||
# 站内信 v2 可配置回信引擎 —— HTTP 覆盖测试报告
|
||||
|
||||
> 生成时间:2026-09-16T18:11:52.145Z | 执行方式:真实 HTTP 链路(POST /warehouse?method=inbox.push)
|
||||
> 生成时间:2026-09-17T14:44:55.082Z | 执行方式:真实 HTTP 链路(POST /warehouse?method=inbox.push)
|
||||
|
||||
## 1. 测试环境
|
||||
|
||||
@ -11,10 +11,9 @@
|
||||
| 数据库 | 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` |
|
||||
| 新 v2 测试群 | `httpv2:1789656295082`(首推自动登记后开启 store/after_sales + ai_enabled=1 + template_reply_enabled=1) |
|
||||
| 新 express 测试群 | `httpv2expr:1789656295082`(express/after_sales,开启 v2) |
|
||||
| 模块优先测试群 | `httpv2aioff:1789656295082`(ai_enabled=0 + template_reply_enabled=1) |
|
||||
|
||||
## 2. 链路
|
||||
|
||||
@ -33,7 +32,7 @@ flowchart LR
|
||||
|
||||
## 3. 用例结果总览
|
||||
|
||||
- 总计:**12** 用例,通过:**12**,失败:**0**
|
||||
- 总计:**11** 用例,通过:**11**,失败:**0**
|
||||
|
||||
| # | 用例 | 内容 | 结果 |
|
||||
|---|---|---|---|
|
||||
@ -47,37 +46,51 @@ flowchart LR
|
||||
| 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 |
|
||||
| TC11 | 模块优先(ai_enabled=0 但 template_reply_enabled=1) | `破损 SF1234567890123` | ✅ PASS |
|
||||
|
||||
## 4. 用例明细
|
||||
|
||||
### TC01 破损建单(新 v2 群) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-01-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-01-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 入站消息入库 | ✅ | id=2016 |
|
||||
| v2 命中轨迹写入 ai_thoughts(function=handleStoreFeedback) | ✅ | [object Object] |
|
||||
| 出站回执存在(sys:ack) | ✅ | sys:ack:api:APP2025011514315678:httpv2-01-1789582314626 |
|
||||
| 入站消息入库 | ✅ | id=2118 |
|
||||
| v2 命中轨迹写入 ai_thoughts(function=handleStoreFeedback) | ✅ | [{"round":0,"action":"rule","params":{"keyword":"SF1234567890123","issue_type":"damaged"},"reason":"v2 关键词命中: 破损","function":"handleStoreFeedback","functionResult":{"error":"未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试","success":false}}] |
|
||||
| 出站回执存在(sys:ack) | ✅ | sys:ack:api:APP2025011514315678:httpv2-01-1789656298793 |
|
||||
| 出站 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:
|
||||
- 入站消息 id=2118,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {
|
||||
"keyword": "SF1234567890123",
|
||||
"issue_type": "damaged"
|
||||
},
|
||||
"reason": "v2 关键词命中: 破损",
|
||||
"function": "handleStoreFeedback",
|
||||
"functionResult": {
|
||||
"error": "未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-01-1789582314626` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-01-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
@ -86,7 +99,7 @@ flowchart LR
|
||||
### TC02 改地址 ✅ PASS
|
||||
|
||||
- 消息:`改地址 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-02-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-02-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
@ -94,17 +107,32 @@ flowchart LR
|
||||
| 出站回执存在 | ✅ | push_status=2 |
|
||||
| 函数已执行(工单或错误文案) | ✅ | \| 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 |
|
||||
|
||||
- 入站消息 id=2018,ai_thoughts:
|
||||
- 入站消息 id=2120,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {
|
||||
"keyword": "SF1234567890123,1234567890123",
|
||||
"issue_type": "addr"
|
||||
},
|
||||
"reason": "v2 关键词命中: 改地址",
|
||||
"function": "changeAddr",
|
||||
"functionResult": {
|
||||
"error": "未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-02-1789582314626` | 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-02-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
@ -113,7 +141,7 @@ flowchart LR
|
||||
### TC03 换快递(express 取号) ✅ PASS
|
||||
|
||||
- 消息:`改快递 SF1234567890123 圆通`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-03-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-03-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
@ -121,17 +149,40 @@ flowchart LR
|
||||
| 取号含 express=圆通 | ✅ | thoughts 含 express 字段 |
|
||||
| 出站回执存在 | ✅ | 未找到订单:SF1234567890123、1234567890123 |
|
||||
|
||||
- 入站消息 id=2020,ai_thoughts:
|
||||
- 入站消息 id=2122,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {
|
||||
"express": "圆通",
|
||||
"keyword": "SF1234567890123,1234567890123"
|
||||
},
|
||||
"reason": "v2 关键词命中: 改快递",
|
||||
"function": "changeExpress",
|
||||
"functionResult": {
|
||||
"data": {
|
||||
"changed": 0,
|
||||
"express": "圆通快递",
|
||||
"message": "未找到订单:SF1234567890123、1234567890123",
|
||||
"allocated": 0,
|
||||
"not_found": 2,
|
||||
"direct_reply": true,
|
||||
"not_in_pending": 0
|
||||
},
|
||||
"success": true
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-03-1789582314626` | 未找到订单:SF1234567890123、1234567890123 | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-03-1789656298793` | 未找到订单:SF1234567890123、1234567890123 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
@ -140,24 +191,36 @@ flowchart LR
|
||||
### TC04 拦截 ✅ PASS
|
||||
|
||||
- 消息:`拦截 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-04-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-04-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| v2 命中 interceptWaybill | ✅ | |
|
||||
| 出站回执存在 | ✅ | 请提供运单号 |
|
||||
|
||||
- 入站消息 id=2022,ai_thoughts:
|
||||
- 入站消息 id=2124,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {},
|
||||
"reason": "v2 关键词命中: 拦截",
|
||||
"function": "interceptWaybill",
|
||||
"functionResult": {
|
||||
"error": "请提供运单号",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-04-1789582314626` | 请提供运单号 | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-04-1789656298793` | 请提供运单号 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
@ -166,24 +229,36 @@ flowchart LR
|
||||
### TC05 揽收(上门取件) ✅ PASS
|
||||
|
||||
- 消息:`上门取件 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-05-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-05-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| v2 命中 requestPickup | ✅ | |
|
||||
| 出站回执存在 | ✅ | 请提供运单号 |
|
||||
|
||||
- 入站消息 id=2024,ai_thoughts:
|
||||
- 入站消息 id=2126,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {},
|
||||
"reason": "v2 关键词命中: 上门取件",
|
||||
"function": "requestPickup",
|
||||
"functionResult": {
|
||||
"error": "请提供运单号",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-05-1789582314626` | 请提供运单号 | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-05-1789656298793` | 请提供运单号 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
@ -192,24 +267,33 @@ flowchart LR
|
||||
### TC06 取号失败引导语 ✅ PASS
|
||||
|
||||
- 消息:`破损`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-06-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-06-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 出站回执为取号引导语 | ✅ | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) |
|
||||
| 未建工单(取号失败不调用函数) | ✅ | |
|
||||
|
||||
- 入站消息 id=2026,ai_thoughts:
|
||||
- 入站消息 id=2128,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {},
|
||||
"reason": "v2 关键词命中: 破损,取号失败-引导提示",
|
||||
"function": "handleStoreFeedback",
|
||||
"functionResult": null
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-06-1789582314626` | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-06-1789656298793` | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
@ -218,7 +302,7 @@ flowchart LR
|
||||
### TC07 v2 未命中静默(模块接管) ✅ PASS
|
||||
|
||||
- 消息:`今天天气怎么样`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-07-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-07-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
@ -226,7 +310,7 @@ flowchart LR
|
||||
| 无 ai_thoughts 轨迹 | ✅ | 空 |
|
||||
| 无新工单 | ✅ | 0 条 |
|
||||
|
||||
- 入站消息 id=2028,ai_thoughts:
|
||||
- 入站消息 id=2130,ai_thoughts:
|
||||
|
||||
```json
|
||||
null
|
||||
@ -235,15 +319,15 @@ null
|
||||
### TC08 历史消息静默跳过 ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-08-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-08-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 入站仍入库 | ✅ | id=2029 |
|
||||
| 入站仍入库 | ✅ | id=2131 |
|
||||
| 无出站回执(静默跳过) | ✅ | |
|
||||
| 无新工单 | ✅ | 0 条 |
|
||||
|
||||
- 入站消息 id=2029,ai_thoughts:
|
||||
- 入站消息 id=2131,ai_thoughts:
|
||||
|
||||
```json
|
||||
null
|
||||
@ -252,7 +336,7 @@ null
|
||||
### TC09 幂等(同 requestId 两次推送) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF9999999999999`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-09-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-09-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
@ -260,17 +344,32 @@ null
|
||||
| 入站仅 1 条 | ✅ | 1 -> 1 |
|
||||
| 出站仅 1 条(不重复处理) | ✅ | 出站条数 1 -> 1 |
|
||||
|
||||
- 入站消息 id=2030,ai_thoughts:
|
||||
- 入站消息 id=2132,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {
|
||||
"keyword": "SF9999999999999",
|
||||
"issue_type": "damaged"
|
||||
},
|
||||
"reason": "v2 关键词命中: 破损",
|
||||
"function": "handleStoreFeedback",
|
||||
"functionResult": {
|
||||
"error": "未找到当前货主在仓库中的运单「SF9999999999999」,请核实单号后重试",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-09-1789582314626` | 未找到当前货主在仓库中的运单「SF9999999999999」,请核实单号后重试 | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-09-1789656298793` | 未找到当前货主在仓库中的运单「SF9999999999999」,请核实单号后重试 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
@ -279,63 +378,62 @@ null
|
||||
### TC10 express 群白名单放行但函数越权拦截(静默) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-10-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-10-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 入站消息入库 | ✅ | id=2032 |
|
||||
| 入站消息入库 | ✅ | id=2134 |
|
||||
| 无出站回执(静默) | ✅ | |
|
||||
| 白名单行存在(express/after_sales 允许 damage 子类型) | ✅ | 行数=1 |
|
||||
| 函数越权拦截(handleStoreFeedback 仅 store 群可用 → 无轨迹) | ✅ | 无轨迹 |
|
||||
|
||||
- 入站消息 id=2032,ai_thoughts:
|
||||
- 入站消息 id=2134,ai_thoughts:
|
||||
|
||||
```json
|
||||
null
|
||||
```
|
||||
|
||||
### TC11 v1 分叉确认(template_reply_enabled=0 群) ✅ PASS
|
||||
### TC11 模块优先(ai_enabled=0 但 template_reply_enabled=1) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-11-1789582314626`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-11-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 未走 v2 引擎(thoughts 无 v2 轨迹特征) | ✅ | [{"round":0,"action":"rule","params":{"keyword":"SF1234567890123","issue_type":"damaged"},"reason":"关键词规则命中: 破损","function":"handleStoreFeedback","functionResult":{"error":"未找到当前货主在仓库中的运单「SF1234567890 |
|
||||
| 群配置 template_reply_enabled=0 已确认 | ✅ | |
|
||||
| 不依赖 ai_enabled,仍走 v2(轨迹含 v2 关键词命中) | ✅ | [{"round":0,"action":"rule","params":{"keyword":"SF1234567890123","issue_type":"damaged"},"reason":"v2 关键词命中: 破损","function":"handleStoreFeedback","functionResult":{"error":"未找到当前货主在仓库中的运单「SF123456789 |
|
||||
| 出站回执存在 | ✅ | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 |
|
||||
|
||||
- 入站消息 id=2033,ai_thoughts:
|
||||
- 入站消息 id=2135,ai_thoughts:
|
||||
|
||||
```json
|
||||
[object Object]
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {
|
||||
"keyword": "SF1234567890123",
|
||||
"issue_type": "damaged"
|
||||
},
|
||||
"reason": "v2 关键词命中: 破损",
|
||||
"function": "handleStoreFeedback",
|
||||
"functionResult": {
|
||||
"error": "未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-11-1789582314626` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 |
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-11-1789656298793` | 未找到当前货主在仓库中的运单「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. 测试产生的入站/出站消息、工单等数据**已保留**(未自动清理),可直接在库中核对。
|
||||
|
||||
@ -120,6 +120,8 @@ WHERE group_id = '{测试群ID}' AND warehouse_id = {仓库ID};
|
||||
```
|
||||
|
||||
- `template_reply_enabled=1` 的群在第 6 步自动走 `inbox.v2.rules.handle`(已接入);
|
||||
- **模块优先语义**:`template_reply_enabled=1` 即为模块总开关,开启时不依赖 `ai_enabled`
|
||||
(两个开关同开时也走 v2 不走 v1/AI;`ai_enabled` 只约束未开启模板开关的群);
|
||||
- **模块接管模式**:v2 开启群的未命中消息直接静默,不走 v1 规则、不走 AI 兜底;
|
||||
- 群信息每条消息实时查库(`_loadGroupInfo` 不缓存),SQL 改动对下一条消息立即生效;
|
||||
- v2 配置数据(关键词/白名单/函数/取号/回复)有 300s 缓存,改动后需
|
||||
@ -179,7 +181,7 @@ WHERE app_key = '{测试app_key}';
|
||||
| 6 | 关键词命中 | 长词优先;命中后先过防误判守卫(如"拦截" vs "查物流") |
|
||||
| 7 | 函数越权 | `callFunction` 按群活跃分组校验,越权返回错误(DB 配置只做可见性,代码是最终权威) |
|
||||
| 8 | 取号失败 | 子类型关联了取号规则但未提取到值 → 回复引导语(`no_number_hint` → target 专属 → 默认),**不调用函数** |
|
||||
| 9 | 回复决策 | 回复表 `is_reply=1` → 自定义文案;`is_reply=0` → 静默(函数仍执行);无配置 → 函数返回值兜底 |
|
||||
| 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 分钟内不生效 |
|
||||
@ -214,7 +216,7 @@ WHERE app_key = '{测试app_key}';
|
||||
| `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` 引导语 |
|
||||
| `wms_after_sale_reply` | 仓库级(`warehouse_id` 非空)覆盖系统级;`is_reply=0` 静默、`no_number_hint` 引导语、`create_work_order=0` 函数照常执行但内部跳过工单登记 |
|
||||
|
||||
---
|
||||
|
||||
@ -223,6 +225,7 @@ WHERE app_key = '{测试app_key}';
|
||||
### 6.1 开关与分叉边界
|
||||
|
||||
- **AI 开关**:`ai_enabled != 1` 一律跳过(安全默认,快递群默认关闭);
|
||||
例外:`template_reply_enabled=1` 的群不依赖 AI 开关(模块优先);
|
||||
- **群未绑定**:`group_type` 为空跳过;`store` 群无 `store_id` 归属时主分组不激活(`resolveActiveGroups`);
|
||||
- **v1/v2 分叉**(已接入):`template_reply_enabled=1` 走 `inbox.v2.rules.handle`,
|
||||
否则走 `inbox.rules.handle`(v1 分支原逻辑零改动);
|
||||
@ -238,7 +241,8 @@ WHERE app_key = '{测试app_key}';
|
||||
合并去重 join 逗号 → `keyword`;`express_name→express`;
|
||||
子类型转译 `issue_type`(damage→damaged、change_address→addr、rejected→return、urge→urge 等);
|
||||
- **多函数子类型**:按 `sort_order` 依次执行,任一失败立即返回失败文案;
|
||||
- **回复优先级**:回复表(仓库级 > 系统级)> 函数返回值(`direct_reply.messages` > `data.message` > `error`);
|
||||
- **回复优先级**:回复表(仓库级 > 系统级);模板渲染为空或无配置时**默认不回复**(函数照常执行);
|
||||
`{back_text}` 占位符由 help 函数提供,业务函数无该内容时渲染为空 → 不回复;
|
||||
- **缓存失效**:管理接口增删改配置后必须调用 `ctx.service.inbox.v2.config.invalidate(warehouseId)`;
|
||||
启动时**不清** v2 缓存(防雪崩)。
|
||||
|
||||
@ -275,8 +279,8 @@ SET group_type='store', sub_type='after_sales',
|
||||
WHERE group_id='{测试群ID}' AND warehouse_id={仓库ID};
|
||||
```
|
||||
|
||||
v2 链路的四个开关缺一不可:`group_type` 非空 → `ai_enabled=1` → `template_reply_enabled=1`
|
||||
→ 消息内容命中 v2 关键词。
|
||||
v2 链路只需三个条件(模板开关优先,不依赖 AI 开关):`group_type` 非空 →
|
||||
`template_reply_enabled=1` → 消息内容命中 v2 关键词;`ai_enabled` 开或关都不影响 v2。
|
||||
|
||||
### 7.2 推送消息并核对(HTTP 入口)
|
||||
|
||||
@ -313,8 +317,10 @@ v2 链路的四个开关缺一不可:`group_type` 非空 → `ai_enabled=1`
|
||||
| 揽收 | `上门取件 SF1234567890123` | `requestPickup` + pickup 工单 |
|
||||
| 取号失败 | `破损` | 回复引导语,**不建工单** |
|
||||
| v2 未命中 | `今天天气怎么样` | 模块接管静默:无函数调用、无回执记录 |
|
||||
| 模块优先 | 同破损内容 + `ai_enabled=0`(`template_reply_enabled=1` 不变) | 仍走 v2 并回执(不依赖 AI 开关) |
|
||||
| 历史消息 | 同破损内容 + `sendTime` 为 30 分钟前 | 静默跳过:无回执、无工单 |
|
||||
| 群开关关闭 | 同破损内容 + `template_reply_enabled=0` | 走 v1(不属 v2 测试范围,仅确认分叉生效) |
|
||||
|
||||
> 所有用例的群必须 `template_reply_enabled=1`;**不测** `template_reply_enabled=0` 的 v1 场景。
|
||||
|
||||
### 7.4 边界补充
|
||||
|
||||
|
||||
@ -77,6 +77,7 @@ module.exports = {
|
||||
ORDER_WAVE_AUTO_GROUP: '自动加团',
|
||||
ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次',
|
||||
ORDER_WAVE_CLAIM: '领取波次',
|
||||
ORDER_CONFIRM_PRINT: '确认打印',
|
||||
ORDER_AUTO_EXPRESS_SKIP: '跳过自动分配快递',
|
||||
ORDER_PICK_COMPLETE: '拣货完成',
|
||||
ORDER_RECHECK: '订单复核',
|
||||
|
||||
@ -32,6 +32,12 @@ module.exports = app => {
|
||||
defaultValue: 1,
|
||||
comment: '是否回复:1=命中后回复,0=静默不回复',
|
||||
},
|
||||
create_work_order: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否登记工单:1=执行函数处理(可能建工单,默认),0=仅回复不执行函数',
|
||||
},
|
||||
no_number_hint: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
|
||||
@ -15,6 +15,7 @@ module.exports = app => {
|
||||
SENDED_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||
INSPECTION_STATUS: [ 'none', 'padding', 'running', 'fin', 'error' ],
|
||||
PRINT_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||
CONFIRM_PRINT_STATUS: [ 'none', 'fin' ],
|
||||
PRINT_LOCK_STATUS: [ 'none', 'warehouse' ],
|
||||
CLAIM_STATUS: [ 'none', 'padding', 'fin', 'error' ],
|
||||
OUTBOUND_STATUS: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
|
||||
@ -533,6 +534,12 @@ module.exports = app => {
|
||||
defaultValue: 'none',
|
||||
comment: '打印状态机',
|
||||
},
|
||||
confirm_print_status: {
|
||||
type: ENUM(...StatusEnum.CONFIRM_PRINT_STATUS),
|
||||
allowNull: true,
|
||||
defaultValue: 'none',
|
||||
comment: '确认打印状态机(打印完成后真实扫描面单确认)',
|
||||
},
|
||||
claim_status: {
|
||||
type: ENUM(...StatusEnum.CLAIM_STATUS),
|
||||
allowNull: true,
|
||||
|
||||
@ -1182,6 +1182,7 @@ module.exports = app => {
|
||||
inspection_status: [ 'none', 'padding', 'running', 'fin', 'error' ],
|
||||
step: [ 0, 1 ],
|
||||
print_status: [ 'none', 'padding', 'fin', 'error' ],
|
||||
confirm_print_status: [ 'none', 'fin' ],
|
||||
print_lock_status: [ 'none', 'warehouse' ],
|
||||
claim_status: [ 'none', 'padding', 'fin', 'error' ],
|
||||
outbound_status: [ 'none', 'padding', 'fin', 'timeout', 'error' ],
|
||||
|
||||
@ -130,6 +130,7 @@ module.exports = app => {
|
||||
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
|
||||
{ name: 'idx_warehouse_create_time', fields: [ 'warehouse_id', 'create_time' ] },
|
||||
{ name: 'idx_workbench_id', fields: [ 'workbench_id' ] },
|
||||
{ name: 'idx_workbench_create_time', fields: [ 'workbench_id', 'create_time' ] },
|
||||
{ name: 'idx_wave_id', fields: [ 'wave_id' ] },
|
||||
{ name: 'idx_waybill_code', fields: [ 'waybill_code' ] },
|
||||
{ name: 'idx_pack_mode_status', fields: [ 'pack_mode', 'status' ] },
|
||||
|
||||
@ -20,6 +20,16 @@ function extractLicensePlate(text) {
|
||||
return m ? m[0] : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 回复配置 create_work_order=0 时,v2 引擎注入 ctx.inboxContext.skip_work_order,
|
||||
* 函数照常执行但建单前应跳过工单登记。
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {boolean} 是否跳过工单登记。
|
||||
*/
|
||||
function shouldSkipWorkOrder(ctx) {
|
||||
return !!(ctx && ctx.inboxContext && ctx.inboxContext.skip_work_order === true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 站内信函数注册表。
|
||||
* 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。
|
||||
@ -41,6 +51,58 @@ class InboxFunctionsService extends Service {
|
||||
* 注册内置函数。
|
||||
*/
|
||||
registerBuiltinFunctions() {
|
||||
this.register('help', {
|
||||
description: '帮助指令:枚举当前仓库可见的售后类型与子类型(含关键词),返回可用指令清单(back_text),供回复模板 {back_text} 占位符渲染',
|
||||
params: {},
|
||||
groups: [ GROUP.COMMON ],
|
||||
weight: 0,
|
||||
keywords: [ '指令', '帮助' ],
|
||||
handler: async (params = {}) => {
|
||||
const { ctx } = this;
|
||||
void params;
|
||||
const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0);
|
||||
|
||||
let cfg = null;
|
||||
try {
|
||||
cfg = await ctx.service.inbox.v2.config.load(warehouseId);
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[inbox functions] help 加载 v2 配置失败: ${e.message}`);
|
||||
}
|
||||
|
||||
// 类型名映射
|
||||
let typeNameMap = {};
|
||||
try {
|
||||
const types = await ctx.model.AfterSaleType.findAll({ attributes: [ 'type', 'name' ], raw: true });
|
||||
typeNameMap = {};
|
||||
for (const t of types) typeNameMap[t.type] = t.name;
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
// 关键词按子类型聚合(可见配置)
|
||||
const kwBySubType = {};
|
||||
if (cfg && Array.isArray(cfg.keywords)) {
|
||||
for (const k of cfg.keywords) {
|
||||
if (!kwBySubType[k.sub_type_id]) kwBySubType[k.sub_type_id] = [];
|
||||
kwBySubType[k.sub_type_id].push(k.keyword);
|
||||
}
|
||||
}
|
||||
|
||||
const lines = [];
|
||||
const subTypes = (cfg && cfg.subTypes) ? Object.values(cfg.subTypes) : [];
|
||||
for (const st of subTypes) {
|
||||
const tName = typeNameMap[st.type] || st.type;
|
||||
const kws = kwBySubType[st.id] || [];
|
||||
lines.push(`${tName}:`);
|
||||
lines.push(` ${st.name}:关键词:${kws.length > 0 ? kws.join(',') : '(未配置)'}`);
|
||||
}
|
||||
const backText = lines.length > 0 ? lines.join('\n') : '(当前仓库未配置可用指令)';
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: { back_text: backText },
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
this.register('hello', {
|
||||
description: '问候接口,返回欢迎信息。传入 name 参数可个性化问候',
|
||||
params: {
|
||||
@ -979,6 +1041,11 @@ class InboxFunctionsService extends Service {
|
||||
interceptMsgContent ? `原消息: ${interceptMsgContent}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
|
||||
if (shouldSkipWorkOrder(ctx)) {
|
||||
ctx.logger.info(`[inbox functions] 拦截: skip_work_order,跳过工单登记 ${e.waybill_code}`);
|
||||
return { success: true, data: { message: '已记录拦截诉求(本次不登记工单)', skipped_work_order: true } };
|
||||
}
|
||||
|
||||
await ctx.service.systems.afterSale.create({
|
||||
warehouse_id: warehouseId,
|
||||
after_sale_no: afterSaleNo,
|
||||
@ -1117,7 +1184,7 @@ class InboxFunctionsService extends Service {
|
||||
await logService.createOperationLogs(
|
||||
interceptOrderIds.map(oid => ({
|
||||
businessType: 'order',
|
||||
businessId: String(warehouseId),
|
||||
businessId: String(oid),
|
||||
operationCode: 'ORDER_INTERCEPT_REQUEST',
|
||||
operator: { id: '0', name: groupName || 'AI系统' },
|
||||
extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' },
|
||||
@ -1400,6 +1467,11 @@ class InboxFunctionsService extends Service {
|
||||
originalText ? `原文: ${originalText}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
|
||||
if (shouldSkipWorkOrder(ctx)) {
|
||||
ctx.logger.info(`[inbox functions] 揽收: skip_work_order,跳过工单登记 ${e.waybill_code}`);
|
||||
return { success: true, data: { message: '已记录揽收诉求(本次不登记工单)', skipped_work_order: true } };
|
||||
}
|
||||
|
||||
await ctx.service.systems.afterSale.create({
|
||||
warehouse_id: warehouseId,
|
||||
after_sale_no: afterSaleNo,
|
||||
@ -1629,7 +1701,9 @@ class InboxFunctionsService extends Service {
|
||||
const unpackId = Number(unpack.id || 0);
|
||||
if (videos.length > 0) {
|
||||
for (const video of videos) {
|
||||
if (video.video_url) lines.push(String(video.video_url));
|
||||
if (!video.video_url) continue;
|
||||
const cameraName = String(video.camera_name || '').trim();
|
||||
lines.push(cameraName ? `${cameraName}:${video.video_url}` : String(video.video_url));
|
||||
}
|
||||
lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询');
|
||||
// 视频已可用:推进补录请求状态为 completed(回写视频地址)
|
||||
@ -1829,6 +1903,10 @@ class InboxFunctionsService extends Service {
|
||||
// 第四步:无工单的按拦截规则创建
|
||||
const createdNos = [];
|
||||
if (toCreate.length > 0) {
|
||||
if (shouldSkipWorkOrder(ctx)) {
|
||||
ctx.logger.info('[inbox functions] 取消拦截: skip_work_order,跳过创建工单');
|
||||
return { success: true, data: { message: '取消拦截信息已登记(本次不创建工单)', skipped_work_order: true } };
|
||||
}
|
||||
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
|
||||
for (const e of toCreate) {
|
||||
const afterSaleNo = await ctx.service.systemMethods.afterSale.generateAfterSaleNo(warehouseId);
|
||||
@ -1943,7 +2021,7 @@ class InboxFunctionsService extends Service {
|
||||
await logSvc.createOperationLogs(
|
||||
interceptOrderIds.map(oid => ({
|
||||
businessType: 'order',
|
||||
businessId: String(warehouseId),
|
||||
businessId: String(oid),
|
||||
operationCode: 'ORDER_INTERCEPT_REQUEST',
|
||||
operator: { id: '0', name: groupName || 'AI系统' },
|
||||
extras: { warehouseId, orderId: oid, newInterceptStatus: 'requested' },
|
||||
@ -2149,6 +2227,11 @@ class InboxFunctionsService extends Service {
|
||||
msgContent ? `原消息: ${msgContent}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
|
||||
if (shouldSkipWorkOrder(ctx)) {
|
||||
ctx.logger.info(`[inbox functions] 问题反馈: skip_work_order,跳过工单登记 ${e.waybill_code}`);
|
||||
return { success: true, data: { message: '已记录问题反馈(本次不登记工单)', skipped_work_order: true } };
|
||||
}
|
||||
|
||||
await ctx.service.systems.afterSale.create({
|
||||
warehouse_id: warehouseId,
|
||||
after_sale_no: afterSaleNo,
|
||||
@ -2299,6 +2382,10 @@ class InboxFunctionsService extends Service {
|
||||
for (const r of existingASList) {
|
||||
waybillToAsNo[r.waybill_id] = r.after_sale_no;
|
||||
}
|
||||
if (shouldSkipWorkOrder(ctx)) {
|
||||
ctx.logger.info('[inbox functions] 改地址/催件: skip_work_order,跳过工单登记');
|
||||
return { success: true, data: { message: '已记录诉求(本次不登记工单)', skipped_work_order: true } };
|
||||
}
|
||||
if (toCreate.length > 0) {
|
||||
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
|
||||
for (const e of toCreate) {
|
||||
@ -2537,6 +2624,10 @@ class InboxFunctionsService extends Service {
|
||||
// 第三步:创建工单(含原文)并映射 waybill_id → 工单号
|
||||
const createdNos = [];
|
||||
const waybillToAsNo = {};
|
||||
if (shouldSkipWorkOrder(ctx)) {
|
||||
ctx.logger.info('[inbox functions] 核实签收: skip_work_order,跳过工单登记');
|
||||
return { success: true, data: { message: '已记录核实签收诉求(本次不登记工单)', skipped_work_order: true } };
|
||||
}
|
||||
if (toCreate.length > 0) {
|
||||
const creatorLabel = [ groupName, userName ].filter(Boolean).join('-') || 'AI系统';
|
||||
for (const e of toCreate) {
|
||||
@ -3303,7 +3394,7 @@ class InboxFunctionsService extends Service {
|
||||
// 第五步:查打包视频
|
||||
const taskIds = packTasks.map(t => t.id);
|
||||
const videos = await ctx.model.PackTaskVideo.findAll({
|
||||
attributes: [ 'id', 'video_url', 'status' ],
|
||||
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
|
||||
where: {
|
||||
pack_task_id: { [Op.in]: taskIds },
|
||||
deleted_at: null,
|
||||
@ -3345,7 +3436,29 @@ class InboxFunctionsService extends Service {
|
||||
reRecordFailedWbs.push(e.waybill_code);
|
||||
}
|
||||
} else {
|
||||
videoLines.push(`${e.waybill_code}\n${urls.join('\n')}`);
|
||||
// 摄像头名称放链接前(系统设置的自定义名称优先,通道原始名称兜底)
|
||||
const packCameraIds = [ ...new Set(videos.filter(v => v.camera_id).map(v => v.camera_id)) ];
|
||||
const packCameraNameMap = new Map();
|
||||
if (packCameraIds.length > 0) {
|
||||
const packCameras = await ctx.model.Camera.findAll({
|
||||
attributes: [ 'id', 'custom_name', 'channel_name' ],
|
||||
where: { id: { [Op.in]: packCameraIds } },
|
||||
raw: true,
|
||||
});
|
||||
for (const c of packCameras) {
|
||||
packCameraNameMap.set(Number(c.id), String(c.custom_name || c.channel_name || '').trim());
|
||||
}
|
||||
}
|
||||
const displayLines = videos
|
||||
.filter(v => String(v.status || '') !== 'failed')
|
||||
.map(v => {
|
||||
const url = inboxTools.buildVideoUrl(warehouseId, recordingComputerId, v.video_url);
|
||||
if (!url) return '';
|
||||
const cameraName = v.camera_id ? (packCameraNameMap.get(Number(v.camera_id)) || '') : '';
|
||||
return cameraName ? `${cameraName}:${url}` : url;
|
||||
})
|
||||
.filter(Boolean);
|
||||
videoLines.push(`${e.waybill_code}\n${displayLines.join('\n')}`);
|
||||
// 视频已可用:推进补录请求状态为 completed(回写视频地址)
|
||||
for (const task of packTasks) {
|
||||
try {
|
||||
@ -3629,6 +3742,11 @@ class InboxFunctionsService extends Service {
|
||||
feedbackMsgContent ? `原文: ${feedbackMsgContent}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
|
||||
if (shouldSkipWorkOrder(ctx)) {
|
||||
ctx.logger.info(`[inbox functions] 快递反馈: skip_work_order,跳过工单登记 ${e.waybill_code}`);
|
||||
return { success: true, data: { message: '已记录快递反馈(本次不登记工单)', skipped_work_order: true } };
|
||||
}
|
||||
|
||||
await ctx.service.systems.afterSale.create({
|
||||
warehouse_id: warehouseId,
|
||||
after_sale_no: afterSaleNo,
|
||||
|
||||
@ -213,7 +213,10 @@ class InboxProcessorService extends Service {
|
||||
|
||||
// 5. 群未启用AI → 跳过(ai_enabled != 1 一律跳过,安全默认)
|
||||
// 快递群默认 ai_enabled=0,需手动开启后才会走 AI 处理
|
||||
if (ctx.inboxContext.ai_enabled !== 1) {
|
||||
// v2 例外:模板回信引擎(template_reply_enabled=1)优先于原链路,
|
||||
// 即使 ai_enabled=0 也进入第 6 步走 v2;两开关同开时仍走 v2 不走 v1/AI。
|
||||
const v2Enabled = ctx.inboxContext.template_reply_enabled === 1;
|
||||
if (ctx.inboxContext.ai_enabled !== 1 && !v2Enabled) {
|
||||
ctx.logger.info(`[inbox processor] 群未启用AI自动回复,跳过 AI ext_id=${extId}`);
|
||||
return;
|
||||
}
|
||||
@ -235,7 +238,6 @@ class InboxProcessorService extends Service {
|
||||
// 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);
|
||||
|
||||
@ -383,7 +383,7 @@ const STORE_RULES = [
|
||||
tip: '如需催退回,发送:催退回+运单号\n例:催退回 SF123' },
|
||||
{ keys: [ '催件', '催派', '催促', '尽快安排派送', '未中转', '物流停滞' ], fn: 'changeAddr', issueType: 'urge', waybill: true,
|
||||
tip: '如需催件,发送:催件+运单号\n例:催件 SF123' },
|
||||
{ keys: [ '查退回', '是否已退回' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code',
|
||||
{ keys: [ '查退回', '是否已退回', '查退件', '查件' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code',
|
||||
tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' },
|
||||
{ keys: [ '退回', '拒收' ], fn: 'queryReturn', waybill: true, paramName: 'waybill_code',
|
||||
tip: '如需查退回,发送:查退回+运单号\n例:查退回 SF123' },
|
||||
|
||||
@ -126,9 +126,17 @@ class InboxV2ConfigService extends Service {
|
||||
});
|
||||
const funcIdMap = {};
|
||||
const functionEnabled = {};
|
||||
// 启用状态硬编码:代码注册表中存在的函数即启用(DB is_enabled 仅作展示参考,不再作为启用依据)
|
||||
let registry = null;
|
||||
try {
|
||||
registry = this.ctx.service.inbox.functions.registry;
|
||||
} catch (e) { /* ignore */ }
|
||||
for (const f of funcRows) {
|
||||
funcIdMap[f.id] = f.function_code;
|
||||
if (Number(f.is_enabled) === 1) functionEnabled[f.function_code] = true;
|
||||
const inRegistry = registry instanceof Map && registry.has(f.function_code);
|
||||
if (inRegistry || (registry === null && Number(f.is_enabled) === 1)) {
|
||||
functionEnabled[f.function_code] = true;
|
||||
}
|
||||
}
|
||||
const subTypeFunctions = {};
|
||||
for (const r of funcRelRows) {
|
||||
@ -170,7 +178,7 @@ class InboxV2ConfigService extends Service {
|
||||
// 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' ],
|
||||
attributes: [ 'warehouse_id', 'sub_type_id', 'reply', 'is_reply', 'create_work_order', 'no_number_hint' ],
|
||||
raw: true,
|
||||
});
|
||||
const replies = {};
|
||||
@ -182,6 +190,7 @@ class InboxV2ConfigService extends Service {
|
||||
replies[r.sub_type_id] = {
|
||||
reply: String(r.reply || ''),
|
||||
is_reply: Number(r.is_reply) === 1 ? 1 : 0,
|
||||
create_work_order: Number(r.create_work_order) === 0 ? 0 : 1,
|
||||
no_number_hint: r.no_number_hint ? String(r.no_number_hint) : '',
|
||||
warehouse_id: isWh ? r.warehouse_id : null,
|
||||
};
|
||||
|
||||
@ -2,6 +2,41 @@
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* function_code → 中文名称映射(管理界面展示用)。
|
||||
* 未列出的函数回退到 function_code(英文注册名)。
|
||||
*/
|
||||
const FUNCTION_NAME_MAP = {
|
||||
hello: '问候',
|
||||
help: '帮助',
|
||||
queryPrintBalance: '查询面单余额',
|
||||
createWaybill: '创建运单号',
|
||||
searchStock: '搜索货主商品',
|
||||
searchWarehouseStock: '搜索仓库商品',
|
||||
queryOrder: '查询订单',
|
||||
recallHistory: '回顾对话历史',
|
||||
createOrder: '创建发货单',
|
||||
blockUser: '屏蔽用户',
|
||||
interceptWaybill: '拦截运单',
|
||||
requestPickup: '揽收处理',
|
||||
queryReturn: '查询退回单',
|
||||
cancelIntercept: '取消拦截',
|
||||
handleStoreFeedback: '问题反馈建单',
|
||||
changeAddr: '改地址/催件处理',
|
||||
weishoudao: '核实签收',
|
||||
changeExpress: '改快递',
|
||||
createPostnum: '分配快递号',
|
||||
queryPackVideo: '查询打包视频',
|
||||
queryWeight: '查询重量',
|
||||
handleExpressFeedback: '快递反馈处理',
|
||||
queryWarehouseAddress: '查询仓库地址',
|
||||
listGroups: '查询群列表',
|
||||
openDoor: '开门',
|
||||
registerLicensePlate: '到货登记',
|
||||
departure: '离场登记',
|
||||
enter: '进场登记',
|
||||
};
|
||||
|
||||
/**
|
||||
* 售后函数表同步服务(v2 仓库可配置回信引擎)。
|
||||
*
|
||||
@ -48,7 +83,7 @@ class InboxV2FunctionSyncService extends Service {
|
||||
seen.add(code);
|
||||
rows.push({
|
||||
function_code: code,
|
||||
name: code,
|
||||
name: FUNCTION_NAME_MAP[code] || code,
|
||||
description: (typeof def.description === 'string' ? def.description : '').slice(0, 500) || null,
|
||||
});
|
||||
}
|
||||
@ -65,11 +100,22 @@ class InboxV2FunctionSyncService extends Service {
|
||||
stats.updated = rows.length - stats.created;
|
||||
|
||||
// bulkCreate + updateOnDuplicate:新行插入(is_enabled 默认 1、sort_order 默认 0),
|
||||
// 已有行仅刷新 name/description,不覆盖管理端维护的 is_enabled / sort_order。
|
||||
// 已有行刷新 name/description;启用状态硬编码——注册表存在即启用(is_enabled 同步为 1),
|
||||
// sort_order 由接口配置,不同步覆盖。
|
||||
await ctx.model.AfterSaleFunction.bulkCreate(rows, {
|
||||
updateOnDuplicate: [ 'name', 'description' ],
|
||||
updateOnDuplicate: [ 'name', 'description', 'is_enabled' ],
|
||||
});
|
||||
|
||||
// 代码已删除的函数:保留行但标记下线(is_enabled=0),不删除。
|
||||
if (rows.length > 0) {
|
||||
const codes = rows.map(r => r.function_code);
|
||||
const { Op } = ctx.app.Sequelize;
|
||||
await ctx.model.AfterSaleFunction.update(
|
||||
{ is_enabled: 0 },
|
||||
{ where: { function_code: { [Op.notIn]: codes } } }
|
||||
);
|
||||
}
|
||||
|
||||
stats.ok = true;
|
||||
return stats;
|
||||
} catch (error) {
|
||||
|
||||
@ -130,53 +130,66 @@ class InboxV2RulesService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 2.4 逐函数执行(按 sort_order;任一失败立即以失败出参返回)
|
||||
// 2.4 逐函数执行:函数照常执行;create_work_order=0 时注入 skip_work_order
|
||||
// 标记,由函数内部在建工单前自行跳过登记(其余处理不受影响)。
|
||||
const replyCfgNow = (cfg.replies || {})[cand.sub_type_id];
|
||||
const workOrderSkip = !!replyCfgNow && replyCfgNow.create_work_order === 0;
|
||||
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;
|
||||
if (workOrderSkip) {
|
||||
ctx.inboxContext.skip_work_order = true;
|
||||
ctx.logger.info(
|
||||
`[inbox v2] 执行 fn=${f.function_code} sub=${subType.type}:${subType.sub_type} ` +
|
||||
`params=${JSON.stringify(params)} success=${!!result.success}`
|
||||
`[inbox v2] 子类型 ${subType.type}:${subType.sub_type} 配置为不登记工单,函数照常执行但跳过建单`
|
||||
);
|
||||
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,
|
||||
};
|
||||
}
|
||||
try {
|
||||
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 });
|
||||
}
|
||||
results.push({ fn: f.function_code, params, result });
|
||||
} finally {
|
||||
if (workOrderSkip) ctx.inboxContext.skip_work_order = false;
|
||||
}
|
||||
if (!executed) continue;
|
||||
|
||||
// 2.5 回复决策:回复表(仓库级覆盖系统级)→ 函数返回值兜底
|
||||
// 2.5 回复决策:完全由回复配置控制(仓库级覆盖系统级)
|
||||
return this._buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text);
|
||||
}
|
||||
|
||||
@ -220,8 +233,10 @@ class InboxV2RulesService extends Service {
|
||||
const rows = (cfg.groupWhitelist || {})[subTypeId];
|
||||
if (!Array.isArray(rows) || rows.length === 0) return false;
|
||||
return rows.some(r => {
|
||||
if (r.group_type === '*') return true; // 全通配:所有群可用(如 help 指令)
|
||||
if (r.group_type !== groupType) return false;
|
||||
if (!groupSubType) return true; // 群未绑子类型:只按主类型放行
|
||||
if (r.sub_group === '*') return true; // 主类型内子类型通配(如 warehouse:*)
|
||||
return r.sub_group === groupSubType;
|
||||
});
|
||||
}
|
||||
@ -318,7 +333,7 @@ class InboxV2RulesService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 出参构建:回复表决策(仓库级覆盖系统级)→ 函数返回值兜底。
|
||||
* 出参构建:回复决策完全由回复配置控制(仓库级覆盖系统级)。
|
||||
* @param {Object} cfg v2 配置。
|
||||
* @param {Object} cand 命中候选。
|
||||
* @param {Object} subType 子类型记录。
|
||||
@ -329,22 +344,23 @@ class InboxV2RulesService extends Service {
|
||||
* @return {Object} 与 v1 rules.handle 同构的出参。
|
||||
*/
|
||||
_buildOutcome(cfg, cand, subType, results, lastFn, lastParams, text) {
|
||||
const last = results[results.length - 1];
|
||||
const last = results.length > 0 ? results[results.length - 1] : null;
|
||||
const replyCfg = (cfg.replies || {})[cand.sub_type_id];
|
||||
|
||||
// 回复表显式配置:is_reply=0 静默;is_reply=1 用自定义文案(占位符替换)
|
||||
// 回复决策:完全由回复配置控制。
|
||||
// - is_reply=0 → 静默;
|
||||
// - reply 模板渲染非空 → 回复;
|
||||
// - 无回复配置或模板渲染为空 → 不回复(函数已照常执行,仅不出回执)。
|
||||
if (replyCfg && replyCfg.is_reply === 0) {
|
||||
return { handled: true, silent: true };
|
||||
}
|
||||
let reply;
|
||||
let reply = null;
|
||||
if (replyCfg && replyCfg.reply) {
|
||||
reply = this._renderReply(replyCfg.reply, subType, results, text);
|
||||
} else {
|
||||
// 无回复配置:函数返回值兜底(与 v1 buildReply 同构语义)
|
||||
reply = this._buildReplyFromResult(results);
|
||||
const rendered = this._renderReply(replyCfg.reply, subType, results, text, lastParams);
|
||||
if (rendered && String(rendered).trim()) reply = rendered;
|
||||
}
|
||||
|
||||
const thoughts = results.map((r, idx) => ({
|
||||
let thoughts = results.map((r, idx) => ({
|
||||
round: idx,
|
||||
action: 'rule',
|
||||
function: r.fn,
|
||||
@ -352,60 +368,52 @@ class InboxV2RulesService extends Service {
|
||||
reason: `v2 关键词命中: ${cand.keyword}`,
|
||||
functionResult: r.result,
|
||||
}));
|
||||
if (thoughts.length === 0 && lastParams) {
|
||||
// 兜底(一般不可达:fns 全部不可用才出现):记录一条无函数调用的轨迹
|
||||
thoughts = [{
|
||||
round: 0,
|
||||
action: 'rule',
|
||||
function: lastFn,
|
||||
params: lastParams,
|
||||
reason: `v2 关键词命中: ${cand.keyword}(无可用函数)`,
|
||||
functionResult: null,
|
||||
}];
|
||||
}
|
||||
|
||||
return {
|
||||
handled: true,
|
||||
reply,
|
||||
fn: lastFn || last.fn,
|
||||
params: lastParams || last.params,
|
||||
result: last.result,
|
||||
fn: lastFn || (last && last.fn),
|
||||
params: lastParams || (last && last.params),
|
||||
result: last ? last.result : null,
|
||||
matchedKey: cand.keyword,
|
||||
thoughts,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 回复文案占位符渲染:{sub_type_name}/{keyword}/{express}。
|
||||
* 回复文案占位符渲染:{sub_type_name}/{keyword}/{express}/{back_text}。
|
||||
* {back_text} 取自函数返回的 data.back_text(如 help 函数生成的指令清单)。
|
||||
* @param {string} tpl 模板文案。
|
||||
* @param {Object} subType 子类型记录。
|
||||
* @param {Array} results 函数执行结果。
|
||||
* @param {string} text 消息正文。
|
||||
* @param {Object} [fallbackParams] 未执行函数时的备用参数(create_work_order=0 场景)。
|
||||
* @return {string} 渲染后的文案。
|
||||
*/
|
||||
_renderReply(tpl, subType, results, text) {
|
||||
const last = results[results.length - 1];
|
||||
const params = (last && last.params) || {};
|
||||
_renderReply(tpl, subType, results, text, fallbackParams) {
|
||||
const last = results.length > 0 ? results[results.length - 1] : null;
|
||||
const params = (last && last.params) || fallbackParams || {};
|
||||
const backText = (last && last.result && last.result.data && last.result.data.back_text)
|
||||
? String(last.result.data.back_text)
|
||||
: '';
|
||||
return String(tpl)
|
||||
.replace(/\{sub_type_name\}/g, subType.name || '')
|
||||
.replace(/\{keyword\}/g, String(params.keyword || ''))
|
||||
.replace(/\{express\}/g, String(params.express || ''))
|
||||
.replace(/\{back_text\}/g, backText)
|
||||
.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;
|
||||
|
||||
@ -53,6 +53,29 @@ class InboxSystemService extends MainService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* v2 可配置回信引擎配置管理子入口,供 /system dispatcher 按 inbox.v2.* 路径访问。
|
||||
* 全部委托给 systems/inbox/v2.js(配置管理系统服务层),本层只做 checkAuth 代理。
|
||||
* @return {Object} v2 配置管理方法集合(type/subType/keyword/numberRule/function/reply/relation)。
|
||||
*/
|
||||
get v2() {
|
||||
const { ctx } = this;
|
||||
const svc = () => ctx.service.systems.inbox.v2;
|
||||
return {
|
||||
type: { ...svc().type, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
subType: { ...svc().subType, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
keyword: { ...svc().keyword, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
numberRule: { ...svc().numberRule, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
function: { ...svc().function, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
reply: { ...svc().reply, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
relation: {
|
||||
function: { ...svc().relation.function, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
rule: { ...svc().relation.rule, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
group: { ...svc().relation.group, checkAuth: (...args) => this.checkAuth(...args) },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成货主绑群码。
|
||||
* 委托给 systems.store.bindCode 执行:校验 StoreWarehouse 合约 → 生成12位随机码 → 缓存300秒。
|
||||
@ -182,7 +205,8 @@ class InboxSystemService extends MainService {
|
||||
|
||||
/**
|
||||
* 修改群信息。
|
||||
* 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。
|
||||
* 支持修改 group_type / sub_type / store_id / express_interfaces /
|
||||
* system_express_code / ai_enabled / template_reply_enabled。
|
||||
* warehouseId 从 ctx.user.store_id 自动注入。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
@ -192,6 +216,8 @@ class InboxSystemService extends MainService {
|
||||
* @param {number} [data.storeId] 关联货主ID。
|
||||
* @param {number[]} [data.expressInterfaces] 快递接口ID数组(仅 express 生效)。
|
||||
* @param {string} [data.systemExpressCode] 系统快递编码(express 时必填)。
|
||||
* @param {number} [data.aiEnabled] 是否启用AI自动回复: 0=关闭 1=开启。
|
||||
* @param {number} [data.templateReplyEnabled] 是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)。
|
||||
* @return {Promise<Object>} { message: 操作结果 }。
|
||||
*/
|
||||
async groupUpdate(data = {}) {
|
||||
@ -199,6 +225,7 @@ class InboxSystemService extends MainService {
|
||||
const {
|
||||
id, groupType, subType, storeId,
|
||||
expressInterfaces, systemExpressCode, aiEnabled,
|
||||
templateReplyEnabled,
|
||||
} = data;
|
||||
const warehouseId = Number(ctx.user?.store_id || 0);
|
||||
|
||||
@ -211,6 +238,7 @@ class InboxSystemService extends MainService {
|
||||
expressInterfaces,
|
||||
systemExpressCode,
|
||||
aiEnabled,
|
||||
templateReplyEnabled,
|
||||
});
|
||||
|
||||
return { message: '群信息修改成功' };
|
||||
|
||||
@ -45,7 +45,7 @@ const ORDER_LIST_BASE_ATTRIBUTES = [
|
||||
'wave_strategy_version',
|
||||
'wave_scan_result',
|
||||
'post_status', 'storage_status', 'pick_status', 'pack_status',
|
||||
'inspection_status', 'print_status', 'claim_status',
|
||||
'inspection_status', 'print_status', 'confirm_print_status', 'claim_status',
|
||||
'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status',
|
||||
'create_channel',
|
||||
'store_id',
|
||||
|
||||
@ -26,6 +26,9 @@ const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_CACHE_KEY_PREFIX = 'wave:quick-sca
|
||||
const WAVE_STRATEGY_QUICK_SCAN_WAREHOUSE_LOCK_TTL_SECONDS = 60 * 60 * 2;
|
||||
const WAVE_STRATEGY_LIST_CACHE_KEY_PREFIX = 'wave:strategy-list:';
|
||||
const WAVE_STRATEGY_LIST_CACHE_TTL_SECONDS = 60 * 30;
|
||||
const CONFIRM_PRINT_UNCLAIMED_VERSION_KEY_PREFIX = 'wave:confirm-print:unclaimed:version:';
|
||||
const CONFIRM_PRINT_UNCLAIMED_POLL_TIMEOUT_MS = 60 * 1000;
|
||||
const CONFIRM_PRINT_UNCLAIMED_POLL_INTERVAL_MS = 1000;
|
||||
const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID = 1;
|
||||
const BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_IDS = [ BATCH_ALLOCATE_STORAGE_FORCE_BUSINESS_ID ];
|
||||
const BATCH_ALLOCATE_STORAGE_WAREHOUSE_TASK_LOCK_MAP = new Map();
|
||||
@ -87,6 +90,17 @@ const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({
|
||||
statsColumnPrefix: 'print',
|
||||
withErrorStatus: false,
|
||||
}),
|
||||
confirm_print: Object.freeze({
|
||||
fieldName: 'confirm_print_assignment_status',
|
||||
enumMap: Object.freeze({
|
||||
unconfirmed: 'none',
|
||||
partially_confirmed: 'partial',
|
||||
confirmed: 'finished',
|
||||
}),
|
||||
caseInsensitive: true,
|
||||
statsColumnPrefix: 'confirm_print',
|
||||
withErrorStatus: false,
|
||||
}),
|
||||
review: Object.freeze({
|
||||
fieldName: 'review_assignment_status',
|
||||
enumMap: Object.freeze({
|
||||
@ -98,6 +112,17 @@ const BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS = Object.freeze({
|
||||
statsColumnPrefix: 'review',
|
||||
withErrorStatus: true,
|
||||
}),
|
||||
sync: Object.freeze({
|
||||
fieldName: 'sync_assignment_status',
|
||||
enumMap: Object.freeze({
|
||||
unsynced: 'none',
|
||||
partially_synced: 'partial',
|
||||
synced: 'finished',
|
||||
}),
|
||||
caseInsensitive: true,
|
||||
statsColumnPrefix: 'sync',
|
||||
withErrorStatus: true,
|
||||
}),
|
||||
});
|
||||
|
||||
class WaveService extends OrderBaseService {
|
||||
@ -109,9 +134,9 @@ class WaveService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress';
|
||||
const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress';
|
||||
const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress';
|
||||
const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount';
|
||||
const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintScan,confirmPrintUnclaimedWaveCount';
|
||||
const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -1185,6 +1210,9 @@ class WaveService extends OrderBaseService {
|
||||
scene: 'fetchSingleStructure',
|
||||
});
|
||||
|
||||
// 抓取波次(source=1/2)会冗余写入领料人/领料时间,递增统计版本号驱动长轮询
|
||||
await this.bumpConfirmPrintUnclaimedWaveVersion(warehouseId);
|
||||
|
||||
const mergedOrderIds = [ ...new Set(allOrderIds) ].sort((a, b) => a - b);
|
||||
this.enqueueWaveStrategyQuickScanPostOrderChange(warehouseId, mergedOrderIds, {
|
||||
triggerScan: false,
|
||||
@ -1395,6 +1423,43 @@ class WaveService extends OrderBaseService {
|
||||
return this.normalizeBatchListAssignmentStatusFilterByType(value, 'print');
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化波次列表确认打印状态筛选值(英文枚举)。
|
||||
*
|
||||
* @param {string} value 入参筛选值。
|
||||
* @return {string} 规范化后的筛选值,未传时返回空字符串。
|
||||
*/
|
||||
normalizeBatchListConfirmPrintAssignmentStatusFilter(value) {
|
||||
return this.normalizeBatchListAssignmentStatusFilterByType(value, 'confirm_print');
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化波次列表领料状态筛选值。
|
||||
*
|
||||
* 领料状态以波次表 claim_time 为准(二态,无 partial):
|
||||
* - none = 未领料(claim_time IS NULL);
|
||||
* - finished = 已领料(claim_time IS NOT NULL)。
|
||||
*
|
||||
* @param {string} value 入参筛选值(unclaimed/claimed,兼容中文 未领料/已领料)。
|
||||
* @return {string} 规范化后的筛选值(none/finished),未传时返回空字符串。
|
||||
*/
|
||||
normalizeBatchListClaimAssignmentStatusFilter(value) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return '';
|
||||
}
|
||||
const normalizedValue = String(value).trim().toLowerCase();
|
||||
if (!normalizedValue) {
|
||||
return '';
|
||||
}
|
||||
if ([ 'unclaimed', 'none', '未领料', '未领单' ].includes(normalizedValue)) {
|
||||
return 'none';
|
||||
}
|
||||
if ([ 'claimed', 'finished', '已领料', '已领单' ].includes(normalizedValue)) {
|
||||
return 'finished';
|
||||
}
|
||||
throw new Error('claim_assignment_status 参数不合法,仅支持: unclaimed / claimed(未领料 / 已领料)');
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化波次列表复核状态筛选值(英文枚举)。
|
||||
*
|
||||
@ -1405,10 +1470,20 @@ class WaveService extends OrderBaseService {
|
||||
return this.normalizeBatchListAssignmentStatusFilterByType(value, 'review');
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化波次列表同步状态筛选值(英文枚举)。
|
||||
*
|
||||
* @param {string} value 入参筛选值。
|
||||
* @return {string} 规范化后的筛选值,未传时返回空字符串。
|
||||
*/
|
||||
normalizeBatchListSyncAssignmentStatusFilter(value) {
|
||||
return this.normalizeBatchListAssignmentStatusFilterByType(value, 'sync');
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据类型获取波次分配状态筛选配置。
|
||||
*
|
||||
* @param {'storage'|'express'|'print'} type 筛选类型。
|
||||
* @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。
|
||||
* @return {{ fieldName: string, enumMap: Object, caseInsensitive: boolean, statsColumnPrefix: string, withErrorStatus: boolean }} 筛选配置。
|
||||
*/
|
||||
getBatchListAssignmentFilterSchema(type) {
|
||||
@ -1424,7 +1499,7 @@ class WaveService extends OrderBaseService {
|
||||
* 按类型规范化波次列表分配状态筛选值。
|
||||
*
|
||||
* @param {string} value 入参筛选值。
|
||||
* @param {'storage'|'express'|'print'} type 筛选类型。
|
||||
* @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。
|
||||
* @return {string} 规范化后的筛选值,未传时返回空字符串。
|
||||
*/
|
||||
normalizeBatchListAssignmentStatusFilterByType(value, type) {
|
||||
@ -1532,6 +1607,45 @@ class WaveService extends OrderBaseService {
|
||||
return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'print');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建波次列表确认打印状态筛选 SQL 条件。
|
||||
*
|
||||
* @param {string} statusFilter 确认打印状态筛选值(none/partial/finished)。
|
||||
* @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。
|
||||
*/
|
||||
buildBatchListConfirmPrintAssignmentFilterClause(statusFilter = '') {
|
||||
return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'confirm_print');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建波次列表领料状态筛选 SQL 条件(波次表 claim_time 口径,二态)。
|
||||
*
|
||||
* @param {string} statusFilter 领料状态筛选值(none/finished)。
|
||||
* @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。
|
||||
*/
|
||||
buildBatchListClaimAssignmentFilterClause(statusFilter = '') {
|
||||
const normalizedStatusFilter = String(statusFilter || '').trim();
|
||||
if (!normalizedStatusFilter) {
|
||||
return {
|
||||
sql: '',
|
||||
replacements: {},
|
||||
};
|
||||
}
|
||||
if (normalizedStatusFilter === 'none') {
|
||||
return {
|
||||
sql: '\n AND wb.claim_time IS NULL',
|
||||
replacements: {},
|
||||
};
|
||||
}
|
||||
if (normalizedStatusFilter === 'finished') {
|
||||
return {
|
||||
sql: '\n AND wb.claim_time IS NOT NULL',
|
||||
replacements: {},
|
||||
};
|
||||
}
|
||||
throw new Error(`不支持的领料状态筛选值: ${normalizedStatusFilter}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建波次列表复核状态筛选 SQL 条件。
|
||||
*
|
||||
@ -1542,11 +1656,21 @@ class WaveService extends OrderBaseService {
|
||||
return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'review');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建波次列表同步状态筛选 SQL 条件。
|
||||
*
|
||||
* @param {string} statusFilter 同步状态筛选值(none/partial/finished)。
|
||||
* @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。
|
||||
*/
|
||||
buildBatchListSyncAssignmentFilterClause(statusFilter = '') {
|
||||
return this.buildBatchListAssignmentStatusFilterClauseByType(statusFilter, 'sync');
|
||||
}
|
||||
|
||||
/**
|
||||
* 按类型构建波次列表分配状态筛选 SQL 条件。
|
||||
*
|
||||
* @param {string} statusFilter 分配状态筛选值(none/partial/finished)。
|
||||
* @param {'storage'|'express'|'print'} type 筛选类型。
|
||||
* @param {'storage'|'express'|'print'|'confirm_print'} type 筛选类型。
|
||||
* @return {{ sql: string, replacements: Object }} SQL 条件片段与参数。
|
||||
*/
|
||||
buildBatchListAssignmentStatusFilterClauseByType(statusFilter = '', type = 'storage') {
|
||||
@ -1992,7 +2116,10 @@ class WaveService extends OrderBaseService {
|
||||
'storage_assignment_status',
|
||||
'express_assignment_status',
|
||||
'print_assignment_status',
|
||||
'confirm_print_assignment_status',
|
||||
'claim_assignment_status',
|
||||
'review_assignment_status',
|
||||
'sync_assignment_status',
|
||||
'store_id',
|
||||
];
|
||||
|
||||
@ -2194,10 +2321,22 @@ class WaveService extends OrderBaseService {
|
||||
'print_assignment_status',
|
||||
value => this.normalizeBatchListPrintAssignmentStatusFilter(value)
|
||||
);
|
||||
const confirmPrintAssignmentStatus = resolveAssignmentStatusFilter(
|
||||
'confirm_print_assignment_status',
|
||||
value => this.normalizeBatchListConfirmPrintAssignmentStatusFilter(value)
|
||||
);
|
||||
const claimAssignmentStatus = resolveAssignmentStatusFilter(
|
||||
'claim_assignment_status',
|
||||
value => this.normalizeBatchListClaimAssignmentStatusFilter(value)
|
||||
);
|
||||
const reviewAssignmentStatus = resolveAssignmentStatusFilter(
|
||||
'review_assignment_status',
|
||||
value => this.normalizeBatchListReviewAssignmentStatusFilter(value)
|
||||
);
|
||||
const syncAssignmentStatus = resolveAssignmentStatusFilter(
|
||||
'sync_assignment_status',
|
||||
value => this.normalizeBatchListSyncAssignmentStatusFilter(value)
|
||||
);
|
||||
|
||||
return {
|
||||
sql: conditions.length > 0 ? `\n AND ${conditions.join('\n AND ')}` : '',
|
||||
@ -2205,7 +2344,10 @@ class WaveService extends OrderBaseService {
|
||||
storageAssignmentStatus,
|
||||
expressAssignmentStatus,
|
||||
printAssignmentStatus,
|
||||
confirmPrintAssignmentStatus,
|
||||
claimAssignmentStatus,
|
||||
reviewAssignmentStatus,
|
||||
syncAssignmentStatus,
|
||||
storeIds: storeIdCondition.ids,
|
||||
storeIdOperator: storeIdCondition.operator,
|
||||
};
|
||||
@ -5032,7 +5174,10 @@ class WaveService extends OrderBaseService {
|
||||
const storageAssignmentFilterClause = this.buildBatchListStorageAssignmentFilterClause(whereClause.storageAssignmentStatus);
|
||||
const expressAssignmentFilterClause = this.buildBatchListExpressAssignmentFilterClause(whereClause.expressAssignmentStatus);
|
||||
const printAssignmentFilterClause = this.buildBatchListPrintAssignmentFilterClause(whereClause.printAssignmentStatus);
|
||||
const confirmPrintAssignmentFilterClause = this.buildBatchListConfirmPrintAssignmentFilterClause(whereClause.confirmPrintAssignmentStatus);
|
||||
const claimAssignmentFilterClause = this.buildBatchListClaimAssignmentFilterClause(whereClause.claimAssignmentStatus);
|
||||
const reviewAssignmentFilterClause = this.buildBatchListReviewAssignmentFilterClause(whereClause.reviewAssignmentStatus);
|
||||
const syncAssignmentFilterClause = this.buildBatchListSyncAssignmentFilterClause(whereClause.syncAssignmentStatus);
|
||||
const onlyTodo = Number(requestData.only_todo || 0);
|
||||
const baseBatchWhereSql = `
|
||||
warehouse_id = :warehouseId
|
||||
@ -5077,6 +5222,8 @@ class WaveService extends OrderBaseService {
|
||||
item_snapshot_key,
|
||||
warehouse_id,
|
||||
creator,
|
||||
claim_operator,
|
||||
claim_time,
|
||||
create_time,
|
||||
update_time
|
||||
FROM wms_wave_batch
|
||||
@ -5094,9 +5241,14 @@ class WaveService extends OrderBaseService {
|
||||
SUM(CASE WHEN od.post_status = 'error' THEN 1 ELSE 0 END) AS post_error_count,
|
||||
SUM(CASE WHEN od.print_status = 'none' THEN 1 ELSE 0 END) AS print_none_count,
|
||||
SUM(CASE WHEN od.print_status = 'fin' THEN 1 ELSE 0 END) AS print_fin_count,
|
||||
SUM(CASE WHEN od.confirm_print_status = 'none' THEN 1 ELSE 0 END) AS confirm_print_none_count,
|
||||
SUM(CASE WHEN od.confirm_print_status = 'fin' THEN 1 ELSE 0 END) AS confirm_print_fin_count,
|
||||
SUM(CASE WHEN od.recheck_status = 'fin' THEN 1 ELSE 0 END) AS review_fin_count,
|
||||
SUM(CASE WHEN od.recheck_status = 'error' THEN 1 ELSE 0 END) AS review_error_count,
|
||||
SUM(CASE WHEN od.recheck_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS review_none_count,
|
||||
SUM(CASE WHEN od.sync_status = 'fin' THEN 1 ELSE 0 END) AS sync_fin_count,
|
||||
SUM(CASE WHEN od.sync_status = 'error' THEN 1 ELSE 0 END) AS sync_error_count,
|
||||
SUM(CASE WHEN od.sync_status IS NULL OR od.sync_status NOT IN ('fin', 'error') THEN 1 ELSE 0 END) AS sync_none_count,
|
||||
SUM(CASE WHEN od.pick_status = 'none' THEN 1 ELSE 0 END) AS pick_none_count,
|
||||
SUM(CASE WHEN od.pick_status = 'fin' THEN 1 ELSE 0 END) AS pick_fin_count,
|
||||
SUM(CASE WHEN od.pick_status = 'error' THEN 1 ELSE 0 END) AS pick_error_count,
|
||||
@ -5118,7 +5270,10 @@ class WaveService extends OrderBaseService {
|
||||
${storageAssignmentFilterClause.sql}
|
||||
${expressAssignmentFilterClause.sql}
|
||||
${printAssignmentFilterClause.sql}
|
||||
${confirmPrintAssignmentFilterClause.sql}
|
||||
${claimAssignmentFilterClause.sql}
|
||||
${reviewAssignmentFilterClause.sql}
|
||||
${syncAssignmentFilterClause.sql}
|
||||
${onlyTodo === 1 ? '\n AND COALESCE(wave_order_stats.order_total, 0) - COALESCE(wave_order_stats.review_fin_count, 0) > 0' : ''}
|
||||
`;
|
||||
|
||||
@ -5137,6 +5292,8 @@ class WaveService extends OrderBaseService {
|
||||
wb.item_snapshot_key,
|
||||
wb.warehouse_id,
|
||||
wb.creator,
|
||||
wb.claim_operator,
|
||||
wb.claim_time,
|
||||
wb.create_time,
|
||||
wb.update_time,
|
||||
COALESCE(wave_order_stats.order_total, 0) AS order_total,
|
||||
@ -5148,12 +5305,17 @@ class WaveService extends OrderBaseService {
|
||||
COALESCE(wave_order_stats.post_error_count, 0) AS post_error_count,
|
||||
COALESCE(wave_order_stats.print_none_count, 0) AS print_none_count,
|
||||
COALESCE(wave_order_stats.print_fin_count, 0) AS print_fin_count,
|
||||
COALESCE(wave_order_stats.confirm_print_none_count, 0) AS confirm_print_none_count,
|
||||
COALESCE(wave_order_stats.confirm_print_fin_count, 0) AS confirm_print_fin_count,
|
||||
COALESCE(wave_order_stats.review_fin_count, 0) AS review_fin_count,
|
||||
COALESCE(wave_order_stats.review_error_count, 0) AS review_error_count,
|
||||
COALESCE(wave_order_stats.review_none_count, 0) AS review_none_count,
|
||||
COALESCE(wave_order_stats.pick_none_count, 0) AS pick_none_count,
|
||||
COALESCE(wave_order_stats.pick_fin_count, 0) AS pick_fin_count,
|
||||
COALESCE(wave_order_stats.pick_error_count, 0) AS pick_error_count,
|
||||
COALESCE(wave_order_stats.sync_none_count, 0) AS sync_none_count,
|
||||
COALESCE(wave_order_stats.sync_fin_count, 0) AS sync_fin_count,
|
||||
COALESCE(wave_order_stats.sync_error_count, 0) AS sync_error_count,
|
||||
COALESCE(wave_order_stats.owner_distinct_count, 0) AS owner_distinct_count,
|
||||
wave_order_stats.owner_store_id,
|
||||
COALESCE(wave_order_stats.owner_named_count, 0) AS owner_named_count
|
||||
@ -5176,7 +5338,10 @@ class WaveService extends OrderBaseService {
|
||||
...storageAssignmentFilterClause.replacements,
|
||||
...expressAssignmentFilterClause.replacements,
|
||||
...printAssignmentFilterClause.replacements,
|
||||
...confirmPrintAssignmentFilterClause.replacements,
|
||||
...claimAssignmentFilterClause.replacements,
|
||||
...reviewAssignmentFilterClause.replacements,
|
||||
...syncAssignmentFilterClause.replacements,
|
||||
...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}),
|
||||
limit: pageSize,
|
||||
offset,
|
||||
@ -5190,7 +5355,10 @@ class WaveService extends OrderBaseService {
|
||||
...storageAssignmentFilterClause.replacements,
|
||||
...expressAssignmentFilterClause.replacements,
|
||||
...printAssignmentFilterClause.replacements,
|
||||
...confirmPrintAssignmentFilterClause.replacements,
|
||||
...claimAssignmentFilterClause.replacements,
|
||||
...reviewAssignmentFilterClause.replacements,
|
||||
...syncAssignmentFilterClause.replacements,
|
||||
...(storeIdFilter.length > 0 ? { whereStoreIds: storeIdFilter } : {}),
|
||||
},
|
||||
}),
|
||||
@ -5228,11 +5396,16 @@ class WaveService extends OrderBaseService {
|
||||
const expressErrorCount = Number(batch && batch.post_error_count || 0);
|
||||
const printNoneCount = Number(batch && batch.print_none_count || 0);
|
||||
const printFinCount = Number(batch && batch.print_fin_count || 0);
|
||||
const confirmPrintNoneCount = Number(batch && batch.confirm_print_none_count || 0);
|
||||
const confirmPrintFinCount = Number(batch && batch.confirm_print_fin_count || 0);
|
||||
const pickNoneCount = Number(batch && batch.pick_none_count || 0);
|
||||
const pickFinCount = Number(batch && batch.pick_fin_count || 0);
|
||||
const pickErrorCount = Number(batch && batch.pick_error_count || 0);
|
||||
const reviewFinCount = Number(batch && batch.review_fin_count || 0);
|
||||
const reviewErrorCount = Number(batch && batch.review_error_count || 0);
|
||||
const syncNoneCount = Number(batch && batch.sync_none_count || 0);
|
||||
const syncFinCount = Number(batch && batch.sync_fin_count || 0);
|
||||
const syncErrorCount = Number(batch && batch.sync_error_count || 0);
|
||||
const unreviewedOrderCount = orderCount - reviewFinCount;
|
||||
const ownerDistinctCount = Number(batch && batch.owner_distinct_count || 0);
|
||||
const ownerNamedCount = Number(batch && batch.owner_named_count || 0);
|
||||
@ -5283,6 +5456,14 @@ class WaveService extends OrderBaseService {
|
||||
partial: '部分打印',
|
||||
finished: '已打印',
|
||||
}),
|
||||
confirm_print_assignment_status: this.resolveAssignmentStatus(orderCount, confirmPrintNoneCount, confirmPrintFinCount, 0, {
|
||||
none: '未确认打印',
|
||||
partial: '部分确认打印',
|
||||
finished: '已确认打印',
|
||||
}),
|
||||
claim_assignment_status: batch && batch.claim_time ? '已领料' : '未领料',
|
||||
claim_time: batch && batch.claim_time || null,
|
||||
claim_operator: String(batch && batch.claim_operator || '').trim(),
|
||||
pick_assignment_status: this.resolveAssignmentStatus(orderCount, pickNoneCount, pickFinCount, pickErrorCount, {
|
||||
none: '未拣货',
|
||||
partial: '部分拣货',
|
||||
@ -5290,6 +5471,12 @@ class WaveService extends OrderBaseService {
|
||||
error: '拣货异常',
|
||||
}),
|
||||
review_assignment_status: reviewAssignmentStatus,
|
||||
sync_assignment_status: this.resolveAssignmentStatus(orderCount, syncNoneCount, syncFinCount, syncErrorCount, {
|
||||
none: '未同步',
|
||||
partial: '部分同步',
|
||||
finished: '已同步',
|
||||
error: '同步异常',
|
||||
}),
|
||||
unreviewed_order_count: unreviewedOrderCount,
|
||||
store_name: ownerName,
|
||||
};
|
||||
@ -5308,6 +5495,214 @@ class WaveService extends OrderBaseService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取确认打印未领单波次版本号的缓存 key。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {string} 缓存 key。
|
||||
*/
|
||||
getConfirmPrintUnclaimedVersionKey(warehouseId) {
|
||||
return `${CONFIRM_PRINT_UNCLAIMED_VERSION_KEY_PREFIX}${warehouseId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递增确认打印未领单波次版本号。
|
||||
*
|
||||
* 确认打印(print.confirmWavePrint)与领单(pick.waveClaimScan)会改变统计结果,
|
||||
* 操作成功后调用本方法,驱动 confirmPrintUnclaimedWaveCount 长轮询立即返回新值。
|
||||
* Redis 不可用或失败仅记录 warn,不影响主流程(长轮询端会降级为轮询 DB)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async bumpConfirmPrintUnclaimedWaveVersion(warehouseId) {
|
||||
try {
|
||||
const client = this.app && this.app.redis && typeof this.app.redis.get === 'function'
|
||||
? this.app.redis.get('cache')
|
||||
: null;
|
||||
if (client && typeof client.incr === 'function') {
|
||||
await client.incr(this.getConfirmPrintUnclaimedVersionKey(warehouseId));
|
||||
}
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[wave.confirmPrintVersion] 版本号递增失败', {
|
||||
warehouseId,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取确认打印未领单波次版本号。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<number|null>} 版本号,读取失败或不存在时返回 null。
|
||||
*/
|
||||
async getConfirmPrintUnclaimedWaveVersion(warehouseId) {
|
||||
try {
|
||||
const client = this.app && this.app.redis && typeof this.app.redis.get === 'function'
|
||||
? this.app.redis.get('cache')
|
||||
: null;
|
||||
if (!client || typeof client.get !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const rawValue = await client.get(this.getConfirmPrintUnclaimedVersionKey(warehouseId));
|
||||
const value = Number(rawValue);
|
||||
return Number.isFinite(value) && value > 0 ? value : null;
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[wave.confirmPrintVersion] 版本号读取失败', {
|
||||
warehouseId,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询「已确认打印但未领单」的波次数量(波次表驱动口径)。
|
||||
*
|
||||
* 口径说明:
|
||||
* - 未领单:以波次表为准(wb.claim_time IS NULL)。历史领单发生在 wms_wave_batch
|
||||
* 增加 claim_time 字段之前时,订单维度 claim_status 可能已是 'fin' 但波次表无
|
||||
* 记录,故不能用订单 claim_status 判断「波次是否领单」。
|
||||
* - 已确认打印:波次下存在 confirm_print_status='fin' 的非取消订单。
|
||||
* - 仅统计 wave_status 0/1 的波次(与波次列表一致)。
|
||||
*
|
||||
* @param {number} warehouseId 仓库ID。
|
||||
* @return {Promise<number>} 波次数量。
|
||||
*/
|
||||
async queryConfirmPrintUnclaimedWaveCount(warehouseId) {
|
||||
const orderModel = await this.getOrderModel('pendingOrder', warehouseId);
|
||||
const orderTableName = this.getModelTableSqlName(orderModel);
|
||||
const rows = await this.ctx.model.query(
|
||||
`SELECT COUNT(*) AS wave_count
|
||||
FROM wms_wave_batch wb
|
||||
WHERE wb.warehouse_id = :warehouseId
|
||||
AND wb.wave_status IN (0, 1)
|
||||
AND wb.claim_time IS NULL
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM ${orderTableName} od
|
||||
WHERE od.wave_id = wb.wave_id
|
||||
AND od.warehouse_id = wb.warehouse_id
|
||||
AND od.status <> 'cancel'
|
||||
AND od.confirm_print_status = 'fin'
|
||||
)`,
|
||||
{ replacements: { warehouseId } }
|
||||
);
|
||||
const rawList = Array.isArray(rows && rows[0]) ? rows[0] : [];
|
||||
return Number(rawList[0] && rawList[0].wave_count || 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认打印扫描(与领单 pick.waveClaimScan 操作一致):
|
||||
* 扫波次内任一订单面单号,将波次下已打印且非拦截的订单批量置
|
||||
* confirm_print_status='fin' 并写订单操作日志。
|
||||
*
|
||||
* 实际复用 print.confirmWavePrint 实现,避免重复维护;
|
||||
* 成功后递增统计版本号,驱动 confirmPrintUnclaimedWaveCount 长轮询。
|
||||
*
|
||||
* @param {Object} data 入参。
|
||||
* @param {string} data.waybill_no 面单号/运单号(必填)。
|
||||
* @return {Promise<Object>} 统一返回结构。
|
||||
*/
|
||||
async confirmPrintScan(data = {}) {
|
||||
const printService = this.ctx.service
|
||||
&& this.ctx.service.systemMethods
|
||||
&& this.ctx.service.systemMethods.print;
|
||||
if (!printService || typeof printService.confirmWavePrint !== 'function') {
|
||||
return this.fail('确认打印服务不可用', {}, 500);
|
||||
}
|
||||
return await printService.confirmWavePrint(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速查询「已确认打印但未领单」的波次数量(波次表驱动口径:
|
||||
* 未领单以 wms_wave_batch.claim_time IS NULL 为准,已确认打印以波次下存在
|
||||
* confirm_print_status='fin' 的订单为准)。
|
||||
*
|
||||
* 长轮询语义(参考工作台扫码登录):
|
||||
* - 不传 last_count:立即返回当前值(status=current);
|
||||
* - 传 last_count 且与当前值不同:立即返回新值(status=changed);
|
||||
* - 传 last_count 且与当前值相同:进入等待,每 1s 检查一次版本号(确认打印/领单
|
||||
* 成功会递增版本号),最长等待 60s;期间变化立即返回新值(status=changed),
|
||||
* 超时未变化则重查一次返回当前值(status=timeout)。
|
||||
*
|
||||
* @param {Object} [data={}] 入参。
|
||||
* @param {number|string} [data.last_count] 上次调用返回的 count(可选基线)。
|
||||
* @return {Promise<Object>} 统一返回结构,data 含 count / warehouse_id / status。
|
||||
*/
|
||||
async confirmPrintUnclaimedWaveCount(data = {}) {
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const warehouseId = Number(this.getWarehouseId() || 0);
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
return this.fail('未识别到当前仓库上下文', {}, 400);
|
||||
}
|
||||
|
||||
const rawLastCount = requestData.last_count === undefined
|
||||
? requestData.lastCount
|
||||
: requestData.last_count;
|
||||
const hasBaseline = rawLastCount !== undefined && rawLastCount !== null && rawLastCount !== '';
|
||||
const lastCount = hasBaseline ? Number(rawLastCount) : NaN;
|
||||
|
||||
let currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId);
|
||||
|
||||
// 未带基线或基线非法:直接返回当前值(快速查询)
|
||||
if (!hasBaseline || !Number.isFinite(lastCount)) {
|
||||
return this.success('ok', {
|
||||
count: currentCount,
|
||||
warehouse_id: warehouseId,
|
||||
status: 'current',
|
||||
});
|
||||
}
|
||||
|
||||
// 已变化:立即返回新值
|
||||
if (currentCount !== lastCount) {
|
||||
return this.success('ok', {
|
||||
count: currentCount,
|
||||
warehouse_id: warehouseId,
|
||||
status: 'changed',
|
||||
});
|
||||
}
|
||||
|
||||
// 等待变化:优先轮询版本号(低成本),版本号不可用时降级为轮询 DB
|
||||
const baselineVersion = await this.getConfirmPrintUnclaimedWaveVersion(warehouseId);
|
||||
const startedAt = Date.now();
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
while (Date.now() - startedAt < CONFIRM_PRINT_UNCLAIMED_POLL_TIMEOUT_MS) {
|
||||
await sleep(CONFIRM_PRINT_UNCLAIMED_POLL_INTERVAL_MS);
|
||||
|
||||
const currentVersion = await this.getConfirmPrintUnclaimedWaveVersion(warehouseId);
|
||||
if (baselineVersion !== null && currentVersion !== null && currentVersion !== baselineVersion) {
|
||||
currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId);
|
||||
return this.success('ok', {
|
||||
count: currentCount,
|
||||
warehouse_id: warehouseId,
|
||||
status: 'changed',
|
||||
});
|
||||
}
|
||||
|
||||
// 版本号不可用:降级为直接对比 count
|
||||
if (baselineVersion === null || currentVersion === null) {
|
||||
currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId);
|
||||
if (currentCount !== lastCount) {
|
||||
return this.success('ok', {
|
||||
count: currentCount,
|
||||
warehouse_id: warehouseId,
|
||||
status: 'changed',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 超时兜底:重查一次返回当前值(若期间恰好变化也返回新值)
|
||||
currentCount = await this.queryConfirmPrintUnclaimedWaveCount(warehouseId);
|
||||
return this.success('ok', {
|
||||
count: currentCount,
|
||||
warehouse_id: warehouseId,
|
||||
status: currentCount !== lastCount ? 'changed' : 'timeout',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 拣货任务列表查询。
|
||||
*
|
||||
@ -11724,6 +12119,9 @@ class WaveService extends OrderBaseService {
|
||||
transaction,
|
||||
}
|
||||
);
|
||||
|
||||
// 领料时间写入会改变确认打印未领单统计,递增版本号驱动长轮询
|
||||
await this.bumpConfirmPrintUnclaimedWaveVersion(warehouseId);
|
||||
}
|
||||
|
||||
await this.rebuildOrderWaveIndex({
|
||||
|
||||
@ -2035,6 +2035,20 @@ class PickService extends MainService {
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
// 驱动确认打印未领单波次统计长轮询:领单会减少未领单波次数量,递增版本号
|
||||
try {
|
||||
const waveService = ctx.service
|
||||
&& ctx.service.systemMethods
|
||||
&& ctx.service.systemMethods.order
|
||||
&& ctx.service.systemMethods.order.wave;
|
||||
if (waveService && typeof waveService.bumpConfirmPrintUnclaimedWaveVersion === 'function') {
|
||||
await waveService.bumpConfirmPrintUnclaimedWaveVersion(normalizedWarehouseId);
|
||||
}
|
||||
} catch (error) {
|
||||
ctx.logger.warn('[PickService.waveClaimScan] 统计版本号递增失败: %s',
|
||||
error && error.message ? error.message : error);
|
||||
}
|
||||
|
||||
return this.success('ok', {
|
||||
data: {
|
||||
...baseResponse,
|
||||
|
||||
@ -7,7 +7,10 @@ const {
|
||||
ExpressPrintPayloadBuilder,
|
||||
RequestScopedPrintIdGenerator,
|
||||
} = require('../../lib/express_print_payload_builder');
|
||||
const { INTERCEPT_STATUS_NONE } = require('../../lib/intercept_guard');
|
||||
const {
|
||||
INTERCEPT_STATUS_NONE,
|
||||
isInterceptedOrderStatus,
|
||||
} = require('../../lib/intercept_guard');
|
||||
|
||||
/**
|
||||
* 打印 Service
|
||||
@ -1715,6 +1718,222 @@ class PrintService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 波次确认打印:扫描波次内任一订单的面单号,将波次下全部已打印且非拦截的订单
|
||||
* 批量标记 confirm_print_status='fin',记录「打印完成后真实扫描面单确认」。
|
||||
*
|
||||
* 约束:
|
||||
* - 仅当前仓库下的订单可确认(面单定位强制 warehouse_id 隔离);
|
||||
* - 波次下存在未打印订单(print_status != 'fin',拦截订单除外)时阻断;
|
||||
* - 拦截订单跳过(不确认、不阻断);
|
||||
* - 全部已确认时重复扫描返回 already_confirmed,不重复写日志。
|
||||
*
|
||||
* @param {Object} data 入参。
|
||||
* @param {string} data.waybill_no 面单号/运单号(必填)。
|
||||
* @return {Promise<Object>} 统一返回结构。
|
||||
*/
|
||||
async confirmWavePrint(data = {}) {
|
||||
const { ctx } = this;
|
||||
const requestData = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
|
||||
const waybillNo = String(requestData.waybill_no || requestData.waybillNo || '').trim();
|
||||
if (!waybillNo) {
|
||||
return this.fail('waybill_no 必填(面单号/运单号)', {}, 400);
|
||||
}
|
||||
|
||||
// --- 仓库上下文 ---
|
||||
const userWarehouseId = ctx && ctx.user ? ctx.user.store_id : undefined;
|
||||
const stateWarehouseId = ctx && ctx.state && ctx.state.user ? ctx.state.user.store_id : undefined;
|
||||
const warehouseId = Number(userWarehouseId || stateWarehouseId || 0);
|
||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
|
||||
return this.fail('缺少当前用户仓库上下文 store_id', {}, 400);
|
||||
}
|
||||
|
||||
// --- 1. 面单号定位订单 ---
|
||||
const orderExpress = await ctx.model.OrderExpress.findOne({
|
||||
where: {
|
||||
warehouse_id: warehouseId,
|
||||
waybill_code: waybillNo,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const matchedOrderId = Number(orderExpress && orderExpress.order_id || 0);
|
||||
if (!(matchedOrderId > 0)) {
|
||||
return this.fail('未查询到该面单号对应的订单,无记录', {}, 404);
|
||||
}
|
||||
|
||||
// --- 2. 订单定位波次 ---
|
||||
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
|
||||
return this.fail('OrderDeliveryFactory 不可用', {}, 500);
|
||||
}
|
||||
let orderModel = null;
|
||||
try {
|
||||
orderModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
|
||||
} catch (error) {
|
||||
return this.fail(error && error.message ? error.message : '订单模型不可用', {}, 500);
|
||||
}
|
||||
const order = await orderModel.findOne({
|
||||
where: {
|
||||
id: matchedOrderId,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'id', 'wave_id', 'wave_no' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!order) {
|
||||
return this.fail('订单不在待处理订单表,无记录', {}, 404);
|
||||
}
|
||||
const orderWaveId = Number(order.wave_id || 0);
|
||||
const orderWaveNo = String(order.wave_no || '').trim();
|
||||
if (!(orderWaveId > 0 || orderWaveNo)) {
|
||||
return this.fail('运单对应订单未分配波次', {}, 400);
|
||||
}
|
||||
|
||||
// --- 3. 查询波次下全部订单 ---
|
||||
const waveOrderWhere = { warehouse_id: warehouseId };
|
||||
if (orderWaveId > 0) {
|
||||
waveOrderWhere.wave_id = orderWaveId;
|
||||
} else {
|
||||
waveOrderWhere.wave_no = orderWaveNo;
|
||||
}
|
||||
const waveOrderRows = await orderModel.findAll({
|
||||
where: waveOrderWhere,
|
||||
attributes: [ 'id', 'print_status', 'confirm_print_status', 'intercept_status' ],
|
||||
raw: true,
|
||||
});
|
||||
const waveOrders = Array.isArray(waveOrderRows) ? waveOrderRows : [];
|
||||
if (waveOrders.length === 0) {
|
||||
return this.fail('波次下无可用订单', {}, 400);
|
||||
}
|
||||
|
||||
// --- 4. 统计与校验(拦截订单跳过,未打印阻断) ---
|
||||
const interceptedWaveOrderIds = new Set(waveOrders
|
||||
.filter(item => isInterceptedOrderStatus(item && item.intercept_status))
|
||||
.map(item => Number(item && item.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0));
|
||||
|
||||
const unprintedOrderIds = [ ...new Set(waveOrders
|
||||
.filter(item => String(item && item.print_status || '') !== 'fin'
|
||||
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
|
||||
.map(item => Number(item && item.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
if (unprintedOrderIds.length > 0) {
|
||||
return this.fail('波次存在未打印订单,禁止确认打印', {
|
||||
waybill_no: waybillNo,
|
||||
matched_order_id: matchedOrderId,
|
||||
wave_id: orderWaveId,
|
||||
wave_no: orderWaveNo,
|
||||
unprinted_order_count: unprintedOrderIds.length,
|
||||
}, 400);
|
||||
}
|
||||
|
||||
const pendingOrderIds = [ ...new Set(waveOrders
|
||||
.filter(item => String(item && item.print_status || '') === 'fin'
|
||||
&& String(item && item.confirm_print_status || '') !== 'fin'
|
||||
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
|
||||
.map(item => Number(item && item.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
|
||||
const confirmedOrderIds = [ ...new Set(waveOrders
|
||||
.filter(item => String(item && item.confirm_print_status || '') === 'fin'
|
||||
&& !interceptedWaveOrderIds.has(Number(item && item.id || 0)))
|
||||
.map(item => Number(item && item.id || 0))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
|
||||
const baseResponse = {
|
||||
waybill_no: waybillNo,
|
||||
matched_order_id: matchedOrderId,
|
||||
wave_id: orderWaveId,
|
||||
wave_no: orderWaveNo,
|
||||
total_order_count: waveOrders.length,
|
||||
intercepted_order_count: interceptedWaveOrderIds.size,
|
||||
};
|
||||
|
||||
if (pendingOrderIds.length === 0) {
|
||||
return this.success('ok', {
|
||||
code: 200,
|
||||
data: {
|
||||
...baseResponse,
|
||||
confirmed_order_count: confirmedOrderIds.length,
|
||||
status: 'already_confirmed',
|
||||
tip: '该波次订单均已确认打印,无需重复确认',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// --- 5. 事务批量确认并写订单操作日志 ---
|
||||
const operationLogService = ctx.service
|
||||
&& ctx.service.systems
|
||||
&& ctx.service.systems.operationLog;
|
||||
const operator = this.getPrintOrderOperationOperator();
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
const updateResult = await orderModel.update({
|
||||
confirm_print_status: 'fin',
|
||||
}, {
|
||||
where: {
|
||||
id: { [this.app.Sequelize.Op.in]: pendingOrderIds },
|
||||
warehouse_id: warehouseId,
|
||||
print_status: 'fin',
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
const affectedRows = Number(Array.isArray(updateResult) ? updateResult[0] : updateResult) || 0;
|
||||
|
||||
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
|
||||
await operationLogService.createOperationLogs(pendingOrderIds.map(orderId => ({
|
||||
businessType: 'order',
|
||||
businessId: `${orderId}`,
|
||||
operationCode: 'ORDER_CONFIRM_PRINT',
|
||||
operator,
|
||||
operationAction: 'UPDATE',
|
||||
extras: {
|
||||
warehouseId,
|
||||
message: `确认打印(扫描面单 ${waybillNo},波次 ${orderWaveNo})`,
|
||||
},
|
||||
})), { transaction });
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
// 驱动确认打印未领单波次统计长轮询:递增版本号,等待中的查询立即返回新值
|
||||
try {
|
||||
const waveService = ctx.service
|
||||
&& ctx.service.systemMethods
|
||||
&& ctx.service.systemMethods.order
|
||||
&& ctx.service.systemMethods.order.wave;
|
||||
if (waveService && typeof waveService.bumpConfirmPrintUnclaimedWaveVersion === 'function') {
|
||||
await waveService.bumpConfirmPrintUnclaimedWaveVersion(warehouseId);
|
||||
}
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn('[print.confirmWavePrint] 统计版本号递增失败', {
|
||||
warehouseId,
|
||||
error: error && error.message ? error.message : `${error}`,
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[print.confirmWavePrint] 波次确认打印完成 warehouse_id=%d wave_id=%d affected=%d/%d',
|
||||
warehouseId, orderWaveId, affectedRows, pendingOrderIds.length);
|
||||
|
||||
return this.success('ok', {
|
||||
code: 200,
|
||||
data: {
|
||||
...baseResponse,
|
||||
confirmed_order_count: confirmedOrderIds.length + affectedRows,
|
||||
newly_confirmed_order_count: affectedRows,
|
||||
status: 'confirmed',
|
||||
tip: `波次确认打印完成,本次确认 ${affectedRows} 个订单`,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
this.ctx.logger.error('[print.confirmWavePrint] 波次确认打印失败 warehouse_id=%d wave_id=%d reason=%s',
|
||||
warehouseId, orderWaveId, error && error.message ? error.message : `${error}`);
|
||||
return this.fail('确认打印失败', {}, 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在打印发送成功后批量锁定订单。
|
||||
*
|
||||
|
||||
@ -5,10 +5,10 @@ const MainService = require('../main');
|
||||
class WorkbenchService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder';
|
||||
const _noNeedRight = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder';
|
||||
const _noNeedLogin = 'business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder,getWorkbenchCount';
|
||||
const _noNeedRight = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder,getWorkbenchCount';
|
||||
const _noNeedLog = 'list,detail,getWorkbenchInfo,removeMember,bindMember';
|
||||
const _noNeedAuth = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder';
|
||||
const _noNeedAuth = 'list,detail,business,getWorkbenchInfo,removeMember,bindMember,packOrder,finishPack,sendWeight,queryOrder,getWorkbenchCount';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -333,6 +333,29 @@ class WorkbenchService extends MainService {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前工作台班次打包统计(免登录、免鉴权,以工作台 token 鉴权,仓库与工作台由服务端注入)。
|
||||
* 统计窗口:本地时间当日 08:00 至次日 08:00,早于 08:00 时为昨日 08:00 至今日 08:00。
|
||||
* @param {Object} data - { token }
|
||||
*/
|
||||
async getWorkbenchCount(data) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const { token } = data || {};
|
||||
const result = await service.systems.workbench.getWorkbenchCountByToken({ token });
|
||||
if (result && result.success) {
|
||||
return this.success('ok', result);
|
||||
}
|
||||
const statusCode = result && result.statusCode;
|
||||
return this.fail(
|
||||
result && result.message ? result.message : '获取工作台统计失败',
|
||||
statusCode ? { code: statusCode } : undefined
|
||||
);
|
||||
} catch (error) {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WorkbenchService;
|
||||
|
||||
@ -476,6 +476,10 @@ class AfterSaleService extends Service {
|
||||
try {
|
||||
order = await ctx.model.OrderDelivery.findOne({
|
||||
where: { id: orderDeliveryId },
|
||||
attributes: [
|
||||
'id', 'name', 'tel', 'mobile', 'email', 'zip_code', 'country_code',
|
||||
'province', 'city', 'area', 'town', 'detail_address', 'store_id', 'items',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@ -1647,7 +1647,8 @@ class DeliveryOrderService extends Service {
|
||||
const stockId = Number(wms_stock.stock_id) || 0;
|
||||
|
||||
if (!stockId) {
|
||||
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》库存记录不存在`);
|
||||
// 此时 stock_store 存在但未绑定库存记录(stock_id 为空),即仓库侧已解绑
|
||||
errors.push(`第${i + 1}行: 商品《${wms_stock.item_name}》编码《${wms_stock.item_code}》仓库已解绑,请联系仓库关联绑定`);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@ -85,6 +85,7 @@ class InboxGroupService extends Service {
|
||||
source_type: { field: 'source_type' },
|
||||
is_blocked: { field: 'is_blocked' },
|
||||
ai_enabled: { field: 'ai_enabled' },
|
||||
template_reply_enabled: { field: 'template_reply_enabled' },
|
||||
system_express_code: { field: 'system_express_code' },
|
||||
},
|
||||
});
|
||||
@ -103,7 +104,8 @@ class InboxGroupService extends Service {
|
||||
attributes: [
|
||||
'id', 'group_name', 'group_id', 'store_id',
|
||||
'group_type', 'sub_type', 'source_type', 'source_extra',
|
||||
'is_blocked', 'ai_enabled', 'express_interfaces', 'system_express_code',
|
||||
'is_blocked', 'ai_enabled', 'template_reply_enabled',
|
||||
'express_interfaces', 'system_express_code',
|
||||
'created_at', 'updated_at',
|
||||
],
|
||||
where,
|
||||
@ -210,7 +212,7 @@ class InboxGroupService extends Service {
|
||||
* @param {string} [data.keyword] 关键词,模糊匹配 group_name / group_id。
|
||||
* @param {string} [data.groupType] 按群类型筛选:store / warehouse / express。
|
||||
* @param {number} [data.limit=20] 返回条数上限,最大 100。
|
||||
* @return {Promise<{list: Array<{id: number, group_id: (string|null), group_name: string, group_type: (string|null), sub_type: (string|null), is_blocked: number}>}>} 群快速列表。
|
||||
* @return {Promise<{list: Array<{id: number, group_id: (string|null), group_name: string, group_type: (string|null), sub_type: (string|null), is_blocked: number, template_reply_enabled: number}>}>} 群快速列表。
|
||||
*/
|
||||
async quickList(data = {}) {
|
||||
const { ctx } = this;
|
||||
@ -250,7 +252,7 @@ class InboxGroupService extends Service {
|
||||
}
|
||||
|
||||
const rows = await InboxGroup.findAll({
|
||||
attributes: [ 'id', 'group_id', 'group_name', 'group_type', 'sub_type', 'is_blocked' ],
|
||||
attributes: [ 'id', 'group_id', 'group_name', 'group_type', 'sub_type', 'is_blocked', 'template_reply_enabled' ],
|
||||
where,
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
limit,
|
||||
@ -406,6 +408,8 @@ class InboxGroupService extends Service {
|
||||
* 支持修改 group_type / sub_type / store_id / express_interfaces / system_express_code。
|
||||
* 群类型切为 express 时 system_express_code 必填,
|
||||
* express_interfaces 仅在群类型为 express 时生效(非 express 类型忽略)。
|
||||
* ai_enabled 控制是否 AI 处理,template_reply_enabled 控制命中处理后
|
||||
* 是否以模板消息形式回复(0=普通文本回复,1=模板消息回复),两者独立。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
* @param {number} data.id 群记录主键ID(必填)。
|
||||
@ -415,6 +419,8 @@ class InboxGroupService extends Service {
|
||||
* @param {number} [data.storeId] 关联货主ID。
|
||||
* @param {number[]} [data.expressInterfaces] 快递接口ID数组。
|
||||
* @param {string} [data.systemExpressCode] 系统快递编码。
|
||||
* @param {number} [data.aiEnabled] 是否启用AI自动回复: 0=关闭 1=开启。
|
||||
* @param {number} [data.templateReplyEnabled] 是否启用模板消息回复: 0=关闭(普通文本回复) 1=开启(模板消息回复)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async update(data = {}) {
|
||||
@ -525,6 +531,10 @@ class InboxGroupService extends Service {
|
||||
if (data.aiEnabled !== undefined) {
|
||||
updateData.ai_enabled = data.aiEnabled === 1 ? 1 : 0;
|
||||
}
|
||||
// 模板消息回复开关(所有群类型均支持,独立于 AI 开关)
|
||||
if (data.templateReplyEnabled !== undefined) {
|
||||
updateData.template_reply_enabled = data.templateReplyEnabled === 1 ? 1 : 0;
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
throw new Error('未提供任何需要修改的字段');
|
||||
@ -539,7 +549,7 @@ class InboxGroupService extends Service {
|
||||
/**
|
||||
* 清空群类型配置。
|
||||
* 将群恢复为"仅保留创建信息"状态:清空 group_type / sub_type / store_id /
|
||||
* express_interfaces / system_express_code,AI 开关重置为关闭。
|
||||
* express_interfaces / system_express_code,AI 开关与模板消息回复开关重置为关闭。
|
||||
* 保留群名称、群ID、仓库、来源信息、屏蔽状态与扩展数据。
|
||||
*
|
||||
* @param {Object} data 请求数据。
|
||||
@ -574,6 +584,7 @@ class InboxGroupService extends Service {
|
||||
express_interfaces: null,
|
||||
system_express_code: null,
|
||||
ai_enabled: 0,
|
||||
template_reply_enabled: 0,
|
||||
},
|
||||
{ where }
|
||||
);
|
||||
|
||||
798
app/service/systems/inbox/v2.js
Normal file
798
app/service/systems/inbox/v2.js
Normal file
@ -0,0 +1,798 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
/**
|
||||
* v2 可配置回信引擎 —— 配置管理系统服务层。
|
||||
*
|
||||
* 规则:
|
||||
* - warehouseId 一律从登录上下文 ctx.user.store_id 注入(仓库隔离);
|
||||
* - 系统预设锁定:is_system=1 的主数据只读;系统级子类型(warehouse_id=NULL)
|
||||
* 的关联行只读(群白名单另尊重关联行 is_system 列);
|
||||
* - 关键词属仓库级数据(warehouse_id=当前仓库),可挂在系统级子类型下
|
||||
* (keyword.create/update/delete 不做子类型「仓库自定义」限制);
|
||||
* - 自定义子类型可挂在系统级或本仓库自定义类型下(subType.create 父类型只校验存在性);
|
||||
* - 删除子类型前校验引用(关键词/函数/规则/群/回复),有引用拒绝删除;
|
||||
* - 函数表由代码同步权威:只允许改 is_enabled / sort_order,不允许增删改 code;
|
||||
* - 取号规则为全局资源,仓库侧只读;
|
||||
* - 所有写操作完成后失效该仓库 v2 配置缓存(inbox:v2:cfg:{warehouseId})。
|
||||
*/
|
||||
class InboxV2ConfigManageService extends Service {
|
||||
/** 当前仓库ID(从登录上下文注入)。 */
|
||||
get wid() {
|
||||
return Number(this.ctx.user?.store_id || 0);
|
||||
}
|
||||
|
||||
/** 写操作后失效缓存。 */
|
||||
async _invalidate() {
|
||||
try {
|
||||
await this.ctx.service.inbox.v2.config.invalidate(this.wid);
|
||||
} catch (e) {
|
||||
this.ctx.logger.warn(`[inbox v2 manage] 失效缓存失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
_op() {
|
||||
return this.ctx.app.Sequelize.Op;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验子类型是否属于当前仓库可写范围(仓库自定义,warehouse_id=当前仓库)。
|
||||
* @param {number} subTypeId 子类型ID。
|
||||
* @param {string} [label] 错误提示中的实体名称。
|
||||
* @return {Promise<Object>} 子类型记录(raw)。
|
||||
*/
|
||||
async _assertWritableSubType(subTypeId, label = '子类型') {
|
||||
const row = await this.ctx.model.AfterSaleSubType.findOne({
|
||||
where: { id: Number(subTypeId) || 0, warehouse_id: this.wid },
|
||||
attributes: [ 'id', 'warehouse_id', 'is_system' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!row) {
|
||||
throw new Error(`${label}不存在或不是本仓库自定义(系统级只读)`);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取子类型(含系统级+仓库级,用于只读查询)。
|
||||
* @param {number} subTypeId 子类型ID。
|
||||
* @return {Promise<Object|null>} 子类型记录(raw),不存在返回 null。
|
||||
*/
|
||||
async _findSubType(subTypeId) {
|
||||
const Op = this._op();
|
||||
return this.ctx.model.AfterSaleSubType.findOne({
|
||||
where: { id: Number(subTypeId) || 0, [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] },
|
||||
attributes: [ 'id', 'warehouse_id', 'is_system', 'sub_type', 'type' ],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用分页参数。
|
||||
* @param {Object} [params] 请求参数(含 page/pageSize)。
|
||||
* @return {{page: number, pageSize: number}} 归一化分页参数。
|
||||
*/
|
||||
_page(params = {}) {
|
||||
const page = Math.max(1, Number(params.page) || 1);
|
||||
const pageSize = Math.min(200, Math.max(1, Number(params.pageSize) || 20));
|
||||
return { page, pageSize };
|
||||
}
|
||||
|
||||
// ─────────────────────────── 类型 ───────────────────────────
|
||||
|
||||
get type() {
|
||||
const svc = this;
|
||||
return {
|
||||
list: params => svc._typeList(params),
|
||||
create: params => svc._typeCreate(params),
|
||||
update: params => svc._typeUpdate(params),
|
||||
delete: params => svc._typeDelete(params),
|
||||
};
|
||||
}
|
||||
|
||||
async _typeList(params = {}) {
|
||||
const Op = this._op();
|
||||
const { page, pageSize } = this._page(params);
|
||||
const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||||
}
|
||||
const { rows, count } = await this.ctx.model.AfterSaleType.findAndCountAll({
|
||||
where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
offset: (page - 1) * pageSize, limit: pageSize, raw: true,
|
||||
});
|
||||
return { list: rows, pagination: { page, pageSize, total: count } };
|
||||
}
|
||||
|
||||
async _typeCreate(params = {}) {
|
||||
const { AfterSaleType } = this.ctx.model;
|
||||
const type = String(params.type || '').trim();
|
||||
const name = String(params.name || '').trim();
|
||||
if (!type || !name) throw new Error('type 与 name 不能为空');
|
||||
if (type.length > 20 || name.length > 50) throw new Error('type(≤20)/name(≤50) 超长');
|
||||
const exist = await AfterSaleType.findOne({
|
||||
where: { type, warehouse_id: this.wid }, raw: true,
|
||||
});
|
||||
if (exist) throw new Error(`类型编码 ${type} 已存在`);
|
||||
const row = await AfterSaleType.create({
|
||||
warehouse_id: this.wid, type, name, is_system: 0, is_enabled: 1,
|
||||
sort_order: Number(params.sortOrder) || 0,
|
||||
});
|
||||
await this._invalidate();
|
||||
return { id: row.id, message: '创建成功' };
|
||||
}
|
||||
|
||||
async _typeUpdate(params = {}) {
|
||||
const { AfterSaleType } = this.ctx.model;
|
||||
const row = await AfterSaleType.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||||
if (!row) throw new Error('类型不存在或不是本仓库自定义(系统级只读)');
|
||||
if (row.is_system === 1) throw new Error('系统预设类型不可修改');
|
||||
const patch = {};
|
||||
if (params.name !== undefined) {
|
||||
const name = String(params.name || '').trim();
|
||||
if (!name) throw new Error('name 不能为空');
|
||||
patch.name = name.slice(0, 50);
|
||||
}
|
||||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||||
await AfterSaleType.update(patch, { where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '更新成功' };
|
||||
}
|
||||
|
||||
async _typeDelete(params = {}) {
|
||||
const { AfterSaleType, AfterSaleSubType } = this.ctx.model;
|
||||
const row = await AfterSaleType.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||||
if (!row) throw new Error('类型不存在或不是本仓库自定义(系统级只读)');
|
||||
if (row.is_system === 1) throw new Error('系统预设类型不可删除');
|
||||
const subCount = await AfterSaleSubType.count({ where: { type: row.type, warehouse_id: this.wid } });
|
||||
if (subCount > 0) throw new Error(`该类型下还有 ${subCount} 个子类型,请先删除子类型`);
|
||||
await AfterSaleType.destroy({ where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '删除成功' };
|
||||
}
|
||||
|
||||
// ─────────────────────────── 子类型 ───────────────────────────
|
||||
|
||||
get subType() {
|
||||
const svc = this;
|
||||
return {
|
||||
list: params => svc._subTypeList(params),
|
||||
create: params => svc._subTypeCreate(params),
|
||||
update: params => svc._subTypeUpdate(params),
|
||||
delete: params => svc._subTypeDelete(params),
|
||||
};
|
||||
}
|
||||
|
||||
async _subTypeList(params = {}) {
|
||||
const Op = this._op();
|
||||
const { page, pageSize } = this._page(params);
|
||||
const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||||
if (params.type) where.type = String(params.type).trim();
|
||||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||||
}
|
||||
const { rows, count } = await this.ctx.model.AfterSaleSubType.findAndCountAll({
|
||||
where, order: [[ 'type', 'ASC' ], [ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
offset: (page - 1) * pageSize, limit: pageSize, raw: true,
|
||||
});
|
||||
return { list: rows, pagination: { page, pageSize, total: count } };
|
||||
}
|
||||
|
||||
async _subTypeCreate(params = {}) {
|
||||
const { AfterSaleSubType } = this.ctx.model;
|
||||
const type = String(params.type || '').trim();
|
||||
const subType = String(params.subType || '').trim();
|
||||
const name = String(params.name || '').trim();
|
||||
if (!type || !subType || !name) throw new Error('type/subType/name 不能为空');
|
||||
if (subType.length > 50 || name.length > 50) throw new Error('subType/name 超长(≤50)');
|
||||
// 自定义子类型可挂在系统级类型或本仓库自定义类型下:父类型只需存在且可见即可;
|
||||
// 子类型自身始终写 warehouse_id=当前仓库 + is_system=0,因此后续配置全部可写。
|
||||
const Op = this._op();
|
||||
const parent = await this.ctx.model.AfterSaleType.findOne({
|
||||
where: { type, [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] },
|
||||
raw: true,
|
||||
});
|
||||
if (!parent) throw new Error(`类型 ${type} 不存在`);
|
||||
const exist = await AfterSaleSubType.findOne({ where: { type, sub_type: subType, warehouse_id: this.wid }, raw: true });
|
||||
if (exist) throw new Error(`子类型 ${type}:${subType} 已存在`);
|
||||
const row = await AfterSaleSubType.create({
|
||||
warehouse_id: this.wid, type, sub_type: subType, name, is_system: 0, is_enabled: 1,
|
||||
sort_order: Number(params.sortOrder) || 0,
|
||||
});
|
||||
await this._invalidate();
|
||||
return { id: row.id, message: '创建成功' };
|
||||
}
|
||||
|
||||
async _subTypeUpdate(params = {}) {
|
||||
const row = await this._assertWritableSubType(params.id, '子类型');
|
||||
const patch = {};
|
||||
if (params.name !== undefined) {
|
||||
const name = String(params.name || '').trim();
|
||||
if (!name) throw new Error('name 不能为空');
|
||||
patch.name = name.slice(0, 50);
|
||||
}
|
||||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||||
await this.ctx.model.AfterSaleSubType.update(patch, { where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '更新成功' };
|
||||
}
|
||||
|
||||
async _subTypeDelete(params = {}) {
|
||||
const { ctx } = this;
|
||||
const row = await this._assertWritableSubType(params.id, '子类型');
|
||||
// 级联清理关联(关键词/函数关联/取号关联/群白名单/回复),避免逐个手动清理
|
||||
const t = await this.ctx.model.transaction();
|
||||
const counts = {};
|
||||
try {
|
||||
counts.keyword = await ctx.model.AfterSaleKeyword.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||||
counts.function = await ctx.model.AfterSaleSubTypeFunction.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||||
counts.rule = await ctx.model.AfterSaleSubTypeRule.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||||
counts.group = await ctx.model.AfterSaleSubTypeGroup.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||||
counts.reply = await ctx.model.AfterSaleReply.destroy({ where: { sub_type_id: row.id }, transaction: t });
|
||||
await ctx.model.AfterSaleSubType.destroy({ where: { id: row.id }, transaction: t });
|
||||
await t.commit();
|
||||
} catch (e) {
|
||||
await t.rollback();
|
||||
throw e;
|
||||
}
|
||||
await this._invalidate();
|
||||
return {
|
||||
message: `删除成功(已级联清理:关键词 ${counts.keyword}、函数关联 ${counts.function}、取号关联 ${counts.rule}、群白名单 ${counts.group}、回复 ${counts.reply})`,
|
||||
};
|
||||
}
|
||||
|
||||
// ─────────────────────────── 关键词 ───────────────────────────
|
||||
|
||||
get keyword() {
|
||||
const svc = this;
|
||||
return {
|
||||
list: params => svc._keywordList(params),
|
||||
create: params => svc._keywordCreate(params),
|
||||
update: params => svc._keywordUpdate(params),
|
||||
delete: params => svc._keywordDelete(params),
|
||||
};
|
||||
}
|
||||
|
||||
async _keywordList(params = {}) {
|
||||
const Op = this._op();
|
||||
const { page, pageSize } = this._page(params);
|
||||
const where = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||||
if (params.subTypeId) where.sub_type_id = Number(params.subTypeId) || 0;
|
||||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||||
}
|
||||
const { rows, count } = await this.ctx.model.AfterSaleKeyword.findAndCountAll({
|
||||
where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
offset: (page - 1) * pageSize, limit: pageSize, raw: true,
|
||||
});
|
||||
return { list: rows, pagination: { page, pageSize, total: count } };
|
||||
}
|
||||
|
||||
/**
|
||||
* 同词查重(可见范围:系统级 + 本仓库)。
|
||||
* @param {string} keyword 关键词。
|
||||
* @param {number} [excludeId] 排除自身ID(更新场景)。
|
||||
* @return {Promise<string|null>} 重复时的提示文案(含所在级别与子类型),无重复返回 null。
|
||||
*/
|
||||
async _keywordDupDescribe(keyword, excludeId) {
|
||||
const Op = this._op();
|
||||
const rows = await this.ctx.model.AfterSaleKeyword.findAll({
|
||||
where: {
|
||||
keyword,
|
||||
[Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }],
|
||||
},
|
||||
attributes: [ 'id', 'sub_type_id', 'warehouse_id' ],
|
||||
raw: true,
|
||||
});
|
||||
const dup = rows.find(r => Number(r.id) !== Number(excludeId || 0));
|
||||
if (!dup) return null;
|
||||
const sub = await this.ctx.model.AfterSaleSubType.findOne({
|
||||
where: { id: dup.sub_type_id },
|
||||
attributes: [ 'type', 'sub_type', 'name' ],
|
||||
raw: true,
|
||||
});
|
||||
const level = dup.warehouse_id === null ? '系统级' : '本仓库';
|
||||
const rule = sub ? `${sub.type}:${sub.sub_type}(${sub.name})` : `子类型ID ${dup.sub_type_id}`;
|
||||
return `关键词「${keyword}」已存在于【${level}】${rule}下,不可重复添加`;
|
||||
}
|
||||
|
||||
async _keywordCreate(params = {}) {
|
||||
const { AfterSaleKeyword } = this.ctx.model;
|
||||
const subTypeId = Number(params.subTypeId) || 0;
|
||||
const keyword = String(params.keyword || '').trim();
|
||||
if (!subTypeId || !keyword) throw new Error('subTypeId 与 keyword 不能为空');
|
||||
if (keyword.length > 100) throw new Error('关键词超长(≤100)');
|
||||
// 关键词为仓库级数据(warehouse_id=当前仓库):允许绑定系统级子类型或本仓库自定义子类型,
|
||||
// 只校验子类型存在,不做「仓库自定义」限制(与 keyword.update / keyword.delete 的可写范围对齐)。
|
||||
const subType = await this._findSubType(subTypeId);
|
||||
if (!subType) throw new Error('子类型不存在');
|
||||
// 同词查重(系统级+本仓库),重复时提示在哪个规则(子类型)下
|
||||
const dupMsg = await this._keywordDupDescribe(keyword);
|
||||
if (dupMsg) throw new Error(dupMsg);
|
||||
const row = await AfterSaleKeyword.create({
|
||||
warehouse_id: this.wid, sub_type_id: subTypeId, keyword, is_system: 0, is_enabled: 1,
|
||||
sort_order: Number(params.sortOrder) || 0,
|
||||
});
|
||||
await this._invalidate();
|
||||
return { id: row.id, message: '创建成功' };
|
||||
}
|
||||
|
||||
async _keywordUpdate(params = {}) {
|
||||
const { AfterSaleKeyword } = this.ctx.model;
|
||||
const row = await AfterSaleKeyword.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||||
if (!row) throw new Error('关键词不存在或不是本仓库自定义(系统级只读)');
|
||||
if (row.is_system === 1) throw new Error('系统预设关键词不可修改');
|
||||
const patch = {};
|
||||
if (params.keyword !== undefined) {
|
||||
const keyword = String(params.keyword || '').trim();
|
||||
if (!keyword) throw new Error('keyword 不能为空');
|
||||
const sliced = keyword.slice(0, 100);
|
||||
// 改词同样查重(排除自身),重复时提示在哪个规则(子类型)下
|
||||
const dupMsg = await this._keywordDupDescribe(sliced, row.id);
|
||||
if (dupMsg) throw new Error(dupMsg);
|
||||
patch.keyword = sliced;
|
||||
}
|
||||
if (params.subTypeId) {
|
||||
await this._assertWritableSubType(params.subTypeId, '子类型');
|
||||
patch.sub_type_id = Number(params.subTypeId);
|
||||
}
|
||||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') patch.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||||
await AfterSaleKeyword.update(patch, { where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '更新成功' };
|
||||
}
|
||||
|
||||
async _keywordDelete(params = {}) {
|
||||
const { AfterSaleKeyword } = this.ctx.model;
|
||||
const row = await AfterSaleKeyword.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||||
if (!row) throw new Error('关键词不存在或不是本仓库自定义(系统级只读)');
|
||||
if (row.is_system === 1) throw new Error('系统预设关键词不可删除');
|
||||
await AfterSaleKeyword.destroy({ where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '删除成功' };
|
||||
}
|
||||
|
||||
// ─────────────────────────── 取号规则(全局只读) ───────────────────────────
|
||||
|
||||
get numberRule() {
|
||||
const svc = this;
|
||||
return { list: params => svc._numberRuleList(params) };
|
||||
}
|
||||
|
||||
async _numberRuleList() {
|
||||
const rows = await this.ctx.model.InboxNumberRule.findAll({
|
||||
order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||||
});
|
||||
return { list: rows };
|
||||
}
|
||||
|
||||
// ─────────────────────────── 处理函数(代码同步权威,只允许开关/排序) ───────────────────────────
|
||||
|
||||
get function() {
|
||||
const svc = this;
|
||||
return {
|
||||
list: params => svc._functionList(params),
|
||||
update: params => svc._functionUpdate(params),
|
||||
};
|
||||
}
|
||||
|
||||
async _functionList(params = {}) {
|
||||
const Op = this._op();
|
||||
const where = {};
|
||||
if (params.isEnabled !== undefined && params.isEnabled !== null && params.isEnabled !== '') {
|
||||
where.is_enabled = Number(params.isEnabled) === 1 ? 1 : 0;
|
||||
}
|
||||
if (params.keyword) {
|
||||
const like = `%${String(params.keyword).trim()}%`;
|
||||
where[Op.or] = [{ function_code: { [Op.like]: like } }, { name: { [Op.like]: like } }];
|
||||
}
|
||||
const rows = await this.ctx.model.AfterSaleFunction.findAll({
|
||||
where, order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||||
});
|
||||
// 附上代码注册表中是否存在(便于识别已下线函数)
|
||||
let registry = null;
|
||||
try {
|
||||
registry = this.ctx.service.inbox.functions.registry;
|
||||
} catch (e) { /* ignore */ }
|
||||
return {
|
||||
list: rows.map(r => ({
|
||||
...r,
|
||||
in_registry: registry instanceof Map ? registry.has(r.function_code) : null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async _functionUpdate(params = {}) {
|
||||
const { AfterSaleFunction } = this.ctx.model;
|
||||
const row = await AfterSaleFunction.findOne({ where: { id: Number(params.id) || 0 }, raw: true });
|
||||
if (!row) throw new Error('函数不存在');
|
||||
const patch = {};
|
||||
// 启用状态硬编码(代码注册表存在即启用),接口只允许调整排序
|
||||
if (params.sortOrder !== undefined) patch.sort_order = Number(params.sortOrder) || 0;
|
||||
if (Object.keys(patch).length === 0) throw new Error('只允许更新 sortOrder(是否启用由代码硬编码,不做接口配置)');
|
||||
await AfterSaleFunction.update(patch, { where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '更新成功' };
|
||||
}
|
||||
|
||||
// ─────────────────────────── 回复 ───────────────────────────
|
||||
|
||||
get reply() {
|
||||
const svc = this;
|
||||
return {
|
||||
create: params => svc._replyCreate(params),
|
||||
update: params => svc._replyUpdate(params),
|
||||
delete: params => svc._replyDelete(params),
|
||||
// 推荐接口:保存(upsert)/ 还原(删除仓库级,回退系统级)
|
||||
save: params => svc._replySave(params),
|
||||
restore: params => svc._replyRestore(params),
|
||||
merged: params => svc._replyMerged(params),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存仓库级回复配置(upsert):按传入字段保存,未传字段保持原值;
|
||||
* 无仓库级配置时按传入字段创建(默认 reply 空、is_reply=1、create_work_order=1)。
|
||||
* 停用即回退系统级语义由 restore 承担,不再提供 isEnabled 开关。
|
||||
* @param {Object} params 请求参数。
|
||||
* @return {Promise<Object>} 保存结果。
|
||||
*/
|
||||
async _replySave(params = {}) {
|
||||
const { AfterSaleReply } = this.ctx.model;
|
||||
const subTypeId = Number(params.subTypeId) || 0;
|
||||
if (!subTypeId) throw new Error('subTypeId 不能为空');
|
||||
const subType = await this._findSubType(subTypeId);
|
||||
if (!subType) throw new Error('子类型不存在');
|
||||
|
||||
const patch = {};
|
||||
if (params.reply !== undefined && params.reply !== null) patch.reply = String(params.reply).slice(0, 2000);
|
||||
if (params.isReply !== undefined && params.isReply !== null && params.isReply !== '') patch.is_reply = Number(params.isReply) === 0 ? 0 : 1;
|
||||
if (params.createWorkOrder !== undefined && params.createWorkOrder !== null && params.createWorkOrder !== '') patch.create_work_order = Number(params.createWorkOrder) === 0 ? 0 : 1;
|
||||
if (params.noNumberHint !== undefined && params.noNumberHint !== null) patch.no_number_hint = params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null;
|
||||
|
||||
const exist = await AfterSaleReply.findOne({
|
||||
where: { warehouse_id: this.wid, sub_type_id: subTypeId },
|
||||
raw: true,
|
||||
});
|
||||
if (exist) {
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await AfterSaleReply.update(patch, { where: { id: exist.id } });
|
||||
}
|
||||
} else {
|
||||
await AfterSaleReply.create({
|
||||
warehouse_id: this.wid,
|
||||
sub_type_id: subTypeId,
|
||||
reply: patch.reply !== undefined ? patch.reply : '',
|
||||
is_reply: patch.is_reply !== undefined ? patch.is_reply : 1,
|
||||
create_work_order: patch.create_work_order !== undefined ? patch.create_work_order : 1,
|
||||
no_number_hint: patch.no_number_hint !== undefined ? patch.no_number_hint : null,
|
||||
is_enabled: 1,
|
||||
});
|
||||
}
|
||||
await this._invalidate();
|
||||
return {
|
||||
id: exist ? exist.id : null,
|
||||
message: exist ? '保存成功' : '创建成功',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 还原仓库级回复配置:删除仓库级行,回退到系统级配置。
|
||||
* @param {Object} params 请求参数。
|
||||
* @return {Promise<Object>} 还原结果。
|
||||
*/
|
||||
async _replyRestore(params = {}) {
|
||||
const { AfterSaleReply } = this.ctx.model;
|
||||
const subTypeId = Number(params.subTypeId) || 0;
|
||||
if (!subTypeId) throw new Error('subTypeId 不能为空');
|
||||
const row = await AfterSaleReply.findOne({
|
||||
where: { warehouse_id: this.wid, sub_type_id: subTypeId },
|
||||
raw: true,
|
||||
});
|
||||
if (row) {
|
||||
await AfterSaleReply.destroy({ where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '已还原为系统级配置' };
|
||||
}
|
||||
return { message: '本仓库无自定义回复配置,已是系统级配置' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 回复配置(合并后生效配置):以全部有效子类型(系统级+本仓库)为基底,
|
||||
* 每个子类型只返回一条「生效配置」:本仓库有自定义则整行覆盖系统级;
|
||||
* 无任何回复配置行的子类型返回初始值(reply={back_text}、is_reply=1、create_work_order=1、
|
||||
* no_number_hint 按取号规则:express_name→快递提示、有其他规则→运单号提示、无规则→空),
|
||||
* 保证任何仓库都有完整列表。无启用状态字段:停用即回退系统级由 restore 承担。
|
||||
* @param {Object} params 请求参数。
|
||||
* @return {Promise<Object>} { merged, total } 合并后生效配置数组与总数。
|
||||
*/
|
||||
async _replyMerged(params = {}) {
|
||||
const Op = this._op();
|
||||
const wh = { [Op.or]: [{ warehouse_id: null }, { warehouse_id: this.wid }] };
|
||||
// 拉全量(系统级+本仓库级)在内存合并,数据量小
|
||||
const [ rows, subs, ruleRelRows, ruleRows ] = await Promise.all([
|
||||
this.ctx.model.AfterSaleReply.findAll({
|
||||
where: wh,
|
||||
order: [[ 'sub_type_id', 'ASC' ], [ 'warehouse_id', 'ASC' ]],
|
||||
raw: true,
|
||||
}),
|
||||
this.ctx.model.AfterSaleSubType.findAll({
|
||||
where: wh,
|
||||
attributes: [ 'id', 'type', 'sub_type', 'name', 'warehouse_id' ],
|
||||
raw: true,
|
||||
}),
|
||||
this.ctx.model.AfterSaleSubTypeRule.findAll({
|
||||
attributes: [ 'sub_type_id', 'number_rule_id' ],
|
||||
raw: true,
|
||||
}),
|
||||
this.ctx.model.InboxNumberRule.findAll({
|
||||
attributes: [ 'id', 'target' ],
|
||||
raw: true,
|
||||
}),
|
||||
]);
|
||||
const ruleTargets = {};
|
||||
for (const n of ruleRows) ruleTargets[n.id] = n.target;
|
||||
const subTargets = {};
|
||||
for (const rel of ruleRelRows) {
|
||||
const t = ruleTargets[rel.number_rule_id];
|
||||
if (!t) continue;
|
||||
if (!subTargets[rel.sub_type_id]) subTargets[rel.sub_type_id] = [];
|
||||
if (!subTargets[rel.sub_type_id].includes(t)) subTargets[rel.sub_type_id].push(t);
|
||||
}
|
||||
const initialHint = st => {
|
||||
const ts = subTargets[st.id] || [];
|
||||
if (ts.includes('express_name')) {
|
||||
return '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)';
|
||||
}
|
||||
return ts.length > 0 ? '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)' : '';
|
||||
};
|
||||
const mergedMap = new Map();
|
||||
for (const r of rows) {
|
||||
const isWh = r.warehouse_id !== null && r.warehouse_id !== undefined;
|
||||
const existing = mergedMap.get(r.sub_type_id);
|
||||
if (!existing || (isWh && !existing._wh)) {
|
||||
mergedMap.set(r.sub_type_id, { ...r, _wh: isWh });
|
||||
}
|
||||
}
|
||||
const subMap = {};
|
||||
for (const s of subs) subMap[s.id] = s;
|
||||
const toRow = (st, r) => ({
|
||||
id: r ? r.id : null,
|
||||
sub_type_id: st.id,
|
||||
type: String(st.type || ''),
|
||||
sub_type: String(st.sub_type || ''),
|
||||
sub_type_name: String(st.name || ''),
|
||||
warehouse_id: r ? (r._wh ? r.warehouse_id : null) : (st.warehouse_id === null || st.warehouse_id === undefined ? null : this.wid),
|
||||
is_custom: r ? (r._wh ? 1 : 0) : (st.warehouse_id === null || st.warehouse_id === undefined ? 0 : 1),
|
||||
reply: r ? String(r.reply || '') : '{back_text}',
|
||||
is_reply: r ? (Number(r.is_reply) === 1 ? 1 : 0) : 1,
|
||||
create_work_order: r ? (Number(r.create_work_order) === 0 ? 0 : 1) : 1,
|
||||
no_number_hint: r ? (r.no_number_hint ? String(r.no_number_hint) : '') : initialHint(st),
|
||||
created_at: r ? r.created_at : null,
|
||||
updated_at: r ? r.updated_at : null,
|
||||
});
|
||||
let list = subs.map(st => {
|
||||
const r = mergedMap.get(st.id);
|
||||
return toRow(st, r);
|
||||
});
|
||||
if (params.subTypeId) {
|
||||
const sid = Number(params.subTypeId) || 0;
|
||||
list = list.filter(x => x.sub_type_id === sid);
|
||||
}
|
||||
const total = list.length;
|
||||
return { merged: list, total };
|
||||
}
|
||||
|
||||
async _replyCreate(params = {}) {
|
||||
const { AfterSaleReply } = this.ctx.model;
|
||||
const subTypeId = Number(params.subTypeId) || 0;
|
||||
const reply = String(params.reply || '');
|
||||
if (!subTypeId) throw new Error('subTypeId 不能为空');
|
||||
if (!reply) throw new Error('reply 不能为空');
|
||||
// 允许系统级子类型:仓库级回复的语义就是覆盖系统级配置(读取时仓库级优先)
|
||||
const subType = await this._findSubType(subTypeId);
|
||||
if (!subType) throw new Error('子类型不存在');
|
||||
const exist = await AfterSaleReply.findOne({ where: { warehouse_id: this.wid, sub_type_id: subTypeId }, raw: true });
|
||||
if (exist) throw new Error('该子类型已有仓库级回复,请用更新');
|
||||
const row = await AfterSaleReply.create({
|
||||
warehouse_id: this.wid, sub_type_id: subTypeId, reply,
|
||||
is_reply: Number(params.isReply) === 0 ? 0 : 1,
|
||||
create_work_order: Number(params.createWorkOrder) === 0 ? 0 : 1,
|
||||
no_number_hint: params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null,
|
||||
is_enabled: 1,
|
||||
});
|
||||
await this._invalidate();
|
||||
return { id: row.id, message: '创建成功' };
|
||||
}
|
||||
|
||||
async _replyUpdate(params = {}) {
|
||||
const { AfterSaleReply } = this.ctx.model;
|
||||
const row = await AfterSaleReply.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||||
if (!row) throw new Error('回复配置不存在或不是本仓库的(系统级回复只读)');
|
||||
const patch = {};
|
||||
if (params.reply !== undefined) {
|
||||
const reply = String(params.reply || '');
|
||||
if (!reply) throw new Error('reply 不能为空');
|
||||
patch.reply = reply;
|
||||
}
|
||||
if (params.isReply !== undefined && params.isReply !== null && params.isReply !== '') patch.is_reply = Number(params.isReply) === 1 ? 1 : 0;
|
||||
if (params.createWorkOrder !== undefined && params.createWorkOrder !== null && params.createWorkOrder !== '') patch.create_work_order = Number(params.createWorkOrder) === 1 ? 1 : 0;
|
||||
if (params.noNumberHint !== undefined) {
|
||||
patch.no_number_hint = params.noNumberHint ? String(params.noNumberHint).slice(0, 500) : null;
|
||||
}
|
||||
if (Object.keys(patch).length === 0) throw new Error('无可更新字段');
|
||||
await AfterSaleReply.update(patch, { where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '更新成功' };
|
||||
}
|
||||
|
||||
async _replyDelete(params = {}) {
|
||||
const { AfterSaleReply } = this.ctx.model;
|
||||
const row = await AfterSaleReply.findOne({ where: { id: Number(params.id) || 0, warehouse_id: this.wid }, raw: true });
|
||||
if (!row) throw new Error('回复配置不存在或不是本仓库的(系统级回复只读)');
|
||||
await AfterSaleReply.destroy({ where: { id: row.id } });
|
||||
await this._invalidate();
|
||||
return { message: '删除成功' };
|
||||
}
|
||||
|
||||
// ─────────────────────────── 关联关系(set=全量替换,仅本仓库自定义子类型可写) ───────────────────────────
|
||||
|
||||
get relation() {
|
||||
const svc = this;
|
||||
return {
|
||||
function: {
|
||||
list: params => svc._relFunctionList(params),
|
||||
set: params => svc._relFunctionSet(params),
|
||||
},
|
||||
rule: {
|
||||
list: params => svc._relRuleList(params),
|
||||
set: params => svc._relRuleSet(params),
|
||||
},
|
||||
group: {
|
||||
list: params => svc._relGroupList(params),
|
||||
set: params => svc._relGroupSet(params),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async _relFunctionList(params = {}) {
|
||||
const subType = await this._findSubType(params.subTypeId);
|
||||
if (!subType) throw new Error('子类型不存在');
|
||||
const rows = await this.ctx.model.AfterSaleSubTypeFunction.findAll({
|
||||
where: { sub_type_id: subType.id },
|
||||
order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||||
});
|
||||
return { list: rows };
|
||||
}
|
||||
|
||||
async _relFunctionSet(params = {}) {
|
||||
const subType = await this._assertWritableSubType(params.subTypeId, '子类型');
|
||||
const items = Array.isArray(params.items) ? params.items : [];
|
||||
const funcRows = await this.ctx.model.AfterSaleFunction.findAll({ attributes: [ 'id' ], raw: true });
|
||||
const validIds = new Set(funcRows.map(r => r.id));
|
||||
const t = await this.ctx.model.transaction();
|
||||
try {
|
||||
await this.ctx.model.AfterSaleSubTypeFunction.destroy({ where: { sub_type_id: subType.id }, transaction: t });
|
||||
let order = 0;
|
||||
for (const item of items) {
|
||||
const fid = Number(item.functionId) || 0;
|
||||
if (!validIds.has(fid)) continue;
|
||||
await this.ctx.model.AfterSaleSubTypeFunction.create({
|
||||
sub_type_id: subType.id, function_id: fid,
|
||||
sort_order: Number(item.sortOrder) || order,
|
||||
}, { transaction: t });
|
||||
order += 1;
|
||||
}
|
||||
await t.commit();
|
||||
} catch (e) {
|
||||
await t.rollback();
|
||||
throw e;
|
||||
}
|
||||
await this._invalidate();
|
||||
return { message: '关联已更新' };
|
||||
}
|
||||
|
||||
async _relRuleList(params = {}) {
|
||||
const subType = await this._findSubType(params.subTypeId);
|
||||
if (!subType) throw new Error('子类型不存在');
|
||||
const rows = await this.ctx.model.AfterSaleSubTypeRule.findAll({
|
||||
where: { sub_type_id: subType.id },
|
||||
order: [[ 'sort_order', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||||
});
|
||||
return { list: rows };
|
||||
}
|
||||
|
||||
async _relRuleSet(params = {}) {
|
||||
const subType = await this._assertWritableSubType(params.subTypeId, '子类型');
|
||||
const items = Array.isArray(params.items) ? params.items : [];
|
||||
const ruleRows = await this.ctx.model.InboxNumberRule.findAll({ attributes: [ 'id' ], raw: true });
|
||||
const validIds = new Set(ruleRows.map(r => r.id));
|
||||
const t = await this.ctx.model.transaction();
|
||||
try {
|
||||
await this.ctx.model.AfterSaleSubTypeRule.destroy({ where: { sub_type_id: subType.id }, transaction: t });
|
||||
let order = 0;
|
||||
for (const item of items) {
|
||||
const rid = Number(item.ruleId) || 0;
|
||||
if (!validIds.has(rid)) continue;
|
||||
await this.ctx.model.AfterSaleSubTypeRule.create({
|
||||
sub_type_id: subType.id, number_rule_id: rid,
|
||||
sort_order: Number(item.sortOrder) || order,
|
||||
}, { transaction: t });
|
||||
order += 1;
|
||||
}
|
||||
await t.commit();
|
||||
} catch (e) {
|
||||
await t.rollback();
|
||||
throw e;
|
||||
}
|
||||
await this._invalidate();
|
||||
return { message: '关联已更新' };
|
||||
}
|
||||
|
||||
async _relGroupList(params = {}) {
|
||||
const subType = await this._findSubType(params.subTypeId);
|
||||
if (!subType) throw new Error('子类型不存在');
|
||||
const rows = await this.ctx.model.AfterSaleSubTypeGroup.findAll({
|
||||
where: { sub_type_id: subType.id },
|
||||
order: [[ 'group_type', 'ASC' ], [ 'sub_group', 'ASC' ], [ 'id', 'ASC' ]], raw: true,
|
||||
});
|
||||
return { list: rows };
|
||||
}
|
||||
|
||||
async _relGroupSet(params = {}) {
|
||||
const subType = await this._assertWritableSubType(params.subTypeId, '子类型');
|
||||
const items = Array.isArray(params.items) ? params.items : [];
|
||||
const { AfterSaleSubTypeGroup } = this.ctx.model;
|
||||
const validTypes = [ 'store', 'warehouse', 'express', '*' ];
|
||||
const t = await this.ctx.model.transaction();
|
||||
try {
|
||||
// 系统预设行(is_system=1)不可删:保留并合并
|
||||
const sysRows = await AfterSaleSubTypeGroup.findAll({
|
||||
where: { sub_type_id: subType.id, is_system: 1 }, raw: true, transaction: t,
|
||||
});
|
||||
await AfterSaleSubTypeGroup.destroy({ where: { sub_type_id: subType.id, is_system: 0 }, transaction: t });
|
||||
const seen = new Set();
|
||||
for (const row of sysRows) {
|
||||
seen.add(`${row.group_type}:${row.sub_group}`);
|
||||
}
|
||||
// 通配覆盖:groupType='*' 覆盖所有具体类型行;主类型内 subGroup='*' 覆盖该主类型其他具体行
|
||||
const norm = items
|
||||
.map(it => ({
|
||||
gt: String(it.groupType || '').trim(),
|
||||
sg: String(it.subGroup || '').trim(),
|
||||
so: Number(it.sortOrder) || 0,
|
||||
}))
|
||||
.filter(x => validTypes.includes(x.gt));
|
||||
const hasWildcardAll = norm.some(x => x.gt === '*');
|
||||
const wildcardTypes = new Set(norm.filter(x => x.gt !== '*' && x.sg === '*').map(x => x.gt));
|
||||
for (const { gt, sg: rawSg, so } of norm) {
|
||||
let sg = rawSg;
|
||||
if (gt === '*') sg = ''; // 全通配时子类型无意义,归一化为空
|
||||
if (hasWildcardAll && gt !== '*') continue; // 有全部时覆盖掉对应类型
|
||||
if (gt !== '*' && wildcardTypes.has(gt) && sg !== '*') continue; // 主类型内通配覆盖具体行
|
||||
const key = `${gt}:${sg}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
await AfterSaleSubTypeGroup.create({
|
||||
sub_type_id: subType.id, group_type: gt, sub_group: sg,
|
||||
is_system: 0, sort_order: so,
|
||||
}, { transaction: t });
|
||||
}
|
||||
await t.commit();
|
||||
} catch (e) {
|
||||
await t.rollback();
|
||||
throw e;
|
||||
}
|
||||
await this._invalidate();
|
||||
return { message: '关联已更新' };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InboxV2ConfigManageService;
|
||||
@ -861,30 +861,37 @@ class ReturnUnpackService extends Service {
|
||||
const queryWhere = this._buildListWhere(where, Op);
|
||||
const order = this._buildListOrder(sort, 'return_unpack');
|
||||
|
||||
const { count, rows } = await ctx.model.ReturnUnpack.findAndCountAll({
|
||||
where: queryWhere,
|
||||
order,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
raw: false,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ReturnUnpackVideo,
|
||||
as: 'videos',
|
||||
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
|
||||
where: { deleted_at: null },
|
||||
required: false,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Camera,
|
||||
as: 'camera',
|
||||
attributes: [ 'id', 'custom_name', 'channel_name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
// 性能与准确性:count 与 rows 分离。findAndCountAll 携带 hasMany include(videos)时,
|
||||
// Sequelize 生成的是 COUNT(ReturnUnpack.id) + LEFT JOIN 视频表,等于「主表行 × 命中视频条数」,
|
||||
// 会把 total 放大(生产实测 8483 条拆包单被统计成 16961,与 export 口径对不上),
|
||||
// 拆开后 count 走单表条件(与 exportUnpack 的 total_count 完全一致),性能也更好。
|
||||
const count = await ctx.model.ReturnUnpack.count({ where: queryWhere });
|
||||
const rows = count === 0
|
||||
? []
|
||||
: await ctx.model.ReturnUnpack.findAll({
|
||||
where: queryWhere,
|
||||
order,
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: pageSize,
|
||||
raw: false,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.ReturnUnpackVideo,
|
||||
as: 'videos',
|
||||
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
|
||||
where: { deleted_at: null },
|
||||
required: false,
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Camera,
|
||||
as: 'camera',
|
||||
attributes: [ 'id', 'custom_name', 'channel_name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const list = [];
|
||||
for (const row of rows) {
|
||||
@ -1644,6 +1651,23 @@ class ReturnUnpackService extends Service {
|
||||
video.video_url = this._buildVideoUrl(warehouseId, recordingComputerId, video.video_url);
|
||||
}
|
||||
|
||||
// 附加摄像头名称(系统设置的自定义名称优先,通道原始名称兜底)
|
||||
const videoCameraIds = [ ...new Set(videos.map(v => v.camera_id).filter(id => id)) ];
|
||||
const cameraNameMap = new Map();
|
||||
if (videoCameraIds.length > 0) {
|
||||
const cameras = await ctx.model.Camera.findAll({
|
||||
attributes: [ 'id', 'custom_name', 'channel_name' ],
|
||||
where: { id: { [Op.in]: videoCameraIds } },
|
||||
raw: true,
|
||||
});
|
||||
for (const camera of cameras) {
|
||||
cameraNameMap.set(Number(camera.id), String(camera.custom_name || camera.channel_name || '').trim());
|
||||
}
|
||||
}
|
||||
for (const video of videos) {
|
||||
video.camera_name = video.camera_id ? (cameraNameMap.get(Number(video.camera_id)) || '') : '';
|
||||
}
|
||||
|
||||
let received = null;
|
||||
if (unpack.return_received_id) {
|
||||
received = await ctx.model.ReturnReceived.findOne({
|
||||
@ -1934,6 +1958,7 @@ class ReturnUnpackService extends Service {
|
||||
try {
|
||||
order = await ctx.model.OrderDelivery.findOne({
|
||||
where: { id: order_id },
|
||||
attributes: [ 'id', 'source_order_codes', 'source_platform_code', 'logistics_name' ],
|
||||
raw: true,
|
||||
});
|
||||
} catch (err) {
|
||||
@ -2875,7 +2900,13 @@ class ReturnUnpackService extends Service {
|
||||
const allowed = scene === 'return_unpack_detail' ? detailFields : mainFields;
|
||||
const safeSortField = allowed.has(sortField) ? sortField : 'created_at';
|
||||
|
||||
return [[ safeSortField, sortOrder ]];
|
||||
// 追加主键作为次级排序:排序键可能并列(如 created_at 精确到秒,生产存在同秒多条),
|
||||
// 并列时 MySQL 返回顺序不稳定,list 翻页与 export 的 offset 分页会出现重复/漏行。
|
||||
const order = [[ safeSortField, sortOrder ]];
|
||||
if (safeSortField !== 'id') {
|
||||
order.push([ 'id', sortOrder ]);
|
||||
}
|
||||
return order;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -2832,9 +2832,15 @@ class stockStoreService extends Service {
|
||||
deleted_at: null,
|
||||
is_valid: 'Y',
|
||||
};
|
||||
const StockStoreWhere = {};
|
||||
// 过滤条件必须落在主表(wms_stock_store),include 为 LEFT JOIN 时
|
||||
// 条件只会进 ON 子句,无法过滤主表,会导致跨货主/跨仓库数据泄漏。
|
||||
const StockStoreWhere = {
|
||||
warehouse_id: warehouseId,
|
||||
delete_at: null,
|
||||
is_valid: 'Y',
|
||||
};
|
||||
if (store_id) {
|
||||
StockWarehouseWhere.store_id = store_id;
|
||||
StockStoreWhere.store_id = store_id;
|
||||
}
|
||||
if (item_code) {
|
||||
const processedValue = item_code.split(',');
|
||||
@ -2858,19 +2864,13 @@ class stockStoreService extends Service {
|
||||
[ total, barcodes ] = await Promise.all([
|
||||
ctx.model.StockStore.count({
|
||||
where: StockStoreWhere,
|
||||
attributes: [
|
||||
'item_code', 'item_name', 'app_key', 'create_from', 'id', 'stock_id',
|
||||
],
|
||||
include: [{
|
||||
model: ctx.model.StockWarehouse,
|
||||
as: 'warehouse_stock',
|
||||
attributes: [ 'id' ],
|
||||
attributes: [ 'id', 'store_id' ],
|
||||
where: StockWarehouseWhere,
|
||||
required: false,
|
||||
}],
|
||||
limit: parseInt(pageSize),
|
||||
offset: parseInt(offset),
|
||||
raw: true,
|
||||
}),
|
||||
ctx.model.StockStore.findAll({
|
||||
where: StockStoreWhere,
|
||||
@ -2880,7 +2880,7 @@ class stockStoreService extends Service {
|
||||
include: [{
|
||||
model: ctx.model.StockWarehouse,
|
||||
as: 'warehouse_stock',
|
||||
attributes: [ 'id' ],
|
||||
attributes: [ 'id', 'store_id' ],
|
||||
where: StockWarehouseWhere,
|
||||
required: false,
|
||||
}],
|
||||
@ -2916,7 +2916,7 @@ class stockStoreService extends Service {
|
||||
item_name: item.item_name,
|
||||
};
|
||||
});
|
||||
const get_store_id = warehouseStock ? warehouseStock.store_id : barcodes[0]['warehouse_stock.store_id'];
|
||||
const get_store_id = warehouseStock ? warehouseStock.store_id : (barcodes[0] ? barcodes[0]['warehouse_stock.store_id'] : null);
|
||||
return {
|
||||
rows: results,
|
||||
store_id: get_store_id,
|
||||
|
||||
@ -13,6 +13,10 @@ const WAVE_ORDER_COUNT_CACHE_TTL_SECONDS = 15;
|
||||
const WAVE_ITEMS_TOTAL_CACHE_KEY_PREFIX = 'cache:workbench:wave_items_total';
|
||||
/** @type {number} 工作台波次商品总件数缓存 TTL(秒),TTL 内分表 SUM 只执行一次 */
|
||||
const WAVE_ITEMS_TOTAL_CACHE_TTL_SECONDS = 15;
|
||||
/** @type {string} 工作台波次商品 SKU 聚合缓存 key 前缀(最终 key:{前缀}:{warehouseId}:{waveId}) */
|
||||
const WAVE_ITEMS_SUMMARY_CACHE_KEY_PREFIX = 'cache:workbench:wave_items_summary';
|
||||
/** @type {number} 工作台波次商品 SKU 聚合缓存 TTL(秒),TTL 内分表聚合只执行一次 */
|
||||
const WAVE_ITEMS_SUMMARY_CACHE_TTL_SECONDS = 15;
|
||||
|
||||
/** @type {string} 工作台绑定会话缓存 key 前缀(client_code 维度,最终 key:{前缀}{clientCode}) */
|
||||
const WORKBENCH_BIND_CLIENT_CACHE_PREFIX = 'workbench:bind:client:';
|
||||
@ -597,7 +601,10 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新订单打包状态字段(散单按订单ID更新单笔,团购按波次批量更新)。
|
||||
* 更新订单打包状态字段(散单按订单ID更新单笔,团购按波次批量更新),
|
||||
* 并同步补确认打印状态:扫描打包代表面单已真实存在,确认打印状态未写入
|
||||
* (confirm_print_status 为 none/null)时补为 fin(团购按波次补、散单按单补),
|
||||
* 补后递增统计版本号驱动 confirmPrintUnclaimedWaveCount 长轮询。
|
||||
* 遍历 current + dispatch 分表,异常仅记录日志不影响主流程。
|
||||
* 团购批量更新时跳过拦截订单(intercept_status 空值按 none 处理)。
|
||||
*
|
||||
@ -615,6 +622,12 @@ class WorkbenchService extends Service {
|
||||
// 任务状态 <2(0待处理/1打包中)或未传一律视为打包中;>=2 视为已完成
|
||||
const orderPackStatus = (Number.isNaN(statusNum) || statusNum < 2) ? 'padding' : 'fin';
|
||||
const orderUpdateData = { pack_status: orderPackStatus };
|
||||
// 扫描打包即代表面单已真实存在:确认打印状态未写入时补上(团购按波次补、散单按单补)
|
||||
const confirmUpdateData = { confirm_print_status: 'fin' };
|
||||
const confirmBackfillWhere = {
|
||||
confirm_print_status: { [ctx.app.Sequelize.Op.in]: [ 'none', null ] },
|
||||
};
|
||||
let confirmBackfilled = false;
|
||||
|
||||
const orderDeliveryFactory = ctx.model.OrderDeliveryFactory;
|
||||
const tableOrders = [
|
||||
@ -639,6 +652,21 @@ class WorkbenchService extends Service {
|
||||
ctx.logger.info('[%s._updateOrderPackStatus] 团购批量更新订单打包状态 waveId=%d pack_status=%s table=%s affected=%d',
|
||||
caller, waveId, orderPackStatus, entry.label, affected[0]);
|
||||
}
|
||||
|
||||
// 波次补确认打印状态(仅未写入的订单)
|
||||
const confirmAffected = await model.update(confirmUpdateData, {
|
||||
where: {
|
||||
wave_id: waveId,
|
||||
warehouse_id: warehouseId,
|
||||
intercept_status: { [ctx.app.Sequelize.Op.in]: [ 'none', null ] },
|
||||
...confirmBackfillWhere,
|
||||
},
|
||||
});
|
||||
if (confirmAffected[0] > 0) {
|
||||
confirmBackfilled = true;
|
||||
ctx.logger.info('[%s._updateOrderPackStatus] 团购波次补确认打印状态 waveId=%d table=%s affected=%d',
|
||||
caller, waveId, entry.label, confirmAffected[0]);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[%s._updateOrderPackStatus] 更新分表 %s 失败: %s', caller, entry.label, err.message);
|
||||
}
|
||||
@ -655,6 +683,25 @@ class WorkbenchService extends Service {
|
||||
if (affected[0] > 0) {
|
||||
ctx.logger.info('[%s._updateOrderPackStatus] 更新订单打包状态 orderId=%d pack_status=%s table=%s',
|
||||
caller, orderId, orderPackStatus, entry.label);
|
||||
|
||||
// 按单补确认打印状态(仅未写入时)
|
||||
try {
|
||||
const confirmAffected = await model.update(confirmUpdateData, {
|
||||
where: {
|
||||
id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
...confirmBackfillWhere,
|
||||
},
|
||||
});
|
||||
if (confirmAffected[0] > 0) {
|
||||
confirmBackfilled = true;
|
||||
ctx.logger.info('[%s._updateOrderPackStatus] 散单补确认打印状态 orderId=%d table=%s',
|
||||
caller, orderId, entry.label);
|
||||
}
|
||||
} catch (confirmErr) {
|
||||
ctx.logger.warn('[%s._updateOrderPackStatus] 补确认打印状态失败 orderId=%d table=%s: %s',
|
||||
caller, orderId, entry.label, confirmErr.message);
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
@ -663,6 +710,21 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 补了确认打印后递增统计版本号,驱动 confirmPrintUnclaimedWaveCount 长轮询
|
||||
if (confirmBackfilled) {
|
||||
try {
|
||||
const waveService = ctx.service
|
||||
&& ctx.service.systemMethods
|
||||
&& ctx.service.systemMethods.order
|
||||
&& ctx.service.systemMethods.order.wave;
|
||||
if (waveService && typeof waveService.bumpConfirmPrintUnclaimedWaveVersion === 'function') {
|
||||
await waveService.bumpConfirmPrintUnclaimedWaveVersion(warehouseId);
|
||||
}
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[%s._updateOrderPackStatus] 统计版本号递增失败: %s', caller, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return orderPackStatus;
|
||||
}
|
||||
|
||||
@ -861,6 +923,55 @@ class WorkbenchService extends Service {
|
||||
const parsedPackStatus = Number.parseInt(packStatus, 10);
|
||||
const normalizedPackStatus = Number.isFinite(parsedPackStatus) ? parsedPackStatus : 1;
|
||||
|
||||
// 服务端复查落库口径:打包数量/商品总件数/商品种类数均以服务端为准,
|
||||
// 散单取订单分表(orderRow),团购取波次实时统计(totalOrders + 波次商品 SKU 聚合),
|
||||
// 设备端上报值仅作交叉校验日志,不直接落库,防止前端输入失真。
|
||||
let packQuantity = 1;
|
||||
let packItemQuantity = Number(orderRow.items_total) || 0;
|
||||
let packSkuCount = Number(orderRow.items_count) || 0;
|
||||
|
||||
if (isSandan === 0) {
|
||||
// 团购:打包数量 = 波次实时订单数(步骤2 已统计,异常兜底 1)
|
||||
packQuantity = Number.isFinite(totalOrders) && totalOrders > 0 ? totalOrders : 1;
|
||||
// 团购:商品总件数/商品种类数 = 波次商品 SKU 聚合(15s 短缓存兜底,异常降级为扫描订单值)
|
||||
let waveItemsSummary = [];
|
||||
try {
|
||||
waveItemsSummary = await this._fetchWaveItemsSummary(warehouseId, waveId);
|
||||
} catch (summaryErr) {
|
||||
ctx.logger.warn('[Workbench._packOrder] 波次商品聚合失败,商品件数降级为扫描订单值: %s', summaryErr.message);
|
||||
}
|
||||
if (Array.isArray(waveItemsSummary) && waveItemsSummary.length > 0) {
|
||||
packSkuCount = waveItemsSummary.length;
|
||||
const waveItemsTotal = waveItemsSummary.reduce((sum, item) => sum + (Number(item.plan_qty) || 0), 0);
|
||||
if (waveItemsTotal > 0) {
|
||||
packItemQuantity = waveItemsTotal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 交叉校验:设备端上报值与服务端复查不一致时仅记日志,落库以服务端为准
|
||||
const deviceWaveTotal = (waveTotalOrders !== undefined && waveTotalOrders !== null && waveTotalOrders !== '')
|
||||
? parseInt(waveTotalOrders)
|
||||
: 0;
|
||||
const deviceItemsTotal = (itemsTotal !== undefined && itemsTotal !== null && itemsTotal !== '')
|
||||
? parseInt(itemsTotal)
|
||||
: 0;
|
||||
const deviceItemsCount = (itemsCount !== undefined && itemsCount !== null && itemsCount !== '')
|
||||
? parseInt(itemsCount)
|
||||
: 0;
|
||||
if (isSandan === 0 && Number.isFinite(deviceWaveTotal) && deviceWaveTotal > 0 && deviceWaveTotal !== packQuantity) {
|
||||
ctx.logger.info('[Workbench._packOrder] 打包数量复查不一致 waveId=%d 设备端=%d 服务端=%d(以服务端为准)',
|
||||
waveId, deviceWaveTotal, packQuantity);
|
||||
}
|
||||
if (Number.isFinite(deviceItemsTotal) && deviceItemsTotal > 0 && deviceItemsTotal !== packItemQuantity) {
|
||||
ctx.logger.info('[Workbench._packOrder] 商品总件数复查不一致 orderId=%d waveId=%d 设备端=%d 服务端=%d(以服务端为准)',
|
||||
orderId, waveId, deviceItemsTotal, packItemQuantity);
|
||||
}
|
||||
if (Number.isFinite(deviceItemsCount) && deviceItemsCount > 0 && deviceItemsCount !== packSkuCount) {
|
||||
ctx.logger.info('[Workbench._packOrder] 商品种类数复查不一致 orderId=%d waveId=%d 设备端=%d 服务端=%d(以服务端为准)',
|
||||
orderId, waveId, deviceItemsCount, packSkuCount);
|
||||
}
|
||||
|
||||
const packData = {
|
||||
order_id: orderId,
|
||||
warehouse_id: warehouseId,
|
||||
@ -870,9 +981,9 @@ class WorkbenchService extends Service {
|
||||
waybill_code: null, // 后续可从 order_express 补
|
||||
pack_mode: isSandan === 0 ? 2 : 1, // 1=散单 2=团购
|
||||
status: normalizedPackStatus,
|
||||
pack_quantity: waveTotalOrders !== undefined ? parseInt(waveTotalOrders) || 0 : 1,
|
||||
item_quantity: itemsTotal !== undefined ? parseInt(itemsTotal) || 0 : (orderRow.items_total || 0),
|
||||
sku_count: itemsCount !== undefined ? parseInt(itemsCount) || 0 : (orderRow.item_count || 0),
|
||||
pack_quantity: packQuantity,
|
||||
item_quantity: packItemQuantity,
|
||||
sku_count: packSkuCount,
|
||||
start_time: new Date(packTimeMs),
|
||||
end_time: normalizedPackStatus >= 2 ? new Date(packTimeMs) : null,
|
||||
device_ids: deviceIds,
|
||||
@ -1581,6 +1692,231 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时聚合波次商品明细(无缓存,供 _fetchWaveItemsSummary 调用)。
|
||||
* 口径:波次下全部未拦截订单(current + dispatch 分表)的商品明细行按 SKU 聚合计划数量
|
||||
* (stock_id 优先作聚合键,缺省按 item_code+item_name),并合并 stock 详情(条码/图片/包装要求/是否需要复核);
|
||||
* 任一环节异常均降级返回空数组,不抛错。
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number} waveId 波次ID
|
||||
* @return {Promise<Array<Object>>} 波次商品聚合数组(结构与散单 items 一致,另附 is_wave_summary=true)
|
||||
*/
|
||||
async _aggregateWaveItems(warehouseId, waveId) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
const orderIds = await this._getWaveOrderIds(warehouseId, waveId, true);
|
||||
if (!orderIds || orderIds.length === 0) return [];
|
||||
|
||||
const orderItemsFactory = ctx.model.OrderItemsFactory;
|
||||
const itemTables = [
|
||||
{ getModel: () => orderItemsFactory.getCurrentModel(warehouseId) },
|
||||
{ getModel: () => orderItemsFactory.getDispatchModel(warehouseId) },
|
||||
];
|
||||
|
||||
const itemRows = [];
|
||||
for (const entry of itemTables) {
|
||||
try {
|
||||
const model = await entry.getModel();
|
||||
if (!model) continue;
|
||||
const rows = await model.findAll({
|
||||
where: { order_id: { [ctx.app.Sequelize.Op.in]: orderIds } },
|
||||
attributes: [
|
||||
'id', 'order_id', 'item_id', 'item_code', 'item_name',
|
||||
'plan_qty', 'actual_price', 'stock_id', 'order_line_no',
|
||||
'inventory_type',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
itemRows.push(...rows);
|
||||
} catch (_err) { continue; }
|
||||
}
|
||||
|
||||
if (itemRows.length === 0) return [];
|
||||
|
||||
// 按 SKU 聚合(stock_id 优先作聚合键,缺省按 item_code+item_name)
|
||||
const aggregateMap = new Map();
|
||||
for (const row of itemRows) {
|
||||
const stockId = Number(row.stock_id || 0);
|
||||
const itemCode = String(row.item_code || '').trim();
|
||||
const itemName = String(row.item_name || '').trim();
|
||||
const key = stockId > 0 ? `stock:${stockId}` : `code:${itemCode}||${itemName}`;
|
||||
if (!key) continue;
|
||||
const planQty = Number(row.plan_qty || 0);
|
||||
if (!aggregateMap.has(key)) {
|
||||
aggregateMap.set(key, {
|
||||
stock_id: stockId,
|
||||
item_id: row.item_id,
|
||||
item_code: itemCode,
|
||||
item_name: itemName,
|
||||
plan_qty: 0,
|
||||
inventory_type: row.inventory_type || '',
|
||||
});
|
||||
}
|
||||
aggregateMap.get(key).plan_qty += planQty;
|
||||
}
|
||||
|
||||
const aggregates = Array.from(aggregateMap.values());
|
||||
const stockIds = [ ...new Set(aggregates.map(a => a.stock_id).filter(id => id > 0)) ];
|
||||
const stockMap = new Map();
|
||||
if (stockIds.length > 0) {
|
||||
try {
|
||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
|
||||
for (const detail of stockDetails) {
|
||||
stockMap.set(Number(detail.id), detail);
|
||||
}
|
||||
} catch (stockErr) {
|
||||
ctx.logger.warn('[Workbench._aggregateWaveItems] 查询 stock 详情失败: %s', stockErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
return aggregates.map(agg => {
|
||||
const stock = stockMap.get(agg.stock_id) || {};
|
||||
return {
|
||||
id: 0,
|
||||
order_id: 0,
|
||||
item_id: agg.item_id,
|
||||
item_code: agg.item_code || stock.item_code || '',
|
||||
item_name: agg.item_name || stock.item_name || '',
|
||||
plan_qty: agg.plan_qty,
|
||||
actual_price: null,
|
||||
stock_id: agg.stock_id,
|
||||
order_line_no: '',
|
||||
inventory_type: agg.inventory_type || '',
|
||||
sku_property: stock.sku_property || '',
|
||||
stock_unit: stock.stock_unit || '',
|
||||
barcodes: stock.barcodes || [],
|
||||
image_url: stock.image_url || [],
|
||||
packing_requirements: String(stock.packing_requirements || '').trim(),
|
||||
need_recheck: String(stock.need_recheck || 'Y').trim(),
|
||||
is_wave_summary: true,
|
||||
};
|
||||
});
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[Workbench._aggregateWaveItems] 聚合波次商品失败 waveId=%d: %s', waveId, err.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 团购波次商品 SKU 聚合汇总(带 Redis 短 TTL 缓存兜底,供 getWorkbenchInfo 团购任务 items 返回)。
|
||||
* 波次商品明细量大(动辄数百单),逐单返回明细开销高且无必要,
|
||||
* 因此按 (warehouseId, waveId) 维度做 15s 短缓存(与 _countWaveOrdersCached/_sumWaveItemsTotalCached 同款):
|
||||
* TTL 内重复查询直接命中缓存,缓存不可用或读取失败时降级为实时聚合。
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {number} waveId 波次ID
|
||||
* @return {Promise<Array<Object>>} 波次商品汇总数组(异常降级为空数组)
|
||||
*/
|
||||
async _fetchWaveItemsSummary(warehouseId, waveId) {
|
||||
const { ctx, app } = this;
|
||||
const cacheKey = `${WAVE_ITEMS_SUMMARY_CACHE_KEY_PREFIX}:${warehouseId}:${waveId}`;
|
||||
|
||||
if (app && typeof app.getCacheAsync === 'function') {
|
||||
try {
|
||||
const cached = await app.getCacheAsync(cacheKey);
|
||||
if (Array.isArray(cached)) {
|
||||
return cached;
|
||||
}
|
||||
} catch (cacheReadErr) {
|
||||
ctx.logger.warn('[Workbench._fetchWaveItemsSummary] 读取缓存失败,降级为实时聚合: %s', cacheReadErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
const items = await this._aggregateWaveItems(warehouseId, waveId);
|
||||
|
||||
if (app && typeof app.setCacheAsync === 'function') {
|
||||
try {
|
||||
await app.setCacheAsync(cacheKey, items, WAVE_ITEMS_SUMMARY_CACHE_TTL_SECONDS);
|
||||
} catch (cacheWriteErr) {
|
||||
ctx.logger.warn('[Workbench._fetchWaveItemsSummary] 写入缓存失败,不影响本次返回: %s', cacheWriteErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询订单商品明细并合并 stock 详情(供 _queryOrder 与 buildCurrentPackingInfo 复用)。
|
||||
* - 商品明细来自 OrderItemsFactory 分表(sourceTable=dispatch 查配送明细表,其余查 current);
|
||||
* - stock 详情(条码/图片/包装要求等)经 stockWarehouse.getStockDetails 批量查询(自带缓存);
|
||||
* - 任一环节异常均降级返回空数组,不抛错。
|
||||
* @param {number} orderId 订单ID
|
||||
* @param {number} warehouseId 仓库ID
|
||||
* @param {string} [sourceTable] 订单所在分表(dispatch|current),决定明细分表选择
|
||||
* @return {Promise<Array<Object>>} 商品明细数组(含 item_code/item_name/plan_qty/barcodes/image_url 等)
|
||||
*/
|
||||
async _fetchOrderItemsDetail(orderId, warehouseId, sourceTable) {
|
||||
const { ctx } = this;
|
||||
let items = [];
|
||||
try {
|
||||
const getItemsModel = sourceTable === 'dispatch'
|
||||
? () => ctx.model.OrderItemsFactory.getDispatchModel(warehouseId)
|
||||
: () => ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||
const itemsModel = await getItemsModel();
|
||||
if (itemsModel) {
|
||||
const orderItems = await itemsModel.findAll({
|
||||
where: { order_id: orderId },
|
||||
attributes: [
|
||||
'id', 'order_id', 'item_id', 'item_code', 'item_name',
|
||||
'plan_qty', 'actual_price', 'stock_id', 'order_line_no',
|
||||
'inventory_type', 'item_snapshot',
|
||||
],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (orderItems.length > 0) {
|
||||
// 收集所有 stock_id,批量查询 stock 详情(带缓存)
|
||||
const stockIds = [ ...new Set(
|
||||
orderItems.map(item => Number(item.stock_id)).filter(id => id > 0)
|
||||
) ];
|
||||
|
||||
/** @type {Map<number, Object>} */
|
||||
const stockMap = new Map();
|
||||
if (stockIds.length > 0) {
|
||||
try {
|
||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||
stockIds,
|
||||
{ warehouseId }
|
||||
);
|
||||
for (const detail of stockDetails) {
|
||||
stockMap.set(Number(detail.id), detail);
|
||||
}
|
||||
} catch (stockErr) {
|
||||
ctx.logger.warn('[Workbench._fetchOrderItemsDetail] 查询 stock 详情失败: %s', stockErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 组装 items,合并 stock 信息
|
||||
items = orderItems.map(item => {
|
||||
const stockId = Number(item.stock_id);
|
||||
const stock = stockMap.get(stockId) || {};
|
||||
return {
|
||||
id: item.id,
|
||||
order_id: item.order_id,
|
||||
item_id: item.item_id,
|
||||
item_code: item.item_code || stock.item_code || '',
|
||||
item_name: item.item_name || stock.item_name || '',
|
||||
plan_qty: item.plan_qty,
|
||||
actual_price: item.actual_price,
|
||||
stock_id: stockId,
|
||||
order_line_no: item.order_line_no || '',
|
||||
inventory_type: item.inventory_type || '',
|
||||
sku_property: stock.sku_property || '',
|
||||
stock_unit: stock.stock_unit || '',
|
||||
barcodes: stock.barcodes || [],
|
||||
image_url: stock.image_url || '',
|
||||
packing_requirements: String(stock.packing_requirements || '').trim(),
|
||||
need_recheck: String(stock.need_recheck || 'Y').trim(),
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (itemsErr) {
|
||||
ctx.logger.warn('[Workbench._fetchOrderItemsDetail] 查询订单商品失败 orderId=%d: %s', orderId, itemsErr.message);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 条码查订单:条码 → wms_order_express → 待处理/配送订单详情
|
||||
* 散单(isSandan=1)时在响应 order 对象中额外返回 intercept_flag / pack_flag 两个 0/1 标志:
|
||||
@ -1698,74 +2034,8 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 步骤4:查询订单商品明细 + 关联 stock 详情(带缓存)
|
||||
let items = [];
|
||||
try {
|
||||
const getItemsModel = sourceTable === 'dispatch'
|
||||
? () => ctx.model.OrderItemsFactory.getDispatchModel(warehouseId)
|
||||
: () => ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
|
||||
const itemsModel = await getItemsModel();
|
||||
if (itemsModel) {
|
||||
const orderItems = await itemsModel.findAll({
|
||||
where: { order_id: orderId },
|
||||
attributes: [
|
||||
'id', 'order_id', 'item_id', 'item_code', 'item_name',
|
||||
'plan_qty', 'actual_price', 'stock_id', 'order_line_no',
|
||||
'inventory_type', 'item_snapshot',
|
||||
],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (orderItems.length > 0) {
|
||||
// 收集所有 stock_id,批量查询 stock 详情(带缓存)
|
||||
const stockIds = [ ...new Set(
|
||||
orderItems.map(item => Number(item.stock_id)).filter(id => id > 0)
|
||||
) ];
|
||||
|
||||
/** @type {Map<number, Object>} */
|
||||
const stockMap = new Map();
|
||||
if (stockIds.length > 0) {
|
||||
try {
|
||||
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(
|
||||
stockIds,
|
||||
{ warehouseId }
|
||||
);
|
||||
for (const detail of stockDetails) {
|
||||
stockMap.set(Number(detail.id), detail);
|
||||
}
|
||||
} catch (stockErr) {
|
||||
ctx.logger.warn('[Workbench._queryOrder] 查询 stock 详情失败: %s', stockErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 组装 items,合并 stock 信息
|
||||
items = orderItems.map(item => {
|
||||
const stockId = Number(item.stock_id);
|
||||
const stock = stockMap.get(stockId) || {};
|
||||
return {
|
||||
id: item.id,
|
||||
order_id: item.order_id,
|
||||
item_id: item.item_id,
|
||||
item_code: item.item_code || stock.item_code || '',
|
||||
item_name: item.item_name || stock.item_name || '',
|
||||
plan_qty: item.plan_qty,
|
||||
actual_price: item.actual_price,
|
||||
stock_id: stockId,
|
||||
order_line_no: item.order_line_no || '',
|
||||
inventory_type: item.inventory_type || '',
|
||||
sku_property: stock.sku_property || '',
|
||||
stock_unit: stock.stock_unit || '',
|
||||
barcodes: stock.barcodes || [],
|
||||
image_url: stock.image_url || '',
|
||||
packing_requirements: String(stock.packing_requirements || '').trim(),
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (itemsErr) {
|
||||
ctx.logger.warn('[Workbench._queryOrder] 查询订单商品失败: %s', itemsErr.message);
|
||||
}
|
||||
// 步骤4:查询订单商品明细 + 关联 stock 详情(带缓存,公共方法 _fetchOrderItemsDetail)
|
||||
const items = await this._fetchOrderItemsDetail(orderId, warehouseId, sourceTable);
|
||||
|
||||
// 步骤5:查询货主备注(从合约表 store_warehouse.store_remask)
|
||||
let storeRemark = '';
|
||||
@ -2276,8 +2546,11 @@ class WorkbenchService extends Service {
|
||||
/**
|
||||
* 组装工作台当前正在打包的波次与订单信息(供 workbench.getWorkbenchInfo 返回)。
|
||||
* - current_wave:最新一条团购(pack_mode=2)未结束任务对应的波次信息,无则为空对象;
|
||||
* - current_orders:全部未结束打包任务列表(含发货单号、波次号、任务状态等),无则为空数组。
|
||||
* 任一环节异常均降级为空对象/空数组,不影响主信息返回。
|
||||
* - current_orders:全部未结束打包任务列表(含发货单号、波次号、任务状态、商品件数/SKU 数等):
|
||||
* 散单任务(pack_mode=1)items 为单笔订单商品明细(含条码/图片/包装要求/是否需要复核);
|
||||
* 团购任务(pack_mode=2)items 为波次商品 SKU 聚合汇总(波次内全部未拦截订单按 SKU 聚合计划数量,15s 短缓存兜底,
|
||||
* 元素另附 is_wave_summary=true),供工作台退出/刷新后恢复任务上下文。
|
||||
* 任一环节异常均降级为空对象/空数组/空明细,不影响主信息返回。
|
||||
* @param {number} workbenchId 工作台 ID
|
||||
* @param {number} warehouseId 仓库 ID
|
||||
* @return {Promise<{current_wave: Object, current_orders: Array<Object>}>} 当前打包中波次与订单
|
||||
@ -2302,24 +2575,49 @@ class WorkbenchService extends Service {
|
||||
let currentWave = {};
|
||||
const currentOrders = [];
|
||||
for (const task of tasks) {
|
||||
// 按订单ID补齐发货单号(current → dispatch 分表遍历,与 _packOrder 口径一致)
|
||||
// 按订单ID补齐发货单号与订单关键字段(current → dispatch 分表遍历,与 _packOrder 口径一致)
|
||||
let deliveryOrderCode = '';
|
||||
let orderRow = null;
|
||||
let sourceTable = '';
|
||||
for (const entry of tableOrders) {
|
||||
try {
|
||||
const model = await entry.getModel();
|
||||
if (!model) continue;
|
||||
const row = await model.findOne({
|
||||
where: { id: Number(task.order_id || 0), warehouse_id: warehouseId },
|
||||
attributes: [ 'delivery_order_code' ],
|
||||
attributes: [ 'delivery_order_code', 'order_type', 'store_id', 'items_count', 'items_total' ],
|
||||
raw: true,
|
||||
});
|
||||
if (row) {
|
||||
deliveryOrderCode = row.delivery_order_code || '';
|
||||
orderRow = row;
|
||||
sourceTable = entry.label;
|
||||
break;
|
||||
}
|
||||
} catch (_err) { continue; }
|
||||
}
|
||||
|
||||
const isGroup = Number(task.pack_mode) === 2;
|
||||
|
||||
// 散单任务补充单笔订单商品明细;团购任务补充波次商品 SKU 聚合汇总(15s 短缓存兜底),
|
||||
// 均供工作台退出/刷新后恢复任务上下文(异常降级为空数组)
|
||||
let items = [];
|
||||
if (!isGroup && Number(task.order_id || 0) > 0 && sourceTable) {
|
||||
try {
|
||||
items = await this._fetchOrderItemsDetail(Number(task.order_id), warehouseId, sourceTable);
|
||||
} catch (itemsErr) {
|
||||
ctx.logger.warn('[Workbench.buildCurrentPackingInfo] 查询散单商品明细失败 orderId=%d: %s',
|
||||
Number(task.order_id), itemsErr.message);
|
||||
}
|
||||
} else if (isGroup && Number(task.wave_id || 0) > 0) {
|
||||
try {
|
||||
items = await this._fetchWaveItemsSummary(warehouseId, Number(task.wave_id));
|
||||
} catch (itemsErr) {
|
||||
ctx.logger.warn('[Workbench.buildCurrentPackingInfo] 查询团购波次商品汇总失败 waveId=%d: %s',
|
||||
Number(task.wave_id), itemsErr.message);
|
||||
}
|
||||
}
|
||||
|
||||
currentOrders.push({
|
||||
task_id: task.id,
|
||||
order_id: task.order_id,
|
||||
@ -2329,12 +2627,19 @@ class WorkbenchService extends Service {
|
||||
pack_mode: Number(task.pack_mode || 1),
|
||||
status: Number(task.status || 0),
|
||||
pack_quantity: Number(task.pack_quantity || 0),
|
||||
item_quantity: Number(task.item_quantity || 0),
|
||||
sku_count: Number(task.sku_count || 0),
|
||||
waybill_code: task.waybill_code || '',
|
||||
order_type: (orderRow && orderRow.order_type) || '',
|
||||
store_id: Number((orderRow && orderRow.store_id) || 0),
|
||||
items_count: Number((orderRow && orderRow.items_count) || 0),
|
||||
items_total: Number((orderRow && orderRow.items_total) || 0),
|
||||
items,
|
||||
operator_text: task.operator_text || '',
|
||||
start_time: task.start_time,
|
||||
});
|
||||
|
||||
// 团购任务(pack_mode=2)作为当前波次,只取最新一条未结束任务
|
||||
const isGroup = Number(task.pack_mode) === 2;
|
||||
if (isGroup && !currentWave.task_id && Number(task.wave_id) > 0) {
|
||||
// 订单数与商品总件数并行统计(各自带 15s 短 TTL 缓存,缓存命中后几乎零开销)
|
||||
const [ orderCount, itemsTotal ] = await Promise.all([
|
||||
@ -2563,6 +2868,234 @@ class WorkbenchService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计数值保留 2 位小数(四舍五入)。
|
||||
* @param {number} value 原始数值
|
||||
* @return {number} 保留 2 位小数后的数值
|
||||
*/
|
||||
_round2(value) {
|
||||
return Math.round(Number(value) * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化时间为 'YYYY-MM-DD HH:mm:ss'(本地时间,供接口返回展示)。
|
||||
* @param {Date} date 日期对象
|
||||
* @return {string} 格式化后的时间字符串
|
||||
*/
|
||||
_formatPackCountTime(date) {
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
|
||||
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算打包统计时间窗口(班次口径):
|
||||
* 本地时间当日 08:00 至次日 08:00(左闭右开);
|
||||
* 当前本地时间早于 08:00 时,窗口为昨日 08:00 至今日 08:00。
|
||||
* @return {{startTime: Date, endTime: Date}} 窗口起止时间
|
||||
*/
|
||||
buildWorkbenchPackCountTimeRange() {
|
||||
const now = new Date();
|
||||
let startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
|
||||
if (now.getTime() < startTime.getTime()) {
|
||||
startTime = new Date(startTime.getTime() - 86400000);
|
||||
}
|
||||
return { startTime, endTime: new Date(startTime.getTime() + 86400000) };
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 token 获取当前工作台的班次打包统计(供 workbench.getWorkbenchCount)。
|
||||
*
|
||||
* 统一走 resolveWorkbenchContext 校验:无 token 返回 401、token 无效返回 403;
|
||||
* 仓库与工作台均由 token 解析注入,禁止前端传值。
|
||||
*
|
||||
* 统计窗口:本地时间当日 08:00 → 次日 08:00;当前时间早于 08:00 时为昨日 08:00 → 今日 08:00。
|
||||
* - 个人工作台(type=personal):统计「涉及本人」的打包数据(本人 = 工作台成员 user_id,
|
||||
* 范围 = 本工作台产生的任务 ∪ 本人作为打包人参与的任务),返回:
|
||||
* group_wave_count 团购波次数量(pack_mode=2 且 wave_id>0 去重)、
|
||||
* group_order_count 团购订单数量(团购任务 pack_quantity 求和)、
|
||||
* single_order_count 散单数量(pack_mode=1 任务数)、
|
||||
* group_single_ratio 团散(团购波次数/散单数,保留 2 位小数,散单为 0 时 null)、
|
||||
* avg_piece_count 均件数(本人打包任务按 订单数量/人数 折算后求和,保留 2 位小数:
|
||||
* 本人作为打包人参与的任务按任务实际打包人数均分,本工作台单人任务整单计入)。
|
||||
* - 团体工作台(type=group):统计「涉及本工作台」的打包数据,返回:
|
||||
* group_wave_count 团购波次数量、group_order_count 团购订单数量(团购任务 pack_quantity 快照求和)、
|
||||
* single_order_count 散单数量。
|
||||
*
|
||||
* 只查 wms_pack_task / wms_pack_task_packer,全部走现有/配套索引
|
||||
* (idx_warehouse_create_time / idx_workbench_create_time / uix_pack_task_account),
|
||||
* 不做订单分表实时统计,避免慢 SQL。
|
||||
*
|
||||
* @param {Object} [data={}] - { token }
|
||||
* @return {Promise<Object>} { success, code, data, message, statusCode }
|
||||
*/
|
||||
async getWorkbenchCountByToken(data = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
try {
|
||||
const rawToken = typeof data.token === 'string' ? data.token.trim() : '';
|
||||
|
||||
// 统一 token 校验(无 token 401、无效 403),解析成功后写入 ctx 备用
|
||||
const resolved = await this.resolveWorkbenchContext(rawToken);
|
||||
if (!resolved.success) return resolved;
|
||||
|
||||
const workbench = resolved.data;
|
||||
const workbenchId = Number(workbench.id);
|
||||
const warehouseId = Number(workbench.warehouse_id || 0);
|
||||
const isGroup = workbench.type === 'group';
|
||||
const { startTime, endTime } = this.buildWorkbenchPackCountTimeRange();
|
||||
|
||||
// 窗口内打包任务:团体工作台只取本工作台(走 idx_workbench_create_time),
|
||||
// 个人工作台取本仓库窗口内全部任务(走 idx_warehouse_create_time)再按人过滤。
|
||||
const taskWhere = {
|
||||
warehouse_id: warehouseId,
|
||||
create_time: { [Op.gte]: startTime, [Op.lt]: endTime },
|
||||
};
|
||||
if (isGroup) {
|
||||
taskWhere.workbench_id = workbenchId;
|
||||
}
|
||||
const tasks = await ctx.model.PackTask.findAll({
|
||||
where: taskWhere,
|
||||
attributes: [ 'id', 'wave_id', 'pack_mode', 'pack_quantity', 'workbench_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
// 团体工作台:按本工作台任务直接统计
|
||||
if (isGroup) {
|
||||
const groupTasks = tasks.filter(task => Number(task.pack_mode) === 2);
|
||||
const singleTasks = tasks.filter(task => Number(task.pack_mode) === 1);
|
||||
const waveIdSet = new Set(groupTasks.map(task => Number(task.wave_id)).filter(id => id > 0));
|
||||
const groupOrderCount = groupTasks.reduce((sum, task) => sum + (Number(task.pack_quantity) || 0), 0);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
code: 200,
|
||||
data: {
|
||||
workbench_id: workbenchId,
|
||||
workbench_type: workbench.type,
|
||||
time_range: {
|
||||
start_time: this._formatPackCountTime(startTime),
|
||||
end_time: this._formatPackCountTime(endTime),
|
||||
},
|
||||
group_wave_count: waveIdSet.size,
|
||||
group_order_count: groupOrderCount,
|
||||
single_order_count: singleTasks.length,
|
||||
},
|
||||
message: 'ok',
|
||||
};
|
||||
}
|
||||
|
||||
// 个人工作台:本人 = 工作台成员 user_id(个人工作台通常只有一名成员)
|
||||
let personUserId = null;
|
||||
try {
|
||||
const members = await this.listWorkbenchMembers(workbenchId);
|
||||
const userIds = members
|
||||
.map(member => Number(member.user_id))
|
||||
.filter(id => Number.isInteger(id) && id > 0);
|
||||
personUserId = userIds.length > 0 ? userIds[0] : null;
|
||||
} catch (memberErr) {
|
||||
ctx.logger.warn('[Workbench.getWorkbenchCount] 查询工作台成员失败,按本工作台任务统计: %s', memberErr.message);
|
||||
}
|
||||
|
||||
// 本工作台产生的任务
|
||||
const workbenchTaskIds = new Set(
|
||||
tasks.filter(task => Number(task.workbench_id) === workbenchId).map(task => Number(task.id))
|
||||
);
|
||||
|
||||
// 本人作为打包人参与的任务(分批 IN 查询,避免单次 IN 列表过长)
|
||||
const participatedTaskIds = new Set();
|
||||
const taskIds = tasks.map(task => Number(task.id));
|
||||
if (personUserId !== null && taskIds.length > 0) {
|
||||
const batchSize = 500;
|
||||
for (let offset = 0; offset < taskIds.length; offset += batchSize) {
|
||||
const idChunk = taskIds.slice(offset, offset + batchSize);
|
||||
const packerRows = await ctx.model.PackTaskPacker.findAll({
|
||||
where: { pack_task_id: { [Op.in]: idChunk }, account_id: personUserId },
|
||||
attributes: [ 'pack_task_id' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of packerRows) {
|
||||
participatedTaskIds.add(Number(row.pack_task_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 统计对象任务集合:本工作台任务 ∪ 本人作为打包人参与的任务
|
||||
const personalTaskIdSet = new Set([ ...workbenchTaskIds, ...participatedTaskIds ]);
|
||||
|
||||
// 统计各任务的打包人数(供均件数折算使用)
|
||||
const packerCountMap = new Map();
|
||||
if (personalTaskIdSet.size > 0) {
|
||||
const personalIds = [ ...personalTaskIdSet ];
|
||||
const batchSize = 500;
|
||||
for (let offset = 0; offset < personalIds.length; offset += batchSize) {
|
||||
const idChunk = personalIds.slice(offset, offset + batchSize);
|
||||
const packerRows = await ctx.model.PackTaskPacker.findAll({
|
||||
where: { pack_task_id: { [Op.in]: idChunk } },
|
||||
attributes: [ 'pack_task_id' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const row of packerRows) {
|
||||
const key = Number(row.pack_task_id);
|
||||
packerCountMap.set(key, (packerCountMap.get(key) || 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const personalTasks = tasks.filter(task => personalTaskIdSet.has(Number(task.id)));
|
||||
const groupTasks = personalTasks.filter(task => Number(task.pack_mode) === 2);
|
||||
const singleTasks = personalTasks.filter(task => Number(task.pack_mode) === 1);
|
||||
const waveIdSet = new Set(groupTasks.map(task => Number(task.wave_id)).filter(id => id > 0));
|
||||
const groupOrderCount = groupTasks.reduce((sum, task) => sum + (Number(task.pack_quantity) || 0), 0);
|
||||
|
||||
// 均件数:本人打包的每个任务按 订单数量/人数 折算后求和(保留 2 位小数):
|
||||
// 本人作为打包人参与的任务按任务实际打包人数均分(缺省 1);
|
||||
// 本工作台任务未记录到本人时视为单人打包(整单计入本人)。
|
||||
let avgPieceCount = 0;
|
||||
for (const task of personalTasks) {
|
||||
const taskId = Number(task.id);
|
||||
const orderCount = Number(task.pack_mode) === 2 ? (Number(task.pack_quantity) || 0) : 1;
|
||||
if (orderCount <= 0) continue;
|
||||
if (participatedTaskIds.has(taskId)) {
|
||||
const packerCount = packerCountMap.get(taskId) || 1;
|
||||
avgPieceCount += orderCount / packerCount;
|
||||
} else if (workbenchTaskIds.has(taskId)) {
|
||||
avgPieceCount += orderCount;
|
||||
}
|
||||
}
|
||||
|
||||
const singleOrderCount = singleTasks.length;
|
||||
const groupWaveCount = waveIdSet.size;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
code: 200,
|
||||
data: {
|
||||
workbench_id: workbenchId,
|
||||
workbench_type: workbench.type,
|
||||
time_range: {
|
||||
start_time: this._formatPackCountTime(startTime),
|
||||
end_time: this._formatPackCountTime(endTime),
|
||||
},
|
||||
group_wave_count: groupWaveCount,
|
||||
group_order_count: groupOrderCount,
|
||||
single_order_count: singleOrderCount,
|
||||
group_single_ratio: singleOrderCount > 0 ? this._round2(groupWaveCount / singleOrderCount) : null,
|
||||
avg_piece_count: this._round2(avgPieceCount),
|
||||
},
|
||||
message: 'ok',
|
||||
};
|
||||
} catch (error) {
|
||||
app.coreLogger.error(`获取工作台打包统计失败: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '获取工作台打包统计失败,请稍后重试',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 login_code 获取工作台 token(供 index.LoginWorkbenchByCode)。
|
||||
* 按 wms_workbench.login_code 查询;查无工作台返回失败(403);
|
||||
|
||||
123
database/migrations/20260918000000-seed-help-instruction.js
Normal file
123
database/migrations/20260918000000-seed-help-instruction.js
Normal file
@ -0,0 +1,123 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 播种 v2 系统级「帮助 → 指令」链路(幂等,先查后插)。
|
||||
*
|
||||
* - wms_after_sale_type:系统级 type=help(帮助)
|
||||
* - wms_after_sale_sub_type:系统级 type=help / sub_type=instruction(指令)
|
||||
* - wms_after_sale_keyword:系统级关键词「指令」「帮助」→ instruction
|
||||
* - wms_after_sale_function:插入 code=help 函数行(后续启动 sync 会刷新 name/description/is_enabled)
|
||||
* - wms_after_sale_sub_type_function:instruction ↔ help 函数关联
|
||||
* - wms_after_sale_sub_type_group:help 子类型白名单(store.after_sales / warehouse.customer_service / express.after_sales)
|
||||
* - wms_after_sale_reply:系统级回复模板「支持以下命令:\n{back_text}」(仓库可自定义覆盖)
|
||||
*
|
||||
* help 子类型无需取号规则(不关联),help 函数由代码注册表硬编码启用。
|
||||
*/
|
||||
|
||||
const TYPE_TABLE = 'wms_after_sale_type';
|
||||
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
|
||||
const KEYWORD_TABLE = 'wms_after_sale_keyword';
|
||||
const FUNCTION_TABLE = 'wms_after_sale_function';
|
||||
const REL_FN_TABLE = 'wms_after_sale_sub_type_function';
|
||||
const REL_GROUP_TABLE = 'wms_after_sale_sub_type_group';
|
||||
const REPLY_TABLE = 'wms_after_sale_reply';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
const { sequelize } = queryInterface;
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
|
||||
if (!exists(SUB_TYPE_TABLE)) return;
|
||||
|
||||
const q1 = async (sql, replacements) => {
|
||||
const [ rows ] = await sequelize.query(sql, { replacements });
|
||||
return rows && rows.length > 0 ? rows[0] : null;
|
||||
};
|
||||
|
||||
// ─── 1. 系统级类型 help ─────────────────────────────────────
|
||||
if (exists(TYPE_TABLE) && !(await q1('SELECT id FROM `' + TYPE_TABLE + '` WHERE type = :t AND warehouse_id IS NULL LIMIT 1', { t: 'help' }))) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + TYPE_TABLE + '` (warehouse_id, type, name, is_system, is_enabled, sort_order, created_at, updated_at) VALUES (NULL, :t, :n, 1, 1, 100, NOW(), NOW())',
|
||||
{ replacements: { t: 'help', n: '帮助' } }
|
||||
);
|
||||
}
|
||||
|
||||
// ─── 2. 系统级子类型 instruction ────────────────────────────
|
||||
let subId = await q1('SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', { t: 'help', s: 'instruction' });
|
||||
if (!subId) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + SUB_TYPE_TABLE + '` (warehouse_id, type, sub_type, name, is_system, is_enabled, sort_order, created_at, updated_at) VALUES (NULL, :t, :s, :n, 1, 1, 0, NOW(), NOW())',
|
||||
{ replacements: { t: 'help', s: 'instruction', n: '指令' } }
|
||||
);
|
||||
subId = await q1('SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1', { t: 'help', s: 'instruction' });
|
||||
}
|
||||
const instructionId = subId.id;
|
||||
|
||||
// ─── 3. 系统级关键词「指令」「帮助」 ─────────────────────────
|
||||
if (exists(KEYWORD_TABLE)) {
|
||||
let order = 0;
|
||||
for (const kw of [ '指令', '帮助' ]) {
|
||||
const dup = await q1('SELECT id FROM `' + KEYWORD_TABLE + '` WHERE keyword = :k AND warehouse_id IS NULL LIMIT 1', { k: kw });
|
||||
if (!dup) {
|
||||
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, :k, 1, 1, :so, NOW(), NOW())',
|
||||
{ replacements: { sid: instructionId, k: kw, so: order } }
|
||||
);
|
||||
}
|
||||
order += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 4. help 函数行(sync 启动后刷新 name/description/is_enabled) ───
|
||||
let helpFn = null;
|
||||
if (exists(FUNCTION_TABLE)) {
|
||||
helpFn = await q1('SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :c LIMIT 1', { c: 'help' });
|
||||
if (!helpFn) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + FUNCTION_TABLE + '` (function_code, name, description, is_enabled, sort_order, created_at, updated_at) VALUES (:c, :n, :d, 1, 0, NOW(), NOW())',
|
||||
{ replacements: { c: 'help', n: '帮助', d: '帮助指令:枚举当前仓库可见的售后类型与子类型(含关键词),返回可用指令清单(back_text)' } }
|
||||
);
|
||||
helpFn = await q1('SELECT id FROM `' + FUNCTION_TABLE + '` WHERE function_code = :c LIMIT 1', { c: 'help' });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 5. instruction ↔ help 函数关联 ─────────────────────────
|
||||
if (exists(REL_FN_TABLE) && helpFn) {
|
||||
const dup = await q1('SELECT id FROM `' + REL_FN_TABLE + '` WHERE sub_type_id = :s AND function_id = :f LIMIT 1', { s: instructionId, f: helpFn.id });
|
||||
if (!dup) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + REL_FN_TABLE + '` (sub_type_id, function_id, sort_order, created_at, updated_at) VALUES (:s, :f, 1, NOW(), NOW())',
|
||||
{ replacements: { s: instructionId, f: helpFn.id } }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 6. help 子类型群白名单(三类群均可触发) ────────────────
|
||||
if (exists(REL_GROUP_TABLE)) {
|
||||
for (const [ gt, sg ] of [[ 'store', 'after_sales' ], [ 'warehouse', 'customer_service' ], [ 'express', 'after_sales' ]]) {
|
||||
const dup = await q1('SELECT id FROM `' + REL_GROUP_TABLE + '` WHERE sub_type_id = :s AND group_type = :g AND sub_group = :sg LIMIT 1', { s: instructionId, g: gt, sg });
|
||||
if (!dup) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + REL_GROUP_TABLE + '` (sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) VALUES (:s, :g, :sg, 1, 0, NOW(), NOW())',
|
||||
{ replacements: { s: instructionId, g: gt, sg } }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 7. 系统级回复模板(仓库可自定义覆盖) ───────────────────
|
||||
if (exists(REPLY_TABLE)) {
|
||||
const dup = await q1('SELECT id FROM `' + REPLY_TABLE + '` WHERE sub_type_id = :s AND warehouse_id IS NULL LIMIT 1', { s: instructionId });
|
||||
if (!dup) {
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + REPLY_TABLE + '` (warehouse_id, sub_type_id, reply, is_reply, no_number_hint, is_enabled, created_at, updated_at) VALUES (NULL, :s, :r, 1, NULL, 1, NOW(), NOW())',
|
||||
{ replacements: { s: instructionId, r: '支持以下命令:\n{back_text}' } }
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
down: async () => {
|
||||
// 不回退(系统预设种子)
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_after_sale_reply 增加 create_work_order 列(幂等)。
|
||||
*
|
||||
* 语义:是否登记工单。1=函数正常创建售后工单(默认);
|
||||
* 0=函数照常执行(符合入参即执行),但函数内部跳过工单登记
|
||||
* (引擎注入 ctx.inboxContext.skip_work_order 标记,建单函数在建单前检查)。
|
||||
*/
|
||||
|
||||
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.create_work_order) return;
|
||||
|
||||
await queryInterface.addColumn(TABLE, 'create_work_order', {
|
||||
type: Sequelize.TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否登记工单:1=函数正常创建工单(默认),0=函数照常执行但内部跳过工单登记',
|
||||
after: 'is_reply',
|
||||
});
|
||||
},
|
||||
|
||||
down: async () => {
|
||||
// 不回退(新列无副作用)
|
||||
},
|
||||
};
|
||||
47
database/migrations/20260918110000-seed-system-reply-all.js
Normal file
47
database/migrations/20260918110000-seed-system-reply-all.js
Normal file
@ -0,0 +1,47 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 补齐全部系统级子类型的系统级回复配置(幂等,先查后插)。
|
||||
*
|
||||
* - 对每个系统级子类型(warehouse_id IS NULL)补一条系统级回复:
|
||||
* reply='{back_text}'(默认走函数返回内容兜底,help 类占位渲染),
|
||||
* is_reply=1(是否回复统一由回复配置控制)、create_work_order=1、is_enabled=1;
|
||||
* - 已存在回复配置的子类型跳过;
|
||||
* - 仓库自定义子类型不播种(由仓库自行创建仓库级回复)。
|
||||
*/
|
||||
|
||||
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
|
||||
const REPLY_TABLE = 'wms_after_sale_reply';
|
||||
|
||||
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(REPLY_TABLE)) return;
|
||||
|
||||
const [ subRows ] = await sequelize.query(
|
||||
'SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE warehouse_id IS NULL'
|
||||
);
|
||||
const [ replyRows ] = await sequelize.query(
|
||||
'SELECT sub_type_id FROM `' + REPLY_TABLE + '` WHERE warehouse_id IS NULL'
|
||||
);
|
||||
const hasReply = new Set(replyRows.map(r => Number(r.sub_type_id)));
|
||||
|
||||
let inserted = 0;
|
||||
for (const row of subRows) {
|
||||
const sid = Number(row.id);
|
||||
if (hasReply.has(sid)) continue;
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + REPLY_TABLE + '` (warehouse_id, sub_type_id, reply, is_reply, create_work_order, no_number_hint, is_enabled, created_at, updated_at) VALUES (NULL, :sid, :reply, 1, 1, NULL, 1, NOW(), NOW())',
|
||||
{ replacements: { sid, reply: '{back_text}' } }
|
||||
);
|
||||
inserted += 1;
|
||||
}
|
||||
console.log(`[seed-system-reply-all] inserted=${inserted}`);
|
||||
},
|
||||
|
||||
down: async () => {
|
||||
// 不回退(系统预设种子)
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 补齐系统级回复配置的「取号失败引导语」基础配置(幂等,只填空值行)。
|
||||
*
|
||||
* 现状:系统级回复行 no_number_hint 全部为 NULL,取号失败时依赖代码内置默认值。
|
||||
* 本次把基础引导语写入系统级配置:
|
||||
* - 子类型关联了 target='express_name' 取号规则(如 change_carrier 改快递)→ 快递指定提示;
|
||||
* - 其余子类型 → 默认运单号提示。
|
||||
* 仓库级行不处理(留空时仍走代码兜底)。
|
||||
*/
|
||||
|
||||
const REPLY_TABLE = 'wms_after_sale_reply';
|
||||
const REL_TABLE = 'wms_after_sale_sub_type_rule';
|
||||
const RULE_TABLE = 'wms_inbox_number_rule';
|
||||
|
||||
const HINT_EXPRESS = '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)';
|
||||
const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
const { sequelize } = queryInterface;
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
|
||||
if (!exists(REPLY_TABLE)) return;
|
||||
|
||||
// 关联 express_name 取号规则的子类型集合
|
||||
let expressIds = new Set();
|
||||
if (exists(REL_TABLE) && exists(RULE_TABLE)) {
|
||||
const [ relRows ] = await sequelize.query(
|
||||
'SELECT DISTINCT rel.sub_type_id FROM `' + REL_TABLE + '` rel ' +
|
||||
'JOIN `' + RULE_TABLE + '` r ON r.id = rel.number_rule_id WHERE r.target = :t',
|
||||
{ replacements: { t: 'express_name' } }
|
||||
);
|
||||
expressIds = new Set(relRows.map(r => Number(r.sub_type_id)));
|
||||
}
|
||||
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT id, sub_type_id FROM `' + REPLY_TABLE + '` ' +
|
||||
'WHERE warehouse_id IS NULL AND (no_number_hint IS NULL OR no_number_hint = :empty)',
|
||||
{ replacements: { empty: '' } }
|
||||
);
|
||||
|
||||
let updated = 0;
|
||||
for (const row of rows) {
|
||||
const hint = expressIds.has(Number(row.sub_type_id)) ? HINT_EXPRESS : HINT_DEFAULT;
|
||||
await sequelize.query(
|
||||
'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id',
|
||||
{ replacements: { hint, id: row.id } }
|
||||
);
|
||||
updated += 1;
|
||||
}
|
||||
console.log(`[seed-system-no-number-hint] updated=${updated}`);
|
||||
},
|
||||
|
||||
down: async () => {
|
||||
// 不回退(系统预设种子)
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,63 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 修正系统级「取号失败引导语」范围(幂等,按子类型取号规则重算):
|
||||
* - 子类型关联了 target='express_name' 取号规则(如 change_carrier)→ 快递指定提示;
|
||||
* - 子类型关联了其他取号规则 → 默认运单号提示;
|
||||
* - 子类型无任何取号规则(如 help 指令、无取号环节的类型)→ 清空(取号失败分支不会触发,展示空)。
|
||||
*/
|
||||
|
||||
const REPLY_TABLE = 'wms_after_sale_reply';
|
||||
const REL_TABLE = 'wms_after_sale_sub_type_rule';
|
||||
const RULE_TABLE = 'wms_inbox_number_rule';
|
||||
|
||||
const HINT_EXPRESS = '请指定目标快递(圆通/中通/申通/顺丰/韵达/极兔/邮政/EMS/京东/德邦)';
|
||||
const HINT_DEFAULT = '请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔)';
|
||||
|
||||
module.exports = {
|
||||
up: async queryInterface => {
|
||||
const { sequelize } = queryInterface;
|
||||
const tables = await queryInterface.showAllTables();
|
||||
const exists = t => tables.some(x => (typeof x === 'string' ? x : x.tableName) === t);
|
||||
if (!exists(REPLY_TABLE)) return;
|
||||
|
||||
let expressIds = new Set();
|
||||
let ruleIds = new Set();
|
||||
if (exists(REL_TABLE) && exists(RULE_TABLE)) {
|
||||
const [ exRows ] = await sequelize.query(
|
||||
'SELECT DISTINCT rel.sub_type_id FROM `' + REL_TABLE + '` rel ' +
|
||||
'JOIN `' + RULE_TABLE + '` r ON r.id = rel.number_rule_id WHERE r.target = :t',
|
||||
{ replacements: { t: 'express_name' } }
|
||||
);
|
||||
expressIds = new Set(exRows.map(r => Number(r.sub_type_id)));
|
||||
const [ anyRows ] = await sequelize.query(
|
||||
'SELECT DISTINCT sub_type_id FROM `' + REL_TABLE + '`'
|
||||
);
|
||||
ruleIds = new Set(anyRows.map(r => Number(r.sub_type_id)));
|
||||
}
|
||||
|
||||
const [ rows ] = await sequelize.query(
|
||||
'SELECT id, sub_type_id FROM `' + REPLY_TABLE + '` WHERE warehouse_id IS NULL'
|
||||
);
|
||||
|
||||
let updated = 0;
|
||||
let cleared = 0;
|
||||
for (const row of rows) {
|
||||
const sid = Number(row.sub_type_id);
|
||||
let hint = null;
|
||||
if (expressIds.has(sid)) hint = HINT_EXPRESS;
|
||||
else if (ruleIds.has(sid)) hint = HINT_DEFAULT;
|
||||
if (hint === null) cleared += 1;
|
||||
await sequelize.query(
|
||||
'UPDATE `' + REPLY_TABLE + '` SET no_number_hint = :hint WHERE id = :id',
|
||||
{ replacements: { hint, id: row.id } }
|
||||
);
|
||||
updated += 1;
|
||||
}
|
||||
console.log(`[fix-no-number-hint-scope] updated=${updated} cleared=${cleared}`);
|
||||
},
|
||||
|
||||
down: async () => {
|
||||
// 不回退(数据修正)
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* help(指令)子类型群白名单改为通配:所有群都支持(幂等)。
|
||||
*
|
||||
* 原播种为 store.after_sales / warehouse.customer_service / express.after_sales 三条精确白名单,
|
||||
* 其他群子类型(如 store.receiving)无法触发指令。改为 group_type='*' 通配行,
|
||||
* 引擎 _groupAllowed 对 '*' 直接放行;help 函数 groups=[COMMON] 本身所有群可用。
|
||||
*/
|
||||
|
||||
const SUB_TYPE_TABLE = 'wms_after_sale_sub_type';
|
||||
const REL_GROUP_TABLE = 'wms_after_sale_sub_type_group';
|
||||
|
||||
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(REL_GROUP_TABLE)) return;
|
||||
|
||||
const q1 = async (sql, replacements) => {
|
||||
const [ rows ] = await sequelize.query(sql, { replacements });
|
||||
return rows && rows.length > 0 ? rows[0] : null;
|
||||
};
|
||||
|
||||
const sub = await q1(
|
||||
'SELECT id FROM `' + SUB_TYPE_TABLE + '` WHERE type = :t AND sub_type = :s AND warehouse_id IS NULL LIMIT 1',
|
||||
{ t: 'help', s: 'instruction' }
|
||||
);
|
||||
if (!sub) return;
|
||||
const sid = sub.id;
|
||||
|
||||
const wildcard = await q1(
|
||||
'SELECT id FROM `' + REL_GROUP_TABLE + '` WHERE sub_type_id = :s AND group_type = :g LIMIT 1',
|
||||
{ s: sid, g: '*' }
|
||||
);
|
||||
if (wildcard) {
|
||||
console.log('[help-whitelist-all-groups] 已存在通配白名单,跳过');
|
||||
return;
|
||||
}
|
||||
|
||||
const [ del ] = await sequelize.query(
|
||||
'DELETE FROM `' + REL_GROUP_TABLE + '` WHERE sub_type_id = :s',
|
||||
{ replacements: { s: sid } }
|
||||
);
|
||||
await sequelize.query(
|
||||
'INSERT INTO `' + REL_GROUP_TABLE + '` (sub_type_id, group_type, sub_group, is_system, sort_order, created_at, updated_at) VALUES (:s, :g, :sg, 1, 0, NOW(), NOW())',
|
||||
{ replacements: { s: sid, g: '*', sg: '' } }
|
||||
);
|
||||
console.log(`[help-whitelist-all-groups] deleted=${del.affectedRows || 0} inserted-wildcard=1`);
|
||||
},
|
||||
|
||||
down: async () => {
|
||||
// 不回退(语义修正)
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* workbench.getWorkbenchCount 慢查询优化配套索引。
|
||||
* 班次统计按 (workbench_id, create_time) 过滤窗口内打包任务,原 idx_workbench_id 单列索引
|
||||
* 命中后仍需过滤该工作台全部历史行,新增 (workbench_id, create_time) 复合索引
|
||||
* 使窗口过滤走索引范围扫描,避免长跨度扫描导致慢 SQL。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.addIndex('wms_pack_task', [ 'workbench_id', 'create_time' ], {
|
||||
name: 'idx_workbench_create_time',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('wms_pack_task', 'idx_workbench_create_time');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,107 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单表增加 confirm_print_status(确认打印状态)字段。
|
||||
*
|
||||
* 背景:订单表已有 print_status(打印状态机,由打印回执/波次标记更新),
|
||||
* 现增加确认打印状态:打印完成后,操作员真实扫描面单(运单号)进行确认,
|
||||
* 确认后写入 confirm_print_status='fin',用于记录「面单已实际打印并核对」。
|
||||
*
|
||||
* 取值约定:
|
||||
* - none = 未确认打印(默认);
|
||||
* - fin = 已确认打印(扫描面单确认)。
|
||||
*
|
||||
* 覆盖范围:
|
||||
* - 全部仓库分表 wms_order_delivery_{wh}(current)及
|
||||
* _{wh}_history / _{wh}_dispatch / _{wh}_outsourced。
|
||||
*
|
||||
* 说明:基表 wms_order_delivery 业务不使用(订单均写入分表),本迁移
|
||||
* 不对基表加列。基表上仍存在的兜底查询均带 attributes 白名单,不会
|
||||
* 因模型新增字段触发 Unknown column。
|
||||
*
|
||||
* 幂等:列已存在则跳过。分表模型由 app/model/order_delivery_factory.js
|
||||
* 运行时 drift 同步兜底,本迁移提前补齐避免运行时 ALTER。
|
||||
*/
|
||||
|
||||
const SHARD_PATTERN = /^wms_order_delivery_(\d+)(?:_(history|dispatch|outsourced))?$/;
|
||||
|
||||
const COLUMN_NAME = 'confirm_print_status';
|
||||
|
||||
/**
|
||||
* 列举库内全部订单分表。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<string[]>} 分表名列表。
|
||||
*/
|
||||
async function listOrderShards(queryInterface) {
|
||||
const [ rows ] = await queryInterface.sequelize.query(
|
||||
'SELECT TABLE_NAME AS tableName FROM INFORMATION_SCHEMA.TABLES '
|
||||
+ 'WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME LIKE \'wms_order_delivery\\_%\' '
|
||||
+ 'ORDER BY TABLE_NAME'
|
||||
);
|
||||
return (rows || [])
|
||||
.map(row => String(row.tableName || row.TABLE_NAME || ''))
|
||||
.filter(name => SHARD_PATTERN.test(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断列是否已存在。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @param {string} columnName 列名。
|
||||
* @return {Promise<boolean>} 是否存在。
|
||||
*/
|
||||
async function columnExists(queryInterface, tableName, columnName) {
|
||||
const described = await queryInterface.describeTable(tableName);
|
||||
return Boolean(described && described[columnName]);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为基表与全部分表增加 confirm_print_status 列。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 构造器。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const tables = await listOrderShards(queryInterface);
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'exists' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn(tableName, COLUMN_NAME, {
|
||||
type: Sequelize.ENUM('none', 'fin'),
|
||||
allowNull: true,
|
||||
defaultValue: 'none',
|
||||
comment: '确认打印状态机(打印完成后真实扫描面单确认)',
|
||||
});
|
||||
results.push({ tableName, action: 'added' });
|
||||
}
|
||||
|
||||
console.log('[20260920100000-add-confirm-print-status-to-order-delivery] up results:', JSON.stringify(results));
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除基表与全部分表的 confirm_print_status 列。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface) {
|
||||
const tables = await listOrderShards(queryInterface);
|
||||
const results = [];
|
||||
|
||||
for (const tableName of tables) {
|
||||
if (!await columnExists(queryInterface, tableName, COLUMN_NAME)) {
|
||||
results.push({ tableName, action: 'skip', reason: 'missing' });
|
||||
continue;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn(tableName, COLUMN_NAME);
|
||||
results.push({ tableName, action: 'removed' });
|
||||
}
|
||||
|
||||
console.log('[20260920100000-add-confirm-print-status-to-order-delivery] down results:', JSON.stringify(results));
|
||||
},
|
||||
};
|
||||
@ -1,4 +1,238 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.09.20-workbench-pack-backfill-confirm-print",
|
||||
"date": "2026-09-20",
|
||||
"type": "updated",
|
||||
"summary": "打包链路(workbench.packOrder / workbench.finishPack)回写打包状态时同步补确认打印状态:扫描打包即视为面单已真实存在,confirm_print_status 未写入(none/null)时补 fin,团购按波次、散单按单,拦截订单跳过,并递增统计版本号驱动确认打印未领单长轮询。",
|
||||
"methods": [
|
||||
"workbench.packOrder",
|
||||
"workbench.finishPack"
|
||||
],
|
||||
"notes": [
|
||||
"实现入口:systems/workbench.js _updateOrderPackStatus(覆盖开始打包/完成打包/关闭旧任务全部路径)",
|
||||
"幂等:仅 confirm_print_status 为 none/null 时补 fin"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.20-wave-confirmPrintScan-need-right",
|
||||
"date": "2026-09-20",
|
||||
"type": "updated",
|
||||
"summary": "order.wave.confirmPrintScan 改为需要接口权限(isNeedAuth=true),从免权限名单移除;confirmPrintUnclaimedWaveCount 保持免权限。",
|
||||
"methods": [
|
||||
"order.wave.confirmPrintScan"
|
||||
],
|
||||
"notes": [
|
||||
"运行时:wave.js _noNeedRight/_noNeedAuth 已移除 confirmPrintScan,checkAuth 走 checkApiPermission",
|
||||
"权限记录由 permission:sync:system-api 从 system.json isNeedAuth=true 接口同步并授权角色 2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.20-pendingOrder-list-confirm-print-claim-fields",
|
||||
"date": "2026-09-20",
|
||||
"type": "updated",
|
||||
"summary": "order.pendingOrder.list 文档补充 confirm_print_status(确认打印)与 claim_status(领料)的 where 筛选说明与响应字段说明(功能已支持,本次仅同步文档)。",
|
||||
"methods": [
|
||||
"order.pendingOrder.list"
|
||||
],
|
||||
"notes": [
|
||||
"列表输出 ORDER_LIST_BASE_ATTRIBUTES 已包含 confirm_print_status/claim_status;where 无字段白名单,两列可直接透传筛选"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.20-wave-batchList-claim-status",
|
||||
"date": "2026-09-20",
|
||||
"type": "updated",
|
||||
"summary": "order.wave.batchList 波次列表新增 claim_assignment_status 领料状态显示(含 claim_time/claim_operator)与 where.claim_assignment_status 筛选(波次表 claim_time 口径)。",
|
||||
"methods": [
|
||||
"order.wave.batchList"
|
||||
],
|
||||
"notes": [
|
||||
"领料状态以波次表 wms_wave_batch.claim_time 是否为空判定(二态:未领料/已领料),与 confirmPrintUnclaimedWaveCount 口径一致",
|
||||
"where 新增 claim_assignment_status 筛选字段(仅 eq,unclaimed/claimed,兼容中文)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.20-wave-confirm-print-count-fix",
|
||||
"date": "2026-09-20",
|
||||
"type": "updated",
|
||||
"summary": "order.wave.confirmPrintUnclaimedWaveCount 统计口径修正:未领单由订单维度 claim_status 改为波次表维度 wms_wave_batch.claim_time IS NULL,避免历史领单(波次表加 claim_time 字段前)导致少算。",
|
||||
"methods": [
|
||||
"order.wave.confirmPrintUnclaimedWaveCount"
|
||||
],
|
||||
"notes": [
|
||||
"根因:B2026081500088/89 等波次订单 claim_status='fin'(历史领单)但 wave_batch.claim_time=null,订单维度口径误判为已领单导致 count 少算",
|
||||
"新口径:wave_batch(wave_status 0/1、claim_time IS NULL)+ 波次下存在 confirm_print_status='fin' 的非取消订单"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.20-wave-confirm-print-scan-count",
|
||||
"date": "2026-09-20",
|
||||
"type": "added",
|
||||
"summary": "order.wave 新增两个接口:confirmPrintScan(扫面单批量确认打印并写日志,与领单操作一致)与 confirmPrintUnclaimedWaveCount(快速查询已确认打印但未领单波次数量,支持 60s 长轮询,由确认打印/领单版本号驱动)。",
|
||||
"methods": [
|
||||
"order.wave.confirmPrintScan",
|
||||
"order.wave.confirmPrintUnclaimedWaveCount"
|
||||
],
|
||||
"notes": [
|
||||
"confirmPrintScan 复用 print.confirmWavePrint 实现(同入参同返回)",
|
||||
"confirmPrintUnclaimedWaveCount 长轮询:1s 间隔轮询 Redis 版本号(wave:confirm-print:unclaimed:version:{warehouseId}),60s 超时;Redis 不可用时降级为轮询 DB count",
|
||||
"确认打印(print.confirmWavePrint)与领单(pick.waveClaimScan)成功后均递增统计版本号"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.20-wave-batchList-confirm-print",
|
||||
"date": "2026-09-20",
|
||||
"type": "updated",
|
||||
"summary": "order.wave.batchList 波次列表新增 confirm_print_assignment_status 显示与筛选(确认打印状态:未确认打印/部分确认打印/已确认打印)。",
|
||||
"methods": [
|
||||
"order.wave.batchList"
|
||||
],
|
||||
"notes": [
|
||||
"where 新增 confirm_print_assignment_status 筛选字段(仅 eq,英文枚举 unconfirmed/partially_confirmed/confirmed)",
|
||||
"list 每条新增 confirm_print_assignment_status 汇总状态字段"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.20-confirm-wave-print",
|
||||
"date": "2026-09-20",
|
||||
"type": "added",
|
||||
"summary": "订单表新增 confirm_print_status(确认打印状态)字段,并新增 print.confirmWavePrint 波次确认打印接口:打印完成后扫描波次内任一订单面单,批量确认波次下已打印订单。",
|
||||
"methods": [
|
||||
"print.confirmWavePrint"
|
||||
],
|
||||
"notes": [
|
||||
"订单表 wms_order_delivery 及全部分表新增 confirm_print_status ENUM('none','fin'),默认 none;迁移 20260920100000-add-confirm-print-status-to-order-delivery",
|
||||
"波次下存在未打印订单(print_status != 'fin',拦截订单除外)时阻断确认",
|
||||
"拦截订单跳过(不确认、不阻断);全部已确认时重复扫描返回 already_confirmed"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.19-workbench-packOrder-server-side-verification",
|
||||
"date": "2026-09-19",
|
||||
"type": "enhance",
|
||||
"summary": "workbench.packOrder 落库数量改为服务端复查:打包数量/商品总件数/商品种类数不再取设备端上报值,散单取订单分表(orderRow),团购取波次实时统计(totalOrders + 波次商品 SKU 聚合 _fetchWaveItemsSummary),设备端 wave_total_orders/items_count/items_total 仅作交叉校验日志;修复团购波次打包数量落 0/1 的失真问题。",
|
||||
"methods": [
|
||||
"workbench.packOrder"
|
||||
],
|
||||
"notes": [
|
||||
"代码:app/service/systems/workbench.js _packOrder 步骤6 改为服务端复查口径:packQuantity 散单固定 1、团购取 totalOrders(>0 否则 1);packItemQuantity/packSkuCount 散单取 orderRow.items_total/items_count(注:分表列名为 items_count 而非 item_count,此前兜底读 item_count 导致散单 sku_count 兜底落 0,已一并修正),团购取 _fetchWaveItemsSummary(15s 短缓存)聚合 rows.length 与 plan_qty 求和,聚合失败降级为扫描订单值",
|
||||
"交叉校验:设备端上报值与服务端不一致时仅 ctx.logger.info 告警(打包数量/商品总件数/商品种类数三组),落库始终以服务端为准",
|
||||
"开发库数据回填:temp/fix-dev-pack-task-quantities.cjs 已按新口径重算 wms_pack_task 存量 30 条并更新 19 条(保留 update_time、不删行;散单/团购各自取服务端口径,旧 6 月订单缺失的 6 条跳过)",
|
||||
"背景:原语义 pack_quantity=wave_total_orders(缺省 1、传 0 落 0),服务端实时波次订单数未回写,导致列表/统计口径失真",
|
||||
"methods/system.json:workbench.packOrder 参数 wave_total_orders/items_count/items_total 描述同步服务端复查口径;版本 0.3.140 -> 0.3.141(docMeta.version),updatedAt 保持 2026-09-19"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.19-workbench-getWorkbenchCount-avg-piece-count",
|
||||
"date": "2026-09-19",
|
||||
"type": "enhance",
|
||||
"summary": "workbench.getWorkbenchCount 个人工作台返回调整:新增 group_order_count(团购订单数量,团购任务 pack_quantity 求和,个人/团体工作台均返回);均件数 avg_piece_count 口径改为本人打包任务按 订单数量/人数 折算求和(本人作为打包人参与的任务按任务实际打包人数均分、缺省 1,本工作台单人任务整单计入),不再只统计打包人数≥2 的任务,单人打包 500 单波次可正确得到 500。",
|
||||
"methods": [
|
||||
"workbench.getWorkbenchCount"
|
||||
],
|
||||
"notes": [
|
||||
"代码:app/service/systems/workbench.js getWorkbenchCountByToken 个人分支:新增 groupOrderCount(groupTasks 对 pack_quantity 求和);均件数循环改为 participatedTaskIds 按 packerCount(缺省 1)均分、workbenchTaskIds 未记本人时整单计入",
|
||||
"methods/system.json:getWorkbenchCount response 更新 avg_piece_count/group_order_count 描述;版本 0.3.141 -> 0.3.142(docMeta.version),updatedAt 保持 2026-09-19"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.19-workbench-getWorkbenchCount",
|
||||
"date": "2026-09-19",
|
||||
"type": "enhance",
|
||||
"summary": "新增 workbench.getWorkbenchCount 当前工作台班次打包统计(免登录/免权限/免鉴权,以工作台 token 鉴权):统计窗口为本地时间当日 08:00 至次日 08:00,早于 08:00 时为昨日 08:00 至今日 08:00;个人工作台(type=personal)统计涉及本人(工作台成员 user_id)的打包数据,返回团购波次数量/散单数量/团散(团购波次数/散单数 2 位小数)/均件数(多人打包任务按 订单数量/人数 折算求和 2 位小数);团体工作台(type=group)返回团购波次数量/团购订单数量(pack_quantity 快照求和)/散单数量。",
|
||||
"methods": [
|
||||
"workbench.getWorkbenchCount"
|
||||
],
|
||||
"notes": [
|
||||
"代码:app/service/systems/workbench.js 新增 getWorkbenchCountByToken(resolveWorkbenchContext 统一 token 校验,无 token 401/无效 403)与辅助方法 buildWorkbenchPackCountTimeRange(8 点班次窗口)/ _round2 / _formatPackCountTime",
|
||||
"个人统计:窗口内本仓库任务走 idx_warehouse_create_time;本人参与任务通过 wms_pack_task_packer(account_id=成员 user_id,分批 IN 500)与 uix_pack_task_account 索引判定;统计范围 = 本工作台任务 ∪ 本人作为打包人参与的任务;均件数只折算本人参与的多人打包(打包人数≥2)任务",
|
||||
"团体统计:workbench_id+create_time 走新增 idx_workbench_create_time 索引",
|
||||
"索引:数据库迁移 20260919100000-add-workbench-create-time-index-to-wms-pack-task.js 为 wms_pack_task 新增 (workbench_id, create_time) 复合索引,避免窗口统计长跨度扫描导致慢 SQL;模型 app/model/pack_task.js indexes 同步补充",
|
||||
"methods/system.json:工作台模块新增 workbench.getWorkbenchCount 条目;版本 0.3.138 -> 0.3.139(docMeta.version),updatedAt 保持 2026-09-19"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.19-wave-batchList-sync-assignment-status",
|
||||
"date": "2026-09-19",
|
||||
"type": "enhance",
|
||||
"summary": "order.wave.batchList 响应新增 sync_assignment_status(同步状态,取值:未同步/部分同步/已同步/同步异常),并支持 where.sync_assignment_status 筛选(英文枚举 unsynced/partially_synced/synced,仅 eq,error 并入未同步集合)。",
|
||||
"methods": [
|
||||
"order.wave.batchList"
|
||||
],
|
||||
"notes": [
|
||||
"代码:app/service/systemMethods/order/wave.js BATCH_LIST_ASSIGNMENT_FILTER_SCHEMAS 新增 sync 类型(fieldName=sync_assignment_status,enumMap unsynced/partially_synced/synced → none/partial/finished,caseInsensitive=true,statsColumnPrefix=sync,withErrorStatus=true)",
|
||||
"聚合:wave_order_stats 子查询新增 sync_none_count/sync_fin_count/sync_error_count,按订单 sync_status(padding/fin/error)聚合;none 口径为 sync_status IS NULL 或 NOT IN ('fin','error'),与 review 统计口径一致",
|
||||
"输出:list[].sync_assignment_status 复用 resolveAssignmentStatus,error 优先判定为同步异常,labels 为未同步/部分同步/已同步/同步异常",
|
||||
"筛选:buildBatchListWhereClause allowedFields 新增 sync_assignment_status,仅支持 eq;normalizeBatchListSyncAssignmentStatusFilter/buildBatchListSyncAssignmentFilterClause 复用通用 schema 链路",
|
||||
"methods/system.json:batchList description/where/response 同步 sync_assignment_status 说明;版本 0.3.137 -> 0.3.138(docMeta.version),updatedAt 保持 2026-09-19"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.19-workbench-getWorkbenchInfo-wave-items-summary",
|
||||
"date": "2026-09-19",
|
||||
"type": "enhance",
|
||||
"summary": "workbench.getWorkbenchInfo 团购任务(pack_mode=2)current_orders items 由空数组改为波次商品 SKU 聚合汇总,彻底解决工作台退出/刷新后团购打包任务无商品信息的问题:新增 _aggregateWaveItems(波次内全部未拦截订单(current+dispatch 分表)商品明细按 SKU 聚合计划数量并合并 stock 详情,聚合行另附 is_wave_summary=true)与 _fetchWaveItemsSummary(按 warehouseId+waveId 维度 15s 短缓存兜底,与 order_count/items_total 同款缓存模式),buildCurrentPackingInfo 团购任务分支调用;散单任务 items 口径不变。",
|
||||
"methods": [
|
||||
"workbench.getWorkbenchInfo"
|
||||
],
|
||||
"notes": [
|
||||
"代码:app/service/systems/workbench.js 新增常量 WAVE_ITEMS_SUMMARY_CACHE_KEY_PREFIX/WAVE_ITEMS_SUMMARY_CACHE_TTL_SECONDS(15s);_aggregateWaveItems 聚合键 stock_id 优先、缺省按 item_code+item_name,stock 详情走 stockWarehouse.getStockDetails 通用缓存链路,异常降级空数组;buildCurrentPackingInfo 团购任务(wave_id>0)调用 _fetchWaveItemsSummary 填 items",
|
||||
"结构:聚合行与散单 items 结构同源(id/order_id 置 0、order_line_no 空串、actual_price null、plan_qty 为波次内该 SKU 合计),另附 is_wave_summary=true 供前端区分单笔明细与波次汇总",
|
||||
"性能:15s 短缓存保证 TTL 内重复查询零开销;缓存未命中时波次订单 ID 查询走 wave_id 索引、items 按 order_id IN 查询走索引,500 单规模波次一次聚合可接受;packOrder/finishPack 后 token 缓存失效,波次聚合缓存在 TTL 内可能与最新波次状态有最多 15s 滞后(与 order_count/items_total 同口径)",
|
||||
"methods/system.json:workbench.getWorkbenchInfo description 与 current_orders[].items/items[].id/items[].order_id/items[].plan_qty 描述更新为双口径,response 新增 current_orders[].items[].is_wave_summary 条目;版本 0.3.136 -> 0.3.137(docMeta.version),updatedAt 保持 2026-09-19"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.19-workbench-order-items-need-recheck",
|
||||
"date": "2026-09-19",
|
||||
"type": "updated",
|
||||
"summary": "workbench.queryOrder 与 workbench.getWorkbenchInfo 响应商品明细 items 新增 need_recheck 字段(Y=需要复核,N=不需要复核(免验),缺省 Y):组装链路 _fetchOrderItemsDetail 从 stock 详情(getStockDetails 通用缓存链路,其 attributes 已含 need_recheck)透出,补齐工作台打包端商品列表缺少免验标识的问题。",
|
||||
"methods": [
|
||||
"workbench.queryOrder",
|
||||
"workbench.getWorkbenchInfo"
|
||||
],
|
||||
"notes": [
|
||||
"代码:app/service/systems/workbench.js _fetchOrderItemsDetail items 组装新增 need_recheck: String(stock.need_recheck || 'Y').trim()(与 order.recheckOrder.scanOrder/scanTask 同口径,getStockDetails 旧缓存无该字段时兜底 Y)",
|
||||
"workbench.queryOrder 与 workbench.getWorkbenchInfo(current_orders[].items)共用 _fetchOrderItemsDetail,两接口 items 同步生效",
|
||||
"methods/system.json:workbench.queryOrder description 补充 need_recheck 说明,response 新增 items[].need_recheck 条目;workbench.getWorkbenchInfo description 补充「是否需要复核 need_recheck」,response 新增 current_orders[].items[].need_recheck 条目,并将 current_orders[].items[].image_url 类型由 string 修正为 array(实际返回数组);版本 0.3.135 -> 0.3.136(docMeta.version),updatedAt 保持 2026-09-19"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.19-workbench-getWorkbenchInfo-order-items",
|
||||
"date": "2026-09-19",
|
||||
"type": "enhance",
|
||||
"summary": "enhance: workbench.getWorkbenchInfo 响应 data.current_orders 补全任务上下文字段,解决工作台退出/刷新后无法恢复任务信息的问题:散单任务(pack_mode=1)新增 items 商品明细数组(wms_order_items 分表按 order_id 查询并合并 stock 详情,含 item_code/item_name/plan_qty/barcodes/image_url/packing_requirements 等,与 workbench.queryOrder 返回结构同源),团购任务(pack_mode=2)波次商品明细量大,items 置空数组、以 current_wave 汇总展示;同时每项新增 wms_pack_task 已有字段 item_quantity/sku_count/waybill_code 与订单分表字段 order_type/store_id/items_count/items_total。",
|
||||
"methods": [
|
||||
"workbench.getWorkbenchInfo"
|
||||
],
|
||||
"notes": [
|
||||
"实现:app/service/systems/workbench.js 从 _queryOrder 步骤4 抽取公共方法 _fetchOrderItemsDetail(orderId, warehouseId, sourceTable)(sourceTable=dispatch 查配送明细分表、其余查 current;stock 详情走 stockWarehouse.getStockDetails 自带缓存;异常降级空数组),_queryOrder 改为复用(响应结构不变);buildCurrentPackingInfo 任务遍历时记录订单所在分表 sourceTable 并多取 order_type/store_id/items_count/items_total 字段,散单任务调用 _fetchOrderItemsDetail 补 items,团购任务 items 置空数组",
|
||||
"口径:items 仅对 pack_mode=1 散单任务查询(团购波次逐单聚合开销大且前端以 current_wave 汇总展示);单笔商品明细查询异常仅该项 items 降级为空数组,不影响主信息与其余字段",
|
||||
"性能:buildCurrentPackingInfo 仅在 token 缓存(workbench:token:{token},TTL 300s)未命中或打包状态变更失效后执行,未结束任务通常单条,items 按 order_id 走索引查询,无新增高频开销",
|
||||
"methods/system.json:workbench.getWorkbenchInfo description 补充散单 items/团购空数组与新增字段说明,response 新增 current_orders[].item_quantity/sku_count/waybill_code/order_type/store_id/items_count/items_total 与 current_orders[].items 及 items[] 下 16 个子字段条目(沿用 current_orders[].xxx 嵌套命名惯例);版本 0.3.134 -> 0.3.135(docMeta.version),updatedAt 2026-09-17 -> 2026-09-19"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.17-inbox-group-template-reply-switch",
|
||||
"date": "2026-09-17",
|
||||
"type": "enhance",
|
||||
"summary": "enhance: inbox.group 系列接口接入模板消息回复开关 templateReplyEnabled/template_reply_enabled(0=关闭(普通文本回复) / 1=开启(模板消息回复)),默认 0,所有群类型均支持且独立于 aiEnabled。update 新增入参(未传不修改),reset 重置为关闭,list 返回字段与 where 筛选支持、quickList 返回字段同步补全。",
|
||||
"methods": [
|
||||
"inbox.group.update",
|
||||
"inbox.group.reset",
|
||||
"inbox.group.list",
|
||||
"inbox.group.quickList"
|
||||
],
|
||||
"notes": [
|
||||
"字段落位:wms_inbox_group.template_reply_enabled(TINYINT(1) NOT NULL DEFAULT 0,迁移 database/migrations/20260917100000-add-template-reply-enabled-to-inbox-group.js,model app/model/inbox_group.js 已同步)",
|
||||
"语义:ai_enabled 控制是否 AI 处理;template_reply_enabled 控制命中处理后是否以模板消息形式回复(0=普通文本回复,1=模板消息回复),两开关相互独立",
|
||||
"update:data.templateReplyEnabled===1 时写 1,否则写 0,未传不修改;reset:清空配置时 template_reply_enabled 重置为 0;方法层 app/service/systemMethods/inbox.js#groupUpdate 透传",
|
||||
"list:attributes 与 where specialFieldMap 新增 template_reply_enabled(可筛选),返回行沿用 snake_case 风格(template_reply_enabled)与 ai_enabled 相邻",
|
||||
"quickList:轻量字段新增 template_reply_enabled,下拉选择可感知模板回信开关",
|
||||
"消费方:app/service/inbox/processor.js#loadGroupConfig 读取 template_reply_enabled,为 1 的群命中处理后走 inbox.v2.rules 可配置引擎(模板消息回复)",
|
||||
"文档版本 0.3.133 -> 0.3.134,updatedAt 2026-09-17"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.09.16-inbox-push-retry-warehouse-setting",
|
||||
"date": "2026-09-16",
|
||||
|
||||
1734
methods/system.json
1734
methods/system.json
File diff suppressed because one or more lines are too long
@ -149,9 +149,10 @@ function buildPermissionDefaults(methodPath, templateRow) {
|
||||
path: methodPath,
|
||||
type: 'api',
|
||||
component: templateRow ? templateRow.component : null,
|
||||
name: templateRow && templateRow.name ? templateRow.name : methodPath,
|
||||
// name/title 一律按 method 路径生成,不继承模板行(历史模板行 title 可能与本接口无关)
|
||||
name: methodPath,
|
||||
redirect: templateRow ? templateRow.redirect : null,
|
||||
meta_title: templateRow && templateRow.meta_title ? templateRow.meta_title : `API:${methodPath}`,
|
||||
meta_title: `API:${methodPath}`,
|
||||
meta_icon: templateRow ? templateRow.meta_icon : null,
|
||||
hidden: templateRow ? Number(templateRow.hidden || 0) : 0,
|
||||
always_show: templateRow ? Number(templateRow.always_show || 0) : 0,
|
||||
|
||||
@ -1,23 +0,0 @@
|
||||
'use strict';
|
||||
const mysql = require('mysql2/promise');
|
||||
(async () => {
|
||||
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
|
||||
|
||||
// bindDetailProduct 自动写入的条码(本次测试的 TMPBC/FULLBC 前缀)
|
||||
const [barcodes] = await c.query(`
|
||||
SELECT id, stock_id, warehouse_id, barcode
|
||||
FROM wms_stock_barcodes
|
||||
WHERE barcode LIKE 'TMPBC%' OR barcode LIKE 'FULLBC%'
|
||||
ORDER BY id`);
|
||||
console.log('== wms_stock_barcodes 测试写入的条码(共 ' + barcodes.length + ' 行) ==');
|
||||
console.log(JSON.stringify(barcodes, null, 2));
|
||||
|
||||
// 商品 159061/159064 上的全部条码
|
||||
const [all] = await c.query(
|
||||
`SELECT id, stock_id, barcode FROM wms_stock_barcodes WHERE stock_id IN (159061, 159064) ORDER BY id`
|
||||
);
|
||||
console.log('== 两商品全部条码 ==');
|
||||
console.log(JSON.stringify(all, null, 2));
|
||||
await c.end();
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,51 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 回填 wms_wave_pick_task.batch_no_array(生产只读预检)。
|
||||
*
|
||||
* 从 wms_wave_pick_task_wave 按 task_id 聚合 wave_no(逗号分隔,按 id 升序),
|
||||
* 只更新 batch_no_array IS NULL 的任务,幂等可重复执行。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async (sql, repl) => {
|
||||
const rows = await s.query(sql, { replacements: repl, type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const total = await q('SELECT COUNT(*) AS c FROM wms_wave_pick_task');
|
||||
console.log('A. 任务总数:', JSON.stringify(total));
|
||||
|
||||
const nullable = await q("SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE batch_no_array IS NULL OR batch_no_array = ''");
|
||||
console.log('B. batch_no_array 为空的任务数:', JSON.stringify(nullable));
|
||||
|
||||
const backfillable = await q(
|
||||
"SELECT COUNT(DISTINCT tw.task_id) AS c FROM wms_wave_pick_task_wave tw "
|
||||
+ "INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id "
|
||||
+ "WHERE tw.wave_no IS NOT NULL AND tw.wave_no <> '' "
|
||||
+ "AND (t.batch_no_array IS NULL OR t.batch_no_array = '')"
|
||||
);
|
||||
console.log('C. 可回填的任务数(有 wave 记录且 batch_no_array 为空):', JSON.stringify(backfillable));
|
||||
|
||||
const byWaveRows = await q(
|
||||
"SELECT task_id, COUNT(*) AS c FROM wms_wave_pick_task_wave "
|
||||
+ "WHERE wave_no IS NOT NULL AND wave_no <> '' GROUP BY task_id ORDER BY c DESC LIMIT 5"
|
||||
);
|
||||
console.log('D. 单任务最多波次记录数样例:', JSON.stringify(byWaveRows));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,55 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本:核实生产库历史任务的领料人回填来源。
|
||||
* 1) wms_wave_batch 波次表 claim 字段现状;
|
||||
* 2) order_operation_log 中 ORDER_WAVE_CLAIM 领料日志数量与样例。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async sql => {
|
||||
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const waveClaim = await q(
|
||||
"SELECT wave_id, wave_no, claim_operator, claim_time FROM wms_wave_batch "
|
||||
+ "WHERE wave_no IN ('B2026081500040','B2026081500038','B2026081500084','B2026081500075','B2026081500023','B2026081500022','B2026081500085') "
|
||||
+ "ORDER BY wave_id DESC"
|
||||
);
|
||||
console.log('A. 波次表 claim 现状:', JSON.stringify(waveClaim, null, 2));
|
||||
|
||||
const claimLogTotal = await q(
|
||||
"SELECT COUNT(*) AS c FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'"
|
||||
);
|
||||
console.log('B. 领料日志总数:', JSON.stringify(claimLogTotal));
|
||||
|
||||
const claimLogSample = await q(
|
||||
"SELECT id, business_id, operation_code, operator_id, operator_name, message, create_time "
|
||||
+ "FROM order_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' "
|
||||
+ "ORDER BY id DESC LIMIT 10"
|
||||
);
|
||||
console.log('C. 领料日志最近10条:', JSON.stringify(claimLogSample, null, 2));
|
||||
|
||||
const taskClaim = await q(
|
||||
"SELECT id, task_no, pick_mode, source, claim_operator_id, claim_operator FROM wms_wave_pick_task "
|
||||
+ "WHERE id IN (259, 251, 229) ORDER BY id DESC"
|
||||
);
|
||||
console.log('D. 任务表 claim 现状:', JSON.stringify(taskClaim, null, 2));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,48 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本 v2:核实生产库历史领料人回填来源(wms_operation_log)。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async sql => {
|
||||
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const claimLogTotal = await q(
|
||||
"SELECT COUNT(*) AS c, COUNT(DISTINCT warehouse_id) AS wh "
|
||||
+ "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM'"
|
||||
);
|
||||
console.log('A. 领料日志总数/仓库数:', JSON.stringify(claimLogTotal));
|
||||
|
||||
const claimLogSample = await q(
|
||||
"SELECT id, business_type, business_id, operation_code, operator_id, operator_name, message, warehouse_id, created_at "
|
||||
+ "FROM wms_operation_log WHERE operation_code = 'ORDER_WAVE_CLAIM' "
|
||||
+ "ORDER BY id DESC LIMIT 5"
|
||||
);
|
||||
console.log('B. 领料日志最近5条:', JSON.stringify(claimLogSample, null, 2));
|
||||
|
||||
const claimLogByOperator = await q(
|
||||
"SELECT operator_id, operator_name, COUNT(*) AS c FROM wms_operation_log "
|
||||
+ "WHERE operation_code = 'ORDER_WAVE_CLAIM' GROUP BY operator_id, operator_name "
|
||||
+ "ORDER BY c DESC LIMIT 10"
|
||||
);
|
||||
console.log('C. 领料日志按操作人分布:', JSON.stringify(claimLogByOperator, null, 2));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,42 +0,0 @@
|
||||
'use strict';
|
||||
const mysql = require('mysql2/promise');
|
||||
(async () => {
|
||||
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
|
||||
|
||||
// 1. 请求日志表:本次重测 A(1530)/B(1531) 相关的接口调用日志
|
||||
const [sysLogs] = await c.query(`
|
||||
SELECT id, method, v, store_id, use_time, LEFT(body, 120) AS body_snip, created_at
|
||||
FROM wms_system_log
|
||||
WHERE body LIKE '%R20688012%' OR body LIKE '%R20688013%'
|
||||
OR body LIKE '%"receiving_id":1530%' OR body LIKE '%"receiving_id":1531%'
|
||||
OR body LIKE '%"ids":[1530%' OR body LIKE '%"ids":[1531%'
|
||||
OR body LIKE '%"entry_order_id":387%' OR body LIKE '%"entry_order_id":388%'
|
||||
ORDER BY id`);
|
||||
console.log('== wms_system_log 请求日志(本次重测相关,共 ' + sysLogs.length + ' 条) ==');
|
||||
console.log(JSON.stringify(sysLogs, null, 2));
|
||||
|
||||
// 2. 通知发送日志表(失败才写)
|
||||
const [notiLogs] = await c.query(`
|
||||
SELECT id, trace_id, store_id, warehouse_id, business_name, event, status, http_status, created_at
|
||||
FROM wms_notification_send_log
|
||||
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 2 DAY)
|
||||
ORDER BY id DESC LIMIT 10`);
|
||||
console.log('== wms_notification_send_log 最近两天(共 ' + notiLogs.length + ' 条) ==');
|
||||
console.log(JSON.stringify(notiLogs, null, 2));
|
||||
|
||||
// 3. 商品资料异步补全相关(无图片/无重量时应无写入)
|
||||
const [stockRow] = await c.query(
|
||||
`SELECT id, is_images, gross_weight FROM wms_stock_warehouse WHERE id IN (159061, 159064)`
|
||||
);
|
||||
console.log('== 商品资料快照(is_images/gross_weight,验证异步补全未触发) ==');
|
||||
console.log(JSON.stringify(stockRow, null, 2));
|
||||
|
||||
const [fileRefs] = await c.query(
|
||||
`SELECT id, business_type, business_id, file_id FROM wms_file_reference WHERE business_type='stock' AND business_id IN ('159061','159064')`
|
||||
);
|
||||
console.log('== wms_file_reference(stock 类型,共 ' + fileRefs.length + ' 行) ==');
|
||||
console.log(JSON.stringify(fileRefs, null, 2));
|
||||
|
||||
await c.end();
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,118 +0,0 @@
|
||||
/**
|
||||
* 临时校验:拦截规则防误判守卫(INTERCEPT_GUARD)修复效果。
|
||||
* 背景:机器人格式 "物流单号:SF123 拦截" 因含"物流"被守卫拦掉 → 规则未命中 → 静默不回信。
|
||||
* 用 fake ctx 直接实例化 inbox.rules Service,不连库、不写库。
|
||||
* 运行:node script/tmp-check-inbox-intercept-guard.cjs
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const RulesService = require('../app/service/inbox/rules');
|
||||
|
||||
function buildService(groupType, calls) {
|
||||
const svc = Object.create(RulesService.prototype);
|
||||
const registry = new Map([
|
||||
[ 'interceptWaybill', { groups: [ 'bound:store:after_sales' ] }],
|
||||
[ 'cancelIntercept', { groups: [ 'bound:store:after_sales' ] }],
|
||||
[ 'queryWeight', { groups: [ 'bound:store:after_sales' ] }],
|
||||
[ 'changeAddr', { groups: [ 'bound:store:after_sales' ] }],
|
||||
]);
|
||||
svc.ctx = {
|
||||
inboxContext: { group_type: groupType },
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
service: {
|
||||
inbox: {
|
||||
groups: {
|
||||
resolveActiveGroups: () => [ 'bound:store:after_sales' ],
|
||||
isFunctionAvailable: def => Array.isArray(def.groups) && def.groups.length > 0,
|
||||
},
|
||||
functions: {
|
||||
registry,
|
||||
callFunction: async (fn, params) => {
|
||||
calls.push({ fn, params });
|
||||
return { success: true, data: { direct_reply: true, message: `MOCK ${fn}` } };
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
return svc;
|
||||
}
|
||||
|
||||
const CASES = [
|
||||
// [说明, 正文, 期望是否已处理, 期望函数, 期望提取到的运单号(可选,'' 表示应为空)]
|
||||
[ '机器人格式-物流单号+拦截', '优禾康官方旗舰店LSFJY202609143442\n物流单号:SF5151786672496 拦截', true, 'interceptWaybill' ],
|
||||
[ '机器人格式-单号中间带空格', '罗斯福医疗器械专营店LSFJY202608307192\n物流单 号:SF5117392937919 拦截', true, 'interceptWaybill' ],
|
||||
[ '机器人格式-物流二字被空格断开', '优禾康番茄健康监测专卖店LSFJY202609022796\n物 流单号:SF6048940605674 拦截', true, 'interceptWaybill' ],
|
||||
[ '机器人格式-快递单号标签', '快递单号:SF5151786672496 拦截', true, 'interceptWaybill' ],
|
||||
[ '普通拦截请求', '拦截 SF5151786672496', true, 'interceptWaybill' ],
|
||||
[ '取消拦截(长词优先)', '取消拦截 SF5151786672496', true, 'cancelIntercept' ],
|
||||
[ '查询物流到哪了(不应拦截)', '这个件拦截的物流到哪了 SF5151786672496', false, null ],
|
||||
[ '标签外仍有物流查询词(不应拦截)', '物流单号:SF5151786672496 拦截,顺便查下这个物流到哪了', false, null ],
|
||||
[ '查快递(无拦截词)', '帮我查快递 SF5151786672496 到哪了', false, null ],
|
||||
[ '客服对话-物流显示签收+拦截有风险', '772077887170843:已登记退回,物流显示签收,已通知站点核实处理,因签收之后的包裹拦截有风险', false, null ],
|
||||
[ '客服对话-物流轨迹查询', '麻烦看下这个件拦截了没有,物流轨迹一直没更新 SF5151786672496', false, null ],
|
||||
[ '确认语静默', '好的', true, null ],
|
||||
// 2026-09-15 回归:14 位纯数字运单号被“日期时间戳”过滤器误杀,规则只能回引导语
|
||||
[ '改地址+14位中通运单号(不应被日期戳过滤)',
|
||||
'79140215263762 改地址 广东省广州市番禺区洛浦街道西三村友谊路1号菜鸟站(不打电话)收件人:王小姐19875119016',
|
||||
true, 'changeAddr', '79140215263762' ],
|
||||
[ '改地址+截断的11位手机号仍应被过滤(保留原行为)',
|
||||
'改地址 19875119016', true, 'changeAddr', '' ],
|
||||
[ '日期时间戳仍应被过滤(保留原行为)',
|
||||
'改地址 20260914201201', true, 'changeAddr', '' ],
|
||||
];
|
||||
|
||||
(async () => {
|
||||
let pass = 0;
|
||||
const fails = [];
|
||||
for (const [ desc, text, expectHandled, expectFn, expectKeyword ] of CASES) {
|
||||
const calls = [];
|
||||
const svc = buildService('store', calls);
|
||||
const res = await svc.handle(text);
|
||||
const handled = !!res.handled;
|
||||
const fn = res.fn || null;
|
||||
const keyword = res.params && res.params.keyword != null ? String(res.params.keyword) : '';
|
||||
let ok = handled === expectHandled && fn === expectFn;
|
||||
if (ok && expectKeyword !== undefined) {
|
||||
ok = expectKeyword === '' ? keyword === '' : keyword.includes(expectKeyword);
|
||||
}
|
||||
if (ok) pass++;
|
||||
else fails.push({ desc, expectHandled, expectFn, expectKeyword, handled, fn, keyword, silent: !!res.silent, calls });
|
||||
console.log(
|
||||
`${ok ? '✅' : '❌'} ${desc} → handled=${handled} fn=${fn} silent=${!!res.silent} ` +
|
||||
`keyword=${JSON.stringify(keyword)} ` +
|
||||
`reply=${res.reply ? JSON.stringify(String(res.reply).slice(0, 40)) : '-'}`
|
||||
);
|
||||
}
|
||||
console.log(`\n结果:${pass}/${CASES.length} 通过`);
|
||||
if (fails.length > 0) {
|
||||
console.log('失败明细:', JSON.stringify(fails, null, 2));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
// ---- 生产群上下文模拟:真实分组解析 + 函数可用性(groups.js 为纯逻辑,不连库)----
|
||||
const GroupsService = require('../app/service/inbox/groups');
|
||||
const prodCtx = {
|
||||
inboxContext: {
|
||||
warehouse_id: 1000028,
|
||||
store_id: 1000249,
|
||||
group_type: 'store',
|
||||
sub_type: 'after_sales',
|
||||
group_id: '47357811653@chatroom',
|
||||
},
|
||||
logger: { info() {}, warn() {}, error() {} },
|
||||
};
|
||||
const groupsSvc = Object.create(GroupsService.prototype);
|
||||
groupsSvc.ctx = prodCtx;
|
||||
const active = groupsSvc.resolveActiveGroups();
|
||||
const available = groupsSvc.isFunctionAvailable(
|
||||
{ groups: [ 'bound:warehouse:customer_service', 'bound:store:after_sales' ] },
|
||||
active
|
||||
);
|
||||
console.log(
|
||||
'\n生产群 47357811653@chatroom(store/after_sales/store_id=1000249) ' +
|
||||
`activeGroups=${JSON.stringify(active)} interceptWaybill可用=${available}`
|
||||
);
|
||||
if (!available) process.exitCode = 1;
|
||||
})();
|
||||
|
||||
@ -1,47 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 检查保留的 8 条今日前订单的状态字段,定位第一池查询返回 0 的原因。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT id, create_at, items_hash, wave_id, step, post_status, storage_status,
|
||||
print_status, status, outbound_status, intercept_status, lock_status
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE id IN (1245, 3014, 5547, 6327, 6462, 7797, 7909, 8455)
|
||||
ORDER BY id ASC`
|
||||
);
|
||||
console.log('===== 保留8条状态 =====');
|
||||
console.log(JSON.stringify(rows));
|
||||
|
||||
const [ hashRows ] = await connection.query(
|
||||
`SELECT items_hash, COUNT(1) AS cnt, SUM(CASE WHEN wave_id = 0 THEN 1 ELSE 0 END) AS waveZero
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE items_hash IN (SELECT items_hash FROM wms_order_delivery_100000 WHERE id IN (1245, 3014, 5547))
|
||||
GROUP BY items_hash`
|
||||
);
|
||||
console.log('===== 同结构计数 =====');
|
||||
console.log(JSON.stringify(hashRows));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,55 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 检查负向验证订单的实际快递字段与最新订单列表。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ recentOrders ] = await connection.query(
|
||||
`SELECT id, sys_platform_code, logistics_code, sys_logistics_code,
|
||||
post_status, storage_status, step, wave_id
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE id >= 122595
|
||||
ORDER BY id ASC
|
||||
LIMIT 20`
|
||||
);
|
||||
console.log('===== 最近订单 =====');
|
||||
console.log(JSON.stringify(recentOrders));
|
||||
|
||||
const [ expressRows ] = await connection.query(
|
||||
`SELECT order_id, waybill_code, logistics_code, logistics_name, platform_code, status
|
||||
FROM wms_order_express
|
||||
WHERE order_id >= 122595
|
||||
ORDER BY id DESC
|
||||
LIMIT 20`
|
||||
);
|
||||
console.log('===== 最近运单 =====');
|
||||
console.log(JSON.stringify(expressRows));
|
||||
|
||||
const [ policyRow ] = await connection.query(
|
||||
`SELECT policy_config FROM wms_store_warehouse WHERE id = 100000`
|
||||
);
|
||||
console.log('===== 合约100000 policy_config =====');
|
||||
console.log(JSON.stringify(policyRow));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,26 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 只读排查脚本:抓取 2026-09-12 16:25:0x ~ 16:25:4x(CST)窗口内与订单分表结构/重建相关的日志。
|
||||
* 仅执行 grep 等只读命令,不做任何写入或清理。
|
||||
*/
|
||||
|
||||
const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs');
|
||||
|
||||
function buildRemoteScript() {
|
||||
return [
|
||||
'set -uo pipefail',
|
||||
'D=/root/logs/wms',
|
||||
'echo "===ALERT_WINDOW==="',
|
||||
'for f in "$D/wms-web.log.2026-09-12" "$D/common-error.log.2026-09-12" "$D/wms-web.log.2026-09-13"; do',
|
||||
' [ -f "$f" ] || continue',
|
||||
' echo "--- $f ---"',
|
||||
' grep -a "2026-09-12 16:2[4-6]:" "$f" 2>/dev/null | grep -aiE "alter|backup|重建|schema|watermark|自增|order_delivery" | head -20 || true',
|
||||
'done',
|
||||
'echo "===FACTORY_WARNINGS==="',
|
||||
'grep -ah "order_delivery_factory\\|订单工厂\\|alterManagedTableSchema\\|ensureAutoIncrementWatermark" "$D/wms-web.log.2026-09-12" 2>/dev/null | tail -25 || true',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const config = loadDeployConfig('production');
|
||||
console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' }));
|
||||
@ -1,117 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 检查本地开发库中 OTHER 平台/快递相关数据现状。
|
||||
*
|
||||
* 用于定位「其他平台(OTHER)/其他快递(OTHER)分配不了运单号」的数据缺失点:
|
||||
* - wms_platform 是否已有 OTHER 平台记录
|
||||
* - wms_express 是否已有 OTHER 快递记录
|
||||
* - wms_print_platform 是否已有 platform_code=OTHER 记录
|
||||
* - wms_express_interface 是否已有 platform_code=OTHER 的接口配置
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
/**
|
||||
* 查询本地开发库并输出结果。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ platformRows ] = await connection.query(
|
||||
`SELECT code, name, print_platform_id FROM wms_platform ORDER BY code ASC`
|
||||
);
|
||||
console.log('===== wms_platform =====');
|
||||
platformRows.forEach(row => {
|
||||
console.log(`code=${row.code}, name=${row.name}, print_platform_id=${row.print_platform_id}`);
|
||||
});
|
||||
|
||||
const [ expressOtherRows ] = await connection.query(
|
||||
`SELECT code, name FROM wms_express WHERE UPPER(code) = 'OTHER'`
|
||||
);
|
||||
console.log('===== wms_express code=OTHER =====');
|
||||
console.log(JSON.stringify(expressOtherRows));
|
||||
|
||||
const [ printPlatformRows ] = await connection.query(
|
||||
`SELECT * FROM wms_print_platform WHERE id = 9 OR UPPER(platform_code) = 'OTHER' OR UPPER(request_platform_code) = 'OTHER'`
|
||||
);
|
||||
console.log('===== wms_print_platform id=9 / OTHER =====');
|
||||
console.log(JSON.stringify(printPlatformRows));
|
||||
|
||||
const [ expressInterfaceRows ] = await connection.query(
|
||||
`SELECT id, warehouse_id, platform_code, express_code, sys_express_code, is_enabled
|
||||
FROM wms_express_interface
|
||||
WHERE UPPER(platform_code) = 'OTHER' OR UPPER(express_code) = 'OTHER' OR UPPER(sys_express_code) = 'OTHER'
|
||||
LIMIT 20`
|
||||
);
|
||||
console.log('===== wms_express_interface 含 OTHER =====');
|
||||
console.log(JSON.stringify(expressInterfaceRows));
|
||||
|
||||
const [ allInterfaceRows ] = await connection.query(
|
||||
`SELECT warehouse_id, platform_code, COUNT(1) AS cnt
|
||||
FROM wms_express_interface
|
||||
GROUP BY warehouse_id, platform_code
|
||||
ORDER BY warehouse_id, platform_code`
|
||||
);
|
||||
console.log('===== wms_express_interface 按仓库+平台统计 =====');
|
||||
console.log(JSON.stringify(allInterfaceRows));
|
||||
|
||||
const [ contractRows ] = await connection.query(
|
||||
`SELECT id, store_id, warehouse_id, policy_config
|
||||
FROM wms_store_warehouse
|
||||
ORDER BY id DESC
|
||||
LIMIT 10`
|
||||
);
|
||||
console.log('===== wms_store_warehouse 最近合约 policy_config =====');
|
||||
contractRows.forEach(row => {
|
||||
let policyText = String(row.policy_config || '');
|
||||
if (row.policy_config && typeof row.policy_config === 'object') {
|
||||
policyText = JSON.stringify(row.policy_config);
|
||||
}
|
||||
console.log(`id=${row.id}, store=${row.store_id}, warehouse=${row.warehouse_id}, policy=${policyText.slice(0, 400)}`);
|
||||
});
|
||||
|
||||
const [ tableRows ] = await connection.query(
|
||||
`SHOW TABLES`
|
||||
);
|
||||
console.log('===== 全部表名 =====');
|
||||
const allTableNames = tableRows.map(row => Object.values(row)[0]);
|
||||
console.log(allTableNames.filter(name => /order|delivery/i.test(name)).join('\n'));
|
||||
|
||||
const [ orderOtherRows ] = await connection.query(
|
||||
`SELECT id, sys_platform_code, logistics_code, post_status, step, status, create_at
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE sys_platform_code = 'OTHER' OR logistics_code = 'OTHER'
|
||||
ORDER BY id DESC
|
||||
LIMIT 20`
|
||||
);
|
||||
console.log('===== 仓库100000 OTHER 订单 =====');
|
||||
console.log(JSON.stringify(orderOtherRows));
|
||||
|
||||
const [ failLogRows ] = await connection.query(
|
||||
`SELECT business_id, extras, create_at
|
||||
FROM wms_operation_log
|
||||
WHERE operation_code = 'ORDER_EXPRESS_ALLOCATE_FAILED'
|
||||
ORDER BY id DESC
|
||||
LIMIT 10`
|
||||
);
|
||||
console.log('===== 最近快递分配失败日志 =====');
|
||||
console.log(JSON.stringify(failLogRows));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,87 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const MIGRATIONS_DIR = path.join(ROOT, 'database', 'migrations');
|
||||
|
||||
async function main() {
|
||||
// 1. 收集本地所有迁移文件
|
||||
const allFiles = fs.readdirSync(MIGRATIONS_DIR).filter(f => f.endsWith('.js')).sort();
|
||||
console.log(`[本地] 迁移文件总数: ${allFiles.length}`);
|
||||
|
||||
// 2. 连接生产数据库
|
||||
const dbConfig = {
|
||||
host: '112.124.21.102',
|
||||
port: 3306,
|
||||
user: 'wms',
|
||||
password: 'P6j3YTHTpirepYWz',
|
||||
database: 'wms',
|
||||
};
|
||||
|
||||
const sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
|
||||
host: dbConfig.host,
|
||||
port: dbConfig.port,
|
||||
dialect: 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await sequelize.authenticate();
|
||||
console.log('[DB] 生产数据库连接成功');
|
||||
} catch (e) {
|
||||
console.error('[DB] 生产数据库连接失败:', e.message);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// 3. 检查 SequelizeMeta 表是否存在
|
||||
let appliedNames = [];
|
||||
try {
|
||||
const [rows] = await sequelize.query('SELECT name FROM SequelizeMeta ORDER BY name');
|
||||
appliedNames = rows.map(r => (typeof r === 'string' ? r : r.name)).filter(Boolean);
|
||||
} catch (e) {
|
||||
console.error('[DB] 读取 SequelizeMeta 失败:', e.message);
|
||||
await sequelize.close();
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
console.log(`[DB] SequelizeMeta 已记录迁移数: ${appliedNames.length}`);
|
||||
|
||||
// 4. 找出未执行的迁移
|
||||
const appliedSet = new Set(appliedNames);
|
||||
const pending = allFiles.filter(f => !appliedSet.has(f));
|
||||
const archived = allFiles.filter(f => f.startsWith('archive/'));
|
||||
|
||||
console.log(`\n========== 结果汇总 ==========`);
|
||||
console.log(`本地迁移文件总数: ${allFiles.length}`);
|
||||
console.log(`已执行 (SequelizeMeta): ${appliedNames.length}`);
|
||||
console.log(`未执行 (pending): ${pending.length}`);
|
||||
console.log(`===============================\n`);
|
||||
|
||||
if (pending.length === 0) {
|
||||
console.log('✅ 所有迁移脚本均已执行,无 pending migration。');
|
||||
} else {
|
||||
console.log(`❌ 发现 ${pending.length} 个未执行的迁移脚本:\n`);
|
||||
pending.forEach((f, i) => {
|
||||
console.log(` ${String(i + 1).padStart(3, ' ')}. ${f}`);
|
||||
});
|
||||
|
||||
// 额外检查:有没有本地没有但 DB 已记录的(可能被删除了)
|
||||
const localSet = new Set(allFiles);
|
||||
const orphanInDb = appliedNames.filter(n => !localSet.has(n));
|
||||
if (orphanInDb.length > 0) {
|
||||
console.log(`\n⚠️ DB 中记录了 ${orphanInDb.length} 个本地已不存在的迁移(可能已被删除):`);
|
||||
orphanInDb.forEach(n => console.log(` - ${n}`));
|
||||
}
|
||||
}
|
||||
|
||||
await sequelize.close();
|
||||
console.log('\n[DONE] 检查完成');
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('脚本执行异常:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,64 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时脚本:影响范围确认(只读)——
|
||||
* wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 的回填范围。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async sql => {
|
||||
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const total = await q(
|
||||
"SELECT COUNT(*) AS c FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2"
|
||||
);
|
||||
console.log('A. 目标行数 (pick_mode=1 AND source=2):', JSON.stringify(total));
|
||||
|
||||
const byStatus = await q(
|
||||
'SELECT status, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 GROUP BY status ORDER BY status'
|
||||
);
|
||||
console.log('B. 按任务状态分布:', JSON.stringify(byStatus));
|
||||
|
||||
const byWaveCount = await q(
|
||||
'SELECT wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode = 1 AND source = 2 GROUP BY wave_count ORDER BY wave_count'
|
||||
);
|
||||
console.log('C. 按 wave_count 分布(确认单波次):', JSON.stringify(byWaveCount));
|
||||
|
||||
const byTaskNoPrefix = await q(
|
||||
"SELECT LEFT(task_no, 2) AS prefix, COUNT(*) AS cnt FROM wms_wave_pick_task "
|
||||
+ "WHERE pick_mode = 1 AND source = 2 GROUP BY prefix"
|
||||
);
|
||||
console.log('D. task_no 前缀分布(PK=拣货创建):', JSON.stringify(byTaskNoPrefix));
|
||||
|
||||
const waveRel = await q(
|
||||
'SELECT COUNT(*) AS c FROM wms_wave_pick_task t '
|
||||
+ 'INNER JOIN wms_wave_pick_task_wave tw ON tw.task_id = t.id '
|
||||
+ 'WHERE t.pick_mode = 1 AND t.source = 2'
|
||||
);
|
||||
console.log('E. 目标任务中已有波次关联记录的任务数:', JSON.stringify(waveRel));
|
||||
|
||||
const noWaveRel = await q(
|
||||
'SELECT COUNT(*) AS c FROM wms_wave_pick_task t '
|
||||
+ 'LEFT JOIN wms_wave_pick_task_wave tw ON tw.task_id = t.id '
|
||||
+ 'WHERE t.pick_mode = 1 AND t.source = 2 AND tw.task_id IS NULL'
|
||||
);
|
||||
console.log('F. 目标任务中无波次关联记录的任务数:', JSON.stringify(noWaveRel));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,15 +0,0 @@
|
||||
'use strict';
|
||||
const mysql = require('mysql2/promise');
|
||||
(async () => {
|
||||
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
|
||||
const [r] = await c.query(
|
||||
`SELECT id, store_id, warehouse_id, warehouse_use_status,
|
||||
JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct,
|
||||
JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick
|
||||
FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000`
|
||||
);
|
||||
console.log('store_warehouse:', JSON.stringify(r, null, 2));
|
||||
const [r2] = await c.query('SELECT id, store_id, warehouse_id, status, is_review, storage_status FROM wms_receiving WHERE id IN (1521,1522,1523,1524)');
|
||||
console.log('receivings:', JSON.stringify(r2, null, 2));
|
||||
await c.end();
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,12 +0,0 @@
|
||||
'use strict';
|
||||
const mysql = require('mysql2/promise');
|
||||
(async () => {
|
||||
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
|
||||
const [p] = await c.query("SELECT id, path, meta_title FROM wms_permission WHERE path LIKE 'storage.inventory%' AND type='api'");
|
||||
console.log('perms:', JSON.stringify(p));
|
||||
const [r] = await c.query('SELECT id, permissions FROM wms_role WHERE id IN (7)');
|
||||
console.log('roles:', JSON.stringify(r));
|
||||
const [col] = await c.query('SHOW COLUMNS FROM wms_role');
|
||||
console.log('cols:', col.map(x => x.Field + ':' + x.Type).join(', '));
|
||||
await c.end();
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,28 +0,0 @@
|
||||
'use strict';
|
||||
const mysql = require('mysql2/promise');
|
||||
(async () => {
|
||||
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
|
||||
|
||||
// 两个测试商品在 wms_storage 中的全部行
|
||||
const [rows] = await c.query(`
|
||||
SELECT id, warehouse_id, store_id, space_id, stock_id, batch_no, inventory_type,
|
||||
quantity, locked_quantity, available_quantity,
|
||||
inbound_order_no, receiving_id, entry_order_id, inbound_time
|
||||
FROM wms_storage
|
||||
WHERE stock_id IN (159061, 159064)
|
||||
ORDER BY id`);
|
||||
console.log('== wms_storage 中两个测试商品的全部行(共 ' + rows.length + ' 行) ==');
|
||||
console.log(JSON.stringify(rows, null, 2));
|
||||
|
||||
// 两商品的库位流水(逐笔证据)
|
||||
const [txns] = await c.query(`
|
||||
SELECT id, order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no
|
||||
FROM wms_storage_transaction
|
||||
WHERE stock_id IN (159061, 159064)
|
||||
ORDER BY id`);
|
||||
console.log('== wms_storage_transaction 两商品逐笔流水(共 ' + txns.length + ' 条) ==');
|
||||
console.log(JSON.stringify(txns, null, 2));
|
||||
|
||||
await c.end();
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,41 +0,0 @@
|
||||
'use strict';
|
||||
const mysql = require('mysql2/promise');
|
||||
(async () => {
|
||||
const c = await mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
|
||||
|
||||
// 1. wms_storage 当前状态(A/B 共用的累加行)
|
||||
const [storages] = await c.query(`
|
||||
SELECT id, space_id, stock_id, batch_no, quantity, locked_quantity, available_quantity,
|
||||
inbound_order_no, receiving_id, entry_order_id, inbound_time
|
||||
FROM wms_storage WHERE id IN (408, 409)`);
|
||||
console.log('== wms_storage 当前行(408/409) ==');
|
||||
console.log(JSON.stringify(storages, null, 2));
|
||||
|
||||
// 2. wms_stock_warehouse 当前数量
|
||||
const [stocks] = await c.query(`
|
||||
SELECT id, item_code, quantity, locked_quantity, is_valid
|
||||
FROM wms_stock_warehouse WHERE id IN (159061, 159064)`);
|
||||
console.log('== wms_stock_warehouse 当前数量 ==');
|
||||
console.log(JSON.stringify(stocks, null, 2));
|
||||
|
||||
// 3. A(入库单 387)与 B(入库单 388)各自的库位流水(证明 storage 写入)
|
||||
const [storageTxns] = await c.query(`
|
||||
SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no
|
||||
FROM wms_storage_transaction
|
||||
WHERE order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008')
|
||||
ORDER BY id`);
|
||||
console.log('== wms_storage_transaction:A(387)/B(388) 的库位流水 ==');
|
||||
console.log(JSON.stringify(storageTxns, null, 2));
|
||||
|
||||
// 4. A/B 各自的商品流水(证明 stock_warehouse 数量变更)
|
||||
const [stockTxns] = await c.query(`
|
||||
SELECT order_no, transaction_type, stock_id, quantity, before_quantity, after_quantity, entry_order_id
|
||||
FROM wms_stock_transaction
|
||||
WHERE entry_order_id IN (387, 388) OR order_no IN ('SCRK202608240007','SCRK202608240008')
|
||||
ORDER BY id`);
|
||||
console.log('== wms_stock_transaction:A(387)/B(388) 的商品流水 ==');
|
||||
console.log(JSON.stringify(stockTxns, null, 2));
|
||||
|
||||
await c.end();
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,55 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 抽查 UPDATE 影响范围。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ sample ] = await connection.query(
|
||||
`SELECT id, create_at
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE id BETWEEN 1591 AND 1660
|
||||
ORDER BY id ASC
|
||||
LIMIT 15`
|
||||
);
|
||||
console.log('===== 1591-1660 区间 =====');
|
||||
console.log(JSON.stringify(sample));
|
||||
|
||||
const [ todayCount ] = await connection.query(
|
||||
`SELECT COUNT(1) AS cnt
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE create_at >= '2026-09-05 16:00:00'`
|
||||
);
|
||||
console.log('===== 全表今天订单数 =====');
|
||||
console.log(JSON.stringify(todayCount));
|
||||
|
||||
const [ keepRows ] = await connection.query(
|
||||
`SELECT id, create_at
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE id IN (1245, 3014, 5547, 6327, 6462, 7797, 7909, 8455)
|
||||
ORDER BY id ASC`
|
||||
);
|
||||
console.log('===== 保留8条 =====');
|
||||
console.log(JSON.stringify(keepRows));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,63 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时校验:video_record_request 模型定义与 wms_video_record_request 表结构是否一致。
|
||||
* 仅只读(describeTable + findAll limit 1),默认连本地开发库:
|
||||
* Remove-Item Env:\NODE_ENV; $env:WMS_DB_TARGET='local'; node script/tmp-check-video-record-request.cjs
|
||||
*/
|
||||
|
||||
const SequelizeLib = require('sequelize');
|
||||
const dbConfig = require('../database/config');
|
||||
|
||||
/**
|
||||
* 主流程:加载模型定义并与实际表结构比对。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function main() {
|
||||
const config = dbConfig.production;
|
||||
console.log(`[check] target=${config.host}:${config.port}/${config.database} (${(dbConfig.dbTarget || {}).source})`);
|
||||
|
||||
const sequelize = new SequelizeLib(config.database, config.username, config.password, {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
dialect: config.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const app = {
|
||||
Sequelize: SequelizeLib,
|
||||
model: { define: (name, attrs, opts) => sequelize.define(name, attrs, opts) },
|
||||
};
|
||||
|
||||
try {
|
||||
const model = require('../app/model/video_record_request')(app);
|
||||
const tableInfo = await sequelize.getQueryInterface().describeTable('wms_video_record_request');
|
||||
const tableCols = Object.keys(tableInfo);
|
||||
const modelCols = Object.keys(model.rawAttributes);
|
||||
|
||||
const missingInModel = tableCols.filter(col => !modelCols.includes(col));
|
||||
const missingInTable = modelCols.filter(col => !tableCols.includes(col));
|
||||
|
||||
console.log('[check] modelCols =', modelCols.join(','));
|
||||
console.log('[check] missingInModel =', JSON.stringify(missingInModel));
|
||||
console.log('[check] missingInTable =', JSON.stringify(missingInTable));
|
||||
|
||||
const rows = await model.findAll({ limit: 1, raw: true });
|
||||
console.log('[check] findAll ok, rows =', rows.length);
|
||||
|
||||
// 状态机枚举可达性(只读:构造 where 不执行写入)
|
||||
const counting = await model.count({ where: { status: 'pending' } });
|
||||
console.log('[check] count(status=pending) =', counting);
|
||||
|
||||
console.log(missingInModel.length === 0 && missingInTable.length === 0
|
||||
? '[check] OK: 模型与表结构一致'
|
||||
: '[check] MISMATCH: 存在差异');
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error('[check] FAILED:', err.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@ -1,28 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 只读排查脚本:抓取生产环境 2026-09-12 08:2x 波次自动终结(wave-batch-closure)日志。
|
||||
*
|
||||
* 目的:确认 08:25:33 那一轮 candidate/closed 数量,判断是"整表读空"还是"仅这 6 个波次读空"。
|
||||
* 仅执行 grep / zcat 等只读命令,不做任何写入或清理。
|
||||
*/
|
||||
|
||||
const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs');
|
||||
|
||||
function buildRemoteScript() {
|
||||
return [
|
||||
'set -uo pipefail',
|
||||
'D=/root/logs/wms',
|
||||
'echo "===FILES==="',
|
||||
'ls -lh "$D" 2>&1 | head -12 || true',
|
||||
'echo "===NONZERO_CLOSED_0912==="',
|
||||
'grep -ah "本轮完成 closed=" "$D/wms-web.log.2026-09-12" 2>/dev/null | grep -av "closed=0 " | tail -20 || true',
|
||||
'echo "===CLOSURE_DETAIL_0912==="',
|
||||
'grep -ah "波次终结结果" "$D/wms-web.log.2026-09-12" 2>/dev/null | tail -20 || true',
|
||||
'echo "===WINDOW_0825==="',
|
||||
'grep -ah "2026-09-12 08:2" "$D/wms-web.log.2026-09-12" 2>/dev/null | grep -a "本轮完成" | tail -10 || true',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const config = loadDeployConfig('production');
|
||||
console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' }));
|
||||
@ -1,65 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 检查联调订单实际字段与任务状态。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ orderRows ] = await connection.query(
|
||||
`SELECT id, sys_platform_code, logistics_code, sys_logistics_code,
|
||||
post_status, storage_status, step, status, wave_id, wave_scan_result,
|
||||
wave_strategy_version, items_hash
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE id IN (122546, 122547, 122548)
|
||||
ORDER BY id ASC`
|
||||
);
|
||||
console.log('===== 联调订单字段 =====');
|
||||
console.log(JSON.stringify(orderRows));
|
||||
|
||||
const [ taskRows ] = await connection.query(
|
||||
`SELECT id, task_no, status, pick_mode, wave_id, pick_user_id
|
||||
FROM wms_wave_pick_task
|
||||
WHERE warehouse_id = 100000 AND status IN (0, 1)
|
||||
ORDER BY id DESC
|
||||
LIMIT 5`
|
||||
);
|
||||
console.log('===== 活跃拣货任务 =====');
|
||||
console.log(JSON.stringify(taskRows));
|
||||
|
||||
const [ strategyRows ] = await connection.query(
|
||||
`SELECT id, strategy_name, strategy_type, batch_mode, min_same_structure, status
|
||||
FROM wms_wave_strategy
|
||||
WHERE warehouse_id = 100000
|
||||
ORDER BY id DESC
|
||||
LIMIT 5`
|
||||
);
|
||||
console.log('===== 最近策略 =====');
|
||||
console.log(JSON.stringify(strategyRows));
|
||||
|
||||
const [ versionRows ] = await connection.query(
|
||||
`SELECT subject_config FROM wms_store_warehouse WHERE id = 100000`
|
||||
);
|
||||
console.log('===== 仓库 subject_config(版本) =====');
|
||||
console.log(JSON.stringify(versionRows));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,85 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 排查联调问题:
|
||||
* 1. 历史成功订单(122442)使用的商品 stock_id(可用于选一个能完整走通的商品);
|
||||
* 2. 订单 122546 储位分配失败原因;
|
||||
* 3. 商品 159063 的库位库存分布。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ historyItems ] = await connection.query(
|
||||
`SELECT order_id, item_id, stock_id, item_name, plan_qty
|
||||
FROM wms_order_items_100000
|
||||
WHERE order_id IN (122442, 122546)
|
||||
ORDER BY order_id ASC`
|
||||
);
|
||||
console.log('===== 历史成功订单/联调订单明细 =====');
|
||||
console.log(JSON.stringify(historyItems));
|
||||
|
||||
const [ logColumns ] = await connection.query(
|
||||
`SHOW COLUMNS FROM wms_operation_log`
|
||||
);
|
||||
console.log('===== wms_operation_log 列 =====');
|
||||
console.log(JSON.stringify(logColumns.map(item => item.Field)));
|
||||
|
||||
const [ failLogs ] = await connection.query(
|
||||
`SELECT business_id, operation_code, message
|
||||
FROM wms_operation_log
|
||||
WHERE business_id IN ('122546', '122547') AND operation_code LIKE '%STORAGE%'
|
||||
ORDER BY id DESC
|
||||
LIMIT 10`
|
||||
);
|
||||
console.log('===== 储位分配相关日志 =====');
|
||||
console.log(JSON.stringify(failLogs));
|
||||
|
||||
const [ stockWarehouseRows ] = await connection.query(
|
||||
`SELECT id, store_id, quantity, locked_quantity, prohibited_id, is_valid, deleted_at
|
||||
FROM wms_stock_warehouse WHERE id = 101397`
|
||||
);
|
||||
console.log('===== 商品101397 主表 =====');
|
||||
console.log(JSON.stringify(stockWarehouseRows));
|
||||
|
||||
const [ stockLocationRows ] = await connection.query(
|
||||
`SELECT id, stock_id, location_id, qty
|
||||
FROM wms_stock_location WHERE stock_id = 101397 LIMIT 10`
|
||||
);
|
||||
console.log('===== 商品101397 库位库存 =====');
|
||||
console.log(JSON.stringify(stockLocationRows));
|
||||
|
||||
const [ storageAllocRows ] = await connection.query(
|
||||
`SELECT * FROM wms_order_storage_allocation
|
||||
WHERE order_id IN (122546, 122547)
|
||||
ORDER BY id DESC
|
||||
LIMIT 10`
|
||||
);
|
||||
console.log('===== 122546/122547 储位分配记录 =====');
|
||||
console.log(JSON.stringify(storageAllocRows));
|
||||
|
||||
const [ storageTables ] = await connection.query(
|
||||
`SHOW TABLES LIKE '%storage%'`
|
||||
);
|
||||
console.log('===== storage 相关表 =====');
|
||||
console.log(JSON.stringify(storageTables));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,75 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本:核实生产库 wms_wave_pick_task 的 pick_mode / source / wave_count /
|
||||
* batch_no 写入情况,以及团购任务(pick_mode=1/5)是否单波次。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
console.log('=== 1) 主表按 source/pick_mode 统计(batch_no / batch_no_array 非空数、wave_count 分布) ===');
|
||||
const [ rows1 ] = await s.query(`
|
||||
SELECT t.source,
|
||||
t.pick_mode,
|
||||
COUNT(*) AS cnt,
|
||||
SUM(t.batch_no IS NOT NULL AND t.batch_no <> '') AS with_batch_no,
|
||||
SUM(t.batch_no_array IS NOT NULL AND t.batch_no_array <> '') AS with_batch_no_array,
|
||||
MIN(t.wave_count) AS min_wave_count,
|
||||
MAX(t.wave_count) AS max_wave_count
|
||||
FROM wms_wave_pick_task t
|
||||
GROUP BY t.source, t.pick_mode
|
||||
ORDER BY t.source, t.pick_mode
|
||||
`, { type: Sequelize.QueryTypes.SELECT });
|
||||
console.table(rows1);
|
||||
|
||||
console.log('=== 2) 团购任务(pick_mode IN (1,5))与波次关联表记录数分布(判断单波次/多波次) ===');
|
||||
const [ rows2 ] = await s.query(`
|
||||
SELECT t.source,
|
||||
t.pick_mode,
|
||||
t.wave_count,
|
||||
COUNT(*) AS cnt
|
||||
FROM wms_wave_pick_task t
|
||||
WHERE t.pick_mode IN (1, 5)
|
||||
GROUP BY t.source, t.pick_mode, t.wave_count
|
||||
ORDER BY t.source, t.pick_mode, t.wave_count
|
||||
`, { type: Sequelize.QueryTypes.SELECT });
|
||||
console.table(rows2);
|
||||
|
||||
console.log('=== 3) 团购任务主表 wave_id 非空占比与 wave_count 实际值(抽样) ===');
|
||||
const [ rows3 ] = await s.query(`
|
||||
SELECT t.id, t.task_no, t.source, t.pick_mode, t.wave_id, t.wave_count, t.batch_no, t.batch_no_array,
|
||||
(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows
|
||||
FROM wms_wave_pick_task t
|
||||
WHERE t.pick_mode IN (1, 5)
|
||||
ORDER BY t.id DESC
|
||||
LIMIT 20
|
||||
`, { type: Sequelize.QueryTypes.SELECT });
|
||||
console.table(rows3);
|
||||
|
||||
console.log('=== 4) wms_wave_pick_task_wave 中单任务波次数 > 1 的任务(按 task_id 分组) ===');
|
||||
const [ rows4 ] = await s.query(`
|
||||
SELECT tw.task_id, t.source, t.pick_mode, t.wave_count, COUNT(*) AS task_wave_rows
|
||||
FROM wms_wave_pick_task_wave tw
|
||||
INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id
|
||||
GROUP BY tw.task_id, t.source, t.pick_mode, t.wave_count
|
||||
HAVING COUNT(*) > 1
|
||||
ORDER BY tw.task_id DESC
|
||||
LIMIT 20
|
||||
`, { type: Sequelize.QueryTypes.SELECT });
|
||||
console.table(rows4);
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,68 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本(v2):JSON 输出核实生产库 wms_wave_pick_task 的
|
||||
* pick_mode/source 分布与团购任务波次数。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const [ total ] = await s.query('SELECT COUNT(*) AS c FROM wms_wave_pick_task', { type: Sequelize.QueryTypes.SELECT });
|
||||
console.log('A. 主表总数:', JSON.stringify(total));
|
||||
|
||||
const [ byMode ] = await s.query(
|
||||
'SELECT pick_mode, source, COUNT(*) AS cnt FROM wms_wave_pick_task GROUP BY pick_mode, source ORDER BY pick_mode, source',
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('B. pick_mode/source 分布:', JSON.stringify(byMode));
|
||||
|
||||
const [ byWaveCount ] = await s.query(
|
||||
'SELECT pick_mode, wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode IN (1, 5) GROUP BY pick_mode, wave_count ORDER BY pick_mode, wave_count',
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('C. 团购任务 wave_count 分布:', JSON.stringify(byWaveCount));
|
||||
|
||||
const [ multiWave ] = await s.query(
|
||||
'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows '
|
||||
+ 'FROM wms_wave_pick_task_wave tw '
|
||||
+ 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id '
|
||||
+ 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count '
|
||||
+ 'ORDER BY tw.task_id DESC LIMIT 10',
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('D. 任务-波次关联(最近10条):', JSON.stringify(multiWave));
|
||||
|
||||
const [ taskWaveTotal ] = await s.query('SELECT COUNT(*) AS c FROM wms_wave_pick_task_wave', { type: Sequelize.QueryTypes.SELECT });
|
||||
console.log('E. 波次关联表总数:', JSON.stringify(taskWaveTotal));
|
||||
|
||||
const [ sampleGroup ] = await s.query(
|
||||
"SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, "
|
||||
+ "(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows "
|
||||
+ "FROM wms_wave_pick_task t WHERE pick_mode = 1 ORDER BY id DESC LIMIT 10",
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('F. 团购任务最近10条:', JSON.stringify(sampleGroup));
|
||||
|
||||
const [ sampleScatter ] = await s.query(
|
||||
"SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, "
|
||||
+ "(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows "
|
||||
+ "FROM wms_wave_pick_task t WHERE pick_mode IN (2, 3, 4) ORDER BY id DESC LIMIT 10",
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('G. 散单任务最近10条:', JSON.stringify(sampleScatter));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,76 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本(v3):修正 SELECT 结果解构,JSON 输出核实生产库
|
||||
* wms_wave_pick_task 的 pick_mode/source 分布与团购任务波次数。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const q = async sql => {
|
||||
const rows = await s.query(sql, { type: Sequelize.QueryTypes.SELECT });
|
||||
return Array.isArray(rows) ? rows : [];
|
||||
};
|
||||
|
||||
const total = await q('SELECT COUNT(*) AS c FROM wms_wave_pick_task');
|
||||
console.log('A. 主表总数:', JSON.stringify(total));
|
||||
|
||||
const byMode = await q(
|
||||
'SELECT pick_mode, source, COUNT(*) AS cnt FROM wms_wave_pick_task GROUP BY pick_mode, source ORDER BY pick_mode, source'
|
||||
);
|
||||
console.log('B. pick_mode/source 分布:', JSON.stringify(byMode));
|
||||
|
||||
const byWaveCount = await q(
|
||||
'SELECT pick_mode, wave_count, COUNT(*) AS cnt FROM wms_wave_pick_task WHERE pick_mode IN (1, 5) GROUP BY pick_mode, wave_count ORDER BY pick_mode, wave_count'
|
||||
);
|
||||
console.log('C. 团购任务 wave_count 分布:', JSON.stringify(byWaveCount));
|
||||
|
||||
const multiWave = await q(
|
||||
'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows '
|
||||
+ 'FROM wms_wave_pick_task_wave tw '
|
||||
+ 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id '
|
||||
+ 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count '
|
||||
+ 'HAVING COUNT(*) > 1 '
|
||||
+ 'ORDER BY tw.task_id DESC LIMIT 10'
|
||||
);
|
||||
console.log('D. 多波次任务样例:', JSON.stringify(multiWave));
|
||||
|
||||
const singleWave = await q(
|
||||
'SELECT tw.task_id, t.pick_mode, t.source, t.wave_count, COUNT(*) AS task_wave_rows '
|
||||
+ 'FROM wms_wave_pick_task_wave tw '
|
||||
+ 'INNER JOIN wms_wave_pick_task t ON t.id = tw.task_id '
|
||||
+ 'GROUP BY tw.task_id, t.pick_mode, t.source, t.wave_count '
|
||||
+ 'HAVING COUNT(*) = 1 '
|
||||
+ 'ORDER BY tw.task_id DESC LIMIT 10'
|
||||
);
|
||||
console.log('E. 单波次任务样例:', JSON.stringify(singleWave));
|
||||
|
||||
const sampleGroup = await q(
|
||||
'SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, '
|
||||
+ '(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows '
|
||||
+ 'FROM wms_wave_pick_task t WHERE pick_mode = 1 ORDER BY id DESC LIMIT 10'
|
||||
);
|
||||
console.log('F. 团购任务最近10条:', JSON.stringify(sampleGroup));
|
||||
|
||||
const sampleScatter = await q(
|
||||
'SELECT id, task_no, source, pick_mode, wave_id, wave_count, batch_no, '
|
||||
+ '(SELECT COUNT(*) FROM wms_wave_pick_task_wave tw WHERE tw.task_id = t.id) AS task_wave_rows '
|
||||
+ 'FROM wms_wave_pick_task t WHERE pick_mode IN (2, 3, 4) ORDER BY id DESC LIMIT 10'
|
||||
);
|
||||
console.log('G. 散单任务最近10条:', JSON.stringify(sampleScatter));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,89 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 统计策略 7(边拣边分)候选订单池:
|
||||
* 命中匹配表、未分配波次、状态满足抓取口径的订单,按同结构与创建时间分布统计。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT
|
||||
o.id,
|
||||
o.items_hash,
|
||||
o.create_at,
|
||||
o.step,
|
||||
o.post_status,
|
||||
o.storage_status,
|
||||
o.print_status,
|
||||
o.status,
|
||||
o.outbound_status,
|
||||
o.intercept_status,
|
||||
o.lock_status,
|
||||
o.wave_id
|
||||
FROM wms_order_wave_strategy_match m
|
||||
INNER JOIN wms_order_delivery_100000 o
|
||||
ON o.id = m.order_id
|
||||
WHERE m.warehouse_id = 100000
|
||||
AND m.strategy_id = 7
|
||||
ORDER BY o.id DESC`
|
||||
);
|
||||
console.log(`===== 命中策略7订单总数: ${rows.length} =====`);
|
||||
|
||||
const todayStartUtc = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00
|
||||
const beforeToday = rows.filter(row => row.create_at && new Date(row.create_at).getTime() < todayStartUtc);
|
||||
const today = rows.filter(row => row.create_at && new Date(row.create_at).getTime() >= todayStartUtc);
|
||||
console.log(`今日前订单数: ${beforeToday.length}`);
|
||||
console.log(`今日订单数: ${today.length}`);
|
||||
|
||||
const eligible = rows.filter(row =>
|
||||
Number(row.wave_id) === 0
|
||||
&& Number(row.step) !== 0
|
||||
&& String(row.post_status) === 'fin'
|
||||
&& String(row.storage_status) === 'fin'
|
||||
&& String(row.print_status) !== 'fin'
|
||||
&& String(row.status) !== 'cancel'
|
||||
&& String(row.outbound_status) !== 'padding'
|
||||
&& String(row.intercept_status) === 'none'
|
||||
&& String(row.lock_status) === 'none'
|
||||
);
|
||||
console.log(`===== 满足抓取口径订单数: ${eligible.length} =====`);
|
||||
const eligibleBeforeToday = eligible.filter(row => new Date(row.create_at).getTime() < todayStartUtc);
|
||||
const eligibleToday = eligible.filter(row => new Date(row.create_at).getTime() >= todayStartUtc);
|
||||
console.log(` 其中今日前: ${eligibleBeforeToday.length}`);
|
||||
console.log(` 其中今天: ${eligibleToday.length}`);
|
||||
|
||||
const hashGroups = new Map();
|
||||
for (const row of eligible) {
|
||||
const key = String(row.items_hash || '').trim();
|
||||
if (!key) continue;
|
||||
if (!hashGroups.has(key)) hashGroups.set(key, []);
|
||||
hashGroups.get(key).push(row);
|
||||
}
|
||||
console.log('===== 同结构分组(仅数量>=2) =====');
|
||||
for (const [ key, list ] of hashGroups.entries()) {
|
||||
if (list.length < 2) continue;
|
||||
const beforeCount = list.filter(row => new Date(row.create_at).getTime() < todayStartUtc).length;
|
||||
console.log(`hash=${key.slice(0, 12)} 总数=${list.length} 今日前=${beforeCount} 今天=${list.length - beforeCount}`);
|
||||
}
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,53 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 查询联调所需测试数据:仓库 100000 下的货主合约与可用商品库存。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ contractRows ] = await connection.query(
|
||||
`SELECT id, store_id, warehouse_id, auth_status
|
||||
FROM wms_store_warehouse
|
||||
WHERE warehouse_id = 100000 AND auth_status = 2
|
||||
ORDER BY id DESC
|
||||
LIMIT 20`
|
||||
);
|
||||
console.log('===== 仓库100000 已通过合约(auth_status=2) =====');
|
||||
console.log(JSON.stringify(contractRows));
|
||||
|
||||
const [ columns ] = await connection.query(
|
||||
`SHOW COLUMNS FROM wms_stock_warehouse`
|
||||
);
|
||||
console.log('===== wms_stock_warehouse 列 =====');
|
||||
console.log(JSON.stringify(columns.map(item => item.Field)));
|
||||
|
||||
const [ stockRows ] = await connection.query(
|
||||
`SELECT * FROM wms_stock_warehouse
|
||||
WHERE warehouse_id = 100000
|
||||
ORDER BY id DESC
|
||||
LIMIT 10`
|
||||
);
|
||||
console.log('===== 仓库100000 库存示例 =====');
|
||||
console.log(JSON.stringify(stockRows));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,13 +0,0 @@
|
||||
'use strict';
|
||||
const Redis = require('ioredis');
|
||||
(async () => {
|
||||
const r = new Redis({ host: '127.0.0.1', port: 6379, password: 'qwe2019', db: 10 });
|
||||
const keys = await r.keys('user:info:*');
|
||||
console.log('matched keys:', keys);
|
||||
for (const k of keys) {
|
||||
await r.del(k);
|
||||
console.log('deleted:', k);
|
||||
}
|
||||
r.disconnect();
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,173 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
function extractTopLevelFieldsFromObjectBody(body) {
|
||||
const fields = [];
|
||||
let i = 0;
|
||||
let depth = 0;
|
||||
while (i < body.length) {
|
||||
const ch = body[i];
|
||||
if (ch === '{') {
|
||||
depth++;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '}') {
|
||||
depth--;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (depth === 0) {
|
||||
const m = body.slice(i).match(/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*\{/);
|
||||
if (m) {
|
||||
const key = m[1];
|
||||
fields.push(key);
|
||||
i += m[0].length;
|
||||
let inner = 1;
|
||||
while (i < body.length && inner > 0) {
|
||||
const c = body[i++];
|
||||
if (c === '{') inner++;
|
||||
if (c === '}') inner--;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return [...new Set(fields)];
|
||||
}
|
||||
|
||||
function getObjectBodyByMarker(text, marker) {
|
||||
const start = text.indexOf(marker);
|
||||
if (start < 0) return null;
|
||||
const braceStart = text.indexOf('{', start + marker.length);
|
||||
if (braceStart < 0) return null;
|
||||
let i = braceStart + 1;
|
||||
let depth = 1;
|
||||
let body = '';
|
||||
while (i < text.length && depth > 0) {
|
||||
const ch = text[i++];
|
||||
if (ch === '{') depth++;
|
||||
if (ch === '}') depth--;
|
||||
if (depth > 0) body += ch;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function extractDefineFields(text) {
|
||||
const definePos = text.indexOf('define(');
|
||||
if (definePos < 0) return [];
|
||||
const firstBrace = text.indexOf('{', definePos);
|
||||
if (firstBrace < 0) return [];
|
||||
let i = firstBrace + 1;
|
||||
let depth = 1;
|
||||
let body = '';
|
||||
while (i < text.length && depth > 0) {
|
||||
const ch = text[i++];
|
||||
if (ch === '{') depth++;
|
||||
if (ch === '}') depth--;
|
||||
if (depth > 0) body += ch;
|
||||
}
|
||||
return extractTopLevelFieldsFromObjectBody(body);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const root = process.cwd();
|
||||
const tempDir = path.join(root, 'temp');
|
||||
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||
const projectRequire = createRequire(path.join(root, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
const cfgFactory = require(path.join(root, 'config', 'config.local.js'));
|
||||
const cfg = typeof cfgFactory === 'function' ? cfgFactory({ name: 'wms-debug' }) : cfgFactory;
|
||||
const client = cfg?.mysql?.clients?.wms;
|
||||
if (!client) throw new Error('mysql client wms not found');
|
||||
|
||||
const conn = await mysql.createConnection({
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
});
|
||||
|
||||
const [tableRows] = await conn.query(
|
||||
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND (TABLE_NAME IN ('wms_order_delivery','wms_order_items','wms_entry_order') OR TABLE_NAME LIKE 'wms_order_delivery_%' OR TABLE_NAME LIKE 'wms_order_items_%') ORDER BY TABLE_NAME"
|
||||
);
|
||||
|
||||
const tableSchemas = {};
|
||||
for (const t of tableRows.map(x => x.TABLE_NAME)) {
|
||||
const [cols] = await conn.query(
|
||||
"SELECT COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA,COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION",
|
||||
[t]
|
||||
);
|
||||
tableSchemas[t] = cols;
|
||||
}
|
||||
|
||||
const targets = [
|
||||
{ table: 'wms_order_delivery', modelFile: 'app/model/order_delivery.js', type: 'baseModel' },
|
||||
{ table: 'wms_order_items', modelFile: 'app/model/order_items.js', type: 'define' },
|
||||
{ table: 'wms_entry_order', modelFile: 'app/model/entry_order.js', type: 'define' },
|
||||
];
|
||||
|
||||
const compareWithModel = targets.map(t => {
|
||||
const txt = fs.readFileSync(path.join(root, t.modelFile), 'utf8');
|
||||
let modelFields = [];
|
||||
if (t.type === 'baseModel') {
|
||||
const body = getObjectBodyByMarker(txt, 'const baseModel =');
|
||||
modelFields = body ? extractTopLevelFieldsFromObjectBody(body) : [];
|
||||
} else {
|
||||
modelFields = extractDefineFields(txt);
|
||||
}
|
||||
|
||||
const dbColumns = (tableSchemas[t.table] || []).map(c => c.COLUMN_NAME);
|
||||
const modelOnly = modelFields.filter(f => !dbColumns.includes(f));
|
||||
const dbOnly = dbColumns.filter(c => !modelFields.includes(c));
|
||||
|
||||
return {
|
||||
table: t.table,
|
||||
modelFile: t.modelFile,
|
||||
modelFieldCount: modelFields.length,
|
||||
dbFieldCount: dbColumns.length,
|
||||
modelOnly,
|
||||
dbOnly,
|
||||
allMatched: modelOnly.length === 0 && dbOnly.length === 0,
|
||||
};
|
||||
});
|
||||
|
||||
const dynamicTableCheck = [];
|
||||
const dynamicTables = Object.keys(tableSchemas).filter(t => t.endsWith('_100000'));
|
||||
for (const dt of dynamicTables) {
|
||||
const baseTable = dt.startsWith('wms_order_delivery_') ? 'wms_order_delivery' : dt.startsWith('wms_order_items_') ? 'wms_order_items' : null;
|
||||
if (!baseTable) continue;
|
||||
const baseCols = (tableSchemas[baseTable] || []).map(c => c.COLUMN_NAME);
|
||||
const dynCols = (tableSchemas[dt] || []).map(c => c.COLUMN_NAME);
|
||||
dynamicTableCheck.push({
|
||||
table: dt,
|
||||
baseTable,
|
||||
missingFromDynamic: baseCols.filter(c => !dynCols.includes(c)),
|
||||
extraInDynamic: dynCols.filter(c => !baseCols.includes(c)),
|
||||
allMatched: baseCols.length === dynCols.length && baseCols.every(c => dynCols.includes(c)),
|
||||
});
|
||||
}
|
||||
|
||||
const out = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
dbName: client.database,
|
||||
tables: tableRows.map(x => x.TABLE_NAME),
|
||||
compareWithModel,
|
||||
dynamicTableCheck,
|
||||
schema: tableSchemas,
|
||||
};
|
||||
|
||||
fs.writeFileSync(path.join(tempDir, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2));
|
||||
await conn.end();
|
||||
console.log('WROTE temp/tmp-order-schema-compare.json');
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err && err.stack ? err.stack : String(err));
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,58 +0,0 @@
|
||||
'use strict';
|
||||
/* 临时探索脚本:查询直入/转入库单对比测试所需数据(只读) */
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
(async () => {
|
||||
const conn = await mysql.createConnection({
|
||||
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
|
||||
});
|
||||
|
||||
const [cols] = await conn.query('SHOW COLUMNS FROM wms_employee_role');
|
||||
console.log('== wms_employee_role columns ==');
|
||||
console.log(cols.map(c => c.Field).join(','));
|
||||
|
||||
const [whUsers] = await conn.query(`
|
||||
SELECT a.id account_id, a.username, a.status, e.id employee_id, e.store_id warehouse_id, r.id role_id, r.role_type
|
||||
FROM wms_account a
|
||||
JOIN wms_account_store_employee e ON e.account_id = a.id AND e.deleted_at IS NULL
|
||||
LEFT JOIN wms_employee_role er ON er.employee_id = e.id
|
||||
LEFT JOIN wms_role r ON r.id = er.role_id
|
||||
WHERE a.status = 1
|
||||
ORDER BY e.id ASC LIMIT 8`);
|
||||
console.log('== accounts ==');
|
||||
console.log(JSON.stringify(whUsers, null, 2));
|
||||
|
||||
if (whUsers.length === 0) { await conn.end(); return; }
|
||||
const whId = whUsers[0].warehouse_id;
|
||||
console.log('== using warehouse_id = ' + whId + ' ==');
|
||||
|
||||
const [stores] = await conn.query(`
|
||||
SELECT sw.store_id, sw.warehouse_use_status, sw.policy_config, s.company_name
|
||||
FROM wms_store_warehouse sw JOIN wms_store s ON s.id = sw.store_id
|
||||
WHERE sw.warehouse_id = ? AND sw.warehouse_use_status = 1
|
||||
ORDER BY sw.id DESC LIMIT 5`, [ whId ]);
|
||||
console.log('== store_warehouse contracts (warehouse=' + whId + ') ==');
|
||||
console.log(JSON.stringify(stores, null, 2));
|
||||
|
||||
const [stocks] = await conn.query(`
|
||||
SELECT sw.id, sw.item_code, sw.item_name, sw.is_batch_mgmt, sw.is_shelf_life_mgmt, sw.is_valid, sw.quantity, sw.store_id
|
||||
FROM wms_stock_warehouse sw
|
||||
WHERE sw.warehouse_id = ? AND sw.is_valid = 'Y' AND sw.deleted_at IS NULL
|
||||
ORDER BY sw.id DESC LIMIT 8`, [ whId ]);
|
||||
console.log('== stock_warehouse products ==');
|
||||
console.log(JSON.stringify(stocks, null, 2));
|
||||
|
||||
const [spacesCols] = await conn.query('SHOW COLUMNS FROM wms_location_space');
|
||||
console.log('== wms_location_space columns ==');
|
||||
console.log(spacesCols.map(c => c.Field).join(','));
|
||||
|
||||
const [spaces] = await conn.query(`
|
||||
SELECT id, space_code, custom_name, is_enabled, current_quantity
|
||||
FROM wms_location_space
|
||||
WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL
|
||||
ORDER BY id LIMIT 8`, [ whId ]);
|
||||
console.log('== location spaces ==');
|
||||
console.log(JSON.stringify(spaces, null, 2));
|
||||
|
||||
await conn.end();
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,99 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = process.cwd();
|
||||
const tempDir = path.join(root, 'temp');
|
||||
const serviceRoot = path.join(root, 'app', 'service');
|
||||
|
||||
function walk(dir) {
|
||||
const out = [];
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const full = path.join(dir, name);
|
||||
const st = fs.statSync(full);
|
||||
if (st.isDirectory()) out.push(...walk(full));
|
||||
else if (name.endsWith('.js')) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractClassMethods(content) {
|
||||
const methods = [];
|
||||
const classIdx = content.indexOf('class ');
|
||||
if (classIdx < 0) return methods;
|
||||
const braceStart = content.indexOf('{', classIdx);
|
||||
if (braceStart < 0) return methods;
|
||||
|
||||
let i = braceStart + 1;
|
||||
let depth = 1;
|
||||
let body = '';
|
||||
while (i < content.length && depth > 0) {
|
||||
const ch = content[i++];
|
||||
if (ch === '{') depth++;
|
||||
if (ch === '}') depth--;
|
||||
if (depth > 0) body += ch;
|
||||
}
|
||||
|
||||
let p = 0;
|
||||
let nested = 0;
|
||||
while (p < body.length) {
|
||||
const ch = body[p];
|
||||
if (ch === '{') { nested++; p++; continue; }
|
||||
if (ch === '}') { nested--; p++; continue; }
|
||||
|
||||
if (nested === 0) {
|
||||
const slice = body.slice(p);
|
||||
const m = slice.match(/^\s*(?:async\s+)?([A-Za-z_$][\w$]*)\s*\(/);
|
||||
if (m) {
|
||||
const name = m[1];
|
||||
if (name !== 'constructor') methods.push(name);
|
||||
|
||||
// move to method body end
|
||||
p += m[0].length;
|
||||
while (p < body.length && body[p] !== '{') p++;
|
||||
if (body[p] === '{') {
|
||||
p++;
|
||||
let inMethod = 1;
|
||||
while (p < body.length && inMethod > 0) {
|
||||
if (body[p] === '{') inMethod++;
|
||||
else if (body[p] === '}') inMethod--;
|
||||
p++;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
p++;
|
||||
}
|
||||
|
||||
return [...new Set(methods)];
|
||||
}
|
||||
|
||||
const files = walk(serviceRoot)
|
||||
.map(full => path.relative(root, full).replace(/\\/g, '/'))
|
||||
.sort((a, b) => a.localeCompare(b));
|
||||
|
||||
const inventory = [];
|
||||
for (const rel of files) {
|
||||
const full = path.join(root, rel);
|
||||
const content = fs.readFileSync(full, 'utf8');
|
||||
const methods = extractClassMethods(content);
|
||||
inventory.push({ file: rel, methodCount: methods.length, methods });
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
let md = '';
|
||||
md += `自动生成时间: ${now}\n\n`;
|
||||
md += `扫描范围: app/service/**/*.js\n`;
|
||||
md += `文件数: ${inventory.length}\n\n`;
|
||||
for (const item of inventory) {
|
||||
md += `- ${item.file} (${item.methodCount})\n`;
|
||||
if (item.methods.length === 0) {
|
||||
md += ` - <no-class-method-found>\n`;
|
||||
} else {
|
||||
md += ` - ${item.methods.join(', ')}\n`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(tempDir, 'tmp-service-method-inventory.md'), md, 'utf8');
|
||||
console.log('WROTE temp/tmp-service-method-inventory.md');
|
||||
@ -1,116 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = process.cwd();
|
||||
const defaultBaselinePath = path.join(root, 'temp', 'method-output', 'method-output-baseline.json');
|
||||
const defaultTargetPath = path.join(root, 'temp', 'generated-tests', 'system.method-output.generated.test.js');
|
||||
const legacyBaselinePath = path.join(root, 'run', 'method-output-baseline.json');
|
||||
let baselinePath = process.argv[2]
|
||||
? path.resolve(process.argv[2])
|
||||
: defaultBaselinePath;
|
||||
const targetPath = process.argv[3]
|
||||
? path.resolve(process.argv[3])
|
||||
: defaultTargetPath;
|
||||
|
||||
if (!process.argv[2] && !fs.existsSync(baselinePath) && fs.existsSync(legacyBaselinePath)) {
|
||||
baselinePath = legacyBaselinePath;
|
||||
}
|
||||
|
||||
const supportClientPath = path.relative(
|
||||
path.dirname(targetPath),
|
||||
path.join(root, 'test', 'support', 'system_method_client')
|
||||
).replace(/\\/g, '/');
|
||||
const supportRequirePath = supportClientPath.startsWith('.') ? supportClientPath : `./${supportClientPath}`;
|
||||
const describePath = path.relative(root, targetPath).replace(/\\/g, '/');
|
||||
|
||||
if (!fs.existsSync(baselinePath)) {
|
||||
console.error(`Baseline not found: ${baselinePath}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8'));
|
||||
const cases = Array.isArray(baseline.cases) ? baseline.cases : [];
|
||||
|
||||
const header = `// @eggjs-test-generated
|
||||
// @purpose 接口返回数据一致性校验(自动生成,请勿手改)
|
||||
// @source ${path.relative(root, baselinePath).replace(/\\/g, '/')}
|
||||
// @generatedAt ${new Date().toISOString()}
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
getAuthToken,
|
||||
invokeSystemMethod,
|
||||
} = require('${supportRequirePath}');
|
||||
|
||||
const VOLATILE_KEYS = new Set([
|
||||
'timestamp',
|
||||
'token',
|
||||
'last_login_at',
|
||||
'updated_at',
|
||||
'update_at',
|
||||
'created_at',
|
||||
'create_at',
|
||||
'login_time',
|
||||
'iat',
|
||||
'exp',
|
||||
]);
|
||||
|
||||
function normalize(value) {
|
||||
if (value === null || value === undefined) return value;
|
||||
if (Array.isArray(value)) return value.map(item => normalize(item));
|
||||
if (typeof value !== 'object') return value;
|
||||
const out = {};
|
||||
for (const key of Object.keys(value)) {
|
||||
if (VOLATILE_KEYS.has(key)) {
|
||||
out[key] = '__VOLATILE__';
|
||||
continue;
|
||||
}
|
||||
out[key] = normalize(value[key]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe(${JSON.stringify(describePath)}, () => {
|
||||
let token = '';
|
||||
|
||||
before(async () => {
|
||||
const auth = await getAuthToken();
|
||||
token = auth.token;
|
||||
assert.ok(token, 'token should be available');
|
||||
});
|
||||
`;
|
||||
|
||||
const body = cases.map((item, idx) => {
|
||||
const title = `[${idx + 1}] ${item.method} (sourceId=${item.sourceId})`;
|
||||
const requestBody = JSON.stringify(item.requestBody || {}, null, 2);
|
||||
const expected = JSON.stringify(item.normalized || {}, null, 2);
|
||||
const platform = JSON.stringify((item.headers && item.headers.platform) || 'web');
|
||||
const project = JSON.stringify((item.headers && item.headers.project) || 'wms');
|
||||
|
||||
return `
|
||||
it(${JSON.stringify(title)}, async () => {
|
||||
const res = await invokeSystemMethod(
|
||||
${JSON.stringify(item.method)},
|
||||
${requestBody},
|
||||
token,
|
||||
{ platform: ${platform}, project: ${project} }
|
||||
);
|
||||
|
||||
assert.equal(res.status, ${Number(item.httpStatus || 200)});
|
||||
const normalized = normalize(res.body);
|
||||
const expected = ${expected};
|
||||
assert.deepEqual(normalized, expected);
|
||||
});
|
||||
`;
|
||||
}).join('\n');
|
||||
|
||||
const footer = `
|
||||
});
|
||||
`;
|
||||
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
||||
fs.writeFileSync(targetPath, header + body + footer, 'utf8');
|
||||
|
||||
console.log(`GENERATED ${targetPath}`);
|
||||
console.log(`CASE_COUNT ${cases.length}`);
|
||||
@ -1,194 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = process.cwd();
|
||||
const methodsDir = path.join(root, 'app', 'service', 'qimenMethods');
|
||||
const outputPath = path.join(root, 'methods', 'qimen.json');
|
||||
|
||||
function walk(dir) {
|
||||
const out = [];
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
const full = path.join(dir, name);
|
||||
const stat = fs.statSync(full);
|
||||
if (stat.isDirectory()) {
|
||||
out.push(...walk(full));
|
||||
} else if (name.endsWith('.js')) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractAsyncMethods(content) {
|
||||
const methods = [];
|
||||
const classMatch = content.match(/class\s+[A-Za-z_$][\w$]*\s+extends\s+[A-Za-z_$][\w$]*\s*\{([\s\S]*)\}\s*module\.exports\s*=\s*/);
|
||||
if (!classMatch) {
|
||||
return methods;
|
||||
}
|
||||
|
||||
const body = classMatch[1];
|
||||
const regex = /async\s+([A-Za-z_$][\w$]*)\s*\(/g;
|
||||
let m = regex.exec(body);
|
||||
while (m) {
|
||||
if (m[1] !== 'constructor') {
|
||||
methods.push(m[1]);
|
||||
}
|
||||
m = regex.exec(body);
|
||||
}
|
||||
|
||||
return Array.from(new Set(methods));
|
||||
}
|
||||
|
||||
function extractRequestKeys(content) {
|
||||
const keys = new Set();
|
||||
const patterns = [
|
||||
/data\.request(?:\?|)\.(\w+)/g,
|
||||
/data\?\.request\?\.(\w+)/g,
|
||||
];
|
||||
|
||||
for (const re of patterns) {
|
||||
let m = re.exec(content);
|
||||
while (m) {
|
||||
const key = m[1];
|
||||
if (key) keys.add(key);
|
||||
m = re.exec(content);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(keys).sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function buildMethodItem(fullMethod, requestKeys) {
|
||||
const params = [
|
||||
{
|
||||
name: 'app_key',
|
||||
type: 'string',
|
||||
required: true,
|
||||
source: 'query',
|
||||
description: 'app_key 参数',
|
||||
},
|
||||
{
|
||||
name: 'method',
|
||||
type: 'string',
|
||||
required: true,
|
||||
source: 'query',
|
||||
description: 'method 参数',
|
||||
},
|
||||
{
|
||||
name: 'v',
|
||||
type: 'string',
|
||||
required: true,
|
||||
source: 'query',
|
||||
description: 'v 参数',
|
||||
},
|
||||
{
|
||||
name: 'format',
|
||||
type: 'string',
|
||||
required: true,
|
||||
source: 'query',
|
||||
description: 'format 参数',
|
||||
},
|
||||
{
|
||||
name: 'sign_method',
|
||||
type: 'string',
|
||||
required: true,
|
||||
source: 'query',
|
||||
description: 'sign_method 参数',
|
||||
},
|
||||
{
|
||||
name: 'sign',
|
||||
type: 'string',
|
||||
required: true,
|
||||
source: 'query',
|
||||
description: 'sign 参数',
|
||||
},
|
||||
{
|
||||
name: 'timestamp',
|
||||
type: 'string',
|
||||
required: true,
|
||||
source: 'query',
|
||||
description: 'timestamp 参数',
|
||||
},
|
||||
{
|
||||
name: 'request',
|
||||
type: 'object',
|
||||
required: true,
|
||||
source: 'body',
|
||||
description: 'request XML 节点',
|
||||
},
|
||||
];
|
||||
|
||||
for (const key of requestKeys) {
|
||||
params.push({
|
||||
name: `request.${key}`,
|
||||
type: 'string',
|
||||
required: false,
|
||||
source: 'body',
|
||||
description: `request.${key} 参数`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
method: fullMethod,
|
||||
description: `${fullMethod} 接口`,
|
||||
isNeedAuth: false,
|
||||
isNeedLogin: false,
|
||||
headers: [],
|
||||
params,
|
||||
response: [],
|
||||
errors: [],
|
||||
};
|
||||
}
|
||||
|
||||
function main() {
|
||||
if (!fs.existsSync(methodsDir)) {
|
||||
throw new Error(`目录不存在: ${methodsDir}`);
|
||||
}
|
||||
|
||||
const files = walk(methodsDir).sort((a, b) => a.localeCompare(b));
|
||||
const groupMap = new Map();
|
||||
|
||||
for (const file of files) {
|
||||
const content = fs.readFileSync(file, 'utf8');
|
||||
const rel = path.relative(methodsDir, file).replace(/\\/g, '/').replace(/\.js$/, '');
|
||||
const moduleName = rel.replace(/\//g, '.');
|
||||
const methodNames = extractAsyncMethods(content);
|
||||
const requestKeys = extractRequestKeys(content);
|
||||
|
||||
if (!groupMap.has(moduleName)) {
|
||||
groupMap.set(moduleName, []);
|
||||
}
|
||||
|
||||
for (const methodName of methodNames) {
|
||||
const fullMethod = `${moduleName}.${methodName}`;
|
||||
groupMap.get(moduleName).push(buildMethodItem(fullMethod, requestKeys));
|
||||
}
|
||||
}
|
||||
|
||||
const groups = Array.from(groupMap.entries())
|
||||
.map(([ moduleName, list ]) => ({
|
||||
groupName: `${moduleName} 模块`,
|
||||
module: moduleName,
|
||||
list: list.sort((a, b) => a.method.localeCompare(b.method)),
|
||||
}))
|
||||
.sort((a, b) => a.module.localeCompare(b.module));
|
||||
|
||||
const now = new Date().toISOString().slice(0, 10);
|
||||
const doc = {
|
||||
module: 'qimen',
|
||||
description: '奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)',
|
||||
version: '0.3.0',
|
||||
updatedAt: now,
|
||||
headers: [],
|
||||
methods: {
|
||||
groups,
|
||||
},
|
||||
};
|
||||
|
||||
fs.writeFileSync(outputPath, JSON.stringify(doc, null, 2) + '\n', 'utf8');
|
||||
|
||||
const methodCount = groups.reduce((sum, group) => sum + group.list.length, 0);
|
||||
console.log(`WROTE methods/qimen.json, groups=${groups.length}, methods=${methodCount}`);
|
||||
}
|
||||
|
||||
main();
|
||||
@ -1,95 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 边界场景数据准备:让策略 7 的第一订单池(今日前)仅剩 8 条同结构订单,
|
||||
* 其余满足抓取口径的候选订单全部改为今天,用于验证:
|
||||
* - 第一池不足 20 时不会用第二池填充;
|
||||
* - 第一池抓取完毕后,第二轮才开始抓第二池(今天订单)并抓满 20。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const TODAY_TIME = '2026-09-06 11:00:00';
|
||||
const KEEP_COUNT = 8;
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT o.id, o.create_at, o.items_hash
|
||||
FROM wms_order_wave_strategy_match m
|
||||
INNER JOIN wms_order_delivery_100000 o
|
||||
ON o.id = m.order_id
|
||||
WHERE m.warehouse_id = 100000
|
||||
AND m.strategy_id = 7
|
||||
AND o.wave_id = 0
|
||||
AND o.step != 0
|
||||
AND o.post_status = 'fin'
|
||||
AND o.storage_status = 'fin'
|
||||
AND o.print_status != 'fin'
|
||||
AND o.status != 'cancel'
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
ORDER BY o.id ASC`
|
||||
);
|
||||
console.log(`满足口径且未分配波次的候选总数: ${rows.length}`);
|
||||
|
||||
const todayStart = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00
|
||||
const beforeToday = rows.filter(row => new Date(row.create_at).getTime() < todayStart);
|
||||
console.log(`其中今日前候选: ${beforeToday.length}`);
|
||||
|
||||
// 选择同一 hash 的 8 条今日前订单保留
|
||||
const hashGroups = new Map();
|
||||
for (const row of beforeToday) {
|
||||
const key = String(row.items_hash || '').trim();
|
||||
if (!key) continue;
|
||||
if (!hashGroups.has(key)) hashGroups.set(key, []);
|
||||
hashGroups.get(key).push(row);
|
||||
}
|
||||
let keepGroup = null;
|
||||
for (const list of hashGroups.values()) {
|
||||
if (list.length >= KEEP_COUNT) {
|
||||
keepGroup = list;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!keepGroup) {
|
||||
console.log('未找到同结构数量>=8的今日前分组,改用任意8条');
|
||||
keepGroup = beforeToday.slice(0, KEEP_COUNT);
|
||||
}
|
||||
const keepIds = keepGroup.slice(0, KEEP_COUNT).map(row => Number(row.id));
|
||||
const keepSet = new Set(keepIds);
|
||||
const moveIds = rows.map(row => Number(row.id)).filter(id => !keepSet.has(id));
|
||||
|
||||
console.log(`保留为今日前的订单(将不足20): [${keepIds.join(', ')}]`);
|
||||
console.log(`改为今天的订单数: ${moveIds.length}`);
|
||||
|
||||
if (moveIds.length > 0) {
|
||||
const [ result ] = await connection.query(
|
||||
`UPDATE wms_order_delivery_100000
|
||||
SET create_at = ?
|
||||
WHERE id IN (?)`,
|
||||
[ TODAY_TIME, moveIds ]
|
||||
);
|
||||
console.log(`已更新行数: ${result.affectedRows}`);
|
||||
}
|
||||
console.log('数据准备完成');
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`执行失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,99 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 边界场景数据准备(v3):
|
||||
* 当前今日前候选只有 ac1b 组 8 条(同结构总数 14,超 max_same_structure=12,不入选)。
|
||||
* 改为:从同结构总数 2~12 的组中选 8 条改为今日前,其余候选(含 ac1b 组 8 条)全部改为今天。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const TODAY_TIME = '2026-09-06 12:30:00';
|
||||
const BEFORE_TODAY = '2026-01-13 07:26:07';
|
||||
const KEEP_COUNT = 8;
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT o.id, o.items_hash
|
||||
FROM wms_order_wave_strategy_match m
|
||||
INNER JOIN wms_order_delivery_100000 o
|
||||
ON o.id = m.order_id
|
||||
WHERE m.warehouse_id = 100000
|
||||
AND m.strategy_id = 7
|
||||
AND o.wave_id = 0
|
||||
AND o.step != 0
|
||||
AND o.post_status = 'fin'
|
||||
AND o.storage_status = 'fin'
|
||||
AND o.print_status != 'fin'
|
||||
AND o.status != 'cancel'
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
ORDER BY o.id ASC`
|
||||
);
|
||||
console.log(`候选总数: ${rows.length}`);
|
||||
|
||||
const hashGroups = new Map();
|
||||
for (const row of rows) {
|
||||
const key = String(row.items_hash || '').trim();
|
||||
if (!key) continue;
|
||||
if (!hashGroups.has(key)) hashGroups.set(key, []);
|
||||
hashGroups.get(key).push(row);
|
||||
}
|
||||
|
||||
let picked = null;
|
||||
for (const [ key, list ] of hashGroups.entries()) {
|
||||
if (list.length >= KEEP_COUNT && list.length <= 12) {
|
||||
picked = { key, list };
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!picked) {
|
||||
// 选数量最小的 8~12 组,找不到则选任意 >=8 组
|
||||
for (const [ key, list ] of hashGroups.entries()) {
|
||||
if (list.length >= KEEP_COUNT) {
|
||||
picked = { key, list };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!picked) {
|
||||
throw new Error('未找到可用的同结构分组');
|
||||
}
|
||||
|
||||
const keepIds = picked.list.slice(0, KEEP_COUNT).map(row => Number(row.id));
|
||||
const keepSet = new Set(keepIds);
|
||||
console.log(`选中分组: hash=${picked.key.slice(0, 12)} 总数=${picked.list.length}`);
|
||||
console.log(`保留为今日前的订单: [${keepIds.join(', ')}]`);
|
||||
|
||||
const allIds = rows.map(row => Number(row.id));
|
||||
await connection.query(
|
||||
`UPDATE wms_order_delivery_100000 SET create_at = ? WHERE id IN (?)`,
|
||||
[ TODAY_TIME, allIds ]
|
||||
);
|
||||
await connection.query(
|
||||
`UPDATE wms_order_delivery_100000 SET create_at = ? WHERE id IN (?)`,
|
||||
[ BEFORE_TODAY, keepIds ]
|
||||
);
|
||||
console.log(`其余 ${allIds.length - keepIds.length} 条已改为今天 ${TODAY_TIME}`);
|
||||
console.log('数据准备完成');
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`执行失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,73 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单池分割测试数据准备:
|
||||
* 将策略 7 候选订单中按 id 升序前 10 条的 create_at 改为今天(2026-09-06 09:00:00),
|
||||
* 使候选池同时存在「今日前订单」与「今天订单」。
|
||||
*
|
||||
* 选单口径与抓取候选一致(wave_id=0 且状态满足抓取条件)。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const TARGET_DATE = '2026-09-06 09:00:00';
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT o.id, o.create_at, o.items_hash
|
||||
FROM wms_order_wave_strategy_match m
|
||||
INNER JOIN wms_order_delivery_100000 o
|
||||
ON o.id = m.order_id
|
||||
WHERE m.warehouse_id = 100000
|
||||
AND m.strategy_id = 7
|
||||
AND o.wave_id = 0
|
||||
AND o.step != 0
|
||||
AND o.post_status = 'fin'
|
||||
AND o.storage_status = 'fin'
|
||||
AND o.print_status != 'fin'
|
||||
AND o.status != 'cancel'
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
ORDER BY o.id ASC
|
||||
LIMIT 10`
|
||||
);
|
||||
console.log('===== 将被改为今天的订单(原 create_at) =====');
|
||||
rows.forEach(row => {
|
||||
console.log(`id=${row.id}, 原create_at=${row.create_at && row.create_at.toISOString ? row.create_at.toISOString() : row.create_at}, hash=${String(row.items_hash || '').slice(0, 12)}`);
|
||||
});
|
||||
|
||||
const ids = rows.map(row => Number(row.id));
|
||||
if (ids.length === 0) {
|
||||
console.log('无候选订单可修改');
|
||||
return;
|
||||
}
|
||||
|
||||
const [ result ] = await connection.query(
|
||||
`UPDATE wms_order_delivery_100000
|
||||
SET create_at = ?
|
||||
WHERE id IN (?)`,
|
||||
[ TARGET_DATE, ids ]
|
||||
);
|
||||
console.log(`===== 已更新行数: ${result.affectedRows} =====`);
|
||||
console.log(`被修改订单ID: [${ids.join(', ')}]`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`执行失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,318 +0,0 @@
|
||||
/**
|
||||
* 临时脚本:本地以「机器人拦截格式」推送一条站内信,验证规则引擎修复效果(不连生产、不清理数据)。
|
||||
*
|
||||
* 格式来源(生产 优禾康(天豹)顺丰对接群 实测):
|
||||
* <店铺名>LSFJY<日期><序号>\n物流单号:<运单号> 拦截
|
||||
*
|
||||
* 走真实入站链路:POST /warehouse?method=inbox.push(interface_type_id=3,MD5 签名)
|
||||
* → receiver.receive 写库 → setImmediate 异步 handleApiMessage → rules 规则引擎 → 回信
|
||||
*
|
||||
* 用法:node script/tmp-push-inbox-robot-intercept.cjs
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const mysql = require('mysql2/promise');
|
||||
const { signRequest } = require('../app/lib/api_sign');
|
||||
|
||||
const BASE_URL = process.env.INBOX_BASE_URL || 'http://127.0.0.1:6060';
|
||||
const APP_KEY = process.env.INBOX_APP_KEY || 'AK2026080103072276d0e140'; // 本地 warehouse 100000 应用
|
||||
|
||||
/** 测试群(本地 100000 / 货主 1000000 的售后群) */
|
||||
const GROUP = {
|
||||
group_id: 'g_after_sales_1785917104039',
|
||||
group_name: '测试售后群_1785917104039',
|
||||
user_id: 'wxid_robot_uat_0001',
|
||||
user_name: '探域售后机器人',
|
||||
};
|
||||
|
||||
/**
|
||||
* 用例来源:从本地库自动挑选**真实存在**的顺丰运单(货主 1000000、订单在待处理/波次中、
|
||||
* 未拦截、无未完结拦截工单),并按运单号形态去重覆盖(纯数字 / SF+数字 / 其他前缀)。
|
||||
* 正文固定用生产机器人原文格式。
|
||||
*/
|
||||
const WAREHOUSE_ID = 100000;
|
||||
const STORE_ID = 1000000;
|
||||
const CASE_LIMIT = Number(process.env.INBOX_CASE_LIMIT || 4);
|
||||
|
||||
/** 生产原文里的店铺单号前缀(仅用于拼出同款正文) */
|
||||
const SHOP_CODE = '优禾康官方旗舰店LSFJY202609143442';
|
||||
|
||||
/**
|
||||
* 运单号形态归类:开头字母前缀;纯数字归 DIGITS
|
||||
* @param {string} code 运单号。
|
||||
* @return {string} 形态标签。
|
||||
*/
|
||||
function waybillPattern(code) {
|
||||
const m = String(code).match(/^[A-Za-z]+/);
|
||||
return m ? m[0].toUpperCase() : 'DIGITS';
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询可用的顺丰测试运单。
|
||||
* @param {Object} conn mysql2 连接。
|
||||
* @param {number} limit 最多取几个(按运单号形态去重后)。
|
||||
* @return {Promise<Array>} 用例列表 [{ tag, desc, waybill, expressId, orderId, content }]。
|
||||
*/
|
||||
async function findSfCases(conn, limit) {
|
||||
const [ rows ] = await conn.query(
|
||||
'SELECT e.id AS express_id, e.waybill_code, e.order_id, e.logistics_name, e.logistics_interface_id, ' +
|
||||
'd.step, d.wave_id, d.intercept_status ' +
|
||||
'FROM wms_order_express e JOIN wms_order_delivery_100000 d ON d.id = e.order_id ' +
|
||||
'WHERE e.warehouse_id = ? AND e.store_id = ? AND e.logistics_code = "SF" ' +
|
||||
'AND d.step IN (1,2,3) AND (d.intercept_status IS NULL OR d.intercept_status = "none") ' +
|
||||
'AND (e.is_intercept IS NULL OR e.is_intercept <> "Y") ' +
|
||||
'AND e.id NOT IN (SELECT waybill_id FROM wms_after_sale WHERE waybill_id IS NOT NULL ' +
|
||||
' AND sub_type = "intercept" AND status NOT IN ("completed","closed","cancelled")) ' +
|
||||
'ORDER BY e.id DESC',
|
||||
[ WAREHOUSE_ID, STORE_ID ]
|
||||
);
|
||||
|
||||
const picked = [];
|
||||
const usedPatterns = new Set();
|
||||
for (const row of rows) {
|
||||
const pattern = waybillPattern(row.waybill_code);
|
||||
if (usedPatterns.has(pattern)) continue;
|
||||
usedPatterns.add(pattern);
|
||||
picked.push({
|
||||
tag: String(picked.length + 1),
|
||||
waybill: row.waybill_code,
|
||||
expressId: row.express_id,
|
||||
orderId: row.order_id,
|
||||
desc: `形态=${pattern} 顺丰运单 ${row.waybill_code} (express id=${row.express_id}, order=${row.order_id})`,
|
||||
content: `${SHOP_CODE}\n物流单号:${row.waybill_code} 拦截`,
|
||||
});
|
||||
if (picked.length >= limit) break;
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
function loadDbConfig() {
|
||||
const factory = require(path.resolve(projectRoot, 'config/config.local.js'));
|
||||
const config = typeof factory === 'function' ? factory({ name: 'wms-inbox-push' }) : factory;
|
||||
const client = config.mysql.clients.wms;
|
||||
return {
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
};
|
||||
}
|
||||
|
||||
async function getAppSecret(conn, appKey) {
|
||||
const [ rows ] = await conn.query(
|
||||
'SELECT self_app_key, self_app_secret, warehouse_id FROM wms_api_app WHERE self_app_key = ?',
|
||||
[ appKey ]
|
||||
);
|
||||
if (rows.length === 0) throw new Error(`本地库未找到 app_key=${appKey} 的应用`);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
async function pushMessage({ appKey, secret, requestId, content }) {
|
||||
const body = {
|
||||
requestId,
|
||||
groupId: GROUP.group_id,
|
||||
groupName: GROUP.group_name,
|
||||
userId: GROUP.user_id,
|
||||
userName: GROUP.user_name,
|
||||
content,
|
||||
extData: { type: 1, source: 'wx' },
|
||||
flags: {},
|
||||
};
|
||||
const query = {
|
||||
method: 'inbox.push',
|
||||
v: '1.0',
|
||||
timestamp: String(Math.floor(Date.now() / 1000)),
|
||||
app_key: appKey,
|
||||
};
|
||||
const { sign, canonicalQuery } = signRequest({ query, body, selfAppSecret: secret });
|
||||
const search = new URLSearchParams({ ...query, sign }).toString();
|
||||
const url = `${BASE_URL}/warehouse?${search}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const text = await res.text();
|
||||
let json = null;
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch (e) { /* 保留原始文本 */ }
|
||||
return { status: res.status, json, text, canonicalQuery };
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询等待异步处理完成(ai_thoughts 或回信出现)。
|
||||
* @param {Object} conn mysql2 连接实例。
|
||||
* @param {string} extId 入站消息外部唯一键。
|
||||
* @param {Object} [opts] 轮询配置。
|
||||
* @param {number} [opts.timeoutMs] 最长等待毫秒数。
|
||||
* @param {number} [opts.intervalMs] 轮询间隔毫秒数。
|
||||
* @return {Promise<Object>} { inbound, replies, timedOut }。
|
||||
*/
|
||||
async function waitProcessed(conn, extId, { timeoutMs = 20000, intervalMs = 1000 } = {}) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let inbound = null;
|
||||
while (Date.now() < deadline) {
|
||||
const [ rows ] = await conn.query(
|
||||
'SELECT id, direction, group_id, group_name, user_id, user_name, content, ai_thoughts, push_status, created_at ' +
|
||||
'FROM wms_inbox_message WHERE ext_id = ? AND direction = "inbound" ORDER BY id DESC LIMIT 1',
|
||||
[ extId ]
|
||||
);
|
||||
inbound = rows[0] || null;
|
||||
if (inbound) {
|
||||
const [ replies ] = await conn.query(
|
||||
'SELECT id, content, push_status, created_at FROM wms_inbox_message WHERE parent_id = ? ORDER BY id',
|
||||
[ inbound.id ]
|
||||
);
|
||||
if ((inbound.ai_thoughts && String(inbound.ai_thoughts).length > 2) || replies.length > 0) {
|
||||
return { inbound, replies };
|
||||
}
|
||||
}
|
||||
await new Promise(r => setTimeout(r, intervalMs));
|
||||
}
|
||||
const [ replies ] = inbound
|
||||
? await conn.query('SELECT id, content, push_status, created_at FROM wms_inbox_message WHERE parent_id = ? ORDER BY id', [ inbound.id ])
|
||||
: [[]];
|
||||
return { inbound, replies, timedOut: true };
|
||||
}
|
||||
|
||||
async function collectSideEffects(conn, waybills) {
|
||||
if (waybills.length === 0) return { express: [], afterSales: [], orders: [] };
|
||||
const [ express ] = await conn.query(
|
||||
'SELECT id, waybill_code, order_id, store_id, is_intercept FROM wms_order_express WHERE warehouse_id = ? AND waybill_code IN (?)',
|
||||
[ WAREHOUSE_ID, waybills ]
|
||||
);
|
||||
const expressIds = express.map(r => r.id);
|
||||
const orderIds = express.map(r => r.order_id).filter(Boolean);
|
||||
let afterSales = [];
|
||||
if (expressIds.length > 0) {
|
||||
const [ rows ] = await conn.query(
|
||||
'SELECT id, after_sale_no, waybill_id, waybill_no, type, sub_type, status, title FROM wms_after_sale WHERE waybill_id IN (?) ORDER BY id DESC',
|
||||
[ expressIds ]
|
||||
);
|
||||
afterSales = rows;
|
||||
}
|
||||
let orders = [];
|
||||
if (orderIds.length > 0) {
|
||||
const [ rows ] = await conn.query(
|
||||
'SELECT id, step, wave_id, intercept_status, intercept_time FROM wms_order_delivery_100000 WHERE id IN (?)',
|
||||
[ orderIds ]
|
||||
);
|
||||
orders = rows;
|
||||
}
|
||||
return { express, afterSales, orders };
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const dbConfig = loadDbConfig();
|
||||
const conn = await mysql.createConnection(dbConfig);
|
||||
const app = await getAppSecret(conn, APP_KEY);
|
||||
console.log(`目标服务: ${BASE_URL} 应用: ${app.self_app_key} (warehouse ${app.warehouse_id})`);
|
||||
console.log(`测试群: ${GROUP.group_name} / ${GROUP.group_id} 发送人: ${GROUP.user_name}\n`);
|
||||
|
||||
// 支持临时指定正文(INBOX_CONTENT=...),用于其它规则的端到端复现;不指定则自动挑顺丰运单
|
||||
const adhoc = String(process.env.INBOX_CONTENT || '').trim();
|
||||
let cases;
|
||||
if (adhoc) {
|
||||
cases = [{ tag: 'X', waybill: '-', desc: '自定义正文(INBOX_CONTENT)', content: adhoc }];
|
||||
console.log('使用自定义正文(INBOX_CONTENT)');
|
||||
} else {
|
||||
cases = await findSfCases(conn, CASE_LIMIT);
|
||||
if (cases.length === 0) {
|
||||
console.log('❌ 本地库没有可用的未拦截顺丰运单样本');
|
||||
await conn.end();
|
||||
return;
|
||||
}
|
||||
console.log(`自动挑选到 ${cases.length} 个真实顺丰运单样本(按运单号形态去重):`);
|
||||
for (const c of cases) console.log(` - ${c.desc}`);
|
||||
}
|
||||
|
||||
const waybills = cases.map(c => c.waybill).filter(code => code && code !== '-');
|
||||
const results = [];
|
||||
|
||||
for (const item of cases) {
|
||||
const requestId = `UATTEST${item.tag}${Date.now()}`;
|
||||
const extId = `api:${APP_KEY}:${requestId}`;
|
||||
console.log('\n' + '='.repeat(96));
|
||||
console.log(`【用例 ${item.tag}】${item.desc}`);
|
||||
console.log(`正文: ${JSON.stringify(item.content)}`);
|
||||
console.log(`requestId=${requestId} ext_id=${extId}`);
|
||||
|
||||
const pushRes = await pushMessage({
|
||||
appKey: APP_KEY,
|
||||
secret: app.self_app_secret,
|
||||
requestId,
|
||||
content: item.content,
|
||||
});
|
||||
console.log(`入站响应: HTTP ${pushRes.status} ${pushRes.text}`);
|
||||
|
||||
const { inbound, replies, timedOut } = await waitProcessed(conn, extId);
|
||||
if (!inbound) {
|
||||
console.log('❌ 未查到入站消息记录,请检查 dev 服务日志');
|
||||
results.push({ ...item, ok: false, note: '未查到入站记录' });
|
||||
continue;
|
||||
}
|
||||
const thoughts = Array.isArray(inbound.ai_thoughts)
|
||||
? inbound.ai_thoughts
|
||||
: (inbound.ai_thoughts ? [ inbound.ai_thoughts ] : []);
|
||||
const fnName = thoughts[0] ? thoughts[0].function || '-' : '-';
|
||||
console.log(`\n入站记录: id=${inbound.id} group=${inbound.group_name} 用户=${inbound.user_name}`);
|
||||
console.log(` ai_thoughts = ${inbound.ai_thoughts ? JSON.stringify(inbound.ai_thoughts) : 'null'}`);
|
||||
console.log(` push_status = ${inbound.push_status}`);
|
||||
if (replies.length === 0) {
|
||||
console.log(` ⚠ 无回信记录${timedOut ? '(等待超时)' : ''}`);
|
||||
} else {
|
||||
for (const r of replies) {
|
||||
console.log(` 回信 id=${r.id} push_status=${r.push_status}: ${JSON.stringify(r.content)}`);
|
||||
}
|
||||
}
|
||||
if (timedOut) console.log(' (等待处理超时,可能仍在异步处理中)');
|
||||
results.push({
|
||||
...item,
|
||||
inboundId: inbound.id,
|
||||
fn: fnName,
|
||||
reply: replies.map(r => r.content).join(' | ') || '(无回信)',
|
||||
ok: replies.length > 0,
|
||||
});
|
||||
}
|
||||
|
||||
const { express, afterSales, orders } = await collectSideEffects(conn, waybills);
|
||||
console.log('\n' + '='.repeat(96));
|
||||
console.log('副作用核对(本地库,保留不清理)');
|
||||
console.log('运单:');
|
||||
for (const e of express) {
|
||||
console.log(` express id=${e.id} ${e.waybill_code} order_id=${e.order_id} store_id=${e.store_id} is_intercept=${e.is_intercept}`);
|
||||
}
|
||||
console.log('售后工单:');
|
||||
for (const a of afterSales) {
|
||||
console.log(` ${a.after_sale_no} waybill=${a.waybill_no} ${a.type}/${a.sub_type} status=${a.status}\n title=${a.title}`);
|
||||
}
|
||||
if (afterSales.length === 0) console.log(' (无)');
|
||||
console.log('订单拦截状态:');
|
||||
for (const o of orders) {
|
||||
console.log(` order id=${o.id} step=${o.step} wave_id=${o.wave_id} intercept_status=${o.intercept_status} intercept_time=${o.intercept_time ? o.intercept_time.toISOString() : null}`);
|
||||
}
|
||||
if (orders.length === 0) console.log(' (无)');
|
||||
|
||||
console.log('\n' + '='.repeat(96));
|
||||
console.log('汇总');
|
||||
let pass = 0;
|
||||
for (const r of results) {
|
||||
if (r.ok) pass++;
|
||||
console.log(
|
||||
`${r.ok ? '✅' : '❌'} 用例${r.tag} ${r.waybill} | fn=${r.fn || '-'} | 入站id=${r.inboundId || '-'} | ${r.reply}`
|
||||
);
|
||||
}
|
||||
console.log(`\n有回信用例:${pass}/${results.length}`);
|
||||
|
||||
await conn.end();
|
||||
})().catch(err => {
|
||||
console.error('脚本执行失败:', err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@ -1,78 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 复现 getWaveStrategyFetchCandidateOrders 的第一池查询,
|
||||
* 验证 createdBefore='2026-09-06 00:00:00' 时 8 条今日前订单是否被命中。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
async function main() {
|
||||
const connection = await mysql.createConnection({
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
});
|
||||
|
||||
try {
|
||||
const warehouseId = 100000;
|
||||
const createdBefore = new Date(2026, 8, 6, 0, 0, 0);
|
||||
const minSameStructure = 2;
|
||||
const maxSameStructure = 999;
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT o.id, o.items_hash
|
||||
FROM wms_order_wave_strategy_match m
|
||||
INNER JOIN wms_order_delivery_100000 o
|
||||
ON o.id = m.order_id
|
||||
AND o.warehouse_id = ?
|
||||
AND o.wave_id = 0
|
||||
AND o.step != 0
|
||||
AND o.post_status = 'fin'
|
||||
AND o.storage_status = 'fin'
|
||||
AND o.print_status != 'fin'
|
||||
AND o.status != 'cancel'
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
AND (? IS NULL OR o.create_at < ?)
|
||||
INNER JOIN (
|
||||
SELECT
|
||||
src.items_hash AS structure_key,
|
||||
COUNT(1) AS same_structure_count
|
||||
FROM wms_order_delivery_100000 src
|
||||
WHERE src.warehouse_id = ?
|
||||
AND src.wave_id = 0
|
||||
AND src.step != 0
|
||||
AND src.post_status = 'fin'
|
||||
AND src.storage_status = 'fin'
|
||||
AND src.print_status != 'fin'
|
||||
AND src.status != 'cancel'
|
||||
AND src.outbound_status != 'padding'
|
||||
AND src.intercept_status = 'none'
|
||||
AND src.lock_status = 'none'
|
||||
GROUP BY src.items_hash
|
||||
) same_structure
|
||||
ON same_structure.structure_key = o.items_hash
|
||||
WHERE m.warehouse_id = ?
|
||||
AND m.strategy_id = 7
|
||||
AND same_structure.same_structure_count >= ?
|
||||
AND (? IS NULL OR same_structure.same_structure_count <= ?)
|
||||
ORDER BY o.id ASC`,
|
||||
[ warehouseId, createdBefore, createdBefore, warehouseId, warehouseId, minSameStructure, maxSameStructure, maxSameStructure ]
|
||||
);
|
||||
|
||||
console.log(`第一池(createdBefore=2026-09-06 00:00)命中数: ${rows.length}`);
|
||||
console.log(JSON.stringify(rows.slice(0, 30)));
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`查询失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,28 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 只读脚本:读取生产环境最后一次发布信息(不触发任何发布/回退动作)。
|
||||
* 仅执行 cat / tail / ls / stat 等只读命令。
|
||||
*/
|
||||
|
||||
const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs');
|
||||
|
||||
function buildRemoteScript() {
|
||||
return [
|
||||
'set -uo pipefail',
|
||||
'ROOT=/www/wwwroot/qimen',
|
||||
'echo "===QIMEN_PROC_START==="',
|
||||
'ps -eo pid,lstart,cmd 2>/dev/null | grep "/www/wwwroot/qimen" | grep -v grep | head -6 || true',
|
||||
'echo "===V2_APP_NEWEST_FILES==="',
|
||||
'find "$ROOT/v2/app" "$ROOT/v2/methods" "$ROOT/v2/script" -type f -printf "%TY-%Tm-%Td %TH:%TM %p\\n" 2>/dev/null | sort | tail -12 || true',
|
||||
'echo "===V2_CONFIG_NEWEST==="',
|
||||
'find "$ROOT/v2/config" -maxdepth 1 -type f -printf "%TY-%Tm-%Td %TH:%TM %p\\n" 2>/dev/null | sort | tail -6 || true',
|
||||
'echo "===V2_APP_DIR_LS==="',
|
||||
'ls -lt --time-style=long-iso "$ROOT/v2/app" 2>/dev/null | head -6',
|
||||
'echo "===INCOMING_ALL==="',
|
||||
'ls -lt --time-style=long-iso "$ROOT/.deploy/incoming" 2>/dev/null || echo MISSING',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const config = loadDeployConfig('production');
|
||||
console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' }));
|
||||
@ -1,421 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const acorn = require('acorn');
|
||||
|
||||
const baseDir = process.cwd();
|
||||
const methodsDir = path.join(baseDir, 'app', 'service', 'systemMethods');
|
||||
const jsonPath = path.join(baseDir, 'methods', 'system.json');
|
||||
|
||||
function walk(node, visitor, parent = null) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
visitor(node, parent);
|
||||
for (const key of Object.keys(node)) {
|
||||
const value = node[key];
|
||||
if (!value) continue;
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) walk(item, visitor, node);
|
||||
} else if (typeof value === 'object' && value.type) {
|
||||
walk(value, visitor, node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function walkFiles(dir) {
|
||||
const files = [];
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) files.push(...walkFiles(full));
|
||||
if (entry.isFile() && entry.name.endsWith('.js')) files.push(full);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function getPropName(node) {
|
||||
if (!node) return null;
|
||||
if (node.type === 'Identifier') return node.name;
|
||||
if (node.type === 'Literal') return String(node.value);
|
||||
return null;
|
||||
}
|
||||
|
||||
function memberPath(node) {
|
||||
if (!node) return null;
|
||||
if (node.type === 'ChainExpression') return memberPath(node.expression);
|
||||
if (node.type === 'Identifier') return node.name;
|
||||
if (node.type === 'ThisExpression') return 'this';
|
||||
if (node.type !== 'MemberExpression') return null;
|
||||
const left = memberPath(node.object);
|
||||
if (!left) return null;
|
||||
if (node.computed) {
|
||||
if (node.property.type === 'Literal') return `${left}.${String(node.property.value)}`;
|
||||
if (node.property.type === 'Identifier') return left;
|
||||
return left;
|
||||
}
|
||||
const right = getPropName(node.property);
|
||||
return right ? `${left}.${right}` : left;
|
||||
}
|
||||
|
||||
function classifySourceByExpr(expr, signatureSet) {
|
||||
const sources = new Set();
|
||||
const visit = node => {
|
||||
if (!node) return;
|
||||
if (node.type === 'Identifier' && signatureSet.has(node.name)) {
|
||||
sources.add('body');
|
||||
return;
|
||||
}
|
||||
if (node.type === 'MemberExpression' || node.type === 'ChainExpression') {
|
||||
const p = memberPath(node);
|
||||
if (p && p.startsWith('ctx.request.body')) sources.add('body');
|
||||
else if (p && p.startsWith('ctx.query')) sources.add('query');
|
||||
else if (p && p.startsWith('ctx.params')) sources.add('path');
|
||||
else if (p && p.startsWith('ctx.headers')) sources.add('header');
|
||||
return;
|
||||
}
|
||||
if (node.type === 'LogicalExpression' || node.type === 'BinaryExpression') {
|
||||
visit(node.left);
|
||||
visit(node.right);
|
||||
return;
|
||||
}
|
||||
if (node.type === 'ConditionalExpression') {
|
||||
visit(node.consequent);
|
||||
visit(node.alternate);
|
||||
return;
|
||||
}
|
||||
};
|
||||
visit(expr);
|
||||
if (!sources.size) return null;
|
||||
return Array.from(sources).sort().join('|');
|
||||
}
|
||||
|
||||
function inferTypeByName(name) {
|
||||
if (!name) return 'string';
|
||||
if (/ids$/i.test(name)) return 'array';
|
||||
if (/^(where|pagination|item|template|data|filters?)$/i.test(name)) return 'object';
|
||||
if (/^(is_|has_|need|sync)/i.test(name)) return 'boolean';
|
||||
if (/(^id$|_id$|^page$|^pageSize$|^limit$|^offset$|^count$|_count$|^x$|^y$|^z$|^rows$|^columns$|^levels$|^width$|^height$|^length$)/i.test(name)) return 'number';
|
||||
if (/(^date$|_date$|^time$|_time$|timestamp)/i.test(name)) return 'string';
|
||||
return 'string';
|
||||
}
|
||||
|
||||
function inferTypeByNode(node, fallbackName = '') {
|
||||
if (!node) return inferTypeByName(fallbackName);
|
||||
if (node.type === 'Literal') {
|
||||
if (typeof node.value === 'number') return 'number';
|
||||
if (typeof node.value === 'boolean') return 'boolean';
|
||||
return 'string';
|
||||
}
|
||||
if (node.type === 'ObjectExpression') return 'object';
|
||||
if (node.type === 'ArrayExpression') return 'array';
|
||||
return inferTypeByName(fallbackName);
|
||||
}
|
||||
|
||||
function mapValidateType(v) {
|
||||
if (!v) return 'string';
|
||||
const t = String(v).toLowerCase();
|
||||
if (t === 'int' || t === 'integer' || t === 'number') return 'number';
|
||||
if (t === 'boolean' || t === 'bool') return 'boolean';
|
||||
if (t === 'array') return 'array';
|
||||
if (t === 'object') return 'object';
|
||||
return 'string';
|
||||
}
|
||||
|
||||
function extractNoNeedLists(classNode) {
|
||||
const result = { noNeedLogin: [], noNeedAuth: ['*'] };
|
||||
const ctor = classNode.body.body.find(m => m.type === 'MethodDefinition' && m.kind === 'constructor');
|
||||
if (!ctor) return result;
|
||||
|
||||
for (const stmt of ctor.value.body.body || []) {
|
||||
if (stmt.type !== 'VariableDeclaration') continue;
|
||||
for (const decl of stmt.declarations || []) {
|
||||
if (decl.id.type !== 'Identifier' || !decl.init || decl.init.type !== 'Literal') continue;
|
||||
const name = decl.id.name;
|
||||
const value = String(decl.init.value || '');
|
||||
if (name === '_noNeedLogin') result.noNeedLogin = value.split(',').map(s => s.trim()).filter(Boolean);
|
||||
if (name === '_noNeedAuth') result.noNeedAuth = value.split(',').map(s => s.trim()).filter(Boolean);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectMethodParams(methodNode) {
|
||||
const signatureNames = [];
|
||||
for (const p of methodNode.value.params || []) {
|
||||
if (p.type === 'Identifier') signatureNames.push(p.name);
|
||||
else if (p.type === 'AssignmentPattern' && p.left.type === 'Identifier') signatureNames.push(p.left.name);
|
||||
}
|
||||
const signatureSet = new Set(signatureNames);
|
||||
const aliasMap = new Map();
|
||||
const entries = new Map();
|
||||
const listFields = [];
|
||||
|
||||
function resolveName(localName) {
|
||||
return aliasMap.get(localName) || localName;
|
||||
}
|
||||
|
||||
function ensure(name) {
|
||||
if (!entries.has(name)) {
|
||||
entries.set(name, {
|
||||
name,
|
||||
type: inferTypeByName(name),
|
||||
required: false,
|
||||
source: new Set(),
|
||||
});
|
||||
}
|
||||
return entries.get(name);
|
||||
}
|
||||
|
||||
function addParam(name, patch = {}) {
|
||||
if (!name) return;
|
||||
if ([ 'ctx', 'service', 'app', 'result', 'error', 'e' ].includes(name)) return;
|
||||
const item = ensure(name);
|
||||
if (patch.type) item.type = patch.type;
|
||||
if (patch.required === true) item.required = true;
|
||||
if (patch.source) item.source.add(patch.source);
|
||||
}
|
||||
|
||||
function addRequiredFromTest(testNode) {
|
||||
if (!testNode) return;
|
||||
if (testNode.type === 'UnaryExpression' && testNode.operator === '!') {
|
||||
if (testNode.argument.type === 'Identifier') {
|
||||
const local = testNode.argument.name;
|
||||
const resolved = resolveName(local);
|
||||
if (resolved !== local || entries.has(resolved)) {
|
||||
addParam(resolved, { required: true });
|
||||
}
|
||||
}
|
||||
if (testNode.argument.type === 'MemberExpression' || testNode.argument.type === 'ChainExpression') {
|
||||
const p = memberPath(testNode.argument);
|
||||
if (!p) return;
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) {
|
||||
addParam(parts[1], { required: true, source: 'body' });
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (testNode.type === 'LogicalExpression') {
|
||||
addRequiredFromTest(testNode.left);
|
||||
addRequiredFromTest(testNode.right);
|
||||
return;
|
||||
}
|
||||
if (testNode.type === 'CallExpression') {
|
||||
const callee = memberPath(testNode.callee);
|
||||
if (callee === 'Array.isArray' && testNode.arguments[0] && testNode.arguments[0].type === 'Identifier') {
|
||||
const local = testNode.arguments[0].name;
|
||||
const resolved = resolveName(local);
|
||||
if (resolved !== local || entries.has(resolved)) {
|
||||
addParam(resolved, { required: true, type: 'array' });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(methodNode.value.body, (node, parent) => {
|
||||
if (node.type === 'VariableDeclarator') {
|
||||
if (node.id.type === 'ObjectPattern' && node.init) {
|
||||
const source = classifySourceByExpr(node.init, signatureSet);
|
||||
if (!source) return;
|
||||
for (const prop of node.id.properties || []) {
|
||||
if (prop.type !== 'Property') continue;
|
||||
const keyName = getPropName(prop.key);
|
||||
if (!keyName) continue;
|
||||
|
||||
let localName = keyName;
|
||||
let type = inferTypeByName(keyName);
|
||||
|
||||
if (prop.value.type === 'Identifier') {
|
||||
localName = prop.value.name;
|
||||
} else if (prop.value.type === 'AssignmentPattern') {
|
||||
if (prop.value.left.type === 'Identifier') localName = prop.value.left.name;
|
||||
type = inferTypeByNode(prop.value.right, keyName);
|
||||
}
|
||||
|
||||
aliasMap.set(localName, keyName);
|
||||
addParam(keyName, { source, type });
|
||||
}
|
||||
}
|
||||
|
||||
if (node.id.type === 'Identifier' && node.init) {
|
||||
const local = node.id.name;
|
||||
|
||||
if (node.init.type === 'MemberExpression' || node.init.type === 'ChainExpression') {
|
||||
const p = memberPath(node.init);
|
||||
if (p) {
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) {
|
||||
aliasMap.set(local, parts[1]);
|
||||
addParam(parts[1], { source: 'body' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') {
|
||||
aliasMap.set(local, parts[2]);
|
||||
addParam(parts[2], { source: 'query' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') {
|
||||
aliasMap.set(local, parts[2]);
|
||||
addParam(parts[2], { source: 'path' });
|
||||
}
|
||||
if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') {
|
||||
aliasMap.set(local, parts[3]);
|
||||
addParam(parts[3], { source: 'body' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((/allowedFields|eqFields/i).test(local) && node.init.type === 'ArrayExpression') {
|
||||
const arr = [];
|
||||
for (const el of node.init.elements || []) {
|
||||
if (el && el.type === 'Literal' && typeof el.value === 'string') arr.push(el.value);
|
||||
}
|
||||
if (arr.length) listFields.push(...arr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (node.type === 'IfStatement') {
|
||||
addRequiredFromTest(node.test);
|
||||
}
|
||||
|
||||
if (node.type === 'CallExpression') {
|
||||
const callee = memberPath(node.callee);
|
||||
|
||||
if (callee === 'ctx.validate' && node.arguments[0] && node.arguments[0].type === 'ObjectExpression') {
|
||||
for (const p of node.arguments[0].properties || []) {
|
||||
if (p.type !== 'Property') continue;
|
||||
const field = getPropName(p.key);
|
||||
if (!field || p.value.type !== 'ObjectExpression') continue;
|
||||
let required = false;
|
||||
let type = null;
|
||||
for (const conf of p.value.properties || []) {
|
||||
if (conf.type !== 'Property') continue;
|
||||
const confKey = getPropName(conf.key);
|
||||
if (!confKey) continue;
|
||||
if (confKey === 'required' && conf.value.type === 'Literal') {
|
||||
required = Boolean(conf.value.value);
|
||||
}
|
||||
if (confKey === 'type' && conf.value.type === 'Literal') {
|
||||
type = mapValidateType(conf.value.value);
|
||||
}
|
||||
}
|
||||
addParam(field, { required, type: type || inferTypeByName(field), source: 'body' });
|
||||
}
|
||||
}
|
||||
|
||||
if (callee === 'Array.isArray' && node.arguments[0] && node.arguments[0].type === 'Identifier') {
|
||||
const local = node.arguments[0].name;
|
||||
const resolved = resolveName(local);
|
||||
if (resolved !== local || entries.has(resolved)) {
|
||||
addParam(resolved, { type: 'array' });
|
||||
}
|
||||
}
|
||||
|
||||
if ((callee === 'parseInt' || callee === 'Number') && node.arguments[0]) {
|
||||
const arg = node.arguments[0];
|
||||
if (arg.type === 'Identifier') {
|
||||
const resolved = resolveName(arg.name);
|
||||
if (resolved !== arg.name || entries.has(resolved)) {
|
||||
addParam(resolved, { type: 'number' });
|
||||
}
|
||||
}
|
||||
if (arg.type === 'MemberExpression' || arg.type === 'ChainExpression') {
|
||||
const p = memberPath(arg);
|
||||
if (p) {
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) addParam(parts[1], { type: 'number', source: 'body' });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (node.type === 'MemberExpression' || node.type === 'ChainExpression') {
|
||||
const p = memberPath(node);
|
||||
if (!p) return;
|
||||
const parts = p.split('.');
|
||||
if (parts.length === 2 && signatureSet.has(parts[0])) {
|
||||
addParam(parts[1], { source: 'body' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'query') {
|
||||
addParam(parts[2], { source: 'query' });
|
||||
}
|
||||
if (parts.length >= 3 && parts[0] === 'ctx' && parts[1] === 'params') {
|
||||
addParam(parts[2], { source: 'path' });
|
||||
}
|
||||
if (parts.length >= 4 && parts[0] === 'ctx' && parts[1] === 'request' && parts[2] === 'body') {
|
||||
addParam(parts[3], { source: 'body' });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for (const f of listFields) {
|
||||
addParam(f, { source: 'body' });
|
||||
}
|
||||
|
||||
const result = Array.from(entries.values()).map(item => ({
|
||||
name: item.name,
|
||||
type: item.type,
|
||||
required: item.required,
|
||||
source: item.source.size ? Array.from(item.source).sort().join('|') : 'body',
|
||||
description: `${item.name} 参数`,
|
||||
}));
|
||||
|
||||
result.sort((a, b) => {
|
||||
if (a.required !== b.required) return a.required ? -1 : 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildMethodParamMap() {
|
||||
const map = new Map();
|
||||
const files = walkFiles(methodsDir);
|
||||
|
||||
for (const file of files) {
|
||||
const source = fs.readFileSync(file, 'utf8');
|
||||
const ast = acorn.parse(source, { ecmaVersion: 'latest', sourceType: 'script' });
|
||||
const relative = path.relative(methodsDir, file).replace(/\\/g, '/').replace(/\.js$/, '');
|
||||
const moduleName = relative.replace(/\//g, '.');
|
||||
|
||||
for (const node of ast.body) {
|
||||
if (node.type !== 'ClassDeclaration') continue;
|
||||
const noNeed = extractNoNeedLists(node);
|
||||
for (const method of node.body.body) {
|
||||
if (method.type !== 'MethodDefinition') continue;
|
||||
if (method.kind !== 'method') continue;
|
||||
if (!method.value.async) continue;
|
||||
const methodName = method.key && method.key.name;
|
||||
if (!methodName) continue;
|
||||
|
||||
const fullMethod = `${moduleName}.${methodName}`;
|
||||
const params = collectMethodParams(method);
|
||||
|
||||
for (const p of params) {
|
||||
if (noNeed.noNeedLogin.includes('*') || noNeed.noNeedLogin.includes(methodName)) {
|
||||
if (p.name.toLowerCase().includes('authorization') || p.source === 'header') p.required = false;
|
||||
}
|
||||
}
|
||||
|
||||
map.set(fullMethod, params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
const methodParamMap = buildMethodParamMap();
|
||||
const doc = JSON.parse(fs.readFileSync(jsonPath, 'utf8'));
|
||||
|
||||
let updated = 0;
|
||||
for (const group of doc.methods.groups || []) {
|
||||
for (const item of group.list || []) {
|
||||
const next = methodParamMap.get(item.method) || [];
|
||||
item.params = next;
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
doc.version = '0.3.0';
|
||||
doc.updatedAt = '2026-03-22';
|
||||
|
||||
fs.writeFileSync(jsonPath, JSON.stringify(doc, null, 2) + '\n', 'utf8');
|
||||
console.log(`updated methods: ${updated}`);
|
||||
console.log(`mapped methods: ${methodParamMap.size}`);
|
||||
@ -1,60 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 本地自测桩:模拟远端只读探测输出,验证 check-root-logs.cjs 的
|
||||
* --clean dry-run 删除计划逻辑(不连接任何真实服务器)。
|
||||
*
|
||||
* 用法:node script/tmp-test-clean-plan.cjs --clean
|
||||
*/
|
||||
|
||||
const path = require('node:path');
|
||||
|
||||
const deployLibPath = require.resolve('./deploy-lib.cjs');
|
||||
|
||||
/**
|
||||
* 构造模拟的远端探测输出:
|
||||
* 总大小约 6.37 GiB(超过 4 GiB 阈值),包含活跃日志、7 个轮转日志、
|
||||
* 其他命名模式的日志与 .gz 文件,用于验证排除规则与删除计划
|
||||
*
|
||||
* @return {string} 模拟的远端探测标准输出
|
||||
*/
|
||||
function buildFakeProbeOutput() {
|
||||
const files = [
|
||||
// 正在写入的活跃日志(无日期后缀),必须被排除
|
||||
{ mtime: 1757780000, size: 1181116006, filePath: '/root/logs/wms/wms-web.log' },
|
||||
// 历史轮转日志(mtime 升序,最旧的 4 个较大)
|
||||
{ mtime: 1756150000, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-24' },
|
||||
{ mtime: 1756236400, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-25' },
|
||||
{ mtime: 1756322800, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-26' },
|
||||
{ mtime: 1756409200, size: 1288490188, filePath: '/root/logs/wms/wms-web.log.2026-08-27' },
|
||||
{ mtime: 1756495600, size: 214748365, filePath: '/root/logs/wms/wms-web.log.2026-08-28' },
|
||||
{ mtime: 1756582000, size: 107374182, filePath: '/root/logs/wms/wms-web.log.2026-08-29' },
|
||||
{ mtime: 1756668400, size: 107374182, filePath: '/root/logs/wms/wms-web.log.2026-08-30' },
|
||||
// 非 wms-web 轮转命名模式的文件,必须被排除
|
||||
{ mtime: 1756583000, size: 29360128, filePath: '/root/logs/wms/common-error.log.2026-08-29' },
|
||||
{ mtime: 1756720000, size: 12582912, filePath: '/root/logs/wms/egg-schedule.log.2026-08-31' },
|
||||
// .gz 后缀文件不符合严格命名模式,必须被排除
|
||||
{ mtime: 1756730000, size: 31457280, filePath: '/root/logs/wms/wms-web.log.2026-08-31.gz' },
|
||||
];
|
||||
const totalBytes = files.reduce((sum, item) => sum + item.size, 0);
|
||||
return [
|
||||
`PROBE_TOTAL_BYTES=${totalBytes}`,
|
||||
...files.map(item => `${item.mtime}\t${item.size}\t${item.filePath}`),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
// 将 deploy-lib.cjs 替换为本地桩,避免真实 SSH 连接
|
||||
require.cache[deployLibPath] = {
|
||||
id: deployLibPath,
|
||||
filename: deployLibPath,
|
||||
loaded: true,
|
||||
exports: {
|
||||
ensureCommandAvailable() {},
|
||||
loadDeployConfig: () => ({ envName: 'production', username: 'root', host: '127.0.0.1', port: 22 }),
|
||||
quoteForBash: value => `'${String(value)}'`,
|
||||
runSsh: () => buildFakeProbeOutput(),
|
||||
},
|
||||
};
|
||||
|
||||
// 加载被测脚本(其 main() 会读取当前进程参数,即 --clean)
|
||||
require(path.resolve(__dirname, 'check-root-logs.cjs'));
|
||||
@ -1,136 +0,0 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 批次维度对比测试(真实接口):
|
||||
* 1. A 两步:批次 B-A-1 入库 10 件 → storage 建行
|
||||
* 2. B 一步:批次 B-B-1 入库 10 件 → storage 建行(不同批次不互相影响)
|
||||
* 3. A 两步:批次 B-A-1 再入库 5 件 → 同批次累加到 15
|
||||
* 4. B 一步:批次 B-B-1 再入库 5 件 → 同批次累加到 15
|
||||
* 商品 159061 / 库位 5918。测试数据不清理。
|
||||
*/
|
||||
const mysql = require('mysql2/promise');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const BASE = 'http://127.0.0.1:6060';
|
||||
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
|
||||
const ACCOUNT_ID = 1;
|
||||
const STORE_ID = 1000000;
|
||||
const STOCK_ID = 159061;
|
||||
const SPACE_ID = 5918;
|
||||
|
||||
const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 });
|
||||
|
||||
async function db() {
|
||||
return mysql.createConnection({ host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms' });
|
||||
}
|
||||
|
||||
async function call(method, data) {
|
||||
const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(data || {}),
|
||||
});
|
||||
const text = await res.text();
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(text); } catch { parsed = text; }
|
||||
return { http: res.status, body: parsed };
|
||||
}
|
||||
|
||||
function step(name, res) {
|
||||
const code = res.body && res.body.code;
|
||||
const ok = res.http === 200 && res.body && res.body.flag === 'success' && (code === 200 || code === 1);
|
||||
console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${code} msg=${res.body && res.body.message}`);
|
||||
if (!ok) console.log(' 响应:', JSON.stringify(res.body).slice(0, 600));
|
||||
return ok;
|
||||
}
|
||||
|
||||
async function runFlow(tag, mode, batchNo, qty) {
|
||||
console.log(`\n===== ${tag}:批次=${batchNo} 数量=${qty} =====`);
|
||||
const conn = await db();
|
||||
const [before] = await conn.query(
|
||||
`SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ]
|
||||
);
|
||||
|
||||
// 收货单全链路
|
||||
const createRes = await call('storage.receiving.create', {
|
||||
store_id: STORE_ID, delivery_method: 'other', loading_method: 'with_pallet',
|
||||
remark: `[批次对比-${tag}-${batchNo}]`, status: 'receiving',
|
||||
});
|
||||
const b = createRes.body || {};
|
||||
const receivingId = (b.data && b.data.id) || b.id;
|
||||
if (!step('创建收货单', createRes)) { await conn.end(); return null; }
|
||||
|
||||
const addRes = await call('storage.receiving.addDetail', {
|
||||
receiving_id: receivingId,
|
||||
item: { product_name: '批次对比测试商品', barcode: `B${Date.now()}`, actual_quantity: qty, batch_number: batchNo, space_id: SPACE_ID },
|
||||
});
|
||||
const addBody = addRes.body || {};
|
||||
const addData = addBody.data || addBody;
|
||||
const detailId = addData.selectId || (addData.details && addData.details[0] && addData.details[0].id);
|
||||
if (!step('添加明细', addRes)) { await conn.end(); return null; }
|
||||
|
||||
if (!step('绑定商品', await call('storage.receiving.bindDetailProduct', { detail_id: detailId, system_product_id: STOCK_ID }))) { await conn.end(); return null; }
|
||||
if (!step('完成收货', await call('storage.receiving.completeReceiving', { id: receivingId }))) { await conn.end(); return null; }
|
||||
if (!step('审核', await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] }))) { await conn.end(); return null; }
|
||||
|
||||
let entryOrderId;
|
||||
if (mode === 'A') {
|
||||
const pRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId });
|
||||
if (!step('quickPutaway', pRes)) { await conn.end(); return null; }
|
||||
entryOrderId = pRes.body.data.entry_order_id;
|
||||
if (!step('addItem(绑定收货明细)', await call('storage.entry.addItem', {
|
||||
entry_order_id: entryOrderId,
|
||||
items: [{ stock_id: STOCK_ID, quantity: qty, space_id: SPACE_ID, receiving_detail_id: detailId, allocated_quantity: qty, inbound_type: 'pda' }],
|
||||
}))) { await conn.end(); return null; }
|
||||
if (!step('commit', await call('storage.entry.commit', { entry_order_id: entryOrderId }))) { await conn.end(); return null; }
|
||||
} else {
|
||||
const dRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId });
|
||||
if (!step('directPutaway', dRes)) { await conn.end(); return null; }
|
||||
entryOrderId = dRes.body.data.entry_order_id;
|
||||
}
|
||||
|
||||
const [after] = await conn.query(
|
||||
`SELECT quantity FROM wms_stock_warehouse WHERE id = ?`, [ STOCK_ID ]
|
||||
);
|
||||
console.log(` ── wms_stock_warehouse ${STOCK_ID}: ${before[0].quantity} → ${after[0].quantity}(+${qty})`);
|
||||
|
||||
const [storages] = await conn.query(
|
||||
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, available_quantity, inbound_order_no, entry_order_id
|
||||
FROM wms_storage WHERE stock_id = ? AND space_id = ? ORDER BY batch_no`, [ STOCK_ID, SPACE_ID ]
|
||||
);
|
||||
console.log(' ── wms_storage(商品 159061 / 库位 5918 全部行)──');
|
||||
console.log(' ', JSON.stringify(storages));
|
||||
|
||||
await conn.end();
|
||||
return { receivingId, entryOrderId };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await runFlow('① A-两步', 'A', 'B-A-1', 10);
|
||||
await runFlow('② B-一步', 'B', 'B-B-1', 10);
|
||||
await runFlow('③ A-两步(同批次累加)', 'A', 'B-A-1', 5);
|
||||
await runFlow('④ B-一步(同批次累加)', 'B', 'B-B-1', 5);
|
||||
|
||||
const conn = await db();
|
||||
const [storages] = await conn.query(
|
||||
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, inbound_order_no, receiving_id, entry_order_id
|
||||
FROM wms_storage WHERE stock_id = 159061 AND space_id = 5918 ORDER BY batch_no`
|
||||
);
|
||||
console.log('\n========== 最终 wms_storage 对比(商品 159061 / 库位 5918) ==========');
|
||||
console.log(JSON.stringify(storages, null, 2));
|
||||
|
||||
const [txns] = await conn.query(
|
||||
`SELECT order_no, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type
|
||||
FROM wms_storage_transaction WHERE stock_id = 159061 AND space_id = 5918 AND batch_no IN ('B-A-1','B-B-1') ORDER BY id`
|
||||
);
|
||||
console.log('\n========== 库位流水(批次 B-A-1 / B-B-1) ==========');
|
||||
console.log(JSON.stringify(txns, null, 2));
|
||||
await conn.end();
|
||||
console.log('\n================ 批次对比测试结束 ================');
|
||||
}
|
||||
|
||||
main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,261 +0,0 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 临时对比测试:quickPutaway(转入库单) vs directPutaway(直入库存)
|
||||
* 全链路走真实接口:创建收货单 → 添加明细 → 绑定商品 → 完成收货 → 审核 → 上架。
|
||||
* 测试数据不清理,保留以便核对。
|
||||
* 用法:node script/tmp-test-putaway-compare.cjs
|
||||
*/
|
||||
const mysql = require('mysql2/promise');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const BASE = 'http://127.0.0.1:6060';
|
||||
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
|
||||
const ACCOUNT_ID = 1;
|
||||
const WAREHOUSE_ID = 100000;
|
||||
const STORE_ID = 1000000;
|
||||
|
||||
// 商品:159061 非批次非效期;159064 效期管理(非批次)
|
||||
const PRODUCTS = [
|
||||
{ stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null },
|
||||
{ stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null },
|
||||
];
|
||||
|
||||
const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 });
|
||||
|
||||
async function db() {
|
||||
return mysql.createConnection({
|
||||
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
|
||||
});
|
||||
}
|
||||
|
||||
async function call(method, data) {
|
||||
const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(data || {}),
|
||||
});
|
||||
const text = await res.text();
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(text); } catch { parsed = text; }
|
||||
return { http: res.status, body: parsed };
|
||||
}
|
||||
|
||||
function step(name, res, extract) {
|
||||
const bodyCode = res.body && res.body.code;
|
||||
const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1);
|
||||
let extra = '';
|
||||
if (extract && res.body && res.body.data) {
|
||||
try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ }
|
||||
}
|
||||
console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`);
|
||||
return ok;
|
||||
}
|
||||
|
||||
async function runFlow(tag, putawayMethod) {
|
||||
console.log(`\n================ 流程 ${tag}(${putawayMethod}) ================`);
|
||||
const conn = await db();
|
||||
|
||||
// 快照入库前商品总库存
|
||||
const stockIds = PRODUCTS.map(p => p.stock_id);
|
||||
const [beforeStock] = await conn.query(
|
||||
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
|
||||
);
|
||||
|
||||
// 1. 创建收货单
|
||||
const createRes = await call('storage.receiving.create', {
|
||||
store_id: STORE_ID,
|
||||
delivery_method: 'other',
|
||||
loading_method: 'with_pallet',
|
||||
remark: `[自动对比测试-${tag}]`,
|
||||
status: 'receiving',
|
||||
});
|
||||
const createBody = createRes.body || {};
|
||||
const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id;
|
||||
const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number;
|
||||
if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) {
|
||||
console.log(' create 响应:', JSON.stringify(createBody).slice(0, 600));
|
||||
return { conn, receivingId: 0 };
|
||||
}
|
||||
console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`);
|
||||
|
||||
// 2. 添加明细(含库位)
|
||||
const detailIds = [];
|
||||
for (let i = 0; i < PRODUCTS.length; i++) {
|
||||
const p = PRODUCTS[i];
|
||||
const addRes = await call('storage.receiving.addDetail', {
|
||||
receiving_id: receivingId,
|
||||
item: {
|
||||
product_name: `对比测试商品${i + 1}`,
|
||||
barcode: `TMPBC${Date.now()}${i}`,
|
||||
actual_quantity: p.qty,
|
||||
batch_number: p.batch_number,
|
||||
production_date: p.production_date || null,
|
||||
expiry_date: p.expiry_date || null,
|
||||
space_id: p.space_id,
|
||||
},
|
||||
});
|
||||
const addBody = addRes.body || {};
|
||||
const addData = addBody.data || addBody;
|
||||
const newDetailId = addData.selectId
|
||||
|| (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id);
|
||||
if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) {
|
||||
console.log(' addDetail 响应:', JSON.stringify(addBody).slice(0, 600));
|
||||
return { conn, receivingId };
|
||||
}
|
||||
detailIds.push(newDetailId);
|
||||
}
|
||||
|
||||
// 3. 绑定系统商品
|
||||
for (let i = 0; i < PRODUCTS.length; i++) {
|
||||
const bindRes = await call('storage.receiving.bindDetailProduct', {
|
||||
detail_id: detailIds[i],
|
||||
system_product_id: PRODUCTS[i].stock_id,
|
||||
});
|
||||
if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) return { conn, receivingId };
|
||||
}
|
||||
|
||||
// 4. 完成收货
|
||||
const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId });
|
||||
if (!step('完成收货', completeRes, d => ({ status: d.status || d.receiving_status }))) {
|
||||
console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500));
|
||||
return { conn, receivingId };
|
||||
}
|
||||
|
||||
// 5. 审核
|
||||
const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] });
|
||||
if (!step('审核收货单', reviewRes)) {
|
||||
console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500));
|
||||
return { conn, receivingId };
|
||||
}
|
||||
|
||||
// 6. 上架
|
||||
const putawayRes = await call(putawayMethod, { receiving_id: receivingId });
|
||||
if (!step(`上架(${putawayMethod})`, putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) {
|
||||
console.log(' 上架响应:', JSON.stringify(putawayRes.body).slice(0, 800));
|
||||
return { conn, receivingId };
|
||||
}
|
||||
|
||||
// 7. 对比验证数据
|
||||
const entryOrderId = putawayRes.body.data.entry_order_id;
|
||||
const entryOrderCode = putawayRes.body.data.entry_order_code;
|
||||
|
||||
const [afterStock] = await conn.query(
|
||||
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
|
||||
);
|
||||
console.log(' ── 商品总库存(wms_stock_warehouse)──');
|
||||
for (const b of beforeStock) {
|
||||
const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' };
|
||||
console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`);
|
||||
}
|
||||
|
||||
const [entryOrder] = await conn.query(
|
||||
`SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ]
|
||||
);
|
||||
console.log(' ── 入库单(wms_entry_order)──');
|
||||
console.log(' ', JSON.stringify(entryOrder[0] || null));
|
||||
|
||||
const [entryItems] = await conn.query(
|
||||
`SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ]
|
||||
);
|
||||
console.log(' ── 入库单明细(wms_entry_items,共 ' + entryItems.length + ' 行)──');
|
||||
console.log(' ', JSON.stringify(entryItems));
|
||||
|
||||
const [orderReceiving] = await conn.query(
|
||||
`SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ]
|
||||
);
|
||||
console.log(' ── 绑定(wms_entry_order_receiving)──');
|
||||
console.log(' ', JSON.stringify(orderReceiving));
|
||||
|
||||
const [receivingRow] = await conn.query(
|
||||
`SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ]
|
||||
);
|
||||
console.log(' ── 收货单主表(wms_receiving)──');
|
||||
console.log(' ', JSON.stringify(receivingRow[0] || null));
|
||||
|
||||
const [receivingDetails] = await conn.query(
|
||||
`SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ]
|
||||
);
|
||||
console.log(' ── 收货明细(wms_receiving_detail)──');
|
||||
console.log(' ', JSON.stringify(receivingDetails));
|
||||
|
||||
const [storages] = await conn.query(
|
||||
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity,
|
||||
inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date
|
||||
FROM wms_storage
|
||||
WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?)
|
||||
ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ]
|
||||
);
|
||||
console.log(' ── 库位库存(wms_storage,共 ' + storages.length + ' 行)──');
|
||||
console.log(' ', JSON.stringify(storages));
|
||||
|
||||
const [stockTxns] = await conn.query(
|
||||
`SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id
|
||||
FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
|
||||
);
|
||||
console.log(' ── 商品流水(wms_stock_transaction,共 ' + stockTxns.length + ' 行)──');
|
||||
console.log(' ', JSON.stringify(stockTxns));
|
||||
|
||||
const [storageTxns] = await conn.query(
|
||||
`SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no
|
||||
FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
|
||||
);
|
||||
console.log(' ── 库位流水(wms_storage_transaction,共 ' + storageTxns.length + ' 行)──');
|
||||
console.log(' ', JSON.stringify(storageTxns));
|
||||
|
||||
const [opLogs] = await conn.query(
|
||||
`SELECT business_type, operation_code, business_id, operator_name, message
|
||||
FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(entryOrderId) ]
|
||||
);
|
||||
console.log(' ── 操作日志(wms_operation_log,共 ' + opLogs.length + ' 行)──');
|
||||
console.log(' ', JSON.stringify(opLogs));
|
||||
|
||||
await conn.end();
|
||||
return { receivingId, entryOrderId, entryOrderCode };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const conn = await db();
|
||||
// 取两个真实库位
|
||||
const [spaces] = await conn.query(
|
||||
`SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 3`,
|
||||
[ WAREHOUSE_ID ]
|
||||
);
|
||||
console.log('使用库位:', JSON.stringify(spaces));
|
||||
PRODUCTS[0].space_id = spaces[0].id;
|
||||
PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id;
|
||||
|
||||
// 开关状态:quick 已开(货主 1000000 配置为 1);direct 需开启
|
||||
const [beforePolicy] = await conn.query(
|
||||
`SELECT policy_config FROM wms_store_warehouse WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ]
|
||||
);
|
||||
console.log('货主 policy_config:', JSON.stringify(beforePolicy[0] && beforePolicy[0].policy_config));
|
||||
await conn.end();
|
||||
|
||||
// 流程 A:转入库单(可用 node script/tmp-test-putaway-compare.cjs A 单独跑)
|
||||
if (!process.argv[2] || process.argv[2] === 'A') {
|
||||
await runFlow('A-quickPutaway', 'storage.inventory.quickPutaway');
|
||||
}
|
||||
|
||||
// 开启直入开关(测试准备,SQL 直接配置)
|
||||
const conn2 = await db();
|
||||
await conn2.query(
|
||||
`UPDATE wms_store_warehouse SET policy_config = JSON_SET(COALESCE(policy_config,'{}'), '$.allow_receiving_direct_putaway', 1)
|
||||
WHERE store_id = ? AND warehouse_id = ?`, [ STORE_ID, WAREHOUSE_ID ]
|
||||
);
|
||||
await conn2.end();
|
||||
console.log('\n已开启 allow_receiving_direct_putaway=1(store=1000000, warehouse=100000)');
|
||||
|
||||
// 流程 B:直入库存
|
||||
if (!process.argv[2] || process.argv[2] === 'B') {
|
||||
await runFlow('B-directPutaway', 'storage.inventory.directPutaway');
|
||||
}
|
||||
|
||||
console.log('\n================ 测试结束 ================');
|
||||
}
|
||||
|
||||
main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,281 +0,0 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 临时完整对比测试:
|
||||
* 流程 A(两步):storage.inventory.quickPutaway(转入库单)
|
||||
* → storage.entry.addItem(导入入库,绑定收货明细)
|
||||
* → storage.entry.commit(提交确认写库存)
|
||||
* 流程 B(一步):storage.inventory.directPutaway(直入库存)
|
||||
* 收货单链路全部走真实接口。测试数据不清理。
|
||||
* 用法:node script/tmp-test-putaway-full-compare.cjs [A|B]
|
||||
*/
|
||||
const mysql = require('mysql2/promise');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
const BASE = 'http://127.0.0.1:6060';
|
||||
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
|
||||
const ACCOUNT_ID = 1;
|
||||
const WAREHOUSE_ID = 100000;
|
||||
const STORE_ID = 1000000;
|
||||
|
||||
const PRODUCTS = [
|
||||
{ stock_id: 159061, item_code: '20260703', qty: 30, batch_number: 'TQB1', space_id: null },
|
||||
{ stock_id: 159064, item_code: '544354', qty: 7, batch_number: 'TQB2', production_date: '2026-01-01', expiry_date: '2027-01-01', space_id: null },
|
||||
];
|
||||
|
||||
const token = jwt.sign({ id: ACCOUNT_ID }, JWT_SECRET, { expiresIn: 14400 });
|
||||
|
||||
async function db() {
|
||||
return mysql.createConnection({
|
||||
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
|
||||
});
|
||||
}
|
||||
|
||||
async function call(method, data) {
|
||||
const res = await fetch(`${BASE}/system?method=${method}&v=1×tamp=${Date.now()}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(data || {}),
|
||||
});
|
||||
const text = await res.text();
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(text); } catch { parsed = text; }
|
||||
return { http: res.status, body: parsed };
|
||||
}
|
||||
|
||||
function step(name, res, extract) {
|
||||
const bodyCode = res.body && res.body.code;
|
||||
const ok = res.http === 200 && res.body && res.body.flag === 'success' && (bodyCode === 200 || bodyCode === 1);
|
||||
let extra = '';
|
||||
if (extract && res.body && res.body.data) {
|
||||
try { extra = JSON.stringify(extract(res.body.data)); } catch (e) { /* ignore */ }
|
||||
}
|
||||
console.log(` [${ok ? 'OK' : 'FAIL'}] ${name} http=${res.http} code=${bodyCode} msg=${res.body && res.body.message} ${extra}`);
|
||||
return ok;
|
||||
}
|
||||
|
||||
async function verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock) {
|
||||
const stockIds = PRODUCTS.map(p => p.stock_id);
|
||||
const [afterStock] = await conn.query(
|
||||
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
|
||||
);
|
||||
console.log(` ── [${tag}] 商品总库存(wms_stock_warehouse)──`);
|
||||
for (const b of beforeStock) {
|
||||
const a = afterStock.find(x => String(x.id) === String(b.id)) || { quantity: '?', locked_quantity: '?' };
|
||||
console.log(` stock_id=${b.id} before=${b.quantity} after=${a.quantity} locked=${a.locked_quantity}`);
|
||||
}
|
||||
|
||||
const [entryOrder] = await conn.query(
|
||||
`SELECT id, entry_order_code, order_type, order_status, sync_status, total_order_lines FROM wms_entry_order WHERE id = ?`, [ entryOrderId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 入库单(wms_entry_order)──`);
|
||||
console.log(' ', JSON.stringify(entryOrder[0] || null));
|
||||
|
||||
const [entryItems] = await conn.query(
|
||||
`SELECT order_line_no, item_code, stock_id, count, received_quantity, inventory_type FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ entryOrderId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 入库单明细(wms_entry_items,共 ${entryItems.length} 行)──`);
|
||||
console.log(' ', JSON.stringify(entryItems));
|
||||
|
||||
const [orderReceiving] = await conn.query(
|
||||
`SELECT entry_order_id, receiving_id FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ entryOrderId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 绑定(wms_entry_order_receiving)──`);
|
||||
console.log(' ', JSON.stringify(orderReceiving));
|
||||
|
||||
const [receivingRow] = await conn.query(
|
||||
`SELECT id, status, is_review, storage_status, detail_status FROM wms_receiving WHERE id = ?`, [ receivingId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 收货单主表(wms_receiving)──`);
|
||||
console.log(' ', JSON.stringify(receivingRow[0] || null));
|
||||
|
||||
const [receivingDetails] = await conn.query(
|
||||
`SELECT id, system_product_id, actual_quantity, stored_quantity, storage_status, space_id, batch_number FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ receivingId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 收货明细(wms_receiving_detail)──`);
|
||||
console.log(' ', JSON.stringify(receivingDetails));
|
||||
|
||||
const [storages] = await conn.query(
|
||||
`SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity,
|
||||
inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date
|
||||
FROM wms_storage
|
||||
WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?)
|
||||
ORDER BY id`, [ entryOrderId, entryOrderCode, receivingId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 库位库存(wms_storage,共 ${storages.length} 行)──`);
|
||||
console.log(' ', JSON.stringify(storages));
|
||||
|
||||
const [stockTxns] = await conn.query(
|
||||
`SELECT transaction_type, stock_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id
|
||||
FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 商品流水(wms_stock_transaction,共 ${stockTxns.length} 行)──`);
|
||||
console.log(' ', JSON.stringify(stockTxns));
|
||||
|
||||
const [storageTxns] = await conn.query(
|
||||
`SELECT transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity, batch_no, order_type, order_no
|
||||
FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ entryOrderCode, entryOrderId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 库位流水(wms_storage_transaction,共 ${storageTxns.length} 行)──`);
|
||||
console.log(' ', JSON.stringify(storageTxns));
|
||||
|
||||
const [directLogs] = await conn.query(
|
||||
`SELECT id, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type
|
||||
FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ entryOrderId ]
|
||||
);
|
||||
console.log(` ── [${tag}] 导入入库记录(wms_inbound_direct_log,共 ${directLogs.length} 行)──`);
|
||||
console.log(' ', JSON.stringify(directLogs));
|
||||
|
||||
const [opLogs] = await conn.query(
|
||||
`SELECT business_type, operation_code, operator_name, message
|
||||
FROM wms_operation_log WHERE business_id = ? AND operation_code IN
|
||||
('ENTRY_ORDER_QUICK_PUTAWAY','ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT')
|
||||
ORDER BY id`, [ String(entryOrderId) ]
|
||||
);
|
||||
console.log(` ── [${tag}] 本流程操作日志(wms_operation_log,共 ${opLogs.length} 行)──`);
|
||||
console.log(' ', JSON.stringify(opLogs));
|
||||
}
|
||||
|
||||
async function runFlow(tag, mode) {
|
||||
console.log(`\n================ 流程 ${tag}(${mode}) ================`);
|
||||
const conn = await db();
|
||||
|
||||
const stockIds = PRODUCTS.map(p => p.stock_id);
|
||||
const [beforeStock] = await conn.query(
|
||||
`SELECT id, quantity, locked_quantity FROM wms_stock_warehouse WHERE id IN (?)`, [ stockIds ]
|
||||
);
|
||||
|
||||
// 收货单全链路
|
||||
const createRes = await call('storage.receiving.create', {
|
||||
store_id: STORE_ID,
|
||||
delivery_method: 'other',
|
||||
loading_method: 'with_pallet',
|
||||
remark: `[完整对比测试-${tag}]`,
|
||||
status: 'receiving',
|
||||
});
|
||||
const createBody = createRes.body || {};
|
||||
const receivingId = createBody.data && createBody.data.id ? createBody.data.id : createBody.id;
|
||||
const receivingNumber = (createBody.data && createBody.data.receiving_number) || createBody.receiving_number;
|
||||
if (!step('创建收货单', createRes, () => ({ id: receivingId, receiving_number: receivingNumber }))) {
|
||||
await conn.end(); return;
|
||||
}
|
||||
console.log(` receiving_id=${receivingId} receiving_number=${receivingNumber}`);
|
||||
|
||||
const detailIds = [];
|
||||
for (let i = 0; i < PRODUCTS.length; i++) {
|
||||
const p = PRODUCTS[i];
|
||||
const addRes = await call('storage.receiving.addDetail', {
|
||||
receiving_id: receivingId,
|
||||
item: {
|
||||
product_name: `完整对比测试商品${i + 1}`,
|
||||
barcode: `FULLBC${Date.now()}${i}`,
|
||||
actual_quantity: p.qty,
|
||||
batch_number: p.batch_number,
|
||||
production_date: p.production_date || null,
|
||||
expiry_date: p.expiry_date || null,
|
||||
space_id: p.space_id,
|
||||
},
|
||||
});
|
||||
const addBody = addRes.body || {};
|
||||
const addData = addBody.data || addBody;
|
||||
const newDetailId = addData.selectId
|
||||
|| (addData.details && Array.isArray(addData.details) && addData.details[0] && addData.details[0].id);
|
||||
if (!step(`添加明细#${i + 1}`, addRes, () => ({ detail_id: newDetailId }))) { await conn.end(); return; }
|
||||
detailIds.push(newDetailId);
|
||||
}
|
||||
|
||||
for (let i = 0; i < PRODUCTS.length; i++) {
|
||||
const bindRes = await call('storage.receiving.bindDetailProduct', {
|
||||
detail_id: detailIds[i],
|
||||
system_product_id: PRODUCTS[i].stock_id,
|
||||
});
|
||||
if (!step(`绑定商品#${i + 1}`, bindRes, d => ({ detail_id: d.detail_id, system_product_id: d.system_product_id }))) { await conn.end(); return; }
|
||||
}
|
||||
|
||||
const completeRes = await call('storage.receiving.completeReceiving', { id: receivingId });
|
||||
if (!step('完成收货', completeRes)) {
|
||||
console.log(' completeReceiving 响应:', JSON.stringify(completeRes.body).slice(0, 500));
|
||||
await conn.end(); return;
|
||||
}
|
||||
|
||||
const reviewRes = await call('storage.receiving.reviewReceiving', { ids: [ receivingId ] });
|
||||
if (!step('审核收货单', reviewRes)) {
|
||||
console.log(' reviewReceiving 响应:', JSON.stringify(reviewRes.body).slice(0, 500));
|
||||
await conn.end(); return;
|
||||
}
|
||||
|
||||
let entryOrderId;
|
||||
let entryOrderCode;
|
||||
|
||||
if (mode === 'A') {
|
||||
// 两步流程第一步:转入库单
|
||||
const putawayRes = await call('storage.inventory.quickPutaway', { receiving_id: receivingId });
|
||||
if (!step('① quickPutaway(转入库单)', putawayRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) {
|
||||
console.log(' 响应:', JSON.stringify(putawayRes.body).slice(0, 600));
|
||||
await conn.end(); return;
|
||||
}
|
||||
entryOrderId = putawayRes.body.data.entry_order_id;
|
||||
entryOrderCode = putawayRes.body.data.entry_order_code;
|
||||
|
||||
// 两步流程第二步:导入入库(绑定收货明细 + 收货明细库位)
|
||||
const addItemRes = await call('storage.entry.addItem', {
|
||||
entry_order_id: entryOrderId,
|
||||
items: [
|
||||
{ stock_id: PRODUCTS[0].stock_id, quantity: PRODUCTS[0].qty, space_id: PRODUCTS[0].space_id, receiving_detail_id: detailIds[0], allocated_quantity: PRODUCTS[0].qty, inbound_type: 'pda' },
|
||||
{ stock_id: PRODUCTS[1].stock_id, quantity: PRODUCTS[1].qty, space_id: PRODUCTS[1].space_id, receiving_detail_id: detailIds[1], allocated_quantity: PRODUCTS[1].qty, inbound_type: 'pda' },
|
||||
],
|
||||
});
|
||||
if (!step('② storage.entry.addItem(导入入库,绑定收货明细)', addItemRes, d => ({ count: d.count, total_quantity: d.total_quantity }))) {
|
||||
console.log(' 响应:', JSON.stringify(addItemRes.body).slice(0, 800));
|
||||
await conn.end(); return;
|
||||
}
|
||||
|
||||
// 两步流程第三步:提交确认写库存
|
||||
const commitRes = await call('storage.entry.commit', { entry_order_id: entryOrderId });
|
||||
if (!step('③ storage.entry.commit(提交确认入库)', commitRes, d => ({ success: d.success, message: d.message }))) {
|
||||
console.log(' 响应:', JSON.stringify(commitRes.body).slice(0, 800));
|
||||
await conn.end(); return;
|
||||
}
|
||||
} else {
|
||||
// 一步直入
|
||||
const directRes = await call('storage.inventory.directPutaway', { receiving_id: receivingId });
|
||||
if (!step('① directPutaway(一步直入)', directRes, d => ({ entry_order_id: d.entry_order_id, entry_order_code: d.entry_order_code, order_status: d.order_status }))) {
|
||||
console.log(' 响应:', JSON.stringify(directRes.body).slice(0, 600));
|
||||
await conn.end(); return;
|
||||
}
|
||||
entryOrderId = directRes.body.data.entry_order_id;
|
||||
entryOrderCode = directRes.body.data.entry_order_code;
|
||||
}
|
||||
|
||||
await verifyFlow(conn, tag, receivingId, entryOrderId, entryOrderCode, beforeStock);
|
||||
await conn.end();
|
||||
console.log(`================ 流程 ${tag} 完成:receiving=${receivingId} entry_order=${entryOrderId} ================`);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const conn = await db();
|
||||
const [spaces] = await conn.query(
|
||||
`SELECT id, space_code FROM wms_location_space WHERE warehouse_id = ? AND is_enabled = 1 AND deleted_at IS NULL ORDER BY id LIMIT 2`,
|
||||
[ WAREHOUSE_ID ]
|
||||
);
|
||||
console.log('使用库位:', JSON.stringify(spaces));
|
||||
PRODUCTS[0].space_id = spaces[0].id;
|
||||
PRODUCTS[1].space_id = spaces[1] ? spaces[1].id : spaces[0].id;
|
||||
await conn.end();
|
||||
|
||||
const only = (process.argv[2] || '').toUpperCase();
|
||||
if (!only || only === 'A') {
|
||||
await runFlow('A-两步', 'A');
|
||||
}
|
||||
if (!only || only === 'B') {
|
||||
await runFlow('B-一步', 'B');
|
||||
}
|
||||
|
||||
console.log('\n================ 测试结束 ================');
|
||||
}
|
||||
|
||||
main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,632 +0,0 @@
|
||||
/**
|
||||
* 只读校验脚本(开发库 127.0.0.1:3307/wms,仅 SELECT):
|
||||
* 验证 stock.report 修复后的 intervalEdge / preStart 快照 SQL 正确性。
|
||||
*
|
||||
* 场景1:货主口径(wms_stock_transaction, store_id=1000000)全量恒等式 + oracle 对照
|
||||
* 场景3:库位口径(wms_storage_transaction, store_id=1000000)全量恒等式 + oracle 对照
|
||||
* 场景4:start_time 边界(preStart 快照,含同秒多行 tie-break)+ 带 start_time 的窗口恒等式
|
||||
*
|
||||
* 无任何写操作、无清理逻辑。
|
||||
* 用法:
|
||||
* Remove-Item Env:\NODE_ENV -ErrorAction SilentlyContinue
|
||||
* node script/tmp-test-stockreport-fix-dev.cjs
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
function loadDevDbConfig() {
|
||||
const configPath = path.join(projectRoot, 'config', 'config.local.js');
|
||||
const factory = require(configPath);
|
||||
const config = typeof factory === 'function'
|
||||
? factory({ name: 'tmp-test-stockreport-fix', baseDir: projectRoot })
|
||||
: factory;
|
||||
const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms;
|
||||
if (client && client.host) {
|
||||
return {
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
};
|
||||
}
|
||||
throw new Error('无法解析开发库配置 config.local.js(mysql.clients.wms)');
|
||||
}
|
||||
|
||||
const STORE_ID = 1000000;
|
||||
|
||||
/** 汇总通过/失败计数 */
|
||||
const counters = { pass: 0, fail: 0 };
|
||||
function verdict(name, pass, detail) {
|
||||
if (pass) {
|
||||
counters.pass += 1;
|
||||
console.log(`PASS | ${name}${detail ? ` | ${detail}` : ''}`);
|
||||
} else {
|
||||
counters.fail += 1;
|
||||
console.log(`FAIL | ${name}${detail ? ` | ${detail}` : ''}`);
|
||||
}
|
||||
return pass;
|
||||
}
|
||||
|
||||
function num(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
const n = Number(value);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
function dimKey(row, isBySpace) {
|
||||
const spaceId = isBySpace ? (num(row.space_id) || 0) : 0;
|
||||
return isBySpace
|
||||
? `${row.stock_id}_${spaceId}_${row.store_id}`
|
||||
: `${row.stock_id}_${row.store_id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用全量流水在 Node 侧推演 oracle 快照:
|
||||
* 首条(created_at, id 最小)的 before_quantity、末条(created_at, id 最大)的 after_quantity。
|
||||
* ct 为 DATE_FORMAT 字符串('%Y-%m-%d %H:%i:%s.%f'),字典序即时间序。
|
||||
* @param {Object[]} rows 全量流水行
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @return {Map<string, {first: {ct: string, id: number, before: number|null}, last: {ct: string, id: number, after: number|null}}>} oracle 映射
|
||||
*/
|
||||
function buildFullOracle(rows, isBySpace) {
|
||||
const map = new Map();
|
||||
for (const row of rows) {
|
||||
const key = dimKey(row, isBySpace);
|
||||
const id = num(row.id);
|
||||
const ct = String(row.ct);
|
||||
if (!map.has(key)) {
|
||||
map.set(key, {
|
||||
first: { ct, id, before: num(row.before_quantity) },
|
||||
last: { ct, id, after: num(row.after_quantity) },
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const entry = map.get(key);
|
||||
if (ct < entry.first.ct || (ct === entry.first.ct && id < entry.first.id)) {
|
||||
entry.first = { ct, id, before: num(row.before_quantity) };
|
||||
}
|
||||
if (ct > entry.last.ct || (ct === entry.last.ct && id > entry.last.id)) {
|
||||
entry.last = { ct, id, after: num(row.after_quantity) };
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取指定维度全量流水明细(含格式化时间字符串)。
|
||||
* @param {Object} conn mysql2 连接
|
||||
* @param {string} tableName 表名
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @param {number} primaryVal 主维度值(store_id)
|
||||
* @return {Promise<Object[]>} 流水明细列表
|
||||
*/
|
||||
async function fetchAllRows(conn, tableName, isBySpace, primaryVal) {
|
||||
const spaceSelect = isBySpace ? 'COALESCE(space_id, 0) AS space_id, ' : '0 AS space_id, ';
|
||||
const [ rows ] = await conn.query(
|
||||
`SELECT id, stock_id, ${spaceSelect}store_id,
|
||||
transaction_type, quantity, before_quantity, after_quantity,
|
||||
DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s.%f') AS ct
|
||||
FROM ${tableName}
|
||||
WHERE store_id = ?`,
|
||||
[ primaryVal ]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 rangeRows 汇总 SQL(与 report.js 口径一致)。
|
||||
* @param {string} tableName 表名
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @param {boolean} withStart 是否带 created_at >= start 条件
|
||||
* @return {string} SQL 文本
|
||||
*/
|
||||
function buildRangeSql(tableName, isBySpace, withStart) {
|
||||
const spaceSelect = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id, ' : '';
|
||||
const spaceGroup = isBySpace ? ', COALESCE(t.space_id, 0)' : '';
|
||||
const startClause = withStart ? ' AND t.created_at >= ?' : '';
|
||||
return `
|
||||
SELECT t.stock_id,
|
||||
${spaceSelect}t.store_id,
|
||||
SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total,
|
||||
SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total
|
||||
FROM ${tableName} t
|
||||
WHERE t.store_id = ?${startClause}
|
||||
GROUP BY t.stock_id${spaceGroup}, t.store_id
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 intervalEdge 快照 SQL(fixed:含 stock/store 关联;buggy:不含)。
|
||||
* @param {string} tableName 表名
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @param {boolean} withStart 是否带 created_at >= start 条件
|
||||
* @param {boolean} fixed 是否修复版
|
||||
* @return {string} SQL 文本
|
||||
*/
|
||||
function buildEdgeSql(tableName, isBySpace, withStart, fixed) {
|
||||
const spaceSelect = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id, ' : '0 AS space_id, ';
|
||||
const spaceGroup = isBySpace ? ', COALESCE(t.space_id, 0)' : '';
|
||||
const startClauseG = withStart ? ' AND t.created_at >= ?' : '';
|
||||
const startClause2 = withStart ? ' AND t2.created_at >= ?' : '';
|
||||
const startClause3 = withStart ? ' AND t3.created_at >= ?' : '';
|
||||
const spaceJoin2 = isBySpace ? ' AND COALESCE(t2.space_id, 0) = g.space_id' : '';
|
||||
const spaceJoin3 = isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : '';
|
||||
const dimJoin2 = fixed ? ' AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id' : '';
|
||||
const dimJoin3 = fixed ? ' AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id' : '';
|
||||
return `
|
||||
SELECT g.stock_id, g.space_id, g.store_id,
|
||||
ft.before_quantity, lt.after_quantity
|
||||
FROM (
|
||||
SELECT t.stock_id,
|
||||
${spaceSelect}t.store_id,
|
||||
MIN(t.created_at) AS _min_ct,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM ${tableName} t
|
||||
WHERE t.store_id = ?${startClauseG}
|
||||
GROUP BY t.stock_id${spaceGroup}, t.store_id
|
||||
) g
|
||||
LEFT JOIN ${tableName} ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id)
|
||||
FROM ${tableName} t2
|
||||
WHERE t2.store_id = ?${startClause2}${spaceJoin2}${dimJoin2}
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN ${tableName} lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM ${tableName} t3
|
||||
WHERE t3.store_id = ?${startClause3}${spaceJoin3}${dimJoin3}
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id, g.space_id, g.store_id
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造 preStart 快照 SQL(fixed:含 stock/store 关联;buggy:不含)。
|
||||
* @param {string} tableName 表名
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @param {boolean} fixed 是否修复版
|
||||
* @return {string} SQL 文本
|
||||
*/
|
||||
function buildPreStartSql(tableName, isBySpace, fixed) {
|
||||
const spaceSelect = isBySpace ? 'COALESCE(t.space_id, 0) AS space_id, ' : '0 AS space_id, ';
|
||||
const spaceGroup = isBySpace ? ', COALESCE(t.space_id, 0)' : '';
|
||||
const spaceJoin = isBySpace ? ' AND COALESCE(t3.space_id, 0) = g.space_id' : '';
|
||||
const dimJoin = fixed ? ' AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id' : '';
|
||||
return `
|
||||
SELECT g.stock_id, g.space_id, g.store_id, lt.after_quantity
|
||||
FROM (
|
||||
SELECT t.stock_id,
|
||||
${spaceSelect}t.store_id,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM ${tableName} t
|
||||
WHERE t.store_id = ? AND t.created_at < ?
|
||||
GROUP BY t.stock_id${spaceGroup}, t.store_id
|
||||
) g
|
||||
LEFT JOIN ${tableName} lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM ${tableName} t3
|
||||
WHERE t3.store_id = ? AND t3.created_at < ?${spaceJoin}${dimJoin}
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id, g.space_id, g.store_id
|
||||
`;
|
||||
}
|
||||
|
||||
function edgeParams(storeId, withStart, startLiteral) {
|
||||
const base = [ storeId ];
|
||||
if (withStart) {
|
||||
base.push(startLiteral);
|
||||
}
|
||||
// g 外层 1 次 + t2 子查询 1 次 + t3 子查询 1 次
|
||||
return [ ...base, ...base, ...base ];
|
||||
}
|
||||
|
||||
function preStartParams(storeId, startLiteral) {
|
||||
return [ storeId, startLiteral, storeId, startLiteral ];
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析每条维度键的流水链路一致性(原始数据质量),识别:
|
||||
* - null_before_after:before/after 为 NULL
|
||||
* - delta_mismatch:INBOUND 应为 +qty、OUTBOUND 应为 -qty、其他应为 0
|
||||
* - chain_break:前一条 after 与后一条 before 不衔接
|
||||
* @param {Object[]} rows 全量流水行
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @return {Map<string, string[]>} 异常键到原因列表的映射
|
||||
*/
|
||||
function analyzeChain(rows, isBySpace) {
|
||||
const byKey = new Map();
|
||||
for (const row of rows) {
|
||||
const key = dimKey(row, isBySpace);
|
||||
if (!byKey.has(key)) {
|
||||
byKey.set(key, []);
|
||||
}
|
||||
byKey.get(key).push(row);
|
||||
}
|
||||
|
||||
const anomalies = new Map();
|
||||
for (const [ key, list ] of byKey.entries()) {
|
||||
list.sort((a, b) => {
|
||||
if (a.ct !== b.ct) {
|
||||
return a.ct < b.ct ? -1 : 1;
|
||||
}
|
||||
return num(a.id) - num(b.id);
|
||||
});
|
||||
|
||||
const reasons = [];
|
||||
let prevAfter = null;
|
||||
for (let i = 0; i < list.length; i += 1) {
|
||||
const row = list[i];
|
||||
const before = num(row.before_quantity);
|
||||
const after = num(row.after_quantity);
|
||||
if (before === null || after === null) {
|
||||
reasons.push(`null_before_after@id=${row.id}`);
|
||||
prevAfter = after;
|
||||
continue;
|
||||
}
|
||||
const qty = num(row.quantity);
|
||||
if (qty !== null) {
|
||||
let expectedDelta = 0;
|
||||
if (row.transaction_type === 'INBOUND') {
|
||||
expectedDelta = qty;
|
||||
} else if (row.transaction_type === 'OUTBOUND') {
|
||||
expectedDelta = -qty;
|
||||
}
|
||||
if (after - before !== expectedDelta) {
|
||||
reasons.push(`delta_mismatch@id=${row.id}`);
|
||||
}
|
||||
}
|
||||
if (i > 0 && prevAfter !== null && prevAfter !== before) {
|
||||
reasons.push(`chain_break@id=${row.id}(prev_after=${prevAfter},before=${before})`);
|
||||
}
|
||||
prevAfter = after;
|
||||
}
|
||||
if (reasons.length > 0) {
|
||||
anomalies.set(key, reasons);
|
||||
}
|
||||
}
|
||||
return anomalies;
|
||||
}
|
||||
|
||||
/**
|
||||
* 全量(无 start_time)场景:fixed/buggy 快照 SQL vs oracle + 恒等式。
|
||||
* @param {Object} conn mysql2 连接
|
||||
* @param {string} tableName 表名
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @param {string} label 场景标签
|
||||
* @return {Promise<Object>} 校验中间结果
|
||||
*/
|
||||
async function verifyFullRange(conn, tableName, isBySpace, label) {
|
||||
console.log(`\n===== ${label}:全量 intervalEdge 快照校验(store_id=${STORE_ID}) =====`);
|
||||
const rows = await fetchAllRows(conn, tableName, isBySpace, STORE_ID);
|
||||
console.log(`全量流水行数: ${rows.length}`);
|
||||
|
||||
const oracle = buildFullOracle(rows, isBySpace);
|
||||
|
||||
const [ rangeRows ] = await conn.query(buildRangeSql(tableName, isBySpace, false), [ STORE_ID ]);
|
||||
const [ fixedRows ] = await conn.query(buildEdgeSql(tableName, isBySpace, false, true), edgeParams(STORE_ID, false, null));
|
||||
const [ buggyRows ] = await conn.query(buildEdgeSql(tableName, isBySpace, false, false), edgeParams(STORE_ID, false, null));
|
||||
|
||||
const fixedMap = new Map();
|
||||
for (const row of fixedRows) {
|
||||
fixedMap.set(dimKey(row, isBySpace), row);
|
||||
}
|
||||
const buggyMap = new Map();
|
||||
for (const row of buggyRows) {
|
||||
buggyMap.set(dimKey(row, isBySpace), row);
|
||||
}
|
||||
const rangeMap = new Map();
|
||||
for (const row of rangeRows) {
|
||||
rangeMap.set(dimKey(row, isBySpace), row);
|
||||
}
|
||||
|
||||
const dimKeyCount = oracle.size;
|
||||
console.log(`维度键(stock[,space],store)数: ${dimKeyCount}`);
|
||||
|
||||
const anomalies = analyzeChain(rows, isBySpace);
|
||||
|
||||
let fixedBeginMismatch = 0;
|
||||
let fixedEndMismatch = 0;
|
||||
let buggyMismatch = 0;
|
||||
let identityMismatch = 0;
|
||||
let identityChecked = 0;
|
||||
let nullEdgeKeys = 0;
|
||||
const buggySamples = [];
|
||||
const identitySamples = [];
|
||||
|
||||
for (const [ key, expected ] of oracle.entries()) {
|
||||
const fixedRow = fixedMap.get(key);
|
||||
const buggyRow = buggyMap.get(key);
|
||||
const rangeRow = rangeMap.get(key);
|
||||
|
||||
if (!fixedRow) {
|
||||
fixedBeginMismatch += 1;
|
||||
fixedEndMismatch += 1;
|
||||
continue;
|
||||
}
|
||||
const fixedBegin = num(fixedRow.before_quantity);
|
||||
const fixedEnd = num(fixedRow.after_quantity);
|
||||
if (fixedBegin === null || fixedEnd === null) {
|
||||
nullEdgeKeys += 1;
|
||||
}
|
||||
if (fixedBegin !== expected.first.before) {
|
||||
fixedBeginMismatch += 1;
|
||||
}
|
||||
if (fixedEnd !== expected.last.after) {
|
||||
fixedEndMismatch += 1;
|
||||
}
|
||||
if (buggyRow && (num(buggyRow.before_quantity) !== expected.first.before
|
||||
|| num(buggyRow.after_quantity) !== expected.last.after)) {
|
||||
buggyMismatch += 1;
|
||||
if (buggySamples.length < 5) {
|
||||
buggySamples.push(`${key}: oracle(${expected.first.before}/${expected.last.after}) buggy(${num(buggyRow.before_quantity)}/${num(buggyRow.after_quantity)})`);
|
||||
}
|
||||
}
|
||||
|
||||
// 恒等式只对链路一致的键断言(null/断链/增量不一致属原始数据质量问题,与本次修复无关)
|
||||
if (anomalies.has(key)) {
|
||||
continue;
|
||||
}
|
||||
const inbound = rangeRow ? num(rangeRow.inbound_total) : 0;
|
||||
const outbound = rangeRow ? num(rangeRow.outbound_total) : 0;
|
||||
identityChecked += 1;
|
||||
if (fixedEnd !== fixedBegin + inbound - outbound) {
|
||||
identityMismatch += 1;
|
||||
if (identitySamples.length < 5) {
|
||||
identitySamples.push(`${key}: end=${fixedEnd} begin=${fixedBegin} in=${inbound} out=${outbound} diff=${fixedEnd - (fixedBegin + inbound - outbound)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
verdict(`${label} | fixed 首条 before 与 oracle 完全一致`, fixedBeginMismatch === 0,
|
||||
fixedBeginMismatch === 0 ? `0 不一致 / ${dimKeyCount} 键` : `${fixedBeginMismatch} 键不一致`);
|
||||
verdict(`${label} | fixed 末条 after 与 oracle 完全一致`, fixedEndMismatch === 0,
|
||||
fixedEndMismatch === 0 ? `0 不一致 / ${dimKeyCount} 键` : `${fixedEndMismatch} 键不一致`);
|
||||
const consistentKeyCount = dimKeyCount - anomalies.size;
|
||||
console.log(` 链路一致的维度键: ${consistentKeyCount}/${dimKeyCount};异常键(原始数据质量): ${anomalies.size}`);
|
||||
if (nullEdgeKeys > 0) {
|
||||
console.log(` 说明: ${nullEdgeKeys} 键的首/末行 before/after 为 NULL(原始数据既有,report.js toNumber 会按 0 处理),不属于修复问题`);
|
||||
}
|
||||
if (anomalies.size > 0) {
|
||||
for (const [ key, reasons ] of anomalies.entries()) {
|
||||
console.log(` 数据异常键 ${key}: ${reasons.slice(0, 4).join(' ; ')}`);
|
||||
}
|
||||
}
|
||||
verdict(`${label} | 恒等式 end = begin + in - out(链路一致键)全部成立`, identityMismatch === 0,
|
||||
`${identityMismatch} 违反 / 校验 ${identityChecked} 键`);
|
||||
verdict(`${label} | buggy(无关联) 与 oracle 不一致样本数`, true,
|
||||
`不一致 ${buggyMismatch} 键(用于说明缺陷影响面)`);
|
||||
if (buggySamples.length > 0) {
|
||||
console.log(` buggy 不一致样本: ${buggySamples.join(' ; ')}`);
|
||||
}
|
||||
if (identitySamples.length > 0) {
|
||||
console.log(` 恒等式违反样本: ${identitySamples.join(' ; ')}`);
|
||||
}
|
||||
|
||||
return { rows, oracle, fixedMap, rangeMap, anomalies };
|
||||
}
|
||||
|
||||
/**
|
||||
* 场景4:start_time 边界——preStart 快照(start 前最近一条 after),
|
||||
* 特别选取「期初边界处同秒多条流水」的时间点。
|
||||
* @param {Object} conn mysql2 连接
|
||||
* @param {string} tableName 表名
|
||||
* @param {boolean} isBySpace 是否按库位维度
|
||||
* @param {string} label 场景标签
|
||||
* @return {Promise<Object>} 校验中间结果
|
||||
*/
|
||||
async function verifyPreStartBoundary(conn, tableName, isBySpace, label) {
|
||||
console.log(`\n===== ${label}:start_time 边界 preStart 快照校验 =====`);
|
||||
const rows = await fetchAllRows(conn, tableName, isBySpace, STORE_ID);
|
||||
|
||||
// 找「两个相邻时间戳都含同键多行」的维度键,把较晚时间戳作为 start(前一批成为期初边界)。
|
||||
const byKey = new Map();
|
||||
for (const row of rows) {
|
||||
const key = dimKey(row, isBySpace);
|
||||
if (!byKey.has(key)) {
|
||||
byKey.set(key, new Map());
|
||||
}
|
||||
const ctMap = byKey.get(key);
|
||||
ctMap.set(String(row.ct), (ctMap.get(String(row.ct)) || 0) + 1);
|
||||
}
|
||||
|
||||
let chosenKey = null;
|
||||
let chosenStart = null;
|
||||
for (const [ key, ctMap ] of byKey.entries()) {
|
||||
const cts = [ ...ctMap.keys() ].sort();
|
||||
for (let i = 1; i < cts.length; i += 1) {
|
||||
if ((ctMap.get(cts[i - 1]) || 0) >= 2 && (ctMap.get(cts[i]) || 0) >= 2) {
|
||||
chosenKey = key;
|
||||
chosenStart = cts[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (chosenKey) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!chosenStart) {
|
||||
// 退而求其次:任一含同秒多行的时间戳,往后取相邻时间戳作为 start
|
||||
let found = false;
|
||||
for (const [ key, ctMap ] of byKey.entries()) {
|
||||
if (found) {
|
||||
break;
|
||||
}
|
||||
const cts = [ ...ctMap.keys() ].sort();
|
||||
for (let i = 0; i < cts.length; i += 1) {
|
||||
if ((ctMap.get(cts[i]) || 0) >= 2) {
|
||||
chosenKey = key;
|
||||
chosenStart = i + 1 < cts.length ? cts[i + 1] : cts[i];
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!chosenStart) {
|
||||
verdict(`${label} | preStart 边界同秒样本`, false, '未找到同秒多行样本,跳过');
|
||||
return { oraclePreStart: null, chosenStart: null, rows, chosenKey: null };
|
||||
}
|
||||
|
||||
console.log(`选中维度键: ${chosenKey}, start_time 边界: ${chosenStart}`);
|
||||
|
||||
// oracle:created_at < start 的最近一条(created_at, id 排序)
|
||||
const preStartOracle = new Map();
|
||||
for (const row of rows) {
|
||||
const key = dimKey(row, isBySpace);
|
||||
if (String(row.ct) >= chosenStart) {
|
||||
continue;
|
||||
}
|
||||
const id = num(row.id);
|
||||
const ct = String(row.ct);
|
||||
const after = num(row.after_quantity);
|
||||
if (!preStartOracle.has(key)) {
|
||||
preStartOracle.set(key, { ct, id, after });
|
||||
continue;
|
||||
}
|
||||
const current = preStartOracle.get(key);
|
||||
if (ct > current.ct || (ct === current.ct && id > current.id)) {
|
||||
preStartOracle.set(key, { ct, id, after });
|
||||
}
|
||||
}
|
||||
|
||||
const [ fixedPreRows ] = await conn.query(
|
||||
buildPreStartSql(tableName, isBySpace, true),
|
||||
preStartParams(STORE_ID, chosenStart)
|
||||
);
|
||||
const [ buggyPreRows ] = await conn.query(
|
||||
buildPreStartSql(tableName, isBySpace, false),
|
||||
preStartParams(STORE_ID, chosenStart)
|
||||
);
|
||||
|
||||
const fixedPreMap = new Map();
|
||||
for (const row of fixedPreRows) {
|
||||
fixedPreMap.set(dimKey(row, isBySpace), row);
|
||||
}
|
||||
const buggyPreMap = new Map();
|
||||
for (const row of buggyPreRows) {
|
||||
buggyPreMap.set(dimKey(row, isBySpace), row);
|
||||
}
|
||||
|
||||
let fixedPreMismatch = 0;
|
||||
let nullPreCount = 0;
|
||||
let buggyPreMismatch = 0;
|
||||
for (const [ key, expected ] of preStartOracle.entries()) {
|
||||
const fixedRow = fixedPreMap.get(key);
|
||||
if (!fixedRow) {
|
||||
fixedPreMismatch += 1;
|
||||
continue;
|
||||
}
|
||||
if (num(fixedRow.after_quantity) === null) {
|
||||
nullPreCount += 1;
|
||||
}
|
||||
if (num(fixedRow.after_quantity) !== expected.after) {
|
||||
fixedPreMismatch += 1;
|
||||
}
|
||||
const buggyRow = buggyPreMap.get(key);
|
||||
if (buggyRow && num(buggyRow.after_quantity) !== expected.after) {
|
||||
buggyPreMismatch += 1;
|
||||
}
|
||||
}
|
||||
|
||||
verdict(`${label} | preStart 最近一条 after 与 oracle 完全一致`, fixedPreMismatch === 0,
|
||||
`不一致 ${fixedPreMismatch},共 ${preStartOracle.size} 键`);
|
||||
if (nullPreCount > 0) {
|
||||
console.log(` 说明: ${nullPreCount} 键的期初行 after_quantity 为 NULL(原始数据既有,report.js toNumber 会按 0 处理),不属于修复问题`);
|
||||
}
|
||||
verdict(`${label} | preStart buggy 不一致样本数`, true,
|
||||
`不一致 ${buggyPreMismatch} 键(用于说明缺陷影响面)`);
|
||||
|
||||
// 窗口恒等式:以 chosenStart 为 start、以该键末条时间为 end,验证
|
||||
// end_total = preStartAfter + Σin - Σout(含 start_time 的 intervalEdge 修复版)
|
||||
const chosenParts = chosenKey.split('_');
|
||||
const chosenStockId = chosenParts[0];
|
||||
const [ rangeWithStart ] = await conn.query(
|
||||
buildRangeSql(tableName, isBySpace, true),
|
||||
[ STORE_ID, chosenStart ]
|
||||
);
|
||||
const [ edgeWithStart ] = await conn.query(
|
||||
buildEdgeSql(tableName, isBySpace, true, true),
|
||||
edgeParams(STORE_ID, true, chosenStart)
|
||||
);
|
||||
const rangeWithStartMap = new Map();
|
||||
for (const row of rangeWithStart) {
|
||||
rangeWithStartMap.set(dimKey(row, isBySpace), row);
|
||||
}
|
||||
const edgeWithStartMap = new Map();
|
||||
for (const row of edgeWithStart) {
|
||||
edgeWithStartMap.set(dimKey(row, isBySpace), row);
|
||||
}
|
||||
|
||||
const anomalies = analyzeChain(rows, isBySpace);
|
||||
let windowIdentityMismatch = 0;
|
||||
let windowChecked = 0;
|
||||
for (const [ key, expected ] of preStartOracle.entries()) {
|
||||
if (anomalies.has(key)) {
|
||||
continue;
|
||||
}
|
||||
const edgeRow = edgeWithStartMap.get(key);
|
||||
const rangeRow = rangeWithStartMap.get(key);
|
||||
if (!edgeRow || num(edgeRow.after_quantity) === null) {
|
||||
continue;
|
||||
}
|
||||
const end = num(edgeRow.after_quantity);
|
||||
const begin = expected.after;
|
||||
const inbound = rangeRow ? num(rangeRow.inbound_total) : 0;
|
||||
const outbound = rangeRow ? num(rangeRow.outbound_total) : 0;
|
||||
windowChecked += 1;
|
||||
if (end !== begin + inbound - outbound) {
|
||||
windowIdentityMismatch += 1;
|
||||
}
|
||||
}
|
||||
|
||||
verdict(`${label} | 带 start_time 窗口恒等式 end = 期初 + in - out(链路一致键)`, windowIdentityMismatch === 0,
|
||||
`${windowIdentityMismatch} 违反 / 校验 ${windowChecked} 键`);
|
||||
|
||||
return { oraclePreStart: preStartOracle, chosenStart, rows, chosenKey, chosenStockId };
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const dbConfig = loadDevDbConfig();
|
||||
console.log('目标: 开发库', `${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`);
|
||||
|
||||
const connection = await mysql.createConnection(dbConfig);
|
||||
try {
|
||||
// 场景1:货主口径(by_space=false 等价,维度键 stock+store)
|
||||
await verifyFullRange(connection, 'wms_stock_transaction', false, '场景1 货主口径(wms_stock_transaction)');
|
||||
|
||||
// 场景3:库位口径(by_space=true,维度键 stock+space+store)
|
||||
await verifyFullRange(connection, 'wms_storage_transaction', true, '场景3 库位口径(wms_storage_transaction)');
|
||||
|
||||
// 场景4:start_time 边界
|
||||
await verifyPreStartBoundary(connection, 'wms_stock_transaction', false, '场景4 货主口径 start_time 边界');
|
||||
await verifyPreStartBoundary(connection, 'wms_storage_transaction', true, '场景4 库位口径 start_time 边界');
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
|
||||
console.log('\n===== 汇总 =====');
|
||||
console.log(`PASS: ${counters.pass}, FAIL: ${counters.fail}`);
|
||||
if (counters.fail > 0) {
|
||||
process.exit(1);
|
||||
}
|
||||
})().catch(err => {
|
||||
console.error(err && err.stack ? err.stack : String(err));
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,25 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 只读排查脚本:追踪 2026-09-12 当天与波次 1777888535813505 相关的 SQL 及订单表 DDL。
|
||||
* 仅执行 grep / cut / uniq 等只读命令。
|
||||
*/
|
||||
|
||||
const { loadDeployConfig, runSsh } = require('./deploy-lib.cjs');
|
||||
|
||||
const WAVE_ID = '1777888535813505';
|
||||
|
||||
function buildRemoteScript() {
|
||||
return [
|
||||
'set -uo pipefail',
|
||||
'F=/www/wwwroot/qimen/v2/app/service/systemMethods/order/wave.js',
|
||||
'echo "===GREP_FUNCS==="',
|
||||
'grep -n "async batchCancel\\|batchCancelWave\\|cancelSingleWave\\|wave_status = -1\\|wave_status: -1" "$F" 2>/dev/null | head -20 || true',
|
||||
'echo "===SHOW_BATCHCANCEL_REGION==="',
|
||||
'S=$(grep -n "async batchCancel(" "$F" | head -1 | cut -d: -f1)',
|
||||
'if [ -n "$S" ]; then sed -n "${S},$((S+120))p" "$F"; fi',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
const config = loadDeployConfig('production');
|
||||
console.log(runSsh(config, buildRemoteScript(), { stdio: 'pipe' }));
|
||||
@ -1,104 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 一次性数据修复:解绑生产残留的拣货车绑定。
|
||||
*
|
||||
* 背景:修复前打印解绑核实逻辑对「波次含拦截订单」的场景永远不满足,
|
||||
* 导致 wms_pick_task_cart_binding.is_active=1 残留(车未解锁)。
|
||||
* 核对结论(2026-09-06):
|
||||
* - 生产残留 39 条,全部 task.status=2(拣货完成待复核)、review_status=0;
|
||||
* - 同车重复活跃绑定 0 条、已复核仍残留 0 条;
|
||||
* - 关联订单已全部打印(散单/团购均无未打印订单)。
|
||||
*
|
||||
* 用法:
|
||||
* node script/tmp-unbind-prod-cart.cjs # dry-run:核对范围与快照,不写库
|
||||
* node script/tmp-unbind-prod-cart.cjs --apply # 执行解绑 UPDATE,并回读确认
|
||||
*/
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
(async () => {
|
||||
const apply = process.argv.includes('--apply');
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
const configPath = path.join(projectRoot, 'script', 'db-query-prod-config.js');
|
||||
const config = require(configPath);
|
||||
const client = config && config.mysql && config.mysql.clients
|
||||
&& config.mysql.clients.wms;
|
||||
if (!client) {
|
||||
throw new Error('生产连接配置缺失 (script/db-query-prod-config.js -> mysql.clients.wms)');
|
||||
}
|
||||
|
||||
const connection = await mysql.createConnection({
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
});
|
||||
|
||||
try {
|
||||
// 目标范围:活跃绑定且任务已结束(待复核/完成/取消)。当前核对全部 status=2。
|
||||
const targetSql = `
|
||||
SELECT
|
||||
b.id, b.task_id, b.cart_id, b.cart_code_snapshot,
|
||||
b.warehouse_id, b.bind_user_id,
|
||||
DATE_FORMAT(b.bind_time, '%Y-%m-%d %H:%i') AS bind_time,
|
||||
t.task_no, t.status AS task_status, t.review_status
|
||||
FROM wms_pick_task_cart_binding b
|
||||
JOIN wms_wave_pick_task t ON t.id = b.task_id
|
||||
WHERE b.is_active = 1
|
||||
AND t.status IN (2, 3, 9)
|
||||
ORDER BY b.id ASC
|
||||
`;
|
||||
const [targetRows] = await connection.query(targetSql);
|
||||
const targetIds = targetRows.map(row => Number(row.id));
|
||||
|
||||
console.log(`[unbind-prod-cart] 目标环境: ${client.host}:${client.port}/${client.database}`);
|
||||
console.log(`[unbind-prod-cart] 命中活跃绑定: ${targetIds.length} 条`);
|
||||
if (targetRows.length > 0) {
|
||||
console.table(targetRows.slice(0, 50));
|
||||
}
|
||||
|
||||
if (targetIds.length === 0) {
|
||||
console.log('[unbind-prod-cart] 无待解绑记录,结束。');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!apply) {
|
||||
console.log('[unbind-prod-cart] dry-run 完成,未写库。确认无误后加 --apply 执行。');
|
||||
return;
|
||||
}
|
||||
|
||||
// 执行解绑(仅限命中范围,保留 is_active=1 条件防止并发误伤)
|
||||
const [updateResult] = await connection.query(`
|
||||
UPDATE wms_pick_task_cart_binding
|
||||
SET is_active = 0,
|
||||
unbind_user_id = 0,
|
||||
unbind_time = NOW(),
|
||||
update_time = NOW()
|
||||
WHERE is_active = 1
|
||||
AND id IN (?)
|
||||
`, [ targetIds ]);
|
||||
console.log(`[unbind-prod-cart] 解绑 UPDATE 完成,受影响行数: ${updateResult.affectedRows}`);
|
||||
|
||||
// 回读确认
|
||||
const [remainingRows] = await connection.query(`
|
||||
SELECT COUNT(*) AS cnt
|
||||
FROM wms_pick_task_cart_binding b
|
||||
JOIN wms_wave_pick_task t ON t.id = b.task_id
|
||||
WHERE b.is_active = 1
|
||||
AND t.status IN (2, 3, 9)
|
||||
`);
|
||||
const remainingCount = Number(remainingRows[0] && remainingRows[0].cnt || 0);
|
||||
console.log(`[unbind-prod-cart] 回读确认:剩余活跃绑定 ${remainingCount} 条`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
})().catch(error => {
|
||||
console.error('[unbind-prod-cart] 执行失败:', error && error.message ? error.message : error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@ -1,30 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = process.cwd();
|
||||
const target = path.join(root, 'AI_METHOD_ROUTING.md');
|
||||
const inventoryPath = path.join(root, 'temp', 'tmp-service-method-inventory.md');
|
||||
|
||||
const base = fs.readFileSync(target, 'utf8');
|
||||
const inventory = fs.readFileSync(inventoryPath, 'utf8').trim();
|
||||
|
||||
const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n- 临时清单输出:temp/tmp-service-method-inventory.md\n\n<!-- SERVICE_METHOD_INVENTORY:BEGIN -->\n${inventory}\n<!-- SERVICE_METHOD_INVENTORY:END -->\n`;
|
||||
|
||||
const begin = '<!-- SERVICE_METHOD_INVENTORY:BEGIN -->';
|
||||
const end = '<!-- SERVICE_METHOD_INVENTORY:END -->';
|
||||
|
||||
let next;
|
||||
if (base.includes(begin) && base.includes(end)) {
|
||||
const start = base.indexOf(begin);
|
||||
const finish = base.indexOf(end) + end.length;
|
||||
const head = base.slice(0, base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start) >= 0
|
||||
? base.lastIndexOf('\n## 6. 全量 Service Method 能力清单(自动扫描)', start)
|
||||
: start);
|
||||
const tail = base.slice(finish);
|
||||
next = head.trimEnd() + section + tail;
|
||||
} else {
|
||||
next = base.trimEnd() + section;
|
||||
}
|
||||
|
||||
fs.writeFileSync(target, next + '\n', 'utf8');
|
||||
console.log('UPDATED AI_METHOD_ROUTING.md');
|
||||
@ -1,103 +0,0 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 全表核对:A 两步链路(收货单 1526 / 入库单 383) vs B 一步直入(收货单 1528 / 入库单 385)
|
||||
* 覆盖 A 链路涉及的所有表(收货单阶段 + 转入库单 + 导入入库 + 提交确认)。
|
||||
* 只读,不产生数据。
|
||||
*/
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const A = { receiving: 1526, entryOrder: 383, code: 'SCRK202608240003', detailIds: [ 2711, 2712 ] };
|
||||
const B = { receiving: 1528, entryOrder: 385, code: 'SCRK202608240005', detailIds: [ 2715, 2716 ] };
|
||||
|
||||
(async () => {
|
||||
const conn = await mysql.createConnection({
|
||||
host: '127.0.0.1', port: 3307, user: 'wms', password: 'dspxmRwRdRbWtbm7', database: 'wms',
|
||||
});
|
||||
|
||||
const show = async (title, sql, params) => {
|
||||
const [rows] = await conn.query(sql, params);
|
||||
console.log(`\n===== ${title} =====`);
|
||||
console.log(JSON.stringify(rows, null, 2));
|
||||
};
|
||||
|
||||
for (const [ tag, t ] of [ [ 'A-两步', A ], [ 'B-一步', B ] ]) {
|
||||
console.log(`\n########## ${tag}(receiving=${t.receiving}, entry_order=${t.entryOrder}) ##########`);
|
||||
|
||||
await show('1. wms_receiving 收货单主表', `
|
||||
SELECT id, receiving_number, status, is_review, storage_status, detail_status, store_id, warehouse_id, total_items, total_quantity
|
||||
FROM wms_receiving WHERE id = ?`, [ t.receiving ]);
|
||||
|
||||
await show('2. wms_receiving_detail 收货明细', `
|
||||
SELECT id, receiving_id, system_product_id, actual_quantity, stored_quantity, storage_status,
|
||||
space_id, batch_number, production_date, expiry_date, barcode, receiving_status
|
||||
FROM wms_receiving_detail WHERE receiving_id = ? ORDER BY id`, [ t.receiving ]);
|
||||
|
||||
await show('3. wms_entry_order 入库单', `
|
||||
SELECT id, entry_order_code, order_type, order_status, sync_status, sync_message, source_type,
|
||||
total_order_lines, warehouse_id, store_id, store_name, warehouse_name, remark
|
||||
FROM wms_entry_order WHERE id = ?`, [ t.entryOrder ]);
|
||||
|
||||
await show('4. wms_entry_items 入库明细', `
|
||||
SELECT id, order_id, order_line_no, item_code, stock_id, count, received_quantity, confirm_quantity, inventory_type
|
||||
FROM wms_entry_items WHERE order_id = ? ORDER BY order_line_no`, [ t.entryOrder ]);
|
||||
|
||||
await show('5. wms_entry_order_receiving 主表绑定', `
|
||||
SELECT id, entry_order_id, receiving_id, created_at FROM wms_entry_order_receiving WHERE entry_order_id = ?`, [ t.entryOrder ]);
|
||||
|
||||
await show('6. wms_inbound_direct_log 导入入库记录(两步中间态)', `
|
||||
SELECT id, entry_order_id, entry_order_code, stock_id, quantity, entry_item_id, receiving_detail_id, space_id, status, inbound_type, remark
|
||||
FROM wms_inbound_direct_log WHERE entry_order_id = ? ORDER BY id`, [ t.entryOrder ]);
|
||||
|
||||
await show('7. wms_stock_warehouse 商品总库存', `
|
||||
SELECT id, item_code, quantity, locked_quantity, is_valid FROM wms_stock_warehouse WHERE id IN (159061, 159064) ORDER BY id`);
|
||||
|
||||
await show('8. wms_storage 库位库存', `
|
||||
SELECT id, space_id, stock_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity,
|
||||
inbound_order_no, receiving_id, entry_order_id, production_date, expiry_date, inbound_time
|
||||
FROM wms_storage WHERE entry_order_id = ? OR (inbound_order_no = ? AND receiving_id = ?) ORDER BY id`,
|
||||
[ t.entryOrder, t.code, t.receiving ]);
|
||||
|
||||
await show('9. wms_stock_transaction 商品流水', `
|
||||
SELECT id, transaction_type, stock_id, quantity, before_quantity, after_quantity,
|
||||
before_locked_quantity, after_locked_quantity, batch_no, order_type, order_no, receiving_id, entry_order_id, remark
|
||||
FROM wms_stock_transaction WHERE order_no = ? OR entry_order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]);
|
||||
|
||||
await show('10. wms_storage_transaction 库位流水', `
|
||||
SELECT id, transaction_type, stock_id, storage_id, space_id, quantity, before_quantity, after_quantity,
|
||||
before_locked_quantity, after_locked_quantity, batch_no, inventory_type, order_type, order_no, order_id
|
||||
FROM wms_storage_transaction WHERE order_no = ? OR order_id = ? ORDER BY id`, [ t.code, t.entryOrder ]);
|
||||
|
||||
await show('11. wms_operation_log 本流程操作日志', `
|
||||
SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message
|
||||
FROM wms_operation_log
|
||||
WHERE business_id = ? AND operation_code IN
|
||||
('RECEIVING_CREATE','RECEIVING_ADD_DETAIL','RECEIVING_BIND_PRODUCT','RECEIVING_COMPLETE','RECEIVING_REVIEW',
|
||||
'ENTRY_ORDER_QUICK_PUTAWAY','DIRECT_INBOUND_ADD','DIRECT_INBOUND_COMMIT',
|
||||
'ENTRY_ORDER_DIRECT_PUTAWAY','STORAGE_DIRECT_PUTAWAY','STOCK_DIRECT_PUTAWAY')
|
||||
ORDER BY id`, [ String(t.entryOrder) ]);
|
||||
|
||||
await show('12. wms_operation_log 收货单维度操作日志', `
|
||||
SELECT id, business_type, business_id, operation_code, operator_name, warehouse_id, message
|
||||
FROM wms_operation_log WHERE business_id = ? ORDER BY id`, [ String(t.receiving) ]);
|
||||
|
||||
await show('13. wms_store_warehouse 货主签约与开关', `
|
||||
SELECT id, store_id, warehouse_id, warehouse_use_status,
|
||||
JSON_EXTRACT(policy_config, '$.allow_receiving_quick_putaway') AS quick,
|
||||
JSON_EXTRACT(policy_config, '$.allow_receiving_direct_putaway') AS direct
|
||||
FROM wms_store_warehouse WHERE store_id = 1000000 AND warehouse_id = 100000`);
|
||||
|
||||
await show('14. wms_stock_barcodes 本次绑定的条码', `
|
||||
SELECT id, stock_id, warehouse_id, barcode
|
||||
FROM wms_stock_barcodes
|
||||
WHERE stock_id IN (159061, 159064)
|
||||
AND barcode IN (SELECT barcode FROM wms_receiving_detail WHERE receiving_id = ?)
|
||||
ORDER BY id`, [ t.receiving ]);
|
||||
|
||||
await show('15. wms_location_space 库位统计快照(入库链路不维护该统计)', `
|
||||
SELECT id, space_code, current_quantity, current_sku_count, is_enabled
|
||||
FROM wms_location_space WHERE id IN (5918, 5919)`);
|
||||
}
|
||||
|
||||
await conn.end();
|
||||
process.exit(0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@ -1,37 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本:查询生产库 wms_wave_pick_task.batch_no_array 字段是否已添加。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const [ rows ] = await s.query(
|
||||
"SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_COMMENT "
|
||||
+ "FROM INFORMATION_SCHEMA.COLUMNS "
|
||||
+ "WHERE TABLE_SCHEMA = DATABASE() "
|
||||
+ "AND TABLE_NAME = 'wms_wave_pick_task' "
|
||||
+ "AND COLUMN_NAME = 'batch_no_array'"
|
||||
);
|
||||
console.log(JSON.stringify(rows, null, 2));
|
||||
|
||||
const [ meta ] = await s.query(
|
||||
"SELECT name FROM SequelizeMeta WHERE name = '20260904120000-add-batch-no-array-to-wms-wave-pick-task.js'"
|
||||
);
|
||||
console.log('SequelizeMeta 记录:', JSON.stringify(meta));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,39 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本:查询生产库 wms_wave_batch 领料字段与 SequelizeMeta 记录。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const rows = await s.query(
|
||||
"SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT "
|
||||
+ "FROM INFORMATION_SCHEMA.COLUMNS "
|
||||
+ "WHERE TABLE_SCHEMA = DATABASE() "
|
||||
+ "AND TABLE_NAME = 'wms_wave_batch' "
|
||||
+ "AND COLUMN_NAME IN ('claim_operator', 'claim_time')",
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('字段:', JSON.stringify(rows));
|
||||
|
||||
const meta = await s.query(
|
||||
"SELECT name FROM SequelizeMeta WHERE name = '20260904130000-add-claim-operator-to-wms-wave-batch.js'",
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('Meta:', JSON.stringify(meta));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,228 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时端到端校验脚本(开发库,只读):库内确定拦截订单明细报表类型 interceptOrder。
|
||||
*
|
||||
* 校验两条链路(不做任何数据库写操作):
|
||||
* A. 真实查询器链路:以 egg 真实上下文(含 orderExport 服务与配送表模型)
|
||||
* 调用查询器,验证 dispatch 表位/模型解析、dispath_time 区间 SQL、meta 口径可正常执行;
|
||||
* 开发库历史拦截单 dispath_time 均为 NULL(该列 2026-09-07 才上线),因此预期 0 行。
|
||||
* B. 真实数据映射链路(对照 A 的非空场景):以「仅 intercept_status 过滤(不限时间)」
|
||||
* 调用 orderExport.buildOrderExportPage(mode=item),取真实拦截订单明细行,
|
||||
* 经 pickReportRow 裁剪后用 renderSheetByType 渲染,核对表头 46 列与数据行。
|
||||
*
|
||||
* 运行:node script/tmp-verify-intercept-order-dev.cjs
|
||||
*/
|
||||
const path = require('node:path');
|
||||
const mm = require('egg-mock');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const interceptOrder = require(path.join(projectRoot, 'app/service/systems/report/queries/interceptOrder.js'));
|
||||
const { renderSheetByType } = require(path.join(projectRoot, 'app/lib/report/render.js'));
|
||||
|
||||
const WAREHOUSE_ID = 100000;
|
||||
|
||||
let failed = 0;
|
||||
const check = (condition, label, detail = '') => {
|
||||
if (condition) {
|
||||
console.log(` ✔ ${label}${detail ? ` | ${detail}` : ''}`);
|
||||
return;
|
||||
}
|
||||
failed += 1;
|
||||
console.log(` ✘ ${label}${detail ? ` | ${detail}` : ''}`);
|
||||
};
|
||||
|
||||
(async () => {
|
||||
mm.env('local');
|
||||
const app = mm.app({ baseDir: projectRoot });
|
||||
await app.ready();
|
||||
const ctx = app.createAnonymousContext();
|
||||
ctx.user = { store_id: WAREHOUSE_ID };
|
||||
const orderExport = ctx.service.systems.orderExport;
|
||||
|
||||
try {
|
||||
console.log('\n[A] 查询器真实链路(warehouse=%s,昨日自然日)', WAREHOUSE_ID);
|
||||
const yesterdayDate = new Date();
|
||||
yesterdayDate.setDate(yesterdayDate.getDate() - 1);
|
||||
const bizDate = `${yesterdayDate.getFullYear()}-${String(yesterdayDate.getMonth() + 1).padStart(2, '0')}`
|
||||
+ `-${String(yesterdayDate.getDate()).padStart(2, '0')}`;
|
||||
const result = await interceptOrder({
|
||||
ctx,
|
||||
storeId: null,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
params: { bizDate },
|
||||
});
|
||||
console.log(' meta=' + JSON.stringify(result.meta));
|
||||
console.log(' rows=' + result.rows.length);
|
||||
check(result.meta.bizDate === bizDate, 'meta.bizDate 与入参一致', result.meta.bizDate);
|
||||
check(result.meta.timeField === 'dispath_time', 'meta.timeField=dispath_time');
|
||||
check(
|
||||
result.meta.interceptStatus === 'intercepted_at_warehouse',
|
||||
'meta.interceptStatus=intercepted_at_warehouse'
|
||||
);
|
||||
check(result.meta.rowCount === result.rows.length, 'meta.rowCount 与行数一致');
|
||||
check(Array.isArray(result.windows) && result.windows.length === 0, 'windows 为空(无展开列)');
|
||||
check(
|
||||
result.meta.startTime === `${bizDate} 00:00:00` && result.meta.endTime > result.meta.startTime,
|
||||
'统计区间为指定自然日整天(左闭右开)',
|
||||
`${result.meta.startTime} ~ ${result.meta.endTime}`
|
||||
);
|
||||
// 开发库历史拦截单 dispath_time 多数为 NULL(仅补测的几单有值),此处校验口径一致性
|
||||
const distinctOrderCount = new Set(result.rows.map(row => Number(row.id))).size;
|
||||
check(
|
||||
distinctOrderCount === result.meta.orderCount,
|
||||
'meta.orderCount = 明细行去重订单数',
|
||||
`orders=${distinctOrderCount}/${result.meta.orderCount}`
|
||||
);
|
||||
|
||||
console.log('\n[B] 真实拦截订单明细映射链路(忽略时间过滤,仅验证列与取值)');
|
||||
const target = orderExport.resolveExportTarget({ tableType: 'dispatch' });
|
||||
const orderModel = await orderExport.getOrderModelByTableType('dispatch', WAREHOUSE_ID);
|
||||
const pageResult = await orderExport.buildOrderExportPage({
|
||||
page: 1,
|
||||
pageSize: 5,
|
||||
queryWhere: { intercept_status: 'intercepted_at_warehouse' },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
orderModel,
|
||||
target,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
mode: 'item',
|
||||
});
|
||||
console.log(` 命中订单=${pageResult.orderCount},导出行=${pageResult.exportRows.length}`);
|
||||
check(pageResult.orderCount > 0, '开发库存在库内确定拦截订单(用于映射验证)', String(pageResult.orderCount));
|
||||
|
||||
const reportRows = pageResult.exportRows.map(row => interceptOrder.pickReportRow(row));
|
||||
const sample = reportRows[0] || {};
|
||||
console.log(' 明细首行抽样=' + JSON.stringify({
|
||||
id: sample.id,
|
||||
delivery_order_code: sample.delivery_order_code,
|
||||
item_name: sample.item_name,
|
||||
item_quantity: sample.item_quantity,
|
||||
waybill_code: sample.waybill_code,
|
||||
outbound_status: sample.outbound_status,
|
||||
create_channel: sample.create_channel,
|
||||
}, null, 2));
|
||||
check(
|
||||
reportRows.every(row => Object.keys(row).length === interceptOrder.fields.length),
|
||||
'每行键数=注册字段数',
|
||||
String(interceptOrder.fields.length)
|
||||
);
|
||||
check(
|
||||
reportRows.every(row => !Object.prototype.hasOwnProperty.call(row, 'item_image')),
|
||||
'行不含商品图片列'
|
||||
);
|
||||
check(
|
||||
reportRows.some(row => Number(row.item_quantity) > 0) || reportRows.length > 0,
|
||||
'存在数据行'
|
||||
);
|
||||
|
||||
console.log('\n[C] 渲染链路(renderSheetByType)');
|
||||
const sheet = renderSheetByType({
|
||||
type: 'interceptOrder',
|
||||
title: '库内确定拦截订单明细',
|
||||
fields: interceptOrder.fields.map(field => ({ ...field })),
|
||||
rows: reportRows,
|
||||
windows: [],
|
||||
});
|
||||
const header = sheet.rows[0];
|
||||
console.log(' 表头列数=' + header.length + ',总行数=' + sheet.rows.length);
|
||||
check(sheet.name === '库内确定拦截订单明细', 'sheet 名称为报表标题', sheet.name);
|
||||
check(header.length === interceptOrder.fields.length, '表头列数与注册字段一致', String(header.length));
|
||||
check(header[0] === '订单ID' && header[header.length - 2] === '通知拦截时间'
|
||||
&& header[header.length - 1] === '库内确定拦截时间', '表头首列与末尾两列拦截时间正确');
|
||||
check(sheet.rows.length === reportRows.length + 1, '单行表头 + 数据行(无展开列)');
|
||||
check(
|
||||
Array.isArray(sheet.merges) && sheet.merges.length === 0,
|
||||
'无展开列时不需要表头合并'
|
||||
);
|
||||
check(
|
||||
!Object.prototype.hasOwnProperty.call(sheet, 'textColumns'),
|
||||
'未声明 asText,不输出 textColumns(与订单导出一致)'
|
||||
);
|
||||
|
||||
console.log('\n[D] 附加列富化(平台交易单号 + 两列拦截时间,真实数据交叉核对)');
|
||||
const sampleOrders = await orderModel.findAll({
|
||||
where: { intercept_status: 'intercepted_at_warehouse' },
|
||||
attributes: [ 'id', 'source_order_codes', 'intercept_time', 'dispath_time' ],
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
limit: 5,
|
||||
raw: true,
|
||||
});
|
||||
const timeRows = sampleOrders.map(row => ({
|
||||
id: Number(row.id),
|
||||
source_order_codes: '',
|
||||
intercept_notice_time: '',
|
||||
intercept_confirm_time: '',
|
||||
}));
|
||||
await interceptOrder.enrichInterceptFields({
|
||||
ctx,
|
||||
app: ctx.app,
|
||||
orderModel,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
rows: timeRows,
|
||||
});
|
||||
|
||||
const sampleIds = timeRows.map(row => String(row.id));
|
||||
const logRows = await ctx.model.query(
|
||||
`SELECT business_id, MIN(created_at) AS notice_time
|
||||
FROM wms_operation_log
|
||||
WHERE business_type = 'order'
|
||||
AND operation_code = 'ORDER_INTERCEPT_REQUEST'
|
||||
AND warehouse_id = :warehouseId
|
||||
AND business_id IN (:ids)
|
||||
GROUP BY business_id`,
|
||||
{
|
||||
replacements: { warehouseId: WAREHOUSE_ID, ids: sampleIds },
|
||||
type: ctx.model.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
const logMap = new Map((Array.isArray(logRows) ? logRows : []).map(row => [ String(row.business_id), row.notice_time ]));
|
||||
const formatExpected = value => {
|
||||
if (value === null || value === undefined || value === '') {
|
||||
return '';
|
||||
}
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? '' : ctx.app.formatDate(date);
|
||||
};
|
||||
|
||||
for (const row of timeRows) {
|
||||
const orderRow = sampleOrders.find(item => Number(item.id) === row.id) || {};
|
||||
const expectedNotice = formatExpected(orderRow.intercept_time) || formatExpected(logMap.get(String(row.id)));
|
||||
const expectedConfirm = formatExpected(orderRow.dispath_time);
|
||||
const expectedSourceOrderCodes = orderRow.source_order_codes === null || orderRow.source_order_codes === undefined
|
||||
? ''
|
||||
: String(orderRow.source_order_codes);
|
||||
console.log(
|
||||
` id=${row.id} 平台交易单号=${row.source_order_codes || '(空)'} / 期望=${expectedSourceOrderCodes || '(空)'}`
|
||||
+ ` | 通知拦截时间=${row.intercept_notice_time || '(空)'} / 期望=${expectedNotice || '(空)'}`
|
||||
+ ` | 库内确定拦截时间=${row.intercept_confirm_time || '(空)'} / 期望=${expectedConfirm || '(空)'}`
|
||||
);
|
||||
check(
|
||||
row.source_order_codes === expectedSourceOrderCodes,
|
||||
`id=${row.id} 平台交易单号=配送表 source_order_codes 一致`
|
||||
);
|
||||
check(
|
||||
row.intercept_notice_time === expectedNotice,
|
||||
`id=${row.id} 通知拦截时间=intercept_time(为空时回落 ORDER_INTERCEPT_REQUEST 日志)一致`
|
||||
);
|
||||
check(
|
||||
row.intercept_confirm_time === expectedConfirm,
|
||||
`id=${row.id} 库内确定拦截时间=配送表 dispath_time 一致`
|
||||
);
|
||||
}
|
||||
check(
|
||||
timeRows.every(row => typeof row.source_order_codes === 'string'
|
||||
&& typeof row.intercept_notice_time === 'string'
|
||||
&& typeof row.intercept_confirm_time === 'string'),
|
||||
'附加列均为字符串(时间列为 YYYY-MM-DD HH:mm:ss 或空串)'
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
console.log(failed === 0 ? '\n全部校验通过' : `\n校验失败 ${failed} 项`);
|
||||
process.exit(failed === 0 ? 0 : 1);
|
||||
})().catch(error => {
|
||||
console.error('脚本执行异常:', error && error.stack ? error.stack : error);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,39 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时核验脚本:查询生产库 wms_wave_pick_task 领料字段与 SequelizeMeta 记录。
|
||||
*/
|
||||
|
||||
const dbConfig = require('../database/config.js');
|
||||
const Sequelize = require('sequelize');
|
||||
|
||||
(async () => {
|
||||
const cfg = dbConfig.production;
|
||||
const s = new Sequelize(cfg.database, cfg.username, cfg.password, {
|
||||
host: cfg.host,
|
||||
port: cfg.port,
|
||||
dialect: cfg.dialect || 'mysql',
|
||||
logging: false,
|
||||
});
|
||||
|
||||
const rows = await s.query(
|
||||
"SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_COMMENT "
|
||||
+ "FROM INFORMATION_SCHEMA.COLUMNS "
|
||||
+ "WHERE TABLE_SCHEMA = DATABASE() "
|
||||
+ "AND TABLE_NAME = 'wms_wave_pick_task' "
|
||||
+ "AND COLUMN_NAME IN ('claim_operator_id', 'claim_operator')",
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('字段:', JSON.stringify(rows));
|
||||
|
||||
const meta = await s.query(
|
||||
"SELECT name FROM SequelizeMeta WHERE name = '20260904140000-add-claim-operator-to-wms-wave-pick-task.js'",
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
console.log('Meta:', JSON.stringify(meta));
|
||||
|
||||
await s.close();
|
||||
})().catch(e => {
|
||||
console.error('ERROR:', e.message);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,151 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 通过 pick.wavePickTaskComplete 提交任务 271 拣货完成(订单不回池),
|
||||
* 然后再次抓取,验证第一池已清空后回落第二池抓满 20 条今天订单。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const BASE_URL = 'http://127.0.0.1:6060';
|
||||
const DB_CONFIG = {
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
};
|
||||
const TODAY_START_UTC = Date.UTC(2026, 8, 5, 16, 0, 0);
|
||||
|
||||
/**
|
||||
* 发送 /system POST 请求。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {string} method 方法名。
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 响应 JSON。
|
||||
*/
|
||||
async function sysCall(token, method, data) {
|
||||
const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'wms',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
const res = await fetch(`${BASE_URL}/system?${qs}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const text = await res.text();
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return { raw: text };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度优先查找对象中第一个匹配 key 的非空值。
|
||||
*
|
||||
* @param {*} target 待查找对象。
|
||||
* @param {string} key 目标字段名。
|
||||
* @return {*} 匹配值或 undefined。
|
||||
*/
|
||||
function deepFind(target, key) {
|
||||
if (target === null || target === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(target)) {
|
||||
for (const item of target) {
|
||||
const found = deepFind(item, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (typeof target === 'object') {
|
||||
for (const [ currentKey, value ] of Object.entries(target)) {
|
||||
if (currentKey === key && value !== null && value !== undefined && value !== '') {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(target)) {
|
||||
const found = deepFind(value, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主流程入口。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function main() {
|
||||
const login = await sysCall(null, 'user.login', {
|
||||
username: 'liufumingren',
|
||||
password: '111111',
|
||||
});
|
||||
const token = deepFind(login, 'token');
|
||||
if (!token) {
|
||||
throw new Error(`登录失败: ${JSON.stringify(login)}`);
|
||||
}
|
||||
console.log('[1] 登录成功');
|
||||
|
||||
// 1. 提交任务 271 拣货完成(订单不回池)
|
||||
const completeRes = await sysCall(token, 'pick.wavePickTaskComplete', {
|
||||
task_id: 271,
|
||||
mode: 1,
|
||||
});
|
||||
console.log(`[2] wavePickTaskComplete(271) 响应: ${JSON.stringify(completeRes).slice(0, 500)}`);
|
||||
|
||||
// 2. 再次抓取
|
||||
let fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
let state = Number(deepFind(fetchRes, 'fetch_state') || 0);
|
||||
let taskId = Number(deepFind(fetchRes, 'task_id') || 0);
|
||||
if (state === 3 && taskId > 0) {
|
||||
console.log(`[3] 存在未完成任务 ${taskId},取消后重试`);
|
||||
await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId });
|
||||
fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
state = Number(deepFind(fetchRes, 'fetch_state') || 0);
|
||||
taskId = Number(deepFind(fetchRes, 'task_id') || 0);
|
||||
}
|
||||
if (state !== 1 || taskId <= 0) {
|
||||
throw new Error(`抓取失败: ${JSON.stringify(fetchRes).slice(0, 400)}`);
|
||||
}
|
||||
console.log(`[3] 新任务 ${taskId} 创建成功`);
|
||||
|
||||
// 3. 验证新任务订单
|
||||
const connection = await mysql.createConnection(DB_CONFIG);
|
||||
try {
|
||||
const [ taskOrderRows ] = await connection.query(
|
||||
`SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`,
|
||||
[ taskId ]
|
||||
);
|
||||
const orderIds = taskOrderRows.map(row => Number(row.order_id));
|
||||
const [ orderRows ] = await connection.query(
|
||||
`SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`,
|
||||
[ orderIds ]
|
||||
);
|
||||
const todayCount = orderRows.filter(row => new Date(row.create_at).getTime() >= TODAY_START_UTC).length;
|
||||
console.log(`[4] 新任务抓取订单数: ${orderRows.length}, 其中今天订单: ${todayCount}`);
|
||||
console.log(` 订单ID: [${orderIds.join(', ')}]`);
|
||||
const passed = orderRows.length === 20 && todayCount === 20;
|
||||
console.log(`结论: ${passed ? '✅ 拣货完成后订单不回池,第一池已空,回落第二池抓满 20 条今天订单' : '❌ 与预期不符'}`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`验证失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,234 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 完整流程验证(按正规接口):
|
||||
* 1. 恢复 8 条今日前订单(1552 等)为未分配(wave_id=0),构成第一池;
|
||||
* 2. 取消活跃任务;
|
||||
* 3. 抓取 -> 新任务仅抓 8 条今日前订单(不足20不填充);
|
||||
* 4. pickCart.bindTaskCart 绑定拣货车;
|
||||
* 5. pick.wavePickTaskComplete 提交拣货完成 -> 订单不回池;
|
||||
* 6. 再次抓取 -> 第一池已空,回落第二池抓满 20 条今天订单。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const BASE_URL = 'http://127.0.0.1:6060';
|
||||
const DB_CONFIG = {
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
};
|
||||
const TODAY_START_UTC = Date.UTC(2026, 8, 5, 16, 0, 0);
|
||||
const KEEP_ORDER_IDS = [ 1552, 1757, 1859, 2229, 2555, 4705, 6260, 6488 ];
|
||||
|
||||
/**
|
||||
* 发送 /system POST 请求。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {string} method 方法名。
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 响应 JSON。
|
||||
*/
|
||||
async function sysCall(token, method, data) {
|
||||
const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'wms',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
const res = await fetch(`${BASE_URL}/system?${qs}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const text = await res.text();
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return { raw: text };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度优先查找对象中第一个匹配 key 的非空值。
|
||||
*
|
||||
* @param {*} target 待查找对象。
|
||||
* @param {string} key 目标字段名。
|
||||
* @return {*} 匹配值或 undefined。
|
||||
*/
|
||||
function deepFind(target, key) {
|
||||
if (target === null || target === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(target)) {
|
||||
for (const item of target) {
|
||||
const found = deepFind(item, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (typeof target === 'object') {
|
||||
for (const [ currentKey, value ] of Object.entries(target)) {
|
||||
if (currentKey === key && value !== null && value !== undefined && value !== '') {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(target)) {
|
||||
const found = deepFind(value, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一轮抓取(存在未完成任务时取消后重试)。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {number} round 轮次。
|
||||
* @return {Promise<number>} 任务 ID。
|
||||
*/
|
||||
async function fetchOnce(token, round) {
|
||||
const res = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
let state = Number(deepFind(res, 'fetch_state') || 0);
|
||||
let taskId = Number(deepFind(res, 'task_id') || 0);
|
||||
if (state === 3 && taskId > 0) {
|
||||
await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId });
|
||||
const retry = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
state = Number(deepFind(retry, 'fetch_state') || 0);
|
||||
taskId = Number(deepFind(retry, 'task_id') || 0);
|
||||
}
|
||||
if (state !== 1 || taskId <= 0) {
|
||||
throw new Error(`第${round}轮抓取失败: state=${state}`);
|
||||
}
|
||||
return taskId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取任务抓取订单的 create_at。
|
||||
*
|
||||
* @param {Object} connection 数据库连接。
|
||||
* @param {number} taskId 任务 ID。
|
||||
* @return {Promise<Array<Object>>} 订单行。
|
||||
*/
|
||||
async function readTaskOrders(connection, taskId) {
|
||||
const [ taskOrderRows ] = await connection.query(
|
||||
'SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC',
|
||||
[ taskId ]
|
||||
);
|
||||
const orderIds = taskOrderRows.map(row => Number(row.order_id));
|
||||
if (orderIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const [ orderRows ] = await connection.query(
|
||||
'SELECT id, create_at, wave_id FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC',
|
||||
[ orderIds ]
|
||||
);
|
||||
return orderRows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主流程入口。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function main() {
|
||||
const login = await sysCall(null, 'user.login', {
|
||||
username: 'liufumingren',
|
||||
password: '111111',
|
||||
});
|
||||
const token = deepFind(login, 'token');
|
||||
if (!token) {
|
||||
throw new Error(`登录失败: ${JSON.stringify(login)}`);
|
||||
}
|
||||
console.log('[1] 登录成功');
|
||||
|
||||
const connection = await mysql.createConnection(DB_CONFIG);
|
||||
try {
|
||||
// 1. 恢复 8 条今日前订单为未分配
|
||||
await connection.query(
|
||||
'UPDATE wms_order_delivery_100000 SET wave_id = 0 WHERE id IN (?)',
|
||||
[ KEEP_ORDER_IDS ]
|
||||
);
|
||||
console.log(`[2] 已恢复 8 条今日前订单为未分配: [${KEEP_ORDER_IDS.join(', ')}]`);
|
||||
|
||||
// 2. 取消活跃任务
|
||||
const [ activeTasks ] = await connection.query(
|
||||
'SELECT id FROM wms_wave_pick_task WHERE warehouse_id = 100000 AND status IN (0, 1)'
|
||||
);
|
||||
for (const row of activeTasks) {
|
||||
await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: Number(row.id) });
|
||||
}
|
||||
console.log(`[3] 已取消活跃任务: [${activeTasks.map(row => row.id).join(', ')}]`);
|
||||
|
||||
// 3. 第一轮抓取
|
||||
const firstTaskId = await fetchOnce(token, 1);
|
||||
const firstOrders = await readTaskOrders(connection, firstTaskId);
|
||||
const firstBeforeToday = firstOrders.filter(row => new Date(row.create_at).getTime() < TODAY_START_UTC);
|
||||
const firstPassed = firstOrders.length === 8 && firstBeforeToday.length === 8;
|
||||
console.log(`[4] 第一轮任务 ${firstTaskId} 抓取订单数: ${firstOrders.length}`);
|
||||
console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`);
|
||||
console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单' : '❌ 与预期不符'}`);
|
||||
|
||||
// 4. 找一台可用拣货车并绑车
|
||||
const [ cartRows ] = await connection.query(
|
||||
`SELECT id, cart_code FROM wms_pick_cart
|
||||
WHERE warehouse_id = 100000 AND status = 1
|
||||
ORDER BY id ASC LIMIT 1`
|
||||
);
|
||||
if (cartRows.length === 0) {
|
||||
throw new Error('仓库 100000 无可用拣货车');
|
||||
}
|
||||
const cartId = Number(cartRows[0].id);
|
||||
const bindRes = await sysCall(token, 'pickCart.bindTaskCart', {
|
||||
task_id: firstTaskId,
|
||||
cart_id: cartId,
|
||||
});
|
||||
console.log(`[5] 绑车(cart_id=${cartId})响应: ${JSON.stringify(bindRes).slice(0, 300)}`);
|
||||
|
||||
// 5. 提交拣货完成(订单不回池)
|
||||
const completeRes = await sysCall(token, 'pick.wavePickTaskComplete', {
|
||||
task_id: firstTaskId,
|
||||
mode: 1,
|
||||
});
|
||||
console.log(`[6] wavePickTaskComplete 响应: ${JSON.stringify(completeRes).slice(0, 400)}`);
|
||||
|
||||
const [ afterCompleteOrders ] = await connection.query(
|
||||
'SELECT id, wave_id FROM wms_order_delivery_100000 WHERE id IN (?)',
|
||||
[ KEEP_ORDER_IDS ]
|
||||
);
|
||||
const stayOutOfPool = afterCompleteOrders.every(row => Number(row.wave_id) > 0);
|
||||
console.log(`[7] 拣货完成后订单 wave_id 保持非0(不回池): ${stayOutOfPool ? '✅' : '❌'}`);
|
||||
|
||||
// 6. 第二轮抓取(第一池已空,回落第二池)
|
||||
const secondTaskId = await fetchOnce(token, 2);
|
||||
const secondOrders = await readTaskOrders(connection, secondTaskId);
|
||||
const secondToday = secondOrders.filter(row => new Date(row.create_at).getTime() >= TODAY_START_UTC);
|
||||
const secondPassed = secondOrders.length === 20 && secondToday.length === 20;
|
||||
console.log(`[8] 第二轮任务 ${secondTaskId} 抓取订单数: ${secondOrders.length}`);
|
||||
console.log(` 今天订单数: ${secondToday.length}, 订单ID: [${secondOrders.map(row => row.id).join(', ')}]`);
|
||||
console.log(` 验证(第一池清空后抓满20条今天订单): ${secondPassed ? '✅ 回落第二池并抓满 20' : '❌ 与预期不符'}`);
|
||||
|
||||
console.log('==================== 总结 ====================');
|
||||
console.log(`第一轮(第一池8条): 实际 ${firstOrders.length} 条 -> ${firstPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`拣货完成不回池: ${stayOutOfPool ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`第二轮(第二池今天): 实际 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`结论: ${firstPassed && stayOutOfPool && secondPassed ? '✅ 全部通过: 不足20不填充;拣货完成后订单不回池;第一池清空后回落第二池抓满20' : '❌ 存在与预期不符的环节'}`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`验证失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,341 +0,0 @@
|
||||
/**
|
||||
* 临时验证脚本:对比 stock.report.search 改造后的 SQL(聚合极值)与旧 SQL(全量明细+JS归并)在开发库的结果等价性。
|
||||
* 用法:node script/tmp-verify-report-edge-sql.cjs
|
||||
* 验证完成后可删除。
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
const { createRequire } = require('module');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
function buildOldEdgeMap(rows, keyFn) {
|
||||
const map = new Map();
|
||||
for (const row of rows) {
|
||||
const key = keyFn(row);
|
||||
if (!map.has(key)) {
|
||||
map.set(key, {
|
||||
first_before: row.before_quantity,
|
||||
last_after: row.after_quantity,
|
||||
});
|
||||
} else {
|
||||
map.get(key).last_after = row.after_quantity;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function buildOldPreStartMap(rows, keyFn) {
|
||||
const latest = new Map();
|
||||
for (const row of rows) {
|
||||
const key = keyFn(row);
|
||||
if (!key) continue;
|
||||
const ct = new Date(row.created_at).getTime();
|
||||
const id = Number(row.id);
|
||||
const cur = latest.get(key);
|
||||
if (!cur || ct > cur.ct || (ct === cur.ct && id > cur.id)) {
|
||||
latest.set(key, { after_quantity: row.after_quantity, ct, id });
|
||||
}
|
||||
}
|
||||
const map = new Map();
|
||||
for (const [ key, v ] of latest.entries()) {
|
||||
map.set(key, v.after_quantity);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function diffMaps(label, oldMap, newMap) {
|
||||
const keys = new Set([ ...oldMap.keys(), ...newMap.keys() ]);
|
||||
const diffs = [];
|
||||
for (const key of keys) {
|
||||
const a = oldMap.get(key);
|
||||
const b = newMap.get(key);
|
||||
const isScalarOld = a === null || typeof a !== 'object';
|
||||
const isScalarNew = b === null || typeof b !== 'object';
|
||||
if (isScalarOld || isScalarNew) {
|
||||
const av = Number(a === undefined || a === null ? 0 : a);
|
||||
const bv = Number(b === undefined || b === null ? 0 : b);
|
||||
if (av !== bv) {
|
||||
diffs.push(`${key}: old=${JSON.stringify(a)} new=${JSON.stringify(b)}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const aFirst = a.first_before === undefined ? null : a.first_before;
|
||||
const aLast = a.last_after === undefined ? null : a.last_after;
|
||||
const bFirst = b.first_before === undefined ? null : b.first_before;
|
||||
const bLast = b.last_after === undefined ? null : b.last_after;
|
||||
if (Number(aFirst) !== Number(bFirst) || Number(aLast) !== Number(bLast)) {
|
||||
diffs.push(`${key}: old=(${aFirst},${aLast}) new=(${bFirst},${bLast})`);
|
||||
}
|
||||
}
|
||||
console.log(`[${label}] old keys=${oldMap.size}, new keys=${newMap.size}, diffs=${diffs.length}`);
|
||||
diffs.slice(0, 10).forEach(d => console.log(' DIFF ' + d));
|
||||
return diffs.length === 0;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const configFactory = require(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const config = typeof configFactory === 'function' ? configFactory({ name: 'wms-debug' }) : configFactory;
|
||||
const client = config.mysql.clients.wms;
|
||||
|
||||
const connection = await mysql.createConnection({
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: 'utf8mb4',
|
||||
});
|
||||
|
||||
try {
|
||||
const startTime = '2026-08-01 00:00:00';
|
||||
const endTime = '2026-08-31 23:59:59';
|
||||
// by_space=false 分支用更宽区间(覆盖区间内有流水的场景)
|
||||
const wideStart = '2026-05-01 00:00:00';
|
||||
const wideEnd = '2026-09-03 00:00:00';
|
||||
|
||||
// ============ by_space=false(wms_stock_transaction) ============
|
||||
const warehouseId = 1000028;
|
||||
const oldRangeParams = [ warehouseId, wideStart, wideEnd ];
|
||||
|
||||
const oldIntervalRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at ASC, t.id ASC`,
|
||||
oldRangeParams
|
||||
))[0];
|
||||
|
||||
const newIntervalRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
ft.before_quantity,
|
||||
lt.after_quantity,
|
||||
ft.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
0 AS space_id,
|
||||
t.store_id,
|
||||
MIN(t.created_at) AS _min_ct,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id)
|
||||
FROM wms_stock_transaction t2
|
||||
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
|
||||
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_stock_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`,
|
||||
[ warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd, warehouseId, wideStart, wideEnd ]
|
||||
))[0];
|
||||
|
||||
const oldEdge = buildOldEdgeMap(oldIntervalRows, r => `${r.stock_id}_${r.store_id}`);
|
||||
const newEdge = new Map(newIntervalRows.map(r => [
|
||||
`${r.stock_id}_${r.store_id}`,
|
||||
{ first_before: r.before_quantity, last_after: r.after_quantity },
|
||||
]));
|
||||
const edgeOk = diffMaps('edge by_space=false', oldEdge, newEdge);
|
||||
|
||||
// 旧 preStart(全量历史 + JS 归并)
|
||||
const oldPreRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, t.store_id, t.after_quantity, t.created_at
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at DESC, t.id DESC`,
|
||||
[ warehouseId, startTime ]
|
||||
))[0];
|
||||
|
||||
const newPreRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
lt.after_quantity,
|
||||
lt.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
0 AS space_id,
|
||||
t.store_id,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_stock_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at < ?
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`,
|
||||
[ warehouseId, startTime, warehouseId, startTime ]
|
||||
))[0];
|
||||
|
||||
const oldPre = buildOldPreStartMap(oldPreRows, r => `${r.stock_id}_${r.store_id}`);
|
||||
const newPre = new Map(newPreRows.map(r => [ `${r.stock_id}_${r.store_id}`, r.after_quantity ]));
|
||||
const preOk = diffMaps('preStart by_space=false', oldPre, newPre);
|
||||
|
||||
// ============ by_space=true(wms_storage_transaction) ============
|
||||
const whRows = (await connection.query(
|
||||
'SELECT warehouse_id, COUNT(*) AS cnt FROM wms_storage_transaction GROUP BY warehouse_id ORDER BY cnt DESC LIMIT 1'
|
||||
))[0];
|
||||
const storageWh = Number(whRows[0] && whRows[0].warehouse_id) || 0;
|
||||
console.log(`storage_transaction max warehouse_id=${storageWh}`);
|
||||
|
||||
const oldSpaceRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.before_quantity, t.after_quantity, t.created_at
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at ASC, t.id ASC`,
|
||||
[ storageWh, startTime, endTime ]
|
||||
))[0];
|
||||
|
||||
const newSpaceRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
ft.before_quantity,
|
||||
lt.after_quantity,
|
||||
ft.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
COALESCE(t.space_id, 0) AS space_id,
|
||||
t.store_id,
|
||||
MIN(t.created_at) AS _min_ct,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_storage_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id)
|
||||
FROM wms_storage_transaction t2
|
||||
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
|
||||
AND t2.stock_id = g.stock_id AND COALESCE(t2.space_id, 0) = g.space_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_storage_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_storage_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
|
||||
AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._min_ct ASC, g._max_ct ASC`,
|
||||
[ storageWh, startTime, endTime, storageWh, startTime, endTime, storageWh, startTime, endTime ]
|
||||
))[0];
|
||||
|
||||
const oldSpaceEdge = buildOldEdgeMap(oldSpaceRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`);
|
||||
const newSpaceEdge = new Map(newSpaceRows.map(r => [
|
||||
`${r.stock_id}_${r.space_id}_${r.store_id}`,
|
||||
{ first_before: r.before_quantity, last_after: r.after_quantity },
|
||||
]));
|
||||
const spaceEdgeOk = diffMaps('edge by_space=true', oldSpaceEdge, newSpaceEdge);
|
||||
|
||||
const oldSpacePreRows = (await connection.query(
|
||||
`SELECT t.id, t.stock_id, COALESCE(t.space_id, 0) AS space_id, t.store_id, t.after_quantity, t.created_at
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
ORDER BY t.stock_id ASC, COALESCE(t.space_id, 0) ASC, t.store_id ASC, t.created_at DESC, t.id DESC`,
|
||||
[ storageWh, startTime ]
|
||||
))[0];
|
||||
|
||||
const newSpacePreRows = (await connection.query(
|
||||
`SELECT
|
||||
g.stock_id,
|
||||
g.space_id,
|
||||
g.store_id,
|
||||
lt.after_quantity,
|
||||
lt.created_at
|
||||
FROM (
|
||||
SELECT
|
||||
t.stock_id,
|
||||
COALESCE(t.space_id, 0) AS space_id,
|
||||
t.store_id,
|
||||
MAX(t.created_at) AS _max_ct
|
||||
FROM wms_storage_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at < ?
|
||||
GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_storage_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id)
|
||||
FROM wms_storage_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at < ?
|
||||
AND t3.stock_id = g.stock_id AND COALESCE(t3.space_id, 0) = g.space_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id ASC, g.space_id ASC, g.store_id ASC, g._max_ct DESC`,
|
||||
[ storageWh, startTime, storageWh, startTime ]
|
||||
))[0];
|
||||
|
||||
const oldSpacePre = buildOldPreStartMap(oldSpacePreRows, r => `${r.stock_id}_${r.space_id}_${r.store_id}`);
|
||||
const newSpacePre = new Map(newSpacePreRows.map(r => [ `${r.stock_id}_${r.space_id}_${r.store_id}`, r.after_quantity ]));
|
||||
const spacePreOk = diffMaps('preStart by_space=true', oldSpacePre, newSpacePre);
|
||||
|
||||
// ============ EXPLAIN 新 intervalEdge SQL ============
|
||||
const explainRows = (await connection.query(
|
||||
`EXPLAIN
|
||||
SELECT
|
||||
g.stock_id, g.space_id, g.store_id, ft.before_quantity, lt.after_quantity, ft.created_at
|
||||
FROM (
|
||||
SELECT t.stock_id, 0 AS space_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.warehouse_id = ? AND t.created_at >= ? AND t.created_at <= ?
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id) FROM wms_stock_transaction t2
|
||||
WHERE t2.warehouse_id = ? AND t2.created_at >= ? AND t2.created_at <= ?
|
||||
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id) FROM wms_stock_transaction t3
|
||||
WHERE t3.warehouse_id = ? AND t3.created_at >= ? AND t3.created_at <= ?
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)`,
|
||||
[ warehouseId, startTime, endTime, warehouseId, startTime, endTime, warehouseId, startTime, endTime ]
|
||||
))[0];
|
||||
console.log('--- EXPLAIN new intervalEdge ---');
|
||||
explainRows.forEach(r => console.log(` ${r.id} | ${r.select_type} | ${r.table} | type=${r.type} | possible_keys=${r.possible_keys} | key=${r.key} | rows=${r.rows}`));
|
||||
|
||||
const allOk = edgeOk && preOk && spaceEdgeOk && spacePreOk;
|
||||
console.log(allOk ? '\n=== ALL PASS ===' : '\n=== FAIL ===');
|
||||
process.exit(allOk ? 0 : 1);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
})().catch(err => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,77 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时预演脚本(只读,不投递):按投递计划 id=2(store 1000000 / report_definition_id=3 /
|
||||
* 时间点 19:40 → biz_date=2026-09-09)的参数,走报表引擎 buildWorkbookSheets 生成工作簿,
|
||||
* 检查「库内确定拦截订单明细」投递结果是否与预期一致(行数 / 表头 / 抽样单元格)。
|
||||
*
|
||||
* 不做任何数据库写操作,不上传文件(用 generateBuffer)。
|
||||
* 运行:node script/tmp-verify-report-plan-2-preview.cjs
|
||||
*/
|
||||
const path = require('node:path');
|
||||
const mm = require('egg-mock');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const STORE_ID = 1000000;
|
||||
const WAREHOUSE_ID = 100000;
|
||||
const REPORT_ID = 3;
|
||||
const BIZ_DATE = '2026-09-09';
|
||||
|
||||
(async () => {
|
||||
mm.env('local');
|
||||
const app = mm.app({ baseDir: projectRoot });
|
||||
await app.ready();
|
||||
const ctx = app.createAnonymousContext();
|
||||
ctx.user = { store_id: WAREHOUSE_ID, role: 1, id: 1, name: 'preview', employees_id: 1, employees_name: 'preview' };
|
||||
|
||||
try {
|
||||
// 1) 查询器口径(含 storeId 过滤)
|
||||
const querier = require(path.join(projectRoot, 'app/service/systems/report/queries/interceptOrder.js'));
|
||||
const queryData = await querier({
|
||||
ctx,
|
||||
storeId: STORE_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
params: { bizDate: BIZ_DATE },
|
||||
});
|
||||
console.log('[查询器] meta=' + JSON.stringify(queryData.meta));
|
||||
console.log('[查询器] rows=' + queryData.rows.length);
|
||||
for (const row of queryData.rows.slice(0, 5)) {
|
||||
console.log(' ' + JSON.stringify({
|
||||
id: row.id,
|
||||
delivery_order_code: row.delivery_order_code,
|
||||
intercept_notice_time: row.intercept_notice_time,
|
||||
intercept_confirm_time: row.intercept_confirm_time,
|
||||
waybill_code: row.waybill_code,
|
||||
item_quantity: row.item_quantity,
|
||||
}));
|
||||
}
|
||||
|
||||
// 2) 报表引擎(按报表定义 id=3 的勾选字段渲染工作簿)
|
||||
const workbook = await ctx.service.systems.report.buildWorkbookSheets({
|
||||
reportId: REPORT_ID,
|
||||
storeId: STORE_ID,
|
||||
warehouseId: WAREHOUSE_ID,
|
||||
params: { bizDate: BIZ_DATE },
|
||||
});
|
||||
const sheet = workbook.sheets[0];
|
||||
console.log('[工作簿] filename=' + workbook.filename);
|
||||
console.log('[工作簿] sheet=' + sheet.name + ' 表头列数=' + (sheet.rows[0] || []).length + ' 总行数=' + sheet.rows.length);
|
||||
console.log('[工作簿] 表头=' + JSON.stringify(sheet.rows[0]));
|
||||
for (const row of sheet.rows.slice(1, 6)) {
|
||||
console.log('[工作簿] 数据行=' + JSON.stringify(row));
|
||||
}
|
||||
|
||||
// 3) 结论
|
||||
const dataRows = Math.max(0, sheet.rows.length - 1);
|
||||
console.log(
|
||||
dataRows > 0
|
||||
? `\n预演结果:投递将包含 ${dataRows} 行数据(订单 ${queryData.meta.orderCount} 单)`
|
||||
: '\n预演结果:投递将为空表(0 行),需要检查统计窗口与 dispath_time 数据'
|
||||
);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
})().catch(error => {
|
||||
console.error('预演执行异常:', error && error.stack ? error.stack : error);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,226 +0,0 @@
|
||||
/**
|
||||
* 临时只读核对脚本(生产库,仅 SELECT):
|
||||
* 核对 stock.report.searchStore 报表期初/期末快照 SQL 的关联缺失问题。
|
||||
*
|
||||
* 用法(生产):
|
||||
* $env:NODE_ENV='production'; node script/tmp-verify-stockreport-edge-prod.cjs
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const { createRequire } = require('module');
|
||||
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
function loadProdDbConfig() {
|
||||
const defaultConfigPath = path.join(projectRoot, 'config', 'config.default.js');
|
||||
const defaultConfigFactory = require(defaultConfigPath);
|
||||
const defaultConfig = typeof defaultConfigFactory === 'function'
|
||||
? defaultConfigFactory({ name: 'tmp-verify-stockreport-edge', baseDir: projectRoot })
|
||||
: defaultConfigFactory;
|
||||
const sequelizeConfig = defaultConfig && defaultConfig.sequelize;
|
||||
if (sequelizeConfig && sequelizeConfig.host) {
|
||||
return {
|
||||
host: sequelizeConfig.host,
|
||||
port: Number(sequelizeConfig.port || 3306),
|
||||
user: sequelizeConfig.username,
|
||||
password: sequelizeConfig.password,
|
||||
database: sequelizeConfig.database || 'wms',
|
||||
};
|
||||
}
|
||||
throw new Error('无法解析生产数据库配置');
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const dbConfig = loadProdDbConfig();
|
||||
console.log('目标:', dbConfig.host + ':' + dbConfig.port + '/' + dbConfig.database, '(生产 config.default.js)');
|
||||
|
||||
const connection = await mysql.createConnection(dbConfig);
|
||||
|
||||
try {
|
||||
const storeId = 1000166;
|
||||
const warehouseId = 1000028;
|
||||
const stockIds = [ 132556, 132603, 132604, 132610, 132611, 133746, 133747, 133752 ];
|
||||
|
||||
console.log('\n=== 1) 目标 SKU 的仓库绑定与当前库存 ===');
|
||||
const [ swRows ] = await connection.query(
|
||||
'SELECT id, store_id, warehouse_id, quantity, item_code, item_name FROM wms_stock_warehouse WHERE id IN (?) ORDER BY id',
|
||||
[ stockIds ]
|
||||
);
|
||||
for (const row of swRows) {
|
||||
console.log(JSON.stringify(row));
|
||||
}
|
||||
|
||||
console.log('\n=== 2) 全部流水明细(wms_stock_transaction,按 SKU 分组) ===');
|
||||
const [ flowRows ] = await connection.query(
|
||||
`SELECT id, stock_id, transaction_type, quantity, before_quantity, after_quantity,
|
||||
DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') AS created_at
|
||||
FROM wms_stock_transaction
|
||||
WHERE stock_id IN (?) AND store_id = ? AND warehouse_id = ?
|
||||
ORDER BY stock_id, created_at, id
|
||||
LIMIT 300`,
|
||||
[ stockIds, storeId, warehouseId ]
|
||||
);
|
||||
let lastStockId = null;
|
||||
for (const row of flowRows) {
|
||||
if (row.stock_id !== lastStockId) {
|
||||
console.log(`\n-- stock_id ${row.stock_id} --`);
|
||||
lastStockId = row.stock_id;
|
||||
}
|
||||
console.log(
|
||||
` id=${row.id} type=${row.transaction_type} qty=${row.quantity} before=${row.before_quantity} after=${row.after_quantity} at=${row.created_at}`
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\n=== 3) 区间汇总(rangeRows 口径:INBOUND/OUTBOUND 求和) ===');
|
||||
const [ rangeRows ] = await connection.query(
|
||||
`SELECT t.stock_id,
|
||||
SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total,
|
||||
SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.store_id = ? AND t.warehouse_id = ? AND t.stock_id IN (?)
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
ORDER BY t.stock_id`,
|
||||
[ storeId, warehouseId, stockIds ]
|
||||
);
|
||||
for (const row of rangeRows) {
|
||||
console.log(JSON.stringify(row));
|
||||
}
|
||||
|
||||
console.log('\n=== 4) 现有快照 SQL(缺 stock_id 关联,BUG 版本) vs 修正版 ===');
|
||||
const [ buggy ] = await connection.query(
|
||||
`SELECT g.stock_id,
|
||||
ft.before_quantity AS buggy_begin,
|
||||
lt.after_quantity AS buggy_end
|
||||
FROM (
|
||||
SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.store_id = ? AND t.warehouse_id = ? AND t.stock_id IN (?)
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id) FROM wms_stock_transaction t2
|
||||
WHERE t2.store_id = ? AND t2.warehouse_id = ? AND t2.stock_id IN (?)
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id) FROM wms_stock_transaction t3
|
||||
WHERE t3.store_id = ? AND t3.warehouse_id = ? AND t3.stock_id IN (?)
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id`,
|
||||
[ storeId, warehouseId, stockIds, storeId, warehouseId, stockIds, storeId, warehouseId, stockIds ]
|
||||
);
|
||||
|
||||
const [ fixed ] = await connection.query(
|
||||
`SELECT g.stock_id,
|
||||
ft.before_quantity AS fixed_begin,
|
||||
lt.after_quantity AS fixed_end
|
||||
FROM (
|
||||
SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.store_id = ? AND t.warehouse_id = ? AND t.stock_id IN (?)
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id) FROM wms_stock_transaction t2
|
||||
WHERE t2.store_id = ? AND t2.warehouse_id = ? AND t2.stock_id IN (?)
|
||||
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id) FROM wms_stock_transaction t3
|
||||
WHERE t3.store_id = ? AND t3.warehouse_id = ? AND t3.stock_id IN (?)
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id`,
|
||||
[ storeId, warehouseId, stockIds, storeId, warehouseId, stockIds, storeId, warehouseId, stockIds ]
|
||||
);
|
||||
|
||||
const buggyMap = new Map(buggy.map(r => [ r.stock_id, r ]));
|
||||
console.log('stock_id | buggy_begin | buggy_end | fixed_begin | fixed_end');
|
||||
for (const row of fixed) {
|
||||
const b = buggyMap.get(row.stock_id) || {};
|
||||
console.log(
|
||||
`${row.stock_id} | ${b.buggy_begin} | ${b.buggy_end} | ${row.fixed_begin} | ${row.fixed_end}`
|
||||
);
|
||||
}
|
||||
|
||||
console.log('\n=== 5) 不带仓库过滤(货主全仓库口径,用户报表场景) ===');
|
||||
const [ buggy2 ] = await connection.query(
|
||||
`SELECT g.stock_id,
|
||||
ft.before_quantity AS buggy_begin,
|
||||
lt.after_quantity AS buggy_end
|
||||
FROM (
|
||||
SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.store_id = ? AND t.stock_id IN (?)
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id) FROM wms_stock_transaction t2
|
||||
WHERE t2.store_id = ? AND t2.stock_id IN (?)
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id) FROM wms_stock_transaction t3
|
||||
WHERE t3.store_id = ? AND t3.stock_id IN (?)
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id`,
|
||||
[ storeId, stockIds, storeId, stockIds, storeId, stockIds ]
|
||||
);
|
||||
|
||||
const [ fixed2 ] = await connection.query(
|
||||
`SELECT g.stock_id,
|
||||
ft.before_quantity AS fixed_begin,
|
||||
lt.after_quantity AS fixed_end
|
||||
FROM (
|
||||
SELECT t.stock_id, t.store_id, MIN(t.created_at) AS _min_ct, MAX(t.created_at) AS _max_ct
|
||||
FROM wms_stock_transaction t
|
||||
WHERE t.store_id = ? AND t.stock_id IN (?)
|
||||
GROUP BY t.stock_id, t.store_id
|
||||
) g
|
||||
LEFT JOIN wms_stock_transaction ft
|
||||
ON ft.id = (
|
||||
SELECT MIN(t2.id) FROM wms_stock_transaction t2
|
||||
WHERE t2.store_id = ? AND t2.stock_id IN (?)
|
||||
AND t2.stock_id = g.stock_id AND t2.store_id = g.store_id
|
||||
AND t2.created_at = g._min_ct
|
||||
)
|
||||
LEFT JOIN wms_stock_transaction lt
|
||||
ON lt.id = (
|
||||
SELECT MAX(t3.id) FROM wms_stock_transaction t3
|
||||
WHERE t3.store_id = ? AND t3.stock_id IN (?)
|
||||
AND t3.stock_id = g.stock_id AND t3.store_id = g.store_id
|
||||
AND t3.created_at = g._max_ct
|
||||
)
|
||||
ORDER BY g.stock_id`,
|
||||
[ storeId, stockIds, storeId, stockIds, storeId, stockIds ]
|
||||
);
|
||||
|
||||
const buggy2Map = new Map(buggy2.map(r => [ r.stock_id, r ]));
|
||||
console.log('stock_id | buggy_begin | buggy_end | fixed_begin | fixed_end');
|
||||
for (const row of fixed2) {
|
||||
const b = buggy2Map.get(row.stock_id) || {};
|
||||
console.log(
|
||||
`${row.stock_id} | ${b.buggy_begin} | ${b.buggy_end} | ${row.fixed_begin} | ${row.fixed_end}`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
})().catch(err => {
|
||||
console.error(err && err.stack ? err.stack : String(err));
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,193 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 边界验证:第一订单池不足 20 时抓取行为。
|
||||
*
|
||||
* 验证点:
|
||||
* 1. 第一池(今日前)仅 8 条时,抓取数量 = 8,不会用第二池(今天订单)填充到 20;
|
||||
* 2. 第一池抓取完毕后,第二轮抓取进入第二池,抓满 20 条今天订单。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const BASE_URL = 'http://127.0.0.1:6060';
|
||||
const DB_CONFIG = {
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
};
|
||||
|
||||
/**
|
||||
* 发送 /system POST 请求。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {string} method 方法名。
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 响应 JSON。
|
||||
*/
|
||||
async function sysCall(token, method, data) {
|
||||
const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'wms',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
const res = await fetch(`${BASE_URL}/system?${qs}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const text = await res.text();
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return { raw: text };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度优先查找对象中第一个匹配 key 的非空值。
|
||||
*
|
||||
* @param {*} target 待查找对象。
|
||||
* @param {string} key 目标字段名。
|
||||
* @return {*} 匹配值或 undefined。
|
||||
*/
|
||||
function deepFind(target, key) {
|
||||
if (target === null || target === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(target)) {
|
||||
for (const item of target) {
|
||||
const found = deepFind(item, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (typeof target === 'object') {
|
||||
for (const [ currentKey, value ] of Object.entries(target)) {
|
||||
if (currentKey === key && value !== null && value !== undefined && value !== '') {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(target)) {
|
||||
const found = deepFind(value, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一轮抓取,返回 { taskId, orderRows }。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {Object} connection 数据库连接。
|
||||
* @return {Promise<Object>} 抓取结果。
|
||||
*/
|
||||
async function fetchOnce(token, connection, round) {
|
||||
const fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
const fetchState = Number(deepFind(fetchRes, 'fetch_state') || 0);
|
||||
const taskId = Number(deepFind(fetchRes, 'task_id') || 0);
|
||||
if (fetchState === 3 && taskId > 0) {
|
||||
await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId });
|
||||
const retryRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
const retryState = Number(deepFind(retryRes, 'fetch_state') || 0);
|
||||
const retryTaskId = Number(deepFind(retryRes, 'task_id') || 0);
|
||||
if (retryState !== 1 || retryTaskId <= 0) {
|
||||
throw new Error(`第${round}轮抓取重试后仍未创建任务: ${JSON.stringify(retryRes).slice(0, 400)}`);
|
||||
}
|
||||
return { taskId: retryTaskId };
|
||||
}
|
||||
if (fetchState !== 1 || taskId <= 0) {
|
||||
throw new Error(`第${round}轮抓取未创建任务: ${JSON.stringify(fetchRes).slice(0, 400)}`);
|
||||
}
|
||||
return { taskId };
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取任务订单与 create_at。
|
||||
*
|
||||
* @param {Object} connection 数据库连接。
|
||||
* @param {number} taskId 任务 ID。
|
||||
* @return {Promise<Array<Object>>} 订单行。
|
||||
*/
|
||||
async function readTaskOrders(connection, taskId) {
|
||||
const [ taskOrderRows ] = await connection.query(
|
||||
`SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`,
|
||||
[ taskId ]
|
||||
);
|
||||
const orderIds = taskOrderRows.map(row => Number(row.order_id));
|
||||
if (orderIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const [ orderRows ] = await connection.query(
|
||||
`SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`,
|
||||
[ orderIds ]
|
||||
);
|
||||
return orderRows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主流程入口。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function main() {
|
||||
const login = await sysCall(null, 'user.login', {
|
||||
username: 'liufumingren',
|
||||
password: '111111',
|
||||
});
|
||||
const token = deepFind(login, 'token');
|
||||
if (!token) {
|
||||
throw new Error(`登录失败: ${JSON.stringify(login)}`);
|
||||
}
|
||||
console.log('[1] 登录成功');
|
||||
|
||||
// 取消上一轮活跃任务 261
|
||||
await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: 261 });
|
||||
console.log('[2] 已取消任务 261');
|
||||
|
||||
const connection = await mysql.createConnection(DB_CONFIG);
|
||||
try {
|
||||
const todayStart = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00
|
||||
|
||||
// 第一轮:第一池仅 8 条今日前订单
|
||||
const first = await fetchOnce(token, connection, 1);
|
||||
const firstOrders = await readTaskOrders(connection, first.taskId);
|
||||
const firstBeforeToday = firstOrders.filter(row => new Date(row.create_at).getTime() < todayStart);
|
||||
console.log(`[3] 第一轮任务 ${first.taskId} 抓取订单数: ${firstOrders.length}`);
|
||||
console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`);
|
||||
const firstPassed = firstOrders.length === 8 && firstBeforeToday.length === 8;
|
||||
console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单,未填充今天订单' : '❌ 行为与预期不符'}`);
|
||||
|
||||
// 第二轮:第一池已空,进入第二池抓满 20
|
||||
const second = await fetchOnce(token, connection, 2);
|
||||
const secondOrders = await readTaskOrders(connection, second.taskId);
|
||||
const secondToday = secondOrders.filter(row => new Date(row.create_at).getTime() >= todayStart);
|
||||
console.log(`[4] 第二轮任务 ${second.taskId} 抓取订单数: ${secondOrders.length}`);
|
||||
console.log(` 今天订单数: ${secondToday.length}, 订单ID: [${secondOrders.map(row => row.id).join(', ')}]`);
|
||||
const secondPassed = secondOrders.length === 20 && secondToday.length === 20;
|
||||
console.log(` 验证(第一池清空后抓满20条今天订单): ${secondPassed ? '✅ 第一池抓完后回落第二池并抓满 20' : '❌ 行为与预期不符'}`);
|
||||
|
||||
console.log('==================== 总结 ====================');
|
||||
console.log(`第一轮(第一池8条): 实际抓取 ${firstOrders.length} 条 -> ${firstPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`第二轮(第二池今天): 实际抓取 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`结论: ${firstPassed && secondPassed ? '✅ 边界行为符合预期: 不足20不填充;第一池抓完才抓第二池' : '❌ 存在与预期不符的环节,请排查'}`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`验证失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,274 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单池边界验证(重做版):
|
||||
* 1. 取消所有活跃任务(释放订单回池);
|
||||
* 2. 重建混合池:满足抓取口径且未分配波次的候选,保留 8 条同结构今日前订单,其余全部改为今天;
|
||||
* 3. 第一轮抓取:预期仅抓 8 条今日前订单,不用今天订单填充到 20;
|
||||
* 4. 第二轮抓取:第一池清空后回落第二池,抓满 20 条今天订单;
|
||||
* 5. 输出验证结论。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const BASE_URL = 'http://127.0.0.1:6060';
|
||||
const DB_CONFIG = {
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
};
|
||||
const TODAY_TIME = '2026-09-06 12:00:00';
|
||||
const KEEP_COUNT = 8;
|
||||
const TODAY_START_UTC = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00
|
||||
|
||||
/**
|
||||
* 发送 /system POST 请求。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {string} method 方法名。
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 响应 JSON。
|
||||
*/
|
||||
async function sysCall(token, method, data) {
|
||||
const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'wms',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
const res = await fetch(`${BASE_URL}/system?${qs}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const text = await res.text();
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return { raw: text };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度优先查找对象中第一个匹配 key 的非空值。
|
||||
*
|
||||
* @param {*} target 待查找对象。
|
||||
* @param {string} key 目标字段名。
|
||||
* @return {*} 匹配值或 undefined。
|
||||
*/
|
||||
function deepFind(target, key) {
|
||||
if (target === null || target === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(target)) {
|
||||
for (const item of target) {
|
||||
const found = deepFind(item, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (typeof target === 'object') {
|
||||
for (const [ currentKey, value ] of Object.entries(target)) {
|
||||
if (currentKey === key && value !== null && value !== undefined && value !== '') {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(target)) {
|
||||
const found = deepFind(value, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消指定任务(不存在/已取消时静默)。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {number} taskId 任务 ID。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function cancelTask(token, taskId) {
|
||||
const res = await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId });
|
||||
const count = Number(deepFind(res, 'cancelled_count') || 0);
|
||||
console.log(` 取消任务 ${taskId}: cancelled_count=${count}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一轮抓取(存在未完成任务时取消后重试)。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {number} round 轮次。
|
||||
* @return {Promise<number>} 任务 ID。
|
||||
*/
|
||||
async function fetchOnce(token, round) {
|
||||
const res = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
let state = Number(deepFind(res, 'fetch_state') || 0);
|
||||
let taskId = Number(deepFind(res, 'task_id') || 0);
|
||||
if (state === 3 && taskId > 0) {
|
||||
await cancelTask(token, taskId);
|
||||
const retry = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
state = Number(deepFind(retry, 'fetch_state') || 0);
|
||||
taskId = Number(deepFind(retry, 'task_id') || 0);
|
||||
}
|
||||
if (state !== 1 || taskId <= 0) {
|
||||
throw new Error(`第${round}轮抓取失败: state=${state}`);
|
||||
}
|
||||
return taskId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取任务抓取订单的 create_at。
|
||||
*
|
||||
* @param {Object} connection 数据库连接。
|
||||
* @param {number} taskId 任务 ID。
|
||||
* @return {Promise<Array<Object>>} 订单行。
|
||||
*/
|
||||
async function readTaskOrders(connection, taskId) {
|
||||
const [ taskOrderRows ] = await connection.query(
|
||||
`SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`,
|
||||
[ taskId ]
|
||||
);
|
||||
const orderIds = taskOrderRows.map(row => Number(row.order_id));
|
||||
if (orderIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const [ orderRows ] = await connection.query(
|
||||
`SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`,
|
||||
[ orderIds ]
|
||||
);
|
||||
return orderRows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主流程入口。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function main() {
|
||||
const login = await sysCall(null, 'user.login', {
|
||||
username: 'liufumingren',
|
||||
password: '111111',
|
||||
});
|
||||
const token = deepFind(login, 'token');
|
||||
if (!token) {
|
||||
throw new Error(`登录失败: ${JSON.stringify(login)}`);
|
||||
}
|
||||
console.log('[1] 登录成功');
|
||||
|
||||
const connection = await mysql.createConnection(DB_CONFIG);
|
||||
try {
|
||||
// 2. 取消所有活跃任务
|
||||
const [ activeTasks ] = await connection.query(
|
||||
`SELECT id FROM wms_wave_pick_task WHERE warehouse_id = 100000 AND status IN (0, 1)`
|
||||
);
|
||||
for (const row of activeTasks) {
|
||||
await cancelTask(token, Number(row.id));
|
||||
}
|
||||
console.log('[2] 已取消全部活跃任务');
|
||||
|
||||
// 3. 重建混合池
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT o.id, o.create_at, o.items_hash
|
||||
FROM wms_order_wave_strategy_match m
|
||||
INNER JOIN wms_order_delivery_100000 o
|
||||
ON o.id = m.order_id
|
||||
WHERE m.warehouse_id = 100000
|
||||
AND m.strategy_id = 7
|
||||
AND o.wave_id = 0
|
||||
AND o.step != 0
|
||||
AND o.post_status = 'fin'
|
||||
AND o.storage_status = 'fin'
|
||||
AND o.print_status != 'fin'
|
||||
AND o.status != 'cancel'
|
||||
AND o.outbound_status != 'padding'
|
||||
AND o.intercept_status = 'none'
|
||||
AND o.lock_status = 'none'
|
||||
ORDER BY o.id ASC`
|
||||
);
|
||||
const beforeToday = rows.filter(row => new Date(row.create_at).getTime() < TODAY_START_UTC);
|
||||
console.log(`[3] 候选总数: ${rows.length},其中今日前: ${beforeToday.length}`);
|
||||
|
||||
const hashGroups = new Map();
|
||||
for (const row of beforeToday) {
|
||||
const key = String(row.items_hash || '').trim();
|
||||
if (!key) continue;
|
||||
if (!hashGroups.has(key)) hashGroups.set(key, []);
|
||||
hashGroups.get(key).push(row);
|
||||
}
|
||||
|
||||
// 策略 7 max_same_structure=12(仓库下调),须选同结构总数 2~12 的组
|
||||
let keepGroup = null;
|
||||
for (const list of hashGroups.values()) {
|
||||
const groupHash = String(list[0] && list[0].items_hash || '').trim();
|
||||
const [ countRows ] = await connection.query(
|
||||
`SELECT COUNT(1) AS cnt FROM wms_order_delivery_100000
|
||||
WHERE items_hash = ? AND wave_id = 0 AND step != 0 AND post_status = 'fin'
|
||||
AND storage_status = 'fin' AND print_status != 'fin' AND status != 'cancel'
|
||||
AND outbound_status != 'padding' AND intercept_status = 'none' AND lock_status = 'none'`,
|
||||
[ groupHash ]
|
||||
);
|
||||
const totalCount = Number(countRows && countRows[0] && countRows[0].cnt || 0);
|
||||
if (totalCount >= KEEP_COUNT && totalCount <= 12) {
|
||||
keepGroup = list;
|
||||
console.log(`[3] 选中保留组: hash=${groupHash.slice(0, 12)} 同结构总数=${totalCount}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!keepGroup) {
|
||||
console.log('未找到同结构总数 8~12 的今日前分组');
|
||||
keepGroup = beforeToday.slice(0, KEEP_COUNT);
|
||||
}
|
||||
const keepIds = keepGroup.slice(0, KEEP_COUNT).map(row => Number(row.id));
|
||||
const keepSet = new Set(keepIds);
|
||||
const moveIds = rows.map(row => Number(row.id)).filter(id => !keepSet.has(id));
|
||||
|
||||
if (moveIds.length > 0) {
|
||||
const [ updateResult ] = await connection.query(
|
||||
`UPDATE wms_order_delivery_100000 SET create_at = ? WHERE id IN (?)`,
|
||||
[ TODAY_TIME, moveIds ]
|
||||
);
|
||||
console.log(`[3] 保留今日前订单 ${keepIds.length} 条: [${keepIds.join(', ')}]`);
|
||||
console.log(`[3] 其余 ${updateResult.affectedRows} 条已改为今天 ${TODAY_TIME}`);
|
||||
}
|
||||
|
||||
// 4. 第一轮抓取
|
||||
const firstTaskId = await fetchOnce(token, 1);
|
||||
const firstOrders = await readTaskOrders(connection, firstTaskId);
|
||||
const firstBeforeToday = firstOrders.filter(row => new Date(row.create_at).getTime() < TODAY_START_UTC);
|
||||
const firstPassed = firstOrders.length === KEEP_COUNT && firstBeforeToday.length === KEEP_COUNT;
|
||||
console.log(`[4] 第一轮任务 ${firstTaskId} 抓取订单数: ${firstOrders.length}`);
|
||||
console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`);
|
||||
console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单,未用今天订单填充' : '❌ 行为与预期不符'}`);
|
||||
|
||||
// 5. 第二轮抓取
|
||||
const secondTaskId = await fetchOnce(token, 2);
|
||||
const secondOrders = await readTaskOrders(connection, secondTaskId);
|
||||
const secondToday = secondOrders.filter(row => new Date(row.create_at).getTime() >= TODAY_START_UTC);
|
||||
const secondPassed = secondOrders.length === 20 && secondToday.length === 20;
|
||||
console.log(`[5] 第二轮任务 ${secondTaskId} 抓取订单数: ${secondOrders.length}`);
|
||||
console.log(` 今天订单数: ${secondToday.length}, 订单ID: [${secondOrders.map(row => row.id).join(', ')}]`);
|
||||
console.log(` 验证(第一池清空后抓满20条今天订单): ${secondPassed ? '✅ 回落第二池并抓满 20' : '❌ 行为与预期不符'}`);
|
||||
|
||||
console.log('==================== 总结 ====================');
|
||||
console.log(`第一轮(第一池8条): 实际 ${firstOrders.length} 条 -> ${firstPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`第二轮(第二池今天): 实际 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`结论: ${firstPassed && secondPassed ? '✅ 边界行为符合预期: 不足20不填充;第一池抓完才抓第二池' : '❌ 存在与预期不符的环节,请排查'}`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`验证失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,190 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 边界验证(数据已由 tmp-prepare-wave-pool-boundary3 构造):
|
||||
* 第一池=8 条今日前订单(c51053111531 组),其余候选为今天订单。
|
||||
* 验证:第一轮仅抓 8 条今日前(不填充到 20);第二轮回落第二池抓满 20 条今天订单。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const BASE_URL = 'http://127.0.0.1:6060';
|
||||
const DB_CONFIG = {
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
};
|
||||
const TODAY_START_UTC = Date.UTC(2026, 8, 5, 16, 0, 0); // 2026-09-06 00:00 +08:00
|
||||
|
||||
/**
|
||||
* 发送 /system POST 请求。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {string} method 方法名。
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 响应 JSON。
|
||||
*/
|
||||
async function sysCall(token, method, data) {
|
||||
const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'wms',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
const res = await fetch(`${BASE_URL}/system?${qs}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const text = await res.text();
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return { raw: text };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度优先查找对象中第一个匹配 key 的非空值。
|
||||
*
|
||||
* @param {*} target 待查找对象。
|
||||
* @param {string} key 目标字段名。
|
||||
* @return {*} 匹配值或 undefined。
|
||||
*/
|
||||
function deepFind(target, key) {
|
||||
if (target === null || target === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(target)) {
|
||||
for (const item of target) {
|
||||
const found = deepFind(item, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (typeof target === 'object') {
|
||||
for (const [ currentKey, value ] of Object.entries(target)) {
|
||||
if (currentKey === key && value !== null && value !== undefined && value !== '') {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(target)) {
|
||||
const found = deepFind(value, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一轮抓取(存在未完成任务时取消后重试)。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {number} round 轮次。
|
||||
* @return {Promise<number>} 任务 ID。
|
||||
*/
|
||||
async function fetchOnce(token, round) {
|
||||
const res = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
let state = Number(deepFind(res, 'fetch_state') || 0);
|
||||
let taskId = Number(deepFind(res, 'task_id') || 0);
|
||||
if (state === 3 && taskId > 0) {
|
||||
await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: taskId });
|
||||
const retry = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
state = Number(deepFind(retry, 'fetch_state') || 0);
|
||||
taskId = Number(deepFind(retry, 'task_id') || 0);
|
||||
}
|
||||
if (state !== 1 || taskId <= 0) {
|
||||
throw new Error(`第${round}轮抓取失败: state=${state}`);
|
||||
}
|
||||
return taskId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取任务抓取订单的 create_at。
|
||||
*
|
||||
* @param {Object} connection 数据库连接。
|
||||
* @param {number} taskId 任务 ID。
|
||||
* @return {Promise<Array<Object>>} 订单行。
|
||||
*/
|
||||
async function readTaskOrders(connection, taskId) {
|
||||
const [ taskOrderRows ] = await connection.query(
|
||||
`SELECT order_id FROM wms_wave_pick_task_order WHERE task_id = ? ORDER BY box_no ASC`,
|
||||
[ taskId ]
|
||||
);
|
||||
const orderIds = taskOrderRows.map(row => Number(row.order_id));
|
||||
if (orderIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const [ orderRows ] = await connection.query(
|
||||
`SELECT id, create_at FROM wms_order_delivery_100000 WHERE id IN (?) ORDER BY id ASC`,
|
||||
[ orderIds ]
|
||||
);
|
||||
return orderRows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主流程入口。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function main() {
|
||||
const login = await sysCall(null, 'user.login', {
|
||||
username: 'liufumingren',
|
||||
password: '111111',
|
||||
});
|
||||
const token = deepFind(login, 'token');
|
||||
if (!token) {
|
||||
throw new Error(`登录失败: ${JSON.stringify(login)}`);
|
||||
}
|
||||
console.log('[1] 登录成功');
|
||||
|
||||
const connection = await mysql.createConnection(DB_CONFIG);
|
||||
try {
|
||||
const [ activeTasks ] = await connection.query(
|
||||
`SELECT id FROM wms_wave_pick_task WHERE warehouse_id = 100000 AND status IN (0, 1)`
|
||||
);
|
||||
for (const row of activeTasks) {
|
||||
await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: Number(row.id) });
|
||||
}
|
||||
console.log(`[2] 已取消活跃任务: [${activeTasks.map(row => row.id).join(', ')}]`);
|
||||
|
||||
// 第一轮
|
||||
const firstTaskId = await fetchOnce(token, 1);
|
||||
const firstOrders = await readTaskOrders(connection, firstTaskId);
|
||||
const firstBeforeToday = firstOrders.filter(row => new Date(row.create_at).getTime() < TODAY_START_UTC);
|
||||
const firstPassed = firstOrders.length === 8 && firstBeforeToday.length === 8;
|
||||
console.log(`[3] 第一轮任务 ${firstTaskId} 抓取订单数: ${firstOrders.length}`);
|
||||
console.log(` 今日前订单数: ${firstBeforeToday.length}, 订单ID: [${firstOrders.map(row => row.id).join(', ')}]`);
|
||||
console.log(` 验证(不足20不填充): ${firstPassed ? '✅ 仅抓 8 条今日前订单,未用今天订单填充' : '❌ 行为与预期不符'}`);
|
||||
|
||||
// 第二轮
|
||||
const secondTaskId = await fetchOnce(token, 2);
|
||||
const secondOrders = await readTaskOrders(connection, secondTaskId);
|
||||
const secondToday = secondOrders.filter(row => new Date(row.create_at).getTime() >= TODAY_START_UTC);
|
||||
const secondPassed = secondOrders.length === 20 && secondToday.length === 20;
|
||||
console.log(`[4] 第二轮任务 ${secondTaskId} 抓取订单数: ${secondOrders.length}`);
|
||||
console.log(` 今天订单数: ${secondToday.length}, 订单ID: [${secondOrders.map(row => row.id).join(', ')}]`);
|
||||
console.log(` 验证(第一池清空后抓满20条今天订单): ${secondPassed ? '✅ 回落第二池并抓满 20' : '❌ 行为与预期不符'}`);
|
||||
|
||||
console.log('==================== 总结 ====================');
|
||||
console.log(`第一轮(第一池8条): 实际 ${firstOrders.length} 条 -> ${firstPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`第二轮(第二池今天): 实际 ${secondOrders.length} 条 -> ${secondPassed ? 'PASS' : 'FAIL'}`);
|
||||
console.log(`结论: ${firstPassed && secondPassed ? '✅ 边界行为符合预期: 不足20不填充;第一池抓完才抓第二池' : '❌ 存在与预期不符的环节,请排查'}`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`验证失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,170 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单池分割验证:抓取并验证「今日前订单优先、不掺入今天订单」。
|
||||
*
|
||||
* 流程:
|
||||
* 1. 登录测试账号;
|
||||
* 2. 取消当前活跃任务(wavePickTaskCancelSelf,若存在);
|
||||
* 3. waveStrategyFetchPda 按策略 7 抓取(batch_max_orders=20);
|
||||
* 4. 从库中读取新任务抓取的订单,校验 create_at 全部早于今日 0 点。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const BASE_URL = 'http://127.0.0.1:6060';
|
||||
const DB_CONFIG = {
|
||||
host: '127.0.0.1',
|
||||
port: 3307,
|
||||
user: 'wms',
|
||||
password: 'dspxmRwRdRbWtbm7',
|
||||
database: 'wms',
|
||||
};
|
||||
|
||||
/**
|
||||
* 发送 /system POST 请求。
|
||||
*
|
||||
* @param {string} token 登录令牌。
|
||||
* @param {string} method 方法名。
|
||||
* @param {Object} data 请求体。
|
||||
* @return {Promise<Object>} 响应 JSON。
|
||||
*/
|
||||
async function sysCall(token, method, data) {
|
||||
const qs = `method=${encodeURIComponent(method)}&v=1.0×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
platform: 'web',
|
||||
project: 'wms',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
const res = await fetch(`${BASE_URL}/system?${qs}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
const text = await res.text();
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch (error) {
|
||||
return { raw: text };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 深度优先查找对象中第一个匹配 key 的非空值。
|
||||
*
|
||||
* @param {*} target 待查找对象。
|
||||
* @param {string} key 目标字段名。
|
||||
* @return {*} 匹配值或 undefined。
|
||||
*/
|
||||
function deepFind(target, key) {
|
||||
if (target === null || target === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(target)) {
|
||||
for (const item of target) {
|
||||
const found = deepFind(item, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (typeof target === 'object') {
|
||||
for (const [ currentKey, value ] of Object.entries(target)) {
|
||||
if (currentKey === key && value !== null && value !== undefined && value !== '') {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const value of Object.values(target)) {
|
||||
const found = deepFind(value, key);
|
||||
if (found !== undefined) {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 主流程入口。
|
||||
*
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function main() {
|
||||
const login = await sysCall(null, 'user.login', {
|
||||
username: 'liufumingren',
|
||||
password: '111111',
|
||||
});
|
||||
const token = deepFind(login, 'token');
|
||||
if (!token) {
|
||||
throw new Error(`登录失败: ${JSON.stringify(login)}`);
|
||||
}
|
||||
console.log('[1] 登录成功');
|
||||
|
||||
// 取消活跃任务 260(若存在)
|
||||
const cancelRes = await sysCall(token, 'order.wave.wavePickTaskCancelSelf', { task_id: 260 });
|
||||
console.log(`[2] 取消任务260响应: ${JSON.stringify(cancelRes).slice(0, 200)}`);
|
||||
|
||||
// 按策略 7 抓取
|
||||
const fetchRes = await sysCall(token, 'order.wave.waveStrategyFetchPda', { strategy_id: 7 });
|
||||
console.log(`[3] 抓取响应: ${JSON.stringify(fetchRes).slice(0, 600)}`);
|
||||
const fetchState = Number(deepFind(fetchRes, 'fetch_state') || 0);
|
||||
const taskId = Number(deepFind(fetchRes, 'task_id') || 0);
|
||||
if (fetchState !== 1 || taskId <= 0) {
|
||||
throw new Error(`抓取未创建新任务: fetch_state=${fetchState}`);
|
||||
}
|
||||
|
||||
// 从库读取该任务订单
|
||||
const connection = await mysql.createConnection(DB_CONFIG);
|
||||
try {
|
||||
const [ taskOrderRows ] = await connection.query(
|
||||
`SELECT order_id, wave_id, box_no
|
||||
FROM wms_wave_pick_task_order
|
||||
WHERE task_id = ?
|
||||
ORDER BY box_no ASC`,
|
||||
[ taskId ]
|
||||
);
|
||||
const orderIds = taskOrderRows.map(row => Number(row.order_id));
|
||||
console.log(`[4] 任务 ${taskId} 抓取订单数: ${orderIds.length}`);
|
||||
console.log(` 订单ID: [${orderIds.join(', ')}]`);
|
||||
|
||||
if (orderIds.length === 0) {
|
||||
throw new Error('任务未关联任何订单');
|
||||
}
|
||||
|
||||
const [ orderRows ] = await connection.query(
|
||||
`SELECT id, create_at
|
||||
FROM wms_order_delivery_100000
|
||||
WHERE id IN (?)
|
||||
ORDER BY id ASC`,
|
||||
[ orderIds ]
|
||||
);
|
||||
|
||||
// 今日 0 点(+08:00):2026-09-06 00:00 本地
|
||||
const todayStart = Date.UTC(2026, 8, 5, 16, 0, 0);
|
||||
const todayOrderIds = orderRows
|
||||
.filter(row => new Date(row.create_at).getTime() >= todayStart)
|
||||
.map(row => Number(row.id));
|
||||
const beforeTodayCount = orderRows.length - todayOrderIds.length;
|
||||
|
||||
console.log('===== 验证结果 =====');
|
||||
console.log(`任务抓取订单总数: ${orderRows.length}`);
|
||||
console.log(`其中今日前订单数: ${beforeTodayCount}`);
|
||||
console.log(`其中今天订单数: ${todayOrderIds.length}`);
|
||||
if (todayOrderIds.length > 0) {
|
||||
console.log(`混入的今天订单ID: [${todayOrderIds.join(', ')}]`);
|
||||
}
|
||||
const passed = beforeTodayCount === orderRows.length && orderRows.length > 0;
|
||||
console.log(`结论: ${passed ? '✅ 今日前订单优先出库验证通过,抓取未掺入今天订单' : '❌ 抓取掺入了今天订单,池分割未生效'}`);
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(`验证失败: ${error.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -1,100 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 临时观察脚本:轮询开发库投递记录,等待指定时间点的报表投递完成并打印结果。
|
||||
*
|
||||
* 作用:设置新投递时间点后无人值守地等结果(到点自动投递 → 打印 status/文件名/下载链接/错误)。
|
||||
* 只读(仅 SELECT),不修改任何数据。
|
||||
*
|
||||
* 用法:node script/tmp-watch-report-delivery.cjs [timePoint] [timeoutSeconds]
|
||||
* 默认 timePoint=20:25、timeout=900 秒(15 分钟)
|
||||
*/
|
||||
const path = require('node:path');
|
||||
const { createRequire } = require('node:module');
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
|
||||
const mysql = projectRequire('mysql2/promise');
|
||||
|
||||
const TIME_POINT = process.argv[2] || '20:25';
|
||||
const TIMEOUT_SECONDS = Number(process.argv[3] || 900);
|
||||
const TARGET_DEFINITION_IDS = [ 1, 3 ];
|
||||
const POLL_INTERVAL_MS = 10000;
|
||||
|
||||
/**
|
||||
* 读取开发库连接配置。
|
||||
* @return {Object} mysql 连接参数
|
||||
*/
|
||||
function loadDevDbConfig() {
|
||||
const factory = require(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const config = typeof factory === 'function' ? factory({ name: 'tmp-watch-delivery', baseDir: projectRoot }) : factory;
|
||||
const client = config && config.mysql && config.mysql.clients && config.mysql.clients.wms;
|
||||
if (!client || !client.host) {
|
||||
throw new Error('无法解析开发库配置 config.local.js(mysql.clients.wms)');
|
||||
}
|
||||
return {
|
||||
host: client.host,
|
||||
port: Number(client.port),
|
||||
user: client.user,
|
||||
password: client.password,
|
||||
database: client.database,
|
||||
charset: client.charset || 'utf8mb4',
|
||||
};
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const connection = await mysql.createConnection(loadDevDbConfig());
|
||||
const deadline = Date.now() + TIMEOUT_SECONDS * 1000;
|
||||
console.log(`[watch] 等待 time_point=${TIME_POINT} 的投递(定义 ${TARGET_DEFINITION_IDS.join('/')}),超时 ${TIMEOUT_SECONDS}s`);
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
const [ rows ] = await connection.query(
|
||||
`SELECT id, store_id, report_definition_id, report_name, biz_date, time_point, status,
|
||||
retry_count, error_message, delivered_at, file_url
|
||||
FROM wms_report_delivery_log
|
||||
WHERE time_point = ?
|
||||
AND report_definition_id IN (${TARGET_DEFINITION_IDS.map(() => '?').join(',')})
|
||||
ORDER BY report_definition_id`,
|
||||
[ TIME_POINT, ...TARGET_DEFINITION_IDS ]
|
||||
);
|
||||
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
const pending = list.filter(row => [ 'pending', 'exporting' ].includes(String(row.status)));
|
||||
const terminal = list.filter(row => [ 'delivered', 'failed', 'cancelled' ].includes(String(row.status)));
|
||||
|
||||
if (list.length > 0) {
|
||||
console.log(`[watch] ${new Date().toLocaleTimeString('zh-CN', { hour12: false })} 记录 ${list.length} 条(终态 ${terminal.length})`);
|
||||
}
|
||||
|
||||
if (terminal.length >= TARGET_DEFINITION_IDS.length || (list.length > 0 && pending.length === 0)) {
|
||||
for (const row of list) {
|
||||
console.log(
|
||||
`\n[结果] 定义=${row.report_definition_id}(${row.report_name})`
|
||||
+ `\n status=${row.status} biz_date=${row.biz_date} time_point=${row.time_point}`
|
||||
+ `\n retry_count=${row.retry_count}`
|
||||
+ `\n delivered_at=${row.delivered_at || '(空)'}`
|
||||
+ `\n 文件=${row.file_url || '(空)'}`
|
||||
+ (row.error_message ? `\n 错误=${row.error_message}` : '')
|
||||
);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (Date.now() >= deadline) {
|
||||
console.log(`\n[watch] 等待超时(${TIMEOUT_SECONDS}s),当前命中 ${list.length} 条记录`);
|
||||
for (const row of list) {
|
||||
console.log(` 定义=${row.report_definition_id} status=${row.status} 文件=${row.file_url || '(空)'} 错误=${row.error_message || '(空)'}`);
|
||||
}
|
||||
process.exit(list.length > 0 ? 0 : 1);
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS));
|
||||
}
|
||||
} finally {
|
||||
await connection.end();
|
||||
}
|
||||
})().catch(error => {
|
||||
console.error('[watch] 执行异常:', error && error.message ? error.message : error);
|
||||
process.exit(1);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user