From 57f1f44baeff01bc57f0c78865b6c6b4ad68ada7 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 9 Apr 2026 15:45:14 +0800 Subject: [PATCH] feat: sync wms updates --- .github/agents/开发.agent.md | 123 ++++- app/model/stock_transaction.js | 20 + app/service/systemMethods/index.js | 35 +- app/service/systemMethods/storage/entry.js | 5 +- .../systemMethods/storeWarehouse/store.js | 286 +++++++++++- app/service/systems/auth/user.js | 10 +- app/service/systems/license_plate.js | 255 ++++++++++ app/service/systems/stock_store.js | 380 ++++++++++----- app/service/systems/stock_transaction.js | 78 ++++ app/service/systems/storage/entry.js | 135 +++++- app/service/systems/storage/inventory.js | 24 +- app/service/systems/storage/receiving.js | 55 ++- app/service/systems/store_warehouse.js | 439 ++++++++++++++++++ app/service/systems/upload.js | 68 ++- config/config.default.js | 8 +- ...0408140000-create-wms-stock-transaction.js | 20 + ...apshot-columns-to-wms-stock-transaction.js | 63 +++ docs/qimen-interface-reference.md | 226 +++++++++ methods/changes/system.json | 45 ++ methods/system.json | 79 +++- .../system.storage.transaction.test.js | 16 + .../storeWarehouse/store.test.js | 157 +++++++ .../systems/auth.user.loginWechatCode.test.js | 53 +++ .../app/service/systems/license_plate.test.js | 75 +++ .../systems/stock_transaction.create.test.js | 85 ++++ .../systems/storage.entry.cancel.test.js | 171 +++++++ .../systems/storage.receiving.report.test.js | 160 ++++++- test/app/service/systems/upload.test.js | 55 +++ 28 files changed, 2909 insertions(+), 217 deletions(-) create mode 100644 app/service/systems/license_plate.js create mode 100644 database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js create mode 100644 docs/qimen-interface-reference.md create mode 100644 test/app/service/systemMethods/storeWarehouse/store.test.js create mode 100644 test/app/service/systems/license_plate.test.js create mode 100644 test/app/service/systems/stock_transaction.create.test.js create mode 100644 test/app/service/systems/storage.entry.cancel.test.js diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index ee288e4..e1f0122 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -41,7 +41,128 @@ model: GPT-5.3-Codex (copilot) - `npm run permission:sync:system-api` - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” 7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 -8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,如果要修改的文件大部分缺失注释,必须先驳回到调度 agent 让其补齐拆解分析再修改,禁止直接改代码后再补注释的流程 +8. **所有修改的函数必须要有 JSDoc 注释**,必要时补充说明参数、返回值、错误码等信息;新增或修改的 JSDoc 必须使用中文描述,参数名/返回值说明也必须中文化,避免再出现英文 JSDoc;如果修改的方法中没有注释,必须补充完整的 JSDoc 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDoc 注释后再提交 +9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 +10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 +11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 +12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 + +## 关键定位地图 + +### 1) 接口入口与 Method 路由 + +- `/system`:Web / PDA 统一接口(POST) +- `/qimen`:奇门接口(POST) +- 路由说明文档:`AI_METHOD_ROUTING.md` + +### 2) 文档单一事实来源(SSOT) + +- `methods/system.json` +- `methods/qimen.json` + +### 3) App 能力入口 + +- `app.js` +- `app/extend/application.js` + +### 4) 常用开发辅助文件 + +- `app/service/main.js`:where 统一处理、权限校验等公共逻辑 +- `test/app/controller/system.user.info.web.test.js` +- `test/app/controller/system.user.changeRole.test.js` + +## 推荐工作流 + +### 代码修改 / 修 bug + +1. 先定位 method 与实现链路 +2. 如需测试设计或补回归,先委派 `wms-test-agent` 补失败用例 +3. 做最小根因修复 +4. 跑相关检查验证 +5. 若涉及接口变更(参数、响应、新增、删除),**必须委派 `wms-doc-agent`** 同步 `methods/*.json`、追加 `methods/changes/*.json` 变更记录 + +### 接口参数变更 + +```powershell +node .\script\tmp-struct-system-params.cjs +``` + +然后人工补齐: +- `description` +- `response` +- `errors` +- 特殊枚举值与业务约束 + +## 建议提问方式 + +```text +请使用 wms-dev-agent 帮我: +1) 定位这个 method / controller / service 的实现链路 +2) 修复问题并说明最小代码改动 +3) 输出验证结果;若需要补测试,请转给 `wms-test-agent` +``` + +## 输出要求 + +- 所有回复建议以 `[Dev]` 开头 +- 先给结论,再给定位链路、修改点、验证结果 +- 涉及接口改动时,明确说明已委派 `wms-doc-agent` 完成文档同步(或提示调用方需要委派) + +## 结论 + +通用开发能力文档已统一收口到本 Agent;测试相关请求请转给 `wms-test-agent`,工具箱只保留“开发相关必须使用 `wms-dev-agent`”的规则入口。 + +## 代码风格 + +- 先定位代码真实实现与调用链 +- 只改最小必要代码,避免大面积重构 +- 改代码后必须跑相关测试验证 +- 涉及接口变更必须委派 `wms-doc-agent` 同步文档,本 agent 不直接修改文档文件 +- 除了json,其他字符串输出必须使用模板字符串,必要时分行保持可读性 +- --- +name: wms-dev-agent +description: "Use when the user asks about 开发、改代码、修 bug、调试、接口定位、method routing、where 规范、权限映射、Egg.js service 分层。专用于 WMS 通用开发与代码实现。" +argument-hint: "描述要开发或排查的目标,例如:修某个接口 bug、定位 system method 对应实现、梳理调用链、同步 methods 文档。" +tools: ['read', 'search', 'edit', 'execute', 'todo'] +model: GPT-5.3-Codex (copilot) +--- + +# WMS 开发代理(`wms-dev-agent`) + +## 适用范围 + +- 项目根目录:`D:\wms` +- 主要开发目录:`app/`、`methods/`、`docs/` +- 适用于 Egg.js 业务开发、接口联调与文档同步;如重点是测试设计、回归验证、TDD,请转给 `wms-test-agent` + +## 何时必须使用本 Agent + +出现以下任一诉求时,必须使用 `wms-dev-agent`: + +- 改代码 / 修 bug / 重构 / 性能优化 +- 定位 `/system` / `/qimen` method 映射关系 +- 排查 `where` 规则、权限映射、分层职责问题 +- 分析 `app.js` / `app/extend/application.js` / `systemMethods` / `systems` 调用链 +- 如诉求重点是测试设计、回归验证、TDD,请委派给 `wms-test-agent` +- 如涉及文档同步,委派给 `wms-doc-agent` + +## 开发规则 + +1. **先定位后修改**:先找 `controller / systemMethods / systems / model` 的实际链路 +2. **分层约定必须保持**: + - `systemMethods` 只保留出口包装层 + - 业务逻辑统一下沉到 `systems` +3. **如诉求重点是测试设计、补回归、接口验证或 TDD,委派给** `wms-test-agent` +4. **禁止直接修改文档文件**:`methods/*.json`、`methods/changes/*.json`、`docs/*.md` 的所有新增与修改必须委派给 `wms-doc-agent` 完成,`wms-dev-agent` 只负责代码文件(`app/`、`config/`、`database/`、`test/`) +5. **where 规则统一走** `app/service/main.js` 的 `prepareWhereContext(data, options)` +6. **新建接口时,必须先判断是通用接口还是需授权接口**: + - 先明确 `isNeedAuth`,代码实现完成后委派 `wms-doc-agent` 同步 `methods/system.json` 并追加变更记录 + - 若为需授权接口,必须优先通过既有同步流程 / 标准方式补齐权限记录(如 `wms_permission`),必要时使用: + - `npm run permission:sync:system-api -- --dry-run` + - `npm run permission:sync:system-api` + - **绝对不能直接扩大任何角色的授权范围**,不得直接改 `wms_role.permissions` 或其他角色授权绑定来“顺手放开权限” +7. **必须做验证**:改代码后跑相关检查,确认响应结构与文档一致 +8. **所有修改的函数必须要有 JSDOC 注释**,必要时补充说明参数、返回值、错误码等信息,如果修改的方法中没有注释,必须补充完整的 JSDOC 注释后再提交,严禁入参与返回值都没有注释的函数存在于代码中,非本次修改的函数如果没有注释,除非有明确的理由,否则也必须补充完整的 JSDOC 注释后再提交 9. **method入参必须解构再传入service **,禁止直接把 method 入参对象传给 service,必须先在 method 层解构出具体参数,再传给 service,保持层与层之间的清晰边界和职责分离,如果拆解参数过多,可以先在 controller 层做多步骤访问service方法处理,但是必须在service层处理,禁止在method层调用method层。 10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js index 88ddf39..996d3ab 100644 --- a/app/model/stock_transaction.js +++ b/app/model/stock_transaction.js @@ -45,6 +45,26 @@ module.exports = app => { allowNull: false, comment: '变动数量(正数)', }, + before_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, batch_no: { type: STRING(100), allowNull: true, diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 82f4f68..9797138 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -3,12 +3,17 @@ const MainService = require('../main'); class indexService extends MainService { + /** + * 初始化基础方法的免登录、免权限、免鉴权和免日志配置。 + * + * @param {Egg.Context} ctx 上下文对象 + */ constructor(ctx) { super(ctx); const _noNeedLogin = 'getI18nMessage,putI18nCollect'; - const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes'; + const _noNeedRight = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getCOSUploadConfig,uploadSuccessNotify,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate'; const _noNeedLog = '*'; - const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes'; + const _noNeedAuth = 'getI18nMessage,putI18nCollect,fastWhereTree,loadStores,getImages,getMessageDetail,searchSpace,listInterfaceTypes,recognizeLicensePlate'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } async fastWhereTree(data) { @@ -38,6 +43,32 @@ class indexService extends MainService { const result = await service.systems.upload.uploadSuccessNotify(data); return this.success('ok', { data: result, code: 200 }); } + /** + * 识别车牌号码。 + * + * @param {Object} data 请求参数 + * @param {string} data.base64 base64 图片 + * @param {string} [data.imageBase64] 兼容的 base64 字段 + * @param {string} [data.image_base64] 兼容的 base64 字段 + * @returns {Promise} 识别结果 + */ + async recognizeLicensePlate(data) { + const { service, ctx } = this; + const { base64 = '', imageBase64 = '', image_base64 = '' } = data || {}; + const imageBase64Value = String(base64 || imageBase64 || image_base64 || '').trim(); + + if (!imageBase64Value) { + return this.fail('base64 图片不能为空', { code: 400 }); + } + + try { + const result = await service.systems.licensePlate.recognizeLicensePlate(imageBase64Value); + return this.success('ok', { data: result, code: 200 }); + } catch (error) { + ctx.logger.error('车牌识别失败:', error); + return this.fail(error.message || '车牌识别失败', { code: 500 }); + } + } async ReferenceFile(data) { const { service } = this; const result = await service.systems.file.ReferenceFile(data); diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index 8350116..3b808cd 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -52,7 +52,10 @@ class entryService extends MainService { /** * 作废入库单。 - * @param {Object} data 请求体 + * 支持传入单个 id 或批量 ids,保持透传给业务层处理。 + * @param {Object} data 请求体 + * @param {number} [data.id] 单个入库单ID + * @param {number[]} [data.ids] 批量入库单ID数组 * @return {Promise} 统一 success 包装 */ async cancel(data = {}) { diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js index c4a7635..12394fd 100644 --- a/app/service/systemMethods/storeWarehouse/store.js +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -2,7 +2,27 @@ const MainService = require('../../main'); + +/** + * 规范仓库配置方法入参,避免把原始引用直接传给下游服务。 + * + * @param {Object} data 请求数据。 + * @return {Object} 复制后的请求数据。 + */ +function normalizeStoreWarehousePayload(data) { + if (!data || typeof data !== 'object' || Array.isArray(data)) { + return {}; + } + + return { ...data }; +} + class StoreWarehouseStoreService extends MainService { + /** + * 创建一个仓库配置 store 服务。 + * + * @param {Object} ctx 上下文对象。 + */ constructor(ctx) { super(ctx); const _noNeedLogin = ''; @@ -12,60 +32,290 @@ class StoreWarehouseStoreService extends MainService { this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } - async callSystemStoreWarehouse(methodName, data = {}, defaultMessage) { - const { service } = this; + /** + * 获取签约列表。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ + async list(data = {}) { + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.list !== 'function') { + return this.fail('获取签约列表失败', { + code: 500, + }); + } + try { - const result = await service.systems.storeWarehouse[methodName](data); + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.list(payload); return this.success('ok', result); } catch (error) { - return this.fail(error.message || defaultMessage, { + return this.fail(error.message || '获取签约列表失败', { code: Number(error.code) || 500, }); } } - async list(data = {}) { - return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); - } - + /** + * 发起签约。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async sign(data = {}) { - return this.callSystemStoreWarehouse('sign', data, '签约失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.sign !== 'function') { + return this.fail('签约失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.sign(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '签约失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 修改签约名称。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async rename(data = {}) { - return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.rename !== 'function') { + return this.fail('修改签约名称失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.rename(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '修改签约名称失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 解除签约。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async unbind(data = {}) { - return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.unbind !== 'function') { + return this.fail('解除签约失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.unbind(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '解除签约失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 人工调整面单余额。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async adjustPrintQuantity(data = {}) { - return this.callSystemStoreWarehouse('adjustPrintQuantity', data, '人工调整面单余额失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.adjustPrintQuantity !== 'function') { + return this.fail('人工调整面单余额失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.adjustPrintQuantity(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '人工调整面单余额失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 获取合约策略配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async getPolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.getPolicyConfig !== 'function') { + return this.fail('获取合约策略配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.getPolicyConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取合约策略配置失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 获取合约策略字段信息。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async getPolicyConfigFields(data = {}) { - return this.callSystemStoreWarehouse('getPolicyConfigFields', data, '获取合约策略字段信息失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.getPolicyConfigFields !== 'function') { + return this.fail('获取合约策略字段信息失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.getPolicyConfigFields(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取合约策略字段信息失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 保存合约策略配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async savePolicyConfig(data = {}) { - return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.savePolicyConfig !== 'function') { + return this.fail('保存合约策略配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.savePolicyConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存合约策略配置失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 获取接口配置列表。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async listApiConfig(data = {}) { - return this.callSystemStoreWarehouse('listApiConfig', data, '获取接口配置列表失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.listApiConfig !== 'function') { + return this.fail('获取接口配置列表失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.listApiConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取接口配置列表失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 保存接口配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async saveApiConfig(data = {}) { - return this.callSystemStoreWarehouse('saveApiConfig', data, '保存接口配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.saveApiConfig !== 'function') { + return this.fail('保存接口配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.saveApiConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '保存接口配置失败', { + code: Number(error.code) || 500, + }); + } } + /** + * 删除奇门接口配置。 + * + * @param {Object} data 请求数据。 + * @return {Promise} 统一响应结果。 + */ async deleteQimenConfig(data = {}) { - return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除接口配置失败'); + const targetService = this.service && this.service.systems && this.service.systems.storeWarehouse; + + if (!targetService || typeof targetService.deleteQimenConfig !== 'function') { + return this.fail('删除接口配置失败', { + code: 500, + }); + } + + try { + const payload = normalizeStoreWarehousePayload(data); + const result = await targetService.deleteQimenConfig(payload); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '删除接口配置失败', { + code: Number(error.code) || 500, + }); + } } } diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index e4db6bb..9e10c2f 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -614,6 +614,12 @@ class UserService extends Service { return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; } + /** + * 等待微信登录事件并解析事件中的 ye4s 用户 ID。 + * @param {string} clientCode 客户端编码 + * @param {number} timeoutMs 等待超时时间,单位为毫秒 + * @return {Promise} 事件监听结果 + */ async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { const { app } = this; const normalizedClientCode = this.parseWechatBindCode(clientCode); @@ -634,7 +640,7 @@ class UserService extends Service { let settled = false; let timer = null; - function onMessage(messageChannel, message) { + const onMessage = (messageChannel, message) => { if (messageChannel !== channel) { return; } @@ -651,7 +657,7 @@ class UserService extends Service { event: eventData, ye4s_user_id: ye4sUserId, }); - } + }; function onError(error) { app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); diff --git a/app/service/systems/license_plate.js b/app/service/systems/license_plate.js new file mode 100644 index 0000000..bb761b1 --- /dev/null +++ b/app/service/systems/license_plate.js @@ -0,0 +1,255 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('crypto'); +const https = require('https'); + +const OCR_HOST = 'ocr.tencentcloudapi.com'; +const OCR_SERVICE = 'ocr'; +const OCR_VERSION = '2018-11-19'; +const OCR_ACTION = 'LicensePlateOCR'; +const MAX_IMAGE_BYTES = 7 * 1024 * 1024; + +class LicensePlateService extends Service { + /** + * 获取腾讯云公共配置。 + * + * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, + * 以保证历史配置方式仍然可用。 + * + * @returns {Object} 腾讯云公共配置对象 + */ + getTencentCloudConfig() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return { + appId: tencentCloudConfig.appId ?? cosConfig.appId, + secretId: tencentCloudConfig.secretId ?? cosConfig.secretId, + secretKey: tencentCloudConfig.secretKey ?? cosConfig.secretKey, + }; + } + + /** + * 获取腾讯云 OCR 的默认区域。 + * + * @returns {string} 腾讯云区域标识 + */ + getTencentCloudRegion() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return tencentCloudConfig.region || cosConfig.region || 'ap-guangzhou'; + } + + /** + * 规范化并校验 base64 图片。 + * + * @param {string} imageBase64 前端传入的 base64 图片 + * @returns {{ base64: string, buffer: Buffer, size: number }} 规范化后的图片信息 + */ + normalizeBase64Image(imageBase64) { + const rawValue = String(imageBase64 || '').trim(); + + if (!rawValue) { + throw new Error('base64 图片不能为空'); + } + + const normalizedBase64 = rawValue + .replace(/^data:[^;]+;base64,/i, '') + .replace(/\s+/g, ''); + + if (!normalizedBase64) { + throw new Error('base64 图片不能为空'); + } + + if (!/^[A-Za-z0-9+/=]+$/.test(normalizedBase64)) { + throw new Error('base64 图片格式不正确'); + } + + const buffer = Buffer.from(normalizedBase64, 'base64'); + + if (!buffer.length) { + throw new Error('base64 图片解码失败'); + } + + if (buffer.length > MAX_IMAGE_BYTES) { + throw new Error('图片大小不能超过 7MB'); + } + + const normalizedWithoutPadding = normalizedBase64.replace(/=+$/u, ''); + const roundTripWithoutPadding = buffer.toString('base64').replace(/=+$/u, ''); + + if (normalizedWithoutPadding !== roundTripWithoutPadding) { + throw new Error('base64 图片格式不正确'); + } + + return { + base64: normalizedBase64, + buffer, + size: buffer.length, + }; + } + + /** + * 生成腾讯云 TC3 请求签名。 + * + * @param {Object} options 请求参数 + * @param {string} options.action 腾讯云动作名 + * @param {string} options.service 腾讯云服务名 + * @param {string} options.version 腾讯云接口版本 + * @param {string} options.region 腾讯云区域 + * @param {Object} options.payload 请求体 + * @returns {{ requestOptions: Object, payloadString: string }} 请求配置 + */ + buildTencentCloudRequest({ action, service, version, region, payload }) { + const { secretId, secretKey } = this.getTencentCloudConfig(); + + if (!secretId || !secretKey) { + throw new Error('腾讯云密钥未配置'); + } + + const timestamp = Math.floor(Date.now() / 1000); + const date = new Date(timestamp * 1000).toISOString().slice(0, 10); + const payloadString = JSON.stringify(payload || {}); + const hashedRequestPayload = crypto.createHash('sha256').update(payloadString).digest('hex'); + const canonicalHeaders = `content-type:application/json; charset=utf-8\nhost:${OCR_HOST}\n`; + const signedHeaders = 'content-type;host'; + const canonicalRequest = [ + 'POST', + '/', + '', + canonicalHeaders, + signedHeaders, + hashedRequestPayload, + ].join('\n'); + const credentialScope = `${date}/${service}/tc3_request`; + const stringToSign = [ + 'TC3-HMAC-SHA256', + timestamp, + credentialScope, + crypto.createHash('sha256').update(canonicalRequest).digest('hex'), + ].join('\n'); + + const secretDate = crypto.createHmac('sha256', `TC3${secretKey}`).update(date).digest(); + const secretService = crypto.createHmac('sha256', secretDate).update(service).digest(); + const secretSigning = crypto.createHmac('sha256', secretService).update('tc3_request').digest(); + const signature = crypto.createHmac('sha256', secretSigning).update(stringToSign).digest('hex'); + + const authorization = `TC3-HMAC-SHA256 Credential=${secretId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`; + + return { + payloadString, + requestOptions: { + hostname: OCR_HOST, + method: 'POST', + path: '/', + headers: { + Authorization: authorization, + 'Content-Type': 'application/json; charset=utf-8', + Host: OCR_HOST, + 'X-TC-Action': action, + 'X-TC-Version': version, + 'X-TC-Timestamp': String(timestamp), + 'X-TC-Region': region, + }, + }, + }; + } + + /** + * 发送腾讯云请求并解析 JSON 响应。 + * + * @param {Object} requestConfig 请求配置 + * @param {Object} requestConfig.requestOptions https 请求参数 + * @param {string} requestConfig.payloadString 请求体字符串 + * @returns {Promise} 腾讯云响应对象 + */ + async sendTencentCloudRequest(requestConfig) { + const { requestOptions, payloadString } = requestConfig; + + const responseText = await new Promise((resolve, reject) => { + const request = https.request(requestOptions, response => { + response.setEncoding('utf8'); + let responseBody = ''; + + response.on('data', chunk => { + responseBody += chunk; + }); + + response.on('end', () => { + resolve(responseBody); + }); + }); + + request.on('error', reject); + request.setTimeout(30000, () => { + request.destroy(new Error('腾讯云车牌识别请求超时')); + }); + request.write(payloadString); + request.end(); + }); + + let parsedResponse; + try { + parsedResponse = JSON.parse(responseText); + } catch (error) { + throw new Error(`腾讯云响应解析失败: ${error.message}`); + } + + const responsePayload = parsedResponse && parsedResponse.Response ? parsedResponse.Response : parsedResponse; + + if (responsePayload && responsePayload.Error) { + const { Code = 'TencentCloudError', Message = '腾讯云接口调用失败' } = responsePayload.Error; + throw new Error(`${Code}: ${Message}`); + } + + return parsedResponse; + } + + /** + * 识别车牌号码。 + * + * @param {string} imageBase64 前端传入的 base64 图片 + * @returns {Promise} 车牌识别结果 + */ + async recognizeLicensePlate(imageBase64) { + const { base64, size } = this.normalizeBase64Image(imageBase64); + const region = this.getTencentCloudRegion(); + const requestConfig = this.buildTencentCloudRequest({ + action: OCR_ACTION, + service: OCR_SERVICE, + version: OCR_VERSION, + region, + payload: { + ImageBase64: base64, + }, + }); + + const response = await this.sendTencentCloudRequest(requestConfig); + return this.formatLicensePlateResult(response); + } + + /** + * 统一整理腾讯云车牌识别响应。 + * + * @param {Object} response 腾讯云响应 + * @returns {Object} 归一化后的识别结果 + */ + formatLicensePlateResult(response) { + const responseData = response && response.Response ? response.Response : response || {}; + const licensePlate = String( + responseData.LicensePlate + || responseData.Number + || responseData.PlateNumber + || responseData.CarPlateNumber + || '' + ).trim(); + + return { + licensePlate, + }; + } +} + +module.exports = LicensePlateService; \ No newline at end of file diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index cbe2292..42e9ec3 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -413,6 +413,32 @@ class stockStoreService extends Service { app.logger.warn(`[缓存清理失败] 商品 ${itemId}`, error.message); } } + + /** + * 在给定事务中执行库存写操作,未传入事务时自动创建并提交回滚。 + * + * @param {Object} externalTransaction 外部传入的数据库事务 + * @param {Function} handler 业务处理函数 + * @return {Promise<*>} 业务处理结果 + */ + async _runWithTransaction(externalTransaction, handler) { + const { ctx } = this; + + if (externalTransaction) { + return handler(externalTransaction, true); + } + + const internalTransaction = await ctx.model.transaction(); + try { + const result = await handler(internalTransaction, false); + await internalTransaction.commit(); + return result; + } catch (error) { + await internalTransaction.rollback(); + throw error; + } + } + async lockItemStorages(stockWarehouseId, quantity, transaction) { const { ctx, @@ -592,19 +618,35 @@ class stockStoreService extends Service { } try { - // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, transaction); + return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { + // 2. 获取商品和库存信息(复用) + const stockResult = await this.getItemStorages(itemId, currentTransaction); - if (!stockResult.success) { - // 入库失败:商品不存在或未绑定 - return stockResult; - } - const { - storage, - } = stockResult.data; + if (!stockResult.success) { + if (hasExternalTransaction) { + throw new Error(stockResult.error); + } + return stockResult; + } + + const { storage } = stockResult.data; + + // 3. 执行库存增加 + if (!storage.exists) { + const failureResult = { + success: false, + error: '库存记录不存在,首次入库需要完整参数', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + const beforeQuantity = Number(storage.quantity) || 0; + const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; - // 3. 执行库存增加 - if (storage.exists) { // 非首次入库:更新现有记录(只增加quantity) await ctx.model.StockWarehouse.increment('quantity', { by: inboundQty, @@ -613,50 +655,75 @@ class stockStoreService extends Service { is_valid: 'Y', deleted_at: null, }, - transaction, + transaction: currentTransaction, + }); + + const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { + transaction: currentTransaction, + raw: true, + }); + + const afterQuantity = Number(updatedRecord.quantity) || 0; + const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; + + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, + store_id: ctx.user.store_id, + stock_id: storage.id, + storage_id: null, + space_id: null, + quantity: inboundQty, + batch_no: null, + inventory_type: 'ZP', + order_type: 'STOCK_STORE_INBOUND', + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '商品入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { + transaction: currentTransaction, }); app.logger.info('[入库] 更新现有库存', { itemId, stockId: storage.id, quantity: inboundQty, - before: storage.quantity, - after: storage.quantity + inboundQty, + before: beforeQuantity, + after: afterQuantity, }); - } else { - // 首次入库:需要创建库存记录(stock_id应该已存在) - // 注意:这里需要更多信息,如warehouse_id等,实际场景可能需要额外参数 - return { - success: false, - error: '库存记录不存在,首次入库需要完整参数', - data: null, - }; - } - // 4. 获取更新后的数据 - const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { - transaction, - raw: true, + return { + success: true, + data: { + itemId, + stockId: storage.id, + action: 'inbound', + quantity: inboundQty, + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + available: afterQuantity - afterLockedQuantity, + updatedAt: updatedRecord.update_at, + }, + error: null, + }; }); - return { - success: true, - data: { - itemId, - stockId: storage.id, - action: 'inbound', - quantity: inboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - available: updatedRecord.quantity - updatedRecord.locked_quantity, - updatedAt: updatedRecord.update_at, - }, - error: null, - }; - } catch (error) { + if (transaction) { + throw error; + } + app.logger.error('[inbound] 入库失败', { itemId, quantity, @@ -694,107 +761,162 @@ class stockStoreService extends Service { } try { - // 2. 获取商品和库存信息(复用) - const stockResult = await this.getItemStorages(itemId, transaction); + return await this._runWithTransaction(transaction, async (currentTransaction, hasExternalTransaction) => { + // 2. 获取商品和库存信息(复用) + const stockResult = await this.getItemStorages(itemId, currentTransaction); - if (!stockResult.success) { - return stockResult; - } + if (!stockResult.success) { + if (hasExternalTransaction) { + throw new Error(stockResult.error); + } + return stockResult; + } - const { - storage, - } = stockResult.data; + const { storage } = stockResult.data; - // 3. 检查库存是否足够出库 - if (!storage.exists) { - return { - success: false, - error: '库存记录不存在,无法出库', - data: null, - }; - } + // 3. 检查库存是否足够出库 + if (!storage.exists) { + const failureResult = { + success: false, + error: '库存记录不存在,无法出库', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } - // 关键检查:总库存是否足够 - if (storage.quantity < outboundQty) { - return { - success: false, - error: `总库存不足,当前 ${storage.quantity},需求 ${outboundQty}`, - data: null, - }; - } + const beforeQuantity = Number(storage.quantity) || 0; + const beforeLockedQuantity = Number(storage.lockedQuantity) || 0; - // 关键检查:锁定库存是否足够扣减 - if (storage.lockedQuantity < outboundQty) { - return { - success: false, - error: `锁定库存不足,已锁定 ${storage.lockedQuantity},需求 ${outboundQty}`, - data: null, - }; - } + // 关键检查:总库存是否足够 + if (beforeQuantity < outboundQty) { + const failureResult = { + success: false, + error: `总库存不足,当前 ${beforeQuantity},需求 ${outboundQty}`, + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } - // 4. 执行出库扣减(同时减少quantity和locked_quantity) - const result = await ctx.model.StockWarehouse.update({ - quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), - locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`), - update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), - }, { - where: { - id: storage.id, - is_valid: 'Y', - deleted_at: null, - // 乐观锁条件:确保更新时库存仍然足够 - quantity: { - [app.Sequelize.Op.gte]: outboundQty, + // 关键检查:锁定库存是否足够扣减 + if (beforeLockedQuantity < outboundQty) { + const failureResult = { + success: false, + error: `锁定库存不足,已锁定 ${beforeLockedQuantity},需求 ${outboundQty}`, + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } + + // 4. 执行出库扣减(同时减少quantity和locked_quantity) + const result = await ctx.model.StockWarehouse.update({ + quantity: app.Sequelize.literal(`quantity - ${outboundQty}`), + locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`), + update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'), + }, { + where: { + id: storage.id, + is_valid: 'Y', + deleted_at: null, + quantity: { + [app.Sequelize.Op.gte]: outboundQty, + }, + locked_quantity: { + [app.Sequelize.Op.gte]: outboundQty, + }, }, - locked_quantity: { - [app.Sequelize.Op.gte]: outboundQty, - }, - }, - transaction, - }); + transaction: currentTransaction, + }); - if (result[0] === 0) { - return { - success: false, - error: '出库失败:库存已被其他操作修改', - data: null, - }; - } + if (result[0] === 0) { + const failureResult = { + success: false, + error: '出库失败:库存已被其他操作修改', + data: null, + }; + if (hasExternalTransaction) { + throw new Error(failureResult.error); + } + return failureResult; + } - // 5. 获取更新后的数据 - const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { - transaction, - raw: true, - }); + // 5. 获取更新后的数据 + const updatedRecord = await ctx.model.StockWarehouse.findByPk(storage.id, { + transaction: currentTransaction, + raw: true, + }); - app.logger.info('[出库] 成功', { - itemId, - stockId: storage.id, - quantity: outboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - }); + const afterQuantity = Number(updatedRecord.quantity) || 0; + const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; - return { - success: true, - data: { + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'OUTBOUND', + warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, + store_id: ctx.user.store_id, + stock_id: storage.id, + storage_id: null, + space_id: null, + quantity: outboundQty, + batch_no: null, + inventory_type: 'ZP', + order_type: 'STOCK_STORE_OUTBOUND', + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '商品出库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { + transaction: currentTransaction, + }); + + app.logger.info('[出库] 成功', { itemId, stockId: storage.id, - action: 'outbound', quantity: outboundQty, - beforeQuantity: storage.quantity, - afterQuantity: updatedRecord.quantity, - beforeLocked: storage.lockedQuantity, - afterLocked: updatedRecord.locked_quantity, - available: updatedRecord.quantity - updatedRecord.locked_quantity, - updatedAt: updatedRecord.update_at, - }, - error: null, - }; + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + }); + + return { + success: true, + data: { + itemId, + stockId: storage.id, + action: 'outbound', + quantity: outboundQty, + beforeQuantity, + afterQuantity, + beforeLocked: beforeLockedQuantity, + afterLocked: afterLockedQuantity, + available: afterQuantity - afterLockedQuantity, + updatedAt: updatedRecord.update_at, + }, + error: null, + }; + }); } catch (error) { + if (transaction) { + throw error; + } + app.logger.error('[outbound] 出库失败', { itemId, quantity, diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index f975737..144efa4 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -4,6 +4,84 @@ const Service = require('egg').Service; class StockTransactionService extends Service { + /** + * 统一写入库存流水记录。 + * + * @param {Object} data 流水数据 + * @param {string} data.transaction_type 出入库类型 + * @param {number} data.warehouse_id 仓库ID + * @param {number} data.store_id 货主ID + * @param {number} data.stock_id 商品库存ID + * @param {number} [data.storage_id] 库位库存ID + * @param {number} [data.space_id] 库位ID + * @param {number} data.quantity 变动数量 + * @param {string} [data.batch_no] 批次号 + * @param {string} [data.inventory_type] 库存类型 + * @param {string} [data.order_type] 关联单据类型 + * @param {string} [data.order_no] 关联单据号 + * @param {number} [data.order_id] 关联单据ID + * @param {number} [data.receiving_id] 关联收货单ID + * @param {number} [data.entry_order_id] 关联入库单ID + * @param {string} [data.operator_id] 操作人ID + * @param {string} [data.operator_name] 操作人名称 + * @param {string} [data.remark] 备注 + * @param {number} [data.before_quantity] 变更前总库存数量 + * @param {number} [data.after_quantity] 变更后总库存数量 + * @param {number} [data.before_locked_quantity] 变更前锁定数量 + * @param {number} [data.after_locked_quantity] 变更后锁定数量 + * @param {Date} [data.created_at] 创建时间 + * @param {Object} [options] 写入选项 + * @param {Object} [options.transaction] 数据库事务 + * @return {Promise} 新增的流水记录 + */ + async create(data = {}, options = {}) { + const { ctx } = this; + + const quantity = Number(data.quantity); + if (!data.transaction_type) { + throw new Error('transaction_type 必填'); + } + if (!data.warehouse_id) { + throw new Error('warehouse_id 必填'); + } + if (!data.store_id) { + throw new Error('store_id 必填'); + } + if (!data.stock_id) { + throw new Error('stock_id 必填'); + } + if (!Number.isFinite(quantity) || quantity <= 0) { + throw new Error('quantity 必须为正数'); + } + + const payload = { + transaction_type: data.transaction_type, + warehouse_id: data.warehouse_id, + store_id: data.store_id, + stock_id: data.stock_id, + storage_id: data.storage_id ?? null, + space_id: data.space_id ?? null, + quantity, + batch_no: data.batch_no ?? null, + inventory_type: data.inventory_type || 'ZP', + order_type: data.order_type ?? null, + order_no: data.order_no ?? null, + order_id: data.order_id ?? null, + receiving_id: data.receiving_id ?? null, + entry_order_id: data.entry_order_id ?? null, + operator_id: data.operator_id ?? null, + operator_name: data.operator_name ?? null, + remark: data.remark ?? null, + before_quantity: data.before_quantity ?? null, + after_quantity: data.after_quantity ?? null, + before_locked_quantity: data.before_locked_quantity ?? null, + after_locked_quantity: data.after_locked_quantity ?? null, + created_at: data.created_at || new Date(), + }; + + return ctx.model.StockTransaction.create(payload, options); + } + async list(pageParams = {}, sortParams = {}, groupByBatch = false) { const { ctx, app } = this; const { Op, fn, col, literal } = app.Sequelize; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 9f18bd1..cf85bbf 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -353,6 +353,66 @@ class EntryService extends Service { }; } + /** + * 归一化作废入参中的入库单 ID 列表。 + * 优先使用 ids;未传 ids 时回退到 id。 + * @param {Object} data 请求体 + * @return {{ ok: boolean, ids?: number[], code?: number, message?: string }} 归一化结果 + */ + normalizeCancelEntryOrderIds(data = {}) { + const hasIdsField = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasIdField = Object.prototype.hasOwnProperty.call(data, 'id'); + + if (!hasIdsField && !hasIdField) { + return { + ok: false, + code: 400, + message: 'id 或 ids 必填', + }; + } + + const rawIds = hasIdsField ? data.ids : [ data.id ]; + + if (hasIdsField) { + if (!Array.isArray(rawIds) || rawIds.length === 0) { + return { + ok: false, + code: 400, + message: 'ids 必须是非空数组', + }; + } + } else if (!Number.isInteger(Number(rawIds[0])) || Number(rawIds[0]) <= 0) { + return { + ok: false, + code: 400, + message: 'id 必填且必须为正整数', + }; + } + + const normalizedIds = []; + for (const rawId of rawIds) { + const normalizedId = Number(rawId); + if (!Number.isInteger(normalizedId) || normalizedId <= 0) { + return { + ok: false, + code: 400, + message: 'ids 必须为正整数数组', + }; + } + normalizedIds.push(normalizedId); + } + + return { + ok: true, + ids: [ ...new Set(normalizedIds) ], + }; + } + + /** + * 查询当前仓库可访问的入库单。 + * @param {number} id 入库单ID + * @return {Promise} 入库单实例 + */ async getOwnedEntryOrderById(id) { const { ctx } = this; return await ctx.model.EntryOrder.findOne({ @@ -585,43 +645,72 @@ class EntryService extends Service { * @return {Promise} code/data/message 结构 */ async cancel(data = {}) { - const orderId = Number(data.id || 0); + const { ctx } = this; + const normalizedResult = this.normalizeCancelEntryOrderIds(data); - if (!orderId) { + if (!normalizedResult.ok) { return { - code: 400, - message: 'id 必填', + code: normalizedResult.code || 400, + message: normalizedResult.message || '参数错误', data: null, }; } - const entryOrder = await this.getOwnedEntryOrderById(orderId); - if (!entryOrder) { - return { - code: 404, - message: '入库单不存在或无权访问', - data: null, - }; + const orderIds = normalizedResult.ids || []; + const entryOrders = []; + + for (const orderId of orderIds) { + const entryOrder = await this.getOwnedEntryOrderById(orderId); + if (!entryOrder) { + return { + code: 404, + message: '入库单不存在或无权访问', + data: null, + }; + } + + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '已完成入库单不允许作废', + data: null, + }; + } + + entryOrders.push(entryOrder); } - if (entryOrder.order_status === 'COMPLETED') { - return { - code: 400, - message: '已完成入库单不允许作废', - data: null, - }; - } + const transaction = ctx.model && typeof ctx.model.transaction === 'function' + ? await ctx.model.transaction() + : null; - await entryOrder.update({ - order_status: 'CANCELLED', - updated_at: new Date(), - }); + try { + const updatedAt = new Date(); + + for (const entryOrder of entryOrders) { + await entryOrder.update({ + order_status: 'CANCELLED', + updated_at: updatedAt, + }, transaction ? { + transaction, + } : undefined); + } + + if (transaction && typeof transaction.commit === 'function') { + await transaction.commit(); + } + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; + } return { code: 200, message: '作废成功', data: { - id: entryOrder.id, + [orderIds.length === 1 ? 'id' : 'ids']: orderIds.length === 1 ? entryOrders[0].id : orderIds, }, }; } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 1cdd5c0..1e63294 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -55,8 +55,6 @@ class InventoryService extends Service { 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 }; @@ -158,11 +156,16 @@ class InventoryService extends Service { } // 5b. 增加 StockWarehouse 库存数量 + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true, }); + await stockRecord.reload({ transaction }); + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; // 5c. 写入/更新 wms_storage 库存位置表 const spaceId = detail.space_id || 1; // 明细有库位则用,否则默认库位 @@ -233,7 +236,7 @@ class InventoryService extends Service { }, { transaction }); // 5d+. 写入出入库记录 - await ctx.model.StockTransaction.create({ + await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: receiving.store_id || warehouseId, @@ -251,6 +254,10 @@ class InventoryService extends Service { operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: `快捷入库-收货单 ${receiving.receiving_number}`, + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); @@ -535,11 +542,16 @@ class InventoryService extends Service { continue; } + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; await stockRecord.increment('quantity', { by: actualInbound, transaction, silent: true, }); + await stockRecord.reload({ transaction }); + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; // 6b. 写入/更新 wms_storage(取第一个收货明细的信息) const firstRcvDetail = rcvGroup[0].detail; @@ -597,7 +609,7 @@ class InventoryService extends Service { } // 6b+. 写入出入库记录 - await ctx.model.StockTransaction.create({ + await ctx.service.systems.stockTransaction.create({ transaction_type: 'INBOUND', warehouse_id: warehouseId, store_id: firstRcv.store_id || warehouseId, @@ -615,6 +627,10 @@ class InventoryService extends Service { operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', remark: '匹配入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, created_at: new Date(), }, { transaction }); diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 8a316e2..847dfa7 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -2311,6 +2311,35 @@ class ReceivingService extends Service { return methodMap[normalizedValue] || normalizedValue; } + /** + * 获取完成收货时需要展示的联系字段。 + * @param {Object} receiving 收货单快照。 + * @return {Array} 需要展示的联系字段列表。 + */ + getCompletionContactFields(receiving) { + const deliveryMethod = String((receiving && receiving.delivery_method) || '').trim(); + + if (deliveryMethod === 'truck') { + return [[ '车牌号', receiving && receiving.license_plate ]]; + } + + if (deliveryMethod === 'express') { + return [[ '物流单号', receiving && receiving.tracking_number ]]; + } + + return []; + } + + /** + * 生成收货完成报表的工作表数据。 + * @param {Object} options 报表参数。 + * @param {Object} options.receiving 收货单快照。 + * @param {Object} [options.operator={}] 操作人信息。 + * @param {Object} [options.stats={}] 收货统计数据。 + * @param {Map} [options.detailImageMap=new Map()] 明细图片映射。 + * @param {Array} [options.receivingImages=[]] 收货单图片列表。 + * @return {Array} 工作表列表。 + */ buildCompletionReportSheets({ receiving, operator = {}, @@ -2389,8 +2418,7 @@ class ReceivingService extends Service { [ '收货单号', receiving && receiving.receiving_number ], [ '货主', receiving && receiving.store_name ], [ '来货方式', this.formatDeliveryMethod(receiving && receiving.delivery_method) ], - [ '车牌号', receiving && receiving.license_plate ], - [ '物流单号', receiving && receiving.tracking_number ], + ...this.getCompletionContactFields(receiving), [ '总明细数', stats.total_details || details.length ], [ '已匹配明细数', stats.matched_details || 0 ], [ '未匹配明细数', stats.unmatched_details || 0 ], @@ -2605,13 +2633,24 @@ class ReceivingService extends Service { (completionReport && (completionReport.filename || completionReport.fileKey || completionReport.key)) || `收货完成_${receivingNumber}.xlsx` ).trim(); const title = `收货单${receivingNumber}已完成`; + const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`); const content = [ - `收货单${receivingNumber}已完成`, - `匹配商品${matchedDetails}件`, - `未匹配商品${unmatchedDetails}件`, - `总数量${totalQuantity}`, - operatorName ? `完成人${operatorName}` : '', - ].filter(Boolean).join(',') + '。'; + `收货单号:${receivingNumber} 已完成`, + `货主:${receiving.store_name || '未知'}`, + `来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`, + ...contactLines, + `总明细数:${Number(stats.total_details || 0)}件`, + `匹配商品:${matchedDetails}件`, + `未匹配商品:${unmatchedDetails}件`, + `总数量:${totalQuantity}`, + `总箱数:${receiving.total_boxes || 0}`, + `总托盘数:${receiving.total_pallets || 0}`, + operatorName ? `完成人:${operatorName}` : '', + `开始时间:${this.formatReportDate(receiving.created_at)}`, + `完成时间:${this.formatReportDate(receiving.receiving_end_time)}`, + `备注:${receiving.remark || '无'}`, + + ].filter(Boolean).join('\n') + '。'; return await noticeService.send({ warehouseId, diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js index 38d619c..71e6cb8 100644 --- a/app/service/systems/store_warehouse.js +++ b/app/service/systems/store_warehouse.js @@ -13,12 +13,25 @@ const AUTH_STATUS_LABELS = Object.freeze({ }); class SettingStoreWarehouseService extends Service { + /** + * 创建统一错误对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=500] HTTP 状态码。 + * @return {Error} 带 code 属性的错误对象。 + */ createError(message, code = 500) { const error = new Error(message); error.code = code; return error; } + /** + * 获取当前登录主体的货主 ID。 + * + * @return {number} 当前主体的货主 ID。 + * @throws {Error} 当无法识别当前主体时抛出,状态码为 400。 + */ getCurrentStoreId() { const storeId = Number(this.ctx.user && this.ctx.user.store_id); if (!Number.isFinite(storeId) || storeId <= 0) { @@ -27,6 +40,12 @@ class SettingStoreWarehouseService extends Service { return storeId; } + /** + * 获取当前登录账号 ID。 + * + * @return {number} 当前登录账号 ID。 + * @throws {Error} 当无法识别当前登录账号时抛出,状态码为 401。 + */ getCurrentAccountId() { const accountId = Number(this.ctx.user && this.ctx.user.id); if (!Number.isFinite(accountId) || accountId <= 0) { @@ -35,6 +54,16 @@ class SettingStoreWarehouseService extends Service { return accountId; } + /** + * 将输入值规范化为正数。 + * + * @param {*} value 待转换的值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowEmpty=false] 是否允许空值返回 null。 + * @return {number|null} 规范化后的正数或 null。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ toPositiveNumber(value, fieldName, options = {}) { const { allowEmpty = false } = options; if (allowEmpty && (value === undefined || value === null || value === '')) { @@ -48,6 +77,16 @@ class SettingStoreWarehouseService extends Service { return num; } + /** + * 规范化分页参数。 + * + * @param {*} value 待处理的页码或分页大小。 + * @param {string} fieldName 字段名。 + * @param {number} defaultValue 默认值。 + * @param {number} maxValue 最大值。 + * @return {number} 规范化后的分页值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizePage(value, fieldName, defaultValue, maxValue) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -59,6 +98,15 @@ class SettingStoreWarehouseService extends Service { return Math.min(Math.floor(num), maxValue); } + /** + * 规范化状态标记。 + * + * @param {*} value 待处理的状态值。 + * @param {string} fieldName 字段名。 + * @param {number|null} [defaultValue=null] 默认值。 + * @return {number|null} 0、1 或默认值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeStatusFlag(value, fieldName, defaultValue = null) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -70,6 +118,13 @@ class SettingStoreWarehouseService extends Service { throw this.createError(`${fieldName} 参数不合法`, 400); } + /** + * 规范化签约状态。 + * + * @param {*} value 待处理的签约状态值。 + * @return {number|null} 合法的签约状态或 null。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeAuthStatus(value) { if (value === undefined || value === null || value === '') { return null; @@ -81,6 +136,15 @@ class SettingStoreWarehouseService extends Service { throw this.createError('auth_status 参数不合法', 400); } + /** + * 规范化非负整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} [defaultValue=0] 默认值。 + * @return {number} 非负整数。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -92,6 +156,16 @@ class SettingStoreWarehouseService extends Service { return Math.floor(num); } + /** + * 规范化整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowZero=true] 是否允许 0。 + * @return {number} 整数值。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeInteger(value, fieldName, options = {}) { const { allowZero = true } = options; if (value === undefined || value === null || value === '') { @@ -108,6 +182,15 @@ class SettingStoreWarehouseService extends Service { return num; } + /** + * 规范化文本内容。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} [maxLength=500] 最大长度。 + * @return {string|null} 规范化后的文本或 null。 + * @throws {Error} 文本超长时抛出,状态码为 400。 + */ normalizeText(value, fieldName, maxLength = 500) { if (value === undefined || value === null) { return null; @@ -119,6 +202,17 @@ class SettingStoreWarehouseService extends Service { return normalized; } + /** + * 规范化区间整数。 + * + * @param {*} value 待处理的值。 + * @param {string} fieldName 字段名。 + * @param {number} defaultValue 默认值。 + * @param {number} minValue 最小值。 + * @param {number} maxValue 最大值。 + * @return {number} 区间内的整数。 + * @throws {Error} 参数非法时抛出,状态码为 400。 + */ normalizeIntegerRange(value, fieldName, defaultValue, minValue, maxValue) { if (value === undefined || value === null || value === '') { return defaultValue; @@ -130,6 +224,13 @@ class SettingStoreWarehouseService extends Service { return Math.floor(num); } + /** + * 规范化邮箱地址。 + * + * @param {*} value 待处理的邮箱值。 + * @return {string|null} 合法邮箱或 null。 + * @throws {Error} 邮箱格式非法时抛出,状态码为 400。 + */ normalizeEmail(value) { const email = this.normalizeText(value, 'email', 100); if (!email) { @@ -143,6 +244,11 @@ class SettingStoreWarehouseService extends Service { return email; } + /** + * 获取策略配置字段清单。 + * + * @return {Array} 策略配置字段数组。 + */ getPolicyConfigFieldList() { const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; if (!storeWarehouseModel || typeof storeWarehouseModel.getPolicyConfigFieldList !== 'function') { @@ -151,6 +257,17 @@ class SettingStoreWarehouseService extends Service { return storeWarehouseModel.getPolicyConfigFieldList(); } + /** + * 规范化策略配置内容。 + * + * @param {*} value 待处理的配置值。 + * @param {string} [fieldName='policy_config'] 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowEmpty=false] 是否允许空值。 + * @param {boolean} [options.sanitizeOnly=false] 是否仅做清洗不做强校验。 + * @return {*|null} 规范化后的策略配置。 + * @throws {Error} 模型未提供规则或参数非法时抛出,对应状态码为 400/500。 + */ normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) { const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; if (!storeWarehouseModel || typeof storeWarehouseModel.normalizePolicyConfig !== 'function') { @@ -168,10 +285,21 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 生成策略配置缓存键。 + * + * @param {number|string} contractId 合同 ID。 + * @return {string} 缓存键。 + */ getPolicyConfigCacheKey(contractId) { return `store_warehouse:policy:${contractId}`; } + /** + * 判断表中是否存在 policy_config 字段。 + * + * @return {Promise} 是否存在该字段。 + */ async hasPolicyConfigColumn() { if (this._hasPolicyConfigColumn !== undefined) { return this._hasPolicyConfigColumn; @@ -188,6 +316,13 @@ class SettingStoreWarehouseService extends Service { return this._hasPolicyConfigColumn; } + /** + * 按合同 ID 读取策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise<*>} 规范化后的策略配置。 + */ async loadPolicyConfigByContractId(contractId, transaction = null) { const normalizedId = Number(contractId || 0); if (normalizedId <= 0) { @@ -218,6 +353,15 @@ class SettingStoreWarehouseService extends Service { }); } + /** + * 按合同 ID 保存策略配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {*} policyConfig 策略配置内容。 + * @param {Object|null} [transaction=null] 事务对象。 + * @return {Promise} 无返回值。 + * @throws {Error} 合同 ID 非法时抛出,状态码为 400。 + */ async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) { const normalizedId = Number(contractId || 0); if (normalizedId <= 0) { @@ -241,12 +385,25 @@ class SettingStoreWarehouseService extends Service { await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); } + /** + * 校验当前主体是否为仓库主体。 + * + * @param {Object} currentSubject 当前主体。 + * @param {string} [actionLabel='签约配置'] 操作名称。 + * @return {void} + * @throws {Error} 当前主体不是仓库主体时抛出,状态码为 403。 + */ ensureWarehouseSubject(currentSubject, actionLabel = '签约配置') { if (!currentSubject || !currentSubject.isWarehouse) { throw this.createError(`仅仓库主体可维护${actionLabel}`, 403); } } + /** + * 获取通知服务实例。 + * + * @return {Object|null} 通知服务或 null。 + */ getNoticeService() { const rawNoticeService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.notice; if (rawNoticeService && typeof rawNoticeService.send === 'function') { @@ -258,6 +415,20 @@ class SettingStoreWarehouseService extends Service { return null; } + /** + * 发送面单余额调整通知。 + * + * @param {Object} options 通知参数。 + * @param {Object} [options.relation] 签约关系。 + * @param {Object} [options.currentSubject] 当前主体。 + * @param {Object} [options.changeLog] 调整日志。 + * @param {number} [options.operatorId] 操作人 ID。 + * @param {number} [options.changeQuantity] 变更数量。 + * @param {number} [options.balanceBefore] 调整前余额。 + * @param {number} [options.balanceAfter] 调整后余额。 + * @param {string} [options.reason] 调整原因。 + * @return {Promise} 通知发送结果或 null。 + */ async sendPrintQuantityAdjustNotice({ relation, currentSubject, @@ -330,6 +501,12 @@ class SettingStoreWarehouseService extends Service { }); } + /** + * 解析签约关系 ID。 + * + * @param {Object} [data={}] 请求参数。 + * @return {number|null} 关系 ID 或 null。 + */ resolveRelationId(data = {}) { return this.toPositiveNumber( data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id), @@ -338,6 +515,16 @@ class SettingStoreWarehouseService extends Service { ); } + /** + * 规范化日期值。 + * + * @param {*} value 待处理的日期值。 + * @param {string} fieldName 字段名。 + * @param {Object} [options={}] 配置项。 + * @param {boolean} [options.allowNull=true] 是否允许空值。 + * @return {Date|null} 规范化后的日期对象或 null。 + * @throws {Error} 日期非法时抛出,状态码为 400。 + */ normalizeDate(value, fieldName, options = {}) { const { allowNull = true } = options; if (value === undefined || value === null || value === '') { @@ -354,6 +541,13 @@ class SettingStoreWarehouseService extends Service { return date; } + /** + * 规范化签约动作。 + * + * @param {*} value 待处理的动作值。 + * @return {string} 规范化后的动作值。 + * @throws {Error} 动作非法时抛出,状态码为 400。 + */ normalizeSignAction(value) { if (value === undefined || value === null || value === '') { return ''; @@ -366,6 +560,13 @@ class SettingStoreWarehouseService extends Service { throw this.createError('action 参数不合法', 400); } + /** + * 规范化临时码。 + * + * @param {*} value 待处理的临时码。 + * @return {string} 大写后的临时码。 + * @throws {Error} 临时码为空或非法时抛出,状态码为 400。 + */ normalizeTempCode(value) { const code = String(value || '').trim().toUpperCase(); if (!code) { @@ -374,18 +575,42 @@ class SettingStoreWarehouseService extends Service { return code; } + /** + * 生成临时码缓存键。 + * + * @param {string} tempCode 临时码。 + * @return {string} 缓存键。 + */ getTempCodeCacheKey(tempCode) { return `store_warehouse:sign:${tempCode}`; } + /** + * 生成临时码。 + * + * @return {string} 临时码。 + */ createTempCode() { return crypto.randomBytes(6).toString('hex').toUpperCase(); } + /** + * 选择当前主体对应的脱敏字段。 + * + * @param {Object} currentSubject 当前主体。 + * @return {string} 脱敏字段名。 + */ pickRemaskField(currentSubject) { return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; } + /** + * 解析脱敏展示名称。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {string|null} 脱敏名称。 + */ resolveRemaskValue(data, currentSubject) { const raw = data.remask !== undefined ? data.remask @@ -393,6 +618,13 @@ class SettingStoreWarehouseService extends Service { return this.normalizeText(raw, 'remask', 50); } + /** + * 构建当前主体的脱敏字段更新内容。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 待更新字段对象。 + */ buildCurrentRemaskPatch(data, currentSubject) { const remask = this.resolveRemaskValue(data, currentSubject); if (remask === null) { @@ -404,6 +636,14 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 构建强制要求的脱敏字段更新内容。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 待更新字段对象。 + * @throws {Error} 未提供脱敏名称时抛出,状态码为 400。 + */ requireCurrentRemaskPatch(data, currentSubject) { const patch = this.buildCurrentRemaskPatch(data, currentSubject); if (!Object.keys(patch).length) { @@ -412,6 +652,12 @@ class SettingStoreWarehouseService extends Service { return patch; } + /** + * 保存临时签约载荷。 + * + * @param {Object} payload 临时载荷。 + * @return {Promise} 保存后的临时码信息。 + */ async saveTempSignPayload(payload) { const now = Date.now(); const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); @@ -427,6 +673,13 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 读取临时签约载荷。 + * + * @param {string} tempCode 临时码。 + * @return {Promise} 临时码与载荷信息。 + * @throws {Error} 临时码无效或已过期时抛出,状态码为 404。 + */ async getTempSignPayload(tempCode) { const normalizedCode = this.normalizeTempCode(tempCode); const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); @@ -439,6 +692,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 清理临时签约载荷。 + * + * @param {string} tempCode 临时码。 + * @return {Promise} 无返回值。 + */ async clearTempSignPayload(tempCode) { const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; if (cacheRedis && cacheRedis.del) { @@ -448,6 +707,14 @@ class SettingStoreWarehouseService extends Service { await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); } + /** + * 构建临时签约预览视图。 + * + * @param {string} tempCode 临时码。 + * @param {Object} payload 临时载荷。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 预览视图对象。 + */ buildTempSignView(tempCode, payload, currentSubject) { const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; const currentSubjectId = Number(currentSubject && currentSubject.id); @@ -483,6 +750,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取当前主体信息。 + * + * @return {Promise} 当前主体对象。 + * @throws {Error} 当前主体不存在时抛出,状态码为 404。 + */ async getCurrentSubject() { const { ctx } = this; const storeId = this.getCurrentStoreId(); @@ -506,6 +779,14 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取签约对方主体信息。 + * + * @param {number} counterpartyId 对方主体 ID。 + * @param {string} expectedRole 期望角色。 + * @return {Promise} 对方主体对象。 + * @throws {Error} 对方主体不存在或角色不匹配时抛出,状态码为 400/404。 + */ async getCounterparty(counterpartyId, expectedRole) { const { ctx } = this; const counterparty = await ctx.model.Store.findOne({ @@ -530,6 +811,13 @@ class SettingStoreWarehouseService extends Service { return counterparty; } + /** + * 构建列表查询条件。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} where 查询条件。 + */ buildListWhere(data, currentSubject) { const where = {}; @@ -569,6 +857,11 @@ class SettingStoreWarehouseService extends Service { return where; } + /** + * 获取签约关系关联模型。 + * + * @return {Array} 关联配置数组。 + */ getRelationIncludes() { const { ctx } = this; return [ @@ -587,10 +880,24 @@ class SettingStoreWarehouseService extends Service { ]; } + /** + * 生成奇门合同缓存键。 + * + * @param {string} appKey 应用标识。 + * @param {string} customerId 客户标识。 + * @param {string} warehouseCode 仓库编码。 + * @return {string} 缓存键。 + */ getQimenContractCacheKey(appKey, customerId, warehouseCode) { return `contract:${appKey}:${customerId}:${warehouseCode}`; } + /** + * 清理奇门合同缓存。 + * + * @param {Array} configs 配置列表。 + * @return {Promise} 无返回值。 + */ async clearQimenContractCache(configs = []) { const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; const keys = [ ...new Set(configs.map(item => { @@ -622,6 +929,18 @@ class SettingStoreWarehouseService extends Service { await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null))); } + /** + * 获取接口类型。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=false] 是否允许禁用接口类型。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @param {boolean} [options.requireId=false] 是否必须传入 interface_type_id。 + * @param {string|null} [options.interfaceCategory=null] 接口分类。 + * @return {Promise} 接口类型对象。 + * @throws {Error} 参数非法或接口类型不存在时抛出,状态码为 400/404。 + */ async getApiInterfaceType(data = {}, options = {}) { const { ctx } = this; const { allowDisabled = false, transaction = null, requireId = false, interfaceCategory = null } = options; @@ -655,10 +974,23 @@ class SettingStoreWarehouseService extends Service { return interfaceType; } + /** + * 获取奇门接口类型。 + * + * @param {Object} [data={}] 请求参数。 + * @param {Object} [options={}] 选项。 + * @return {Promise} 接口类型对象。 + */ async getQimenInterfaceType(data = {}, options = {}) { return this.getApiInterfaceType(data, options); } + /** + * 序列化奇门配置。 + * + * @param {Object} config 配置实例或普通对象。 + * @return {Object|null} 序列化后的配置对象。 + */ serializeQimenConfig(config) { if (!config) { return null; @@ -697,6 +1029,16 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取奇门配置映射。 + * + * @param {Array} contractIds 合同 ID 列表。 + * @param {Object} [options={}] 选项。 + * @param {boolean} [options.allowDisabled=true] 是否允许禁用接口类型。 + * @param {number|null} [options.interfaceTypeId=null] 指定接口类型 ID。 + * @param {Object|null} [options.transaction=null] 事务对象。 + * @return {Promise} 合同 ID 到配置的映射。 + */ async getQimenConfigMap(contractIds = [], options = {}) { const { ctx } = this; const { allowDisabled = true, interfaceTypeId = null, transaction = null } = options; @@ -743,11 +1085,26 @@ class SettingStoreWarehouseService extends Service { return configMap; } + /** + * 获取单个奇门配置。 + * + * @param {number|string} contractId 合同 ID。 + * @param {Object} [options={}] 选项。 + * @return {Promise} 单个配置对象或 null。 + */ async getSingleQimenConfig(contractId, options = {}) { const configMap = await this.getQimenConfigMap([ contractId ], options); return configMap.get(Number(contractId)) || null; } + /** + * 解析成对的合同主体 ID。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @return {Object} 包含 storeId、warehouseId、counterpartyId 的对象。 + * @throws {Error} 对方主体参数非法时抛出,状态码为 400。 + */ resolvePairIds(data, currentSubject) { const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; const rawCounterpartyId = data.counterparty_id !== undefined @@ -770,6 +1127,14 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 序列化签约关系。 + * + * @param {Object} relation 签约关系实例或普通对象。 + * @param {Object} currentSubject 当前主体。 + * @param {Object|null} [qimenConfig=null] 奇门配置。 + * @return {Object} 序列化后的签约关系对象。 + */ serializeRelation(relation, currentSubject, qimenConfig = null) { const item = relation && typeof relation.get === 'function' ? relation.get({ plain: true }) @@ -829,6 +1194,15 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取受限范围内的签约关系。 + * + * @param {Object} data 请求参数。 + * @param {Object} currentSubject 当前主体。 + * @param {Object} transaction 事务对象。 + * @return {Promise} 签约关系实例。 + * @throws {Error} 签约关系不存在或无权限操作时抛出,状态码为 404。 + */ async findScopedRelation(data, currentSubject, transaction) { const { ctx } = this; const where = currentSubject.isWarehouse @@ -857,6 +1231,12 @@ class SettingStoreWarehouseService extends Service { return relation; } + /** + * 查询签约关系列表。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async list(data = {}) { const { ctx, app } = this; const { Op } = app.Sequelize; @@ -912,6 +1292,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 发起或确认签约。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async sign(data = {}) { const action = this.normalizeSignAction(data.action || data.mode); if (data.temp_code || data.tempCode || action === 'preview') { @@ -1081,6 +1467,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 修改签约关系脱敏名称。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async rename(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1134,6 +1526,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 调整面单余额。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async adjustPrintQuantity(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1263,6 +1661,11 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 获取策略配置字段。 + * + * @return {Promise} 接口响应对象。 + */ async getPolicyConfigFields() { return { code: 200, @@ -1270,6 +1673,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 获取签约策略配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async getPolicyConfig(data = {}) { const currentSubject = await this.getCurrentSubject(); const relation = await this.findScopedRelation(data, currentSubject); @@ -1288,6 +1697,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 保存签约策略配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async savePolicyConfig(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1345,6 +1760,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 查询接口配置列表。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async listApiConfig(data = {}) { const { ctx } = this; const currentSubject = await this.getCurrentSubject(); @@ -1388,6 +1809,12 @@ class SettingStoreWarehouseService extends Service { }; } + /** + * 保存接口配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async saveApiConfig(data = {}) { const { ctx, app } = this; const transaction = await ctx.model.transaction(); @@ -1589,6 +2016,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 删除奇门接口配置。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async deleteQimenConfig(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); @@ -1670,6 +2103,12 @@ class SettingStoreWarehouseService extends Service { } } + /** + * 解绑签约关系。 + * + * @param {Object} [data={}] 请求参数。 + * @return {Promise} 接口响应对象。 + */ async unbind(data = {}) { const { ctx } = this; const transaction = await ctx.model.transaction(); diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index cff423f..c79f78d 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -11,8 +11,37 @@ class UploadService extends Service { super(ctx); this.initCOS(); } + + /** + * 获取腾讯云公共配置。 + * + * 说明:优先读取独立的腾讯云公共配置,若不存在则回退到兼容的 COS 配置, + * 以保证历史配置方式仍然可用。 + * + * @returns {Object} 腾讯云公共配置对象 + */ + getTencentCloudConfig() { + const tencentCloudConfig = this.config.tencentCloud || {}; + const cosConfig = this.config.cos || {}; + + return { + appId: tencentCloudConfig.appId ?? cosConfig.appId, + secretId: tencentCloudConfig.secretId ?? cosConfig.secretId, + secretKey: tencentCloudConfig.secretKey ?? cosConfig.secretKey, + }; + } + + /** + * 获取 COS 产品配置。 + * + * @returns {Object} COS 产品配置对象 + */ + getCosConfig() { + return this.config.cos || {}; + } + initCOS() { - const { secretId, secretKey } = this.config.cos; + const { secretId, secretKey } = this.getTencentCloudConfig(); this.cos = new COS({ SecretId: secretId, SecretKey: secretKey, @@ -26,6 +55,8 @@ class UploadService extends Service { */ async getUploadParams(fileInfo) { const { ctx } = this; + const cosConfig = this.getCosConfig(); + const tencentCloudConfig = this.getTencentCloudConfig(); const warehouseId = ctx.user.store_id; const { fileName, fileType, fileSize, type, md5 } = fileInfo; @@ -71,7 +102,7 @@ class UploadService extends Service { // 获取当前时间戳 const now = Math.floor(Date.now() / 1000); - const expire = now + this.config.cos.expire; + const expire = now + cosConfig.expire; const keyTime = `${now};${expire}`; // 使用与PHP一致的算法生成签名 @@ -80,11 +111,11 @@ class UploadService extends Service { // 构建返回参数 return { fileName: cosFileName, - uploadUrl: `https://${this.config.cos.bucket}.cos.${this.config.cos.region}.myqcloud.com`, - bucket: this.config.cos.bucket, - region: this.config.cos.region, + uploadUrl: `https://${cosConfig.bucket}.cos.${cosConfig.region}.myqcloud.com`, + bucket: cosConfig.bucket, + region: cosConfig.region, signature: { - secretId: this.config.cos.secretId, + secretId: tencentCloudConfig.secretId, signature, keyTime, key: cosFileName, @@ -94,7 +125,7 @@ class UploadService extends Service { key: cosFileName, policy, 'q-sign-algorithm': 'sha1', - 'q-ak': this.config.cos.secretId, + 'q-ak': tencentCloudConfig.secretId, 'q-sign-time': keyTime, 'q-key-time': keyTime, 'q-signature': signature, @@ -113,7 +144,7 @@ class UploadService extends Service { md5, }, // 有效期 - expires: this.config.cos.expire, + expires: cosConfig.expire, // 前端需要的额外参数 frontendConfig: this.getFrontendConfig(fileType, fileSize), isNew: true, @@ -129,7 +160,7 @@ class UploadService extends Service { * @param {number} expireTime 过期时间戳 */ generatePolicyAndSignature(key, startTime, expireTime) { - const { secretId, secretKey } = this.config.cos; + const { secretId, secretKey } = this.getTencentCloudConfig(); const keyTime = `${startTime};${expireTime}`; // 1. 生成策略 - 与PHP完全一致 @@ -178,7 +209,7 @@ class UploadService extends Service { * @param {number} root0.fileSize 文件大小 */ validateFileInfo({ fileName, fileSize }) { - const { maxsize, mimetype } = this.config.cos; + const { maxsize, mimetype } = this.getCosConfig(); // 验证文件大小 const maxSizeBytes = this.parseSizeToBytes(maxsize); @@ -205,7 +236,7 @@ class UploadService extends Service { * @param {string} md5 文件 MD5 */ generateFileName(fileName, fileType, category = '', md5) { - const { savekey, dirs } = this.config.cos; + const { savekey, dirs } = this.getCosConfig(); const ext = path.extname(fileName); const name = path.basename(fileName, ext); const timestamp = dayjs().format('YYYYMMDDHHmmss'); @@ -285,7 +316,7 @@ class UploadService extends Service { * @param {number} fileSize 文件大小 */ getFrontendConfig(fileType, fileSize) { - const { chunkSize } = this.config.cos; + const { chunkSize } = this.getCosConfig(); return { useMultipart: fileSize > 5 * 1024 * 1024, @@ -304,7 +335,7 @@ class UploadService extends Service { * @param {Object} options 上传选项 */ async uploadFile(fileStream, options = {}) { - const { bucket, region } = this.config.cos; + const { bucket, region, uploadurl, cdnurl } = this.getCosConfig(); try { this.validateFile(fileStream, options); @@ -326,9 +357,9 @@ class UploadService extends Service { return { fileName, - cosUrl: `${this.config.cos.uploadurl}/${fileName}`, - cdnUrl: `${this.config.cos.cdnurl}/${fileName}`, - url: `${this.config.cos.cdnurl}/${fileName}`, + cosUrl: `${uploadurl}/${fileName}`, + cdnUrl: `${cdnurl}/${fileName}`, + url: `${cdnurl}/${fileName}`, etag: result.ETag, location: result.Location, uploadAt: new Date().toISOString(), @@ -345,7 +376,7 @@ class UploadService extends Service { * @param {Object} options 上传选项 */ validateFile(fileStream, options = {}) { - const { maxsize, mimetype } = this.config.cos; + const { maxsize, mimetype } = this.getCosConfig(); const { filename, fileSize } = fileStream; const maxSizeBytes = this.parseSizeToBytes(maxsize); @@ -378,6 +409,7 @@ class UploadService extends Service { */ async uploadSuccessNotify(data) { const { ctx } = this; + const cosConfig = this.getCosConfig(); try { // 从上下文获取用户信息(根据你的实际用户认证方式) const warehouseId = ctx.user?.store_id || ctx.query.warehouseId || ctx.request.body.warehouseId; @@ -394,7 +426,7 @@ class UploadService extends Service { const resolvedFileSize = Number(data.fileSize || data.size || 0); // 生成完整的访问URL - const fileUrl = `${this.config.cos.cdnurl || this.config.cos.uploadurl}/${resolvedFileKey}`; + const fileUrl = `${cosConfig.cdnurl || cosConfig.uploadurl}/${resolvedFileKey}`; // 计算哈希值(如果前端没有提供) let md5Hash = data.md5Hash || data.md5 || ''; diff --git a/config/config.default.js b/config/config.default.js index 289a620..b9f1c46 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -18,6 +18,7 @@ module.exports = appInfo => { const userConfig = { // myAppName: 'egg', }; + const tencentCloudConfig = require('./tencent-cloud'); config.redis = { clients: { cache: { @@ -43,10 +44,11 @@ module.exports = appInfo => { appKey: 23535631, security: 'd0cbd3935e3afa2b42b5dc600c08a795', }; + config.tencentCloud = { + ...tencentCloudConfig, + }; config.cos = { - appId: 1234567890, - secretId: 'AKIDeFhx1tQ5PYVYP9K8PXUFoazHRPBlpTXP', - secretKey: 'pcHtKbhcKqDNLqEQRIxRjpjRHxTnvGQT', + ...config.tencentCloud, bucket: 'ye4s-1255377868', region: 'ap-guangzhou', uploadurl: 'https://ye4s-1255377868.cos.ap-guangzhou.myqcloud.com', diff --git a/database/migrations/20260408140000-create-wms-stock-transaction.js b/database/migrations/20260408140000-create-wms-stock-transaction.js index 08e5ca0..1ef7427 100644 --- a/database/migrations/20260408140000-create-wms-stock-transaction.js +++ b/database/migrations/20260408140000-create-wms-stock-transaction.js @@ -56,6 +56,26 @@ module.exports = { allowNull: false, comment: '变动数量(正数)', }, + before_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }, + after_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }, + before_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }, + after_locked_quantity: { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }, batch_no: { type: STRING(100), allowNull: true, diff --git a/database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js b/database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js new file mode 100644 index 0000000..0909653 --- /dev/null +++ b/database/migrations/20260409120000-add-snapshot-columns-to-wms-stock-transaction.js @@ -0,0 +1,63 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { INTEGER } = Sequelize; + const tableName = 'wms_stock_transaction'; + const tableInfo = await queryInterface.describeTable(tableName); + + const columns = [ + [ 'before_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更前总库存数量', + }], + [ 'after_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更后总库存数量', + }], + [ 'before_locked_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更前锁定数量', + }], + [ 'after_locked_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '变更后锁定数量', + }], + ]; + + for (const [ columnName, columnDefinition ] of columns) { + if (tableInfo[columnName]) { + continue; + } + + await queryInterface.addColumn(tableName, columnName, columnDefinition); + } + }, + + async down(queryInterface) { + const tableName = 'wms_stock_transaction'; + const tableInfo = await queryInterface.describeTable(tableName).catch(() => null); + if (!tableInfo) { + return; + } + + const columns = [ + 'after_locked_quantity', + 'before_locked_quantity', + 'after_quantity', + 'before_quantity', + ]; + + for (const columnName of columns) { + if (!tableInfo[columnName]) { + continue; + } + + await queryInterface.removeColumn(tableName, columnName); + } + }, +}; diff --git a/docs/qimen-interface-reference.md b/docs/qimen-interface-reference.md new file mode 100644 index 0000000..70a0a5a --- /dev/null +++ b/docs/qimen-interface-reference.md @@ -0,0 +1,226 @@ +# 奇门接口技术备忘 + +## 1. 文档来源 + +- 官方来源:open.taobao.com 文档,docId=118403,页面章节为“5. 接口说明” +- 适用对象:WMS 与 ERP 之间的奇门对接排障、接口回查、协议备忘 +- 本文目标:把官方白皮书里的核心调用约定、接口地图和本地实现入口沉淀到仓库内,便于技术备用 + +## 2. 接入总览 + +奇门接口的统一特征是: + +- 请求方式以 POST 为主 +- query 中携带 app_key、method、v、format、sign_method、sign、timestamp 等标准参数 +- body 使用 XML,根节点通常为 request +- 响应也使用 XML,根节点通常为 response +- 响应通常包含 flag、code、message 三个固定字段 + +官方白皮书中明确说明: + +- 很多接口是同步接口,返回 success 不只是“消息接收成功”,而是代表业务已处理完成 +- 批量接口通常会在一个订单下承载多个 item 或 order 节点 +- 非叶子节点通常允许增加 remark 和 extendProps + +## 3. 通用字段与约定 + +### 3.1 常见主键字段 + +- ownerCode:货主编码 +- warehouseCode:仓库编码,统仓统配等场景常填 OTHER +- itemCode:ERP 商品编码 +- itemId:WMS 商品编码或仓储系统商品 ID,通常是条件必填 +- orderCode:单据编码 +- orderId:仓储系统单据编码 +- outBizCode:外部业务编码,常作为幂等键 + +### 3.2 常见状态枚举 + +订单类状态常见值: + +- NEW:未开始处理 +- ACCEPT:仓库接单 +- PRINT:打印 +- PICK:拣货 +- CHECK:复核 +- PACKAGE:打包 +- WEIGH:称重 +- READY:待提货 +- DELIVERED:已发货 +- PARTDELIVERED:部分发货完成 +- PARTFULFILLED:部分收货完成 +- FULFILLED:收货完成 +- EXCEPTION:异常 +- CANCELED:取消 +- CLOSED:关闭 +- REJECT:拒单 +- REFUSE:客户拒签 +- SIGN:签收 + +库存类常见值: + +- ZP:正品 +- CC:残次 +- JS:机损 +- XS:箱损 +- FP:废品 +- ZT:在途库存 +- DJ:冻结 +- OTHER:其他 + +### 3.3 常见业务规则 + +- 组合商品、条码、批次、生产日期、过期日期、生产批号等字段在多个接口里复用 +- 一些接口对 itemId 有条件必填要求,通常与仓库是否自定义 WMS 商品编码有关 +- 多次收货、多次发货、多次确认类接口会使用 confirmType +- 分批发送时,totalOrderLines 常用于说明总行数,接收方据此判断是否收齐 + +## 4. 接口地图 + +以下为官方文档 5.x 章节的接口目录,按业务域整理。 + +### 4.1 商品与商品映射 + +- 5.1 商品查询接口:taobao.qimen.singleitem.query / singleitem.query +- 5.2 商品同步接口:taobao.qimen.singleitem.synchronize / singleitem.synchronize +- 5.3 商品同步接口(批量):taobao.qimen.items.synchronize / items.synchronize +- 5.4 组合商品接口:taobao.qimen.combineitem.synchronize / combineitem.synchronize +- 5.5 创建前后端商品映射接口:taobao.qimen.itemmapping.create / itemmapping.create +- 5.6 前后端商品映射查询接口:taobao.qimen.itemmapping.query / itemmapping.query + +### 4.2 入库与退货入库 + +- 5.7 入库单创建接口:taobao.qimen.entryorder.create / entryorder.create +- 5.8 入库单确认接口:taobao.qimen.entryorder.confirm / entryorder.confirm +- 5.9 入库单查询接口:taobao.qimen.entryorder.query / entryorder.query +- 5.10 退货入库单创建接口:taobao.qimen.returnorder.create / returnorder.create +- 5.11 退货入库单确认接口:taobao.qimen.returnorder.confirm / returnorder.confirm +- 5.12 退货入库单查询接口:taobao.qimen.returnorder.query / returnorder.query + +### 4.3 出库、发货与确认 + +- 5.13 出库单创建接口:taobao.qimen.stockout.create / stockout.create +- 5.14 出库单确认接口:taobao.qimen.stockout.confirm / stockout.confirm +- 5.15 出库单查询接口:taobao.qimen.stockout.query / stockout.query +- 5.16 发货单创建接口:taobao.qimen.deliveryorder.create / deliveryorder.create +- 5.17 发货单创建接口(批量):taobao.qimen.deliveryorder.batchcreate / deliveryorder.batchcreate +- 5.18 发货单创建结果通知接口(批量):taobao.qimen.deliveryorder.batchcreate.answer / deliveryorder.batchcreate.answer +- 5.19 发货单确认接口:taobao.qimen.deliveryorder.confirm / deliveryorder.confirm +- 5.20 发货单确认接口(批量):taobao.qimen.deliveryorder.batchconfirm / deliveryorder.batchconfirm +- 5.21 发货单查询接口:taobao.qimen.deliveryorder.query / deliveryorder.query + +### 4.4 SN 与订单流水 + +- 5.22 订单SN通知接口:taobao.qimen.order.sn.report / order.sn.report +- 5.23 发货单SN通知接口:taobao.qimen.sn.report / sn.report +- 5.24 订单流水查询接口:taobao.qimen.orderprocess.query / orderprocess.query +- 5.25 订单状态查询接口(批量):taobao.qimen.orderstatus.batchquery / orderstatus.batchquery +- 5.26 订单流水通知接口:taobao.qimen.orderprocess.report / orderprocess.report +- 5.27 订单异常通知接口:taobao.qimen.orderexception.report / orderexception.report + +### 4.5 异常、退货、缺货与挂起 + +- 5.28 退货异常包裹单通知接口:taobao.qimen.returnapply.report / returnapply.report +- 5.29 退货包裹状态通知接口:taobao.qimen.returnpackage.report / returnpackage.report +- 5.30 发货单缺货通知接口:taobao.qimen.itemlack.report / itemlack.report +- 5.31 发货单缺货查询接口:taobao.qimen.itemlack.query / itemlack.query +- 5.32 单据取消接口:taobao.qimen.order.cancel / order.cancel +- 5.33 单据挂起(恢复)接口:taobao.qimen.order.pending / order.pending + +### 4.6 库存、仓库、加工与异动 + +- 5.34 库存查询接口(多商品):taobao.qimen.inventory.query / inventory.query +- 5.35 库存查询接口(多条件):taobao.qimen.stock.query / stock.query +- 5.36 仓库查询接口:taobao.qimen.warehouseinfo.query / warehouseinfo.query +- 5.37 仓库同步接口:taobao.qimen.warehouseinfo.synchronize / warehouseinfo.synchronize +- 5.38 库存盘点通知接口:taobao.qimen.inventory.report / inventory.report +- 5.39 库存盘点查询接口:taobao.qimen.inventorycheck.query / inventorycheck.query +- 5.40 仓内加工单创建接口:taobao.qimen.storeprocess.create / storeprocess.create +- 5.41 仓内加工单确认接口:taobao.qimen.storeprocess.confirm / storeprocess.confirm +- 5.42 库存异动通知接口:taobao.qimen.stockchange.report / stockchange.report + +### 4.7 店铺、波次、调拨、规则与统计 + +- 5.43 店铺同步接口:taobao.qimen.shop.synchronize / shop.synchronize +- 5.44 发货单波次通知接口:taobao.qimen.wavenum.report / wavenum.report +- 5.45 调拨单创建接口:taobao.qimen.transferorder.create / transferorder.create +- 5.46 调拨单查询接口:taobao.qimen.transferorder.query / transferorder.query +- 5.47 调拨单通知接口:taobao.qimen.transferorder.report / transferorder.report +- 5.48 渠道间库存规则设置接口:taobao.qimen.inventoryrule.create / inventoryrule.create +- 5.49 库存汇总报表查询接口:taobao.qimen.inventorysum.query / inventorysum.query +- 5.50 订单出库统计查询接口:taobao.qimen.deliveryordersum.query / deliveryordersum.query + +### 4.8 基础能力 + +- 5.51 心跳接口:taobao.qimen.service.heartbeat / service.heartbeat +- 5.52 供应商信息同步接口:taobao.qimen.supplier.synchronize / supplier.synchronize +- 5.53 配送公司信息查询:taobao.qimen.expressinfo.query / expressinfo.query + +## 5. 官方白皮书里的关键细节 + +### 5.1 商品接口 + +- 单品查询与单品同步字段高度一致,itemCode、itemName、barCode、itemType、brand、重量、尺寸、批次、保质期相关字段都会复用 +- 批量商品同步使用 items 节点包裹 item 列表 +- 组合商品接口的核心是 itemCode、ownerCode、warehouseCode 与子商品清单 + +### 5.2 入库与退货入库 + +- entryorder.create 与 returnorder.create 都是同步创建 +- confirm 接口用于最终状态回告,不只是接收消息 +- 订单行内常包含 itemCode、itemId、planQty、actualQty、inventoryType、batchCode、productDate、expireDate、produceCode +- 入库场景支持 relatedOrders 关联单据信息 + +### 5.3 出库与发货 + +- stockout 更偏普通出库,不强调订单履约语义 +- deliveryorder 更偏订单驱动发货 +- 批量版 create/confirm 接口支持 orders 与 order 节点 +- 发货单确认会带包裹、发票、物流、重量、体积、SN、批次等信息 + +### 5.4 库存与盘点 + +- inventory.query 与 stock.query 都是库存查询,但入参组织方式不同 +- inventory.report 与 inventorycheck.query 用于盘点回传和盘点查询 +- stockchange.report 用于把引起库存变动的单据和库存变化同步给 ERP + +### 5.5 组织与基础资料 + +- warehouseinfo.query / synchronize 处理仓库基础资料 +- shop.synchronize 处理店铺基础资料 +- supplier.synchronize 处理供应商基础资料 +- expressinfo.query 处理配送公司信息 + +## 6. 本地实现落点 + +当前仓库里与奇门相关的本地实现入口主要是: + +- app/service/qimen.js:统一 XML 解析、method 路由与 XML 响应封装 +- app/service/qimenMethods/:具体奇门业务方法实现目录 +- typings/app/service/index.d.ts:qimenMethods 的类型入口 +- methods/qimen.json:当前奇门方法定义与参数结构的主索引 +- methods/changes/qimen.json:奇门文档变更记录副本 + +从代码层看,qimen.js 会先解析 XML,再根据 method 对应到 qimenMethods 下的具体模块调用。 + +## 7. 排障时的实用检查点 + +1. 先确认 method 名是否与官方文档一致,尤其是 singleitem、deliveryorder、entryorder、returnorder、stockout、inventory 这些主模块 +2. 再确认 XML 根节点和字段名是否和官方定义一致,奇门对字段名大小写和层级通常比较敏感 +3. 关注 itemId 是否被误传为空,很多接口里它是条件必填 +4. 关注 warehouseCode 是否在统仓统配场景下正确使用 OTHER +5. 批量接口要核对 totalOrderLines、currentPage、pageSize 和明细数量是否一致 +6. 发生返回 success 但业务未落库时,要继续检查本地实现是否只是接收成功而不是业务处理成功 + +## 8. 结论 + +这份奇门白皮书覆盖了 WMS 与 ERP 对接的完整主干能力,核心可以归纳为: + +- 商品主数据 +- 入库、退货入库、出库、发货 +- SN、流水、状态、异常 +- 库存、盘点、加工、异动 +- 仓库、店铺、供应商、配送公司基础资料 +- 调拨、波次、缺货、规则、统计与心跳 + +在本仓库中,奇门的本地实现已经有统一入口和方法分层,适合把本文作为日常联调与故障排查的快速备忘。 \ No newline at end of file diff --git a/methods/changes/system.json b/methods/changes/system.json index e280450..b10aa81 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -271,4 +271,49 @@ "summary": "将 storage.stockout.toOrder 标记为占位接口", "detail": "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" } + , + { + "version": "2026.04.09-system-01", + "date": "2026-04-09", + "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", + "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", + "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", + "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", + "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" + ] + } + , + { + "id": "2026.04.09-system-02", + "date": "2026-04-09", + "method": "index.recognizeLicensePlate", + "type": "added", + "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", + "detail": "新增 recognizeLicensePlate 方法,归属基础模块(index),接收 base64 图片(字段 base64/ imageBase64/ image_base64),返回识别结果包含 licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData。isNeedAuth=false, isNeedLogin=true。", + "notes": [ + "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", + "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", + "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未配置)", + "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露。" + ] + } + }, + { + "id": "2026.04.09-system-03", + "date": "2026-04-09", + "method": "index.recognizeLicensePlate", + "type": "changed", + "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", + "detail": "为简化对外契约,index.recognizeLicensePlate 的响应已从包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData 调整为仅包含 licensePlate。isNeedAuth=false, isNeedLogin=true。", + "notes": [ + "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", + "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存在。", + "文档中未包含任何云密钥或敏感配置信息。" + ] + } ] diff --git a/methods/system.json b/methods/system.json index c339b7e..5c3625f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -345,6 +345,60 @@ "response": [], "errors": [] }, + { + "method": "index.recognizeLicensePlate", + "description": "识别车牌号码(通过 base64 图片)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "base64", + "type": "string", + "required": true, + "source": "body", + "description": "base64 图片,支持 data URL 前缀(data:image/...;base64,)或纯 base64 字符串" + }, + { + "name": "imageBase64", + "type": "string", + "required": false, + "source": "body", + "description": "兼容字段(同 base64)" + }, + { + "name": "image_base64", + "type": "string", + "required": false, + "source": "body", + "description": "兼容字段(同 base64)" + } + ], + "response": [ + { + "name": "licensePlate", + "type": "string", + "description": "识别到的车牌号(对外契约,仅返回该字段)" + } + ], + "errors": [ + { + "code": "400", + "description": "base64 图片不能为空 / base64 图片格式不正确 / 图片大小不能超过 7MB" + }, + { + "code": "500", + "description": "第三方 OCR 服务调用失败或腾讯云配置未设置" + } + ] + }, { "method": "index.getI18nMessage", "description": "index.getI18nMessage 接口", @@ -3879,7 +3933,7 @@ }, { "method": "storage.entry.cancel", - "description": "作废入库单", + "description": "作废入库单(支持单条或批量作废)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -3894,23 +3948,36 @@ { "name": "id", "type": "number", - "required": true, + "required": false, "source": "body", - "description": "入库单ID" + "description": "入库单ID,兼容旧调用;与 `ids` 二选一。若同时传入 `ids`,以 `ids` 为准。" + }, + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "入库单ID数组(number[]),用于批量作废;必须为非空数组,建议批量操作使用 `ids`,优先于 `id`。" } ], "response": [ { "name": "id", "type": "number", - "required": true, - "description": "作废成功的入库单ID" + "required": false, + "description": "单条作废时返回的入库单ID" + }, + { + "name": "ids", + "type": "array", + "required": false, + "description": "批量作废时返回的已成功作废入库单ID数组(number[])" } ], "errors": [ { "code": "400", - "description": "参数不合法或已完成单据不允许作废" + "description": "参数错误/参数不合法:需传入非空的 `id` 或 `ids`;`ids` 必须为数字数组且不得包含非法或重复值" }, { "code": "404", diff --git a/test/app/controller/system.storage.transaction.test.js b/test/app/controller/system.storage.transaction.test.js index 30f20df..5417560 100644 --- a/test/app/controller/system.storage.transaction.test.js +++ b/test/app/controller/system.storage.transaction.test.js @@ -253,6 +253,22 @@ describe('test/app/controller/system.storage.transaction.test.js', () => { assert.ok(Number(row.quantity) > 0, `record ${row.id}: quantity 应 > 0, 实际: ${row.quantity}`); + // 前后快照字段存在 + assert.ok(Number.isFinite(Number(row.before_quantity)), + `record ${row.id}: before_quantity 应存在, 实际: ${row.before_quantity}`); + assert.ok(Number.isFinite(Number(row.after_quantity)), + `record ${row.id}: after_quantity 应存在, 实际: ${row.after_quantity}`); + assert.ok(Number.isFinite(Number(row.before_locked_quantity)), + `record ${row.id}: before_locked_quantity 应存在, 实际: ${row.before_locked_quantity}`); + assert.ok(Number.isFinite(Number(row.after_locked_quantity)), + `record ${row.id}: after_locked_quantity 应存在, 实际: ${row.after_locked_quantity}`); + + // 快照关系应与流水数量一致 + assert.equal(Number(row.after_quantity) - Number(row.before_quantity), Number(row.quantity), + `record ${row.id}: after_quantity - before_quantity 应等于 quantity`); + assert.equal(Number(row.after_locked_quantity), Number(row.before_locked_quantity), + `record ${row.id}: 入库路径锁定数量前后应保持一致`); + // stock_id > 0 assert.ok(Number(row.stock_id) > 0, `record ${row.id}: stock_id 应 > 0, 实际: ${row.stock_id}`); diff --git a/test/app/service/systemMethods/storeWarehouse/store.test.js b/test/app/service/systemMethods/storeWarehouse/store.test.js new file mode 100644 index 0000000..90ea02d --- /dev/null +++ b/test/app/service/systemMethods/storeWarehouse/store.test.js @@ -0,0 +1,157 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StoreWarehouseStoreService = require('../../../../../app/service/systemMethods/storeWarehouse/store'); + +function createContext(options = {}) { + const { + includeList = true, + includeSign = true, + } = options; + + const actionCalls = { + list: [], + sign: [], + }; + + const storeWarehouse = {}; + + if (includeList) { + storeWarehouse.list = async function list(data) { + actionCalls.list.push(data); + data.touched = true; + return { + received: data, + }; + }; + } + + if (includeSign) { + storeWarehouse.sign = async function sign(data) { + actionCalls.sign.push(data); + data.touched = true; + return { + received: data, + }; + }; + } + + const ctx = { + app: { + config: {}, + }, + service: { + systems: { + storeWarehouse, + }, + }, + }; + + return { + actionCalls, + ctx, + }; +} + +describe('test/app/service/systemMethods/storeWarehouse/store.test.js', () => { + it('should copy payload before calling list', async () => { + const { actionCalls, ctx } = createContext(); + const service = new StoreWarehouseStoreService(ctx); + const payload = { + page: 1, + page_size: 20, + nested: { + keep: true, + }, + }; + + const result = await service.list(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(actionCalls.list.length, 1); + assert.notStrictEqual(actionCalls.list[0], payload); + assert.deepEqual(actionCalls.list[0], { + page: 1, + page_size: 20, + nested: { + keep: true, + }, + touched: true, + }); + assert.equal(payload.touched, undefined); + assert.deepEqual(payload, { + page: 1, + page_size: 20, + nested: { + keep: true, + }, + }); + }); + + it('should copy payload before calling sign', async () => { + const { actionCalls, ctx } = createContext(); + const service = new StoreWarehouseStoreService(ctx); + const payload = { + warehouse_id: 1001, + nested: { + keep: true, + }, + }; + + const result = await service.sign(payload); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, 'ok'); + assert.equal(actionCalls.sign.length, 1); + assert.notStrictEqual(actionCalls.sign[0], payload); + assert.deepEqual(actionCalls.sign[0], { + warehouse_id: 1001, + nested: { + keep: true, + }, + touched: true, + }); + assert.equal(payload.touched, undefined); + assert.deepEqual(payload, { + warehouse_id: 1001, + nested: { + keep: true, + }, + }); + }); + + it('should keep the failure fallback for missing list method', async () => { + const { actionCalls, ctx } = createContext({ + includeList: false, + }); + const service = new StoreWarehouseStoreService(ctx); + + const result = await service.list({ + page: 1, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '获取签约列表失败'); + assert.equal(Number(result.code), 500); + assert.equal(actionCalls.list.length, 0); + assert.equal(actionCalls.sign.length, 0); + }); + + it('should keep the failure fallback for missing sign method', async () => { + const { actionCalls, ctx } = createContext({ + includeSign: false, + }); + const service = new StoreWarehouseStoreService(ctx); + + const result = await service.sign({ + warehouse_id: 1001, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '签约失败'); + assert.equal(Number(result.code), 500); + assert.equal(actionCalls.list.length, 0); + assert.equal(actionCalls.sign.length, 0); + }); +}); diff --git a/test/app/service/systems/auth.user.loginWechatCode.test.js b/test/app/service/systems/auth.user.loginWechatCode.test.js index 7d559fd..78150c7 100644 --- a/test/app/service/systems/auth.user.loginWechatCode.test.js +++ b/test/app/service/systems/auth.user.loginWechatCode.test.js @@ -100,4 +100,57 @@ describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => { assert.equal(result.code, 0); assert.match(String(result.message || ''), /客户端编码/); }); + + it('should resolve login event and parse ye4s user id from redis message', async () => { + const { service } = createServiceHarness(); + const listeners = new Map(); + + const subscriber = { + on(event, handler) { + listeners.set(event, handler); + return this; + }, + removeListener(event, handler) { + if (listeners.get(event) === handler) { + listeners.delete(event); + } + return this; + }, + async subscribe(channel) { + setImmediate(() => { + const messageHandler = listeners.get('message'); + if (messageHandler) { + messageHandler(channel, JSON.stringify({ ye4sUserId: 88 })); + } + }); + }, + unsubscribe() { + return Promise.resolve(); + }, + quit() { + return Promise.resolve(); + }, + disconnect() {}, + }; + + service.app.redis = { + get(name) { + if (name !== 'cache') { + return null; + } + return { + duplicate() { + return subscriber; + }, + }; + }, + }; + + const result = await service.waitForWechatLoginEvent('AB12CD', 50); + + assert.equal(result.timed_out, false); + assert.equal(result.reason, 'event'); + assert.equal(result.ye4s_user_id, 88); + assert.deepEqual(result.event, { ye4sUserId: 88 }); + }); }); diff --git a/test/app/service/systems/license_plate.test.js b/test/app/service/systems/license_plate.test.js new file mode 100644 index 0000000..c3e8837 --- /dev/null +++ b/test/app/service/systems/license_plate.test.js @@ -0,0 +1,75 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const LicensePlateService = require('../../../../app/service/systems/license_plate'); + +const fixtureImagePath = path.join(__dirname, '../../../../temp/cp.png'); +const fixtureImageBase64 = fs.readFileSync(fixtureImagePath).toString('base64'); + +class TestLicensePlateService extends LicensePlateService { + buildTencentCloudRequest(requestConfig) { + this.requestAction = requestConfig.action; + return super.buildTencentCloudRequest(requestConfig); + } + + async sendTencentCloudRequest(requestConfig) { + this.requestConfig = requestConfig; + return { + Response: { + LicensePlate: '桂MMU905', + Confidence: 98, + Color: '蓝色', + RequestId: 'req-test-001', + }, + }; + } +} + +function createService(overrides = {}) { + const ctx = { + app: { + config: { + tencentCloud: { + appId: 1234567890, + secretId: 'AKID-public-1234567890', + secretKey: 'PUBLICSECRETKEY1234567890', + region: 'ap-guangzhou', + }, + cos: { + region: 'ap-guangzhou', + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + ...overrides, + }; + + return new TestLicensePlateService(ctx); +} + +describe('test/app/service/systems/license_plate.test.js', () => { + it('should read fixture image and return normalized recognition result', async () => { + const service = createService(); + + const result = await service.recognizeLicensePlate(fixtureImageBase64); + + assert.equal(service.requestAction, 'LicensePlateOCR'); + assert.equal(JSON.parse(service.requestConfig.payloadString).ImageBase64, fixtureImageBase64); + assert.equal(result.licensePlate, '桂MMU905'); + }); + + it('should reject empty or invalid base64 input', async () => { + const service = createService(); + + await assert.rejects( + () => service.recognizeLicensePlate('not-a-base64-image'), + /base64 图片格式不正确/ + ); + }); +}); \ No newline at end of file diff --git a/test/app/service/systems/stock_transaction.create.test.js b/test/app/service/systems/stock_transaction.create.test.js new file mode 100644 index 0000000..9bf7a1f --- /dev/null +++ b/test/app/service/systems/stock_transaction.create.test.js @@ -0,0 +1,85 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StockTransactionService = require('../../../../app/service/systems/stock_transaction'); + +function createServiceHarness() { + const calls = { + createArgs: null, + }; + + const model = { + StockTransaction: { + async create(payload, options) { + calls.createArgs = { + payload, + options, + }; + return { + id: 1, + ...payload, + }; + }, + }, + }; + + const ctx = { + model, + app: { + model, + }, + }; + + const service = new StockTransactionService(ctx); + + return { + service, + calls, + }; +} + +describe('test/app/service/systems/stock_transaction.create.test.js', () => { + it('should create stock transaction with snapshot fields', async () => { + const { service, calls } = createServiceHarness(); + const transaction = { + id: 'tx-1', + }; + + const result = await service.create({ + transaction_type: 'INBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + storage_id: 300001, + space_id: 400001, + quantity: 12, + batch_no: 'BATCH-001', + inventory_type: 'ZP', + order_type: 'SCRK', + order_no: 'EO-001', + order_id: 500001, + receiving_id: 600001, + entry_order_id: 700001, + operator_id: 'op-1', + operator_name: '测试人员', + remark: '测试流水', + before_quantity: 88, + after_quantity: 100, + before_locked_quantity: 5, + after_locked_quantity: 5, + created_at: new Date('2026-04-09T08:00:00Z'), + }, { + transaction, + }); + + assert.equal(result.id, 1); + assert.ok(calls.createArgs, '应调用 StockTransaction.create'); + assert.equal(calls.createArgs.options.transaction, transaction); + assert.equal(calls.createArgs.payload.before_quantity, 88); + assert.equal(calls.createArgs.payload.after_quantity, 100); + assert.equal(calls.createArgs.payload.before_locked_quantity, 5); + assert.equal(calls.createArgs.payload.after_locked_quantity, 5); + assert.equal(calls.createArgs.payload.quantity, 12); + assert.equal(calls.createArgs.payload.transaction_type, 'INBOUND'); + }); +}); diff --git a/test/app/service/systems/storage.entry.cancel.test.js b/test/app/service/systems/storage.entry.cancel.test.js new file mode 100644 index 0000000..eb67532 --- /dev/null +++ b/test/app/service/systems/storage.entry.cancel.test.js @@ -0,0 +1,171 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const EntryService = require('../../../../app/service/systems/storage/entry'); + +function createOrder(id, orderStatus = 'CREATED') { + return { + id, + warehouse_id: 1001, + is_enabled: 1, + deleted_at: null, + order_status: orderStatus, + updateCalls: [], + async update(values, options = {}) { + this.updateCalls.push({ + values, + options, + }); + Object.assign(this, values); + return this; + }, + }; +} + +function createServiceHarness(orders = []) { + const orderMap = new Map(orders.map(order => [ Number(order.id), order ])); + const transaction = { + commitCalls: 0, + rollbackCalls: 0, + async commit() { + this.commitCalls += 1; + }, + async rollback() { + this.rollbackCalls += 1; + }, + }; + + const ctx = { + user: { + store_id: 1001, + }, + app: { + Sequelize: { + Op: {}, + }, + coreLogger: { + warn() {}, + error() {}, + }, + }, + model: { + async transaction() { + return transaction; + }, + EntryOrder: { + async findOne({ where = {} }) { + const order = orderMap.get(Number(where.id)); + if (!order) { + return null; + } + + if (Number(where.warehouse_id) !== Number(order.warehouse_id)) { + return null; + } + + if (Object.prototype.hasOwnProperty.call(where, 'is_enabled') && Number(where.is_enabled) !== Number(order.is_enabled)) { + return null; + } + + if (Object.prototype.hasOwnProperty.call(where, 'deleted_at') && where.deleted_at === null && order.deleted_at !== null) { + return null; + } + + return order; + }, + }, + }, + }; + + const service = new EntryService(ctx); + + return { + service, + transaction, + orders: orderMap, + }; +} + +describe('test/app/service/systems/storage.entry.cancel.test.js', () => { + it('should cancel single entry order by id', async () => { + const order = createOrder(11); + const { service, transaction } = createServiceHarness([ order ]); + + const result = await service.cancel({ + id: 11, + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '作废成功'); + assert.deepEqual(result.data, { id: 11 }); + assert.equal(order.order_status, 'CANCELLED'); + assert.equal(order.updateCalls.length, 1); + assert.equal(transaction.commitCalls, 1); + assert.equal(transaction.rollbackCalls, 0); + }); + + it('should cancel batch entry orders by ids', async () => { + const orderA = createOrder(21); + const orderB = createOrder(22); + const { service, transaction } = createServiceHarness([ orderA, orderB ]); + + const result = await service.cancel({ + ids: [ 21, 22 ], + }); + + assert.equal(result.code, 200); + assert.equal(result.message, '作废成功'); + assert.deepEqual(result.data, { ids: [ 21, 22 ] }); + assert.equal(orderA.order_status, 'CANCELLED'); + assert.equal(orderB.order_status, 'CANCELLED'); + assert.equal(orderA.updateCalls.length, 1); + assert.equal(orderB.updateCalls.length, 1); + assert.equal(transaction.commitCalls, 1); + assert.equal(transaction.rollbackCalls, 0); + }); + + it('should reject empty or illegal ids', async () => { + const { service } = createServiceHarness(); + + const emptyResult = await service.cancel({ + ids: [], + }); + + assert.equal(emptyResult.code, 400); + assert.match(String(emptyResult.message || ''), /ids 必须是非空数组/); + + const illegalResult = await service.cancel({ + ids: [ 'abc' ], + }); + + assert.equal(illegalResult.code, 400); + assert.match(String(illegalResult.message || ''), /ids 必须为正整数数组/); + }); + + it('should reject batch cancel when any order is missing or completed', async () => { + const existingOrder = createOrder(31); + const completedOrder = createOrder(32, 'COMPLETED'); + const { service, transaction } = createServiceHarness([ existingOrder, completedOrder ]); + + const missingResult = await service.cancel({ + ids: [ 31, 999 ], + }); + + assert.equal(missingResult.code, 404); + assert.match(String(missingResult.message || ''), /入库单不存在或无权访问/); + assert.equal(existingOrder.updateCalls.length, 0); + assert.equal(transaction.commitCalls, 0); + assert.equal(transaction.rollbackCalls, 0); + + const statusResult = await service.cancel({ + ids: [ 31, 32 ], + }); + + assert.equal(statusResult.code, 400); + assert.match(String(statusResult.message || ''), /已完成入库单不允许作废/); + assert.equal(existingOrder.updateCalls.length, 0); + assert.equal(completedOrder.updateCalls.length, 0); + assert.equal(transaction.commitCalls, 0); + assert.equal(transaction.rollbackCalls, 0); + }); +}); diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js index b425a28..53e8cb8 100644 --- a/test/app/service/systems/storage.receiving.report.test.js +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -180,6 +180,33 @@ function createCompleteReceivingService({ }; } +function createReceivingSnapshot(deliveryMethod) { + return { + id: 123, + receiving_number: 'RCV202604040001', + warehouse_id: 2001, + store_id: 3001, + store_name: '测试货主', + delivery_method: deliveryMethod, + license_plate: '粤A12345', + tracking_number: 'YT123456789', + total_boxes: 3, + total_pallets: 1, + remark: '完成收货测试', + receiving_end_time: new Date('2026-04-04T12:30:00Z'), + details: [ + { + id: 501, + product_name: '测试商品A', + system_product_id: 9001, + barcode: 'SKU-001', + actual_quantity: 8, + weight: 12, + }, + ], + }; +} + describe('test/app/service/systems/storage.receiving.report.test.js', () => { it('should build and upload completion excel in a single sheet with one preview column', async () => { const { service, excelCalls } = createService(); @@ -303,10 +330,139 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { assert.equal(options.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); assert.equal(options.subject.id, 2001); assert.equal(options.subject.name, '测试仓库'); - assert.match(String(options.content || ''), /收货单RCV202604040001已完成/); + assert.match(String(options.content || ''), /收货单号:RCV202604040001 已完成/); assert.equal(result.success, true); }); + it('should show only license plate for truck in notice content and report main rows', async () => { + const { service, excelCalls, noticeCalls } = createService(); + const receiving = createReceivingSnapshot('truck'); + + await service.sendCompletionNotice({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + }); + + await service.uploadCompletionExcelReport({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map(), + receivingImages: [], + }); + + assert.equal(noticeCalls.length, 1); + assert.match(String(noticeCalls[0].content || ''), /车牌号:粤A12345/); + assert.ok(!String(noticeCalls[0].content || '').includes('物流单号')); + + assert.equal(excelCalls.length, 1); + const [ sheet ] = excelCalls[0].sheets; + const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || '')); + assert.ok(labels.includes('车牌号')); + assert.ok(!labels.includes('物流单号')); + }); + + it('should show only tracking number for express in notice content and report main rows', async () => { + const { service, excelCalls, noticeCalls } = createService(); + const receiving = createReceivingSnapshot('express'); + + await service.sendCompletionNotice({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + }); + + await service.uploadCompletionExcelReport({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map(), + receivingImages: [], + }); + + assert.equal(noticeCalls.length, 1); + assert.match(String(noticeCalls[0].content || ''), /物流单号:YT123456789/); + assert.ok(!String(noticeCalls[0].content || '').includes('车牌号')); + + assert.equal(excelCalls.length, 1); + const [ sheet ] = excelCalls[0].sheets; + const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || '')); + assert.ok(labels.includes('物流单号')); + assert.ok(!labels.includes('车牌号')); + }); + + it('should hide both contact fields for other delivery methods', async () => { + const { service, excelCalls, noticeCalls } = createService(); + const receiving = createReceivingSnapshot('other'); + + await service.sendCompletionNotice({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + }); + + await service.uploadCompletionExcelReport({ + receiving, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map(), + receivingImages: [], + }); + + assert.equal(noticeCalls.length, 1); + assert.ok(!String(noticeCalls[0].content || '').includes('车牌号')); + assert.ok(!String(noticeCalls[0].content || '').includes('物流单号')); + + assert.equal(excelCalls.length, 1); + const [ sheet ] = excelCalls[0].sheets; + const labels = sheet.rows.filter(Array.isArray).map(item => String(item[0] || '')); + assert.ok(!labels.includes('车牌号')); + assert.ok(!labels.includes('物流单号')); + }); + it('should support nested notice.index service shape from Egg loader', async () => { const noticeCalls = []; const ctx = { @@ -407,7 +563,7 @@ describe('test/app/service/systems/storage.receiving.report.test.js', () => { system_product_id: null, barcode: '', weight: 0, - actual_quantity: 0, + actual_quantity: 1, }, itemImages: [], }); diff --git a/test/app/service/systems/upload.test.js b/test/app/service/systems/upload.test.js index 17a4ce2..5ba80c1 100644 --- a/test/app/service/systems/upload.test.js +++ b/test/app/service/systems/upload.test.js @@ -16,9 +16,37 @@ function createService(overrides = {}) { const ctx = { app: { config: { + tencentCloud: { + appId: 1234567890, + secretId: 'AKID-public-1234567890', + secretKey: 'PUBLICSECRETKEY1234567890', + }, cos: { cdnurl: 'https://cdn.example.com', uploadurl: 'https://upload.example.com', + bucket: 'bucket-example', + region: 'ap-guangzhou', + expire: 600, + savekey: '/{warehouseId}/{dir}/{year}{mon}{day}/{filemd5}{.suffix}', + maxsize: '100M', + mimetype: 'jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx,apk', + dirs: { + image: '/images/', + document: '/documents/', + apk: '/apks/', + temp: '/temp/', + }, + }, + fileTypes: { + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'document', + }, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async query() { + return [{ remaining_bytes: 1024 * 1024 * 1024 }]; }, }, }, @@ -69,6 +97,33 @@ function createService(overrides = {}) { } describe('test/app/service/systems/upload.test.js', () => { + it('should prefer tencent cloud auth config while keeping COS upload parameters', async () => { + const { service } = createService({ + model: { + File: { + async findOne() { + return null; + }, + }, + }, + }); + + const result = await service.getUploadParams({ + fileName: 'report.xlsx', + fileType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + fileSize: 2048, + type: 'document', + md5: 'c688dd719a7260404822d7dfebdc6115', + }); + + assert.equal(result.uploadUrl, 'https://bucket-example.cos.ap-guangzhou.myqcloud.com'); + assert.equal(result.bucket, 'bucket-example'); + assert.equal(result.region, 'ap-guangzhou'); + assert.equal(result.signature.secretId, 'AKID-public-1234567890'); + assert.equal(result.data['q-ak'], 'AKID-public-1234567890'); + assert.equal(result.isNew, true); + }); + it('should create file reference with warehouse and creator when saving upload record', async () => { const { service, fileCreates, fileReferenceCreates } = createService();