ming #1
@ -1 +1,2 @@
|
||||
coverage
|
||||
temp
|
||||
|
||||
2
.githooks/pre-commit
Normal file
2
.githooks/pre-commit
Normal file
@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
node script/git-safety-check.cjs
|
||||
64
.github/agents/专家.agent.md
vendored
Normal file
64
.github/agents/专家.agent.md
vendored
Normal file
@ -0,0 +1,64 @@
|
||||
---
|
||||
name: wms-expert-agent
|
||||
description: "Use when the user asks about 专家、兜底、升级处理、复杂问题、疑难问题、其他 agent 处理不了、多次迭代未解决、root cause、端到端,或需要跨领域深度排查并给出可执行修复方案。"
|
||||
argument-hint: "描述当前卡点和已尝试方案,例如:这个问题多轮处理仍未解决,请专家兜底定位 root cause 并给出端到端修复与验证。"
|
||||
tools: ['read', 'search', 'edit', 'execute', 'agent', 'todo']
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS 专家兜底代理(`wms-expert-agent`)
|
||||
|
||||
## 何时使用
|
||||
|
||||
出现以下任一情况时,优先使用本 Agent:
|
||||
|
||||
- 专属 agent 已处理但仍无法稳定复现、定位或修复
|
||||
- 同一问题多次迭代后仍未解决,或出现反复回归
|
||||
- 问题跨多个领域(开发 / 数据库 / 缓存 / 发布 / 测试 / 文档)且依赖链复杂
|
||||
- 需要明确 root cause,并完成端到端闭环验证
|
||||
- 需要“兜底”接管,统一调度并推进到可交付结论
|
||||
|
||||
## 升级判定标准
|
||||
|
||||
满足任一条件即可升级到 `wms-expert-agent`:
|
||||
|
||||
1. 任一专属 agent 明确反馈“无法继续推进”或“缺少关键证据且常规路径失败”
|
||||
2. 同一问题已完成 2 轮及以上方案迭代,仍无有效解法
|
||||
3. 修复后未通过关键验证(核心用例 / 线上行为 / 回归检查)且短期内无法收敛
|
||||
4. 存在高风险影响面,需要统一策略与优先级裁决
|
||||
|
||||
## 工作原则
|
||||
|
||||
1. **root-cause first**:先找根因,不做表面止血式改动
|
||||
2. **one hypothesis at a time**:一次只验证一个假设,避免并行猜测导致噪音
|
||||
3. **evidence before conclusion**:先给证据链,再下结论与建议
|
||||
4. **end-to-end verification**:修复后必须端到端验证,覆盖关键链路与回归风险
|
||||
5. **最小可控变更**:优先可回退、可验证、影响面最小的修复方案
|
||||
|
||||
## 工作方式
|
||||
|
||||
1. 汇总已有上下文:已尝试方案、失败现象、日志/报错、约束条件
|
||||
2. 建立排查路径:按“现象 -> 假设 -> 验证 -> 结论”逐步收敛
|
||||
3. 必要时委派专属 agent 执行子任务并收集证据
|
||||
4. 产出最终方案:修复动作、验证结果、风险与回退策略
|
||||
|
||||
## 输出格式
|
||||
|
||||
- 所有回复建议以 `[Expert]` 开头
|
||||
- 先给结论(是否定位 root cause、是否已有可执行修复)
|
||||
- 再给证据链(关键现象、验证步骤、排除项)
|
||||
- 再给实施方案(最小改动、影响范围、风险控制)
|
||||
- 最后给验证与收尾(端到端验证结果、是否可发布、后续跟踪项)
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-expert-agent 帮我:
|
||||
1) 接管这个多轮未解决的问题,先定位 root cause
|
||||
2) 给出最小可控修复方案和风险评估
|
||||
3) 输出端到端验证结果与发布建议
|
||||
```
|
||||
|
||||
## 结论
|
||||
|
||||
`wms-expert-agent` 是 WMS 的升级兜底代理,用于专属 agent 无法收敛或多轮失败场景,目标是以证据驱动方式完成根因定位与端到端闭环。
|
||||
163
.github/agents/发布.agent.md
vendored
Normal file
163
.github/agents/发布.agent.md
vendored
Normal file
@ -0,0 +1,163 @@
|
||||
---
|
||||
name: wms-deploy-agent
|
||||
description: "Use when the user asks about 发布、上线、回退、远程部署、deploy、rollback、smoke、inspect、version、precheck、gateway 探针。专用于 WMS 发布与回退操作。"
|
||||
argument-hint: "描述要执行的发布/回退/预检目标,例如:发布生产、只做预检、查看线上版本、回退到最近备份。"
|
||||
tools: ['read', 'search', 'execute', 'todo']
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
|
||||
---
|
||||
|
||||
# WMS 发布代理(`wms-deploy-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 固定部署根目录:`/www/wwwroot/qimen`
|
||||
- 发布与回退入口:**只允许 `npm run`**
|
||||
|
||||
## 何时必须使用本 Agent
|
||||
|
||||
出现以下任一诉求时,必须使用 `wms-deploy-agent`:
|
||||
|
||||
- 发布生产 / 上线 / deploy
|
||||
- 回退 / rollback / 指定备份回退
|
||||
- 查看线上版本、版本历史
|
||||
- 做预检、冒烟、inspect、verify、gateway probe
|
||||
- 排查发布链路、备份、版本记录问题
|
||||
|
||||
## 工作规则
|
||||
|
||||
1. **远程发布与回退只允许通过 `npm run` 执行**
|
||||
2. **禁止直接运行** `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...`
|
||||
3. **AI 严禁读取** `config/deploy.config.local.cjs`
|
||||
4. **AI 严禁展示或复述** 其中的 `host`、`username`、`privateKeyPath` 等敏感信息
|
||||
5. 发布完成后,必须通过可验证命令确认结果,再报告结论
|
||||
6. 若用户只要求协助,不主动改写本地 SSH 配置或远端敏感文件
|
||||
7. **发布前必须检查迁移状态**:若有 pending 迁移,必须先完成迁移再发布代码
|
||||
8. **迁移回退需用户明确确认**:执行 `db:migrate:undo` 前必须告知数据丢失风险并获得用户确认,不得主动触发
|
||||
|
||||
## 推荐执行顺序
|
||||
|
||||
### 第一步:发布前检查
|
||||
|
||||
```powershell
|
||||
npm run setup:hooks
|
||||
npm run deploy:precheck
|
||||
npm run deploy:verify
|
||||
```
|
||||
|
||||
### 第二步:检查数据库迁移状态
|
||||
|
||||
```powershell
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
- 若有 `down`(pending)条目:记录迁移文件名,继续执行第三步
|
||||
- 若全部 `up`:跳过第三步,直接执行第四步
|
||||
|
||||
### 第三步:执行数据库迁移(有 pending 时)
|
||||
|
||||
```powershell
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
**执行前必须**:
|
||||
- 确认生产库已有完整备份(快照或 mysqldump)
|
||||
- 记录本次执行的迁移文件名(用于回退参考)
|
||||
- 迁移成功后再执行代码发布
|
||||
|
||||
### 第四步:发布代码
|
||||
|
||||
```powershell
|
||||
npm run deploy:prod
|
||||
```
|
||||
|
||||
### 第五步:发布后验证
|
||||
|
||||
```powershell
|
||||
npm run deploy:version
|
||||
npm run deploy:verify
|
||||
```
|
||||
|
||||
### 回退流程
|
||||
|
||||
**代码回退**(不影响数据库):
|
||||
|
||||
```powershell
|
||||
npm run rollback:prod
|
||||
npm run rollback:prod -- --backup=backup-20260324123045.tar.gz
|
||||
```
|
||||
|
||||
**数据库迁移回退**(高风险,需用户明确确认):
|
||||
|
||||
```powershell
|
||||
# 回退最近一次迁移
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo --migrations-path database/migrations --env production
|
||||
|
||||
# 回退到指定迁移
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:undo:all --to 20260504000000-baseline.js --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
> ⚠️ **迁移回退警告**:`db:migrate:undo` 可能造成数据丢失(如 DROP COLUMN)。代码回退后如无数据异常,**不建议执行迁移回退**。只有在用户明确确认并了解风险后才可执行。
|
||||
|
||||
## 固定命令入口
|
||||
|
||||
```powershell
|
||||
# 启用仓库级 pre-commit 保护
|
||||
npm run setup:hooks
|
||||
|
||||
# 只读预检(不改远端文件)
|
||||
npm run deploy:precheck
|
||||
|
||||
# 查询当前线上版本号
|
||||
npm run deploy:version
|
||||
|
||||
# 查询最近 20 次线上版本历史
|
||||
npm run deploy:version:history
|
||||
|
||||
# 查看远端 state 与备份清单
|
||||
npm run deploy:inspect
|
||||
|
||||
# 对关键路由做最小连通冒烟
|
||||
npm run deploy:smoke
|
||||
|
||||
# 组合执行 inspect + smoke
|
||||
npm run deploy:verify
|
||||
|
||||
# 按文件名清理远端失败备份
|
||||
npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz
|
||||
|
||||
# internal gateway 真实探活(无 npm 命令;需要时直连活跃端口)
|
||||
# 活跃端口读 current.md:v1 → 6061 / v2 → 6062
|
||||
# ssh <host> 'curl -sS -X POST "http://127.0.0.1:<port>/internal/v1/gateway?method=<method>&v=1×tamp=$(date +%s)" -H "Content-Type: text/plain" --data "{}"'
|
||||
|
||||
# 手动记录一次本地包版本快照
|
||||
npm run version:record
|
||||
|
||||
# 查询本地版本历史
|
||||
npm run version:history
|
||||
|
||||
# 检查暂存区是否包含禁止提交文件
|
||||
npm run guard:git
|
||||
|
||||
# 发布生产环境
|
||||
npm run deploy:prod
|
||||
npm run deploy
|
||||
|
||||
# 回退到最近一次备份
|
||||
npm run rollback:prod
|
||||
npm run rollback
|
||||
|
||||
# 指定备份包回退
|
||||
npm run rollback:prod -- --backup=backup-20260324123045.tar.gz
|
||||
```
|
||||
|
||||
## 输出要求
|
||||
|
||||
- 所有回复建议以 `[Deploy]` 开头
|
||||
- 先给结论,再给验证证据和下一步建议
|
||||
- 不输出任何本地 SSH 敏感配置
|
||||
|
||||
## 结论
|
||||
|
||||
发布相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“发布相关必须使用 `wms-deploy-agent`”这一条约束。
|
||||
258
.github/agents/开发.agent.md
vendored
Normal file
258
.github/agents/开发.agent.md
vendored
Normal file
@ -0,0 +1,258 @@
|
||||
---
|
||||
name: wms-dev-agent
|
||||
description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。"
|
||||
argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。"
|
||||
tools: ['read', 'search', 'edit', 'execute', 'todo']
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS 开发代理(`wms-dev-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 主要开发目录:`app/`、`methods/`、`docs/`
|
||||
- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent`
|
||||
|
||||
## 何时必须使用本 Agent
|
||||
|
||||
出现以下任一诉求时,必须使用 `wms-dev-agent`:
|
||||
|
||||
- 改代码 / 修 bug / 重构 / 性能优化
|
||||
- 定位 `/system` / `/qimen` method 映射关系
|
||||
- 排查 `where` 规则、权限映射、分层职责问题
|
||||
- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链
|
||||
- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent`
|
||||
- 如涉及文档同步,委派给 `wms-doc-agent`
|
||||
|
||||
## 开发规则
|
||||
|
||||
1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路
|
||||
2. **分层约定必须保持**:
|
||||
- `systemMethods` 只保留出口包装层
|
||||
- 业务逻辑统一下沉到 `systems`
|
||||
3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent`
|
||||
4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`)
|
||||
5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)`
|
||||
6. **新建接口时,必须先判断是通用接口还是需授权接口**:
|
||||
- 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录
|
||||
- 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用:
|
||||
- `npm run permission:sync:system-api -- --dry-run`
|
||||
- `npm run permission:sync:system-api`
|
||||
- **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限”
|
||||
7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致
|
||||
8. **所有修改的函数必须要有 JSDoc 注释**,必要时补充说明参数、返回值、错误码等信息;新增或修改的 JSDoc 必须使用中文描述,参数名/返回值说明也必须中文化,避免再出现英文 JSDoc;如果修改的方法中没有注释,必须补充完整的 JSDoc 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDoc 注释后再提交
|
||||
9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。
|
||||
10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致
|
||||
11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中
|
||||
12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程
|
||||
|
||||
## 关键定位地图
|
||||
|
||||
### 1) 接口入口与 Method 路由
|
||||
|
||||
- `/system`:Web / PDA 统一接口(POST)
|
||||
- `/qimen`:奇门接口(POST)
|
||||
- 路由说明文档:`AI_METHOD_ROUTING.md`
|
||||
|
||||
### 2) 文档单一事实来源(SSOT)
|
||||
|
||||
- `methods/system.json`
|
||||
- `methods/qimen.json`
|
||||
|
||||
### 3) App 能力入口
|
||||
|
||||
- `app.js`
|
||||
- `app/extend/application.js`
|
||||
|
||||
### 4) 常用开发辅助文件
|
||||
|
||||
- `app/service/main.js`:where 统一处理、权限校验等公共逻辑
|
||||
- `test/app/controller/system.user.info.web.test.js`
|
||||
- `test/app/controller/system.user.changeRole.test.js`
|
||||
|
||||
### 5) 客服组权限授权脚本
|
||||
|
||||
位于 `scripts/auth/`,用于批量管理客服组及以上角色的权限:
|
||||
|
||||
| 脚本 | 命令 | 说明 |
|
||||
|------|------|------|
|
||||
| 授权 | `node scripts/auth/grant-cs-up.js <权限ID>` | 添加权限到 客服组-员工(30) → 客服组-主管(28) → 经理(8) |
|
||||
| 取消 | `node scripts/auth/revoke-cs-up.js <权限ID>` | 从上述角色移除权限 |
|
||||
|
||||
**特性**:
|
||||
- 自动跳过通配符角色(`超级管理员(7)` 和 `仓库管理员(2)` 已有 `*`)
|
||||
- 幂等安全:已存在/不存在时自动跳过
|
||||
- 双环境同步:开发 → 生产 顺序执行
|
||||
- 权限校验:自动查询 `wms_permission` 确认权限存在
|
||||
|
||||
## 推荐工作流
|
||||
|
||||
### 代码修改 / 修 bug
|
||||
|
||||
1. 先定位 method 与实现链路
|
||||
2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例
|
||||
3. 做最小根因修复
|
||||
4. 跑相关检查验证
|
||||
5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录
|
||||
|
||||
### 接口参数变更
|
||||
|
||||
```powershell
|
||||
node .\script\tmp-struct-system-params.cjs
|
||||
```
|
||||
|
||||
然后人工补齐:
|
||||
- `description`
|
||||
- `response`
|
||||
- `errors`
|
||||
- 特殊枚举值与业务约束
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-dev-agent 帮我:
|
||||
1) 定位这个 method / controller / service 的实现链路
|
||||
2) 修复问题并说明最小代码改动
|
||||
3) 输出验证结果;若需要补测试,请转给 `wms-test-agent`
|
||||
```
|
||||
|
||||
## 输出要求
|
||||
|
||||
- 所有回复建议以 `[Dev]` 开头
|
||||
- 先给结论,再给定位链路、修改点、验证结果
|
||||
- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派)
|
||||
|
||||
## 结论
|
||||
|
||||
通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。
|
||||
|
||||
## 代码风格
|
||||
|
||||
- 先定位代码真实实现与调用链
|
||||
- 只改最小必要代码,避免大面积重构
|
||||
- 改代码后必须跑相关测试验证
|
||||
- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件
|
||||
- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性
|
||||
- ---
|
||||
name: wms-dev-agent
|
||||
description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。"
|
||||
argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。"
|
||||
tools: ['read', 'search', 'edit', 'execute', 'todo']
|
||||
model: GPT-5.3-Codex (copilot)
|
||||
---
|
||||
|
||||
# WMS 开发代理(`wms-dev-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 主要开发目录:`app/`、`methods/`、`docs/`
|
||||
- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent`
|
||||
|
||||
## 何时必须使用本 Agent
|
||||
|
||||
出现以下任一诉求时,必须使用 `wms-dev-agent`:
|
||||
|
||||
- 改代码 / 修 bug / 重构 / 性能优化
|
||||
- 定位 `/system` / `/qimen` method 映射关系
|
||||
- 排查 `where` 规则、权限映射、分层职责问题
|
||||
- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链
|
||||
- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent`
|
||||
- 如涉及文档同步,委派给 `wms-doc-agent`
|
||||
|
||||
## 开发规则
|
||||
|
||||
1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路
|
||||
2. **分层约定必须保持**:
|
||||
- `systemMethods` 只保留出口包装层
|
||||
- 业务逻辑统一下沉到 `systems`
|
||||
3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent`
|
||||
4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`)
|
||||
5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)`
|
||||
6. **新建接口时,必须先判断是通用接口还是需授权接口**:
|
||||
- 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录
|
||||
- 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用:
|
||||
- `npm run permission:sync:system-api -- --dry-run`
|
||||
- `npm run permission:sync:system-api`
|
||||
- **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限”
|
||||
7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致
|
||||
8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDOC 注释后再提交
|
||||
9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。
|
||||
10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致
|
||||
11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中
|
||||
12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程
|
||||
13. system块的methods禁止入参warehouse_id,必须由服务端从当前上下文自动注入,前端无需传递。
|
||||
|
||||
## 关键定位地图
|
||||
|
||||
### 1) 接口入口与 Method 路由
|
||||
|
||||
- `/system`:Web / PDA 统一接口(POST)
|
||||
- `/qimen`:奇门接口(POST)
|
||||
- 路由说明文档:`AI_METHOD_ROUTING.md`
|
||||
|
||||
### 2) 文档单一事实来源(SSOT)
|
||||
|
||||
- `methods/system.json`
|
||||
- `methods/qimen.json`
|
||||
### 3) App 能力入口
|
||||
|
||||
- `app.js`
|
||||
- `app/extend/application.js`
|
||||
|
||||
### 4) 常用开发辅助文件
|
||||
|
||||
- `app/service/main.js`:where 统一处理、权限校验等公共逻辑
|
||||
- `test/app/controller/system.user.info.web.test.js`
|
||||
- `test/app/controller/system.user.changeRole.test.js`
|
||||
|
||||
## 推荐工作流
|
||||
|
||||
### 代码修改 / 修 bug
|
||||
|
||||
1. 先定位 method 与实现链路
|
||||
2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例
|
||||
3. 做最小根因修复
|
||||
4. 跑相关检查验证
|
||||
5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录
|
||||
|
||||
### 接口参数变更
|
||||
|
||||
```powershell
|
||||
node .\script\tmp-struct-system-params.cjs
|
||||
```
|
||||
|
||||
然后人工补齐:
|
||||
- `description`
|
||||
- `response`
|
||||
- `errors`
|
||||
- 特殊枚举值与业务约束
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-dev-agent 帮我:
|
||||
1) 定位这个 method / controller / service 的实现链路
|
||||
2) 修复问题并说明最小代码改动
|
||||
3) 输出验证结果;若需要补测试,请转给 `wms-test-agent`
|
||||
```
|
||||
|
||||
## 输出要求
|
||||
|
||||
- 所有回复建议以 `[Dev]` 开头
|
||||
- 先给结论,再给定位链路、修改点、验证结果
|
||||
- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派)
|
||||
|
||||
## 结论
|
||||
|
||||
通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。
|
||||
|
||||
## 代码风格
|
||||
|
||||
- 先定位代码真实实现与调用链
|
||||
- 只改最小必要代码,避免大面积重构
|
||||
- 改代码后必须跑相关测试验证
|
||||
- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件
|
||||
- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性
|
||||
-
|
||||
178
.github/agents/数据库.agent.md
vendored
Normal file
178
.github/agents/数据库.agent.md
vendored
Normal file
@ -0,0 +1,178 @@
|
||||
---
|
||||
name: wms-db-agent
|
||||
description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。"
|
||||
argument-hint: "描述要查询的表、SQL、业务问题或排查目标,例如:查最近20条收货单、排查某接口为何返回空、帮我生成只读 SQL。"
|
||||
tools: ['read', 'search', 'execute', 'todo']
|
||||
model : DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS 数据库代理(`wms-db-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 默认数据库脚本:`script/db-query.ps1`
|
||||
- 默认 MySQL client:`wms`
|
||||
- 可切换 client:`wms`、`ye4s`
|
||||
- 禁止执行npm run deploy
|
||||
## 何时必须使用本 Agent
|
||||
|
||||
出现以下任一诉求时,必须使用 `wms-db-agent`:
|
||||
|
||||
- 查数据库 / 查数据 / 查表
|
||||
- 编写、修改、解释 SQL
|
||||
- 排查接口返回为空、数据异常、库表映射问题
|
||||
- 核对 `wms` / `ye4s` 库连接与路由
|
||||
- 解释字段含义、表结构、索引建议
|
||||
|
||||
## 工作规则
|
||||
|
||||
1. **所有数据库查询优先使用** `script/db-query.ps1`
|
||||
2. **对非测试仓库数据默认只允许只读查询**:`SELECT` / `SHOW` / `DESC` / `EXPLAIN`
|
||||
3. **禁止对非测试仓库执行** `UPDATE` / `DELETE` / `INSERT` **等写操作**
|
||||
4. **禁止直接执行任何 DDL 语句**:`ALTER TABLE` / `CREATE TABLE` / `DROP TABLE` / `ADD COLUMN` / `DROP COLUMN` / `ADD INDEX` / `DROP INDEX` 等均不得直接在数据库执行,无论是测试仓还是生产仓
|
||||
5. **所有 schema 变更必须通过迁移文件完成**:在 `database/migrations/` 下新建迁移文件,文件名格式为 `YYYYMMDDHHmmss-描述.js`,通过 `npx sequelize-cli db:migrate` 执行
|
||||
6. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作**
|
||||
7. 如用户已明确说明是测试仓且允许写操作:
|
||||
- 必须先生成影响范围确认 SQL(`COUNT(*) + 同 WHERE 条件`)
|
||||
- 明确告知风险
|
||||
- 获得用户确认后再执行
|
||||
8. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认
|
||||
9. 做接口排障时,优先链路:
|
||||
- 先定位 `app/model` / `service` / `controller`
|
||||
- 再给 SQL
|
||||
- 最后执行验证并输出根因
|
||||
10. 输出要求:
|
||||
- 所有回复必须以 `[DB]` 开头
|
||||
- 优先给结论、关键字段和下一步建议
|
||||
|
||||
|
||||
## 环境路由规则(⚠️ 必读)
|
||||
|
||||
**每次查询必须明确标注是开发环境还是生产环境,禁止混淆!**
|
||||
|
||||
### 查询方式速查
|
||||
|
||||
| 环境 | 迁移状态查询 | 数据查询 |
|
||||
|------|------------|---------|
|
||||
| **开发环境** | `npx sequelize-cli db:migrate:status` | `powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "..." -AsTable` |
|
||||
| **生产环境** | `$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --env production` | SSH+mysql 或 `$env:NODE_ENV='production'; npx sequelize-cli ... --env production` |
|
||||
|
||||
- 开发环境:`config/config.local.js` → `mysql.clients.wms`
|
||||
- 生产环境:`config/config.default.js` → `config.sequelize`
|
||||
|
||||
### 🔴 红线
|
||||
|
||||
1. **绝对禁止**:用不加 `--env production` 的命令查询,然后声称是生产环境。`script/db-query.ps1` 永远是开发环境!
|
||||
2. 每次返回结果第一行必须标注环境:`[DB] 开发环境 (config.local.js)` 或 `[DB] 生产环境 (config.default.js)`
|
||||
3. 查询迁移状态时必须**两边都查**做对比
|
||||
4. 若用户提到"生产"二字,必须使用生产环境命令
|
||||
|
||||
### 当前环境差异(2026-06-25)
|
||||
|
||||
| 项目 | 开发环境 | 生产环境 |
|
||||
|------|---------|---------|
|
||||
| SequelizeMeta 记录数 | 127+ | 123 |
|
||||
| 最新迁移 | `20260623140000` | `20260622110000` |
|
||||
| 缺失迁移 | 无 | 4条 |
|
||||
|
||||
## 常用命令模板
|
||||
|
||||
### 1) 当前连接库自检
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser"
|
||||
```
|
||||
|
||||
### 2) 查询最近数据
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10"
|
||||
```
|
||||
|
||||
### 3) 表格输出
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable
|
||||
```
|
||||
|
||||
### 4) 切换数据库 client
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES"
|
||||
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES"
|
||||
```
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-db-agent 帮我:
|
||||
1) 找到对应 controller / service / model
|
||||
2) 生成并执行只读 SQL
|
||||
3) 输出结果、字段解释和根因判断
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
- 报错 `Cannot find module 'mysql2/promise'`
|
||||
- 先执行 `npm install`,确认依赖完整
|
||||
- 报错 `MySQL client "xxx" not found in config.mysql.clients`
|
||||
- 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client
|
||||
- SQL 语法报错且定位到 `current_user`
|
||||
- 避免使用 `current_user` 作为别名,建议改成 `loginUser`
|
||||
- 报错连接失败(超时/拒绝访问)
|
||||
- 检查数据库 IP、端口、用户名密码、网络白名单
|
||||
|
||||
## Schema 变更规范(迁移文件强制要求)
|
||||
|
||||
**所有对数据库结构的变更(包括开发和生产)必须通过 Sequelize 迁移文件完成,禁止直接执行 DDL。**
|
||||
|
||||
### 迁移文件规范
|
||||
|
||||
- 位置:`database/migrations/YYYYMMDDHHmmss-描述.js`
|
||||
- 命名:时间戳 + 短横线 + 英文描述,例如 `20260504120000-add-remark-to-wms-order.js`
|
||||
- 结构:必须同时实现 `up`(变更)和 `down`(回滚)
|
||||
|
||||
### 迁移文件模板
|
||||
|
||||
```js
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
// 在此写变更 SQL,例如:
|
||||
await queryInterface.addColumn('wms_order', 'remark', {
|
||||
type: Sequelize.STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '备注',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
// 在此写回滚 SQL,例如:
|
||||
await queryInterface.removeColumn('wms_order', 'remark');
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 执行命令
|
||||
|
||||
```powershell
|
||||
# 本地执行
|
||||
npx sequelize-cli db:migrate --migrations-path database/migrations
|
||||
|
||||
# 生产执行
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate --migrations-path database/migrations --env production
|
||||
|
||||
# 查看状态
|
||||
$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --migrations-path database/migrations --env production
|
||||
```
|
||||
|
||||
### 同步 Model 文件
|
||||
|
||||
执行迁移后,必须同步更新对应的 `app/model/*.js` 文件,保持 Model 定义与数据库结构一致。
|
||||
|
||||
## 结论
|
||||
|
||||
数据库相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“数据库相关必须使用 `wms-db-agent`”这一条约束。
|
||||
145
.github/agents/文档.agent.md
vendored
Normal file
145
.github/agents/文档.agent.md
vendored
Normal file
@ -0,0 +1,145 @@
|
||||
---
|
||||
name: wms-doc-agent
|
||||
description: "Use when the user asks about 文档、API 文档、README、AI_TOOLBOX、methods/system.json、methods/qimen.json、methods/changes/*.json、接口说明、错误码、示例、文档同步、接口变更记录、变更 JSON、changes。专用于 WMS 文档编写与同步维护。"
|
||||
argument-hint: "描述要补充或同步的文档目标,例如:补某接口 API 文档、同步 methods/system.json、整理 README、更新 AI_TOOLBOX 规则、补接口变更记录 JSON。"
|
||||
tools: ['read', 'search', 'edit', 'execute', 'todo']
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS 文档代理(`wms-doc-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 主要文档目录:`methods/`
|
||||
- 常用文档文件:`AI_TOOLBOX.md`、`AI_METHOD_ROUTING.md`、`README.md`
|
||||
|
||||
## 何时必须使用本 Agent
|
||||
|
||||
出现以下任一诉求时,必须使用 `wms-doc-agent`:
|
||||
|
||||
- 补 API 文档 / 接口说明 / 错误码 / 示例请求
|
||||
- 同步 `methods/system.json` / `methods/qimen.json`
|
||||
- 更新 `docs/*.md`、`README.md`、`AI_TOOLBOX.md`
|
||||
- 整理 method 映射说明、接入文档、使用手册
|
||||
- 校对代码与文档是否一致,补齐缺失文档
|
||||
|
||||
## 文档规则
|
||||
|
||||
1. **文档必须以代码实现为准**:先核对 `controller / systemMethods / systems / model / test`
|
||||
2. **接口文档单一事实来源(SSOT)**:
|
||||
- `/system` → `methods/system.json`
|
||||
- `/qimen` → `methods/qimen.json`
|
||||
3. **复杂业务说明可补充到** `docs/*.md`
|
||||
4. **接口变更必须同步文档**:
|
||||
- 参数变化
|
||||
- 响应结构变化
|
||||
- 错误码变化
|
||||
- 公共请求头变化
|
||||
- 鉴权方式变化
|
||||
- 每次 API 接口变更(新增 / 修改 / 删除 method、参数、响应、错误码、header、鉴权等)后,除了更新 `methods/*.json`,**还必须追加一条变更记录到对应的 `methods/changes/<docName>.json` 数组**
|
||||
- **system.json 已库表化维护(2026-09-23)**:维护源为 `wms_api_method_doc`(方法表)+ `wms_method_doc_meta`(文档元信息),`methods/system.json` 是导出产物(docs 页面仍读该文件)
|
||||
- 新建:`node script/method-doc-create.cjs --method <m> --module <模块> --group <分组名> --description "说明" [--login 1] [--auth 0] [--params @p.json] [--response @r.json] [--errors @e.json] [--headers @h.json] [--bump]`
|
||||
- 更新:`node script/method-doc-update.cjs --method <m> [--description ...] [--login 1|0] [--auth 1|0] [--status 1|0] [--params @p.json] ... [--bump]`
|
||||
- 查询:`node script/method-doc-get.cjs --method <m>`;列表:`node script/method-doc-list.cjs [--module <模块>] [--search <关键词>]`
|
||||
- 下线/删除:`node script/method-doc-delete.cjs --method <m> --yes [--hard] [--bump]`(默认软删 status=0,导出时排除;--hard 真删)
|
||||
- JSON 字段(headers/params/response/errors)支持内联 JSON 或 `@文件路径`
|
||||
- **改完库必须回写文件**:`node script/method-doc-export.cjs`(原子写入 methods/system.json);首次使用先 `node script/method-doc-import.cjs` 全量导入
|
||||
- 生产库操作加 `--env production`(慎用)
|
||||
- 变更记录仍走原流程(不可绕过):先按 `docs/api-doc-update-workflow.md` 生成固定 spec,`npm run doc:api:update -- --spec=<path>` 写入前先执行 `--dry-run` 验证;禁止直接手写 `methods/changes/*.json`
|
||||
- 修补 JSON 文件时必须强校验 JSON 格式正确性,确保不会引入无法解析或破坏结构的问题
|
||||
- `wms_api_method_doc` 是维护源,`methods/system.json` 是导出产物,`methods/changes/*.json` 仅记录差异历史
|
||||
- 变更记录建议字段至少包含:`version`、`date`、`summary`、`methods`、`notes`
|
||||
5. 如 system 入参有变化,可执行:
|
||||
|
||||
```powershell
|
||||
node .\script\tmp-struct-system-params.cjs
|
||||
```
|
||||
|
||||
然后人工补齐:
|
||||
- `description`
|
||||
- `response`
|
||||
- `errors`
|
||||
- 特殊枚举值与业务约束
|
||||
|
||||
6. **禁止把敏感配置写入文档**:
|
||||
- 禁止读取或复述 `config/deploy.config.local.cjs`
|
||||
- 禁止把 SSH、密钥、账号密码写入文档
|
||||
|
||||
## 推荐工作流
|
||||
|
||||
1. 先定位代码真实实现与调用链
|
||||
2. 在temp/apiDoc/目录下先备份对应的时间的json文档方便后续对比和回档,自动归档人工回档都在这个目录下进行
|
||||
2. 如 system 入参结构变化,可先执行 `node .\script\tmp-struct-system-params.cjs`
|
||||
3. 按 `docs/api-doc-update-workflow.md` 生成固定 spec JSON
|
||||
4. 先执行 `npm run doc:api:update -- --spec=<path> --dry-run`
|
||||
5. 确认后执行 `npm run doc:api:update -- --spec=<path>` 写入 `methods/*.json` 与 `methods/changes/*.json`
|
||||
6. 再补充 `docs/*.md` / `README.md`,并校验 method 名称、参数、响应与代码一致
|
||||
|
||||
## 常用验证方式
|
||||
|
||||
### 校验 `methods/system.json` 格式
|
||||
|
||||
```powershell
|
||||
node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')"
|
||||
```
|
||||
|
||||
### 通过固定 spec dry-run 校验 API 文档写入
|
||||
|
||||
```powershell
|
||||
npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
|
||||
```
|
||||
|
||||
### 核对 method 是否已登记
|
||||
|
||||
```powershell
|
||||
Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetailProduct"
|
||||
```
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-doc-agent 帮我:
|
||||
1) 根据代码现状整理接口或业务文档
|
||||
2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update
|
||||
3) 同步 docs/*.md / README,并校验文档与实现一致
|
||||
```
|
||||
|
||||
## 脚本使用示例
|
||||
|
||||
推荐的最小操作序列(PowerShell 示例):
|
||||
|
||||
```powershell
|
||||
# 1) 从示例复制 spec 到 temp 并编辑
|
||||
Copy-Item docs/api-doc-update-spec.example.json temp/api-doc-update.json
|
||||
|
||||
# 2) 先 dry-run(仅校验并打印差异)
|
||||
npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
|
||||
|
||||
# 3) 检查 dry-run 输出并修正 spec;确认无误后正式写入
|
||||
npm run doc:api:update -- --spec=temp/api-doc-update.json
|
||||
|
||||
# 4) 仅修补主文档且不追加 changes(慎用)
|
||||
npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only
|
||||
```
|
||||
|
||||
脚本职责(由 `script/update-api-doc.cjs` 实现):
|
||||
|
||||
- 校验 spec JSON 结构与必填字段
|
||||
- 在 dry-run 模式下不写入,仅打印将要变更的差异并返回校验结果
|
||||
- 校验目标 `methods/*.json` 与 `methods/changes/*.json` 的可解析性
|
||||
- 按 `group` + `method` 执行 upsert,避免覆盖或破坏其它分组/方法
|
||||
- 保留目标文件原有缩进与换行风格,尽量减少无关 diff
|
||||
- 校验 change 版本不重复并拒绝重复写入
|
||||
|
||||
## 输出要求
|
||||
|
||||
- 所有回复建议以 `[Doc]` 开头
|
||||
- 先给结论,再给修改文件、关键字段、验证结果
|
||||
- 若同步了 `methods/*.json`,明确说明 method 名称与变更点
|
||||
- 若接口有变更,需说明是否已同步写入 `methods/changes/*.json`
|
||||
- 若执行了文档脚本,需明确说明 spec 路径、dry-run 结果与正式写入结果
|
||||
|
||||
## 结论
|
||||
|
||||
文档相关能力文档已统一收口到本 Agent;工具箱只保留“文档相关必须使用 `wms-doc-agent`”的规则入口。
|
||||
86
.github/agents/测试.agent.md
vendored
Normal file
86
.github/agents/测试.agent.md
vendored
Normal file
@ -0,0 +1,86 @@
|
||||
---
|
||||
name: wms-test-agent
|
||||
description: "Use when the user asks about 测试、单元测试、集成测试、回归测试、TDD、接口验证、mock、覆盖率、验证修复、复现 bug。专用于 WMS 测试设计、执行与验证。"
|
||||
argument-hint: "描述要验证或补齐的测试目标,例如:补某接口单元测试、复现 bug 并加回归、按 TDD 验证修复、审查 mock/断言是否合理。"
|
||||
tools: ['read', 'search', 'edit', 'execute', 'todo']
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS 测试代理(`wms-test-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 主要目录:`test/`、`app/`、`methods/`
|
||||
- 适用于单元测试、集成测试、回归测试、接口验证与修复验证
|
||||
- 禁止执行npm run deploy
|
||||
## 测试环境固定参数
|
||||
|
||||
| 参数 | 值 | 说明 |
|
||||
|------|----|------|
|
||||
| 测试仓库 ID | `100000` | 用户角色切换后 `ctx.user.store_id` 对应的 warehouse_id |
|
||||
| 测试货主 ID | `1000000` | 绑定收货单时使用的 store_id |
|
||||
|
||||
> 所有集成测试在创建收货单、绑定货主等步骤中,必须使用上述固定值,**禁止**从动态接口随机选取仓库或货主。
|
||||
|
||||
## 测试账号为拥有所有的权限,测试过程中出现403无权限的情况,需要委托 `wms-db-agent` 直接在权限表添加对应method的记录,无需修改任何角色授权范围。
|
||||
|
||||
|
||||
## 何时必须使用本 Agent
|
||||
|
||||
出现以下任一诉求时,必须使用 `wms-test-agent`:
|
||||
|
||||
- 写测试 / 补回归 / 提升覆盖率
|
||||
- 跑接口验证 / 验证修复 / 复现 bug
|
||||
- 按 TDD 流程推进问题修复
|
||||
- 审查 mock / 断言是否只测到了假行为
|
||||
- 核对失败用例、测试边界与回归范围
|
||||
|
||||
## 测试规则
|
||||
|
||||
1. **TDD 优先**:先写失败用例,再做最小修复
|
||||
2. **测试真实行为**:优先验证真实输入/输出与实际调用链,不要只测 mock,测试所有的文件是否符合eslint规范,不规范的代码必须驳回修改后再验证,并告知驳回原因
|
||||
3. **禁止 test-only 生产代码**:不要为测试给生产代码加仅供测试使用的方法或分支
|
||||
4. **mock 要克制且完整**:仅在理解依赖副作用后于最低必要层 mock,且结构必须与真实数据一致
|
||||
5. **改动后必须验证**:跑相关测试并明确报告 passing 数量、失败数与验证范围
|
||||
6. **接口验证以真实链路为准**:必要时结合 `methods/*.json`、controller/service 实现与返回结构共同校验
|
||||
7. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中,如有 ESLint 错误或警告,必须驳回到开发修改后再验证
|
||||
8. **测试仓库与货主范围固定** 必须检查测试中创建的资源(如收货单、绑定货主等)是否使用了固定的测试仓库 ID `100000` 和测试货主 ID `1000000`,禁止使用随机生成的仓库或货主 ID 以及其他非固定值,否则必须驳回修改后再验证,并告知驳回原因。
|
||||
## 常用命令示例
|
||||
|
||||
### PowerShell 执行
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -Command "npm run test:local"
|
||||
powershell -ExecutionPolicy Bypass -Command "npx egg-bin test --grep 'system'"
|
||||
```
|
||||
|
||||
### npm / egg-bin
|
||||
|
||||
```powershell
|
||||
npm run test:local
|
||||
npm run test:local -- --grep "keyword"
|
||||
npx egg-bin test
|
||||
npx egg-bin test test/app/controller/**/*.test.js
|
||||
```
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-test-agent 帮我:
|
||||
1) 先复现问题并补一个失败用例
|
||||
2) 按 TDD 验证修复是否生效
|
||||
3) 输出测试结果、passing 数量与剩余风险
|
||||
```
|
||||
|
||||
## 输出要求
|
||||
|
||||
- 所有回复建议以 `[Test]` 开头
|
||||
- 先给结论,再给测试范围、关键用例、验证结果
|
||||
- 明确说明 passing 数量、失败数与是否已覆盖回归场景
|
||||
- 直接输出测试报告到 `test_reports/` 目录下的文件中,测试分为可以通过和不可以通过部分,分别为 `test_reports/pass/` 和 `test_reports/fail/`,测试完成后并返回文件路径,报告路径必须包含日期时间和中文描述,例如:`test_reports/pass/20260410-货主超卖链路测试报告.md`
|
||||
- 如有失败用例,必须明确失败原因、失败用例名称与代码位置
|
||||
- 测试报告格式必须清晰、结构化,包含测试目标、测试范围、测试产物、测试结果摘要、结论与建议,测试类型(单元/集成/回归/接口验证)必须明确标注
|
||||
## 结论
|
||||
|
||||
测试相关能力文档已统一收口到本 Agent;工具箱只保留“测试相关必须使用 `wms-test-agent`”的规则入口。
|
||||
101
.github/agents/缓存.agent.md
vendored
Normal file
101
.github/agents/缓存.agent.md
vendored
Normal file
@ -0,0 +1,101 @@
|
||||
---
|
||||
name: wms-redis-agent
|
||||
description: "Use when the user asks about Redis、缓存、cache key、TTL、session、script/redis-cache.ps1、hgetall/hset、set/get/del、缓存排障、键值核对。专用于 WMS Redis 查询与缓存变更。"
|
||||
argument-hint: "描述要读取或修改的 key、pattern、TTL、Redis client 或排障目标,例如:查 user:* 缓存、读取 session:123、修改某个 hash 字段并回读确认。"
|
||||
tools: ['read', 'search', 'execute', 'todo']
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS Redis 代理(`wms-redis-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 默认缓存脚本:`script/redis-cache.ps1`
|
||||
- 默认 Redis client:`cache`
|
||||
|
||||
## 何时必须使用本 Agent
|
||||
|
||||
出现以下任一诉求时,必须使用 `wms-redis-agent`:
|
||||
|
||||
- 查 Redis key / pattern / TTL / exists
|
||||
- 读取或修改缓存值
|
||||
- 操作 Hash:`hget` / `hset` / `hgetall` / `hdel`
|
||||
- 排查登录态、session、缓存不一致、缓存未刷新
|
||||
- 核对某接口是否命中缓存或缓存值异常
|
||||
|
||||
## 工作规则
|
||||
|
||||
1. **所有 Redis 操作优先使用** `script/redis-cache.ps1`
|
||||
2. **对非测试仓库相关缓存默认只允许读取**:`get` / `mget` / `ttl` / `exists` / `hget` / `hgetall`
|
||||
3. **禁止对非测试仓库执行** `set` / `del` / `hset` / `hdel` / `incr` / `decr` / `expire` **等写操作**
|
||||
4. **若无法确认是否测试仓,默认按非测试仓处理,只提供只读排查建议**
|
||||
5. 如用户已明确说明是测试仓且允许修改,**写操作前必须先读**:`set / del / hset / hdel / incr / decr / expire` 前,先读取当前值并确认影响范围
|
||||
6. **列 key 优先使用扫描模式**,避免直接进行高风险全量操作
|
||||
7. 做缓存排障时,优先链路:
|
||||
- 先定位 key 规则 / 调用代码
|
||||
- 再读取当前缓存值与 TTL
|
||||
- 如需修改,执行后必须回读验证
|
||||
8. 输出要求:
|
||||
- 所有回复必须以 `[Redis]` 开头
|
||||
- 优先给结论、当前值、TTL 和下一步建议
|
||||
9. 写入值时,如未携带TTL,全部拒绝
|
||||
|
||||
## 常用命令模板
|
||||
|
||||
### 1) 列出目标 key
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable
|
||||
```
|
||||
|
||||
### 2) 读取字符串缓存
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system"
|
||||
```
|
||||
|
||||
### 3) 查看 TTL / 是否存在
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action ttl -RedisClient cache -Key "system"
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action exists -RedisClient cache -Key "system"
|
||||
```
|
||||
|
||||
### 4) 读取或修改 Hash
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hgetall -RedisClient cache -Key "session:123" -AsTable
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hset -RedisClient cache -Key "session:123" -Field "status" -Value "active"
|
||||
```
|
||||
|
||||
### 5) 修改后回读确认
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action set -RedisClient cache -Key "system" -Value "{\"ok\":1}" -ExpireSeconds 600
|
||||
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system"
|
||||
```
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-redis-agent 帮我:
|
||||
1) 找到相关 key 或 pattern
|
||||
2) 读取当前值、TTL、exists 状态
|
||||
3) 如需修改,先展示变更前后对比并回读确认
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
- 报错 `Cannot find module 'ioredis'`
|
||||
- 先执行 `npm install`,确认依赖完整
|
||||
- 报错 `Redis client "xxx" not found in config.redis.clients`
|
||||
- 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client
|
||||
- 报错 Redis 连接失败(超时/认证失败)
|
||||
- 检查 Redis host/port/password/db 与网络连通性
|
||||
- PowerShell 执行策略限制
|
||||
- 使用命令中的 `-ExecutionPolicy Bypass`
|
||||
|
||||
## 结论
|
||||
|
||||
Redis 相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“Redis 相关必须使用 `wms-redis-agent`”这一条约束。
|
||||
63
.github/agents/评审.agent.md
vendored
Normal file
63
.github/agents/评审.agent.md
vendored
Normal file
@ -0,0 +1,63 @@
|
||||
---
|
||||
name: wms-review-agent
|
||||
description: "Use when the user asks for 代码评审、审查、review、缺陷、风险、回归、兼容性、可维护性、代码质量检查、变更影响分析。专用于 WMS 只读代码评审与风险识别。"
|
||||
argument-hint: "描述要评审的代码、分支或变更范围,例如:评审某个 PR、审查某个接口改动、检查回归风险、分析兼容性问题。"
|
||||
tools: ['read', 'search']
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS 评审代理(`wms-review-agent`)
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 项目根目录:`D:\wms`
|
||||
- 主要关注目录:`app/`、`config/`、`database/`、`test/`、`methods/`
|
||||
- 适用于代码评审、变更审查、风险分析、回归影响判断与可维护性检查
|
||||
|
||||
## 角色定位
|
||||
|
||||
本代理只做只读评审,不进行任何代码修改、文件写入、格式化、重构或执行类操作。
|
||||
|
||||
## 评审重点
|
||||
|
||||
1. **缺陷**:逻辑错误、边界条件遗漏、异常处理不足、空值与并发问题
|
||||
2. **风险**:回归风险、兼容性风险、权限与数据安全风险、性能退化风险
|
||||
3. **回归点**:接口行为变化、状态流转变化、数据结构变化、默认值变化
|
||||
4. **可维护性**:职责是否清晰、耦合是否过高、命名是否准确、重复逻辑是否明显
|
||||
5. **一致性**:实现与既有分层约定、既有模式、既有测试和文档是否一致
|
||||
|
||||
## 评审规则
|
||||
|
||||
1. **只读评审**:只允许阅读和检索,不做任何修改
|
||||
2. **先找事实**:基于代码、调用链、测试和上下文给出结论,不凭空猜测
|
||||
3. **优先指出问题**:发现问题时要明确说明影响范围、触发条件和严重程度
|
||||
4. **避免泛泛而谈**:每条 findings 都要能对应到具体代码位置或明确行为
|
||||
5. **必要时说明未验证项**:如果无法确认某个点,必须标注为开放问题或残余风险
|
||||
|
||||
## 输出要求
|
||||
|
||||
- 先列出 findings,再列残余风险或开放问题
|
||||
- findings 必须按严重程度排序,优先级高的放前面
|
||||
- 每条 finding 需要包含问题、影响、依据,最好附带代码位置
|
||||
- 如果没有发现问题,要明确说明“未发现明确缺陷”或同义结论
|
||||
- 结尾可给出简短结论,但不要把结论放在 findings 之前
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-review-agent 帮我:
|
||||
1) 评审这个变更的缺陷和回归风险
|
||||
2) 检查兼容性、边界条件和可维护性
|
||||
3) 先输出 findings,再输出残余风险或开放问题
|
||||
```
|
||||
|
||||
## 输出风格
|
||||
|
||||
- 所有回复建议以 `[Review]` 开头
|
||||
- 语气保持直接、准确、可执行
|
||||
- 不输出代码修改建议为最终动作,不执行修复
|
||||
- 如需后续修复,建议交由开发类 agent 处理
|
||||
|
||||
## 结论
|
||||
|
||||
本代理专用于只读代码评审与风险识别;工具箱仅保留 `read` 与 `search`,禁止任何修改或执行类能力。
|
||||
78
.github/agents/调度.agent.md
vendored
Normal file
78
.github/agents/调度.agent.md
vendored
Normal file
@ -0,0 +1,78 @@
|
||||
---
|
||||
name: wms-dispatcher-agent
|
||||
description: "Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。"
|
||||
argument-hint: "描述你的目标或问题,例如:帮我判断这是数据库、测试还是缓存问题并分派、这个线上异常该交给谁处理。"
|
||||
tools: [execute/runNotebookCell, execute/getTerminalOutput, execute/killTerminal, execute/sendToTerminal, execute/createAndRunTask, execute/runInTerminal, read/getNotebookSummary, read/problems, read/readFile, read/viewImage, read/terminalSelection, read/terminalLastCommand, agent/runSubagent, search/codebase, search/fileSearch, search/listDirectory, search/textSearch, search/usages, todo]
|
||||
model: DeepSeek V4 Pro (deepseek)
|
||||
---
|
||||
|
||||
# WMS 调度代理(`wms-dispatcher-agent`)
|
||||
|
||||
## 角色定位
|
||||
|
||||
你是一个 **项目经理(Project Manager)**,负责:
|
||||
|
||||
- 分析用户请求,判断归属领域
|
||||
- 规划子任务的拆分与执行顺序
|
||||
- 将子任务委派给最合适的专属 agent
|
||||
- 等待各子任务返回结果,汇总后给出最终结论
|
||||
- **不深入专属 agent 的内部技术细节**,只关注其输入、输出和完成状态
|
||||
- 本项目无需重启, 也不需要你直接修改代码、数据库或 Redis;所有操作都必须通过专属 agent 执行
|
||||
## 适用范围
|
||||
|
||||
以下场景优先使用本 Agent:
|
||||
|
||||
- 用户**不确定该找哪个专属 agent**
|
||||
- 一个问题同时涉及 **数据库 / Redis / 发布 / 代码修改 / 测试验证 / 文档同步** 多个领域
|
||||
- 需要先做 **分诊、拆任务、确定顺序**,再交给具体执行 agent
|
||||
- 线上问题需要判断究竟属于数据、缓存、部署、测试还是代码逻辑
|
||||
|
||||
## 委派规则
|
||||
|
||||
1. **数据库 / SQL / 库表定位** → `wms-db-agent`
|
||||
2. **Redis / 缓存 / TTL / session / key 排障** → `wms-redis-agent`
|
||||
3. **发布 / 回退 / 预检 / 冒烟 / 版本查询** → `wms-deploy-agent`
|
||||
4. **文档补充 / API 文档 / README / `methods/*.json` / `docs/*.md`** → `wms-doc-agent`
|
||||
5. **测试 / 回归 / 接口验证 / TDD / mock 审查** → `wms-test-agent` 必须在委派时告知测试目标和所有涉及的文件路径
|
||||
6. **纯代码修改 / method 映射 / 权限联动** → `wms-dev-agent`
|
||||
7. **代码 + 文档混合变更** → 必须拆分为两个子任务:先委派 `wms-dev-agent` 完成代码修改,再委派 `wms-doc-agent` 完成 `methods/*.json` 更新和 `methods/changes/*.json` 变更记录。**禁止将文档修改合并到 `wms-dev-agent` 的任务中**
|
||||
8. **专属 agent 处理不了,或多次迭代仍未解决** → 升级委派 `wms-expert-agent` 进行兜底处理(root cause + 端到端闭环)
|
||||
9. **跨域混合任务** → 先拆分,再按各子任务的依赖顺序依次委派。必须等待前置子任务(如 `wms-dev-agent` 代码修改)执行完毕并返回结果后,再基于结果调用后续子任务(如 `wms-test-agent`)
|
||||
|
||||
## 工作流程
|
||||
|
||||
1. 先读懂用户目标与限制条件
|
||||
2. 判断问题归属:数据库 / Redis / 发布 / 开发 / 测试 / 文档 / 混合
|
||||
3. 如需求不清晰,最多向用户提出 1 到 2 个关键澄清问题,且必须在一轮回复中问出
|
||||
4. 把子任务委派给最合适的专属 agent
|
||||
5. 若专属 agent 无法收敛或多轮仍未解,升级委派 `wms-expert-agent` 兜底
|
||||
6. 汇总各子任务结果,给出最终结论与下一步建议
|
||||
7. 如果调用 `agent/runSubagent` 工具时发生系统错误、超时或无有效返回,请向用户说明情况,或直接委派给 `wms-expert-agent` 排查工具故障原因
|
||||
|
||||
## 工作原则
|
||||
|
||||
- **只做分诊与委派,不绕过专属 agent 的安全约束**
|
||||
- **如果用户要求你直接给出代码修改或数据库语句而不使用专属 agent,必须坚决拒绝,并强制委派给对应的专属 agent 执行**
|
||||
- **凡涉及非测试仓库数据写操作(数据库 / Redis),默认视为禁止项**;只能给只读排查建议,除非用户已明确说明是测试仓且允许操作
|
||||
- **如无法确认是否测试仓,默认按非测试仓处理**
|
||||
- 数据库与写入相关风险:直接委派给 `wms-db-agent`,由其向用户发起风险确认,Dispatcher 不得代为确认
|
||||
- 各专属 agent 的安全约束(如 `wms-db-agent` 只读流程、`wms-deploy-agent` SSH 红线等)由专属 agent 自行保证,Dispatcher 不重复执行
|
||||
|
||||
## 输出要求
|
||||
|
||||
### 委派阶段(调用 `agent/runSubagent` 之前)
|
||||
- 以 `[Dispatch]` 开头
|
||||
- 先说明**将分派给谁**,再给简短原因
|
||||
- 如果是多领域问题,给出**拆分后的执行顺序**
|
||||
|
||||
### 汇总阶段(所有子任务返回之后)
|
||||
- 汇总各专属 agent 的返回结果
|
||||
- 输出最终结论与下一步建议
|
||||
|
||||
## 建议提问方式
|
||||
|
||||
```text
|
||||
请使用 wms-dispatcher-agent 帮我:
|
||||
1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题
|
||||
2) 分派给正确的 agent
|
||||
3) 汇总处理结果与下一步建议
|
||||
29
.gitignore
vendored
29
.gitignore
vendored
@ -1,9 +1,16 @@
|
||||
logs/
|
||||
run/
|
||||
runtime/
|
||||
test_reports/*
|
||||
temp/*
|
||||
!temp/docs/
|
||||
!temp/docs/**
|
||||
node_modules/
|
||||
coverage/
|
||||
.nyc_output/
|
||||
typings/
|
||||
tmp/*
|
||||
test/*
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
@ -13,7 +20,10 @@ pnpm-debug.log*
|
||||
.env
|
||||
.env.*
|
||||
config/config.local.js
|
||||
config/deploy.config.local.cjs
|
||||
database/config.json
|
||||
# 数据库备份/迁移前快照(本地与临时产物,只留在磁盘,不入库)
|
||||
database/backups/
|
||||
|
||||
native/addons/*.node
|
||||
|
||||
@ -23,3 +33,22 @@ native/addons/*.node
|
||||
Thumbs.db
|
||||
*.sw*
|
||||
*.un~
|
||||
todo.txt
|
||||
test/.runtime/
|
||||
.deploy-state/
|
||||
versioning/*
|
||||
!versioning/.gitkeep
|
||||
|
||||
app/public/exports/
|
||||
script/debug-*.cjs
|
||||
|
||||
# nginx local wiring (generated server blocks / certs / upstream, not committed)
|
||||
.ssl/
|
||||
nginx_config/
|
||||
nginx-upstream-local.conf
|
||||
|
||||
# frpc binary (installed on demand by script/frp/frp-install.ps1)
|
||||
script/frp/*.exe
|
||||
# 库存差异核对导出(scripts/stock_diff_report.js 生成,文件名带时间戳)
|
||||
库存差异核对_*.xlsx
|
||||
~$库存差异核对_20261028-0751.xlsx
|
||||
|
||||
@ -3,8 +3,8 @@
|
||||
const path = require('path');
|
||||
|
||||
module.exports = {
|
||||
"config": path.join(__dirname, 'database/config.json'),
|
||||
"migrations-path": path.join(__dirname, 'database/migrations'),
|
||||
"seeders-path": path.join(__dirname, 'database/seeders'),
|
||||
"models-path": path.join(__dirname, 'app/model'),
|
||||
config: path.join(__dirname, 'database/config.js'),
|
||||
'migrations-path': path.join(__dirname, 'database/migrations'),
|
||||
'seeders-path': path.join(__dirname, 'database/seeders'),
|
||||
'models-path': path.join(__dirname, 'app/model'),
|
||||
};
|
||||
849
AI_METHOD_ROUTING.md
Normal file
849
AI_METHOD_ROUTING.md
Normal file
File diff suppressed because one or more lines are too long
268
AI_TOOLBOX.md
Normal file
268
AI_TOOLBOX.md
Normal file
@ -0,0 +1,268 @@
|
||||
# AI 工具箱(WMS)
|
||||
|
||||
|
||||
## 🤖 AI阅读优先级
|
||||
1. **必读**:第2节(数据库 agent 入口)、第4节(Redis agent 入口)、第7节(开发 agent 入口)、第8节(文档 agent 入口)、第9节(测试 agent 入口)- 最常用
|
||||
2. **重要**:第3节(提问模板)、第6节(安全约束)、第10节(发布 agent 入口)
|
||||
3. **按需**:第11节(开发细节移交说明)、第16节(消息通知)
|
||||
4. **红线**:10(发布必须走 agent)、6(SQL安全)
|
||||
|
||||
|
||||
## Agent配置文件位置
|
||||
|
||||
GitHub Copilot 读取 `.github/agents/*.agent.md`;Cursor 使用 `.cursor/agents/wms-*-agent.md`(Subagent,YAML 为 Cursor 格式:`model` / `readonly` / `is_background` 等)。两处业务规则应保持一致。
|
||||
|
||||
| Agent名称 | GitHub Copilot | Cursor |
|
||||
|-----------|----------------|--------|
|
||||
| wms-db-agent | `.github/agents/数据库.agent.md` | `.cursor/agents/wms-db-agent.md` |
|
||||
| wms-redis-agent | `.github/agents/缓存.agent.md` | `.cursor/agents/wms-redis-agent.md` |
|
||||
| wms-deploy-agent | `.github/agents/发布.agent.md` | `.cursor/agents/wms-deploy-agent.md` |
|
||||
| wms-dev-agent | `.github/agents/开发.agent.md` | `.cursor/agents/wms-dev-agent.md` |
|
||||
| wms-test-agent | `.github/agents/测试.agent.md` | `.cursor/agents/wms-test-agent.md` |
|
||||
| wms-doc-agent | `.github/agents/文档.agent.md` | `.cursor/agents/wms-doc-agent.md` |
|
||||
| wms-dispatcher-agent | `.github/agents/调度.agent.md` | `.cursor/agents/wms-dispatcher-agent.md` |
|
||||
| wms-expert-agent | `.github/agents/专家.agent.md` | `.cursor/agents/wms-expert-agent.md` |
|
||||
| wms-review-agent | `.github/agents/评审.agent.md` | `.cursor/agents/wms-review-agent.md` |
|
||||
|
||||
|
||||
## 快速响应规则
|
||||
- 用户要求查数据库/查数据/写 SQL → **必须使用 `wms-db-agent`**
|
||||
- 用户要求查缓存/改缓存/Redis 排障 → **必须使用 `wms-redis-agent`**
|
||||
- 用户要求发布/回退/查线上版本/做冒烟 → **必须使用 `wms-deploy-agent`**
|
||||
- 用户要求改代码/修 bug/定位 method → **必须使用 `wms-dev-agent`**
|
||||
- 用户要求写测试/补回归/跑接口验证/TDD/验证修复 → **必须使用 `wms-test-agent`**
|
||||
- 用户要求补文档/同步 `methods/*.json` / 更新 `docs/*.md` / README → **必须使用 `wms-doc-agent`**
|
||||
- 用户不确定该找哪个 agent,或问题横跨多个领域 → **必须使用 `wms-dispatcher-agent`**
|
||||
- **全局安全红线(适用于所有 AI)**:**禁止删改处理非测试仓库的数据,包括数据库和缓存**;对非测试仓库默认只读;无法确认是否测试仓时,默认按非测试仓处理并拒绝写操作
|
||||
- 所有回复结尾加"喵~"
|
||||
|
||||
## 1. 适用范围
|
||||
|
||||
- 项目根目录:D:\\wms
|
||||
- 主要用途:本地调试、数据库取数、问题定位
|
||||
- 默认环境:PowerShell + Node.js
|
||||
|
||||
## 2. 数据库能力移交规则
|
||||
|
||||
数据库相关能力文档已统一移交给 `wms-db-agent`。
|
||||
|
||||
适用场景:
|
||||
- 查数据库 / 查数据 / 查表
|
||||
- 编写或审查 SQL
|
||||
- 排查接口与数据库数据不一致
|
||||
- 核对 `wms` / `ye4s` client 路由
|
||||
- 输出字段含义、异常数据判断、索引建议
|
||||
|
||||
执行要求(强制):
|
||||
- **涉及数据库的任何问题,必须使用 `wms-db-agent`**
|
||||
- 默认 agent 不再在本文件重复维护数据库命令细节
|
||||
- 具体命令、示例、输出格式、安全约束统一见:`.github/agents/数据库.agent.md`
|
||||
|
||||
## 3. AI 协助时建议使用的提问模板
|
||||
|
||||
### 3.1 数据库类请求(强制走 Agent)
|
||||
|
||||
```text
|
||||
请使用 wms-db-agent 帮我:
|
||||
1) 定位相关 controller / service / model
|
||||
2) 生成并执行只读 SQL
|
||||
3) 输出结果、字段解释和结论
|
||||
```
|
||||
|
||||
### 3.2 Redis 类请求(强制走 Agent)
|
||||
|
||||
```text
|
||||
请使用 wms-redis-agent 帮我:
|
||||
1) 找到相关 key 或 pattern
|
||||
2) 读取当前值、TTL、exists 状态
|
||||
3) 如需修改,先展示变更前后对比并回读确认
|
||||
```
|
||||
|
||||
### 3.3 开发类请求(强制走 Dev Agent)
|
||||
|
||||
```text
|
||||
请使用 wms-dev-agent 帮我:
|
||||
1) 定位这个 method / controller / service 的实现链路
|
||||
2) 修复问题并说明最小代码改动方案
|
||||
3) 给出验证结果与后续开发建议
|
||||
```
|
||||
|
||||
### 3.4 测试类请求(强制走 Test Agent)
|
||||
|
||||
```text
|
||||
请使用 wms-test-agent 帮我:
|
||||
1) 先复现问题并补一个失败用例
|
||||
2) 按 TDD 跑回归或接口验证
|
||||
3) 输出 passing 数量、失败数和修复验证结论
|
||||
```
|
||||
|
||||
### 3.5 文档类请求(强制走 Doc Agent)
|
||||
|
||||
```text
|
||||
请使用 wms-doc-agent 帮我:
|
||||
1) 根据代码现状整理接口或业务文档
|
||||
2) 先按 docs/api-doc-update-workflow.md 生成固定 spec,再执行 npm run doc:api:update
|
||||
3) 同步 docs/*.md / README,并校验 methods/*.json 与 methods/changes/*.json 可解析
|
||||
```
|
||||
|
||||
### 3.6 混合任务 / 不确定归属(强制走 Dispatcher)
|
||||
|
||||
```text
|
||||
请使用 wms-dispatcher-agent 帮我:
|
||||
1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题
|
||||
2) 分派给正确的 agent
|
||||
3) 汇总处理结果与下一步建议
|
||||
```
|
||||
|
||||
## 4. Redis 能力移交规则
|
||||
|
||||
Redis 相关能力文档已统一移交给 `wms-redis-agent`。
|
||||
|
||||
适用场景:
|
||||
- 查 Redis key / pattern / TTL / exists
|
||||
- 读取或修改缓存值
|
||||
- 排查 session、登录态、缓存不一致问题
|
||||
- 核对某接口是否命中缓存或缓存值异常
|
||||
|
||||
执行要求(强制):
|
||||
- **涉及 Redis / 缓存的任何问题,必须使用 `wms-redis-agent`**
|
||||
- 默认 agent 不再在本文件重复维护 Redis 命令细节
|
||||
- 具体命令、示例、输出格式、安全约束统一见:`.github/agents/缓存.agent.md`
|
||||
|
||||
## 5. 常见问题
|
||||
|
||||
- 数据库相关报错、SQL 问题、连接路由问题
|
||||
- 统一转给 `wms-db-agent` 处理
|
||||
|
||||
- Redis 相关报错、key 排查、TTL 问题、缓存变更
|
||||
- 统一转给 `wms-redis-agent` 处理
|
||||
|
||||
- 发布相关报错、预检失败、回退、版本查询、冒烟验证
|
||||
- 统一转给 `wms-deploy-agent` 处理
|
||||
|
||||
- 开发相关问题:代码修改、method 路由、权限联动
|
||||
- 统一转给 `wms-dev-agent` 处理
|
||||
|
||||
- 测试相关问题:写单元测试、补回归、接口验证、TDD、验证修复、审查 mock / 断言
|
||||
- 统一转给 `wms-test-agent` 处理
|
||||
|
||||
- 文档相关问题:API 文档、README、`methods/system.json`(已库表化:`wms_api_method_doc` + `script/method-doc-*.cjs` 维护并导出回写)、`docs/*.md`、使用说明
|
||||
- 统一转给 `wms-doc-agent` 处理
|
||||
|
||||
- 不确定该用哪个 agent,或问题横跨数据库 / Redis / 发布 / 代码 / 测试 / 文档
|
||||
- 统一转给 `wms-dispatcher-agent` 处理
|
||||
|
||||
- PowerShell 执行策略限制
|
||||
- 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效)
|
||||
|
||||
## 6. 安全约束
|
||||
|
||||
- **全局安全红线(适用于所有 AI)**:禁止删改处理非测试仓库的数据,包括数据库和缓存;对非测试仓库默认只读;无法确认是否测试仓时,默认按非测试仓处理并拒绝 `UPDATE` / `DELETE` / `INSERT`、`set` / `del` / `hset` / `hdel` / `incr` / `decr` / `expire` 等写操作
|
||||
- 数据库相关操作必须使用 `wms-db-agent`,并按该 agent 内的只读/确认流程执行
|
||||
- Redis 相关操作必须使用 `wms-redis-agent`,并按该 agent 内的先读后改/回读确认流程执行
|
||||
- 发布相关操作必须使用 `wms-deploy-agent`,并坚持仅走 `npm run` 固定入口;禁止读取 `config/deploy.config.local.cjs`
|
||||
- 开发相关操作必须使用 `wms-dev-agent`,并坚持“先定位、后修改、再验证”的流程
|
||||
- 测试相关操作必须使用 `wms-test-agent`,并坚持“先写失败用例、再修复、后跑相关测试并报告 passing 数量”;禁止只测 mock 或给生产代码加 test-only 方法
|
||||
- 文档相关操作必须使用 `wms-doc-agent`,并坚持“先核对代码与测试,再更新文档;禁止写入敏感配置”的流程
|
||||
- 涉及生产数据时,优先在测试环境验证
|
||||
|
||||
|
||||
## 7. 开发能力移交规则
|
||||
|
||||
通用开发能力文档已统一移交给 `wms-dev-agent`。
|
||||
|
||||
适用场景:
|
||||
- 改代码 / 修 bug / 重构 / 性能优化
|
||||
- 定位 `/system` / `/qimen` method 映射关系
|
||||
- 排查 `where` 规则、权限映射、分层职责问题
|
||||
|
||||
执行要求(强制):
|
||||
- **涉及代码开发的任何问题,必须使用 `wms-dev-agent`**
|
||||
- 默认 agent 不再在本文件重复维护开发细节
|
||||
- 如诉求重点是测试设计、补回归、接口验证、TDD 或验证修复,转给 `wms-test-agent`
|
||||
- 如需同步 API 文档、`methods/*.json`、`docs/*.md`,转给 `wms-doc-agent`
|
||||
- 具体目录地图、联动规则统一见:`.github/agents/开发.agent.md`
|
||||
|
||||
## 8. 文档能力移交规则
|
||||
|
||||
文档相关能力文档已统一移交给 `wms-doc-agent`。
|
||||
|
||||
适用场景:
|
||||
- 补 API 文档 / 接口说明 / 错误码 / 示例请求
|
||||
- 同步 `methods/system.json` / `methods/qimen.json`
|
||||
- 更新 `docs/*.md`、`README.md`、`AI_TOOLBOX.md`
|
||||
- 整理 method 映射说明、接入文档、使用手册
|
||||
|
||||
执行要求(强制):
|
||||
- **涉及文档编写或同步的任何问题,必须使用 `wms-doc-agent`**
|
||||
- 文档必须以代码实现、测试结果和现有 JSON 文档为准,不得凭空编写
|
||||
- 默认禁止直接手写 `methods/*.json` 和 `methods/changes/*.json`;必须先按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 组织 spec,再执行 `npm run doc:api:update -- --spec=<path>`
|
||||
- system 参数变化可先执行:`node .\script\tmp-struct-system-params.cjs`
|
||||
- 正式写入前必须先执行:`npm run doc:api:update -- --spec=<path> --dry-run`
|
||||
- 具体工作流统一见:`.github/agents/文档.agent.md`
|
||||
|
||||
## 9. 测试能力移交规则
|
||||
|
||||
测试相关能力文档已统一移交给 `wms-test-agent`。
|
||||
|
||||
适用场景:
|
||||
- 写测试 / 单元测试 / 集成测试 / 补回归
|
||||
- 跑接口验证 / 复现 bug / 验证修复
|
||||
- 按 TDD 流程推进开发修复
|
||||
- 审查 mock / 断言规范与覆盖率范围
|
||||
|
||||
执行要求(强制):
|
||||
- **涉及测试设计、回归验证、接口验证、TDD 的任何问题,必须使用 `wms-test-agent`**
|
||||
- 必须坚持先写失败用例再修复,不允许只测 mock 行为
|
||||
- 不得为生产代码添加 test-only 方法或分支
|
||||
- 改动后必须跑相关测试并报告 passing 数量
|
||||
- 具体命令与测试规范统一见:`.github/agents/测试.agent.md`
|
||||
|
||||
## 10. 发布能力移交规则
|
||||
|
||||
发布相关能力文档已统一移交给 `wms-deploy-agent`。
|
||||
|
||||
适用场景:
|
||||
- 发布生产 / 上线 / deploy
|
||||
- 回退 / rollback / 指定备份回退
|
||||
- 查询线上版本、版本历史
|
||||
- 做预检、inspect、smoke、verify、gateway probe
|
||||
- 排查发布链路、备份、版本记录问题
|
||||
|
||||
执行要求(强制):
|
||||
- **涉及发布 / 回退 / 线上验证的任何问题,必须使用 `wms-deploy-agent`**
|
||||
- 固定入口只允许 `npm run ...`,禁止直接运行底层 `node ./script/deploy-remote.cjs ...` / `rollback-remote.cjs ...`
|
||||
- AI 禁止读取 `config/deploy.config.local.cjs`
|
||||
- 具体命令、回退规则、版本管理、安全红线统一见:`.github/agents/发布.agent.md`
|
||||
|
||||
## 11. 开发细节移交说明
|
||||
|
||||
以下开发细节文档已统一移交给 `wms-dev-agent`:
|
||||
|
||||
- App 能力地图(`app.js`、`app/extend/application.js`)
|
||||
- Web 用户信息与角色切换测试链路
|
||||
- `setting.account` 接口分层约定
|
||||
- `where` 参数统一规范
|
||||
- `system API` 权限映射规则
|
||||
|
||||
执行要求(强制):
|
||||
- **涉及代码开发、接口联动的任何问题,必须使用 `wms-dev-agent`**
|
||||
- 如需测试设计、补回归、接口验证或验证修复,转给 `wms-test-agent`
|
||||
- 若涉及文档更新,转给 `wms-doc-agent`
|
||||
- 具体定位地图、命令与工作流统一见:`.github/agents/开发.agent.md`
|
||||
|
||||
## 16. 通知能力路由(notice / WebHook / 事件注册)
|
||||
|
||||
- 详细能力说明统一沉淀在:
|
||||
- `docs/notification-webhook-capability.md`
|
||||
- `docs/notification-event-api.md`
|
||||
- 工具箱只保留入口与分工,不再重复维护 notice 的字段、payload、重试和示例细节。
|
||||
- 若其他 agent 或开发任务遇到“**新功能需要通知**”,按以下路由处理:
|
||||
1. **代码接入** → 使用 `wms-dev-agent`:在业务 service 中接入 `ctx.service.systems.notice.send(options)`,并完成事件注册与最小回归验证
|
||||
2. **文档同步** → 使用 `wms-doc-agent`:同步通知能力文档、事件文档及必要的接口说明
|
||||
- 当前统一入口:`ctx.service.systems.notice.send(options)`
|
||||
- 当前代码位置:`app/service/systems/notice/index.js`
|
||||
- 配置底线:`wms_store.subject_config.max_notice_webhook_count`
|
||||
- 默认值:`5`
|
||||
- 合法范围:`0 ~ 5`
|
||||
- 创建/更新主体与 WebHook 分发时都必须遵守该上限
|
||||
@ -1,143 +0,0 @@
|
||||
{
|
||||
"openapi": "3.0.1",
|
||||
"info": {
|
||||
"title": "打印相关接口",
|
||||
"description": "print service methods",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"paths": {
|
||||
"/system": {
|
||||
"post": {
|
||||
"summary": "打印台相关接口",
|
||||
"operationId": "printStationOperations",
|
||||
"description": "根据method参数执行不同的打印台操作",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "method",
|
||||
"in": "query",
|
||||
"description": "调用方法名,如print.getList、print.getItem、print.updateItem、print.del、print.getComputer、print.getComputerPrinter、print.savePrinters",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"print.getList",
|
||||
"print.getItem",
|
||||
"print.updateItem",
|
||||
"print.del",
|
||||
"print.getComputer",
|
||||
"print.getComputerPrinter",
|
||||
"print.savePrinters"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "v",
|
||||
"in": "query",
|
||||
"description": "版本号",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"example": "2.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "timestamp",
|
||||
"in": "query",
|
||||
"description": "时间戳",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"example": "1646908800000"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": false,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"page": { "type": "integer", "example": 1 },
|
||||
"pageSize": { "type": "integer", "example": 20 },
|
||||
"where": {
|
||||
"type": "object",
|
||||
"example": { "name": "A台" }
|
||||
},
|
||||
"id": { "type": "integer", "example": 1 },
|
||||
"name": { "type": "string", "example": "A台" },
|
||||
"computer_id": { "type": "integer", "example": 2 },
|
||||
"custom_barcode": { "type": "string", "example": "123456" },
|
||||
"ids": {
|
||||
"type": "array",
|
||||
"items": { "type": "integer" },
|
||||
"example": [1,2]
|
||||
},
|
||||
"default": { "type": "string", "example": "打印机名称" },
|
||||
"express": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"express_id": { "type": "integer" },
|
||||
"name": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"example": [{ "express_id": 1, "name": "顺丰" }]
|
||||
},
|
||||
"print_station_id": { "type": "integer", "example": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功响应",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": { "type": "integer", "description": "状态码" },
|
||||
"message": { "type": "string", "description": "返回信息" },
|
||||
"data": { "type": "object", "description": "返回数据" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "错误请求",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": { "type": "integer" },
|
||||
"message": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "未授权"
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{ "bearer": [] }
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"securitySchemes": {
|
||||
"bearer": {
|
||||
"type": "http",
|
||||
"scheme": "bearer",
|
||||
"bearerFormat": "JWT"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
107
Apifox/test.json
107
Apifox/test.json
@ -1,107 +0,0 @@
|
||||
{
|
||||
"openapi": "3.0.1",
|
||||
"info": {
|
||||
"title": "默认模块",
|
||||
"description": "",
|
||||
"version": "1.0.0"
|
||||
},
|
||||
"tags": [],
|
||||
"paths": {
|
||||
"/system": {
|
||||
"post": {
|
||||
"summary": "未命名接口",
|
||||
"deprecated": false,
|
||||
"description": "",
|
||||
"tags": [],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "method",
|
||||
"in": "query",
|
||||
"description": "",
|
||||
"required": false,
|
||||
"example": "user.login",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "v",
|
||||
"in": "query",
|
||||
"description": "",
|
||||
"required": false,
|
||||
"example": "2.0",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "timestamp",
|
||||
"in": "query",
|
||||
"description": "",
|
||||
"required": false,
|
||||
"example": "{{$date.now}}",
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"userName": {
|
||||
"type": "string"
|
||||
},
|
||||
"passWord": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"userName",
|
||||
"passWord"
|
||||
]
|
||||
},
|
||||
"example": {
|
||||
"userName": "夫立伟",
|
||||
"passWord": "Ut cillum veniam"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"headers": {}
|
||||
}
|
||||
},
|
||||
"security": [
|
||||
{
|
||||
"bearer": []
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
"schemas": {},
|
||||
"responses": {},
|
||||
"securitySchemes": {
|
||||
"bearer": {
|
||||
"type": "http",
|
||||
"scheme": "bearer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"servers": [],
|
||||
"security": []
|
||||
}
|
||||
447
INBOX_V2_HTTP_TEST_REPORT.md
Normal file
447
INBOX_V2_HTTP_TEST_REPORT.md
Normal file
@ -0,0 +1,447 @@
|
||||
# 站内信 v2 可配置回信引擎 —— HTTP 覆盖测试报告
|
||||
|
||||
> 生成时间:2026-09-17T14:44:55.082Z | 执行方式:真实 HTTP 链路(POST /warehouse?method=inbox.push)
|
||||
|
||||
## 1. 测试环境
|
||||
|
||||
| 项 | 值 |
|
||||
|---|---|
|
||||
| 服务 | http://127.0.0.1:6060(本地 egg 服务,运行中) |
|
||||
| 回调接收服务 | http://127.0.0.1:9001/ack(本地 ack 服务,返回 {code:200}) |
|
||||
| 数据库 | 127.0.0.1:3307/wms(本地库) |
|
||||
| API 应用 | wms_api_app id=3,app_key=APP2025011514315678,warehouse_id=100000 |
|
||||
| 原 callback_url | `http://localhost:6061/push` → 测试期间改为本地 ack 服务(**未自动恢复**) |
|
||||
| 新 v2 测试群 | `httpv2: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. 链路
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[测试脚本] -->|POST /warehouse inbox.push 验签| B[warehouseMethods/inbox.push]
|
||||
B --> C[receiver.receive 幂等写库 + 自动登记群]
|
||||
C -->|source_type=api setImmediate| D[processor.handleApiMessage]
|
||||
D --> E{群校验 ai_enabled / group_type / 历史消息}
|
||||
E -->|template_reply_enabled=1| F[inbox.v2.rules 可配置引擎]
|
||||
F --> G[关键词→白名单→取号→callFunction→回复表]
|
||||
G --> H[writeOutboundReply]
|
||||
H -->|POST notify.reply| I[本地 ack 服务 9001]
|
||||
I --> J[push_status=2]
|
||||
```
|
||||
|
||||
## 3. 用例结果总览
|
||||
|
||||
- 总计:**11** 用例,通过:**11**,失败:**0**
|
||||
|
||||
| # | 用例 | 内容 | 结果 |
|
||||
|---|---|---|---|
|
||||
| TC01 | 破损建单(新 v2 群) | `破损 SF1234567890123` | ✅ PASS |
|
||||
| TC02 | 改地址 | `改地址 SF1234567890123` | ✅ PASS |
|
||||
| TC03 | 换快递(express 取号) | `改快递 SF1234567890123 圆通` | ✅ PASS |
|
||||
| TC04 | 拦截 | `拦截 SF1234567890123` | ✅ PASS |
|
||||
| TC05 | 揽收(上门取件) | `上门取件 SF1234567890123` | ✅ PASS |
|
||||
| TC06 | 取号失败引导语 | `破损` | ✅ PASS |
|
||||
| TC07 | v2 未命中静默(模块接管) | `今天天气怎么样` | ✅ PASS |
|
||||
| TC08 | 历史消息静默跳过 | `破损 SF1234567890123` | ✅ PASS |
|
||||
| TC09 | 幂等(同 requestId 两次推送) | `破损 SF9999999999999` | ✅ PASS |
|
||||
| TC10 | express 群白名单放行但函数越权拦截(静默) | `破损 SF1234567890123` | ✅ PASS |
|
||||
| TC11 | 模块优先(ai_enabled=0 但 template_reply_enabled=1) | `破损 SF1234567890123` | ✅ PASS |
|
||||
|
||||
## 4. 用例明细
|
||||
|
||||
### TC01 破损建单(新 v2 群) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-01-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 入站消息入库 | ✅ | 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=2118,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"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-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
### TC02 改地址 ✅ PASS
|
||||
|
||||
- 消息:`改地址 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-02-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| v2 命中 changeAddr | ✅ | |
|
||||
| 出站回执存在 | ✅ | push_status=2 |
|
||||
| 函数已执行(工单或错误文案) | ✅ | \| 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 |
|
||||
|
||||
- 入站消息 id=2120,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"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-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123,1234567890123」,请核实单号后重试 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
### TC03 换快递(express 取号) ✅ PASS
|
||||
|
||||
- 消息:`改快递 SF1234567890123 圆通`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-03-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| v2 命中 changeExpress | ✅ | |
|
||||
| 取号含 express=圆通 | ✅ | thoughts 含 express 字段 |
|
||||
| 出站回执存在 | ✅ | 未找到订单:SF1234567890123、1234567890123 |
|
||||
|
||||
- 入站消息 id=2122,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"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-1789656298793` | 未找到订单:SF1234567890123、1234567890123 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
### TC04 拦截 ✅ PASS
|
||||
|
||||
- 消息:`拦截 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-04-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| v2 命中 interceptWaybill | ✅ | |
|
||||
| 出站回执存在 | ✅ | 请提供运单号 |
|
||||
|
||||
- 入站消息 id=2124,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {},
|
||||
"reason": "v2 关键词命中: 拦截",
|
||||
"function": "interceptWaybill",
|
||||
"functionResult": {
|
||||
"error": "请提供运单号",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-04-1789656298793` | 请提供运单号 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
### TC05 揽收(上门取件) ✅ PASS
|
||||
|
||||
- 消息:`上门取件 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-05-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| v2 命中 requestPickup | ✅ | |
|
||||
| 出站回执存在 | ✅ | 请提供运单号 |
|
||||
|
||||
- 入站消息 id=2126,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {},
|
||||
"reason": "v2 关键词命中: 上门取件",
|
||||
"function": "requestPickup",
|
||||
"functionResult": {
|
||||
"error": "请提供运单号",
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-05-1789656298793` | 请提供运单号 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
### TC06 取号失败引导语 ✅ PASS
|
||||
|
||||
- 消息:`破损`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-06-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 出站回执为取号引导语 | ✅ | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) |
|
||||
| 未建工单(取号失败不调用函数) | ✅ | |
|
||||
|
||||
- 入站消息 id=2128,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"round": 0,
|
||||
"action": "rule",
|
||||
"params": {},
|
||||
"reason": "v2 关键词命中: 破损,取号失败-引导提示",
|
||||
"function": "handleStoreFeedback",
|
||||
"functionResult": null
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- 出站回执:
|
||||
|
||||
| ext_id | content | push_status |
|
||||
|---|---|---|
|
||||
| `sys:ack:api:APP2025011514315678:httpv2-06-1789656298793` | 请提供运单号(发送:指令+运单号,多个单号用逗号或空格分隔) | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
### TC07 v2 未命中静默(模块接管) ✅ PASS
|
||||
|
||||
- 消息:`今天天气怎么样`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-07-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 无出站回执(静默) | ✅ | |
|
||||
| 无 ai_thoughts 轨迹 | ✅ | 空 |
|
||||
| 无新工单 | ✅ | 0 条 |
|
||||
|
||||
- 入站消息 id=2130,ai_thoughts:
|
||||
|
||||
```json
|
||||
null
|
||||
```
|
||||
|
||||
### TC08 历史消息静默跳过 ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-08-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 入站仍入库 | ✅ | id=2131 |
|
||||
| 无出站回执(静默跳过) | ✅ | |
|
||||
| 无新工单 | ✅ | 0 条 |
|
||||
|
||||
- 入站消息 id=2131,ai_thoughts:
|
||||
|
||||
```json
|
||||
null
|
||||
```
|
||||
|
||||
### TC09 幂等(同 requestId 两次推送) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF9999999999999`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-09-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 两次推送均返回成功(flag=success) | ✅ | 第一次 flag=success,第二次 flag=success |
|
||||
| 入站仅 1 条 | ✅ | 1 -> 1 |
|
||||
| 出站仅 1 条(不重复处理) | ✅ | 出站条数 1 -> 1 |
|
||||
|
||||
- 入站消息 id=2132,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"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-1789656298793` | 未找到当前货主在仓库中的运单「SF9999999999999」,请核实单号后重试 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
### TC10 express 群白名单放行但函数越权拦截(静默) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-10-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 入站消息入库 | ✅ | id=2134 |
|
||||
| 无出站回执(静默) | ✅ | |
|
||||
| 白名单行存在(express/after_sales 允许 damage 子类型) | ✅ | 行数=1 |
|
||||
| 函数越权拦截(handleStoreFeedback 仅 store 群可用 → 无轨迹) | ✅ | 无轨迹 |
|
||||
|
||||
- 入站消息 id=2134,ai_thoughts:
|
||||
|
||||
```json
|
||||
null
|
||||
```
|
||||
|
||||
### TC11 模块优先(ai_enabled=0 但 template_reply_enabled=1) ✅ PASS
|
||||
|
||||
- 消息:`破损 SF1234567890123`
|
||||
- ext_id:`api:APP2025011514315678:httpv2-11-1789656298793`
|
||||
|
||||
| 校验项 | 结果 | 详情 |
|
||||
|---|---|---|
|
||||
| 不依赖 ai_enabled,仍走 v2(轨迹含 v2 关键词命中) | ✅ | [{"round":0,"action":"rule","params":{"keyword":"SF1234567890123","issue_type":"damaged"},"reason":"v2 关键词命中: 破损","function":"handleStoreFeedback","functionResult":{"error":"未找到当前货主在仓库中的运单「SF123456789 |
|
||||
| 出站回执存在 | ✅ | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 |
|
||||
|
||||
- 入站消息 id=2135,ai_thoughts:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"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-1789656298793` | 未找到当前货主在仓库中的运单「SF1234567890123」,请核实单号后重试 | 2 |
|
||||
|
||||
- 本地 ack 服务收到 notify.reply:type=ai
|
||||
|
||||
- wms_warehouse_log notify.reply 日志:http_status=200
|
||||
|
||||
## 5. 说明与后续
|
||||
|
||||
1. 测试产生的入站/出站消息、工单等数据**已保留**(未自动清理),可直接在库中核对。
|
||||
2. `wms_api_app` id=3 的 callback_url 测试期间被改为本地 ack 服务,如需恢复:
|
||||
|
||||
```sql
|
||||
UPDATE wms_api_app SET callback_url = 'http://localhost:6061/push' WHERE id = 3;
|
||||
```
|
||||
|
||||
3. 测试脚本与明细数据位于 `temp/inbox_v2_http_test/`(`run_http_test.js`、`ack_server.js`、`report.json`)。
|
||||
|
||||
333
INBOX_V2_TEST_GUIDE.md
Normal file
333
INBOX_V2_TEST_GUIDE.md
Normal file
@ -0,0 +1,333 @@
|
||||
# 站内信 v2 可配置回信引擎 —— 端到端测试流程指南
|
||||
|
||||
> 适用对象:开发/测试人员。覆盖消息 HTTP 推送进入、群类型创建、回传数据接收、
|
||||
> 校验准则、涉及表的状态变化与特殊流程边界。
|
||||
> 所有示例基于本地环境(服务 `127.0.0.1:6060`,MySQL `127.0.0.1:3307/wms`),
|
||||
> 生产环境仅做只读核对,禁止写操作。
|
||||
|
||||
## 测试范围(重要)
|
||||
|
||||
- **只测 v2 链路**:`template_reply_enabled=1` 的群走 `inbox.v2.rules` 可配置引擎;
|
||||
- **v1 链路不需要测试**:processor 分叉为 `else` 分支原样保留,v1 规则表
|
||||
(`inbox/rules.js` 静态规则)与 AI 兜底逻辑零改动,无需回归;
|
||||
- 自动化验证已覆盖:`test/inbox/v2_rules_engine.test.js`(引擎 9 用例)、
|
||||
`test/inbox/v2_processor_fork.test.js`(分叉 3 用例)、
|
||||
`test/inbox/v2_function_sync.test.js`(函数同步 4 用例)。
|
||||
|
||||
---
|
||||
|
||||
## 0. 总体链路
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[外部适配器] -->|POST /warehouse inbox.push 验签| B[warehouseMethods/inbox.push]
|
||||
B --> C[receiver.receive 幂等写库<br/>wms_inbox_message inbound]
|
||||
C -->|自动登记群| D[wms_inbox_group]
|
||||
C -->|source_type=api 异步| E[processor.handleApiMessage]
|
||||
E --> F{群校验: group_type / ai_enabled}
|
||||
F -->|未通过| G[静默跳过]
|
||||
F -->|通过| H{规则引擎}
|
||||
H -->|v1| I[rules.handle]
|
||||
H -->|template_reply_enabled=1| J[inbox.v2.rules 引擎<br/>模块接管]|
|
||||
I --> K[callFunction 代码越权校验]
|
||||
K --> L[writeOutboundReply 出站回执]
|
||||
L -->|POST notify.reply| M[回调 URL<br/>wms_api_app.callback_url]
|
||||
L --> N[wms_inbox_message outbound + wms_warehouse_log]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. 消息 HTTP 推送进入(inbox.push)
|
||||
|
||||
### 1.1 入口
|
||||
|
||||
```
|
||||
POST http://127.0.0.1:6060/warehouse?method=inbox.push&v=1.0×tamp={秒级时间戳}&app_key={appKey}&sign={sign}
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
- `warehouse_id` 由验签后的 `wms_api_app` 上下文注入,**禁止外部传入**;
|
||||
- `ext_id` 由服务端组合:`api:{appKey}:{requestId}`,用于幂等去重。
|
||||
|
||||
### 1.2 签名算法(app/lib/api_sign.js)
|
||||
|
||||
```
|
||||
bodySign = md5(stableStringify(body)) // 对象键按字母序排序后序列化
|
||||
canonical = query 参数按 key 字母序拼接 "k=v&k2=v2"(排除 sign/signature)
|
||||
sign = md5(canonical + self_app_secret + bodySign)
|
||||
```
|
||||
|
||||
- `self_app_secret` 来自 `wms_api_app.self_app_secret`(按 `app_key` 查询);
|
||||
- `app_key` 对应仓库的 API 应用需存在且已启用。
|
||||
|
||||
### 1.3 请求体字段
|
||||
|
||||
| 字段 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `requestId` | ✅ | 来源请求唯一 ID,与 appKey 组成 `ext_id` |
|
||||
| `content` | - | 消息正文(触发规则引擎的输入) |
|
||||
| `groupId` | - | 外部群 ID,用于关联群与货主路由 |
|
||||
| `groupName` | - | 群名称(首次推送会自动登记群) |
|
||||
| `userId` / `userName` | - | 外部用户 ID / 名称 |
|
||||
| `parentId` | - | 关联消息 ID(回信时形成对话链) |
|
||||
| `targetType` | - | `im` / `api` / `webhook`,默认 `im` |
|
||||
| `extData` | - | 透传 JSON,WMS 不解析,回信原样带回 |
|
||||
| `sendTime` | - | 消息原始发送时间(毫秒/秒/ISO),用于历史消息过滤 |
|
||||
| `flags` | - | `{skipAi:true}` 显式跳过 AI;`{send_time:ms}` 等价 sendTime |
|
||||
|
||||
### 1.4 响应与幂等
|
||||
|
||||
- 成功:`{code:0, message:'ok', data:{ok:true, id, ext_id}}`;
|
||||
- 相同 `ext_id` 重复推送:直接返回已存在记录,**不重复入库、不重复触发处理**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 创建特定群类型
|
||||
|
||||
### 2.1 自动登记(首次推送即建群)
|
||||
|
||||
首次推送含 `groupName` 的消息时,`receiver.receive` 自动在 `wms_inbox_group`
|
||||
创建群记录(按 `group_id + warehouse_id` 唯一):
|
||||
- `ai_enabled=0`、`group_type/sub_type=NULL`、`store_id` 取自绑定的货主;
|
||||
- 群名变化只更新名称,不重复建群。
|
||||
|
||||
### 2.2 配置群类型(管理接口)
|
||||
|
||||
```
|
||||
POST http://127.0.0.1:6060/system?method=inbox.group.update&v=1.0×tamp={ts}
|
||||
Authorization: Bearer {登录 token}
|
||||
Content-Type: application/json
|
||||
|
||||
{ "id": {群记录ID}, "groupType": "store", "subType": "after_sales",
|
||||
"storeId": 1000000, "aiEnabled": 1 }
|
||||
```
|
||||
|
||||
- `groupType`:`store`(货主)/ `warehouse`(仓库)/ `express`(快递);
|
||||
- `subType`(群子类型):
|
||||
- store:`after_sales` / `finance` / `receiving`
|
||||
- warehouse:`receiving` / `production` / `stockout` / `finance` / `all` / `customer_service` / `exception`
|
||||
- express:`pickup` / `after_sales`
|
||||
- `aiEnabled=1` 才会进入规则引擎(第 5 步开关);
|
||||
- `inbox.group.reset`:清空群类型配置并重置 AI 开关。
|
||||
|
||||
### 2.3 v2 回信开关(开启即接管链路)
|
||||
|
||||
v2 引擎开关 `template_reply_enabled`(管理接口未上线前用 SQL 设置):
|
||||
|
||||
```sql
|
||||
UPDATE wms_inbox_group SET template_reply_enabled = 1
|
||||
WHERE group_id = '{测试群ID}' AND warehouse_id = {仓库ID};
|
||||
```
|
||||
|
||||
- `template_reply_enabled=1` 的群在第 6 步自动走 `inbox.v2.rules.handle`(已接入);
|
||||
- **模块优先语义**:`template_reply_enabled=1` 即为模块总开关,开启时不依赖 `ai_enabled`
|
||||
(两个开关同开时也走 v2 不走 v1/AI;`ai_enabled` 只约束未开启模板开关的群);
|
||||
- **模块接管模式**:v2 开启群的未命中消息直接静默,不走 v1 规则、不走 AI 兜底;
|
||||
- 群信息每条消息实时查库(`_loadGroupInfo` 不缓存),SQL 改动对下一条消息立即生效;
|
||||
- v2 配置数据(关键词/白名单/函数/取号/回复)有 300s 缓存,改动后需
|
||||
`ctx.service.inbox.v2.config.invalidate(warehouseId)` 或等 TTL 过期。
|
||||
|
||||
---
|
||||
|
||||
## 3. 接收回传数据
|
||||
|
||||
### 3.1 出站回执方向(WMS → 外部)
|
||||
|
||||
规则处理完成后,`processor.writeOutboundReply` 向 `wms_api_app.callback_url`
|
||||
POST 回执(`notify.reply`):
|
||||
|
||||
```
|
||||
POST {callback_url}?app_key={k}&method=notify.reply×tamp={秒}&sign={md5(appSecret + timestamp + bodyJson)}
|
||||
```
|
||||
|
||||
回执 body 关键字段:
|
||||
- `data.type`:`ai`(规则/AI 自动回复)、`system`、`bind`、`balance`、`error`;
|
||||
- `data.content`:回复内容;`data.ext_data`:入站 `extData` 原样带回;
|
||||
- `data.ext_id`:出站消息记录 ID;`data.group_id` / `user_id` / `user_name`:目标群与用户。
|
||||
|
||||
### 3.2 测试接收方法
|
||||
|
||||
方式 A(推荐):临时把本地库 `wms_api_app.callback_url` 指向本地 HTTP 接收服务,
|
||||
观察收到的 `notify.reply` 报文并返回 `{code:200}`:
|
||||
|
||||
```sql
|
||||
UPDATE wms_api_app SET callback_url = 'http://127.0.0.1:9001/ack'
|
||||
WHERE app_key = '{测试app_key}';
|
||||
```
|
||||
|
||||
方式 B(不落回执服务):直接核对库表:
|
||||
- `wms_inbox_message`:`direction='outbound'`、`ext_id='sys:ack:{入站ext_id}'`;
|
||||
- `wms_warehouse_log`:`method='notify.reply'` 的出站通知日志(含 http_status/body/result)。
|
||||
|
||||
### 3.3 推送状态核对
|
||||
|
||||
| push_status | 含义 |
|
||||
|---|---|
|
||||
| 0/1 | 未推送 / 待推送 |
|
||||
| 2 | 回调返回 HTTP 200 且 `code=200` → 推送成功 |
|
||||
| 3 | 回调非 200 / 无回调地址 / 异常 → 推送失败(可 `inbox.message.retry` 重推) |
|
||||
|
||||
---
|
||||
|
||||
## 4. 校验准则
|
||||
|
||||
| # | 校验项 | 准则 |
|
||||
|---|---|---|
|
||||
| 1 | 幂等 | 相同 `ext_id` 只入库一次、只处理一次 |
|
||||
| 2 | 群类型 | `group_type` 为空 → 跳过处理(未绑定任务类型) |
|
||||
| 3 | AI 开关 | `ai_enabled != 1` → 跳过(快递群默认 0,需手动开) |
|
||||
| 4 | 历史消息 | `send_time` 距今 > 10 分钟(`config.inbox.historyMessageMaxAgeMs` 可调)→ 跳过,不回复不建工单 |
|
||||
| 5 | 屏蔽 | 屏蔽用户/群 → 跳过处理(`blockUser` 函数 / `wms_inbox_block`) |
|
||||
| 6 | 关键词命中 | 长词优先;命中后先过防误判守卫(如"拦截" vs "查物流") |
|
||||
| 7 | 函数越权 | `callFunction` 按群活跃分组校验,越权返回错误(DB 配置只做可见性,代码是最终权威) |
|
||||
| 8 | 取号失败 | 子类型关联了取号规则但未提取到值 → 回复引导语(`no_number_hint` → target 专属 → 默认),**不调用函数** |
|
||||
| 9 | 回复决策 | 回复完全由回复配置控制:`is_reply=1` 且模板渲染非空 → 回复;`is_reply=0` → 静默(函数仍执行);无配置/模板渲染为空 → **默认不回复**(函数已执行,仅不出回执) |
|
||||
| 10 | 快递群 | express 群仅执行函数,**不回信** |
|
||||
| 11 | 出站回执 | 回执 `ext_id='sys:ack:{入站ext_id}'` 唯一,重复处理不重复出站 |
|
||||
| 12 | 缓存 | v2 配置缓存 `inbox:v2:cfg:{warehouseId}` TTL 300s;配置变更后必须 `invalidate`,否则 5 分钟内不生效 |
|
||||
|
||||
---
|
||||
|
||||
## 5. 涉及表的状态变化
|
||||
|
||||
### 5.1 消息链路表
|
||||
|
||||
| 表 | 变化 |
|
||||
|---|---|
|
||||
| `wms_inbox_message` | 入站:`direction='inbound'`、`push_status=0`;规则命中后写 `ai_thoughts`(轨迹 JSON)。出站:`direction='outbound'`、`ext_id='sys:ack:{ext_id}'`、`parent_id=入站ID`;推送后 `push_status=2/3`、`push_response`、`pushed_at` |
|
||||
| `wms_inbox_group` | 首次推送自动登记(`ai_enabled=0`);`group.update` 写 `group_type/sub_type/store_id/ai_enabled`;群名变化只更新名称 |
|
||||
| `wms_warehouse_log` | 每次出站 `notify.reply` 写一条(`method/url/http_status/body/result/use_time`) |
|
||||
|
||||
### 5.2 业务函数表(v1 与 v2 共用函数)
|
||||
|
||||
| 表 | 变化(以函数为准) |
|
||||
|---|---|
|
||||
| `wms_after_sale` | `interceptWaybill`(type=order, sub_type=intercept, status=pending)、`changeAddr`(change_address/rejected/urge)、`handleStoreFeedback`(mis_shipment/damage/extra_item/missing_item)、`weishoudao`(verify_delivery)、`requestPickup`(pickup)等创建售后工单 |
|
||||
| `wms_order_express` | 拦截成功后写 `intercept_status='requested'` 与 `intercept_time`(值域见 `intercept-status-values` 约定) |
|
||||
| `wms_order_delivery_{warehouseId}` | `createPostnum` 分配运单号后写 `logistics_*`/`post_status`;`changeExpress` 修改快递分配 |
|
||||
|
||||
### 5.3 v2 配置表(全部只读,引擎启动时一次性同步函数表)
|
||||
|
||||
| 表 | 变化 |
|
||||
|---|---|
|
||||
| `wms_after_sale_function` | 启动时 `functionSync.sync()` 幂等 upsert(只增改不删、不覆盖 `is_enabled/sort_order`) |
|
||||
| `wms_after_sale_type` / `wms_after_sale_sub_type` | 系统级 + 仓库级(`warehouse_id NULL` 全局可见) |
|
||||
| `wms_after_sale_keyword` | 关键词 → 子类型映射(长词优先、`sort_order` 同长时生效) |
|
||||
| `wms_after_sale_sub_type_group` | 子类型 × 群类型 × 群子类型白名单(`uk(sub_type_id, group_type, sub_group)`) |
|
||||
| `wms_after_sale_sub_type_function` | 子类型 → 处理函数(`function_id` + `sort_order`) |
|
||||
| `wms_after_sale_sub_type_rule` + `wms_inbox_number_rule` | 子类型 → 取号规则(`target/regexp/sort_order`) |
|
||||
| `wms_after_sale_reply` | 仓库级(`warehouse_id` 非空)覆盖系统级;`is_reply=0` 静默、`no_number_hint` 引导语、`create_work_order=0` 函数照常执行但内部跳过工单登记 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 特殊流程边界
|
||||
|
||||
### 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 分支原逻辑零改动);
|
||||
- **模块接管**:v2 开启群的未命中消息直接静默 return,不回落到 v1 规则与 AI 兜底。
|
||||
|
||||
### 6.2 v2 引擎边界(已接入 processor)
|
||||
|
||||
- **关键词命中**:长词优先;同长多个子类型均按序尝试;
|
||||
- **白名单过滤**:`(group_type, sub_group)` 双维度;群 `sub_type` 为空时**只按主类型放行**
|
||||
(随后由 `callFunction` groups 校验兜底收紧);
|
||||
- **取号正则安全三件套**:保存时校验 + 长度 ≤ 500 + 每次 `new RegExp`(非法正则跳过并告警);
|
||||
- **入参组装**:`waybill_no/order_no/source_order_codes/receiving_no/entry_order_no/stockout_no`
|
||||
合并去重 join 逗号 → `keyword`;`express_name→express`;
|
||||
子类型转译 `issue_type`(damage→damaged、change_address→addr、rejected→return、urge→urge 等);
|
||||
- **多函数子类型**:按 `sort_order` 依次执行,任一失败立即返回失败文案;
|
||||
- **回复优先级**:回复表(仓库级 > 系统级);模板渲染为空或无配置时**默认不回复**(函数照常执行);
|
||||
`{back_text}` 占位符由 help 函数提供,业务函数无该内容时渲染为空 → 不回复;
|
||||
- **缓存失效**:管理接口增删改配置后必须调用 `ctx.service.inbox.v2.config.invalidate(warehouseId)`;
|
||||
启动时**不清** v2 缓存(防雪崩)。
|
||||
|
||||
### 6.3 消息边界
|
||||
|
||||
- **历史/补推消息**:`sendTime` 超阈值 → 静默跳过(不回复、不建工单);
|
||||
- **屏蔽**:屏蔽用户(`wms_inbox_block`)/ 屏蔽群(`is_blocked=1`)→ 跳过处理;
|
||||
- **express 群**:函数照常执行(如 `handleExpressFeedback`),但**不回信**;
|
||||
- **幂等回执**:`sys:ack:{ext_id}` 保证同一入站消息只产生一条出站回执;
|
||||
- **多条回复**:引擎返回数组时逐条出站,`ext_id` 追加 `:r0/:r1` 避免唯一键冲突;
|
||||
- **渠道校正**:回执 `ext_data.source` 按群 ID 格式校正(`@chatroom→wx`、纯数字→qiwe),防止投递到错误渠道。
|
||||
|
||||
### 6.4 数据层已知状态(2026-09-17 已修复)
|
||||
|
||||
1. ✅ `change_carrier`(换快递)已补 `express_name` 取号规则关联(迁移 `20260917130000`),
|
||||
"改快递 {单号} 圆通" 可完整组装 `keyword + express`;
|
||||
2. ✅ 关键词表已补 `intercept`(拦截/退回/召回/追回/取消快递)与 `pickup`(揽收/上门取件/取件/退货取件)共 9 条;
|
||||
3. ⚠️ `wrong_sku`/`quality_issue` 无群白名单关联行(预期内,引擎白名单过滤后跳过)。
|
||||
|
||||
---
|
||||
|
||||
## 7. v2 链路测试步骤(本地)
|
||||
|
||||
> v1 链路不需要测试(分叉 else 分支原样保留)。以下步骤专测 v2。
|
||||
|
||||
### 7.1 前置:准备好一个 v2 开启的测试群
|
||||
|
||||
```sql
|
||||
-- 1) 确保群存在(可由首次推送自动登记,或手动插入)
|
||||
-- 2) 配置群类型 + 开关(管理接口未上线前用 SQL)
|
||||
UPDATE wms_inbox_group
|
||||
SET group_type='store', sub_type='after_sales',
|
||||
store_id={货主ID}, ai_enabled=1, template_reply_enabled=1
|
||||
WHERE group_id='{测试群ID}' AND warehouse_id={仓库ID};
|
||||
```
|
||||
|
||||
v2 链路只需三个条件(模板开关优先,不依赖 AI 开关):`group_type` 非空 →
|
||||
`template_reply_enabled=1` → 消息内容命中 v2 关键词;`ai_enabled` 开或关都不影响 v2。
|
||||
|
||||
### 7.2 推送消息并核对(HTTP 入口)
|
||||
|
||||
```powershell
|
||||
# 1) 推送入站消息:POST /warehouse?method=inbox.push(签名见 1.2)
|
||||
# body: {"requestId":"v2-001","content":"破损 SF1234567890123",
|
||||
# "groupId":"{测试群ID}","groupName":"{群名}",
|
||||
# "userId":"u1","userName":"测试用户"}
|
||||
# 2) 核对入站:
|
||||
# SELECT id, direction, ai_thoughts FROM wms_inbox_message
|
||||
# WHERE ext_id='api:{appKey}:v2-001';
|
||||
# → direction='inbound',ai_thoughts 含 v2 轨迹(action=rule、function=handleStoreFeedback)
|
||||
# 3) 核对出站回执:
|
||||
# SELECT id, ext_id, direction, content, push_status FROM wms_inbox_message
|
||||
# WHERE ext_id='sys:ack:api:{appKey}:v2-001';
|
||||
# → direction='outbound'、push_status=2(回调可用时)/3(未配置回调)
|
||||
# 4) 核对工单:
|
||||
# SELECT after_sale_no, type, sub_type, status FROM wms_after_sale
|
||||
# WHERE warehouse_id={仓库ID} ORDER BY id DESC LIMIT 5;
|
||||
# → sub_type='damage'、status='pending'
|
||||
# 5) 核对出站日志:
|
||||
# SELECT method, http_status, result FROM wms_warehouse_log
|
||||
# WHERE warehouse_id={仓库ID} AND method='notify.reply' ORDER BY id DESC LIMIT 5;
|
||||
```
|
||||
|
||||
### 7.3 推荐用例集(全部走 v2 群)
|
||||
|
||||
| 用例 | 消息 | 预期 |
|
||||
|---|---|---|
|
||||
| 破损建单 | `破损 SF1234567890123` | `handleStoreFeedback(issue_type=damaged)` + damage 工单 + 回执 |
|
||||
| 改地址 | `改地址 SF1234567890123` | `changeAddr(issue_type=addr)` + change_address 工单 |
|
||||
| 换快递 | `改快递 SF1234567890123 圆通` | `changeExpress(keyword=..., express=圆通)` |
|
||||
| 拦截 | `拦截 SF1234567890123` | `interceptWaybill` + intercept 工单(`wms_order_express.intercept_status='requested'`) |
|
||||
| 揽收 | `上门取件 SF1234567890123` | `requestPickup` + pickup 工单 |
|
||||
| 取号失败 | `破损` | 回复引导语,**不建工单** |
|
||||
| v2 未命中 | `今天天气怎么样` | 模块接管静默:无函数调用、无回执记录 |
|
||||
| 模块优先 | 同破损内容 + `ai_enabled=0`(`template_reply_enabled=1` 不变) | 仍走 v2 并回执(不依赖 AI 开关) |
|
||||
| 历史消息 | 同破损内容 + `sendTime` 为 30 分钟前 | 静默跳过:无回执、无工单 |
|
||||
|
||||
> 所有用例的群必须 `template_reply_enabled=1`;**不测** `template_reply_enabled=0` 的 v1 场景。
|
||||
|
||||
### 7.4 边界补充
|
||||
|
||||
- 快递群(express)命中 v2:函数照常执行,但**不回信**(复用现有回执逻辑);
|
||||
- 相同 `requestId` 重复推送:幂等,只处理一次;
|
||||
- 回复表 `is_reply=0`:函数执行但静默(可临时插行验证,见 `wms_after_sale_reply`)。
|
||||
|
||||
> 补充:egg 测试环境运行 DB 相关测试必须
|
||||
> `$env:DISPATCH_FACTORY_TEST_MYSQL='1'; $env:EGG_SERVER_ENV='local'; npx egg-bin test {文件}`
|
||||
> (默认 unittest 环境禁用 sequelize 且 `config.default.js` 指向生产库,禁止裸跑)。
|
||||
258
README.md
258
README.md
@ -1,31 +1,259 @@
|
||||
# qimen
|
||||
# 奇门WMS(qimen-wms)
|
||||
|
||||
奇门wms
|
||||
基于 Egg.js 的仓储管理系统(WMS),支持支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。
|
||||
|
||||
## QuickStart
|
||||
## 文档导航
|
||||
|
||||
<!-- add docs here for user -->
|
||||
- 项目协作工具箱:`AI_TOOLBOX.md`
|
||||
- Method 路由映射说明:`AI_METHOD_ROUTING.md`
|
||||
- system 接口文档源:`methods/system.json`
|
||||
- qimen 接口文档源:`methods/qimen.json`
|
||||
- 配置驱动报表配置说明:`docs/report-config-guide.md`
|
||||
- 日报:`day.log`
|
||||
|
||||
see [egg docs][egg] for more detail.
|
||||
## 项目目录结构
|
||||
|
||||
### Development
|
||||
```text
|
||||
├── app/ # 业务主目录(controller, service, model, router 等)
|
||||
│ ├── controller/ # 控制器(API、文档、模板、认证等)
|
||||
│ ├── service/ # 业务服务(system/qimen/print 等)
|
||||
│ ├── model/ # Sequelize 模型
|
||||
│ ├── dict/ # 业务字典
|
||||
│ ├── view/ # 前端模板
|
||||
│ └── router.js # 路由定义
|
||||
├── config/ # 配置(poloapi、redis、数据库等)
|
||||
├── database/ # 迁移与数据库配置
|
||||
├── methods/ # 接口文档数据源(JSON)
|
||||
├── script/ # 调试与文档生成脚本
|
||||
├── logs/ # 日志
|
||||
├── run/ # 运行时/元数据
|
||||
├── test/ # 单元测试
|
||||
├── app.js # 应用入口
|
||||
├── package.json # 依赖与脚本
|
||||
└── README.md # 项目说明
|
||||
```
|
||||
|
||||
## 文档结构
|
||||
|
||||
- `README.md`:项目入口文档,提供整体说明与规范入口。
|
||||
- `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。
|
||||
- `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。
|
||||
- `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。
|
||||
- `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。
|
||||
- `docs/report-config-guide.md`:配置驱动通用报表(wms_report_definition 三段 JSON 配置、内置查询器口径)与货主定时投递说明。
|
||||
- `day.log`:每日工作留痕。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
npm i
|
||||
npm install
|
||||
npm run dev
|
||||
open http://localhost:7001/
|
||||
```
|
||||
|
||||
### Deploy
|
||||
默认访问地址:`http://localhost:6060/`
|
||||
|
||||
## 运行命令
|
||||
|
||||
- `npm run dev`:本地开发
|
||||
- `npm start`:启动生产服务
|
||||
- `npm stop`:停止生产服务
|
||||
- `npm run lint`:代码风格检查
|
||||
- `npm test`:单元测试
|
||||
|
||||
## 主要依赖
|
||||
|
||||
- egg.js 3.x
|
||||
- egg-sequelize、egg-mysql、egg-redis
|
||||
- egg-jwt、egg-cors、egg-view-ejs
|
||||
- fast-xml-parser、cos-js-sdk-v5、qiniu-js、soap
|
||||
|
||||
## 接口入口
|
||||
|
||||
- `GET /`:健康检查
|
||||
- `POST /qimen`:奇门接口
|
||||
- `POST /system`:system 统一入口
|
||||
- `POST /api/v1`:旧版 API
|
||||
- `POST /api/v2`:新版 API
|
||||
- `GET /template/xml/:id`:打印模板
|
||||
- `GET|POST /auth/printSetting/:code`:打印台设置
|
||||
|
||||
## API 文档与调试
|
||||
|
||||
- `GET /api/docs`:默认文档页
|
||||
- `GET /api/docs/:docName`:按文档名查看(如 `system`、`qimen`)
|
||||
- `GET /api/docs/:docName/raw`:查看原始 JSON
|
||||
|
||||
文档页能力:
|
||||
|
||||
- 分组折叠与 method 搜索
|
||||
- 全局 Authorization 设置
|
||||
- 全局业务 Header(如 `platform`、`project`)设置
|
||||
- 方法级在线 POST 调试
|
||||
|
||||
## 接口文档联动维护(强制)
|
||||
|
||||
当出现以下任一变更时,必须同步更新 `methods` 下对应文档:
|
||||
|
||||
1. 新增接口 method
|
||||
2. 修改接口参数(新增/删除/重命名/必填变化)
|
||||
3. 修改公共 Header(如 `platform`、`project`、`Authorization`)
|
||||
4. 修改响应结构或错误码
|
||||
|
||||
建议流程:
|
||||
|
||||
1. 先完成代码改动(controller/service/model)
|
||||
2. 按 [docs/api-doc-update-workflow.md](docs/api-doc-update-workflow.md) 复制固定 spec 到 `temp/`,默认通过 `npm run doc:api:update -- --spec=...` 写入 `methods/*.json`
|
||||
3. system 参数改动后可先执行:
|
||||
|
||||
```powershell
|
||||
node .\script\tmp-struct-system-params.cjs
|
||||
```
|
||||
|
||||
4. 先执行:
|
||||
|
||||
```powershell
|
||||
npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
|
||||
```
|
||||
|
||||
5. 确认无误后执行正式写入,再补充自动提取无法覆盖的信息(description/response/errors/枚举约束)
|
||||
|
||||
## 配置说明
|
||||
|
||||
- 主要配置文件在 `config/`(如 `config.default.js`、`config.local.js`、`poloapi.js`)
|
||||
- 数据库、Redis、平台配置在对应配置文件中维护
|
||||
- 敏感信息不要提交到仓库
|
||||
|
||||
## 发布与运维(deploy / 证书同步 / 看门狗)
|
||||
|
||||
### 部署根布局(生产 `deployRoot` 默认 `/www/wwwroot/qimen`)
|
||||
|
||||
```text
|
||||
<deployRoot>/
|
||||
├── current.md # 当前活跃版本(v1 | v2)
|
||||
├── nginx-upstream.conf # 发布时改写:proxy_pass 指向活跃版本端口(v1:6061 / v2:6062)
|
||||
├── front.conf # 站点内容片段(root / 伪静态),运维维护、脚本绝不覆盖
|
||||
├── .ssl/ # 证书目录(cron 写入 {store_id}_{domain}.pem|.key,私钥 0600)
|
||||
├── nginx_config/ # nginx server 块目录(cron 写入 {domain}-<ver>.conf,如 web.wms.gztbyc.com-1.conf)
|
||||
├── script/
|
||||
│ ├── warehouse-cert-sync.sh # 证书同步薄包装(cron 每分钟入口)
|
||||
│ ├── warehouse-cert-sync.cjs # 证书同步主脚本(读库→写证书/conf→nginx -t+reload→回写状态)
|
||||
│ ├── warehouse-cert-sync.config.prod.json # 生产运行时配置(服务器自管:仅首次放置,永不覆盖)
|
||||
│ └── qimen-watchdog.sh # 接口服务看门狗(/etc/cron.d 每 5 分钟)
|
||||
├── database/config.js # 上述脚本自用的 DB 配置(install 时上传)
|
||||
├── .deploy/ # 发布状态 / 暂存 / 备份
|
||||
└── v1/ v2/ # 版本实例目录(发布与回退只清理这里)
|
||||
```
|
||||
|
||||
### 目录约定(**硬约定**:只随 `deployRoot` 变,不随版本切换变)
|
||||
|
||||
| 用途 | 路径 | 配置来源 |
|
||||
|------|------|----------|
|
||||
| 证书 | `<deployRoot>/.ssl` | `script/warehouse-cert-sync.config.prod.json` → `"certDir": "./.ssl"`(开发 `D:/wms/.ssl`) |
|
||||
| nginx server 块 | `<deployRoot>/nginx_config` | 同上 → `"confDir": "./nginx_config"`(开发 `D:/wms/nginx_config`) |
|
||||
| 站点内容片段 | `upstreamInclude` 指向的片段文件(生产 `<deployRoot>/front.conf`) | 同上 → `"upstreamInclude"`(**绝对路径**,**运维维护**) |
|
||||
|
||||
- 相对路径按 **cwd=部署根** 解析(薄包装先 `cd <deployRoot>`),目录不存在时脚本自动递归创建。
|
||||
- 这两个目录都在**部署根一级**(非版本目录):发布/回退只清理 `v1|v2`,不会触碰它们。
|
||||
- **server 块命名含 `-<ver>`**:文件名为 `<domainSafe><suffix>-<ver>.conf`(suffix 仅当域名清洗后与原名不一致时出现),版本键 `ver` 在运行时配置里(`"ver": "1"`),可用 CLI `--ver` / 环境变量 `CERT_SYNC_VER` 临时覆盖;nginx 主配置 `include <deployRoot>/nginx_config/*.conf;` 与新命名兼容,无需改 nginx。
|
||||
- **每轮声明式对账 + 自愈**:cron 每分钟把库内「期望集合」(domain 非空且已验证)逐行与磁盘核对,证书 / 私钥 / server 块缺失、被改坏或**命名过期**(旧的无后缀命名、旧 `-<ver>`、手工改名)都会自动重建 / 清理后 reload;内容一致时零写入、零 reload。不再只依赖后台“重新上传证书”触发同步。
|
||||
- **失败态(`sync_status=2`)同样收敛,不是「终态豁免」**:失败行也参与文件层对账——盘上证书 / 私钥 / server 块缺失或与库不一致就按库内容重建,本轮 `nginx -t`/reload 通过后自动回写 `sync_status=1`(日志 `[RECOVER]` / `[RECOVERED]`)。所以「手工删掉 `.ssl`、`nginx_config`」「早期遗留的失败行」都能自动恢复,**无需人工重传证书**。唯一需要人工的情形:库内 `cert_pem`/`cert_key` 为空或非法(无内容可写,日志 `[BLOCKED]`,需在后台上传证书)。
|
||||
- **nginx 全局失败不写行失败**:`nginx -t` / reload 失败属环境问题(主配置、片段 include、目录),此时待同步行保持 `sync_status=0`、已同步行保持 `1`、失败行保持 `2`,只落 `last_sync_error` 并下一轮自动重试,避免「运维修好配置后行却卡死在 2、必须人工重传证书」。
|
||||
- **下线 = 配置差集(不需要两阶段切换的额外机制)**:期望集合 = 库内「已配置 + 已验证 + 证书就绪」的行,且**每个仓库只取一条**(同一 `store_id` 多行时按 id 最小者生效,其余行 WARN 后忽略)。`nginx_config/`、`.ssl/` 中属于本系统命名规则、但域名已不在期望集合内的文件会被删除并 reload(日志 `DELETE … 原因=orphan`)。所以**换域名不需要人工下线**:旧域名在提升后已不是该行的 `domain`,下一轮即被清掉;`retired_domain` / `retired_at` 仅作应用侧审计留痕,脚本不读取、不写回。
|
||||
- **证书没配置就不写配置**:`cert_pem` / `cert_key` 为空的行**不生成** server 块,也不作为文件保留依据(其遗留 conf / 证书会被差集回收——conf 引用不存在的证书会让 `nginx -t` 全局失败),行状态回写 `sync_status=0` 待同步;证书非空但非法(或域名形态非法)才记行级失败(`sync_status=2`)。
|
||||
- **ver 轮转步骤**:改服务器 `warehouse-cert-sync.config.prod.json` 的 `"ver"`(或临时 `--ver`)→ 下一轮 cron 自动生成新命名 `<domain>-<新ver>.conf`、删除旧命名并 reload;无需清空库、无需重传证书(证书文件名不含 ver,不受影响)。
|
||||
- **站点内容单一片段**:生成的 server 块 = 证书骨架 + `include <upstreamInclude>;`;站点内容(root / 伪静态 或 反代)统一由 `upstreamInclude` 指向的片段文件提供(生产 `/www/wwwroot/qimen/front.conf`),**由运维维护、脚本绝不覆盖**;前端个性化在运行时由配置接口按域名完成,nginx 侧无需按域名区分站点内容。
|
||||
- ⚠️ **`upstreamInclude` 必须写绝对路径,且片段文件必须先存在**:nginx 解析 `include` 相对路径的基准是 **nginx prefix**(宝塔为 `/www/server/nginx/conf`),**不是脚本 cwd(部署根)**;写相对路径会让生成的 server 块 include 到不存在的文件 → `nginx -t` 失败 → 整轮变更回滚(连本轮写入的证书一起被当孤儿回收)。脚本启动即校验,不满足直接 `exit 1`(致命退出、不写盘、不改库)。
|
||||
- **改名/搬迁必须同步三处**:① nginx 主配置的 `include <deployRoot>/nginx_config/*.conf;`;② 服务器上的 `warehouse-cert-sync.config.prod.json`;③ 库表 `wms_warehouse_front_config.cert_path/key_path`(触发一次重同步即可刷新)。
|
||||
- 安全:`.ssl/` 与 `nginx_config/` 已在 `.gitignore` 忽略,且列入发布默认排除(`deploy-lib.cjs` 的 `DEFAULT_EXCLUDE_PATHS`),私钥不会进仓库或发布包。
|
||||
|
||||
### 定时任务
|
||||
|
||||
| 任务 | 载体 | 频率 | 入口与日志 |
|
||||
|------|------|------|-----------|
|
||||
| 证书/站点配置同步 | root crontab(**宝塔「计划任务」里看不到**,它是直接写入 crontab 的裸命令) | 每分钟(`flock` 锁 `/var/lock/warehouse-cert-sync.lock`) | `<deployRoot>/script/warehouse-cert-sync.sh` → `/var/log/warehouse-cert-sync.log` |
|
||||
| 接口服务看门狗 | `/etc/cron.d/qimen-watchdog`(**刻意不放 root crontab**:宝塔面板会整体重写 root crontab) | 每 5 分钟 | `<deployRoot>/script/qimen-watchdog.sh` → `/www/wwwlogs/wms/qimen-watchdog.log` |
|
||||
|
||||
### 运维命令
|
||||
|
||||
```bash
|
||||
npm start
|
||||
npm stop
|
||||
npm run deploy:precheck / deploy:authcheck / deploy:inspect / deploy:smoke / deploy:verify
|
||||
npm run deploy:version / deploy:version:history / deploy:cleanup-backups
|
||||
npm run deploy # 发布(= deploy:prod);npm run rollback # 回退
|
||||
npm run deploy:cert-sync:install / npm run deploy:cert-sync:uninstall
|
||||
npm run deploy:watchdog:install / npm run deploy:watchdog:uninstall
|
||||
```
|
||||
|
||||
### npm scripts
|
||||
- **部署配置**:`config/deploy.config.local.cjs`(**本地文件、已被 `.gitignore` 忽略**;模板 `config/deploy.config.example.cjs`)。键:`host / port / username / privateKeyPath / deployRoot / sharedDirs / preserveDirs / keepBackups / preDeployCommands / postDeployCommands / healthCheckUrl / deployIncludePaths / deployExcludePaths / sshOptions`;缺省值在 `script/deploy-lib.cjs`。查看归一化后的生效配置:
|
||||
```bash
|
||||
node -e "console.log(JSON.stringify(require('./script/deploy-lib.cjs').loadDeployConfig('production'),null,2))"
|
||||
```
|
||||
- **证书同步运行时配置**:`script/warehouse-cert-sync.config.prod.json`(生产)/ `.dev.json`(开发)。生产那份是**服务器自管**(`deploy:cert-sync:install` 仅首次放置,之后永不覆盖)——改生产运行参数请在**服务器上**直接改它,改本地仓库无效。
|
||||
- **安装位置**:`deploy:cert-sync:install` 与 `deploy:watchdog:install` 都装到 `<deployRoot>/script/`;覆盖前会留 `.prev-<时间戳>` 备份,历史根目录副本会被一次性挪成 `<名>.legacy-<时间戳>`。
|
||||
- **卸载**(`deploy:cert-sync:uninstall`):先备份再删除——备份到服务器 `/tmp/wms-cert-sync-uninstall-<时间戳>/`(`cp -a` 保留权限/时间),删除包装脚本、主脚本、双环境配置、`database/config.js`、历史位置与 `.prev-*`/`.legacy-*` 备份、crontab 中 `warehouse-cert-sync` 行;支持 `--dry-run` 只打印计划。**不删**证书与生成的 server 块(nginx 仍在 include,删了会立断 443,由运维自行决定)、不删 `/var/log/warehouse-cert-sync.log`(默认保留作排查线索)、不碰任何 watchdog 相关文件/任务。
|
||||
- **卸载(watchdog)**(`deploy:watchdog:uninstall [--dry-run]`):备份到 `/tmp/qimen-watchdog-uninstall-<时间戳>/` 后**注销调度**——删除 `/etc/cron.d/qimen-watchdog`,并清理 root crontab 中残留的 `qimen-watchdog` 行(历史手工安装可能留过,双跑会并发 kill/start 同一实例);再删除服务器副本 `<deployRoot>/script/qimen-watchdog.sh`(含 `.prev-*` / `.legacy-*` 与历史根目录副本)。**不删** `/www/wwwlogs/wms/qimen-watchdog.log`(留作排查线索)、锁文件与接口服务进程;`deploy:watchdog:install` 会先只读打印一份目标机环境快照。
|
||||
- **运行期手动排查**:仍可直接执行服务器上的 `<deployRoot>/script/warehouse-cert-sync.sh --dry-run`(主脚本 CLI 不变:`--cleanup-only --dry-run` / `--cleanup-only` / `--env production`)。
|
||||
|
||||
- Use `npm run lint` to check code style.
|
||||
- Use `npm test` to run unit test.
|
||||
## 功能模块
|
||||
|
||||
[egg]: https://eggjs.org
|
||||
- 多快递平台对接(快手/PolyAPI 等)
|
||||
- 订单管理与履约
|
||||
- 打印与打印台管理
|
||||
- 仓库/门店管理
|
||||
- 权限与角色管理
|
||||
- Excel 表格生成、导入与解析
|
||||
|
||||
## Excel 服务能力
|
||||
|
||||
系统已提供服务类:`app/service/systems/excel.js`,可通过 `ctx.service.systems.excel` 调用。
|
||||
|
||||
支持能力:
|
||||
|
||||
- 生成单 sheet / 多 sheet Excel
|
||||
- 按 `columns + rows` 输出表格
|
||||
- 输出 `Buffer`、写入本地文件、直接作为下载响应返回
|
||||
- 解析 `.xlsx` / `.xls` 文件内容为 JSON
|
||||
- 自动处理空表头、重复表头
|
||||
|
||||
常用方法:
|
||||
|
||||
- `generateBuffer(options)`:生成 Excel 二进制内容
|
||||
- `writeFile(filePath, options)`:写入本地文件
|
||||
- `sendFile({ filename, sheets })`:HTTP 下载输出
|
||||
- `parseBuffer(buffer, options)`:解析上传后的文件流
|
||||
- `parseFile(filePath, options)`:解析本地 Excel 文件
|
||||
|
||||
示例:
|
||||
|
||||
```js
|
||||
const buffer = await ctx.service.systems.excel.generateBuffer({
|
||||
sheets: [
|
||||
{
|
||||
name: '入库单',
|
||||
columns: [
|
||||
{ header: '单号', key: 'order_no', width: 20 },
|
||||
{ header: '货主', key: 'owner_name', width: 18 },
|
||||
],
|
||||
rows: [
|
||||
{ order_no: 'RK20260404001', owner_name: '测试货主' },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = await ctx.service.systems.excel.parseFile('D:/tmp/demo.xlsx');
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
- 启动端口默认 6060,可在配置中调整
|
||||
- 数据库/Redis 连接失败优先检查 `config/config.local.js`
|
||||
- 接口路由映射可查阅 `AI_METHOD_ROUTING.md`
|
||||
|
||||
## 日报维护
|
||||
|
||||
- 日报统一记录在 `day.log`
|
||||
- 每次更新日报内容时,需同步更新 `day.log`
|
||||
|
||||
## 参考
|
||||
|
||||
- Egg.js 官方文档:https://v3.eggjs.org/
|
||||
|
||||
107
app.js
107
app.js
@ -1,82 +1,79 @@
|
||||
// app.js
|
||||
const path = require('path');
|
||||
const LocalFileWriter = require('./app/lib/file_writer');
|
||||
const QimenClient = require('./app/lib/qimen_client');
|
||||
|
||||
const businessDict = require('./app/dict/businessDict.js');
|
||||
|
||||
// 直接导出函数,而不是类
|
||||
/**
|
||||
* 挂载应用级扩展能力。
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {void}
|
||||
*/
|
||||
module.exports = app => {
|
||||
// 设置全局应用根目录
|
||||
global.APP_ROOT = path.resolve(__dirname, './');
|
||||
app.appRoot = APP_ROOT;
|
||||
// ========== 挂载字典到 app ==========
|
||||
app.businessDict = businessDict;
|
||||
|
||||
// 添加字典工具方法
|
||||
app.getBusinessTypeName = code => {
|
||||
const dict = app.businessDict.BUSINESS_TYPE || {};
|
||||
for (const key in dict) {
|
||||
if (dict[key].code === code) {
|
||||
return dict[key].name;
|
||||
}
|
||||
}
|
||||
return code;
|
||||
};
|
||||
|
||||
app.getOperationCodeName = code => {
|
||||
return app.businessDict.OPERATION_CODE?.[code] || code;
|
||||
};
|
||||
app.getPlatformName = code => {
|
||||
return app.businessDict.PLATFORM_CODE?.[code] || code;
|
||||
};
|
||||
|
||||
app.getExternalLogTypeName = type => {
|
||||
return app.businessDict.EXTERNAL_LOG_TYPE?.[type] || type;
|
||||
};
|
||||
|
||||
app.logger.info('✅ 业务字典已挂载到 app');
|
||||
app.appRoot = global.APP_ROOT;
|
||||
app.fileWriter = new LocalFileWriter(app);
|
||||
app.qimenClient = new QimenClient(app);
|
||||
app.logger.info('✅ Application 扩展能力已加载');
|
||||
app.logger.info('✅ fileWriter 已挂载到 app.fileWriter');
|
||||
app.logger.info('✅ qimenClient 已挂载到 app.qimenClient');
|
||||
// 初始化工厂
|
||||
app.beforeStart(async () => {
|
||||
// skip factory init when model layer is absent (e.g. during tests)
|
||||
const OrderDeliveryFactory = require('./app/model/order_delivery_factory');
|
||||
app.OrderDeliveryFactory = OrderDeliveryFactory(app);
|
||||
|
||||
// skip 热区工厂 when model layer is absent (e.g. 部分单测)
|
||||
if (!app.model) {
|
||||
app.logger.info('⚠️ skipping factory init: app.model not available');
|
||||
app.logger.info('⚠️ skipping OrderDelivery/OrderItems factory init: app.model not available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const OrderDeliveryFactory = require('./app/model/order_delivery_factory');
|
||||
const OrderItemsFactory = require('./app/model/order_items_factory');
|
||||
app.OrderDeliveryFactory = OrderDeliveryFactory(app);
|
||||
app.model.OrderDeliveryFactory = app.OrderDeliveryFactory;
|
||||
app.OrderItemsFactory = OrderItemsFactory(app);
|
||||
app.model.OrderItemsFactory = app.OrderItemsFactory;
|
||||
app.logger.info('✅ 工厂类初始化完成');
|
||||
} catch (error) {
|
||||
|
||||
app.logger.error('❌ 工厂类初始化失败:', error);
|
||||
}
|
||||
|
||||
// 启动初检:异步为已有分表的仓库确保订单 id 序列表存在且水位正确。
|
||||
// 只做建表 + 水位抬升,不迁移数据(位置指针回填由 backfill-order-id-location 脚本负责);
|
||||
// 异步执行不阻塞启动,失败仅告警,后续建单/迁移触发时还会再次 ensure。
|
||||
setImmediate(() => {
|
||||
const factory = app.model && app.model.OrderDeliveryFactory;
|
||||
if (factory && typeof factory.ensureAllLocationSequenceTables === 'function') {
|
||||
factory.ensureAllLocationSequenceTables().catch(error => {
|
||||
app.logger.warn(`[启动初检] 序列表初检异常: ${error && error.message ? error.message : error}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 售后函数表启动同步(v2 可配置回信引擎):
|
||||
// 把 inbox functions 代码注册表幂等 upsert 到 wms_after_sale_function,
|
||||
// 只增改不删、不覆盖管理端 is_enabled/sort_order;失败仅告警,不影响启动。
|
||||
try {
|
||||
const ctx = app.createAnonymousContext();
|
||||
if (ctx && ctx.service && ctx.service.inbox
|
||||
&& ctx.service.inbox.v2 && ctx.service.inbox.v2.functionSync) {
|
||||
const stats = await ctx.service.inbox.v2.functionSync.sync();
|
||||
app.logger.info(`✅ 售后函数表同步完成: ${JSON.stringify(stats)}`);
|
||||
}
|
||||
} catch (error) {
|
||||
app.logger.warn(`⚠️ 售后函数表同步失败(不影响启动): ${error && error.message ? error.message : error}`);
|
||||
}
|
||||
|
||||
// 验证缓存方法
|
||||
if (typeof app.setCacheAsync === 'function') {
|
||||
app.setCacheAsync('system', 'eggjs');
|
||||
await app.setCacheAsync('system', 'wms', 10);
|
||||
const system = await app.getCacheAsync('system');
|
||||
app.logger.info('✅ 缓存方法验证通过' + system);
|
||||
if (system !== 'wms') {
|
||||
app.logger.error('❌ 缓存方法验证失败: setCacheAsync/getCacheAsync 不一致');
|
||||
} else {
|
||||
app.logger.info(`✅ 缓存方法验证通过${system}`);
|
||||
}
|
||||
}
|
||||
app.logger.info('✅ l类型' + typeof app.Message);
|
||||
});
|
||||
|
||||
// 扩展 Date 原型
|
||||
Date.prototype.format = function(formatStr = 'YYYY-MM-DD HH:mm:ss') {
|
||||
const year = this.getFullYear();
|
||||
const month = String(this.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(this.getDate()).padStart(2, '0');
|
||||
const hours = String(this.getHours()).padStart(2, '0');
|
||||
const minutes = String(this.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(this.getSeconds()).padStart(2, '0');
|
||||
|
||||
return formatStr
|
||||
.replace('YYYY', year)
|
||||
.replace('MM', month)
|
||||
.replace('DD', day)
|
||||
.replace('HH', hours)
|
||||
.replace('mm', minutes)
|
||||
.replace('ss', seconds);
|
||||
};
|
||||
};
|
||||
|
||||
@ -1,169 +0,0 @@
|
||||
const { Controller } = require('egg');
|
||||
|
||||
class ApiV2Controller extends Controller {
|
||||
async index() {
|
||||
const { ctx, service } = this;
|
||||
ctx.query_count = 1;
|
||||
const startTime = Date.now();
|
||||
const logData = {
|
||||
method: '',
|
||||
v: '',
|
||||
url: ctx.request.href,
|
||||
created_at: new Date(),
|
||||
body: '',
|
||||
headers: JSON.stringify(ctx.headers),
|
||||
result: '',
|
||||
use_time: 0,
|
||||
auth: '',
|
||||
store_id: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const getParams = ctx.query;
|
||||
logData.method = getParams.method || '';
|
||||
logData.v = getParams.v || '';
|
||||
// 验证必要参数
|
||||
if (!service.system.validateParams(getParams)) {
|
||||
const errorMsg = '参数缺失或错误';
|
||||
const response = this.errorResponse(errorMsg, 'json');
|
||||
logData.result = response;
|
||||
service.system.saveLog(logData, startTime);
|
||||
ctx.body = response;
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
const authHeader = ctx.headers.authorization;
|
||||
ctx.device = ctx.headers.device;
|
||||
ctx.project = ctx.headers.project;
|
||||
|
||||
// 处理method参数
|
||||
const method = getParams.method;
|
||||
const methods = method.split('.');
|
||||
const actionName = methods.pop();
|
||||
const className = methods
|
||||
.map((item, index) =>
|
||||
(index === methods.length - 1 ? item : item)
|
||||
)
|
||||
.join('.');
|
||||
|
||||
// 获取JSON数据
|
||||
let jsonData = '';
|
||||
if (ctx.request.rawBody) {
|
||||
jsonData = ctx.request.rawBody;
|
||||
} else {
|
||||
jsonData = await new Promise((resolve, reject) => {
|
||||
let data = '';
|
||||
ctx.req.on('data', chunk => {
|
||||
data += chunk;
|
||||
});
|
||||
ctx.req.on('end', () => {
|
||||
resolve(data);
|
||||
});
|
||||
ctx.req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
jsonData = jsonData ? String(jsonData) : '';
|
||||
logData.body = jsonData;
|
||||
if (!jsonData || jsonData.trim() === '') {
|
||||
throw new Error('json数据为空');
|
||||
}
|
||||
try {
|
||||
jsonData = JSON.parse(jsonData);
|
||||
} catch (e) {
|
||||
throw new Error('json数据解析错误');
|
||||
}
|
||||
|
||||
// 调用扁平 dispatcher 服务
|
||||
const { isLog, result } = await service.dispatcher.invoke(
|
||||
getParams.method,
|
||||
jsonData,
|
||||
authHeader,
|
||||
ctx
|
||||
);
|
||||
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
|
||||
if (ctx.user) {
|
||||
logData.auth = JSON.stringify(ctx.user);
|
||||
logData.store_id = ctx.user.store_id;
|
||||
}
|
||||
// 保存原来的日志逻辑仍然通过 system.saveLog
|
||||
if (isLog) {
|
||||
service.system.saveLog(logData, startTime);
|
||||
}
|
||||
if (result.status && result.status !== 200) {
|
||||
// propagate failure message
|
||||
ctx.body = result.message ? { message: result.message } : result.data;
|
||||
} else {
|
||||
ctx.body = result.data;
|
||||
}
|
||||
ctx.type = 'application/json';
|
||||
ctx.status = result.status || 200;
|
||||
} catch (error) {
|
||||
ctx.status = 500;
|
||||
console.log(error);
|
||||
const response = this.errorResponse('接口错误: ' + error.message, 'json');
|
||||
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
|
||||
service.system.saveLog(logData, startTime);
|
||||
ctx.body = response;
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
}
|
||||
|
||||
validateParams(params) {
|
||||
const required = [ 'method', 'v', 'format', 'timestamp' ];
|
||||
|
||||
for (const field of required) {
|
||||
if (!params[field]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
errorResponse(message, format = 'json') {
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
|
||||
if (format.toLowerCase() === 'xml') {
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<response>
|
||||
<flag>failure</flag>
|
||||
<code>0</code>
|
||||
<message>${this.escapeXml(message)}</message>
|
||||
</response>`;
|
||||
}
|
||||
|
||||
return {
|
||||
flag: false,
|
||||
message,
|
||||
code: 0,
|
||||
timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
escapeXml(unsafe) {
|
||||
if (!unsafe) return '';
|
||||
return unsafe.replace(/[<>&'\"]/g, c => {
|
||||
switch (c) {
|
||||
case '<':
|
||||
return '<';
|
||||
case '>':
|
||||
return '>';
|
||||
case '&':
|
||||
return '&';
|
||||
case "'":
|
||||
return ''';
|
||||
case '"':
|
||||
return '"';
|
||||
default:
|
||||
return c;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ApiV2Controller;
|
||||
@ -4,115 +4,115 @@ const Controller = require('egg').Controller;
|
||||
|
||||
|
||||
class AuthController extends Controller {
|
||||
async printerSetting() {
|
||||
const { ctx } = this;
|
||||
const redis = this.app.redis;
|
||||
if (ctx.method === 'GET') {
|
||||
const code = ctx.params.code || '';
|
||||
if (!code) {
|
||||
ctx.body = { error: '缺少code参数' };
|
||||
return;
|
||||
}
|
||||
const bindValue = await redis.get('printer').get(`bind:${code}`);
|
||||
if (!bindValue) {
|
||||
ctx.body = { error: '无效code或未绑定' };
|
||||
return;
|
||||
}
|
||||
await redis.get('printer').setex(`binding:${code}`, 300, bindValue);
|
||||
await ctx.render('printer_setting.html', {
|
||||
title: '打印台设置',
|
||||
code,
|
||||
bindValue,
|
||||
});
|
||||
} else if (ctx.method === 'POST') {
|
||||
const { code, printer, warehouse } = ctx.request.body;
|
||||
if (!code || !printer || !warehouse) {
|
||||
ctx.body = { success: false, error: '参数缺失' };
|
||||
return;
|
||||
}
|
||||
// 获取临时binding:code
|
||||
const bindingValue = await redis.get('printer').get(`binding:${code}`);
|
||||
if (!bindingValue) {
|
||||
ctx.body = { success: false, error: '超时或未绑定' };
|
||||
return;
|
||||
}
|
||||
// 反序列化bindingValue
|
||||
let bindingValueObj = bindingValue;
|
||||
try {
|
||||
bindingValueObj = JSON.parse(bindingValue);
|
||||
} catch (e) {
|
||||
bindingValueObj = bindingValue;
|
||||
}
|
||||
// 使用 Store model 校验仓库id
|
||||
const Store = ctx.model.Store;
|
||||
const warehouseInfo = await Store.findOne({ where: { id: warehouse } });
|
||||
console.log('warehouseInfo:', warehouseInfo);
|
||||
if (!warehouseInfo || warehouseInfo.project !== 'warehouse') {
|
||||
ctx.body = { success: false, error: '仓库id校验失败' };
|
||||
return;
|
||||
}
|
||||
// 查找仓库id下是否有重名的电脑
|
||||
const PrintComputer = ctx.model.PrintComputer;
|
||||
let computerId = null;
|
||||
const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } });
|
||||
if (existComputer) {
|
||||
if (existComputer.status === 1) {
|
||||
ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' };
|
||||
return;
|
||||
} else {
|
||||
computerId = existComputer.id;
|
||||
}
|
||||
} else {
|
||||
// 创建新打印电脑
|
||||
console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 });
|
||||
const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 });
|
||||
console.log('newComputer:', newComputer);
|
||||
computerId = newComputer.id;
|
||||
}
|
||||
// 调用打印服务 /auth/bind,使用egg内置curl
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
let printServiceResult = null;
|
||||
try {
|
||||
const res = await ctx.curl(`${printServiceUrl}/auth/bind`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId },
|
||||
dataType: 'json',
|
||||
});
|
||||
printServiceResult = res.data;
|
||||
} catch (err) {
|
||||
console.log('调用打印服务失败:', err);
|
||||
printServiceResult = { success: false, error: '打印服务通讯失败' };
|
||||
}
|
||||
console.log('printServiceResult:', printServiceResult);
|
||||
// 判断打印服务返回结果
|
||||
if (printServiceResult && printServiceResult.status === 'fail') {
|
||||
ctx.body = {
|
||||
success: false,
|
||||
msg: printServiceResult.message || '打印服务失败',
|
||||
code,
|
||||
printer,
|
||||
warehouse,
|
||||
bindingValue: bindingValueObj,
|
||||
printServiceResult
|
||||
};
|
||||
return;
|
||||
}
|
||||
console.log('printServiceResult:', printServiceResult);
|
||||
ctx.body = {
|
||||
success: true,
|
||||
msg: '参数已接收',
|
||||
code,
|
||||
printer,
|
||||
warehouse,
|
||||
bindingValue: bindingValueObj,
|
||||
computerId,
|
||||
printServiceResult
|
||||
};
|
||||
} else {
|
||||
ctx.body = { msg: '不支持的请求方法' };
|
||||
async printerSetting() {
|
||||
const { ctx } = this;
|
||||
const redis = this.app.redis;
|
||||
if (ctx.method === 'GET') {
|
||||
const code = ctx.params.code || '';
|
||||
if (!code) {
|
||||
ctx.body = { error: '缺少code参数' };
|
||||
return;
|
||||
}
|
||||
const bindValue = await redis.get('printer').get(`bind:${code}`);
|
||||
if (!bindValue) {
|
||||
ctx.body = { error: '无效code或未绑定' };
|
||||
return;
|
||||
}
|
||||
await redis.get('printer').setex(`binding:${code}`, 300, bindValue);
|
||||
await ctx.render('printer_setting.html', {
|
||||
title: '打印台设置',
|
||||
code,
|
||||
bindValue,
|
||||
});
|
||||
} else if (ctx.method === 'POST') {
|
||||
const { code, printer, warehouse } = ctx.request.body;
|
||||
if (!code || !printer || !warehouse) {
|
||||
ctx.body = { success: false, error: '参数缺失' };
|
||||
return;
|
||||
}
|
||||
// 获取临时binding:code
|
||||
const bindingValue = await redis.get('printer').get(`binding:${code}`);
|
||||
if (!bindingValue) {
|
||||
ctx.body = { success: false, error: '超时或未绑定' };
|
||||
return;
|
||||
}
|
||||
// 反序列化bindingValue
|
||||
let bindingValueObj = bindingValue;
|
||||
try {
|
||||
bindingValueObj = JSON.parse(bindingValue);
|
||||
} catch (e) {
|
||||
bindingValueObj = bindingValue;
|
||||
}
|
||||
// 使用 Store model 校验仓库id
|
||||
const Store = ctx.model.Store;
|
||||
const warehouseInfo = await Store.findOne({ where: { id: warehouse } });
|
||||
console.log('warehouseInfo:', warehouseInfo);
|
||||
if (!warehouseInfo || warehouseInfo.project !== 'warehouse') {
|
||||
ctx.body = { success: false, error: '仓库id校验失败' };
|
||||
return;
|
||||
}
|
||||
// 查找仓库id下是否有重名的电脑
|
||||
const PrintComputer = ctx.model.PrintComputer;
|
||||
let computerId = null;
|
||||
const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } });
|
||||
if (existComputer) {
|
||||
if (existComputer.status === 1) {
|
||||
ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' };
|
||||
return;
|
||||
}
|
||||
computerId = existComputer.id;
|
||||
|
||||
} else {
|
||||
// 创建新打印电脑
|
||||
console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 });
|
||||
const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 });
|
||||
console.log('newComputer:', newComputer);
|
||||
computerId = newComputer.id;
|
||||
}
|
||||
// 调用打印服务 /auth/bind,使用egg内置curl
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
let printServiceResult = null;
|
||||
try {
|
||||
const res = await ctx.curl(`${printServiceUrl}/auth/bind`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId },
|
||||
dataType: 'json',
|
||||
});
|
||||
printServiceResult = res.data;
|
||||
} catch (err) {
|
||||
console.log('调用打印服务失败:', err);
|
||||
printServiceResult = { success: false, error: '打印服务通讯失败' };
|
||||
}
|
||||
console.log('printServiceResult:', printServiceResult);
|
||||
// 判断打印服务返回结果
|
||||
if (printServiceResult && printServiceResult.status === 'fail') {
|
||||
ctx.body = {
|
||||
success: false,
|
||||
msg: printServiceResult.message || '打印服务失败',
|
||||
code,
|
||||
printer,
|
||||
warehouse,
|
||||
bindingValue: bindingValueObj,
|
||||
printServiceResult,
|
||||
};
|
||||
return;
|
||||
}
|
||||
console.log('printServiceResult:', printServiceResult);
|
||||
ctx.body = {
|
||||
success: true,
|
||||
msg: '参数已接收',
|
||||
code,
|
||||
printer,
|
||||
warehouse,
|
||||
bindingValue: bindingValueObj,
|
||||
computerId,
|
||||
printServiceResult,
|
||||
};
|
||||
} else {
|
||||
ctx.body = { msg: '不支持的请求方法' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AuthController;
|
||||
module.exports = AuthController;
|
||||
|
||||
2302
app/controller/docs.js
Normal file
2302
app/controller/docs.js
Normal file
File diff suppressed because it is too large
Load Diff
118
app/controller/gateway.js
Normal file
118
app/controller/gateway.js
Normal file
@ -0,0 +1,118 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||||
|
||||
class GatewayController extends Controller {
|
||||
validateParams(params) {
|
||||
const required = [ 'method', 'v', 'timestamp' ];
|
||||
|
||||
for (const field of required) {
|
||||
if (!params[field]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof params.method !== 'string' || !params.method.includes('.')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
normalizeResult(result) {
|
||||
if (result && typeof result === 'object' && Object.prototype.hasOwnProperty.call(result, 'success') && Object.prototype.hasOwnProperty.call(result, 'code')) {
|
||||
if (result.success === false || Number(result.code) <= 0) {
|
||||
return {
|
||||
httpStatus: 200,
|
||||
body: toFailure({
|
||||
message: result.message || '请求失败',
|
||||
httpStatus: 200,
|
||||
code: typeof result.code === 'number' ? result.code : 0,
|
||||
data: result.data || null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
httpStatus: 200,
|
||||
body: toSuccess({
|
||||
flag: 'success',
|
||||
code: result.code,
|
||||
message: result.message || 'ok',
|
||||
data: result.data || null,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
httpStatus: 200,
|
||||
body: toSuccess(result),
|
||||
};
|
||||
}
|
||||
|
||||
async internal() {
|
||||
const { ctx, service } = this;
|
||||
|
||||
try {
|
||||
const getParams = ctx.query;
|
||||
if (!this.validateParams(getParams)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = toFailure({
|
||||
message: '参数缺失或错误: method/v/timestamp',
|
||||
httpStatus: 400,
|
||||
code: 400,
|
||||
});
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
|
||||
const methods = String(getParams.method).split('.');
|
||||
const actionName = methods.pop();
|
||||
const className = methods.join('.');
|
||||
|
||||
let jsonData = '';
|
||||
if (ctx.request.rawBody) {
|
||||
jsonData = ctx.request.rawBody;
|
||||
} else {
|
||||
jsonData = await new Promise((resolve, reject) => {
|
||||
let data = '';
|
||||
ctx.req.on('data', chunk => {
|
||||
data += chunk;
|
||||
});
|
||||
ctx.req.on('end', () => {
|
||||
resolve(data);
|
||||
});
|
||||
ctx.req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
jsonData = jsonData ? String(jsonData) : '';
|
||||
if (!jsonData || jsonData.trim() === '') {
|
||||
throw new Error('json数据为空');
|
||||
}
|
||||
|
||||
try {
|
||||
jsonData = JSON.parse(jsonData);
|
||||
} catch (error) {
|
||||
throw new Error('json数据解析错误');
|
||||
}
|
||||
|
||||
const result = await service.api.callMethod(className, actionName, jsonData);
|
||||
const normalized = this.normalizeResult(result);
|
||||
ctx.status = normalized.httpStatus;
|
||||
ctx.body = normalized.body;
|
||||
ctx.type = 'application/json';
|
||||
} catch (error) {
|
||||
ctx.status = 500;
|
||||
ctx.body = toFailure({
|
||||
message: '接口错误: ' + error.message,
|
||||
httpStatus: 500,
|
||||
code: 500,
|
||||
});
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = GatewayController;
|
||||
File diff suppressed because it is too large
Load Diff
68
app/controller/im.js
Normal file
68
app/controller/im.js
Normal file
@ -0,0 +1,68 @@
|
||||
const { Controller } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// 统一的返回格式
|
||||
const result = {
|
||||
code: 0,
|
||||
message: '接口错误',
|
||||
data: null,
|
||||
};
|
||||
|
||||
module.exports = class ImController extends Controller {
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
|
||||
// GET请求参数sign
|
||||
const queryData = ctx.query;
|
||||
const receivedSign = queryData.sign;
|
||||
|
||||
// 解析POST请求的body数据
|
||||
const requestData = ctx.request.body;
|
||||
const im_secret = this.config.im.secret;
|
||||
|
||||
// 验证签名:将请求体的base64字符串与预设的密钥进行拼接后进行sha256哈希
|
||||
if (!receivedSign) {
|
||||
ctx.body = { ...result, message: 'Missing signature parameter' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 将请求体转换为base64字符串
|
||||
let bodyBase64;
|
||||
try {
|
||||
bodyBase64 = Buffer.from(JSON.stringify(requestData)).toString('base64');
|
||||
} catch (err) {
|
||||
ctx.body = { ...result, message: 'Invalid request body' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 计算期望的签名
|
||||
const expectedSign = crypto
|
||||
.createHash('sha256')
|
||||
.update(bodyBase64 + im_secret)
|
||||
.digest('hex');
|
||||
|
||||
// 比对签名(使用时间恒定的比较方法防止时序攻击)
|
||||
if (!crypto.timingSafeEqual(Buffer.from(receivedSign), Buffer.from(expectedSign))) {
|
||||
ctx.body = { ...result, message: 'Invalid signature' };
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Received IM query data:', queryData);
|
||||
console.log('Received IM request data:', requestData);
|
||||
|
||||
const { method, data: data_data } = requestData || {};
|
||||
|
||||
// 通配method调用service层im的不同方法
|
||||
if (method && this.service.im[method]) {
|
||||
try {
|
||||
const { code, message, data } = await this.service.im[method](data_data);
|
||||
ctx.body = { code, message, data };
|
||||
} catch (error) {
|
||||
ctx.logger.error('IM service error:', error);
|
||||
ctx.body = { ...result, message: 'Service execution failed' };
|
||||
}
|
||||
} else {
|
||||
ctx.body = { ...result, message: 'Invalid method' };
|
||||
}
|
||||
}
|
||||
};
|
||||
56
app/controller/openapi.js
Normal file
56
app/controller/openapi.js
Normal file
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||||
|
||||
class OpenapiController extends Controller {
|
||||
/**
|
||||
* 输出 openapi 统一失败响应。
|
||||
* @param {number} httpStatus HTTP 状态码。
|
||||
* @param {string} message 错误消息。
|
||||
* @param {number} [code=httpStatus] 业务错误码。
|
||||
* @return {void} 无返回值。
|
||||
*/
|
||||
writeFailureResponse(httpStatus, message, code = httpStatus) {
|
||||
const { ctx } = this;
|
||||
ctx.status = httpStatus;
|
||||
ctx.body = toFailure({
|
||||
message,
|
||||
httpStatus,
|
||||
code,
|
||||
});
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAPI 统一入口,仅负责转发到 openapi service 并输出标准响应。
|
||||
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
|
||||
try {
|
||||
const result = await ctx.service.openapiEntry.processRequest();
|
||||
if (result.ok) {
|
||||
ctx.status = Number(result.httpStatus) || 200;
|
||||
ctx.body = toSuccess(result.data, result.message || 'ok');
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
|
||||
this.writeFailureResponse(
|
||||
Number(result.httpStatus) || 500,
|
||||
String(result.message || '请求失败'),
|
||||
Number(result.code) || Number(result.httpStatus) || 500
|
||||
);
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = String(error && error.message || '请求失败');
|
||||
this.writeFailureResponse(500, `接口错误: ${message}`, 500);
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiController;
|
||||
282
app/controller/openapiCallback.js
Normal file
282
app/controller/openapiCallback.js
Normal file
@ -0,0 +1,282 @@
|
||||
'use strict';
|
||||
const { Controller } = require('egg');
|
||||
const { CALLBACK_EVENTS } = require('../service/openapi/callbackRegistry');
|
||||
|
||||
/**
|
||||
* OpenAPI 回调测试控制器。
|
||||
* 提供独立的回调调试页面,用于模拟回调推送并查看响应结果。
|
||||
*/
|
||||
class OpenapiCallbackController extends Controller {
|
||||
/**
|
||||
* 渲染回调测试页面。
|
||||
* 页面支持选择已注册的回调事件,选中后自动填充与真实回调完全一致的
|
||||
* 完整报文体 { request: {...} }(奇门同层级,可编辑)、填入测试 URL 和密钥,
|
||||
* 前端计算 MD5 签名后 POST 到目标 URL 并展示完整请求/响应。
|
||||
*/
|
||||
async testPage() {
|
||||
const { ctx } = this;
|
||||
|
||||
const eventsJson = JSON.stringify(CALLBACK_EVENTS);
|
||||
|
||||
ctx.type = 'text/html; charset=utf-8';
|
||||
ctx.body = `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>OpenAPI 回调测试</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { font-family: "Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; background: #f4f6fb; color: #1f2a44; margin: 0; padding: 24px; }
|
||||
.container { max-width: 720px; margin: 0 auto; }
|
||||
h1 { font-size: 22px; margin: 0 0 8px; }
|
||||
.card { background: #fff; border: 1px solid #dbe1ee; border-radius: 12px; padding: 20px; margin-bottom: 16px; box-shadow: 0 4px 16px rgba(18,48,102,0.06); }
|
||||
label { display: block; font-weight: 600; margin: 12px 0 4px; color: #254974; font-size: 13px; }
|
||||
select, input, textarea { width: 100%; border: 1px solid #b5ccec; border-radius: 8px; padding: 8px 10px; font-size: 13px; font-family: inherit; }
|
||||
textarea { font-family: ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace; resize: vertical; }
|
||||
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||
.send-btn { border: 1px solid #0f5cb2; background: #1565c0; color: #fff; border-radius: 8px; padding: 10px 20px; cursor: pointer; font-size: 14px; margin-top: 12px; }
|
||||
.send-btn:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
pre { background: #0d1d33; color: #d8e7ff; border-radius: 8px; padding: 12px; font-size: 12px; overflow: auto; max-height: 400px; white-space: pre-wrap; word-break: break-all; margin: 12px 0 0; }
|
||||
.muted { color: #62708a; font-size: 12px; }
|
||||
.desc { color: #62708a; font-size: 13px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card">
|
||||
<h1>OpenAPI 回调测试</h1>
|
||||
<p class="desc">选择已注册的回调事件,自动填充与真实回调完全一致的完整报文体(奇门同层级 { request },可编辑),填入测试 URL 模拟推送。</p>
|
||||
<p style="margin-top:6px;font-size:13px;">
|
||||
<a href="/docs/api/openapi" style="color:#1565c0;">← 返回 API 文档</a>
|
||||
|
|
||||
<a href="/docs/api/openapi_callback" style="color:#1565c0;">→ 出站回调文档</a>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<label>回调事件</label>
|
||||
<select id="eventSelect">
|
||||
<option value="">请选择事件</option>
|
||||
</select>
|
||||
<p id="eventDesc" class="muted"></p>
|
||||
|
||||
<div class="row">
|
||||
<div>
|
||||
<label>app_key</label>
|
||||
<input id="appKeyInput" type="text" placeholder="APP2024011514301234" />
|
||||
</div>
|
||||
<div>
|
||||
<label>self_app_secret</label>
|
||||
<input id="secretInput" type="password" placeholder="密钥" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label>测试回调 URL</label>
|
||||
<input id="callbackUrlInput" type="text" placeholder="https://your-system.com/api/callback" />
|
||||
|
||||
<label>完整报文体(奇门同层级 { request },与真实回调一致,可编辑)</label>
|
||||
<textarea id="dataInput" rows="8" placeholder='{"request":{}}'></textarea>
|
||||
|
||||
<button id="sendBtn" class="send-btn" onclick="sendTest()">发送测试回调</button>
|
||||
|
||||
<pre id="resultBox">点击发送后显示响应</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
var EVENTS = ${eventsJson};
|
||||
|
||||
var eventSelect = document.getElementById('eventSelect');
|
||||
var eventDesc = document.getElementById('eventDesc');
|
||||
var dataInput = document.getElementById('dataInput');
|
||||
var resultBox = document.getElementById('resultBox');
|
||||
|
||||
// 填充下拉列表
|
||||
EVENTS.forEach(function(ev) {
|
||||
var opt = document.createElement('option');
|
||||
opt.value = ev.name;
|
||||
opt.textContent = ev.label + ' (' + ev.name + ')';
|
||||
eventSelect.appendChild(opt);
|
||||
});
|
||||
|
||||
eventSelect.addEventListener('change', function() {
|
||||
var name = eventSelect.value;
|
||||
var found = EVENTS.find(function(e) { return e.name === name; });
|
||||
if (found) {
|
||||
eventDesc.textContent = found.description;
|
||||
dataInput.value = JSON.stringify({
|
||||
request: found.request || {},
|
||||
}, null, 2);
|
||||
} else {
|
||||
eventDesc.textContent = '';
|
||||
dataInput.value = '{}';
|
||||
}
|
||||
});
|
||||
|
||||
function nowTimestamp() { return Math.floor(Date.now() / 1000); }
|
||||
|
||||
function md5(value) {
|
||||
// 使用与 docs.js 一致的 md5 实现(修复后版本)
|
||||
function add32(a,b){return(a+b)&0xFFFFFFFF}
|
||||
function cmn(q,a,b,x,s,t){a=add32(add32(a,q),add32(x,t));return add32((a<<s)|(a>>>32-s),b)}
|
||||
function ff(a,b,c,d,x,s,t){return cmn((b&c)|((~b)&d),a,b,x,s,t)}
|
||||
function gg(a,b,c,d,x,s,t){return cmn((b&d)|(c&(~d)),a,b,x,s,t)}
|
||||
function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t)}
|
||||
function ii(a,b,c,d,x,s,t){return cmn(c^(b|(~d)),a,b,x,s,t)}
|
||||
|
||||
var originalLength = value.length;
|
||||
var str = value;
|
||||
var m = [];
|
||||
var i = 0;
|
||||
while (str.length >= 64) {
|
||||
m = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
|
||||
for (var j = 0; j < 64; j++) m[j>>2] |= str.charCodeAt(j) << ((j%4)*8);
|
||||
var block = m;
|
||||
var a0=1732584193,b0=-271733879,c0=-1732584194,d0=271733878;
|
||||
var a=a0,b=b0,c=c0,d=d0;
|
||||
a=ff(a,b,c,d,block[0],7,-680876936);d=ff(d,a,b,c,block[1],12,-389564586);
|
||||
c=ff(c,d,a,b,block[2],17,606105819);b=ff(b,c,d,a,block[3],22,-1044525330);
|
||||
a=ff(a,b,c,d,block[4],7,-176418897);d=ff(d,a,b,c,block[5],12,1200080426);
|
||||
c=ff(c,d,a,b,block[6],17,-1473231341);b=ff(b,c,d,a,block[7],22,-45705983);
|
||||
a=ff(a,b,c,d,block[8],7,1770035416);d=ff(d,a,b,c,block[9],12,-1958414417);
|
||||
c=ff(c,d,a,b,block[10],17,-42063);b=ff(b,c,d,a,block[11],22,-1990404162);
|
||||
a=ff(a,b,c,d,block[12],7,1804603682);d=ff(d,a,b,c,block[13],12,-40341101);
|
||||
c=ff(c,d,a,b,block[14],17,-1502002290);b=ff(b,c,d,a,block[15],22,1236535329);
|
||||
a=gg(a,b,c,d,block[1],5,-165796510);d=gg(d,a,b,c,block[6],9,-1069501632);
|
||||
c=gg(c,d,a,b,block[11],14,643717713);b=gg(b,c,d,a,block[0],20,-373897302);
|
||||
a=gg(a,b,c,d,block[5],5,-701558691);d=gg(d,a,b,c,block[10],9,38016083);
|
||||
c=gg(c,d,a,b,block[15],14,-660478335);b=gg(b,c,d,a,block[4],20,-405537848);
|
||||
a=gg(a,b,c,d,block[9],5,568446438);d=gg(d,a,b,c,block[14],9,-1019803690);
|
||||
c=gg(c,d,a,b,block[3],14,-187363961);b=gg(b,c,d,a,block[8],20,1163531501);
|
||||
a=gg(a,b,c,d,block[13],5,-1444681467);d=gg(d,a,b,c,block[2],9,-51403784);
|
||||
c=gg(c,d,a,b,block[7],14,1735328473);b=gg(b,c,d,a,block[12],20,-1926607734);
|
||||
a=hh(a,b,c,d,block[5],4,-378558);d=hh(d,a,b,c,block[8],11,-2022574463);
|
||||
c=hh(c,d,a,b,block[11],16,1839030562);b=hh(b,c,d,a,block[14],23,-35309556);
|
||||
a=hh(a,b,c,d,block[1],4,-1530992060);d=hh(d,a,b,c,block[4],11,1272893353);
|
||||
c=hh(c,d,a,b,block[7],16,-155497632);b=hh(b,c,d,a,block[10],23,-1094730640);
|
||||
a=hh(a,b,c,d,block[13],4,681279174);d=hh(d,a,b,c,block[0],11,-358537222);
|
||||
c=hh(c,d,a,b,block[3],16,-722521979);b=hh(b,c,d,a,block[6],23,76029189);
|
||||
a=hh(a,b,c,d,block[9],4,-640364487);d=hh(d,a,b,c,block[12],11,-421815835);
|
||||
c=hh(c,d,a,b,block[15],16,530742520);b=hh(b,c,d,a,block[2],23,-995338651);
|
||||
a=ii(a,b,c,d,block[0],6,-198630844);d=ii(d,a,b,c,block[7],10,1126891415);
|
||||
c=ii(c,d,a,b,block[14],15,-1416354905);b=ii(b,c,d,a,block[5],21,-57434055);
|
||||
a=ii(a,b,c,d,block[12],6,1700485571);d=ii(d,a,b,c,block[3],10,-1894986606);
|
||||
c=ii(c,d,a,b,block[10],15,-1051523);b=ii(b,c,d,a,block[1],21,-2054922799);
|
||||
a=ii(a,b,c,d,block[8],6,1873313359);d=ii(d,a,b,c,block[15],10,-30611744);
|
||||
c=ii(c,d,a,b,block[6],15,-1560198380);b=ii(b,c,d,a,block[13],21,1309151649);
|
||||
a=ii(a,b,c,d,block[4],6,-145523070);d=ii(d,a,b,c,block[11],10,-1120210379);
|
||||
c=ii(c,d,a,b,block[2],15,718787259);b=ii(b,c,d,a,block[9],21,-343485551);
|
||||
a0=add32(a0,a);b0=add32(b0,b);c0=add32(c0,c);d0=add32(d0,d);
|
||||
str = str.substring(64);
|
||||
}
|
||||
|
||||
var tail = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
|
||||
for (i = 0; i < str.length; i++) tail[i>>2] |= str.charCodeAt(i) << ((i%4)*8);
|
||||
tail[i>>2] |= 0x80 << ((i%4)*8);
|
||||
tail[14] = originalLength * 8; // 修复:使用原始长度
|
||||
|
||||
a0=ff(a0,b0,c0,d0,tail[0],7,-680876936);d0=ff(d0,a0,b0,c0,tail[1],12,-389564586);
|
||||
c0=ff(c0,d0,a0,b0,tail[2],17,606105819);b0=ff(b0,c0,d0,a0,tail[3],22,-1044525330);
|
||||
a0=ff(a0,b0,c0,d0,tail[4],7,-176418897);d0=ff(d0,a0,b0,c0,tail[5],12,1200080426);
|
||||
c0=ff(c0,d0,a0,b0,tail[6],17,-1473231341);b0=ff(b0,c0,d0,a0,tail[7],22,-45705983);
|
||||
a0=ff(a0,b0,c0,d0,tail[8],7,1770035416);d0=ff(d0,a0,b0,c0,tail[9],12,-1958414417);
|
||||
c0=ff(c0,d0,a0,b0,tail[10],17,-42063);b0=ff(b0,c0,d0,a0,tail[11],22,-1990404162);
|
||||
a0=ff(a0,b0,c0,d0,tail[12],7,1804603682);d0=ff(d0,a0,b0,c0,tail[13],12,-40341101);
|
||||
c0=ff(c0,d0,a0,b0,tail[14],17,-1502002290);b0=ff(b0,c0,d0,a0,tail[15],22,1236535329);
|
||||
|
||||
function toHex(num) {
|
||||
var s = ''; for (var k = 0; k < 4; k++) s += ('0' + ((num>>>(k*8))&0xFF).toString(16)).slice(-2);
|
||||
return s;
|
||||
}
|
||||
return (toHex(a0)+toHex(b0)+toHex(c0)+toHex(d0)).toLowerCase();
|
||||
}
|
||||
|
||||
function stableStringify(value) {
|
||||
if (value === undefined) return '';
|
||||
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
||||
if (Array.isArray(value)) {
|
||||
var items = value.map(function(v) { return stableStringify(v); });
|
||||
return '[' + items.join(',') + ']';
|
||||
}
|
||||
if (Object.prototype.toString.call(value) !== '[object Object]') return JSON.stringify(value);
|
||||
var keys = Object.keys(value).sort();
|
||||
var fields = keys.map(function(k) { return JSON.stringify(k) + ':' + stableStringify(value[k]); });
|
||||
return '{' + fields.join(',') + '}';
|
||||
}
|
||||
|
||||
function computeSign(query, body, secret) {
|
||||
// 排除 sign/signature,按 key 字母序排序
|
||||
var ignoreKeys = ['sign', 'signature'];
|
||||
var sortedKeys = Object.keys(query).filter(function(k) {
|
||||
return ignoreKeys.indexOf(k.toLowerCase()) === -1 && query[k] !== undefined;
|
||||
}).sort();
|
||||
var canonicalQuery = sortedKeys.map(function(k) {
|
||||
return k + '=' + String(query[k] == null ? '' : typeof query[k] === 'object' ? stableStringify(query[k]) : query[k]);
|
||||
}).join('&');
|
||||
|
||||
var bodySign = md5(stableStringify(body));
|
||||
var signText = canonicalQuery + secret + bodySign;
|
||||
return md5(signText);
|
||||
}
|
||||
|
||||
async function sendTest() {
|
||||
var appKey = document.getElementById('appKeyInput').value.trim();
|
||||
var secret = document.getElementById('secretInput').value.trim();
|
||||
var callbackUrl = document.getElementById('callbackUrlInput').value.trim();
|
||||
var eventName = eventSelect.value;
|
||||
var dataText = dataInput.value.trim();
|
||||
var sendBtn = document.getElementById('sendBtn');
|
||||
|
||||
if (!eventName) { resultBox.textContent = '请选择回调事件'; return; }
|
||||
if (!appKey) { resultBox.textContent = '请输入 app_key'; return; }
|
||||
if (!secret) { resultBox.textContent = '请输入 self_app_secret'; return; }
|
||||
if (!callbackUrl) { resultBox.textContent = '请输入测试回调 URL'; return; }
|
||||
|
||||
sendBtn.disabled = true;
|
||||
sendBtn.textContent = '发送中...';
|
||||
resultBox.textContent = '请求中...';
|
||||
|
||||
try {
|
||||
var body = JSON.parse(dataText);
|
||||
var ts = nowTimestamp();
|
||||
var query = { method: eventName, v: '1.0', timestamp: ts, app_key: appKey };
|
||||
var sign = computeSign(query, body, secret);
|
||||
|
||||
var reqUrl = callbackUrl + (callbackUrl.indexOf('?') >= 0 ? '&' : '?') +
|
||||
'method=' + encodeURIComponent(eventName) +
|
||||
'&v=1.0' +
|
||||
'×tamp=' + ts +
|
||||
'&app_key=' + encodeURIComponent(appKey) +
|
||||
'&sign=' + sign;
|
||||
|
||||
resultBox.textContent = \`POST \${reqUrl}\n\n\${JSON.stringify(body, null, 2)}\n\n请求中...\`;
|
||||
|
||||
var resp = await fetch(reqUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
var respText = await resp.text();
|
||||
var respInfo = \`HTTP \${resp.status} \${resp.statusText}\n\n\`;
|
||||
try {
|
||||
var respJson = JSON.parse(respText);
|
||||
respInfo += JSON.stringify(respJson, null, 2);
|
||||
} catch(e) {
|
||||
respInfo += respText;
|
||||
}
|
||||
resultBox.textContent = \`POST \${reqUrl}\n\n\${JSON.stringify(body, null, 2)}\n\n--- 响应 ---\n\${respInfo}\`;
|
||||
} catch(e) {
|
||||
resultBox.textContent = '请求失败: ' + e.message;
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
sendBtn.textContent = '发送测试回调';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OpenapiCallbackController;
|
||||
61
app/controller/tempFileWriter.js
Normal file
61
app/controller/tempFileWriter.js
Normal file
@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
Controller,
|
||||
} = require('egg');
|
||||
const { toFailure, toSuccess } = require('../lib/api_response');
|
||||
|
||||
class TempFileWriterController extends Controller {
|
||||
/**
|
||||
* 触发一次临时 fileWriter 消费,并返回本次消费结果。
|
||||
* @return {Promise<void>} 无返回值,结果写入响应体。
|
||||
*/
|
||||
async consume() {
|
||||
const { ctx, app } = this;
|
||||
const { businessName, consumerName } = ctx.query;
|
||||
|
||||
if (!businessName) {
|
||||
ctx.status = 400;
|
||||
ctx.body = toFailure({
|
||||
httpStatus: 400,
|
||||
message: 'businessName 不能为空',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const progressFilePath = app.fileWriter.getProgressFilePath(
|
||||
businessName,
|
||||
null,
|
||||
consumerName || 'temp-http-consumer'
|
||||
);
|
||||
const consumedRecords = [];
|
||||
|
||||
try {
|
||||
const result = await app.fileWriter.consumeFiles({
|
||||
businessName,
|
||||
progressFilePath,
|
||||
parseJson: ctx.query.parseJson !== 'false',
|
||||
onRecord: async record => {
|
||||
consumedRecords.push(record);
|
||||
},
|
||||
});
|
||||
|
||||
ctx.body = toSuccess({
|
||||
businessName,
|
||||
progressFilePath,
|
||||
consumedRecords,
|
||||
processedCount: result.processedCount,
|
||||
progress: result.progress,
|
||||
dataFiles: result.dataFiles,
|
||||
});
|
||||
} catch (error) {
|
||||
ctx.status = error && error.message === 'businessName 不能为空' ? 400 : 500;
|
||||
ctx.body = toFailure({
|
||||
httpStatus: ctx.status,
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TempFileWriterController;
|
||||
@ -8,5 +8,6 @@ class TemplateController extends Controller {
|
||||
const result = await service.systems.setting.printTemplate.getXmlByTemplate(ctx.params.id);
|
||||
ctx.body = result;
|
||||
}
|
||||
|
||||
}
|
||||
module.exports = TemplateController;
|
||||
|
||||
109
app/controller/warehouse.js
Normal file
109
app/controller/warehouse.js
Normal file
@ -0,0 +1,109 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
const { toSuccess, toFailure } = require('../lib/api_response');
|
||||
|
||||
/** 日志内容长度上限 */
|
||||
const LOG_BODY_MAX = 65535;
|
||||
|
||||
class WarehouseController extends Controller {
|
||||
/**
|
||||
* 输出仓库 API 统一失败响应。
|
||||
* @param {number} httpStatus HTTP 状态码。
|
||||
* @param {string} message 错误消息。
|
||||
* @param {number} [code=httpStatus] 业务错误码。
|
||||
* @return {void} 无返回值。
|
||||
*/
|
||||
writeFailureResponse(httpStatus, message, code = httpStatus) {
|
||||
const { ctx } = this;
|
||||
ctx.status = httpStatus;
|
||||
ctx.body = toFailure({
|
||||
message,
|
||||
httpStatus,
|
||||
code,
|
||||
});
|
||||
ctx.type = 'application/json';
|
||||
}
|
||||
|
||||
/**
|
||||
* 截断日志内容到上限长度。
|
||||
* @param {string} value 原始字符串。
|
||||
* @return {string} 截断后的字符串。
|
||||
*/
|
||||
truncateLogBody(value) {
|
||||
const str = typeof value === 'string' ? value : JSON.stringify(value);
|
||||
if (str.length > LOG_BODY_MAX) {
|
||||
return str.substring(0, LOG_BODY_MAX);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仓库 API 统一入口,记录请求日志并转发到 warehouse service。
|
||||
* @return {Promise<void>} 无返回值,结果写入 ctx.body。
|
||||
*/
|
||||
async index() {
|
||||
const { ctx, app } = this;
|
||||
const startTime = Date.now();
|
||||
const logId = 'WL-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex');
|
||||
|
||||
const query = ctx.query || {};
|
||||
let result;
|
||||
|
||||
try {
|
||||
result = await ctx.service.warehouse.processRequest();
|
||||
|
||||
if (result.ok) {
|
||||
ctx.status = Number(result.httpStatus) || 200;
|
||||
ctx.body = toSuccess(result.data, result.message || 'ok');
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
}
|
||||
|
||||
this.writeFailureResponse(
|
||||
Number(result.httpStatus) || 500,
|
||||
String(result.message || '请求失败'),
|
||||
Number(result.code) || Number(result.httpStatus) || 500
|
||||
);
|
||||
ctx.type = 'application/json';
|
||||
return;
|
||||
} catch (error) {
|
||||
const message = String(error && error.message || '请求失败');
|
||||
this.writeFailureResponse(500, `接口错误: ${message}`, 500);
|
||||
ctx.type = 'application/json';
|
||||
// 异常情况下 result 为 undefined,构造一个 fallback
|
||||
result = {
|
||||
ok: false,
|
||||
httpStatus: 500,
|
||||
message: error.message || '未知错误',
|
||||
warehouseId: null,
|
||||
appKey: String(query.app_key || '').trim() || null,
|
||||
};
|
||||
} finally {
|
||||
// 异步写日志,不阻塞响应
|
||||
try {
|
||||
const logData = {
|
||||
log_id: logId,
|
||||
app_key: (result && result.appKey) || String(query.app_key || '').trim() || null,
|
||||
method: String(query.method || '').trim() || null,
|
||||
warehouse_id: (result && result.warehouseId) || null,
|
||||
url: ctx.request.href || null,
|
||||
http_status: ctx.status || (result && result.httpStatus) || null,
|
||||
body: this.truncateLogBody(ctx.request.rawBody || JSON.stringify(ctx.request.body || {})),
|
||||
result: this.truncateLogBody(typeof ctx.body === 'string' ? ctx.body : JSON.stringify(ctx.body || {})),
|
||||
use_time: Date.now() - startTime,
|
||||
created_at: new Date(),
|
||||
};
|
||||
|
||||
app.fileWriter.writeRecord('warehouse-logs', logData).catch(writeErr => {
|
||||
ctx.logger.error('[warehouse-log-sink] 写入文件失败: ' + writeErr.message);
|
||||
});
|
||||
} catch (logErr) {
|
||||
ctx.logger.error('[warehouse-log] 日志记录异常: ' + logErr.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WarehouseController;
|
||||
754
app/controller/wechatOpen.js
Normal file
754
app/controller/wechatOpen.js
Normal file
@ -0,0 +1,754 @@
|
||||
'use strict';
|
||||
|
||||
const Controller = require('egg').Controller;
|
||||
const wechatOpenCrypt = require('../lib/wechat_open_crypt');
|
||||
const WechatOpenClient = require('../lib/wechat_open_client');
|
||||
|
||||
/**
|
||||
* 微信全网发布检测专用测试号(官方文档 5 组随机分配),用于日志标注公众号/小程序场景。
|
||||
* 步骤2=公众号被动回复;步骤3=公众号客服消息;步骤4=小程序客服消息。
|
||||
*/
|
||||
const WECHAT_TEST_ACCOUNTS = {
|
||||
mp: new Set([
|
||||
'wx570bc396a51b8ff8', 'wx9252c5e0bb1836fc', 'wx8e1097c5bc82cde9',
|
||||
'wx14550af28c71a144', 'wxa35b9c23cfe664eb',
|
||||
]),
|
||||
mini: new Set([
|
||||
'wxd101a85aa106f53e', 'wxc39235c15087f6f3', 'wx7720d01d4b2a4500',
|
||||
'wx05d483572dcd5d8b', 'wx5910277cae6fd970',
|
||||
]),
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断 appid 属于公众号/小程序测试号(用于日志标注,未知账号不影响处理)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @return {string} '公众号' | '小程序' | '未知账号'。
|
||||
*/
|
||||
function detectAccountType(appid) {
|
||||
if (WECHAT_TEST_ACCOUNTS.mp.has(appid)) return '公众号';
|
||||
if (WECHAT_TEST_ACCOUNTS.mini.has(appid)) return '小程序';
|
||||
return '未知账号';
|
||||
}
|
||||
|
||||
/**
|
||||
* autoReply 返回该值表示「显式不回复,响应体回空串」:
|
||||
* 官方检测步骤3要求 5 秒内返回空串表明暂时不回复(不能回 success)。
|
||||
*/
|
||||
const EMPTY_REPLY = '__EMPTY_REPLY__';
|
||||
|
||||
/**
|
||||
* 微信开放平台第三方平台回调 Controller。
|
||||
* 接收微信服务器推送的授权事件(组件票据/授权成功/授权更新/取消授权),
|
||||
* 对应路由 GET|POST /Authorization。
|
||||
*/
|
||||
class WechatOpenController extends Controller {
|
||||
/**
|
||||
* 读取原始请求体(微信推送为 text/xml,bodyParser 默认不解析)。
|
||||
* @return {Promise<string>} 原始请求体字符串。
|
||||
*/
|
||||
async readRawBody() {
|
||||
const { ctx } = this;
|
||||
if (ctx.request.rawBody) {
|
||||
return String(ctx.request.rawBody);
|
||||
}
|
||||
return await new Promise((resolve, reject) => {
|
||||
let data = '';
|
||||
ctx.req.on('data', chunk => {
|
||||
data += chunk;
|
||||
});
|
||||
ctx.req.on('end', () => resolve(data));
|
||||
ctx.req.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权事件接收入口(GET=URL 验证,POST=事件推送)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async authorization() {
|
||||
const { ctx, app } = this;
|
||||
const config = (app.config && app.config.wechatOpen) || {};
|
||||
|
||||
const signature = String(ctx.query.signature || '');
|
||||
const timestamp = String(ctx.query.timestamp || '');
|
||||
const nonce = String(ctx.query.nonce || '');
|
||||
const echostr = String(ctx.query.echostr || '');
|
||||
const msgSignature = String(ctx.query.msg_signature || '');
|
||||
const state = String(ctx.query.state || '');
|
||||
const authCode = String(ctx.query.auth_code || '');
|
||||
|
||||
// ─── URL 有效性验证(首次配置服务器地址时) ───────────────
|
||||
if (echostr) {
|
||||
const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce);
|
||||
ctx.logger.info(`[wechatOpen] URL 验证 ${valid ? '通过' : '失败'}`);
|
||||
ctx.body = valid ? echostr : '签名验证失败';
|
||||
return;
|
||||
}
|
||||
|
||||
// ─── 授权回跳(微信授权完成后重定向 GET,带 state/auth_code;state 缺失同样走 view 提示) ───
|
||||
if (ctx.method === 'GET') {
|
||||
await this.handleAuthCallback(state, authCode);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const rawBody = await this.readRawBody();
|
||||
if (!rawBody || !rawBody.trim()) {
|
||||
ctx.logger.error('[wechatOpen] 接收到的推送体为空');
|
||||
ctx.body = 'fail';
|
||||
return;
|
||||
}
|
||||
|
||||
const decryptResult = wechatOpenCrypt.decryptMsg({
|
||||
token: config.token,
|
||||
encodingAesKey: config.encoding_aes_key,
|
||||
componentAppid: config.component_appid,
|
||||
msgSignature,
|
||||
timestamp,
|
||||
nonce,
|
||||
encryptedXml: rawBody,
|
||||
});
|
||||
|
||||
if (decryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
|
||||
ctx.logger.error(`[wechatOpen] 消息解密失败 code=${decryptResult.code} msg=${decryptResult.msg}`);
|
||||
ctx.body = 'fail';
|
||||
return;
|
||||
}
|
||||
|
||||
const msgObj = wechatOpenCrypt.parseXml(decryptResult.msg);
|
||||
const infoType = String(msgObj.InfoType || '');
|
||||
const event = String(msgObj.Event || '');
|
||||
ctx.logger.info(`[wechatOpen] 收到推送 InfoType=${infoType} Event=${event}`);
|
||||
|
||||
// 小程序事件(如审核结果)用 Event 字段分发,组件事件用 InfoType 分发
|
||||
await this.handleEvent(event || infoType, msgObj);
|
||||
|
||||
// 微信要求回显 success 表示处理成功
|
||||
ctx.body = 'success';
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen] 处理异常: ${e.message}`, e);
|
||||
ctx.body = 'fail';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权回跳处理:凭 state 取回仓库信息,用 auth_code 换取令牌并落库绑定仓库。
|
||||
* @param {string} state 发起授权时缓存的随机 state。
|
||||
* @param {string} authCode 微信回跳携带的授权码。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async handleAuthCallback(state, authCode) {
|
||||
const { ctx, app } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
const render = viewData => ctx.render('wechat_auth_callback.html', viewData);
|
||||
|
||||
if (!state) {
|
||||
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 state 参数,请从系统重新发起授权' });
|
||||
}
|
||||
|
||||
const stateInfo = await client.getAuthState(state);
|
||||
if (!stateInfo) {
|
||||
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '授权链接已过期或不存在,请重新发起授权' });
|
||||
}
|
||||
if (!authCode) {
|
||||
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 auth_code 参数' });
|
||||
}
|
||||
|
||||
try {
|
||||
// 用授权码换取授权方令牌(不依赖 authorized 事件时序)
|
||||
const authorizationInfo = await client.queryAuth(authCode);
|
||||
const authorizerAppid = authorizationInfo.authorizer_appid;
|
||||
if (!authorizerAppid) throw new Error('授权信息缺少 authorizer_appid');
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const fields = {
|
||||
warehouse_id: stateInfo.warehouse_id || null,
|
||||
authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null,
|
||||
auth_time: nowSec,
|
||||
func_info: JSON.stringify(authorizationInfo.func_info || []),
|
||||
is_enabled: 1,
|
||||
};
|
||||
|
||||
// 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断
|
||||
try {
|
||||
const detail = await client.getAuthorizerDetail(authorizerAppid);
|
||||
if (detail) {
|
||||
Object.assign(
|
||||
fields,
|
||||
ctx.service.systems.wechat.buildAuthorizerPatch(
|
||||
detail.authorizer_info,
|
||||
detail.authorization_info || {}
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`);
|
||||
}
|
||||
|
||||
const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } });
|
||||
if (existing) {
|
||||
await existing.update(fields);
|
||||
} else {
|
||||
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
|
||||
// 首次授权:写入系统默认用户须知作为第一版(幂等)
|
||||
await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid);
|
||||
}
|
||||
|
||||
// 令牌写入 Redis 缓存(不落库)
|
||||
await client.cacheSet(
|
||||
`App:${authorizerAppid}:AuthorizerAccessToken`,
|
||||
authorizationInfo.authorizer_access_token,
|
||||
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
|
||||
);
|
||||
await client.cacheSet(
|
||||
`App:${authorizerAppid}:authorizer_refresh_token`,
|
||||
authorizationInfo.authorizer_refresh_token,
|
||||
30 * 24 * 3600
|
||||
);
|
||||
|
||||
// state 一次性消费
|
||||
await client.clearAuthState(state);
|
||||
|
||||
ctx.logger.info(`[wechatOpen] 授权回调成功 appid=${authorizerAppid} warehouse_id=${fields.warehouse_id}`);
|
||||
return render({
|
||||
title: '微信授权结果',
|
||||
resultLevel: 'success',
|
||||
resultText: '授权成功,小程序已绑定仓库',
|
||||
appid: authorizerAppid,
|
||||
nickname: fields.nickname || '',
|
||||
warehouseId: fields.warehouse_id || null,
|
||||
});
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen] 授权回调处理失败: ${e.message}`, e);
|
||||
return render({
|
||||
title: '微信授权结果',
|
||||
resultLevel: 'error',
|
||||
resultText: `授权处理失败:${e.message}`,
|
||||
appid: '',
|
||||
nickname: '',
|
||||
warehouseId: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 InfoType 分发处理授权事件。
|
||||
* @param {string} infoType 事件类型。
|
||||
* @param {object} msgObj 解密后的消息对象。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async handleEvent(infoType, msgObj) {
|
||||
const { ctx, app } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
|
||||
switch (infoType) {
|
||||
case 'component_verify_ticket': {
|
||||
// 组件票据:每 10 分钟推送一次,缓存后用于换取 component_access_token
|
||||
const ticket = String(msgObj.ComponentVerifyTicket || '');
|
||||
if (!ticket) {
|
||||
ctx.logger.error('[wechatOpen] component_verify_ticket 事件缺少 ComponentVerifyTicket');
|
||||
return;
|
||||
}
|
||||
await client.saveComponentVerifyTicket(ticket);
|
||||
ctx.logger.info(`[wechatOpen] 已保存 ComponentVerifyTicket(AppId: ${msgObj.AppId})`);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'authorized':
|
||||
case 'updateauthorized': {
|
||||
const authorizerAppid = String(msgObj.AuthorizerAppid || '');
|
||||
const authorizationCode = String(msgObj.AuthorizationCode || '');
|
||||
if (!authorizerAppid || !authorizationCode) {
|
||||
ctx.logger.error(`[wechatOpen] ${infoType} 事件缺少 AuthorizerAppid/AuthorizationCode`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 暂存授权码(供后续换取令牌使用)
|
||||
await client.saveAuthorizationCode(authorizerAppid, authorizationCode);
|
||||
|
||||
// 用授权码换取授权方令牌与权限集合。
|
||||
// 注意:同一 authorization_code 只能 queryAuth 成功一次。微信全网发布检测时,
|
||||
// authorized 事件与 QUERY_AUTH_CODE 文本消息几乎同时推送(实测仅差 1 秒),
|
||||
// 文本分支也会用同一 code 调 queryAuth——谁先到谁消费。此处失败不抛错重试,
|
||||
// 令牌可由文本分支/授权回跳链路换得,保证「授权成功」检测项始终响应 success。
|
||||
let authorizationInfo = null;
|
||||
try {
|
||||
authorizationInfo = await client.queryAuth(authorizationCode);
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen] ${infoType} 换取授权方令牌失败(可能已被 QUERY_AUTH_CODE 文本消费): ${e.message}`);
|
||||
return;
|
||||
}
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const fields = {
|
||||
authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null,
|
||||
auth_time: nowSec,
|
||||
func_info: JSON.stringify(authorizationInfo.func_info || []),
|
||||
is_enabled: 1,
|
||||
};
|
||||
|
||||
// authorizer_access_token 存入 Redis 缓存(自动过期),不落库
|
||||
await client.cacheSet(
|
||||
`App:${authorizerAppid}:AuthorizerAccessToken`,
|
||||
authorizationInfo.authorizer_access_token,
|
||||
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
|
||||
);
|
||||
await client.cacheSet(
|
||||
`App:${authorizerAppid}:authorizer_refresh_token`,
|
||||
authorizationInfo.authorizer_refresh_token,
|
||||
30 * 24 * 3600
|
||||
);
|
||||
|
||||
// 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断
|
||||
try {
|
||||
const detail = await client.getAuthorizerDetail(authorizerAppid);
|
||||
if (detail) {
|
||||
Object.assign(
|
||||
fields,
|
||||
ctx.service.systems.wechat.buildAuthorizerPatch(
|
||||
detail.authorizer_info,
|
||||
detail.authorization_info || {}
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`);
|
||||
}
|
||||
|
||||
const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } });
|
||||
if (existing) {
|
||||
await existing.update(fields);
|
||||
ctx.logger.info(`[wechatOpen] 已更新授权记录 appid=${authorizerAppid}`);
|
||||
} else {
|
||||
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
|
||||
// 首次授权:写入系统默认用户须知作为第一版(幂等)
|
||||
await ctx.service.systems.wechat.ensureDefaultAgreementVersion(authorizerAppid);
|
||||
ctx.logger.info(`[wechatOpen] 已新增授权记录 appid=${authorizerAppid}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'unauthorized': {
|
||||
const authorizerAppid = String(msgObj.AuthorizerAppid || '');
|
||||
if (!authorizerAppid) {
|
||||
ctx.logger.error('[wechatOpen] unauthorized 事件缺少 AuthorizerAppid');
|
||||
return;
|
||||
}
|
||||
// 清理令牌缓存
|
||||
await client.clearAuthorizerCache(authorizerAppid);
|
||||
// 停用授权记录(保留记录供追溯)
|
||||
await app.model.WechatApp.update(
|
||||
{ is_enabled: 0 },
|
||||
{ where: { appid: authorizerAppid } }
|
||||
);
|
||||
ctx.logger.info(`[wechatOpen] 已停用授权记录 appid=${authorizerAppid}`);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'weapp_audit_success': {
|
||||
// 代码审核通过:按小程序原始ID(ToUserName=gh_xxx)定位记录,状态置 2
|
||||
const originalId = String(msgObj.ToUserName || '').trim();
|
||||
if (!originalId) {
|
||||
ctx.logger.error('[wechatOpen] weapp_audit_success 缺少 ToUserName');
|
||||
return;
|
||||
}
|
||||
await app.model.WechatApp.update(
|
||||
{ audit_status: 2, audit_reason: '' },
|
||||
{ where: { user_name: originalId } }
|
||||
);
|
||||
ctx.logger.info(`[wechatOpen] 审核通过 originalId=${originalId}`);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'weapp_audit_fail': {
|
||||
// 代码审核驳回:状态置 3 并记录驳回原因
|
||||
const originalId = String(msgObj.ToUserName || '').trim();
|
||||
if (!originalId) {
|
||||
ctx.logger.error('[wechatOpen] weapp_audit_fail 缺少 ToUserName');
|
||||
return;
|
||||
}
|
||||
await app.model.WechatApp.update(
|
||||
{ audit_status: 3, audit_reason: String(msgObj.Reason || '') },
|
||||
{ where: { user_name: originalId } }
|
||||
);
|
||||
ctx.logger.info(`[wechatOpen] 审核驳回 originalId=${originalId} reason=${msgObj.Reason || ''}`);
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
ctx.logger.info(`[wechatOpen] 未处理的 InfoType: ${infoType}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权方(小程序/公众号)消息与事件推收入口,参考 PHP /index/index/events/appid/$APPID$。
|
||||
* GET=服务器地址 URL 有效性验证(echostr),POST=消息/事件推送(组件密钥加密)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async events() {
|
||||
const { ctx, app } = this;
|
||||
const { params } = ctx;
|
||||
const appid = String((params && params.appid) || '').trim();
|
||||
const config = app.config.wechatOpen || {};
|
||||
|
||||
if (!appid) {
|
||||
ctx.logger.error('[wechatOpen.events] 缺少 appid 参数');
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const signature = String(ctx.query.signature || '');
|
||||
const timestamp = String(ctx.query.timestamp || '');
|
||||
const nonce = String(ctx.query.nonce || '');
|
||||
const echostr = String(ctx.query.echostr || '');
|
||||
const msgSignature = String(ctx.query.msg_signature || '');
|
||||
|
||||
// ─── URL 有效性验证(首次配置服务器地址时) ───────────────
|
||||
if (echostr) {
|
||||
ctx.body = await this.verifyEventUrl(appid, signature, timestamp, nonce, echostr);
|
||||
return;
|
||||
}
|
||||
|
||||
// ─── 消息/事件推送 ───────────────────────────────────────
|
||||
try {
|
||||
const rawBody = await this.readRawBody();
|
||||
if (!rawBody || !rawBody.trim()) {
|
||||
ctx.logger.error(`[wechatOpen.events] 事件推送数据为空 appid=${appid}`);
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const decryptResult = wechatOpenCrypt.decryptMsg({
|
||||
token: config.token,
|
||||
encodingAesKey: config.encoding_aes_key,
|
||||
componentAppid: config.component_appid,
|
||||
msgSignature,
|
||||
timestamp,
|
||||
nonce,
|
||||
encryptedXml: rawBody,
|
||||
});
|
||||
|
||||
if (decryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
|
||||
ctx.logger.error(`[wechatOpen.events] 消息解密失败 appid=${appid} code=${decryptResult.code} msg=${decryptResult.msg}`);
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const data = wechatOpenCrypt.parseXml(decryptResult.msg);
|
||||
ctx.logger.info(`[wechatOpen.events] 事件推送 appid=${appid}: ${decryptResult.msg}`);
|
||||
|
||||
const msgType = String(data.MsgType || '');
|
||||
const event = String(data.Event || '');
|
||||
|
||||
// 文本消息全量落盘(WARN 级):生产日志只落 WARN+,用于检测场景定位回复问题
|
||||
if (msgType === 'text') {
|
||||
ctx.logger.warn(`[wechatOpen.events] 收到文本消息 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} content=${JSON.stringify(String(data.Content || ''))}`);
|
||||
}
|
||||
|
||||
switch (msgType) {
|
||||
case 'event':
|
||||
await this.handlePushEvent(appid, event, data);
|
||||
break;
|
||||
|
||||
case 'text': {
|
||||
// 记录文本消息并自动回复(被动回复返回加密 XML;客服消息场景返回空串)
|
||||
const reply = await this.autoReply(appid, data, nonce);
|
||||
if (reply === EMPTY_REPLY) {
|
||||
// 官方检测步骤3/4:5 秒内返回空串表明暂时不回复,客服消息在后台异步发送
|
||||
ctx.logger.warn(`[wechatOpen.events] 返回空串响应(客服消息后台发送中) appid=${appid} type=${detectAccountType(appid)}`);
|
||||
ctx.body = '';
|
||||
return;
|
||||
}
|
||||
if (reply) {
|
||||
ctx.logger.warn(`[wechatOpen.events] 被动回复已返回 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} length=${reply.length}`);
|
||||
ctx.type = 'application/xml';
|
||||
ctx.body = reply;
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'image':
|
||||
await this.recordUserAction(appid, data, 'image');
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx.logger.info(`[wechatOpen.events] 未处理的消息类型 appid=${appid} MsgType=${msgType}`);
|
||||
break;
|
||||
}
|
||||
|
||||
// 微信要求回显 success 表示处理成功
|
||||
ctx.body = 'success';
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 处理异常 appid=${appid}: ${e.message}`, e);
|
||||
ctx.body = 'success';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证事件推送服务器 URL(参考 PHP verifyEventUrl)。
|
||||
* 签名使用第三方平台(组件)Token 校验(与 /Authorization 的 URL 验证一致)。
|
||||
* appid 记录不存在时不阻断验证:首次配置服务器地址、微信全网发布检测等场景下,
|
||||
* 微信会先发 echostr 验证 URL,此时可能尚无授权记录,仍按组件 Token 验签回显。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} signature 微信回传签名。
|
||||
* @param {string} timestamp 时间戳。
|
||||
* @param {string} nonce 随机串。
|
||||
* @param {string} echostr 回显串。
|
||||
* @return {Promise<string>} 验证通过返回 echostr,否则返回错误提示。
|
||||
*/
|
||||
async verifyEventUrl(appid, signature, timestamp, nonce, echostr) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
// 对应小程序应已授权登记;未登记仅告警,不阻断 URL 验证
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
if (!record) {
|
||||
ctx.logger.warn(`[wechatOpen.events] URL 验证:appid 尚无授权记录(首次配置或检测场景),仍按组件 Token 验签 appid=${appid}`);
|
||||
}
|
||||
|
||||
const config = app.config.wechatOpen || {};
|
||||
const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce);
|
||||
ctx.logger.info(`[wechatOpen.events] URL 验证 appid=${appid} ${valid ? '通过' : '失败'}`);
|
||||
return valid ? echostr : '验证失败';
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理事件类型推送(MsgType=event,参考 PHP handleEvent)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} event 事件类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/TEMPLATESENDJOBFINISH)。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async handlePushEvent(appid, event, data) {
|
||||
const { ctx } = this;
|
||||
const openid = String(data.FromUserName || '');
|
||||
|
||||
switch (event) {
|
||||
case 'subscribe':
|
||||
// 关注事件:记录行为并发送欢迎消息(客服消息,非被动回复)
|
||||
await this.recordUserAction(appid, data, 'subscribe');
|
||||
await this.sendWelcomeMessage(appid, openid);
|
||||
break;
|
||||
|
||||
case 'unsubscribe':
|
||||
await this.recordUserAction(appid, data, 'unsubscribe');
|
||||
break;
|
||||
|
||||
case 'SCAN':
|
||||
case 'CLICK':
|
||||
case 'VIEW':
|
||||
case 'TEMPLATESENDJOBFINISH':
|
||||
await this.recordUserAction(appid, data, event);
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx.logger.info(`[wechatOpen.events] 未处理的事件类型 appid=${appid} Event=${event}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文本消息自动回复(参考 PHP autoReply):先记录用户行为,
|
||||
* 关键词命中生成被动回复并加密;QUERY_AUTH_CODE 场景改为客服消息直发、不被动回复。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @param {string} nonce 微信回传随机串(用于回复签名)。
|
||||
* @return {Promise<string>} 加密回复 XML;无需被动回复时返回空串。
|
||||
*/
|
||||
async autoReply(appid, data, nonce) {
|
||||
const { ctx, app } = this;
|
||||
const config = app.config.wechatOpen || {};
|
||||
|
||||
const openid = String(data.FromUserName || '');
|
||||
const appName = String(data.ToUserName || '');
|
||||
const content = String(data.Content || '');
|
||||
|
||||
// 记录用户文本消息
|
||||
await this.recordUserAction(appid, data, 'text');
|
||||
|
||||
try {
|
||||
const lowerContent = content.toLowerCase();
|
||||
let replyContent = '';
|
||||
|
||||
// 关键词回复(与参考实现保持一致)
|
||||
if (content.includes('你好') || lowerContent.includes('hello')) {
|
||||
replyContent = '你好!有什么可以帮您的吗?';
|
||||
} else if (content.includes('帮助') || lowerContent.includes('help')) {
|
||||
replyContent = '输入以下关键词获取帮助:\n1. 功能 - 查看功能列表\n2. 关于 - 了解更多信息';
|
||||
} else if (content.includes('TESTCOMPONENT_MSG_TYPE_TEXT')) {
|
||||
replyContent = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
|
||||
ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤2-公众号被动回复 appid=${appid} type=${detectAccountType(appid)}`);
|
||||
} else if (content.includes('QUERY_AUTH_CODE')) {
|
||||
// 微信全网发布检测场景(官方步骤3=公众号客服/步骤4=小程序客服):文本携带授权码
|
||||
// (QUERY_AUTH_CODE:<code>)。处理:响应体直接回空串(官方要求「5 秒内返回空串
|
||||
// 表明暂时不回复」),客服消息由后台异步发送(含前缀/去前缀双发)。
|
||||
const authCode = content.replace('QUERY_AUTH_CODE:', '').trim();
|
||||
const accountType = detectAccountType(appid);
|
||||
ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤3/4-客服消息回复 appid=${appid} type=${accountType} code=${authCode}`);
|
||||
|
||||
// 官方要求:不被动回复,响应体回空串;客服消息流程放入后台异步执行
|
||||
ctx.runInBackground(async () => {
|
||||
const client = new WechatOpenClient(ctx);
|
||||
let refreshToken = null;
|
||||
let tokenSource = '';
|
||||
|
||||
// 1) 优先使用已存储的 refresh_token(authorized 事件已换取):Redis → DB。
|
||||
// 真实业务中用户消息不带 code,只能依赖存储的令牌(与 PHP 参考实现一致)。
|
||||
refreshToken = await client.cacheGet(`App:${appid}:authorizer_refresh_token`);
|
||||
if (refreshToken) {
|
||||
tokenSource = 'redis';
|
||||
} else {
|
||||
try {
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
if (record && record.authorizer_refresh_token) {
|
||||
refreshToken = String(record.authorizer_refresh_token);
|
||||
tokenSource = 'db';
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 2) 存储令牌不存在(文本消息先于 authorized 事件到达),用文本携带的授权码换取(官方检测意图)
|
||||
if (!refreshToken && authCode) {
|
||||
try {
|
||||
const authorizationInfo = await client.queryAuth(authCode);
|
||||
refreshToken = authorizationInfo.authorizer_refresh_token || null;
|
||||
if (refreshToken) {
|
||||
tokenSource = 'query_auth';
|
||||
await client.cacheSet(`App:${appid}:authorizer_refresh_token`, refreshToken, 30 * 24 * 3600);
|
||||
if (authorizationInfo.authorizer_access_token) {
|
||||
await client.cacheSet(
|
||||
`App:${appid}:AuthorizerAccessToken`,
|
||||
authorizationInfo.authorizer_access_token,
|
||||
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.logger.warn(`[wechatOpen.events] 客服回复令牌来源 source=${tokenSource || 'none'} appid=${appid} has_token=${!!refreshToken}`);
|
||||
|
||||
// 客服消息双发兼容:官方文档字面要求回复 <queryauthcode@@@code>_from_api;
|
||||
// 检测脚本可能按「去掉 queryauthcode@@@ 标记前缀的真实 code」核对,两条都发确保命中。
|
||||
const codeValue = authCode.trim();
|
||||
const pureCode = codeValue.startsWith('queryauthcode@@@')
|
||||
? codeValue.slice('queryauthcode@@@'.length)
|
||||
: codeValue;
|
||||
try {
|
||||
await this.sendMessage(appid, openid, `${codeValue}_from_api`, refreshToken);
|
||||
if (pureCode && pureCode !== codeValue) {
|
||||
await this.sendMessage(appid, openid, `${pureCode}_from_api`, refreshToken);
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 客服消息发送异常: ${e.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
// 响应体回空串(不被动回复,与 PHP 参考实现一致)
|
||||
return EMPTY_REPLY;
|
||||
} else {
|
||||
replyContent = `收到您的消息:${content}\n我会尽快回复您!`;
|
||||
}
|
||||
|
||||
// 组装明文回复 XML(ToUserName=用户 openid,FromUserName=公众号原始 ID)
|
||||
const plainXml = '<xml>'
|
||||
+ `<ToUserName><![CDATA[${openid}]]></ToUserName>`
|
||||
+ `<FromUserName><![CDATA[${appName}]]></FromUserName>`
|
||||
+ `<CreateTime>${Math.floor(Date.now() / 1000)}</CreateTime>`
|
||||
+ '<MsgType><![CDATA[text]]></MsgType>'
|
||||
+ `<Content><![CDATA[${replyContent}]]></Content>`
|
||||
+ '</xml>';
|
||||
|
||||
const encryptResult = wechatOpenCrypt.encryptMsg({
|
||||
token: config.token,
|
||||
encodingAesKey: config.encoding_aes_key,
|
||||
componentAppid: config.component_appid,
|
||||
plainXml,
|
||||
nonce,
|
||||
});
|
||||
|
||||
if (encryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
|
||||
ctx.logger.error(`[wechatOpen.events] 回复消息加密失败 code=${encryptResult.code}`);
|
||||
return '';
|
||||
}
|
||||
return encryptResult.encryptedXml;
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 自动回复失败: ${e.message}`);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录用户行为到 Redis(参考 PHP recordUserAction)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @param {string} action 行为类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/text/image 等)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async recordUserAction(appid, data, action) {
|
||||
const { ctx } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
const openid = String(data.FromUserName || '');
|
||||
if (!openid) return;
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const key = `UserAction:${appid}:${openid}:${nowSec}`;
|
||||
await client.cacheSet(key, JSON.stringify({
|
||||
appid,
|
||||
openid,
|
||||
action,
|
||||
data,
|
||||
time: nowSec,
|
||||
}), 86400);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送客服文本消息(refreshToken 优先,其次从 DB 兜底读取,避免 Redis 丢失导致失败)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} openid 用户 openid。
|
||||
* @param {string} content 文本内容。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(调用方已获取时传入)。
|
||||
* @return {Promise<object>} 微信原始响应。
|
||||
*/
|
||||
async sendMessage(appid, openid, content, refreshToken) {
|
||||
const { ctx, app } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
|
||||
// Redis 中的 refresh token 可能丢失,从 wms_wechat_app 兜底读取
|
||||
let token = refreshToken || null;
|
||||
try {
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
if (record && record.authorizer_refresh_token) {
|
||||
token = String(record.authorizer_refresh_token);
|
||||
}
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败 appid=${appid}: ${e.message}`);
|
||||
}
|
||||
|
||||
ctx.logger.warn(`[wechatOpen.events] 发送客服消息 appid=${appid} openid=${openid} content=${JSON.stringify(content)} has_token=${!!token}`);
|
||||
const result = await client.sendCustomMessage(appid, openid, content, token);
|
||||
ctx.logger.warn(`[wechatOpen.events] 客服消息发送结果: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送关注欢迎消息(失败仅记录日志,不阻断事件处理)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} openid 用户 openid。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async sendWelcomeMessage(appid, openid) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
await this.sendMessage(appid, openid, '欢迎关注!感谢您的支持!');
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 发送欢迎消息失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatOpenController;
|
||||
@ -21,6 +21,8 @@ module.exports = {
|
||||
LOCATION: { code: 'location', name: '库位管理' },
|
||||
USER: { code: 'user', name: '用户管理' },
|
||||
SYSTEM: { code: 'system', name: '系统管理' },
|
||||
ENTRY: { code: 'entry', name: '入库管理' },
|
||||
STORE: { code: 'store', name: '货主管理' },
|
||||
},
|
||||
|
||||
/**
|
||||
@ -56,8 +58,50 @@ module.exports = {
|
||||
ORDER_PACKED: '订单打包',
|
||||
ORDER_SHIPPED: '订单发货',
|
||||
ORDER_COMPLETE: '订单完成',
|
||||
ORDER_UPDATE_PLATFORM: '更新平台',
|
||||
ORDER_UPDATE_EXPRESS: '更新快递',
|
||||
ORDER_UPDATE_ADDRESS: '更新地址',
|
||||
ORDER_CLONE_SOURCE: '克隆来源订单',
|
||||
ORDER_CLONE_TARGET: '克隆目标订单',
|
||||
ORDER_MANUAL_WAYBILL: '手工录入运单号',
|
||||
ORDER_RESOLVE_EXCEPTION: '处理异常',
|
||||
ORDER_INTERCEPT_CONFIRM: '确认拦截',
|
||||
ORDER_PLATFORM_FALLBACK: '平台降级',
|
||||
ORDER_EXPRESS_FALLBACK: '快递降级',
|
||||
ORDER_EXPRESS_POLICY_MATCH: '策略命中',
|
||||
ORDER_WAVE_UPDATE: '更新波次',
|
||||
ORDER_WAVE_ASSIGN: '分配波次',
|
||||
ORDER_WAVE_REMOVE: '移出波次',
|
||||
ORDER_WAVE_CANCEL: '取消波次',
|
||||
ORDER_WAVE_GRAB: '抓取波次',
|
||||
ORDER_WAVE_AUTO_GROUP: '自动加团',
|
||||
ORDER_WAVE_STRATEGY_FETCH: '策略抓取波次',
|
||||
ORDER_WAVE_CLAIM: '领取波次',
|
||||
ORDER_CONFIRM_PRINT: '确认打印',
|
||||
ORDER_AUTO_EXPRESS_SKIP: '跳过自动分配快递',
|
||||
ORDER_PICK_COMPLETE: '拣货完成',
|
||||
ORDER_RECHECK: '订单复核',
|
||||
ORDER_RECHECK_BATCH: '批量复核',
|
||||
ORDER_SYNC: '同步订单',
|
||||
ORDER_WEIGH: '称重',
|
||||
ORDER_PACKAGE_MATERIAL_BIND: '绑定包材',
|
||||
ORDER_STORAGE_ALLOCATE_SUCCESS: '分配储位成功',
|
||||
ORDER_STORAGE_ALLOCATE_FAILED: '分配储位失败',
|
||||
ORDER_STORAGE_UNALLOCATE_SUCCESS: '取消分配储位成功',
|
||||
ORDER_STORAGE_UNALLOCATE_FAILED: '取消分配储位失败',
|
||||
ORDER_EXPRESS_ALLOCATE_SUBMITTED: '分配快递任务已提交',
|
||||
ORDER_EXPRESS_ALLOCATE_FAILED: '分配快递失败',
|
||||
ORDER_INTERCEPT_REQUEST: '请求订单拦截',
|
||||
ORDER_INTERCEPT_CANCEL: '解除订单拦截',
|
||||
ORDER_RETURN_RECEIVED: '退回收到',
|
||||
ORDER_LOCK: '订单锁定',
|
||||
ORDER_UNLOCK: '订单解锁',
|
||||
ORDER_AUTO_OUTBOUND: '自动出库',
|
||||
|
||||
// 库存管理
|
||||
STORAGE_TRANSFER_LOCATION: '库位调拨',
|
||||
STORAGE_TRANSFER_BY_PRODUCT: '商品调拨',
|
||||
STORAGE_UPDATE_EXPIRY: '维护库存效期',
|
||||
STOCK_IN: '商品入库',
|
||||
STOCK_OUT: '商品出库',
|
||||
STOCK_ADJUST: '库存调整',
|
||||
@ -103,6 +147,35 @@ module.exports = {
|
||||
UPDATE_IMAGES: '更新图片',
|
||||
UPDATE_BARCODE: '更新条码',
|
||||
BIND: '绑定',
|
||||
|
||||
// 入库管理
|
||||
QUICK_PUTAWAY: '快捷入库',
|
||||
|
||||
// 收货管理
|
||||
RECEIVING_CREATE: '创建收货单',
|
||||
RECEIVING_COMPLETE: '完成收货',
|
||||
RECEIVING_CANCEL: '作废收货单',
|
||||
RECEIVING_BATCH_CANCEL: '批量作废收货单',
|
||||
RECEIVING_BIND_STORE: '绑定货主',
|
||||
RECEIVING_ADD_DETAIL: '新增收货明细',
|
||||
RECEIVING_DELETE_DETAIL: '删除收货明细',
|
||||
RECEIVING_BIND_PRODUCT: '绑定商品',
|
||||
RECEIVING_UPDATE_DETAIL: '修改收货明细',
|
||||
RECEIVING_UPDATE: '修改收货单',
|
||||
RECEIVING_REVIEW: '审核收货单',
|
||||
RECEIVING_REJECT: '驳回收货单',
|
||||
|
||||
// 货主管理
|
||||
STORE_CREATE: '创建货主',
|
||||
STORE_CREATE_WAREHOUSE: '创建仓库',
|
||||
STORE_SIGN: '签约货主',
|
||||
STORE_OPEN_ACCOUNT: '仓库代开户',
|
||||
STORE_RENAME: '修改签约备注',
|
||||
STORE_UNBIND: '解绑签约',
|
||||
STORE_SAVE_POLICY_CONFIG: '保存签约策略配置',
|
||||
STORE_SAVE_API_CONFIG: '保存接口配置',
|
||||
STORE_DELETE_API_CONFIG: '删除接口配置',
|
||||
STORE_ADJUST_PRINT_QUANTITY: '调整面单余额',
|
||||
},
|
||||
|
||||
/**
|
||||
@ -125,6 +198,9 @@ module.exports = {
|
||||
SUCCESS: '成功',
|
||||
FAILED: '失败',
|
||||
PROCESSING: '处理中',
|
||||
SUBMITTED: '已提交',
|
||||
RUNNING: '进行中',
|
||||
NOT_FOUND: '未找到',
|
||||
},
|
||||
|
||||
/**
|
||||
@ -161,7 +237,7 @@ module.exports = {
|
||||
|
||||
/**
|
||||
* 获取指定业务类型的操作编码
|
||||
* @param businessType
|
||||
* @param {string} businessType 业务类型
|
||||
*/
|
||||
getOperationCodesByBusinessType(businessType) {
|
||||
const prefix = businessType.toUpperCase() + '_';
|
||||
@ -178,8 +254,8 @@ module.exports = {
|
||||
|
||||
/**
|
||||
* 验证操作编码是否属于指定业务类型
|
||||
* @param code
|
||||
* @param businessType
|
||||
* @param {string} code 操作编码
|
||||
* @param {string} businessType 业务类型
|
||||
*/
|
||||
validateOperationCode(code, businessType) {
|
||||
if (!businessType) return true;
|
||||
|
||||
@ -1,14 +1,296 @@
|
||||
class MessageClass {
|
||||
async action() {
|
||||
const soap = require('soap');
|
||||
const businessDict = require('../dict/businessDict');
|
||||
|
||||
const LOCAL_CACHE_CLEANUP_INTERVAL_MS = 60 * 1000;
|
||||
const LOCAL_CACHE_STATE_KEY = '__wmsLocalCacheState';
|
||||
|
||||
/**
|
||||
* 获取缓存日志记录器。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @return {Object|null} 日志对象。
|
||||
*/
|
||||
function getCacheLogger(app) {
|
||||
return app && (app.logger || app.coreLogger) ? (app.logger || app.coreLogger) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取或初始化进程内缓存状态。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @return {Object|null} 进程内缓存状态。
|
||||
*/
|
||||
function getLocalCacheState(app) {
|
||||
if (!app) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!app[LOCAL_CACHE_STATE_KEY]) {
|
||||
app[LOCAL_CACHE_STATE_KEY] = {
|
||||
store: new Map(),
|
||||
cleanupTimer: null,
|
||||
lastCleanupAt: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return app[LOCAL_CACHE_STATE_KEY];
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化缓存过期秒数。
|
||||
*
|
||||
* @param {*} expireSeconds 过期秒数。
|
||||
* @return {number} 规范化后的秒数。
|
||||
*/
|
||||
function normalizeExpireSeconds(expireSeconds) {
|
||||
const ttl = Number(expireSeconds);
|
||||
if (!Number.isFinite(ttl) || ttl <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return Math.floor(ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制缓存值,避免进程内缓存被外部引用直接修改。
|
||||
*
|
||||
* @param {*} value 缓存值。
|
||||
* @return {*} 复制后的缓存值。
|
||||
*/
|
||||
function cloneCacheValue(value) {
|
||||
if (value === null || value === undefined) {
|
||||
return value;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(value));
|
||||
} catch (error) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理已经过期的进程内缓存。
|
||||
*
|
||||
* @param {Object} state 进程内缓存状态。
|
||||
* @return {number} 清理的条目数。
|
||||
*/
|
||||
function cleanupLocalCache(state) {
|
||||
if (!state || !state.store) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
let removedCount = 0;
|
||||
|
||||
for (const [ cacheKey, cacheEntry ] of state.store.entries()) {
|
||||
if (!cacheEntry || cacheEntry.expireAt <= now) {
|
||||
state.store.delete(cacheKey);
|
||||
removedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
state.lastCleanupAt = now;
|
||||
return removedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动进程内缓存的定时清理任务。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @return {Object|null} 进程内缓存状态。
|
||||
*/
|
||||
function ensureLocalCacheCleanupTimer(app) {
|
||||
const state = getLocalCacheState(app);
|
||||
if (!state || state.cleanupTimer) {
|
||||
return state;
|
||||
}
|
||||
|
||||
state.cleanupTimer = setInterval(() => {
|
||||
cleanupLocalCache(state);
|
||||
}, LOCAL_CACHE_CLEANUP_INTERVAL_MS);
|
||||
|
||||
if (state.cleanupTimer && typeof state.cleanupTimer.unref === 'function') {
|
||||
state.cleanupTimer.unref();
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Redis 缓存客户端。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @return {Object|null} Redis 缓存客户端。
|
||||
*/
|
||||
function getRedisCacheClient(app) {
|
||||
try {
|
||||
return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null;
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(app);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn('[CacheRedisUnavailable] 获取 Redis 缓存客户端失败', error.message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将值写入进程内缓存。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @param {string} cacheKey 缓存键。
|
||||
* @param {*} data 缓存数据。
|
||||
* @param {number} expireSeconds 过期秒数。
|
||||
*/
|
||||
function setLocalCacheValue(app, cacheKey, data, expireSeconds) {
|
||||
const state = ensureLocalCacheCleanupTimer(app);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ttl = normalizeExpireSeconds(expireSeconds);
|
||||
if (ttl <= 0) {
|
||||
state.store.delete(cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
state.store.set(cacheKey, {
|
||||
value: cloneCacheValue(data),
|
||||
expireAt: Date.now() + (ttl * 1000),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从进程内缓存读取值。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @param {string} cacheKey 缓存键。
|
||||
* @return {*} 缓存值或 null。
|
||||
*/
|
||||
function getLocalCacheValue(app, cacheKey) {
|
||||
const state = getLocalCacheState(app);
|
||||
if (!state) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheEntry = state.store.get(cacheKey);
|
||||
if (!cacheEntry) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (cacheEntry.expireAt <= Date.now()) {
|
||||
state.store.delete(cacheKey);
|
||||
return null;
|
||||
}
|
||||
|
||||
return cloneCacheValue(cacheEntry.value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从进程内缓存删除值。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @param {string} cacheKey 缓存键。
|
||||
*/
|
||||
function deleteLocalCacheValue(app, cacheKey) {
|
||||
const state = getLocalCacheState(app);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.store.delete(cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Redis 返回的数据解析为对象。
|
||||
*
|
||||
* @param {string} cacheValue Redis 缓存字符串。
|
||||
* @return {*} 解析后的值。
|
||||
*/
|
||||
function parseRedisCacheValue(cacheValue) {
|
||||
if (cacheValue === undefined || cacheValue === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parse(cacheValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用超时保护执行 Redis 命令,避免 Redis 卡顿拖慢接口响应。
|
||||
*
|
||||
* @param {Object} app 应用实例。
|
||||
* @param {Promise<*>} commandPromise Redis 命令 Promise。
|
||||
* @param {string} commandName Redis 命令名。
|
||||
* @return {Promise<*>} Redis 命令执行结果。
|
||||
*/
|
||||
async function withRedisCommandTimeout(app, commandPromise, commandName) {
|
||||
const timeoutConfig = Number(app && app.config ? app.config.cacheRedisCommandTimeoutMs : 0);
|
||||
const timeoutMs = Number.isFinite(timeoutConfig) && timeoutConfig > 0 ? timeoutConfig : 800;
|
||||
|
||||
let timeoutId = null;
|
||||
|
||||
const timeoutPromise = new Promise((resolve, reject) => {
|
||||
timeoutId = setTimeout(() => {
|
||||
const timeoutError = new Error(`Redis 命令执行超时: ${commandName}, timeout=${timeoutMs}ms`);
|
||||
timeoutError.code = 'CACHE_REDIS_TIMEOUT';
|
||||
reject(timeoutError);
|
||||
}, timeoutMs);
|
||||
|
||||
if (timeoutId && typeof timeoutId.unref === 'function') {
|
||||
timeoutId.unref();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
return await Promise.race([ commandPromise, timeoutPromise ]);
|
||||
} finally {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
}
|
||||
const soap = require('soap');
|
||||
const MESSAGE_CLASS = Symbol('Application#Message');
|
||||
module.exports = {
|
||||
get businessDict() {
|
||||
return businessDict;
|
||||
},
|
||||
getBusinessTypeName(code) {
|
||||
const dict = this.businessDict.BUSINESS_TYPE || {};
|
||||
for (const key in dict) {
|
||||
if (dict[key].code === code) {
|
||||
return dict[key].name;
|
||||
}
|
||||
}
|
||||
return code;
|
||||
},
|
||||
getOperationCodeName(code) {
|
||||
return this.businessDict.OPERATION_CODE?.[code] || code;
|
||||
},
|
||||
getPlatformName(code) {
|
||||
return this.businessDict.PLATFORM_CODE?.[code] || code;
|
||||
},
|
||||
getExternalLogTypeName(type) {
|
||||
return this.businessDict.EXTERNAL_LOG_TYPE?.[type] || type;
|
||||
},
|
||||
formatDate(date, formatStr = 'YYYY-MM-DD HH:mm:ss') {
|
||||
const targetDate = date instanceof Date ? date : new Date(date);
|
||||
const year = targetDate.getFullYear();
|
||||
const month = String(targetDate.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(targetDate.getDate()).padStart(2, '0');
|
||||
const hours = String(targetDate.getHours()).padStart(2, '0');
|
||||
const minutes = String(targetDate.getMinutes()).padStart(2, '0');
|
||||
const seconds = String(targetDate.getSeconds()).padStart(2, '0');
|
||||
|
||||
return formatStr
|
||||
.replace('YYYY', year)
|
||||
.replace('MM', month)
|
||||
.replace('DD', day)
|
||||
.replace('HH', hours)
|
||||
.replace('mm', minutes)
|
||||
.replace('ss', seconds);
|
||||
},
|
||||
async wsdl(methodName, args) {
|
||||
try {
|
||||
const wsdlUrl = "http://ye4s.com/webservice/ws?wsdl";
|
||||
const wsdlUrl = 'http://ye4s.com/webservice/ws?wsdl';
|
||||
const obj = {};
|
||||
args.forEach((value, index) => {
|
||||
obj['arg' + index] = value;
|
||||
@ -17,47 +299,111 @@ module.exports = {
|
||||
const result = await client[methodName + 'Async'](obj);
|
||||
return result[0];
|
||||
} catch (error) {
|
||||
console.error('Error calling SOAP service:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 写入缓存。
|
||||
*
|
||||
* Redis 可用时优先写入 Redis;当 Redis 不可用或写入失败时,自动降级到进程内缓存。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键。
|
||||
* @param {*} data 缓存数据。
|
||||
* @param {number} [expireSeconds=300] 过期秒数。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async setCacheAsync(cacheKey, data, expireSeconds = 300) {
|
||||
const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null;
|
||||
if (!cacheRedis) {
|
||||
this.logger.warn('[RedisNotAvailable] Cannot set cache, Redis client is not available');
|
||||
const ttl = normalizeExpireSeconds(expireSeconds);
|
||||
const cacheRedis = getRedisCacheClient(this);
|
||||
|
||||
if (ttl <= 0) {
|
||||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||||
try {
|
||||
await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del');
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(this);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deleteLocalCacheValue(this, cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await cacheRedis.setex(cacheKey, expireSeconds, JSON.stringify(data));
|
||||
this.logger.debug('[CacheSet] Successfully set cache', cacheKey);
|
||||
} catch (error) {
|
||||
this.logger.error('[CacheSetError] Failed to set cache', error.message, cacheKey);
|
||||
}
|
||||
},
|
||||
async getCacheAsync(cacheKey) {
|
||||
const cacheRedis = this.redis && this.redis.get ? this.redis.get('cache') : null;
|
||||
if (!cacheRedis) {
|
||||
this.logger.warn('[RedisNotAvailable] Cannot get cache, Redis client is not available');
|
||||
return null;
|
||||
if (cacheRedis && typeof cacheRedis.setex === 'function') {
|
||||
try {
|
||||
await withRedisCommandTimeout(this, cacheRedis.setex(cacheKey, ttl, JSON.stringify(data)), 'setex');
|
||||
|
||||
setLocalCacheValue(this, cacheKey, data, ttl);
|
||||
|
||||
return;
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(this);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn('[CacheRedisSetError] Redis 写入缓存失败,已降级到进程内缓存', error.message, cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await cacheRedis.get(cacheKey);
|
||||
if (data) {
|
||||
return JSON.parse(data);
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
this.logger.error('[CacheGetError] Failed to get cache', error.message, cacheKey);
|
||||
return null;
|
||||
}
|
||||
setLocalCacheValue(this, cacheKey, data, ttl);
|
||||
},
|
||||
get Message() {
|
||||
if (!this[MESSAGE_CLASS]) {
|
||||
// 返回类本身,不是实例
|
||||
this[MESSAGE_CLASS] = MessageClass;
|
||||
/**
|
||||
* 删除缓存。
|
||||
*
|
||||
* Redis 可用时优先删除 Redis;无论 Redis 是否可用,都会同步清理进程内缓存。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async delCacheAsync(cacheKey) {
|
||||
if (!cacheKey) {
|
||||
return;
|
||||
}
|
||||
return this[MESSAGE_CLASS];
|
||||
|
||||
const cacheRedis = getRedisCacheClient(this);
|
||||
|
||||
if (cacheRedis && typeof cacheRedis.del === 'function') {
|
||||
try {
|
||||
await withRedisCommandTimeout(this, cacheRedis.del(cacheKey), 'del');
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(this);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn('[CacheRedisDeleteError] Redis 删除缓存失败', error.message, cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deleteLocalCacheValue(this, cacheKey);
|
||||
},
|
||||
/**
|
||||
* 读取缓存。
|
||||
*
|
||||
* Redis 可用时优先读取 Redis;当 Redis 不可用、读取失败或命中为空时,自动回退到进程内缓存。
|
||||
*
|
||||
* @param {string} cacheKey 缓存键。
|
||||
* @return {Promise<*>} 缓存数据,未命中时返回 null。
|
||||
*/
|
||||
async getCacheAsync(cacheKey) {
|
||||
const cacheRedis = getRedisCacheClient(this);
|
||||
|
||||
if (cacheRedis && typeof cacheRedis.get === 'function') {
|
||||
try {
|
||||
const data = await withRedisCommandTimeout(this, cacheRedis.get(cacheKey), 'get');
|
||||
if (data === undefined || data === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return parseRedisCacheValue(data);
|
||||
} catch (error) {
|
||||
const logger = getCacheLogger(this);
|
||||
if (logger && typeof logger.warn === 'function') {
|
||||
logger.warn('[CacheRedisGetError] Redis 读取缓存失败,已回退到进程内缓存', error.message, cacheKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return getLocalCacheValue(this, cacheKey);
|
||||
},
|
||||
};
|
||||
|
||||
190
app/lib/api_log_sink.js
Normal file
190
app/lib/api_log_sink.js
Normal file
@ -0,0 +1,190 @@
|
||||
// app/lib/api_log_sink.js
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 接口日志落盘器:接口流水经 Egg 日志写出(`wms_system_log` 表已下线删除)。
|
||||
*
|
||||
* 设计要点:
|
||||
* 1. 只使用 Egg 自带 logger(`app.getLogger('apiLog')`),不自行操作 fs ——
|
||||
* egg-logger 的 FileTransport 以 O_APPEND 追加写、多 worker 共写同一文件、
|
||||
* 自动创建目录并按天轮转,避免自建写流带来的「轮转后句柄失效 / ENOSPC 崩进程 /
|
||||
* 每请求建流导致 fd 泄漏 / 退出前未 flush」等问题。
|
||||
* 2. 一行一条记录,形如 `HH:mm:ss {JSON}`:
|
||||
* 前缀是**本地时区的时分秒**,只给人眼定位用(tail/grep 时有个时间锚点),
|
||||
* 机器解析请用行内的 `created_at`(ISO 8601 UTC,无时区歧义,与前缀为同一时刻);
|
||||
* 前缀之后是沿用旧 `wms_system_log` 表结构的平铺 JSON(不嵌套,首字符是 `{`),
|
||||
* 可直接用 grep 搜索;用 jq 时先剥前缀:`jq -R 'sub("^[0-9:]+ "; "") | fromjson'`。
|
||||
* 3. 写入失败绝不影响接口返回:异常由调用方兜底,只记 app logger。
|
||||
*/
|
||||
|
||||
/** body / result 截断长度:沿用旧 wms_system_log 入库时的长文本上限(65535) */
|
||||
const TEXT_LIMIT = 65535;
|
||||
|
||||
/** customLogger.apiLog 缺失的告警只打一次,避免每请求刷屏 */
|
||||
let warnedApiLogMissing = false;
|
||||
|
||||
/**
|
||||
* 归一化为字符串,必要时截断。
|
||||
* @param {*} value 原始值。
|
||||
* @param {number} [limit] 截断长度(正数才生效),默认不截断。
|
||||
* @return {string} 字符串结果。
|
||||
*/
|
||||
function toText(value, limit) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
// 对象/数组一律 JSON 序列化:调用方若漏了 JSON.stringify(例如 controller 直接把
|
||||
// 响应对象塞进 logData.result),String() 会得到 "[object Object]" 而丢掉内容。
|
||||
let text;
|
||||
if (typeof value === 'string') {
|
||||
text = value;
|
||||
} else if (typeof value === 'object') {
|
||||
try {
|
||||
text = JSON.stringify(value);
|
||||
} catch (e) {
|
||||
text = String(value);
|
||||
}
|
||||
} else {
|
||||
text = String(value);
|
||||
}
|
||||
if (Number(limit) > 0 && text.length > Number(limit)) {
|
||||
return text.substring(0, Number(limit));
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造一行平铺记录。
|
||||
*
|
||||
* 字段与顺序沿用旧 `wms_system_log` 入库时的入参:
|
||||
* method / v / url / headers / auth / created_at / body / result / use_time / store_id / device。
|
||||
* `created_at` 统一写 ISO 8601(UTC,带 Z):与原入库是同一时刻,但没有时区歧义。
|
||||
*
|
||||
* @param {object} logData 原始日志数据。
|
||||
* @param {object} [options] 选项。
|
||||
* @param {number} [options.startTime] 请求开始时间戳(ms),用于计算 use_time。
|
||||
* @param {number} [options.useTime] 直接指定耗时(ms),优先于 startTime。
|
||||
* @param {string} [options.device] 设备标识。
|
||||
* @param {Date} [options.createdAt] 记录时间,默认当前时间。
|
||||
* @return {object} 平铺记录对象。
|
||||
*/
|
||||
function buildRecord(logData, options = {}) {
|
||||
const source = logData && typeof logData === 'object' ? logData : {};
|
||||
const createdAt = options.createdAt instanceof Date ? options.createdAt : new Date();
|
||||
|
||||
let useTime = 0;
|
||||
if (options.useTime !== undefined) {
|
||||
useTime = Number(options.useTime);
|
||||
} else if (Number(options.startTime) > 0) {
|
||||
useTime = Date.now() - Number(options.startTime);
|
||||
}
|
||||
if (!Number.isFinite(useTime) || useTime < 0) {
|
||||
useTime = 0;
|
||||
}
|
||||
|
||||
return {
|
||||
method: toText(source.method),
|
||||
v: toText(source.v),
|
||||
url: toText(source.url),
|
||||
headers: toText(source.headers),
|
||||
auth: toText(source.auth),
|
||||
created_at: createdAt.toISOString(),
|
||||
body: toText(source.body, TEXT_LIMIT),
|
||||
result: toText(source.result, TEXT_LIMIT),
|
||||
use_time: useTime,
|
||||
store_id: source.store_id || null,
|
||||
device: toText(options.device),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* customLogger.apiLog 缺失时的显式告警(每个 worker 只打一次)。
|
||||
*
|
||||
* egg 的 `app.getLogger(name)` 对未声明的 name 返回 null 而不抛错,
|
||||
* 若不处理就会「日志静默消失、且无任何报错」。
|
||||
* 生产 config 不参与 deploy,「代码已上线、配套配置没上」极易发生,故必须显式报出来。
|
||||
*
|
||||
* @param {Egg.Application} app Egg 应用实例。
|
||||
* @return {void}
|
||||
*/
|
||||
function warnApiLogMissing(app) {
|
||||
if (warnedApiLogMissing) {
|
||||
return;
|
||||
}
|
||||
warnedApiLogMissing = true;
|
||||
const logger = app && typeof app.getLogger === 'function' ? app.getLogger('logger') : null;
|
||||
if (logger && typeof logger.error === 'function') {
|
||||
logger.error(
|
||||
'[api_log_sink] config.customLogger.apiLog 未配置,接口日志不会落盘!' +
|
||||
'请在 config.default.js 补上 customLogger.apiLog' +
|
||||
'(生产 config 不参与 deploy,需手工同步到线上)。'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 两位补零。
|
||||
* @param {number} value 待补零的数字。
|
||||
* @return {string} 补零后的字符串。
|
||||
*/
|
||||
function pad2(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成日志行的时间前缀(本地时区 `HH:mm:ss`)。
|
||||
*
|
||||
* 整行内容本身是完整 JSON(首字符是 `{`),直接 tail/grep 时没有时间锚点,
|
||||
* 故在行首加一个本地时间的时分秒前缀。前缀只给人看:
|
||||
* 它与行内 `created_at` 取同一时刻,仅表达方式不同(本地 `HH:mm:ss` vs UTC ISO 8601)。
|
||||
* 日期无需前缀 —— 日志按天轮转为 `wms-api.log.YYYY-MM-DD`,日期由文件名提供。
|
||||
*
|
||||
* @param {Date|string} [value] 记录时间;缺省或非法时回退当前时间。
|
||||
* @return {string} `HH:mm:ss` 形式的前缀。
|
||||
*/
|
||||
function formatTimePrefix(value) {
|
||||
const parsed = value instanceof Date ? value : new Date(value || Date.now());
|
||||
const date = Number.isNaN(parsed.getTime()) ? new Date() : parsed;
|
||||
return `${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写出接口日志。
|
||||
*
|
||||
* 只落 Egg 日志文件(`config.customLogger.apiLog`);wms_system_log 表已下线,
|
||||
* 不再存在任何入库分支。
|
||||
*
|
||||
* @param {Egg.Application} app Egg 应用实例。
|
||||
* @param {object} payload 负载。
|
||||
* @param {object} payload.logData 原始日志数据。
|
||||
* @param {number} [payload.startTime] 请求开始时间戳(ms)。
|
||||
* @param {number} [payload.useTime] 直接指定耗时(ms)。
|
||||
* @param {string} [payload.device] 设备标识。
|
||||
* @param {Date} [payload.createdAt] 记录时间。
|
||||
* @return {Promise<object>} 实际写出的平铺记录。
|
||||
*/
|
||||
async function write(app, payload = {}) {
|
||||
const record = buildRecord(payload.logData, {
|
||||
startTime: payload.startTime,
|
||||
useTime: payload.useTime,
|
||||
device: payload.device,
|
||||
createdAt: payload.createdAt,
|
||||
});
|
||||
|
||||
const logger = app && typeof app.getLogger === 'function' ? app.getLogger('apiLog') : null;
|
||||
if (logger) {
|
||||
// 一行一条:`HH:mm:ss {完整 JSON}`,前缀与行内 created_at 是同一时刻
|
||||
logger.info(`${formatTimePrefix(record.created_at)} ${JSON.stringify(record)}`);
|
||||
} else {
|
||||
warnApiLogMissing(app);
|
||||
}
|
||||
|
||||
return record;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TEXT_LIMIT,
|
||||
buildRecord,
|
||||
formatTimePrefix,
|
||||
write,
|
||||
};
|
||||
59
app/lib/api_response.js
Normal file
59
app/lib/api_response.js
Normal file
@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
function nowTimestamp() {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function isObject(value) {
|
||||
return value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isStandardPayload(payload) {
|
||||
return isObject(payload)
|
||||
&& Object.prototype.hasOwnProperty.call(payload, 'flag')
|
||||
&& Object.prototype.hasOwnProperty.call(payload, 'code')
|
||||
&& Object.prototype.hasOwnProperty.call(payload, 'message');
|
||||
}
|
||||
|
||||
function toSuccess(payload, message = 'ok') {
|
||||
if (isStandardPayload(payload)) {
|
||||
const normalized = {
|
||||
...payload,
|
||||
flag: payload.flag === true || payload.flag === 'success' ? 'success' : payload.flag,
|
||||
};
|
||||
if (!Object.prototype.hasOwnProperty.call(normalized, 'timestamp')) {
|
||||
normalized.timestamp = nowTimestamp();
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return {
|
||||
flag: 'success',
|
||||
code: 1,
|
||||
message,
|
||||
data: payload ?? null,
|
||||
timestamp: nowTimestamp(),
|
||||
};
|
||||
}
|
||||
|
||||
function toFailure(options = {}) {
|
||||
const {
|
||||
message = '请求失败',
|
||||
httpStatus = 500,
|
||||
code,
|
||||
data = null,
|
||||
} = options;
|
||||
|
||||
return {
|
||||
flag: 'failure',
|
||||
code: typeof code === 'number' ? code : httpStatus,
|
||||
message,
|
||||
data,
|
||||
timestamp: nowTimestamp(),
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
toSuccess,
|
||||
toFailure,
|
||||
};
|
||||
195
app/lib/api_sign.js
Normal file
195
app/lib/api_sign.js
Normal file
@ -0,0 +1,195 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DEFAULT_IGNORE_KEYS = [ 'sign', 'signature' ];
|
||||
|
||||
/**
|
||||
* 判断输入是否为普通对象。
|
||||
* @param {*} value 任意输入值。
|
||||
* @return {boolean} 是否为普通对象。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将忽略字段列表归一化为小写集合。
|
||||
* @param {string[]} [ignoreKeys=[]] 忽略字段数组。
|
||||
* @return {Set<string>} 小写忽略字段集合。
|
||||
*/
|
||||
function normalizeIgnoreKeySet(ignoreKeys = []) {
|
||||
const rawKeys = Array.isArray(ignoreKeys)
|
||||
? ignoreKeys
|
||||
: [];
|
||||
|
||||
return new Set(rawKeys.map(key => String(key).toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 对任意值做稳定序列化,确保对象键顺序固定。
|
||||
* @param {*} value 待序列化值。
|
||||
* @return {string} 稳定序列化后的字符串。
|
||||
*/
|
||||
function stableStringify(value) {
|
||||
if (value === undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const serializedItems = value.map(item => stableStringify(item));
|
||||
return `[${serializedItems.join(',')}]`;
|
||||
}
|
||||
|
||||
if (!isPlainObject(value)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const keys = Object.keys(value).sort();
|
||||
const serializedFields = keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
|
||||
return `{${serializedFields.join(',')}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化参数值为可拼接字符串。
|
||||
* @param {*} value 参数值。
|
||||
* @return {string} 归一化后的字符串。
|
||||
*/
|
||||
function normalizeParamValue(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
return stableStringify(value);
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建按 key 字母序排列的 query 参数串。
|
||||
* @param {Object} [params={}] 请求 query 参数对象。
|
||||
* @param {string[]} [ignoreKeys=[]] 需要忽略的字段名列表。
|
||||
* @return {string} 规范化后的 query 串,格式为 key=value&key2=value2。
|
||||
*/
|
||||
function buildCanonicalQuery(params = {}, ignoreKeys = []) {
|
||||
if (!isPlainObject(params)) {
|
||||
throw new Error('query 参数必须是对象');
|
||||
}
|
||||
|
||||
const ignoreKeySet = normalizeIgnoreKeySet(ignoreKeys);
|
||||
const keys = Object.keys(params)
|
||||
.filter(key => !ignoreKeySet.has(String(key).toLowerCase()))
|
||||
.filter(key => params[key] !== undefined)
|
||||
.sort();
|
||||
|
||||
return keys.map(key => `${key}=${normalizeParamValue(params[key])}`).join('&');
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建请求体签名,算法为 md5(稳定序列化后的 body)。
|
||||
* @param {*} body 请求体,可为对象、数组、字符串或空值。
|
||||
* @return {string} 小写十六进制 body 签名。
|
||||
*/
|
||||
function buildBodySign(body) {
|
||||
const serializedBody = typeof body === 'string'
|
||||
? body
|
||||
: stableStringify(body);
|
||||
|
||||
return crypto.createHash('md5').update(serializedBody, 'utf8').digest('hex')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算请求签名。
|
||||
* 参与签名字符串 = canonicalQuery + selfAppSecret + bodySign。
|
||||
* 最终签名 = md5(参与签名字符串)。
|
||||
* @param {Object} options 签名参数。
|
||||
* @param {Object} [options.query={}] 请求 query 参数。
|
||||
* @param {*} [options.body] 请求体。
|
||||
* @param {string} options.selfAppSecret 密钥。
|
||||
* @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。
|
||||
* @return {{ canonicalQuery: string, bodySign: string, sign: string }} 计算结果。
|
||||
*/
|
||||
function signRequest({ query = {}, body, selfAppSecret, ignoreKeys } = {}) {
|
||||
const normalizedSecret = String(selfAppSecret || '').trim();
|
||||
if (!normalizedSecret) {
|
||||
throw new Error('selfAppSecret 不能为空');
|
||||
}
|
||||
|
||||
const mergedIgnoreKeys = [ ...DEFAULT_IGNORE_KEYS, ...(Array.isArray(ignoreKeys) ? ignoreKeys : []) ];
|
||||
const canonicalQuery = buildCanonicalQuery(query, mergedIgnoreKeys);
|
||||
const bodySign = buildBodySign(body);
|
||||
const signText = `${canonicalQuery}${normalizedSecret}${bodySign}`;
|
||||
const sign = crypto.createHash('md5').update(signText, 'utf8').digest('hex')
|
||||
.toLowerCase();
|
||||
|
||||
return {
|
||||
canonicalQuery,
|
||||
bodySign,
|
||||
sign,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证请求签名。
|
||||
* @param {Object} options 验签参数。
|
||||
* @param {Object} [options.query={}] 请求 query 参数。
|
||||
* @param {*} [options.body] 请求体。
|
||||
* @param {string} options.providedSign 调用方提供的签名。
|
||||
* @param {string} options.selfAppSecret 密钥。
|
||||
* @param {string[]} [options.ignoreKeys] 需要忽略的 query 字段。
|
||||
* @return {{ ok: boolean, expectedSign: string, providedSign: string, message: string }} 验签结果。
|
||||
*/
|
||||
function verifyRequestSign({ query = {}, body, providedSign, selfAppSecret, ignoreKeys } = {}) {
|
||||
const normalizedProvidedSign = String(providedSign || '').trim().toLowerCase();
|
||||
if (!normalizedProvidedSign) {
|
||||
return {
|
||||
ok: false,
|
||||
expectedSign: '',
|
||||
providedSign: '',
|
||||
message: 'providedSign 不能为空',
|
||||
};
|
||||
}
|
||||
|
||||
let expected;
|
||||
try {
|
||||
expected = signRequest({ query, body, selfAppSecret, ignoreKeys }).sign;
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
expectedSign: '',
|
||||
providedSign: normalizedProvidedSign,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
|
||||
if (expected !== normalizedProvidedSign) {
|
||||
return {
|
||||
ok: false,
|
||||
expectedSign: expected,
|
||||
providedSign: normalizedProvidedSign,
|
||||
message: '签名不匹配',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
expectedSign: expected,
|
||||
providedSign: normalizedProvidedSign,
|
||||
message: '签名验证通过',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_IGNORE_KEYS,
|
||||
buildCanonicalQuery,
|
||||
buildBodySign,
|
||||
signRequest,
|
||||
verifyRequestSign,
|
||||
};
|
||||
38
app/lib/callback_functions.js
Normal file
38
app/lib/callback_functions.js
Normal file
@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 出站回调 method 注册表(代码注册,管理端多选列表经拉取接口透出)。
|
||||
*
|
||||
* method 即出站路由键:wms_api_app.callback_functions 勾选后,
|
||||
* 出站回调按 warehouse_id + method 自动路由到承接该 method 的应用;
|
||||
* callback_functions 为空/未勾选 = 不承接任何回调。
|
||||
*
|
||||
* 新增出站回调能力时在此登记 method,管理端接口自动可见。
|
||||
*/
|
||||
const CALLBACK_FUNCTIONS = [
|
||||
{
|
||||
method: 'notify.reply',
|
||||
name: '站内信通知回执',
|
||||
description: '站内信/系统通知/回执出站推送(warehouseNotify 与 inbox 回执共用)',
|
||||
},
|
||||
{
|
||||
method: 'waybill.getreceive',
|
||||
name: '运单揽收状态查询',
|
||||
description: '按运单号批量查询是否已揽收:请求 { waybill_codes: [...] },'
|
||||
+ '外部返回 [{ waybill_code, is_galaxy_receive: 1|0 }],回写 wms_order_express.is_galaxy_receive',
|
||||
},
|
||||
{
|
||||
method: 'waybill.getTrace',
|
||||
name: '运单物流轨迹查询',
|
||||
description: '按运单号查询物流轨迹(实时回源,不落库):请求 { waybill_codes: [运单号] },'
|
||||
+ '外部返回 [{ waybillNo, trace: { opTime, outBizCode, memo, opOrgCityName, weight, scanType } }]',
|
||||
},
|
||||
];
|
||||
|
||||
/** method 合法值集合(供管理端 create/update 校验) */
|
||||
const CALLBACK_METHOD_SET = new Set(CALLBACK_FUNCTIONS.map(item => item.method));
|
||||
|
||||
module.exports = {
|
||||
CALLBACK_FUNCTIONS,
|
||||
CALLBACK_METHOD_SET,
|
||||
};
|
||||
330
app/lib/delivery_order_summary.js
Normal file
330
app/lib/delivery_order_summary.js
Normal file
@ -0,0 +1,330 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 配送订单每日汇总纯函数工具(无 egg / DB 依赖,可单测)。
|
||||
*
|
||||
* 口径约定:
|
||||
* 1. 日期维度为本地时区自然日(yyyy-MM-dd),区间左闭右开 [start, end+1day);
|
||||
* 2. 缺省统计区间为「结束日往前 7 个自然日」(含结束日);
|
||||
* 3. 单次最多 {@link MAX_DAY_COUNT} 天,避免跨过订单归档边界(history 分表不参与统计);
|
||||
* 4. 每日指标缺失时补 0,保证前端按日绘图的连续性。
|
||||
*/
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
|
||||
/** 缺省统计天数(含结束日)。 */
|
||||
const DEFAULT_DAY_COUNT = 7;
|
||||
/** 单次查询最大天数。 */
|
||||
const MAX_DAY_COUNT = 90;
|
||||
|
||||
/** 每日指标字段清单(顺序即响应字段顺序)。 */
|
||||
const METRIC_FIELDS = Object.freeze([
|
||||
'order_count',
|
||||
'dispatch_count',
|
||||
'shipped_count',
|
||||
'shipped_items_total',
|
||||
'shipped_amount',
|
||||
'intercepted_count',
|
||||
'intercepted_at_warehouse_count',
|
||||
'cancelled_count',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 两位补零。
|
||||
* @param {number} value 数值。
|
||||
* @return {string} 补零字符串。
|
||||
*/
|
||||
function pad2(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地时区格式化为 yyyy-MM-dd。
|
||||
* @param {Date} date 日期对象。
|
||||
* @return {string} 格式化结果。
|
||||
*/
|
||||
function formatDate(date) {
|
||||
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造日期偏移(按本地年月日加减,规避夏令时步进偏差)。
|
||||
* @param {Date} date 基准日期。
|
||||
* @param {number} days 偏移天数(可为负)。
|
||||
* @return {Date} 偏移后的日期(00:00:00.000)。
|
||||
*/
|
||||
function addDays(date, days) {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两个日期相差的自然日数量(按 UTC 年月日归一化,忽略时分秒)。
|
||||
* @param {Date} start 开始日期。
|
||||
* @param {Date} end 结束日期。
|
||||
* @return {number} 相差天数(end - start)。
|
||||
*/
|
||||
function diffDays(start, end) {
|
||||
const startDay = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate()) / DAY_MS;
|
||||
const endDay = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate()) / DAY_MS;
|
||||
return endDay - startDay;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 yyyy-MM-dd(兼容 yyyy-MM-dd HH:mm:ss 等带时间后缀的入参)。
|
||||
* @param {*} value 待解析值(字符串 / Date)。
|
||||
* @return {Date|null} 本地时区 00:00:00.000 的日期;无法解析时返回 null。
|
||||
*/
|
||||
function parseDateOnly(value) {
|
||||
if (value instanceof Date) {
|
||||
return Number.isNaN(value.getTime())
|
||||
? null
|
||||
: new Date(value.getFullYear(), value.getMonth(), value.getDate());
|
||||
}
|
||||
|
||||
const text = String(value === null || value === undefined ? '' : value).trim();
|
||||
if (!text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const matched = DATE_PATTERN.exec(text.slice(0, 10));
|
||||
if (!matched) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const year = Number(matched[1]);
|
||||
const month = Number(matched[2]);
|
||||
const day = Number(matched[3]);
|
||||
const candidate = new Date(year, month - 1, day);
|
||||
if (
|
||||
candidate.getFullYear() !== year
|
||||
|| candidate.getMonth() !== month - 1
|
||||
|| candidate.getDate() !== day
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造统计区间非法错误。
|
||||
* @param {string} message 错误文案。
|
||||
* @return {Error} 带 INVALID_SUMMARY_RANGE 错误码的异常。
|
||||
*/
|
||||
function buildRangeError(message) {
|
||||
const error = new Error(message);
|
||||
error.code = 'INVALID_SUMMARY_RANGE';
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并校验统计区间。
|
||||
*
|
||||
* 规则:
|
||||
* - 仅传 endDate:startDate = endDate - (DEFAULT_DAY_COUNT - 1) 天;
|
||||
* - 仅传 startDate:endDate = 今天;
|
||||
* - 都不传:最近 DEFAULT_DAY_COUNT 个自然日(含今天);
|
||||
* - startDate 晚于 endDate、区间超过 MAX_DAY_COUNT 天、格式非法均抛错。
|
||||
*
|
||||
* @param {Object} [options={}] 入参。
|
||||
* @param {*} [options.startDate] 开始日期(yyyy-MM-dd)。
|
||||
* @param {*} [options.endDate] 结束日期(yyyy-MM-dd)。
|
||||
* @param {Date} [options.now=new Date()] 当前时间(便于单测注入)。
|
||||
* @return {{start: Date, end: Date, endExclusive: Date, startDate: string, endDate: string, dayCount: number}} 区间信息。
|
||||
*/
|
||||
function resolveSummaryRange({ startDate = null, endDate = null, now = new Date() } = {}) {
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const hasStart = String(startDate === null || startDate === undefined ? '' : startDate).trim() !== '';
|
||||
const hasEnd = String(endDate === null || endDate === undefined ? '' : endDate).trim() !== '';
|
||||
const parsedStart = parseDateOnly(startDate);
|
||||
const parsedEnd = parseDateOnly(endDate);
|
||||
|
||||
if (hasStart && !parsedStart) {
|
||||
throw buildRangeError('开始日期格式不正确,应为 yyyy-MM-dd');
|
||||
}
|
||||
if (hasEnd && !parsedEnd) {
|
||||
throw buildRangeError('结束日期格式不正确,应为 yyyy-MM-dd');
|
||||
}
|
||||
|
||||
const end = parsedEnd || todayStart;
|
||||
const start = parsedStart || addDays(end, -(DEFAULT_DAY_COUNT - 1));
|
||||
|
||||
if (start.getTime() > end.getTime()) {
|
||||
throw buildRangeError('开始日期不能晚于结束日期');
|
||||
}
|
||||
|
||||
const dayCount = diffDays(start, end) + 1;
|
||||
if (dayCount > MAX_DAY_COUNT) {
|
||||
throw buildRangeError(`汇总天数不能超过 ${MAX_DAY_COUNT} 天`);
|
||||
}
|
||||
|
||||
return {
|
||||
start,
|
||||
end,
|
||||
endExclusive: addDays(end, 1),
|
||||
startDate: formatDate(start),
|
||||
endDate: formatDate(end),
|
||||
dayCount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成区间内逐日日期键(含首尾)。
|
||||
* @param {Date} start 开始日期。
|
||||
* @param {Date} end 结束日期(含)。
|
||||
* @return {Array<string>} yyyy-MM-dd 列表。
|
||||
*/
|
||||
function buildDateKeys(start, end) {
|
||||
const total = diffDays(start, end) + 1;
|
||||
const keys = [];
|
||||
for (let index = 0; index < total; index += 1) {
|
||||
keys.push(formatDate(addDays(start, index)));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建全零的每日指标对象。
|
||||
* @return {Object} 指标对象。
|
||||
*/
|
||||
function createEmptyMetrics() {
|
||||
const metrics = {};
|
||||
for (const field of METRIC_FIELDS) {
|
||||
metrics[field] = 0;
|
||||
}
|
||||
return metrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按日期键初始化每日指标映射。
|
||||
* @param {Array<string>} dateKeys 日期键列表。
|
||||
* @return {Map<string, Object>} 日期键到指标对象的映射。
|
||||
*/
|
||||
function buildDailyMap(dateKeys) {
|
||||
const dailyMap = new Map();
|
||||
for (const key of dateKeys) {
|
||||
dailyMap.set(key, createEmptyMetrics());
|
||||
}
|
||||
return dailyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化聚合行返回的日期值(MySQL DATE() 可能返回字符串或 Date 实例)。
|
||||
* @param {*} value 原始日期值。
|
||||
* @return {string} yyyy-MM-dd;无法识别时返回空串。
|
||||
*/
|
||||
function normalizeRowDate(value) {
|
||||
if (value instanceof Date) {
|
||||
return Number.isNaN(value.getTime()) ? '' : formatDate(value);
|
||||
}
|
||||
const text = String(value === null || value === undefined ? '' : value).trim();
|
||||
return text.slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 数值安全转换。
|
||||
* @param {*} value 原始值。
|
||||
* @return {number} 数值;非法值按 0 处理。
|
||||
*/
|
||||
function toNumber(value) {
|
||||
const num = Number(value);
|
||||
return Number.isFinite(num) ? num : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 金额保留两位小数。
|
||||
* @param {*} value 原始值。
|
||||
* @return {number} 保留两位小数的金额。
|
||||
*/
|
||||
function roundAmount(value) {
|
||||
return Math.round(toNumber(value) * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并按日计数的聚合行到每日映射(区间外日期忽略)。
|
||||
* @param {Map<string, Object>} dailyMap 每日映射。
|
||||
* @param {Array<Object>} rows 聚合行(date / count)。
|
||||
* @param {string} field 目标指标字段。
|
||||
* @return {Map<string, Object>} 同一映射。
|
||||
*/
|
||||
function addCountRows(dailyMap, rows, field) {
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
for (const row of list) {
|
||||
const target = dailyMap.get(normalizeRowDate(row && row.date));
|
||||
if (target) {
|
||||
target[field] += toNumber(row.count);
|
||||
}
|
||||
}
|
||||
return dailyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并发货聚合行(订单数 / 商品件数 / 金额)到每日映射。
|
||||
* @param {Map<string, Object>} dailyMap 每日映射。
|
||||
* @param {Array<Object>} rows 聚合行(date / count / items_total / amount)。
|
||||
* @return {Map<string, Object>} 同一映射。
|
||||
*/
|
||||
function addShippedRows(dailyMap, rows) {
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
for (const row of list) {
|
||||
const target = dailyMap.get(normalizeRowDate(row && row.date));
|
||||
if (!target) {
|
||||
continue;
|
||||
}
|
||||
target.shipped_count += toNumber(row.count);
|
||||
target.shipped_items_total += toNumber(row.items_total);
|
||||
target.shipped_amount += toNumber(row.amount);
|
||||
}
|
||||
return dailyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按日期顺序输出每日行,金额统一保留两位小数。
|
||||
* @param {Array<string>} dateKeys 日期键列表。
|
||||
* @param {Map<string, Object>} dailyMap 每日映射。
|
||||
* @return {Array<Object>} 每日汇总行。
|
||||
*/
|
||||
function finalizeDailyRows(dateKeys, dailyMap) {
|
||||
return dateKeys.map(date => {
|
||||
const metrics = dailyMap.get(date) || createEmptyMetrics();
|
||||
return {
|
||||
date,
|
||||
...metrics,
|
||||
shipped_amount: roundAmount(metrics.shipped_amount),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总每日行,输出区间合计。
|
||||
* @param {Array<Object>} rows 每日汇总行。
|
||||
* @return {Object} 合计指标。
|
||||
*/
|
||||
function summarizeRows(rows) {
|
||||
const summary = createEmptyMetrics();
|
||||
for (const row of (Array.isArray(rows) ? rows : [])) {
|
||||
for (const field of METRIC_FIELDS) {
|
||||
summary[field] += toNumber(row && row[field]);
|
||||
}
|
||||
}
|
||||
summary.shipped_amount = roundAmount(summary.shipped_amount);
|
||||
return summary;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_DAY_COUNT,
|
||||
MAX_DAY_COUNT,
|
||||
METRIC_FIELDS,
|
||||
formatDate,
|
||||
addDays,
|
||||
parseDateOnly,
|
||||
resolveSummaryRange,
|
||||
buildDateKeys,
|
||||
createEmptyMetrics,
|
||||
buildDailyMap,
|
||||
normalizeRowDate,
|
||||
addCountRows,
|
||||
addShippedRows,
|
||||
finalizeDailyRows,
|
||||
summarizeRows,
|
||||
};
|
||||
303
app/lib/express_print_payload_builder.js
Normal file
303
app/lib/express_print_payload_builder.js
Normal file
@ -0,0 +1,303 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const PrinterDataBuilder = require('./printer_data_builder');
|
||||
|
||||
const TEMPLATE_CACHE = new Map();
|
||||
|
||||
/**
|
||||
* 判断是否为普通对象。
|
||||
* @param {any} value 待判断值。
|
||||
* @return {boolean} 判断结果。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 以 JSON 方式做深拷贝,避免污染模板缓存对象。
|
||||
* @param {Object} source 原对象。
|
||||
* @return {Object} 深拷贝结果。
|
||||
*/
|
||||
function deepClone(source) {
|
||||
return JSON.parse(JSON.stringify(source));
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求内 ID 生成器。
|
||||
*/
|
||||
class RequestScopedPrintIdGenerator {
|
||||
/**
|
||||
* @param {string} requestCode 前端请求参数码。
|
||||
*/
|
||||
constructor(requestCode) {
|
||||
this.requestCode = String(requestCode || '').trim();
|
||||
this.sequence = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成请求 ID。
|
||||
* @return {string} 唯一请求 ID。
|
||||
*/
|
||||
nextRequestId() {
|
||||
return this.next('request');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成任务 ID。
|
||||
* @return {string} 唯一任务 ID。
|
||||
*/
|
||||
nextTaskId() {
|
||||
return this.next('task');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成文档 ID。
|
||||
* @return {string} 唯一文档 ID。
|
||||
*/
|
||||
nextDocumentId() {
|
||||
return this.next('document');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带前缀的递增 ID。
|
||||
* @param {string} prefix ID 前缀。
|
||||
* @return {string} 生成结果。
|
||||
*/
|
||||
next(prefix) {
|
||||
this.sequence += 1;
|
||||
return `${this.requestCode}_${prefix}_${this.sequence}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 快递打印请求组装器。
|
||||
*/
|
||||
class ExpressPrintPayloadBuilder {
|
||||
/**
|
||||
* @param {Object} options 初始化参数。
|
||||
* @param {string} options.baseDir 项目根目录。
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
const requestOptions = isPlainObject(options) ? options : {};
|
||||
this.baseDir = String(requestOptions.baseDir || process.cwd());
|
||||
this.templateDir = path.join(this.baseDir, 'printer_data_template');
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装平台快递打印 payload。
|
||||
* @param {Object} options 组装参数。
|
||||
* @param {string} options.platform 平台编码。
|
||||
* @param {string} options.printerName 打印机名称。
|
||||
* @param {Array<Object>} options.orders 外部传入的订单打印数据数组。
|
||||
* @param {RequestScopedPrintIdGenerator} options.idGenerator 请求内 ID 生成器。
|
||||
* @return {Object} 可直接发送给打印服务的 payload。
|
||||
*/
|
||||
buildPayload(options = {}) {
|
||||
const requestOptions = isPlainObject(options) ? options : {};
|
||||
const platform = String(requestOptions.platform || '').trim();
|
||||
const normalizedPlatform = this.normalizePlatform(platform);
|
||||
if (!platform) {
|
||||
throw new Error('快递打印缺少平台标识');
|
||||
}
|
||||
|
||||
const idGenerator = requestOptions.idGenerator;
|
||||
if (!idGenerator || typeof idGenerator.nextRequestId !== 'function') {
|
||||
throw new Error('快递打印缺少请求 ID 生成器');
|
||||
}
|
||||
|
||||
const printerName = String(requestOptions.printerName || '').trim();
|
||||
if (!printerName) {
|
||||
throw new Error('快递打印缺少打印机名称');
|
||||
}
|
||||
|
||||
const orders = Array.isArray(requestOptions.orders) ? requestOptions.orders : [];
|
||||
if (orders.length === 0) {
|
||||
throw new Error('快递打印缺少订单数据');
|
||||
}
|
||||
|
||||
const payload = this.loadTemplate(platform);
|
||||
|
||||
const requestId = idGenerator.nextRequestId();
|
||||
this.applyRequestId(payload, requestId);
|
||||
payload.printer = printerName;
|
||||
|
||||
if (Array.isArray(payload.taskList)) {
|
||||
payload.taskList.forEach(item => {
|
||||
if (isPlainObject(item)) {
|
||||
item.printer = printerName;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (normalizedPlatform === 'sph') {
|
||||
payload.taskList = this.buildTaskListFromOrders(orders, idGenerator);
|
||||
} else {
|
||||
if (!isPlainObject(payload.task)) {
|
||||
payload.task = {};
|
||||
}
|
||||
payload.task.taskID = idGenerator.nextTaskId();
|
||||
payload.task.printer = printerName;
|
||||
payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator);
|
||||
}
|
||||
|
||||
if (normalizedPlatform === 'jd') {
|
||||
this.mergeJdParametersContents(payload, printerName);
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将京东平台模板参数中的 contents 替换为订单实际内容。
|
||||
* @param {Object} payload 打印请求 payload。
|
||||
* @param {string} printerName 打印机名称。
|
||||
*/
|
||||
mergeJdParametersContents(payload, printerName) {
|
||||
if (!isPlainObject(payload.parameters)) {
|
||||
payload.parameters = {};
|
||||
}
|
||||
|
||||
payload.parameters.printName = printerName;
|
||||
|
||||
const documents = Array.isArray(payload.task && payload.task.documents) ? payload.task.documents : [];
|
||||
payload.parameters.contents = documents.map(document => {
|
||||
if (!isPlainObject(document) || !Array.isArray(document.contents) || !document.contents[0]) {
|
||||
return {};
|
||||
}
|
||||
return deepClone(document.contents[0]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 orders 映射为 SPH taskList 项。
|
||||
* SPH 的 task item 结构(taskID / printInfo / customInfo / extendData 等)与通用 document 结构不兼容,
|
||||
* 因此需要独立的构建方法,但处理模式与 buildDocumentsFromOrders 一致:
|
||||
* 遍历 orders → deepClone → 分配唯一 ID → 放入数组。
|
||||
*
|
||||
* @param {Array<Object>} orders 订单数组,每个元素直接是 SPH task item 对象。
|
||||
* @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。
|
||||
* @return {Array<Object>} taskList 数组。
|
||||
*/
|
||||
buildTaskListFromOrders(orders, idGenerator) {
|
||||
const taskList = [];
|
||||
for (const order of orders) {
|
||||
if (order && typeof order === 'object' && !Array.isArray(order)) {
|
||||
const taskItem = deepClone(order);
|
||||
taskItem.taskID = idGenerator.nextTaskId();
|
||||
taskList.push(taskItem);
|
||||
}
|
||||
}
|
||||
return taskList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 orders 映射为 documents。
|
||||
* @param {Array<Object>} orders 订单数组。
|
||||
* @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。
|
||||
* @return {Array<Object>} documents 数组。
|
||||
*/
|
||||
buildDocumentsFromOrders(orders, idGenerator) {
|
||||
return orders.map((order, index) => {
|
||||
const sourceDocument = this.resolveOrderDocument(order, index);
|
||||
const document = deepClone(sourceDocument);
|
||||
if (!Array.isArray(document.contents)) {
|
||||
document.contents = [];
|
||||
}
|
||||
document.documentID = idGenerator.nextDocumentId();
|
||||
return document;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析单个订单对应的 document。
|
||||
* @param {Object} order 订单对象。
|
||||
* @param {number} index 订单索引。
|
||||
* @return {Object} document 对象。
|
||||
*/
|
||||
resolveOrderDocument(order, index) {
|
||||
if (!isPlainObject(order)) {
|
||||
throw new Error(`orders[${index}] 必须是对象`);
|
||||
}
|
||||
|
||||
const printData = isPlainObject(order.print_data) ? order.print_data : order;
|
||||
if (!isPlainObject(printData)) {
|
||||
throw new Error(`orders[${index}] 缺少 print_data`);
|
||||
}
|
||||
|
||||
const hasDocumentShape = Object.prototype.hasOwnProperty.call(printData, 'documentID')
|
||||
|| Array.isArray(printData.contents);
|
||||
if (!hasDocumentShape) {
|
||||
throw new Error(`orders[${index}] 的 print_data 不是有效 document 结构`);
|
||||
}
|
||||
|
||||
return printData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入请求 ID,兼容 requestID / requetID 两种字段。
|
||||
* @param {Object} payload 请求 payload。
|
||||
* @param {string} requestId 请求 ID。
|
||||
*/
|
||||
applyRequestId(payload, requestId) {
|
||||
const hasRequestId = Object.prototype.hasOwnProperty.call(payload, 'requestID');
|
||||
const hasRequetId = Object.prototype.hasOwnProperty.call(payload, 'requetID');
|
||||
|
||||
if (hasRequestId) {
|
||||
payload.requestID = requestId;
|
||||
}
|
||||
if (hasRequetId) {
|
||||
payload.requetID = requestId;
|
||||
}
|
||||
if (!hasRequestId && !hasRequetId) {
|
||||
payload.requestID = requestId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载并缓存平台模板,然后返回深拷贝对象。
|
||||
* @param {string} platform 平台编码。
|
||||
* @return {Object} 模板拷贝。
|
||||
*/
|
||||
loadTemplate(platform) {
|
||||
const normalizedPlatform = this.normalizePlatform(platform);
|
||||
const templatePath = path.join(this.templateDir, `${normalizedPlatform}.json`);
|
||||
if (!TEMPLATE_CACHE.has(templatePath)) {
|
||||
let templateContent = '';
|
||||
try {
|
||||
templateContent = fs.readFileSync(templatePath, 'utf8');
|
||||
} catch (error) {
|
||||
throw new Error(`未找到平台模板: ${normalizedPlatform}.json`);
|
||||
}
|
||||
|
||||
let templateData;
|
||||
try {
|
||||
templateData = JSON.parse(templateContent);
|
||||
} catch (error) {
|
||||
throw new Error(`平台模板 JSON 解析失败: ${normalizedPlatform}.json`);
|
||||
}
|
||||
TEMPLATE_CACHE.set(templatePath, templateData);
|
||||
}
|
||||
|
||||
return deepClone(TEMPLATE_CACHE.get(templatePath));
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化平台编码。
|
||||
* @param {string} platform 平台编码或别名。
|
||||
* @return {string} 规范化平台编码。
|
||||
*/
|
||||
normalizePlatform(platform) {
|
||||
const normalized = PrinterDataBuilder.normalizePlatformAlias(platform);
|
||||
if (normalized && normalized.platform) {
|
||||
return normalized.platform;
|
||||
}
|
||||
return String(platform || '').trim().toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ExpressPrintPayloadBuilder,
|
||||
RequestScopedPrintIdGenerator,
|
||||
};
|
||||
1574
app/lib/file_writer.js
Normal file
1574
app/lib/file_writer.js
Normal file
File diff suppressed because it is too large
Load Diff
54
app/lib/inbox_channel.js
Normal file
54
app/lib/inbox_channel.js
Normal file
@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 站内信 IM 渠道来源工具。
|
||||
*
|
||||
* 群ID 格式与渠道来源一一对应(生产 11 万+ 入站消息 100% 满足该对应关系):
|
||||
* - `xxx@chatroom` 结尾 → wx(个人微信)
|
||||
* - 纯数字(如 10845468709699144)→ qiwe(企业微信)
|
||||
*
|
||||
* ext_data.source 决定回执/通知透传给哪个桥接渠道;一旦与群ID格式不符,
|
||||
* 回执会被投递到错误渠道(典型现象:wx 群用 qiwe 渠道投递 → "qiwe offline" 503)。
|
||||
*/
|
||||
|
||||
/** 个人微信群ID 后缀 */
|
||||
const WX_GROUP_ID_SUFFIX = '@chatroom';
|
||||
|
||||
/**
|
||||
* 按群ID格式推导渠道来源。
|
||||
* @param {string} groupId 外部群ID。
|
||||
* @return {string|null} wx / qiwe;无法判定时返回 null。
|
||||
*/
|
||||
function resolveChannelSource(groupId) {
|
||||
const id = String(groupId || '').trim();
|
||||
if (!id) return null;
|
||||
if (id.endsWith(WX_GROUP_ID_SUFFIX)) return 'wx';
|
||||
if (/^\d+$/.test(id)) return 'qiwe';
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按群ID格式校正 ext_data.source(不修改入参)。
|
||||
* 仅在 ext_data 已带 source 且与群ID格式不符时返回新对象;
|
||||
* 无 ext_data / 无 source / 群ID无法判定 / 已一致时原样返回。
|
||||
* @param {string} groupId 外部群ID。
|
||||
* @param {Object|null} extData 原始透传数据。
|
||||
* @return {Object|null} 校正后的透传数据。
|
||||
*/
|
||||
function normalizeExtDataSource(groupId, extData) {
|
||||
if (!extData || typeof extData !== 'object' || Array.isArray(extData)) {
|
||||
return extData || null;
|
||||
}
|
||||
const expected = resolveChannelSource(groupId);
|
||||
const current = extData.source;
|
||||
if (!expected || !current || current === expected) {
|
||||
return extData;
|
||||
}
|
||||
return { ...extData, source: expected };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
WX_GROUP_ID_SUFFIX,
|
||||
resolveChannelSource,
|
||||
normalizeExtDataSource,
|
||||
};
|
||||
200
app/lib/intercept_guard.js
Normal file
200
app/lib/intercept_guard.js
Normal file
@ -0,0 +1,200 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单拦截状态共享定义。
|
||||
*
|
||||
* wms_order_delivery.intercept_status 枚举(order_delivery.js / order_delivery_factory.js)实际取值为:
|
||||
* none / requesting / requested / intercepting / intercepted_in_transit / intercepted_at_warehouse /
|
||||
* returning / returned / delivered_by_mistake / timeout / cancelled / failed / exception。
|
||||
*
|
||||
* 业务约定:拦截状态只要不是 'none'(即任意进入拦截流程/拦截结果的状态),一律视为"已拦截",
|
||||
* 禁止继续执行仓储作业(分配波次/分配储位/分配快递/打印/抓取波次/拣货/复核/打包/称重/绑定包材等),
|
||||
* 被拦截订单一律跳过。
|
||||
*/
|
||||
const INTERCEPT_STATUS_NONE = 'none';
|
||||
|
||||
/**
|
||||
* 判断订单拦截状态是否属于"已拦截"。
|
||||
* 空值/NULL 归一化为 none 处理;除此之外任何非 none 状态(含 requested/intercepting/intercepted_*、
|
||||
* returning/returned/cancelled/failed/exception 等)均视为已拦截。
|
||||
* @param {*} status 拦截状态值。
|
||||
* @return {boolean} 是否已拦截。
|
||||
*/
|
||||
function isInterceptedOrderStatus(status) {
|
||||
const normalizedStatus = String(status || '').trim() || INTERCEPT_STATUS_NONE;
|
||||
return normalizedStatus !== INTERCEPT_STATUS_NONE;
|
||||
}
|
||||
|
||||
/** 团购波次类型。 */
|
||||
const WAVE_TYPE_GROUP_BUY = 1;
|
||||
|
||||
/** 散单波次类型。 */
|
||||
const WAVE_TYPE_SCATTER = 2;
|
||||
|
||||
/**
|
||||
* 返回不允许写入拦截请求状态(requested / intercepting)的阻断原因文案;空字符串表示允许写入。
|
||||
*
|
||||
* 规则:
|
||||
* - 团购波次(wave_type=1):inspection_status === 'fin'(已复核)→ 不允许写入拦截请求状态;
|
||||
* - 散单波次(wave_type=2):weighing_weight > 0(已称重)→ 不允许写入拦截请求状态;
|
||||
* - 其余情况(无波次 / 其他波次类型 / 未复核 / 未称重)不阻断。
|
||||
*
|
||||
* @param {Object} params 参数。
|
||||
* @param {number|string} [params.waveType] 波次类型。
|
||||
* @param {string} [params.inspectionStatus] 订单复核状态。
|
||||
* @param {number|string} [params.weighingWeight] 散单称重重量。
|
||||
* @return {string} 阻断原因;空字符串表示允许写入。
|
||||
*/
|
||||
function getInterceptRequestBlockReason({ waveType, inspectionStatus, weighingWeight } = {}) {
|
||||
const normalizedWaveType = Number(waveType || 0);
|
||||
if (normalizedWaveType === WAVE_TYPE_GROUP_BUY) {
|
||||
return String(inspectionStatus || '').trim() === 'fin' ? '团购单已复核' : '';
|
||||
}
|
||||
if (normalizedWaveType === WAVE_TYPE_SCATTER) {
|
||||
return Number(weighingWeight || 0) > 0 ? '散单已称重' : '';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断订单是否因「团购已复核 / 散单已称重」而不允许写入拦截请求状态。
|
||||
*
|
||||
* @param {Object} params 参数,同 getInterceptRequestBlockReason。
|
||||
* @return {boolean} true 表示不允许写入拦截请求状态。
|
||||
*/
|
||||
function isInterceptRequestBlockedByRecheckOrWeigh(params = {}) {
|
||||
return getInterceptRequestBlockReason(params) !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取单订单的拦截请求前置校验信息(波次类型 + 散单称重重量)。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Object} params 参数。
|
||||
* @param {number|string} params.orderId 订单 ID。
|
||||
* @param {number|string} [params.waveId] 波次 ID。
|
||||
* @param {number|string} params.warehouseId 仓库 ID。
|
||||
* @param {Object} [params.transaction] 可选事务对象。
|
||||
* @return {Promise<{ waveType: number, weighingWeight: number }>} 校验信息。
|
||||
*/
|
||||
async function resolveInterceptRequestGuardInfo(ctx, params = {}) {
|
||||
const { orderId, waveId, warehouseId, transaction } = params;
|
||||
let waveType = 0;
|
||||
if (Number(waveId || 0) > 0 && ctx && ctx.model && ctx.model.WaveBatch) {
|
||||
try {
|
||||
const waveRow = await ctx.model.WaveBatch.findOne({
|
||||
where: { wave_id: Number(waveId), warehouse_id: warehouseId },
|
||||
attributes: [ 'wave_id', 'wave_type' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
waveType = Number(waveRow && waveRow.wave_type || 0);
|
||||
} catch (error) { /* 查询失败不阻断主流程,按无波次处理 */ }
|
||||
}
|
||||
|
||||
let weighingWeight = 0;
|
||||
if (ctx && ctx.model && ctx.model.OrderExpress) {
|
||||
try {
|
||||
// 强制同仓校验:读取称重重量必须同时带订单ID与仓库ID,禁止跨仓串读
|
||||
const expressRows = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
order_id: Number(orderId || 0),
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'weighing_weight' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
for (const row of (Array.isArray(expressRows) ? expressRows : [])) {
|
||||
weighingWeight = Math.max(weighingWeight, Number(row && row.weighing_weight || 0));
|
||||
}
|
||||
} catch (error) { /* 查询失败不阻断主流程,按未称重处理 */ }
|
||||
}
|
||||
|
||||
return { waveType, weighingWeight };
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量拉取订单的拦截请求前置校验信息(波次类型 + 散单称重重量)。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @param {Object} params 参数。
|
||||
* @param {Array<Object>} params.orderRows 订单行数组(需含 id、wave_id 字段)。
|
||||
* @param {number|string} params.warehouseId 仓库 ID。
|
||||
* @param {Object} [params.transaction] 可选事务对象。
|
||||
* @return {Promise<Map<number, { waveType: number, weighingWeight: number }>>} 按订单 ID 索引的校验信息。
|
||||
*/
|
||||
async function resolveInterceptRequestGuardInfoMap(ctx, params = {}) {
|
||||
const orderRows = Array.isArray(params.orderRows) ? params.orderRows : [];
|
||||
const { warehouseId, transaction } = params;
|
||||
|
||||
const infoMap = new Map();
|
||||
if (orderRows.length === 0 || !ctx) {
|
||||
return infoMap;
|
||||
}
|
||||
|
||||
const orderIds = orderRows
|
||||
.map(row => Number(row && row.id || 0))
|
||||
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
|
||||
const waveIds = [ ...new Set(orderRows
|
||||
.map(row => Number(row && row.wave_id || 0))
|
||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
|
||||
|
||||
for (const orderId of orderIds) {
|
||||
infoMap.set(orderId, { waveType: 0, weighingWeight: 0 });
|
||||
}
|
||||
|
||||
if (waveIds.length > 0 && ctx.model && ctx.model.WaveBatch) {
|
||||
try {
|
||||
const { Op } = ctx.app && ctx.app.Sequelize || {};
|
||||
const waves = await ctx.model.WaveBatch.findAll({
|
||||
where: { wave_id: { [Op.in]: waveIds }, warehouse_id: warehouseId },
|
||||
attributes: [ 'wave_id', 'wave_type' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const waveTypeMap = new Map((Array.isArray(waves) ? waves : [])
|
||||
.map(wave => [ Number(wave && wave.wave_id || 0), Number(wave && wave.wave_type || 0) ]));
|
||||
for (const row of orderRows) {
|
||||
const info = infoMap.get(Number(row.id));
|
||||
if (info) {
|
||||
info.waveType = waveTypeMap.get(Number(row.wave_id || 0)) || 0;
|
||||
}
|
||||
}
|
||||
} catch (error) { /* 查询失败不阻断主流程,按无波次处理 */ }
|
||||
}
|
||||
|
||||
if (orderIds.length > 0 && ctx.model && ctx.model.OrderExpress) {
|
||||
try {
|
||||
const { Op } = ctx.app && ctx.app.Sequelize || {};
|
||||
const expressRows = await ctx.model.OrderExpress.findAll({
|
||||
where: { order_id: { [Op.in]: orderIds }, warehouse_id: warehouseId },
|
||||
attributes: [ 'order_id', 'weighing_weight' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
for (const expressRow of (Array.isArray(expressRows) ? expressRows : [])) {
|
||||
const info = infoMap.get(Number(expressRow && expressRow.order_id || 0));
|
||||
if (info) {
|
||||
info.weighingWeight = Math.max(
|
||||
info.weighingWeight,
|
||||
Number(expressRow && expressRow.weighing_weight || 0)
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) { /* 查询失败不阻断主流程,按未称重处理 */ }
|
||||
}
|
||||
|
||||
return infoMap;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
INTERCEPT_STATUS_NONE,
|
||||
isInterceptedOrderStatus,
|
||||
WAVE_TYPE_GROUP_BUY,
|
||||
WAVE_TYPE_SCATTER,
|
||||
getInterceptRequestBlockReason,
|
||||
isInterceptRequestBlockedByRecheckOrWeigh,
|
||||
resolveInterceptRequestGuardInfo,
|
||||
resolveInterceptRequestGuardInfoMap,
|
||||
};
|
||||
82
app/lib/intercept_time.js
Normal file
82
app/lib/intercept_time.js
Normal file
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 通知拦截时间(wms_order_delivery.intercept_time)字段口径工具(纯函数,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 背景:`intercept_time` 语义原为「进入拦截流程/库内拦截确认时写入」,
|
||||
* 确认拦截会覆盖发起时刻,导致「通知拦截时间」丢失、且无法与「库内确定拦截时刻」区分。
|
||||
*
|
||||
* 自 2026-09-10 起统一为「最近一次发起拦截的通知时刻」:
|
||||
* 1. 发起/通知拦截:**首次写入**(当前时间);重复发起**不覆盖**已有值;
|
||||
* 2. 库内拦截确认(confirmIntercept / 拦截扫描 / 自动确认)、退回入库(returned):**不写该字段**(不覆盖);
|
||||
* 3. 取消/解除拦截(batchUnintercept)与订单克隆重置:**置空 null**;
|
||||
* 4. 因此「库内确定拦截时刻」不再使用本字段,改用配送表 `dispath_time`(订单迁移进配送表的时间,
|
||||
* 库内确定拦截后基本都会走迁移)。
|
||||
*/
|
||||
|
||||
/** 字段名常量 */
|
||||
const INTERCEPT_TIME_FIELD = 'intercept_time';
|
||||
|
||||
/**
|
||||
* 判断通知拦截时间是否为空(null/undefined/空串)。
|
||||
* @param {*} value 字段值
|
||||
* @return {boolean} 是否为空
|
||||
*/
|
||||
function isEmptyInterceptTime(value) {
|
||||
return value === null || value === undefined || value === '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造发起拦截时的更新片段:仅当当前值为空时才写入通知拦截时间(首次写入,不覆盖)。
|
||||
*
|
||||
* 用法(实例更新,实例行需能取到 intercept_time):
|
||||
* ```js
|
||||
* await order.update({ intercept_status: 'requested', ...buildNoticeTimePatch(order.intercept_time), updated_at: now });
|
||||
* ```
|
||||
*
|
||||
* @param {*} currentValue 订单当前 intercept_time
|
||||
* @param {Date} [now=new Date()] 本次通知时刻
|
||||
* @return {Object} 需要写入的字段片段;已有值时返回空对象(不覆盖)
|
||||
*/
|
||||
function buildNoticeTimePatch(currentValue, now = new Date()) {
|
||||
return isEmptyInterceptTime(currentValue) ? { [INTERCEPT_TIME_FIELD]: now } : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从订单行中筛出「尚未写入通知拦截时间」的订单ID(批量写入用)。
|
||||
*
|
||||
* 用法(批量更新):主更新不写 intercept_time,随后仅对返回的订单ID写一次通知时刻:
|
||||
* ```js
|
||||
* const fillIds = pickNoticeTimeOrderIds(orderRows);
|
||||
* await model.update({ intercept_status: 'requested', updated_at: now }, { where: { id: { [Op.in]: ids } } });
|
||||
* if (fillIds.length > 0) {
|
||||
* await model.update({ intercept_time: now }, { where: { id: { [Op.in]: fillIds } } });
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param {Array<Object>} rows 订单行(需含 id 与 intercept_time)
|
||||
* @return {Array<number>} 需要写入通知拦截时间的订单ID(正整数,保序去重)
|
||||
*/
|
||||
function pickNoticeTimeOrderIds(rows = []) {
|
||||
const seen = new Set();
|
||||
const orderIds = [];
|
||||
for (const row of (Array.isArray(rows) ? rows : [])) {
|
||||
if (!row || !isEmptyInterceptTime(row[INTERCEPT_TIME_FIELD])) {
|
||||
continue;
|
||||
}
|
||||
const orderId = Number(row.id || 0);
|
||||
if (!Number.isInteger(orderId) || orderId <= 0 || seen.has(orderId)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(orderId);
|
||||
orderIds.push(orderId);
|
||||
}
|
||||
return orderIds;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
INTERCEPT_TIME_FIELD,
|
||||
isEmptyInterceptTime,
|
||||
buildNoticeTimePatch,
|
||||
pickNoticeTimeOrderIds,
|
||||
};
|
||||
522
app/lib/jd_client.js
Normal file
522
app/lib/jd_client.js
Normal file
@ -0,0 +1,522 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const http = require('node:http');
|
||||
const https = require('node:https');
|
||||
|
||||
/** 京东物流开放平台默认网关 */
|
||||
const DEFAULT_BASE_URI = 'https://api.jdl.com';
|
||||
|
||||
/** 京东物流开放平台协议版本 */
|
||||
const DEFAULT_VERSION = '2.0';
|
||||
|
||||
/** 默认签名算法(md5(content) 小写十六进制) */
|
||||
const DEFAULT_ALGORITHM = 'md5-salt';
|
||||
|
||||
/** 单次请求默认超时时间(毫秒) */
|
||||
const DEFAULT_TIMEOUT = 15000;
|
||||
|
||||
/** 标识调用方 HTTP 客户端(与京东示例一致,仅作统计用途) */
|
||||
const DEFAULT_USER_AGENT = 'lop-http/nodejs';
|
||||
|
||||
/** HMac 系列算法名 → node:crypto 摘要名 */
|
||||
const HMAC_ALGORITHMS = {
|
||||
HMacMD5: 'md5',
|
||||
HMacSHA1: 'sha1',
|
||||
HMacSHA256: 'sha256',
|
||||
HMacSHA512: 'sha512',
|
||||
};
|
||||
|
||||
/** 只能在 request() 传入的请求级参数(init 里传会被忽略,因此显式报错) */
|
||||
const REQUEST_ONLY_KEYS = [ 'path', 'method', 'body', 'query', 'headers', 'timestamp', 'now', 'raw' ];
|
||||
|
||||
/**
|
||||
* 判断输入是否为普通对象。
|
||||
* @param {*} value 任意输入值。
|
||||
* @return {boolean} 是否为普通对象。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按京东开放平台规则生成签名。
|
||||
* @param {string} algorithm 算法名:md5-salt / HMacMD5 / HMacSHA1 / HMacSHA256 / HMacSHA512。
|
||||
* @param {string} data 待签名原文(见 buildSignContent)。
|
||||
* @param {string} [secret] 密钥(仅 HMac 系列使用)。
|
||||
* @return {string} 签名值:md5-salt 为小写十六进制,HMac 系列为 base64。
|
||||
* @throws {Error} 算法不支持时抛出。
|
||||
*/
|
||||
function sign(algorithm, data, secret) {
|
||||
const name = String(algorithm || DEFAULT_ALGORITHM);
|
||||
const text = String(data === undefined || data === null ? '' : data);
|
||||
|
||||
if (name === 'md5-salt') {
|
||||
return crypto.createHash('md5').update(text, 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
const hmacName = HMAC_ALGORITHMS[name];
|
||||
if (!hmacName) {
|
||||
throw new Error(`Algorithm ${name} not supported yet`);
|
||||
}
|
||||
|
||||
return crypto.createHmac(hmacName, String(secret === undefined || secret === null ? '' : secret))
|
||||
.update(text, 'utf8')
|
||||
.digest('base64');
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化签名为 `YYYY-MM-DD HH:mm:ss`(服务器本地时区,与京东 PHP 示例 date() 口径一致)。
|
||||
* @param {Date} [date] 时间对象,默认当前时间。
|
||||
* @return {string} 格式化后的时间戳。
|
||||
*/
|
||||
function formatTimestamp(date = new Date()) {
|
||||
const pad = num => String(num).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
|
||||
+ `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化当前时区相对 UTC 的小时数,用于 lop-tz 请求头(东八区为 '8')。
|
||||
* @param {Date} [date] 时间对象,默认当前时间。
|
||||
* @return {string} 时区小时数(如 '8'、'5.5'、'-5')。
|
||||
*/
|
||||
function formatTimezoneOffset(date = new Date()) {
|
||||
return String(-date.getTimezoneOffset() / 60);
|
||||
}
|
||||
|
||||
/**
|
||||
* 拼接签名原文。
|
||||
*
|
||||
* 与京东 PHP 示例完全一致:
|
||||
* `secret + 'access_token' + token + 'app_key' + key + 'method' + path +
|
||||
* 'param_json' + body + 'timestamp' + ts + 'v' + version + secret`
|
||||
*
|
||||
* @param {Object} options 签名要素。
|
||||
* @param {string} options.appSecret 应用密钥。
|
||||
* @param {string} [options.accessToken] 访问令牌。
|
||||
* @param {string} options.appKey 应用 AppKey。
|
||||
* @param {string} options.method 接口路径(京东协议中 method 即 path)。
|
||||
* @param {string} [options.paramJson] 业务报文原文。
|
||||
* @param {string} options.timestamp 请求时间戳。
|
||||
* @param {string} options.version 协议版本。
|
||||
* @return {string} 签名原文。
|
||||
*/
|
||||
function buildSignContent({ appSecret, accessToken, appKey, method, paramJson, timestamp, version }) {
|
||||
const toString = value => String(value === undefined || value === null ? '' : value);
|
||||
return [
|
||||
toString(appSecret),
|
||||
'access_token', toString(accessToken),
|
||||
'app_key', toString(appKey),
|
||||
'method', toString(method),
|
||||
'param_json', toString(paramJson),
|
||||
'timestamp', toString(timestamp),
|
||||
'v', toString(version),
|
||||
toString(appSecret),
|
||||
].join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 京东物流开放平台客户端(api.jdl.com)。
|
||||
*
|
||||
* 使用方式:
|
||||
* ```js
|
||||
* const jdClient = require('./jd_client');
|
||||
* jdClient.init(appKey, appSecret, { accessToken });
|
||||
* const res = await jdClient.request({
|
||||
* path: '/jd/tracking/query',
|
||||
* domain: 'Tracking_JD',
|
||||
* body: [{ referenceNumber: 'JDAP20626092313', referenceType: '20000', phone: '7068' }],
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
class JdClient {
|
||||
/**
|
||||
* @param {Object} [options={}] 默认配置。
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
this.options = {
|
||||
baseUri: DEFAULT_BASE_URI,
|
||||
version: DEFAULT_VERSION,
|
||||
algorithm: DEFAULT_ALGORITHM,
|
||||
timeout: DEFAULT_TIMEOUT,
|
||||
userAgent: DEFAULT_USER_AGENT,
|
||||
appKey: '',
|
||||
appSecret: '',
|
||||
accessToken: '',
|
||||
domain: '',
|
||||
logger: null,
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化凭据与默认配置(可重复调用覆盖)。
|
||||
*
|
||||
* 只能传「请求之间不变」的配置;`path` / `body` / `method` / `query` / `headers` /
|
||||
* `timestamp` 等请求级参数请传给 request(),误传到这里会直接报错。
|
||||
*
|
||||
* @param {string} appKey 应用 AppKey。
|
||||
* @param {string} appSecret 应用 AppSecret。
|
||||
* @param {Object} [options={}] 可选默认配置。
|
||||
* @param {string} [options.accessToken] 访问令牌,也可后续用 setAccessToken 设置。
|
||||
* @param {string} [options.domain] 接口域(LOP-DN),如 Tracking_JD。
|
||||
* @param {string} [options.baseUri] 网关地址,默认 https://api.jdl.com。
|
||||
* @param {string} [options.version] 协议版本,默认 2.0。
|
||||
* @param {string} [options.algorithm] 签名算法,默认 md5-salt。
|
||||
* @param {number} [options.timeout] 超时毫秒数,默认 15000。
|
||||
* @param {string} [options.userAgent] UA,默认 lop-http/nodejs。
|
||||
* @param {Object} [options.logger] 可选日志器(需实现 warn)。
|
||||
* @return {JdClient} 当前实例(便于链式调用)。
|
||||
* @throws {Error} options 里出现请求级参数时抛出。
|
||||
*/
|
||||
init(appKey, appSecret, options = {}) {
|
||||
const safeOptions = isPlainObject(options) ? options : {};
|
||||
const invalidKeys = Object.keys(safeOptions).filter(key => REQUEST_ONLY_KEYS.includes(key));
|
||||
if (invalidKeys.length > 0) {
|
||||
throw new Error(
|
||||
`init 不支持请求级参数:${invalidKeys.join(', ')},请在 request() 中传入`
|
||||
);
|
||||
}
|
||||
|
||||
this.options = {
|
||||
...this.options,
|
||||
...safeOptions,
|
||||
appKey: String(appKey || '').trim(),
|
||||
appSecret: String(appSecret || '').trim(),
|
||||
};
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新访问令牌。
|
||||
* @param {string} accessToken 访问令牌。
|
||||
* @return {JdClient} 当前实例。
|
||||
*/
|
||||
setAccessToken(accessToken) {
|
||||
this.options.accessToken = String(accessToken || '').trim();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析本次请求的凭据与配置(请求级参数优先于 init 默认值)。
|
||||
* @param {Object} [options={}] 请求参数。
|
||||
* @return {Object} 解析后的配置。
|
||||
*/
|
||||
resolveOptions(options = {}) {
|
||||
const source = isPlainObject(options) ? options : {};
|
||||
const pick = key => (source[key] === undefined || source[key] === null
|
||||
? this.options[key]
|
||||
: source[key]);
|
||||
|
||||
const appKey = String(pick('appKey') || '').trim();
|
||||
const appSecret = String(pick('appSecret') || '').trim();
|
||||
if (!appKey || !appSecret) {
|
||||
throw new Error('京东开放平台 appKey / appSecret 未配置');
|
||||
}
|
||||
|
||||
return {
|
||||
appKey,
|
||||
appSecret,
|
||||
accessToken: String(pick('accessToken') || '').trim(),
|
||||
domain: String(pick('domain') || '').trim(),
|
||||
baseUri: String(pick('baseUri') || DEFAULT_BASE_URI).replace(/\/+$/, ''),
|
||||
version: String(pick('version') || DEFAULT_VERSION),
|
||||
algorithm: String(pick('algorithm') || DEFAULT_ALGORITHM),
|
||||
timeout: Number(pick('timeout')) || DEFAULT_TIMEOUT,
|
||||
userAgent: String(pick('userAgent') || DEFAULT_USER_AGENT),
|
||||
logger: pick('logger') || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化业务报文:字符串原样使用(签名与发送必须完全一致),其余按 JSON 序列化。
|
||||
* @param {*} body 业务报文。
|
||||
* @return {string} param_json 原文。
|
||||
*/
|
||||
normalizeParamJson(body) {
|
||||
if (body === undefined || body === null) return '';
|
||||
if (typeof body === 'string') return body;
|
||||
return JSON.stringify(body);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建已签名的请求参数(不发请求,便于日志与单测)。
|
||||
* @param {Object} [options={}] 请求参数。
|
||||
* @param {string} options.path 接口路径(如 /jd/tracking/query),京东协议中同时作为签名 method。
|
||||
* @param {string} [options.method='POST'] HTTP 方法。
|
||||
* @param {*} [options.body] 业务报文(对象/数组/字符串),序列化后作为 param_json。
|
||||
* @param {Object} [options.query={}] 额外查询参数(如京东要求的业务 query 参数)。
|
||||
* @param {Object} [options.headers={}] 额外请求头。
|
||||
* @param {string} [options.timestamp] 指定时间戳(默认当前本地时间),便于复现。
|
||||
* @param {Date} [options.now] 指定当前时间对象(影响时间戳与 lop-tz)。
|
||||
* @return {Object} { url, method, headers, body, paramJson, sign, timestamp, content, query }。
|
||||
*/
|
||||
buildRequestOptions(options = {}) {
|
||||
const {
|
||||
path: apiPath,
|
||||
method = 'POST',
|
||||
body,
|
||||
query: extraQuery = {},
|
||||
headers: extraHeaders = {},
|
||||
timestamp,
|
||||
now,
|
||||
} = options;
|
||||
|
||||
const config = this.resolveOptions(options);
|
||||
const path = String(apiPath || '').trim();
|
||||
if (!path) {
|
||||
throw new Error('京东接口 path 不能为空');
|
||||
}
|
||||
|
||||
const httpMethod = String(method || 'POST').toUpperCase();
|
||||
const paramJson = this.normalizeParamJson(body);
|
||||
const nowDate = now instanceof Date ? now : new Date();
|
||||
const requestTimestamp = timestamp ? String(timestamp) : formatTimestamp(nowDate);
|
||||
|
||||
const content = buildSignContent({
|
||||
appSecret: config.appSecret,
|
||||
accessToken: config.accessToken,
|
||||
appKey: config.appKey,
|
||||
method: path,
|
||||
paramJson,
|
||||
timestamp: requestTimestamp,
|
||||
version: config.version,
|
||||
});
|
||||
const signValue = sign(config.algorithm, content, config.appSecret);
|
||||
|
||||
const queryPairs = [];
|
||||
if (config.domain) queryPairs.push([ 'LOP-DN', config.domain ]);
|
||||
queryPairs.push([ 'app_key', config.appKey ]);
|
||||
queryPairs.push([ 'access_token', config.accessToken ]);
|
||||
queryPairs.push([ 'timestamp', requestTimestamp ]);
|
||||
queryPairs.push([ 'v', config.version ]);
|
||||
queryPairs.push([ 'sign', signValue ]);
|
||||
queryPairs.push([ 'algorithm', config.algorithm ]);
|
||||
if (httpMethod === 'GET' && paramJson) {
|
||||
queryPairs.push([ 'param_json', paramJson ]);
|
||||
}
|
||||
for (const [ key, value ] of Object.entries(isPlainObject(extraQuery) ? extraQuery : {})) {
|
||||
if (value === undefined || value === null) continue;
|
||||
queryPairs.push([ key, String(value) ]);
|
||||
}
|
||||
|
||||
const search = new URLSearchParams();
|
||||
for (const [ key, value ] of queryPairs) {
|
||||
search.append(key, value);
|
||||
}
|
||||
|
||||
const url = `${config.baseUri}${path}${search.toString() ? `?${search.toString()}` : ''}`;
|
||||
const headers = {
|
||||
'content-type': 'application/json;charset=utf-8',
|
||||
'lop-tz': formatTimezoneOffset(nowDate),
|
||||
'user-agent': config.userAgent,
|
||||
...(isPlainObject(extraHeaders) ? extraHeaders : {}),
|
||||
};
|
||||
const requestBody = httpMethod === 'GET' ? null : paramJson;
|
||||
if (requestBody !== null && headers['content-length'] === undefined) {
|
||||
headers['content-length'] = String(Buffer.byteLength(requestBody, 'utf8'));
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
method: httpMethod,
|
||||
headers,
|
||||
body: requestBody,
|
||||
paramJson,
|
||||
sign: signValue,
|
||||
timestamp: requestTimestamp,
|
||||
content,
|
||||
query: Object.fromEntries(queryPairs),
|
||||
timeout: config.timeout,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用京东开放平台接口。
|
||||
* @param {Object} [options={}] 请求参数,见 buildRequestOptions。
|
||||
* @param {boolean} [options.raw=false] 为 true 时返回 { status, headers, text } 原始响应。
|
||||
* @return {Promise<Object>} 默认返回 { success, status, headers, data, text, url }。
|
||||
*/
|
||||
async request(options = {}) {
|
||||
const prepared = this.buildRequestOptions(options);
|
||||
const response = await this.send(prepared);
|
||||
const text = response.text;
|
||||
let data = null;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : null;
|
||||
} catch (_e) {
|
||||
data = text;
|
||||
}
|
||||
|
||||
const result = {
|
||||
success: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
headers: response.headers,
|
||||
data,
|
||||
text,
|
||||
url: prepared.url,
|
||||
};
|
||||
|
||||
if (options && options.raw === true) {
|
||||
return { status: response.status, headers: response.headers, text, url: prepared.url };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 HTTP 请求(内置 http/https,不依赖第三方请求库)。
|
||||
* @param {Object} prepared buildRequestOptions 的返回值。
|
||||
* @return {Promise<{status: number, headers: Object, text: string}>} 响应。
|
||||
*/
|
||||
send(prepared) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const target = new URL(prepared.url);
|
||||
const transport = target.protocol === 'http:' ? http : https;
|
||||
const req = transport.request({
|
||||
protocol: target.protocol,
|
||||
hostname: target.hostname,
|
||||
port: target.port || (target.protocol === 'http:' ? 80 : 443),
|
||||
path: `${target.pathname}${target.search}`,
|
||||
method: prepared.method,
|
||||
headers: prepared.headers,
|
||||
timeout: prepared.timeout,
|
||||
}, res => {
|
||||
const chunks = [];
|
||||
res.on('data', chunk => chunks.push(chunk));
|
||||
res.on('end', () => {
|
||||
resolve({
|
||||
status: Number(res.statusCode) || 0,
|
||||
headers: res.headers,
|
||||
text: Buffer.concat(chunks).toString('utf8'),
|
||||
});
|
||||
});
|
||||
res.on('error', reject);
|
||||
});
|
||||
|
||||
req.on('timeout', () => {
|
||||
req.destroy(new Error(`京东接口请求超时(${prepared.timeout}ms)`));
|
||||
});
|
||||
req.on('error', reject);
|
||||
if (prepared.body !== null && prepared.body !== undefined) {
|
||||
req.write(prepared.body);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 驱动式调用:兼容 `execute({ url, body })` 写法(与其它快递驱动保持一致)。
|
||||
*
|
||||
* - `url` 可传完整地址(自动拆成 baseUri + path + query),也可只传 path;
|
||||
* - `body` 为对象/数组时自动 JSON.stringify,字符串原样使用(签名与发送同一份);
|
||||
* - 返回类 fetch 响应对象,支持 `await res.text()` / `await res.json()`。
|
||||
*
|
||||
* @param {Object} [request={}] 请求参数。
|
||||
* @param {string} request.url 接口地址(完整 URL 或 path)。
|
||||
* @param {*} [request.body] 业务报文。
|
||||
* @param {string} [request.method='POST'] HTTP 方法。
|
||||
* @param {Object} [request.query] 额外 query 参数。
|
||||
* @param {Object} [request.headers] 额外请求头。
|
||||
* @param {string} [request.domain] 接口域(LOP-DN)。
|
||||
* @param {string} [request.accessToken] 覆盖默认 access_token。
|
||||
* @return {Promise<Object>} { ok, status, statusText, headers, url, data, text(), json() }。
|
||||
*/
|
||||
async execute(request = {}) {
|
||||
const safeRequest = isPlainObject(request) ? request : {};
|
||||
const targetUrl = String(safeRequest.url || '').trim();
|
||||
if (!targetUrl) {
|
||||
throw new Error('京东接口 url 不能为空');
|
||||
}
|
||||
|
||||
const isAbsolute = /^https?:\/\//i.test(targetUrl);
|
||||
const parsed = isAbsolute ? new URL(targetUrl) : null;
|
||||
const urlQuery = {};
|
||||
if (parsed) {
|
||||
for (const [ key, value ] of parsed.searchParams.entries()) {
|
||||
urlQuery[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
const result = await this.request({
|
||||
...safeRequest,
|
||||
baseUri: parsed ? `${parsed.protocol}//${parsed.host}` : safeRequest.baseUri,
|
||||
path: parsed ? parsed.pathname : targetUrl,
|
||||
query: { ...urlQuery, ...(isPlainObject(safeRequest.query) ? safeRequest.query : {}) },
|
||||
});
|
||||
|
||||
const text = result.text === undefined || result.text === null ? '' : String(result.text);
|
||||
return {
|
||||
ok: result.success,
|
||||
status: result.status,
|
||||
statusText: result.success ? 'OK' : 'ERROR',
|
||||
headers: result.headers || {},
|
||||
url: result.url,
|
||||
data: result.data,
|
||||
text: async () => text,
|
||||
json: async () => {
|
||||
if (text) return JSON.parse(text);
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const defaultClient = new JdClient();
|
||||
|
||||
module.exports = {
|
||||
JdClient,
|
||||
buildSignContent,
|
||||
formatTimestamp,
|
||||
formatTimezoneOffset,
|
||||
sign,
|
||||
/**
|
||||
* 初始化默认客户端。
|
||||
* @param {string} appKey 应用 AppKey。
|
||||
* @param {string} appSecret 应用 AppSecret。
|
||||
* @param {Object} [options={}] 默认配置。
|
||||
* @return {JdClient} 默认客户端实例。
|
||||
*/
|
||||
init(appKey, appSecret, options) {
|
||||
return defaultClient.init(appKey, appSecret, options);
|
||||
},
|
||||
/**
|
||||
* 更新默认客户端的访问令牌。
|
||||
* @param {string} accessToken 访问令牌。
|
||||
* @return {JdClient} 默认客户端实例。
|
||||
*/
|
||||
setAccessToken(accessToken) {
|
||||
return defaultClient.setAccessToken(accessToken);
|
||||
},
|
||||
/**
|
||||
* 用默认客户端构建签名请求参数。
|
||||
* @param {Object} [options={}] 请求参数。
|
||||
* @return {Object} 已签名请求参数。
|
||||
*/
|
||||
buildRequestOptions(options) {
|
||||
return defaultClient.buildRequestOptions(options);
|
||||
},
|
||||
/**
|
||||
* 用默认客户端调用接口。
|
||||
* @param {Object} [options={}] 请求参数。
|
||||
* @return {Promise<Object>} 响应。
|
||||
*/
|
||||
request(options) {
|
||||
return defaultClient.request(options);
|
||||
},
|
||||
/**
|
||||
* 用默认客户端做驱动式调用(兼容 execute({ url, body }))。
|
||||
* @param {Object} [request={}] 请求参数。
|
||||
* @return {Promise<Object>} 类 fetch 响应(支持 text() / json())。
|
||||
*/
|
||||
execute(request) {
|
||||
return defaultClient.execute(request);
|
||||
},
|
||||
/**
|
||||
* 默认客户端实例。
|
||||
* @return {JdClient} 实例。
|
||||
*/
|
||||
get client() {
|
||||
return defaultClient;
|
||||
},
|
||||
};
|
||||
29
app/lib/lock_guard.js
Normal file
29
app/lib/lock_guard.js
Normal file
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单锁定状态共享定义。
|
||||
*
|
||||
* wms_order_delivery.lock_status 枚举(order_delivery.js / order_delivery_factory.js)实际取值为:
|
||||
* none / warehouse / store。
|
||||
*
|
||||
* 业务约定:锁定状态只要不是 'none'(即被仓库或货主锁定的订单),一律视为"已锁定",
|
||||
* 禁止继续执行仓储作业(分配储位/分配快递/抓取波次/自动加团等),
|
||||
* 已锁定订单一律跳过。
|
||||
*/
|
||||
const LOCK_STATUS_NONE = 'none';
|
||||
|
||||
/**
|
||||
* 判断订单锁定状态是否属于"已锁定"。
|
||||
* 空值/NULL 归一化为 none 处理;除此之外任何非 none 状态(含 warehouse/store)均视为已锁定。
|
||||
* @param {*} status 锁定状态值。
|
||||
* @return {boolean} 是否已锁定。
|
||||
*/
|
||||
function isLockedOrderStatus(status) {
|
||||
const normalizedStatus = String(status || '').trim() || LOCK_STATUS_NONE;
|
||||
return normalizedStatus !== LOCK_STATUS_NONE;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
LOCK_STATUS_NONE,
|
||||
isLockedOrderStatus,
|
||||
};
|
||||
105
app/lib/order_lookup.js
Normal file
105
app/lib/order_lookup.js
Normal file
@ -0,0 +1,105 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 订单分表跨表查询共享工具。
|
||||
*
|
||||
* 订单按仓库分表且按生命周期流转于多张物理表之间:
|
||||
* current(待出库)→ dispatch(配送)→ history(历史归档),另有 outsourced(外包)。
|
||||
* 各分表唯一索引均为 (delivery_order_code, store_id, warehouse_id),跨表间约束独立。
|
||||
* 任何"按单号判断订单是否存在/可用"的场景都必须跨表遍历,否则会误判
|
||||
* (如订单已流转到 dispatch 后,仅查 current 会返回"未找到订单",诱导调用方重推)。
|
||||
*
|
||||
* 注意事项:
|
||||
* - 分表模型首次获取可能执行 DDL(隐式提交),因此必须在事务外调用 preloadOrderModels
|
||||
* 完成模型预取,再在事务内用 findOrderAcrossTables 查询;
|
||||
* - findOrderByCodeAcrossTables 内部会预取模型,仅适用于非事务场景。
|
||||
*/
|
||||
|
||||
/** 默认跨表查找顺序:current → dispatch → history → outsourced。 */
|
||||
const TABLE_TYPE_ORDER = [ 'current', 'dispatch', 'history', 'outsourced' ];
|
||||
|
||||
/** 表位 → OrderDeliveryFactory 模型获取方法名。 */
|
||||
const MODEL_GETTER_BY_TYPE = {
|
||||
current: 'getCurrentModel',
|
||||
dispatch: 'getDispatchModel',
|
||||
history: 'getHistoryModel',
|
||||
outsourced: 'getOutsourcedModel',
|
||||
};
|
||||
|
||||
/**
|
||||
* 预取订单分表模型。
|
||||
* 必须在事务外调用:模型首次获取可能执行 DDL(隐式提交)。
|
||||
*
|
||||
* @param {Object} ctx egg ctx。
|
||||
* @param {string|number} warehouseId 仓库ID(分表后缀)。
|
||||
* @param {string[]} [tableTypes] 需要预取的表位,默认四表。
|
||||
* @return {Promise<Object>} 表位 → 模型 的映射(缺失模型不会出现在结果中)。
|
||||
*/
|
||||
async function preloadOrderModels(ctx, warehouseId, tableTypes = TABLE_TYPE_ORDER) {
|
||||
const factory = ctx && ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
if (!factory) {
|
||||
throw new Error('OrderDeliveryFactory 不可用,无法跨表查询订单');
|
||||
}
|
||||
const models = {};
|
||||
for (const tableType of tableTypes) {
|
||||
const getter = MODEL_GETTER_BY_TYPE[tableType];
|
||||
if (!getter || typeof factory[getter] !== 'function') {
|
||||
continue;
|
||||
}
|
||||
const model = await factory[getter](warehouseId);
|
||||
if (model && typeof model.findOne === 'function') {
|
||||
models[tableType] = model;
|
||||
}
|
||||
}
|
||||
return models;
|
||||
}
|
||||
|
||||
/**
|
||||
* 跨表按条件查找订单,按 tableTypes 顺序命中即停。
|
||||
*
|
||||
* @param {Object} models preloadOrderModels 返回的表位 → 模型映射。
|
||||
* @param {Object} where 查询条件(findOne where,例如 delivery_order_code + store_id + warehouse_id)。
|
||||
* @param {Object} [options] 可选配置。
|
||||
* @param {string[]} [options.tableTypes] 查找表位顺序,默认四表。
|
||||
* @param {Object} [options.findOptions] 透传给 findOne 的其余选项(transaction/lock/attributes 等)。
|
||||
* @return {Promise<{ order: Object|null, location: string|null }>} 命中订单与所在表位;未命中 order=null。
|
||||
*/
|
||||
async function findOrderAcrossTables(models, where, options = {}) {
|
||||
const { tableTypes = TABLE_TYPE_ORDER, findOptions = {} } = options;
|
||||
for (const tableType of tableTypes) {
|
||||
const model = models && models[tableType];
|
||||
if (!model || typeof model.findOne !== 'function') {
|
||||
continue;
|
||||
}
|
||||
const order = await model.findOne({
|
||||
where,
|
||||
...findOptions,
|
||||
});
|
||||
if (order) {
|
||||
return { order, location: tableType };
|
||||
}
|
||||
}
|
||||
return { order: null, location: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 便捷入口:预取模型后按条件跨表查找(仅限非事务场景)。
|
||||
* 事务内请使用 preloadOrderModels + findOrderAcrossTables。
|
||||
*
|
||||
* @param {Object} ctx egg ctx。
|
||||
* @param {string|number} warehouseId 仓库ID。
|
||||
* @param {Object} where 查询条件。
|
||||
* @param {Object} [options] 同 findOrderAcrossTables 的 options,另支持 tableTypes 用于预取过滤。
|
||||
* @return {Promise<{ order: Object|null, location: string|null }>} 命中订单与所在表位;未命中 order 为 null。
|
||||
*/
|
||||
async function findOrderByCodeAcrossTables(ctx, warehouseId, where, options = {}) {
|
||||
const models = await preloadOrderModels(ctx, warehouseId, options.tableTypes);
|
||||
return findOrderAcrossTables(models, where, options);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
TABLE_TYPE_ORDER,
|
||||
preloadOrderModels,
|
||||
findOrderAcrossTables,
|
||||
findOrderByCodeAcrossTables,
|
||||
};
|
||||
102
app/lib/osd_client.js
Normal file
102
app/lib/osd_client.js
Normal file
@ -0,0 +1,102 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* OSD(屏幕菜单叠加)客户端模块。
|
||||
* 负责组装 RTSP URL 并调用打印服务设置摄像头 OSD 文字叠加。
|
||||
*
|
||||
* 使用方式:
|
||||
* const osdClient = new (require('../lib/osd_client'))(ctx);
|
||||
* await osdClient.setOsd({ camera, warehouseId, text, x, y });
|
||||
*/
|
||||
class OsdClient {
|
||||
constructor(ctx) {
|
||||
this.ctx = ctx;
|
||||
this.logger = ctx.logger || console;
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装摄像头 RTSP 地址
|
||||
* 格式: rtsp://{username}:{password}@{ip}:554/stream{channelId}
|
||||
*
|
||||
* @param {Object} camera - 摄像头记录(含 ip/username/password/channel_id)
|
||||
* @return {string} RTSP URL
|
||||
*/
|
||||
buildRtspUrl(camera) {
|
||||
const ip = camera.ip;
|
||||
if (!ip) {
|
||||
throw new Error('摄像头未配置IP地址,无法组装RTSP地址');
|
||||
}
|
||||
|
||||
const username = camera.username || 'admin';
|
||||
const password = camera.password || '';
|
||||
const channelId = camera.channel_id;
|
||||
const rtspPort = 554;
|
||||
|
||||
return `rtsp://${username}:${password}@${ip}:${rtspPort}/stream${channelId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送 OSD 叠加指令到打印服务
|
||||
*
|
||||
* @param {Object} options - 配置选项
|
||||
* @param {Object} options.camera - 摄像头记录
|
||||
* @param {Object} [options.server] - 关联的录像服务器(fallback 认证信息)
|
||||
* @param {number} options.warehouseId - 仓库ID
|
||||
* @param {string} options.text - OSD 叠加文字
|
||||
* @param {number} [options.x] - X 坐标(-1 到 1,默认 -0.9)
|
||||
* @param {number} [options.y] - Y 坐标(-1 到 1,默认 0.8)
|
||||
* @return {Promise<Object>} 打印服务响应 { status, data, error }
|
||||
*/
|
||||
async setOsd(options = {}) {
|
||||
const { ctx } = this;
|
||||
const { camera, warehouseId, text, x, y } = options;
|
||||
|
||||
if (!camera) throw new Error('摄像头信息不能为空');
|
||||
if (!text) throw new Error('OSD文字不能为空');
|
||||
if (warehouseId === undefined || warehouseId === null) throw new Error('仓库ID不能为空');
|
||||
|
||||
const rtspUrl = this.buildRtspUrl(camera);
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
|
||||
const requestData = {
|
||||
warehouse_id: String(warehouseId),
|
||||
rtspUrl,
|
||||
text,
|
||||
x: x !== undefined ? x : -0.9,
|
||||
y: y !== undefined ? y : 0.8,
|
||||
};
|
||||
|
||||
const targetUrl = `${printServiceUrl}/camera/setOSD`;
|
||||
ctx.logger.info('[OSD] 发送设置请求', { url: targetUrl, body: requestData });
|
||||
|
||||
let response = null;
|
||||
let error = null;
|
||||
try {
|
||||
const res = await ctx.curl(targetUrl, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: requestData,
|
||||
dataType: 'json',
|
||||
timeout: 10000,
|
||||
});
|
||||
response = {
|
||||
status: res.status,
|
||||
headers: res.headers,
|
||||
data: res.data,
|
||||
};
|
||||
ctx.logger.info('[OSD] 打印服务回信', { status: res.status, data: res.data });
|
||||
} catch (err) {
|
||||
error = err.message;
|
||||
ctx.logger.warn('[OSD] 打印服务请求失败', { camera_id: camera.id, error: err.message });
|
||||
}
|
||||
|
||||
return {
|
||||
success: !error && response && response.status >= 200 && response.status < 300,
|
||||
error,
|
||||
response,
|
||||
request: requestData,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OsdClient;
|
||||
150
app/lib/pdd_client.js
Normal file
150
app/lib/pdd_client.js
Normal file
@ -0,0 +1,150 @@
|
||||
'use strict';
|
||||
|
||||
const pddSign = require('./pdd_sign');
|
||||
|
||||
const DEFAULT_BASE_URL = 'https://gw-api.pinduoduo.com/api/router';
|
||||
|
||||
/**
|
||||
* 判断输入是否为普通对象。
|
||||
* @param {*} value 任意输入值。
|
||||
* @return {boolean} 是否为普通对象。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前秒级时间戳。
|
||||
* @return {string} 秒级 UNIX 时间戳。
|
||||
*/
|
||||
function nowSec() {
|
||||
return String(Math.floor(Date.now() / 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* 拼多多开放平台 API 客户端。
|
||||
* 负责组装请求体、生成签名、发送请求。
|
||||
*/
|
||||
class PddClient {
|
||||
/**
|
||||
* @param {object} ctx - Egg 上下文对象。
|
||||
* @param {object} [options={}] - 客户端默认配置。
|
||||
*/
|
||||
constructor(ctx, options = {}) {
|
||||
this.ctx = ctx;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析客户端凭据。
|
||||
* @param {object} [options={}] 请求级配置。
|
||||
* @return {{ clientId: string, clientSecret: string }} 凭据。
|
||||
*/
|
||||
resolveCredentials(options = {}) {
|
||||
const config = (this.ctx && this.ctx.app && this.ctx.app.config && this.ctx.app.config.pdd) || {};
|
||||
|
||||
const clientId = options.clientId
|
||||
?? this.options.clientId
|
||||
?? config.client_id
|
||||
?? config.clientId
|
||||
?? '';
|
||||
const clientSecret = options.clientSecret
|
||||
?? this.options.clientSecret
|
||||
?? config.client_secret
|
||||
?? config.clientSecret
|
||||
?? '';
|
||||
|
||||
return {
|
||||
clientId: String(clientId || '').trim(),
|
||||
clientSecret: String(clientSecret || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建请求体。
|
||||
* @param {object} [options={}] 请求参数。
|
||||
* @return {{ requestBody: object, signText: string, sortedPairs: Array<[string, string]> }} 请求体和签名信息。
|
||||
*/
|
||||
buildRequest(options = {}) {
|
||||
const {
|
||||
type,
|
||||
bizParams = {},
|
||||
request = {},
|
||||
accessToken,
|
||||
dataType = 'JSON',
|
||||
version,
|
||||
timestamp = nowSec(),
|
||||
} = options;
|
||||
|
||||
const { clientId, clientSecret } = this.resolveCredentials(options);
|
||||
const payload = isPlainObject(bizParams) ? { ...bizParams } : {};
|
||||
if (isPlainObject(request)) {
|
||||
Object.assign(payload, request);
|
||||
}
|
||||
|
||||
const signed = pddSign.buildRequestBody({
|
||||
type,
|
||||
clientId,
|
||||
timestamp,
|
||||
dataType,
|
||||
accessToken,
|
||||
version,
|
||||
bizParams: payload,
|
||||
clientSecret,
|
||||
});
|
||||
|
||||
return signed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起拼多多 API 请求。
|
||||
* @param {object} [options={}] 请求参数。
|
||||
* @return {Promise<any>} 接口响应。
|
||||
*/
|
||||
async request(options = {}) {
|
||||
const {
|
||||
baseUrl = DEFAULT_BASE_URL,
|
||||
headers = {},
|
||||
timeout,
|
||||
responseType = 'json',
|
||||
} = options;
|
||||
|
||||
if (!baseUrl) {
|
||||
throw new Error('baseUrl 不能为空');
|
||||
}
|
||||
|
||||
const { requestBody } = this.buildRequest(options);
|
||||
const response = await this.ctx.curl(String(baseUrl), {
|
||||
method: 'POST',
|
||||
dataType: responseType,
|
||||
timeout,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(headers || {}),
|
||||
},
|
||||
data: requestBody,
|
||||
});
|
||||
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步调用接口,和 request 等价。
|
||||
* @param {object} [options={}] 请求参数。
|
||||
* @return {Promise<any>} 接口响应。
|
||||
*/
|
||||
async syncInvoke(options = {}) {
|
||||
return this.request(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步调用接口,和 request 等价。
|
||||
* @param {object} [options={}] 请求参数。
|
||||
* @return {Promise<any>} 接口响应。
|
||||
*/
|
||||
async asyncInvoke(options = {}) {
|
||||
return this.request(options);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PddClient;
|
||||
189
app/lib/pdd_sign.js
Normal file
189
app/lib/pdd_sign.js
Normal file
@ -0,0 +1,189 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
/**
|
||||
* 判断输入是否为普通对象。
|
||||
* @param {*} value 任意输入值。
|
||||
* @return {boolean} 是否为普通对象。
|
||||
*/
|
||||
function isPlainObject(value) {
|
||||
return Object.prototype.toString.call(value) === '[object Object]';
|
||||
}
|
||||
|
||||
/**
|
||||
* 将对象按 key 排序后稳定序列化。
|
||||
* @param {*} value 待序列化值。
|
||||
* @return {string} 稳定序列化字符串。
|
||||
*/
|
||||
function stableStringify(value) {
|
||||
if (value === undefined) {
|
||||
return 'null';
|
||||
}
|
||||
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
||||
}
|
||||
|
||||
if (!isPlainObject(value)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const keys = Object.keys(value)
|
||||
.filter(key => value[key] !== undefined)
|
||||
.sort();
|
||||
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化参数值为可拼接字符串。
|
||||
* @param {*} value 参数值。
|
||||
* @return {string} 归一化后的字符串。
|
||||
*/
|
||||
function normalizeValue(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
return stableStringify(value);
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化密钥值。
|
||||
* @param {string} clientSecret 客户端密钥。
|
||||
* @return {string} 归一化后的密钥。
|
||||
*/
|
||||
function normalizeSecret(clientSecret) {
|
||||
return String(clientSecret || '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化并排序请求参数。
|
||||
* @param {Object} [params={}] 请求参数。
|
||||
* @return {Array<[string, string]>} 排序后的键值对。
|
||||
*/
|
||||
function buildSortedPairs(params = {}) {
|
||||
if (!isPlainObject(params)) {
|
||||
throw new Error('params 必须是对象');
|
||||
}
|
||||
|
||||
return Object.keys(params)
|
||||
.filter(key => params[key] !== undefined)
|
||||
.sort()
|
||||
.map(key => [ key, normalizeValue(params[key]) ]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建拼多多签名原文。
|
||||
* @param {Object} [params={}] 所有参与签名的参数。
|
||||
* @param {string} clientSecret 客户端密钥。
|
||||
* @return {{ signText: string, sortedPairs: Array<[string, string]> }} 签名原文与排序结果。
|
||||
*/
|
||||
function buildSignText(params = {}, clientSecret) {
|
||||
const secret = normalizeSecret(clientSecret);
|
||||
if (!secret) {
|
||||
throw new Error('clientSecret 不能为空');
|
||||
}
|
||||
|
||||
const sortedPairs = buildSortedPairs(params);
|
||||
const signText = secret + sortedPairs.map(([ key, value ]) => key + value).join('') + secret;
|
||||
|
||||
return {
|
||||
signText,
|
||||
sortedPairs,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成拼多多 API 签名。
|
||||
* @param {Object} [params={}] 所有参与签名的参数。
|
||||
* @param {string} clientSecret 客户端密钥。
|
||||
* @return {{ sign: string, signText: string, sortedPairs: Array<[string, string]> }} 签名结果。
|
||||
*/
|
||||
function sign(params = {}, clientSecret) {
|
||||
const { signText, sortedPairs } = buildSignText(params, clientSecret);
|
||||
|
||||
return {
|
||||
signText,
|
||||
sortedPairs,
|
||||
sign: crypto.createHash('md5').update(signText, 'utf8').digest('hex')
|
||||
.toUpperCase(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建拼多多接口请求体,并自动补充 sign。
|
||||
* @param {Object} [options={}] 请求选项。
|
||||
* @param {string} options.type API 接口名。
|
||||
* @param {string|number} options.clientId 应用 client_id。
|
||||
* @param {string|number} options.timestamp UNIX 时间戳。
|
||||
* @param {string} [options.dataType='JSON'] 返回数据格式。
|
||||
* @param {string} [options.accessToken] 用户授权令牌。
|
||||
* @param {string} [options.version] API 版本。
|
||||
* @param {Object} [options.bizParams={}] 业务参数。
|
||||
* @param {string} options.clientSecret 客户端密钥。
|
||||
* @return {{ requestBody: Object, signText: string, sortedPairs: Array<[string, string]> }} 请求结果。
|
||||
*/
|
||||
function buildRequestBody(options = {}) {
|
||||
const {
|
||||
type,
|
||||
clientId,
|
||||
timestamp,
|
||||
dataType = 'JSON',
|
||||
accessToken,
|
||||
version,
|
||||
bizParams = {},
|
||||
clientSecret,
|
||||
} = options;
|
||||
|
||||
const requestBody = {
|
||||
...(isPlainObject(bizParams) ? bizParams : {}),
|
||||
type,
|
||||
client_id: clientId,
|
||||
timestamp,
|
||||
data_type: dataType,
|
||||
access_token: accessToken,
|
||||
version,
|
||||
};
|
||||
|
||||
Object.keys(requestBody).forEach(key => {
|
||||
if (requestBody[key] === undefined || requestBody[key] === null || requestBody[key] === '') {
|
||||
delete requestBody[key];
|
||||
}
|
||||
});
|
||||
|
||||
// PDD 路由参数验签以字符串值为准,复杂参数需与签名使用同一序列化结果。
|
||||
Object.keys(requestBody).forEach(key => {
|
||||
if (requestBody[key] && typeof requestBody[key] === 'object') {
|
||||
requestBody[key] = normalizeValue(requestBody[key]);
|
||||
}
|
||||
});
|
||||
|
||||
const signed = sign(requestBody, clientSecret);
|
||||
|
||||
return {
|
||||
requestBody: {
|
||||
...requestBody,
|
||||
sign: signed.sign,
|
||||
},
|
||||
signText: signed.signText,
|
||||
sortedPairs: signed.sortedPairs,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildRequestBody,
|
||||
buildSignText,
|
||||
normalizeSecret,
|
||||
normalizeValue,
|
||||
sign,
|
||||
stableStringify,
|
||||
};
|
||||
218
app/lib/polo_api_client.js
Normal file
218
app/lib/polo_api_client.js
Normal file
@ -0,0 +1,218 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
/**
|
||||
* PolyAPI 底层 HTTP 客户端。
|
||||
* 封装签名、表单编码、请求发送等通用逻辑,与业务无关。
|
||||
*/
|
||||
class PoloApiClient {
|
||||
/**
|
||||
* @param {object} ctx - Egg 上下文对象。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
this.ctx = ctx;
|
||||
this.contenttype = 'json';
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起 PolyAPI 表单 POST 请求。
|
||||
*
|
||||
* @param {object} options - 请求参数。
|
||||
* @param {string} options.method - 远端接口方法名。
|
||||
* @param {number|string} options.platid - 平台 ID。
|
||||
* @param {object|string} [options.bizcontent={}] - 业务参数内容。
|
||||
* @return {Promise<any>} 接口响应 data。
|
||||
*/
|
||||
async request(options = {}) {
|
||||
const {
|
||||
method,
|
||||
bizcontent = {},
|
||||
config = {},
|
||||
token,
|
||||
} = options;
|
||||
if (!config || !config.interface_url) {
|
||||
throw new Error('[PoloApiClient.request] 未提供有效的 config,无法发送请求');
|
||||
}
|
||||
const configWithToken = config;
|
||||
if (token) {
|
||||
configWithToken.token = token;
|
||||
}
|
||||
console.log('configWithToken', configWithToken);
|
||||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||||
console.log('signMap', signMap);
|
||||
const signText = this._getSignText(signMap, config.app_secret);
|
||||
const sign = this._md5(signText);
|
||||
// const formBody = this._encodeForm({ ...signMap, sign });
|
||||
signMap.sign = sign;
|
||||
const formBody = Object.keys(signMap)
|
||||
.map(key => `${key}=${encodeURIComponent(signMap[key])}`)
|
||||
.join('&');
|
||||
console.log('查询菠萝派平台数据,接口URL:', config.interface_url, '入参bizcontent:', JSON.stringify(bizcontent));
|
||||
|
||||
await this.ctx.app.setCacheAsync('PoloApiquery', '查询菠萝派平台数据,接口URL:' + config.interface_url + ',入参bizcontent:' + formBody, 3600);
|
||||
|
||||
const response = await this.ctx.curl(String(config.interface_url || ''), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
},
|
||||
content: formBody,
|
||||
});
|
||||
|
||||
console.log('formBody', formBody);
|
||||
let result;
|
||||
if (Buffer.isBuffer(response.data)) {
|
||||
// 如果是 Buffer,转字符串再解析
|
||||
const str = response.data.toString('utf8');
|
||||
result = JSON.parse(str);
|
||||
} else if (typeof response.data === 'string') {
|
||||
result = JSON.parse(response.data);
|
||||
} else {
|
||||
result = response.data;
|
||||
}
|
||||
await this.ctx.app.setCacheAsync('PoloApiresult', JSON.stringify(result), 3600);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起 PolyAPI GET 请求。
|
||||
*
|
||||
* @param {object} options - 请求参数。
|
||||
* @param {string} options.method - 远端接口方法名。
|
||||
* @param {object|string} [options.bizcontent={}] - 业务参数内容。
|
||||
* @param {object} [options.config={}] - 平台配置。
|
||||
* @param {string} [options.token] - 可选 token,传入时优先覆盖配置 token。
|
||||
* @return {Promise<any>} 接口响应 data。
|
||||
*/
|
||||
async get(options = {}) {
|
||||
const {
|
||||
method,
|
||||
bizcontent = {},
|
||||
config = {},
|
||||
token,
|
||||
} = options;
|
||||
if (!config || !config.interface_url) {
|
||||
throw new Error('[PoloApiClient.get] 未提供有效的 config,无法发送请求');
|
||||
}
|
||||
const configWithToken = { ...config, token: token || config.token };
|
||||
const signMap = this._buildSignMap(configWithToken, method, config.platid, bizcontent);
|
||||
const signText = this._getSignText(signMap, config.app_secret);
|
||||
const sign = this._md5(signText);
|
||||
const formBody = this._encodeForm({ ...signMap, sign });
|
||||
const requestUrl = `http://39.98.7.126/OpenApi/Do?${formBody}`;
|
||||
|
||||
const response = await this.ctx.curl(requestUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||
},
|
||||
});
|
||||
let result;
|
||||
if (Buffer.isBuffer(response.data)) {
|
||||
// 如果是 Buffer,转字符串再解析
|
||||
const str = response.data.toString('utf8');
|
||||
console.log('菠萝派平台接口响应原始数据', str);
|
||||
result = JSON.parse(str);
|
||||
} else if (typeof response.data === 'string') {
|
||||
result = JSON.parse(response.data);
|
||||
} else {
|
||||
result = response.data;
|
||||
}
|
||||
return result;
|
||||
|
||||
}
|
||||
// ── 内部方法 ──
|
||||
|
||||
/**
|
||||
* 组装签名所需的请求参数。
|
||||
* @param {object} config 平台配置对象。
|
||||
* @param {string} method 接口方法名。
|
||||
* @param {number|string} platid 平台 ID。
|
||||
* @param {object|string} bizcontent 业务参数。
|
||||
* @return {object} 签名参数映射。
|
||||
*/
|
||||
_buildSignMap(config, method, platid, bizcontent) {
|
||||
const normalizedBizcontent = bizcontent && typeof bizcontent === 'object'
|
||||
? JSON.stringify(bizcontent)
|
||||
: (bizcontent === undefined || bizcontent === null ? '' : bizcontent);
|
||||
const res = {
|
||||
method,
|
||||
appkey: config.appkey,
|
||||
platid,
|
||||
version: config.version,
|
||||
contenttype: this.contenttype,
|
||||
bizcontent: normalizedBizcontent,
|
||||
timestamp: this._formatDate(new Date()),
|
||||
};
|
||||
if (config.token) {
|
||||
res.token = config.token;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成签名原文 = secret + key1value1 + key2value2 ... + secret(按 key 字母序)。
|
||||
* @param {object} signMap 待签名参数映射。
|
||||
* @param {string} secret 签名密钥。
|
||||
* @return {string} 转小写后的签名原文字符串。
|
||||
*/
|
||||
_getSignText(signMap, secret) {
|
||||
let sb = '' + secret;
|
||||
Object.keys(signMap).sort().forEach(key => {
|
||||
sb += key + signMap[key];
|
||||
});
|
||||
sb += secret;
|
||||
return sb.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* MD5 摘要。
|
||||
* @param {string} text 待摘要文本。
|
||||
* @param {BufferEncoding} [encoding='utf8'] 文本编码。
|
||||
* @return {string} 十六进制 MD5 值。
|
||||
*/
|
||||
_md5(text, encoding = 'utf8') {
|
||||
return crypto.createHash('md5').update(text, encoding).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将参数编码为 application/x-www-form-urlencoded。
|
||||
* @param {object} map 表单参数映射。
|
||||
* @return {string} URL 编码后的查询串。
|
||||
*/
|
||||
_encodeForm(map) {
|
||||
const params = new URLSearchParams();
|
||||
for (const key of Object.keys(map)) {
|
||||
const v = map[key];
|
||||
params.append(key, v === undefined || v === null ? '' : (typeof v === 'object' ? JSON.stringify(v) : String(v)));
|
||||
}
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期 → yyyy-MM-dd HH:mm:ss。
|
||||
* @param {Date} date 日期对象。
|
||||
* @return {string} 格式化后的时间字符串。
|
||||
*/
|
||||
_formatDate(date) {
|
||||
const pad = n => (n < 10 ? '0' + n : n);
|
||||
return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' '
|
||||
+ pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化取件日期。
|
||||
* @param {number} year 年。
|
||||
* @param {number} month 月。
|
||||
* @param {number} day 日。
|
||||
* @return {string} 取件日期时间字符串。
|
||||
*/
|
||||
_formatPickupDate(year, month, day) {
|
||||
const pad = n => (n < 10 ? '0' + n : n);
|
||||
return `${year}-${pad(month)}-${pad(day)} 18:00:00`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PoloApiClient;
|
||||
2737
app/lib/printer_data_builder.js
Normal file
2737
app/lib/printer_data_builder.js
Normal file
File diff suppressed because it is too large
Load Diff
325
app/lib/ptz_client.js
Normal file
325
app/lib/ptz_client.js
Normal file
@ -0,0 +1,325 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* PTZ(云台控制)客户端模块。
|
||||
* 负责组装 RTSP URL 并调用打印服务的云台端点下发控制指令。
|
||||
* 与 `lib/osd_client.js` 同风格:独立端点 + 独立请求体,**不带 computerId**
|
||||
* (打印服务按 rtspUrl 定位摄像头,无需房间路由)。
|
||||
*
|
||||
* 端点与请求体(warehouse_id 为字符串、cameraId 为摄像头ID,与 setOSD 口径一致):
|
||||
* - /camera/ptzControl :按下(按方向持续转动),松手时必须配对调用 stop
|
||||
* { warehouse_id, cameraId, rtspUrl, action, speed }
|
||||
* - /camera/ptzStop :松手(停止转动),action 必须与按下时一致
|
||||
* { warehouse_id, cameraId, rtspUrl, action }
|
||||
* - /camera/ptzPresetGoto :跳转预置点,一次调用即可,无需 stop
|
||||
* { warehouse_id, cameraId, rtspUrl, presetId }
|
||||
* - /camera/ptzPresetSet :设置预置点(把当前机位存为指定编号),一次调用即可
|
||||
* { warehouse_id, cameraId, rtspUrl, presetId }
|
||||
*
|
||||
* 使用方式:
|
||||
* const PtzClient = require('../lib/ptz_client');
|
||||
* const ptzClient = new PtzClient(ctx);
|
||||
* await ptzClient.control({ camera, warehouseId, action, speed });
|
||||
*/
|
||||
|
||||
/** 打印服务云台端点路径 */
|
||||
const PTZ_PATH = {
|
||||
CONTROL: '/camera/ptzControl',
|
||||
STOP: '/camera/ptzStop',
|
||||
PRESET_GOTO: '/camera/ptzPresetGoto',
|
||||
PRESET_SET: '/camera/ptzPresetSet',
|
||||
};
|
||||
|
||||
/** 云台方向枚举(与打印服务约定的 8 个位置,顺序固定) */
|
||||
const PTZ_ACTION_LIST = [
|
||||
{ value: 'up', name: '上' },
|
||||
{ value: 'down', name: '下' },
|
||||
{ value: 'left', name: '左' },
|
||||
{ value: 'right', name: '右' },
|
||||
{ value: 'upleft', name: '左上' },
|
||||
{ value: 'upright', name: '右上' },
|
||||
{ value: 'downleft', name: '左下' },
|
||||
{ value: 'downright', name: '右下' },
|
||||
];
|
||||
|
||||
/** 云台方向值列表 */
|
||||
const PTZ_ACTIONS = PTZ_ACTION_LIST.map(item => item.value);
|
||||
|
||||
/** 默认转速 */
|
||||
const PTZ_DEFAULT_SPEED = 4;
|
||||
/** 转速下限 */
|
||||
const PTZ_MIN_SPEED = 1;
|
||||
/** 转速上限 */
|
||||
const PTZ_MAX_SPEED = 7;
|
||||
/** 预置点编号下限 */
|
||||
const PTZ_MIN_PRESET_ID = 1;
|
||||
/** 预置点编号上限 */
|
||||
const PTZ_MAX_PRESET_ID = 256;
|
||||
/** 打印服务请求超时(毫秒) */
|
||||
const PTZ_REQUEST_TIMEOUT = 10000;
|
||||
|
||||
class PtzClient {
|
||||
constructor(ctx) {
|
||||
this.ctx = ctx;
|
||||
this.logger = ctx.logger || console;
|
||||
}
|
||||
|
||||
/**
|
||||
* 云台方向枚举(供文档/校验共用)。
|
||||
* @return {Array<Object>} [{ value, name }]
|
||||
*/
|
||||
static getActionList() {
|
||||
return PTZ_ACTION_LIST.map(item => ({ ...item }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装摄像头 RTSP 地址。
|
||||
* 与 `lib/osd_client.js#buildRtspUrl` 保持同口径(打印服务以该地址定位摄像头)。
|
||||
*
|
||||
* @param {Object} camera - 摄像头记录(含 ip/username/password/channel_id)
|
||||
* @return {string} RTSP URL
|
||||
*/
|
||||
buildRtspUrl(camera) {
|
||||
const ip = camera && camera.ip;
|
||||
if (!ip) {
|
||||
throw new Error('摄像头未配置IP地址,无法组装RTSP地址');
|
||||
}
|
||||
|
||||
const username = camera.username || 'admin';
|
||||
const password = camera.password || '';
|
||||
const channelId = camera.channel_id;
|
||||
const rtspPort = 554;
|
||||
|
||||
return `rtsp://${username}:${password}@${ip}:${rtspPort}/stream${channelId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并归一化云台方向。
|
||||
*
|
||||
* @param {string} action - 云台方向
|
||||
* @param {string} [label] - 报错文案中的字段名
|
||||
* @return {string} 归一化后的方向值
|
||||
*/
|
||||
static normalizeAction(action, label = '云台方向') {
|
||||
const value = String(action === undefined || action === null ? '' : action).trim().toLowerCase();
|
||||
if (!value) throw new Error(`${label}不能为空`);
|
||||
if (!PTZ_ACTIONS.includes(value)) {
|
||||
throw new Error(`${label}不合法,仅支持:${PTZ_ACTIONS.join('/')}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并归一化云台转速(缺省 4)。
|
||||
*
|
||||
* @param {number|string} speed - 转速
|
||||
* @return {number} 归一化后的转速
|
||||
*/
|
||||
static normalizeSpeed(speed) {
|
||||
if (speed === undefined || speed === null || speed === '') return PTZ_DEFAULT_SPEED;
|
||||
const value = Number(speed);
|
||||
if (!Number.isInteger(value) || value < PTZ_MIN_SPEED || value > PTZ_MAX_SPEED) {
|
||||
throw new Error(`云台转速需为 ${PTZ_MIN_SPEED}-${PTZ_MAX_SPEED} 的整数`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并归一化预置点编号。
|
||||
*
|
||||
* @param {number|string} presetId - 预置点编号
|
||||
* @return {number} 归一化后的预置点编号
|
||||
*/
|
||||
static normalizePresetId(presetId) {
|
||||
if (presetId === undefined || presetId === null || presetId === '') {
|
||||
throw new Error('预置点编号不能为空');
|
||||
}
|
||||
const value = Number(presetId);
|
||||
if (!Number.isInteger(value) || value < PTZ_MIN_PRESET_ID || value > PTZ_MAX_PRESET_ID) {
|
||||
throw new Error(`预置点编号需为 ${PTZ_MIN_PRESET_ID}-${PTZ_MAX_PRESET_ID} 的整数`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 下发云台指令到打印服务(独立端点,与 setOSD 同风格,不带 computerId)。
|
||||
* 请求体统一携带 warehouse_id(字符串)与 cameraId(摄像头ID)。
|
||||
*
|
||||
* @param {Object} options - 指令参数
|
||||
* @param {Object} options.camera - 摄像头记录(取 id 作为 cameraId,并用于日志)
|
||||
* @param {string} options.path - 打印服务端点路径
|
||||
* @param {number} options.warehouseId - 仓库ID
|
||||
* @param {Object} options.data - 请求体业务字段
|
||||
* @return {Promise<Object>} { success, error, response, request }
|
||||
*/
|
||||
async _send(options = {}) {
|
||||
const { ctx } = this;
|
||||
const { camera, path: targetPath, warehouseId, data } = options;
|
||||
|
||||
if (!targetPath) throw new Error('打印服务端点路径不能为空');
|
||||
if (!camera) throw new Error('摄像头信息不能为空');
|
||||
|
||||
const warehouseValue = Number(warehouseId);
|
||||
if (!Number.isInteger(warehouseValue) || warehouseValue <= 0) {
|
||||
throw new Error('仓库ID不合法');
|
||||
}
|
||||
const cameraValue = Number(camera.id);
|
||||
if (!Number.isInteger(cameraValue) || cameraValue <= 0) {
|
||||
throw new Error('摄像头ID不合法');
|
||||
}
|
||||
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
const targetUrl = `${printServiceUrl}${targetPath}`;
|
||||
const requestData = {
|
||||
warehouse_id: String(warehouseValue),
|
||||
cameraId: cameraValue,
|
||||
...data,
|
||||
};
|
||||
|
||||
ctx.logger.info('[PTZ] 发送云台指令', { url: targetUrl, body: requestData });
|
||||
|
||||
let response = null;
|
||||
let error = null;
|
||||
try {
|
||||
const res = await ctx.curl(targetUrl, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: requestData,
|
||||
dataType: 'json',
|
||||
timeout: PTZ_REQUEST_TIMEOUT,
|
||||
});
|
||||
response = {
|
||||
status: res.status,
|
||||
headers: res.headers,
|
||||
data: res.data,
|
||||
};
|
||||
ctx.logger.info('[PTZ] 打印服务回信', { status: res.status, data: res.data });
|
||||
} catch (err) {
|
||||
error = err.message;
|
||||
ctx.logger.warn('[PTZ] 打印服务请求失败', {
|
||||
camera_id: camera && camera.id,
|
||||
url: targetUrl,
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
|
||||
const httpOk = !!response && response.status >= 200 && response.status < 300;
|
||||
const body = response && response.data;
|
||||
if (!error && httpOk && body && typeof body === 'object'
|
||||
&& (body.status === 'fail' || body.success === false)) {
|
||||
error = body.message || body.error || '打印服务返回失败';
|
||||
}
|
||||
|
||||
return {
|
||||
success: !error && httpOk,
|
||||
error,
|
||||
response,
|
||||
request: requestData,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按下:按指定方向转动云台。
|
||||
*
|
||||
* @param {Object} options - 参数
|
||||
* @param {Object} options.camera - 摄像头记录
|
||||
* @param {number} options.warehouseId - 仓库ID
|
||||
* @param {string} options.action - 云台方向(up/down/left/right/upleft/upright/downleft/downright)
|
||||
* @param {number} [options.speed] - 转速(1-7,默认 4)
|
||||
* @return {Promise<Object>} 打印服务响应
|
||||
*/
|
||||
async control(options = {}) {
|
||||
const { camera, warehouseId, action, speed } = options;
|
||||
if (!camera) throw new Error('摄像头信息不能为空');
|
||||
|
||||
return await this._send({
|
||||
camera,
|
||||
path: PTZ_PATH.CONTROL,
|
||||
warehouseId,
|
||||
data: {
|
||||
rtspUrl: this.buildRtspUrl(camera),
|
||||
action: PtzClient.normalizeAction(action),
|
||||
speed: PtzClient.normalizeSpeed(speed),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 松手:停止云台转动。
|
||||
*
|
||||
* @param {Object} options - 参数
|
||||
* @param {Object} options.camera - 摄像头记录
|
||||
* @param {number} options.warehouseId - 仓库ID
|
||||
* @param {string} options.action - 云台方向(必须与按下时一致)
|
||||
* @return {Promise<Object>} 打印服务响应
|
||||
*/
|
||||
async stop(options = {}) {
|
||||
const { camera, warehouseId, action } = options;
|
||||
if (!camera) throw new Error('摄像头信息不能为空');
|
||||
|
||||
return await this._send({
|
||||
camera,
|
||||
path: PTZ_PATH.STOP,
|
||||
warehouseId,
|
||||
data: {
|
||||
rtspUrl: this.buildRtspUrl(camera),
|
||||
action: PtzClient.normalizeAction(action),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 跳转预置点(一次调用即可,无需 stop)。
|
||||
*
|
||||
* @param {Object} options - 参数
|
||||
* @param {Object} options.camera - 摄像头记录
|
||||
* @param {number} options.warehouseId - 仓库ID
|
||||
* @param {number|string} options.presetId - 预置点编号(1-256)
|
||||
* @return {Promise<Object>} 打印服务响应
|
||||
*/
|
||||
async presetGoto(options = {}) {
|
||||
const { camera, warehouseId, presetId } = options;
|
||||
if (!camera) throw new Error('摄像头信息不能为空');
|
||||
|
||||
return await this._send({
|
||||
camera,
|
||||
path: PTZ_PATH.PRESET_GOTO,
|
||||
warehouseId,
|
||||
data: {
|
||||
rtspUrl: this.buildRtspUrl(camera),
|
||||
presetId: PtzClient.normalizePresetId(presetId),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置预置点:把摄像头当前机位保存为指定预置点编号(一次调用即可)。
|
||||
*
|
||||
* @param {Object} options - 参数
|
||||
* @param {Object} options.camera - 摄像头记录
|
||||
* @param {number} options.warehouseId - 仓库ID
|
||||
* @param {number|string} options.presetId - 预置点编号(1-256)
|
||||
* @return {Promise<Object>} 打印服务响应
|
||||
*/
|
||||
async presetSet(options = {}) {
|
||||
const { camera, warehouseId, presetId } = options;
|
||||
if (!camera) throw new Error('摄像头信息不能为空');
|
||||
|
||||
return await this._send({
|
||||
camera,
|
||||
path: PTZ_PATH.PRESET_SET,
|
||||
warehouseId,
|
||||
data: {
|
||||
rtspUrl: this.buildRtspUrl(camera),
|
||||
presetId: PtzClient.normalizePresetId(presetId),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PtzClient;
|
||||
module.exports.PTZ_PATH = PTZ_PATH;
|
||||
module.exports.PTZ_ACTIONS = PTZ_ACTIONS;
|
||||
module.exports.PTZ_DEFAULT_SPEED = PTZ_DEFAULT_SPEED;
|
||||
module.exports.PTZ_MAX_SPEED = PTZ_MAX_SPEED;
|
||||
module.exports.PTZ_MAX_PRESET_ID = PTZ_MAX_PRESET_ID;
|
||||
315
app/lib/qimen_client.js
Normal file
315
app/lib/qimen_client.js
Normal file
@ -0,0 +1,315 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('crypto');
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
|
||||
class QimenClient {
|
||||
constructor(app) {
|
||||
this.app = app;
|
||||
}
|
||||
|
||||
resolveRuntime(runtime = {}) {
|
||||
const ctx = runtime.ctx || {};
|
||||
const qimenService = ctx.service && ctx.service.qimen ? ctx.service.qimen : null;
|
||||
const signService = ctx.service && ctx.service.systems && ctx.service.systems.sign ? ctx.service.systems.sign : null;
|
||||
|
||||
return {
|
||||
ctx,
|
||||
toXml: runtime.toXml || (signService && typeof signService.toXml === 'function'
|
||||
? signService.toXml.bind(signService)
|
||||
: qimenService && typeof qimenService.formatResponse === 'function'
|
||||
? qimenService.formatResponse.bind(qimenService)
|
||||
: null),
|
||||
parseXmlToArray: runtime.parseXmlToArray || (qimenService && typeof qimenService.parseXmlToArray === 'function'
|
||||
? qimenService.parseXmlToArray.bind(qimenService)
|
||||
: null),
|
||||
saveQimenLog: runtime.saveQimenLog || (qimenService && typeof qimenService.saveQimenLog === 'function'
|
||||
? qimenService.saveQimenLog.bind(qimenService)
|
||||
: async () => null),
|
||||
signTopRequest: runtime.signTopRequest || (signService && typeof signService.signTopRequest === 'function'
|
||||
? signService.signTopRequest.bind(signService)
|
||||
: null),
|
||||
formatDate: runtime.formatDate || ctx.app?.formatDate || this.app.formatDate || (date => (date && typeof date.toISOString === 'function' ? date.toISOString() : String(date))),
|
||||
};
|
||||
}
|
||||
|
||||
normalizeRequestPayload(data) {
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
||||
return { request: data };
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(data, 'request')) {
|
||||
return data;
|
||||
}
|
||||
|
||||
return { request: data };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成出站奇门请求的唯一日志 ID。
|
||||
* 不复用入站请求的 ctx.qimenLogId,避免与入站文件队列落库产生唯一索引冲突。
|
||||
* @return {string} 唯一日志 ID。
|
||||
*/
|
||||
generateLogId() {
|
||||
return `QL-${Date.now()}-${crypto.randomBytes(3).toString('hex')}`;
|
||||
}
|
||||
|
||||
replaceXmlTagsWithString(xmlString, oldTag, newTag) {
|
||||
const startTagRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?>`, 'gi');
|
||||
const endTagRegex = new RegExp(`<\\s*/\\s*${oldTag}\\s*>`, 'gi');
|
||||
const selfClosingRegex = new RegExp(`<\\s*${oldTag}(\\s+[^>]*)?\\s*/>`, 'gi');
|
||||
|
||||
return xmlString
|
||||
.replace(startTagRegex, (match, attributes = '') => `<${newTag}${attributes}>`)
|
||||
.replace(endTagRegex, `</${newTag}>`)
|
||||
.replace(selfClosingRegex, (match, attributes = '') => `<${newTag}${attributes}/>`);
|
||||
}
|
||||
|
||||
replaceDeliveryConfirmSnListTags(xmlString) {
|
||||
const snListBlockRegex = /<\s*snList(\s+[^>]*)?>[\s\S]*?<\s*\/\s*snList\s*>/gi;
|
||||
|
||||
return String(xmlString || '').replace(snListBlockRegex, block => {
|
||||
// 奇门 deliveryorder.confirm 要求 snList 下为 <sn> 子节点,而 buildXmlNode 对标量数组统一输出 <item>
|
||||
return this.replaceXmlTagsWithString(block, 'item', 'sn');
|
||||
});
|
||||
}
|
||||
|
||||
replaceDeliveryConfirmOrderLineTags(xmlString) {
|
||||
const orderLinesBlockRegex = /<\s*orderLines(\s+[^>]*)?>[\s\S]*?<\s*\/\s*orderLines\s*>/gi;
|
||||
|
||||
return String(xmlString || '').replace(orderLinesBlockRegex, block => {
|
||||
// 先修正 snList 内的 <item>,否则会被下面的 item→orderLine 替换误伤
|
||||
const withSnList = this.replaceDeliveryConfirmSnListTags(block);
|
||||
return this.replaceXmlTagsWithString(withSnList, 'item', 'orderLine');
|
||||
});
|
||||
}
|
||||
|
||||
replaceDeliveryConfirmPackageTags(xmlString) {
|
||||
const packagesBlockRegex = /<\s*packages(\s+[^>]*)?>([\s\S]*?)<\s*\/\s*packages\s*>/gi;
|
||||
|
||||
return String(xmlString || '').replace(packagesBlockRegex, (match, attributes = '', inner = '') => {
|
||||
// buildXmlNode 把 packages.package 数组序列化成 <package><item>…</item></package>,
|
||||
// 奇门要求 <packages><package>…</package></packages>:去掉数组容器,再把每个 <item> 改名为 <package>,
|
||||
// 否则一单多运单号(多个包裹)时标签会错位成 <item>/</package>
|
||||
const withoutContainer = String(inner)
|
||||
.replace(/^\s*<\s*package\s*>/, '')
|
||||
.replace(/<\s*\/\s*package\s*>\s*$/, '');
|
||||
|
||||
// <items> 下的 <item> 是包裹内商品明细,必须保留原名;先占位保护,改名后再还原
|
||||
const innerItemsBlocks = [];
|
||||
const protectedInner = withoutContainer.replace(/<\s*items(\s+[^>]*)?>[\s\S]*?<\s*\/\s*items\s*>/gi, block => {
|
||||
innerItemsBlocks.push(block);
|
||||
return `@@PACKAGE_ITEMS_${innerItemsBlocks.length - 1}@@`;
|
||||
});
|
||||
|
||||
const renamed = this.replaceXmlTagsWithString(protectedInner, 'item', 'package');
|
||||
const restored = renamed.replace(/@@PACKAGE_ITEMS_(\d+)@@/g,
|
||||
(placeholder, index) => innerItemsBlocks[Number(index)] || placeholder);
|
||||
|
||||
return `<packages${attributes}>${restored}</packages>`;
|
||||
});
|
||||
}
|
||||
|
||||
replaceDeliveryConfirmPayloadTags(xmlString) {
|
||||
const withPackages = this.replaceDeliveryConfirmPackageTags(xmlString);
|
||||
return this.replaceDeliveryConfirmOrderLineTags(withPackages);
|
||||
}
|
||||
|
||||
addSign(baseQueryParams, sign) {
|
||||
return Object.assign({}, baseQueryParams, { sign });
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建奇门请求查询参数。
|
||||
* @param {string} method 接口方法名
|
||||
* @param {string} appKey 应用 Key
|
||||
* @param {string} version 接口版本
|
||||
* @param {?string} customerId 货主标识
|
||||
* @param {Function} formatDate 时间格式化函数
|
||||
* @return {Object} 查询参数对象
|
||||
*/
|
||||
getQueryParams(method, appKey, version, customerId, formatDate) {
|
||||
const queryParams = {
|
||||
method,
|
||||
format: 'xml',
|
||||
app_key: appKey,
|
||||
v: version,
|
||||
sign_method: 'md5',
|
||||
timestamp: formatDate(new Date()),
|
||||
};
|
||||
|
||||
if (customerId != null) {
|
||||
queryParams.customerId = customerId;
|
||||
}
|
||||
|
||||
return queryParams;
|
||||
}
|
||||
|
||||
generateUrlWithParams(baseUrl, params) {
|
||||
if (!params || Object.keys(params).length === 0) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
const queryString = Object.keys(params)
|
||||
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
|
||||
.join('&');
|
||||
|
||||
const separator = baseUrl.includes('?') ? '&' : '?';
|
||||
return `${baseUrl}${separator}${queryString}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送奇门请求并记录请求日志。
|
||||
* @param {string} method 接口方法名
|
||||
* @param {?string} customerId 货主标识
|
||||
* @param {Object} data 业务请求数据
|
||||
* @param {Object} runtime 运行时依赖
|
||||
* @return {Promise<{queryId: *, xmlArray: *}>} 查询结果
|
||||
*/
|
||||
async send(method, customerId, data, runtime = {}) {
|
||||
const helpers = this.resolveRuntime(runtime);
|
||||
|
||||
if (!helpers.toXml) {
|
||||
throw new Error('缺少奇门 XML 转换器');
|
||||
}
|
||||
|
||||
if (!helpers.parseXmlToArray) {
|
||||
throw new Error('缺少奇门响应解析器');
|
||||
}
|
||||
|
||||
if (!helpers.signTopRequest) {
|
||||
throw new Error('缺少奇门签名器');
|
||||
}
|
||||
|
||||
const wmsAppKey = this.app.config.qimen.appKey;
|
||||
const baseQueryParams = this.getQueryParams(method, wmsAppKey, '2.0', customerId, helpers.formatDate);
|
||||
const baseUrl = 'http://qimen.api.taobao.com/router/qimen/service';
|
||||
const requestPayload = this.normalizeRequestPayload(data);
|
||||
const xmlData = await helpers.toXml(requestPayload);
|
||||
const queryData = method === 'taobao.qimen.deliveryorder.confirm' || method === 'taobao.qimen.stockout.confirm'
|
||||
? this.replaceDeliveryConfirmPayloadTags(xmlData)
|
||||
: this.replaceXmlTagsWithString(xmlData, 'item', 'orderLine');
|
||||
const sign = await helpers.signTopRequest(baseQueryParams, queryData, this.app.config.qimen.security, 'md5');
|
||||
const queryParams = this.addSign(baseQueryParams, sign);
|
||||
const url = this.generateUrlWithParams(baseUrl, queryParams);
|
||||
const logData = {
|
||||
from_key: this.app.config.qimen.appKey,
|
||||
to_key: wmsAppKey,
|
||||
method,
|
||||
sign,
|
||||
v: '2.0',
|
||||
url,
|
||||
created_at: new Date(),
|
||||
body: '',
|
||||
result: '',
|
||||
use_time: 0,
|
||||
};
|
||||
|
||||
if (customerId != null) {
|
||||
logData.costomer_id = customerId;
|
||||
}
|
||||
console.log('发送奇门请求,URL:', url, '请求数据:', queryData);
|
||||
const result = await this.sendRequest(url, queryData, logData, helpers);
|
||||
console.log('奇门请求响应:', result);
|
||||
const xmlArray = await helpers.parseXmlToArray(result.res);
|
||||
return { queryId: result.queryId, xmlArray };
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送出站奇门 HTTP 请求,并把出站请求日志直接落库。
|
||||
* 出站日志使用独立生成的 log_id,不复用入站请求的 ctx.qimenLogId,
|
||||
* 避免与入站日志的文件队列落库路径产生 log_id 唯一索引冲突。
|
||||
* @param {string} url 请求地址。
|
||||
* @param {Object|string} requestData 请求数据(对象或 XML 字符串)。
|
||||
* @param {Object} [logData={}] 日志附加字段。
|
||||
* @param {Object} [runtime={}] 运行时依赖。
|
||||
* @return {Promise<{queryId: number|undefined, res: string}>} 查询 ID 与响应内容。
|
||||
*/
|
||||
async sendRequest(url, requestData, logData = {}, runtime = {}) {
|
||||
const helpers = this.resolveRuntime(runtime);
|
||||
const startTime = Date.now();
|
||||
// 出站请求不复用入站 ctx.qimenLogId:入站日志统一由文件队列异步落库,
|
||||
// log_id 唯一索引下共用同一 ID 会触发 Duplicate entry 冲突。
|
||||
const requestLogData = Object.assign({
|
||||
body: requestData,
|
||||
result: '',
|
||||
log_id: this.generateLogId(),
|
||||
}, logData);
|
||||
|
||||
requestLogData.body = requestLogData.body || requestData;
|
||||
requestLogData.result = requestLogData.result || '';
|
||||
requestLogData.log_id = requestLogData.log_id || this.generateLogId();
|
||||
|
||||
const httpquery = url.indexOf('https://') > -1 ? https : http;
|
||||
let requestXml;
|
||||
|
||||
try {
|
||||
if (typeof requestData === 'string') {
|
||||
requestXml = requestData;
|
||||
if (requestXml.trim() === '') {
|
||||
throw new Error('请求数据为空字符串');
|
||||
}
|
||||
} else {
|
||||
requestXml = await helpers.toXml(requestData);
|
||||
}
|
||||
|
||||
if (!requestXml || requestXml.trim() === '') {
|
||||
throw new Error('XML内容为空');
|
||||
}
|
||||
} catch (error) {
|
||||
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
|
||||
await helpers.saveQimenLog(requestLogData, startTime);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const header = {
|
||||
'Content-Type': 'application/xml',
|
||||
'Content-Length': Buffer.byteLength(requestXml, 'utf8'),
|
||||
'User-Agent': 'EggJS Client',
|
||||
};
|
||||
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: header,
|
||||
};
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await new Promise((resolve, reject) => {
|
||||
let req;
|
||||
try {
|
||||
req = httpquery.request(url, options, response => {
|
||||
let datas = '';
|
||||
response.on('data', chunk => {
|
||||
datas += chunk;
|
||||
});
|
||||
response.on('end', () => {
|
||||
resolve(datas);
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
req.on('error', error => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
req.write(requestXml);
|
||||
req.end();
|
||||
});
|
||||
} catch (error) {
|
||||
requestLogData.result = error.stack || `${error.name || 'Error'}: ${error.message || String(error)}`;
|
||||
await helpers.saveQimenLog(requestLogData, startTime);
|
||||
throw error;
|
||||
}
|
||||
|
||||
requestLogData.result = res;
|
||||
const queryId = await helpers.saveQimenLog(requestLogData, startTime);
|
||||
return { queryId, res };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = QimenClient;
|
||||
333
app/lib/query_condition_parser.js
Normal file
333
app/lib/query_condition_parser.js
Normal file
@ -0,0 +1,333 @@
|
||||
'use strict';
|
||||
|
||||
function isPlainObject(value) {
|
||||
return value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isEmptyValue(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && value.trim() === '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (Array.isArray(value) && value.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function formatLocalDateTime(date, isEnd = false) {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day} ${isEnd ? '23:59:59' : '00:00:00'}`;
|
||||
}
|
||||
|
||||
function normalizeDate(value, options = {}) {
|
||||
const { isEnd = false } = options;
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
if (isNaN(value.getTime())) return value;
|
||||
return formatLocalDateTime(value, isEnd);
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
const date = new Date(value);
|
||||
if (isNaN(date.getTime())) return value;
|
||||
return formatLocalDateTime(date, isEnd);
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const date = new Date(Number(trimmed));
|
||||
if (!isNaN(date.getTime())) {
|
||||
return formatLocalDateTime(date, isEnd);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const parsed = new Date(trimmed);
|
||||
if (!isNaN(parsed.getTime())) {
|
||||
return formatLocalDateTime(parsed, isEnd);
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function processConditionValue(value, type) {
|
||||
if (value === undefined || value === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case 'boolean':
|
||||
if (value === true || value === 'true' || value === 'Y' || value === 'y') {
|
||||
return 'Y';
|
||||
}
|
||||
if (value === false || value === 'false' || value === 'N' || value === 'n') {
|
||||
return 'N';
|
||||
}
|
||||
return value;
|
||||
|
||||
case 'date':
|
||||
return normalizeDate(value, { isEnd: false });
|
||||
|
||||
case 'daterange':
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((v, index) => normalizeDate(v, { isEnd: index === value.length - 1 }));
|
||||
}
|
||||
return normalizeDate(value, { isEnd: false });
|
||||
|
||||
case 'number': {
|
||||
const num = parseFloat(value);
|
||||
return isNaN(num) ? value : num;
|
||||
}
|
||||
|
||||
case 'text':
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(item => String(item).trim()).filter(Boolean);
|
||||
}
|
||||
return String(value).split(',').map(item => item.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function buildSequelizeCondition(fieldKey, condition, app) {
|
||||
if (!isPlainObject(condition)) {
|
||||
return { ok: false, reason: 'condition 必须是对象' };
|
||||
}
|
||||
|
||||
const { Sequelize } = app;
|
||||
const {
|
||||
operator = 'eq', value, type,
|
||||
} = condition;
|
||||
|
||||
const fieldName = condition.field || fieldKey;
|
||||
const processedValue = processConditionValue(value, type);
|
||||
const op = String(operator || 'eq').toLowerCase();
|
||||
|
||||
switch (op) {
|
||||
case 'eq':
|
||||
return { ok: true, condition: { [fieldName]: processedValue } };
|
||||
|
||||
case 'ne':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.ne]: processedValue } } };
|
||||
|
||||
case 'contains':
|
||||
case 'like':
|
||||
if (Array.isArray(processedValue) && processedValue.length > 0) {
|
||||
return {
|
||||
ok: true,
|
||||
condition: {
|
||||
[Sequelize.Op.or]: processedValue.map(val => ({
|
||||
[fieldName]: {
|
||||
[Sequelize.Op.like]: `%${val}%`,
|
||||
},
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}%` } } };
|
||||
|
||||
case 'notlike':
|
||||
if (Array.isArray(processedValue) && processedValue.length > 0) {
|
||||
return {
|
||||
ok: true,
|
||||
condition: {
|
||||
[Sequelize.Op.and]: processedValue.map(val => ({
|
||||
[fieldName]: {
|
||||
[Sequelize.Op.notLike]: `%${val}%`,
|
||||
},
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notLike]: `%${processedValue}%` } } };
|
||||
|
||||
case 'startswith':
|
||||
if (Array.isArray(processedValue) && processedValue.length > 0) {
|
||||
return {
|
||||
ok: true,
|
||||
condition: {
|
||||
[Sequelize.Op.or]: processedValue.map(val => ({
|
||||
[fieldName]: {
|
||||
[Sequelize.Op.like]: `${val}%`,
|
||||
},
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `${processedValue}%` } } };
|
||||
|
||||
case 'endswith':
|
||||
if (Array.isArray(processedValue) && processedValue.length > 0) {
|
||||
return {
|
||||
ok: true,
|
||||
condition: {
|
||||
[Sequelize.Op.or]: processedValue.map(val => ({
|
||||
[fieldName]: {
|
||||
[Sequelize.Op.like]: `%${val}`,
|
||||
},
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.like]: `%${processedValue}` } } };
|
||||
|
||||
case 'gt':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gt]: processedValue } } };
|
||||
|
||||
case 'lt':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lt]: processedValue } } };
|
||||
|
||||
case 'ge':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.gte]: processedValue } } };
|
||||
|
||||
case 'le':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.lte]: processedValue } } };
|
||||
|
||||
case 'in':
|
||||
if (!Array.isArray(processedValue)) {
|
||||
return { ok: false, reason: `${fieldName} 的 in 操作符要求 value 为数组` };
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.in]: processedValue } } };
|
||||
|
||||
case 'notin':
|
||||
if (!Array.isArray(processedValue)) {
|
||||
return { ok: false, reason: `${fieldName} 的 notin 操作符要求 value 为数组` };
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notIn]: processedValue } } };
|
||||
|
||||
case 'between':
|
||||
if (!Array.isArray(processedValue) || processedValue.length !== 2) {
|
||||
return { ok: false, reason: `${fieldName} 的 between 操作符要求 value 为长度为2的数组` };
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.between]: processedValue } } };
|
||||
|
||||
case 'notbetween':
|
||||
if (!Array.isArray(processedValue) || processedValue.length !== 2) {
|
||||
return { ok: false, reason: `${fieldName} 的 notbetween 操作符要求 value 为长度为2的数组` };
|
||||
}
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notBetween]: processedValue } } };
|
||||
|
||||
case 'isnull':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.is]: null } } };
|
||||
|
||||
case 'isnotnull':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.not]: null } } };
|
||||
|
||||
case 'regexp':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.regexp]: processedValue } } };
|
||||
|
||||
case 'notregexp':
|
||||
return { ok: true, condition: { [fieldName]: { [Sequelize.Op.notRegexp]: processedValue } } };
|
||||
|
||||
default:
|
||||
return { ok: true, condition: { [fieldName]: processedValue } };
|
||||
}
|
||||
}
|
||||
|
||||
function parseWhereConditions(options = {}) {
|
||||
const {
|
||||
where,
|
||||
app,
|
||||
specialFieldMap = {},
|
||||
} = options;
|
||||
|
||||
if (where === undefined || where === null) {
|
||||
return {
|
||||
ok: true,
|
||||
result: {
|
||||
dynamicConditions: [],
|
||||
bucketConditions: {},
|
||||
bucketFlags: {},
|
||||
rawConditionsByField: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!isPlainObject(where)) {
|
||||
return { ok: false, reason: 'where 必须是对象' };
|
||||
}
|
||||
|
||||
const dynamicConditions = [];
|
||||
const bucketConditions = {};
|
||||
const bucketFlags = {};
|
||||
const rawConditionsByField = {};
|
||||
|
||||
for (const [ fieldKey, condition ] of Object.entries(where)) {
|
||||
if (!isPlainObject(condition)) {
|
||||
return { ok: false, reason: `字段 ${fieldKey} 条件必须是对象` };
|
||||
}
|
||||
|
||||
if (isEmptyValue(condition.value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const mapped = specialFieldMap[fieldKey] || {};
|
||||
const normalizedCondition = {
|
||||
...condition,
|
||||
};
|
||||
|
||||
if (mapped.field) {
|
||||
normalizedCondition.field = mapped.field;
|
||||
}
|
||||
|
||||
const built = buildSequelizeCondition(fieldKey, normalizedCondition, app);
|
||||
if (!built.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: `字段 ${fieldKey} 解析失败: ${built.reason}`,
|
||||
};
|
||||
}
|
||||
|
||||
if (mapped.bucket) {
|
||||
if (!bucketConditions[mapped.bucket]) {
|
||||
bucketConditions[mapped.bucket] = [];
|
||||
}
|
||||
bucketConditions[mapped.bucket].push(built.condition);
|
||||
bucketFlags[mapped.bucket] = true;
|
||||
rawConditionsByField[fieldKey] = normalizedCondition;
|
||||
continue;
|
||||
}
|
||||
|
||||
dynamicConditions.push(built.condition);
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
result: {
|
||||
dynamicConditions,
|
||||
bucketConditions,
|
||||
bucketFlags,
|
||||
rawConditionsByField,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isEmptyValue,
|
||||
normalizeDate,
|
||||
processConditionValue,
|
||||
buildSequelizeCondition,
|
||||
parseWhereConditions,
|
||||
};
|
||||
171
app/lib/report/day_window.js
Normal file
171
app/lib/report/day_window.js
Normal file
@ -0,0 +1,171 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 报表「日窗口」纯函数工具模块(无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 日窗口定义:[D 07:00, D+1 07:00) 半开区间(毫秒时间戳),
|
||||
* 与旧 PHP《7日出入库数据》(Wms.php putout_putin_storage7) 的
|
||||
* 07:00 切日口径保持一致,统一使用服务器本地时区(不依赖 UTC)。
|
||||
*/
|
||||
|
||||
const DEFAULT_DAY_COUNT = 7;
|
||||
const DEFAULT_CUTOVER_HOUR = 7;
|
||||
|
||||
/**
|
||||
* 数字补零为两位字符串。
|
||||
* @param {number} value 数值
|
||||
* @return {string} 补零后的两位字符串
|
||||
*/
|
||||
function pad2(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 按本地时区构建连续的日窗口列表(最旧在前)。
|
||||
*
|
||||
* 规则:
|
||||
* 1. 每个窗口为 [D 07:00, D+1 07:00)(cutoverHour 可配置),start 含、end 不含;
|
||||
* 2. 最新窗口是「包含 now 的窗口」:now 当日已过切点时从今日切点起算,
|
||||
* 未过切点时从昨日切点起算;
|
||||
* 3. 窗口共 dayCount 个,按时间从旧到新排列;
|
||||
* 4. 通过 `new Date(y, m, d + offset, hour)` 构造,规避夏令时导致的 24h 步进偏差。
|
||||
*
|
||||
* @param {Object} [options={}] 构建选项
|
||||
* @param {number} [options.dayCount=7] 窗口数量
|
||||
* @param {number} [options.cutoverHour=7] 切点小时(0-23)
|
||||
* @param {number|Date} [options.now=Date.now()] 参考时刻
|
||||
* @return {Array<{start: number, end: number}>} 日窗口列表(毫秒,最旧在前)
|
||||
*/
|
||||
function buildDayWindows({ dayCount = DEFAULT_DAY_COUNT, cutoverHour = DEFAULT_CUTOVER_HOUR, now = Date.now() } = {}) {
|
||||
const normalizedCount = Math.max(1, Math.floor(Number(dayCount) || DEFAULT_DAY_COUNT));
|
||||
const normalizedHour = Math.min(23, Math.max(0, Math.floor(Number(cutoverHour) || 0)));
|
||||
const current = new Date(Number(now) || Date.now());
|
||||
|
||||
// 今天切点:本地时区当日 07:00
|
||||
let anchor = new Date(
|
||||
current.getFullYear(),
|
||||
current.getMonth(),
|
||||
current.getDate(),
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
|
||||
// 未到今日切点:最新窗口尚未开始,从昨日切点起算
|
||||
if (current.getTime() < anchor.getTime()) {
|
||||
anchor = new Date(
|
||||
anchor.getFullYear(),
|
||||
anchor.getMonth(),
|
||||
anchor.getDate() - 1,
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
const windows = [];
|
||||
for (let index = 0; index < normalizedCount; index += 1) {
|
||||
// 最旧在前:dayOffset 从 -(count-1) 递增到 0
|
||||
const dayOffset = index - (normalizedCount - 1);
|
||||
const start = new Date(
|
||||
anchor.getFullYear(),
|
||||
anchor.getMonth(),
|
||||
anchor.getDate() + dayOffset,
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
const end = new Date(
|
||||
anchor.getFullYear(),
|
||||
anchor.getMonth(),
|
||||
anchor.getDate() + dayOffset + 1,
|
||||
normalizedHour,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
);
|
||||
windows.push({
|
||||
start: start.getTime(),
|
||||
end: end.getTime(),
|
||||
});
|
||||
}
|
||||
|
||||
return windows;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 PHP date() 风格的 token 格式化窗口开始日期(本地时区,无前导零)。
|
||||
*
|
||||
* 支持的 token:
|
||||
* Y=四位年;y=两位年;m=补零月;n=无前导零月;d=补零日;j=无前导零日;
|
||||
* H=补零小时;i=补零分钟;s=补零秒。其余字符原样保留。
|
||||
*
|
||||
* @param {Array<{start: number, end: number}>} windows 日窗口列表
|
||||
* @param {number} index 窗口下标
|
||||
* @param {string} [pattern='Y/n/j'] 日期格式模板(如 '2026/8/23')
|
||||
* @return {string} 格式化后的日期字符串
|
||||
*/
|
||||
function formatWindowStart(windows, index, pattern = 'Y/n/j') {
|
||||
const windowItem = Array.isArray(windows) ? windows[index] : null;
|
||||
if (!windowItem || !Number.isFinite(Number(windowItem.start))) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const date = new Date(Number(windowItem.start));
|
||||
const tokens = {
|
||||
Y: String(date.getFullYear()),
|
||||
y: String(date.getFullYear()).slice(2),
|
||||
m: pad2(date.getMonth() + 1),
|
||||
n: String(date.getMonth() + 1),
|
||||
d: pad2(date.getDate()),
|
||||
j: String(date.getDate()),
|
||||
H: pad2(date.getHours()),
|
||||
i: pad2(date.getMinutes()),
|
||||
s: pad2(date.getSeconds()),
|
||||
};
|
||||
|
||||
return String(pattern || 'Y/n/j').replace(/[YymndjHis]/g, character => tokens[character]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 取时刻的本地 'HH:mm'(补零)。
|
||||
* @param {Date|number} date 日期对象或毫秒时间戳
|
||||
* @return {string} 'HH:mm' 格式字符串
|
||||
*/
|
||||
function hhmmOf(date) {
|
||||
const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now());
|
||||
return `${pad2(normalizedDate.getHours())}:${pad2(normalizedDate.getMinutes())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取时刻的本地自然日('YYYY-MM-DD')。
|
||||
* @param {Date|number} date 日期对象或毫秒时间戳
|
||||
* @return {string} 'YYYY-MM-DD' 格式字符串
|
||||
*/
|
||||
function scheduleDateOf(date) {
|
||||
const normalizedDate = date instanceof Date ? date : new Date(Number(date) || Date.now());
|
||||
return `${normalizedDate.getFullYear()}-${pad2(normalizedDate.getMonth() + 1)}-${pad2(normalizedDate.getDate())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从窗口参数对象解析 dayCount/cutoverHour,供查询器与元数据接口共用。
|
||||
* 口径与查询器保持一致:dayCount 缺省 7(<=0 视为 7),cutoverHour 缺省 7 且钳制到 0-23。
|
||||
* @param {Object} [params={}] 窗口参数(支持 dayCount/day_count、cutoverHour/cutover_hour)
|
||||
* @return {{dayCount: number, cutoverHour: number}} 归一化窗口参数
|
||||
*/
|
||||
function resolveWindowConfig(params = {}) {
|
||||
const dayCount = Math.max(1, Math.floor(Number(params.dayCount || params.day_count || 7)));
|
||||
const cutoverHour = Math.min(23, Math.max(0, Math.floor(Number(params.cutoverHour ?? params.cutover_hour ?? 7))));
|
||||
return { dayCount, cutoverHour };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildDayWindows,
|
||||
formatWindowStart,
|
||||
hhmmOf,
|
||||
scheduleDateOf,
|
||||
resolveWindowConfig,
|
||||
};
|
||||
167
app/lib/report/formatters.js
Normal file
167
app/lib/report/formatters.js
Normal file
@ -0,0 +1,167 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 报表单元格格式化器注册表(纯函数模块,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 设计约定:
|
||||
* 1. 所有格式化器首参为单元格原始值(value),其余参数为格式化参数;
|
||||
* 2. 数值计算统一走「截断取整」(等价旧 PHP 的 intval 语义,向零取整);
|
||||
* 3. 低库存补偿口径与旧 PHP《7日出入库数据》保持一致:
|
||||
* 可用库存 < 20 且 7 日入库 < 20 时视为低库存,触发补偿与预警。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 安全转数值:非有限数值一律按 0 处理。
|
||||
* @param {*} value 原始值
|
||||
* @return {number} 数值
|
||||
*/
|
||||
function toFiniteNumber(value) {
|
||||
const number = Number(value);
|
||||
return Number.isFinite(number) ? number : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 截断取整(PHP intval 语义,向零取整)。
|
||||
* @param {*} value 原始值
|
||||
* @return {number} 整数
|
||||
*/
|
||||
function integer(value) {
|
||||
return Math.trunc(toFiniteNumber(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* 零值占位:0 / '0' / null / undefined / '' 统一显示为 '-'。
|
||||
* 说明:'0' 一并转 '-',与 PHP empty('0') 为真的旧口径保持一致。
|
||||
* @param {*} value 原始值
|
||||
* @return {*} 非零原值或 '-'
|
||||
*/
|
||||
function zeroToDash(value) {
|
||||
if (value === 0 || value === '0' || value === null || value === undefined || value === '') {
|
||||
return '-';
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 布尔转中文:真值 → '是',假值 → '否'。
|
||||
* 说明:''、0、'0'、null、undefined、false 均视为假,与 PHP 布尔语义对齐。
|
||||
* @param {*} flag 原始值
|
||||
* @return {string} '是' 或 '否'
|
||||
*/
|
||||
function yesNo(flag) {
|
||||
const falsy = flag === false
|
||||
|| flag === null
|
||||
|| flag === undefined
|
||||
|| flag === ''
|
||||
|| flag === 0
|
||||
|| flag === '0'
|
||||
|| String(flag).toLowerCase() === 'false';
|
||||
return falsy ? '否' : '是';
|
||||
}
|
||||
|
||||
/**
|
||||
* 7 日日均 ×10 取整(保留一位小数但避免浮点误差)。
|
||||
* 公式:int(total / days * 10),与旧 PHP intval($ck / 7 * 10) 一致。
|
||||
* @param {*} value 周期合计值
|
||||
* @param {*} days 天数
|
||||
* @return {number} 日均×10 的整数
|
||||
*/
|
||||
function avgDaysPerWeek(value, days) {
|
||||
const total = toFiniteNumber(value);
|
||||
const dayCount = toFiniteNumber(days);
|
||||
if (dayCount <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return Math.trunc((total / dayCount) * 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 建议补货量(含低库存补偿):
|
||||
* 基础值 int(ck_total / 7 * 10);仅当低库存(available < 20 且 rk_total < 20)时
|
||||
* 补偿到不低于 30(保证低库存货主获得最小补货建议)。
|
||||
* @param {*} ckTotal 7 日总出库
|
||||
* @param {*} available 可用库存
|
||||
* @param {*} rkTotal 7 日总入库
|
||||
* @return {number} 建议补货量
|
||||
*/
|
||||
function suggestWithCompensate(ckTotal, available, rkTotal) {
|
||||
const base = Math.trunc((toFiniteNumber(ckTotal) / 7) * 10);
|
||||
const availableNumber = toFiniteNumber(available);
|
||||
const rkNumber = toFiniteNumber(rkTotal);
|
||||
if (availableNumber < 20 && rkNumber < 20) {
|
||||
return Math.max(base, 30);
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
/**
|
||||
* 库存预警判定(布尔):
|
||||
* 1. 按 7 日均出库 ×4 折算的周转阈值高于可用库存(int(ck/7*4) - available > 0);
|
||||
* 2. 或处于低库存状态(available < 20 且 rk_total < 20)。
|
||||
* 展示时建议叠加 yesNo 格式化器转中文。
|
||||
* @param {*} ckTotal 7 日总出库
|
||||
* @param {*} available 可用库存
|
||||
* @param {*} rkTotal 7 日总入库
|
||||
* @return {boolean} 是否预警
|
||||
*/
|
||||
function warnOf(ckTotal, available, rkTotal) {
|
||||
const threshold = Math.trunc((toFiniteNumber(ckTotal) / 7) * 4);
|
||||
return threshold - toFiniteNumber(available) > 0
|
||||
|| (toFiniteNumber(available) < 20 && toFiniteNumber(rkTotal) < 20);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文本前缀工厂:返回一个给文本加前缀的格式化函数。
|
||||
* 典型用法:`'` 前缀防科学计数法(Excel 将长数字串强制按文本展示)。
|
||||
* @param {string} [prefix=''] 前缀
|
||||
* @return {Function} 格式化函数 (value) => `${prefix}${value}`
|
||||
*/
|
||||
function textPrefix(prefix = '') {
|
||||
return value => `${String(prefix || '')}${value === null || value === undefined ? '' : String(value)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化器注册表(配置驱动报表按名称引用)。
|
||||
* @type {Object<string, Function>}
|
||||
*/
|
||||
const FORMATTERS = Object.freeze({
|
||||
textPrefix: (value, prefix) => textPrefix(prefix)(value),
|
||||
zeroToDash,
|
||||
yesNo,
|
||||
integer,
|
||||
avgDaysPerWeek,
|
||||
suggestWithCompensate,
|
||||
warnOf,
|
||||
});
|
||||
|
||||
/**
|
||||
* 按名称应用格式化器。
|
||||
* @param {string} name 格式化器名称
|
||||
* @param {*} value 单元格原始值
|
||||
* @param {...*} args 格式化器额外参数
|
||||
* @return {*} 格式化结果
|
||||
* @throws {Error} 未知格式化器名称时抛出
|
||||
*/
|
||||
function applyFormat(name, value, ...args) {
|
||||
const formatterName = String(name || '').trim();
|
||||
if (!formatterName) {
|
||||
return value;
|
||||
}
|
||||
const formatter = FORMATTERS[formatterName];
|
||||
if (typeof formatter !== 'function') {
|
||||
throw new Error(`未知的报表格式化器: ${formatterName}`);
|
||||
}
|
||||
return formatter(value, ...args);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FORMATTERS,
|
||||
applyFormat,
|
||||
textPrefix,
|
||||
zeroToDash,
|
||||
yesNo,
|
||||
integer,
|
||||
avgDaysPerWeek,
|
||||
suggestWithCompensate,
|
||||
warnOf,
|
||||
};
|
||||
101
app/lib/report/notifyTemplate.js
Normal file
101
app/lib/report/notifyTemplate.js
Normal file
@ -0,0 +1,101 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 货主报表文本通知模板渲染器(纯函数模块,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 标签白名单(其余 {xxx} 一律不替换,保存入口由 reportDelivery.savePlan 校验拦截):
|
||||
* - {time} 发送时间,格式 YYYY-MM-DD HH:mm
|
||||
* - {url} 报表文件下载链接(url 为空时替换为兜底文案)
|
||||
* - {report_name} 报表名称
|
||||
* - {biz_date} 数据日期 YYYY-MM-DD
|
||||
*/
|
||||
|
||||
/** 模板标签白名单 */
|
||||
const ALLOWED_TAGS = Object.freeze([ 'time', 'url', 'report_name', 'biz_date' ]);
|
||||
|
||||
/**
|
||||
* url 为空时的兜底文案。
|
||||
* 理由:生成结果 url 可能因异步上传尚未就绪,以占位文案保证通知可达,
|
||||
* 避免因链接缺失引发整链路失败重试风暴;实际链接可在投递记录中查看。
|
||||
*/
|
||||
const EMPTY_URL_FALLBACK = '文件生成中,稍后可在投递记录中查看';
|
||||
|
||||
/** 模板标签匹配正则:{xxx} 占位 */
|
||||
const TAG_PATTERN = /\{([^{}]+)\}/g;
|
||||
|
||||
/**
|
||||
* 提取模板中出现过的全部标签名(按出现顺序,含重复项)。
|
||||
* @param {string} template 模板字符串
|
||||
* @return {Array<string>} 标签名数组
|
||||
*/
|
||||
function extractTagNames(template) {
|
||||
const names = [];
|
||||
const source = String(template || '');
|
||||
let match = TAG_PATTERN.exec(source);
|
||||
while (match) {
|
||||
names.push(String(match[1]).trim());
|
||||
match = TAG_PATTERN.exec(source);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验模板标签是否全部位于白名单内(未知标签不替换、保存时拒绝)。
|
||||
* @param {string} template 模板字符串
|
||||
* @return {{valid: boolean, invalidTags: Array<string>}} 校验结果(invalidTags 已去重)
|
||||
*/
|
||||
function validateNotifyTemplate(template) {
|
||||
const names = extractTagNames(template);
|
||||
const invalidSet = new Set();
|
||||
for (const name of names) {
|
||||
if (!ALLOWED_TAGS.includes(name)) {
|
||||
invalidSet.add(name);
|
||||
}
|
||||
}
|
||||
return { valid: invalidSet.size === 0, invalidTags: [ ...invalidSet ] };
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染通知模板:仅替换白名单标签,未知标签原样保留(保存入口已校验拦截)。
|
||||
* @param {string} template 模板字符串
|
||||
* @param {Object} [context={}] 渲染上下文
|
||||
* @param {string} [context.time=''] 发送时间(YYYY-MM-DD HH:mm)
|
||||
* @param {string} [context.url=''] 报表文件下载链接(空则替换为兜底文案)
|
||||
* @param {string} [context.reportName=''] 报表名称
|
||||
* @param {string} [context.bizDate=''] 数据日期(YYYY-MM-DD)
|
||||
* @return {string} 渲染后的通知文本
|
||||
*/
|
||||
function renderNotifyTemplate(template, context = {}) {
|
||||
const url = String((context && context.url) || '').trim() || EMPTY_URL_FALLBACK;
|
||||
const replacements = {
|
||||
time: String((context && context.time) || ''),
|
||||
url,
|
||||
report_name: String((context && context.reportName) || ''),
|
||||
biz_date: String((context && context.bizDate) || ''),
|
||||
};
|
||||
return String(template || '').replace(TAG_PATTERN, (raw, name) => {
|
||||
const key = String(name).trim();
|
||||
return Object.prototype.hasOwnProperty.call(replacements, key) ? replacements[key] : raw;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化发送时间为 YYYY-MM-DD HH:mm(服务器本地时区)。
|
||||
* @param {Date} [date=new Date()] 时刻
|
||||
* @return {string} 格式化后的时间字符串
|
||||
*/
|
||||
function formatNotifyTime(date) {
|
||||
const target = date instanceof Date ? date : new Date();
|
||||
const pad = value => String(value).padStart(2, '0');
|
||||
return `${target.getFullYear()}-${pad(target.getMonth() + 1)}-${pad(target.getDate())} `
|
||||
+ `${pad(target.getHours())}:${pad(target.getMinutes())}`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ALLOWED_TAGS,
|
||||
EMPTY_URL_FALLBACK,
|
||||
extractTagNames,
|
||||
validateNotifyTemplate,
|
||||
renderNotifyTemplate,
|
||||
formatNotifyTime,
|
||||
};
|
||||
233
app/lib/report/render.js
Normal file
233
app/lib/report/render.js
Normal file
@ -0,0 +1,233 @@
|
||||
'use strict';
|
||||
|
||||
const { applyFormat } = require('./formatters');
|
||||
const { formatWindowStart } = require('./day_window');
|
||||
|
||||
/**
|
||||
* 报表渲染翻译层(纯函数模块,无 ctx 依赖,可单测)。
|
||||
*
|
||||
* 输入:报表类型 type 的硬编码字段注册清单(fields,按勾选顺序)+ 查询器产出的数据 rows;
|
||||
* 输出:适配 `app/service/systems/excel.js` 的 sheets 参数结构
|
||||
* ({ name, columns, rows, merges, styledRows, textColumns? })。
|
||||
*
|
||||
* 约定(与 excel.js 的 buildExcelJsWorkbook 对齐):
|
||||
* 1. 数据以 AOA(二维数组)形式输出,表头行内联在 rows 首位,columns 恒传空数组;
|
||||
* 2. merges 统一输出 {s:{r,c}, e:{r,c}} 结构(excel.js 两套构建器均支持);
|
||||
* 3. textColumns 输出 0 基列索引,由 excel.js 落地为文本单元格。
|
||||
*
|
||||
* 列规则(全部由字段注册清单硬编码决定,无 sheet_config 自定义):
|
||||
* 1. string 字段 → 静态列(header=label),asText=true 时加入 textColumns;
|
||||
* 2. number 字段 → 静态列,统一 zeroToDash(0/''/null 显示 '-');
|
||||
* 3. boolean 字段 → 静态列,统一 yesNo(真→是,假→否);
|
||||
* 4. array 字段 → 窗口展开列:per=窗口数,pair=children keys,表头第 1 行按窗口
|
||||
* 输出 '{date}' 日期(Y/n/j 无前导零)并在每窗口 pair.length>1 时横向合并,
|
||||
* 表头第 2 行按 children label 填充;子字段为 number 时单元格统一 zeroToDash;
|
||||
* 5. 存在展开列时启用两行表头,其余列表头纵向合并(如 A1:A2)。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 判断字段是否为普通对象。
|
||||
* @param {*} field 待判断字段
|
||||
* @return {boolean} 是否普通对象
|
||||
*/
|
||||
function isPlainObject(field) {
|
||||
return Boolean(field) && typeof field === 'object' && !Array.isArray(field);
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化字段注册清单:仅保留含 key 的对象,key 统一为字符串。
|
||||
* @param {Array<Object>} fields 字段清单(注册表 fields,按勾选顺序)
|
||||
* @return {Array<Object>} 规范化字段清单
|
||||
*/
|
||||
function normalizeFields(fields) {
|
||||
if (!Array.isArray(fields)) {
|
||||
return [];
|
||||
}
|
||||
return fields
|
||||
.filter(field => isPlainObject(field) && String(field.key || '').trim())
|
||||
.map(field => ({ ...field, key: String(field.key).trim() }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按类型字段清单构建列计划(含窗口展开与表头合并)。
|
||||
* @param {Object} [options={}] 构建选项
|
||||
* @param {Array<Object>} [options.fields=[]] 字段注册清单(按勾选顺序)
|
||||
* @param {Array<Object>} [options.windows=[]] 日窗口列表(展开列 per 取窗口数)
|
||||
* @return {{columns: Array<Object>, headerRowCount: number, generatedMerges: Array<Object>}} 列计划
|
||||
*/
|
||||
function buildColumnPlan({ fields = [], windows = [] } = {}) {
|
||||
const safeFields = normalizeFields(fields);
|
||||
const safeWindows = Array.isArray(windows) ? windows : [];
|
||||
const expandPer = Math.max(1, safeWindows.length || 7);
|
||||
|
||||
const columns = [];
|
||||
const generatedMerges = [];
|
||||
let expandStartColumn = -1;
|
||||
|
||||
for (const field of safeFields) {
|
||||
if (field.type === 'array') {
|
||||
const children = Array.isArray(field.children) ? field.children : [];
|
||||
const pair = children.length > 0 ? children : [{ key: 'value', label: '值', type: 'string' }];
|
||||
expandStartColumn = columns.length;
|
||||
for (let windowIndex = 0; windowIndex < expandPer; windowIndex += 1) {
|
||||
for (let pairIndex = 0; pairIndex < pair.length; pairIndex += 1) {
|
||||
columns.push({
|
||||
type: 'expand',
|
||||
windowIndex,
|
||||
pairIndex,
|
||||
pair: pair[pairIndex] && isPlainObject(pair[pairIndex]) ? pair[pairIndex] : {},
|
||||
headerRow1Template: '{date}',
|
||||
headerRow2List: pair.map(child => String((child && child.label) || '')),
|
||||
});
|
||||
}
|
||||
if (pair.length > 1) {
|
||||
// 每窗口多列表头横向合并(如 D1:E1 … P1:Q1)
|
||||
const groupStart = expandStartColumn + windowIndex * pair.length;
|
||||
generatedMerges.push({
|
||||
s: { r: 0, c: groupStart },
|
||||
e: { r: 0, c: groupStart + pair.length - 1 },
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
columns.push({
|
||||
type: field.type === 'array' ? 'static' : (field.type || 'string'),
|
||||
header: String(field.label || field.key || ''),
|
||||
field: field.key,
|
||||
asText: field.asText === true,
|
||||
});
|
||||
}
|
||||
|
||||
const hasExpandColumn = columns.some(column => column.type === 'expand');
|
||||
const headerRowCount = hasExpandColumn ? 2 : 1;
|
||||
|
||||
// 两行表头下,非展开列按列纵向合并(A1:A2 等)
|
||||
if (headerRowCount === 2) {
|
||||
columns.forEach((column, columnIndex) => {
|
||||
if (column.type !== 'expand') {
|
||||
generatedMerges.push({
|
||||
s: { r: 0, c: columnIndex },
|
||||
e: { r: 1, c: columnIndex },
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
columns,
|
||||
headerRowCount,
|
||||
generatedMerges,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建表头第 1 行(展开列按窗口开始日期输出 'Y/n/j' 无前导零)。
|
||||
* @param {Array<Object>} columns 列计划
|
||||
* @param {Array<Object>} windows 日窗口列表
|
||||
* @return {Array<string>} 表头第 1 行
|
||||
*/
|
||||
function buildHeaderRow1(columns, windows = []) {
|
||||
return columns.map(column => {
|
||||
if (column.type === 'expand') {
|
||||
return formatWindowStart(windows, column.windowIndex, 'Y/n/j');
|
||||
}
|
||||
return column.header;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建表头第 2 行(单行表头模式下返回 null;展开列按 pair label 填充)。
|
||||
* @param {Array<Object>} columns 列计划
|
||||
* @param {number} headerRowCount 表头行数
|
||||
* @return {Array<string>|null} 表头第 2 行
|
||||
*/
|
||||
function buildHeaderRow2(columns, headerRowCount) {
|
||||
if (headerRowCount !== 2) {
|
||||
return null;
|
||||
}
|
||||
return columns.map(column => {
|
||||
if (column.type === 'expand') {
|
||||
const list = column.headerRow2List;
|
||||
return list.length > 0 ? list[column.pairIndex % list.length] || '' : '';
|
||||
}
|
||||
return '';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染单个单元格(按列类型与字段类型硬编码格式化口径)。
|
||||
* @param {Object} column 列计划
|
||||
* @param {Object} row 数据行
|
||||
* @return {*} 单元格值
|
||||
*/
|
||||
function renderCell(column, row = {}) {
|
||||
if (column.type === 'expand') {
|
||||
const daily = Array.isArray(row.daily) ? row.daily : [];
|
||||
const day = daily[column.windowIndex];
|
||||
const value = day && typeof day === 'object' ? day[column.pair.key] : 0;
|
||||
return applyFormat(column.pair.type === 'number' ? 'zeroToDash' : '', value);
|
||||
}
|
||||
|
||||
const value = row[column.field];
|
||||
if (column.type === 'boolean') {
|
||||
return applyFormat('yesNo', value);
|
||||
}
|
||||
if (column.type === 'number') {
|
||||
return applyFormat('zeroToDash', value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按类型字段注册清单渲染 sheet(配置极简:无 sheet_config 自定义列/合并/样式)。
|
||||
*
|
||||
* @param {Object} [options={}] 渲染选项
|
||||
* @param {string} [options.type=''] 报表类型(查询器注册 key,仅透传不参与渲染口径)
|
||||
* @param {string} [options.title='报表'] sheet 名称(报表标题)
|
||||
* @param {Array<Object>} [options.fields=[]] 字段注册清单(按勾选顺序)
|
||||
* @param {Array<Object>} [options.rows=[]] 查询器产出的数据行
|
||||
* @param {Array<Object>} [options.windows=[]] 日窗口列表
|
||||
* @return {Object} excel.js sheet 参数
|
||||
* ({name, columns, rows, merges, styledRows},存在 asText 列时附带 textColumns)
|
||||
*/
|
||||
function renderSheetByType({ type = '', title = '报表', fields = [], rows = [], windows = [] } = {}) {
|
||||
void type;
|
||||
const plan = buildColumnPlan({ fields, windows });
|
||||
const safeRows = Array.isArray(rows) ? rows : [];
|
||||
|
||||
const headerRow1 = buildHeaderRow1(plan.columns, windows);
|
||||
const headerRow2 = buildHeaderRow2(plan.columns, plan.headerRowCount);
|
||||
|
||||
const aoaRows = [ headerRow1 ];
|
||||
if (headerRow2) {
|
||||
aoaRows.push(headerRow2);
|
||||
}
|
||||
for (const row of safeRows) {
|
||||
aoaRows.push(plan.columns.map(column => renderCell(column, row)));
|
||||
}
|
||||
|
||||
// asText 列收集为 0 基列索引,交由 excel.js 落地文本单元格(无 asText 时不输出)
|
||||
const textColumns = plan.columns
|
||||
.map((column, columnIndex) => (column.asText ? columnIndex : -1))
|
||||
.filter(columnIndex => columnIndex >= 0);
|
||||
|
||||
const result = {
|
||||
name: String(title || '报表'),
|
||||
columns: [],
|
||||
rows: aoaRows,
|
||||
merges: plan.generatedMerges,
|
||||
styledRows: [],
|
||||
};
|
||||
|
||||
if (textColumns.length > 0) {
|
||||
result.textColumns = textColumns;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
renderSheetByType,
|
||||
buildColumnPlan,
|
||||
};
|
||||
53
app/lib/shop_soft_delete.js
Normal file
53
app/lib/shop_soft_delete.js
Normal file
@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
const DELETED_SHOP_NAME_PREFIX = 'DELETED_SHOP_';
|
||||
|
||||
/**
|
||||
* 判断店铺名是否为软删除墓碑名。
|
||||
*
|
||||
* @param {*} shopName 店铺名称
|
||||
* @return {boolean} 是否为已软删除店铺
|
||||
*/
|
||||
function isDeletedShopName(shopName) {
|
||||
return String(shopName || '').trim().startsWith(DELETED_SHOP_NAME_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断店铺记录是否为软删除状态。
|
||||
*
|
||||
* @param {Object} shop 店铺记录或模型实例
|
||||
* @return {boolean} 是否已软删除
|
||||
*/
|
||||
function isSoftDeletedShop(shop) {
|
||||
if (!shop || typeof shop !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const plainShop = typeof shop.get === 'function'
|
||||
? shop.get({ plain: true })
|
||||
: shop;
|
||||
|
||||
return isDeletedShopName(plainShop && plainShop.shop_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建排除软删除店铺的 Sequelize where 条件。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例
|
||||
* @param {string} [fieldName='shop_name'] 店铺名字段名
|
||||
* @return {Object} Sequelize where 条件
|
||||
*/
|
||||
function buildNotDeletedShopWhere(app, fieldName = 'shop_name') {
|
||||
return {
|
||||
[fieldName]: {
|
||||
[app.Sequelize.Op.notLike]: `${DELETED_SHOP_NAME_PREFIX}%`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DELETED_SHOP_NAME_PREFIX,
|
||||
isDeletedShopName,
|
||||
isSoftDeletedShop,
|
||||
buildNotDeletedShopWhere,
|
||||
};
|
||||
147
app/lib/stop_current_egg.js
Normal file
147
app/lib/stop_current_egg.js
Normal file
@ -0,0 +1,147 @@
|
||||
'use strict';
|
||||
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
const isWin = process.platform === 'win32';
|
||||
const appRoot = process.cwd();
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
function listNodeProcesses() {
|
||||
if (isWin) {
|
||||
try {
|
||||
const output = execFileSync('wmic', [ 'Path', 'win32_process', 'Where', "Name = 'node.exe'", 'Get', 'CommandLine,ProcessId' ], {
|
||||
encoding: 'utf8',
|
||||
stdio: [ 'ignore', 'pipe', 'pipe' ],
|
||||
});
|
||||
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean)
|
||||
.map(line => {
|
||||
const match = line.match(/^(.*)\s+(\d+)$/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
pid: Number(match[2]),
|
||||
cmd: match[1],
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
const output = execFileSync('powershell', [
|
||||
'-NoProfile',
|
||||
'-Command',
|
||||
"Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Select-Object ProcessId, CommandLine | ConvertTo-Json -Compress",
|
||||
], {
|
||||
encoding: 'utf8',
|
||||
stdio: [ 'ignore', 'pipe', 'pipe' ],
|
||||
}).trim();
|
||||
|
||||
if (!output) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(output);
|
||||
const items = Array.isArray(parsed) ? parsed : [ parsed ];
|
||||
return items
|
||||
.map(item => ({
|
||||
pid: Number(item.ProcessId),
|
||||
cmd: String(item.CommandLine || ''),
|
||||
}))
|
||||
.filter(item => item.pid && item.cmd);
|
||||
}
|
||||
}
|
||||
|
||||
const output = execFileSync('ps', [ '-eo', 'pid=,args=' ], {
|
||||
encoding: 'utf8',
|
||||
stdio: [ 'ignore', 'pipe', 'pipe' ],
|
||||
});
|
||||
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean)
|
||||
.map(line => {
|
||||
const match = line.match(/^(\d+)\s+(.*)$/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
pid: Number(match[1]),
|
||||
cmd: match[2],
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function isMasterProcess(cmd) {
|
||||
return cmd.includes('start-cluster');
|
||||
}
|
||||
|
||||
function isWorkerProcess(cmd) {
|
||||
return cmd.includes('egg-cluster/lib/app_worker.js')
|
||||
|| cmd.includes('egg-cluster/lib/agent_worker.js')
|
||||
|| cmd.includes('egg-cluster\\lib\\app_worker.js')
|
||||
|| cmd.includes('egg-cluster\\lib\\agent_worker.js');
|
||||
}
|
||||
|
||||
function matchesCurrentApp(processInfo) {
|
||||
if (!processInfo || !processInfo.cmd || !processInfo.pid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (processInfo.pid === process.pid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return processInfo.cmd.includes(appRoot) && (isMasterProcess(processInfo.cmd) || isWorkerProcess(processInfo.cmd));
|
||||
}
|
||||
|
||||
function killPids(pids, signal) {
|
||||
for (const pid of pids) {
|
||||
try {
|
||||
process.kill(pid, signal);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ESRCH') {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const processList = listNodeProcesses().filter(matchesCurrentApp);
|
||||
const masterPids = processList.filter(item => isMasterProcess(item.cmd)).map(item => item.pid);
|
||||
|
||||
if (masterPids.length > 0) {
|
||||
console.log(`stopping current egg masters: ${masterPids.join(', ')}`);
|
||||
killPids(masterPids, 'SIGTERM');
|
||||
await sleep(5000);
|
||||
} else {
|
||||
console.log('no current egg master process found');
|
||||
}
|
||||
|
||||
const remainingWorkers = listNodeProcesses()
|
||||
.filter(matchesCurrentApp)
|
||||
.filter(item => isWorkerProcess(item.cmd))
|
||||
.map(item => item.pid);
|
||||
|
||||
if (remainingWorkers.length > 0) {
|
||||
console.log(`killing remaining current egg workers: ${remainingWorkers.join(', ')}`);
|
||||
killPids(remainingWorkers, 'SIGKILL');
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(error.message || error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
93
app/lib/warehouse_shard_guard.js
Normal file
93
app/lib/warehouse_shard_guard.js
Normal file
@ -0,0 +1,93 @@
|
||||
'use strict';
|
||||
|
||||
const MAX_DECIMAL_DIGITS = 20;
|
||||
|
||||
/**
|
||||
* 将分表用的仓库 ID 规范为纯十进制数字串(与 wms_store.id / BIGINT 一致)。
|
||||
* @param {*} value 待规范化的仓库 ID。
|
||||
* @return {string} 规范化后的仓库 ID 字符串。
|
||||
*/
|
||||
function normalizeWarehouseShardId(value) {
|
||||
if (value === null || value === undefined || value === '') {
|
||||
throw new Error('warehouse_id 不能为空');
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
throw new Error('warehouse_id 必须为数字');
|
||||
}
|
||||
const s = String(value).trim();
|
||||
if (!/^\d+$/.test(s)) {
|
||||
throw new Error('warehouse_id 必须为数字');
|
||||
}
|
||||
if (s === '0') {
|
||||
throw new Error('warehouse_id 非法');
|
||||
}
|
||||
if (s.length > MAX_DECIMAL_DIGITS) {
|
||||
throw new Error('warehouse_id 超出范围');
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 wms_store 中存在对应 ID 且主体为仓库(project = warehouse)。
|
||||
* @param {import('egg').Application} app 应用实例。
|
||||
* @param {string} warehouseIdStr normalizeWarehouseShardId 的返回值。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async function assertWarehouseStoreSubject(app, warehouseIdStr) {
|
||||
if (!app.model || !app.model.Store) {
|
||||
return;
|
||||
}
|
||||
const row = await app.model.Store.findOne({
|
||||
where: {
|
||||
id: warehouseIdStr,
|
||||
project: 'warehouse',
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
paranoid: true,
|
||||
});
|
||||
if (!row) {
|
||||
throw new Error(`仓库主体不存在或非仓库类型(wms_store.project 须为 warehouse): ${warehouseIdStr}`);
|
||||
}
|
||||
}
|
||||
|
||||
function validatedSetFor(app) {
|
||||
if (!app._shardWarehouseIdsValidated) {
|
||||
app._shardWarehouseIdsValidated = new Set();
|
||||
}
|
||||
return app._shardWarehouseIdsValidated;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范化并校验仓库分表 ID。
|
||||
* @param {import('egg').Application} app 应用实例。
|
||||
* @param {*} raw 原始仓库 ID。
|
||||
* @return {Promise<string>} 规范化并校验后的仓库 ID 字符串。
|
||||
*/
|
||||
async function ensureShardWarehouseId(app, raw) {
|
||||
const idStr = normalizeWarehouseShardId(raw);
|
||||
const validatedSet = validatedSetFor(app);
|
||||
if (validatedSet.has(idStr)) {
|
||||
return idStr;
|
||||
}
|
||||
await assertWarehouseStoreSubject(app, idStr);
|
||||
validatedSet.add(idStr);
|
||||
return idStr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理进程内「已校验仓库主体」缓存(例如单测或手动 clear 动态模型缓存时)。
|
||||
* @param {import('egg').Application} app 应用实例。
|
||||
* @return {void}
|
||||
*/
|
||||
function clearShardWarehouseValidationCache(app) {
|
||||
if (app && app._shardWarehouseIdsValidated) {
|
||||
app._shardWarehouseIdsValidated.clear();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeWarehouseShardId,
|
||||
assertWarehouseStoreSubject,
|
||||
ensureShardWarehouseId,
|
||||
clearShardWarehouseValidationCache,
|
||||
};
|
||||
195
app/lib/wave_strategy_quick_scan_runner.js
Normal file
195
app/lib/wave_strategy_quick_scan_runner.js
Normal file
@ -0,0 +1,195 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 执行波次策略快速扫描通用流程。
|
||||
*
|
||||
* @param {Object} [options={}] 扫描参数。
|
||||
* @param {Array<Object>} [options.orders] 订单数组。
|
||||
* @param {Array<Object>} [options.strategyList] 策略数组。
|
||||
* @param {Function} [options.getStructureKey] 获取订单结构 key。
|
||||
* @param {Function} [options.getExpressKey] 获取订单快递 key。
|
||||
* @param {Function} [options.isOrderMatched] 判断订单是否命中策略。
|
||||
* @param {Function} [options.getMatchedStrategyIds] 获取订单命中策略ID数组。
|
||||
* @param {Function} [options.onProgress] 异步进度回调。
|
||||
* @return {Promise<{totalOrderCount:number, processedOrderCount:number, matchedOrderIds:Array<number>, unmatchedOrderIds:Array<number>, matchedStrategyIdsByOrder:Object}>} 扫描结果。
|
||||
*/
|
||||
async function runWaveStrategyQuickScanRunner(options = {}) {
|
||||
const normalizedOptions = options && typeof options === 'object' ? options : {};
|
||||
const normalizedOrders = Array.isArray(normalizedOptions.orders) ? normalizedOptions.orders : [];
|
||||
const strategyList = Array.isArray(normalizedOptions.strategyList) ? normalizedOptions.strategyList : [];
|
||||
const getStructureKey = typeof normalizedOptions.getStructureKey === 'function'
|
||||
? normalizedOptions.getStructureKey
|
||||
: () => '';
|
||||
const getExpressKey = typeof normalizedOptions.getExpressKey === 'function'
|
||||
? normalizedOptions.getExpressKey
|
||||
: () => '';
|
||||
const isOrderMatched = typeof normalizedOptions.isOrderMatched === 'function'
|
||||
? normalizedOptions.isOrderMatched
|
||||
: () => false;
|
||||
const getMatchedStrategyIds = typeof normalizedOptions.getMatchedStrategyIds === 'function'
|
||||
? normalizedOptions.getMatchedStrategyIds
|
||||
: null;
|
||||
const onProgress = typeof normalizedOptions.onProgress === 'function'
|
||||
? normalizedOptions.onProgress
|
||||
: null;
|
||||
|
||||
const structureStoreSetMap = new Map();
|
||||
const structureOwnerCountMap = new Map();
|
||||
const structureExpressCountMap = new Map();
|
||||
|
||||
for (const order of normalizedOrders) {
|
||||
const structureKey = String(getStructureKey(order) || '').trim();
|
||||
if (!structureKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const storeId = String(order && order.store_id || '').trim().toLowerCase();
|
||||
if (!structureStoreSetMap.has(structureKey)) {
|
||||
structureStoreSetMap.set(structureKey, new Set());
|
||||
}
|
||||
if (!structureOwnerCountMap.has(structureKey)) {
|
||||
structureOwnerCountMap.set(structureKey, new Map());
|
||||
}
|
||||
if (!structureExpressCountMap.has(structureKey)) {
|
||||
structureExpressCountMap.set(structureKey, new Map());
|
||||
}
|
||||
if (storeId) {
|
||||
structureStoreSetMap.get(structureKey).add(storeId);
|
||||
const ownerCountMap = structureOwnerCountMap.get(structureKey);
|
||||
ownerCountMap.set(storeId, Number(ownerCountMap.get(storeId) || 0) + 1);
|
||||
}
|
||||
|
||||
const expressKey = String(getExpressKey(order) || '').trim().toLowerCase();
|
||||
if (expressKey) {
|
||||
const expressCountMap = structureExpressCountMap.get(structureKey);
|
||||
expressCountMap.set(expressKey, Number(expressCountMap.get(expressKey) || 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
const structurePrimaryOwnerMap = new Map();
|
||||
for (const [ structureKey, ownerCountMap ] of structureOwnerCountMap.entries()) {
|
||||
if (!(ownerCountMap instanceof Map) || ownerCountMap.size === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let primaryOwner = '';
|
||||
let maxCount = 0;
|
||||
for (const [ storeId, count ] of ownerCountMap.entries()) {
|
||||
const normalizedStoreId = String(storeId || '').trim().toLowerCase();
|
||||
const normalizedCount = Number(count || 0);
|
||||
if (!normalizedStoreId || normalizedCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedCount > maxCount
|
||||
|| (normalizedCount === maxCount && (!primaryOwner || normalizedStoreId < primaryOwner))
|
||||
) {
|
||||
maxCount = normalizedCount;
|
||||
primaryOwner = normalizedStoreId;
|
||||
}
|
||||
}
|
||||
|
||||
if (primaryOwner) {
|
||||
structurePrimaryOwnerMap.set(structureKey, primaryOwner);
|
||||
}
|
||||
}
|
||||
|
||||
const structurePrimaryExpressMap = new Map();
|
||||
for (const [ structureKey, expressCountMap ] of structureExpressCountMap.entries()) {
|
||||
if (!(expressCountMap instanceof Map) || expressCountMap.size === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let primaryExpressKey = '';
|
||||
let maxCount = 0;
|
||||
for (const [ expressKey, count ] of expressCountMap.entries()) {
|
||||
const normalizedExpressKey = String(expressKey || '').trim().toLowerCase();
|
||||
const normalizedCount = Number(count || 0);
|
||||
if (!normalizedExpressKey || normalizedCount <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedCount > maxCount
|
||||
|| (normalizedCount === maxCount && (!primaryExpressKey || normalizedExpressKey < primaryExpressKey))
|
||||
) {
|
||||
maxCount = normalizedCount;
|
||||
primaryExpressKey = normalizedExpressKey;
|
||||
}
|
||||
}
|
||||
|
||||
if (primaryExpressKey) {
|
||||
structurePrimaryExpressMap.set(structureKey, primaryExpressKey);
|
||||
}
|
||||
}
|
||||
|
||||
const matchedOrderIds = [];
|
||||
const unmatchedOrderIds = [];
|
||||
const matchedStrategyIdsByOrder = {};
|
||||
const totalOrderCount = normalizedOrders.length;
|
||||
let processedOrderCount = 0;
|
||||
|
||||
for (const order of normalizedOrders) {
|
||||
const context = {
|
||||
structureStoreSetMap,
|
||||
structureOwnerCountMap,
|
||||
structurePrimaryOwnerMap,
|
||||
structureExpressCountMap,
|
||||
structurePrimaryExpressMap,
|
||||
};
|
||||
const orderId = Number(order && order.id || 0);
|
||||
let matched = false;
|
||||
|
||||
if (getMatchedStrategyIds) {
|
||||
const rawMatchedStrategyIds = getMatchedStrategyIds(order, strategyList, context);
|
||||
const matchedStrategyIds = [ ...new Set((Array.isArray(rawMatchedStrategyIds) ? rawMatchedStrategyIds : [])
|
||||
.map(id => Number(id))
|
||||
.filter(id => Number.isInteger(id) && id > 0)) ];
|
||||
matched = matchedStrategyIds.length > 0;
|
||||
|
||||
if (Number.isInteger(orderId) && orderId > 0) {
|
||||
matchedStrategyIdsByOrder[orderId] = matchedStrategyIds;
|
||||
}
|
||||
} else {
|
||||
matched = Boolean(isOrderMatched(order, strategyList, context));
|
||||
}
|
||||
|
||||
if (Number.isInteger(orderId) && orderId > 0) {
|
||||
if (matched) {
|
||||
matchedOrderIds.push(orderId);
|
||||
} else {
|
||||
unmatchedOrderIds.push(orderId);
|
||||
}
|
||||
}
|
||||
|
||||
processedOrderCount += 1;
|
||||
if (onProgress && (processedOrderCount % 200 === 0 || processedOrderCount === totalOrderCount)) {
|
||||
await onProgress({
|
||||
totalOrderCount,
|
||||
processedOrderCount,
|
||||
matchedOrderCount: matchedOrderIds.length,
|
||||
unmatchedOrderCount: unmatchedOrderIds.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (onProgress && totalOrderCount === 0) {
|
||||
await onProgress({
|
||||
totalOrderCount,
|
||||
processedOrderCount,
|
||||
matchedOrderCount: 0,
|
||||
unmatchedOrderCount: 0,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
totalOrderCount,
|
||||
processedOrderCount,
|
||||
matchedOrderIds,
|
||||
unmatchedOrderIds,
|
||||
matchedStrategyIdsByOrder,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = runWaveStrategyQuickScanRunner;
|
||||
35
app/lib/waybill_code.js
Normal file
35
app/lib/waybill_code.js
Normal file
@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 运单号公共工具。
|
||||
* 统一处理一单多件分段单号(如 JDX057941864338-1-1-)的包裹序号后缀剥离与 like 通配符转义,
|
||||
* 保证「剥离后缀后主体运单号必须等值匹配」的业务规则在各扫描入口保持一致。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 剥离运单号尾部的包裹序号段(一单多件分段格式:-包裹序号-总件数[-])。
|
||||
* 例如 'JDX057941864338-1-1-' → 'JDX057941864338';
|
||||
* 'JDX057941864338' 无分段后缀时原样返回。
|
||||
*
|
||||
* @param {string} waybillCode 运单号
|
||||
* @return {string} 剥离分段后缀后的主体运单号
|
||||
*/
|
||||
function stripWaybillSegmentSuffix(waybillCode) {
|
||||
return String(waybillCode || '').trim().replace(/(?:-\d+){2,}-?$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 转义 like 匹配中的通配符(% _ \),避免用户输入中的特殊字符扩大匹配范围。
|
||||
* 用于「主体运单号 + -%」前缀匹配场景,确保主体部分被等值比较。
|
||||
*
|
||||
* @param {string} value 待转义的字符串
|
||||
* @return {string} 转义后的字符串
|
||||
*/
|
||||
function escapeLikeWildcards(value) {
|
||||
return String(value || '').replace(/[%_\\]/g, m => `\\${m}`);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
stripWaybillSegmentSuffix,
|
||||
escapeLikeWildcards,
|
||||
};
|
||||
724
app/lib/wechat_open_client.js
Normal file
724
app/lib/wechat_open_client.js
Normal file
@ -0,0 +1,724 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信开放平台第三方平台 API 客户端。
|
||||
* 封装组件级接口调用与 token 管理(Redis 缓存,Key 与参考实现一致):
|
||||
* - component_access_token:调用授权方接口的组件凭证(约 2 小时)。
|
||||
* - App:{appid}:authorization_code:授权码(authorized 事件推送后暂存)。
|
||||
* - App:{appid}:authorizer_refresh_token:授权方刷新令牌(长期)。
|
||||
* - App:{appid}:AuthorizerAccessToken:授权方接口调用凭证(约 2 小时)。
|
||||
*
|
||||
* 配置读取 app.config.wechatOpen:
|
||||
* - component_appid / component_secret / token / encoding_aes_key / api_base
|
||||
*/
|
||||
|
||||
const DEFAULT_API_BASE = 'https://api.weixin.qq.com';
|
||||
|
||||
/** 缓存预留提前量(秒):token 在过期前提前失效,避免临界调用失败。 */
|
||||
const EXPIRE_MARGIN = 300;
|
||||
|
||||
class WechatOpenClient {
|
||||
/**
|
||||
* @param {object} ctx Egg 上下文。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
this.ctx = ctx;
|
||||
this.app = ctx.app;
|
||||
this.config = (this.app && this.app.config && this.app.config.wechatOpen) || {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Redis 客户端(cache 库),不可用时返回 null。
|
||||
* @return {object|null} ioredis 客户端。
|
||||
*/
|
||||
redis() {
|
||||
return this.app && this.app.redis && typeof this.app.redis.get === 'function'
|
||||
? this.app.redis.get('cache')
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取缓存。
|
||||
* @param {string} key Redis key。
|
||||
* @return {Promise<string|null>} 缓存值。
|
||||
*/
|
||||
async cacheGet(key) {
|
||||
const redis = this.redis();
|
||||
if (!redis) return null;
|
||||
return redis.get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入缓存。
|
||||
* @param {string} key Redis key。
|
||||
* @param {string} value 值。
|
||||
* @param {number} ttl 过期秒数。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async cacheSet(key, value, ttl) {
|
||||
const redis = this.redis();
|
||||
if (!redis) return;
|
||||
await redis.set(key, value, 'EX', ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存。
|
||||
* @param {...string} keys Redis keys。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async cacheDel(...keys) {
|
||||
const redis = this.redis();
|
||||
if (!redis || keys.length === 0) return;
|
||||
await redis.del(...keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起微信 API POST 请求(JSON)。
|
||||
* @param {string} path API 路径(不含 base)。
|
||||
* @param {object} body 请求体。
|
||||
* @param {string} [token] component_access_token(作为 URL query 拼接)。
|
||||
* @return {Promise<object>} 响应 JSON。
|
||||
*/
|
||||
async apiPost(path, body, token) {
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
let url = base.replace(/\/$/, '') + path;
|
||||
if (token) {
|
||||
url += `${url.includes('?') ? '&' : '?'}component_access_token=${encodeURIComponent(token)}`;
|
||||
}
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携带 component_access_token 发起 POST 请求;遇 40001(invalid credential,token 被别处刷新顶掉)
|
||||
* 时自动清除缓存 token、重取后重试一次。
|
||||
*
|
||||
* @param {string} path API 路径(不含 base)。
|
||||
* @param {object} body 请求体。
|
||||
* @return {Promise<object>} 响应 JSON(必要时重试后)。
|
||||
*/
|
||||
async apiPostWithComponentToken(path, body) {
|
||||
let result = await this.apiPost(path, body, await this.getComponentAccessToken());
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] component_access_token 失效(40001),清除缓存重试: ${path}`);
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await this.apiPost(path, body, await this.getComponentAccessToken());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存 ComponentVerifyTicket(component_verify_ticket 事件推送后调用)。
|
||||
* @param {string} ticket 推送的 Ticket。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async saveComponentVerifyTicket(ticket) {
|
||||
// 微信每 10 分钟推送一次,ticket 有效期 12 小时。
|
||||
// 缓存 12 小时:异常未及时收到推送时,继续用上一次可用 ticket 换取 component_access_token(官方建议)。
|
||||
await this.cacheSet('ComponentVerifyTicket', ticket, 12 * 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取组件接口调用凭证 component_access_token(缓存优先)。
|
||||
* @return {Promise<string>} component_access_token。
|
||||
*/
|
||||
async getComponentAccessToken() {
|
||||
const cached = await this.cacheGet('component_access_token');
|
||||
if (cached) return cached;
|
||||
|
||||
const ticket = await this.cacheGet('ComponentVerifyTicket');
|
||||
if (!ticket) {
|
||||
throw new Error('ComponentVerifyTicket 不存在,请等待微信推送后重试');
|
||||
}
|
||||
|
||||
const result = await this.apiPost('/cgi-bin/component/api_component_token', {
|
||||
component_appid: this.config.component_appid,
|
||||
component_appsecret: this.config.component_secret,
|
||||
component_verify_ticket: ticket,
|
||||
});
|
||||
|
||||
if (result && result.component_access_token) {
|
||||
const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN;
|
||||
await this.cacheSet('component_access_token', result.component_access_token, Math.max(ttl, 60));
|
||||
return result.component_access_token;
|
||||
}
|
||||
throw new Error(`获取 component_access_token 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存授权码(authorized/updateauthorized 事件推送后调用)。
|
||||
* @param {string} authorizerAppid 授权方小程序 AppID。
|
||||
* @param {string} authorizationCode 授权码。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async saveAuthorizationCode(authorizerAppid, authorizationCode) {
|
||||
// 授权码有效期 1 小时
|
||||
await this.cacheSet(`App:${authorizerAppid}:authorization_code`, authorizationCode, 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用授权码换取授权方令牌(api_query_auth)。
|
||||
* @param {string} authorizationCode 授权码。
|
||||
* @return {Promise<object>} authorization_info(含 authorizer_refresh_token/
|
||||
* authorizer_access_token/expires_in/func_info 等)。
|
||||
*/
|
||||
async queryAuth(authorizationCode) {
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_query_auth', {
|
||||
component_appid: this.config.component_appid,
|
||||
authorization_code: authorizationCode,
|
||||
});
|
||||
if (result && result.authorization_info) {
|
||||
return result.authorization_info;
|
||||
}
|
||||
throw new Error(`获取 authorizer_refresh_token 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取/刷新授权方接口调用凭证 authorizer_access_token(缓存优先)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取)。
|
||||
* @return {Promise<object>} { authorizerAccessToken, authorizerRefreshToken }。
|
||||
*/
|
||||
async getAuthorizerAccessToken(appid, refreshToken) {
|
||||
const tokenKey = `App:${appid}:AuthorizerAccessToken`;
|
||||
const cached = await this.cacheGet(tokenKey);
|
||||
if (cached) {
|
||||
return { authorizerAccessToken: cached, authorizerRefreshToken: refreshToken || null };
|
||||
}
|
||||
|
||||
let token = refreshToken || (await this.cacheGet(`App:${appid}:authorizer_refresh_token`));
|
||||
if (!token) {
|
||||
throw new Error(`App:${appid} 的 authorizer_refresh_token 不存在`);
|
||||
}
|
||||
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_authorizer_token', {
|
||||
component_appid: this.config.component_appid,
|
||||
authorizer_appid: appid,
|
||||
authorizer_refresh_token: token,
|
||||
});
|
||||
|
||||
if (result && result.authorizer_access_token) {
|
||||
const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN;
|
||||
await this.cacheSet(tokenKey, result.authorizer_access_token, Math.max(ttl, 60));
|
||||
if (result.authorizer_refresh_token) {
|
||||
token = result.authorizer_refresh_token;
|
||||
await this.cacheSet(`App:${appid}:authorizer_refresh_token`, token, 30 * 24 * 3600);
|
||||
}
|
||||
return { authorizerAccessToken: result.authorizer_access_token, authorizerRefreshToken: token };
|
||||
}
|
||||
throw new Error(`获取 authorizer_access_token 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权方基本信息(api_get_authorizer_info:昵称/头像/原始ID)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @return {Promise<object>} authorizer_info。
|
||||
*/
|
||||
async getAuthorizerInfo(appid) {
|
||||
const detail = await this.getAuthorizerDetail(appid);
|
||||
if (detail && detail.authorizer_info) {
|
||||
return detail.authorizer_info;
|
||||
}
|
||||
throw new Error(`获取授权方信息失败: ${JSON.stringify(detail)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权账号详情(api_get_authorizer_info 完整返回:authorizer_info + authorization_info)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @return {Promise<object>} { authorizer_info, authorization_info }。
|
||||
*/
|
||||
async getAuthorizerDetail(appid) {
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_get_authorizer_info', {
|
||||
component_appid: this.config.component_appid,
|
||||
authorizer_appid: appid,
|
||||
});
|
||||
if (result && (result.authorizer_info || result.authorization_info)) {
|
||||
return result;
|
||||
}
|
||||
throw new Error(`获取授权账号详情失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建预授权码(用于生成授权链接)。
|
||||
* @return {Promise<string>} pre_auth_code。
|
||||
*/
|
||||
async createPreAuthCode() {
|
||||
const cached = await this.cacheGet('preauthcode');
|
||||
if (cached) return cached;
|
||||
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_create_preauthcode', {
|
||||
component_appid: this.config.component_appid,
|
||||
});
|
||||
if (result && result.pre_auth_code) {
|
||||
await this.cacheSet('preauthcode', result.pre_auth_code, result.expires_in || 1800);
|
||||
return result.pre_auth_code;
|
||||
}
|
||||
throw new Error(`创建预授权码失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询小程序认证进度(POST wxa/sec/queryauth,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取,Redis 丢失可用 DB 值兜底)。
|
||||
* @param {string} taskid 认证任务 id(发起认证接口返回)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/task_status/apply_status/orderid/auth_url 等)。
|
||||
*/
|
||||
async queryMiniProgramAuth(appid, refreshToken, taskid) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/queryauth`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: { taskid },
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/sec/queryauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起小程序认证(POST wxa/sec/wxaauth,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* ⚠ 微信已下线旧接口 /wxa/sec/wxaapi/wxaauth(调用返回 40066 invalid url);
|
||||
* 现行接口路径为 /wxa/sec/wxaauth,请求体为 { auth_data: {...} }(由业务层组装)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {object} body 认证请求体({ auth_data: {...} },字段见业务层白名单)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/taskid/auth_url)。
|
||||
*/
|
||||
async wxaauth(appid, refreshToken, body) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/wxaauth`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/sec/wxaauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传认证材料图片到微信换取 mediaid(POST wxa/sec/uploadauthmaterial,
|
||||
* authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* ⚠ 微信已下线旧接口 /wxa/sec/wxaapi/uploadmedia;现行接口为 /wxa/sec/uploadauthmaterial,
|
||||
* 仅 media 一个 multipart 字段(图片 ≤2M,PNG/JPEG/JPG/GIF),成功返回 mediaid
|
||||
* (本方法归一化为 media_id 供上层使用)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {Buffer} buffer 图片内容。
|
||||
* @param {string} filename 文件名(含扩展名,如 idcard.jpg)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/media_id/mediaid)。
|
||||
*/
|
||||
async uploadAuthMedia(appid, refreshToken, buffer, filename) {
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const tmpFile = path.join(
|
||||
os.tmpdir(),
|
||||
`wxauth-${Date.now()}-${Math.random().toString(36).slice(2, 10)}-${path.basename(filename || 'image.jpg')}`
|
||||
);
|
||||
await fs.promises.writeFile(tmpFile, buffer);
|
||||
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/uploadauthmaterial`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
files: { media: tmpFile },
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
try {
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/sec/uploadauthmaterial token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
// 现行接口成功返回字段为 mediaid,归一化为 media_id 供上层使用
|
||||
if (result && Number(result.errcode) === 0 && !result.media_id && result.mediaid) {
|
||||
result = { ...result, media_id: result.mediaid };
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
await fs.promises.unlink(tmpFile).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小程序模板列表(wxa/gettemplatelist,仅支持 component_access_token,GET 请求)。
|
||||
*
|
||||
* @param {number} [templateType] 0=普通模板、1=标准模板,不传返回全部。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/template_list)。
|
||||
*/
|
||||
async getTemplateList(templateType) {
|
||||
const request = async () => {
|
||||
const componentAccessToken = await this.getComponentAccessToken();
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/gettemplatelist`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'GET',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
data: {
|
||||
access_token: componentAccessToken,
|
||||
...(templateType !== undefined && templateType !== null ? { template_type: templateType } : {}),
|
||||
},
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn('[wechatOpen] gettemplatelist 40001 component_access_token 失效,清除缓存重试');
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交代码审核(wxa/submit_audit,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {object} body 请求体(item_list/version_desc 等,均为可选)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/auditid)。
|
||||
*/
|
||||
async submitAudit(appid, refreshToken, body) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/submit_audit`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/submit_audit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取体验版二维码(wxa/get_qrcode,使用 authorizer_access_token 代商家调用,权限集 18/86)。
|
||||
*
|
||||
* 成功返回图片二进制(contentType=image/jpeg),失败返回微信 JSON(errcode/errmsg)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {string} [path] 二维码扫码进入的页面路径(可选,自动 urlencode)。
|
||||
* @return {Promise<object>} { errcode, errmsg } 或 { errcode: 0, contentType, buffer }。
|
||||
*/
|
||||
async getTrialQRCode(appid, refreshToken, path) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
let url = `${base.replace(/\/$/, '')}/wxa/get_qrcode`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
if (path) {
|
||||
url += `&path=${encodeURIComponent(path)}`;
|
||||
}
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'GET',
|
||||
timeout: 30000,
|
||||
});
|
||||
const contentType = String((response.headers && response.headers['content-type']) || '');
|
||||
if (contentType.includes('image')) {
|
||||
return { errcode: 0, errmsg: 'ok', contentType, buffer: response.data };
|
||||
}
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/get_qrcode token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传代码并生成体验版(wxa/commit,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {object} body { template_id, ext_json, user_version, user_desc }。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
|
||||
*/
|
||||
async commitTemplate(appid, refreshToken, body) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/commit`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/commit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速注册企业小程序(fastregisterweapp,仅支持第三方平台 component_access_token)。
|
||||
*
|
||||
* @param {string} action create=创建小程序 / search=查询创建任务状态。
|
||||
* @param {object} body 请求体。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
|
||||
*/
|
||||
async fastRegisterWeapp(action, body) {
|
||||
const request = async () => {
|
||||
const componentAccessToken = await this.getComponentAccessToken();
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/cgi-bin/component/fastregisterweapp`
|
||||
+ `?action=${encodeURIComponent(action)}`
|
||||
+ `&component_access_token=${encodeURIComponent(componentAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn('[wechatOpen] fastregisterweapp 40001 component_access_token 失效,清除缓存重试');
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序登录凭证校验(jscode2session):第三方平台代小程序实现登录。
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} jsCode wx.login 获取的 code。
|
||||
* @return {Promise<object>} { openid, session_key, unionid }。
|
||||
*/
|
||||
async jscode2session(appid, jsCode) {
|
||||
const request = async () => {
|
||||
const componentAccessToken = await this.getComponentAccessToken();
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/sns/component/jscode2session`
|
||||
+ `?appid=${encodeURIComponent(appid)}`
|
||||
+ '&grant_type=authorization_code'
|
||||
+ `&component_appid=${encodeURIComponent(this.config.component_appid)}`
|
||||
+ `&component_access_token=${encodeURIComponent(componentAccessToken)}`
|
||||
+ `&js_code=${encodeURIComponent(jsCode)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'GET',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
|
||||
// 40001:component_access_token 被别处刷新顶掉(not latest),清除缓存重取后重试一次
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn('[wechatOpen] jscode2session 40001 component_access_token 失效,清除缓存重试');
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await request();
|
||||
}
|
||||
|
||||
// 调试:打印微信原始返回报文(仅 openid/session_key/unionid,无昵称头像)
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.info(`[wechatOpen] jscode2session appid=${appid} 返回: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
if (result && result.openid) {
|
||||
return result;
|
||||
}
|
||||
throw new Error(`jscode2session 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理授权方相关缓存(unauthorized 取消授权事件后调用)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async clearAuthorizerCache(appid) {
|
||||
await this.cacheDel(
|
||||
`App:${appid}:authorization_code`,
|
||||
`App:${appid}:authorizer_refresh_token`,
|
||||
`App:${appid}:AuthorizerAccessToken`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存授权 state(发起授权时缓存仓库信息,回跳时凭 state 取回)。
|
||||
* @param {string} state 随机 state。
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @param {number} [ttl=600] 过期秒数。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async saveAuthState(state, warehouseId, ttl = 600) {
|
||||
await this.cacheSet(
|
||||
`wechat_auth_state:${state}`,
|
||||
JSON.stringify({ warehouse_id: warehouseId, created_at: Math.floor(Date.now() / 1000) }),
|
||||
ttl
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取授权 state 对应的仓库信息。
|
||||
* @param {string} state 随机 state。
|
||||
* @return {Promise<object|null>} { warehouse_id, created_at },不存在/过期返回 null。
|
||||
*/
|
||||
async getAuthState(state) {
|
||||
const cached = await this.cacheGet(`wechat_auth_state:${state}`);
|
||||
if (!cached) return null;
|
||||
try {
|
||||
return JSON.parse(cached);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除授权 state 缓存(回调消费后调用,保证一次性)。
|
||||
* @param {string} state 随机 state。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async clearAuthState(state) {
|
||||
await this.cacheDel(`wechat_auth_state:${state}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送客服文本消息(POST cgi-bin/message/custom/send,使用 authorizer_access_token
|
||||
* 代授权方调用,用于用户关注欢迎语、关键词自动回复等场景)。
|
||||
*
|
||||
* @param {string} appid 授权方(小程序/公众号)AppID。
|
||||
* @param {string} touser 用户 openid。
|
||||
* @param {string} content 文本内容。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
|
||||
*/
|
||||
async sendCustomMessage(appid, touser, content, refreshToken) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/cgi-bin/message/custom/send`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: {
|
||||
touser,
|
||||
msgtype: 'text',
|
||||
text: { content },
|
||||
},
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] message/custom/send token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatOpenClient;
|
||||
304
app/lib/wechat_open_crypt.js
Normal file
304
app/lib/wechat_open_crypt.js
Normal file
@ -0,0 +1,304 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const { XMLParser } = require('fast-xml-parser');
|
||||
|
||||
/**
|
||||
* 微信开放平台第三方平台消息加解密工具(Node 版 WXBizMsgCrypt)。
|
||||
* 对应微信官方示例(PHP WXBizMsgCrypt)能力:
|
||||
* - URL 有效性验证(首次配置服务器地址时的 echostr 校验)
|
||||
* - 事件推送消息解密(AES-256-CBC + PKCS#7,密文格式:
|
||||
* 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid)
|
||||
*
|
||||
* 错误码沿用微信官方定义:
|
||||
* -40001 签名验证错误 / -40004 encodingAesKey 非法 / -40005 appid 校验错误 /
|
||||
* -40007 AES 解密失败 / -40008 解密后 buffer 非法 / -40010 base64 解码失败。
|
||||
*/
|
||||
|
||||
const ERROR_CODES = {
|
||||
OK: 0,
|
||||
VALIDATE_SIGNATURE_ERROR: -40001,
|
||||
ILLEGAL_AES_KEY: -40004,
|
||||
VALIDATE_APPID_ERROR: -40005,
|
||||
DECRYPT_AES_ERROR: -40007,
|
||||
ILLEGAL_BUFFER: -40008,
|
||||
DECODE_BASE64_ERROR: -40010,
|
||||
};
|
||||
|
||||
/**
|
||||
* 计算 SHA1(hex)。
|
||||
* @param {string} input 输入字符串。
|
||||
* @return {string} SHA1 摘要。
|
||||
*/
|
||||
function sha1(input) {
|
||||
return crypto.createHash('sha1').update(input, 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成消息签名:sha1(sort(token, timestamp, nonce, encrypt))。
|
||||
* @param {string} token 第三方平台消息校验 Token。
|
||||
* @param {string} timestamp 时间戳。
|
||||
* @param {string} nonce 随机串。
|
||||
* @param {string} [encrypt=''] 加密内容(URL 验证时为空)。
|
||||
* @return {string} 签名。
|
||||
*/
|
||||
function getSignature(token, timestamp, nonce, encrypt = '') {
|
||||
const arr = [ token, String(timestamp), String(nonce), String(encrypt || '') ].sort();
|
||||
return sha1(arr.join(''));
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 URL 有效性签名:signature === sha1(sort(token, timestamp, nonce))。
|
||||
* @param {string} token 第三方平台消息校验 Token。
|
||||
* @param {string} signature 微信回传的 signature。
|
||||
* @param {string} timestamp 时间戳。
|
||||
* @param {string} nonce 随机串。
|
||||
* @return {boolean} 是否通过。
|
||||
*/
|
||||
function verifyUrlSignature(token, signature, timestamp, nonce) {
|
||||
if (!token || !signature || timestamp === undefined || timestamp === null || nonce === undefined || nonce === null) {
|
||||
return false;
|
||||
}
|
||||
const expected = getSignature(token, timestamp, nonce);
|
||||
return expected === String(signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析加密推送 XML,提取 <Encrypt> 内容。
|
||||
* @param {string} encryptedXml 微信推送的加密 XML。
|
||||
* @return {string} Encrypt 密文(base64 字符串)。
|
||||
*/
|
||||
function extractEncrypt(encryptedXml) {
|
||||
if (!encryptedXml) return '';
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
parseTagValue: false,
|
||||
parseAttributeValue: false,
|
||||
trimValues: false,
|
||||
});
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parser.parse(encryptedXml.trim());
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
return (parsed && parsed.xml && parsed.xml.Encrypt) || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCS#7 去除填充。
|
||||
* @param {Buffer} buf 解密后的带填充 buffer。
|
||||
* @return {Buffer} 去填充后的 buffer。
|
||||
*/
|
||||
function pkcs7Decode(buf) {
|
||||
const pad = buf[buf.length - 1];
|
||||
if (pad >= 1 && pad <= 32) {
|
||||
return buf.subarray(0, buf.length - pad);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCS#7 填充(微信 AES 块大小为 32 字节)。
|
||||
* @param {Buffer} buf 原始 buffer。
|
||||
* @return {Buffer} 填充后的 buffer。
|
||||
*/
|
||||
function pkcs7Encode(buf) {
|
||||
const blockSize = 32;
|
||||
const pad = blockSize - (buf.length % blockSize);
|
||||
const result = Buffer.alloc(buf.length + pad);
|
||||
buf.copy(result);
|
||||
result.fill(pad, buf.length);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* AES-256-CBC 解密微信密文。
|
||||
* @param {string} encrypted base64 密文。
|
||||
* @param {Buffer} aesKey 32 字节 AES Key。
|
||||
* @return {{ code: number, buf: Buffer }} 解密结果(失败时 buf 为空 Buffer)。
|
||||
*/
|
||||
function aesDecrypt(encrypted, aesKey) {
|
||||
const encryptedBuf = Buffer.from(String(encrypted), 'base64');
|
||||
if (!encryptedBuf.length) {
|
||||
return { code: ERROR_CODES.DECODE_BASE64_ERROR, buf: Buffer.alloc(0) };
|
||||
}
|
||||
try {
|
||||
const iv = aesKey.subarray(0, 16);
|
||||
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv);
|
||||
decipher.setAutoPadding(false);
|
||||
const decoded = pkcs7Decode(Buffer.concat([ decipher.update(encryptedBuf), decipher.final() ]));
|
||||
return { code: ERROR_CODES.OK, buf: decoded };
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.DECRYPT_AES_ERROR, buf: Buffer.alloc(0) };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密事件推送消息(完整流程:签名校验 → base64/AES 解密 → 报文解析 → appid 校验)。
|
||||
* @param {object} opts 参数。
|
||||
* @param {string} opts.token 第三方平台消息校验 Token。
|
||||
* @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。
|
||||
* @param {string} opts.componentAppid 第三方平台 AppID。
|
||||
* @param {string} opts.msgSignature 消息签名 msg_signature。
|
||||
* @param {string|number} opts.timestamp 时间戳。
|
||||
* @param {string} opts.nonce 随机串。
|
||||
* @param {string} opts.encryptedXml 微信推送的加密 XML。
|
||||
* @return {{ code: number, msg: string }} code=0 时 msg 为解密后的明文 XML。
|
||||
*/
|
||||
function decryptMsg(opts) {
|
||||
const {
|
||||
token,
|
||||
encodingAesKey,
|
||||
componentAppid,
|
||||
msgSignature,
|
||||
timestamp,
|
||||
nonce,
|
||||
encryptedXml,
|
||||
} = opts || {};
|
||||
|
||||
const encrypt = extractEncrypt(encryptedXml);
|
||||
if (!encrypt) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '加密 XML 中未找到 Encrypt 内容' };
|
||||
}
|
||||
|
||||
// 1. 校验消息签名
|
||||
const expectedSignature = getSignature(token, timestamp, nonce, encrypt);
|
||||
if (expectedSignature !== String(msgSignature)) {
|
||||
return { code: ERROR_CODES.VALIDATE_SIGNATURE_ERROR, msg: '消息签名校验失败' };
|
||||
}
|
||||
|
||||
// 2. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节)
|
||||
let aesKey;
|
||||
try {
|
||||
aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 非法' };
|
||||
}
|
||||
if (aesKey.length !== 32) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 解码后长度不是 32 字节' };
|
||||
}
|
||||
|
||||
// 3. AES 解密
|
||||
const decrypted = aesDecrypt(encrypt, aesKey);
|
||||
if (decrypted.code !== ERROR_CODES.OK) {
|
||||
return { code: decrypted.code, msg: 'AES 解密失败' };
|
||||
}
|
||||
|
||||
// 4. 解析明文(二进制 buffer):16 字节随机串 + 4 字节大端长度 + 消息体 + appid
|
||||
const content = decrypted.buf;
|
||||
if (content.length < 20) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后 buffer 长度非法' };
|
||||
}
|
||||
const msgLen = content.readUInt32BE(16);
|
||||
if (20 + msgLen > content.length) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后消息长度非法' };
|
||||
}
|
||||
const xmlContent = content.subarray(20, 20 + msgLen).toString('utf8');
|
||||
const fromAppid = content.subarray(20 + msgLen).toString('utf8');
|
||||
|
||||
// 5. 校验 appid
|
||||
if (fromAppid !== String(componentAppid)) {
|
||||
return { code: ERROR_CODES.VALIDATE_APPID_ERROR, msg: `appid 校验失败: ${fromAppid}` };
|
||||
}
|
||||
|
||||
return { code: ERROR_CODES.OK, msg: xmlContent };
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析明文 XML 为对象({ AppId, InfoType, ... })。
|
||||
* @param {string} xml 明文 XML。
|
||||
* @return {object} 解析后的对象(失败返回空对象)。
|
||||
*/
|
||||
function parseXml(xml) {
|
||||
if (!xml) return {};
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
parseTagValue: false,
|
||||
parseAttributeValue: false,
|
||||
trimValues: false,
|
||||
});
|
||||
try {
|
||||
const parsed = parser.parse(xml.trim());
|
||||
return (parsed && parsed.xml) || {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密被动回复消息(完整流程:明文组装 → PKCS#7 → AES-256-CBC → base64 → 签名 → 组装 XML)。
|
||||
* 用于第三方平台模式下回复授权方(小程序/公众号)用户消息:
|
||||
* 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid,密钥与推送解密共用组件密钥。
|
||||
* @param {object} opts 参数。
|
||||
* @param {string} opts.token 第三方平台消息校验 Token。
|
||||
* @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。
|
||||
* @param {string} opts.componentAppid 第三方平台 AppID。
|
||||
* @param {string} opts.plainXml 明文回复 XML。
|
||||
* @param {string} opts.nonce 微信回传的随机串(用于回复签名)。
|
||||
* @return {{ code: number, encryptedXml: string }} code=0 时 encryptedXml 为加密回复 XML。
|
||||
*/
|
||||
function encryptMsg(opts) {
|
||||
const {
|
||||
token,
|
||||
encodingAesKey,
|
||||
componentAppid,
|
||||
plainXml,
|
||||
nonce,
|
||||
} = opts || {};
|
||||
|
||||
if (!token || !encodingAesKey || !componentAppid || !plainXml) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 1. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节)
|
||||
let aesKey;
|
||||
try {
|
||||
aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' };
|
||||
}
|
||||
if (aesKey.length !== 32) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 2. 组装明文:16 字节随机串 + 4 字节大端长度 + 明文 XML + component_appid
|
||||
const random = crypto.randomBytes(16);
|
||||
const plainBuf = Buffer.from(String(plainXml), 'utf8');
|
||||
const lenBuf = Buffer.alloc(4);
|
||||
lenBuf.writeUInt32BE(plainBuf.length, 0);
|
||||
const appidBuf = Buffer.from(String(componentAppid), 'utf8');
|
||||
const padded = pkcs7Encode(Buffer.concat([ random, lenBuf, plainBuf, appidBuf ]));
|
||||
|
||||
// 3. AES-256-CBC 加密(iv = key 前 16 字节,手动填充)
|
||||
let encrypt;
|
||||
try {
|
||||
const iv = aesKey.subarray(0, 16);
|
||||
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, iv);
|
||||
cipher.setAutoPadding(false);
|
||||
encrypt = Buffer.concat([ cipher.update(padded), cipher.final() ]).toString('base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.DECRYPT_AES_ERROR, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 4. 签名与组装回复 XML
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const signature = getSignature(token, timestamp, nonce, encrypt);
|
||||
const encryptedXml = `<xml><Encrypt><![CDATA[${encrypt}]]></Encrypt>`
|
||||
+ `<MsgSignature><![CDATA[${signature}]]></MsgSignature>`
|
||||
+ `<TimeStamp>${timestamp}</TimeStamp>`
|
||||
+ `<Nonce><![CDATA[${String(nonce)}]]></Nonce></xml>`;
|
||||
|
||||
return { code: ERROR_CODES.OK, encryptedXml };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ERROR_CODES,
|
||||
sha1,
|
||||
getSignature,
|
||||
verifyUrlSignature,
|
||||
extractEncrypt,
|
||||
decryptMsg,
|
||||
parseXml,
|
||||
encryptMsg,
|
||||
};
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, DATE, TINYINT, fn } = app.Sequelize;
|
||||
const { BIGINT, STRING, DATE, TINYINT, fn } = app.Sequelize;
|
||||
|
||||
const Account = app.model.define('account', {
|
||||
id: {
|
||||
@ -74,6 +74,18 @@ module.exports = app => {
|
||||
},
|
||||
comment: '状态:0-封号,1-启用',
|
||||
},
|
||||
is_custom_password: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 0, 1 ]],
|
||||
msg: '自定义密码标记值不合法,0-否,1-是',
|
||||
},
|
||||
},
|
||||
comment: '是否自定义密码:0-否,1-是',
|
||||
},
|
||||
last_login_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
@ -131,14 +143,11 @@ module.exports = app => {
|
||||
});
|
||||
|
||||
// 关联关系
|
||||
Account.associate = function(models) {
|
||||
Account.associate = function() {
|
||||
const { AccountStoreEmployee, AccountPlatformActive } = app.model;
|
||||
/* if (models.AccountStoreRole) {
|
||||
|
||||
}*/
|
||||
Account.hasMany(AccountStoreEmployee, {
|
||||
foreignKey: 'account_id',
|
||||
as: 'accountStoreRoles',
|
||||
as: 'accountStoreEmployees',
|
||||
});
|
||||
Account.hasMany(AccountPlatformActive, {
|
||||
foreignKey: 'account_id',
|
||||
|
||||
@ -75,7 +75,7 @@ module.exports = app => {
|
||||
});
|
||||
|
||||
// 关联关系 - 注释掉或删除,统一在 app.js 中处理
|
||||
AccountPlatformActive.associate = function(models) {
|
||||
AccountPlatformActive.associate = function() {
|
||||
const { Account, AccountStoreEmployee } = app.model;
|
||||
AccountPlatformActive.belongsTo(Account, {
|
||||
foreignKey: 'account_id',
|
||||
|
||||
@ -78,8 +78,8 @@ module.exports = app => {
|
||||
});
|
||||
|
||||
// 关联关系
|
||||
AccountStoreEmployee.associate = function(models) {
|
||||
const { Account, Store, Role, AccountPlatformActive, EmployeeRole, Receiving } = app.model;
|
||||
AccountStoreEmployee.associate = function() {
|
||||
const { Account, Store, AccountPlatformActive, EmployeeRole, Receiving } = app.model;
|
||||
AccountStoreEmployee.belongsTo(Account, {
|
||||
foreignKey: 'account_id',
|
||||
as: 'account',
|
||||
@ -94,7 +94,7 @@ module.exports = app => {
|
||||
});
|
||||
AccountStoreEmployee.hasMany(EmployeeRole, {
|
||||
foreignKey: 'employee_id',
|
||||
as: 'employeeRole',
|
||||
as: 'employeeRoles',
|
||||
});
|
||||
AccountStoreEmployee.hasMany(Receiving, {
|
||||
foreignKey: 'creator_id',
|
||||
|
||||
424
app/model/after_sale.js
Normal file
424
app/model/after_sale.js
Normal file
@ -0,0 +1,424 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 售后主表 Model,基于 `wms_after_sale` 表。
|
||||
* @param {import('egg').Application} app Egg 应用实例
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 售后 Model(含常量挂载)
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, INTEGER, DECIMAL, TEXT, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
// ============================
|
||||
// 枚举常量定义
|
||||
// ============================
|
||||
|
||||
/**
|
||||
* 售后类型 + 子类型枚举,按业务单据维度分类。
|
||||
* @type {Array<{name: string, type: string, subType: Array<{name: string, value: string}>}>}
|
||||
*/
|
||||
const AFTER_SALE_TYPES = [
|
||||
{
|
||||
name: '订单',
|
||||
type: 'order',
|
||||
subType: [
|
||||
{ name: '破损', value: 'damage' },
|
||||
{ name: '少发', value: 'missing_item' },
|
||||
{ name: '错发', value: 'mis_shipment' },
|
||||
{ name: '错品', value: 'wrong_sku' },
|
||||
{ name: '质量问题', value: 'quality_issue' },
|
||||
{ name: '发货延迟', value: 'delivery_delay' },
|
||||
{ name: '物流异常', value: 'logistics_issue' },
|
||||
{ name: '客户拒收', value: 'rejected' },
|
||||
{ name: '拦截', value: 'intercept' },
|
||||
{ name: '取消拦截', value: 'cancel_intercept' },
|
||||
{ name: '核实签收', value: 'verify_delivery' },
|
||||
{ name: '催件', value: 'urge' },
|
||||
{ name: '多发', value: 'extra_item' },
|
||||
{ name: '改地址', value: 'change_address' },
|
||||
{ name: '换快递', value: 'change_carrier' },
|
||||
{ name: '揽收', value: 'pickup' },
|
||||
{ name: '重量异常', value: 'weight_issue' },
|
||||
{ name: '运费争议', value: 'freight_issue' },
|
||||
{ name: '其他', value: 'other' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: '收货单',
|
||||
type: 'receiving',
|
||||
subType: [
|
||||
{ name: '少货', value: 'shortage' },
|
||||
{ name: '破损', value: 'damage' },
|
||||
{ name: '错品', value: 'wrong_sku' },
|
||||
{ name: '质量问题', value: 'quality_issue' },
|
||||
{ name: '其他', value: 'other' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: '入库单',
|
||||
type: 'entry',
|
||||
subType: [
|
||||
{ name: '少货', value: 'shortage' },
|
||||
{ name: '破损', value: 'damage' },
|
||||
{ name: '错品', value: 'wrong_sku' },
|
||||
{ name: '质量问题', value: 'quality_issue' },
|
||||
{ name: '其他', value: 'other' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: '出库单',
|
||||
type: 'stockout',
|
||||
subType: [
|
||||
{ name: '退货异常', value: 'return_issue' },
|
||||
{ name: '错发', value: 'wrong_outbound' },
|
||||
{ name: '少发', value: 'shortage' },
|
||||
{ name: '其他', value: 'other' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 售后处理角色组枚举。
|
||||
* @type {{customer_service: string, warehouse: string, finance: string}}
|
||||
*/
|
||||
const AFTER_SALE_ROLE_GROUPS = {
|
||||
customer_service: '客服组',
|
||||
warehouse: '仓库组',
|
||||
finance: '财务组',
|
||||
};
|
||||
|
||||
/**
|
||||
* 售后单状态枚举。
|
||||
* @type {{pending: string, processing: string, waiting: string, completed: string, closed: string, cancelled: string}}
|
||||
*/
|
||||
const AFTER_SALE_STATUS = {
|
||||
pending: '待处理',
|
||||
processing: '处理中',
|
||||
pending_feedback: '等待外部反馈',
|
||||
completed: '已完成',
|
||||
closed: '已关闭',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
|
||||
/**
|
||||
* 理赔状态枚举(仓库理赔 & 运方理赔通用)。
|
||||
* @type {{pending: string, reviewing: string, approved: string, paid: string, monthly: string, rejected: string}}
|
||||
*/
|
||||
const CLAIM_STATUS = {
|
||||
pending: '待理赔',
|
||||
reviewing: '审核中',
|
||||
approved: '已通过',
|
||||
paid: '已打款',
|
||||
monthly: '月结',
|
||||
rejected: '已拒绝',
|
||||
};
|
||||
|
||||
// ============================
|
||||
// Model 定义
|
||||
// ============================
|
||||
|
||||
const AfterSale = app.model.define('after_sale', {
|
||||
/** 主键 */
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
/** 仓库ID */
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
/** 货主ID */
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '货主ID',
|
||||
},
|
||||
/** 售后单号,唯一 */
|
||||
after_sale_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '售后单号,唯一。生成规则:前缀AS + 日期YYYYMMDD + 6位序号',
|
||||
},
|
||||
/** 售后类型 */
|
||||
type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
comment: '售后类型:order=订单, receiving=收货单, entry=入库单, stockout=出库单',
|
||||
},
|
||||
/** 售后子类型 */
|
||||
sub_type: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '售后子类型,与 type 组成二级分类',
|
||||
},
|
||||
/** 售后状态 */
|
||||
status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '售后状态:pending=待处理, processing=处理中, pending_feedback=等待外部反馈, completed=已完成, closed=已关闭, cancelled=已取消',
|
||||
},
|
||||
/** 优先级 */
|
||||
priority: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '优先级,数值越大越优先(0=普通,10=紧急)',
|
||||
},
|
||||
/** 售后标题 */
|
||||
title: {
|
||||
type: STRING(200),
|
||||
allowNull: false,
|
||||
comment: '售后标题(简要描述)',
|
||||
},
|
||||
/** 售后详细描述 */
|
||||
description: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '售后详细描述',
|
||||
},
|
||||
/** 创建人账户ID */
|
||||
creator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '创建人账户ID(关联 accounts 表)',
|
||||
},
|
||||
/** 关联站内信消息ID */
|
||||
inbox_message_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联 wms_inbox_message.id,为空表示无关联信息',
|
||||
},
|
||||
/** 当前处理角色组 */
|
||||
role_group: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '当前处理角色组:customer_service=客服组, warehouse=仓库组, finance=财务组。NULL 表示未分配',
|
||||
},
|
||||
/** 最终处理结果说明 */
|
||||
resolution: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '最终处理结果说明',
|
||||
},
|
||||
/** 完结时间 */
|
||||
resolved_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '完结时间(状态变为 completed 时写入)',
|
||||
},
|
||||
/** 下次跟进时间 */
|
||||
followup_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '下次跟进时间:设为 pending_feedback 时可指定,超时后需二次跟进',
|
||||
},
|
||||
/** 仓库理赔标记 */
|
||||
claim_needed: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '仓库理赔标记:0=不需要,1=需要',
|
||||
},
|
||||
/** 仓库理赔金额(元) */
|
||||
claim_amount: {
|
||||
type: DECIMAL(12, 2),
|
||||
allowNull: true,
|
||||
comment: '仓库理赔金额,单位:人民币(元),claim_needed=1 时可填写',
|
||||
},
|
||||
/** 仓库理赔状态 */
|
||||
claim_status: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '仓库理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝',
|
||||
},
|
||||
/** 运方理赔标记 */
|
||||
carrier_claim_needed: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '运方理赔标记:0=不需要,1=需要',
|
||||
},
|
||||
/** 运方理赔金额(元) */
|
||||
carrier_claim_amount: {
|
||||
type: DECIMAL(12, 2),
|
||||
allowNull: true,
|
||||
comment: '运方理赔金额,单位:人民币(元),carrier_claim_needed=1 时可填写',
|
||||
},
|
||||
/** 运方理赔状态 */
|
||||
carrier_claim_status: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '运方理赔状态:pending=待理赔, reviewing=审核中, approved=已通过, paid=已打款, monthly=月结, rejected=已拒绝',
|
||||
},
|
||||
// ========== 单据关联字段(替代旧版多态关联) ==========
|
||||
/** 运单ID */
|
||||
waybill_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '运单ID(关联 wms_order_express.id)',
|
||||
},
|
||||
/** 运单号(冗余) */
|
||||
waybill_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '运单号(冗余字段,方便查询展示)',
|
||||
},
|
||||
/** 订单ID */
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '订单ID(关联 wms_order_delivery.id)',
|
||||
},
|
||||
/** 入库单ID */
|
||||
entry_order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '入库单ID(关联 wms_entry_order.id)',
|
||||
},
|
||||
/** 入库单号(冗余) */
|
||||
entry_order_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '入库单号(冗余字段)',
|
||||
},
|
||||
/** 出库单/退货出库单ID */
|
||||
order_stockout_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '出库单/退货出库单ID(关联 wms_order_stockout.id)',
|
||||
},
|
||||
/** 出库单号(冗余) */
|
||||
order_stockout_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '出库单号(冗余字段)',
|
||||
},
|
||||
/** 收货单ID */
|
||||
receiving_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '收货单ID(关联 wms_receiving.id)',
|
||||
},
|
||||
/** 收货单号(冗余) */
|
||||
receiving_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '收货单号(冗余字段)',
|
||||
},
|
||||
/** 创建时间 */
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
/** 更新时间 */
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '更新时间',
|
||||
},
|
||||
/** 软删除时间 */
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale',
|
||||
comment: '售后主表',
|
||||
timestamps: false,
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_after_sale_no',
|
||||
unique: true,
|
||||
fields: [ 'after_sale_no' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_status',
|
||||
fields: [ 'warehouse_id', 'status', 'deleted_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_type',
|
||||
fields: [ 'warehouse_id', 'type', 'deleted_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_type_subtype',
|
||||
fields: [ 'warehouse_id', 'type', 'sub_type', 'deleted_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_store_id',
|
||||
fields: [ 'store_id', 'deleted_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_creator_id',
|
||||
fields: [ 'creator_id', 'deleted_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_role_group',
|
||||
fields: [ 'role_group', 'status', 'deleted_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_created_at',
|
||||
fields: [ 'warehouse_id', 'created_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_waybill_id',
|
||||
fields: [ 'waybill_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_order_id',
|
||||
fields: [ 'order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_entry_order_id',
|
||||
fields: [ 'entry_order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_order_stockout_id',
|
||||
fields: [ 'order_stockout_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_receiving_id',
|
||||
fields: [ 'receiving_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_carrier_claim_status',
|
||||
fields: [ 'carrier_claim_status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_inbox_message_id',
|
||||
fields: [ 'inbox_message_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// ============================
|
||||
// 关联关系
|
||||
// ============================
|
||||
|
||||
AfterSale.associate = function() {
|
||||
const { AfterSale, AfterSaleDetail } = app.model;
|
||||
|
||||
// 关联售后进度步骤(一对多)
|
||||
AfterSale.hasMany(AfterSaleDetail, {
|
||||
foreignKey: 'after_sale_id',
|
||||
as: 'details',
|
||||
});
|
||||
};
|
||||
|
||||
// ============================
|
||||
// 常量挂载到 Model
|
||||
// ============================
|
||||
|
||||
AfterSale.AFTER_SALE_TYPES = AFTER_SALE_TYPES;
|
||||
AfterSale.AFTER_SALE_ROLE_GROUPS = AFTER_SALE_ROLE_GROUPS;
|
||||
AfterSale.AFTER_SALE_STATUS = AFTER_SALE_STATUS;
|
||||
AfterSale.CLAIM_STATUS = CLAIM_STATUS;
|
||||
|
||||
return AfterSale;
|
||||
};
|
||||
144
app/model/after_sale_detail.js
Normal file
144
app/model/after_sale_detail.js
Normal file
@ -0,0 +1,144 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 售后进度步骤表 Model,基于 `wms_after_sale_detail` 表。
|
||||
* @param {import('egg').Application} app Egg 应用实例
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 售后进度步骤 Model(含常量挂载)
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
// ============================
|
||||
// 枚举常量定义
|
||||
// ============================
|
||||
|
||||
/**
|
||||
* 步骤状态枚举(与 wms_after_sale.status 一致)。
|
||||
*/
|
||||
const STEP_STATUS = {
|
||||
pending: '待处理',
|
||||
processing: '处理中',
|
||||
pending_feedback: '等待外部反馈',
|
||||
completed: '已完成',
|
||||
closed: '已关闭',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
|
||||
// ============================
|
||||
// Model 定义
|
||||
// ============================
|
||||
|
||||
const AfterSaleDetail = app.model.define('after_sale_detail', {
|
||||
/** 主键 */
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
/** 关联售后主表ID */
|
||||
after_sale_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '关联售后主表ID(wms_after_sale.id)',
|
||||
},
|
||||
/** 步骤记录时售后主表的状态 */
|
||||
step_status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'processing',
|
||||
comment: '步骤记录时售后主表的状态,与 wms_after_sale.status 一致: pending | processing | pending_feedback | completed | closed | cancelled',
|
||||
},
|
||||
/** 操作人账户ID */
|
||||
operator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '操作人账户ID(关联 accounts 表);外部系统回调/自动触发的步骤可为空',
|
||||
},
|
||||
/** 操作人信息快照 */
|
||||
operator_snapshot: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '操作人信息快照(JSON),如 {"name":"张三","role":"客服"},防止账户删除后历史丢失',
|
||||
},
|
||||
/** 操作动作描述 */
|
||||
action: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '操作动作描述,如"确认收货"、"审核驳回"、"发起退款"',
|
||||
},
|
||||
/** 处理备注 */
|
||||
remark: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '处理备注',
|
||||
},
|
||||
/** 步骤开始时间 */
|
||||
started_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '步骤开始时间',
|
||||
},
|
||||
/** 步骤完成时间 */
|
||||
completed_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '步骤完成时间',
|
||||
},
|
||||
/** 创建时间 */
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
/** 更新时间 */
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '更新时间',
|
||||
},
|
||||
/** 软删除时间 */
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_detail',
|
||||
comment: '售后进度步骤表',
|
||||
timestamps: false,
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_after_sale_id',
|
||||
fields: [ 'after_sale_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_operator_id',
|
||||
fields: [ 'operator_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// ============================
|
||||
// 关联关系
|
||||
// ============================
|
||||
|
||||
AfterSaleDetail.associate = function() {
|
||||
const { AfterSale, AfterSaleDetail } = app.model;
|
||||
|
||||
// 关联售后主表(多对一)
|
||||
AfterSaleDetail.belongsTo(AfterSale, {
|
||||
foreignKey: 'after_sale_id',
|
||||
as: 'afterSale',
|
||||
});
|
||||
};
|
||||
|
||||
// ============================
|
||||
// 常量挂载到 Model
|
||||
// ============================
|
||||
|
||||
AfterSaleDetail.STEP_STATUS = STEP_STATUS;
|
||||
|
||||
return AfterSaleDetail;
|
||||
};
|
||||
67
app/model/after_sale_function.js
Normal file
67
app/model/after_sale_function.js
Normal file
@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleFunction = app.model.define('afterSaleFunction', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
function_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '处理函数编码(与 inbox functions registry 注册名一致)',
|
||||
},
|
||||
name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '处理函数名称',
|
||||
},
|
||||
description: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '处理函数说明',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:1=启用,0=停用',
|
||||
},
|
||||
sort_order: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '排序值,越小越靠前',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_function',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '售后处理函数表(子类型处理链路)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'function_code' ],
|
||||
name: 'uk_function_code',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleFunction;
|
||||
};
|
||||
81
app/model/after_sale_keyword.js
Normal file
81
app/model/after_sale_keyword.js
Normal file
@ -0,0 +1,81 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleKeyword = app.model.define('afterSaleKeyword', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义,仅该仓库可见)',
|
||||
},
|
||||
sub_type_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
|
||||
},
|
||||
keyword: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '关键词,命中即映射到对应售后子类型',
|
||||
},
|
||||
is_system: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否系统级:1=系统级(全部仓库可读,不允许编辑/删除),0=仓库自定义',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:1=启用,0=停用',
|
||||
},
|
||||
sort_order: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '匹配优先级,数值小者优先(同长度命中时生效)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_keyword',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '售后关键词表(关键词 → 售后子类型映射)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'keyword', 'warehouse_id' ],
|
||||
name: 'uk_keyword_warehouse',
|
||||
},
|
||||
{
|
||||
fields: [ 'sub_type_id' ],
|
||||
name: 'idx_sub_type_id',
|
||||
},
|
||||
{
|
||||
fields: [ 'warehouse_id' ],
|
||||
name: 'idx_warehouse_id',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleKeyword;
|
||||
};
|
||||
87
app/model/after_sale_reply.js
Normal file
87
app/model/after_sale_reply.js
Normal file
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleReply = app.model.define('afterSaleReply', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '仓库ID(NULL=系统级默认回复;非NULL=仓库级自定义回复,覆盖系统级)',
|
||||
},
|
||||
sub_type_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
|
||||
},
|
||||
reply: {
|
||||
type: TEXT,
|
||||
allowNull: false,
|
||||
comment: '自定义回复文案(支持换行,可含占位符)',
|
||||
},
|
||||
is_reply: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否回复:1=命中后回复,0=静默不回复',
|
||||
},
|
||||
create_work_order: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否登记工单:1=执行函数处理(可能建工单,默认),0=仅回复不执行函数',
|
||||
},
|
||||
no_number_hint: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '未取到单据号时的引导语(如:请提供运单号;为空则用默认引导语)',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:1=启用,0=停用(停用视为未设置,回退系统级)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_reply',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '售后自定义回复表(仓库级覆盖系统级)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'warehouse_id', 'sub_type_id' ],
|
||||
name: 'uk_warehouse_sub_type',
|
||||
},
|
||||
{
|
||||
fields: [ 'sub_type_id' ],
|
||||
name: 'idx_sub_type_id',
|
||||
},
|
||||
{
|
||||
fields: [ 'is_enabled' ],
|
||||
name: 'idx_is_enabled',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleReply;
|
||||
};
|
||||
86
app/model/after_sale_sub_type.js
Normal file
86
app/model/after_sale_sub_type.js
Normal file
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleSubType = app.model.define('afterSaleSubType', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义)',
|
||||
},
|
||||
type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
comment: '所属售后类型编码(对应 wms_after_sale_type.type)',
|
||||
},
|
||||
sub_type: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '售后子类型编码(与 wms_after_sale.sub_type 对应)',
|
||||
},
|
||||
name: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '售后子类型名称',
|
||||
},
|
||||
is_system: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否系统级:1=系统级(不可编辑/删除),0=仓库自定义',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:1=启用,0=停用',
|
||||
},
|
||||
sort_order: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '排序值,越小越靠前',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_sub_type',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '售后子类型表(系统级 + 仓库自定义)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'type', 'sub_type', 'warehouse_id' ],
|
||||
name: 'uk_type_subtype_warehouse',
|
||||
},
|
||||
{
|
||||
fields: [ 'warehouse_id' ],
|
||||
name: 'idx_warehouse_id',
|
||||
},
|
||||
{
|
||||
fields: [ 'is_system' ],
|
||||
name: 'idx_is_system',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleSubType;
|
||||
};
|
||||
59
app/model/after_sale_sub_type_function.js
Normal file
59
app/model/after_sale_sub_type_function.js
Normal file
@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleSubTypeFunction = app.model.define('afterSaleSubTypeFunction', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
sub_type_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
|
||||
},
|
||||
function_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '处理函数ID(关联 wms_after_sale_function.id)',
|
||||
},
|
||||
sort_order: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同子类型下处理函数执行顺序,数值小者优先',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_sub_type_function',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '售后子类型-处理函数关联表(多对多)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'sub_type_id', 'function_id' ],
|
||||
name: 'uk_sub_type_function',
|
||||
},
|
||||
{
|
||||
fields: [ 'function_id' ],
|
||||
name: 'idx_function_id',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleSubTypeFunction;
|
||||
};
|
||||
70
app/model/after_sale_sub_type_group.js
Normal file
70
app/model/after_sale_sub_type_group.js
Normal file
@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleSubTypeGroup = app.model.define('afterSaleSubTypeGroup', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
sub_type_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
|
||||
},
|
||||
group_type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
comment: '群类型:store=货主群 / warehouse=仓库群 / express=快递群',
|
||||
},
|
||||
sub_group: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
comment: '群子类型:store(after_sales/finance/receiving)、warehouse(customer_service/...)、express(pickup/after_sales)',
|
||||
},
|
||||
is_system: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否系统预设关联:1=系统级子类型默认分配(锁定不可改),0=自定义',
|
||||
},
|
||||
sort_order: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '排序值,越小越靠前',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_sub_type_group',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '群类型-售后子类型关联表(多对多)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'sub_type_id', 'group_type', 'sub_group' ],
|
||||
name: 'uk_sub_type_group',
|
||||
},
|
||||
{
|
||||
fields: [ 'group_type', 'sub_group' ],
|
||||
name: 'idx_group_type',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleSubTypeGroup;
|
||||
};
|
||||
59
app/model/after_sale_sub_type_rule.js
Normal file
59
app/model/after_sale_sub_type_rule.js
Normal file
@ -0,0 +1,59 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleSubTypeRule = app.model.define('afterSaleSubTypeRule', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
sub_type_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '售后子类型ID(关联 wms_after_sale_sub_type.id)',
|
||||
},
|
||||
number_rule_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '取号规则ID(关联 wms_inbox_number_rule.id)',
|
||||
},
|
||||
sort_order: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '同一子类型下规则的提取顺序,数值小者优先',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_sub_type_rule',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '售后子类型-取号规则关联表(多对多)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'sub_type_id', 'number_rule_id' ],
|
||||
name: 'uk_sub_type_rule',
|
||||
},
|
||||
{
|
||||
fields: [ 'number_rule_id' ],
|
||||
name: 'idx_number_rule_id',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleSubTypeRule;
|
||||
};
|
||||
81
app/model/after_sale_type.js
Normal file
81
app/model/after_sale_type.js
Normal file
@ -0,0 +1,81 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const AfterSaleType = app.model.define('afterSaleType', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '仓库ID(NULL=系统级,全部仓库可见;非NULL=该仓库自定义)',
|
||||
},
|
||||
type: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
comment: '售后类型编码:order/receiving/entry/stockout,仓库自定义可自定义编码',
|
||||
},
|
||||
name: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '售后类型名称',
|
||||
},
|
||||
is_system: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否系统级:1=系统级(不可编辑/删除),0=仓库自定义',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:1=启用,0=停用',
|
||||
},
|
||||
sort_order: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '排序值,越小越靠前',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_after_sale_type',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '售后类型表(系统级 + 仓库自定义)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'type', 'warehouse_id' ],
|
||||
name: 'uk_type_warehouse',
|
||||
},
|
||||
{
|
||||
fields: [ 'warehouse_id' ],
|
||||
name: 'idx_warehouse_id',
|
||||
},
|
||||
{
|
||||
fields: [ 'is_system' ],
|
||||
name: 'idx_is_system',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return AfterSaleType;
|
||||
};
|
||||
@ -65,6 +65,16 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '自身IP白名单',
|
||||
},
|
||||
callback_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: 'API回调通知URL',
|
||||
},
|
||||
callback_functions: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '承接的出站回调 method 列表(空/未勾选=不承接任何回调;按 method 自动路由)',
|
||||
},
|
||||
qimen_app_key: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
@ -103,10 +113,10 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
defaultValue: 'md5',
|
||||
validate: {
|
||||
isIn: [[ 'md5', 'hmac', 'sha256' ]],
|
||||
isIn: [[ 'md5' ]],
|
||||
len: [ 0, 50 ],
|
||||
},
|
||||
comment: '签名方法',
|
||||
comment: '签名方法(当前仅支持 md5)',
|
||||
},
|
||||
rate_limit: {
|
||||
type: INTEGER(11),
|
||||
@ -177,6 +187,7 @@ module.exports = app => {
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
paranoid: false,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
comment: 'API应用配置表',
|
||||
@ -194,7 +205,7 @@ module.exports = app => {
|
||||
{
|
||||
name: 'uk_interface_warehouse',
|
||||
unique: true,
|
||||
fields: [ 'qimen_app_key', 'qimen_customer_id' ],
|
||||
fields: [ 'qimen_app_key', 'qimen_warehouse_code' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_interface_contract',
|
||||
@ -226,7 +237,7 @@ module.exports = app => {
|
||||
|
||||
// 定义关联关系
|
||||
ApiApp.associate = function() {
|
||||
const { InterfaceType, StoreWarehouse, Store, InterfaceLog } = app.model;
|
||||
const { InterfaceType, StoreWarehouse, Store } = app.model;
|
||||
|
||||
// 关联接口类型
|
||||
ApiApp.belongsTo(InterfaceType, {
|
||||
@ -288,22 +299,5 @@ module.exports = app => {
|
||||
return generatedSignature === signature;
|
||||
};
|
||||
|
||||
// 类方法 - 根据AppKey查找
|
||||
ApiApp.findByAppKey = async function(appKey) {
|
||||
return await this.findOne({
|
||||
where: { self_app_key: appKey },
|
||||
});
|
||||
};
|
||||
|
||||
// 类方法 - 根据奇门配置查找
|
||||
ApiApp.findByQimenConfig = async function(appKey, customerId) {
|
||||
return await this.findOne({
|
||||
where: {
|
||||
qimen_app_key: appKey,
|
||||
qimen_customer_id: customerId,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return ApiApp;
|
||||
};
|
||||
|
||||
125
app/model/camera.js
Normal file
125
app/model/camera.js
Normal file
@ -0,0 +1,125 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize;
|
||||
|
||||
const Camera = app.model.define('camera', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
server_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '所属录像服务器ID,关联 wms_camera_server.id',
|
||||
},
|
||||
channel_id: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '通道编号(DVR/NVR 上的物理通道号)',
|
||||
},
|
||||
channel_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '通道原始名称',
|
||||
},
|
||||
ip: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '摄像头IP地址',
|
||||
},
|
||||
port: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: 'SDK管理端口(通常2020/8000)',
|
||||
},
|
||||
model: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '摄像头型号',
|
||||
},
|
||||
serial_number: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '摄像头序列号',
|
||||
},
|
||||
stream_type: {
|
||||
type: STRING(20),
|
||||
allowNull: true,
|
||||
comment: '码流类型(auto/main/sub)',
|
||||
},
|
||||
username: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '摄像头登录用户名',
|
||||
},
|
||||
password: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '摄像头登录密码',
|
||||
},
|
||||
custom_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '自定义摄像头名称',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_camera',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '摄像头表',
|
||||
indexes: [
|
||||
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
|
||||
{ name: 'idx_server_id', fields: [ 'server_id' ] },
|
||||
{ name: 'uk_server_channel', unique: true, fields: [ 'server_id', 'channel_id', 'deleted_at' ] },
|
||||
{ name: 'idx_status', fields: [ 'status' ] },
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
Camera.associate = () => {
|
||||
app.model.Camera.belongsTo(app.model.CameraServer, {
|
||||
foreignKey: 'server_id',
|
||||
targetKey: 'id',
|
||||
as: 'server',
|
||||
});
|
||||
};
|
||||
|
||||
return Camera;
|
||||
};
|
||||
100
app/model/camera_server.js
Normal file
100
app/model/camera_server.js
Normal file
@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, BIGINT, INTEGER, DATE, TINYINT } = app.Sequelize;
|
||||
|
||||
const CameraServer = app.model.define('camera_server', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '服务器名称',
|
||||
},
|
||||
brand: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '品牌(如 Hikvision/Dahua)',
|
||||
},
|
||||
public_ip: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '公网IP',
|
||||
},
|
||||
internal_ip: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '内网IP',
|
||||
},
|
||||
public_port: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '远程/公网端口',
|
||||
},
|
||||
internal_port: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '本地/内网端口',
|
||||
},
|
||||
username: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '登录账号',
|
||||
},
|
||||
password: {
|
||||
type: STRING(200),
|
||||
allowNull: true,
|
||||
comment: '登录密码',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT,
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用 1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_camera_server',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '录像服务器表',
|
||||
indexes: [
|
||||
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
|
||||
{ name: 'idx_status', fields: [ 'status' ] },
|
||||
{ name: 'idx_deleted_at', fields: [ 'deleted_at' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return CameraServer;
|
||||
};
|
||||
112
app/model/client_error_log.js
Normal file
112
app/model/client_error_log.js
Normal file
@ -0,0 +1,112 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 客户端错误日志暂存表模型(wms_client_error_log)。
|
||||
*
|
||||
* Android/iOS/Web 等设备端通过 index.uploadClientErrorLog 上报的运行时错误日志暂存,
|
||||
* 仅做数据落库供人工/后台查询分析;report_uuid 唯一索引承担幂等去重(重复上报静默成功)。
|
||||
* created_at/updated_at 由 Sequelize 时间戳统一取服务器当前时间,不采信客户端时间。
|
||||
*
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE, TEXT } = app.Sequelize;
|
||||
|
||||
const ClientErrorLog = app.model.define('client_error_log', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
client_type: {
|
||||
type: STRING(32),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端类型:android/ios/web 等',
|
||||
},
|
||||
app_version: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端版本号',
|
||||
},
|
||||
device_id: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '设备唯一标识',
|
||||
},
|
||||
os_version: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '操作系统版本',
|
||||
},
|
||||
device_model: {
|
||||
type: STRING(128),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '设备型号',
|
||||
},
|
||||
error_type: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '错误类型/等级',
|
||||
},
|
||||
error_message: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '错误信息(服务端截断上限 5000 字符)',
|
||||
},
|
||||
error_stack: {
|
||||
type: TEXT('medium'),
|
||||
allowNull: true,
|
||||
comment: '错误堆栈(服务端截断上限 65535 字符)',
|
||||
},
|
||||
extra: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '附加上下文(JSON 字符串,服务端截断上限 65535 字符)',
|
||||
},
|
||||
report_uuid: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
defaultValue: '',
|
||||
comment: '客户端上报幂等ID(唯一索引,重复上报静默成功)',
|
||||
},
|
||||
client_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '客户端错误发生时间(仅参考,不作为记录时间)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '服务端写入时间(统一取服务器当前时间)',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_client_error_log',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '客户端错误日志暂存表(设备端运行时错误上报暂存)',
|
||||
indexes: [
|
||||
{ name: 'uk_report_uuid', unique: true, fields: [ 'report_uuid' ] },
|
||||
{ name: 'idx_created_at', fields: [ 'created_at' ] },
|
||||
{ name: 'idx_client_type_app_version', fields: [ 'client_type', 'app_version' ] },
|
||||
{ name: 'idx_device_id', fields: [ 'device_id' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return ClientErrorLog;
|
||||
};
|
||||
81
app/model/container.js
Normal file
81
app/model/container.js
Normal file
@ -0,0 +1,81 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 容器(篮筐)资产登记表 Model。
|
||||
*
|
||||
* 对应数据库表 `wms_container`,登记仓库的物理容器(篮筐)资产:
|
||||
* 容器编号、使用状态、是否损坏、损坏说明、备注等。
|
||||
* 同一仓库内容器编号唯一,通过 warehouse_id 做数据隔离维度。
|
||||
* 后续散单拣货把购物车商品临时转移到容器时,通过 status 标记占用/空闲。
|
||||
* @param {import('egg').Application} app - Egg 应用实例
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, ENUM } = app.Sequelize;
|
||||
|
||||
const Container = app.model.define('wms_container', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID(数据隔离维度)',
|
||||
},
|
||||
container_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '容器编号(篮筐编号)',
|
||||
},
|
||||
status: {
|
||||
type: ENUM('idle', 'in_use'),
|
||||
allowNull: false,
|
||||
defaultValue: 'idle',
|
||||
comment: '使用状态:idle=空闲 in_use=占用(散单商品临时转移)',
|
||||
},
|
||||
is_damaged: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: false,
|
||||
defaultValue: 'N',
|
||||
comment: '是否损坏:Y=损坏 N=正常',
|
||||
},
|
||||
damage_remark: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '损坏说明',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '登记人账户ID',
|
||||
},
|
||||
creator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '登记人名称快照',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_container',
|
||||
comment: '容器(篮筐)资产登记表',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
indexes: [
|
||||
{ name: 'uk_warehouse_container_no', unique: true, fields: [ 'warehouse_id', 'container_no' ] },
|
||||
{ name: 'idx_warehouse_id', fields: [ 'warehouse_id' ] },
|
||||
{ name: 'idx_status', fields: [ 'status' ] },
|
||||
{ name: 'idx_is_damaged', fields: [ 'is_damaged' ] },
|
||||
],
|
||||
});
|
||||
|
||||
return Container;
|
||||
};
|
||||
107
app/model/embargo_policy.js
Normal file
107
app/model/embargo_policy.js
Normal file
@ -0,0 +1,107 @@
|
||||
// app/model/embargo_policy.js
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING, ENUM, TEXT, DATEONLY, DATE, BOOLEAN, BIGINT } = app.Sequelize;
|
||||
|
||||
const EmbargoPolicy = app.model.define('wms_embargo_policies', {
|
||||
id: {
|
||||
type: INTEGER.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: 'ID',
|
||||
},
|
||||
policy_name: {
|
||||
type: STRING(100),
|
||||
allowNull: false,
|
||||
comment: '策略名称',
|
||||
},
|
||||
status: {
|
||||
type: ENUM('ACTIVE', 'INACTIVE', 'PENDING', 'EXPIRED'),
|
||||
allowNull: true,
|
||||
defaultValue: 'PENDING',
|
||||
comment: '状态',
|
||||
},
|
||||
embargo_scope: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '禁运范围(数组)',
|
||||
},
|
||||
start_date: {
|
||||
type: DATEONLY,
|
||||
allowNull: false,
|
||||
comment: '生效开始日期',
|
||||
},
|
||||
end_date: {
|
||||
type: DATEONLY,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '结束日期',
|
||||
},
|
||||
is_permanent: {
|
||||
type: BOOLEAN,
|
||||
allowNull: true,
|
||||
defaultValue: false,
|
||||
comment: '是否永久有效',
|
||||
},
|
||||
description: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '策略描述',
|
||||
},
|
||||
created_by: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '创建人',
|
||||
},
|
||||
updated_by: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '更新人',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_embargo_policies',
|
||||
timestamps: false,
|
||||
underscored: false,
|
||||
comment: '禁运策略主表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_status',
|
||||
fields: [ 'status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_dates',
|
||||
fields: [ 'start_date', 'end_date' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_created_at',
|
||||
fields: [ 'created_at' ],
|
||||
},
|
||||
{
|
||||
name: 'warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return EmbargoPolicy;
|
||||
};
|
||||
@ -128,6 +128,8 @@ module.exports = app => {
|
||||
foreignKey: 'stock_id',
|
||||
as: 'stock',
|
||||
});
|
||||
|
||||
|
||||
};
|
||||
|
||||
// 实例方法 - 验证收货数量
|
||||
@ -191,76 +193,8 @@ module.exports = app => {
|
||||
};
|
||||
};
|
||||
|
||||
// 静态方法 - 批量更新收货数量(带验证)
|
||||
EntryItems.batchUpdateReceived = async function(app, updates, options = {}) {
|
||||
const transaction = options.transaction || await app.model.transaction();
|
||||
|
||||
try {
|
||||
// 先检查所有更新是否合法
|
||||
for (const update of updates) {
|
||||
const { id, quantity } = update;
|
||||
const item = await app.model.EntryItems.findByPk(id, { transaction });
|
||||
|
||||
if (!item) {
|
||||
throw new Error(`入库明细 ${id} 不存在`);
|
||||
}
|
||||
|
||||
// 验证数量
|
||||
item.validateReceiveQuantity(quantity);
|
||||
}
|
||||
|
||||
// 执行更新
|
||||
for (const update of updates) {
|
||||
const { id, quantity } = update;
|
||||
const item = await app.model.EntryItems.findByPk(id, { transaction });
|
||||
|
||||
const newReceived = (item.received_quantity || 0) + quantity;
|
||||
await item.update({
|
||||
received_quantity: newReceived,
|
||||
}, { transaction });
|
||||
}
|
||||
|
||||
if (!options.transaction) {
|
||||
await transaction.commit();
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
if (!options.transaction) {
|
||||
await transaction.rollback();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// 静态方法 - 获取入库单总进度
|
||||
EntryItems.getOrderProgress = async function(app, orderId) {
|
||||
const items = await app.model.EntryItems.findAll({
|
||||
where: { order_id: orderId },
|
||||
attributes: [
|
||||
[ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ],
|
||||
[ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ],
|
||||
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ],
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const result = items[0] || {};
|
||||
const totalPlan = parseInt(result.total_plan) || 0;
|
||||
const totalReceived = parseInt(result.total_received) || 0;
|
||||
|
||||
return {
|
||||
total_plan: totalPlan,
|
||||
total_received: totalReceived,
|
||||
total_remaining: Math.max(0, totalPlan - totalReceived),
|
||||
item_count: parseInt(result.item_count) || 0,
|
||||
progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0,
|
||||
is_completed: totalReceived >= totalPlan,
|
||||
};
|
||||
};
|
||||
|
||||
// 钩子函数 - 保存前验证
|
||||
EntryItems.beforeSave(async (instance, options) => {
|
||||
EntryItems.beforeSave(async instance => {
|
||||
const received = instance.received_quantity || 0;
|
||||
const plan = instance.count || 0;
|
||||
|
||||
@ -278,7 +212,7 @@ module.exports = app => {
|
||||
});
|
||||
|
||||
// 钩子函数 - 更新前验证
|
||||
EntryItems.beforeUpdate(async (instance, options) => {
|
||||
EntryItems.beforeUpdate(async instance => {
|
||||
// 如果更新了received_quantity,进行验证
|
||||
if (instance.changed('received_quantity')) {
|
||||
const received = instance.received_quantity || 0;
|
||||
|
||||
@ -19,7 +19,7 @@ module.exports = app => {
|
||||
},
|
||||
},
|
||||
order_type: {
|
||||
type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK'),
|
||||
type: ENUM('SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK', 'B2BRK', 'XNRK', 'SHRK'),
|
||||
allowNull: false,
|
||||
comment: '业务类型',
|
||||
},
|
||||
@ -81,10 +81,10 @@ module.exports = app => {
|
||||
comment: '来源类型',
|
||||
},
|
||||
order_status: {
|
||||
type: ENUM('PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED', 'CREATED', 'CREATING'),
|
||||
type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'),
|
||||
allowNull: false,
|
||||
defaultValue: 'PENDING',
|
||||
comment: '订单状态',
|
||||
defaultValue: 'CREATED',
|
||||
comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废',
|
||||
},
|
||||
sync_status: {
|
||||
type: ENUM('PENDING', 'SUCCESS', 'FAILED'),
|
||||
@ -137,6 +137,18 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: 'ERP备注',
|
||||
},
|
||||
expense_record: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '费用是否记录',
|
||||
},
|
||||
is_virtual_inbound: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '是否虚拟入库:0=否 1=是',
|
||||
},
|
||||
store_name: {
|
||||
type: STRING(200),
|
||||
allowNull: true,
|
||||
@ -209,7 +221,7 @@ module.exports = app => {
|
||||
|
||||
// 关联关系
|
||||
EntryOrder.associate = function() {
|
||||
const { EntryOrder, Store, EntryItems } = app.model;
|
||||
const { EntryOrder, Store, EntryItems, EntryOrderReceiving } = app.model;
|
||||
|
||||
// 关联仓库
|
||||
EntryOrder.belongsTo(Store, {
|
||||
@ -228,15 +240,21 @@ module.exports = app => {
|
||||
foreignKey: 'order_id',
|
||||
as: 'items',
|
||||
});
|
||||
|
||||
// 关联入库单-收货单绑定记录
|
||||
EntryOrder.hasMany(EntryOrderReceiving, {
|
||||
foreignKey: 'entry_order_id',
|
||||
as: 'receivingBindings',
|
||||
});
|
||||
};
|
||||
|
||||
// 实例方法
|
||||
EntryOrder.prototype.isPending = function() {
|
||||
return this.order_status === 'PENDING';
|
||||
EntryOrder.prototype.isCreated = function() {
|
||||
return this.order_status === 'CREATED';
|
||||
};
|
||||
|
||||
EntryOrder.prototype.isConfirmed = function() {
|
||||
return this.order_status === 'CONFIRMED';
|
||||
EntryOrder.prototype.isPending = function() {
|
||||
return this.order_status === 'PENDING';
|
||||
};
|
||||
|
||||
EntryOrder.prototype.isCompleted = function() {
|
||||
@ -247,20 +265,16 @@ module.exports = app => {
|
||||
return this.order_status === 'CANCELLED';
|
||||
};
|
||||
|
||||
EntryOrder.prototype.isPartialReceived = function() {
|
||||
return this.order_status === 'PARTIAL_RECEIVED';
|
||||
};
|
||||
|
||||
EntryOrder.prototype.canConfirm = function() {
|
||||
return [ 'PENDING', 'CREATED' ].includes(this.order_status);
|
||||
return [ 'CREATED', 'PENDING' ].includes(this.order_status);
|
||||
};
|
||||
|
||||
EntryOrder.prototype.canCancel = function() {
|
||||
return [ 'PENDING', 'CONFIRMED', 'CREATED' ].includes(this.order_status);
|
||||
return [ 'CREATED', 'PENDING' ].includes(this.order_status);
|
||||
};
|
||||
|
||||
EntryOrder.prototype.canComplete = function() {
|
||||
return [ 'CONFIRMED', 'PARTIAL_RECEIVED' ].includes(this.order_status);
|
||||
return [ 'PENDING' ].includes(this.order_status);
|
||||
};
|
||||
|
||||
EntryOrder.prototype.isSyncSuccess = function() {
|
||||
@ -275,237 +289,5 @@ module.exports = app => {
|
||||
return this.is_enabled === 1 && !this.deleted_at;
|
||||
};
|
||||
|
||||
// 静态方法
|
||||
EntryOrder.findByOrderCode = async function(app, entryOrderCode, warehouseId, storeId) {
|
||||
return await app.model.EntryOrder.findOne({
|
||||
where: {
|
||||
entry_order_code: entryOrderCode,
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
is_enabled: 1,
|
||||
deleted_at: null,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: app.model.Store,
|
||||
as: 'warehouse',
|
||||
attributes: [ 'store_name', 'store_code' ],
|
||||
},
|
||||
{
|
||||
model: app.model.Store,
|
||||
as: 'store',
|
||||
attributes: [ 'store_name' ],
|
||||
},
|
||||
{
|
||||
model: app.model.EntryItems,
|
||||
as: 'items',
|
||||
include: [{
|
||||
model: app.model.StockWarehouse,
|
||||
as: 'stock',
|
||||
attributes: [ 'product_code', 'product_name' ],
|
||||
}],
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
EntryOrder.findByStatus = async function(app, status, params = {}) {
|
||||
const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params;
|
||||
|
||||
const where = {
|
||||
order_status: status,
|
||||
is_enabled: 1,
|
||||
deleted_at: null,
|
||||
};
|
||||
|
||||
if (warehouse_id) {
|
||||
where.warehouse_id = warehouse_id;
|
||||
}
|
||||
|
||||
if (store_id) {
|
||||
where.store_id = store_id;
|
||||
}
|
||||
|
||||
if (start_date || end_date) {
|
||||
where.created_at = {};
|
||||
if (start_date) {
|
||||
where.created_at[app.Sequelize.Op.gte] = start_date;
|
||||
}
|
||||
if (end_date) {
|
||||
where.created_at[app.Sequelize.Op.lte] = end_date;
|
||||
}
|
||||
}
|
||||
|
||||
const { count, rows } = await app.model.EntryOrder.findAndCountAll({
|
||||
where,
|
||||
include: [
|
||||
{
|
||||
model: app.model.Store,
|
||||
as: 'warehouse',
|
||||
attributes: [ 'store_name' ],
|
||||
},
|
||||
{
|
||||
model: app.model.Store,
|
||||
as: 'store',
|
||||
attributes: [ 'store_name' ],
|
||||
},
|
||||
],
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
offset: (page - 1) * pageSize,
|
||||
limit: parseInt(pageSize),
|
||||
distinct: true,
|
||||
});
|
||||
|
||||
return {
|
||||
list: rows,
|
||||
pagination: {
|
||||
page: parseInt(page),
|
||||
pageSize: parseInt(pageSize),
|
||||
total: count,
|
||||
totalPages: Math.ceil(count / pageSize),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
EntryOrder.getStatsByWarehouse = async function(app, warehouseId, startDate, endDate) {
|
||||
const where = {
|
||||
warehouse_id: warehouseId,
|
||||
is_enabled: 1,
|
||||
deleted_at: null,
|
||||
};
|
||||
|
||||
if (startDate || endDate) {
|
||||
where.created_at = {};
|
||||
if (startDate) {
|
||||
where.created_at[app.Sequelize.Op.gte] = startDate;
|
||||
}
|
||||
if (endDate) {
|
||||
where.created_at[app.Sequelize.Op.lte] = endDate;
|
||||
}
|
||||
}
|
||||
|
||||
const result = await app.model.EntryOrder.findAll({
|
||||
attributes: [
|
||||
'order_status',
|
||||
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ],
|
||||
[ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ],
|
||||
],
|
||||
where,
|
||||
group: [ 'order_status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const stats = {
|
||||
pending: 0,
|
||||
confirmed: 0,
|
||||
partial_received: 0,
|
||||
completed: 0,
|
||||
cancelled: 0,
|
||||
total: 0,
|
||||
total_lines: 0,
|
||||
};
|
||||
|
||||
result.forEach(item => {
|
||||
const status = item.order_status.toLowerCase();
|
||||
if (stats[status] !== undefined) {
|
||||
stats[status] = parseInt(item.count) || 0;
|
||||
}
|
||||
stats.total += parseInt(item.count) || 0;
|
||||
stats.total_lines += parseInt(item.total_lines) || 0;
|
||||
});
|
||||
|
||||
return stats;
|
||||
};
|
||||
|
||||
EntryOrder.updateSyncStatus = async function(app, orderId, status, message = null) {
|
||||
const order = await app.model.EntryOrder.findByPk(orderId);
|
||||
|
||||
if (!order) {
|
||||
throw new Error('入库单不存在');
|
||||
}
|
||||
|
||||
const updateData = {
|
||||
sync_status: status,
|
||||
};
|
||||
|
||||
if (message !== null) {
|
||||
updateData.sync_message = message;
|
||||
}
|
||||
|
||||
return await order.update(updateData);
|
||||
};
|
||||
|
||||
EntryOrder.updateOrderStatus = async function(app, orderId, status) {
|
||||
const order = await app.model.EntryOrder.findByPk(orderId);
|
||||
|
||||
if (!order) {
|
||||
throw new Error('入库单不存在');
|
||||
}
|
||||
|
||||
const validTransitions = {
|
||||
PENDING: [ 'CONFIRMED', 'CANCELLED' ],
|
||||
CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ],
|
||||
PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ],
|
||||
CREATED: [ 'PENDING', 'CANCELLED' ],
|
||||
CREATING: [ 'PENDING', 'CANCELLED' ],
|
||||
};
|
||||
|
||||
const allowedTransitions = validTransitions[order.order_status];
|
||||
if (!allowedTransitions || !allowedTransitions.includes(status)) {
|
||||
throw new Error(`状态从${order.order_status}转换到${status}不被允许`);
|
||||
}
|
||||
|
||||
return await order.update({ order_status: status });
|
||||
};
|
||||
|
||||
EntryOrder.calculateReceivedQuantities = async function(app, orderId) {
|
||||
// 这里需要根据实际业务逻辑计算已收货数量
|
||||
// 通常需要查询入库明细和实际收货记录
|
||||
|
||||
// 示例:查询入库明细
|
||||
const items = await app.model.EntryItems.findAll({
|
||||
where: { order_id: orderId },
|
||||
attributes: [
|
||||
'id',
|
||||
'count',
|
||||
[ app.Sequelize.literal('(SELECT SUM(quantity) FROM wms_storage WHERE inbound_order_no = wms_entry_order.entry_order_code AND item_id = wms_entry_items.item_id)'), 'received' ],
|
||||
],
|
||||
include: [{
|
||||
model: app.model.EntryOrder,
|
||||
as: 'order',
|
||||
attributes: [ 'entry_order_code' ],
|
||||
}],
|
||||
});
|
||||
|
||||
let totalExpected = 0;
|
||||
let totalReceived = 0;
|
||||
let allReceived = true;
|
||||
let anyReceived = false;
|
||||
|
||||
items.forEach(item => {
|
||||
const expected = item.count || 0;
|
||||
const received = item.received || 0;
|
||||
|
||||
totalExpected += expected;
|
||||
totalReceived += received;
|
||||
|
||||
if (expected > 0 && received < expected) {
|
||||
allReceived = false;
|
||||
}
|
||||
|
||||
if (received > 0) {
|
||||
anyReceived = true;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
total_expected: totalExpected,
|
||||
total_received: totalReceived,
|
||||
all_received: allReceived,
|
||||
any_received: anyReceived,
|
||||
percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0,
|
||||
};
|
||||
};
|
||||
|
||||
return EntryOrder;
|
||||
};
|
||||
|
||||
82
app/model/entry_order_receiving.js
Normal file
82
app/model/entry_order_receiving.js
Normal file
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize;
|
||||
|
||||
const EntryOrderReceiving = app.model.define('wms_entry_order_receiving', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
entry_order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '入库单ID,关联 wms_entry_order.id',
|
||||
},
|
||||
receiving_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '收货单ID,关联 wms_receiving.id',
|
||||
},
|
||||
allocated_quantity: {
|
||||
type: JSON_TYPE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '数量台账:收货明细ID→已分配数量(JSON对象,如 {"123":8});null 表示旧数据未初始化',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_entry_order_receiving',
|
||||
comment: '入库单-收货单主表级绑定关系表',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_entry_order_id',
|
||||
fields: [ 'entry_order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_receiving_id',
|
||||
fields: [ 'receiving_id' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_entry_order_receiving',
|
||||
unique: true,
|
||||
fields: [ 'entry_order_id', 'receiving_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 关联关系
|
||||
EntryOrderReceiving.associate = function() {
|
||||
const { EntryOrderReceiving, EntryOrder, Receiving } = app.model;
|
||||
|
||||
// 关联入库单
|
||||
EntryOrderReceiving.belongsTo(EntryOrder, {
|
||||
foreignKey: 'entry_order_id',
|
||||
as: 'entryOrder',
|
||||
});
|
||||
|
||||
// 关联收货单
|
||||
EntryOrderReceiving.belongsTo(Receiving, {
|
||||
foreignKey: 'receiving_id',
|
||||
as: 'receiving',
|
||||
});
|
||||
};
|
||||
|
||||
return EntryOrderReceiving;
|
||||
};
|
||||
99
app/model/entry_receiving_binding.js
Normal file
99
app/model/entry_receiving_binding.js
Normal file
@ -0,0 +1,99 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, BIGINT, ENUM, DATE } = app.Sequelize;
|
||||
|
||||
const EntryReceivingBinding = app.model.define('wms_entry_receiving_binding', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
entry_item_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '入库明细ID',
|
||||
},
|
||||
receiving_detail_id: {
|
||||
type: INTEGER,
|
||||
allowNull: false,
|
||||
comment: '收货明细ID',
|
||||
},
|
||||
allocated_quantity: {
|
||||
type: INTEGER,
|
||||
allowNull: false,
|
||||
comment: '预分配数量',
|
||||
validate: {
|
||||
min: 1,
|
||||
},
|
||||
},
|
||||
status: {
|
||||
type: ENUM('pending', 'committed', 'released'),
|
||||
allowNull: false,
|
||||
defaultValue: 'pending',
|
||||
comment: '绑定状态:pending-待提交 committed-已提交 released-已释放',
|
||||
},
|
||||
creator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '创建人ID',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_entry_receiving_binding',
|
||||
comment: '入库单明细-收货明细绑定关系表',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_entry_item_id',
|
||||
fields: [ 'entry_item_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_receiving_detail_id',
|
||||
fields: [ 'receiving_detail_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_status',
|
||||
fields: [ 'status' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_entry_receiving',
|
||||
unique: true,
|
||||
fields: [ 'entry_item_id', 'receiving_detail_id', 'status' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 关联关系
|
||||
EntryReceivingBinding.associate = function() {
|
||||
const { EntryReceivingBinding, EntryItems, ReceivingDetail } = app.model;
|
||||
|
||||
// 关联入库明细
|
||||
EntryReceivingBinding.belongsTo(EntryItems, {
|
||||
foreignKey: 'entry_item_id',
|
||||
as: 'entryItem',
|
||||
});
|
||||
|
||||
// 关联收货明细
|
||||
EntryReceivingBinding.belongsTo(ReceivingDetail, {
|
||||
foreignKey: 'receiving_detail_id',
|
||||
as: 'receivingDetail',
|
||||
});
|
||||
};
|
||||
|
||||
return EntryReceivingBinding;
|
||||
};
|
||||
86
app/model/express.js
Normal file
86
app/model/express.js
Normal file
@ -0,0 +1,86 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 定义快递基础信息模型。
|
||||
* @param {import('egg').Application} app Egg 应用实例
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 快递模型
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { STRING, JSON } = app.Sequelize;
|
||||
|
||||
const Express = app.model.define('express', {
|
||||
code: {
|
||||
type: STRING(50),
|
||||
primaryKey: true,
|
||||
allowNull: false,
|
||||
comment: '快递编码',
|
||||
},
|
||||
name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '快递名称',
|
||||
},
|
||||
KS: {
|
||||
type: STRING(255),
|
||||
field: 'KS',
|
||||
allowNull: true,
|
||||
comment: '快手编码',
|
||||
},
|
||||
polyapi_extra_info: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '聚合接口扩展信息',
|
||||
},
|
||||
PDD: {
|
||||
field: 'PDD',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '拼多多编码',
|
||||
},
|
||||
DY: {
|
||||
field: 'DY',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '抖音编码',
|
||||
},
|
||||
CAINIAO: {
|
||||
field: 'CAINIAO',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '菜鸟编码',
|
||||
},
|
||||
SPH: {
|
||||
field: 'SPH',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'SPH编码',
|
||||
},
|
||||
XHS: {
|
||||
field: 'XHS',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '小红书编码',
|
||||
},
|
||||
DW: {
|
||||
field: 'DW',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: 'DW编码',
|
||||
},
|
||||
JD: {
|
||||
field: 'JD',
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '京东编码',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
paranoid: false,
|
||||
comment: '快递基础信息表',
|
||||
});
|
||||
|
||||
return Express;
|
||||
};
|
||||
260
app/model/express_interface.js
Normal file
260
app/model/express_interface.js
Normal file
@ -0,0 +1,260 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 定义快递接口配置模型。
|
||||
* @param {Object} app Egg 应用对象。
|
||||
* @return {Object} 快递接口配置模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING, BIGINT, TINYINT, JSON } = app.Sequelize;
|
||||
|
||||
const ExpressInterface = app.model.define('express_interface', {
|
||||
id: {
|
||||
type: INTEGER(11).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '接口名称',
|
||||
},
|
||||
express_code: {
|
||||
type: STRING(255),
|
||||
allowNull: false,
|
||||
comment: '快递编码',
|
||||
},
|
||||
platform_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '平台编码',
|
||||
},
|
||||
sys_express_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '系统快递编码',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库编码',
|
||||
},
|
||||
shop_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '店铺ID',
|
||||
},
|
||||
platform_shop_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '平台店铺ID',
|
||||
},
|
||||
template_id: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '模板ID',
|
||||
},
|
||||
paymode: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '付款方式',
|
||||
},
|
||||
brandno: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '品牌编码',
|
||||
},
|
||||
providertype: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '服务商类型编码',
|
||||
},
|
||||
providerid: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '服务商ID',
|
||||
},
|
||||
sender_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '寄件人',
|
||||
},
|
||||
sender_tel: {
|
||||
type: STRING(11),
|
||||
allowNull: true,
|
||||
comment: '寄件电话',
|
||||
},
|
||||
weight: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '排序',
|
||||
},
|
||||
token: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '令牌',
|
||||
},
|
||||
viewer: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '验视员',
|
||||
},
|
||||
client_id: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '客户id',
|
||||
},
|
||||
is_share: {
|
||||
type: TINYINT(1),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '是否分享接口',
|
||||
},
|
||||
share_id: {
|
||||
type: INTEGER(11).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '分享id',
|
||||
},
|
||||
can_use_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '可用数量',
|
||||
},
|
||||
province_name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '寄件人名称',
|
||||
},
|
||||
city_name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '寄件人城市',
|
||||
},
|
||||
district_name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '寄件人区/县',
|
||||
},
|
||||
site_code: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '网点编码',
|
||||
},
|
||||
product_type: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '产品编码',
|
||||
},
|
||||
weight_type: {
|
||||
type: INTEGER(10),
|
||||
allowNull: true,
|
||||
comment: '重量类型',
|
||||
},
|
||||
shop_name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '平台店铺',
|
||||
},
|
||||
address: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '地址',
|
||||
},
|
||||
town_name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '寄件人街道',
|
||||
},
|
||||
ispickup: {
|
||||
type: TINYINT(1),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '是否上门取件',
|
||||
},
|
||||
is_hide_goods: {
|
||||
type: TINYINT(1),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '是否隐藏物品信息',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: true,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用(1=启用,0=停用)',
|
||||
},
|
||||
shipperno: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '寄件网点编码',
|
||||
},
|
||||
template_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '打印模板链接',
|
||||
},
|
||||
ext_data: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '扩展信息',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_interface',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
paranoid: false,
|
||||
comment: '快递接口配置表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* 定义快递接口与系统快递、店铺、打印平台的关联关系。
|
||||
*
|
||||
* 说明:
|
||||
* - `wms_express_interface.sys_express_code` 对应 `wms_express.code`
|
||||
* - `wms_express_interface.shop_id` 对应 `wms_shops.id`
|
||||
* - `wms_express_interface.platform_code` 对应 `wms_print_platform.platform_code`
|
||||
*/
|
||||
ExpressInterface.associate = function() {
|
||||
const { Express, Shop, PrintPlatform } = app.model;
|
||||
|
||||
if (Express && typeof ExpressInterface.belongsTo === 'function') {
|
||||
ExpressInterface.belongsTo(Express, {
|
||||
foreignKey: 'sys_express_code',
|
||||
targetKey: 'code',
|
||||
as: 'express',
|
||||
constraints: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (Shop && typeof ExpressInterface.belongsTo === 'function') {
|
||||
ExpressInterface.belongsTo(Shop, {
|
||||
foreignKey: 'shop_id',
|
||||
targetKey: 'id',
|
||||
as: 'shop',
|
||||
constraints: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (PrintPlatform && typeof ExpressInterface.belongsTo === 'function') {
|
||||
ExpressInterface.belongsTo(PrintPlatform, {
|
||||
foreignKey: 'platform_code',
|
||||
targetKey: 'platform_code',
|
||||
as: 'printPlatform',
|
||||
constraints: false,
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
return ExpressInterface;
|
||||
};
|
||||
229
app/model/express_print_record.js
Normal file
229
app/model/express_print_record.js
Normal file
@ -0,0 +1,229 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, DATE, TEXT, JSON } = app.Sequelize;
|
||||
|
||||
const ExpressPrintRecord = app.model.define('express_print_record', {
|
||||
id: {
|
||||
type: BIGINT(20),
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
express_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: false,
|
||||
comment: '快递记录ID',
|
||||
},
|
||||
order_id: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '订单ID',
|
||||
},
|
||||
express_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '快递单号',
|
||||
},
|
||||
platform: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '平台编码',
|
||||
},
|
||||
template_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: false,
|
||||
comment: '模板ID',
|
||||
},
|
||||
template_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '模板URL',
|
||||
},
|
||||
printer_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '打印机名称',
|
||||
},
|
||||
printer_config_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: true,
|
||||
comment: '打印配置ID',
|
||||
},
|
||||
print_data: {
|
||||
type: JSON,
|
||||
allowNull: false,
|
||||
comment: '打印请求数据',
|
||||
},
|
||||
encrypted_data: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '加密数据',
|
||||
},
|
||||
signature: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '签名',
|
||||
},
|
||||
add_data: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '附加数据',
|
||||
},
|
||||
custom_data: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '自定义数据',
|
||||
},
|
||||
print_status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'PENDING',
|
||||
comment: '打印状态',
|
||||
},
|
||||
print_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '打印次数',
|
||||
},
|
||||
last_print_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '最近打印时间',
|
||||
},
|
||||
next_retry_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '下次重试时间',
|
||||
},
|
||||
request_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '请求ID',
|
||||
},
|
||||
document_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '文档ID',
|
||||
},
|
||||
batch_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '批次号',
|
||||
},
|
||||
print_result: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '打印结果',
|
||||
},
|
||||
error_message: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '错误信息',
|
||||
},
|
||||
print_cost_time: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '打印耗时(ms)',
|
||||
},
|
||||
create_interface: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '创建接口名',
|
||||
},
|
||||
print_interface: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '打印接口名',
|
||||
},
|
||||
operator_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: true,
|
||||
comment: '操作人ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
print_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '打印时间',
|
||||
},
|
||||
update_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_print_record',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '快递面单打印记录表',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
name: 'uk_express_print',
|
||||
fields: [ 'express_id', 'print_status' ],
|
||||
},
|
||||
{
|
||||
unique: true,
|
||||
name: 'uk_request_id',
|
||||
fields: [ 'request_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_order_id',
|
||||
fields: [ 'order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_express_no',
|
||||
fields: [ 'express_no' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_platform',
|
||||
fields: [ 'platform' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_print_status',
|
||||
fields: [ 'print_status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_create_time',
|
||||
fields: [ 'create_time' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_batch_no',
|
||||
fields: [ 'batch_no' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_template_id',
|
||||
fields: [ 'template_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_printer_config_id',
|
||||
fields: [ 'printer_config_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_print_time',
|
||||
fields: [ 'print_time' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return ExpressPrintRecord;
|
||||
};
|
||||
44
app/model/express_product_type.js
Normal file
44
app/model/express_product_type.js
Normal file
@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 定义快递产品类型模型。
|
||||
* @param {Object} app Egg 应用对象。
|
||||
* @return {Object} 快递产品类型模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING } = app.Sequelize;
|
||||
|
||||
const ExpressProductType = app.model.define('express_product_type', {
|
||||
id: {
|
||||
type: INTEGER(11).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '产品名称',
|
||||
},
|
||||
express_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '物流编码',
|
||||
},
|
||||
code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '产品编码',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_product_type',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
paranoid: false,
|
||||
comment: '快递产品类型表',
|
||||
});
|
||||
|
||||
return ExpressProductType;
|
||||
};
|
||||
58
app/model/express_setting.js
Normal file
58
app/model/express_setting.js
Normal file
@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING, BIGINT, DATE } = app.Sequelize;
|
||||
|
||||
const ExpressSetting = app.model.define('express_setting', {
|
||||
id: {
|
||||
type: INTEGER(11),
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
express_code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '系统快递编码',
|
||||
},
|
||||
code: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '自设编码',
|
||||
},
|
||||
name: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '别名',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库主体ID',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_setting',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '快递配置表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_express_code',
|
||||
fields: [ 'express_code' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_deleted_at',
|
||||
fields: [ 'warehouse_id', 'deleted_at' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return ExpressSetting;
|
||||
};
|
||||
@ -2,7 +2,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN } = app.Sequelize;
|
||||
const { BIGINT, INTEGER, STRING, DATE, BOOLEAN } = app.Sequelize;
|
||||
|
||||
const File = app.model.define('wms_file', {
|
||||
id: {
|
||||
@ -102,6 +102,12 @@ module.exports = app => {
|
||||
defaultValue: null,
|
||||
comment: '更新时间',
|
||||
},
|
||||
expire_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '过期时间,为空表示永不过期',
|
||||
},
|
||||
is_deleted: {
|
||||
type: BOOLEAN,
|
||||
allowNull: false,
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, STRING, TEXT, DATE, BOOLEAN, JSON: JSON_TYPE } = app.Sequelize;
|
||||
const { BIGINT, INTEGER, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const FileReference = app.model.define('wms_file_reference', {
|
||||
id: {
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, DATE } = app.Sequelize;
|
||||
const { STRING, INTEGER } = app.Sequelize;
|
||||
|
||||
const I18nKey = app.model.define('wms_i18n_key', {
|
||||
id: {
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, DATE, Op } = app.Sequelize;
|
||||
const { STRING, INTEGER } = app.Sequelize;
|
||||
|
||||
// 直接在文件中定义常量
|
||||
const CONSTANTS = {
|
||||
@ -60,123 +60,5 @@ module.exports = app => {
|
||||
// 挂载常量到模型(可选)
|
||||
I18nTranslation.CONSTANTS = CONSTANTS;
|
||||
|
||||
/**
|
||||
* 获取翻译
|
||||
* @param keyId
|
||||
* @param language
|
||||
*/
|
||||
I18nTranslation.getTranslation = async function(keyId, language) {
|
||||
return await this.findOne({
|
||||
where: { key_id: keyId, language },
|
||||
include: [{
|
||||
model: app.model.I18nKey,
|
||||
as: 'key',
|
||||
}],
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 批量获取翻译
|
||||
* @param keyIds
|
||||
* @param language
|
||||
*/
|
||||
I18nTranslation.batchGetTranslations = async function(keyIds, language) {
|
||||
const records = await this.findAll({
|
||||
where: {
|
||||
key_id: keyIds,
|
||||
language,
|
||||
},
|
||||
include: [{
|
||||
model: app.model.I18nKey,
|
||||
as: 'key',
|
||||
attributes: [ 'key_name' ],
|
||||
}],
|
||||
});
|
||||
|
||||
// 返回键值对
|
||||
const result = {};
|
||||
records.forEach(record => {
|
||||
if (record.key) {
|
||||
result[record.key.key_name] = record.translation || record.key.key_name;
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取项目翻译
|
||||
* @param project
|
||||
* @param language
|
||||
*/
|
||||
I18nTranslation.getProjectTranslations = async function(project, language) {
|
||||
const records = await this.findAll({
|
||||
include: [{
|
||||
model: app.model.I18nKey,
|
||||
as: 'key',
|
||||
where: { project },
|
||||
attributes: [ 'key_name' ],
|
||||
}],
|
||||
where: { language },
|
||||
});
|
||||
|
||||
const result = {};
|
||||
records.forEach(record => {
|
||||
if (record.key && record.key.key_name) {
|
||||
result[record.key.key_name] = record.translation || record.key.key_name;
|
||||
}
|
||||
});
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* 创建或更新翻译
|
||||
* @param keyId
|
||||
* @param language
|
||||
* @param translation
|
||||
*/
|
||||
I18nTranslation.upsertTranslation = async function(keyId, language, translation) {
|
||||
const [ record, created ] = await this.findOrCreate({
|
||||
where: { key_id: keyId, language },
|
||||
defaults: {
|
||||
key_id: keyId,
|
||||
language,
|
||||
translation: translation || null,
|
||||
translation_status: translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED,
|
||||
},
|
||||
});
|
||||
|
||||
if (!created) {
|
||||
record.translation = translation || null;
|
||||
record.translation_status = translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED;
|
||||
await record.save();
|
||||
}
|
||||
|
||||
return record;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取未翻译列表
|
||||
* @param language
|
||||
* @param project
|
||||
*/
|
||||
I18nTranslation.getUntranslated = async function(language, project) {
|
||||
return await this.findAll({
|
||||
include: [{
|
||||
model: app.model.I18nKey,
|
||||
as: 'key',
|
||||
where: { project },
|
||||
}],
|
||||
where: {
|
||||
language,
|
||||
[Op.or]: [
|
||||
{ translation: null },
|
||||
{ translation: '' },
|
||||
],
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return I18nTranslation;
|
||||
};
|
||||
|
||||
166
app/model/inbound_direct_log.js
Normal file
166
app/model/inbound_direct_log.js
Normal file
@ -0,0 +1,166 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize;
|
||||
|
||||
const InboundDirectLog = app.model.define('wms_inbound_direct_log', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '货主ID',
|
||||
},
|
||||
stock_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: false,
|
||||
comment: '商品SKU ID,关联 wms_stock_warehouse.id',
|
||||
},
|
||||
quantity: {
|
||||
type: INTEGER(12),
|
||||
allowNull: false,
|
||||
comment: '入库数量',
|
||||
},
|
||||
inbound_type: {
|
||||
type: ENUM('import', 'pda'),
|
||||
allowNull: false,
|
||||
comment: '入库方式:import-导入入库 pda-PDA入库',
|
||||
},
|
||||
entry_order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '关联入库单ID(可选),关联 wms_entry_order.id',
|
||||
},
|
||||
entry_order_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '入库单号(冗余,方便查询)',
|
||||
},
|
||||
entry_item_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '入库明细ID',
|
||||
},
|
||||
receiving_detail_id: {
|
||||
type: INTEGER,
|
||||
allowNull: true,
|
||||
comment: '收货明细ID,绑定收货时使用',
|
||||
},
|
||||
status: {
|
||||
type: ENUM('pending', 'committed', 'released'),
|
||||
allowNull: true,
|
||||
comment: '绑定状态:pending=待提交 committed=已提交 released=已释放,非绑定模式为NULL',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '备注(如导入文件名、PDA操作备注等)',
|
||||
},
|
||||
space_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '存放库位ID,关联 wms_location_space.id',
|
||||
},
|
||||
operator_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '操作人ID',
|
||||
},
|
||||
operator_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '操作人名称',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '软删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_inbound_direct_log',
|
||||
comment: '非收货单途径入库直接记录表(导入/PDA入库)',
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_stock_id',
|
||||
fields: [ 'stock_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_inbound_type',
|
||||
fields: [ 'inbound_type' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_entry_order_id',
|
||||
fields: [ 'entry_order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_created_at',
|
||||
fields: [ 'created_at' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_entry_item_id',
|
||||
fields: [ 'entry_item_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_receiving_detail_id',
|
||||
fields: [ 'receiving_detail_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_status',
|
||||
fields: [ 'status' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_entry_receiving_binding',
|
||||
unique: true,
|
||||
fields: [ 'entry_item_id', 'receiving_detail_id', 'status' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 关联关系
|
||||
InboundDirectLog.associate = function() {
|
||||
const { InboundDirectLog, EntryItems, ReceivingDetail } = app.model;
|
||||
|
||||
// 关联入库明细
|
||||
InboundDirectLog.belongsTo(EntryItems, {
|
||||
foreignKey: 'entry_item_id',
|
||||
as: 'entryItem',
|
||||
});
|
||||
|
||||
// 关联收货明细
|
||||
InboundDirectLog.belongsTo(ReceivingDetail, {
|
||||
foreignKey: 'receiving_detail_id',
|
||||
as: 'receivingDetail',
|
||||
});
|
||||
};
|
||||
|
||||
return InboundDirectLog;
|
||||
};
|
||||
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