diff --git a/.github/agents/专家.agent.md b/.github/agents/专家.agent.md new file mode 100644 index 0000000..f45c97d --- /dev/null +++ b/.github/agents/专家.agent.md @@ -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: Claude Opus 4.6 +--- + +# 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 无法收敛或多轮失败场景,目标是以证据驱动方式完成根因定位与端到端闭环。 \ No newline at end of file diff --git a/.github/agents/发布.agent.md b/.github/agents/发布.agent.md new file mode 100644 index 0000000..7e1ff09 --- /dev/null +++ b/.github/agents/发布.agent.md @@ -0,0 +1,126 @@ +--- +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: GPT-5 mini (copilot) + +--- + +# 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 配置或远端敏感文件 + +## 推荐执行顺序 + +### 发布前 + +```powershell +npm run setup:hooks +npm run deploy:precheck +npm run deploy:verify +``` + +### 正式发布 + +```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 +# 启用仓库级 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 做 method 连通探针 +npm run deploy:gateway-probe -- releaseProbe.ping "{}" + +# 手动记录一次本地包版本快照 +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`”这一条约束。 \ No newline at end of file diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md new file mode 100644 index 0000000..f472027 --- /dev/null +++ b/.github/agents/开发.agent.md @@ -0,0 +1,122 @@ +--- +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 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,如果要修改的文件大部分缺失注释,必须先驳回到调度 agent 让其补齐拆解分析再修改,禁止直接改代码后再补注释的流程 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 controller 层解构出具体参数,再传给 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` + +## 推荐工作流 + +### 代码修改 / 修 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,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- \ No newline at end of file diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md new file mode 100644 index 0000000..ea2f2ec --- /dev/null +++ b/.github/agents/数据库.agent.md @@ -0,0 +1,96 @@ +--- +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 : GPT-5 mini (copilot) +--- + +# WMS 数据库代理(`wms-db-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 默认数据库脚本:`script/db-query.ps1` +- 默认 MySQL client:`wms` +- 可切换 client:`wms`、`ye4s` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-db-agent`: + +- 查数据库 / 查数据 / 查表 +- 编写、修改、解释 SQL +- 排查接口返回为空、数据异常、库表映射问题 +- 核对 `wms` / `ye4s` 库连接与路由 +- 解释字段含义、表结构、索引建议 + +## 工作规则 + +1. **所有数据库查询优先使用** `script/db-query.ps1` +2. **对非测试仓库数据默认只允许只读查询**:`SELECT` / `SHOW` / `DESC` / `EXPLAIN` +3. **禁止对非测试仓库执行** `UPDATE` / `DELETE` / `INSERT` **等写操作** +4. **若无法确认仓库是否为测试仓,默认按非测试仓处理并拒绝写操作** +5. 如用户已明确说明是测试仓且允许写操作: + - 必须先生成影响范围确认 SQL(`COUNT(*) + 同 WHERE 条件`) + - 明确告知风险 + - 获得用户确认后再执行 +6. **如果是为了支持新接口而补权限,只能新增 / 补齐权限记录本身**(如 `wms_permission`);**默认禁止直接修改角色授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定,除非用户已明确确认 +7. 做接口排障时,优先链路: + - 先定位 `app/model` / `service` / `controller` + - 再给 SQL + - 最后执行验证并输出根因 +8. 输出要求: + - 所有回复必须以 `[DB]` 开头 + - 优先给结论、关键字段和下一步建议 + +## 常用命令模板 + +### 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、端口、用户名密码、网络白名单 + +## 结论 + +数据库相关能力文档已统一收口到本 Agent;工作区其它通用文档只保留“数据库相关必须使用 `wms-db-agent`”这一条约束。 diff --git a/.github/agents/文档.agent.md b/.github/agents/文档.agent.md new file mode 100644 index 0000000..9cfebcd --- /dev/null +++ b/.github/agents/文档.agent.md @@ -0,0 +1,100 @@ +--- +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: GPT-5 mini (copilot) +--- + +# WMS 文档代理(`wms-doc-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要文档目录:`methods/`、`docs/` +- 常用文档文件:`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` / `docs/*.md`,**还必须追加一条变更记录到对应的 `methods/changes/.json` 数组** + - `methods/*.json` 仍是 SSOT,`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. 找到对应的 `methods/*.json` / `docs/*.md` +3. 以代码和测试结果为准更新文档 +4. 更新文档后同步追加对应的 `methods/changes/.json` 变更记录 +5. 校验 method 名称、参数、响应与代码一致 +6. 必要时验证 JSON 格式可正常解析 + +## 常用验证方式 + +### 校验 `methods/system.json` 格式 + +```powershell +node -e "JSON.parse(require('fs').readFileSync('methods/system.json','utf8')); console.log('system.json OK')" +``` + +### 核对 method 是否已登记 + +```powershell +Select-String -Path "methods/system.json" -Pattern "storage.receiving.bindDetailProduct" +``` + +## 建议提问方式 + +```text +请使用 wms-doc-agent 帮我: +1) 根据代码现状整理接口或业务文档 +2) 同步 methods/*.json / docs/*.md / README +3) 校验文档与实现一致 +``` + +## 输出要求 + +- 所有回复建议以 `[Doc]` 开头 +- 先给结论,再给修改文件、关键字段、验证结果 +- 若同步了 `methods/*.json`,明确说明 method 名称与变更点 +- 若接口有变更,需说明是否已同步写入 `methods/changes/*.json` + +## 结论 + +文档相关能力文档已统一收口到本 Agent;工具箱只保留“文档相关必须使用 `wms-doc-agent`”的规则入口。 \ No newline at end of file diff --git a/.github/agents/测试.agent.md b/.github/agents/测试.agent.md new file mode 100644 index 0000000..4fdcd52 --- /dev/null +++ b/.github/agents/测试.agent.md @@ -0,0 +1,84 @@ +--- +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: GPT-5.1 (copilot) +--- + +# WMS 测试代理(`wms-test-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要目录:`test/`、`app/`、`methods/` +- 适用于单元测试、集成测试、回归测试、接口验证与修复验证 + +## 测试环境固定参数 + +| 参数 | 值 | 说明 | +|------|----|------| +| 测试仓库 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 +3. **禁止 test-only 生产代码**:不要为测试给生产代码加仅供测试使用的方法或分支 +4. **mock 要克制且完整**:仅在理解依赖副作用后于最低必要层 mock,且结构必须与真实数据一致 +5. **改动后必须验证**:跑相关测试并明确报告 passing 数量、失败数与验证范围 +6. **接口验证以真实链路为准**:必要时结合 `methods/*.json`、controller/service 实现与返回结构共同校验 +7. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中,如有 ESLint 错误或警告,必须驳回到开发修改后再验证 + +## 常用命令示例 + +### 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 数量、失败数与是否已覆盖回归场景 + +## 结论 + +测试相关能力文档已统一收口到本 Agent;工具箱只保留“测试相关必须使用 `wms-test-agent`”的规则入口。 diff --git a/.github/agents/缓存.agent.md b/.github/agents/缓存.agent.md new file mode 100644 index 0000000..c43f289 --- /dev/null +++ b/.github/agents/缓存.agent.md @@ -0,0 +1,100 @@ +--- +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'] +--- + +# 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`”这一条约束。 diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md new file mode 100644 index 0000000..7c35ceb --- /dev/null +++ b/.github/agents/调度.agent.md @@ -0,0 +1,71 @@ +--- +name: wms-dispatcher-agent +description: "Use when the user asks about 任务委派、任务分派、调度、router、triage、多领域排障、不确定该找哪个 agent,或需要把问题分给 数据库/Redis/发布/开发/测试/文档 等模块。专用于 WMS 任务分诊与委派。" +argument-hint: "描述你的目标或问题,例如:帮我判断这是数据库、测试还是缓存问题并分派、这个线上异常该交给谁处理。" +tools: ['read', 'search', 'agent', 'todo'] +model: GPT-5.4 mini (copilot) +--- + +# WMS 调度代理(`wms-dispatcher-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. **跨域混合任务** → 先拆分,再按依赖顺序委派并汇总结果 + +## 工作流程 + +1. 先读懂用户目标与限制条件 +2. 判断问题归属:数据库 / Redis / 发布 / 开发 / 测试 / 文档 / 混合 +3. 如需求不清晰,只补问最少的关键问题 +4. 把子任务委派给最合适的专属 agent +5. 若专属 agent 无法收敛或多轮仍未解,升级委派 `wms-expert-agent` 兜底 +6. 汇总各子任务结果,给出最终结论与下一步建议 + +## 工作原则 + +- **只做分诊与委派,不绕过专属 agent 的安全约束** +- **凡涉及非测试仓库数据写操作(数据库 / Redis),默认视为禁止项**;只能给只读排查建议,除非用户已明确说明是测试仓且允许操作 +- **如无法确认是否测试仓,默认按非测试仓处理** +- 遇到数据库相关,必须遵守 `wms-db-agent` 的只读 / 风险确认流程 +- 遇到 Redis 相关,必须遵守 `wms-redis-agent` 的先读后改 / 回读确认流程 +- 遇到发布相关,必须遵守 `wms-deploy-agent` 的 `npm run` 固定入口与 SSH 安全红线 +- 遇到开发相关,必须遵守 `wms-dev-agent` 的“先定位、后修改、再验证”流程 +- 遇到测试相关,必须遵守 `wms-test-agent` 的“TDD 优先、测试真实行为、报告 passing 数量”流程 +- 遇到文档相关,必须遵守 `wms-doc-agent` 的“先核对代码与测试,再更新文档”流程 + +## 输出要求 + +- 所有回复建议以 `[Dispatch]` 开头 +- 先说明**将分派给谁**,再给简短原因 +- 如果是多领域问题,给出**拆分后的执行顺序** +- 最后输出汇总结论和下一步建议 + +## 建议提问方式 + +```text +请使用 wms-dispatcher-agent 帮我: +1) 判断这个问题属于数据库、Redis、发布、开发、测试还是文档问题 +2) 分派给正确的 agent +3) 汇总处理结果与下一步建议 +``` + +## 结论 + +`wms-dispatcher-agent` 用于 WMS 场景下的任务分诊与委派;当用户不确定该找哪个 agent,或问题跨多个领域时,应优先交给本 Agent。 \ No newline at end of file diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 755553e..b7d7dfd 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -1,15 +1,34 @@ # AI 工具箱(WMS) + ## 🤖 AI阅读优先级 -1. **必读**:第2节(数据库)、第4节(Redis)- 最常用 -2. **重要**:第3节(提问模板)、第6节(安全约束)、第14节(where规范) -3. **按需**:第10节(远程发布)、第15节(权限映射)、第16节(消息通知) -4. **红线**:10.4(SSH禁止读取)、6(SQL安全) +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配置文件位置 +| Agent名称 | 配置文件路径 | +|-----------|--------------| +| wms-db-agent | `.github/agents/数据库.agent.md` | +| wms-redis-agent | `.github/agents/缓存.agent.md` | +| wms-deploy-agent | `.github/agents/发布.agent.md` | +| wms-dev-agent | `.github/agents/开发.agent.md` | +| wms-test-agent | `.github/agents/测试.agent.md` | +| wms-doc-agent | `.github/agents/文档.agent.md` | +| wms-dispatcher-agent | `.github/agents/调度.agent.md` | + ## 快速响应规则 -- 用户要求查数据 → 直接执行 script/db-query.ps1 -- 用户要求改缓存 → 先用redis-cache.ps1读,再改 -- 用户要求发布 → 只提示命令,不读SSH配置 +- 用户要求查数据库/查数据/写 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. 适用范围 @@ -18,703 +37,225 @@ - 主要用途:本地调试、数据库取数、问题定位 - 默认环境:PowerShell + Node.js -## 2. 数据库调试脚本 +## 2. 数据库能力移交规则 -临时文件规则(强制): -- 所有临时产物统一生成到 `temp/` 目录。 -- `temp/` 目录不提交到 git。 +数据库相关能力文档已统一移交给 `wms-db-agent`。 -项目已提供数据库查询脚本:`script/db-query.ps1` +适用场景: +- 查数据库 / 查数据 / 查表 +- 编写或审查 SQL +- 排查接口与数据库数据不一致 +- 核对 `wms` / `ye4s` client 路由 +- 输出字段含义、异常数据判断、索引建议 -脚本能力: -- 自动读取 `config/config.local.js` 中的 `config.mysql.clients.` 配置 -- 支持通过 `-DbClient` 显式切换 mysql client(如 `wms`、`ye4s`),默认 `wms` -- 执行传入 SQL 并返回 JSON -- 可选表格输出,便于命令行快速查看 - -### 2.1 基本用法 - -```powershell -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT 1 AS ok" -``` - -### 2.2 常用示例 - -```powershell -# 查询最近 10 条账号 -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT * FROM account ORDER BY id DESC LIMIT 10" - -# 表格输出 -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id, name FROM store LIMIT 20" -AsTable - -# 指定 mysql client(默认是 wms) -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES" - -# 切换到 ye4s client -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES" - -# 快速确认当前连接到哪个库/账号 -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser" -powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SELECT DATABASE() AS db, USER() AS loginUser" -``` - -### 2.3 参数说明 - -- `-Query`:必填,SQL 语句 -- `-DbClient`:可选,MySQL 客户端名(例如 `wms`、`ye4s`),默认 `wms` -- `-ConfigPath`:可选,配置文件路径,默认 `.\config\config.local.js`(相对于项目根目录) -- `-AsTable`:可选,按表格输出结果 - -### 2.4 返回结果说明 - -默认输出 JSON,结构如下: - -```json -{ - "client": "wms", - "rowCount": 1, - "rows": [ - { - "ok": 1 - } - ] -} -``` - -### 2.5 区分 wms 与 ye4s(快速自检) - -- 步骤 1:不传 `-DbClient` 执行一次 `SELECT DATABASE() AS db, USER() AS loginUser` -- 步骤 2:传 `-DbClient ye4s` 再执行同一条 SQL -- 期望结果: - - 默认执行返回 `client = wms` 且 `db = wms` - - 指定 `ye4s` 返回 `client = ye4s` 且 `db = ye4s` - -说明:脚本会从 `config.mysql.clients.` 读取连接参数,返回体中的 `client` 字段可直接用于确认当前路由。 +执行要求(强制): +- **涉及数据库的任何问题,必须使用 `wms-db-agent`** +- 默认 agent 不再在本文件重复维护数据库命令细节 +- 具体命令、示例、输出格式、安全约束统一见:`.github/agents/数据库.agent.md` ## 3. AI 协助时建议使用的提问模板 -### 3.1 只读查询(推荐) +### 3.1 数据库类请求(强制走 Agent) ```text -请在项目根目录执行 script/db-query.ps1,查询 SQL: -SELECT * FROM account LIMIT 20; -并把结果按表格给我,同时解释关键字段含义。 +请使用 wms-db-agent 帮我: +1) 定位相关 controller / service / model +2) 生成并执行只读 SQL +3) 输出结果、字段解释和结论 ``` -### 3.2 先分析再查询 +### 3.2 Redis 类请求(强制走 Agent) ```text -请先阅读 app/model 下与 store 相关的模型,再使用 script/db-query.ps1 查询最近 50 条门店数据, -最后输出:1) 字段映射说明 2) 异常数据判断规则 3) 建议补充索引。 +请使用 wms-redis-agent 帮我: +1) 找到相关 key 或 pattern +2) 读取当前值、TTL、exists 状态 +3) 如需修改,先展示变更前后对比并回读确认 ``` -### 3.3 联合排障 +### 3.3 开发类请求(强制走 Dev Agent) ```text -请帮我排查某接口返回为空: -1) 找到对应 controller 和 service -2) 给出需要执行的 SQL -3) 使用 script/db-query.ps1 验证每一步 -4) 输出最终根因和修复建议 +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动方案 +3) 给出验证结果与后续开发建议 ``` -## 4. Redis 缓存调试脚本 - -项目已提供 Redis 调试脚本:`script/redis-cache.ps1` - -脚本能力: -- 自动读取 `config/config.local.js`(可切换 `-ConfigPath`)中的 `config.redis.clients.` 配置连接 Redis -- 支持缓存读取与修改:`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr` -- 可选表格输出(`-AsTable`) - -### 4.1 基本用法 - -```powershell -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" -``` - -### 4.2 常用示例 - -```powershell -# 列出 key(使用 SCAN,不直接 KEYS 阻塞) -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable - -# 读取/写入字符串缓存 -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system" -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 del -RedisClient cache -Key "system" - -# Hash 结构读写 -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" - -# 自增/自减计数器 -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action incr -RedisClient cache -Key "counter:order" -powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action decr -RedisClient cache -Key "counter:order" -Value 2 -``` - -### 4.3 参数说明 - -- `-Action`:必填,操作类型(`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr`) -- `-RedisClient`:可选,Redis 客户端名,默认 `cache` -- `-Key`:按操作需要传入 -- `-Value`:`set/hset/incr/decr` 等操作使用 -- `-Field`:`hget/hset/hdel` 必填 -- `-ExpireSeconds`:`set`(可选)和 `expire`(必填) -- `-Pattern`:`keys` 操作匹配模式,默认 `*` -- `-ConfigPath`:可选,默认 `.\config\config.local.js` -- `-AsTable`:可选,表格输出 - -### 4.4 AI 调用模板(缓存读改) +### 3.4 测试类请求(强制走 Test Agent) ```text -请在项目根目录执行 script/redis-cache.ps1: -1) 用 Action=keys, Pattern="user:*" 列出目标缓存键 -2) 读取 key=xxx 的当前值(Action=get) -3) 按我提供的新值执行 Action=set 并设置过期时间 600 秒 -4) 回读一次确认变更生效,并输出变更前后对比 +请使用 wms-test-agent 帮我: +1) 先复现问题并补一个失败用例 +2) 按 TDD 跑回归或接口验证 +3) 输出 passing 数量、失败数和修复验证结论 ``` +### 3.5 文档类请求(强制走 Doc Agent) + +```text +请使用 wms-doc-agent 帮我: +1) 根据代码现状整理接口或业务文档 +2) 同步 methods/*.json / docs/*.md / README +3) 校验文档与实现一致 +``` + +### 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. 常见问题 -- 报错 `Cannot find module 'mysql2/promise'` - - 先执行 `npm install`,确认依赖完整 +- 数据库相关报错、SQL 问题、连接路由问题 + - 统一转给 `wms-db-agent` 处理 -- 报错 `Cannot find module 'ioredis'` - - 先执行 `npm install`,确认依赖完整 +- Redis 相关报错、key 排查、TTL 问题、缓存变更 + - 统一转给 `wms-redis-agent` 处理 -- 报错 `MySQL client "xxx" not found in config.mysql.clients` - - 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client +- 发布相关报错、预检失败、回退、版本查询、冒烟验证 + - 统一转给 `wms-deploy-agent` 处理 -- SQL 语法报错且定位到 `current_user` - - 避免使用 `current_user` 作为别名,建议改成 `loginUser` 等非保留字名称 +- 开发相关问题:代码修改、method 路由、权限联动 + - 统一转给 `wms-dev-agent` 处理 -- 报错 `Redis client "xxx" not found in config.redis.clients` - - 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client +- 测试相关问题:写单元测试、补回归、接口验证、TDD、验证修复、审查 mock / 断言 + - 统一转给 `wms-test-agent` 处理 -- 报错连接失败(超时/拒绝访问) - - 检查数据库 IP、端口、用户名密码、网络白名单 +- 文档相关问题:API 文档、README、`methods/system.json`、`docs/*.md`、使用说明 + - 统一转给 `wms-doc-agent` 处理 -- 报错 Redis 连接失败(超时/认证失败) - - 检查 Redis host/port/password/db 与网络连通性 +- 不确定该用哪个 agent,或问题横跨数据库 / Redis / 发布 / 代码 / 测试 / 文档 + - 统一转给 `wms-dispatcher-agent` 处理 - PowerShell 执行策略限制 - 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效) ## 6. 安全约束 -- 默认只执行 SELECT/SHOW 等只读 SQL -- 执行 UPDATE/DELETE 前必须先让 AI 生成影响范围确认 SQL(COUNT + WHERE 条件) +- **全局安全红线(适用于所有 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`,并坚持“先核对代码与测试,再更新文档;禁止写入敏感配置”的流程 - 涉及生产数据时,优先在测试环境验证 -- Redis 写操作(`set/del/hset/hdel/incr/decr/expire`)前,先执行一次读取并确认影响 key 范围 -## 7. 接口入口与 Method 指向 - -- 入口风格: - - `/qimen`:奇门开发接口(POST) - - `/system`:Web 端与 PDA 端统一接口(POST) - -- 外部请求示例: - - `http://127.0.0.1:6060/system?method=print.getComputerPrinter&v=1.0×tamp=1773386721` - -- Method 指向说明文档: - - 见 `AI_METHOD_ROUTING.md` - - 文档记录了 method 到 `app/service/systemMethods`、`app/service/qimenMethods` 的映射规则与示例。 - -## 8. methods 目录地图 - -目录:`methods/` - -- `methods/system.json` - - 作用:维护 `/system`(及 system 风格 method)的接口说明。 - - 覆盖内容:公共请求头、method 分组、params、response、errors。 - -- `methods/qimen.json` - - 作用:维护 `/qimen` 接口说明。 - - 覆盖内容:奇门 method、请求格式、响应格式、错误码。 - -建议将 `methods/*.json` 视为“接口文档单一事实来源(SSOT)”。 - -## 9. 接口变更联动工作流(强制) - -当出现以下任一变更时,必须同步更新 `methods` 目录下对应 JSON: - -1. 新增接口(新增 method) -2. 修改接口入参(新增/删除/重命名/必填变化) -3. 修改公共请求头(如 `platform`、`project`、`Authorization`) -4. 修改响应结构或错误码 - -执行步骤: - -1. 先改代码(controller/service/model) -2. 更新对应文档文件: - - system 入口改 `methods/system.json` - - qimen 入口改 `methods/qimen.json` -3. 若 system 入参有变化,执行参数结构化脚本刷新: - -```powershell -node .\script\tmp-struct-system-params.cjs -``` - -4. 人工补充自动脚本无法推断的信息: - - `description` - - `response` - - `errors` - - 特殊枚举值与业务约束 -5. 提交前自检: - - method 名称与代码一致 - - params 的 `name/type/required/source` 完整 - - 公共头部声明与实际鉴权逻辑一致 - -## 10. 远程发布与回退工具 - -发布配置文件: - -- 模板:`config/deploy.config.example.cjs` -- 本地真实配置:`config/deploy.config.local.cjs` - -说明: - -- 生产目录固定为 `/www/wwwroot/qimen` -- `config/deploy.config.local.cjs` 已加入 git ignore,避免 SSH 配置误提交 -- 发布前会自动备份远端当前目录到 `/www/wwwroot/qimen/.deploy/backups/` -- 回退默认使用最近一次发布前备份 -- 发布包按 Egg.js 最小运行集自动裁剪(默认 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`) -- 发布与回退均保留远端 `config/`,不做覆盖 -- 发布与回退的停服务逻辑仅匹配当前 `deployRoot` 对应的 Egg 进程,不再用全局 `egg-scripts stop` 扫整机 - -### 10.1 固定命令入口(仅 npm script) - -执行要求: - -- 远程发布与回退只允许通过 `npm run` 执行。 -- 禁止直接运行 `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...`。 -- `npm stop` 已改为仅停止当前目录对应的 Egg 进程,不再直接调用全局 `egg-scripts stop`。 - -标准格式: - -```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 做 method 连通探针 -npm run deploy:gateway-probe -- releaseProbe.ping "{}" - -# 手动记录一次本地包版本快照 -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 -``` - -### 10.2 SSH 配置字段 - -- `host`:生产服务器 IP 或域名 -- `port`:SSH 端口,默认 `22` -- `username`:SSH 登录用户 -- `privateKeyPath`:本机私钥路径 -- `deployRoot`:固定为 `/www/wwwroot/qimen` -- `sharedDirs`:发布时保留目录,默认 `logs/run/temp` -- `postDeployCommands`:发布后执行命令;发布链路会强制确保包含 `npm install --production`,并自动剥离其中的通用 stop 命令,改为按当前部署目录定点停进程 - -最小发布相关可选字段: - -- `deployIncludePaths`:最小发布白名单路径(不填则使用默认最小集) -- `deployExcludePaths`:发布排除路径(默认包含 `config/**`) -- `preserveDirs`:远端覆盖时额外保留目录(默认包含 `config`) - -### 10.5 线上版本号规则与查询 - -- 版本号自动生成时机:每次执行 `npm run deploy:prod`。 -- 版本号格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。 -- 远端保存位置: - - 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json` - - 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl` -- 查询命令(固定 npm script): - - 当前版本:`npm run deploy:version` - - 历史版本:`npm run deploy:version:history` - -### 10.6 本地版本管理目录(回退辅助) - -- 目录:`versioning/` -- 记录目标:每次更新的包版本号、提交号、分支、时间。 -- 自动记录:每次 `npm run deploy:prod` 成功后自动写入本地记录。 -- 手动记录:`npm run version:record` -- 本地历史查询:`npm run version:history` -- 文件: - - `versioning/package-version-current.json` - - `versioning/package-version-history.jsonl` -- git 规则:`versioning/` 的记录文件默认不提交,仅保留目录占位。 - -### 10.3 安全约束 - -- pre-commit 会阻止以下内容进入 git: - - `config/config.local.js` - - `config/deploy.config.local.cjs` - - `database/config.json` - - `temp/`、`logs/`、`run/` - - `.env*`、`.pem`、`.key` -- 真实 SSH 信息只写入本地配置文件,不写入 README、脚本或示例文件 -- 在补齐 SSH 配置前,不执行发布/回退测试 - -### 10.4 AI 安全红线(强制) - -- 明文规则:AI 禁止读取 SSH 本地配置文件 `config/deploy.config.local.cjs`。 -- AI 禁止通过任何方式展示、提取、复述该文件中的 `host`、`username`、`privateKeyPath` 等敏感内容。 -- AI 禁止把 SSH 配置写入文档、日志、日报、提交信息或任意可提交文件。 -- 如需发布/回退协助,AI 仅可提示用户“自行填写或核对该文件”,不可主动读取文件内容。 - -执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。 - -## 11. App 能力地图(优先定位) - -能力入口文件: - -- `app.js` -- `app/extend/application.js` - -### 11.1 启动与初始化能力(app.js) - -- 设置应用根路径:`global.APP_ROOT`、`app.appRoot` -- 启动前初始化动态工厂: - - `OrderDeliveryFactory` - - `OrderItemsFactory` -- 启动时能力自检: - - `app.setCacheAsync` / `app.getCacheAsync` - - `app.Message` -- 全局日期格式化扩展:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` - -### 11.2 Application 扩展能力(app/extend/application.js) - -- 业务字典访问: - - `businessDict` - - `getBusinessTypeName(code)` - - `getOperationCodeName(code)` - - `getPlatformName(code)` - - `getExternalLogTypeName(type)` -- 外部 SOAP 调用: - - `wsdl(methodName, args)` -- Redis 缓存(cache client): - - `setCacheAsync(cacheKey, data, expireSeconds = 300)` - - `getCacheAsync(cacheKey)` -- Message 扩展: - - `Message` getter(返回 `MessageClass`) - -### 11.3 AI 调试优先顺序 - -- 遇到“方法不存在/映射异常”优先检查 `app/extend/application.js` 是否包含对应能力。 -- 遇到“动态分表模型不可用”优先检查 `app.js` 的工厂初始化是否执行成功。 -- 遇到“缓存读写异常”优先检查 Redis client `cache` 配置及 `setCacheAsync/getCacheAsync` 调用链。 - - -## 12. Web 用户信息与切换角色测试(已验证) - -目标: -- 使用 `/system` 入口验证 Web 端用户信息获取与角色切换链路。 -- 固定请求头:`platform=web`、`project=all`。 -- 将接口返回暂存到 `test/.runtime/` 便于回放与比对。 - -测试文件: -- `test/app/controller/system.user.info.web.test.js` - - 调用 `user.info` - - 断言 `status=200`、`flag=success`、`code=200` - - 断言返回 `platform_code=web` - - 落盘:`test/.runtime/system_user_info_web_all.json` - -- `test/app/controller/system.user.changeRole.test.js` - - 先调用 `user.info` 读取当前角色与可切换角色 - - 调用 `user.changeRole`(`roleId` 取可用候选角色) - - 使用返回的新 token 再调 `user.info` 验证 `employees_id` 已切换 - - 落盘:`test/.runtime/system_user_change_role_web_all.json` - - 末尾自动切回原角色,降低对其他测试影响 - -一键执行: - -```powershell -npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/controller/system.user.changeRole.test.js -``` - -本地验证结果: -- 2 passing - -建议排查顺序(当返回菜单/权限为空时): -1. 先查 `user.info` 返回中的 `employees_id`、`store_id`、`platform_code` -2. 确认请求头是否为 `platform=web`、`project=all` -3. 若仍为空,检查账号角色授权与当前激活角色是否存在 - -## 13. setting.account 接口说明(system) - -适用入口:`POST /system?method=setting.account.xxx` - -### 13.1 setting.account.list - -用途:查询当前主体下工号列表(默认只返回启用工号)。 - -入参(body): -- `status`(number,可选):状态筛选,默认 `1` -- `includeDisabled`(boolean,可选):`true` 时包含停用工号 - -返回(`data[]` 关键字段): -- `employee_id`:工号 ID -- `account_id`:账号 ID -- `store_id`:主体 ID -- `real_name`:工号姓名 -- `status`:工号状态(`1` 启用 / `0` 停用) -- `username` / `phone` / `email`:账号基础信息 -- `avatar_file_id` / `avatar_url`:头像信息 - -### 13.2 setting.account.add - -用途:新增工号;手机号存在则复用账号,不存在则创建账号并绑定工号。 - -入参(body): -- `phone`(string,必填):11 位手机号 -- `real_name`(string,必填):工号姓名 -- `role_id`(number,可选):不传时继承当前操作人工号角色 -- `username`(string,可选):仅新建账号时生效 -- `password`(string,可选):仅新建账号时生效,默认 `111111` -- `email`(string,可选):仅新建账号时生效 - -返回(`data` 关键字段): -- `employee_id` / `account_id` / `role_id` -- `is_new_account`:是否本次新建账号 -- `phone` / `username` - -错误码: -- `400`:参数错误、手机号格式错误、保留名称限制 -- `409`:账号禁用、重复绑定、用户名冲突 - -### 13.3 setting.account.delete - -用途:停用工号绑定,不删除底层账号。 - -入参(body): -- `employee_id`(number,必填) - -返回(`data`): -- `employee_id` / `account_id` -- `status`:固定 `deleted` -- `already_deleted`(可选):原本已是停用状态 - -### 13.4 setting.account.update - -用途:更新工号姓名和/或头像引用。 - -入参(body): -- `employee_id`(number,必填) -- `real_name`(string,可选) -- `file_id`(number,可选):头像文件 ID - -约束:`real_name` 与 `file_id` 至少传一个。 - -返回(`data`): -- 更新后的工号完整信息(同 list 列表项结构) - -### 13.5 代码分层约定 - -- 对外 method 包装层:`app/service/systemMethods/setting/account.js` -- 业务实现层:`app/service/systems/setting/account.js` -- 约定:非暴露辅助函数与业务逻辑统一下沉到 `systems`,`systemMethods` 只保留出口包装。 - -## 14. where 参数统一规范(强制) - -适用范围:所有包含 `where` 筛选条件的 `/system` 接口。 - -### 14.1 标准结构 - -`where` 必须使用统一条件对象格式: - -```json -{ - "where": { - "item_code": { "operator": "like", "value": "SKU" }, - "status": { "operator": "eq", "value": "created" }, - "quantity": { "operator": "ge", "type": "number", "value": "10" }, - "create_at": { "operator": "between", "type": "date", "value": ["2026-03-01", "2026-03-31"] }, - "quickWhere": { "operator": "like", "type": "text", "value": "关键字" } - } -} -``` - -### 14.2 统一处理入口 - -- `where` 统一在 `app/service/main.js` 中处理:`prepareWhereContext(data, options)`。 -- 处理后上下文约定: - - `ctx.where`:标准化后的 where 条件对象(含 `operator/value/type`) - - `ctx.whereValue`:仅提取 value 的兼容对象(给旧逻辑渐进兼容) - - `ctx.whereParsed`:基于 `app/lib/query_condition_parser.js` 解析后的动态条件结构 - -### 14.3 实施规则 - -- 所有 method 层(`systemMethods`)收到 `where` 后,必须先调用 `prepareWhereContext`。 -- 所有 systems 层查询逻辑优先读取 `ctx.where` / `ctx.whereParsed`,不得重复定义另一套 where 规则。 -- 历史简写结构(如 `where: { status: 1 }`)允许输入,但会在 main 层自动标准化为条件对象。 - -### 14.4 回归覆盖建议 - -- 至少验证:空 where、eq、like、in、between、quickWhere。 -- 对日志中高频接口优先回归: - - `print.getList` - - `storage.entry.list` - - `stock.warehouse.list` - -## 15. system API 权限映射规则(wms_permission) - -适用范围:`/system` 入口,权限类型为 `type=api`。 - -### 15.1 映射规则 - -- `wms_permission.path` 作为 system method 的权限标识(例如:`setting.account.list`)。 -- 同步来源以 `methods/system.json` 为准:`isNeedAuth=true` 的 method 必须存在对应 `wms_permission(type=api,path=method)`。 -- 角色权限不再以 `wms_role_permission` 作为主存储,统一写入 `wms_role.permissions`。 -- `wms_role.permissions` 支持两种值: - - JSON 数组:如 `[1,2,3]` - - `"*"`:表示拥有所有权限 -- 新增 API 权限后,`role_id=2` 的授权应同步更新其 `permissions` 字段;若该字段为 `"*"` 则无需额外追加。 - -### 15.2 外部脚本(批量补齐) - -固定命令: - -```powershell -# 预览差异(不写库) -npm run permission:sync:system-api -- --dry-run - -# 执行补齐(写库) -npm run permission:sync:system-api -``` - -可选参数: - -- `--role-id=2`:绑定角色 ID(默认 `2`) -- `--db-client=wms`:数据库客户端名(默认 `wms`) -- `--config-path=./config/config.local.js`:配置文件路径 -- `--method-doc=./methods/system.json`:method 文档路径 - -### 15.3 运行时兜底(仅 debug) - -- 入口:`app/service/main.js` 的 `checkApiPermission`。 -- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动: - 1. 参考现有 `type=api` 权限行构建缺失权限行; - 2. 更新 `wms_role(id=2).permissions`,将新权限 ID 追加到 JSON 数组;若该字段为 `"*"` 则保持不变。 -- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。 - - ## 16 消息推送配置规则 - -- `wms_store.subject_config` 用于保存主体级通知配置。 -- 当前默认初始化字段:`max_notice_webhook_count = 5`。 -- 该字段表示“当前主体最多允许绑定的消息推送接口数量”。 -- 合法范围:`0 ~ 5` 的整数。 -- 创建或更新主体时,如携带 `subject_config.max_notice_webhook_count`,必须通过合法性校验;超出范围或类型错误视为非法。 -- WebHook 分发侧也必须遵守该上限,超过上限的回调接口不应继续发送。 - -## 16.1 统一 WebHook 推送能力(notice) - -- 能力总览文档:`docs/notification-webhook-capability.md` -- 事件 API 文档:`docs/notification-event-api.md` -- 统一入口:`ctx.service.systems.notice.send(options)` -- 代码位置:`app/service/systems/notice/index.js` -- 固定发送方式:`POST + application/json` -- `hook_type` 支持: - - `customize`:当前默认统一推送流程,按标准 JSON 透传 - - `wecom`:企业微信 WebHook 直发,自动转为企微机器人消息体 -- 必传参数:`warehouseId` -- 可空参数:`storeId / ownerId` -- 货主信息补充:若传 `storeId` / `ownerId`,会优先查缓存键 `warehouse:xxxstore:xxx:info`(TTL = `600`),未命中再查: - - `wms_store.business_license` - - `wms_store_warehouse.store_remask` -- `events` 支持以下订阅写法: - - `all` / `*`:接收全部已注册事件 - - `receiving_completed`:当前唯一已注册的业务事件(收货完成) -- 事件命名规则:仅允许小写字母、数字、下划线,且首字符不能为数字;**禁止使用 `.`** -- 推送事件注册:需先在 `app/model/notification_webhook.js` 中注册,未注册事件不允许直接发送 -- 传参伪代码: - -```js -await ctx.service.systems.notice.send({ - warehouseId: 100000, - storeId: 200000, // 可选,也可传 ownerId - businessName: 'receiving', - event: 'receiving_completed', - messageType: 'text', // text / image / file - title: '收货单已完成', - content: '收货单 RCV202604050001 已完成', - // image / file 时必传 - url: 'https://cdn.example.com/report.xlsx', - fileName: '收货完成_RCV202604050001.xlsx', - mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', - businessId: 12345, - subject: { - id: 100000, - type: 'warehouse', - name: '广州仓', - }, - sender: { - id: 10001, - name: '张三', - }, - metadata: { - receivingId: 12345, - receivingNumber: 'RCV202604050001', - }, -}); -``` -- WebHook 命中规则: - 1. 先查仓库 `warehouseId` 绑定的接口 - 2. 若 `storeId / ownerId` 非空,再查货主绑定的接口并一并发送 - 3. 最终按 `subject_config.max_notice_webhook_count` 限制最大推送数量 -- 推送事件底线: - 1. 业务 service 中只负责调用发送入口,不需要各自重复写重试和异常兜底 - 2. 统一入口会处理失败重试与异常处理:按 `3秒 -> 6秒 -> 12秒` 阶梯重试共 3 次 - 3. 若最终仍失败,写入 `wms_notification_send_log` 供后续排查与补偿 -### 16.2 WebHook 可信结论 - -- 返回值判定约定: - - 返回 `1` = **成功** - - 返回 `0` = **失败** -- 可信结论: - - **地址为外部配置,需要检查返回结果** - - **发送数据只使用POST 方式** - - 若 `notice.send()` 的实际推送触发远端 无法解析的文本视为推送失败 +## 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 文档为准,不得凭空编写 +- system 参数变化可执行:`node .\script\tmp-struct-system-params.cjs` +- 具体工作流统一见:`.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 分发时都必须遵守该上限 diff --git a/app.js b/app.js index 353440d..a96fa2b 100644 --- a/app.js +++ b/app.js @@ -5,7 +5,7 @@ const path = require('path'); module.exports = app => { // 设置全局应用根目录 global.APP_ROOT = path.resolve(__dirname, './'); - app.appRoot = APP_ROOT; + app.appRoot = global.APP_ROOT; app.logger.info('✅ Application 扩展能力已加载'); // 初始化工厂 app.beforeStart(async () => { @@ -35,21 +35,4 @@ module.exports = app => { 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); - }; }; diff --git a/app/controller/docs.js b/app/controller/docs.js index db09e9f..d6425ea 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -24,6 +24,18 @@ function slugify(value) { .replace(/(^-|-$)/g, ''); } +function isValidDocName(docName) { + return /^[a-zA-Z0-9_-]+$/.test(docName || ''); +} + +function getDocFilePath(app, docName) { + return path.join(app.baseDir, 'methods', `${docName}.json`); +} + +function getDocChangesFilePath(app, docName) { + return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`); +} + function normalizeGroups(docData) { if (docData && docData.methods && Array.isArray(docData.methods.groups)) { return docData.methods.groups.map(group => ({ @@ -194,6 +206,8 @@ function renderHtmlPage({ const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0); const globalHeaders = toArray(docData.headers); const globalHeadersControls = renderGlobalHeadersControls(globalHeaders); + const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`; + const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`; const navHtml = docs.map(name => { const activeClass = name === docName ? 'active' : ''; return `${escapeHtml(name)}`; @@ -292,7 +306,8 @@ function renderHtmlPage({ border-radius: 8px; font-size: 13px; } - .global-auth button { + .global-auth button, + .doc-tools button { border: 1px solid #9fc2eb; background: #fff; color: #174c94; @@ -300,6 +315,20 @@ function renderHtmlPage({ padding: 8px 12px; cursor: pointer; } + .doc-tools { + margin-top: 14px; + border: 1px solid #d7e4f7; + background: #fcfdff; + border-radius: 10px; + padding: 12px; + } + .doc-tools h3 { margin: 0 0 8px; font-size: 15px; } + .doc-tools-actions { + display: flex; + gap: 8px; + flex-wrap: wrap; + margin-bottom: 8px; + } .global-headers-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); @@ -544,7 +573,8 @@ function renderHtmlPage({

全局 Authorization

@@ -557,6 +587,16 @@ function renderHtmlPage({ ${globalHeadersControls}

来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。

+
+

文档资源

+
+ 打开变更记录 + 打开原文 JSON + + +
+
点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。
+
@@ -587,6 +627,11 @@ function renderHtmlPage({ var searchStats = document.getElementById('searchStats'); var expandAllBtn = document.getElementById('expandAllBtn'); var collapseAllBtn = document.getElementById('collapseAllBtn'); + var previewChangesBtn = document.getElementById('previewChangesBtn'); + var previewRawBtn = document.getElementById('previewRawBtn'); + var resourcePreview = document.getElementById('docResourcePreview'); + var changesUrl = ${JSON.stringify(changesUrl)}; + var rawUrl = ${JSON.stringify(rawUrl)}; function nowTimestamp() { return Math.floor(Date.now() / 1000); @@ -600,6 +645,25 @@ function renderHtmlPage({ } } + async function previewDocResource(url, title) { + if (resourcePreview) { + resourcePreview.textContent = title + ' 加载中...'; + } + + try { + var response = await fetch(url); + var text = await response.text(); + var pretty = formatPretty(text); + if (resourcePreview) { + resourcePreview.textContent = title + ' (HTTP ' + response.status + ')' + pretty; + } + } catch (error) { + if (resourcePreview) { + resourcePreview.textContent = title + ' 加载失败: ' + error.message; + } + } + } + function buildDefaultQuery(card) { var moduleName = card.getAttribute('data-module') || ''; var methodName = card.getAttribute('data-method') || ''; @@ -774,6 +838,18 @@ function renderHtmlPage({ }); } + if (previewChangesBtn) { + previewChangesBtn.addEventListener('click', function() { + previewDocResource(changesUrl, '变更记录'); + }); + } + + if (previewRawBtn) { + previewRawBtn.addEventListener('click', function() { + previewDocResource(rawUrl, '原文 JSON'); + }); + } + document.addEventListener('click', async function(event) { var btn = event.target.closest('.send-btn'); if (!btn) return; @@ -890,13 +966,13 @@ class DocsController extends Controller { const { ctx } = this; const docName = ctx.params.docName; - if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) { + if (!isValidDocName(docName)) { ctx.status = 400; ctx.body = { code: 400, message: '无效文档名' }; return; } - const filePath = path.join(this.app.baseDir, 'methods', `${docName}.json`); + const filePath = getDocFilePath(this.app, docName); try { const content = await fs.readFile(filePath, 'utf8'); @@ -911,6 +987,38 @@ class DocsController extends Controller { } } + async changes() { + const { ctx } = this; + const docName = ctx.params.docName; + + if (!isValidDocName(docName)) { + ctx.status = 400; + ctx.body = { code: 400, message: '无效文档名' }; + return; + } + + const filePath = getDocChangesFilePath(this.app, docName); + + try { + const content = await fs.readFile(filePath, 'utf8'); + ctx.type = 'application/json; charset=utf-8'; + ctx.body = toArray(JSON.parse(content)); + } catch (error) { + if (error.code === 'ENOENT') { + ctx.type = 'application/json; charset=utf-8'; + ctx.body = []; + return; + } + + ctx.status = 500; + ctx.body = { + code: 500, + message: `读取变更记录失败: ${docName}`, + error: error.message, + }; + } + } + async getDocNames() { const docsDir = path.join(this.app.baseDir, 'methods'); const entries = await fs.readdir(docsDir, { withFileTypes: true }); @@ -924,13 +1032,13 @@ class DocsController extends Controller { async renderDoc(docName) { const { ctx, app } = this; - if (!/^[a-zA-Z0-9_-]+$/.test(docName || '')) { + if (!isValidDocName(docName)) { ctx.status = 400; ctx.body = { code: 400, message: '无效文档名' }; return; } - const filePath = path.join(app.baseDir, 'methods', `${docName}.json`); + const filePath = getDocFilePath(app, docName); try { const [ content, docs ] = await Promise.all([ diff --git a/app/controller/home.js b/app/controller/home.js index 021bbee..b33945b 100644 --- a/app/controller/home.js +++ b/app/controller/home.js @@ -96,7 +96,6 @@ class HomeController extends Controller { const xmlArray = await service.qimen.parseXmlToArray(xmlData); xmlArray.app_key = appkey; let warehouseCode = xmlArray.request.warehouseCode || ''; - const ownerCode = customerId; await service.qimen.saveQimenLogBody(xmlData); const erpName = await service.qimen.getErpName(appkey); @@ -110,7 +109,9 @@ class HomeController extends Controller { warehouseCode = xmlArray.request?.entryOrder?.warehouseCode || xmlArray.request?.deliveryOrder?.warehouseCode || ''; - } catch (e) { } + } catch (e) { + throw new Error('XML数据格式错误,无法提取warehouseCode'); + } } if (warehouseCode && customerId) { // 验证接口是否存在且启用 @@ -119,21 +120,19 @@ class HomeController extends Controller { const errorMsg = `奇门${erpName}客户编码${customerId}仓库编码${warehouseCode}未绑定到你的货主或未启用,请联系仓库绑定`; const response = this.errorResponse(errorMsg, 'xml'); await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; } - if (api_info.contract_auth_status != 2) { + if (api_info.contract_auth_status !== 2) { const errorMsg = `货主与仓库签约状态异常,请到WMS核实签约状态${api_info.contract_auth_status}`; const response = this.errorResponse(errorMsg, 'xml'); await service.qimen.saveQimenLogResult(response); - ctx.body = response; ctx.type = 'application/xml'; return; } - if (api_info.warehouse_status == 0) { + if (api_info.warehouse_status === 0) { const errorMsg = '仓库状态异常,请联系仓库核实WMS状态'; const response = this.errorResponse(errorMsg, 'xml'); await service.qimen.saveQimenLogResult(response); @@ -403,12 +402,6 @@ class HomeController extends Controller { ctx.body = response; ctx.type = 'application/json'; } - } - async store() { - - } - async warehouse() { - } async system() { const { diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 38e3fab..07837bf 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -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: '货主管理' }, }, /** @@ -103,6 +105,31 @@ 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: '修改收货明细', + + // 货主管理 + STORE_CREATE: '创建货主', + STORE_CREATE_WAREHOUSE: '创建仓库', + STORE_SIGN: '签约货主', + STORE_RENAME: '修改签约备注', + STORE_UNBIND: '解绑签约', + STORE_SAVE_POLICY_CONFIG: '保存签约策略配置', + STORE_SAVE_API_CONFIG: '保存接口配置', + STORE_DELETE_API_CONFIG: '删除接口配置', + STORE_ADJUST_PRINT_QUANTITY: '调整面单余额', }, /** @@ -161,7 +188,7 @@ module.exports = { /** * 获取指定业务类型的操作编码 - * @param businessType + * @param {string} businessType 业务类型 */ getOperationCodesByBusinessType(businessType) { const prefix = businessType.toUpperCase() + '_'; @@ -178,8 +205,8 @@ module.exports = { /** * 验证操作编码是否属于指定业务类型 - * @param code - * @param businessType + * @param {string} code 操作编码 + * @param {string} businessType 业务类型 */ validateOperationCode(code, businessType) { if (!businessType) return true; diff --git a/app/extend/application.js b/app/extend/application.js index 9f2574f..e3c55da 100644 --- a/app/extend/application.js +++ b/app/extend/application.js @@ -1,11 +1,5 @@ -class MessageClass { - async action() { - - } -} const soap = require('soap'); const businessDict = require('../dict/businessDict'); -const MESSAGE_CLASS = Symbol('Application#Message'); module.exports = { get businessDict() { return businessDict; @@ -28,6 +22,23 @@ module.exports = { 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'; @@ -75,11 +86,4 @@ module.exports = { return null; } }, - get Message() { - if (!this[MESSAGE_CLASS]) { - // 返回类本身,不是实例 - this[MESSAGE_CLASS] = MessageClass; - } - return this[MESSAGE_CLASS]; - }, }; diff --git a/app/lib/stop_current_egg.js b/app/lib/stop_current_egg.js index 64894d8..34f4216 100644 --- a/app/lib/stop_current_egg.js +++ b/app/lib/stop_current_egg.js @@ -121,7 +121,6 @@ function killPids(pids, signal) { async function main() { const processList = listNodeProcesses().filter(matchesCurrentApp); const masterPids = processList.filter(item => isMasterProcess(item.cmd)).map(item => item.pid); - const workerPids = processList.filter(item => isWorkerProcess(item.cmd)).map(item => item.pid); if (masterPids.length > 0) { console.log(`stopping current egg masters: ${masterPids.join(', ')}`); diff --git a/app/model/account.js b/app/model/account.js index 74846d6..eec7981 100644 --- a/app/model/account.js +++ b/app/model/account.js @@ -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: { @@ -131,7 +131,7 @@ module.exports = app => { }); // 关联关系 - Account.associate = function(models) { + Account.associate = function() { const { AccountStoreEmployee, AccountPlatformActive } = app.model; Account.hasMany(AccountStoreEmployee, { foreignKey: 'account_id', diff --git a/app/model/account_platform_active.js b/app/model/account_platform_active.js index c5b72e9..9142143 100644 --- a/app/model/account_platform_active.js +++ b/app/model/account_platform_active.js @@ -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', diff --git a/app/model/account_store_employee.js b/app/model/account_store_employee.js index 60cf702..5cfe23e 100644 --- a/app/model/account_store_employee.js +++ b/app/model/account_store_employee.js @@ -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', diff --git a/app/model/api_app.js b/app/model/api_app.js index d0540e3..7ecbacd 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -65,6 +65,11 @@ module.exports = app => { allowNull: true, comment: '自身IP白名单', }, + callback_url: { + type: STRING(500), + allowNull: true, + comment: 'API回调通知URL', + }, qimen_app_key: { type: STRING(100), allowNull: true, @@ -227,7 +232,7 @@ module.exports = app => { // 定义关联关系 ApiApp.associate = function() { - const { InterfaceType, StoreWarehouse, Store, InterfaceLog } = app.model; + const { InterfaceType, StoreWarehouse, Store } = app.model; // 关联接口类型 ApiApp.belongsTo(InterfaceType, { diff --git a/app/model/entry_items.js b/app/model/entry_items.js index 6af2ecc..0969a64 100644 --- a/app/model/entry_items.js +++ b/app/model/entry_items.js @@ -192,7 +192,7 @@ module.exports = app => { }; // 钩子函数 - 保存前验证 - EntryItems.beforeSave(async (instance, options) => { + EntryItems.beforeSave(async instance => { const received = instance.received_quantity || 0; const plan = instance.count || 0; @@ -210,7 +210,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; diff --git a/app/model/file.js b/app/model/file.js index 2499a4a..785def8 100644 --- a/app/model/file.js +++ b/app/model/file.js @@ -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: { diff --git a/app/model/file_reference.js b/app/model/file_reference.js index b90a8db..fe4ebec 100644 --- a/app/model/file_reference.js +++ b/app/model/file_reference.js @@ -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: { diff --git a/app/model/i18n_key.js b/app/model/i18n_key.js index eb96cbc..4516877 100644 --- a/app/model/i18n_key.js +++ b/app/model/i18n_key.js @@ -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: { diff --git a/app/model/interface_type.js b/app/model/interface_type.js index 2e845e2..c0d64d5 100644 --- a/app/model/interface_type.js +++ b/app/model/interface_type.js @@ -105,6 +105,16 @@ module.exports = app => { ], }); + InterfaceType.associate = function() { + const { ApiApp } = app.model; + + InterfaceType.hasMany(ApiApp, { + foreignKey: 'interface_type_id', + sourceKey: 'id', + as: 'api_apps', + }); + }; + // 实例方法 - 检查接口是否可用 InterfaceType.prototype.isAvailable = function() { return this.is_enabled === 1; diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index 6c769b5..aff14fe 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -39,6 +39,18 @@ module.exports = app => { Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }), Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }), Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), + Object.freeze({ + code: 'store_warehouse_print_quantity_adjusted', + name: '货主面单余额调整', + business: 'store_warehouse', + description: '货主-仓库签约下的面单余额被人工调整后的通知', + }), + Object.freeze({ + code: 'storage_transfer_completed', + name: '移库操作完成', + business: 'storage', + description: '库存库位转移操作完成后的通知', + }), ]); const AVAILABLE_EVENT_CODE_SET = new Set(AVAILABLE_EVENTS.map(item => item.code)); diff --git a/app/model/order_delivery_factory.js b/app/model/order_delivery_factory.js index a5df849..20f8769 100644 --- a/app/model/order_delivery_factory.js +++ b/app/model/order_delivery_factory.js @@ -2,7 +2,6 @@ 'use strict'; module.exports = app => { - const { Sequelize, model } = app; class OrderDeliveryFactory { constructor() { @@ -12,7 +11,8 @@ module.exports = app => { /** * 获取当前表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 当前表模型 */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); @@ -20,7 +20,8 @@ module.exports = app => { /** * 获取历史表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 历史表模型 */ async getHistoryModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'history'); @@ -28,7 +29,8 @@ module.exports = app => { /** * 根据表名直接获取模型 - * @param tableName + * @param {string} tableName 表名 + * @return {Promise} 动态模型 */ async getModelByTableName(tableName) { const cacheKey = `table_${tableName}`; @@ -61,8 +63,9 @@ module.exports = app => { /** * 获取或创建模型 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} 动态模型 */ async getOrCreateModel(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); @@ -103,9 +106,10 @@ module.exports = app => { /** * 获取模型配置选项 - * @param tableName - * @param warehouseId - * @param type + * @param {string} tableName 表名 + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Object} Sequelize 模型配置 */ getModelOptions(tableName, warehouseId, type) { const options = { @@ -128,8 +132,9 @@ module.exports = app => { /** * 获取索引配置 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Array} 索引配置 */ getIndexes(warehouseId, type) { const prefix = `${warehouseId}_${type}`; @@ -180,9 +185,10 @@ module.exports = app => { /** * 设置关联关系 - * @param DynamicModel - * @param warehouseId - * @param type + * @param {Object} DynamicModel 动态模型 + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} */ async setupAssociations(DynamicModel, warehouseId, type) { try { @@ -231,7 +237,8 @@ module.exports = app => { /** * 检查表是否存在 - * @param tableName + * @param {string} tableName 表名 + * @return {Promise} 是否存在 */ async checkTableExists(tableName) { const sequelize = this.app.model; @@ -258,8 +265,9 @@ module.exports = app => { /** * 创建物理表 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} */ async createPhysicalTable(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); @@ -271,9 +279,6 @@ module.exports = app => { const historyFields = type === 'history' ? ',\n`archive_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT \'归档时间\'' : ''; - // 状态机枚举值 - const statusEnums = this.getStatusEnumValues(); - const createTableSQL = ` CREATE TABLE \`${tableName}\` ( \`id\` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, @@ -393,8 +398,9 @@ module.exports = app => { /** * 生成表名 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {string} 表名 */ generateTableName(warehouseId, type) { const suffix = type === 'history' ? '_history' : ''; diff --git a/app/model/order_items.js b/app/model/order_items.js index a1a971a..efe064b 100644 --- a/app/model/order_items.js +++ b/app/model/order_items.js @@ -3,7 +3,7 @@ module.exports = app => { const { Sequelize, model } = app; - const { STRING, BIGINT, DECIMAL, TEXT, INTEGER, JSON } = Sequelize; + const { STRING, BIGINT, DECIMAL, INTEGER, JSON } = Sequelize; const OrderItems = model.define('wms_order_items', { id: { diff --git a/app/model/order_items_factory.js b/app/model/order_items_factory.js index 61d41d4..3ff60f1 100644 --- a/app/model/order_items_factory.js +++ b/app/model/order_items_factory.js @@ -2,7 +2,7 @@ 'use strict'; module.exports = app => { - const { Sequelize, model } = app; + const { Sequelize } = app; class OrderItemsFactory { constructor() { @@ -13,7 +13,8 @@ module.exports = app => { /** * 获取当前表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 当前表模型 */ async getCurrentModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'current'); @@ -21,7 +22,8 @@ module.exports = app => { /** * 获取历史表模型 - * @param warehouseId + * @param {number} warehouseId 仓库ID + * @return {Promise} 历史表模型 */ async getHistoryModel(warehouseId) { return await this.getOrCreateModel(warehouseId, 'history'); @@ -29,8 +31,9 @@ module.exports = app => { /** * 获取或创建模型 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @return {Promise} 动态模型 */ async getOrCreateModel(warehouseId, type = 'current') { const cacheKey = `${warehouseId}_${type}`; @@ -65,11 +68,12 @@ module.exports = app => { /** * 带重试的模型创建 - * @param warehouseId - * @param type - * @param tableName - * @param cacheKey - * @param retryCount + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 + * @param {string} tableName 表名 + * @param {string} cacheKey 缓存键 + * @param {number} retryCount 重试次数 + * @return {Promise} 动态模型 */ async createModelWithRetry(warehouseId, type, tableName, cacheKey, retryCount = 3) { for (let i = 0; i < retryCount; i++) { @@ -120,8 +124,8 @@ module.exports = app => { /** * 复制关联关系 - * @param sourceModel - * @param targetModel + * @param {Object} sourceModel 源模型 + * @param {Object} targetModel 目标模型 */ copyAssociations(sourceModel, targetModel) { if (sourceModel.associations) { @@ -148,7 +152,7 @@ module.exports = app => { /** * 生成索引配置 - * @param warehouseId + * @param {number} warehouseId 仓库ID */ generateIndexes(warehouseId) { return [ @@ -189,7 +193,7 @@ module.exports = app => { /** * 检查表是否存在 - * @param tableName + * @param {string} tableName 表名 */ async checkTableExists(tableName) { try { @@ -211,8 +215,8 @@ module.exports = app => { /** * 创建物理表 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 */ async createPhysicalTable(warehouseId, type = 'current') { const tableName = this.generateTableName(warehouseId, type); @@ -263,8 +267,8 @@ module.exports = app => { /** * 生成表名 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 */ generateTableName(warehouseId, type) { const suffix = type === 'history' ? '_history' : ''; @@ -273,8 +277,8 @@ module.exports = app => { /** * 清除缓存 - * @param warehouseId - * @param type + * @param {number} warehouseId 仓库ID + * @param {string} type 模型类型 */ clearCache(warehouseId, type) { const cacheKey = `${warehouseId}_${type}`; @@ -290,7 +294,7 @@ module.exports = app => { /** * 休眠函数 - * @param ms + * @param {number} ms 毫秒数 */ sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); diff --git a/app/model/print_item.js b/app/model/print_item.js index d26e294..d9659a1 100644 --- a/app/model/print_item.js +++ b/app/model/print_item.js @@ -1,6 +1,6 @@ // app/model/print_item.js module.exports = app => { - const { STRING, INTEGER, BOOLEAN, TEXT, JSON, DATE } = app.Sequelize; + const { STRING, INTEGER, BOOLEAN, JSON, DATE } = app.Sequelize; const PrintItem = app.model.define('print_item', { id: { diff --git a/app/model/qimen_log.js b/app/model/qimen_log.js index 7f9ed9e..42f0bb6 100644 --- a/app/model/qimen_log.js +++ b/app/model/qimen_log.js @@ -3,7 +3,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, BIGINT, TEXT, DATE, BOOLEAN } = app.Sequelize; + const { STRING, INTEGER, BIGINT, TEXT, DATE } = app.Sequelize; const QimenLog = app.model.define('qimen_log', { id: { diff --git a/app/model/receiving.js b/app/model/receiving.js index b885599..fe07bcc 100644 --- a/app/model/receiving.js +++ b/app/model/receiving.js @@ -1,6 +1,6 @@ // app/model/receiving.js module.exports = app => { - const { STRING, INTEGER, DATE, DECIMAL, TEXT, BOOLEAN, ENUM } = app.Sequelize; + const { STRING, INTEGER, DATE, TEXT, BOOLEAN, ENUM } = app.Sequelize; const Receiving = app.model.define('wms_receiving', { id: { diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index 6f1f0fe..a634b90 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -1,6 +1,6 @@ // app/model/receiving_detail.js module.exports = app => { - const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM, BOOLEAN, BIGINT } = app.Sequelize; + const { STRING, INTEGER, DATE, DECIMAL, TEXT, ENUM, BIGINT } = app.Sequelize; const ReceivingDetail = app.model.define('wms_receiving_detail', { id: { diff --git a/app/model/stock_barcode.js b/app/model/stock_barcode.js index 21e7b86..374a892 100644 --- a/app/model/stock_barcode.js +++ b/app/model/stock_barcode.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { STRING, BIGINT, DATE, TEXT } = app.Sequelize; + const { STRING, BIGINT, DATE } = app.Sequelize; const StockBarcode = app.model.define('stock_barcodes', { id: { diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js new file mode 100644 index 0000000..88ddf39 --- /dev/null +++ b/app/model/stock_transaction.js @@ -0,0 +1,154 @@ +'use strict'; + +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + + const StockTransaction = app.model.define('stock_transaction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + transaction_type: { + type: ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号', + }, + inventory_type: { + type: ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + defaultValue: 'ZP', + comment: '库存类型', + }, + order_type: { + type: STRING(50), + allowNull: true, + comment: '关联单据类型(如 SCRK=收货入库, MATCH=匹配入库, CGTH=采购退货等)', + }, + order_no: { + type: STRING(100), + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '关联收货单ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID', + }, + operator_id: { + type: STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + tableName: 'wms_stock_transaction', + freezeTableName: true, + timestamps: false, + comment: '出入库流水记录表', + indexes: [ + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_warehouse_time', + fields: [ 'warehouse_id', 'created_at' ], + }, + { + name: 'idx_order', + fields: [ 'order_type', 'order_id' ], + }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, + { + name: 'idx_created_at', + fields: [ 'created_at' ], + }, + { + name: 'idx_store_transaction_type', + fields: [ 'store_id', 'transaction_type' ], + }, + ], + }); + + StockTransaction.associate = function() { + const { StockWarehouse, Storage } = app.model; + StockTransaction.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockItem', + }); + StockTransaction.belongsTo(Storage, { + foreignKey: 'storage_id', + as: 'storageRecord', + }); + }; + + return StockTransaction; +}; diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 2d0107b..2eee63b 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -222,8 +222,8 @@ module.exports = app => { ], }); - StockWarehouse.associate = function(models) { - const { StoreWarehouse, StockBarcode, ProhibitedType, StockImage, StockStore, Storage } = app.model; + StockWarehouse.associate = function() { + const { StoreWarehouse, StockBarcode, ProhibitedType, StockStore, Storage } = app.model; // store_stock 关联依赖 store_id + warehouse_id 复合语义,单列关联仅作为 include 入口。 StockWarehouse.belongsTo(StoreWarehouse, { foreignKey: 'store_id', // 当前表的外键字段 @@ -250,6 +250,12 @@ module.exports = app => { as: 'storage', }); + const { StockTransaction } = app.model; + StockWarehouse.hasMany(StockTransaction, { + foreignKey: 'stock_id', + as: 'transactions', + }); + }; return StockWarehouse; diff --git a/app/model/storage.js b/app/model/storage.js index 7646aee..5d359d0 100644 --- a/app/model/storage.js +++ b/app/model/storage.js @@ -101,6 +101,24 @@ module.exports = app => { notEmpty: true, }, }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '收货单ID', + references: { + model: 'wms_receiving', + key: 'id', + }, + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID', + references: { + model: 'wms_entry_order', + key: 'id', + }, + }, supplier_id: { type: BIGINT(20).UNSIGNED, allowNull: true, @@ -138,6 +156,8 @@ module.exports = app => { tableName: 'wms_storage', comment: '库存表', timestamps: false, + paranoid: true, + deletedAt: 'delete_at', indexes: [ { name: 'uk_location_sku_batch_type', @@ -164,6 +184,14 @@ module.exports = app => { name: 'idx_inbound_order', fields: [ 'inbound_order_no' ], }, + { + name: 'idx_receiving_id', + fields: [ 'receiving_id' ], + }, + { + name: 'idx_entry_order_id', + fields: [ 'entry_order_id' ], + }, { name: 'idx_store_id', fields: [ 'store_id' ], @@ -215,6 +243,18 @@ module.exports = app => { as: 'stock', }); + // 关联收货单 + Storage.belongsTo(app.model.Receiving, { + foreignKey: 'receiving_id', + as: 'receiving', + }); + + // 关联入库单 + Storage.belongsTo(app.model.EntryOrder, { + foreignKey: 'entry_order_id', + as: 'entryOrder', + }); + }; // 实例方法 diff --git a/app/model/store_warehouse.js b/app/model/store_warehouse.js index f0a2ae3..611d9ff 100644 --- a/app/model/store_warehouse.js +++ b/app/model/store_warehouse.js @@ -1,7 +1,211 @@ 'use strict'; module.exports = app => { - const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize; + const { BIGINT, TEXT, STRING, DATE, TINYINT, INTEGER, JSON: JSON_TYPE } = app.Sequelize; + + const POLICY_CONFIG_FIELDS = Object.freeze([ + Object.freeze({ + key: 'receive_mode', + name: '收货模式', + type: 'enum', + default: 'standard', + required: false, + description: '控制货主在该仓下的收货校验模式', + options: [ 'standard', 'strict', 'manual' ], + }), + Object.freeze({ + key: 'sku_visibility', + name: 'SKU 可见范围', + type: 'enum', + default: 'all', + required: false, + description: '控制货主在该仓下的 SKU 可见策略', + options: [ 'all', 'whitelist', 'blacklist' ], + }), + Object.freeze({ + key: 'auto_allocate_bin', + name: '自动分配库位', + type: 'flag', + default: 0, + required: false, + description: '收货上架时是否自动推荐库位', + }), + Object.freeze({ + key: 'allow_mix_batch', + name: '允许混批', + type: 'flag', + default: 0, + required: false, + description: '是否允许不同批次混合存放', + }), + Object.freeze({ + key: 'allow_temp_storage', + name: '允许临时存放', + type: 'flag', + default: 0, + required: false, + description: '是否允许进入临时存放区', + }), + Object.freeze({ + key: 'print_recharge_price', + name: '面单充值元/单', + type: 'number', + default: 0, + required: false, + description: '面单充值元/单,支持 2 位小数', + min: 0, + max: 1000000, + precision: 2, + step: 0.01, + }), + Object.freeze({ + key: 'max_daily_inbound', + name: '单日最大收货量', + type: 'integer', + default: 0, + required: false, + description: '限制该货主在仓库内的日收货上限', + min: 0, + max: 1000000, + }), + Object.freeze({ + key: 'remark', + name: '策略备注', + type: 'string', + default: '', + required: false, + description: '补充说明该货主在仓库内的特殊约束', + maxLength: 200, + }), + ]); + const POLICY_CONFIG_FIELD_MAP = Object.freeze(POLICY_CONFIG_FIELDS.reduce((result, field) => { + result[field.key] = field; + return result; + }, {})); + + const clonePolicyConfigField = field => ({ + key: field.key, + name: field.name, + type: field.type, + default: field.default, + required: field.required, + description: field.description, + ...(Array.isArray(field.options) ? { options: [ ...field.options ] } : {}), + ...(field.min !== undefined ? { min: field.min } : {}), + ...(field.max !== undefined ? { max: field.max } : {}), + ...(field.precision !== undefined ? { precision: field.precision } : {}), + ...(field.step !== undefined ? { step: field.step } : {}), + ...(field.maxLength !== undefined ? { maxLength: field.maxLength } : {}), + }); + + const parsePolicyConfig = (value, fieldName = 'policy_config') => { + if (typeof value === 'string') { + try { + return JSON.parse(value); + } catch (error) { + throw new Error(`${fieldName} 不是合法JSON`); + } + } + return value; + }; + + const normalizePolicyConfig = (value, options = {}) => { + const { + fieldName = 'policy_config', + allowEmpty = false, + sanitizeOnly = false, + } = options; + + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw new Error(`${fieldName} 参数不能为空`); + } + + const parsed = parsePolicyConfig(value, fieldName); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`${fieldName} 必须为对象`); + } + + const supportedKeys = Object.keys(POLICY_CONFIG_FIELD_MAP); + const unsupportedKeys = Object.keys(parsed).filter(key => !POLICY_CONFIG_FIELD_MAP[key]); + if (unsupportedKeys.length && !sanitizeOnly) { + throw new Error(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${supportedKeys.join(', ')}`); + } + + const normalized = {}; + for (const field of POLICY_CONFIG_FIELDS) { + if (!Object.prototype.hasOwnProperty.call(parsed, field.key)) { + continue; + } + + const rawValue = parsed[field.key]; + if (rawValue === undefined || rawValue === null || rawValue === '') { + if (field.type === 'string') { + normalized[field.key] = ''; + } + continue; + } + + try { + if (field.type === 'enum') { + const valueText = String(rawValue).trim(); + if (!field.options.includes(valueText)) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + normalized[field.key] = valueText; + continue; + } + + if (field.type === 'flag') { + if (rawValue === true || rawValue === 1 || rawValue === '1') { + normalized[field.key] = 1; + continue; + } + if (rawValue === false || rawValue === 0 || rawValue === '0') { + normalized[field.key] = 0; + continue; + } + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + + if (field.type === 'integer') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < field.min || num > field.max) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + normalized[field.key] = Math.floor(num); + continue; + } + + if (field.type === 'number') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < field.min || num > field.max) { + throw new Error(`${fieldName}.${field.key} 参数不合法`); + } + const precision = Number.isInteger(field.precision) ? field.precision : 2; + const factor = 10 ** precision; + normalized[field.key] = Math.round(num * factor) / factor; + continue; + } + + if (field.type === 'string') { + const text = String(rawValue).trim(); + if (text.length > field.maxLength) { + throw new Error(`${fieldName}.${field.key} 长度不能超过 ${field.maxLength}`); + } + normalized[field.key] = text; + } + } catch (error) { + if (!sanitizeOnly) { + throw error; + } + } + } + + return Object.keys(normalized).length ? normalized : null; + }; const StoreWarehouse = app.model.define('store_warehouse', { id: { @@ -119,6 +323,25 @@ module.exports = app => { }, comment: '仓库备注', }, + policy_config: { + type: JSON_TYPE, + allowNull: true, + defaultValue: null, + comment: '货主在仓库下的固定策略配置(JSON)', + get() { + return normalizePolicyConfig(this.getDataValue('policy_config'), { + fieldName: 'policy_config', + allowEmpty: true, + sanitizeOnly: true, + }); + }, + set(value) { + this.setDataValue('policy_config', normalizePolicyConfig(value, { + fieldName: 'policy_config', + allowEmpty: true, + })); + }, + }, use_status: { type: INTEGER(1), allowNull: false, @@ -179,7 +402,7 @@ module.exports = app => { // 定义关联关系 StoreWarehouse.associate = function() { - const { Store, Account, StockWarehouse, Receiving } = app.model; + const { Store, Account, StockWarehouse, Receiving, StoreWarehousePrintQuantityLog } = app.model; // 授权关系属于商家 StoreWarehouse.belongsTo(Store, { @@ -229,6 +452,21 @@ module.exports = app => { as: 'receiving', constraints: false, }); + + StoreWarehouse.hasMany(StoreWarehousePrintQuantityLog, { + foreignKey: 'contract_id', + sourceKey: 'id', + as: 'print_quantity_logs', + constraints: false, + }); + }; + + StoreWarehouse.getPolicyConfigFieldList = function() { + return POLICY_CONFIG_FIELDS.map(clonePolicyConfigField); + }; + + StoreWarehouse.normalizePolicyConfig = function(value, options = {}) { + return normalizePolicyConfig(value, options); }; // 统一构造复合键语义的 where 条件,避免 service 侧重复散落。 diff --git a/app/model/store_warehouse_print_quantity_log.js b/app/model/store_warehouse_print_quantity_log.js new file mode 100644 index 0000000..87c7487 --- /dev/null +++ b/app/model/store_warehouse_print_quantity_log.js @@ -0,0 +1,174 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TEXT, DATE } = app.Sequelize; + + const StoreWarehousePrintQuantityLog = app.model.define('store_warehouse_print_quantity_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + contract_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '签约关系ID,对应 wms_store_warehouse.id', + references: { + model: 'store_warehouse', + key: 'id', + }, + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + change_type: { + type: STRING(50), + allowNull: false, + comment: '变更类型,如 manual_adjust / order_deduct', + }, + business_type: { + type: STRING(50), + allowNull: true, + comment: '业务来源类型,如 order_express', + }, + business_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '业务关联ID,预留关联 wms_order_express.id', + }, + change_quantity: { + type: BIGINT(20), + allowNull: false, + comment: '本次变更数量,整数,可正可负', + }, + balance_before: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更前余额', + }, + balance_after: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更后余额', + }, + reason: { + type: TEXT, + allowNull: true, + comment: '变更缘由;人工调整时必填', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账号ID', + }, + created_by: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账号ID', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_store_warehouse_print_quantity_log', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + comment: '货主-仓库签约面单余额变更记录表', + indexes: [ + { + name: 'idx_sw_print_qty_log_contract_id', + fields: [ 'contract_id', 'id' ], + }, + { + name: 'idx_sw_print_qty_log_store_warehouse', + fields: [ 'store_id', 'warehouse_id' ], + }, + { + name: 'idx_sw_print_qty_log_business', + fields: [ 'business_type', 'business_id' ], + }, + { + name: 'idx_sw_print_qty_log_change_type', + fields: [ 'change_type' ], + }, + { + name: 'idx_sw_print_qty_log_created_at', + fields: [ 'created_at' ], + }, + ], + }); + + StoreWarehousePrintQuantityLog.associate = function() { + const { StoreWarehouse, Store, Account, OrderExpress } = app.model; + + StoreWarehousePrintQuantityLog.belongsTo(StoreWarehouse, { + foreignKey: 'contract_id', + targetKey: 'id', + as: 'contract', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Store, { + foreignKey: 'store_id', + targetKey: 'id', + as: 'store', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Store, { + foreignKey: 'warehouse_id', + targetKey: 'id', + as: 'warehouse', + }); + + StoreWarehousePrintQuantityLog.belongsTo(Account, { + foreignKey: 'operator_id', + targetKey: 'id', + as: 'operator', + constraints: false, + }); + + StoreWarehousePrintQuantityLog.belongsTo(Account, { + foreignKey: 'created_by', + targetKey: 'id', + as: 'creator', + constraints: false, + }); + + StoreWarehousePrintQuantityLog.belongsTo(OrderExpress, { + foreignKey: 'business_id', + targetKey: 'id', + as: 'order_express', + constraints: false, + }); + }; + + return StoreWarehousePrintQuantityLog; +}; diff --git a/app/router.js b/app/router.js index 1ed412f..c96daa7 100644 --- a/app/router.js +++ b/app/router.js @@ -11,17 +11,14 @@ module.exports = app => { // 奇门接口 router.post('/qimen', controller.home.qimen); - // 预留第三方系统接口 - router.post('/api/warehouse', controller.home.warehouse); - router.post('/api/store', controller.home.store); - // 系统接口 PDA/WEB 统一入口 router.post('/system', controller.home.system); // api文档相关 router.get('/api/docs', controller.docs.list); - router.get('/api/docs/:docName', controller.docs.detail); router.get('/api/docs/:docName/raw', controller.docs.raw); + router.get('/api/docs/:docName/changes', controller.docs.changes); + router.get('/api/docs/:docName', controller.docs.detail); // 打印模板 router.get('/template/xml/:id', controller.template.xml); diff --git a/app/service/api.js b/app/service/api.js index 544067c..aad17c5 100644 --- a/app/service/api.js +++ b/app/service/api.js @@ -1,17 +1,15 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); class ApiService extends Service { /** * 调用业务方法 - * @param className - * @param actionName - * @param jsonData - * @param format + * @param {string} className 服务类路径 + * @param {string} actionName 方法名 + * @param {Object} jsonData 请求数据 */ - async callMethod(className, actionName, jsonData, format = 'json') { + async callMethod(className, actionName, jsonData) { try { // 构建服务类路径 const servicePath = `${className}`; diff --git a/app/service/apiMethods/test.js b/app/service/apiMethods/test.js index 7630273..7284f49 100644 --- a/app/service/apiMethods/test.js +++ b/app/service/apiMethods/test.js @@ -11,17 +11,15 @@ class testServer extends Service { this.addon = require(app.appRoot + '/native/addons/subset_selector.node'); this.addonLoaded = true; this.ctx.logger.info('[FibonacciService] C++插件加载成功'); - console.log(this.addon); } catch (error) { - this.addonLoaded = false; this.ctx.logger.error('[FibonacciService] C++插件加载失败:', error); } } async entryorderConfirm(data) { - const { app, ctx } = this; + const { ctx } = this; return await ctx.service.systems.entryOrder.entryorderConfirm(data.id, data.isCompleted); } async playbackRequest(data) { @@ -33,7 +31,6 @@ class testServer extends Service { }, }); if (entryOrder) { - console.log('entryOrder', entryOrder.body); const body = await this.ctx.service.systems.qimenQuery.sendRequest(entryOrder.url, entryOrder.body); return { body }; } @@ -65,8 +62,6 @@ class testServer extends Service { raw: true, }); - console.log('查询到的订单ID数量:', deliveryResult.length); - if (deliveryResult.length === 0) { return { orderIds: [], @@ -93,8 +88,6 @@ class testServer extends Service { raw: true, }); - console.log('查询到的商品记录数量:', itemsResult.length); - // 4. 按订单分组商品 const itemsByOrder = {}; itemsResult.forEach(item => { @@ -116,8 +109,6 @@ class testServer extends Service { }; }).filter(order => order.skus.length > 0); // 过滤掉没有商品的订单 - console.log('有效订单数量:', orders.length); - if (orders.length === 0) { return { orderIds: [], diff --git a/app/service/main.js b/app/service/main.js index 7a1a728..5b0f62c 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -31,7 +31,6 @@ class MainService extends Service { } fail(message, data, code = 0) { - console.log('fail', message, data); const result = { flag: 'failure', code, @@ -309,7 +308,6 @@ class MainService extends Service { const _noNeedAuth = (this._noNeedAuth || '').split(','); const _noNeedLog = (this._noNeedLog || '').split(','); const api_path = `${servicePath}.${actionName}`; - console.log(api_path, '_noNeedLog', _noNeedLog); const result = { status: 401, message: '', @@ -357,7 +355,6 @@ class MainService extends Service { // 设置新的 token 到响应头 ctx.set('Authorization', `Bearer ${newToken}`); - console.log('Token 已刷新,新 token:', newToken.substring(0, 50) + '...'); } // 4. 获取用户信息 const user = await ctx.service.systems.auth.user.findById(decoded.id || decoded.userId); @@ -393,11 +390,8 @@ class MainService extends Service { } // 6. 验证API权限(只检查类型为api的权限) - console.log('检查权限开始'); const hasPermission = await this.checkApiPermission(user, api_path); - console.log('检查权限结束', hasPermission); - if (!hasPermission) { result.status = 403; @@ -440,20 +434,163 @@ class MainService extends Service { * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { - console.log(user); + const normalizedApiPath = String(apiPath || '').trim().toLowerCase(); + if (!normalizedApiPath) { + return false; + } + try { - // 方法1: 从用户的权限列表中检查(如果已经加载了权限) - if (user.permissions && Array.isArray(user.permissions)) { - // 用户权限列表中可能包含所有权限,需要过滤出api权限 - console.log('user.permissions', user.permissions); - return user.permissions.includes(apiPath); + const { allAccess, pathSet, permissionIds } = this.extractApiPermissionState(user); + if (allAccess) { + return true; } + + if (pathSet.has(normalizedApiPath)) { + return true; + } + + if (permissionIds.size > 0 && this.ctx.model && this.ctx.model.Permission && typeof this.ctx.model.Permission.findAll === 'function') { + const permissionRows = await this.ctx.model.Permission.findAll({ + where: { + id: [ ...permissionIds ], + status: 1, + }, + attributes: [ 'id', 'path' ], + raw: true, + }); + + return permissionRows.some(item => String(item && item.path || '').trim().toLowerCase() === normalizedApiPath); + } + return false; } catch (error) { console.error('检查API权限失败:', error); return false; } } + + extractApiPermissionState(user = {}) { + const state = { + allAccess: false, + pathSet: new Set(), + permissionIds: new Set(), + }; + const visited = new Set(); + const sources = [ + user.permissions, + user.role_permissions, + user.permission_ids, + user.permissionIds, + ]; + + for (const source of sources) { + this.collectApiPermissionValue(source, state, visited); + if (state.allAccess) { + break; + } + } + + return state; + } + + collectApiPermissionValue(value, state, visited) { + if (state.allAccess || value === undefined || value === null) { + return; + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return; + } + + if (trimmed === '*') { + state.allAccess = true; + return; + } + + if ((trimmed.startsWith('[') && trimmed.endsWith(']')) || (trimmed.startsWith('{') && trimmed.endsWith('}'))) { + try { + const parsed = JSON.parse(trimmed); + if (parsed !== value) { + this.collectApiPermissionValue(parsed, state, visited); + return; + } + } catch (_) { + // 忽略 JSON 解析失败,继续按普通字符串处理。 + } + } + + if (trimmed.includes(',')) { + this.collectApiPermissionValue(trimmed.split(','), state, visited); + return; + } + + const asNumber = Number(trimmed); + if (Number.isInteger(asNumber) && String(asNumber) === trimmed) { + state.permissionIds.add(asNumber); + return; + } + + state.pathSet.add(trimmed.toLowerCase()); + return; + } + + if (typeof value === 'number') { + if (Number.isInteger(value) && value > 0) { + state.permissionIds.add(value); + } + return; + } + + if (Array.isArray(value)) { + for (const item of value) { + this.collectApiPermissionValue(item, state, visited); + if (state.allAccess) { + break; + } + } + return; + } + + if (typeof value !== 'object') { + return; + } + + if (visited.has(value)) { + return; + } + visited.add(value); + + if (value.allAccess === true || value.isAllAccess === true) { + state.allAccess = true; + return; + } + + const candidates = [ + value.path, + value.apiPath, + value.permission, + value.permissionPath, + value.value, + value.id, + value.permission_id, + value.permissionId, + value.permissions, + value.permission_ids, + value.permissionIds, + value.children, + value.items, + value.list, + ]; + + for (const candidate of candidates) { + this.collectApiPermissionValue(candidate, state, visited); + if (state.allAccess) { + break; + } + } + } /** * 设置用户上下文信息 * @param {Object} ctx - 上下文对象 @@ -467,7 +604,6 @@ class MainService extends Service { ctx.username = user.username; ctx.realName = user.real_name; - if (user.store_id) { ctx.currentStoreId = user.store_id; } diff --git a/app/service/pda.js b/app/service/pda.js index de8f355..de670ba 100644 --- a/app/service/pda.js +++ b/app/service/pda.js @@ -1,7 +1,6 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); class pdaService extends Service { async callMethod(className, actionName, requestData, authHeader) { @@ -31,9 +30,8 @@ class pdaService extends Service { // 调用方法 const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader); const isLog = authPass.isLog; - if (authPass.status == 200) { + if (authPass.status === 200) { result.data = await serviceInstance[actionName](requestData); - console.log(result.data); result.status = 200; } else { diff --git a/app/service/qimen.js b/app/service/qimen.js index 33bff3d..8e2b44d 100644 --- a/app/service/qimen.js +++ b/app/service/qimen.js @@ -6,14 +6,13 @@ const { XMLParser } = require('fast-xml-parser'); class QimenService extends Service { /** * 验证接口是否存在且启用 - * @param appkey - * @param customerId - * @param warehouseCode + * @param {string} appkey 应用编码 + * @param {string} customerId 客户编码 + * @param {string} warehouseCode 仓库编码 */ async validateApi(appkey, customerId, warehouseCode) { try { - const { ctx } = this; const result = await this.ctx.service.main.findQimenAppWithContract(appkey, customerId, warehouseCode); return result; } catch (error) { @@ -41,7 +40,7 @@ class QimenService extends Service { } /** * 解析XML到数组 - * @param xmlString + * @param {string} xmlString XML 字符串 */ async parseXmlToArray(xmlString) { const cleanedXml = this.cleanXmlString(xmlString); @@ -60,7 +59,7 @@ class QimenService extends Service { trimValues: false, // 也关闭trim,保持原始格式 ignoreDeclaration: true, // 添加标签值处理器,手动控制转换 - tagValueProcessor: (tagName, tagValue, jPath, hasAttributes, isLeafNode) => { + tagValueProcessor: tagValue => { // 如果是叶子节点且需要保持字符串格式的标签,可以在这里特殊处理 // 默认返回原始值 return tagValue; @@ -77,7 +76,7 @@ class QimenService extends Service { /** * 清理XML字符串 - * @param xmlString + * @param {string} xmlString XML 字符串 */ cleanXmlString(xmlString) { if (!xmlString) return ''; @@ -103,17 +102,17 @@ class QimenService extends Service { /** * 调用业务方法 - * @param className - * @param actionName - * @param xmlData - * @param storeId - * @param warehouseId - * @param appKey - * @param customerId - * @param warehouseCode - * @param format + * @param {string} className 类名 + * @param {string} actionName 方法名 + * @param {Object} xmlData 解析后的 XML 数据 + * @param {number} storeId 货主ID + * @param {number} warehouseId 仓库ID + * @param {string} appKey 应用编码 + * @param {string} customerId 客户编码 + * @param {string} warehouseCode 仓库编码 + * @return {Promise} 调用结果 */ - async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode, format = 'xml') { + async callMethod(className, actionName, xmlData, storeId, warehouseId, appKey, customerId, warehouseCode) { try { // 构建服务类路径 const servicePath = `${className}`; @@ -148,7 +147,7 @@ class QimenService extends Service { /** * 格式化响应 - * @param data + * @param {Object} data 响应数据 */ formatResponse(data) { return this.xmlResponse(data); @@ -156,7 +155,7 @@ class QimenService extends Service { /** * XML响应 - * @param data + * @param {Object} data 响应数据 */ xmlResponse(data) { let xml = '\n'; @@ -180,9 +179,9 @@ class QimenService extends Service { /** * 构建XML节点 - 支持多层级 - * @param key - * @param value - * @param level + * @param {string} key 节点名 + * @param {*} value 节点值 + * @param {number} level 缩进层级 */ buildXmlNode(key, value, level = 0) { const indent = ' '.repeat(level); @@ -218,7 +217,7 @@ class QimenService extends Service { /** * XML转义 - * @param unsafe + * @param {*} unsafe 待转义值 */ escapeXml(unsafe) { if (unsafe === null || unsafe === undefined) return ''; diff --git a/app/service/qimenMethods/deliveryorder.js b/app/service/qimenMethods/deliveryorder.js index 635c0ae..9ba30c3 100644 --- a/app/service/qimenMethods/deliveryorder.js +++ b/app/service/qimenMethods/deliveryorder.js @@ -5,7 +5,6 @@ const MainService = require('../main'); class deliveryorderServer extends MainService { async query(data) { const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(this.warehouseId); - const hisDeliveryModel = await this.ctx.model.OrderDeliveryFactory.getHistoryModel(this.warehouseId); const order = await DeliveryModel.findOne({ where: { delivery_order_code: data.request.orderCode } }); const totalLines = 0; if (order) { @@ -35,9 +34,9 @@ class deliveryorderServer extends MainService { const info = this.getInfo; const res = await this.ctx.service.systems.deliveryOrder.addOrder(data, this.getInfo(), 'QM'); if (res.success) { - return this.success(res.message, { createTime: new Date().format(), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); + return this.success(res.message, { createTime: this.app.formatDate(new Date()), deliveryOrderId: res.data.deliveryOrderId, warehouseCode: info.warehouseCode, logisticsCode: res.data.logisticsCode }); } - return this.fail(res.message, { createTime: new Date().format() }); + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); } async batchcreate() { diff --git a/app/service/qimenMethods/entryorder.js b/app/service/qimenMethods/entryorder.js index 67b941d..48efe60 100644 --- a/app/service/qimenMethods/entryorder.js +++ b/app/service/qimenMethods/entryorder.js @@ -4,18 +4,15 @@ const MainService = require('../main'); class entryorderServer extends MainService { async create(data) { - const info = this.getInfo; const res = await this.ctx.service.systems.entryOrder.addOrder(data, this.getInfo(), 'QM'); - console.log('创建入库单返回', res); if (res.success) { - return this.success(res.message, { createTime: new Date().format(), entryOrderId: res.data.entryOrderId }); + return this.success(res.message, { createTime: this.app.formatDate(new Date()), entryOrderId: res.data.entryOrderId }); } - return this.fail(res.message, { createTime: new Date().format() }); + return this.fail(res.message, { createTime: this.app.formatDate(new Date()) }); } - async query(data) { - console.log(data); + async query() { return this.fail('接口未完善'); } diff --git a/app/service/qimenMethods/inventory.js b/app/service/qimenMethods/inventory.js index 3d09f09..19868b5 100644 --- a/app/service/qimenMethods/inventory.js +++ b/app/service/qimenMethods/inventory.js @@ -3,10 +3,6 @@ const MainService = require('../main'); class inventoryServer extends MainService { - - constructor(ctx) { - super(ctx); - } async query(data) { const criteria = data.request.criteriaList.criteria; const list = criteria.warehouseCode ? [ criteria ] : criteria; diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index 02f2287..7161acd 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -94,9 +94,8 @@ class orderServer extends MainService { switch (orderType.method) { case 'ORDER': return this.success('取消订单成功'); - break; - case 'RK' : - console.log(data, info); + case 'RK': + { const existingOrder = await ctx.model.EntryOrder.findOne({ where: { entry_order_code: data.request.orderCode, @@ -112,39 +111,30 @@ class orderServer extends MainService { return this.success('取消入库单成功'); } return this.fail('未找到对应的入库单'); - break; - case 'CK' : + } + case 'CK': return this.fail('取消出库单未开发完成'); - break; - case 'JG' : + case 'JG': return this.fail('取消加工单未开发完成'); - break; case 'BACKORDER': return this.fail('取消退货单未开发完成'); - break; default: return this.fail(`未识别的作业类型${orderType.method}`, {}); } } async pending(data) { - console.log(data); const orderType = this.orderType[data.request.orderType]; switch (orderType.method) { case 'ORDER': return this.fail('锁定订单未开发完成'); - break; - case 'RK' : + case 'RK': return this.fail('锁定入库单未开发完成'); - break; - case 'CK' : + case 'CK': return this.fail('锁定出库单未开发完成'); - break; - case 'JG' : + case 'JG': return this.fail('锁定加工单未开发完成'); - break; case 'BACKORDER': return this.fail('锁定退货单未开发完成'); - break; default: return this.fail(`未识别的作业类型${orderType.method}`, {}); } diff --git a/app/service/qimenMethods/returnorder.js b/app/service/qimenMethods/returnorder.js index af8d247..d271ad5 100644 --- a/app/service/qimenMethods/returnorder.js +++ b/app/service/qimenMethods/returnorder.js @@ -6,13 +6,13 @@ class returnorderServer extends MainService { /* 退货入库创建接口 */ - async create(data) { + async create() { return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId }); } /* 退货入库查询接口 */ - async query(data) { + async query() { return this.fail('接口未完善', { result: 'singleitemServer', storeId: this.storeId }); } } diff --git a/app/service/qimenMethods/singleitem.js b/app/service/qimenMethods/singleitem.js index f14c2f9..1bd411e 100644 --- a/app/service/qimenMethods/singleitem.js +++ b/app/service/qimenMethods/singleitem.js @@ -4,11 +4,8 @@ const MainService = require('../main'); class singleitemServer extends MainService { async synchronize(data) { - const { app } = this; try { - console.log('data', data); const stockData = await this.ctx.service.systems.stockStore.initQimenStockData(data.request, this.appKey, this.storeId, this.warehouseId); - console.log('stockData', stockData); const result = await await this.ctx.service.systems.stockStore.create(stockData); return this.success('同步完成', { itemId: result.id }); } catch (error) { diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index 9eb0827..a5fdb49 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -5,7 +5,9 @@ const MainService = require('../main'); class stockoutServer extends MainService { async create(data) { - const { app } = this; + const { app, ctx, appKey, storeId, warehouseId, customerId, warehouseCode } = this; + const fail = this.fail.bind(this); + const success = this.success.bind(this); let totalOrderLines = data.request.deliveryOrder.totalOrderLines || 0; @@ -13,7 +15,6 @@ class stockoutServer extends MainService { if (orderLine.orderLineNo) { orderLine = [ orderLine ]; } - const isSingle = totalOrderLines ? 0 : 1; totalOrderLines = totalOrderLines || orderLine.length; const errors = []; const items = []; @@ -33,39 +34,37 @@ class stockoutServer extends MainService { wms_stock.item_id = orderLine[i].itemId; items.push(wms_stock); } - console.log('出库单参数:', data.request.deliveryOrder, this.appKey, this.storeId, this.warehouseId, totalOrderLines, 'QM', this.customerId, this.warehouseCode); - console.log('出库单明细:', items); if (errors.length > 0) { return this.fail('创建入库单失败,失败原因:\n' + errors.join('\n')); } - /* const order = await this.ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder,this.appKey, this.storeId, this.warehouseId,totalOrderLines,"QM",this.customerId,this.warehouseCode); - console.log("入库单参数",order); - if(!order.success){ - return this.fail("创建入库单失败,失败原因:\n"+order.error); - } - const orderId = order.deliveryOrderId; - for (var i = 0; i < items.length; i++) { - const item = items[i]; - let res = await this.ctx.service.systems.deliveryOrder.addItems(item,orderId); - console.log("“添加商品返回信息",res); - if(!res.success){ - errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); - } - } - if(errors.length>0){ - await app.model.deliveryOrder.delete(orderId);//失败删除; - return this.fail("创建入库单失败,失败原因:\n"+errors.join("\n")); - } - const lineCount = await this.ctx.service.systems.deliveryOrder.getLineCount(orderId);//获取接收行数 - if(lineCount==totalOrderLines){//所有行数接收完成 - await this.ctx.service.systems.deliveryOrder.received(orderId,this.warehouseId,this.storeId);//接收完成 - return this.success("入库单接收完毕",{deliveryOrderId:orderId}); - }*/ - return this.success('入库单接收中'); + const order = await ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder, appKey, storeId, warehouseId, totalOrderLines, 'QM', customerId, warehouseCode); + if (!order.success) { + return fail('创建入库单失败,失败原因:\n' + order.error); + } + const orderId = order.deliveryOrderId; + for (let i = 0; i < items.length; i++) { + const item = items[i]; + const res = await ctx.service.systems.deliveryOrder.addItems(item, orderId); + if (!res.success) { + errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); + } + } + if (errors.length > 0) { + // 失败删除; + await ctx.model.deliveryOrder.delete(orderId); + return fail('创建入库单失败,失败原因:\n' + errors.join('\n')); + } + const lineCount = await ctx.service.systems.deliveryOrder.getLineCount(orderId); // 获取接收行数 + // 所有行数接收完成 + if (lineCount === totalOrderLines) { + await ctx.service.systems.deliveryOrder.received(orderId, warehouseId, storeId); // 接收完成 + return success('入库单接收完毕', { deliveryOrderId: orderId }); + } + return success('入库单接收中'); } - async query(data) { - console.log(data); - return this.fail('接口未完善'); + async query() { + const { fail } = this; + return fail('接口未完善'); } } diff --git a/app/service/qimenMethods/taobao/qimen/service.js b/app/service/qimenMethods/taobao/qimen/service.js index 5721bec..4e5dab9 100644 --- a/app/service/qimenMethods/taobao/qimen/service.js +++ b/app/service/qimenMethods/taobao/qimen/service.js @@ -1,14 +1,17 @@ 'use strict'; -const MainService = require(`${APP_ROOT}/app/service/main`); +const MainService = require('../../../main'); class serviceServer extends MainService { + /** + * @param {*} data 奇门心跳传入解构 + * @return {Promise} 返回心跳信息 + */ async heartbeat(data) { - console.log(data); if (data?.request?.serialNumber) { - return this.success(new Date().format(), { code: data.request.serialNumber }); + return this.success(this.app.formatDate(new Date()), { code: data.request.serialNumber }); } - return this.fail(new Date().format(), { code: 0 }); + return this.fail(this.app.formatDate(new Date()), { code: 0 }); } } diff --git a/app/service/system.js b/app/service/system.js index 3b1ccad..b3aed28 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -1,7 +1,6 @@ 'use strict'; const Service = require('egg').Service; -const { XMLParser } = require('fast-xml-parser'); const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]); // project: all=全部, warehouse=仓库, store=货主, tms=物流 @@ -10,8 +9,6 @@ const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 's class systemService extends Service { async callMethod(className, actionName, requestData, authHeader) { try { - - // 构建服务类路径 const servicePath = `${className}`; const classs = servicePath.split('.'); @@ -41,7 +38,7 @@ class systemService extends Service { // 调用方法 const authPass = await serviceInstance.checkAuth(servicePath, actionName, authHeader); const isLog = authPass.isLog; - if (authPass.status == 200) { + if (authPass.status === 200) { result.data = await serviceInstance[actionName](requestData); result.status = 200; diff --git a/app/service/systemMethods/config.js b/app/service/systemMethods/config.js index fd57921..849e9b0 100644 --- a/app/service/systemMethods/config.js +++ b/app/service/systemMethods/config.js @@ -12,7 +12,6 @@ class configService extends MainService { async list() { const { ctx, - app, } = this; const user = ctx.user; const result = { diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index f9841c9..82f4f68 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -6,9 +6,9 @@ class indexService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace'; + const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes'; const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace'; + const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -17,7 +17,7 @@ class indexService extends MainService { const result = await service.systems.fastWhere.getTreeByType(type); return this.success('ok', { presetTree: result, code: 200 }); } - async loadStores(data) { + async loadStores() { const { service } = this; const result = await service.systems.store.loadStores(); return this.success('ok', { stores: result, code: 200 }); @@ -276,7 +276,7 @@ class indexService extends MainService { /** * 从键名提取模块 - * @param keyName + * @param {string} keyName 键名 */ extractModule(keyName) { if (!keyName) return 'common'; @@ -294,8 +294,8 @@ class indexService extends MainService { /** * 尝试自动翻译新键值(可选功能) - * @param project - * @param targetLanguage + * @param {string} project 项目 + * @param {string} targetLanguage 目标语言 */ async tryAutoTranslateNewKeys(project, targetLanguage) { const { ctx } = this; @@ -337,7 +337,7 @@ class indexService extends MainService { // 批量创建未翻译的记录 const createPromises = []; - for (const [ keyId, chineseText ] of Object.entries(chineseTranslations)) { + for (const [ keyId ] of Object.entries(chineseTranslations)) { if (!existingKeyIds.has(parseInt(keyId))) { createPromises.push( ctx.model.I18nTranslation.create({ @@ -366,7 +366,27 @@ class indexService extends MainService { const result = await service.systems.space.searchSpace(data); return this.success('ok', result); } - async getExpressList(data) { + async listInterfaceTypes() { + const { ctx } = this; + const rows = await ctx.model.InterfaceType.findAll({ + where: { is_enabled: 1, is_store: 1 }, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'description', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + }); + const list = rows.map(row => { + const item = row.get({ plain: true }); + return { + id: Number(item.id || 0), + interface_code: item.interface_code || '', + interface_name: item.interface_name || '', + interface_category: item.interface_category || '', + description: item.description || '', + is_enabled: Number(item.is_enabled || 0), + }; + }); + return this.success('ok', { list, total: list.length, code: 200 }); + } + async getExpressList() { return this.success('ok', { data: this.app.config.expressList, code: 200 }); } diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 302f241..7195169 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -32,7 +32,6 @@ class PrintService extends MainService { const { ctx } = this; const warehouseId = ctx.user.store_id; const { printer, type, template, data, computerId, timestamp, count } = _data; - console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count); // 生成打印编号并记录到数据库 const printRecord = await ctx.model.PrintRecord.create({ warehouse_id: warehouseId, @@ -52,12 +51,10 @@ class PrintService extends MainService { let content = item.content; for (const key in data) { - console.log('正在匹配字段:', key, '与', item.field_code); if (String(item.field_code) === key) { content = data[key]; } } - console.log('转后的内容:', content); switch (item.type) { case 'text': htm += `
{ const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; const componentInfo = await this.app.redis.get('printer').get(componentKey); - console.log('componentKey and componentInfo', componentKey, componentInfo); if (componentInfo && componentInfo === 'connected') { component.is_online = 1; } @@ -389,7 +380,6 @@ class PrintService extends MainService { const { id } = data; if (!id) return this.fail('参数错误', 1001); const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`); - console.log('getComputerPrinter printerListResult', printerListResult); const printerList = JSON.parse(printerListResult); let printers = []; if (!printerList || !printerList.data || printerList.data.length === 0) { diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js index a1be451..9230e74 100644 --- a/app/service/systemMethods/setting/account.js +++ b/app/service/systemMethods/setting/account.js @@ -26,7 +26,7 @@ class accountService extends MainService { /** * 账号列表。 - * @param {*} data + * @param {Object} data 请求体 */ async list(data = {}) { const { service } = this; @@ -64,7 +64,7 @@ class accountService extends MainService { /** * 新增工号。 - * @param {*} data + * @param {Object} data 请求体 */ async add(data = {}) { return this.callSystemAccount('add', data, '添加工号失败'); @@ -72,7 +72,7 @@ class accountService extends MainService { /** * 删除工号。 - * @param {*} data + * @param {Object} data 请求体 */ async delete(data = {}) { return this.callSystemAccount('delete', data, '删除工号失败'); @@ -80,7 +80,7 @@ class accountService extends MainService { /** * 更新工号。 - * @param {*} data + * @param {Object} data 请求体 */ async update(data = {}) { return this.callSystemAccount('update', data, '更新工号失败'); @@ -88,7 +88,7 @@ class accountService extends MainService { /** * 为其他账号获取微信绑定码。 - * @param {*} data + * @param {Object} data 请求体 */ async getBindWechatCode(data = {}) { return this.callSystemAccount('getBindWechatCode', data, '获取账号绑定微信码失败'); @@ -96,7 +96,7 @@ class accountService extends MainService { /** * 为其他账号解绑微信。 - * @param {*} data + * @param {Object} data 请求体 */ async unbindWechat(data = {}) { return this.callSystemAccount('unbindWechat', data, '解绑账号微信失败'); diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js index c6159ee..66a9a63 100644 --- a/app/service/systemMethods/setting/permission.js +++ b/app/service/systemMethods/setting/permission.js @@ -26,7 +26,7 @@ class permissionService extends MainService { /** * 权限列表。 - * @param {*} data + * @param {Object} data 请求体 */ async list(data = {}) { return this.callSystemPermission('list', data, '获取权限列表失败'); @@ -34,7 +34,7 @@ class permissionService extends MainService { /** * 新增权限。 - * @param {*} data + * @param {Object} data 请求体 */ async add(data = {}) { return this.callSystemPermission('add', data, '新增权限失败'); @@ -42,7 +42,7 @@ class permissionService extends MainService { /** * 删除权限。 - * @param {*} data + * @param {Object} data 请求体 */ async delete(data = {}) { return this.callSystemPermission('delete', data, '删除权限失败'); @@ -50,7 +50,7 @@ class permissionService extends MainService { /** * 更新权限。 - * @param {*} data + * @param {Object} data 请求体 */ async update(data = {}) { return this.callSystemPermission('update', data, '更新权限失败'); diff --git a/app/service/systemMethods/setting/printTemplate.js b/app/service/systemMethods/setting/printTemplate.js index 3f545ab..67f6ed1 100644 --- a/app/service/systemMethods/setting/printTemplate.js +++ b/app/service/systemMethods/setting/printTemplate.js @@ -11,13 +11,12 @@ class printTemplateService extends MainService { const _noNeedAuth = 'list,save,create,delete,listTemplatesByType'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - async list(data) { + async list() { const { service } = this; const result = await service.systems.setting.printTemplate.getTree(); return this.success('ok', { presetTree: result, code: 200 }); } async save(data) { - console.log('接收到保存请求:', data); const { service } = this; const result = await service.systems.setting.printTemplate.save(data); return this.success('ok', result); @@ -70,7 +69,6 @@ class printTemplateService extends MainService { } async listTemplatesByType(data) { const { service } = this; - console.log('接收到根据业务类型查询模板请求:', data); const { businessType } = data; if (!businessType) { throw new Error('缺少业务类型参数'); diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js index f036b54..7fa3469 100644 --- a/app/service/systemMethods/setting/role.js +++ b/app/service/systemMethods/setting/role.js @@ -26,26 +26,23 @@ class roleService extends MainService { /** * 角色列表。 - * @param {*} data + * @param {*} data 请求参数 */ async list(data = {}) { return this.callSystemRole('list', data, '获取角色列表失败'); } /** -<<<<<<< HEAD * 角色权限列表(兼容旧入口)。 - * @param {*} data + * @param {*} data 请求参数 */ async permission(data = {}) { return this.callSystemRole('permission', data, '获取角色权限列表失败'); } /** -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 * 新增角色。 - * @param {*} data + * @param {*} data 请求参数 */ async add(data = {}) { return this.callSystemRole('add', data, '新增角色失败'); @@ -53,7 +50,7 @@ class roleService extends MainService { /** * 删除角色。 - * @param {*} data + * @param {*} data 请求参数 */ async delete(data = {}) { return this.callSystemRole('delete', data, '删除角色失败'); @@ -61,7 +58,7 @@ class roleService extends MainService { /** * 更新角色。 - * @param {*} data + * @param {*} data 请求参数 */ async update(data = {}) { return this.callSystemRole('update', data, '更新角色失败'); diff --git a/app/service/systemMethods/setting/store_warehouse.js b/app/service/systemMethods/setting/store_warehouse.js index c6442c6..3d19407 100644 --- a/app/service/systemMethods/setting/store_warehouse.js +++ b/app/service/systemMethods/setting/store_warehouse.js @@ -2,59 +2,13 @@ const MainService = require('../../main'); -class storeWarehouseService extends MainService { +// 旧兼容入口 `setting.store_warehouse.*` 已下线; +// 保留空服务壳体,确保调用时在 dispatcher 层直接返回“方法不存在”。 +class StoreWarehouseLegacyService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,unbind,rename'; - const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,unbind,rename'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - } - - async callSystemStoreWarehouse(methodName, data, defaultMessage) { - const { service } = this; - try { - const result = await service.systems.storeWarehouse[methodName](data); - return this.success('ok', result); - } catch (error) { - return this.fail(error.message || defaultMessage, { - code: Number(error.code) || 500, - }); - } - } - - /** - * 仓库-货主签约列表。 - * @param {*} data - */ - async list(data = {}) { - return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); - } - - /** - * 建立/更新签约关系。 - * @param {*} data - */ - async sign(data = {}) { - return this.callSystemStoreWarehouse('sign', data, '签约失败'); - } - - /** - * 修改当前主体对签约对象的名称/备注。 - * @param {*} data - */ - async rename(data = {}) { - return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); - } - - /** - * 解除签约关系。 - * @param {*} data - */ - async unbind(data = {}) { - return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + this.systemInit('', '', '*', ''); } } -module.exports = storeWarehouseService; +module.exports = StoreWarehouseLegacyService; diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 894b83a..5fdf65a 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -6,9 +6,9 @@ class WarehouseService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search'; - const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; - const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search'; + const _noNeedRight = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail'; + const _noNeedLog = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; + const _noNeedAuth = 'list,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -154,7 +154,6 @@ class WarehouseService extends MainService { async checkItemCodeUnique(data) { const { ctx, service } = this; const { id, item_code, store_id } = data; - console.log(data); try { if (!item_code || !store_id) { return this.fail('参数错误'); @@ -172,7 +171,6 @@ class WarehouseService extends MainService { * @return {Promise} data 为日志分页结果 */ async queryStockLogs(data) { - console.log('请求'); const { ctx } = this; try { const { service } = this; @@ -180,7 +178,6 @@ class WarehouseService extends MainService { const result = await service.systems.operationLog.queryStockLogs(data); return this.success('ok', { data: result, code: 200 }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -196,7 +193,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.handleBatchDelete(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -212,7 +208,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.deleteUnit(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -228,7 +223,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.deleteProhibited(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 200 }); } } @@ -244,7 +238,6 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.handleBatchChange(data); return this.success(result.message, { data: result.data, code: result.code }); } catch (e) { - console.log(e); return this.success(e.message, { code: 405 }); } } @@ -254,7 +247,6 @@ class WarehouseService extends MainService { * @return {Promise} data 为单位数组 */ async getStockUnits() { - console.log('query_getStockUnits'); const { ctx } = this; const warehouse_id = ctx.user.store_id; @@ -275,7 +267,6 @@ class WarehouseService extends MainService { }); return this.success('ok', { data: units, code: 200 }); } catch (error) { - console.log(error); return this.fail(error.message); } } @@ -285,7 +276,6 @@ class WarehouseService extends MainService { * @return {Promise} data 为单位数组 */ async getUnitList() { - console.log('query_getUnitList'); const { ctx } = this; const warehouse_id = ctx.user.store_id; @@ -303,7 +293,6 @@ class WarehouseService extends MainService { }); return this.success('ok', { data: units, code: 200 }); } catch (error) { - console.log(error); return this.fail(error.message); } } @@ -315,7 +304,6 @@ class WarehouseService extends MainService { * @return {Promise} 成功返回 success;参数校验失败时直接写入 ctx.body */ async createProhibited(data) { - console.log('createProhibited', data); const { ctx } = this; const warehouse_id = ctx.user.store_id || null; const { name } = data; @@ -385,7 +373,6 @@ class WarehouseService extends MainService { }); return this.success('添加成功', { code: 200 }); } catch (error) { - console.log(error); return this.success('创建违禁品类型失败', { code: 405 }); } } @@ -478,6 +465,19 @@ class WarehouseService extends MainService { const result = await service.systems.stockStore.search(data); return this.success('ok', result); } + + /** + * 查询商品库存明细(按库位/批次维度展示库存分布)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品库存ID(stock_warehouse.id) + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} data 为库存明细分页结果 + */ + async getStockDetail(data) { + const { service } = this; + const result = await service.systems.stockStore.getStockDetail(data); + return this.success('ok', result); + } } module.exports = WarehouseService; diff --git a/app/service/systemMethods/storage/delivery.js b/app/service/systemMethods/storage/delivery.js new file mode 100644 index 0000000..90dda57 --- /dev/null +++ b/app/service/systemMethods/storage/delivery.js @@ -0,0 +1,35 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.delivery(已废弃)。 + */ +class StorageDeliveryService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = ''; + const _noNeedLog = ''; + const _noNeedAuth = ''; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + buildRemovedResponse() { + return this.fail('方法已移除', { code: 410 }); + } + + async list() { + return this.buildRemovedResponse(); + } + + async toOrder() { + return this.buildRemovedResponse(); + } + + async listItems() { + return this.buildRemovedResponse(); + } +} + +module.exports = StorageDeliveryService; diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index 0880a02..8350116 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; - const _noNeedLog = 'list,get,addDetail,deleteDetail,detailChange'; - const _noNeedAuth = 'list,get,create,addDetail,deleteDetail,detailChange,cancel,completeEntry'; + const _noNeedRight = 'list,get,cancel,completeEntry'; + const _noNeedLog = 'list,get'; + const _noNeedAuth = 'list,get,cancel,completeEntry'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -50,50 +50,6 @@ class entryService extends MainService { return this.success('ok', result); } - /** - * 新建入库单。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async create(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.create(data); - return this.success('ok', result); - } - - /** - * 新增入库明细。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async addDetail(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.addDetail(data); - return this.success('ok', result); - } - - /** - * 删除入库明细。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async deleteDetail(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.deleteDetail(data); - return this.success('ok', result); - } - - /** - * 修改入库明细。 - * @param {Object} data 请求体 - * @return {Promise} 统一 success 包装 - */ - async detailChange(data = {}) { - const { service } = this; - const result = await service.systems.storage.entry.detailChange(data); - return this.success('ok', result); - } - /** * 作废入库单。 * @param {Object} data 请求体 diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js new file mode 100644 index 0000000..b3f0df8 --- /dev/null +++ b/app/service/systemMethods/storage/inventory.js @@ -0,0 +1,91 @@ +'use strict'; + +const MainService = require('../../main'); + +/** + * 系统方法层:storage.inventory(库存操作接口包装层)。 + * 职责:统一包装库存操作接口,调用底层 systems/storage/inventory service。 + */ +class InventoryMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'matchPutaway,list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 收货单快捷入库上架。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID + * @return {Promise} 统一 success 包装 + */ + async quickPutaway(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.quickPutaway(data); + return this.success('ok', result); + } + + /** + * 匹配入库:收货单与入库单按商品匹配入库。 + * @param {Object} data 请求体 + * @param {number[]} data.receiving_ids 收货单ID列表 + * @param {number[]} data.entry_order_ids 入库单ID列表 + * @return {Promise} 统一 success 包装 + */ + async matchPutaway(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.matchPutaway(data); + return this.success('ok', result); + } + + /** + * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} [data.quantity] 移库数量(可选,默认全部移动) + * @return {Promise} 统一 success 包装 + */ + async transferLocation(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.transferLocation(data); + return this.success('ok', result); + } + + /** + * 按库位+商品维度移库:自动查找该库位下该商品的所有库存记录,合并移动到目标库位。 + * @param {Object} data 请求体 + * @param {number} data.space_id 原库位ID(必填) + * @param {number} data.stock_id 商品SKU ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} data.quantity 移库数量(必填) + * @return {Promise} 统一 success 包装 + */ + async transferByProduct(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.transferByProduct(data); + return this.success('ok', result); + } + + /** + * 库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @param {boolean} [data.group_by_batch=false] 是否按批次查询 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort, group_by_batch } = data; + const { where } = this.prepareWhereContext(data); + const result = await service.systems.storage.inventory.getInventoryList(where, pagination, sort, group_by_batch); + return this.success('ok', result); + } +} + +module.exports = InventoryMethodService; diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js new file mode 100644 index 0000000..7a132d4 --- /dev/null +++ b/app/service/systemMethods/storage/stockout.js @@ -0,0 +1,79 @@ +'use strict'; + +const OrderBaseService = require('../order/base'); + +/** + * 系统方法层:storage.stockout(非订单出库单接口包装层)。 + */ +class StorageStockoutService extends OrderBaseService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,toOrder,listItems'; + const _noNeedLog = 'list,toOrder,listItems'; + const _noNeedAuth = 'list,toOrder,listItems'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async list(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel } = await this.getOrderModels(warehouseId); + this.prepareWhereContext(data); + const whereData = this.ctx.where || {}; + const where = this.buildWhere(whereData, warehouseId); + const { page, pageSize, offset } = this.getPagination(data.pagination); + + const result = await DeliveryModel.findAndCountAll({ + where, + offset, + limit: pageSize, + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + raw: true, + }); + + return this.success('ok', { + data: this.buildListData(result.rows, result.count, page, pageSize), + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } + + async toOrder() { + return this.fail('占位接口,暂未开放', { code: 405, placeholder: true }); + } + + async listItems(data = {}) { + try { + const warehouseId = this.ensureWarehouseId(data); + const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId); + const where = this.getOrderLocatorWhere(data, warehouseId); + + const order = await DeliveryModel.findOne({ + where, + attributes: [ 'id', 'delivery_order_code' ], + raw: true, + }); + if (!order) { + return this.fail('订单不存在', { code: 404 }); + } + + const items = await OrderItemsModel.findAll({ + where: { order_id: order.id }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + return this.success('ok', { + data: { order, items }, + code: 200, + }); + } catch (error) { + return this.fail(error.message, { code: 500 }); + } + } +} + +module.exports = StorageStockoutService; diff --git a/app/service/systemMethods/storage/transaction.js b/app/service/systemMethods/storage/transaction.js new file mode 100644 index 0000000..ff0781c --- /dev/null +++ b/app/service/systemMethods/storage/transaction.js @@ -0,0 +1,33 @@ +'use strict'; + +const MainService = require('../../main'); + +class StorageTransactionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list'; + const _noNeedLog = 'list'; + const _noNeedAuth = 'list'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 出入库记录列表查询,支持 where 条件、分页、排序。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.pagination] 分页参数 { page, pageSize } + * @param {Object} [data.sort] 排序参数 { sortField, sortOrder } + * @param {boolean} [data.group_by_batch=false] 是否按批次查询明细 + * @return {Promise} 统一 success 包装 + */ + async list(data = {}) { + const { service } = this; + const { pagination, sort, group_by_batch } = data; + const { where } = this.prepareWhereContext(data); + const result = await service.systems.stockTransaction.list(where, pagination, sort, group_by_batch); + return this.success('ok', result); + } +} + +module.exports = StorageTransactionService; diff --git a/app/service/systemMethods/store.js b/app/service/systemMethods/store.js index 25b66ff..67bcfe4 100644 --- a/app/service/systemMethods/store.js +++ b/app/service/systemMethods/store.js @@ -35,11 +35,6 @@ class storeService extends MainService { const result = await service.systems.store.getStoreRoles(data); return this.success('ok', result); } - async getStoreRoles(data) { - const { service } = this; - const result = await service.systems.store.getStoreRoles(data); - return this.success('ok', result); - } async auditApply(data) { const { service } = this; const result = await service.systems.store.auditApply(data); diff --git a/app/service/systemMethods/storeWarehouse.js b/app/service/systemMethods/storeWarehouse.js index 761210a..db6e15f 100644 --- a/app/service/systemMethods/storeWarehouse.js +++ b/app/service/systemMethods/storeWarehouse.js @@ -1,65 +1,14 @@ 'use strict'; const MainService = require('../main'); +const StoreWarehouseStoreService = require('./storeWarehouse/store'); -class storeWarehouseAliasService extends MainService { +class StoreWarehouseNamespaceService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = ''; - const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; - const _noNeedLog = '*'; - const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - this.store = this; - } - - async callSystemStoreWarehouse(methodName, data, defaultMessage) { - const { service } = this; - try { - const result = await service.systems.storeWarehouse[methodName](data); - return this.success('ok', result); - } catch (error) { - return this.fail(error.message || defaultMessage, { - code: Number(error.code) || 500, - }); - } - } - - async list(data = {}) { - return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); - } - - async sign(data = {}) { - return this.callSystemStoreWarehouse('sign', data, '签约失败'); - } - - async rename(data = {}) { - return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); - } - - async unbind(data = {}) { - return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); - } - - async getPolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); - } - - async savePolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); - } - - async listQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('listQimenConfig', data, '获取奇门接口配置列表失败'); - } - - async saveQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('saveQimenConfig', data, '保存奇门接口配置失败'); - } - - async deleteQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除奇门接口配置失败'); + this.systemInit('', '', '*', ''); + this.store = new StoreWarehouseStoreService(ctx); } } -module.exports = storeWarehouseAliasService; +module.exports = StoreWarehouseNamespaceService; diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index c012bd3..c4a7635 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -1,3 +1,72 @@ 'use strict'; -module.exports = require('../storeWarehouse'); +const MainService = require('../../main'); + +class StoreWarehouseStoreService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,getPolicyConfigFields,savePolicyConfig,listApiConfig,saveApiConfig,deleteQimenConfig'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemStoreWarehouse(methodName, data = {}, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.storeWarehouse[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + async list(data = {}) { + return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); + } + + async sign(data = {}) { + return this.callSystemStoreWarehouse('sign', data, '签约失败'); + } + + async rename(data = {}) { + return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + } + + async unbind(data = {}) { + return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + } + + async adjustPrintQuantity(data = {}) { + return this.callSystemStoreWarehouse('adjustPrintQuantity', data, '人工调整面单余额失败'); + } + + async getPolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); + } + + async getPolicyConfigFields(data = {}) { + return this.callSystemStoreWarehouse('getPolicyConfigFields', data, '获取合约策略字段信息失败'); + } + + async savePolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); + } + + async listApiConfig(data = {}) { + return this.callSystemStoreWarehouse('listApiConfig', data, '获取接口配置列表失败'); + } + + async saveApiConfig(data = {}) { + return this.callSystemStoreWarehouse('saveApiConfig', data, '保存接口配置失败'); + } + + async deleteQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除接口配置失败'); + } +} + +module.exports = StoreWarehouseStoreService; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 2de6096..b2afa4f 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -15,7 +15,6 @@ class userService extends MainService { const { service } = this; const { username, password } = data; const result = await service.systems.auth.user.login(username, password); - console.log('result', result); if (result.code) { return this.success('登录成功', result); } @@ -25,7 +24,6 @@ class userService extends MainService { async loginByCode(data) { const { service } = this; const code = typeof data?.code === 'string' ? data.code.trim() : ''; - console.log('code', data.code, code); if (!code) { return this.fail('1111登录失败:缺少登录码 code', { success: false, @@ -56,14 +54,6 @@ class userService extends MainService { } return this.fail('获取微信登录码失败:' + result.message, result); } - async getLoginWechatCode(data) { - const { service } = this; - const result = await service.systems.auth.user.getLoginWechatCode(data); - if (result.code) { - return this.success('获取微信登录码成功', result); - } - return this.fail('获取微信登录码失败:' + result.message, result); - } async unbindWechat(data) { const { service } = this; const result = await service.systems.auth.user.unbindWechat(data); diff --git a/app/service/systemMethods/warehouse.js b/app/service/systemMethods/warehouse.js index e053bb1..2e14924 100644 --- a/app/service/systemMethods/warehouse.js +++ b/app/service/systemMethods/warehouse.js @@ -13,22 +13,20 @@ class warehouseService extends MainService { } async getWarehouseZones() { const { ctx, service } = this; - console.log('获取仓库主体下所有实体仓库'); try { const zones = await service.systems.locationZone.getWarehouseLevelZones(ctx.user.store_id); return this.success('获取成功', { zones, code: 200 }); } catch (error) { - console.log(error); return this.fail('获取失败' + error.message, { code: 0 }); } } /** * 获取仓库树状结构 - * @param data + * @param {Object} data 请求体 */ async getWarehouseTree(data) { - const { ctx, service } = this; + const { service } = this; const { warehouseId } = data; try { @@ -45,7 +43,7 @@ class warehouseService extends MainService { /** * 获取子节点(懒加载) - * @param data + * @param {Object} data 请求体 */ async getChildren(data) { const { ctx, service } = this; @@ -65,10 +63,10 @@ class warehouseService extends MainService { /** * 创建分区 - * @param data + * @param {Object} data 请求体 */ async create(data) { - const { ctx, service } = this; + const { service } = this; try { const result = await service.systems.locationZone.createZone(data); @@ -80,19 +78,18 @@ class warehouseService extends MainService { /** * 更新分区 - * @param datas + * @param {Object} datas 请求体 */ async update(datas) { - const { ctx, service } = this; - console.log('接收的数据', datas); + const { service } = this; const { id } = datas; - const { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas; + const { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles } = datas; try { if (!id) { return this.fail('分区ID不能为空'); } - const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles }); + const result = await service.systems.locationZone.updateZone(parseInt(id), { length, width, height, is_active, zone_code, zone_name, x, y, z, direction, rack_columns, rack_levels, rack_rows, cell_width, cell_length, cell_height, aisles }); return this.success(result.message, { data: result.data, code: 200 }); } catch (error) { return this.fail(error.message); @@ -101,10 +98,10 @@ class warehouseService extends MainService { /** * 删除分区 - * @param data + * @param {Object} data 请求体 */ async delete(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { @@ -113,20 +110,18 @@ class warehouseService extends MainService { } const result = await service.systems.locationZone.deleteZone(parseInt(id)); - console.log('删除返回', result); return this.success(result.message, { code: 200 }); } catch (error) { - console.log('error', error); return this.fail(error.message); } } /** * 获取分区详情 - * @param data + * @param {Object} data 请求体 */ async detail(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { @@ -140,9 +135,8 @@ class warehouseService extends MainService { } } async checkBarcodeUnique(data) { - const { ctx, service } = this; + const { service } = this; const { id, barcode } = data; - console.log(data); try { if (!id) { return this.fail('库位ID不能为空'); @@ -158,7 +152,7 @@ class warehouseService extends MainService { } /** * 切换分区状态 - * @param data + * @param {Object} data 请求体 */ async toggleActive(data) { const { ctx, service } = this; @@ -181,7 +175,7 @@ class warehouseService extends MainService { /** * 获取分区路径 - * @param data + * @param {Object} data 请求体 */ async getPath(data) { const { ctx, service } = this; @@ -374,7 +368,7 @@ class warehouseService extends MainService { } } async createRackWithSpaces(data) { - const { ctx, app, service } = this; + const { ctx, service } = this; const { id } = data; if (!id) { return this.fail('货架ID不能为空'); @@ -391,34 +385,31 @@ class warehouseService extends MainService { if (!rack) { throw new Error('货架不存在'); } - if (rack.zone_type != 'rack') { + if (rack.zone_type !== 'rack') { throw new Error('仓库元素不为货架,拒绝生成仓位'); } const message = await service.systems.locationZone.generateSpacesForRack(id, rack, transaction); await transaction.commit(); return this.success(message, { code: 200 }); } catch (e) { - console.log('创建错误', e); await transaction.rollback(); return this.fail(e.message, 500); } } async getSpaceInfo(data) { - const { ctx, service } = this; + const { service } = this; const { id } = data; try { const data = await service.systems.locationZone.getSpaceInfo(id); return this.success('获取成功', { data, code: 200 }); } catch (error) { - console.log(error); return this.fail('获取失败' + error.message, { code: 0 }); } } async updateSpaceInfo(data) { - const { ctx, app, service } = this; - console.log('修改的数据', data); + const { ctx, service } = this; const { id } = data; if (!id) { return this.fail('仓位ID不能为空'); diff --git a/app/service/systems/account_platform.js b/app/service/systems/account_platform.js index bcab6b9..fb0fd34 100644 --- a/app/service/systems/account_platform.js +++ b/app/service/systems/account_platform.js @@ -71,7 +71,7 @@ class AccountPlatformService extends Service { * @param {number} accountId - 账号ID * @param {number} accountStoreRoleId - 账号仓库员工关联ID(保持历史参数名兼容) * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 切换结果 */ async switchActiveRole(accountId, accountStoreRoleId, platformCode) { const { ctx } = this; @@ -150,7 +150,7 @@ class AccountPlatformService extends Service { * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 * @param {boolean} useCache - 是否使用缓存 - * @return {Promise} + * @return {Promise} 当前激活角色 */ async getActiveRoleByPlatform(accountId, platformCode, useCache = true) { const { ctx, app } = this; @@ -201,7 +201,7 @@ class AccountPlatformService extends Service { * 批量获取账号在多个平台的激活状态 * @param {number} accountId - 账号ID * @param {Array} platformCodes - 平台编码数组 - * @return {Promise} + * @return {Promise} 激活状态映射 */ async getMultiplePlatformActiveRoles(accountId, platformCodes) { const { ctx } = this; @@ -243,7 +243,7 @@ class AccountPlatformService extends Service { /** * 获取账号所有平台的激活状态 * @param {number} accountId - 账号ID - * @return {Promise} + * @return {Promise} 平台激活列表 */ async getAllPlatformActives(accountId) { const { ctx } = this; @@ -274,10 +274,10 @@ class AccountPlatformService extends Service { * 清除平台激活状态 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 是否清除成功 */ async clearPlatformActive(accountId, platformCode) { - const { ctx, app } = this; + const { ctx } = this; try { const result = await ctx.model.AccountPlatformActive.destroy({ @@ -298,8 +298,8 @@ class AccountPlatformService extends Service { /** * 清理平台缓存 - * @param accountId - * @param platformCode + * @param {number} accountId 账号ID + * @param {string} platformCode 平台编码 * @private */ async clearPlatformCache(accountId, platformCode) { @@ -317,7 +317,7 @@ class AccountPlatformService extends Service { * 获取账号可用的角色列表 * @param {number} accountId - 账号ID * @param {number} storeId - 仓库ID(可选) - * @return {Promise} + * @return {Promise} 角色列表,包含角色信息和所属仓库信息 */ async getAvailableRoles(accountId, storeId = null) { const { ctx } = this; @@ -390,7 +390,7 @@ class AccountPlatformService extends Service { * 根据平台获取账号的当前仓库和角色 * @param {number} accountId - 账号ID * @param {string} platformCode - 平台编码 - * @return {Promise} + * @return {Promise} 当前上下文 */ async getCurrentContext(accountId, platformCode) { const activeRole = await this.getActiveRoleByPlatform(accountId, platformCode); diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 76c94b1..e4db6bb 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -16,10 +16,6 @@ const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { - constructor(ctx) { - super(ctx); - } - getCurrentAccountId() { const { ctx } = this; const rawUserId = ctx.userId || (ctx.user && ctx.user.id); @@ -266,7 +262,44 @@ class UserService extends Service { let settled = false; let timer = null; - const cleanup = () => { + function onMessage(messageChannel, message) { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = { raw: message }; + } + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + }); + } + + function onError(error) { + app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + }); + } + + function finalize(result) { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + } + + function cleanup() { subscriber.removeListener('message', onMessage); subscriber.removeListener('error', onError); Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { @@ -282,44 +315,7 @@ class UserService extends Service { subscriber.disconnect(); } }); - }; - - const finalize = result => { - if (settled) { - return; - } - settled = true; - if (timer) { - clearTimeout(timer); - } - cleanup(); - resolve(result); - }; - - const onMessage = (messageChannel, message) => { - if (messageChannel !== channel) { - return; - } - let eventData = null; - try { - eventData = message ? JSON.parse(message) : null; - } catch (error) { - eventData = { raw: message }; - } - finalize({ - timed_out: false, - reason: 'event', - event: eventData, - }); - }; - - const onError = error => { - app.coreLogger.warn(`订阅微信绑定事件失败: ${error.message}`); - finalize({ - timed_out: true, - reason: 'subscribe_error', - }); - }; + } timer = setTimeout(() => { finalize({ @@ -442,11 +438,10 @@ class UserService extends Service { * @param {string} username - 用户名/手机号/邮箱 * @param {string} password - 密码 * @param {string} loginType - 登录类型: username, phone, email, auto - * @param {string} platformCode - 平台编码(web、pda、mini等) * @return {Object} 登录结果 */ async login(username, password, loginType = 'auto') { - const { ctx, app } = this; + const { app } = this; try { // 统一的认证错误信息 @@ -459,7 +454,6 @@ class UserService extends Service { app.coreLogger.warn(`登录失败: 用户不存在 [${username}]`); throw authError; } - console.log('登录获取用户信息', user); // 2. 检查用户状态 try { this.checkUserStatus(user); @@ -640,37 +634,7 @@ class UserService extends Service { let settled = false; let timer = null; - const cleanup = () => { - subscriber.removeListener('message', onMessage); - subscriber.removeListener('error', onError); - Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { - if (typeof subscriber.quit === 'function') { - Promise.resolve(subscriber.quit()).catch(() => { - if (typeof subscriber.disconnect === 'function') { - subscriber.disconnect(); - } - }); - return; - } - if (typeof subscriber.disconnect === 'function') { - subscriber.disconnect(); - } - }); - }; - - const finalize = result => { - if (settled) { - return; - } - settled = true; - if (timer) { - clearTimeout(timer); - } - cleanup(); - resolve(result); - }; - - const onMessage = (messageChannel, message) => { + function onMessage(messageChannel, message) { if (messageChannel !== channel) { return; } @@ -687,16 +651,46 @@ class UserService extends Service { event: eventData, ye4s_user_id: ye4sUserId, }); - }; + } - const onError = error => { + function onError(error) { app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); finalize({ timed_out: true, reason: 'subscribe_error', event: null, }); - }; + } + + function finalize(result) { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + } + + function cleanup() { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + } timer = setTimeout(() => { finalize({ @@ -906,8 +900,8 @@ class UserService extends Service { /** * 获取微信扫码登录码 - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 登录码结果 */ async getLoginWechatCode(data = {}) { const { app } = this; @@ -1024,8 +1018,8 @@ class UserService extends Service { /** * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 绑定码结果 */ async getBindWechatCode(data = {}) { const accountId = this.getCurrentAccountId(); @@ -1110,8 +1104,8 @@ class UserService extends Service { /** * 根据绑定临时码获取账号ID(供 ye4s 扫码绑定调用) - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 账号查询结果 */ async getUserByTempCode(data = {}) { const { ctx, app } = this; @@ -1224,8 +1218,8 @@ class UserService extends Service { /** * 账号绑定:供 ye4s 扫码后回调,按临时码绑定到指定 ye4s_user.id - * @param {Object} data - * @return {Object} + * @param {Object} data 请求参数 + * @return {Object} 绑定结果 */ async bindAccountByTempCode(data = {}) { const { ctx, app } = this; @@ -1343,7 +1337,7 @@ class UserService extends Service { /** * 解绑微信:清理 ye4s_user 中与当前账号关联的数据 - * @return {Object} + * @return {Object} 解绑结果 */ async unbindWechat() { const accountId = this.getCurrentAccountId(); @@ -1424,9 +1418,9 @@ class UserService extends Service { /** * 生成统一登录成功结构 - * @param {Object} user - * @param options - * @return {Object} + * @param {Object} user 用户对象 + * @param {Object} options 登录选项 + * @return {Object} 登录结果 */ async buildLoginResult(user, options = {}) { const { ctx, app } = this; @@ -1436,7 +1430,6 @@ class UserService extends Service { const platformCode = ctx.header.platform || 'web'; // 获取用户完整信息 const userInfo = await this.findById(user.id); - console.log('用户信息', userInfo); if (!userInfo) { throw new Error('用户信息加载失败'); } @@ -1492,10 +1485,8 @@ class UserService extends Service { /** * 切换角色(重构版) - * @param {Object} data - 切换角色数据 - * @param {number} data.roleId - 角色关联ID (account_store_role.id) - * @param {string} data.platformCode - 平台编码(web、pda、mini等) - * @return {Object} 切换结果 + * @param {Object} data 切换角色数据 + * @return {Object} 切换结果 */ async changeRole(data) { const { ctx, app } = this; @@ -1571,10 +1562,9 @@ class UserService extends Service { /** * 获取用户信息(重构版) - * @param {Object} data - 请求数据 - * @return {Object} 用户信息 + * @return {Object} 用户信息 */ - async info(data) { + async info() { const { ctx } = this; try { const userId = ctx.userId || (ctx.user && ctx.user.id); @@ -1586,7 +1576,6 @@ class UserService extends Service { code: 200, }; } catch (error) { - console.log(error); return { success: false, data: null, @@ -1597,14 +1586,13 @@ class UserService extends Service { /** * 查找用户所有的角色以及对应的主体(重构版) - * @param {number} userId - 用户ID - * @param {string} platformCode - 平台编码 - * @return {Promise} + * @param {number} userId 用户ID + * @return {Promise} 角色列表 */ async getRoles(userId) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; - const project = ctx.header.project; + const project = ctx.header.project || 'all'; try { const loadAccountStoreEmployees = async projectFilter => { const store_where = { @@ -1613,7 +1601,6 @@ class UserService extends Service { if (projectFilter && projectFilter !== 'all') { store_where.project = projectFilter; } - console.log('store_where', store_where, projectFilter, platformCode, ctx.header); return ctx.model.AccountStoreEmployee.findAll({ where: { account_id: userId, @@ -1652,7 +1639,6 @@ class UserService extends Service { realName: null, }; } - console.log('accountStoreEmployees>>>>>', accountStoreEmployees); // 获取当前平台的激活角色 let activeEmployeeId = null; let realName = null; @@ -1682,10 +1668,10 @@ class UserService extends Service { // 确定当前激活角色 for (const Employee of Employees) { - if (Employee.is_primary == 1) { + if (Employee.is_primary === 1) { activeEmployeeId = Employee.id; realName = Employee.real_name; - userRole = Employee.role_type == 1 ? 'warehouse' : 'customer'; + userRole = Employee.role_type === 1 ? 'warehouse' : 'customer'; break; } } @@ -1694,7 +1680,7 @@ class UserService extends Service { if (!activeEmployeeId && Employees.length > 0) { activeEmployeeId = Employees[0].id; realName = Employees[0].real_name; - userRole = Employees[0].role_type == 1 ? 'warehouse' : 'customer'; + userRole = Employees[0].role_type === 1 ? 'warehouse' : 'customer'; // 设置为激活角色 if (Employees[0].id) { @@ -1705,7 +1691,6 @@ class UserService extends Service { // 获取菜单和权限 const menus = await this.getMenus(activeEmployeeId); - console.log('获取菜单', activeEmployeeId, menus); const permissions = await this.getPermissions(activeEmployeeId); return { Employees, activeEmployeeId, menus, permissions, userRole, realName }; @@ -1724,16 +1709,13 @@ class UserService extends Service { /** * 根据ID查找用户(重构版) - * @param {number} userId - 用户ID - * @param {string} platformCode - 平台编码 - * @param useCache - * @return {Promise} + * @param {number} userId 用户ID + * @param {boolean} useCache 是否使用缓存 + * @return {Promise} 用户信息 */ async findById(userId, useCache = true) { const { ctx } = this; const platformCode = ctx.header.platform || 'web'; - const project = ctx.header.project; - console.log(`调用${ctx.query_count}次,平台为${platformCode}`); ctx.query_count++; try { // 生成缓存key @@ -1744,7 +1726,6 @@ class UserService extends Service { try { const cachedUser = await this.app.getCacheAsync(cacheKey); if (cachedUser) { - console.log('用户信息缓存命中:', userId); return cachedUser; } } catch (cacheError) { @@ -1768,16 +1749,14 @@ class UserService extends Service { } // 3. 获取角色信息(这个方法内部也有缓存逻辑) - let { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); - console.log('activeEmployeeId>>>>>>>>', activeEmployeeId); + let { Employees, activeEmployeeId, menus, permissions, userRole } = await this.getRoles(userId); // pda 场景若缺少激活角色,优先补一条当前平台激活记录,避免直接报错。 - if (platformCode == 'pda' && !activeEmployeeId && Employees.length > 0) { + if (platformCode === 'pda' && !activeEmployeeId && Employees.length > 0) { const fallbackEmployee = Employees[0]; await this.ensurePlatformActiveRole(userId, fallbackEmployee.id, platformCode); activeEmployeeId = fallbackEmployee.id; - userRole = fallbackEmployee.role_type == 1 ? 'warehouse' : 'customer'; - realName = fallbackEmployee.real_name || realName; + userRole = fallbackEmployee.role_type === 1 ? 'warehouse' : 'customer'; menus = await this.getMenus(activeEmployeeId); permissions = await this.getPermissions(activeEmployeeId); } @@ -1801,7 +1780,7 @@ class UserService extends Service { } const avatar = await this.getAvatarByEmployeeId(activeEmployeeId); - if (platformCode == 'pda' && !activeEmployeeId) { + if (platformCode === 'pda' && !activeEmployeeId) { ctx.logger.warn(`pda 平台未找到可激活角色,accountId=${userId},将以空角色上下文返回`); } // 5. 组合用户信息 @@ -1826,11 +1805,9 @@ class UserService extends Service { }; // 6. 设置缓存 if (useCache) { - console.log('设置用户缓存', userInfo); await this.setUserCache(cacheKey, userInfo, 300); // 缓存5分钟 } - console.log('用户信息数据库查询:', userId); return userInfo; } catch (error) { @@ -1839,17 +1816,18 @@ class UserService extends Service { } } /** - * 设置用户缓存 - * @param cacheKey - * @param userInfo - * @param ttl - * @private - */ + * 设置用户缓存 + * @param {string} cacheKey 缓存键 + * @param {Object|null} userInfo 用户信息 + * @param {number} ttl 缓存时间 + * @private + */ async setUserCache(cacheKey, userInfo, ttl = 300) { try { // 移除缓存标识字段 if (userInfo) { - const { cached_at, ...cacheData } = userInfo; + const cacheData = { ...userInfo }; + delete cacheData.cached_at; await this.app.setCacheAsync(cacheKey, cacheData, ttl); } else { await this.app.setCacheAsync(cacheKey, null, ttl); @@ -1859,8 +1837,7 @@ class UserService extends Service { } } async getAvatarByEmployeeId(employeeId) { - const { ctx, app } = this; - const { Op } = app.Sequelize; + const { ctx } = this; let url = ''; const image = await ctx.model.FileReference.findOne({ where: { @@ -1881,8 +1858,8 @@ class UserService extends Service { } /** * 清除用户缓存 - * @param userId - * @param platformCode + * @param {number} userId 用户ID + * @param {string|null} platformCode 平台编码 */ async clearUserCache(userId, platformCode = null) { try { @@ -1902,7 +1879,6 @@ class UserService extends Service { // 同时清除相关的缓存 await this.clearRelatedCache(userId); - console.log('用户缓存已清除:', userId); return true; } catch (error) { console.warn('清除用户缓存失败:', error.message); @@ -1911,7 +1887,7 @@ class UserService extends Service { } /** * 清除用户相关缓存 - * @param userId + * @param {number} userId 用户ID * @private */ async clearRelatedCache(userId) { @@ -1948,9 +1924,8 @@ class UserService extends Service { } /** * 获取权限列表(重构版) - * @param {number} roleId - 角色ID - * @param activeEmployeeId - * @return {Promise} + * @param {number} activeEmployeeId 员工ID + * @return {Promise} 权限列表 */ async getPermissions(activeEmployeeId) { const { ctx, app } = this; @@ -1980,7 +1955,6 @@ class UserService extends Service { ], raw: true, // 获取纯数据对象 }); - console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } @@ -2014,7 +1988,6 @@ class UserService extends Service { [ 'sort', 'ASC' ], ], }); - console.log('permissions列表', permissions); if (!permissions) { return []; } @@ -2026,12 +1999,10 @@ class UserService extends Service { } } - async getMenus(activeEmployeeId) { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; - console.log('获取员工菜单员工id:', activeEmployeeId); if (!ctx.header.platform || !activeEmployeeId) { return []; } @@ -2056,7 +2027,6 @@ class UserService extends Service { ], raw: true, // 获取纯数据对象 }); - console.log('员工绑定的角色', roles); if (!roles || roles.length === 0) { return []; } @@ -2102,7 +2072,7 @@ class UserService extends Service { /** * 转换权限为路由格式(保持不变) - * @param data + * @param {Array} data 权限列表 */ async convertToRoutes(data) { const map = new Map(); @@ -2160,7 +2130,9 @@ class UserService extends Service { // 移除辅助字段 const cleanNode = node => { - const { id, sort, ...rest } = node; + const rest = { ...node }; + delete rest.id; + delete rest.sort; if (rest.children && rest.children.length > 0) { rest.children = rest.children.map(child => cleanNode(child)); } @@ -2172,19 +2144,17 @@ class UserService extends Service { /** * 根据标识符查找用户(已重构) - * @param identifier - * @param type - * @param useCache + * @param {string} identifier 标识符 + * @param {string} type 查找类型 + * @return {Promise} 用户对象 */ - async findUserByIdentifier(identifier, type = 'auto', useCache = true) { - const { ctx, app } = this; + async findUserByIdentifier(identifier, type = 'auto') { + const { ctx } = this; let user; if (type === 'auto') { // 自动判断类型 - const Op = app.Sequelize.Op; - if (/^1[3-9]\d{9}$/.test(identifier)) { // 手机号格式 user = await ctx.model.Account.findOne({ @@ -2232,7 +2202,7 @@ class UserService extends Service { /** * 检查用户状态(保持不变) - * @param user + * @param {Object} user 用户对象 */ checkUserStatus(user) { if (user.status === 0) { @@ -2248,9 +2218,9 @@ class UserService extends Service { /** * 验证密码(重构版) - * @param inputPassword - * @param storedHash - * @param salt + * @param {string} inputPassword 输入密码 + * @param {string} storedHash 存储哈希 + * @param {string} salt 密码盐 */ async verifyPassword(inputPassword, storedHash, salt) { const crypto = require('crypto'); @@ -2266,8 +2236,8 @@ class UserService extends Service { /** * 加密密码(保持不变) - * @param password - * @param salt + * @param {string} password 密码 + * @param {string} salt 密码盐 */ async encryptPassword(password, salt) { const crypto = require('crypto'); @@ -2286,11 +2256,10 @@ class UserService extends Service { /** * 更新最后登录时间(重构版) - * @param userId + * @param {number} userId 用户ID */ async updateLastLoginTime(userId) { const { ctx } = this; - console.log('登录上下文', ctx.request.header['x-real-ip']); await ctx.model.Account.update({ last_login_at: new Date(), last_login_ip: ctx.request.header['x-real-ip'], @@ -2302,9 +2271,9 @@ class UserService extends Service { /** * 确保平台激活角色存在 - * @param accountId - * @param accountStoreRoleId - * @param platformCode + * @param {number} accountId 账号ID + * @param {number} accountStoreRoleId 角色关联ID + * @param {string} platformCode 平台编码 * @private */ async ensurePlatformActiveRole(accountId, accountStoreRoleId, platformCode) { @@ -2321,13 +2290,12 @@ class UserService extends Service { } } - /** * 用户注册(重构版) - * @param userInfo + * @param {Object} userInfo 用户信息 */ async register(userInfo) { - const { ctx, app } = this; + const { ctx } = this; // 检查用户名是否已存在 const existingUser = await this.findUserByIdentifier(userInfo.username, 'username'); diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index ef45491..880a52a 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -98,11 +98,11 @@ class DeliveryOrderService extends Service { }); } - // 异步处理:订单入队列 - this.addOrderToQueue(orderId, info.warehouseId); - await transaction.commit(); + // 异步处理:订单入队列 + await this.addOrderToQueue(orderId, info.warehouseId); + return { success: true, message: '订单创建成功', @@ -132,7 +132,8 @@ class DeliveryOrderService extends Service { /** * 生成订单结构哈希值 * 直接使用itemsInfo中的items_str - * @param itemsInfo + * @param {Object} itemsInfo 订单明细信息 + * @return {string} 结构哈希值 */ generateItemsHash(itemsInfo) { const crypto = require('crypto'); @@ -149,19 +150,21 @@ class DeliveryOrderService extends Service { /** * 计算CRC32校验码 - * @param str + * @param {string} str 待计算字符串 + * @return {number} CRC32校验值 */ calculateCRC32(str) { if (!str) return 0; try { const crc32 = require('crc-32'); - return crc32.str(str) >>> 0; // 转为无符号整数 + const crc = crc32.str(str); + return crc >= 0 ? crc : crc + 4294967296; } catch (error) { // 降级方案:简单校验和 let crc = 0; for (let i = 0; i < str.length; i++) { - crc = (crc + str.charCodeAt(i)) & 0xFFFFFFFF; + crc = (crc + str.charCodeAt(i)) % 4294967296; } return crc; } @@ -201,7 +204,6 @@ class DeliveryOrderService extends Service { logisticsAreaCode, isUrgency, invoiceFlag, - senderInfo, receiverInfo, } = deliveryOrder; @@ -316,11 +318,8 @@ class DeliveryOrderService extends Service { const stockWeightMap = new Map(); // stock_id -> 单件重量(grossWeight) const processedItemIds = new Set(); - console.log('order_items', order_items); - for (let i = 0; i < order_items.length; i++) { const line = order_items[i]; - console.log('line', line); // 跳过空值 if (!line || typeof line !== 'object') { @@ -328,7 +327,6 @@ class DeliveryOrderService extends Service { continue; } - // 数量验证 const planQty = line.planQty ? parseInt(line.planQty) : 0; if (planQty <= 0) { @@ -337,7 +335,6 @@ class DeliveryOrderService extends Service { } let wms_stock = null; if (!line.itemId) { - console.log('ERP不处理WMS的外部商品编码'); // 查找唯一键 wms_stock = await app.model.StockStore.findOne({ where: { item_code: line.itemCode, @@ -362,7 +359,7 @@ class DeliveryOrderService extends Service { continue; } - const { stock, storage } = stockResult.data; + const { storage } = stockResult.data; const stockId = storage.id; if (!stockId) { @@ -516,17 +513,41 @@ class DeliveryOrderService extends Service { // 订单入队列(异步处理) async addOrderToQueue(orderId, warehouseId) { - const { ctx, app } = this; + const { ctx } = this; + + if (!orderId || !warehouseId) { + ctx.logger.warn('[订单入队列] 参数无效', { orderId, warehouseId }); + return; + } + + const cacheRedis = ctx.app && ctx.app.redis && ctx.app.redis.get ? ctx.app.redis.get('cache') : null; + if (!cacheRedis || typeof cacheRedis.publish !== 'function') { + ctx.logger.warn('[订单入队列] Redis 不可用', { orderId, warehouseId }); + return; + } + + const channel = `delivery_order:queue:${warehouseId}`; try { - const queueData = { + await cacheRedis.publish(channel, JSON.stringify({ orderId, warehouseId, timestamp: Date.now(), action: 'order_created', - }; + })); + ctx.logger.info('[订单入队列] 发布成功', { + orderId, + warehouseId, + channel, + }); } catch (error) { + ctx.logger.warn('[订单入队列] 发布失败', { + orderId, + warehouseId, + channel, + error: error.message, + }); } } } diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index b2641a6..bfe24ae 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -8,26 +8,21 @@ class entryOrderService extends Service { const transaction = await app.model.transaction(); // 开启事务 try { - console.log('入库单开始接收处理'); let totalOrderLines = data.request.entryOrder.totalOrderLines || 0; let orderLine = data.request.orderLines.orderLine; if (orderLine.itemCode) { orderLine = [ orderLine ]; } - console.log('orderLine', orderLine); - const isSingle = totalOrderLines ? 0 : 1; totalOrderLines = totalOrderLines || orderLine.length; let errors = []; const items = []; - console.log('循环开始'); // 验证商品 - for (var i = 0; i < orderLine.length; i++) { + for (let i = 0; i < orderLine.length; i++) { let wms_stock = null; // ERP不处理WMS的外部商品编码 if (!orderLine[i].itemId) { - console.log('ERP不处理WMS的外部商品编码'); // 查找唯一键 wms_stock = await app.model.StockStore.findOne({ where: { item_code: orderLine[i].itemCode, @@ -52,7 +47,6 @@ class entryOrderService extends Service { wms_stock.item_id = orderLine[i].itemId || wms_stock.id; items.push(wms_stock); } - console.log('items>>>>>', items); if (errors.length > 0) { await transaction.rollback(); // 验证失败,回滚事务 return { @@ -77,7 +71,6 @@ class entryOrderService extends Service { transaction // 传递事务 ); - console.log('入库单参数', order); if (!order.success) { await transaction.rollback(); return { @@ -94,10 +87,9 @@ class entryOrderService extends Service { errors = []; // 重置错误数组 // 添加商品明细 - for (var i = 0; i < items.length; i++) { + for (let i = 0; i < items.length; i++) { const item = items[i]; const res = await this.addItems(item, orderId, transaction); - console.log('添加商品返回信息', res); if (!res.success) { errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); } @@ -116,8 +108,9 @@ class entryOrderService extends Service { // 获取接收行数并处理状态 const lineCount = await this.getLineCount(orderId, transaction); + const expectedTotalOrderLines = Number(totalOrderLines) || 0; - if (lineCount == totalOrderLines) { + if (lineCount === expectedTotalOrderLines) { // 所有行数接收完成 await this.received(orderId, warehouseId, storeId, transaction); } @@ -125,7 +118,7 @@ class entryOrderService extends Service { // 提交事务 await transaction.commit(); - if (lineCount == totalOrderLines) { + if (lineCount === expectedTotalOrderLines) { return { success: true, message: '入库单接收完毕', @@ -185,7 +178,6 @@ class entryOrderService extends Service { // 辅助函数:标记为已接收(支持事务) async received(orderId, warehouseId, storeId, transaction = null) { const { app } = this; - const updateData = { order_status: 'COMPLETED', updated_at: new Date(), @@ -573,9 +565,7 @@ class entryOrderService extends Service { } async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) { - const { app } = this; const { ctx } = this; - console.log('创建入库单信息', order, appKey, storeId, warehouseId); try { const options = transaction ? { transaction } : {}; @@ -601,8 +591,6 @@ class entryOrderService extends Service { updated_at: new Date(), }, options); - console.log(`入库单 ${order.entryOrderCode} 已存在,状态更新为接收中`); - return { success: true, code: 1, @@ -645,18 +633,18 @@ class entryOrderService extends Service { const warehouse_data = await this.ctx.service.systems.store.getStoreName(warehouseId); let store_name = null; let warehouse_name = null; - if (warehouse_data.code == 200) { + if (warehouse_data.code === 200) { warehouse_name = warehouse_data.data.company_name; } const store_data = await this.ctx.service.systems.store.getStoreName(storeId); - if (store_data.code == 200) { + if (store_data.code === 200) { store_name = store_data.data.company_name; } const contract_data = await this.ctx.service.systems.store.getStoreRemaskName(storeId, warehouseId); let contract = null; - if (contract_data.code == 200) { + if (contract_data.code === 200) { contract = contract_data.data; } // 构建入库单数据 @@ -667,7 +655,7 @@ class entryOrderService extends Service { total_order_lines: totalOrderLines, order_create_time: order.orderCreateTime ? new Date(order.orderCreateTime) : new Date(), expect_start_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), - expect_end_time: order.expectStartTime ? new Date(order.expectStartTime) : new Date(), + expect_end_time: order.expectEndTime ? new Date(order.expectEndTime) : new Date(), logistics_code: order.logisticsCode || '', logistics_name: order.logisticsName || '', express_code: order.expressCode || '', @@ -697,8 +685,6 @@ class entryOrderService extends Service { await internalTransaction.commit(); } - console.log(`成功创建入库单: ${order.entryOrderCode}, ID: ${newEntryOrder.id}`); - return { success: true, code: 1, @@ -708,7 +694,6 @@ class entryOrderService extends Service { }; } catch (error) { - console.log('创建入库单失败', error); // 如果这是内部创建的事务,回滚它 if (internalTransaction) { await internalTransaction.rollback(); @@ -732,9 +717,7 @@ class entryOrderService extends Service { } async addItems(item, orderId, transaction = null) { - const { app } = this; const { ctx } = this; - console.log('添加入库单商品'); try { const options = transaction ? { transaction } : {}; @@ -773,7 +756,6 @@ class entryOrderService extends Service { code: 1, }; } catch (error) { - console.log('添加商品明细出错', error); throw error; } } @@ -795,53 +777,10 @@ class entryOrderService extends Service { } } - async received(orderId, warehouseId, storeId, transaction = null) { - console.log('完结传参', orderId, warehouseId, storeId); - const { app } = this; - const { ctx } = this; - - const options = transaction ? { transaction } : {}; - - const existingOrder = await ctx.model.EntryOrder.findOne({ - where: { - warehouse_id: warehouseId, - store_id: storeId, - id: orderId, - }, - ...options, - }); - - if (!existingOrder) { - return { - success: false, - code: 0, - message: '入库单不存在', - entryOrderId: null, - orderStatus: null, - error: '入库单不存在', - }; - } - - const allowedStatuses = [ 'CREATING' ]; - if (allowedStatuses.includes(existingOrder.order_status)) { - await existingOrder.update({ - order_status: 'CREATED', - updated_at: new Date(), - }, options); - } - - return { - success: true, - code: 1, - message: '完成', - }; - } - async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) { if (orderLines.length < 1) { throw new Error('行不能为空'); } - console.log('isFin:', isFin); const queryData = { request: { entryOrder: { @@ -854,7 +793,7 @@ class entryOrderService extends Service { confirmType: isFin ? 0 : 1, status: isFin ? 'FULFILLED' : 'PARTFULFILLED', freight: 0, - operateTime: new Date().format(), + operateTime: this.app.formatDate(new Date()), remark: entryOrder.remark, }, orderLines, @@ -961,9 +900,8 @@ class entryOrderService extends Service { // 判断是否最终完成 const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty); let qimenResult = {}; - let queryId = null; // 奇门入库单,数据同步到奇门 - if (entryOrder.source_type == 'QM') { + if (String(entryOrder.source_type) === 'QM') { // 第二阶段:调用奇门接口 const Result = await this.qimenEntryorderConfirm( entryOrder, @@ -971,11 +909,9 @@ class entryOrderService extends Service { isFin, Math.round(new Date() / 1000) ); - console.log(Result); - queryId = Result.queryId; qimenResult = Result.xmlArray.response; // 奇门调用失败,回滚事务 - if (!qimenResult || qimenResult.flag != 'success') { + if (!qimenResult || String(qimenResult.flag) !== 'success') { await transaction.rollback(); console.error('奇门接口调用失败:', qimenResult); return { @@ -1000,8 +936,7 @@ class entryOrderService extends Service { }, transaction, }); - const res = await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); - console.log('增加库存返回', res); + await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); if (result[0] === 0) { // 更新失败,可能被并发修改了 console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`); @@ -1054,8 +989,6 @@ class entryOrderService extends Service { // 4. 提交事务 await transaction.commit(); - console.log(`入库单确认成功: id=${entryOrder.id}, 确认增量=${totalConfirmIncrement}, 状态=${newOrderStatus}`); - return { success: true, message: isFin ? '入库单完成确认' : '入库单增量确认成功', diff --git a/app/service/systems/file.js b/app/service/systems/file.js index 1946ac6..a80583f 100644 --- a/app/service/systems/file.js +++ b/app/service/systems/file.js @@ -4,17 +4,23 @@ const Service = require('egg').Service; class FileService extends Service { async getImages(data) { const { ctx } = this; - const result = await ctx.model.FileReference.findAll({ where: { - business_type: data.type, - business_id: data.id, - }, include: [ - { - model: ctx.model.File, - as: 'file', - attributes: [ 'file_url', 'file_name' ], - required: true, + const result = await ctx.model.FileReference.findAll({ + where: { + business_type: data.type, + business_id: data.id, }, - ] }); + include: [ + { + model: ctx.model.File, + as: 'file', + attributes: [ + 'file_url', + 'file_name', + ], + required: true, + }, + ], + }); return result; } async ReferenceFile(data) { @@ -22,9 +28,8 @@ class FileService extends Service { const { id, type, images } = data; const warehouseId = ctx.user.store_id; - console.log('<<>>>', type); switch (type) { - case 'stock': + case 'stock': { const stock = await ctx.model.StockWarehouse.findOne({ where: { warehouse_id: warehouseId, @@ -36,7 +41,6 @@ class FileService extends Service { if (!stock) { throw new Error('找不到商品'); } - console.log('<<>>>', images.length); if (images.length > 0) { await ctx.model.StockWarehouse.update({ is_images: 'Y' }, { @@ -66,9 +70,9 @@ class FileService extends Service { beforeChanges: null, }); break; - + } default: - // code + // code } // 获取现有的file_id const existingRefs = await ctx.model.FileReference.findAll({ diff --git a/app/service/systems/location.js b/app/service/systems/location.js index 578e3da..f2fa307 100644 --- a/app/service/systems/location.js +++ b/app/service/systems/location.js @@ -5,7 +5,7 @@ const Service = require('egg').Service; class LocationService extends Service { /** * 创建货架并自动生成仓位 - * @param params + * @param {Object} params 货架基础参数 */ async createRackWithSpaces(params) { const { ctx } = this; @@ -37,9 +37,9 @@ class LocationService extends Service { /** * 为货架生成仓位 - * @param rackId - * @param rack - * @param transaction + * @param {number|string} rackId 货架ID + * @param {Object} rack 货架信息 + * @param {Object} transaction 事务对象 */ async _generateSpacesForRack(rackId, rack, transaction) { const { app } = this; @@ -97,9 +97,9 @@ class LocationService extends Service { /** * 计算库区内货架的排序(按X坐标排序) - * @param warehouseId - * @param areaId - * @param transaction + * @param {number|string} warehouseId 仓库ID + * @param {number|string} areaId 库区ID + * @param {Object} transaction 事务对象 */ async _calculateAreaRackOrder(warehouseId, areaId, transaction) { const { app } = this; @@ -129,8 +129,8 @@ class LocationService extends Service { /** * 计算仓库的拣货路径 - * @param warehouseId - * @param transaction + * @param {number|string} warehouseId 仓库ID + * @param {Object} transaction 事务对象 */ async _calculatePickPathForWarehouse(warehouseId, transaction) { const { app } = this; @@ -189,10 +189,10 @@ class LocationService extends Service { /** * 更新货架下仓位的拣货顺序 - * @param rackId - * @param rackSequence - * @param rackDistance - * @param transaction + * @param {number|string} rackId 货架ID + * @param {number} rackSequence 货架拣货顺序 + * @param {number} rackDistance 起始点距离 + * @param {Object} transaction 事务对象 */ async _updateSpacePickSequence(rackId, rackSequence, rackDistance, transaction) { const { app } = this; @@ -241,8 +241,8 @@ class LocationService extends Service { /** * 计算拣货优先级 - * @param row - * @param distance + * @param {number} row 层数 + * @param {number} distance 距离 */ _calculatePickPriority(row, distance) { // 行数越小(下层)优先级越高 @@ -257,8 +257,8 @@ class LocationService extends Service { /** * 更新货架位置后重新计算路径 - * @param rackId - * @param newPosition + * @param {number|string} rackId 货架ID + * @param {Object} newPosition 新坐标 */ async updateRackPosition(rackId, newPosition) { const { ctx, app } = this; @@ -305,8 +305,8 @@ class LocationService extends Service { /** * 获取拣货路径 - * @param warehouseId - * @param options + * @param {number|string} warehouseId 仓库ID + * @param {Object} options 查询选项 */ async getPickPath(warehouseId, options = {}) { const { app } = this; @@ -364,7 +364,7 @@ class LocationService extends Service { /** * 批量更新邻居关系 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID */ async updateNeighborRelations(warehouseId) { const { app } = this; @@ -392,8 +392,8 @@ class LocationService extends Service { /** * 查找相邻货架 - * @param currentRack - * @param allRacks + * @param {Object} currentRack 当前货架 + * @param {Array} allRacks 所有货架 */ async _findNeighborRacks(currentRack, allRacks) { const NEIGHBOR_DISTANCE = 2000; // 2米内视为邻居 diff --git a/app/service/systems/location_space.js b/app/service/systems/location_space.js index 779f8b8..0a12e66 100644 --- a/app/service/systems/location_space.js +++ b/app/service/systems/location_space.js @@ -5,7 +5,8 @@ const Service = require('egg').Service; class LocationSpaceService extends Service { /** * 创建仓位 - * @param data + * @param {Object} data 仓位数据 + * @return {Promise} 创建结果 */ async create(data) { const { ctx } = this; @@ -72,7 +73,8 @@ class LocationSpaceService extends Service { /** * 批量创建仓位 - * @param dataList + * @param {Array} dataList 仓位数据列表 + * @return {Promise} 创建结果 */ async batchCreate(dataList) { const { ctx } = this; @@ -133,7 +135,8 @@ class LocationSpaceService extends Service { /** * 获取仓位列表 - * @param params + * @param {Object} params 查询参数 + * @return {Promise} 列表结果 */ async list(params = {}) { const { ctx } = this; @@ -224,7 +227,8 @@ class LocationSpaceService extends Service { /** * 获取仓位详情 - * @param id + * @param {number|string} id 仓位ID + * @return {Promise} 仓位详情 */ async detail(id) { const { ctx } = this; @@ -259,8 +263,9 @@ class LocationSpaceService extends Service { /** * 更新仓位 - * @param id - * @param data + * @param {number|string} id 仓位ID + * @param {Object} data 更新数据 + * @return {Promise} 更新结果 */ async update(id, data) { const { ctx } = this; @@ -323,7 +328,8 @@ class LocationSpaceService extends Service { /** * 删除仓位(软删除) - * @param id + * @param {number|string} id 仓位ID + * @return {Promise} 删除结果 */ async delete(id) { const { ctx } = this; @@ -359,8 +365,9 @@ class LocationSpaceService extends Service { /** * 启用/禁用仓位 - * @param id - * @param enabled + * @param {number|string} id 仓位ID + * @param {boolean} enabled 是否启用 + * @return {Promise} 操作结果 */ async toggleStatus(id, enabled) { const { ctx } = this; @@ -389,8 +396,9 @@ class LocationSpaceService extends Service { /** * 更新仓位状态 - * @param id - * @param status + * @param {number|string} id 仓位ID + * @param {string} status 仓位状态 + * @return {Promise} 操作结果 */ async updateStatus(id, status) { const { ctx } = this; @@ -440,7 +448,8 @@ class LocationSpaceService extends Service { /** * 查询可用仓位 - * @param params + * @param {Object} params 查询参数 + * @return {Promise} 可用仓位列表 */ async findAvailableSpaces(params) { const { ctx } = this; @@ -490,8 +499,9 @@ class LocationSpaceService extends Service { /** * 根据编码查找仓位 - * @param warehouseId - * @param spaceCode + * @param {number|string} warehouseId 仓库ID + * @param {string} spaceCode 仓位编码 + * @return {Promise} 仓位信息 */ async findByCode(warehouseId, spaceCode) { const { ctx } = this; @@ -525,7 +535,8 @@ class LocationSpaceService extends Service { /** * 根据条码查找仓位 - * @param barcode + * @param {string} barcode 条码 + * @return {Promise} 仓位信息 */ async findByBarcode(barcode) { const { ctx } = this; @@ -558,7 +569,8 @@ class LocationSpaceService extends Service { /** * 获取仓库仓位统计 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID + * @return {Promise} 统计结果 */ async getWarehouseStats(warehouseId) { const { ctx } = this; @@ -585,8 +597,9 @@ class LocationSpaceService extends Service { /** * 获取分区的仓位统计 - * @param warehouseId - * @param zoneId + * @param {number|string} warehouseId 仓库ID + * @param {number|string|null} zoneId 分区ID + * @return {Promise} 统计结果 */ async getZoneStats(warehouseId, zoneId = null) { const { ctx } = this; @@ -602,7 +615,8 @@ class LocationSpaceService extends Service { /** * 验证仓位是否可分配 - * @param locationSpaceId + * @param {number|string} locationSpaceId 仓位ID + * @return {Promise} 仓位信息 */ async validateAllocation(locationSpaceId) { const { ctx } = this; @@ -634,7 +648,8 @@ class LocationSpaceService extends Service { /** * 验证仓位是否可移出 - * @param locationSpaceId + * @param {number|string} locationSpaceId 仓位ID + * @return {Promise} 仓位信息 */ async validateTransferOut(locationSpaceId) { const { ctx } = this; @@ -666,7 +681,8 @@ class LocationSpaceService extends Service { /** * 内部方法:验证关联数据 - * @param data + * @param {Object} data 关联数据 + * @return {Promise} */ async _validateReferences(data) { const { ctx } = this; diff --git a/app/service/systems/location_zone.js b/app/service/systems/location_zone.js index 7a857d8..c0647c7 100644 --- a/app/service/systems/location_zone.js +++ b/app/service/systems/location_zone.js @@ -5,11 +5,11 @@ const Service = require('egg').Service; class LocationZoneService extends Service { /** * 获取所有仓库级别的分区列表 - * @param warehouseId + * @param {number|string} warehouseId 仓库ID * @return {Promise} 仓库级别分区列表 */ async getWarehouseLevelZones(warehouseId) { - const { ctx, app } = this; + const { ctx } = this; try { const zones = await ctx.model.LocationZone.findAll({ @@ -32,27 +32,22 @@ class LocationZoneService extends Service { let totalSpaces = 0; for (let ii = 0; ii < warehouse_tree.warehouseRoot.children.length; ii++) { const area = warehouse_tree.warehouseRoot.children[ii]; - console.log('area', area); for (let iii = 0; iii < area.children.length; iii++) { const zone = area.children[iii]; - if (zone.type == 'rack') { - console.log('货架', zone); + if (zone.type === 'rack') { racks.push(zone); rackCount++; - const sz_count = await app.model.LocationSpace.count({ where: { zone_id: zone.id } }); - console.log(sz_count); const { rackColumns = 1, rackRows = 1, rackLevels = 1 } = zone.data; totalSpaces += rackColumns * rackRows * rackLevels; } } - if (area.type == 'area') { + if (area.type === 'area') { areaCount++; } } zones[i].rackCount = rackCount; zones[i].areaCount = areaCount; zones[i].totalSpaces = totalSpaces; - console.log('zones[i]', i, rackCount, areaCount, zones[i].rackCount, zones[i].areaCount); } // 转换为前端需要的格式 return zones.map(zone => ({ @@ -75,11 +70,10 @@ class LocationZoneService extends Service { } /** - * 根据仓库ID获取完整的树状结构(支持Element Tree格式) - * @param {number} warehouseId - 仓库ID - * @param warehouseSpaceId - * @return {Promise} 树状结构数据 - */ + * 根据仓库ID获取完整的树状结构(支持Element Tree格式)。 + * @param {number|string} warehouseSpaceId 仓库分区ID + * @return {Promise} 树状结构数据 + */ async getZoneTreeByWarehouse(warehouseSpaceId) { const { ctx } = this; const warehouseId = ctx.user.store_id; @@ -320,14 +314,9 @@ class LocationZoneService extends Service { /** * 创建元素 - * @param {Object} data - 元素数据 + * @param {Object} data 元素数据 * @return {Promise} 创建的元素 */ - /** - * 创建元素 - * @param {Object} data - 元素数据 - * @return {Promise} 创建的元素 - */ async createZone(data) { const { ctx } = this; try { @@ -342,7 +331,6 @@ class LocationZoneService extends Service { // 3. 验证父元素 await this.validateParentElement(data, warehouse_id); - // 5. 处理编码(根据类型) const zoneCode = this.generateZoneCodeByType(data); @@ -366,7 +354,7 @@ class LocationZoneService extends Service { direction: data.direction, color: data.color || this.getDefaultColorByType(data.zone_type), }); - if (zone.zone_type == 'rack') { + if (zone.zone_type === 'rack') { await this.generateSpacesForRack(zone.id, zone); } return { @@ -382,7 +370,7 @@ class LocationZoneService extends Service { /** * 验证基本字段 - * @param data + * @param {Object} data 元素数据 */ validateBasicFields(data) { // 所有元素都需要这些字段 @@ -405,21 +393,22 @@ class LocationZoneService extends Service { /** * 根据类型进行特定验证 - * @param data - * @param warehouseId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID */ async validateByZoneType(data, warehouseId) { const { ctx } = this; switch (data.zone_type) { - case 'warehouse': + case 'warehouse': { // 仓库必须 parent_id = 0 if (data.parent_id !== 0 && data.parent_id !== null) { throw new Error('仓库元素的父元素必须为0或null'); } break; + } - case 'area': + case 'area': { // 库区必须有父元素且父元素必须是仓库 if (!data.parent_id) { throw new Error('库区必须指定父元素'); @@ -438,8 +427,9 @@ class LocationZoneService extends Service { throw new Error('库区只能创建在仓库上'); } break; + } - case 'rack': + case 'rack': { // 货架必须有父元素且父元素必须是通道 if (!data.parent_id) { throw new Error('货架必须指定父元素'); @@ -471,7 +461,9 @@ class LocationZoneService extends Service { throw new Error('货架列数、层数、分格数必须大于0'); } break; - case 'pick_start': + } + + case 'pick_start': { // 这些元素必须有父元素且父元素可以是任何类型(除了自身) if (!data.parent_id) { throw new Error(`${this.getZoneTypeText(data.zone_type)}必须指定父元素`); @@ -483,13 +475,11 @@ class LocationZoneService extends Service { deleted_at: null, }, }); - if (parentSpecial.zone_type !== 'area') { - throw new Error('拣货起点只能创建在库区上'); - } if (!parentSpecial) { throw new Error('父元素不存在'); } break; + } default: throw new Error('不支持的分区类型'); @@ -498,8 +488,8 @@ class LocationZoneService extends Service { /** * 验证父元素 - * @param data - * @param warehouseId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID */ async validateParentElement(data, warehouseId) { const { ctx } = this; @@ -531,18 +521,21 @@ class LocationZoneService extends Service { const parentEndX = parent.x + parent.length; const parentEndY = parent.y + parent.width; const parentEndZ = parent.z + parent.height; - const elementEndX = data.x + data.length; const elementEndY = data.y + data.width; const elementEndZ = data.z + data.height; + if (elementEndX > parentEndX || elementEndY > parentEndY || elementEndZ > parentEndZ) { + throw new Error('元素必须位于父元素范围内'); + } + } /** * 验证坐标是否重叠 - * @param data - * @param warehouseId - * @param excludeId + * @param {Object} data 元素数据 + * @param {number|string} warehouseId 仓库ID + * @param {number|string|null} excludeId 排除的分区ID */ async validateZoneOverlap(data, warehouseId, excludeId = null) { const { ctx } = this; @@ -565,8 +558,9 @@ class LocationZoneService extends Service { /** * 检查两个元素是否重叠 - * @param zone1 - * @param zone2 + * @param {Object} zone1 元素1 + * @param {Object} zone2 元素2 + * @return {boolean} 是否重叠 */ isOverlap(zone1, zone2) { const zone1EndX = zone1.x + zone1.length; @@ -587,7 +581,8 @@ class LocationZoneService extends Service { /** * 根据类型生成编码 - * @param data + * @param {Object} data 元素数据 + * @return {string|null} 编码 */ generateZoneCodeByType(data) { // 只有特定类型需要编码 @@ -621,7 +616,8 @@ class LocationZoneService extends Service { /** * 根据类型获取默认颜色 - * @param zoneType + * @param {string} zoneType 类型 + * @return {string} 默认颜色 */ getDefaultColorByType(zoneType) { const colorMap = { @@ -638,7 +634,8 @@ class LocationZoneService extends Service { /** * 获取类型文本 - * @param type + * @param {string} type 类型 + * @return {string} 类型文本 */ getZoneTypeText(type) { const typeMap = { @@ -674,18 +671,44 @@ class LocationZoneService extends Service { throw new Error('分区不存在'); } - console.log('修改的数据', data); + const updateData = { ...data }; + + if (data.is_active !== undefined) { + const isActive = [ true, 1, '1', 'true' ].includes(data.is_active); + const isInactive = [ false, 0, '0', 'false' ].includes(data.is_active); + + if (!isActive && !isInactive) { + throw new Error('is_active 参数格式不正确'); + } + + if (isInactive) { + const activeChildren = await ctx.model.LocationZone.count({ + where: { + parent_id: id, + deleted_at: null, + is_active: 1, + }, + }); + + if (activeChildren > 0) { + throw new Error('请先禁用所有子分区'); + } + } + + updateData.is_active = isActive ? 1 : 0; + } + // 验证坐标是否重叠(如果修改了坐标) if ( - (data.x !== undefined || data.y !== undefined || data.length || data.width) && + (updateData.x !== undefined || updateData.y !== undefined || updateData.length || updateData.width) && zone.warehouse_id ) { - const x = data.x !== undefined ? data.x : zone.x; - const y = data.y !== undefined ? data.y : zone.y; - const z = data.z !== undefined ? data.z : zone.z || 0; - const length = data.length || zone.length; - const width = data.width || zone.width; - const height = data.height || zone.height || 0; + const x = updateData.x !== undefined ? updateData.x : zone.x; + const y = updateData.y !== undefined ? updateData.y : zone.y; + const z = updateData.z !== undefined ? updateData.z : zone.z || 0; + const length = updateData.length || zone.length; + const width = updateData.width || zone.width; + const height = updateData.height || zone.height || 0; const overlaps = await this.checkZoneOverlap( zone.warehouse_id, @@ -704,7 +727,7 @@ class LocationZoneService extends Service { } // 更新分区 - await zone.update(data); + await zone.update(updateData); return { success: true, @@ -725,7 +748,6 @@ class LocationZoneService extends Service { */ async deleteZone(id) { const { ctx } = this; - console.log('需要删除的id', id); try { const zone = await ctx.model.LocationZone.findOne({ where: { @@ -744,7 +766,7 @@ class LocationZoneService extends Service { deleted_at: null, }, }); - if (zone.zone_type == 'rack') { + if (zone.zone_type === 'rack') { // 货架执行删除需要检测库位是否还有库存 throw new Error('货架XX库位有库存,禁止删除,请先移库'); } @@ -765,14 +787,14 @@ class LocationZoneService extends Service { /** * 检查区域重叠 - * @param warehouseId - * @param x - * @param y - * @param z - * @param length - * @param width - * @param height - * @param excludeId + * @param {number|string} warehouseId 仓库ID + * @param {number} x X 坐标 + * @param {number} y Y 坐标 + * @param {number} z Z 坐标 + * @param {number} length 长度 + * @param {number} width 宽度 + * @param {number} height 高度 + * @param {number|string|null} excludeId 排除的分区ID * @private */ async checkZoneOverlap(warehouseId, x, y, z, length, width, height, excludeId) { @@ -936,7 +958,6 @@ class LocationZoneService extends Service { const spaces = []; let rackWidth = 0; let rackLength = 0; - const rackHeight = 0; let cellLength = 0; let cellWidth = 0; let cellHeight = 0; @@ -944,7 +965,6 @@ class LocationZoneService extends Service { let prelativeY = 0; let prelativeZ = 0; - rackWidth = rack.width; rackLength = rack.length; prelativeX = x; @@ -979,7 +999,7 @@ class LocationZoneService extends Service { spaces.push({ warehouse_id: rack.warehouse_id, zone_id: rackId, - location_type_id: row == 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储 + location_type_id: row === 1 ? 1 : 2, // 默认第一层为分拣,其他层为存储 space_code: spaceCode, row_no: row.toString(), column_no: column.toString(), @@ -1011,7 +1031,6 @@ class LocationZoneService extends Service { const { ctx } = this; try { - const path = []; const space = await ctx.model.LocationSpace.findOne({ where: { id, @@ -1030,7 +1049,7 @@ class LocationZoneService extends Service { } } async checkBarcodeUnique(id, barcode) { - const { ctx } = this; + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { // 检查条码是否被其他仓位使用(排除当前仓位) diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 2aed6c7..7ac776a 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -20,7 +20,12 @@ const MESSAGE_TYPE_MAP = Object.freeze({ const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; const DEFAULT_RETRY_DELAYS_MS = Object.freeze([ 3000, 6000, 12000 ]); const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/; -const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed' ]); +const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ + 'all', + '*', + 'receiving_completed', + 'store_warehouse_print_quantity_adjusted', +]); const DRIVER_TYPE_ALIASES = Object.freeze({ custom: 'customize', customize: 'customize', @@ -41,7 +46,7 @@ class NoticeService extends Service { /** * 根据 webhook 类型获取对应发送驱动。 * @param {string} [hookType='customize'] webhook 类型 - * @return {object} + * @return {object} webhook 驱动实例 */ getDriver(hookType = 'customize') { const normalizedHookType = String(hookType || 'customize').trim().toLowerCase() || 'customize'; @@ -83,7 +88,7 @@ class NoticeService extends Service { * 将传入值安全转换为对象。 * @param {*} value 原始值 * @param {object} [fallback={}] 转换失败时的兜底对象 - * @return {object} + * @return {object} 转换后的对象 */ toObject(value, fallback = {}) { if (!value) { @@ -109,7 +114,7 @@ class NoticeService extends Service { /** * 规范化订阅事件列表,支持数组、字符串和对象格式。 * @param {*} rawEvents 原始事件配置 - * @return {string[]} + * @return {string[]} 事件编码数组 */ normalizeEventList(rawEvents) { if (!rawEvents) { @@ -156,7 +161,7 @@ class NoticeService extends Service { * 判断当前 webhook 是否命中本次消息事件。 * @param {*} rawEvents 订阅的事件配置 * @param {object} payload 统一消息载荷 - * @return {boolean} + * @return {boolean} 是否命中 */ matchesEvents(rawEvents, payload) { const eventList = this.normalizeEventList(rawEvents); @@ -175,7 +180,7 @@ class NoticeService extends Service { /** * 生成本次通知的追踪 ID。 - * @return {string} + * @return {string} 追踪ID */ buildTraceId() { return `notice_${Date.now()}_${Math.random().toString(16).slice(2, 10)}`; @@ -183,7 +188,7 @@ class NoticeService extends Service { /** * 获取当前模型中已注册的事件编码列表。 - * @return {string[]} + * @return {string[]} 注册的事件编码列表 */ getRegisteredEventCodes() { const notificationWebhookModel = this.ctx.model && this.ctx.model.NotificationWebhook; @@ -211,7 +216,7 @@ class NoticeService extends Service { /** * 判断事件编码是否符合标识符式命名:仅允许小写字母、数字、下划线,且首字符不能为数字。 * @param {string} event 事件编码 - * @return {boolean} + * @return {boolean} 是否有效 */ isValidEventCode(event) { const normalizedEvent = String(event || '').trim().toLowerCase(); @@ -241,7 +246,7 @@ class NoticeService extends Service { /** * 获取通知失败后的重试间隔,默认按 3 秒、6 秒、12 秒阶梯重试。 * @param {object} [options={}] 原始通知入参 - * @return {number[]} + * @return {number[]} 重试间隔数组 */ getRetryDelays(options = {}) { const customDelays = Array.isArray(options.retryDelaysMs) @@ -270,7 +275,7 @@ class NoticeService extends Service { /** * 判断外部 webhook 返回是否可视为成功。 * @param {object} [result={}] 发送结果 - * @return {boolean} + * @return {boolean} 是否成功 */ isSuccessfulResponse(result = {}) { const status = Number(result && result.status || 0); @@ -314,7 +319,7 @@ class NoticeService extends Service { * @param {object} params 参数对象 * @param {object|null} [params.result=null] 最近一次发送结果 * @param {Error|null} [params.error=null] 最近一次异常 - * @return {string} + * @return {string} 失败原因 */ getFailureMessage({ result = null, error = null } = {}) { if (error && error.message) { @@ -404,7 +409,7 @@ class NoticeService extends Service { * @param {object} params 发送参数 * @param {object} params.hook webhook 配置 * @param {object} params.payload 标准化后的 payload - * @return {Promise} + * @return {Promise} 发送结果 */ async sendWithRetry({ hook, payload }) { const driver = this.getDriver(hook && hook.hook_type); @@ -469,7 +474,7 @@ class NoticeService extends Service { * 生成货主/仓库信息缓存键。 * @param {number|string} warehouseId 仓库主体 ID * @param {number|string} storeId 货主 ID - * @return {string} + * @return {string} 缓存键 */ getStoreInfoCacheKey(warehouseId, storeId) { return `warehouse:${Number(warehouseId || 0)}store:${Number(storeId || 0)}:info`; @@ -479,7 +484,7 @@ class NoticeService extends Service { * 解析货主信息,优先命中缓存,未命中时回查数据库并缓存 600 秒。 * @param {object} [options={}] 原始通知入参 * @param {object} [subject={}] 主体信息 - * @return {Promise} + * @return {Promise} 货主信息 */ async resolveStoreInfo(options = {}, subject = {}) { const directStore = this.toObject(options.store || options.owner, {}); @@ -569,7 +574,7 @@ class NoticeService extends Service { * 解析主体配置,优先使用入参,缺失时回查主体表。 * @param {object} [options={}] 原始通知入参 * @param {object} [subject={}] 主体信息 - * @return {Promise} + * @return {Promise} 主体配置 */ async resolveSubjectConfig(options = {}, subject = {}) { const storeModel = this.ctx.model && this.ctx.model.Store; @@ -611,7 +616,7 @@ class NoticeService extends Service { /** * 将业务入参整理为统一通知 payload。 * @param {object} [options={}] 发送入参 - * @return {Promise} + * @return {Promise} 标准化后的 payload */ async normalizePayload(options = {}) { const subject = this.toObject(options.subject, {}); @@ -704,7 +709,7 @@ class NoticeService extends Service { * 构建实际对外发送的统一消息体。 * @param {object} webhook webhook 配置 * @param {object} payload 标准化后的消息载荷 - * @return {object} + * @return {object} 对外发送载荷 */ buildOutgoingPayload(webhook, payload) { return { @@ -725,7 +730,7 @@ class NoticeService extends Service { /** * 获取当前主体允许发送的 webhook 数量上限。 * @param {object} [payload={}] 标准化后的消息载荷 - * @return {number} + * @return {number} 上限数量 */ getWebhookLimit(payload = {}) { const rawLimit = payload && payload.subject && payload.subject.config @@ -743,7 +748,7 @@ class NoticeService extends Service { /** * 根据主体、事件和上限筛选本次需要触达的 webhook。 * @param {object} payload 标准化后的消息载荷 - * @return {Promise} + * @return {Promise} webhook 列表 */ async findMatchedWebhooks(payload) { const webhookLimit = this.getWebhookLimit(payload); @@ -814,7 +819,7 @@ class NoticeService extends Service { /** * 统一通知发送入口:规范化消息、匹配 webhook 并执行分发。 * @param {object} [options={}] 发送入参 - * @return {Promise} + * @return {Promise} 发送汇总结果 */ async send(options = {}) { const payload = await this.normalizePayload(options); diff --git a/app/service/systems/notification.js b/app/service/systems/notification.js deleted file mode 100644 index 62287a3..0000000 --- a/app/service/systems/notification.js +++ /dev/null @@ -1,49 +0,0 @@ -const { Service } = require('egg'); - -class NotificationService extends Service { - constructor(ctx) { - super(ctx); - // 设置全局变量 oldAction - this.oldreceivingUrl = 'http://ye4s.wms.gztbyc.com/index/wms/wms/receiving_notic'; - - } - - /** - * 发送通知 - * @param {Object} options - 通知参数 - * @param {string} options.type - 通知类型,如 'email', 'sms', 'system' - * @param {string} options.title - 通知标题 - * @param {string} options.content - 通知内容 - * @param {string} options.bussinessType - 业务类型,如 'receiving' - * @param {string[]} [options.receivers] - 接收人列表 - * @param {string} options.bussinessId - 业务ID - * @return {Promise} 发送结果 - */ - async send(options) { - const { type, title, content, bussinessType, bussinessId, receivers = [] } = options; - switch (bussinessType) { - case 'receiving': - // 发送接收通知 - await this.ctx.curl(this.oldreceivingUrl, { - method: 'POST', - data: { - id: bussinessId, - }, - dataType: 'json', - }); - break; - } - return { - success: true, - message: '通知已发送', - data: { - type, - title, - content, - receivers, - }, - }; - } -} - -module.exports = NotificationService; diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 976adf0..2fb133d 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -93,7 +93,7 @@ class operationLogService extends Service { const item_tmp = JSON.parse(JSON.stringify(item)); item_tmp.operation_name = app.getOperationCodeName(item.operation_code); item_tmp.platform_name = app.getPlatformName(item.platform_code); - item_tmp.created_at = new Date(item_tmp.created_at).format(); + item_tmp.created_at = app.formatDate(item_tmp.created_at); return item_tmp; }), pagination: { @@ -104,23 +104,19 @@ class operationLogService extends Service { }, }; } catch (e) { - console.log(e); throw e; } - } - async queryOrderLogs() { - } async getMessageDetail(data) { const { id, type } = data; const { ctx } = this; - const warehouseId = ctx.user.store_id; let LogModel = null; switch (type) { case 'QIMEN': - // code LogModel = ctx.model.QimenLog; break; + default: + throw new Error(`不支持的日志类型: ${type}`); } const result = await LogModel.findOne({ where: { id } }); return result; diff --git a/app/service/systems/platform.js b/app/service/systems/platform.js index fa86c81..fe5337d 100644 --- a/app/service/systems/platform.js +++ b/app/service/systems/platform.js @@ -135,7 +135,6 @@ class PlatformService extends Service { * @return {Promise} 平台设置详情 */ async getPlatformSettingDetail(platformCode, warehouseId) { - const { ctx } = this; const cacheKey = `platform_setting_detail:${platformCode}:${warehouseId}`; try { diff --git a/app/service/systems/print/index.js b/app/service/systems/print/index.js index fd15ec2..f031d38 100644 --- a/app/service/systems/print/index.js +++ b/app/service/systems/print/index.js @@ -13,17 +13,15 @@ class PrintService extends Service { if (printerListResult) { // 记录上次更新时间,避免频繁发送更新指令 const printerData = JSON.parse(printerListResult); - console.log('printerData', printerData); lastUpdateTime = printerData.updatedAt || 0; } // 不管是否有打印机列表,都先发送指令让打印电脑更新打印机状态和列表 - const res = await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { + await this.ctx.curl(`${printServiceUrl}/sendToRoom`, { method: 'POST', contentType: 'json', data: { warehouse, computerId, method: 'printer.getWindowsPrinters', data: {} }, dataType: 'json', }); - console.log('lastUpdateTime', lastUpdateTime); // 等待异步获取打印机列表结果,最长等待5秒 const startTime = Date.now(); while (Date.now() - startTime < 5000) { @@ -31,7 +29,6 @@ class PrintService extends Service { printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); const printerData = JSON.parse(printerListResult); if (printerData.updatedAt && printerData.updatedAt > lastUpdateTime) { - console.log('打印机列表已更新', printerData.updatedAt); // 如果更新了打印机列表,跳出循环 break; } @@ -39,7 +36,6 @@ class PrintService extends Service { // 从redis获取打印机 printerListResult = await this.app.redis.get('printer').get(`printer:${computerId}:printerList`); const printerList = JSON.parse(printerListResult); - console.log('sendToComputer printerList', printerList); if (!printerList || !printerList.data || printerList.data.length === 0) { return { success: false, error: '未找到对应的打印机', detail: `computerId: ${computerId} 的打印机列表不存在` }; } @@ -48,7 +44,7 @@ class PrintService extends Service { if (!printerInfo) { return { success: false, error: `打印台没有打印机 ${printer}`, detail: `computerId: ${computerId} 的打印机列表中不存在 printer: ${printer}` }; } - if (printerInfo.workOffline == 'TRUE') { + if (printerInfo.workOffline === 'TRUE') { return { success: false, error: `打印机 ${printer} 处于脱机状态`, detail: `computerId: ${computerId} 的打印机 ${printer} 当前处于离线状态` }; } try { @@ -58,7 +54,6 @@ class PrintService extends Service { data: { warehouse, computerId, method: 'printer.print', data }, dataType: 'json', }); - console.log(res); return res.data; } catch (err) { diff --git a/app/service/systems/qimen_query.js b/app/service/systems/qimen_query.js index 0c378be..602932e 100644 --- a/app/service/systems/qimen_query.js +++ b/app/service/systems/qimen_query.js @@ -65,7 +65,7 @@ class QimenQueryService extends Service { v, sign_method: 'md5', customerId, - timestamp: new Date().format(), + timestamp: this.app.formatDate(new Date()), }; return param; } @@ -102,7 +102,6 @@ class QimenQueryService extends Service { try { // 判断 requestData 是否为字符串,如果是字符串则直接使用,否则进行转换 if (typeof requestData === 'string') { - console.log('requestData 是字符串,直接使用'); requestXml = requestData; // 可选:验证字符串是否是有效的XML @@ -110,7 +109,6 @@ class QimenQueryService extends Service { throw new Error('请求数据为空字符串'); } } else { - console.log('requestData 不是字符串,调用 formatResponse 进行转换'); requestXml = await this.ctx.service.qimen.formatResponse(requestData); } diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js index 6cd2314..185f96a 100644 --- a/app/service/systems/setting/account.js +++ b/app/service/systems/setting/account.js @@ -218,12 +218,9 @@ class SettingAccountService extends Service { let current = roleId; let keep = true; const visited = new Set(); + let parentId = Number(parentMap.get(current) || 0); - while (true) { - const parentId = Number(parentMap.get(current) || 0); - if (!Number.isFinite(parentId) || parentId <= 0) { - break; - } + while (Number.isFinite(parentId) && parentId > 0) { if (visited.has(parentId)) { break; } @@ -235,6 +232,7 @@ class SettingAccountService extends Service { } current = parentId; + parentId = Number(parentMap.get(current) || 0); } if (keep) { diff --git a/app/service/systems/setting/print_template.js b/app/service/systems/setting/print_template.js index 5e810ca..a808573 100644 --- a/app/service/systems/setting/print_template.js +++ b/app/service/systems/setting/print_template.js @@ -9,7 +9,6 @@ class PrintTemplateService extends Service { * @return {Promise} 模板列表 */ async listTemplatesByType(businessType) { - console.log('获取业务类型模板列表, businessType:', businessType); return await this.getTemplatesByType(businessType); } @@ -92,7 +91,6 @@ class PrintTemplateService extends Service { const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; - console.log(businessType, warehouseId); try { const templates = await ctx.model.PrintTemplate.findAll({ where: { @@ -107,7 +105,6 @@ class PrintTemplateService extends Service { [ 'create_at', 'DESC' ], ], }); - console.log(`查询到${templates.length}个模板,businessType: ${businessType}, warehouseId: ${warehouseId}`); return templates.map(template => { const { warehouse_id } = template; return { @@ -123,10 +120,8 @@ class PrintTemplateService extends Service { } } async save(data) { - const { ctx, app } = this; - const { Op } = app.Sequelize; + const { ctx } = this; const warehouseId = ctx.user.store_id; - console.log('保存打印模板数据:', data); const { id, template_name, business_type, page_width, page_height, template_content } = data; try { if (id) { @@ -571,11 +566,15 @@ class PrintTemplateService extends Service { layout += ``; } break; - case 'table': + case 'table': { const tableContent = this.renderTable(el, index); layout += `${tableContent}
`; break; + } case 'shape': + break; + default: + break; } return `${layout} @@ -612,18 +611,24 @@ class PrintTemplateService extends Service { return styleText; } renderTable(el, index) { - const tableText = ''; - const rows = el.rows || []; - // 表头 - let headerTds = ''; - let bodyTds = '<% for(var i=0; i<(_data.items.length); i++) { %>'; - for (let i = 0; i < el.rows; i++) { + const rows = Array.isArray(el.rows) ? el.rows : []; + const fieldCode = String(el.field_code || '').trim(); - headerTds += `${el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`}`; - bodyTds += `]]>`; + if (!fieldCode || rows.length === 0) { + return ''; } + + let headerTds = ''; + let bodyTds = '<% const tableRows = Array.isArray(_data.items) ? _data.items : []; for (var rowIndex = 0; rowIndex < tableRows.length; rowIndex++) { %>'; + + for (let i = 0; i < rows.length; i++) { + const headerText = el.headers && el.headers[i] ? el.headers[i] : `列${i + 1}`; + headerTds += `${headerText}`; + bodyTds += `]]>`; + } + headerTds += ''; - bodyTds += '<%}%>'; + bodyTds += '<% } %>'; return headerTds + bodyTds; } } diff --git a/app/service/systems/sign.js b/app/service/systems/sign.js index 2fecd2d..32667b6 100644 --- a/app/service/systems/sign.js +++ b/app/service/systems/sign.js @@ -158,8 +158,9 @@ class SignService extends Service { /** * HMAC MD5加密 - * @param data - * @param secret + * @param {string} data 待签名内容 + * @param {string} secret 签名密钥 + * @return {Buffer} 加密结果 */ encryptHMAC(data, secret) { const hmac = crypto.createHmac('md5', secret); @@ -169,8 +170,9 @@ class SignService extends Service { /** * HMAC SHA256加密 - * @param data - * @param secret + * @param {string} data 待签名内容 + * @param {string} secret 签名密钥 + * @return {Buffer} 加密结果 */ encryptHMACSHA256(data, secret) { const hmac = crypto.createHmac('sha256', secret); @@ -180,7 +182,8 @@ class SignService extends Service { /** * MD5加密 - * @param data + * @param {string} data 待签名内容 + * @return {Buffer} 加密结果 */ encryptMD5(data) { return crypto.createHash('md5').update(data, 'utf8').digest(); @@ -188,7 +191,8 @@ class SignService extends Service { /** * 二进制转十六进制字符串(大写) - * @param bytes + * @param {Buffer} bytes 二进制数据 + * @return {string} 十六进制字符串 */ byte2hex(bytes) { return Buffer.from(bytes).toString('hex').toUpperCase(); diff --git a/app/service/systems/space.js b/app/service/systems/space.js index 7c20188..eea4b75 100644 --- a/app/service/systems/space.js +++ b/app/service/systems/space.js @@ -2,9 +2,6 @@ const Service = require('egg').Service; class spaceService extends Service { - constructor(ctx) { - super(ctx); - } async searchSpace(data) { const { ctx, app } = this; const { keyword } = data; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 76a2b93..cbe2292 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -9,13 +9,9 @@ const { } = require('../../lib/query_condition_parser'); class stockStoreService extends Service { - constructor(ctx) { - super(ctx); - } async create(stockData) { const { app, - ctx, service, } = this; const warehouseId = stockData.warehouse_id; @@ -139,6 +135,7 @@ class stockStoreService extends Service { return result; } async convertToQimenFormat(stockData) { + const { app } = this; const result = { // 商品信息 item: { @@ -175,22 +172,20 @@ class stockStoreService extends Service { // 其他信息 barCode: stockData.barcode || '', isValid: stockData.is_valid === 'Y' ? 'Y' : 'N', - createTime: stockData.create_time ? new Date(stockData.create_time).format() : '', + createTime: stockData.create_time ? app.formatDate(stockData.create_time) : '', }, }; return result; } async getItemInfoWithCache(itemId) { const { - ctx, - app, - } = this; // 使用 ctx.model 而非 app.model + app, ctx, + } = this; const cacheKey = `item:info:${itemId}`; try { // 1. 尝试从缓存获取 const cached = await app.getCacheAsync(cacheKey); - console.log('缓存》》》》', cached); if (cached !== null && cached !== undefined) { app.logger.debug('[ItemCacheHit]', itemId); @@ -204,7 +199,6 @@ class stockStoreService extends Service { // 2. 缓存未命中,查询数据库 app.logger.debug('[ItemCacheMiss]', itemId); - console.log('缓存》》》》', itemId); // ⭐ 关键修复:使用 raw: true 获取纯对象 const itemInfo = await ctx.model.StockStore.findByPk(itemId, { @@ -226,7 +220,6 @@ class stockStoreService extends Service { await app.setCacheAsync(cacheKey, nullMarker, 120); return null; // 明确返回 null - } catch (error) { app.logger.error('[getItemInfoWithCache] 查询失败', { itemId, @@ -253,7 +246,6 @@ class stockStoreService extends Service { // 数据库也失败,向上抛出 throw new Error(`查询商品信息失败: ${dbError.message}`); } - throw error; } } async getItemStorages(itemId, transaction) { @@ -387,7 +379,7 @@ class stockStoreService extends Service { /** * 计算缓存时间 - * @param storage + * @param {Object} storage - 库存对象 */ _calculateCacheTTL(storage) { if (!storage || !storage._exists || !storage._isValid) { @@ -407,7 +399,7 @@ class stockStoreService extends Service { /** * 清理缓存 - * @param itemId + * @param {number|string} itemId - 商品ID */ async clearItemStorageCache(itemId) { const { @@ -509,10 +501,9 @@ class stockStoreService extends Service { } // 3. 执行锁定/释放操作 - let updateResult; if (isLocking) { // 加锁:增加 locked_quantity - updateResult = await stockRecord.increment('locked_quantity', { + await stockRecord.increment('locked_quantity', { by: absQty, transaction, silent: true, @@ -522,7 +513,7 @@ class stockStoreService extends Service { ); } else { // 减锁:减少 locked_quantity(确保不小于0) - updateResult = await stockRecord.decrement('locked_quantity', { + await stockRecord.decrement('locked_quantity', { by: absQty, transaction, silent: true, @@ -609,15 +600,13 @@ class stockStoreService extends Service { return stockResult; } const { - stock, storage, } = stockResult.data; // 3. 执行库存增加 - let result; if (storage.exists) { // 非首次入库:更新现有记录(只增加quantity) - result = await ctx.model.StockWarehouse.increment('quantity', { + await ctx.model.StockWarehouse.increment('quantity', { by: inboundQty, where: { id: storage.id, @@ -713,7 +702,6 @@ class stockStoreService extends Service { } const { - stock, storage, } = stockResult.data; @@ -1021,7 +1009,6 @@ class stockStoreService extends Service { const { ctx, app, - config, } = this; const { Sequelize, @@ -1347,12 +1334,6 @@ class stockStoreService extends Service { const itemBarcodes = barcodes .filter(barcode => barcode.stock_id === item.id) .map(barcode => barcode.barcode); - const { - cos, - } = config; - const { - cdnurl, - } = cos; const itemImages = images .filter(images => parseInt(images.business_id) === item.id) .map(images => images.file.file_url); @@ -1384,7 +1365,6 @@ class stockStoreService extends Service { }), }; - return { code: 200, data: { @@ -1463,7 +1443,6 @@ class stockStoreService extends Service { return normalizeDateUtil(value); } - /** * 格式化日期显示 * @param {string} dateString - 日期字符串 @@ -1570,13 +1549,12 @@ class stockStoreService extends Service { return barcodes; } async handleBatchChange() { - const { ctx, service, app } = this; + const { ctx, app } = this; const { Op } = app.Sequelize; const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'managementFlags', 'stock_unit' ]; const { ids, method, value } = ctx.request.body; - console.log('批量修改参数', ctx.request.body); try { // 1. 参数验证 @@ -1713,7 +1691,6 @@ class stockStoreService extends Service { const { ctx, service, } = this; - console.log('条码修改提交', data); const { id, barcodes, @@ -1792,14 +1769,12 @@ class stockStoreService extends Service { const { ctx, } = this; - console.log(data); const { stock_id = null, store_id = null, page = 1, pageSize = 20, item_code = '', item_name = '', } = data || {}; const warehouseId = ctx.user.store_id; let barcodes = []; let warehouseStock = null; - console.log(stock_id); let total = 0; if (stock_id) { barcodes = await ctx.model.StockStore.findAll({ @@ -1891,11 +1866,10 @@ class stockStoreService extends Service { }), ]); } - console.log('barcodes>>>>', barcodes); const results = barcodes.map(item => { return { app_key: item.app_key, - create_from: item.create_from == 'qimen' ? '奇门' : 'API', + create_from: item.create_from === 'qimen' ? '奇门' : 'API', id: item.id, app_name: item.app_key, item_code: item.item_code, @@ -1904,9 +1878,7 @@ class stockStoreService extends Service { item_name: item.item_name, }; }); - console.log('warehouseStock>>>', warehouseStock); const get_store_id = warehouseStock ? warehouseStock.store_id : barcodes[0]['warehouse_stock.store_id']; - console.log('get_store_id>>>', get_store_id); return { rows: results, store_id: get_store_id, @@ -1963,7 +1935,6 @@ class stockStoreService extends Service { }); return 1; } catch (e) { - console.log(e); throw e; } } @@ -2000,7 +1971,6 @@ class stockStoreService extends Service { }); return 1; } catch (e) { - console.log(e); throw e; } } @@ -2058,7 +2028,7 @@ class stockStoreService extends Service { const { ctx, service } = this; const warehouseId = ctx.user.store_id; const { - item_code, store_id, item_name, sku_property, stock_unit, + item_code, item_name, sku_property, stock_unit, packing_requirements, length, width, height, volume, gross_weight, net_weight, tag_price, retail_price, is_sn_mgmt, is_shelf_life_mgmt, is_batch_mgmt, @@ -2123,16 +2093,15 @@ class stockStoreService extends Service { box_remark, updated_at: new Date(), }; - console.log('更新数据', updateData); // 5. 清除空值 Object.keys(updateData).forEach(key => { - if (key != 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) { + if (key !== 'prohibited_id' && (updateData[key] === undefined || updateData[key] === null)) { delete updateData[key]; } }); // 6. 执行更新 - const [ affectedRows ] = await ctx.model.StockWarehouse.update(updateData, { + await ctx.model.StockWarehouse.update(updateData, { where: { id, warehouse_id: ctx.user.store_id, @@ -2187,7 +2156,7 @@ class stockStoreService extends Service { prohibited_id, brand_name, managementFlags, enable_box_spec, box_unit, quantity_per_box, box_gross_weight, box_net_weight, box_length, - box_width, box_height, box_volume, box_remark, id, barcode, + box_width, box_height, box_volume, box_remark, barcode, } = data; // 1. 参数验证 @@ -2196,7 +2165,6 @@ class stockStoreService extends Service { try { checkItemCodeUnique = await this.checkItemCodeUnique(null, item_code, store_id, warehouseId); } catch (e) { - console.log(e); throw (e); } if (checkItemCodeUnique && !checkItemCodeUnique.isUnique) { @@ -2248,7 +2216,6 @@ class stockStoreService extends Service { const toCreate = barcodes_arr.filter(item => !existingFileIds.includes(item)); // 批量操作 const promises = []; - console.log('createdRecord', createdRecord.id); if (toCreate.length > 0) { const refData = toCreate.map(item => ({ stock_id: createdRecord.id, @@ -2256,7 +2223,6 @@ class stockStoreService extends Service { warehouse_id: warehouseId, created_at: new Date(), })); - console.log('refData', refData); promises.push(ctx.model.StockBarcode.bulkCreate(refData, { transaction })); await Promise.all(promises); } @@ -2275,7 +2241,6 @@ class stockStoreService extends Service { await transaction.commit(); return await this.getInfo({ id: createdRecord.id }); } catch (e) { - console.log(e); if (transaction) { await transaction.rollback(); } @@ -2308,10 +2273,10 @@ class stockStoreService extends Service { } } async stockLog() { - + return undefined; } async checkItemCodeUnique(id, item_code, store_id, warehouse_id) { - const { ctx } = this; + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; try { // 检查条码是否被其他仓位使用(排除当前仓位) @@ -2349,7 +2314,7 @@ class stockStoreService extends Service { } } async handleBatchDelete(data) { - const { ctx } = this; + const { ctx, app } = this; const { Op } = this.app.Sequelize || app.Sequelize; const { ids } = data; @@ -2379,8 +2344,6 @@ class stockStoreService extends Service { attributes: [ 'id', 'item_name', 'quantity', 'return_quantity' ], }); - console.log('查询到的商品资料:', JSON.stringify(products, null, 2)); - if (products.length === 0) { return { code: 200, message: '未找到对应的商品资料或已删除', data: [] }; } @@ -2423,9 +2386,6 @@ class stockStoreService extends Service { } }); - console.log('可以删除的商品:', deletableProducts); - console.log('不能删除的商品:', undeletableProducts); - if (deletableProducts.length === 0) { return { code: 405, @@ -2511,7 +2471,7 @@ class stockStoreService extends Service { } async deleteUnit(data) { const { id } = data; - const { ctx, app } = this; + const { ctx } = this; const unitExit = await ctx.model.StockUnit.findOne({ where: { id, @@ -2531,7 +2491,7 @@ class stockStoreService extends Service { } async deleteProhibited(data) { const { id } = data; - const { ctx, app } = this; + const { ctx } = this; const unitExit = await ctx.model.ProhibitedType.findOne({ where: { id, @@ -2550,7 +2510,7 @@ class stockStoreService extends Service { return { message: '删除成功', code: 200 }; } async search(data) { - const { keyword, store_id = null } = data; + const { keyword, store_id = null, with_stock = false, is_batch = false } = data; const { ctx, app } = this; const { Op } = app.Sequelize; const warehouseId = ctx.user.store_id; @@ -2617,7 +2577,6 @@ class stockStoreService extends Service { })); // 执行查询 - console.log('查询商品===》'); const results = await app.model.StockWarehouse.findAll({ where: whereCondition, attributes: [ @@ -2641,6 +2600,78 @@ class stockStoreService extends Service { return result; }); + // with_stock=true 时关联查询库存数据 + if (with_stock && formattedResults.length > 0) { + const stockIds = formattedResults.map(r => r.id); + const storageWhere = { + stock_id: { [Op.in]: stockIds }, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }; + + const storageRows = await app.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'inbound_order_no', 'supplier_batch_no', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }], + order: [[ 'created_at', 'DESC' ]], + }); + + // 按 stock_id 分组 + const storageMap = new Map(); + for (const row of storageRows) { + const plain = row.get({ plain: true }); + const key = plain.stock_id; + if (!storageMap.has(key)) { + storageMap.set(key, []); + } + storageMap.get(key).push(plain); + } + + for (const item of formattedResults) { + const storageList = storageMap.get(item.id) || []; + + if (is_batch) { + // is_batch=true:逐条批次明细返回,不分组 + item.storage = storageList; + } else { + // is_batch=false(默认):按库位分组汇总 + const mergedMap = new Map(); + for (const s of storageList) { + const spaceKey = s.space_id; + if (mergedMap.has(spaceKey)) { + const existing = mergedMap.get(spaceKey); + existing.quantity += Number(s.quantity) || 0; + existing.locked_quantity += Number(s.locked_quantity) || 0; + existing.available_quantity = existing.quantity - existing.locked_quantity; + } else { + const quantity = Number(s.quantity) || 0; + const lockedQuantity = Number(s.locked_quantity) || 0; + mergedMap.set(spaceKey, { + space_id: s.space_id, + inventory_type: s.inventory_type, + quantity, + locked_quantity: lockedQuantity, + available_quantity: quantity - lockedQuantity, + space: s.space, + }); + } + } + item.storage = Array.from(mergedMap.values()); + } + } + } + return { code: 200, data: formattedResults, @@ -2655,5 +2686,161 @@ class stockStoreService extends Service { }; } } + + /** + * 查询商品的库存明细(storage 表)。 + * @param {Object} data 请求体 + * @param {number} data.stock_id 商品库存ID(stock_warehouse.id) + * @param {Object} [data.pagination] 分页参数 + * @return {Promise} 库存明细分页结果 + */ + async getStockDetail(data) { + const { ctx, app } = this; + const warehouseId = ctx.user.store_id; + const { stock_id, pagination = {}, group_by_batch = false } = data; + + if (!stock_id) { + return { code: 0, message: '参数 stock_id 不能为空' }; + } + + try { + // 校验商品归属当前仓库 + const stockItem = await app.model.StockWarehouse.findOne({ + where: { + id: stock_id, + warehouse_id: warehouseId, + deleted_at: null, + }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'quantity', 'locked_quantity' ], + raw: true, + }); + + if (!stockItem) { + return { code: 0, message: '商品不存在或不属于当前仓库' }; + } + + const { page = 1, pageSize = 20 } = pagination; + const offset = (page - 1) * pageSize; + + const storageWhere = { + stock_id, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }; + + if (group_by_batch) { + // 区分批次:按原逻辑返回每一条库存明细 + const { count, rows } = await app.model.Storage.findAndCountAll({ + where: storageWhere, + attributes: [ + 'id', 'space_id', 'batch_no', 'inventory_type', + 'quantity', 'locked_quantity', 'available_quantity', + 'production_date', 'expiry_date', 'inbound_time', + 'inbound_order_no', 'supplier_batch_no', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }], + order: [[ 'created_at', 'DESC' ]], + offset, + limit: pageSize, + }); + + return { + code: 200, + data: { + stockItem, + storageList: rows, + pagination: { + page, + pageSize, + total: count, + }, + }, + }; + } + + // 不区分批次:按 space_id 合并库存数据 + const allRows = await app.model.Storage.findAll({ + where: storageWhere, + attributes: [ + 'id', 'space_id', 'inventory_type', + 'quantity', 'locked_quantity', 'created_at', + ], + include: [{ + model: app.model.LocationSpace, + as: 'space', + attributes: [ + 'id', + 'space_code', + 'custom_name', + ], + required: false, + }], + order: [ + [ + 'created_at', + 'DESC', + ], + ], + }); + + // 按 space_id 合并 + const mergedMap = new Map(); + for (const row of allRows) { + const plain = row.get({ plain: true }); + const key = plain.space_id; + if (mergedMap.has(key)) { + const existing = mergedMap.get(key); + existing.quantity += Number(plain.quantity) || 0; + existing.locked_quantity += Number(plain.locked_quantity) || 0; + existing.available_quantity = existing.quantity - existing.locked_quantity; + } else { + const quantity = Number(plain.quantity) || 0; + const lockedQuantity = Number(plain.locked_quantity) || 0; + mergedMap.set(key, { + id: plain.id, + space_id: plain.space_id, + batch_no: null, + inventory_type: plain.inventory_type, + quantity, + locked_quantity: lockedQuantity, + available_quantity: quantity - lockedQuantity, + production_date: null, + expiry_date: null, + inbound_time: null, + inbound_order_no: null, + supplier_batch_no: null, + created_at: plain.created_at, + space: plain.space, + }); + } + } + + const mergedList = Array.from(mergedMap.values()); + const total = mergedList.length; + const storageList = mergedList.slice(offset, offset + pageSize); + + return { + code: 200, + data: { + stockItem, + storageList, + pagination: { + page, + pageSize, + total, + }, + }, + }; + } catch (error) { + ctx.logger.error(`查询商品库存明细失败, stock_id: ${stock_id}`, error); + return { code: 0, message: '查询库存明细失败,请稍后重试' }; + } + } } module.exports = stockStoreService; diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js new file mode 100644 index 0000000..f975737 --- /dev/null +++ b/app/service/systems/stock_transaction.js @@ -0,0 +1,125 @@ +'use strict'; + +const Service = require('egg').Service; + +class StockTransactionService extends Service { + + async list(pageParams = {}, sortParams = {}, groupByBatch = false) { + const { ctx, app } = this; + const { Op, fn, col, literal } = app.Sequelize; + + const warehouseId = ctx.user.store_id; + const { page = 1, pageSize = 20 } = pageParams; + const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + + // 基础条件:当前仓库 + const baseWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + ], + }; + + // 动态 where 条件 + const parsed = ctx.whereParsed; + if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { + baseWhere[Op.and].push(...parsed.dynamicConditions); + } + + const offset = (page - 1) * pageSize; + const limit = pageSize; + + if (groupByBatch) { + // 按批次明细:保持原有逻辑 + const { count: total, rows } = await ctx.model.StockTransaction.findAndCountAll({ + where: baseWhere, + order: [[ sortField, sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockItem', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + ], + }); + + const list = rows.map(item => { + const row = item.get({ plain: true }); + row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + // 不按批次:按 stock_id + space_id + transaction_type + inventory_type 合并 + const groupFields = [ 'stock_id', 'space_id', 'transaction_type', 'inventory_type', 'warehouse_id', 'store_id', 'order_type' ]; + + // 先查总数(分组后的组数) + const countResult = await ctx.model.StockTransaction.count({ + where: baseWhere, + group: groupFields, + }); + const total = Array.isArray(countResult) ? countResult.length : countResult; + + // 查分组数据 + const rows = await ctx.model.StockTransaction.findAll({ + where: baseWhere, + attributes: [ + 'stock_id', + 'space_id', + 'transaction_type', + 'inventory_type', + 'warehouse_id', + 'store_id', + 'order_type', + [ fn('SUM', col('stock_transaction.quantity')), 'quantity' ], + [ fn('MIN', col('stock_transaction.created_at')), 'first_created_at' ], + [ fn('MAX', col('stock_transaction.created_at')), 'last_created_at' ], + [ fn('COUNT', col('stock_transaction.id')), 'record_count' ], + ], + group: groupFields, + order: [[ literal('last_created_at'), sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stockItem', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + const list = rows.map(row => { + row.first_created_at = row.first_created_at ? app.formatDate(row.first_created_at) : ''; + row.last_created_at = row.last_created_at ? app.formatDate(row.last_created_at) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } +} + +module.exports = StockTransactionService; diff --git a/app/service/systems/storage/index.js b/app/service/systems/storage/index.js index f113ac8..613f0c2 100644 --- a/app/service/systems/storage/index.js +++ b/app/service/systems/storage/index.js @@ -2,9 +2,6 @@ const Service = require('egg').Service; class IndexService extends Service { - async index() { - - } async findByStockAndBatch(stockId, batchNo, inventoryType = 'ZP') { const { ctx } = this; diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js new file mode 100644 index 0000000..1cdd5c0 --- /dev/null +++ b/app/service/systems/storage/inventory.js @@ -0,0 +1,1856 @@ +'use strict'; + +const Service = require('egg').Service; + +class InventoryService extends Service { + + /** + * 收货单快捷入库上架。 + * 从收货单直接生成入库单并写入库存。 + * + * 流程: + * 1. 校验收货单状态(必须 completed) + * 2. 校验所有明细已匹配系统商品(system_product_id 不为空) + * 3. 校验未全部入库(storage_status !== 'all') + * 4. 事务内: + * a. 创建入库单(EntryOrder)和入库明细(EntryItems) + * b. 逐条锁定 StockWarehouse 行,增加 quantity + * c. 写入/更新 wms_storage 库存记录 + * d. 更新 receiving_detail 的 storage_status 和 stored_quantity + * e. 更新 receiving 的 storage_status + * + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} code/data/message 结构 + */ + async quickPutaway(data = {}) { + const { ctx, app } = this; + const warehouseId = ctx.user.store_id; + const receivingId = Number(data.receiving_id || data.id || 0); + + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + const transaction = await ctx.model.transaction(); + + try { + // ────────── 1. 查询并锁定收货单 ────────── + const receiving = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + }], + }); + + if (!receiving) { + await transaction.rollback(); + return { code: 404, message: '收货单不存在或无权访问', data: null }; + } + + // ────────── 2. 状态校验 ────────── + if (receiving.status !== 'completed') { + await transaction.rollback(); + return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null }; + } + + if (receiving.storage_status === 'all') { + await transaction.rollback(); + return { code: 400, message: '该收货单已全部入库,无需重复操作', data: null }; + } + + const details = receiving.details || []; + if (!details.length) { + await transaction.rollback(); + return { code: 400, message: '收货单没有明细,无法入库', data: null }; + } + + // ────────── 3. 校验所有明细已匹配系统商品 ────────── + const unmatchedDetails = details.filter(d => !d.system_product_id); + if (unmatchedDetails.length > 0) { + await transaction.rollback(); + const names = unmatchedDetails.map(d => d.product_name).join('、'); + return { + code: 400, + message: `以下商品未匹配系统商品,请先绑定:${names}`, + data: { unmatched_count: unmatchedDetails.length, unmatched_names: names }, + }; + } + + // 过滤出需要入库的明细(排除已全部入库的) + const pendingDetails = details.filter(d => d.storage_status !== 'all'); + if (!pendingDetails.length) { + await transaction.rollback(); + return { code: 400, message: '所有明细已入库完成', data: null }; + } + + // ────────── 4. 创建入库单 ────────── + // 获取仓库名称快照 + let warehouseName = ''; + const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); + if (warehouseData.code === 200 && warehouseData.data) { + warehouseName = warehouseData.data.company_name || ''; + } + + // 获取合约表备注名称(优先使用) + const contract_data = await ctx.service.systems.store.getStoreRemaskName(receiving.store_id, warehouseId); + let contract = null; + if (contract_data.code === 200) { + contract = contract_data.data; + } + + const entryOrderCode = `SCRK${Date.now()}${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`; + const entryOrder = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: 'SCRK', + purchase_order_code: receiving.receiving_number || '', + total_order_lines: pendingDetails.length, + order_create_time: new Date(), + source_type: 'WMS', + order_status: 'CREATED', + sync_status: 'SUCCESS', + sync_message: `快捷入库-来自收货单 ${receiving.receiving_number}`, + is_enabled: 1, + warehouse_id: warehouseId, + store_id: receiving.store_id || warehouseId, + store_name: contract?.store_remask || receiving.store_name || '', + warehouse_name: contract?.warehouse_remask || warehouseName, + remark: `快捷入库,关联收货单 ${receiving.receiving_number}`, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + + // ────────── 5. 逐条处理明细:创建入库明细 + 更新库存 ────────── + const results = []; + const errors = []; + + for (let i = 0; i < pendingDetails.length; i++) { + const detail = pendingDetails[i]; + const stockWarehouseId = detail.system_product_id; + const inboundQty = (detail.actual_quantity || 0) - (detail.stored_quantity || 0); + + if (inboundQty <= 0) { + continue; // 已入库完的跳过 + } + + // 5a. 锁定 StockWarehouse 行 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { + id: stockWarehouseId, + is_valid: 'Y', + deleted_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + errors.push(`商品 ${detail.product_name} 的库存记录不存在 (stock_id: ${stockWarehouseId})`); + continue; + } + + // 5b. 增加 StockWarehouse 库存数量 + await stockRecord.increment('quantity', { + by: inboundQty, + transaction, + silent: true, + }); + + // 5c. 写入/更新 wms_storage 库存位置表 + const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 + const batchNo = detail.batch_number || receiving.receiving_number || entryOrderCode; + const inventoryType = 'ZP'; // 默认正品 + + // 查找是否已有相同 库位+SKU+批次+类型 的库存记录 + let storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockWarehouseId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (storageRecord) { + // 已有记录:累加数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), + entry_order_id: entryOrder.id, + }, { + where: { id: storageRecord.id }, + transaction, + }); + } else { + // 新建库存记录 + storageRecord = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: receiving.store_id || warehouseId, + space_id: spaceId, + stock_id: stockWarehouseId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: inboundQty, + locked_quantity: 0, + available_quantity: inboundQty, + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + inbound_time: new Date(), + inbound_order_no: entryOrderCode, + receiving_id: receivingId, + entry_order_id: entryOrder.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + + // 5d. 创建入库明细 + await ctx.model.EntryItems.create({ + order_id: entryOrder.id, + order_line_no: i + 1, + item_code: stockRecord.item_code || '', + item_id: stockWarehouseId, + count: inboundQty, + inventory_type: inventoryType, + stock_id: stockWarehouseId, + received_quantity: inboundQty, + confirm_quantity: inboundQty, + }, { transaction }); + + // 5d+. 写入出入库记录 + await ctx.model.StockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: receiving.store_id || warehouseId, + stock_id: stockWarehouseId, + storage_id: storageRecord.id, + space_id: spaceId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'SCRK', + order_no: entryOrderCode, + order_id: entryOrder.id, + receiving_id: receivingId, + entry_order_id: entryOrder.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: `快捷入库-收货单 ${receiving.receiving_number}`, + created_at: new Date(), + }, { transaction }); + + // 5e. 更新收货明细的入库状态 + const newStoredQty = (detail.stored_quantity || 0) + inboundQty; + const detailStorageStatus = newStoredQty >= detail.actual_quantity ? 'all' : 'partial'; + await ctx.model.ReceivingDetail.update({ + storage_status: detailStorageStatus, + stored_quantity: newStoredQty, + }, { + where: { id: detail.id }, + transaction, + }); + + results.push({ + detail_id: detail.id, + product_name: detail.product_name, + stock_warehouse_id: stockWarehouseId, + inbound_quantity: inboundQty, + space_id: spaceId, + storage_status: detailStorageStatus, + }); + } + + // 如果全部明细都失败 + if (results.length === 0 && errors.length > 0) { + await transaction.rollback(); + return { + code: 400, + message: `入库失败:${errors.join(';')}`, + data: null, + }; + } + + // ────────── 6. 更新入库单状态 ────────── + await entryOrder.update({ + order_status: 'COMPLETED', + total_order_lines: results.length, + updated_at: new Date(), + }, { transaction }); + + // ────────── 7. 更新收货单入库状态 ────────── + const allDetailsStored = details.every(d => { + if (d.storage_status === 'all') return true; + // 检查本次入库后是否全部完成 + const pending = pendingDetails.find(p => p.id === d.id); + if (!pending) return true; + const newStored = (pending.stored_quantity || 0) + ((pending.actual_quantity || 0) - (pending.stored_quantity || 0)); + return newStored >= pending.actual_quantity; + }); + const receivingStorageStatus = allDetailsStored ? 'all' : 'partial'; + + await ctx.model.Receiving.update({ + storage_status: receivingStorageStatus, + }, { + where: { id: receivingId }, + transaction, + }); + + // ────────── 8. 提交事务 ────────── + await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry', + businessId: entryOrder.id, + operationCode: 'QUICK_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[quickPutaway] 写入操作日志失败,不影响业务', logErr); + } + + ctx.logger.info('[quickPutaway] 快捷入库完成', { + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + entry_order_code: entryOrderCode, + entry_order_id: entryOrder.id, + total_items: results.length, + errors: errors.length, + }); + + return { + code: 200, + message: errors.length + ? `入库部分完成,${results.length} 条成功,${errors.length} 条失败` + : '快捷入库完成', + data: { + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + receiving_storage_status: receivingStorageStatus, + entry_order: { + id: entryOrder.id, + entry_order_code: entryOrderCode, + order_status: 'COMPLETED', + }, + items: results, + errors: errors.length ? errors : undefined, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[quickPutaway] 快捷入库异常', { + receiving_id: receivingId, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { + code: 409, + message: '库存记录被锁定,请稍后重试', + data: null, + }; + } + + throw error; + } + } + + /** + * 匹配入库:将已完成收货的收货单与已有入库单按 stock_warehouse_id 做数量匹配入库。 + * + * @param {Object} data 请求体 + * @param {number[]} data.receiving_ids 收货单ID列表 + * @param {number[]} data.entry_order_ids 入库单ID列表 + * @return {Promise} code/data/message 结构 + */ + async matchPutaway(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const warehouseId = ctx.user.store_id; + + // ────────── 1. 参数校验 ────────── + const receivingIds = Array.isArray(data.receiving_ids) ? data.receiving_ids.map(Number).filter(Boolean) : []; + const entryOrderIds = Array.isArray(data.entry_order_ids) ? data.entry_order_ids.map(Number).filter(Boolean) : []; + + if (!receivingIds.length) { + return { code: 400, message: 'receiving_ids 不能为空', data: null }; + } + if (!entryOrderIds.length) { + return { code: 400, message: 'entry_order_ids 不能为空', data: null }; + } + + // ────────── 2. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 3. 查询并锁定收货单 ────────── + const receivings = await ctx.model.Receiving.findAll({ + where: { + id: { [Op.in]: receivingIds }, + warehouse_id: warehouseId, + status: 'completed', + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'details', + required: false, + }], + }); + + if (!receivings.length) { + await transaction.rollback(); + return { code: 404, message: '未找到符合条件的收货单', data: null }; + } + + // ────────── 4. 查询并锁定入库单 ────────── + const entryOrders = await ctx.model.EntryOrder.findAll({ + where: { + id: { [Op.in]: entryOrderIds }, + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + order_status: { [Op.in]: [ 'PENDING', 'CONFIRMED', 'PARTIAL_RECEIVED', 'CREATED' ] }, + }, + lock: transaction.LOCK.UPDATE, + transaction, + include: [{ + model: ctx.model.EntryItems, + as: 'items', + required: false, + }], + }); + + if (!entryOrders.length) { + await transaction.rollback(); + return { code: 404, message: '未找到符合条件的入库单', data: null }; + } + + // ────────── 5. 按 stock_warehouse_id 汇总 ────────── + // 收货侧:可入库明细(排除已全部入库的) + const rcvDetailsBySWId = {}; // stock_warehouse_id -> [ detail, ... ] + for (const rcv of receivings) { + for (const d of (rcv.details || [])) { + if (d.storage_status === 'all') continue; + if (!d.system_product_id) continue; + const available = (d.actual_quantity || 0) - (d.stored_quantity || 0); + if (available <= 0) continue; + const key = d.system_product_id; + if (!rcvDetailsBySWId[key]) rcvDetailsBySWId[key] = []; + rcvDetailsBySWId[key].push({ detail: d, available, receiving: rcv }); + } + } + + // 入库侧:待入库明细 + const entryItemsBySWId = {}; // stock_warehouse_id -> [ item, ... ] + for (const eo of entryOrders) { + for (const item of (eo.items || [])) { + if (!item.stock_id) continue; + const remaining = (item.count || 0) - (item.received_quantity || 0); + if (remaining <= 0) continue; + const key = item.stock_id; + if (!entryItemsBySWId[key]) entryItemsBySWId[key] = []; + entryItemsBySWId[key].push({ item, remaining, entryOrder: eo }); + } + } + + // ────────── 6. 逐个 stock_warehouse_id 执行匹配 ────────── + const matchedItems = []; + const unmatchedProducts = []; + const warnings = []; + + // 跟踪各明细的累计分配量 + const rcvDetailAllocated = {}; // detail.id -> allocated qty + const entryItemAllocated = {}; // item.id -> allocated qty + + // 取交集 key + const allSWIds = new Set([ + ...Object.keys(rcvDetailsBySWId), + ...Object.keys(entryItemsBySWId), + ]); + + for (const swIdStr of allSWIds) { + const swId = Number(swIdStr); + const rcvGroup = rcvDetailsBySWId[swId]; + const entryGroup = entryItemsBySWId[swId]; + + if (!rcvGroup || !entryGroup) { + if (rcvGroup && !entryGroup) { + unmatchedProducts.push({ stock_warehouse_id: swId, reason: '收货侧有库存但无对应入库计划' }); + } + if (!rcvGroup && entryGroup) { + unmatchedProducts.push({ stock_warehouse_id: swId, reason: '入库计划存在但无对应收货明细' }); + } + continue; + } + + // 计算总量 + const totalRcvAvailable = rcvGroup.reduce((s, r) => s + r.available, 0); + const totalEntryRemaining = entryGroup.reduce((s, e) => s + e.remaining, 0); + const actualInbound = Math.min(totalRcvAvailable, totalEntryRemaining); + + if (actualInbound <= 0) continue; + + if (totalRcvAvailable < totalEntryRemaining) { + warnings.push( + `stock_warehouse_id=${swId}: 收货可入库量(${totalRcvAvailable}) < 入库计划量(${totalEntryRemaining}),按收货量入库` + ); + } + + // 6a. 锁定 stock_warehouse 行并增加 quantity + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: swId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!stockRecord) { + warnings.push(`stock_warehouse_id=${swId}: 库存记录不存在,跳过`); + continue; + } + + await stockRecord.increment('quantity', { + by: actualInbound, + transaction, + silent: true, + }); + + // 6b. 写入/更新 wms_storage(取第一个收货明细的信息) + const firstRcvDetail = rcvGroup[0].detail; + const firstRcv = rcvGroup[0].receiving; + const firstEntryOrder = entryGroup[0].entryOrder; + const spaceId = firstRcvDetail.space_id || 1; + const batchNo = firstRcvDetail.batch_number || firstRcv.receiving_number || ''; + const inventoryType = 'ZP'; + + let storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: swId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (storageRecord) { + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${actualInbound}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${actualInbound}`), + entry_order_id: firstEntryOrder.id, + }, { + where: { id: storageRecord.id }, + transaction, + }); + } else { + storageRecord = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: firstRcv.store_id || warehouseId, + space_id: spaceId, + stock_id: swId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: actualInbound, + locked_quantity: 0, + available_quantity: actualInbound, + production_date: firstRcvDetail.production_date || null, + expiry_date: firstRcvDetail.expiry_date || null, + inbound_time: new Date(), + inbound_order_no: firstEntryOrder.entry_order_code, + receiving_id: firstRcv.id, + entry_order_id: firstEntryOrder.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + + // 6b+. 写入出入库记录 + await ctx.model.StockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: firstRcv.store_id || warehouseId, + stock_id: swId, + storage_id: storageRecord.id, + space_id: spaceId, + quantity: actualInbound, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'MATCH', + order_no: firstEntryOrder.entry_order_code, + order_id: firstEntryOrder.id, + receiving_id: firstRcv.id, + entry_order_id: firstEntryOrder.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '匹配入库', + created_at: new Date(), + }, { transaction }); + + // 6c. 分配到各个收货明细(按顺序依次扣减) + let rcvRemain = actualInbound; + for (const rcvItem of rcvGroup) { + if (rcvRemain <= 0) break; + const allocate = Math.min(rcvRemain, rcvItem.available); + rcvDetailAllocated[rcvItem.detail.id] = (rcvDetailAllocated[rcvItem.detail.id] || 0) + allocate; + rcvRemain -= allocate; + } + + // 6d. 分配到各个入库明细(按顺序依次填充) + let entryRemain = actualInbound; + for (const entryItem of entryGroup) { + if (entryRemain <= 0) break; + const allocate = Math.min(entryRemain, entryItem.remaining); + entryItemAllocated[entryItem.item.id] = (entryItemAllocated[entryItem.item.id] || 0) + allocate; + entryRemain -= allocate; + } + + matchedItems.push({ + stock_warehouse_id: swId, + item_code: stockRecord.item_code || '', + inbound_quantity: actualInbound, + rcv_available: totalRcvAvailable, + entry_planned: totalEntryRemaining, + }); + } + + if (!matchedItems.length) { + await transaction.rollback(); + return { + code: 400, + message: '没有可匹配入库的商品', + data: { unmatched_products: unmatchedProducts }, + }; + } + + // ────────── 7. 更新收货明细 stored_quantity 和 storage_status ────────── + for (const rcv of receivings) { + for (const d of (rcv.details || [])) { + const allocated = rcvDetailAllocated[d.id]; + if (!allocated) continue; + const newStoredQty = (d.stored_quantity || 0) + allocated; + const detailStorageStatus = newStoredQty >= d.actual_quantity ? 'all' : 'partial'; + await ctx.model.ReceivingDetail.update({ + stored_quantity: newStoredQty, + storage_status: detailStorageStatus, + }, { + where: { id: d.id }, + transaction, + }); + } + } + + // ────────── 8. 更新入库明细 received_quantity ────────── + for (const eo of entryOrders) { + for (const item of (eo.items || [])) { + const allocated = entryItemAllocated[item.id]; + if (!allocated) continue; + const newReceivedQty = (item.received_quantity || 0) + allocated; + await ctx.model.EntryItems.update({ + received_quantity: newReceivedQty, + }, { + where: { id: item.id }, + transaction, + }); + } + } + + // ────────── 9. 更新收货单 storage_status ────────── + const receivingResults = []; + for (const rcv of receivings) { + const details = rcv.details || []; + const allStored = details.every(d => { + const allocated = rcvDetailAllocated[d.id] || 0; + const newStored = (d.stored_quantity || 0) + allocated; + return d.storage_status === 'all' || newStored >= d.actual_quantity; + }); + const hasAny = details.some(d => { + const allocated = rcvDetailAllocated[d.id] || 0; + return d.storage_status !== 'none' || allocated > 0; + }); + const newStatus = allStored ? 'all' : (hasAny ? 'partial' : rcv.storage_status); + + if (newStatus !== rcv.storage_status) { + await ctx.model.Receiving.update({ storage_status: newStatus }, { + where: { id: rcv.id }, + transaction, + }); + } + + receivingResults.push({ + receiving_id: rcv.id, + receiving_number: rcv.receiving_number, + storage_status: newStatus, + }); + } + + // ────────── 10. 更新入库单 order_status ────────── + const entryOrderResults = []; + const completedEntryOrders = []; // 事务外回传用 + + for (const eo of entryOrders) { + const items = eo.items || []; + const allFulfilled = items.every(item => { + const allocated = entryItemAllocated[item.id] || 0; + const newReceived = (item.received_quantity || 0) + allocated; + return newReceived >= (item.count || 0); + }); + const hasAnyReceived = items.some(item => { + const allocated = entryItemAllocated[item.id] || 0; + return (item.received_quantity || 0) + allocated > 0; + }); + + let newStatus = eo.order_status; + if (allFulfilled) { + newStatus = 'COMPLETED'; + } else if (hasAnyReceived) { + newStatus = 'PARTIAL_RECEIVED'; + } + + if (newStatus !== eo.order_status) { + await ctx.model.EntryOrder.update({ + order_status: newStatus, + updated_at: new Date(), + }, { + where: { id: eo.id }, + transaction, + }); + } + + const result = { + entry_order_id: eo.id, + entry_order_code: eo.entry_order_code, + order_status: newStatus, + source_type: eo.source_type, + callback_status: null, + }; + entryOrderResults.push(result); + + if (allFulfilled) { + completedEntryOrders.push({ entryOrder: eo, result }); + } else { + warnings.push( + `入库单 ${eo.entry_order_code}: 未全部入库完成(${newStatus}),不触发回传,需手工操作或等待其他收货入库` + ); + } + } + + // ────────── 12. 提交事务 ────────── + await transaction.commit(); + + // ────────── 13. 事务外:对已完成的入库单触发回传 ────────── + for (const { entryOrder, result } of completedEntryOrders) { + try { + if (entryOrder.source_type === 'QM') { + const confirmResult = await ctx.service.systems.entryOrder.entryorderConfirm(entryOrder.id, true); + result.callback_status = confirmResult.success ? 'SUCCESS' : 'FAILED'; + result.callback_detail = confirmResult; + } else if (entryOrder.source_type === 'API') { + const callbackResult = await this.apiCallback(entryOrder); + result.callback_status = callbackResult.success ? 'SUCCESS' : (callbackResult.skipped ? 'SKIPPED' : 'FAILED'); + result.callback_detail = callbackResult; + } else { + result.callback_status = 'NOT_REQUIRED'; + } + } catch (cbErr) { + ctx.logger.error(`[matchPutaway] 入库单 ${entryOrder.entry_order_code} 回传异常`, cbErr); + result.callback_status = 'ERROR'; + result.callback_detail = { error: cbErr.message }; + } + } + + // ────────── 14. 记录操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry', + businessId: entryOrderIds.join(','), + operationCode: 'MATCH_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { warehouseId, receivingIds, entryOrderIds }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[matchPutaway] 写入操作日志失败,不影响业务', logErr); + } + + ctx.logger.info('[matchPutaway] 匹配入库完成', { + receiving_ids: receivingIds, + entry_order_ids: entryOrderIds, + matched_count: matchedItems.length, + unmatched_count: unmatchedProducts.length, + warnings_count: warnings.length, + }); + + // ────────── 15. 返回结果 ────────── + return { + code: 200, + message: '匹配入库完成', + data: { + matched_items: matchedItems, + receiving_results: receivingResults, + entry_order_results: entryOrderResults, + unmatched_products: unmatchedProducts, + warnings: warnings.length ? warnings : undefined, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[matchPutaway] 匹配入库异常', { + receiving_ids: receivingIds, + entry_order_ids: entryOrderIds, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 + * 支持部分/全量移库、目标库位合并。 + * + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(必填) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} [data.quantity] 移库数量(可选,默认全部移动) + * @return {Promise} code/data/message 结构 + */ + async transferLocation(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const storageId = Number(data.storage_id || 0); + if (!storageId) { + return { code: 400, message: 'storage_id 必填', data: null }; + } + + const targetSpaceId = Number(data.target_space_id || 0); + if (!targetSpaceId) { + return { code: 400, message: 'target_space_id 必填', data: null }; + } + + if (data.quantity !== undefined && data.quantity !== null) { + const qty = Number(data.quantity); + if (!Number.isFinite(qty) || qty <= 0) { + return { code: 400, message: 'quantity 必须为正数', data: null }; + } + } + + // ────────── 2. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 3. 锁定并校验原库存记录 ────────── + const srcRecord = await ctx.model.Storage.findOne({ + where: { + id: storageId, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!srcRecord) { + await transaction.rollback(); + return { code: 404, message: `库存记录不存在: storage_id=${storageId}`, data: null }; + } + + const warehouseId = srcRecord.warehouse_id; + + // ────────── 4. 校验目标库位 ────────── + const targetSpace = await ctx.model.LocationSpace.findOne({ + where: { + id: targetSpaceId, + is_enabled: true, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!targetSpace) { + await transaction.rollback(); + return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; + } + if (targetSpace.warehouse_id !== warehouseId) { + await transaction.rollback(); + return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; + } + if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { + await transaction.rollback(); + return { + code: 400, + message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, + data: null, + }; + } + + // ────────── 5. 处理移库 ────────── + const availableQty = srcRecord.quantity - srcRecord.locked_quantity; + const transferQty = (data.quantity !== undefined && data.quantity !== null) + ? Number(data.quantity) + : availableQty; + + // 校验移库数量 + if (transferQty > availableQty) { + await transaction.rollback(); + return { + code: 400, + message: `库存记录 ${storageId} 可用数量不足:可用 ${availableQty},请求移库 ${transferQty}`, + data: null, + }; + } + + // 原库位与目标库位相同则直接返回 + if (srcRecord.space_id === targetSpaceId) { + await transaction.rollback(); + return { + code: 200, + message: '原库位与目标库位相同,无需移库', + data: { + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: 0, + status: 'skipped', + }, + }; + } + + const beforeSnapshot = { + storage_id: storageId, + space_id: srcRecord.space_id, + quantity: srcRecord.quantity, + available_quantity: srcRecord.available_quantity, + }; + + const isFullTransfer = (transferQty === srcRecord.quantity); + + // 查找目标库位是否已有相同 stock_id + batch_no + inventory_type 的记录 + const existingTarget = await ctx.model.Storage.findOne({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, // 排除自身(全量移库时直接改 space_id 的情况) + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let afterSnapshot; + // 原库位统计变化 + const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + // 目标库位统计变化 + const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + + if (existingTarget) { + // ── 目标库位已有同规格记录:合并数量 ── + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: existingTarget.id }, + transaction, + }); + + if (isFullTransfer) { + // 全量移库且合并:删除原记录 + await ctx.model.Storage.update({ + is_enabled: 0, + delete_at: new Date(), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + srcSpaceDelta.qtyDelta -= srcRecord.quantity; + // 检查原库位该 SKU 是否还有其他记录 + const remainingSku = await ctx.model.Storage.count({ + where: { + space_id: srcRecord.space_id, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, + }, + transaction, + }); + if (remainingSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + } else { + // 部分移库:减少原记录数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + srcSpaceDelta.qtyDelta -= transferQty; + } + + // 目标库位数量增加 + tgtSpaceDelta.qtyDelta += transferQty; + // 目标库位该 SKU 之前已有记录,skuDelta 不变 + + afterSnapshot = { + merged_into: existingTarget.id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: isFullTransfer, + }; + } else if (isFullTransfer) { + // ── 全量移库 & 目标无同规格记录:直接修改 space_id ── + await ctx.model.Storage.update({ + space_id: targetSpaceId, + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + srcSpaceDelta.qtyDelta -= srcRecord.quantity; + // 检查原库位该 SKU 是否还有其他记录 + const remainingSku = await ctx.model.Storage.count({ + where: { + space_id: srcRecord.space_id, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, + }, + transaction, + }); + if (remainingSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + + // 目标库位新增一个 SKU + const existingSkuInTarget = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: storageId }, // 排掉自身(此时 space_id 已更新,但事务内逻辑用旧值) + }, + transaction, + }); + if (existingSkuInTarget === 0) { + tgtSpaceDelta.skuDelta += 1; + } + tgtSpaceDelta.qtyDelta += srcRecord.quantity; + + afterSnapshot = { + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: false, + }; + } else { + // ── 部分移库 & 目标无同规格记录:减少原记录数量,新建目标记录 ── + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${transferQty}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${transferQty}`), + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + const newRecord = await ctx.model.Storage.create({ + warehouse_id: srcRecord.warehouse_id, + store_id: srcRecord.store_id, + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + quantity: transferQty, + locked_quantity: 0, + available_quantity: transferQty, + production_date: srcRecord.production_date, + expiry_date: srcRecord.expiry_date, + inbound_time: srcRecord.inbound_time, + inbound_order_no: srcRecord.inbound_order_no, + receiving_id: srcRecord.receiving_id, + entry_order_id: srcRecord.entry_order_id, + supplier_id: srcRecord.supplier_id, + supplier_batch_no: srcRecord.supplier_batch_no, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + + srcSpaceDelta.qtyDelta -= transferQty; + // 原库位 SKU 数不变(原记录仍在) + + // 目标库位:新增 SKU + const existingSkuInTarget = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + // count 包含刚 create 的记录,如果只有 1 条说明之前没有 + if (existingSkuInTarget <= 1) { + tgtSpaceDelta.skuDelta += 1; + } + tgtSpaceDelta.qtyDelta += transferQty; + + afterSnapshot = { + new_storage_id: newRecord.id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + source_deleted: false, + }; + } + + // ────────── 记录操作日志(事务内) ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: storageId, + operationCode: 'STORAGE_TRANSFER_LOCATION', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + }, + beforeChanges: beforeSnapshot, + afterChanges: afterSnapshot, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.transferLocation] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 6. 更新库位统计 ────────── + const updateSpaceStats = async (spaceId, delta) => { + if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; + const updateFields = {}; + if (delta.qtyDelta !== 0) { + updateFields.current_quantity = app.Sequelize.literal( + `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` + ); + } + if (delta.skuDelta !== 0) { + updateFields.current_sku_count = app.Sequelize.literal( + `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` + ); + } + await ctx.model.LocationSpace.update(updateFields, { + where: { id: spaceId }, + transaction, + }); + }; + + await updateSpaceStats(srcRecord.space_id, srcSpaceDelta); + await updateSpaceStats(targetSpaceId, tgtSpaceDelta); + + // ────────── 7. 提交事务 ────────── + await transaction.commit(); + + // ────────── 8. 发送通知(事务外) ────────── + try { + await ctx.service.systems.notice.send({ + event: 'storage_transfer_completed', + businessName: 'storage', + warehouseId, + subjectId: warehouseId, + title: '移库操作完成', + content: `移库完成:库存${storageId} -> 库位${targetSpaceId}(数量:${transferQty})`, + data: { warehouse_id: warehouseId, storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: transferQty }, + sender: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[inventory.transferLocation] 发送通知失败,不影响业务', noticeErr); + } + + ctx.logger.info('[inventory.transferLocation] 移库完成', { + warehouse_id: warehouseId, + storage_id: storageId, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + }); + + return { + code: 200, + message: '移库完成', + data: { + storage_id: storageId, + stock_id: srcRecord.stock_id, + target_space_id: targetSpaceId, + transfer_quantity: transferQty, + status: 'success', + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.transferLocation] 移库异常', { + storage_id: storageId, + target_space_id: targetSpaceId, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * 按库位+商品维度移库。 + * 自动查找该库位下该商品的所有 storage 记录,按 quantity ASC 逐条扣减并合并移动到目标库位。 + * + * @param {Object} data 请求体 + * @param {number} data.space_id 原库位ID(必填) + * @param {number} data.stock_id 商品SKU ID(必填,对应 wms_stock_warehouse.id) + * @param {number} data.target_space_id 目标库位ID(必填) + * @param {number} data.quantity 移库数量(必填) + * @return {Promise} code/data/message 结构 + */ + async transferByProduct(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + // ────────── 1. 参数校验 ────────── + const spaceId = Number(data.space_id || 0); + const stockId = Number(data.stock_id || 0); + const targetSpaceId = Number(data.target_space_id || 0); + const quantity = Number(data.quantity || 0); + + if (!spaceId) { + return { code: 400, message: 'space_id 必填', data: null }; + } + if (!stockId) { + return { code: 400, message: 'stock_id 必填', data: null }; + } + if (!targetSpaceId) { + return { code: 400, message: 'target_space_id 必填', data: null }; + } + if (!Number.isFinite(quantity) || quantity <= 0) { + return { code: 400, message: 'quantity 必须为正数', data: null }; + } + + // ────────── 2. 批次管理校验 ────────── + const stockWarehouse = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'is_batch_mgmt' ], + }); + if (!stockWarehouse) { + return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null }; + } + if (stockWarehouse.is_batch_mgmt === 'Y') { + return { + code: 400, + message: '该商品已开启批次管理,请使用按库存记录移库(transferLocation)', + data: null, + }; + } + + // ────────── 3. 原库位与目标库位相同 ────────── + if (spaceId === targetSpaceId) { + return { + code: 200, + message: '原库位与目标库位相同,无需移库', + data: { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: 0, + affected_storage_count: 0, + status: 'skipped', + }, + }; + } + + // ────────── 4. 开事务 ────────── + const transaction = await ctx.model.transaction(); + + try { + // ────────── 5. 查找并锁定原库存记录 ────────── + const srcRecords = await ctx.model.Storage.findAll({ + where: { + space_id: spaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + order: [[ 'quantity', 'ASC' ]], + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!srcRecords.length) { + await transaction.rollback(); + return { code: 404, message: `原库位 ${spaceId} 下未找到商品 ${stockId} 的库存记录`, data: null }; + } + + const totalAvailable = srcRecords.reduce((sum, r) => sum + (r.quantity - r.locked_quantity), 0); + if (quantity > totalAvailable) { + await transaction.rollback(); + return { + code: 400, + message: `可用数量不足:可用 ${totalAvailable},请求移库 ${quantity}`, + data: null, + }; + } + + const warehouseId = srcRecords[0].warehouse_id; + + // ────────── 6. 校验目标库位 ────────── + const targetSpace = await ctx.model.LocationSpace.findOne({ + where: { + id: targetSpaceId, + is_enabled: true, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!targetSpace) { + await transaction.rollback(); + return { code: 404, message: `目标库位不存在或未启用: space_id=${targetSpaceId}`, data: null }; + } + if (targetSpace.warehouse_id !== warehouseId) { + await transaction.rollback(); + return { code: 400, message: `目标库位 ${targetSpaceId} 不属于仓库 ${warehouseId}`, data: null }; + } + if (![ 'AVAILABLE', 'OCCUPIED' ].includes(targetSpace.space_status)) { + await transaction.rollback(); + return { + code: 400, + message: `目标库位 ${targetSpace.space_code} 状态为 ${targetSpace.space_status},不可移入`, + data: null, + }; + } + + // ────────── 7. 逐条扣减并移库 ────────── + let remainingQty = quantity; + let affectedCount = 0; + const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + const tgtSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; + + // 预先记录目标库位是否已有该 SKU(用于事后计算 skuDelta) + const tgtSkuCountBefore = await ctx.model.Storage.count({ + where: { + space_id: targetSpaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + + for (const srcRecord of srcRecords) { + if (remainingQty <= 0) break; + + const available = srcRecord.quantity - srcRecord.locked_quantity; + const toTransfer = Math.min(available, remainingQty); + if (toTransfer <= 0) continue; + + affectedCount++; + const isFullTransfer = (toTransfer === srcRecord.quantity); + + // ── 在目标库位查找同 stock_id + batch_no + inventory_type 的记录 ── + const existingTarget = await ctx.model.Storage.findOne({ + where: { + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + is_enabled: 1, + delete_at: null, + id: { [Op.ne]: srcRecord.id }, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (existingTarget) { + // 目标已有同规格记录:合并数量 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: existingTarget.id }, + transaction, + }); + + if (isFullTransfer) { + // 全量:软删除原记录 + await ctx.model.Storage.update({ + is_enabled: 0, + delete_at: new Date(), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + } else { + // 部分:减少原记录 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + } + } else if (isFullTransfer) { + // 全量移库 & 目标无同规格记录:直接改 space_id + await ctx.model.Storage.update({ + space_id: targetSpaceId, + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + } else { + // 部分移库 & 目标无同规格记录:减少原记录,新建目标记录 + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity - ${toTransfer}`), + available_quantity: app.Sequelize.literal(`available_quantity - ${toTransfer}`), + updated_at: new Date(), + }, { + where: { id: srcRecord.id }, + transaction, + }); + + await ctx.model.Storage.create({ + warehouse_id: srcRecord.warehouse_id, + store_id: srcRecord.store_id, + space_id: targetSpaceId, + stock_id: srcRecord.stock_id, + batch_no: srcRecord.batch_no, + inventory_type: srcRecord.inventory_type, + quantity: toTransfer, + locked_quantity: 0, + available_quantity: toTransfer, + production_date: srcRecord.production_date, + expiry_date: srcRecord.expiry_date, + inbound_time: srcRecord.inbound_time, + inbound_order_no: srcRecord.inbound_order_no, + receiving_id: srcRecord.receiving_id, + entry_order_id: srcRecord.entry_order_id, + supplier_id: srcRecord.supplier_id, + supplier_batch_no: srcRecord.supplier_batch_no, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + } + + srcSpaceDelta.qtyDelta -= toTransfer; + tgtSpaceDelta.qtyDelta += toTransfer; + remainingQty -= toTransfer; + } + + // ── 计算 SKU 维度统计变化 ── + const remainingSrcSku = await ctx.model.Storage.count({ + where: { + space_id: spaceId, + stock_id: stockId, + is_enabled: 1, + delete_at: null, + }, + transaction, + }); + if (remainingSrcSku === 0) { + srcSpaceDelta.skuDelta -= 1; + } + + if (tgtSkuCountBefore === 0) { + // 操作前目标库位没有该 SKU,现在有了 + tgtSpaceDelta.skuDelta += 1; + } + + // ────────── 8. 操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: spaceId, + operationCode: 'STORAGE_TRANSFER_BY_PRODUCT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }, + beforeChanges: { + space_id: spaceId, + stock_id: stockId, + total_available: totalAvailable, + source_record_count: srcRecords.length, + }, + afterChanges: { + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.transferByProduct] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 9. 更新库位统计 ────────── + const updateSpaceStats = async (updateSpaceId, delta) => { + if (delta.qtyDelta === 0 && delta.skuDelta === 0) return; + const updateFields = {}; + if (delta.qtyDelta !== 0) { + updateFields.current_quantity = app.Sequelize.literal( + `GREATEST(COALESCE(current_quantity, 0) + (${delta.qtyDelta}), 0)` + ); + } + if (delta.skuDelta !== 0) { + updateFields.current_sku_count = app.Sequelize.literal( + `GREATEST(COALESCE(current_sku_count, 0) + (${delta.skuDelta}), 0)` + ); + } + await ctx.model.LocationSpace.update(updateFields, { + where: { id: updateSpaceId }, + transaction, + }); + }; + + await updateSpaceStats(spaceId, srcSpaceDelta); + await updateSpaceStats(targetSpaceId, tgtSpaceDelta); + + // ────────── 10. 提交事务 ────────── + await transaction.commit(); + + // ────────── 11. 发送通知(事务外) ────────── + try { + await ctx.service.systems.notice.send({ + event: 'storage_transfer_completed', + businessName: 'storage', + warehouseId, + subjectId: warehouseId, + title: '按商品移库操作完成', + content: `按商品移库完成:库位${spaceId} 商品${stockId} -> 库位${targetSpaceId}(数量:${quantity},涉及${affectedCount}条记录)`, + data: { + warehouse_id: warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }, + sender: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + }); + } catch (noticeErr) { + ctx.logger.warn('[inventory.transferByProduct] 发送通知失败,不影响业务', noticeErr); + } + + ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', { + warehouse_id: warehouseId, + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + }); + + return { + code: 200, + message: '按商品移库完成', + data: { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + transfer_quantity: quantity, + affected_storage_count: affectedCount, + warehouse_id: warehouseId, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.transferByProduct] 按商品移库异常', { + space_id: spaceId, + stock_id: stockId, + target_space_id: targetSpaceId, + quantity, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + + /** + * API 入库单回调:向 api_app 配置的 callback_url 发送入库确认通知。 + * + * @param {Object} entryOrder 入库单实例 + * @return {Promise} { success, skipped?, status?, error? } + */ + async apiCallback(entryOrder) { + const { ctx, app } = this; + try { + const apiApp = await app.model.ApiApp.findOne({ + where: { + warehouse_id: entryOrder.warehouse_id, + is_enabled: 1, + }, + }); + + if (!apiApp || !apiApp.callback_url) { + ctx.logger.info('[matchPutaway] 未找到API回调配置或无回调地址,跳过回调'); + return { success: true, skipped: true }; + } + + const items = await app.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + }); + + const payload = { + entry_order_code: entryOrder.entry_order_code, + order_type: entryOrder.order_type, + order_status: 'COMPLETED', + warehouse_id: entryOrder.warehouse_id, + store_id: entryOrder.store_id, + items: items.map(item => ({ + item_code: item.item_code, + item_id: item.item_id, + plan_quantity: item.count, + received_quantity: item.received_quantity, + confirm_quantity: item.received_quantity, + })), + confirm_time: new Date().toISOString(), + }; + + const response = await ctx.curl(apiApp.callback_url, { + method: 'POST', + contentType: 'json', + data: payload, + timeout: 10000, + dataType: 'json', + }); + + ctx.logger.info('[matchPutaway] API回调结果', { + entry_order_id: entryOrder.id, + callback_url: apiApp.callback_url, + status: response.status, + }); + + return { success: response.status === 200, status: response.status }; + } catch (err) { + ctx.logger.error('[matchPutaway] API回调失败', err); + return { success: false, error: err.message }; + } + } + + /** + * 库存列表查询。 + * @param {Object} pageParams 分页参数 + * @param {Object} sortParams 排序参数 + * @param {boolean} groupByBatch 是否按批次 + */ + async getInventoryList(pageParams = {}, sortParams = {}, groupByBatch = false) { + const { ctx, app } = this; + const { Op, fn, col, literal } = app.Sequelize; + + const warehouseId = ctx.user.store_id; + const { page = 1, pageSize = 20 } = pageParams; + const { sortField = 'created_at', sortOrder = 'DESC' } = sortParams; + + // 基础条件 + const baseWhere = { + [Op.and]: [ + { warehouse_id: warehouseId }, + { is_enabled: 1 }, + { delete_at: null }, + ], + }; + + // 动态 where 条件 + const parsed = ctx.whereParsed; + if (parsed && parsed.dynamicConditions && parsed.dynamicConditions.length > 0) { + baseWhere[Op.and].push(...parsed.dynamicConditions); + } + + const offset = (page - 1) * pageSize; + const limit = pageSize; + + if (groupByBatch) { + // 按批次明细:逐条返回 + const { count: total, rows } = await ctx.model.Storage.findAndCountAll({ + where: baseWhere, + order: [[ sortField, sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + }); + + const list = rows.map(item => { + const row = item.get({ plain: true }); + row.created_at = row.created_at ? app.formatDate(row.created_at) : ''; + row.updated_at = row.updated_at ? app.formatDate(row.updated_at) : ''; + row.inbound_time = row.inbound_time ? app.formatDate(row.inbound_time) : ''; + row.production_date = row.production_date ? app.formatDate(row.production_date) : ''; + row.expiry_date = row.expiry_date ? app.formatDate(row.expiry_date) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } + + // 不按批次:按 stock_id + space_id + inventory_type 合并 + const groupFields = [ 'stock_id', 'space_id', 'inventory_type', 'warehouse_id', 'store_id' ]; + + const countResult = await ctx.model.Storage.count({ + where: baseWhere, + group: groupFields, + }); + const total = Array.isArray(countResult) ? countResult.length : countResult; + + const rows = await ctx.model.Storage.findAll({ + where: baseWhere, + attributes: [ + 'stock_id', + 'space_id', + 'inventory_type', + 'warehouse_id', + 'store_id', + [ fn('SUM', col('wms_storage.quantity')), 'quantity' ], + [ fn('SUM', col('wms_storage.locked_quantity')), 'locked_quantity' ], + [ fn('SUM', col('wms_storage.available_quantity')), 'available_quantity' ], + [ fn('MIN', col('wms_storage.inbound_time')), 'first_inbound_time' ], + [ fn('MAX', col('wms_storage.inbound_time')), 'last_inbound_time' ], + [ fn('COUNT', col('wms_storage.id')), 'batch_count' ], + ], + group: groupFields, + order: [[ literal('last_inbound_time'), sortOrder ]], + offset, + limit, + include: [ + { + model: ctx.model.StockWarehouse, + as: 'stock', + attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit' ], + required: false, + }, + { + model: ctx.model.LocationSpace, + as: 'space', + attributes: [ 'id', 'space_code', 'custom_name' ], + required: false, + }, + ], + raw: true, + nest: true, + }); + + const list = rows.map(row => { + row.first_inbound_time = row.first_inbound_time ? app.formatDate(row.first_inbound_time) : ''; + row.last_inbound_time = row.last_inbound_time ? app.formatDate(row.last_inbound_time) : ''; + return row; + }); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + }; + } +} + +module.exports = InventoryService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index b165865..8a316e2 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -16,7 +16,6 @@ class ReceivingService extends Service { const { ctx, app, - config, } = this; const { Sequelize, @@ -389,6 +388,28 @@ class ReceivingService extends Service { } // 批量更新状态为cancelled await ctx.model.Receiving.update({ status: 'cancelled' }, { where: { id: { [Op.in]: ids }, warehouse_id } }); + + // 批量记录操作日志 + try { + await Promise.all(ids.map(receivingId => + ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_BATCH_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: null, + }) + )); + } catch (logErr) { + ctx.logger.warn('[receiving.batchCancelReceiving] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '批量作废成功', data: {} }; } catch (error) { @@ -423,7 +444,7 @@ class ReceivingService extends Service { Sequelize, } = app; const { - operator = 'eq', value, type, isMultiple, + operator = 'eq', value, type, } = condition; // 处理字段名 @@ -626,8 +647,6 @@ class ReceivingService extends Service { // 处理日期范围:数组的第一个元素是开始时间,第二个元素是结束时间 if (Array.isArray(value) && value.length === 2) { const [ startDate, endDate ] = value; - console.log(startDate, endDate); - console.log(startDate ? service.main.normalizeDate(startDate, false) : null, endDate ? service.main.normalizeDate(endDate, true) : null); return [ startDate ? service.main.normalizeDate(startDate, false) : null, // 开始时间设为00:00:00 endDate ? service.main.normalizeDate(endDate, true) : null, // 结束时间设为23:59:59 @@ -636,12 +655,11 @@ class ReceivingService extends Service { return value; case 'number': - // 转换为数字 + { const num = parseFloat(value); return isNaN(num) ? value : num; - + } case 'text': - // 文本类型,支持逗号分隔 if (typeof value === 'string') { return value.split(',').map(item => item.trim()); } @@ -729,7 +747,6 @@ class ReceivingService extends Service { // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 const now = new Date(); - console.log('当前时间:', now); const prefix = this.buildReceivingNumberPrefix(now); // 3. 获取店铺名称(如果有货主) @@ -798,6 +815,25 @@ class ReceivingService extends Service { throw lastCreateError || new Error('创建收货任务失败'); } + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: result.id, + operationCode: 'RECEIVING_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.create] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, id: result.id, @@ -923,6 +959,28 @@ class ReceivingService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_BIND_STORE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + store_id: receiving.store_id, + store_name: receiving.store_name, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.bindStore] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '绑定货主成功', @@ -956,7 +1014,6 @@ class ReceivingService extends Service { // 获取用户仓库ID,增加错误处理 const warehouseId = ctx.user?.store_id; - const creator_id = ctx.user.employees_id; if (!warehouseId) { return { code: 0, message: '用户未绑定仓库', data: {} }; } @@ -989,7 +1046,6 @@ class ReceivingService extends Service { if (!receiving) { return { code: 0, message: '无记录或无权访问', data: {} }; } - console.log('查询收货单明细'); // 2. 查询收货单明细 const receivingItems = await app.model.ReceivingDetail.findAll({ where: { @@ -1132,7 +1188,6 @@ class ReceivingService extends Service { creator_id, }); - // 获取更新后的明细列表 const allDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id }, @@ -1161,6 +1216,28 @@ class ReceivingService extends Service { }); await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_ADD_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: { + detail_id: newDetail.id, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.addDetail] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '添加成功', @@ -1318,6 +1395,29 @@ class ReceivingService extends Service { await this.updateReceivingStats(receivingDetail.receiving_id); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingDetail.receiving_id, + operationCode: 'RECEIVING_BIND_PRODUCT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + detail_id: detailId, + old_system_product_id: receivingDetail.system_product_id, + new_system_product_id: systemProductId, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.bindDetailProduct] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '绑定商品成功', @@ -1575,7 +1675,6 @@ class ReceivingService extends Service { }, transaction, }); - console.log('matchedDetail第一个有绑定的商品', matchedDetail); if (matchedDetail && matchedDetail.system_product_id) { try { // 调用 getStockStoreInfo 获取库存信息 @@ -1658,7 +1757,6 @@ class ReceivingService extends Service { if (transaction) { await transaction.rollback(); } - console.log(error); ctx.logger.error('更新收货单统计失败:', error); throw error; } @@ -1758,6 +1856,30 @@ class ReceivingService extends Service { selectId = remainingDetails[0].id; } await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_DELETE_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: warehouse_id, + }, + beforeChanges: { + detail_id, + product_name: detail.product_name, + actual_quantity: detail.actual_quantity, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.deleteDetail] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '删除成功', @@ -1806,7 +1928,6 @@ class ReceivingService extends Service { box_length, weight, } = data; - console.log('barcode', barcode); // 2. 验证必填字段 if (!id) { return { @@ -1822,7 +1943,6 @@ class ReceivingService extends Service { }; } - // 3. 获取收货明细信息 const receivingDetail = await app.model.ReceivingDetail.findOne({ where: { id }, @@ -1848,7 +1968,6 @@ class ReceivingService extends Service { }; } - // 5. 验证箱规数据 if (box_quantity !== undefined && box_quantity < 0) { return { @@ -1915,7 +2034,6 @@ class ReceivingService extends Service { if (stockWarehouse) { // 更新商品相关信息 updateData.system_product_id = system_product_id; - console.log('商品信息', stockWarehouse); // 使用系统商品的条码(如果前端没有提供) const barcodes = stockWarehouse.barcodes?.map(b => b.barcode) || []; updateData.barcode = updateData.barcode || barcodes.join(';'); @@ -1960,13 +2078,36 @@ class ReceivingService extends Service { updateData.space_id = space_id; } } - console.log('更新收货明细', updateData); // 8. 更新收货明细 await ctx.model.ReceivingDetail.update(updateData, { where: { id }, }); - console.log('更新收货明细2'); await this.updateReceivingStats(receiving_id); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receiving_id, + operationCode: 'RECEIVING_UPDATE_DETAIL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + detail_id: id, + product_name: receivingDetail.product_name, + actual_quantity: receivingDetail.actual_quantity, + system_product_id: receivingDetail.system_product_id, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.detailChange] 写入操作日志失败,不影响业务', logErr); + } + // 9. 返回成功响应 return { code: 200, @@ -2091,6 +2232,27 @@ class ReceivingService extends Service { // 8. 提交事务 await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: receivingId, + operationCode: 'RECEIVING_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + previous_status: receiving.status, + invalid_reason, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.invalid] 写入操作日志失败,不影响业务', logErr); + } return { code: 200, @@ -2107,7 +2269,6 @@ class ReceivingService extends Service { }; } catch (error) { - console.log(error); // 10. 回滚事务 if (transaction) { await transaction.rollback(); @@ -2406,7 +2567,7 @@ class ReceivingService extends Service { * @param {Object} [options.operator={}] 操作人信息 * @param {Object} [options.stats={}] 收货统计 * @param {Object|null} [options.completionReport=null] 完成报表信息 - * @return {Promise} + * @return {Promise} 通知发送结果,若条件不满足则返回 null */ async sendCompletionNotice({ receiving, @@ -2562,9 +2723,28 @@ class ReceivingService extends Service { }; } - // 4. 准备明细图片与统计信息。 - // 按最新要求:收货完成通知不再受“必须绑定商品/必须补齐照片条码重量数量”限制, - // 只要用户执行完成收货且存在明细,即允许完成并继续发送通知。 + // 4. 校验明细数量:不允许存在数量为 0 的明细 + const zeroQuantityDetails = receiving.details.filter(d => Number(d.actual_quantity || 0) <= 0); + if (zeroQuantityDetails.length > 0) { + await transaction.rollback(); + const errorMsg = zeroQuantityDetails.length === 1 + ? `商品“${zeroQuantityDetails[0].product_name || '未命名商品'}”的数量为0,请填写实际收货数量` + : `有${zeroQuantityDetails.length}个商品数量为0,请填写实际收货数量`; + return { + success: false, + code: 'DETAIL_QUANTITY_ZERO', + message: errorMsg, + data: { + invalid_details: zeroQuantityDetails.map(d => ({ + detail_id: d.id, + item_name: d.product_name || '未命名商品', + actual_quantity: Number(d.actual_quantity || 0), + })), + }, + }; + } + + // 5. 准备明细图片与统计信息(照片/条码/重量不再强制要求) const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); const detailsIds = receiving.details.map(item => item.id); @@ -2653,6 +2833,28 @@ class ReceivingService extends Service { // 10. 提交事务 await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'receiving', + businessId: id, + operationCode: 'RECEIVING_COMPLETE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + }, + beforeChanges: { + previous_status: receiving.status, + stats, + }, + }); + } catch (logErr) { + ctx.logger.warn('[receiving.completeReceiving] 写入操作日志失败,不影响业务', logErr); + } + const receivingSnapshot = { ...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving), ...updateData, diff --git a/app/service/systems/store.js b/app/service/systems/store.js index de75211..0b8291c 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -89,13 +89,14 @@ class StoreService extends Service { } /** - * 根据ID获取商家信息 - * @param storeId - */ + * 根据ID获取商家信息。 + * @param {number|string} storeId 商家ID + * @return {Promise} 查询结果 + */ async getStoreName(storeId) { try { const store = await this.app.model.Store.findByPk(storeId, { - attributes: [ 'id', 'company_name', 'status', 'is_warehouse' ], + attributes: [ 'id', 'company_name', 'status' ], }); if (!store) { @@ -122,10 +123,11 @@ class StoreService extends Service { } /** - * 获取商家仓库备注名 - * @param storeId - * @param warehouseId - */ + * 获取商家仓库备注名。 + * @param {number|string} storeId 商家ID + * @param {number|string} warehouseId 仓库ID + * @return {Promise} 查询结果 + */ async getStoreRemaskName(storeId, warehouseId) { try { const relation = await this.app.model.StoreWarehouse.findOne({ @@ -159,9 +161,10 @@ class StoreService extends Service { } /** - * 创建商家(不需要审核) - * @param data - */ + * 创建商家(不需要审核)。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async createStore(data) { const { ctx, @@ -245,9 +248,25 @@ class StoreService extends Service { // 为创建者自动分配商家管理员角色 const role_id = await this.assignAdminRoleToCreator(store.id, userId, data.contact_person, transaction); - console.log(role_id); await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: store.id, + operationCode: 'STORE_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: {}, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[store.createStore] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '商家创建成功', @@ -279,9 +298,10 @@ class StoreService extends Service { } /** - * 创建仓库(需要审核) - * @param data - */ + * 创建仓库(需要审核)。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async createWarehouse(data) { const { ctx, @@ -366,6 +386,24 @@ class StoreService extends Service { const role_id = await this.assignAdminRoleToCreator(warehouse.id, userId, data.contact_person, transaction, false); await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: warehouse.id, + operationCode: 'STORE_CREATE_WAREHOUSE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: {}, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[store.createWarehouse] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, message: '仓库创建申请已提交,等待审核', @@ -397,9 +435,10 @@ class StoreService extends Service { } /** - * 加入商家 - * @param data - */ + * 加入商家。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async joinStore(data) { const { ctx, @@ -408,7 +447,6 @@ class StoreService extends Service { try { const userId = ctx.userId || (ctx.user && ctx.user.id); - console.log('申请参数', data); // 验证必填字段 if (!data.employees_name) { return { @@ -427,7 +465,6 @@ class StoreService extends Service { transaction, }); - // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); @@ -447,7 +484,6 @@ class StoreService extends Service { transaction, }); - await transaction.commit(); return { @@ -461,7 +497,6 @@ class StoreService extends Service { } catch (error) { await transaction.rollback(); - console.log('error', error); return { code: 500, message: '创建申请链接失败', @@ -471,9 +506,10 @@ class StoreService extends Service { } /** - * 加入仓库 - * @param data - */ + * 加入仓库。 + * @param {Object} data 请求参数 + * @return {Promise} 创建结果 + */ async joinWarehouse(data) { const { ctx, @@ -482,7 +518,6 @@ class StoreService extends Service { try { const userId = ctx.userId || (ctx.user && ctx.user.id); - console.log('申请参数', data); // 验证必填字段 if (!data.employees_name) { return { @@ -501,7 +536,6 @@ class StoreService extends Service { transaction, }); - // 生成加入链接(用于分享给管理员) const joinToken = this.generateJoinToken(userId, data.store_id); @@ -521,7 +555,6 @@ class StoreService extends Service { transaction, }); - await transaction.commit(); return { @@ -535,7 +568,6 @@ class StoreService extends Service { } catch (error) { await transaction.rollback(); - console.log('error', error); return { code: 500, message: '创建申请链接失败', @@ -546,6 +578,16 @@ class StoreService extends Service { // ==================== 辅助方法 ==================== + /** + * 确保工号与角色已绑定。 + * @param {Object} options 绑定参数 + * @param {number|string} options.accountId 账号ID + * @param {number|string} options.storeId 主体ID + * @param {number|string} options.roleId 角色ID + * @param {string} [options.realName] 真实姓名 + * @param {Object} options.transaction 事务对象 + * @return {Promise} 绑定结果 + */ async ensureEmployeeRoleBinding({ accountId, storeId, roleId, realName = '', transaction }) { const { ctx } = this; @@ -589,13 +631,14 @@ class StoreService extends Service { } /** - * 为创建者分配管理员角色 - * @param storeId - * @param userId - * @param realName - * @param transaction - * @param isStore - */ + * 为创建者分配管理员角色。 + * @param {number|string} storeId 主体ID + * @param {number|string} userId 账号ID + * @param {string} realName 真实姓名 + * @param {Object} transaction 事务对象 + * @param {boolean} [isStore=true] 是否为商家主体 + * @return {Promise} 工号实例 + */ async assignAdminRoleToCreator(storeId, userId, realName, transaction, isStore = true) { const { ctx, @@ -625,13 +668,13 @@ class StoreService extends Service { return employee; } - /** - * 生成加入令牌 - * @param userId - * @param storeId - * @param type - */ + * 生成加入令牌。 + * @param {number|string} userId 账号ID + * @param {number|string} storeId 主体ID + * @param {string} [type='store'] 令牌类型 + * @return {string} 加入令牌 + */ generateJoinToken(userId, storeId, type = 'store') { const crypto = require('crypto'); const timestamp = Date.now(); @@ -643,9 +686,10 @@ class StoreService extends Service { } /** - * 发送通知 - * @param notificationData - */ + * 发送通知。 + * @param {Object} notificationData 通知数据 + * @return {Promise} + */ async sendNotification(notificationData) { const { ctx, @@ -663,9 +707,10 @@ class StoreService extends Service { } /** - * 发送通知给系统管理员 - * @param notificationData - */ + * 发送通知给系统管理员。 + * @param {Object} notificationData 通知数据 + * @return {Promise} + */ async sendNotificationToAdmins(notificationData) { const { ctx, @@ -696,8 +741,6 @@ class StoreService extends Service { ctx, } = this; try { - console.log('ctx', ctx.user.store_id); - const userId = ctx.user.id; const storeId = ctx.user.store_id; // 验证必填字段 if (!data.code) { @@ -708,7 +751,6 @@ class StoreService extends Service { }; } const code = data.code; - console.log('申请参数', userId, storeId, code); const applyData = await ctx.model.StoreJoin.findOne({ where: { join_token: code, @@ -741,7 +783,6 @@ class StoreService extends Service { }, }; } catch (error) { - console.log('error', error); return { code: 500, message: '请求失败', @@ -765,7 +806,7 @@ class StoreService extends Service { } // 2. 验证store_id - if (ctx.user.store_id != data.store_id) { + if (ctx.user.store_id !== data.store_id) { await transaction.rollback(); return { code: 400, @@ -777,8 +818,6 @@ class StoreService extends Service { const { code, audit_status, role_ids } = data; const store_id = ctx.user.store_id; - console.log('申请参数', data); - // 3. 查找申请记录 const applyData = await ctx.model.StoreJoin.findOne({ where: { @@ -883,7 +922,6 @@ class StoreService extends Service { data: null, }; - } catch (error) { await transaction.rollback(); console.error('审核申请出错:', error); @@ -905,7 +943,7 @@ class StoreService extends Service { } } async loadStores() { - const { app, ctx } = this; + const { ctx } = this; try { const stores = await ctx.model.StoreWarehouse.findAll({ diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index a73c73b..38d619c 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -11,34 +11,6 @@ const AUTH_STATUS_LABELS = Object.freeze({ 4: '已解除', 5: '已过期', }); -const POLICY_CONFIG_FIELD_RULES = Object.freeze({ - receive_mode: { - type: 'enum', - values: [ 'standard', 'strict', 'manual' ], - }, - sku_visibility: { - type: 'enum', - values: [ 'all', 'whitelist', 'blacklist' ], - }, - auto_allocate_bin: { - type: 'flag', - }, - allow_mix_batch: { - type: 'flag', - }, - allow_temp_storage: { - type: 'flag', - }, - max_daily_inbound: { - type: 'integer', - min: 0, - max: 1000000, - }, - remark: { - type: 'string', - maxLength: 200, - }, -}); class SettingStoreWarehouseService extends Service { createError(message, code = 500) { @@ -120,6 +92,22 @@ class SettingStoreWarehouseService extends Service { return Math.floor(num); } + normalizeInteger(value, fieldName, options = {}) { + const { allowZero = true } = options; + if (value === undefined || value === null || value === '') { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const num = Number(value); + if (!Number.isFinite(num) || !Number.isInteger(num)) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + if (!allowZero && num === 0) { + throw this.createError(`${fieldName} 不能为 0`, 400); + } + return num; + } + normalizeText(value, fieldName, maxLength = 500) { if (value === undefined || value === null) { return null; @@ -155,77 +143,29 @@ class SettingStoreWarehouseService extends Service { return email; } + getPolicyConfigFieldList() { + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldList !== 'function') { + return []; + } + return storeWarehouseModel.getPolicyConfigFieldList(); + } + normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) { - const { allowEmpty = false } = options; - if (value === undefined || value === null || value === '') { - if (allowEmpty) { - return null; - } - throw this.createError(`${fieldName} 参数不能为空`, 400); + const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; + if (!storeWarehouseModel || typeof storeWarehouseModel.normalizePolicyConfig !== 'function') { + throw this.createError('StoreWarehouse model 未定义 policy_config 规则', 500); } - const parsed = typeof value === 'string' ? (() => { - try { - return JSON.parse(value); - } catch { - throw this.createError(`${fieldName} 不是合法JSON`, 400); - } - })() : value; - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { - throw this.createError(`${fieldName} 必须为对象`, 400); + try { + return storeWarehouseModel.normalizePolicyConfig(value, { + fieldName, + allowEmpty: options.allowEmpty === true, + sanitizeOnly: options.sanitizeOnly === true, + }); + } catch (error) { + throw this.createError(error.message || `${fieldName} 参数不合法`, Number(error.code) || 400); } - - const allowedKeys = Object.keys(POLICY_CONFIG_FIELD_RULES); - const unsupportedKeys = Object.keys(parsed).filter(key => !allowedKeys.includes(key)); - if (unsupportedKeys.length) { - throw this.createError(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${allowedKeys.join(', ')}`, 400); - } - - const normalized = {}; - for (const [ key, rawValue ] of Object.entries(parsed)) { - const rule = POLICY_CONFIG_FIELD_RULES[key]; - if (!rule) { - continue; - } - - if (rule.type === 'enum') { - const valueText = String(rawValue || '').trim(); - if (!rule.values.includes(valueText)) { - throw this.createError(`${fieldName}.${key} 参数不合法`, 400); - } - normalized[key] = valueText; - continue; - } - - if (rule.type === 'flag') { - if (rawValue === true || rawValue === 1 || rawValue === '1') { - normalized[key] = 1; - continue; - } - if (rawValue === false || rawValue === 0 || rawValue === '0') { - normalized[key] = 0; - continue; - } - throw this.createError(`${fieldName}.${key} 参数不合法`, 400); - } - - if (rule.type === 'integer') { - const num = Number(rawValue); - if (!Number.isFinite(num) || num < rule.min || num > rule.max) { - throw this.createError(`${fieldName}.${key} 参数不合法`, 400); - } - normalized[key] = Math.floor(num); - continue; - } - - if (rule.type === 'string') { - const text = this.normalizeText(rawValue, `${fieldName}.${key}`, rule.maxLength); - normalized[key] = text || ''; - } - } - - return normalized; } getPolicyConfigCacheKey(contractId) { @@ -265,22 +205,17 @@ class SettingStoreWarehouseService extends Service { const row = Array.isArray(rows) ? rows[0] : null; const raw = row ? row.policy_config : null; - if (raw === null || raw === undefined || raw === '') { - return null; - } - if (typeof raw === 'object') { - return raw; - } - - try { - return JSON.parse(raw); - } catch { - return null; - } + return this.normalizePolicyConfig(raw, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); } const cached = await this.app.getCacheAsync(this.getPolicyConfigCacheKey(normalizedId)); - return cached && typeof cached === 'object' ? cached : null; + return this.normalizePolicyConfig(cached, 'policy_config', { + allowEmpty: true, + sanitizeOnly: true, + }); } async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) { @@ -306,12 +241,95 @@ class SettingStoreWarehouseService extends Service { await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); } - ensureWarehouseSubject(currentSubject) { + ensureWarehouseSubject(currentSubject, actionLabel = '签约配置') { if (!currentSubject || !currentSubject.isWarehouse) { - throw this.createError('仅仓库主体可维护奇门接口配置', 403); + throw this.createError(`仅仓库主体可维护${actionLabel}`, 403); } } + getNoticeService() { + const rawNoticeService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.notice; + if (rawNoticeService && typeof rawNoticeService.send === 'function') { + return rawNoticeService; + } + if (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function') { + return rawNoticeService.index; + } + return null; + } + + async sendPrintQuantityAdjustNotice({ + relation, + currentSubject, + changeLog, + operatorId, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + } = {}) { + const noticeService = this.getNoticeService(); + if (!noticeService || !relation) { + return null; + } + + const relationData = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + const storeName = relationData.store_remask || (relationData.store && relationData.store.company_name) || ''; + const warehouseName = relationData.warehouse_remask || (relationData.warehouse && relationData.warehouse.company_name) || ''; + const operatorName = String( + (this.ctx.user && (this.ctx.user.real_name || this.ctx.user.employees_name || this.ctx.user.name || this.ctx.user.username)) || '' + ).trim(); + const changeLabel = changeQuantity === 0 + ? '无变化' + : changeQuantity > 0 + ? `增加 ${changeQuantity}` + : `扣减 ${Math.abs(changeQuantity)}`; + + return await noticeService.send({ + warehouseId: Number(relationData.warehouse_id || 0), + storeId: Number(relationData.store_id || 0) || undefined, + messageType: 'text', + businessName: 'store_warehouse', + event: 'store_warehouse_print_quantity_adjusted', + title: '货主面单余额已更新', + content: [ + warehouseName ? `仓库:${warehouseName}` : '', + storeName ? `货主:${storeName}` : '', + `设置余额:${balanceAfter}`, + `变更:${changeLabel}`, + `余额:${balanceBefore} -> ${balanceAfter}`, + `原因:${reason}`, + operatorName ? `操作人:${operatorName}` : '', + ].filter(Boolean).join(';'), + businessId: Number((changeLog && changeLog.id) || relationData.id || 0), + subject: { + id: Number(currentSubject && currentSubject.id || relationData.warehouse_id || 0), + type: currentSubject && currentSubject.isWarehouse ? 'warehouse' : 'store', + name: currentSubject && currentSubject.company_name ? currentSubject.company_name : warehouseName, + }, + sender: { + id: Number(operatorId || 0) || null, + name: operatorName, + }, + metadata: { + contractId: Number(relationData.id || 0), + storeId: Number(relationData.store_id || 0), + warehouseId: Number(relationData.warehouse_id || 0), + changeType: String(changeLog && changeLog.change_type || 'manual_adjust'), + businessType: changeLog && changeLog.business_type ? String(changeLog.business_type) : null, + businessId: changeLog && changeLog.business_id !== undefined && changeLog.business_id !== null + ? Number(changeLog.business_id) + : null, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + }, + }); + } + resolveRelationId(data = {}) { return this.toPositiveNumber( data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id), @@ -604,14 +622,18 @@ class SettingStoreWarehouseService extends Service { await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null))); } - async getQimenInterfaceType(data = {}, options = {}) { + async getApiInterfaceType(data = {}, options = {}) { const { ctx } = this; - const { allowDisabled = false, transaction = null } = options; + const { allowDisabled = false, transaction = null, requireId = false, interfaceCategory = null } = options; const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); - const where = { - interface_category: 'QM_WMS', - }; + if (requireId && !interfaceTypeId) { + throw this.createError('interface_type_id 参数不能为空', 400); + } + const where = {}; + if (interfaceCategory) { + where.interface_category = interfaceCategory; + } if (!allowDisabled) { where.is_enabled = 1; } @@ -627,12 +649,16 @@ class SettingStoreWarehouseService extends Service { }); if (!interfaceType) { - throw this.createError(interfaceTypeId ? '指定的奇门接口类型不存在或不可用' : '未配置可用的奇门接口类型', 404); + throw this.createError(interfaceTypeId ? '指定的接口类型不存在或不可用' : '未配置可用的接口类型', 404); } return interfaceType; } + async getQimenInterfaceType(data = {}, options = {}) { + return this.getApiInterfaceType(data, options); + } + serializeQimenConfig(config) { if (!config) { return null; @@ -652,6 +678,8 @@ class SettingStoreWarehouseService extends Service { contract_id: Number(item.contract_id || 0), warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null, app_name: item.app_name || '', + self_app_key: item.self_app_key || '', + self_app_secret: item.self_app_secret || '', qimen_app_key: item.qimen_app_key || '', qimen_customer_id: item.qimen_customer_id || '', qimen_warehouse_code: item.qimen_warehouse_code || '', @@ -665,6 +693,7 @@ class SettingStoreWarehouseService extends Service { is_enabled: Number(item.is_enabled || 0), created_at: item.created_at || null, updated_at: item.updated_at || null, + callback_url: item.callback_url || '', }; } @@ -677,34 +706,19 @@ class SettingStoreWarehouseService extends Service { return new Map(); } - let interfaceTypeIds = []; + const where = { + contract_id: normalizedContractIds, + }; if (interfaceTypeId) { - interfaceTypeIds = [ Number(interfaceTypeId) ]; - } else { - const interfaceWhere = { - interface_category: 'QM_WMS', - }; - if (!allowDisabled) { - interfaceWhere.is_enabled = 1; - } - - const interfaceTypes = await ctx.model.InterfaceType.findAll({ - where: interfaceWhere, - attributes: [ 'id' ], + const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, { + allowDisabled, transaction, }); - interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); - } - - if (!interfaceTypeIds.length) { - return new Map(); + where.interface_type_id = Number(interfaceType.id || 0); } const rows = await ctx.model.ApiApp.findAll({ - where: { - contract_id: normalizedContractIds, - interface_type_id: interfaceTypeIds, - }, + where, include: [ { model: ctx.model.InterfaceType, @@ -810,7 +824,8 @@ class SettingStoreWarehouseService extends Service { policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null, is_auth_valid: isAuthValid, remaining_days: remainingDays, - qimen_config: normalizedQimenConfig || null, + api_config: normalizedQimenConfig || null, + apiConfig: normalizedQimenConfig || null, }; } @@ -869,14 +884,22 @@ class SettingStoreWarehouseService extends Service { limit: pageSize, distinct: true, }); - const qimenConfigMap = await this.getQimenConfigMap(rows.map(item => Number(item.id || 0)), { - allowDisabled: true, - }); + + const contractIds = rows.map(item => Number(item.id || 0)).filter(id => id > 0); + const qimenConfigMap = contractIds.length + ? await this.getQimenConfigMap(contractIds) + : new Map(); return { code: 200, data: { - list: rows.map(item => this.serializeRelation(item, currentSubject, qimenConfigMap.get(Number(item.id || 0)) || null)), + list: rows.map(item => { + const serialized = this.serializeRelation(item, currentSubject); + delete serialized.api_config; + delete serialized.apiConfig; + serialized.has_qimen_config = qimenConfigMap.has(serialized.id); + return serialized; + }), total: Number(count || 0), page, page_size: pageSize, @@ -970,6 +993,25 @@ class SettingStoreWarehouseService extends Service { await this.clearTempSignPayload(tempCode); await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SIGN', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(payload.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.sign] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { @@ -1061,6 +1103,25 @@ class SettingStoreWarehouseService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_RENAME', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.rename] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { @@ -1073,6 +1134,142 @@ class SettingStoreWarehouseService extends Service { } } + async adjustPrintQuantity(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + this.ensureWarehouseSubject(currentSubject, '面单余额'); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const operatorId = this.getCurrentAccountId(); + const targetQuantityField = [ + [ 'print_quantity', data.print_quantity ], + [ 'target_quantity', data.target_quantity ], + [ 'change_quantity', data.change_quantity ], + [ 'adjust_quantity', data.adjust_quantity ], + ].find(([ , value ]) => value !== undefined && value !== null && value !== ''); + if (!targetQuantityField) { + throw this.createError('print_quantity / target_quantity / change_quantity / adjust_quantity 参数不能为空', 400); + } + const [ targetQuantityFieldName, targetQuantityRaw ] = targetQuantityField; + const targetQuantity = this.normalizeInteger(targetQuantityRaw, targetQuantityFieldName, { allowZero: true }); + if (targetQuantity < 0) { + throw this.createError(`${targetQuantityFieldName} 参数不合法`, 400); + } + const reason = this.normalizeText(data.reason, 'reason', 500); + if (!reason) { + throw this.createError('reason 参数不能为空', 400); + } + + const businessType = this.normalizeText(data.business_type, 'business_type', 50); + const businessId = data.business_id === undefined || data.business_id === null || data.business_id === '' + ? null + : this.toPositiveNumber(data.business_id, 'business_id'); + const balanceBefore = Number(relation.print_quantity || 0); + const balanceAfter = targetQuantity; + const changeQuantity = balanceAfter - balanceBefore; + + await relation.update({ + print_quantity: balanceAfter, + }, { transaction }); + + const changeLogRecord = await ctx.model.StoreWarehousePrintQuantityLog.create({ + contract_id: Number(relation.id || 0), + store_id: Number(relation.store_id || 0), + warehouse_id: Number(relation.warehouse_id || 0), + change_type: 'manual_adjust', + business_type: businessType, + business_id: businessId, + change_quantity: changeQuantity, + balance_before: balanceBefore, + balance_after: balanceAfter, + reason, + operator_id: operatorId, + created_by: operatorId, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + const changeLog = changeLogRecord && typeof changeLogRecord.get === 'function' + ? changeLogRecord.get({ plain: true }) + : (changeLogRecord || {}); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_ADJUST_PRINT_QUANTITY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.adjustPrintQuantity] 写入操作日志失败,不影响业务', logErr); + } + + await this.sendPrintQuantityAdjustNotice({ + relation: result, + currentSubject, + changeLog, + operatorId, + changeQuantity, + balanceBefore, + balanceAfter, + reason, + }).catch(error => { + ctx.logger.warn(`[storeWarehouse.adjustPrintQuantity] 通知发送失败: ${error.message}`); + }); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + change_log: { + id: Number(changeLog.id || 0), + contract_id: Number(changeLog.contract_id || relation.id || 0), + change_type: String(changeLog.change_type || 'manual_adjust'), + business_type: changeLog.business_type ? String(changeLog.business_type) : null, + business_id: changeLog.business_id !== undefined && changeLog.business_id !== null + ? Number(changeLog.business_id) + : null, + change_quantity: Number(changeLog.change_quantity || 0), + balance_before: Number(changeLog.balance_before !== undefined ? changeLog.balance_before : balanceBefore), + balance_after: Number(changeLog.balance_after !== undefined ? changeLog.balance_after : balanceAfter), + reason: changeLog.reason || reason, + operator_id: Number(changeLog.operator_id || operatorId), + created_at: changeLog.created_at || null, + }, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async getPolicyConfigFields() { + return { + code: 200, + data: this.getPolicyConfigFieldList(), + }; + } + async getPolicyConfig(data = {}) { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject); @@ -1098,7 +1295,7 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - this.ensureWarehouseSubject(currentSubject); + this.ensureWarehouseSubject(currentSubject, '签约策略配置'); const policyConfig = this.normalizePolicyConfig( data.policy_config !== undefined ? data.policy_config : data.policy ); @@ -1115,6 +1312,25 @@ class SettingStoreWarehouseService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SAVE_POLICY_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.savePolicyConfig] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { @@ -1129,43 +1345,24 @@ class SettingStoreWarehouseService extends Service { } } - async listQimenConfig(data = {}) { + async listApiConfig(data = {}) { const { ctx } = this; const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject); const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); - const interfaceWhere = { - interface_category: 'QM_WMS', + const where = { + contract_id: Number(relation.id || 0), }; if (interfaceTypeId) { - interfaceWhere.id = interfaceTypeId; - } - - const interfaceTypes = await ctx.model.InterfaceType.findAll({ - where: interfaceWhere, - attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], - order: [[ 'id', 'ASC' ]], - }); - const interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); - - if (!interfaceTypeIds.length) { - return { - code: 200, - data: { - contract_id: Number(relation.id || 0), - contract: this.serializeRelation(relation, currentSubject, null), - list: [], - total: 0, - }, - }; + const interfaceType = await this.getApiInterfaceType({ interface_type_id: interfaceTypeId }, { + allowDisabled: true, + }); + where.interface_type_id = Number(interfaceType.id || 0); } const rows = await ctx.model.ApiApp.findAll({ - where: { - contract_id: Number(relation.id || 0), - interface_type_id: interfaceTypeIds, - }, + where, include: [ { model: ctx.model.InterfaceType, @@ -1178,52 +1375,60 @@ class SettingStoreWarehouseService extends Service { }); const list = rows.map(item => this.serializeQimenConfig(item)); - const primaryQimenConfig = list.length ? list[0] : null; + const primaryApiConfig = list.length ? list[0] : null; return { code: 200, data: { contract_id: Number(relation.id || 0), - contract: this.serializeRelation(relation, currentSubject, primaryQimenConfig), + contract: this.serializeRelation(relation, currentSubject, primaryApiConfig), list, total: list.length, }, }; } - async saveQimenConfig(data = {}) { + async saveApiConfig(data = {}) { const { ctx, app } = this; const transaction = await ctx.model.transaction(); try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - this.ensureWarehouseSubject(currentSubject); - const interfaceType = await this.getQimenInterfaceType(data, { transaction }); - const qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); - if (!qimenAppKey) { - throw this.createError('qimen_app_key 参数不能为空', 400); - } - const qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); - if (!qimenCustomerId) { - throw this.createError('qimen_customer_id 参数不能为空', 400); - } - const qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); - if (!qimenWarehouseCode) { - throw this.createError('qimen_warehouse_code 参数不能为空', 400); + this.ensureWarehouseSubject(currentSubject, '接口配置'); + const interfaceType = await this.getApiInterfaceType(data, { transaction, requireId: true }); + const isOpenApi = interfaceType.interface_category === 'OPEN_API'; + const isQimenWms = interfaceType.interface_category === 'QM_WMS'; + + // 奇门相关字段:QM_WMS 必填,OPEN_API 不需要 + let qimenAppKey = null; + let qimenCustomerId = null; + let qimenWarehouseCode = null; + + if (isQimenWms) { + qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); + if (!qimenAppKey) { + throw this.createError('奇门接口类型下 qimen_app_key 参数不能为空', 400); + } + qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); + if (!qimenCustomerId) { + throw this.createError('奇门接口类型下 qimen_customer_id 参数不能为空', 400); + } + qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); + if (!qimenWarehouseCode) { + throw this.createError('奇门接口类型下 qimen_warehouse_code 参数不能为空', 400); + } + } else { + // OPEN_API: 奇门字段可选输入 + qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100) || null; + qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100) || null; + qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100) || null; } - const relationPlain = relation && typeof relation.get === 'function' - ? relation.get({ plain: true }) - : relation; - const defaultAppName = [ - relationPlain && relationPlain.store_remask ? relationPlain.store_remask : currentSubject.company_name, - relationPlain && relationPlain.warehouse_remask - ? relationPlain.warehouse_remask - : (relationPlain && relationPlain.warehouse && relationPlain.warehouse.company_name ? relationPlain.warehouse.company_name : `contract-${relation.id}`), - '奇门接口', - ].filter(Boolean).join('-').slice(0, 200); - const appName = this.normalizeText(data.app_name, 'app_name', 200) || defaultAppName; + const appName = this.normalizeText(data.app_name, 'app_name', 200); + if (!appName) { + throw this.createError('app_name 参数不能为空', 400); + } const apiVersion = this.normalizeText(data.api_version, 'api_version', 50) || '1.0'; const signMethod = (this.normalizeText(data.sign_method, 'sign_method', 50) || 'md5').toLowerCase(); if (![ 'md5', 'hmac', 'sha256' ].includes(signMethod)) { @@ -1255,21 +1460,41 @@ class SettingStoreWarehouseService extends Service { }); const { Op } = app.Sequelize; - const duplicateWhere = { - interface_type_id: Number(interfaceType.id || 0), - qimen_app_key: qimenAppKey, - qimen_customer_id: qimenCustomerId, - }; - if (config && config.id) { - duplicateWhere.id = { [Op.ne]: config.id }; + // 重复检测:按接口类型不同检查策略 + let duplicateConfig = null; + if (isQimenWms && qimenAppKey && qimenCustomerId) { + const duplicateWhere = { + interface_type_id: Number(interfaceType.id || 0), + qimen_app_key: qimenAppKey, + qimen_customer_id: qimenCustomerId, + }; + if (config && config.id) { + duplicateWhere.id = { [Op.ne]: config.id }; + } + duplicateConfig = await ctx.model.ApiApp.findOne({ + where: duplicateWhere, + attributes: [ 'id', 'contract_id' ], + transaction, + }); + if (duplicateConfig) { + throw this.createError('该 AppKey 和客户ID 已绑定其他签约关系', 409); + } } - const duplicateConfig = await ctx.model.ApiApp.findOne({ - where: duplicateWhere, - attributes: [ 'id', 'contract_id' ], - transaction, - }); - if (duplicateConfig) { - throw this.createError('该奇门 AppKey 和客户ID 已绑定其他签约关系', 409); + + // OPEN_API: 创建时自动生成 self_app_key 和 self_app_secret + let selfAppKey = null; + let selfAppSecret = null; + if (isOpenApi) { + if (config) { + // 更新时保留已有密钥 + selfAppKey = config.self_app_key; + selfAppSecret = config.self_app_secret; + } else { + // 创建时生成新密钥 + const crypto = require('crypto'); + selfAppKey = `WMS${crypto.randomBytes(16).toString('hex').toUpperCase()}`; + selfAppSecret = crypto.randomBytes(32).toString('hex'); + } } const configPayload = { @@ -1277,6 +1502,8 @@ class SettingStoreWarehouseService extends Service { interface_type_id: Number(interfaceType.id || 0), contract_id: Number(relation.id || 0), warehouse_id: relation.warehouse_id ? Number(relation.warehouse_id) : null, + self_app_key: selfAppKey, + self_app_secret: selfAppSecret, qimen_app_key: qimenAppKey, qimen_customer_id: qimenCustomerId, qimen_warehouse_code: qimenWarehouseCode, @@ -1313,28 +1540,49 @@ class SettingStoreWarehouseService extends Service { include: this.getRelationIncludes(), transaction, }); - const qimenConfig = this.serializeQimenConfig(savedConfig); + const apiConfig = this.serializeQimenConfig(savedConfig); await transaction.commit(); - await this.clearQimenContractCache([ previousConfig, qimenConfig ]).catch(error => { - ctx.logger.warn('[storeWarehouse.saveQimenConfig] 清理奇门缓存失败: %s', error.message); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_SAVE_API_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.saveApiConfig] 写入操作日志失败,不影响业务', logErr); + } + + await this.clearQimenContractCache([ previousConfig, apiConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.saveApiConfig] 清理奇门缓存失败: %s', error.message); }); return { code: 200, data: { action, - contract: this.serializeRelation(result, currentSubject, qimenConfig), - qimen_config: qimenConfig, + contract: this.serializeRelation(result, currentSubject, apiConfig), + api_config: apiConfig, + apiConfig, }, }; } catch (error) { await transaction.rollback(); if (error && error.name === 'SequelizeUniqueConstraintError') { - throw this.createError('奇门接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); + throw this.createError('接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); } if (error && error.name === 'SequelizeValidationError') { - const message = error.errors && error.errors.length ? error.errors[0].message : '奇门接口配置参数校验失败'; + const message = error.errors && error.errors.length ? error.errors[0].message : '接口配置参数校验失败'; throw this.createError(message, 400); } throw error; @@ -1348,8 +1596,8 @@ class SettingStoreWarehouseService extends Service { try { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject, transaction); - this.ensureWarehouseSubject(currentSubject); - const interfaceType = await this.getQimenInterfaceType(data, { + this.ensureWarehouseSubject(currentSubject, '接口配置'); + const interfaceType = await this.getApiInterfaceType(data, { allowDisabled: true, transaction, }); @@ -1370,7 +1618,7 @@ class SettingStoreWarehouseService extends Service { }); if (!config) { - throw this.createError('奇门接口配置不存在', 404); + throw this.createError('接口配置不存在', 404); } const removedConfig = this.serializeQimenConfig(config); @@ -1382,6 +1630,26 @@ class SettingStoreWarehouseService extends Service { }); await transaction.commit(); + + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_DELETE_API_CONFIG', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 写入操作日志失败,不影响业务', logErr); + } + await this.clearQimenContractCache([ removedConfig ]).catch(error => { ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 清理奇门缓存失败: %s', error.message); }); @@ -1391,7 +1659,8 @@ class SettingStoreWarehouseService extends Service { data: { deleted: true, contract: this.serializeRelation(result, currentSubject, null), - qimen_config: null, + api_config: null, + apiConfig: null, removed: removedConfig, }, }; @@ -1425,6 +1694,25 @@ class SettingStoreWarehouseService extends Service { await transaction.commit(); + // 记录操作日志 + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'store', + businessId: relation.id, + operationCode: 'STORE_UNBIND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(relation.warehouse_id || 0), + }, + beforeChanges: null, + }); + } catch (logErr) { + ctx.logger.warn('[storeWarehouse.unbind] 写入操作日志失败,不影响业务', logErr); + } + return { code: 200, data: { diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index 0a796da..cff423f 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -4,7 +4,6 @@ const Service = require('egg').Service; const COS = require('cos-nodejs-sdk-v5'); const path = require('path'); const crypto = require('crypto'); -const { v4: uuidv4 } = require('uuid'); const dayjs = require('dayjs'); class UploadService extends Service { @@ -23,13 +22,12 @@ class UploadService extends Service { /** * 获取上传参数 - 使用与PHP一致的算法 - * @param fileInfo + * @param {Object} fileInfo 上传参数对象 */ async getUploadParams(fileInfo) { const { ctx } = this; const warehouseId = ctx.user.store_id; - console.log('fileInfo', fileInfo); - const { fileName, fileType, fileSize, type, id, md5 } = fileInfo; + const { fileName, fileType, fileSize, type, md5 } = fileInfo; if (md5) { const existingFile = await ctx.model.File.findOne({ @@ -52,7 +50,7 @@ class UploadService extends Service { } } // 验证文件 - this.validateFileInfo({ fileName, fileType, fileSize }); + this.validateFileInfo({ fileName, fileSize }); const warehouse_quota = await this.app.model.query( 'SELECT * FROM vw_warehouse_quota WHERE warehouse_id = :warehouseId', @@ -68,7 +66,6 @@ class UploadService extends Service { msg: '空间配额已满', }; } - console.log('空间计算剩余可用', remaining_bytes - fileSize); // 生成文件名 const cosFileName = this.generateFileName(fileName, fileType, type, md5); @@ -127,12 +124,12 @@ class UploadService extends Service { * 生成策略和签名 - 与PHP算法完全一致 * 参考你的PHP代码: * $signature = hash_hmac('sha1', sha1($policy), hash_hmac('sha1', $keytime, $config['secretKey'])); - * @param key - * @param startTime - * @param expireTime + * @param {string} key 文件 key + * @param {number} startTime 开始时间戳 + * @param {number} expireTime 过期时间戳 */ generatePolicyAndSignature(key, startTime, expireTime) { - const { secretId, secretKey, bucket } = this.config.cos; + const { secretId, secretKey } = this.config.cos; const keyTime = `${startTime};${expireTime}`; // 1. 生成策略 - 与PHP完全一致 @@ -165,12 +162,6 @@ class UploadService extends Service { const signature = outerHmac.digest('hex'); // 最终的签名 // 调试信息 - console.log('策略原始内容:', policyString); - console.log('策略Base64:', policyBase64); - console.log('keyTime:', keyTime); - console.log('signKey (内层HMAC):', signKey); - console.log('policyHash (SHA1):', policyHash); - console.log('signature (外层HMAC):', signature); return { policy: policyBase64, @@ -182,12 +173,11 @@ class UploadService extends Service { } /** * 验证文件信息 - * @param root0 - * @param root0.fileName - * @param root0.fileType - * @param root0.fileSize + * @param {Object} root0 文件信息对象 + * @param {string} root0.fileName 文件名 + * @param {number} root0.fileSize 文件大小 */ - validateFileInfo({ fileName, fileType, fileSize }) { + validateFileInfo({ fileName, fileSize }) { const { maxsize, mimetype } = this.config.cos; // 验证文件大小 @@ -209,10 +199,10 @@ class UploadService extends Service { /** * 生成文件唯一名称 - * @param fileName - * @param fileType - * @param category - * @param md5 + * @param {string} fileName 原始文件名 + * @param {string} fileType 文件类型 + * @param {string} category 分类 + * @param {string} md5 文件 MD5 */ generateFileName(fileName, fileType, category = '', md5) { const { savekey, dirs } = this.config.cos; @@ -250,7 +240,7 @@ class UploadService extends Service { /** * 解析文件大小字符串为字节数 - * @param sizeStr + * @param {string|number} sizeStr 文件大小字符串或字节数 */ parseSizeToBytes(sizeStr) { if (typeof sizeStr === 'number') { @@ -277,7 +267,7 @@ class UploadService extends Service { /** * 格式化文件大小 - * @param bytes + * @param {number} bytes 字节数 */ formatFileSize(bytes) { if (bytes === 0) return '0 B'; @@ -291,8 +281,8 @@ class UploadService extends Service { /** * 获取前端配置 - * @param fileType - * @param fileSize + * @param {string} fileType 文件类型 + * @param {number} fileSize 文件大小 */ getFrontendConfig(fileType, fileSize) { const { chunkSize } = this.config.cos; @@ -310,8 +300,8 @@ class UploadService extends Service { /** * 服务器端上传文件 - * @param fileStream - * @param options + * @param {Object} fileStream 文件流对象 + * @param {Object} options 上传选项 */ async uploadFile(fileStream, options = {}) { const { bucket, region } = this.config.cos; @@ -351,8 +341,8 @@ class UploadService extends Service { /** * 验证文件 - * @param fileStream - * @param options + * @param {Object} fileStream 文件流对象 + * @param {Object} options 上传选项 */ validateFile(fileStream, options = {}) { const { maxsize, mimetype } = this.config.cos; @@ -388,7 +378,6 @@ class UploadService extends Service { */ async uploadSuccessNotify(data) { const { ctx } = this; - console.log('上传成功', data); try { // 从上下文获取用户信息(根据你的实际用户认证方式) const warehouseId = ctx.user?.store_id || ctx.query.warehouseId || ctx.request.body.warehouseId; @@ -557,7 +546,7 @@ class UploadService extends Service { /** * 根据文件名获取MIME类型 - * @param fileName + * @param {string} fileName 文件名 */ getMimeType(fileName) { const ext = path.extname(fileName).toLowerCase(); @@ -588,13 +577,13 @@ class UploadService extends Service { /** * 创建文件业务引用关系 - * @param fileId - * @param businessType - * @param businessId - * @param {Object} [options] - * @param {number|string} [options.warehouseId] - * @param {string} [options.createdBy] - * @param {number} [options.displayOrder] + * @param {number|string} fileId 文件 ID + * @param {string} businessType 业务类型 + * @param {number|string} businessId 业务 ID + * @param {Object} [options] 可选参数 + * @param {number|string} [options.warehouseId] 仓库 ID + * @param {string} [options.createdBy] 创建人 + * @param {number} [options.displayOrder] 显示顺序 */ async createFileReference(fileId, businessType, businessId, options = {}) { const { ctx } = this; @@ -658,14 +647,14 @@ class UploadService extends Service { /** * 上传完成回调接口 - 供前端调用 - * @param callbackData + * @param {Object} callbackData 回调数据 */ async handleUploadCallback(callbackData) { const { ctx } = this; try { // 解析回调数据 - const { key, size, mimeType, etag, location, businessInfo } = callbackData; + const { key, size, mimeType, businessInfo } = callbackData; // 构建文件信息 const fileInfo = { diff --git a/config/config.default.js b/config/config.default.js index 76e8613..289a620 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -107,6 +107,7 @@ module.exports = appInfo => { config.cors = { origin: '*', // 允许所有源,生产环境应指定具体域名 allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', + exposeHeaders: 'Authorization', credentials: true, // 允许携带 cookie }; diff --git a/database/migrations/20251109160640-init-wms_account.js b/database/migrations/20251109160640-init-wms_account.js index bae015e..950495e 100644 --- a/database/migrations/20251109160640-init-wms_account.js +++ b/database/migrations/20251109160640-init-wms_account.js @@ -2,7 +2,7 @@ module.exports = { async up(queryInterface, Sequelize) { - const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize; + const { BIGINT, STRING, DATE, TINYINT } = Sequelize; await queryInterface.createTable('wms_account', { id: { @@ -102,7 +102,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { await queryInterface.dropTable('wms_account'); }, }; diff --git a/database/migrations/20251110081122-create-wms-account-login-log.js b/database/migrations/20251110081122-create-wms-account-login-log.js index 06259ed..8d7080a 100644 --- a/database/migrations/20251110081122-create-wms-account-login-log.js +++ b/database/migrations/20251110081122-create-wms-account-login-log.js @@ -100,7 +100,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_account_login_log'" diff --git a/database/migrations/20251110081641-create-wms-qimen-apps.js b/database/migrations/20251110081641-create-wms-qimen-apps.js index ec95c0e..6888e3a 100644 --- a/database/migrations/20251110081641-create-wms-qimen-apps.js +++ b/database/migrations/20251110081641-create-wms-qimen-apps.js @@ -74,7 +74,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_qimen_apps'" diff --git a/database/migrations/20251110082013-create-wms-store.js b/database/migrations/20251110082013-create-wms-store.js index 69904ca..9240b4d 100644 --- a/database/migrations/20251110082013-create-wms-store.js +++ b/database/migrations/20251110082013-create-wms-store.js @@ -182,7 +182,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_store'" diff --git a/database/migrations/20251110084033-create-wms-store-warehouse.js b/database/migrations/20251110084033-create-wms-store-warehouse.js index 36e1f33..91b05b1 100644 --- a/database/migrations/20251110084033-create-wms-store-warehouse.js +++ b/database/migrations/20251110084033-create-wms-store-warehouse.js @@ -185,7 +185,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_store_warehouse'" diff --git a/database/migrations/20251110090742-create-wms-interface-type.js b/database/migrations/20251110090742-create-wms-interface-type.js index 21a1571..5fbbfc3 100644 --- a/database/migrations/20251110090742-create-wms-interface-type.js +++ b/database/migrations/20251110090742-create-wms-interface-type.js @@ -108,7 +108,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_interface_type'" diff --git a/database/migrations/20251110091013-create-wms-api-app.js b/database/migrations/20251110091013-create-wms-api-app.js index ec44d98..05830f2 100644 --- a/database/migrations/20251110091013-create-wms-api-app.js +++ b/database/migrations/20251110091013-create-wms-api-app.js @@ -207,7 +207,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_api_app'" diff --git a/database/migrations/20251111083733-create-wms-stock-store.js b/database/migrations/20251111083733-create-wms-stock-store.js index 173353e..8c246e2 100644 --- a/database/migrations/20251111083733-create-wms-stock-store.js +++ b/database/migrations/20251111083733-create-wms-stock-store.js @@ -285,7 +285,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_stock_store'" diff --git a/database/migrations/20251112085825-create-wms-entry-order.js b/database/migrations/20251112085825-create-wms-entry-order.js index 72a6fed..2561536 100644 --- a/database/migrations/20251112085825-create-wms-entry-order.js +++ b/database/migrations/20251112085825-create-wms-entry-order.js @@ -236,7 +236,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_order'" diff --git a/database/migrations/20251112085844-create-wms-entry-items.js b/database/migrations/20251112085844-create-wms-entry-items.js index d13fe01..faff43c 100644 --- a/database/migrations/20251112085844-create-wms-entry-items.js +++ b/database/migrations/20251112085844-create-wms-entry-items.js @@ -138,7 +138,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { // 安全删除表 const [ tables ] = await queryInterface.sequelize.query( "SHOW TABLES LIKE 'wms_entry_items'" diff --git a/database/migrations/20260323103000-align-role-permission-fk.js b/database/migrations/20260323103000-align-role-permission-fk.js index 892fbb8..3aca3fe 100644 --- a/database/migrations/20260323103000-align-role-permission-fk.js +++ b/database/migrations/20260323103000-align-role-permission-fk.js @@ -1,7 +1,6 @@ 'use strict'; const TABLE = 'wms_role_permission'; -const REF_TABLE = 'wms_permission'; const FK_NAME = 'fk_wms_role_permission_permission'; async function getColumnInfo(queryInterface, tableName, columnName) { diff --git a/database/migrations/20260323113000-add-role-store-fk.js b/database/migrations/20260323113000-add-role-store-fk.js index 62f6591..353aa89 100644 --- a/database/migrations/20260323113000-add-role-store-fk.js +++ b/database/migrations/20260323113000-add-role-store-fk.js @@ -1,7 +1,6 @@ 'use strict'; const TABLE = 'wms_role'; -const REF_TABLE = 'wms_store'; const FK_NAME = 'fk_wms_role_store'; const INDEX_NAME = 'idx_store_id'; diff --git a/database/migrations/20260323123000-add-permission-parent-fk.js b/database/migrations/20260323123000-add-permission-parent-fk.js index eaa39f4..a1321d1 100644 --- a/database/migrations/20260323123000-add-permission-parent-fk.js +++ b/database/migrations/20260323123000-add-permission-parent-fk.js @@ -1,7 +1,6 @@ 'use strict'; const TABLE = 'wms_permission'; -const COLUMN = 'parent_id'; const FK_NAME = 'fk_wms_permission_parent'; async function hasConstraint(queryInterface, tableName, constraintName) { diff --git a/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js index 3ba7243..39475c5 100644 --- a/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js +++ b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js @@ -14,7 +14,7 @@ module.exports = { }); }, - async down(queryInterface, Sequelize) { + async down(queryInterface) { const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); if (columns.length === 0) { return; diff --git a/database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js b/database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js new file mode 100644 index 0000000..cda65b9 --- /dev/null +++ b/database/migrations/20260407153000-create-wms-store-warehouse-print-quantity-log.js @@ -0,0 +1,160 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TEXT, DATE } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_store_warehouse_print_quantity_log'" + ); + + if (tables.length > 0) { + console.log('Table wms_store_warehouse_print_quantity_log already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_store_warehouse_print_quantity_log', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + contract_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store_warehouse', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '签约关系ID,对应 wms_store_warehouse.id', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '货主ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'NO ACTION', + comment: '仓库ID', + }, + change_type: { + type: STRING(50), + allowNull: false, + comment: '变更类型,如 manual_adjust / order_deduct', + }, + business_type: { + type: STRING(50), + allowNull: true, + comment: '业务来源类型,如 order_express', + }, + business_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '业务关联ID,预留关联 wms_order_express.id', + }, + change_quantity: { + type: BIGINT(20), + allowNull: false, + comment: '本次变更数量,整数,可正可负', + }, + balance_before: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更前余额', + }, + balance_after: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '变更后余额', + }, + reason: { + type: TEXT, + allowNull: true, + comment: '变更缘由;人工调整时必填', + }, + operator_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '操作人账号ID', + }, + created_by: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '创建人账号ID', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '货主-仓库签约面单余额变更记录表', + }); + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'contract_id', 'id' ], { + name: 'idx_sw_print_qty_log_contract_id', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'store_id', 'warehouse_id' ], { + name: 'idx_sw_print_qty_log_store_warehouse', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'business_type', 'business_id' ], { + name: 'idx_sw_print_qty_log_business', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'change_type' ], { + name: 'idx_sw_print_qty_log_change_type', + }); + + await safeCreateIndex('wms_store_warehouse_print_quantity_log', [ 'created_at' ], { + name: 'idx_sw_print_qty_log_created_at', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_store_warehouse_print_quantity_log'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_store_warehouse_print_quantity_log'); + } + }, +}; diff --git a/database/migrations/20260407160000-add-receiving-id-to-wms-storage.js b/database/migrations/20260407160000-add-receiving-id-to-wms-storage.js new file mode 100644 index 0000000..45e2010 --- /dev/null +++ b/database/migrations/20260407160000-add-receiving-id-to-wms-storage.js @@ -0,0 +1,35 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'receiving_id'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_storage', 'receiving_id', { + type: Sequelize.INTEGER, + allowNull: true, + comment: '收货单ID', + after: 'inbound_order_no', + }); + + await queryInterface.addIndex('wms_storage', [ 'receiving_id' ], { + name: 'idx_receiving_id', + }); + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_storage` WHERE Key_name = 'idx_receiving_id'" + ); + if (indexes.length > 0) { + await queryInterface.removeIndex('wms_storage', 'idx_receiving_id'); + } + + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'receiving_id'"); + if (columns.length > 0) { + await queryInterface.removeColumn('wms_storage', 'receiving_id'); + } + }, +}; diff --git a/database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js b/database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js new file mode 100644 index 0000000..a88bb5e --- /dev/null +++ b/database/migrations/20260408100000-add-entry-order-id-to-wms-storage.js @@ -0,0 +1,41 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'entry_order_id'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_storage', 'entry_order_id', { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: '入库单ID', + after: 'receiving_id', + references: { + model: 'wms_entry_order', + key: 'id', + }, + onDelete: 'SET NULL', + onUpdate: 'CASCADE', + }); + + await queryInterface.addIndex('wms_storage', [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + }, + + async down(queryInterface) { + const [ indexes ] = await queryInterface.sequelize.query( + "SHOW INDEX FROM `wms_storage` WHERE Key_name = 'idx_entry_order_id'" + ); + if (indexes.length > 0) { + await queryInterface.removeIndex('wms_storage', 'idx_entry_order_id'); + } + + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_storage` LIKE 'entry_order_id'"); + if (columns.length > 0) { + await queryInterface.removeColumn('wms_storage', 'entry_order_id'); + } + }, +}; diff --git a/database/migrations/20260408120000-add-callback-url-to-api-app.js b/database/migrations/20260408120000-add-callback-url-to-api-app.js new file mode 100644 index 0000000..15e8693 --- /dev/null +++ b/database/migrations/20260408120000-add-callback-url-to-api-app.js @@ -0,0 +1,18 @@ +'use strict'; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_api_app', 'callback_url', { + type: Sequelize.STRING(500), + allowNull: true, + defaultValue: null, + comment: 'API回调通知URL', + after: 'self_ip_whitelist', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_api_app', 'callback_url'); + }, +}; diff --git a/database/migrations/20260408140000-create-wms-stock-transaction.js b/database/migrations/20260408140000-create-wms-stock-transaction.js new file mode 100644 index 0000000..08e5ca0 --- /dev/null +++ b/database/migrations/20260408140000-create-wms-stock-transaction.js @@ -0,0 +1,169 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, INTEGER, ENUM, DATE } = Sequelize; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_stock_transaction'" + ); + + if (tables.length > 0) { + console.log('Table wms_stock_transaction already exists, skipping creation'); + return; + } + + await queryInterface.createTable('wms_stock_transaction', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + transaction_type: { + type: ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品库存ID,关联 wms_stock_warehouse.id', + }, + storage_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位库存ID,关联 wms_storage.id', + }, + space_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + comment: '变动数量(正数)', + }, + batch_no: { + type: STRING(100), + allowNull: true, + comment: '批次号', + }, + inventory_type: { + type: ENUM('ZP', 'CC', 'JS', 'XS', 'ZT', 'DJ', 'FP'), + defaultValue: 'ZP', + comment: '库存类型', + }, + order_type: { + type: STRING(50), + allowNull: true, + comment: '关联单据类型', + }, + order_no: { + type: STRING(100), + allowNull: true, + comment: '关联单据号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联单据ID', + }, + receiving_id: { + type: INTEGER, + allowNull: true, + comment: '关联收货单ID', + }, + entry_order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '关联入库单ID', + }, + operator_id: { + type: STRING(100), + allowNull: true, + comment: '操作人ID', + }, + operator_name: { + type: STRING(100), + allowNull: true, + comment: '操作人名称', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_general_ci', + comment: '出入库流水记录表', + }); + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_stock_transaction', [ 'stock_id' ], { + name: 'idx_stock_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'warehouse_id', 'created_at' ], { + name: 'idx_warehouse_time', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'order_type', 'order_id' ], { + name: 'idx_order', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'receiving_id' ], { + name: 'idx_receiving_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'entry_order_id' ], { + name: 'idx_entry_order_id', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'created_at' ], { + name: 'idx_created_at', + }); + + await safeCreateIndex('wms_stock_transaction', [ 'store_id', 'transaction_type' ], { + name: 'idx_store_transaction_type', + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_stock_transaction'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_stock_transaction'); + } + }, +}; diff --git a/docs/notification-event-api.md b/docs/notification-event-api.md index 42e763c..0e9baed 100644 --- a/docs/notification-event-api.md +++ b/docs/notification-event-api.md @@ -11,9 +11,10 @@ - 由内部业务在关键节点触发 `event` - 通过 WebHook 向外部系统推送标准 JSON 消息 -当前第一批落地事件: +当前已落地事件: - `receiving_completed`:收货完成通知 +- `store_warehouse_print_quantity_adjusted`:货主面单余额人工调整通知 --- @@ -50,8 +51,9 @@ await ctx.service.systems.notice.send({ | event | 含义 | |---|---| | `receiving_completed` | 收货单完成通知 | +| `store_warehouse_print_quantity_adjusted` | 货主面单余额人工调整通知 | -> 当前正式注册的业务事件仅保留 `receiving_completed`。 +> 当前正式注册的业务事件包括 `receiving_completed`、`store_warehouse_print_quantity_adjusted`。 对于外部订阅方来说,判断消息类型时,优先看: @@ -201,7 +203,39 @@ Content-Type: application/json --- -## 9. 后续事件扩展建议 +## 9. 当前已落地事件:`store_warehouse_print_quantity_adjusted` + +### 9.1 业务含义 + +当仓库侧对某个货主签约关系执行人工面单余额调整后,系统会向相关 WebHook 推送一条 `store_warehouse_print_quantity_adjusted` 通知。 + +### 9.2 推送目标 + +由 `wms_notification_webhook` 决定: + +- 匹配签约仓库 `warehouseId` 绑定的接口 +- 若签约中带有 `storeId`,同步匹配货主绑定的接口 +- `events` 命中以下任一规则即可推送: + - `all` + - `*` + - `store_warehouse_print_quantity_adjusted` + +### 9.3 metadata 关键字段 + +| 字段 | 类型 | 说明 | +|---|---|---| +| `contractId` | `number` | 签约关系 ID | +| `changeType` | `string` | 当前固定为 `manual_adjust` | +| `businessType` | `string \| null` | 业务类型预留字段 | +| `businessId` | `number \| null` | 业务关联 ID,预留给 `wms_order_express.id` | +| `changeQuantity` | `number` | 本次调整值,整数,可正可负 | +| `balanceBefore` | `number` | 调整前余额 | +| `balanceAfter` | `number` | 调整后余额 | +| `reason` | `string` | 调整缘由 | + +--- + +## 10. 后续事件扩展建议 下一步可继续补充: diff --git a/docs/notification-webhook-capability.md b/docs/notification-webhook-capability.md index 22ba7b9..c115cab 100644 --- a/docs/notification-webhook-capability.md +++ b/docs/notification-webhook-capability.md @@ -251,7 +251,71 @@ warehouse:{warehouseId}store:{storeId}:info --- -## 12. 后续扩展建议 +## 12. 新增功能需要通知时怎么接入 + +当其他功能模块需要新增通知时,建议按下面 4 步接入,避免各自重复造轮子: + +### 12.1 注册事件 + +先在 `app/model/notification_webhook.js` 的 `AVAILABLE_EVENTS` 中登记新的事件编码。 + +要求: + +- 事件名仅允许小写字母、数字、下划线 +- 首字符不能为数字 +- **禁止使用 `.`** +- 未注册的事件,`notice.send()` 会直接拒绝发送 + +### 12.2 在业务 service 调用统一入口 + +在实际业务 service 中调用: + +```js +await ctx.service.systems.notice.send({ + warehouseId, + storeId, // 可选,也可传 ownerId + businessName: 'your_business', + event: 'your_event_code', + messageType: 'text', + title: '通知标题', + content: '通知内容', + businessId, + subject, + sender, + metadata, +}); +``` + +接入原则: + +- `warehouseId` 必传,`storeId / ownerId` 可空 +- 业务侧只负责组装业务语义并调用统一入口 +- 重试、分发、失败日志由 `app/service/systems/notice/index.js` 统一处理 +- 如需图片 / 文件通知,补充 `url`、`fileName`、`mimeType` + +### 12.3 测试验证 + +至少补 2 类验证: + +1. **notice 能力测试**:确认事件注册、WebHook 命中、payload 结构与失败处理符合预期 + - 参考:`test/app/service/systems/notice.test.js` +2. **业务回归测试**:确认业务节点确实会触发通知调用 + - 参考:`test/app/service/systems/storage.receiving.report.test.js` + +若对接的是外部地址,还应额外确认: + +- 返回结果是否符合成功约定(如 `1` / `ok` / `errcode=0`) +- 对方是否能正确解析当前 JSON payload + +### 12.4 文档同步 + +接入完成后,至少同步以下文档: + +- 本文档:补能力边界、接入规则或命中说明 +- `docs/notification-event-api.md`:新增事件说明与 payload 示例 +- 若对外暴露了新的 `/system` 接口或 method,再按需同步 `methods/*.json` + +## 13. 后续扩展建议 建议后续继续补充: diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md new file mode 100644 index 0000000..99208f1 --- /dev/null +++ b/docs/storage-receiving-api.md @@ -0,0 +1,219 @@ +# 收货单 API 文档(`storage.receiving`) + +## 1. 文档说明 + +本文档补充 `storage.receiving` 相关 system 方法中的收货明细商品绑定接口,当前重点覆盖: + +- `storage.receiving.bindDetailProduct` + +适用场景: + +- 新增收货单明细后,为该明细绑定系统商品 +- 已绑定商品时,改绑为另一个系统商品 +- 前端或第三方系统对接收货单明细与系统商品的匹配动作 + +--- + +## 2. 统一调用方式 + +该项目的 system 方法统一通过 `/system` 调用,方法名通过 query 参数 `method` 传入。 + +### 请求方式 + +```http +POST /system?method=storage.receiving.bindDetailProduct&v=1.0×tamp={unix_timestamp} +Content-Type: application/json +Authorization: Bearer +platform: web +project: wms +``` + +### 调用示例 + +```bash +curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailProduct&v=1.0×tamp=1712400000" \ + -H "Authorization: Bearer " \ + -H "Content-Type: application/json" \ + -H "platform: web" \ + -H "project: wms" \ + -d '{ + "detail_id": 12345, + "system_product_id": 67890 + }' +``` + +> 说明:该接口通常要求用户已登录,并以当前仓库角色执行;实际仓库上下文来自 `ctx.user.store_id`。 + +--- + +## 3. 接口:`storage.receiving.bindDetailProduct` + +### 3.1 接口用途 + +用于**绑定或改绑收货单明细的系统商品**。 + +调用成功后,系统会按当前仓库商品信息自动回填或更新以下内容: + +- `system_product_id` +- `product_name` +- `product_snapshot` +- `barcode`(有条码时) +- `weight`(商品存在毛重时) +- 箱规尺寸字段(启用箱规时) + +同时会刷新整张收货单的统计信息。 + +### 3.2 请求参数 + +| 字段 | 类型 | 必填 | 说明 | +|---|---:|---|---| +| `detail_id` | `number` | 是 | 收货单明细 ID | +| `id` | `number` | 否 | 兼容字段,可替代 `detail_id` | +| `system_product_id` | `number` | 是 | 要绑定的系统商品 ID(`StockWarehouse.id`) | + +### 3.3 请求体示例 + +```json +{ + "detail_id": 12345, + "system_product_id": 67890 +} +``` + +--- + +## 4. 成功返回示例 + +```json +{ + "flag": "success", + "code": 200, + "message": "绑定商品成功", + "data": { + "detail_id": 12345, + "receiving_id": 10001, + "system_product_id": 67890, + "product_name": "测试商品A" + } +} +``` + +### 返回字段说明 + +| 字段 | 类型 | 说明 | +|---|---:|---| +| `flag` | `string` | 固定为 `success` | +| `code` | `number` | 业务状态码,成功为 `200` | +| `message` | `string` | 返回说明 | +| `data.detail_id` | `number` | 当前绑定的收货单明细 ID | +| `data.receiving_id` | `number` | 收货单 ID | +| `data.system_product_id` | `number` | 当前绑定的系统商品 ID | +| `data.product_name` | `string` | 自动回填的商品名称 | + +> 注意:该项目的 system 方法经常返回 HTTP `200`,业务是否成功请以响应体内的 `code` 和 `message` 为准。 + +--- + +## 5. 业务校验规则 + +接口内部会执行以下校验: + +1. **当前用户必须有仓库上下文** + - 仓库 ID 取自 `ctx.user.store_id` +2. **收货单明细必须存在** +3. **收货单明细必须属于当前仓库** +4. **收货单状态必须为 `receiving`** + - 已完成、已作废等状态不允许继续绑定或改绑 +5. **目标商品必须属于当前仓库** + - 根据 `StockWarehouse.id + warehouse_id` 校验 + +--- + +## 6. 失败返回示例与错误码 + +### 常见失败场景 + +| `code` | `message` 示例 | 含义 | +|---:|---|---| +| `400` | `用户未绑定仓库` | 当前用户无仓库角色上下文 | +| `400` | `收货单明细ID不能为空` | 未传 `detail_id` / `id` | +| `400` | `商品ID不能为空` | 未传 `system_product_id` | +| `400` | `收货单状态不允许绑定或改绑商品` | 当前收货单状态不允许继续操作 | +| `404` | `收货单明细不存在` | 明细不存在或不属于当前仓库 | +| `404` | `商品不存在或不属于当前仓库` | 商品不存在或仓库不匹配 | +| `500` | `绑定商品失败: ` | 服务内部异常 | + +### 失败响应示例 + +```json +{ + "flag": "success", + "code": 404, + "message": "商品不存在或不属于当前仓库" +} +``` + +--- + +## 7. 推荐调用链路 + +典型前端操作顺序如下: + +1. `storage.receiving.create`:创建收货单 +2. `storage.receiving.addDetail`:新增空白明细,拿到 `selectId` +3. `storage.receiving.bindDetailProduct`:绑定系统商品 +4. `storage.receiving.detailChange`:补充数量、箱数、备注等字段 +5. `storage.receiving.completeReceiving`:完成收货 + +其中第 2 步新增明细后,一般会返回: + +```json +{ + "data": { + "selectId": 12345 + } +} +``` + +该 `selectId` 即可直接作为 `bindDetailProduct` 的 `detail_id`。 + +--- + +## 8. 回归验证参考 + +仓库中已有接口级回归用例,可作为联调参考: + +- `test/app/controller/system.storage.receiving.test.js` + +已覆盖的场景包括: + +- 新建收货单后绑定商品 +- 已绑定商品后再次改绑 +- 绑定成功后返回 `detail_id`、`system_product_id`、`product_name` + +--- + +## 9. 实现位置(源码定位) + +### system 方法包装层 + +- 文件:`app/service/systemMethods/storage/receiving.js` +- 方法:`bindDetailProduct(data)` + +### 实际业务实现 + +- 文件:`app/service/systems/storage/receiving.js` +- 方法:`bindDetailProduct(data)` + +--- + +## 10. 当前接口结论 + +`storage.receiving.bindDetailProduct` 当前已支持: + +- **绑定** 收货明细商品 +- **改绑** 收货明细商品 +- 自动回填商品名称、条码、重量、箱规等信息 +- 自动刷新收货单统计数据 + +适合作为收货单明细与系统商品标准匹配接口对外说明使用。 diff --git a/methods/changes/gateway.json b/methods/changes/gateway.json new file mode 100644 index 0000000..aa2f457 --- /dev/null +++ b/methods/changes/gateway.json @@ -0,0 +1,14 @@ +[ + { + "version": "2026.04.07-gateway-01", + "date": "2026-04-07", + "summary": "初始化 gateway 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/gateway.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + } +] diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json new file mode 100644 index 0000000..c127246 --- /dev/null +++ b/methods/changes/qimen.json @@ -0,0 +1,14 @@ +[ + { + "version": "2026.04.07-qimen-01", + "date": "2026-04-07", + "summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/qimen.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + } +] diff --git a/methods/changes/system.json b/methods/changes/system.json new file mode 100644 index 0000000..a00923b --- /dev/null +++ b/methods/changes/system.json @@ -0,0 +1,283 @@ +[ + { + "version": "2026.04.07-system-01", + "date": "2026-04-07", + "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要登录并走权限校验。", + "methods": [ + "warehouse.getAreaRacks" + ], + "notes": [ + "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", + "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" + ] + }, + { + "version": "2026.04.07-system-02", + "date": "2026-04-07", + "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", + "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并明确 id、change_quantity、reason 等关键入参。" + ] + }, + { + "version": "2026.04.07-system-03", + "date": "2026-04-07", + "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", + "methods": [ + "storeWarehouse.store.listApiConfig", + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.deleteQimenConfig" + ], + "notes": [ + "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", + "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", + "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" + ] + }, + { + "version": "2026.04.07-system-04", + "date": "2026-04-07", + "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", + "methods": [ + "/api/docs", + "/api/docs/:docName", + "/api/docs/:docName/raw", + "/api/docs/:docName/changes" + ], + "notes": [ + "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", + "原文 JSON 入口继续用于直接查看当前生效文档。" + ] + }, + { + "version": "2026.04.07-system-05", + "date": "2026-04-07", + "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", + "methods": [ + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", + "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" + ] + }, + { + "id": "2026.04.07-system-06", + "date": "2026-04-07", + "method": "storeWarehouse.store.saveApiConfig", + "type": "changed", + "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", + "detail": "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" + }, + { + "id": "2026.04.07-system-07", + "date": "2026-04-07", + "method": "index.listInterfaceTypes", + "type": "added", + "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", + "detail": "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" + }, + { + "id": "2026.04.07-system-08", + "date": "2026-04-07", + "method": "storeWarehouse.store.saveApiConfig", + "type": "changed", + "summary": "app_name 改为必传参数", + "detail": "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返回 400 错误。" + }, + { + "id": "2026.04.07-system-09", + "date": "2026-04-07", + "method": "storage.inventory.quickPutaway", + "type": "added", + "summary": "新增收货单快捷入库上架接口", + "detail": "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单(SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" + }, + { + "id": "2026.04.08-system-01", + "date": "2026-04-08", + "method": "storage.inventory.matchPutaway", + "type": "added", + "summary": "新增收货单与入库单匹配入库接口", + "detail": "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" + }, + { + "id": "2026.04.08-system-02", + "date": "2026-04-08", + "method": "storeWarehouse.store.saveApiConfig", + "type": "changed", + "summary": "saveApiConfig 新增 callback_url 可选参数", + "detail": "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的回调地址配置。" + }, + { + "id": "2026.04.08-system-03", + "date": "2026-04-08", + "method": "storeWarehouse.store.list, storeWarehouse.store.listApiConfig", + "type": "changed", + "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", + "detail": "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" + }, + { + "id": "2026.04.08-system-04", + "date": "2026-04-08", + "method": "storage.inventory.transferLocation", + "type": "added", + "summary": "新增库存移库(库位转移)接口", + "detail": "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库,包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件,每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" + }, + { + "id": "2026.04.08-system-05", + "date": "2026-04-08", + "method": "storage.inventory.transferLocation", + "type": "modified", + "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", + "detail": "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" + }, + { + "id": "2026.04.08-system-06", + "date": "2026-04-08", + "method": "stock.warehouse.getStockDetail", + "type": "added", + "summary": "新增商品库存明细查询接口", + "detail": "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" + }, + { + "id": "2026.04.08-system-07", + "date": "2026-04-08", + "method": "stock.warehouse.getStockDetail", + "type": "modified", + "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", + "detail": "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" + }, + { + "id": "2026.04.08-system-08", + "date": "2026-04-08", + "method": "storage.inventory.transferByProduct", + "type": "added", + "summary": "新增按商品维度移库接口", + "detail": "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" + }, + { + "id": "2026.04.08-system-09", + "date": "2026-04-08", + "method": "storeWarehouse.store.list", + "type": "updated", + "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", + "detail": "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" + }, + { + "id": "2026.04.08-system-10", + "date": "2026-04-08", + "method": "storeWarehouse.store.list", + "type": "changed", + "summary": "货主列表返回新增 has_qimen_config 布尔字段", + "detail": "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" + }, + { + "id": "2026.04.08-system-11", + "date": "2026-04-08", + "method": "stock.warehouse.search", + "type": "updated", + "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", + "detail": "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜索失败场景。" + }, + { + "id": "2026.04.08-system-12", + "date": "2026-04-08", + "method": "stock.warehouse.search", + "type": "updated", + "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分组或按批次逐条)", + "detail": "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" + }, + { + "id": "2026.04.08-system-13", + "date": "2026-04-08", + "method": "wms_stock_transaction", + "type": "added", + "summary": "新增 wms_stock_transaction 表和模型", + "detail": "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" + }, + { + "id": "2026.04.08-system-14", + "date": "2026-04-08", + "method": "storage.inventory.quickPutaway,storage.inventory.matchPutaway", + "type": "updated", + "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", + "detail": "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" + }, + { + "id": "2026.04.08-system-15", + "date": "2026-04-08", + "method": "storage.inventory.list", + "type": "added", + "summary": "新增 storage.inventory.list 出入库记录列表查询接口", + "detail": "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" + }, + { + "id": "2026.04.08-system-16", + "date": "2026-04-08", + "module": "storage", + "method": "storage.transaction.list", + "type": "rename", + "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", + "detail": "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + }, + { + "id": "2026.04.08-system-17", + "date": "2026-04-08", + "module": "storage", + "method": "storage.inventory.list", + "type": "add", + "summary": "新增 storage.inventory.list 库存列表查询接口", + "detail": "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + }, + { + "id": "2026.04.08-system-18", + "date": "2026-04-08", + "module": "storage", + "method": "storage.entry.create", + "type": "remove", + "summary": "移除 storage.entry.create 创建入库单接口", + "detail": "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 暴露。" + }, + { + "id": "2026.04.08-system-19", + "date": "2026-04-08", + "module": "storage", + "method": "storage.entry.addDetail, storage.entry.deleteDetail, storage.entry.detailChange", + "type": "remove", + "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外接口", + "detail": "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" + }, + { + "id": "2026.04.08-system-20", + "date": "2026-04-08", + "module": "storage", + "method": "storage.stockout.list, storage.stockout.toOrder, storage.stockout.listItems", + "type": "add", + "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", + "detail": "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层部分能力仍复用 order 模块。" + }, + { + "id": "2026.04.08-system-21", + "date": "2026-04-08", + "method": "storage.stockout.toOrder", + "type": "change", + "summary": "将 storage.stockout.toOrder 标记为占位接口", + "detail": "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" + }, + { + "id": "2026.04.08-system-22", + "date": "2026-04-08", + "module": "storage", + "method": "storage.delivery.*", + "type": "remove", + "summary": "移除 storage.delivery.* 兼容入口", + "detail": "storage.delivery.* 兼容转发已从系统移除,调用方请迁移至 storage.stockout.* 作为主出口。" + } +] diff --git a/methods/qimen.json b/methods/qimen.json index 334a7a5..0f560ac 100644 --- a/methods/qimen.json +++ b/methods/qimen.json @@ -922,7 +922,7 @@ "list": [ { "method": "stockout.create", - "description": "stockout.create 接口", + "description": "stockout.create 接口(创建非订单出库单;对应 system 出口 storage.stockout.*)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], diff --git a/methods/system.json b/methods/system.json index d7c9e13..c339b7e 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.0", - "updatedAt": "2026-03-23", + "version": "0.3.3", + "updatedAt": "2026-04-08", "headers": [ { "name": "platform", @@ -40,7 +40,7 @@ "type": "string", "required": true, "name": "project", - "description": "项目标识,如 all/warehouse/store/tms", + "description": "项目标识,如 all/warehouse/store/tms/wms/scm/other", "list": [ { "value": "all", @@ -57,6 +57,18 @@ { "value": "tms", "name": "物流" + }, + { + "value": "wms", + "name": "WMS" + }, + { + "value": "scm", + "name": "SCM" + }, + { + "value": "other", + "name": "其他" } ] } @@ -424,6 +436,13 @@ "response": [], "errors": [] }, + { + "method": "index.listInterfaceTypes", + "description": "查询可用的接口类型列表(如奇门仓储、开放接口等)", + "isNeedAuth": false, + "isNeedLogin": true, + "params": [] + }, { "method": "index.getExpressList", "description": "index.getExpressList 接口", @@ -464,6 +483,23 @@ "response": [], "errors": [] }, + { + "method": "order.base.getOrderModels", + "description": "订单模型能力兼容入口(当前与 order.getOrderModels 返回一致)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, { "method": "order.list", "description": "分页查询订单列表", @@ -2016,6 +2052,384 @@ "description": "更新失败" } ] + }, + { + "method": "setting.account.getBindWechatCode", + "description": "为指定工号账号获取微信绑定码", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标账号ID,兼容 user_id / id" + }, + { + "name": "longPoll", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否开启长轮询等待状态变化,最长60秒" + }, + { + "name": "waitTimeoutMs", + "type": "number", + "required": false, + "source": "body", + "description": "等待超时毫秒数,后端自动封顶60000" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.account.unbindWechat", + "description": "为指定工号账号解绑微信", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标账号ID,兼容 user_id / id" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "权限管理模块", + "module": "setting.permission", + "list": [ + { + "method": "setting.permission.list", + "description": "查询权限树/权限列表,可附带指定角色的选中状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "角色ID;传入后返回 selected 标记" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "权限类型筛选:web_pages/pda_pages/btns/api/miniprogram_pages/block" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字模糊搜索 path/name/meta_title" + }, + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已停用权限" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.add", + "description": "新增权限节点", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "path", + "type": "string", + "required": true, + "source": "body", + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "source": "body", + "description": "权限类型" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "权限名称" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "父级权限ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.update", + "description": "更新权限节点信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "source": "body", + "description": "权限ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.permission.delete", + "description": "批量停用权限节点", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "待停用的权限ID数组" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "角色管理模块", + "module": "setting.role", + "list": [ + { + "method": "setting.role.list", + "description": "获取当前主体可管理的角色树", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "includeDisabled", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含已停用角色" + }, + { + "name": "includeSystem", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否包含系统角色域" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.permission", + "description": "获取角色权限树(兼容旧入口,等同于 setting.permission.list)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": false, + "source": "body", + "description": "角色ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.add", + "description": "新增角色并绑定权限集合", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_code", + "type": "string", + "required": true, + "source": "body", + "description": "角色编码" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "source": "body", + "description": "角色名称" + }, + { + "name": "permission_ids", + "type": "array", + "required": true, + "source": "body", + "description": "权限ID数组,支持 [\"*\"]" + }, + { + "name": "pid", + "type": "number", + "required": false, + "source": "body", + "description": "父角色ID" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.update", + "description": "更新角色信息并重设权限集合", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "role_id", + "type": "number", + "required": true, + "source": "body", + "description": "角色ID" + }, + { + "name": "permission_ids", + "type": "array", + "required": true, + "source": "body", + "description": "权限ID数组,角色权限需一次性提交" + } + ], + "response": [], + "errors": [] + }, + { + "method": "setting.role.delete", + "description": "批量停用角色", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "待停用的角色ID数组" + } + ], + "response": [], + "errors": [] } ] }, @@ -2426,7 +2840,7 @@ }, { "method": "stock.warehouse.search", - "description": "仓库商品关键字搜索", + "description": "仓库商品关键字搜索,按 item_code / item_name / goods_code / 条形码模糊匹配,最多返回 50 条", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -2437,7 +2851,342 @@ "description": "Bearer token" } ], - "params": [], + "params": [ + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "搜索关键字,模糊匹配 item_code、item_name、goods_code 以及关联的 barcode;为空时返回全部(仍受 limit 50 限制)" + }, + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID,传入时仅返回指定货主的商品" + }, + { + "name": "with_stock", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否返回关联库存数据(wms_storage),为 true 时每条商品新增 storage[] 字段" + }, + { + "name": "is_batch", + "type": "boolean", + "required": false, + "source": "body", + "default": false, + "description": "是否按批次明细返回库存,仅 with_stock=true 时生效。false(默认)按库位分组汇总;true 逐条返回批次明细" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "description": "业务状态码,200 表示成功" + }, + { + "name": "data", + "type": "array", + "description": "商品列表,每项包含以下字段", + "children": [ + { + "name": "id", + "type": "number", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "goods_code", + "type": "string", + "description": "货物编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "sku_property", + "type": "string", + "description": "SKU 规格" + }, + { + "name": "stock_unit", + "type": "string", + "description": "库存单位" + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量" + }, + { + "name": "locked_quantity", + "type": "number", + "description": "锁定数量" + }, + { + "name": "brand_name", + "type": "string", + "description": "品牌名称" + }, + { + "name": "item_type", + "type": "string", + "description": "商品类型" + }, + { + "name": "barcodes", + "type": "array", + "description": "商品条形码列表(string[])" + }, + { + "name": "store_stock", + "type": "object", + "description": "关联的货主签约信息(LEFT JOIN),含 store_id、store_remask;无签约时为 null" + }, + { + "name": "storage", + "type": "array", + "description": "关联库存明细,仅 with_stock=true 时返回。is_batch=false 时按库位分组汇总,is_batch=true 时逐条返回批次明细", + "children_grouped": { + "description": "is_batch=false(默认):按库位分组汇总,每条包含以下字段", + "fields": [ + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "inventory_type", + "type": "string", + "description": "库存类型" + }, + { + "name": "quantity", + "type": "number", + "description": "该库位总库存数量(合并同库位)" + }, + { + "name": "locked_quantity", + "type": "number", + "description": "该库位总锁定数量" + }, + { + "name": "available_quantity", + "type": "number", + "description": "可用数量(quantity - locked_quantity)" + }, + { + "name": "space", + "type": "object", + "description": "库位信息子对象,含 id、space_code、custom_name" + } + ] + }, + "children_batch": { + "description": "is_batch=true:逐条批次明细,每条包含以下字段", + "fields": [ + { + "name": "id", + "type": "number", + "description": "storage 记录ID" + }, + { + "name": "stock_id", + "type": "number", + "description": "关联的商品库存ID" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + }, + { + "name": "inventory_type", + "type": "string", + "description": "库存类型" + }, + { + "name": "quantity", + "type": "number", + "description": "库存数量" + }, + { + "name": "locked_quantity", + "type": "number", + "description": "锁定数量" + }, + { + "name": "available_quantity", + "type": "number", + "description": "可用数量" + }, + { + "name": "production_date", + "type": "string", + "description": "生产日期" + }, + { + "name": "expiry_date", + "type": "string", + "description": "过期日期" + }, + { + "name": "inbound_time", + "type": "string", + "description": "入库时间" + }, + { + "name": "inbound_order_no", + "type": "string", + "description": "入库单号" + }, + { + "name": "supplier_batch_no", + "type": "string", + "description": "供应商批次号" + }, + { + "name": "created_at", + "type": "string", + "description": "记录创建时间" + }, + { + "name": "space", + "type": "object", + "description": "库位信息子对象,含 id、space_code、custom_name" + } + ] + } + } + ] + }, + { + "name": "total", + "type": "number", + "description": "本次返回的记录条数(≤50)" + } + ], + "errors": [ + { + "code": 0, + "message": "搜索失败,请稍后重试", + "description": "服务端查询异常时返回" + } + ] + }, + { + "method": "stock.warehouse.getStockDetail", + "description": "查询商品的库存明细,返回 wms_storage 表的数据(按库位/批次维度展示库存分布)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品库存ID(stock_warehouse.id)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,含 page(页码,默认1)和 pageSize(每页条数,默认20)" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否区分批次。false(默认)时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时按原逻辑返回每条明细" + } + ], + "response": [ + { + "name": "stockItem", + "type": "object", + "description": "商品概要信息,含 id, item_code, item_name, sku_property, stock_unit, quantity, locked_quantity" + }, + { + "name": "storageList", + "type": "array", + "description": "库存明细数组,每条含 id, space_id, batch_no, inventory_type, quantity, locked_quantity, available_quantity, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no, created_at,关联 space 对象(id, space_code, custom_name)。当 group_by_batch=false 时,批次相关字段为 null" + }, + { + "name": "pagination", + "type": "object", + "description": "分页信息,含 page, pageSize, total" + } + ], + "errors": [ + { + "code": 0, + "message": "参数 stock_id 不能为空" + }, + { + "code": 0, + "message": "商品不存在或不属于当前仓库" + }, + { + "code": 0, + "message": "查询库存明细失败,请稍后重试" + } + ] + }, + { + "method": "stock.stockWarehouse", + "description": "仓库商品列表查询兼容入口(等同于 stock.warehouse.list)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "筛选条件,写法与 stock.warehouse.list 一致" + } + ], "response": [], "errors": [] } @@ -2684,6 +3433,146 @@ } ] }, + { + "method": "storage.receiving.bindStore", + "description": "收货单绑定货主", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "货主ID(必须与当前仓库存在有效签约关系)" + } + ], + "response": [ + { + "name": "data.id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "data.store_id", + "type": "number", + "required": true, + "description": "已绑定的货主ID" + }, + { + "name": "data.store_name", + "type": "string", + "required": false, + "description": "货主名称/签约备注名" + }, + { + "name": "data.status", + "type": "string", + "required": true, + "description": "当前收货单状态" + } + ], + "errors": [ + { + "code": "400", + "description": "用户未绑定仓库、收货单ID/货主ID为空、已取消或已绑定货主" + }, + { + "code": "404", + "description": "收货单不存在/无权访问,或货主与当前仓库未建立有效签约关系" + }, + { + "code": "500", + "description": "绑定货主失败" + } + ] + }, + { + "method": "storage.receiving.bindDetailProduct", + "description": "收货单明细绑定或改绑系统商品", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单明细ID(兼容字段 `id`)" + }, + { + "name": "system_product_id", + "type": "number", + "required": true, + "source": "body", + "description": "系统商品ID(`StockWarehouse.id`,且必须属于当前仓库)" + } + ], + "response": [ + { + "name": "data.detail_id", + "type": "number", + "required": true, + "description": "收货单明细ID" + }, + { + "name": "data.receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "data.system_product_id", + "type": "number", + "required": true, + "description": "已绑定的系统商品ID" + }, + { + "name": "data.product_name", + "type": "string", + "required": true, + "description": "自动回填的商品名称" + } + ], + "errors": [ + { + "code": "400", + "description": "用户未绑定仓库、明细ID/商品ID为空,或收货单状态不允许绑定/改绑" + }, + { + "code": "404", + "description": "收货单明细不存在,或商品不存在/不属于当前仓库" + }, + { + "code": "500", + "description": "绑定商品失败" + } + ] + }, { "method": "storage.receiving.addItem", "description": "storage.receiving.addItem 接口", @@ -2866,7 +3755,13 @@ "params": [], "response": [], "errors": [] - }, + } + ] + }, + { + "groupName": "入库单模块", + "module": "storage.entry", + "list": [ { "method": "storage.entry.list", "description": "入库单列表查询", @@ -2982,231 +3877,6 @@ } ] }, - { - "method": "storage.entry.create", - "description": "创建入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务类型:SCRK/LYRK/CCRK/CGRK/DBRK/QTRK/B2BRK/XNRK" - }, - { - "name": "store_id", - "type": "number", - "required": false, - "source": "body", - "description": "货主ID,不传默认使用当前用户 store_id" - }, - { - "name": "entry_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "入库单号,不传时系统自动生成" - }, - { - "name": "purchase_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "采购单号" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "备注" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建入库单ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - } - ], - "errors": [ - { - "code": "400", - "description": "参数缺失或业务类型不合法" - }, - { - "code": "409", - "description": "入库单号已存在" - } - ] - }, - { - "method": "storage.entry.addDetail", - "description": "新增入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - }, - { - "name": "count", - "type": "number", - "required": true, - "source": "body", - "description": "计划入库数量,必须大于0" - }, - { - "name": "item_code", - "type": "string", - "required": false, - "source": "body", - "description": "商品编码" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建明细ID" - }, - { - "name": "order_id", - "type": "number", - "required": true, - "description": "所属入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或状态不允许新增明细" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.entry.deleteDetail", - "description": "删除入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "删除成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或明细已有收货数量" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, - { - "method": "storage.entry.detailChange", - "description": "修改入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - }, - { - "name": "count", - "type": "number", - "required": false, - "source": "body", - "description": "计划入库数量,必须大于0且不能小于已收货数量" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "修改成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或没有可更新字段" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, { "method": "storage.entry.cancel", "description": "作废入库单", @@ -3291,6 +3961,560 @@ } ] }, + { + "groupName": "出库单模块", + "module": "storage.stockout", + "list": [ + { + "method": "storage.stockout.list", + "name": "出库单列表", + "description": "非订单出库单能力(对应奇门 stockout.create):用于处理由奇门创建的非订单出库单;主出口为 storage.stockout.*,不再推荐通过 storage.delivery.* 命名使用。storage.delivery.* 仅保留兼容转发。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder,默认按 updated_at DESC、id DESC" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "出库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": "400", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.stockout.toOrder", + "name": "出库单转订单(占位)", + "description": "占位接口,暂未开放。当前仅保留方法名用于后续扩展,逻辑暂不能使用。参数 id / delivery_order_code 暂未启用。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "预留参数,暂未启用;当前仅保留字段名用于后续扩展。" + }, + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "预留参数,暂未启用;当前仅保留字段名用于后续扩展。" + } + ], + "response": [ + { + "name": "_note", + "type": "string", + "required": false, + "description": "占位接口,当前无有效业务响应" + } + ], + "errors": [ + { + "code": "405", + "description": "占位接口,暂未开放" + } + ] + }, + { + "method": "storage.stockout.listItems", + "name": "出库单拉取明细", + "description": "按出库单查询商品明细(用于非订单出库单),底层复用 order.listItems。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "delivery_order_code", + "type": "string", + "required": false, + "source": "body", + "description": "出库单号,可用于定位订单" + }, + { + "name": "order_id", + "type": "number", + "required": false, + "source": "body", + "description": "订单ID,可与 id 兼容用于定位订单" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "订单ID,可选;与 delivery_order_code / order_id 至少传一个" + } + ], + "response": [ + { + "name": "order", + "type": "object", + "required": true, + "description": "订单基础信息(含 id、delivery_order_code)" + }, + { + "name": "items", + "type": "array", + "required": true, + "description": "出库单商品明细" + } + ], + "errors": [ + { + "code": "404", + "description": "订单不存在" + }, + { + "code": "500", + "description": "缺少定位参数或查询失败" + } + ] + } + ] + }, + { + "groupName": "库存操作模块", + "module": "storage.inventory", + "list": [ + { + "method": "storage.inventory.quickPutaway", + "description": "收货单快捷入库上架。从收货单直接生成入库单并写入库存表,要求收货单已完成且所有明细已匹配系统商品", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID,兼容 id" + } + ], + "response": { + "receiving_id": "收货单ID", + "receiving_number": "收货单号", + "receiving_storage_status": "收货单入库状态(all/partial)", + "entry_order": { + "id": "自动创建的入库单ID", + "entry_order_code": "入库单号", + "order_status": "COMPLETED" + }, + "items": [ + { + "detail_id": "收货明细ID", + "product_name": "商品名称", + "stock_warehouse_id": "库存商品ID", + "inbound_quantity": "入库数量", + "space_id": "库位ID", + "storage_status": "明细入库状态" + } + ] + }, + "errors": [ + { "code": 400, "message": "receiving_id 必填" }, + { "code": 400, "message": "收货单状态须为已完成" }, + { "code": 400, "message": "商品未匹配系统商品" }, + { "code": 400, "message": "已全部入库无需重复操作" }, + { "code": 404, "message": "收货单不存在或无权访问" }, + { "code": 409, "message": "库存记录被锁定(行锁超时)" } + ] + }, + { + "method": "storage.inventory.matchPutaway", + "description": "收货单与入库单匹配入库。接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完成后根据入库单来源(QM/API)自动触发回传", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "receiving_ids", + "type": "array", + "required": true, + "source": "body", + "description": "收货单ID列表" + }, + { + "name": "entry_order_ids", + "type": "array", + "required": true, + "source": "body", + "description": "入库单ID列表" + } + ], + "response": { + "summary": { + "total_products_matched": "匹配的商品种类数", + "total_quantity_inbound": "入库总数量" + }, + "receiving_results": [ + { + "receiving_id": "收货单ID", + "storage_status": "入库状态(all/partial/none)" + } + ], + "entry_order_results": [ + { + "entry_order_id": "入库单ID", + "order_status": "入库单状态(COMPLETED 等)", + "callback_triggered": "是否触发回传(boolean)", + "callback_result": "回传结果对象" + } + ], + "warnings": "匹配过程中的警告信息列表" + }, + "errors": [ + { "code": 400, "message": "receiving_ids 必填且为数组" }, + { "code": 400, "message": "entry_order_ids 必填且为数组" }, + { "code": 404, "message": "收货单不存在或无权访问" }, + { "code": 404, "message": "入库单不存在或无权访问" } + ] + }, + { + "method": "storage.inventory.transferLocation", + "description": "单商品单库位移库,将库存从一个库位移动到另一个库位,支持部分数量移库和全量移库", + "name": "库存移库(库位转移)", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "storage_id", + "type": "number", + "required": true, + "source": "body", + "description": "库存记录ID" + }, + { + "name": "target_space_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标库位ID" + }, + { + "name": "quantity", + "type": "number", + "required": false, + "source": "body", + "description": "移库数量,不传则全部移动" + } + ], + "response": { + "storage_id": "原库存记录ID", + "target_space_id": "目标库位ID", + "quantity": "实际移库数量", + "success": "是否成功(boolean)", + "message": "结果说明" + }, + "errors": [ + { "code": 400, "message": "storage_id 必填" }, + { "code": 400, "message": "target_space_id 必填" }, + { "code": 400, "message": "移库数量必须大于0且不超过可用库存" }, + { "code": 400, "message": "目标库位与原库位相同" }, + { "code": 404, "message": "库存记录不存在或无权访问" }, + { "code": 404, "message": "目标库位不存在或不属于该仓库" } + ] + }, + { + "method": "storage.inventory.transferByProduct", + "description": "按库位+商品维度移库,自动查找原库位下该商品的所有库存记录并合并移动。不适用于开启批次管理的商品", + "name": "按商品移库(库位转移)", + "isNeedAuth": true, + "isNeedLogin": true, + "params": [ + { + "name": "space_id", + "type": "number", + "required": true, + "source": "body", + "description": "原库位ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品SKU ID(wms_stock_warehouse.id)" + }, + { + "name": "target_space_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标库位ID" + }, + { + "name": "quantity", + "type": "number", + "required": true, + "source": "body", + "description": "移库数量" + } + ] + }, + { + "method": "storage.inventory.list", + "description": "库存列表查询(查 wms_storage),支持 where 条件、分页、排序、批次分组。默认按库位+商品合并数量(合并模式),group_by_batch=true 时返回每条库存明细(明细模式)", + "name": "库存列表", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,可用字段:stock_id(商品ID)、space_id(库位ID)、store_id(货主ID)、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、batch_no(批次号)、inbound_order_no(入库单号)、available_quantity(可用数量,支持 gt/lt)、inbound_time(入库时间,支持 between)、created_at(创建时间,支持 between)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数 { sortField, sortOrder },默认 sortField='created_at', sortOrder='DESC'" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按批次查询,默认 false。false=合并模式(按库位+商品聚合quantity/locked_quantity/available_quantity),true=明细模式(逐条返回含 batch_no/production_date/expiry_date 等)" + } + ], + "response": { + "_note": "响应结构因 group_by_batch 而异", + "list_merged": { + "_description": "group_by_batch=false(默认合并模式)", + "list": [ + { + "stock_id": "商品库存ID", + "space_id": "库位ID", + "inventory_type": "库存类型", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "quantity": "总库存数量(SUM)", + "locked_quantity": "总锁定数量(SUM)", + "available_quantity": "总可用数量(SUM)", + "first_inbound_time": "最早入库时间", + "last_inbound_time": "最晚入库时间", + "batch_count": "批次数", + "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, + "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + } + ], + "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + }, + "list_detail": { + "_description": "group_by_batch=true(明细模式)", + "list": [ + { + "id": "库存记录ID", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "space_id": "库位ID", + "stock_id": "商品库存ID", + "batch_no": "批次号", + "inventory_type": "库存类型", + "quantity": "库存数量", + "locked_quantity": "锁定数量", + "available_quantity": "可用数量", + "production_date": "生产日期", + "expiry_date": "过期日期", + "inbound_time": "入库时间", + "inbound_order_no": "入库单号", + "receiving_id": "收货单ID", + "entry_order_id": "入库单ID", + "supplier_batch_no": "供应商批次号", + "created_at": "创建时间", + "updated_at": "更新时间", + "stock": { "id": "商品ID", "item_code": "商品编码", "item_name": "商品名称", "sku_property": "规格", "stock_unit": "单位" }, + "space": { "id": "库位ID", "space_code": "库位编码", "custom_name": "库位名称" } + } + ], + "pagination": { "page": 1, "pageSize": 20, "total": 100, "totalPages": 5 } + } + } + }, + { + "method": "storage.transaction.list", + "description": "出入库记录列表查询,支持 where 条件、分页、排序、批次分组切换。默认按库位合并数量(合并模式),group_by_batch=true 时返回每条明细(明细模式)", + "name": "出入库流水记录列表", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象,可用字段:transaction_type(ENUM INBOUND/OUTBOUND)、stock_id、space_id、store_id、order_type(SCRK/MATCH)、order_no、inventory_type(ZP/CC/JS/XS/ZT/DJ/FP)、operator_name、created_at(支持 between)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数 { page, pageSize },默认 page=1, pageSize=20" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数 { sortField, sortOrder },默认 sortField='created_at', sortOrder='DESC'" + }, + { + "name": "group_by_batch", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按批次查询明细,默认 false。false=合并模式(按库位+商品聚合),true=明细模式(逐条返回)" + } + ], + "response": { + "_note": "响应结构因 group_by_batch 而异", + "list_merged": { + "_description": "group_by_batch=false(默认合并模式)", + "list": [ + { + "stock_id": "商品库存ID", + "space_id": "库位ID", + "transaction_type": "INBOUND/OUTBOUND", + "inventory_type": "库存类型", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "order_type": "关联单据类型", + "quantity": "合计数量", + "first_created_at": "最早记录时间", + "last_created_at": "最晚记录时间", + "record_count": "合并记录条数", + "stockItem": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位" + } + } + ], + "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + }, + "list_detail": { + "_description": "group_by_batch=true(明细模式)", + "list": [ + { + "id": "记录ID", + "transaction_type": "INBOUND/OUTBOUND", + "warehouse_id": "仓库ID", + "store_id": "货主ID", + "stock_id": "商品库存ID", + "storage_id": "库存记录ID", + "space_id": "库位ID", + "quantity": "数量", + "batch_no": "批次号", + "inventory_type": "库存类型", + "order_type": "关联单据类型", + "order_no": "关联单据号", + "order_id": "关联单据ID", + "receiving_id": "收货单ID", + "entry_order_id": "入库单ID", + "operator_id": "操作人ID", + "operator_name": "操作人姓名", + "remark": "备注", + "created_at": "创建时间", + "stockItem": { + "id": "商品ID", + "item_code": "商品编码", + "item_name": "商品名称", + "sku_property": "规格", + "stock_unit": "单位" + } + } + ], + "pagination": { "page": "当前页", "pageSize": "每页条数", "total": "总记录数", "totalPages": "总页数" } + } + }, + "errors": [ + { "code": 400, "message": "where 条件格式不正确" }, + { "code": 400, "message": "分页参数不合法" } + ] + } + ] + }, { "groupName": "主体模块", "module": "store", @@ -3443,6 +4667,603 @@ } ] }, + { + "groupName": "货主-仓库签约模块", + "module": "storeWarehouse.store", + "list": [ + { + "method": "storeWarehouse.store.list", + "description": "查询当前主体可见的仓库-货主签约列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "page_size", + "type": "number", + "required": false, + "source": "body", + "description": "分页大小,默认 20" + }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "签约备注或主体名称关键字" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "description": "签约关系列表" + }, + { + "name": "data.list[].id", + "type": "number", + "description": "签约关系主键 ID" + }, + { + "name": "data.list[].store_id", + "type": "number", + "description": "货主 ID" + }, + { + "name": "data.list[].store_name", + "type": "string", + "description": "货主名称(优先取备注名,无则取 company_name)" + }, + { + "name": "data.list[].warehouse_id", + "type": "number", + "description": "仓库 ID" + }, + { + "name": "data.list[].warehouse_name", + "type": "string", + "description": "仓库名称(优先取备注名,无则取 company_name)" + }, + { + "name": "data.list[].counterparty_id", + "type": "number", + "description": "对方主体 ID(当前为仓库则返回货主 ID,反之亦然)" + }, + { + "name": "data.list[].counterparty_name", + "type": "string", + "description": "对方主体名称" + }, + { + "name": "data.list[].current_subject_role", + "type": "string", + "description": "当前主体角色:warehouse 或 store" + }, + { + "name": "data.list[].auth_status", + "type": "number", + "description": "签约状态:1=申请中 2=已通过 3=已拒绝 4=已解除 5=已过期" + }, + { + "name": "data.list[].auth_status_label", + "type": "string", + "description": "签约状态中文标签" + }, + { + "name": "data.list[].apply_reason", + "type": "string", + "description": "申请原因" + }, + { + "name": "data.list[].review_comment", + "type": "string", + "description": "审核评语" + }, + { + "name": "data.list[].apply_time", + "type": "string|null", + "description": "申请时间" + }, + { + "name": "data.list[].review_time", + "type": "string|null", + "description": "审核时间" + }, + { + "name": "data.list[].auth_start", + "type": "string|null", + "description": "授权开始时间" + }, + { + "name": "data.list[].auth_end", + "type": "string|null", + "description": "授权结束时间" + }, + { + "name": "data.list[].actual_end", + "type": "string|null", + "description": "实际结束时间" + }, + { + "name": "data.list[].print_quantity", + "type": "number", + "description": "面单余额数量" + }, + { + "name": "data.list[].applied_by", + "type": "number|null", + "description": "申请人账号 ID" + }, + { + "name": "data.list[].reviewed_by", + "type": "number|null", + "description": "审核人账号 ID" + }, + { + "name": "data.list[].ended_by", + "type": "number|null", + "description": "解除人账号 ID" + }, + { + "name": "data.list[].remask", + "type": "string", + "description": "备注名(当前为仓库则返回货主备注名,反之亦然)" + }, + { + "name": "data.list[].use_status", + "type": "number", + "description": "启用状态:0=禁用 1=启用" + }, + { + "name": "data.list[].policy_config", + "type": "object|null", + "description": "签约策略配置对象,无则为 null" + }, + { + "name": "data.list[].is_auth_valid", + "type": "boolean", + "description": "签约是否在有效期内" + }, + { + "name": "data.list[].remaining_days", + "type": "number", + "description": "剩余有效天数(未在有效期内时为 0)" + }, + { + "name": "data.list[].has_qimen_config", + "type": "boolean", + "description": "该货主是否已配置奇门(true=已配置,false=未配置)" + }, + { + "name": "data.total", + "type": "number", + "description": "总记录数" + }, + { + "name": "data.page", + "type": "number", + "description": "当前页码" + }, + { + "name": "data.page_size", + "type": "number", + "description": "每页条数" + }, + { + "name": "data.current_subject.store_id", + "type": "number", + "description": "当前主体 ID" + }, + { + "name": "data.current_subject.company_name", + "type": "string", + "description": "当前主体公司名称" + }, + { + "name": "data.current_subject.role", + "type": "string", + "description": "当前主体角色:warehouse 或 store" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.sign", + "description": "发起或确认仓库-货主签约", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "store_id", + "type": "number", + "required": false, + "source": "body", + "description": "货主ID;由仓库侧发起时必传" + }, + { + "name": "warehouse_id", + "type": "number", + "required": false, + "source": "body", + "description": "仓库ID;由货主侧发起时必传" + }, + { + "name": "temp_code", + "type": "string", + "required": false, + "source": "body", + "description": "临时签约码;传入后进入确认或预览流程" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.rename", + "description": "修改当前主体视角下的签约备注名", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.unbind", + "description": "解除或停用签约关系", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "use_status", + "type": "number", + "required": false, + "source": "body", + "description": "使用状态,0=停用,1=恢复" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.adjustPrintQuantity", + "description": "人工调整签约关系下的面单余额并记录变更日志", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "print_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "目标面单余额(覆盖值);优先使用该字段" + }, + { + "name": "target_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "目标面单余额(覆盖值);兼容别名" + }, + { + "name": "change_quantity", + "type": "number", + "required": true, + "source": "body", + "description": "兼容旧字段;当前按目标面单余额(覆盖值)解释,差值将自动写入变更日志" + }, + { + "name": "adjust_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "兼容旧字段;当前按目标面单余额(覆盖值)解释" + }, + { + "name": "reason", + "type": "string", + "required": true, + "source": "body", + "description": "人工调整缘由,必填" + }, + { + "name": "business_type", + "type": "string", + "required": false, + "source": "body", + "description": "业务来源类型,预留给后续 order_express 等自动扣减场景" + }, + { + "name": "business_id", + "type": "number", + "required": false, + "source": "body", + "description": "业务关联ID,预留给后续关联 wms_order_express.id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.getPolicyConfig", + "description": "读取签约策略配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.getPolicyConfigFields", + "description": "获取签约策略可配置字段元信息列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.savePolicyConfig", + "description": "保存签约策略配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "policy_config", + "type": "object", + "required": true, + "source": "body", + "description": "策略配置对象;仅支持 receive_mode、sku_visibility、auto_allocate_bin、allow_mix_batch、allow_temp_storage、print_recharge_price(面单充值元/单,支持 2 位小数)、max_daily_inbound、remark" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.listApiConfig", + "description": "查询签约关系下的接口配置列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型ID,默认查询全部可用类型" + } + ], + "response": [ + { + "name": "data.list[].callback_url", + "type": "string", + "description": "API回调通知URL,来自 serializeQimenConfig 序列化" + } + ], + "errors": [] + }, + { + "method": "storeWarehouse.store.saveApiConfig", + "description": "新增或更新签约关系下的接口配置。QM_WMS 类型须填写奇门字段;OPEN_API 类型由系统自动生成 self_app_key 和 self_app_secret", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": true, + "source": "body", + "description": "接口类型ID,必须是 wms_interface_type 已存在的类型" + }, + { + "name": "qimen_app_key", + "type": "string", + "required": false, + "source": "body", + "description": "奇门 AppKey(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "qimen_customer_id", + "type": "string", + "required": false, + "source": "body", + "description": "奇门客户ID(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "qimen_warehouse_code", + "type": "string", + "required": false, + "source": "body", + "description": "奇门仓库编码(QM_WMS 类型必填,OPEN_API 类型不需要)" + }, + { + "name": "app_name", + "type": "string", + "required": true, + "source": "body", + "description": "应用名称" + }, + { + "name": "callback_url", + "type": "string", + "required": false, + "source": "body", + "description": "API 类型入库单回调地址(VARCHAR(500),仅 OPEN_API 类型使用)" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storeWarehouse.store.deleteQimenConfig", + "description": "删除签约关系下的奇门接口配置", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "签约关系ID,兼容 contract_id" + }, + { + "name": "interface_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "接口类型ID" + } + ], + "response": [], + "errors": [] + } + ] + }, { "groupName": "用户模块", "module": "user", @@ -3490,6 +5311,24 @@ "response": [], "errors": [] }, + { + "method": "user.getLoginWechatCode", + "description": "获取微信扫码登录码(无 clientCode 时分配新客户端编码;有 clientCode 时可长轮询刷新)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "clientCode", + "type": "string", + "required": false, + "source": "body", + "description": "客户端编码;首次可不传,后续轮询建议透传已有值" + } + ], + "response": [], + "errors": [] + }, { "method": "user.getBindWechatCode", "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", @@ -3774,6 +5613,13 @@ "source": "body", "description": "height 参数" }, + { + "name": "is_active", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否启用,支持 true/false 或 1/0" + }, { "name": "length", "type": "number", @@ -4255,7 +6101,7 @@ { "method": "warehouse.getAreaRacks", "description": "warehouse.getAreaRacks 接口", - "isNeedAuth": false, + "isNeedAuth": true, "isNeedLogin": true, "headers": [ { diff --git a/model_todo.txt b/model_todo.txt deleted file mode 100644 index 7c603f0..0000000 --- a/model_todo.txt +++ /dev/null @@ -1,23 +0,0 @@ -Model 重构总计划(已完成归档) -更新时间: 2026-03-25 -当前状态: 已完成 - -[事务归属] -- 本子事务已纳入 `todo.txt` 总事务看板统一管理。 - -[完成状态] -- [x] 阶段 1: 全量盘点与基线建立 -- [x] 阶段 2: Migration 补全与执行顺序设计 -- [x] 阶段 3: Model 命名规范化 -- [x] 阶段 4: 关联关系规范化 -- [x] 阶段 5: Model 内部能力清理 -- [x] 阶段 6: 验证与交接 - -[收口说明] -- [x] 本文件由执行计划切换为归档摘要,不再保留阶段性过程清单。 -- [x] 本任务相关临时文档已从 `temp/docs/` 清理。 -- [x] 本任务相关临时中间文件已从 `temp/` 清理。 -- [x] README 中对已清理临时文档的入口已移除。 - -[追溯方式] -- 需要查看过程细节时,优先使用 git 历史、`todo.txt` 总事务看板与 `versioning/` 本地版本记录。 diff --git a/script/sync-system-api-permission.cjs b/script/sync-system-api-permission.cjs index aa14fba..b79aef0 100644 --- a/script/sync-system-api-permission.cjs +++ b/script/sync-system-api-permission.cjs @@ -86,7 +86,6 @@ function loadAuthRequiredMethods(methodDocPath) { return [ ...methodSet ].sort(); } -<<<<<<< HEAD function normalizeRolePermissions(rawValue) { if (rawValue === undefined || rawValue === null) { return { allAccess: false, permissionIds: [] }; @@ -145,9 +144,6 @@ function serializeRolePermissions(rawValue) { const state = normalizeRolePermissions(rawValue); return state.allAccess ? '*' : JSON.stringify(state.permissionIds); } - -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 function buildPermissionDefaults(methodPath, templateRow) { return { path: methodPath, @@ -181,24 +177,16 @@ async function queryExistingPermissions(conn, methodPaths) { const placeholders = methodPaths.map(() => '?').join(','); const [ rows ] = await conn.query( -<<<<<<< HEAD `SELECT id, path, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, -======= - `SELECT id, path FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 methodPaths ); const result = new Map(); for (const row of rows) { -<<<<<<< HEAD result.set(row.path, { id: Number(row.id), status: Number(row.status), }); -======= - result.set(row.path, row.id); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } return result; } @@ -227,7 +215,6 @@ async function insertPermission(conn, defaults) { return result.insertId; } -<<<<<<< HEAD async function activatePermission(conn, permissionId) { const [ result ] = await conn.query( 'UPDATE wms_permission SET status = 1, update_at = NOW() WHERE id = ? AND status <> 1', @@ -256,12 +243,6 @@ async function bindRolePermission(conn, roleId, permissionId) { const [ result ] = await conn.query( 'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?', [ serializeRolePermissions(nextPermissions), roleId ] -======= -async function bindRolePermission(conn, roleId, permissionId) { - const [ result ] = await conn.query( - 'INSERT IGNORE INTO wms_role_permission (role_id, permission_id, created_at) VALUES (?, ?, NOW())', - [ roleId, permissionId ] ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 ); return result.affectedRows > 0; } @@ -295,7 +276,6 @@ async function main() { const existingMap = await queryExistingPermissions(conn, methodPaths); const missingPaths = methodPaths.filter(item => !existingMap.has(item)); -<<<<<<< HEAD const disabledPaths = methodPaths.filter(item => { const row = existingMap.get(item); return row && Number(row.status) !== 1; @@ -305,12 +285,6 @@ async function main() { const touchedPermissionIds = []; if (!args.dryRun && (missingPaths.length > 0 || disabledPaths.length > 0)) { -======= - const created = []; - const touchedPermissionIds = []; - - if (!args.dryRun && missingPaths.length > 0) { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 await conn.beginTransaction(); try { for (const methodPath of missingPaths) { @@ -319,7 +293,6 @@ async function main() { created.push({ methodPath, permissionId }); touchedPermissionIds.push(permissionId); } -<<<<<<< HEAD for (const methodPath of disabledPaths) { const permissionRow = existingMap.get(methodPath); @@ -334,8 +307,6 @@ async function main() { touchedPermissionIds.push(permissionRow.id); } -======= ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 await conn.commit(); } catch (error) { await conn.rollback(); @@ -348,13 +319,8 @@ async function main() { : await queryExistingPermissions(conn, methodPaths); for (const methodPath of methodPaths) { -<<<<<<< HEAD const permissionRow = latestMap.get(methodPath); if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id); -======= - const permissionId = latestMap.get(methodPath); - if (permissionId) touchedPermissionIds.push(permissionId); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 } const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ]; @@ -373,18 +339,12 @@ async function main() { totalAuthMethods: methodPaths.length, existingPermissionCount: existingMap.size, missingPermissionCount: missingPaths.length, -<<<<<<< HEAD disabledPermissionCount: disabledPaths.length, createdPermissionCount: created.length, reactivatedPermissionCount: reactivated.length, roleBindingCreated, sampleMissing: missingPaths.slice(0, 20), sampleDisabled: disabledPaths.slice(0, 20), -======= - createdPermissionCount: created.length, - roleBindingCreated, - sampleMissing: missingPaths.slice(0, 20), ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 }; console.log('[sync-system-api-permission] summary'); diff --git a/test/app/controller/docs.test.js b/test/app/controller/docs.test.js new file mode 100644 index 0000000..e8d4a52 --- /dev/null +++ b/test/app/controller/docs.test.js @@ -0,0 +1,60 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { app } = require('egg-mock/bootstrap'); + +function hasSemanticKey(keys, candidates) { + return candidates.some(candidate => keys.some(key => key === candidate || key.includes(candidate))); +} + +describe('test/app/controller/docs.test.js', () => { + it('GET /api/docs/system/changes should return 200 and a change-history JSON array', async () => { + const res = await app.httpRequest() + .get('/api/docs/system/changes') + .expect('Content-Type', /json/) + .expect(200); + + assert.ok(Array.isArray(res.body), 'body 应直接返回数组 JSON'); + assert.ok(res.body.length > 0, '变更记录数组至少应包含一条记录'); + + const firstItem = res.body[0]; + assert.equal(typeof firstItem, 'object'); + + const keys = Object.keys(firstItem).map(key => String(key).toLowerCase()); + assert.ok( + hasSemanticKey(keys, [ 'version', 'ver', '版本' ]), + '数组项至少应包含版本字段' + ); + assert.ok( + hasSemanticKey(keys, [ 'date', 'updatedat', 'updated_at', '日期', '时间' ]), + '数组项至少应包含日期字段' + ); + assert.ok( + hasSemanticKey(keys, [ 'summary', 'change', 'desc', 'description', '摘要', '说明' ]), + '数组项至少应包含 summary/摘要字段' + ); + }); + + it('GET /api/docs/system should render HTML entries for change history and raw JSON', async () => { + const res = await app.httpRequest() + .get('/api/docs/system') + .expect('Content-Type', /html/) + .expect(200); + + const html = res.text; + assert.match(html, /\/api\/docs\/system\/changes/, '页面中应提供 /api/docs/system/changes 入口'); + assert.match(html, /查看变更记录|变更记录|changelog/i, '页面中应出现“查看变更记录”或同等入口文案'); + assert.match(html, /\/api\/docs\/system\/raw/, '页面中应提供 /api/docs/system/raw 入口'); + assert.match(html, /查看\s*JSON|raw\s*json/i, '页面中应出现“查看 JSON”入口'); + }); + + it('GET /api/docs/invalid-name!/changes should return 400', async () => { + const res = await app.httpRequest() + .get('/api/docs/invalid-name!/changes') + .expect('Content-Type', /json/) + .expect(400); + + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /无效|invalid/i); + }); +}); diff --git a/test/app/controller/system.setting.permission.test.js b/test/app/controller/system.setting.permission.test.js index 4776ac4..7745d89 100644 --- a/test/app/controller/system.setting.permission.test.js +++ b/test/app/controller/system.setting.permission.test.js @@ -39,13 +39,11 @@ describe('test/app/controller/system.setting.permission.test.js', () => { } }); -<<<<<<< HEAD it('should expose setting.role.permission as alias of setting.permission.list', async () => { const requestData = { type: 'api', includeDisabled: false, }; - const listRes = await invokeSystemMethod('setting.permission.list', requestData, token, EXTRA_HEADERS); const aliasRes = await invokeSystemMethod('setting.role.permission', requestData, token, EXTRA_HEADERS); @@ -153,23 +151,12 @@ describe('test/app/controller/system.setting.permission.test.js', () => { const updateRes = await invokeSystemMethod('setting.permission.update', { permission_id: 999999999, name: 'not_found_update', -======= - it('should reject out-of-scope permission update', async () => { - const updateRes = await invokeSystemMethod('setting.permission.update', { - permission_id: 999999999, - name: 'out_of_scope_update', ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 }, token, EXTRA_HEADERS); assert.equal(updateRes.status, 200); assert.equal(updateRes.body.flag, 'failure'); -<<<<<<< HEAD assert.equal(Number(updateRes.body.code), 404); assert.match(String(updateRes.body.message || ''), /权限不存在/); -======= - assert.ok([ 400, 404 ].includes(Number(updateRes.body.code)), `unexpected code: ${updateRes.body.code}`); - assert.match(String(updateRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 }); it('should create then update then delete permission successfully', async () => { @@ -301,11 +288,7 @@ describe('test/app/controller/system.setting.permission.test.js', () => { } }); -<<<<<<< HEAD it('should reject mixed delete when ids contain non-existent permission', async () => { -======= - it('should reject mixed delete when ids contain out-of-scope permission', async () => { ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 const suffix = Date.now(); const path = `autotest.permission.mixed.outscope.${suffix}`; let permissionId = 0; @@ -331,13 +314,8 @@ describe('test/app/controller/system.setting.permission.test.js', () => { assert.equal(mixedRes.status, 200); assert.equal(mixedRes.body.flag, 'failure'); -<<<<<<< HEAD assert.equal(Number(mixedRes.body.code), 404); assert.match(String(mixedRes.body.message || ''), /权限不存在/); -======= - assert.ok([ 400, 404 ].includes(Number(mixedRes.body.code)), `unexpected code: ${mixedRes.body.code}`); - assert.match(String(mixedRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/); ->>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893 // 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删) const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', { diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js index c645e65..14f8302 100644 --- a/test/app/controller/system.setting.storeWarehouse.test.js +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -268,7 +268,7 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /unexpected_field|不支持字段/); }); - it('should allow warehouse side to save, update and delete qimen config on a contract', async function() { + it('should allow warehouse side to save, update and delete api config on a contract', async function() { const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { page: 1, page_size: 30, @@ -285,13 +285,14 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; const candidate = candidates.find(item => Number(item.id) > 0); - assert.ok(candidate, '需要至少一条签约关系用于奇门配置回归'); + assert.ok(candidate, '需要至少一条签约关系用于接口配置回归'); - const originalQimenConfig = candidate.qimen_config ? { ...candidate.qimen_config } : null; + const originalApiConfig = candidate.api_config || candidate.apiConfig || null; const seed = Date.now(); const createPayload = { id: Number(candidate.id), - app_name: `autotest_qimen_${seed}`, + interface_type_id: Number((originalApiConfig && originalApiConfig.interface_type_id) || 0) || undefined, + app_name: `autotest_api_${seed}`, qimen_app_key: `autotest_app_${seed}`, qimen_customer_id: `autotest_customer_${seed}`, qimen_warehouse_code: `autotest_wh_${seed}`, @@ -302,30 +303,37 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { }; try { - const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, createPayload, token, EXTRA_HEADERS); + const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, createPayload, token, EXTRA_HEADERS); assert.equal(saveRes.status, 200); assert.equal(saveRes.body.flag, 'success'); assert.equal(saveRes.body.code, 200); assert.match(String(saveRes.body?.data?.action || ''), /create|update/); - assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_app_key || ''), createPayload.qimen_app_key); - assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_customer_id || ''), createPayload.qimen_customer_id); - assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code); + + const savedApiConfig = saveRes.body?.data?.api_config || saveRes.body?.data?.apiConfig || saveRes.body?.data?.qimen_config || null; + assert.ok(savedApiConfig, '保存后应返回 api_config'); + assert.equal(String(savedApiConfig?.qimen_app_key || ''), createPayload.qimen_app_key); + assert.equal(String(savedApiConfig?.qimen_customer_id || ''), createPayload.qimen_customer_id); + assert.equal(String(savedApiConfig?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code); const updatePayload = { ...createPayload, + interface_type_id: Number((savedApiConfig && savedApiConfig.interface_type_id) || createPayload.interface_type_id || 0) || undefined, app_name: `${createPayload.app_name}_updated`, qimen_customer_id: `${createPayload.qimen_customer_id}_updated`, qimen_warehouse_code: `${createPayload.qimen_warehouse_code}_updated`, is_enabled: 0, }; - const updateRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, updatePayload, token, EXTRA_HEADERS); + const updateRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, updatePayload, token, EXTRA_HEADERS); assert.equal(updateRes.status, 200); assert.equal(updateRes.body.flag, 'success'); assert.equal(updateRes.body.code, 200); assert.equal(String(updateRes.body?.data?.action || ''), 'update'); - assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); - assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code); - assert.equal(Number(updateRes.body?.data?.qimen_config?.is_enabled), 0); + + const updatedApiConfig = updateRes.body?.data?.api_config || updateRes.body?.data?.apiConfig || updateRes.body?.data?.qimen_config || null; + assert.ok(updatedApiConfig, '更新后应返回 api_config'); + assert.equal(String(updatedApiConfig?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.equal(String(updatedApiConfig?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code); + assert.equal(Number(updatedApiConfig?.is_enabled), 0); const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { id: Number(candidate.id), @@ -334,22 +342,23 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(verifyRes.body.flag, 'success'); assert.equal(verifyRes.body.code, 200); const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null; - assert.ok(verified, '保存奇门配置后应能查询到签约关系'); - assert.equal(String(verified?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.ok(verified, '保存接口配置后应能查询到签约关系'); + assert.equal(String((verified?.api_config || verified?.apiConfig || {}).qimen_customer_id || ''), updatePayload.qimen_customer_id); - const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listApiConfig`, { id: Number(candidate.id), }, token, EXTRA_HEADERS); assert.equal(configListRes.status, 200); assert.equal(configListRes.body.flag, 'success'); assert.equal(configListRes.body.code, 200); assert.equal(Number(configListRes.body?.data?.contract_id || 0), Number(candidate.id)); - assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回奇门配置列表'); - assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条奇门配置'); + assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回接口配置列表'); + assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条接口配置'); assert.equal(String(configListRes.body?.data?.list?.[0]?.qimen_customer_id || ''), updatePayload.qimen_customer_id); const deleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, { id: Number(candidate.id), + interface_type_id: Number((updatedApiConfig && updatedApiConfig.interface_type_id) || createPayload.interface_type_id || 0) || undefined, }, token, EXTRA_HEADERS); assert.equal(deleteRes.status, 200); assert.equal(deleteRes.body.flag, 'success'); @@ -363,10 +372,10 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.equal(verifyDeleteRes.body.flag, 'success'); assert.equal(verifyDeleteRes.body.code, 200); const deletedView = Array.isArray(verifyDeleteRes.body?.data?.list) ? verifyDeleteRes.body.data.list[0] : null; - assert.ok(deletedView, '删除奇门配置后仍应能查询到签约关系'); - assert.equal(deletedView?.qimen_config || null, null); + assert.ok(deletedView, '删除接口配置后仍应能查询到签约关系'); + assert.equal(deletedView?.api_config || deletedView?.apiConfig || null, null); - const emptyListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + const emptyListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listApiConfig`, { id: Number(candidate.id), }, token, EXTRA_HEADERS); assert.equal(emptyListRes.status, 200); @@ -375,17 +384,18 @@ describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { assert.ok(Array.isArray(emptyListRes.body?.data?.list), '删除后仍应返回列表结构'); assert.equal(Number(emptyListRes.body?.data?.total || 0), 0); } finally { - if (originalQimenConfig) { - await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, { + if (originalApiConfig) { + await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, { id: Number(candidate.id), - app_name: originalQimenConfig.app_name, - qimen_app_key: originalQimenConfig.qimen_app_key, - qimen_customer_id: originalQimenConfig.qimen_customer_id, - qimen_warehouse_code: originalQimenConfig.qimen_warehouse_code, - contact_person: originalQimenConfig.contact_person, - contact_phone: originalQimenConfig.contact_phone, - email: originalQimenConfig.email, - is_enabled: Number(originalQimenConfig.is_enabled || 0), + interface_type_id: Number(originalApiConfig.interface_type_id || 0) || undefined, + app_name: originalApiConfig.app_name, + qimen_app_key: originalApiConfig.qimen_app_key, + qimen_customer_id: originalApiConfig.qimen_customer_id, + qimen_warehouse_code: originalApiConfig.qimen_warehouse_code, + contact_person: originalApiConfig.contact_person, + contact_phone: originalApiConfig.contact_phone, + email: originalApiConfig.email, + is_enabled: Number(originalApiConfig.is_enabled || 0), }, token, EXTRA_HEADERS); } } diff --git a/test/app/controller/system.stock.warehouse.getStockDetail.test.js b/test/app/controller/system.stock.warehouse.getStockDetail.test.js new file mode 100644 index 0000000..76959cf --- /dev/null +++ b/test/app/controller/system.stock.warehouse.getStockDetail.test.js @@ -0,0 +1,316 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; + +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { + token: currentToken, + roleId, + }; + } + } + + throw new Error('未找到可访问仓库商品列表的仓库角色'); +} + +/** + * 从仓库商品列表中获取一个有效的 stock_id + * @param {string} token 传入的token必须具有访问仓库商品列表的权限 + */ +async function getValidStockId(token) { + const listRes = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const list = listRes.body?.data?.list; + assert.ok(Array.isArray(list) && list.length > 0, '仓库中没有商品数据,无法执行测试'); + + return list[0].id; +} + +describe('test/app/controller/system.stock.warehouse.getStockDetail.test.js', () => { + let warehouseToken; + let validStockId; + + before(async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + warehouseToken = switched.token; + validStockId = await getValidStockId(warehouseToken); + }); + + it('should return stockItem, storageList and pagination for a valid stock_id', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + + // stockItem 结构校验 + assert.ok(data.stockItem, '缺少 stockItem'); + assert.ok('id' in data.stockItem, 'stockItem 缺少 id'); + assert.ok('item_code' in data.stockItem, 'stockItem 缺少 item_code'); + assert.ok('item_name' in data.stockItem, 'stockItem 缺少 item_name'); + assert.ok('quantity' in data.stockItem, 'stockItem 缺少 quantity'); + assert.ok('locked_quantity' in data.stockItem, 'stockItem 缺少 locked_quantity'); + + // storageList 结构校验 + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + + // pagination 结构校验 + assert.ok(data.pagination, '缺少 pagination'); + assert.ok('page' in data.pagination, 'pagination 缺少 page'); + assert.ok('pageSize' in data.pagination, 'pagination 缺少 pageSize'); + assert.ok('total' in data.pagination, 'pagination 缺少 total'); + }); + + it('should respect pagination parameters', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 2 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + assert.ok(data.storageList.length <= 2, 'storageList 数量应不超过 pageSize'); + assert.equal(data.pagination.page, 1); + assert.equal(data.pagination.pageSize, 2); + }); + + it('should return error when stock_id is empty', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', {}, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 0, '缺少 stock_id 应返回 code=0'); + assert.ok(res.body.message, '缺少 stock_id 应返回错误消息'); + }); + + it('should return error when stock_id does not exist', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: 999999999, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 0, '不存在的 stock_id 应返回 code=0'); + assert.ok(res.body.message, '不存在的 stock_id 应返回错误消息'); + }); + + it('should return empty storageList when stock exists but has no storage records', async () => { + // 使用有效 stock_id 查询,如果该商品恰好有库存,则仅验证结构 + // 若无库存记录,storageList 应为空数组 + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 9999, pageSize: 20 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(data, '响应缺少 data'); + assert.ok(data.stockItem, '缺少 stockItem'); + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + assert.equal(data.storageList.length, 0, '超出范围的分页应返回空 storageList'); + }); + + // ---- group_by_batch 相关用例 ---- + + const BATCH_FIELDS = [ 'batch_no', 'production_date', 'expiry_date', 'inbound_time', 'inbound_order_no', 'supplier_batch_no' ]; + + it('should merge storageList by space_id when group_by_batch is not provided (default)', async () => { + // 先用 group_by_batch=true 获取原始明细 + const rawRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + group_by_batch: true, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(rawRes.status, 200); + assert.equal(rawRes.body.code, 200); + const rawList = rawRes.body.data.storageList; + + // 默认不传 group_by_batch + const mergedRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(mergedRes.status, 200); + assert.equal(mergedRes.body.flag, 'success'); + assert.equal(mergedRes.body.code, 200); + + const mergedList = mergedRes.body.data.storageList; + assert.ok(Array.isArray(mergedList), 'storageList 应为数组'); + + // 按 space_id 分组计算期望的合并数 + const spaceIds = new Set(rawList.map(r => r.space_id)); + assert.equal(mergedList.length, spaceIds.size, '合并后记录数应等于不同 space_id 数量'); + + // 验证批次字段全部置 null + for (const row of mergedList) { + for (const field of BATCH_FIELDS) { + assert.equal(row[field], null, `合并模式下 ${field} 应为 null`); + } + } + + // 验证 quantity 累加正确:raw 按 space_id 分组求和 vs merged + for (const row of mergedList) { + const rawForSpace = rawList.filter(r => r.space_id === row.space_id); + const expectedQty = rawForSpace.reduce((sum, r) => sum + Number(r.quantity), 0); + const expectedLocked = rawForSpace.reduce((sum, r) => sum + Number(r.locked_quantity), 0); + assert.equal(Number(row.quantity), expectedQty, `space_id=${row.space_id} quantity 累加不正确`); + assert.equal(Number(row.locked_quantity), expectedLocked, `space_id=${row.space_id} locked_quantity 累加不正确`); + assert.equal(Number(row.available_quantity), expectedQty - expectedLocked, `space_id=${row.space_id} available_quantity 计算不正确`); + } + }); + + it('should merge storageList by space_id when group_by_batch=false (explicit)', async () => { + // 显式传 false + const explicitRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + group_by_batch: false, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(explicitRes.status, 200); + assert.equal(explicitRes.body.flag, 'success'); + assert.equal(explicitRes.body.code, 200); + + const explicitList = explicitRes.body.data.storageList; + + // 默认不传 group_by_batch + const defaultRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(defaultRes.status, 200); + assert.equal(defaultRes.body.code, 200); + + const defaultList = defaultRes.body.data.storageList; + + // 显式 false 与默认行为一致 + assert.equal(explicitList.length, defaultList.length, '显式 false 与默认不传应返回相同数量'); + + // 验证批次字段全部置 null + for (const row of explicitList) { + for (const field of BATCH_FIELDS) { + assert.equal(row[field], null, `显式 false 模式下 ${field} 应为 null`); + } + } + + // quantity 应一致 + for (let i = 0; i < explicitList.length; i++) { + assert.equal(Number(explicitList[i].quantity), Number(defaultList[i].quantity), `第 ${i} 条 quantity 不一致`); + assert.equal(Number(explicitList[i].locked_quantity), Number(defaultList[i].locked_quantity), `第 ${i} 条 locked_quantity 不一致`); + } + }); + + it('should return independent records per batch when group_by_batch=true', async () => { + const res = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + group_by_batch: true, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const data = res.body.data; + assert.ok(Array.isArray(data.storageList), 'storageList 应为数组'); + + // 验证结构完整:每条记录包含批次字段 + for (const row of data.storageList) { + assert.ok('batch_no' in row, '区分批次模式下应包含 batch_no'); + assert.ok('production_date' in row, '区分批次模式下应包含 production_date'); + assert.ok('expiry_date' in row, '区分批次模式下应包含 expiry_date'); + assert.ok('inbound_time' in row, '区分批次模式下应包含 inbound_time'); + assert.ok('inbound_order_no' in row, '区分批次模式下应包含 inbound_order_no'); + assert.ok('supplier_batch_no' in row, '区分批次模式下应包含 supplier_batch_no'); + assert.ok('quantity' in row, '区分批次模式下应包含 quantity'); + assert.ok('locked_quantity' in row, '区分批次模式下应包含 locked_quantity'); + assert.ok('available_quantity' in row, '区分批次模式下应包含 available_quantity'); + } + + // 与合并模式对比:group_by_batch=true 的记录数应 >= 合并后记录数 + const mergedRes = await invokeSystemMethod('stock.warehouse.getStockDetail', { + stock_id: validStockId, + pagination: { page: 1, pageSize: 200 }, + }, warehouseToken, EXTRA_HEADERS); + + assert.equal(mergedRes.status, 200); + assert.equal(mergedRes.body.code, 200); + + const mergedCount = mergedRes.body.data.storageList.length; + assert.ok(data.storageList.length >= mergedCount, 'group_by_batch=true 记录数应 >= 合并后记录数'); + + // pagination 结构校验 + assert.ok(data.pagination, '缺少 pagination'); + assert.ok('page' in data.pagination, 'pagination 缺少 page'); + assert.ok('pageSize' in data.pagination, 'pagination 缺少 pageSize'); + assert.ok('total' in data.pagination, 'pagination 缺少 total'); + }); +}); diff --git a/test/app/controller/system.storage.delivery.module.test.js b/test/app/controller/system.storage.delivery.module.test.js new file mode 100644 index 0000000..ededb30 --- /dev/null +++ b/test/app/controller/system.storage.delivery.module.test.js @@ -0,0 +1,304 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_WAREHOUSE_ID = 100000; + +function normalizeListPayload(data) { + if (data && Array.isArray(data.list)) return data; + if (data && data.data && Array.isArray(data.data.list)) return data.data; + return null; +} + +async function switchToWarehouseRoleWithDeliveryData(token) { + let currentToken = token; + + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + assert.equal(infoRes.body.code, 200); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const preferredWarehouseRoles = employees.filter(item => + item + && item.role_type === 'warehouse' + && Number(item.id) + && Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const otherWarehouseRoles = employees.filter(item => + item + && item.role_type === 'warehouse' + && Number(item.id) + && Number(item.store_id) !== TEST_WAREHOUSE_ID + ); + + const candidateRoleIds = [ ...new Set([ + ...preferredWarehouseRoles.map(item => Number(item.id)), + ...otherWarehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { + roleId, + }, currentToken, EXTRA_HEADERS); + + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { + continue; + } + + currentToken = changeRes.body?.data?.token || currentToken; + + const statsRes = await invokeSystemMethod('order.stats', { + where: {}, + }, currentToken, EXTRA_HEADERS); + + if (statsRes.status !== 200 || statsRes.body?.flag !== 'success' || statsRes.body?.code !== 200) { + continue; + } + + const total = Number(statsRes.body?.data?.total || 0); + if (total > 0) { + return { + token: currentToken, + roleId, + total, + }; + } + } + + throw new Error('未找到有订单数据的仓库角色'); +} + +async function getFirstDelivery(token) { + const res = await invokeSystemMethod('storage.stockout.list', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + assert.ok(payload, '返回结构中缺少出库单列表 payload'); + assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); + assert.ok(payload.pagination, '出库单 pagination 缺失'); + + const first = payload.list[0]; + assert.ok(first, '出库单列表为空,无法继续验证 toOrder/listItems'); + return first; +} + +async function getEntryContextForRemovedMethods(token) { + const listRes = await invokeSystemMethod('storage.entry.list', { + pagination: { + page: 1, + pageSize: 1, + }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const payload = normalizeListPayload(listRes.body.data); + const entry = payload && Array.isArray(payload.list) ? payload.list[0] : null; + + if (!entry || !entry.id) { + return { + orderId: 1, + detailId: 1, + itemCode: `SKU-${Date.now().toString().slice(-6)}`, + }; + } + + const getRes = await invokeSystemMethod('storage.entry.get', { + id: Number(entry.id), + }, token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(getRes.body.code, 200); + + const entryOrder = getRes.body?.data?.entryOrder || {}; + const firstItem = Array.isArray(entryOrder?.items) ? entryOrder.items[0] : null; + + return { + orderId: Number(entry.id), + detailId: Number(firstItem?.id || 1), + itemCode: String(firstItem?.item_code || firstItem?.stock?.item_code || `SKU-${Date.now().toString().slice(-6)}`), + }; +} + +describe('test/app/controller/system.storage.delivery.module.test.js', function() { + this.timeout(120000); + + it('should not expose storage.delivery methods after compatibility layer removal', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const delivery = await getFirstDelivery(switched.token); + + const removedMethods = [ + { + method: 'storage.delivery.list', + body: { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, + }, + { + method: 'storage.delivery.toOrder', + body: { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, + }, + { + method: 'storage.delivery.listItems', + body: { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, + }, + ]; + + for (const { method, body } of removedMethods) { + const res = await invokeSystemMethod(method, body, switched.token, EXTRA_HEADERS); + const isLegacySuccess = res.status === 200 + && res.body?.flag === 'success' + && Number(res.body?.code) === 200; + + assert.ok(!isLegacySuccess, `${method} 仍然返回 success 200: ${JSON.stringify(res.body)}`); + } + }); + + it('should return delivery list via storage.stockout.list', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + + const res = await invokeSystemMethod('storage.stockout.list', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + assert.ok(payload, '返回结构中缺少出库单列表 payload'); + assert.ok(Array.isArray(payload.list), '出库单 list 不是数组'); + assert.ok(payload.pagination, '出库单 pagination 缺失'); + assert.equal(typeof payload.pagination.total, 'number', 'pagination.total 不是 number'); + }); + + it('should return placeholder failure via storage.stockout.toOrder', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const delivery = await getFirstDelivery(switched.token); + + const res = await invokeSystemMethod('storage.stockout.toOrder', { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, switched.token, EXTRA_HEADERS); + + console.log('[storage.stockout.toOrder]', JSON.stringify({ + flag: res.body?.flag, + code: res.body?.code, + message: res.body?.message, + placeholder: res.body?.placeholder, + })); + + assert.equal(res.status, 200); + assert.notEqual(res.body.flag, 'success', 'toOrder 不应再返回 success'); + assert.equal(Number(res.body.code), 405); + assert.match(String(res.body.message || ''), /占位接口|暂未开放/); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.placeholder, true); + }); + + it('should return item list via storage.stockout.listItems', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const delivery = await getFirstDelivery(switched.token); + + const res = await invokeSystemMethod('storage.stockout.listItems', { + id: Number(delivery.id), + delivery_order_code: delivery.delivery_order_code, + warehouse_id: TEST_WAREHOUSE_ID, + }, switched.token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.ok(res.body.data && typeof res.body.data === 'object', '缺少 data 对象'); + assert.ok(Array.isArray(res.body.data.items), 'data.items 不是数组'); + }); + + it('should not expose removed storage.entry detail methods', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRoleWithDeliveryData(token); + const entryContext = await getEntryContextForRemovedMethods(switched.token); + + const removedMethods = [ + { + method: 'storage.entry.addDetail', + body: { + order_id: entryContext.orderId, + count: 1, + item_code: entryContext.itemCode, + inventory_type: 'ZP', + }, + }, + { + method: 'storage.entry.deleteDetail', + body: { + id: entryContext.detailId, + }, + }, + { + method: 'storage.entry.detailChange', + body: { + id: entryContext.detailId, + count: 2, + item_code: entryContext.itemCode, + }, + }, + ]; + + for (const { method, body } of removedMethods) { + const res = await invokeSystemMethod(method, body, switched.token, EXTRA_HEADERS); + const isLegacySuccess = res.status === 200 + && res.body?.flag === 'success' + && Number(res.body?.code) === 200; + + assert.ok(!isLegacySuccess, `${method} 仍然返回 success 200: ${JSON.stringify(res.body)}`); + } + }); +}); diff --git a/test/app/controller/system.storage.inventory.matchPutaway.test.js b/test/app/controller/system.storage.inventory.matchPutaway.test.js new file mode 100644 index 0000000..896a978 --- /dev/null +++ b/test/app/controller/system.storage.inventory.matchPutaway.test.js @@ -0,0 +1,430 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { platform: 'web', project: 'all' }; +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_STORE_ID = 1000000; +const TEST_WAREHOUSE_ID = 100000; + +// ──── 数据库连接 ──── +const dbConfig = require('../../../database/config'); +const env = process.env.NODE_ENV || 'development'; +const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; + +// ──── switchToWarehouseRole ──── +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => + item && item.role_type === 'warehouse' && Number(item.id) && + Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { roleId }, currentToken, EXTRA_HEADERS); + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) continue; + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { token: currentToken, roleId }; + } + } + throw new Error(`未找到 warehouse_id=${TEST_WAREHOUSE_ID} 的仓库角色`); +} + +// ──── 获取系统商品(至少 minCount 个) ──── +async function getSystemProducts(token, minCount = 2) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 20 }, + where: {}, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + + let list = []; + if (res.body?.data?.data?.list) list = res.body.data.data.list; + else if (res.body?.data?.list) list = res.body.data.list; + + const products = list + .filter(item => Number(item?.id || 0) > 0) + .slice(0, minCount) + .map(item => ({ + id: Number(item.id), + item_name: String(item.item_name || item.name || ''), + item_code: String(item.item_code || ''), + })); + assert.ok(products.length >= minCount, `需至少 ${minCount} 个系统商品,实际只有 ${products.length} 个`); + return products; +} + +// ──── 创建收货单 ──── +async function createReceiving(token) { + const res = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-MP-${Date.now().toString().slice(-6)}`, + loading_method: 'without_pallet', + remark: `matchPutaway集成测试 ${new Date().toISOString()}`, + total_boxes: 1, + total_pallets: 0, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `创建收货单HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `创建收货单失败: ${res.body.message}`); + const receivingId = Number(res.body.id || res.body?.data?.id || 0); + assert.ok(receivingId > 0, '创建收货单无返回ID'); + return receivingId; +} + +// ──── 绑定货主 ──── +async function bindStore(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.bindStore', { + id: receivingId, + store_id: TEST_STORE_ID, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); +} + +// ──── 添加明细 + 修改明细 + 绑定商品 ──── +async function addAndFillDetail(token, receivingId, product, qty) { + const addRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(addRes.status, 200, `添加明细HTTP失败: ${JSON.stringify(addRes.body)}`); + assert.equal(addRes.body.flag, 'success', `添加明细失败: ${addRes.body.message}`); + const detailId = Number(addRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, `添加明细无返回selectId: ${JSON.stringify(addRes.body)}`); + + const changeRes = await invokeSystemMethod('storage.receiving.detailChange', { + id: detailId, + receiving_id: receivingId, + product_name: product.item_name || '测试商品', + barcode: product.item_code || `TEST-BC-${Date.now()}`, + actual_quantity: qty, + box_quantity: 1, + pallet_quantity: 0, + }, token, EXTRA_HEADERS); + assert.equal(changeRes.status, 200, `修改明细失败: ${JSON.stringify(changeRes.body)}`); + assert.equal(changeRes.body.flag, 'success', `修改明细失败: ${changeRes.body.message}`); + + return detailId; +} + +async function bindDetailProduct(token, detailId, productId) { + const res = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: productId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `绑定商品失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `绑定商品失败: ${res.body.message}`); +} + +// ──── 完成收货 ──── +async function completeReceiving(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.completeReceiving', { + id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); +} + +// ──── 创建测试入库单(直接数据库插入) ──── +async function createTestEntryOrder(sequelize, { warehouseId, storeId, items }) { + const code = `TEST-ENTRY-${Date.now()}`; + const [ results ] = await sequelize.query( + `INSERT INTO wms_entry_order (entry_order_code, order_type, total_order_lines, order_create_time, source_type, order_status, sync_status, is_enabled, warehouse_id, store_id, created_at, updated_at) + VALUES (:code, 'CGRK', :lines, NOW(), 'API', 'CREATED', 'PENDING', 1, :warehouseId, :storeId, NOW(), NOW())`, + { replacements: { code, lines: items.length, warehouseId, storeId }, type: Sequelize.QueryTypes.INSERT } + ); + const orderId = results; + + for (let i = 0; i < items.length; i++) { + await sequelize.query( + `INSERT INTO wms_entry_items (order_id, order_line_no, item_code, item_id, count, inventory_type, stock_id, received_quantity, confirm_quantity) + VALUES (:orderId, :lineNo, :itemCode, :itemId, :count, 'ZP', :stockId, 0, 0)`, + { replacements: { orderId, lineNo: i + 1, itemCode: items[i].item_code, itemId: items[i].id, count: items[i].quantity, stockId: items[i].id } } + ); + } + + return { id: orderId, code }; +} + +// ──── matchPutaway 调用 ──── +async function matchPutaway(token, receivingIds, entryOrderIds) { + return invokeSystemMethod('storage.inventory.matchPutaway', { + receiving_ids: receivingIds, + entry_order_ids: entryOrderIds, + }, token, EXTRA_HEADERS); +} + +describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', () => { + let authToken; + let products; // 至少 2 个 + let sequelize; + + before(async function() { + this.timeout(30000); + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + authToken = switched.token; + products = await getSystemProducts(authToken, 2); + console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); + + sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); + }); + + after(async function() { + if (sequelize) { + await sequelize.close(); + console.log('[TEARDOWN] 数据库连接已关闭'); + } + }); + + // ────────────────────────────────────────────────────── + // 1. 精确匹配:收货量 = 入库计划量 + // ────────────────────────────────────────────────────── + it('should match putaway when receiving equals entry order (exact match)', async function() { + this.timeout(60000); + + const quantities = [ 10, 5 ]; + + // 1. 创建收货单 → 添加明细 → 绑定商品 → 完成收货 + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[EXACT] 收货单 ID: ${receivingId}`); + + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[EXACT] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); + } + await completeReceiving(authToken, receivingId); + + // 2. 创建入库单(数量与收货完全一致) + const entryOrder = await createTestEntryOrder(sequelize, { + warehouseId: TEST_WAREHOUSE_ID, + storeId: TEST_STORE_ID, + items: products.map((p, i) => ({ + id: p.id, + item_code: p.item_code, + quantity: quantities[i], + })), + }); + console.log(`[EXACT] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`); + + // 3. 调用 matchPutaway + const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]); + console.log('[EXACT] matchPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`); + + const resultData = res.body?.data?.data || res.body?.data || {}; + const resCode = Number(resultData.code || res.body?.code || 0); + assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`); + + // 4. 验证收货单 storage_status=all + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + console.log(`[EXACT] 收货单 storage_status: ${receivingAfter.storage_status}`); + assert.equal(receivingAfter.storage_status, 'all', `收货单应全部入库, 实际: ${receivingAfter.storage_status}`); + + // 5. 验证入库单 order_status=COMPLETED(查数据库) + const [ entryRows ] = await sequelize.query( + 'SELECT order_status FROM wms_entry_order WHERE id = :id', + { replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT } + ); + console.log(`[EXACT] 入库单 order_status: ${entryRows.order_status}`); + assert.equal(entryRows.order_status, 'COMPLETED', `入库单应已完成, 实际: ${entryRows.order_status}`); + + // 6. 验证 receiving_results + const receivingResults = resultData.receiving_results || []; + const rcvResult = receivingResults.find(r => r.receiving_id === receivingId); + assert.ok(rcvResult, '返回结果中应包含收货单信息'); + assert.equal(rcvResult.storage_status, 'all', '返回中 storage_status 应为 all'); + + // 7. 验证 entry_order_results + const entryOrderResults = resultData.entry_order_results || []; + const eoResult = entryOrderResults.find(r => r.entry_order_id === entryOrder.id); + assert.ok(eoResult, '返回结果中应包含入库单信息'); + assert.equal(eoResult.order_status, 'COMPLETED', '返回中入库单状态应为 COMPLETED'); + }); + + // ────────────────────────────────────────────────────── + // 2. 收货 > 入库计划(部分匹配,有剩余) + // ────────────────────────────────────────────────────── + it('should handle receiving > entry order (partial match with surplus)', async function() { + this.timeout(60000); + + const rcvQuantities = [ 20, 15 ]; + const entryQuantities = [ 10, 5 ]; + + // 1. 创建收货单(数量 20, 15) + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[SURPLUS] 收货单 ID: ${receivingId}`); + + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], rcvQuantities[i]); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[SURPLUS] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`); + } + await completeReceiving(authToken, receivingId); + + // 2. 创建入库单(数量 10, 5 — 小于收货量) + const entryOrder = await createTestEntryOrder(sequelize, { + warehouseId: TEST_WAREHOUSE_ID, + storeId: TEST_STORE_ID, + items: products.map((p, i) => ({ + id: p.id, + item_code: p.item_code, + quantity: entryQuantities[i], + })), + }); + console.log(`[SURPLUS] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`); + + // 3. 调用 matchPutaway + const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]); + console.log('[SURPLUS] matchPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`); + + const resultData = res.body?.data?.data || res.body?.data || {}; + const resCode = Number(resultData.code || res.body?.code || 0); + assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`); + + // 4. 验证收货单 storage_status=partial(只入了部分) + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + console.log(`[SURPLUS] 收货单 storage_status: ${receivingAfter.storage_status}`); + assert.equal(receivingAfter.storage_status, 'partial', `收货单应为部分入库, 实际: ${receivingAfter.storage_status}`); + + // 验证各明细的 stored_quantity < actual_quantity + const detailsAfter = Array.isArray(receivingAfter.details) ? receivingAfter.details : []; + for (const d of detailsAfter) { + if (d.system_product_id) { + assert.ok(Number(d.stored_quantity) < Number(d.actual_quantity), + `明细 ${d.id}: stored(${d.stored_quantity}) 应小于 actual(${d.actual_quantity})`); + console.log(`[SURPLUS] 明细 ${d.id}: stored=${d.stored_quantity}, actual=${d.actual_quantity}, status=${d.storage_status}`); + } + } + + // 5. 验证入库单 order_status=COMPLETED(计划量全部收满) + const [ entryRows ] = await sequelize.query( + 'SELECT order_status FROM wms_entry_order WHERE id = :id', + { replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT } + ); + console.log(`[SURPLUS] 入库单 order_status: ${entryRows.order_status}`); + assert.equal(entryRows.order_status, 'COMPLETED', `入库单应已完成, 实际: ${entryRows.order_status}`); + }); + + // ────────────────────────────────────────────────────── + // 3. 收货 < 入库计划(收货不足) + // ────────────────────────────────────────────────────── + it('should handle receiving < entry order (insufficient receiving)', async function() { + this.timeout(60000); + + const rcvQuantities = [ 5, 3 ]; + const entryQuantities = [ 10, 8 ]; + + // 1. 创建收货单(数量 5, 3) + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[INSUF] 收货单 ID: ${receivingId}`); + + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], rcvQuantities[i]); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[INSUF] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`); + } + await completeReceiving(authToken, receivingId); + + // 2. 创建入库单(数量 10, 8 — 大于收货量) + const entryOrder = await createTestEntryOrder(sequelize, { + warehouseId: TEST_WAREHOUSE_ID, + storeId: TEST_STORE_ID, + items: products.map((p, i) => ({ + id: p.id, + item_code: p.item_code, + quantity: entryQuantities[i], + })), + }); + console.log(`[INSUF] 入库单 ID: ${entryOrder.id}, code: ${entryOrder.code}`); + + // 3. 调用 matchPutaway + const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]); + console.log('[INSUF] matchPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`); + + const resultData = res.body?.data?.data || res.body?.data || {}; + const resCode = Number(resultData.code || res.body?.code || 0); + assert.equal(resCode, 200, `matchPutaway 应返回 code=200, 实际: ${resCode}`); + + // 4. 验证收货单 storage_status=all(收货全部入库了) + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + console.log(`[INSUF] 收货单 storage_status: ${receivingAfter.storage_status}`); + assert.equal(receivingAfter.storage_status, 'all', `收货单应全部入库, 实际: ${receivingAfter.storage_status}`); + + // 5. 验证入库单 order_status=PARTIAL_RECEIVED(未全部完成) + const [ entryRows ] = await sequelize.query( + 'SELECT order_status FROM wms_entry_order WHERE id = :id', + { replacements: { id: entryOrder.id }, type: Sequelize.QueryTypes.SELECT } + ); + console.log(`[INSUF] 入库单 order_status: ${entryRows.order_status}`); + assert.equal(entryRows.order_status, 'PARTIAL_RECEIVED', `入库单应部分收货, 实际: ${entryRows.order_status}`); + + // 6. 验证 warnings 包含提示(收货量 < 入库计划量) + const warnings = resultData.warnings || []; + console.log('[INSUF] warnings:', warnings); + assert.ok(warnings.length > 0, '应包含 warnings 提示'); + const hasInsufficientWarning = warnings.some(w => + w.includes('收货可入库量') || w.includes('未全部入库完成') + ); + assert.ok(hasInsufficientWarning, `warnings 应包含收货不足或未全部完成提示, 实际: ${JSON.stringify(warnings)}`); + }); +}); diff --git a/test/app/controller/system.storage.inventory.quickPutaway.test.js b/test/app/controller/system.storage.inventory.quickPutaway.test.js new file mode 100644 index 0000000..add742b --- /dev/null +++ b/test/app/controller/system.storage.inventory.quickPutaway.test.js @@ -0,0 +1,384 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { platform: 'web', project: 'all' }; +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_STORE_ID = 1000000; +const TEST_WAREHOUSE_ID = 100000; + +// ──── 数据库连接(用于锁冲突测试) ──── +const dbConfig = require('../../../database/config'); +const env = process.env.NODE_ENV || 'development'; +const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; + +// ──── switchToWarehouseRole ──── +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => + item && item.role_type === 'warehouse' && Number(item.id) && + Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { roleId }, currentToken, EXTRA_HEADERS); + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) continue; + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { token: currentToken, roleId }; + } + } + throw new Error(`未找到 warehouse_id=${TEST_WAREHOUSE_ID} 的仓库角色`); +} + +// ──── 获取系统商品(至少 minCount 个) ──── +async function getSystemProducts(token, minCount = 2) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 20 }, + where: {}, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + + let list = []; + if (res.body?.data?.data?.list) list = res.body.data.data.list; + else if (res.body?.data?.list) list = res.body.data.list; + + const products = list + .filter(item => Number(item?.id || 0) > 0) + .slice(0, minCount) + .map(item => ({ + id: Number(item.id), + item_name: String(item.item_name || item.name || ''), + item_code: String(item.item_code || ''), + })); + assert.ok(products.length >= minCount, `需至少 ${minCount} 个系统商品,实际只有 ${products.length} 个`); + return products; +} + +// ──── 创建收货单 ──── +async function createReceiving(token) { + const res = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-QP-${Date.now().toString().slice(-6)}`, + loading_method: 'without_pallet', + remark: `quickPutaway集成测试 ${new Date().toISOString()}`, + total_boxes: 1, + total_pallets: 0, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `创建收货单HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `创建收货单失败: ${res.body.message}`); + const receivingId = Number(res.body.id || res.body?.data?.id || 0); + assert.ok(receivingId > 0, '创建收货单无返回ID'); + return receivingId; +} + +// ──── 绑定货主 ──── +async function bindStore(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.bindStore', { + id: receivingId, + store_id: TEST_STORE_ID, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); +} + +// ──── 添加明细 + 修改明细 + 绑定商品 ──── +async function addAndFillDetail(token, receivingId, product, qty) { + // addDetail + const addRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(addRes.status, 200, `添加明细HTTP失败: ${JSON.stringify(addRes.body)}`); + assert.equal(addRes.body.flag, 'success', `添加明细失败: ${addRes.body.message}`); + const detailId = Number(addRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, `添加明细无返回selectId: ${JSON.stringify(addRes.body)}`); + + // detailChange + const changeRes = await invokeSystemMethod('storage.receiving.detailChange', { + id: detailId, + receiving_id: receivingId, + product_name: product.item_name || '测试商品', + barcode: product.item_code || `TEST-BC-${Date.now()}`, + actual_quantity: qty, + box_quantity: 1, + pallet_quantity: 0, + }, token, EXTRA_HEADERS); + assert.equal(changeRes.status, 200, `修改明细失败: ${JSON.stringify(changeRes.body)}`); + assert.equal(changeRes.body.flag, 'success', `修改明细失败: ${changeRes.body.message}`); + + return detailId; +} + +async function bindDetailProduct(token, detailId, productId) { + const res = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: productId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `绑定商品失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `绑定商品失败: ${res.body.message}`); +} + +// ──── 完成收货 ──── +async function completeReceiving(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.completeReceiving', { + id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); +} + +// ──── 快捷入库 ──── +async function quickPutaway(token, receivingId) { + return invokeSystemMethod('storage.inventory.quickPutaway', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); +} + +describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', () => { + let authToken; + let products; // 至少 3 个 + + before(async function() { + this.timeout(30000); + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + authToken = switched.token; + products = await getSystemProducts(authToken, 3); + console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); + }); + + // ────────────────────────────────────────────────────── + // 1. 部分匹配拒绝 + // ────────────────────────────────────────────────────── + it('should reject quickPutaway for partially matched receiving', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[PARTIAL] 收货单 ID: ${receivingId}`); + + // 添加 3 条明细 + const detailIds = []; + const quantities = [ 5, 3, 2 ]; + for (let i = 0; i < 3; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + console.log(`[PARTIAL] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}`); + } + + // 只绑定前 2 条,第 3 条不绑定 + await bindDetailProduct(authToken, detailIds[0], products[0].id); + await bindDetailProduct(authToken, detailIds[1], products[1].id); + console.log('[PARTIAL] 只绑定了 2/3 条明细的商品'); + + // 完成收货 + await completeReceiving(authToken, receivingId); + + // 快捷入库 → 应被拒绝 + const res = await quickPutaway(authToken, receivingId); + console.log('[PARTIAL] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + const resCode = Number(res.body?.data?.code || res.body?.code || 0); + assert.equal(resCode, 400, `部分匹配应返回 400, 实际: ${resCode}`); + const message = String(res.body?.data?.message || res.body?.message || ''); + assert.ok(message.includes('未匹配'), `message 应包含"未匹配", 实际: ${message}`); + }); + + // ────────────────────────────────────────────────────── + // 2. 全匹配成功 + // ────────────────────────────────────────────────────── + it('should complete quickPutaway for fully matched receiving', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[FULL] 收货单 ID: ${receivingId}`); + + // 添加 2 条明细,全部绑定商品 + const detailIds = []; + const quantities = [ 10, 5 ]; + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[FULL] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); + } + + // 完成收货 + await completeReceiving(authToken, receivingId); + + // 快捷入库 + const res = await quickPutaway(authToken, receivingId); + console.log('[FULL] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + const putawayData = res.body?.data?.data || res.body?.data || {}; + assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); + assert.ok(putawayData.entry_order.id, '返回中缺少 entry_order.id'); + assert.ok(putawayData.entry_order.entry_order_code, '返回中缺少 entry_order_code'); + assert.ok(Array.isArray(putawayData.items), '返回中缺少 items 数组'); + assert.ok(putawayData.items.length > 0, 'items 数组为空'); + + // 验证 storage_status + for (const item of putawayData.items) { + assert.ok(item.storage_status, 'item 缺少 storage_status'); + } + + console.log(`[FULL] 入库单号: ${putawayData.entry_order.entry_order_code}, 明细数: ${putawayData.items.length}`); + + // 验证收货单明细入库状态 + const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { + id: receivingId, + pagination: { page: 1, pageSize: 100 }, + }, authToken, EXTRA_HEADERS); + assert.equal(detailRes.status, 200); + + const detailPayload = detailRes.body?.data?.data || detailRes.body?.data || {}; + const receivingAfter = detailPayload.receiving || {}; + const detailsAfter = Array.isArray(receivingAfter.details) ? receivingAfter.details : []; + + for (const d of detailsAfter) { + assert.equal(d.storage_status, 'all', `明细 ${d.id} 应全部入库, 实际: ${d.storage_status}`); + assert.equal(Number(d.stored_quantity), Number(d.actual_quantity), + `明细 ${d.id} stored_quantity(${d.stored_quantity}) 应等于 actual_quantity(${d.actual_quantity})`); + console.log(`[FULL] 明细 ${d.id}: stored=${d.stored_quantity}, actual=${d.actual_quantity}, status=${d.storage_status}`); + } + + // 重复入库应被拒绝 + const repeatRes = await quickPutaway(authToken, receivingId); + console.log('[FULL] 重复入库响应:', JSON.stringify(repeatRes.body, null, 2)); + const repeatCode = Number(repeatRes.body?.data?.code || repeatRes.body?.code || 0); + assert.equal(repeatCode, 400, `重复入库应返回 400, 实际: ${repeatCode}`); + }); + + // ────────────────────────────────────────────────────── + // 3. 数据库行锁冲突 → 409 + // ────────────────────────────────────────────────────── + it('should return 409 when stock row is locked by concurrent transaction', async function() { + this.timeout(120000); + + const productId = products[0].id; + console.log(`[LOCK] 测试商品 ID: ${productId}`); + console.log('[LOCK] 注意:本测试需等待服务端锁超时(约50秒),请耐心等待'); + + const sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); + + let lockTx; + try { + // 先准备好收货单数据 + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + const detailId = await addAndFillDetail(authToken, receivingId, products[0], 1); + await bindDetailProduct(authToken, detailId, products[0].id); + await completeReceiving(authToken, receivingId); + + // 开事务锁行 + lockTx = await sequelize.transaction(); + await sequelize.query( + 'SELECT * FROM wms_stock_warehouse WHERE id = :productId FOR UPDATE', + { replacements: { productId }, transaction: lockTx } + ); + console.log(`[LOCK] 已锁定 wms_stock_warehouse.id = ${productId}`); + + // 安全网:70秒后自动释放(确保超过服务端默认50秒锁等待) + const releaseTimer = setTimeout(async () => { + try { await lockTx.rollback(); } catch (_) { + console.log('错误中断'); + } + }, 70000); + + // 调 quickPutaway —— 服务端会等50秒左右才超时返回409 + const startTime = Date.now(); + const res = await quickPutaway(authToken, receivingId); + const elapsed = Math.round((Date.now() - startTime) / 1000); + console.log(`[LOCK] quickPutaway 响应 (耗时 ${elapsed}s):`, JSON.stringify(res.body, null, 2)); + + const resCode = Number(res.body?.data?.code || res.body?.code || 0); + assert.equal(resCode, 409, `锁冲突应返回 409, 实际: ${resCode}`); + const message = String(res.body?.data?.message || res.body?.message || ''); + assert.ok(message.includes('锁定'), `message 应包含"锁定", 实际: ${message}`); + + clearTimeout(releaseTimer); + } finally { + try { if (lockTx) await lockTx.rollback(); } catch (_) { + console.log('错误中断'); + } + await sequelize.close(); + console.log('[LOCK] 数据库连接已关闭'); + } + }); + + // ────────────────────────────────────────────────────── + // 4. 无锁冲突正常入库 + // ────────────────────────────────────────────────────── + it('should complete quickPutaway without lock contention', async function() { + this.timeout(60000); + + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[NOLOCK] 收货单 ID: ${receivingId}`); + + // 添加 2 条明细,全部绑定 + const detailIds = []; + const quantities = [ 8, 4 ]; + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[NOLOCK] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); + } + + // 完成收货 → 快捷入库 + await completeReceiving(authToken, receivingId); + const res = await quickPutaway(authToken, receivingId); + console.log('[NOLOCK] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + const putawayData = res.body?.data?.data || res.body?.data || {}; + assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); + assert.ok(putawayData.entry_order.id, '返回中缺少 entry_order.id'); + assert.ok(Array.isArray(putawayData.items), '返回中缺少 items 数组'); + assert.ok(putawayData.items.length === 2, `items 数量应为 2, 实际: ${putawayData.items.length}`); + + console.log(`[NOLOCK] 入库单号: ${putawayData.entry_order.entry_order_code}`); + console.log(`[NOLOCK] 入库明细数: ${putawayData.items.length}`); + + // 验证入库结果 + for (const item of putawayData.items) { + assert.ok(item.detail_id, 'item 缺少 detail_id'); + assert.ok(item.stock_warehouse_id, 'item 缺少 stock_warehouse_id'); + assert.ok(item.inbound_quantity > 0, 'inbound_quantity 应大于 0'); + console.log(`[NOLOCK] 明细 ${item.detail_id}: 入库 ${item.inbound_quantity}, 状态 ${item.storage_status}`); + } + }); +}); diff --git a/test/app/controller/system.storage.transaction.test.js b/test/app/controller/system.storage.transaction.test.js new file mode 100644 index 0000000..30f20df --- /dev/null +++ b/test/app/controller/system.storage.transaction.test.js @@ -0,0 +1,306 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const Sequelize = require('sequelize'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { platform: 'web', project: 'all' }; +const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; +const TEST_STORE_ID = 1000000; +const TEST_WAREHOUSE_ID = 100000; + +// ──── 数据库连接 ──── +const dbConfig = require('../../../database/config'); +const env = process.env.NODE_ENV || 'development'; +const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; + +// ──── switchToWarehouseRole ──── +async function switchToWarehouseRole(token) { + let currentToken = token; + const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); + assert.equal(infoRes.status, 200); + assert.equal(infoRes.body.flag, 'success'); + + const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; + const warehouseRoles = employees.filter(item => + item && item.role_type === 'warehouse' && Number(item.id) && + Number(item.store_id) === TEST_WAREHOUSE_ID + ); + const candidateRoleIds = [ ...new Set([ + ...warehouseRoles.map(item => Number(item.id)), + ...FALLBACK_ROLE_IDS, + ].filter(Boolean)) ]; + assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); + + for (const roleId of candidateRoleIds) { + const changeRes = await invokeSystemMethod('user.changeRole', { roleId }, currentToken, EXTRA_HEADERS); + if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) continue; + currentToken = changeRes.body?.data?.token || currentToken; + + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { page: 1, pageSize: 1 }, + where: {}, + }, currentToken, EXTRA_HEADERS); + if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { + return { token: currentToken, roleId }; + } + } + throw new Error(`未找到 warehouse_id=${TEST_WAREHOUSE_ID} 的仓库角色`); +} + +// ──── 获取系统商品 ──── +async function getSystemProducts(token, minCount = 2) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { page: 1, pageSize: 20 }, + where: {}, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + + let list = []; + if (res.body?.data?.data?.list) list = res.body.data.data.list; + else if (res.body?.data?.list) list = res.body.data.list; + + const products = list + .filter(item => Number(item?.id || 0) > 0) + .slice(0, minCount) + .map(item => ({ + id: Number(item.id), + item_name: String(item.item_name || item.name || ''), + item_code: String(item.item_code || ''), + })); + assert.ok(products.length >= minCount, `需至少 ${minCount} 个系统商品,实际只有 ${products.length} 个`); + return products; +} + +// ──── 创建收货单 ──── +async function createReceiving(token) { + const res = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-TX-${Date.now().toString().slice(-6)}`, + loading_method: 'without_pallet', + remark: `transaction集成测试 ${new Date().toISOString()}`, + total_boxes: 1, + total_pallets: 0, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `创建收货单HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `创建收货单失败: ${res.body.message}`); + const receivingId = Number(res.body.id || res.body?.data?.id || 0); + assert.ok(receivingId > 0, '创建收货单无返回ID'); + return receivingId; +} + +// ──── 绑定货主 ──── +async function bindStore(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.bindStore', { + id: receivingId, + store_id: TEST_STORE_ID, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); +} + +// ──── 添加明细 + 修改明细 ──── +async function addAndFillDetail(token, receivingId, product, qty) { + const addRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(addRes.status, 200, `添加明细HTTP失败: ${JSON.stringify(addRes.body)}`); + assert.equal(addRes.body.flag, 'success', `添加明细失败: ${addRes.body.message}`); + const detailId = Number(addRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, `添加明细无返回selectId: ${JSON.stringify(addRes.body)}`); + + const changeRes = await invokeSystemMethod('storage.receiving.detailChange', { + id: detailId, + receiving_id: receivingId, + product_name: product.item_name || '测试商品', + barcode: product.item_code || `TEST-BC-${Date.now()}`, + actual_quantity: qty, + box_quantity: 1, + pallet_quantity: 0, + }, token, EXTRA_HEADERS); + assert.equal(changeRes.status, 200, `修改明细失败: ${JSON.stringify(changeRes.body)}`); + assert.equal(changeRes.body.flag, 'success', `修改明细失败: ${changeRes.body.message}`); + + return detailId; +} + +async function bindDetailProduct(token, detailId, productId) { + const res = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: productId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `绑定商品失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `绑定商品失败: ${res.body.message}`); +} + +// ──── 完成收货 ──── +async function completeReceiving(token, receivingId) { + const res = await invokeSystemMethod('storage.receiving.completeReceiving', { + id: receivingId, + }, token, EXTRA_HEADERS); + assert.equal(res.status, 200, `完成收货HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); +} + +// ──── 快捷入库 ──── +async function quickPutaway(token, receivingId) { + return invokeSystemMethod('storage.inventory.quickPutaway', { + receiving_id: receivingId, + }, token, EXTRA_HEADERS); +} + +describe('test/app/controller/system.storage.transaction.test.js', () => { + let authToken; + let products; + let sequelize; + + before(async function() { + this.timeout(30000); + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + authToken = switched.token; + products = await getSystemProducts(authToken, 2); + + sequelize = new Sequelize(config.database, config.username, config.password, { + host: config.host, + port: config.port, + dialect: 'mysql', + logging: false, + }); + + console.log(`[SETUP] 测试商品: ${products.map(p => `${p.item_name}(${p.id})`).join(', ')}`); + }); + + after(async function() { + if (sequelize) { + await sequelize.close(); + console.log('[TEARDOWN] 数据库连接已关闭'); + } + }); + + // ────────────────────────────────────────────────────── + // 用例 1:快捷入库后 wms_stock_transaction 记录验证 + // ────────────────────────────────────────────────────── + it('should write INBOUND/SCRK records to wms_stock_transaction after quickPutaway', async function() { + this.timeout(60000); + + // === 准备阶段 === + const receivingId = await createReceiving(authToken); + await bindStore(authToken, receivingId); + console.log(`[TX] 收货单 ID: ${receivingId}`); + + const quantities = [ 7, 3 ]; + const detailIds = []; + for (let i = 0; i < 2; i++) { + const detailId = await addAndFillDetail(authToken, receivingId, products[i], quantities[i]); + detailIds.push(detailId); + await bindDetailProduct(authToken, detailId, products[i].id); + console.log(`[TX] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}(${products[i].id}), qty=${quantities[i]}`); + } + + await completeReceiving(authToken, receivingId); + + // 记录入库前的 transaction 最大 ID,用于过滤 + const [ beforeRows ] = await sequelize.query( + 'SELECT COALESCE(MAX(id), 0) AS max_id FROM wms_stock_transaction' + ); + const beforeMaxId = Number(beforeRows[0].max_id); + console.log(`[TX] 入库前 wms_stock_transaction max_id: ${beforeMaxId}`); + + // === 执行入库 === + const res = await quickPutaway(authToken, receivingId); + console.log('[TX] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); + + assert.equal(res.status, 200, `快捷入库HTTP失败: ${JSON.stringify(res.body)}`); + assert.equal(res.body.flag, 'success', `快捷入库flag失败: ${res.body.message}`); + + const putawayData = res.body?.data?.data || res.body?.data || {}; + assert.ok(putawayData.entry_order, '返回中缺少 entry_order'); + const entryOrderId = putawayData.entry_order.id; + const entryOrderCode = putawayData.entry_order.entry_order_code; + console.log(`[TX] 入库单: id=${entryOrderId}, code=${entryOrderCode}`); + + // === 断言:查询 wms_stock_transaction 新增记录 === + const [ txRows ] = await sequelize.query( + 'SELECT * FROM wms_stock_transaction WHERE id > :beforeMaxId AND receiving_id = :receivingId ORDER BY id ASC', + { replacements: { beforeMaxId, receivingId } } + ); + console.log(`[TX] 新增 transaction 记录数: ${txRows.length}`); + for (const row of txRows) { + console.log(`[TX] record id=${row.id}: type=${row.transaction_type}, order_type=${row.order_type}, stock_id=${row.stock_id}, qty=${row.quantity}, entry_order_id=${row.entry_order_id}, warehouse_id=${row.warehouse_id}, store_id=${row.store_id}`); + } + + // 1. 应至少有 2 条记录(每条明细一条) + assert.ok(txRows.length >= 2, `应至少有 2 条 transaction 记录, 实际: ${txRows.length}`); + + // 2. 逐条验证字段 + for (let i = 0; i < txRows.length; i++) { + const row = txRows[i]; + + // transaction_type + assert.equal(row.transaction_type, 'INBOUND', + `record ${row.id}: transaction_type 应为 INBOUND, 实际: ${row.transaction_type}`); + + // order_type + assert.equal(row.order_type, 'SCRK', + `record ${row.id}: order_type 应为 SCRK, 实际: ${row.order_type}`); + + // quantity > 0 + assert.ok(Number(row.quantity) > 0, + `record ${row.id}: quantity 应 > 0, 实际: ${row.quantity}`); + + // stock_id > 0 + assert.ok(Number(row.stock_id) > 0, + `record ${row.id}: stock_id 应 > 0, 实际: ${row.stock_id}`); + + // warehouse_id + assert.equal(Number(row.warehouse_id), TEST_WAREHOUSE_ID, + `record ${row.id}: warehouse_id 应为 ${TEST_WAREHOUSE_ID}, 实际: ${row.warehouse_id}`); + + // entry_order_id 不为空 + assert.ok(Number(row.entry_order_id) > 0, + `record ${row.id}: entry_order_id 应 > 0, 实际: ${row.entry_order_id}`); + + // entry_order_id 与返回一致 + assert.equal(Number(row.entry_order_id), Number(entryOrderId), + `record ${row.id}: entry_order_id(${row.entry_order_id}) 应等于返回值(${entryOrderId})`); + + // receiving_id 与传入一致 + assert.equal(Number(row.receiving_id), Number(receivingId), + `record ${row.id}: receiving_id(${row.receiving_id}) 应等于 ${receivingId}`); + + // order_no 不为空 + assert.ok(row.order_no && row.order_no.length > 0, + `record ${row.id}: order_no 不应为空`); + + // order_no 与返回的 entry_order_code 一致 + assert.equal(row.order_no, entryOrderCode, + `record ${row.id}: order_no(${row.order_no}) 应等于 ${entryOrderCode}`); + + // store_id > 0 + assert.ok(Number(row.store_id) > 0, + `record ${row.id}: store_id 应 > 0, 实际: ${row.store_id}`); + } + + // 3. 验证入库数量与明细匹配 + // 按 stock_id 分组,对比预期数量 + for (let i = 0; i < products.length; i++) { + const stockId = products[i].id; + const expectedQty = quantities[i]; + const matchingRow = txRows.find(r => Number(r.stock_id) === stockId); + if (matchingRow) { + assert.equal(Number(matchingRow.quantity), expectedQty, + `stock_id=${stockId}: quantity(${matchingRow.quantity}) 应等于 ${expectedQty}`); + console.log(`[TX] ✓ stock_id=${stockId} 数量匹配: ${matchingRow.quantity} === ${expectedQty}`); + } else { + console.log(`[TX] ⚠ stock_id=${stockId} 未找到对应 transaction 记录(可能 stock_warehouse.id 不等于传入 product.id)`); + } + } + + console.log(`[TX] ✓ 全部断言通过,共 ${txRows.length} 条 INBOUND/SCRK 记录`); + }); +}); diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js index b948613..fed081b 100644 --- a/test/app/controller/system.storeWarehouse.test.js +++ b/test/app/controller/system.storeWarehouse.test.js @@ -14,6 +14,18 @@ const EXTRA_HEADERS = { describe('test/app/controller/system.storeWarehouse.test.js', () => { const METHOD_PREFIX = 'storeWarehouse.store'; const REMOVED_SETTING_METHOD_PREFIX = 'setting.storeWarehouse.store'; + const REMOVED_SETTING_SNAKE_METHOD_PREFIX = 'setting.store_warehouse'; + const REMOVED_LEGACY_METHODS = [ + 'list', + 'sign', + 'rename', + 'unbind', + 'getPolicyConfig', + 'getPolicyConfigFields', + 'savePolicyConfig', + 'deleteQimenConfig', + ]; + const REMOVED_COMPAT_SETTING_METHODS = [ 'list', 'sign', 'rename', 'unbind' ]; let token = ''; before(async () => { @@ -31,9 +43,31 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.equal(res.body.flag, 'success'); assert.equal(res.body.code, 200); assert.ok(Array.isArray(res.body?.data?.list), 'storeWarehouse.store.list 应返回 list'); + if (res.body.data.list.length > 0) { + assert.ok(!Object.prototype.hasOwnProperty.call(res.body.data.list[0], 'apiConfig'), '首项不应包含 apiConfig 字段'); + assert.ok(!Object.prototype.hasOwnProperty.call(res.body.data.list[0], 'api_config'), '首项不应包含 api_config 字段'); + assert.ok(!Object.prototype.hasOwnProperty.call(res.body.data.list[0], 'qimenConfig'), '首项不应包含 qimenConfig 字段'); + } assert.equal(typeof res.body?.data?.total, 'number'); }); + it('should not expose removed legacy storeWarehouse.* methods', async () => { + for (const methodName of REMOVED_LEGACY_METHODS) { + const removedRes = await invokeSystemMethod(`storeWarehouse.${methodName}`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(removedRes.status, 500, `legacy method ${methodName} should fail`); + assert.equal(removedRes.body.flag, 'failure'); + assert.equal(Number(removedRes.body.code), 500); + assert.match( + String(removedRes.body.message || ''), + new RegExp(`服务 storeWarehouse 不存在|方法 ${methodName} 不存在`) + ); + } + }); + it('should not expose removed setting.storeWarehouse.store.list alias', async () => { const removedRes = await invokeSystemMethod(`${REMOVED_SETTING_METHOD_PREFIX}.list`, { page: 1, @@ -46,6 +80,20 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(removedRes.body.message || ''), /服务 setting\.storeWarehouse\.store 不存在/); }); + it('should not expose removed setting.store_warehouse.* compatibility methods', async () => { + for (const methodName of REMOVED_COMPAT_SETTING_METHODS) { + const removedRes = await invokeSystemMethod(`${REMOVED_SETTING_SNAKE_METHOD_PREFIX}.${methodName}`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(removedRes.status, 500, `compat setting.store_warehouse.${methodName} should fail`); + assert.equal(removedRes.body.flag, 'failure'); + assert.equal(Number(removedRes.body.code), 500); + assert.match(String(removedRes.body.message || ''), /服务 setting\.store_warehouse 不存在|方法 .* 不存在/); + } + }); + it('should expose standalone storeWarehouse.store.sign parameter validation', async () => { const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { print_quantity: 0, @@ -75,6 +123,24 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /remask|id|counterparty_id|store_id|warehouse_id/); }); + it('should expose standalone storeWarehouse.store.adjustPrintQuantity with auth or validation response', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.adjustPrintQuantity`, { + change_quantity: 1, + }, token, EXTRA_HEADERS); + + assert.notEqual(res.status, 500, '新接口不应是未注册或方法不存在'); + + if (res.status === 403) { + assert.match(String(res.body?.message || ''), /无权访问|未授权|权限/); + return; + } + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.ok([ 400, 403, 404 ].includes(Number(res.body.code))); + assert.match(String(res.body.message || ''), /reason|id|counterparty_id|store_id|warehouse_id|无权访问|不存在/); + }); + it('should expose standalone storeWarehouse.store.getPolicyConfig parameter validation', async () => { const res = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, {}, token, EXTRA_HEADERS); @@ -84,6 +150,26 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); }); + it('should expose standalone storeWarehouse.store.getPolicyConfigFields as a metadata list', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfigFields`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(Number(res.body.code), 200); + assert.ok(Array.isArray(res.body?.data), '字段信息接口应直接返回列表'); + assert.ok(res.body.data.length > 0, '字段信息列表不能为空'); + assert.ok(res.body.data.every(item => item && typeof item === 'object' && item.key && item.name && item.type), '每个字段项都应包含 key/name/type'); + + const printRechargePriceField = res.body.data.find(item => item.key === 'print_recharge_price'); + assert.ok(printRechargePriceField, '字段信息应包含 print_recharge_price'); + assert.equal(printRechargePriceField.name, '面单充值元/单'); + assert.equal(printRechargePriceField.type, 'number'); + assert.equal(Number(printRechargePriceField.default || 0), 0); + assert.equal(Number(printRechargePriceField.precision), 2); + assert.equal(Number(printRechargePriceField.step), 0.01); + assert.match(String(printRechargePriceField.description || ''), /支持\s*2\s*位小数/); + }); + it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => { const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {}, token, EXTRA_HEADERS); @@ -93,13 +179,13 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); }); - it('should expose standalone storeWarehouse.store.saveQimenConfig parameter validation', async () => { - const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, {}, token, EXTRA_HEADERS); + it('should expose standalone storeWarehouse.store.saveApiConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveApiConfig`, {}, token, EXTRA_HEADERS); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(Number(res.body.code), 400); - assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/); + assert.match(String(res.body.message || ''), /interface_type_id|id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/); }); it('should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation', async () => { @@ -111,8 +197,8 @@ describe('test/app/controller/system.storeWarehouse.test.js', () => { assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); }); - it('should expose standalone storeWarehouse.store.listQimenConfig parameter validation', async () => { - const res = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, {}, token, EXTRA_HEADERS); + it('should expose standalone storeWarehouse.store.listApiConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.listApiConfig`, {}, token, EXTRA_HEADERS); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); diff --git a/test/app/service/systemMethods/warehouse.auth.test.js b/test/app/service/systemMethods/warehouse.auth.test.js new file mode 100644 index 0000000..afd06e4 --- /dev/null +++ b/test/app/service/systemMethods/warehouse.auth.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const WarehouseService = require('../../../../app/service/systemMethods/warehouse'); + +function createService(userOverrides = {}, permissionRows = []) { + const responseHeaders = {}; + + const ctx = { + header: { + platform: 'web', + project: 'all', + }, + set(name, value) { + responseHeaders[name] = value; + }, + app: { + config: { + jwt: { + secret: 'test-secret', + expiresIn: '3600', + }, + }, + jwt: { + verify() { + return { + id: 1, + exp: Math.floor(Date.now() / 1000) + 3600, + }; + }, + sign() { + return 'refreshed-token'; + }, + }, + }, + model: { + Permission: { + async findAll({ where = {} } = {}) { + const ids = Array.isArray(where.id) ? where.id.map(Number) : []; + return permissionRows.filter(row => ids.length === 0 || ids.includes(Number(row.id))); + }, + }, + }, + service: { + systems: { + auth: { + user: { + async findById() { + return { + id: 1, + username: 'tester', + status: 1, + permissions: [], + ...userOverrides, + }; + }, + }, + }, + }, + }, + }; + + return { + service: new WarehouseService(ctx), + ctx, + responseHeaders, + }; +} + +describe('test/app/service/systemMethods/warehouse.auth.test.js', () => { + it('should deny getAreaRacks when explicit api permission is missing', async () => { + const { service } = createService(); + + const result = await service.checkAuth('warehouse', 'getAreaRacks', 'Bearer test-token'); + + assert.equal(result.status, 403); + assert.equal(result.message, '无权访问该接口'); + }); + + it('should allow getAreaRacks when user has wildcard permissions', async () => { + const { service } = createService({ permissions: '*' }); + + const result = await service.checkAuth('warehouse', 'getAreaRacks', 'Bearer test-token'); + + assert.equal(result.status, 200); + assert.equal(result.message, 'ok'); + }); + + it('should allow getAreaRacks when permission payload contains matching path or id', async () => { + const scenarios = [ + createService({ permissions: [ 'warehouse.getAreaRacks' ] }), + createService({ permissions: '["warehouse.getAreaRacks"]' }), + createService({ permissions: [{ path: 'warehouse.getAreaRacks' }] }), + createService({ permissions: [ 5161 ] }, [{ id: 5161, path: 'warehouse.getAreaRacks', status: 1 }]), + ]; + + for (const { service } of scenarios) { + const result = await service.checkAuth('warehouse', 'getAreaRacks', 'Bearer test-token'); + assert.equal(result.status, 200); + assert.equal(result.message, 'ok'); + } + }); +}); diff --git a/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js b/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js new file mode 100644 index 0000000..96985f0 --- /dev/null +++ b/test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js @@ -0,0 +1,199 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StoreWarehouseService = require('../../../../app/service/systems/store_warehouse'); + +describe('test/app/service/systems/store_warehouse.adjustPrintQuantity.test.js', () => { + const buildContext = () => { + const capture = { + relationPatch: null, + changeLogPayload: null, + noticePayload: null, + }; + const transaction = { + committed: false, + rolledBack: false, + async commit() { + this.committed = true; + }, + async rollback() { + this.rolledBack = true; + }, + }; + const relation = { + id: 88, + store_id: 100000, + warehouse_id: 200000, + print_quantity: 10, + async update(patch) { + capture.relationPatch = patch; + this.print_quantity = patch.print_quantity; + }, + }; + + const ctx = { + app: { + config: {}, + }, + user: { + id: 9001, + store_id: 200000, + employees_name: '仓管A', + store_name: '测试仓', + }, + model: { + transaction: async () => transaction, + Store: { + async findOne({ where }) { + if (Number(where.id) === 200000) { + return { + id: 200000, + company_name: '测试仓', + project: 'warehouse', + status: 1, + }; + } + return { + id: 100000, + company_name: '测试货主', + project: 'store', + status: 1, + }; + }, + }, + StoreWarehouse: { + async findOne() { + return relation; + }, + async findByPk(id) { + return { + get() { + return { + id, + store_id: 100000, + warehouse_id: 200000, + auth_status: 2, + apply_reason: '', + review_comment: '', + apply_time: new Date('2026-04-07T08:00:00.000Z'), + review_time: new Date('2026-04-07T08:00:00.000Z'), + auth_start: new Date('2026-04-07T08:00:00.000Z'), + auth_end: new Date('2026-12-31T23:59:59.000Z'), + actual_end: null, + print_quantity: relation.print_quantity, + applied_by: 9001, + reviewed_by: 9001, + ended_by: null, + store_remask: '测试货主别名', + warehouse_remask: '测试仓别名', + use_status: 1, + policy_config: null, + store: { + id: 100000, + company_name: '测试货主', + }, + warehouse: { + id: 200000, + company_name: '测试仓', + }, + }; + }, + }; + }, + }, + StoreWarehousePrintQuantityLog: { + async create(payload) { + capture.changeLogPayload = payload; + return { + id: 556, + get() { + return { + ...payload, + id: 556, + created_at: new Date('2026-04-07T09:00:00.000Z'), + }; + }, + }; + }, + }, + }, + service: { + systems: { + notice: { + async send(options) { + capture.noticePayload = options; + return { + success: true, + data: { + sentCount: 0, + }, + }; + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + ctx.app.model = ctx.model; + + return { + capture, + transaction, + ctx, + }; + }; + + it('should require reason when manually adjusting print quantity', async () => { + const { ctx } = buildContext(); + const service = new StoreWarehouseService(ctx); + service.getSingleQimenConfig = async () => null; + + await assert.rejects(async () => { + await service.adjustPrintQuantity({ + id: 88, + change_quantity: 5, + }); + }, /reason 参数不能为空/); + }); + + it('should overwrite target balance instead of incrementing it when manually adjusting print quantity', async () => { + const { ctx, capture, transaction } = buildContext(); + const service = new StoreWarehouseService(ctx); + service.getSingleQimenConfig = async () => null; + + const result = await service.adjustPrintQuantity({ + id: 88, + change_quantity: 7, + reason: '人工覆盖余额测试', + business_type: 'order_express', + business_id: 321, + }); + + assert.equal(result.code, 200); + assert.equal(Number(result.data.contract.id), 88); + assert.equal(Number(result.data.contract.print_quantity), 7); + assert.equal(Number(result.data.change_log.change_quantity), -3); + assert.equal(Number(result.data.change_log.balance_before), 10); + assert.equal(Number(result.data.change_log.balance_after), 7); + assert.equal(String(result.data.change_log.reason || ''), '人工覆盖余额测试'); + + assert.deepEqual(capture.relationPatch, { + print_quantity: 7, + }); + assert.equal(String(capture.changeLogPayload.change_type || ''), 'manual_adjust'); + assert.equal(Number(capture.changeLogPayload.change_quantity), -3); + assert.equal(Number(capture.changeLogPayload.balance_before), 10); + assert.equal(Number(capture.changeLogPayload.balance_after), 7); + assert.equal(String(capture.changeLogPayload.reason || ''), '人工覆盖余额测试'); + assert.equal(String(capture.noticePayload.event || ''), 'store_warehouse_print_quantity_adjusted'); + assert.equal(String(capture.noticePayload.businessName || ''), 'store_warehouse'); + assert.equal(Number(capture.noticePayload.metadata.changeQuantity), -3); + assert.equal(transaction.committed, true); + assert.equal(transaction.rolledBack, false); + }); +}); diff --git a/wms.code-workspace b/wms.code-workspace index 61e510d..cea87c9 100644 --- a/wms.code-workspace +++ b/wms.code-workspace @@ -5,5 +5,6 @@ } ], "settings": { + "workbench.browser.enableChatTools": false } } \ No newline at end of file