1
This commit is contained in:
parent
e7fcd2549e
commit
5ef99e3bed
1
.github/agents/开发.agent.md
vendored
1
.github/agents/开发.agent.md
vendored
@ -167,6 +167,7 @@ model: GPT-5.3-Codex (copilot)
|
|||||||
10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致
|
10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致
|
||||||
11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中
|
11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中
|
||||||
12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程
|
12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程
|
||||||
|
13. system块的methods禁止入参warehouse_id,必须由服务端从当前上下文自动注入,前端无需传递。
|
||||||
|
|
||||||
## 关键定位地图
|
## 关键定位地图
|
||||||
|
|
||||||
|
|||||||
32
.github/agents/数据库.agent.md
vendored
32
.github/agents/数据库.agent.md
vendored
@ -1,4 +1,4 @@
|
|||||||
---
|
---
|
||||||
name: wms-db-agent
|
name: wms-db-agent
|
||||||
description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。"
|
description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。"
|
||||||
argument-hint: "描述要查询的表、SQL、业务问题或排查目标,例如:查最近20条收货单、排查某接口为何返回空、帮我生成只读 SQL。"
|
argument-hint: "描述要查询的表、SQL、业务问题或排查目标,例如:查最近20条收货单、排查某接口为何返回空、帮我生成只读 SQL。"
|
||||||
@ -46,6 +46,36 @@ model : DeepSeek V4 Pro (deepseek)
|
|||||||
- 所有回复必须以 `[DB]` 开头
|
- 所有回复必须以 `[DB]` 开头
|
||||||
- 优先给结论、关键字段和下一步建议
|
- 优先给结论、关键字段和下一步建议
|
||||||
|
|
||||||
|
|
||||||
|
## 环境路由规则(⚠️ 必读)
|
||||||
|
|
||||||
|
**每次查询必须明确标注是开发环境还是生产环境,禁止混淆!**
|
||||||
|
|
||||||
|
### 查询方式速查
|
||||||
|
|
||||||
|
| 环境 | 迁移状态查询 | 数据查询 |
|
||||||
|
|------|------------|---------|
|
||||||
|
| **开发环境** | `npx sequelize-cli db:migrate:status` | `powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "..." -AsTable` |
|
||||||
|
| **生产环境** | `$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --env production` | SSH+mysql 或 `$env:NODE_ENV='production'; npx sequelize-cli ... --env production` |
|
||||||
|
|
||||||
|
- 开发环境:`config/config.local.js` → `mysql.clients.wms`
|
||||||
|
- 生产环境:`config/config.default.js` → `config.sequelize`
|
||||||
|
|
||||||
|
### 🔴 红线
|
||||||
|
|
||||||
|
1. **绝对禁止**:用不加 `--env production` 的命令查询,然后声称是生产环境。`script/db-query.ps1` 永远是开发环境!
|
||||||
|
2. 每次返回结果第一行必须标注环境:`[DB] 开发环境 (config.local.js)` 或 `[DB] 生产环境 (config.default.js)`
|
||||||
|
3. 查询迁移状态时必须**两边都查**做对比
|
||||||
|
4. 若用户提到"生产"二字,必须使用生产环境命令
|
||||||
|
|
||||||
|
### 当前环境差异(2026-06-25)
|
||||||
|
|
||||||
|
| 项目 | 开发环境 | 生产环境 |
|
||||||
|
|------|---------|---------|
|
||||||
|
| SequelizeMeta 记录数 | 127+ | 123 |
|
||||||
|
| 最新迁移 | `20260623140000` | `20260622110000` |
|
||||||
|
| 缺失迁移 | 无 | 4条 |
|
||||||
|
|
||||||
## 常用命令模板
|
## 常用命令模板
|
||||||
|
|
||||||
### 1) 当前连接库自检
|
### 1) 当前连接库自检
|
||||||
|
|||||||
2
.github/agents/调度.agent.md
vendored
2
.github/agents/调度.agent.md
vendored
@ -17,7 +17,7 @@ model: DeepSeek V4 Pro (deepseek)
|
|||||||
- 将子任务委派给最合适的专属 agent
|
- 将子任务委派给最合适的专属 agent
|
||||||
- 等待各子任务返回结果,汇总后给出最终结论
|
- 等待各子任务返回结果,汇总后给出最终结论
|
||||||
- **不深入专属 agent 的内部技术细节**,只关注其输入、输出和完成状态
|
- **不深入专属 agent 的内部技术细节**,只关注其输入、输出和完成状态
|
||||||
|
- 本项目无需重启, 也不需要你直接修改代码、数据库或 Redis;所有操作都必须通过专属 agent 执行
|
||||||
## 适用范围
|
## 适用范围
|
||||||
|
|
||||||
以下场景优先使用本 Agent:
|
以下场景优先使用本 Agent:
|
||||||
|
|||||||
@ -132,7 +132,7 @@ class ExpressPrintPayloadBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (normalizedPlatform === 'sph') {
|
if (normalizedPlatform === 'sph') {
|
||||||
this.applySphTaskDynamicFields(payload, orders);
|
payload.taskList = this.buildTaskListFromOrders(orders, idGenerator);
|
||||||
} else {
|
} else {
|
||||||
if (!isPlainObject(payload.task)) {
|
if (!isPlainObject(payload.task)) {
|
||||||
payload.task = {};
|
payload.task = {};
|
||||||
@ -170,6 +170,28 @@ class ExpressPrintPayloadBuilder {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将 orders 映射为 SPH taskList 项。
|
||||||
|
* SPH 的 task item 结构(taskID / printInfo / customInfo / extendData 等)与通用 document 结构不兼容,
|
||||||
|
* 因此需要独立的构建方法,但处理模式与 buildDocumentsFromOrders 一致:
|
||||||
|
* 遍历 orders → deepClone → 分配唯一 ID → 放入数组。
|
||||||
|
*
|
||||||
|
* @param {Array<Object>} orders 订单数组,每个元素直接是 SPH task item 对象。
|
||||||
|
* @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。
|
||||||
|
* @return {Array<Object>} taskList 数组。
|
||||||
|
*/
|
||||||
|
buildTaskListFromOrders(orders, idGenerator) {
|
||||||
|
const taskList = [];
|
||||||
|
for (const order of orders) {
|
||||||
|
if (order && typeof order === 'object' && !Array.isArray(order)) {
|
||||||
|
const taskItem = deepClone(order);
|
||||||
|
taskItem.taskID = idGenerator.nextTaskId();
|
||||||
|
taskList.push(taskItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return taskList;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将 orders 映射为 documents。
|
* 将 orders 映射为 documents。
|
||||||
* @param {Array<Object>} orders 订单数组。
|
* @param {Array<Object>} orders 订单数组。
|
||||||
@ -188,91 +210,6 @@ class ExpressPrintPayloadBuilder {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 将 SPH 订单中的动态业务字段回填到模板 taskList[0]。
|
|
||||||
*
|
|
||||||
* 仅覆盖动态字段,避免改写模板固定结构。
|
|
||||||
*
|
|
||||||
* @param {Object} payload 打印请求 payload。
|
|
||||||
* @param {Array<Object>} orders 外部传入的订单打印数据数组。
|
|
||||||
*/
|
|
||||||
applySphTaskDynamicFields(payload, orders) {
|
|
||||||
if (!Array.isArray(payload.taskList) || !isPlainObject(payload.taskList[0])) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const sourceTask = this.resolveSphTaskFromOrders(orders);
|
|
||||||
if (!isPlainObject(sourceTask)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const targetTask = payload.taskList[0];
|
|
||||||
const dynamicFields = [
|
|
||||||
'printInfo',
|
|
||||||
'printNum',
|
|
||||||
'splitControl',
|
|
||||||
'showDeliveryLogo',
|
|
||||||
'customInfo',
|
|
||||||
'extendData',
|
|
||||||
'taskID',
|
|
||||||
];
|
|
||||||
|
|
||||||
dynamicFields.forEach(field => {
|
|
||||||
if (Object.prototype.hasOwnProperty.call(sourceTask, field)) {
|
|
||||||
targetTask[field] = deepClone(sourceTask[field]);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 从首个订单提取 SPH 动态任务数据。
|
|
||||||
*
|
|
||||||
* 优先读取标准 taskList[0];若上游直接传 task 结构(printInfo/printNum 等)也兼容。
|
|
||||||
*
|
|
||||||
* @param {Array<Object>} orders 外部传入的订单打印数据数组。
|
|
||||||
* @return {Object|null} SPH 动态任务对象。
|
|
||||||
*/
|
|
||||||
resolveSphTaskFromOrders(orders) {
|
|
||||||
if (!Array.isArray(orders) || orders.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const firstOrder = isPlainObject(orders[0]) ? orders[0] : {};
|
|
||||||
const candidates = [];
|
|
||||||
if (isPlainObject(firstOrder.print_data)) {
|
|
||||||
candidates.push(firstOrder.print_data);
|
|
||||||
}
|
|
||||||
if (isPlainObject(firstOrder)) {
|
|
||||||
candidates.push(firstOrder);
|
|
||||||
}
|
|
||||||
|
|
||||||
const sphDynamicFields = [
|
|
||||||
'printInfo',
|
|
||||||
'printNum',
|
|
||||||
'splitControl',
|
|
||||||
'showDeliveryLogo',
|
|
||||||
'customInfo',
|
|
||||||
'extendData',
|
|
||||||
'taskID',
|
|
||||||
];
|
|
||||||
|
|
||||||
for (const candidate of candidates) {
|
|
||||||
if (Array.isArray(candidate.taskList) && isPlainObject(candidate.taskList[0])) {
|
|
||||||
return candidate.taskList[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isPlainObject(candidate.taskList)) {
|
|
||||||
return candidate.taskList;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sphDynamicFields.some(field => Object.prototype.hasOwnProperty.call(candidate, field))) {
|
|
||||||
return candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析单个订单对应的 document。
|
* 解析单个订单对应的 document。
|
||||||
* @param {Object} order 订单对象。
|
* @param {Object} order 订单对象。
|
||||||
|
|||||||
@ -41,16 +41,16 @@ module.exports = app => {
|
|||||||
indexes: [
|
indexes: [
|
||||||
{
|
{
|
||||||
name: 'idx_entry_order_id',
|
name: 'idx_entry_order_id',
|
||||||
fields: ['entry_order_id'],
|
fields: [ 'entry_order_id' ],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'idx_receiving_id',
|
name: 'idx_receiving_id',
|
||||||
fields: ['receiving_id'],
|
fields: [ 'receiving_id' ],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'uk_entry_order_receiving',
|
name: 'uk_entry_order_receiving',
|
||||||
unique: true,
|
unique: true,
|
||||||
fields: ['entry_order_id', 'receiving_id'],
|
fields: [ 'entry_order_id', 'receiving_id' ],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|||||||
261
app/model/order_stockout.js
Normal file
261
app/model/order_stockout.js
Normal file
@ -0,0 +1,261 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 出库单主表 Model。
|
||||||
|
*
|
||||||
|
* 对应数据库表 `wms_order_stockout`,存储奇门 stockout.create 接口下发的出库单信息。
|
||||||
|
*
|
||||||
|
* 业务类型枚举值:
|
||||||
|
* - JYCK:一般交易出库
|
||||||
|
* - HHCK:换货出库
|
||||||
|
* - BFCK:补发出库
|
||||||
|
* - QTCK:其他出库
|
||||||
|
* @param {import('egg').Application} app - Egg 应用实例
|
||||||
|
*/
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BIGINT, ENUM, TEXT, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize;
|
||||||
|
|
||||||
|
const OrderStockout = app.model.define('wms_order_stockout', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
stockout_order_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '出库单号(对应奇门 deliveryOrderCode)',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
order_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库等)',
|
||||||
|
validate: {
|
||||||
|
notEmpty: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
total_order_lines: {
|
||||||
|
type: INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '单据总行数',
|
||||||
|
},
|
||||||
|
order_create_time: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单创建时间(对应奇门 createTime)',
|
||||||
|
},
|
||||||
|
source_type: {
|
||||||
|
type: ENUM('WMS', 'API', 'QM'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'QM',
|
||||||
|
comment: '来源类型',
|
||||||
|
},
|
||||||
|
order_status: {
|
||||||
|
type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'CREATED',
|
||||||
|
comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废',
|
||||||
|
},
|
||||||
|
sync_status: {
|
||||||
|
type: ENUM('PENDING', 'SUCCESS', 'FAILED'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'PENDING',
|
||||||
|
comment: '同步状态',
|
||||||
|
},
|
||||||
|
sync_message: {
|
||||||
|
type: TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '同步返回信息',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '货主ID',
|
||||||
|
},
|
||||||
|
store_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主名称快照',
|
||||||
|
},
|
||||||
|
warehouse_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库名称快照',
|
||||||
|
},
|
||||||
|
qimen_owner_code: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '奇门货主code(对应 ownerCode)',
|
||||||
|
},
|
||||||
|
qimen_warehouse_code: {
|
||||||
|
type: STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '奇门仓库code(对应 warehouseCode)',
|
||||||
|
},
|
||||||
|
remark: {
|
||||||
|
type: STRING(500),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '备注',
|
||||||
|
},
|
||||||
|
extend_props: {
|
||||||
|
type: JSON_TYPE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '扩展属性',
|
||||||
|
},
|
||||||
|
is_enabled: {
|
||||||
|
type: TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '软删除时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_order_stockout',
|
||||||
|
comment: '出库单主表',
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_stockout_order_code',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'stockout_order_code', 'warehouse_id', 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_type',
|
||||||
|
fields: [ 'order_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_status',
|
||||||
|
fields: [ 'order_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_sync_status',
|
||||||
|
fields: [ 'sync_status' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_source_type',
|
||||||
|
fields: [ 'source_type' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_warehouse_store',
|
||||||
|
fields: [ 'warehouse_id', 'store_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_create_time',
|
||||||
|
fields: [ 'order_create_time' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_is_enabled',
|
||||||
|
fields: [ 'is_enabled' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_deleted_at',
|
||||||
|
fields: [ 'deleted_at' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关联关系定义。
|
||||||
|
* - 关联货主 / 仓库(均通过 Store 表)
|
||||||
|
* - 关联出库明细表
|
||||||
|
*/
|
||||||
|
OrderStockout.associate = function() {
|
||||||
|
const { OrderStockout, Store, OrderStockoutItems } = app.model;
|
||||||
|
|
||||||
|
// 关联仓库
|
||||||
|
OrderStockout.belongsTo(Store, {
|
||||||
|
foreignKey: 'warehouse_id',
|
||||||
|
as: 'warehouse',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联货主
|
||||||
|
OrderStockout.belongsTo(Store, {
|
||||||
|
foreignKey: 'store_id',
|
||||||
|
as: 'store',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联出库明细
|
||||||
|
OrderStockout.hasMany(OrderStockoutItems, {
|
||||||
|
foreignKey: 'order_id',
|
||||||
|
as: 'items',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- 状态机辅助方法 ----------
|
||||||
|
|
||||||
|
/** 判断订单是否处于"已创建"状态 */
|
||||||
|
OrderStockout.prototype.isCreated = function() {
|
||||||
|
return this.order_status === 'CREATED';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 判断订单是否处于"已审核"状态 */
|
||||||
|
OrderStockout.prototype.isPending = function() {
|
||||||
|
return this.order_status === 'PENDING';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 判断订单是否已完成 */
|
||||||
|
OrderStockout.prototype.isCompleted = function() {
|
||||||
|
return this.order_status === 'COMPLETED';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 判断订单是否已作废 */
|
||||||
|
OrderStockout.prototype.isCancelled = function() {
|
||||||
|
return this.order_status === 'CANCELLED';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 当前订单是否允许审核 */
|
||||||
|
OrderStockout.prototype.canConfirm = function() {
|
||||||
|
return [ 'CREATED', 'PENDING' ].includes(this.order_status);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 当前订单是否允许取消 */
|
||||||
|
OrderStockout.prototype.canCancel = function() {
|
||||||
|
return [ 'CREATED', 'PENDING' ].includes(this.order_status);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 当前订单是否允许完成 */
|
||||||
|
OrderStockout.prototype.canComplete = function() {
|
||||||
|
return [ 'PENDING' ].includes(this.order_status);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 同步是否成功 */
|
||||||
|
OrderStockout.prototype.isSyncSuccess = function() {
|
||||||
|
return this.sync_status === 'SUCCESS';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 同步是否失败 */
|
||||||
|
OrderStockout.prototype.isSyncFailed = function() {
|
||||||
|
return this.sync_status === 'FAILED';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 是否启用(未软删除) */
|
||||||
|
OrderStockout.prototype.isEnabled = function() {
|
||||||
|
return this.is_enabled === 1 && !this.deleted_at;
|
||||||
|
};
|
||||||
|
|
||||||
|
return OrderStockout;
|
||||||
|
};
|
||||||
145
app/model/order_stockout_items.js
Normal file
145
app/model/order_stockout_items.js
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 出库单明细表 Model。
|
||||||
|
*
|
||||||
|
* 对应数据库表 `wms_order_stockout_items`,存储奇门 stockout.create 接口中
|
||||||
|
* 每个 <orderLine> 节点的明细数据。
|
||||||
|
*
|
||||||
|
* 与主表 `wms_order_stockout` 通过 `order_id` 外键关联(CASCADE 删除)。
|
||||||
|
* 与库存表 `wms_stock_warehouse` 通过 `stock_id` 外键关联(RESTRICT 删除)。
|
||||||
|
* @param {import('egg').Application} app - Egg 应用实例
|
||||||
|
*/
|
||||||
|
module.exports = app => {
|
||||||
|
const { STRING, INTEGER, BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize;
|
||||||
|
|
||||||
|
const OrderStockoutItems = app.model.define('wms_order_stockout_items', {
|
||||||
|
id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
order_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '出库单ID,外键关联 wms_order_stockout.id',
|
||||||
|
},
|
||||||
|
out_biz_code: {
|
||||||
|
type: STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '外部业务编码(幂等键)',
|
||||||
|
},
|
||||||
|
order_line_no: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '订单行号(对应奇门 orderLineNo)',
|
||||||
|
},
|
||||||
|
owner_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主编码(对应奇门 ownerCode)',
|
||||||
|
},
|
||||||
|
item_code: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品编码(对应奇门 itemCode)',
|
||||||
|
},
|
||||||
|
item_id: {
|
||||||
|
type: BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'WMS商品ID(对应奇门 itemId)',
|
||||||
|
},
|
||||||
|
item_name: {
|
||||||
|
type: STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品名称',
|
||||||
|
},
|
||||||
|
plan_qty: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '计划数量(对应奇门 planQty)',
|
||||||
|
},
|
||||||
|
actual_qty: {
|
||||||
|
type: INTEGER(12),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '实发数量',
|
||||||
|
},
|
||||||
|
inventory_type: {
|
||||||
|
type: STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存类型(ZP正品/CC残次等)',
|
||||||
|
},
|
||||||
|
stock_id: {
|
||||||
|
type: BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存ID,外键关联 wms_stock_warehouse.id',
|
||||||
|
},
|
||||||
|
extend_props: {
|
||||||
|
type: JSON_TYPE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '扩展属性',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: DATE,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
}, {
|
||||||
|
tableName: 'wms_order_stockout_items',
|
||||||
|
comment: '出库明细表',
|
||||||
|
timestamps: false,
|
||||||
|
indexes: [
|
||||||
|
{
|
||||||
|
name: 'uk_order_line_no',
|
||||||
|
unique: true,
|
||||||
|
fields: [ 'order_id', 'order_line_no' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_order_id',
|
||||||
|
fields: [ 'order_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_stock_id',
|
||||||
|
fields: [ 'stock_id' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_item_code',
|
||||||
|
fields: [ 'item_code' ],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'idx_out_biz_code',
|
||||||
|
fields: [ 'out_biz_code' ],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关联关系定义。
|
||||||
|
* - 关联出库单主表
|
||||||
|
* - 关联商品 SKU(wms_stock_warehouse)
|
||||||
|
*/
|
||||||
|
OrderStockoutItems.associate = function() {
|
||||||
|
const { OrderStockoutItems, OrderStockout, StockWarehouse } = app.model;
|
||||||
|
|
||||||
|
// 关联出库单
|
||||||
|
OrderStockoutItems.belongsTo(OrderStockout, {
|
||||||
|
foreignKey: 'order_id',
|
||||||
|
as: 'order',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联商品 SKU
|
||||||
|
OrderStockoutItems.belongsTo(StockWarehouse, {
|
||||||
|
foreignKey: 'stock_id',
|
||||||
|
as: 'stock',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return OrderStockoutItems;
|
||||||
|
};
|
||||||
@ -6,7 +6,7 @@
|
|||||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 平台模型
|
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} 平台模型
|
||||||
*/
|
*/
|
||||||
module.exports = app => {
|
module.exports = app => {
|
||||||
const { STRING, INTEGER, BIGINT } = app.Sequelize;
|
const { STRING, BIGINT } = app.Sequelize;
|
||||||
|
|
||||||
const Platform = app.model.define('platform', {
|
const Platform = app.model.define('platform', {
|
||||||
code: {
|
code: {
|
||||||
|
|||||||
@ -38,10 +38,10 @@ module.exports = app => {
|
|||||||
comment: '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配',
|
comment: '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配',
|
||||||
},
|
},
|
||||||
storage_status: {
|
storage_status: {
|
||||||
type: ENUM('none', 'partial', 'all'),
|
type: ENUM('none', 'waiting', 'partial', 'all'),
|
||||||
defaultValue: 'none',
|
defaultValue: 'none',
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
comment: '入库状态:none-未入库, partial-部分入库, all-全部入库',
|
comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库',
|
||||||
},
|
},
|
||||||
delivery_method: {
|
delivery_method: {
|
||||||
type: ENUM('truck', 'express', 'air_freight', 'sea_freight', 'other'),
|
type: ENUM('truck', 'express', 'air_freight', 'sea_freight', 'other'),
|
||||||
|
|||||||
@ -61,9 +61,9 @@ module.exports = app => {
|
|||||||
comment: '收货状态',
|
comment: '收货状态',
|
||||||
},
|
},
|
||||||
storage_status: {
|
storage_status: {
|
||||||
type: ENUM('none', 'partial', 'all'),
|
type: ENUM('none', 'waiting', 'partial', 'all'),
|
||||||
defaultValue: 'none',
|
defaultValue: 'none',
|
||||||
comment: '入库状态:none-未入库, partial-部分入库, all-全部入库',
|
comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库',
|
||||||
},
|
},
|
||||||
stored_quantity: {
|
stored_quantity: {
|
||||||
type: INTEGER,
|
type: INTEGER,
|
||||||
|
|||||||
@ -18,10 +18,6 @@ class testServer extends Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async entryorderConfirm(data) {
|
|
||||||
const { ctx } = this;
|
|
||||||
return await ctx.service.systems.entryOrder.entryorderConfirm(data.id, data.isCompleted);
|
|
||||||
}
|
|
||||||
async playbackRequest(data) {
|
async playbackRequest(data) {
|
||||||
const { app } = this;
|
const { app } = this;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -75,7 +75,7 @@ class ImService extends Service {
|
|||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 获取主体员工信息
|
* 获取主体员工信息
|
||||||
* @param data {Object<>} 请求数据,包含 store_id
|
* @param {Object} data 请求数据,包含 store_id
|
||||||
* @return {Promise<{code: number, message: string, data: Array}>} 响应数据,包含员工列表
|
* @return {Promise<{code: number, message: string, data: Array}>} 响应数据,包含员工列表
|
||||||
*/
|
*/
|
||||||
async getStoreEmployees(data) {
|
async getStoreEmployees(data) {
|
||||||
|
|||||||
@ -338,7 +338,9 @@ class MainService extends Service {
|
|||||||
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||||
const now = Math.floor(Date.now() / 1000);
|
const now = Math.floor(Date.now() / 1000);
|
||||||
const expiresIn = decoded.exp - now;
|
const expiresIn = decoded.exp - now;
|
||||||
if (expiresIn < 14399 && expiresIn > 0) {
|
const renewThreshold = app.config.jwt.renewThreshold
|
||||||
|
?? (app.config.jwt.expiresIn ? app.config.jwt.expiresIn - 1 : 14399);
|
||||||
|
if (expiresIn < renewThreshold && expiresIn > 0) {
|
||||||
// 移除过期时间(exp)和签发时间(iat),保留其他payload
|
// 移除过期时间(exp)和签发时间(iat),保留其他payload
|
||||||
const payload = { ...decoded };
|
const payload = { ...decoded };
|
||||||
delete payload.exp;
|
delete payload.exp;
|
||||||
|
|||||||
@ -7,7 +7,7 @@ const { signRequest } = require('../../lib/api_sign');
|
|||||||
const MAX_RETRY = 3;
|
const MAX_RETRY = 3;
|
||||||
|
|
||||||
/** @type {number[]} 递增重试延迟(毫秒) */
|
/** @type {number[]} 递增重试延迟(毫秒) */
|
||||||
const RETRY_DELAY_MS = [2000, 5000, 15000];
|
const RETRY_DELAY_MS = [ 2000, 5000, 15000 ];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* OpenAPI 统一回调通知服务。
|
* OpenAPI 统一回调通知服务。
|
||||||
@ -166,7 +166,7 @@ class OpenapiCallbackService extends Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const appConfig = await ctx.model.ApiApp.findOne({
|
const appConfig = await ctx.model.ApiApp.findOne({
|
||||||
attributes: ['self_app_key', 'self_app_secret', 'callback_url'],
|
attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ],
|
||||||
where: {
|
where: {
|
||||||
self_app_key: normalizedAppKey,
|
self_app_key: normalizedAppKey,
|
||||||
is_enabled: 1,
|
is_enabled: 1,
|
||||||
@ -204,11 +204,10 @@ class OpenapiCallbackService extends Service {
|
|||||||
* @param {string} options.callbackUrl 回调目标 URL。
|
* @param {string} options.callbackUrl 回调目标 URL。
|
||||||
* @param {boolean} options.success 是否成功。
|
* @param {boolean} options.success 是否成功。
|
||||||
* @param {number} options.retryCount 重试次数。
|
* @param {number} options.retryCount 重试次数。
|
||||||
* @param {*} options.response 响应数据。
|
|
||||||
* @param {string} [options.error] 错误信息。
|
* @param {string} [options.error] 错误信息。
|
||||||
* @return {void} 无返回值。
|
* @return {void} 无返回值。
|
||||||
*/
|
*/
|
||||||
async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) {
|
async logCallback({ appKey, event, callbackUrl, success, retryCount, error }) {
|
||||||
const { ctx } = this;
|
const { ctx } = this;
|
||||||
const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`;
|
const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`;
|
||||||
|
|
||||||
|
|||||||
@ -23,7 +23,7 @@ class OpenapiCallbackMethodService extends MainService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const appConfig = await ctx.model.ApiApp.findOne({
|
const appConfig = await ctx.model.ApiApp.findOne({
|
||||||
attributes: ['self_app_key'],
|
attributes: [ 'self_app_key' ],
|
||||||
where: {
|
where: {
|
||||||
self_app_key: normalizedAppKey,
|
self_app_key: normalizedAppKey,
|
||||||
is_enabled: 1,
|
is_enabled: 1,
|
||||||
|
|||||||
@ -20,7 +20,7 @@ class OpenapiDeliveryorderService extends MainService {
|
|||||||
attributes: [
|
attributes: [
|
||||||
'id',
|
'id',
|
||||||
'warehouse_id',
|
'warehouse_id',
|
||||||
[app.Sequelize.col('contract.store_id'), 'store_id'],
|
[ app.Sequelize.col('contract.store_id'), 'store_id' ],
|
||||||
],
|
],
|
||||||
where: {
|
where: {
|
||||||
self_app_key: normalizedAppKey,
|
self_app_key: normalizedAppKey,
|
||||||
|
|||||||
@ -129,6 +129,26 @@ class OpenapiOrderService extends MainService {
|
|||||||
|
|
||||||
await transaction.commit();
|
await transaction.commit();
|
||||||
|
|
||||||
|
// 写入取消操作日志(不影响主流程)
|
||||||
|
try {
|
||||||
|
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||||||
|
const appKey = String(query.app_key || '').trim();
|
||||||
|
await this.ctx.model.OperationLog.create({
|
||||||
|
business_type: 'order',
|
||||||
|
business_id: String(existingOrder.id),
|
||||||
|
operation_code: 'ORDER_CANCEL',
|
||||||
|
operator_id: null,
|
||||||
|
operator_name: appKey ? `openapi:${appKey}` : 'openapi',
|
||||||
|
external_log_type: 'NONE',
|
||||||
|
warehouse_id: info.warehouseId || null,
|
||||||
|
platform_code: appKey || 'SYSTEM',
|
||||||
|
message: 'OpenAPI 取消订单',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (logErr) {
|
||||||
|
this.ctx.logger.warn('[OpenapiOrderCancel] 写入取消操作日志失败,不影响主流程', logErr);
|
||||||
|
}
|
||||||
|
|
||||||
// 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)
|
// 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)
|
||||||
try {
|
try {
|
||||||
const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback;
|
const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback;
|
||||||
|
|||||||
@ -203,6 +203,25 @@ class orderServer extends MainService {
|
|||||||
return this.fail('取消失败,已通知拦截执行');
|
return this.fail('取消失败,已通知拦截执行');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 已同步订单不允许取消,转为拦截处理
|
||||||
|
const syncStatus = String(existingOrder.sync_status || '').trim();
|
||||||
|
if (syncStatus === 'fin') {
|
||||||
|
await existingOrder.update({
|
||||||
|
intercept_status: 'requested',
|
||||||
|
updated_at: new Date(),
|
||||||
|
}, {
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
await transaction.commit();
|
||||||
|
await this.sendCancelInterceptNotice({
|
||||||
|
orderCode,
|
||||||
|
existingOrder,
|
||||||
|
info,
|
||||||
|
});
|
||||||
|
return this.fail('订单已同步,不可取消,已转为拦截处理');
|
||||||
|
}
|
||||||
|
|
||||||
await existingOrder.update({
|
await existingOrder.update({
|
||||||
status: 'cancel',
|
status: 'cancel',
|
||||||
outbound_status: 'fin',
|
outbound_status: 'fin',
|
||||||
@ -220,6 +239,27 @@ class orderServer extends MainService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await transaction.commit();
|
await transaction.commit();
|
||||||
|
|
||||||
|
// 写入取消操作日志(不影响主流程)
|
||||||
|
try {
|
||||||
|
if (ctx.model && ctx.model.OperationLog) {
|
||||||
|
const customerId = String(info.customerId || '').trim();
|
||||||
|
await ctx.model.OperationLog.create({
|
||||||
|
business_type: 'order',
|
||||||
|
business_id: String(existingOrder.id),
|
||||||
|
operation_code: 'ORDER_CANCEL',
|
||||||
|
operator_id: null,
|
||||||
|
operator_name: customerId ? `qimen:${customerId}` : 'qimen',
|
||||||
|
external_log_type: 'NONE',
|
||||||
|
warehouse_id: info.warehouseId || null,
|
||||||
|
platform_code: customerId || 'SYSTEM',
|
||||||
|
message: '奇门取消订单',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (logErr) {
|
||||||
|
ctx.logger.warn('[QimenOrderCancel] 写入取消操作日志失败,不影响主流程', logErr);
|
||||||
|
}
|
||||||
|
|
||||||
return this.success('取消订单成功');
|
return this.success('取消订单成功');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -2,69 +2,217 @@
|
|||||||
|
|
||||||
const MainService = require('../main');
|
const MainService = require('../main');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 奇门出库单服务。
|
||||||
|
*
|
||||||
|
* 处理 stockout.create / stockout.query 接口,
|
||||||
|
* 使用专用表 `wms_order_stockout` + `wms_order_stockout_items`。
|
||||||
|
*/
|
||||||
class stockoutServer extends MainService {
|
class stockoutServer extends MainService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建出库单。
|
||||||
|
*
|
||||||
|
* 将奇门 stockout.create 请求的 deliveryOrder / orderLines 写入
|
||||||
|
* `wms_order_stockout` 主表和 `wms_order_stockout_items` 明细表,
|
||||||
|
* 整个过程在一个数据库事务内完成,失败自动回滚。
|
||||||
|
*
|
||||||
|
* @param {object} data - 奇门 stockout.create 请求体
|
||||||
|
* @param {object} data.request - 请求数据
|
||||||
|
* @param {object} data.request.deliveryOrder - 出库单头信息
|
||||||
|
* @param {object} data.request.orderLines - 出库单明细
|
||||||
|
* @param {object|object[]} data.request.orderLines.orderLine - 明细行(单条为对象,多条为数组)
|
||||||
|
* @return {Promise<object>} 返回 success / fail 结果
|
||||||
|
*/
|
||||||
async create(data) {
|
async create(data) {
|
||||||
const { app, ctx, appKey, storeId, warehouseId, customerId, warehouseCode } = this;
|
const { app, ctx, appKey, storeId, warehouseId, warehouseCode } = this;
|
||||||
const fail = this.fail.bind(this);
|
const { deliveryOrder, orderLines } = data.request;
|
||||||
const success = this.success.bind(this);
|
|
||||||
|
|
||||||
let totalOrderLines = data.request.deliveryOrder.totalOrderLines || 0;
|
// 单条 orderLine 转为数组
|
||||||
|
let orderLine = orderLines && orderLines.orderLine;
|
||||||
let orderLine = data.request.orderLines.orderLine;
|
if (orderLine && orderLine.orderLineNo) {
|
||||||
if (orderLine.orderLineNo) {
|
|
||||||
orderLine = [ orderLine ];
|
orderLine = [ orderLine ];
|
||||||
}
|
}
|
||||||
totalOrderLines = totalOrderLines || orderLine.length;
|
|
||||||
|
if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) {
|
||||||
|
return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据');
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length;
|
||||||
|
|
||||||
|
// 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细
|
||||||
const errors = [];
|
const errors = [];
|
||||||
const items = [];
|
const items = [];
|
||||||
for (let i = 0; i < orderLine.length; i++) {
|
for (let i = 0; i < orderLine.length; i++) {
|
||||||
const wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId);
|
const line = orderLine[i];
|
||||||
if (!wms_stock) {
|
const wmsStock = await app.model.StockStore.findByPk(line.itemId);
|
||||||
errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`);
|
if (!wmsStock) {
|
||||||
|
errors.push(
|
||||||
|
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库`
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (!wms_stock.stock_id) {
|
if (!wmsStock.stock_id) {
|
||||||
errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`);
|
errors.push(
|
||||||
|
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品`
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
wms_stock.inventory_type = orderLine[i].inventoryType;
|
const planQty = parseInt(line.planQty) || 0;
|
||||||
wms_stock.order_line_no = orderLine[i].orderLineNo;
|
if (planQty <= 0) {
|
||||||
wms_stock.count = orderLine[i].planQty;
|
errors.push(
|
||||||
wms_stock.item_id = orderLine[i].itemId;
|
`SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0`
|
||||||
items.push(wms_stock);
|
);
|
||||||
}
|
continue;
|
||||||
if (errors.length > 0) {
|
|
||||||
return this.fail('创建入库单失败,失败原因:\n' + errors.join('\n'));
|
|
||||||
}
|
|
||||||
const order = await ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder, appKey, storeId, warehouseId, totalOrderLines, 'QM', customerId, warehouseCode);
|
|
||||||
if (!order.success) {
|
|
||||||
return fail('创建入库单失败,失败原因:\n' + order.error);
|
|
||||||
}
|
|
||||||
const orderId = order.deliveryOrderId;
|
|
||||||
for (let i = 0; i < items.length; i++) {
|
|
||||||
const item = items[i];
|
|
||||||
const res = await ctx.service.systems.deliveryOrder.addItems(item, orderId);
|
|
||||||
if (!res.success) {
|
|
||||||
errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`);
|
|
||||||
}
|
}
|
||||||
|
items.push({
|
||||||
|
orderLineNo: line.orderLineNo,
|
||||||
|
ownerCode: line.ownerCode,
|
||||||
|
itemCode: line.itemCode,
|
||||||
|
itemId: line.itemId,
|
||||||
|
itemName: line.itemName,
|
||||||
|
planQty,
|
||||||
|
inventoryType: line.inventoryType,
|
||||||
|
stockId: wmsStock.stock_id,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (errors.length > 0) {
|
if (errors.length > 0) {
|
||||||
// 失败删除;
|
return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`);
|
||||||
await ctx.model.deliveryOrder.delete(orderId);
|
|
||||||
return fail('创建入库单失败,失败原因:\n' + errors.join('\n'));
|
|
||||||
}
|
}
|
||||||
const lineCount = await ctx.service.systems.deliveryOrder.getLineCount(orderId); // 获取接收行数
|
|
||||||
// 所有行数接收完成
|
// 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB
|
||||||
if (lineCount === totalOrderLines) {
|
const oversellConfig = await ctx.service.systems.stockStore
|
||||||
await ctx.service.systems.deliveryOrder.received(orderId, warehouseId, storeId); // 接收完成
|
.getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId);
|
||||||
return success('入库单接收完毕', { deliveryOrderId: orderId });
|
|
||||||
|
// 第二步:在事务中写入主表 + 库存锁定 + 明细表
|
||||||
|
const transaction = await ctx.model.transaction();
|
||||||
|
try {
|
||||||
|
const order = await ctx.model.OrderStockout.create(
|
||||||
|
{
|
||||||
|
stockout_order_code: deliveryOrder.deliveryOrderCode,
|
||||||
|
order_type: deliveryOrder.orderType,
|
||||||
|
total_order_lines: totalOrderLines,
|
||||||
|
order_create_time: deliveryOrder.createTime
|
||||||
|
? new Date(deliveryOrder.createTime)
|
||||||
|
: null,
|
||||||
|
remark: deliveryOrder.remark || null,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
qimen_owner_code: appKey,
|
||||||
|
qimen_warehouse_code: warehouseCode,
|
||||||
|
source_type: 'QM',
|
||||||
|
created_at: new Date(),
|
||||||
|
updated_at: new Date(),
|
||||||
|
},
|
||||||
|
{ transaction }
|
||||||
|
);
|
||||||
|
|
||||||
|
const orderId = order.id;
|
||||||
|
|
||||||
|
// 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁
|
||||||
|
const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId);
|
||||||
|
for (const item of sortedItems) {
|
||||||
|
const lockResult = await ctx.service.systems.stockStore.lockItemStorages(
|
||||||
|
item.stockId,
|
||||||
|
item.planQty,
|
||||||
|
transaction,
|
||||||
|
oversellConfig
|
||||||
|
);
|
||||||
|
if (!lockResult.success) {
|
||||||
|
throw new Error(
|
||||||
|
`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量创建明细
|
||||||
|
const now = new Date();
|
||||||
|
const itemRecords = items.map(item => ({
|
||||||
|
order_id: orderId,
|
||||||
|
order_line_no: item.orderLineNo,
|
||||||
|
owner_code: item.ownerCode,
|
||||||
|
item_code: item.itemCode,
|
||||||
|
item_id: item.itemId,
|
||||||
|
item_name: item.itemName,
|
||||||
|
plan_qty: item.planQty,
|
||||||
|
inventory_type: item.inventoryType,
|
||||||
|
stock_id: item.stockId,
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now,
|
||||||
|
}));
|
||||||
|
|
||||||
|
await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, {
|
||||||
|
transaction,
|
||||||
|
validate: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await transaction.commit();
|
||||||
|
|
||||||
|
return this.success('出库单创建成功', {
|
||||||
|
stockoutOrderId: order.id,
|
||||||
|
stockoutOrderCode: order.stockout_order_code,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
await transaction.rollback();
|
||||||
|
ctx.logger.error('[stockout.create] 事务写入失败:', err);
|
||||||
|
return this.fail(`创建出库单失败,失败原因:\n${err.message}`);
|
||||||
}
|
}
|
||||||
return success('入库单接收中');
|
|
||||||
}
|
}
|
||||||
async query() {
|
|
||||||
const { fail } = this;
|
/**
|
||||||
return fail('接口未完善');
|
* 查询出库单。
|
||||||
|
*
|
||||||
|
* 根据 deliveryOrderCode 查 `wms_order_stockout` 主表,
|
||||||
|
* 然后关联查 `wms_order_stockout_items` 明细,按奇门标准响应格式返回。
|
||||||
|
*
|
||||||
|
* @param {object} data - 奇门 stockout.query 请求体
|
||||||
|
* @param {object} data.request - 请求数据
|
||||||
|
* @param {object} data.request.deliveryOrder - 出库单查询条件
|
||||||
|
* @param {string} data.request.deliveryOrder.deliveryOrderCode - 出库单号
|
||||||
|
* @return {Promise<object>} 返回 success / fail 结果
|
||||||
|
*/
|
||||||
|
async query(data) {
|
||||||
|
const { app, ctx } = this;
|
||||||
|
const { deliveryOrderCode } = data.request.deliveryOrder;
|
||||||
|
|
||||||
|
// 查主表
|
||||||
|
const order = await ctx.model.OrderStockout.findOne({
|
||||||
|
where: { stockout_order_code: deliveryOrderCode },
|
||||||
|
});
|
||||||
|
if (!order) {
|
||||||
|
return this.fail('未找到出库单');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查明细
|
||||||
|
const items = await ctx.model.OrderStockoutItems.findAll({
|
||||||
|
where: { order_id: order.id },
|
||||||
|
order: [[ 'order_line_no', 'ASC' ]],
|
||||||
|
});
|
||||||
|
|
||||||
|
return this.success('成功', {
|
||||||
|
totalLines: items.length,
|
||||||
|
deliveryOrder: {
|
||||||
|
deliveryOrderCode: order.stockout_order_code,
|
||||||
|
deliveryOrderId: order.id,
|
||||||
|
warehouseCode: order.qimen_warehouse_code,
|
||||||
|
orderType: order.order_type,
|
||||||
|
status: order.order_status,
|
||||||
|
createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null,
|
||||||
|
remark: order.remark || '',
|
||||||
|
},
|
||||||
|
orderLines: {
|
||||||
|
orderLine: items.map(item => ({
|
||||||
|
orderLineNo: item.order_line_no,
|
||||||
|
ownerCode: item.owner_code,
|
||||||
|
itemCode: item.item_code,
|
||||||
|
itemId: item.item_id,
|
||||||
|
itemName: item.item_name,
|
||||||
|
planQty: item.plan_qty,
|
||||||
|
inventoryType: item.inventory_type,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -302,7 +302,7 @@ class dashboardService extends MainService {
|
|||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 订单趋势统计:按小时统计当日订单数与发货数
|
* 订单趋势统计:按小时统计当日订单数与发货数
|
||||||
* @returns {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据
|
* @return {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据
|
||||||
*/
|
*/
|
||||||
async order_trend() {
|
async order_trend() {
|
||||||
const { ctx } = this;
|
const { ctx } = this;
|
||||||
|
|||||||
@ -377,7 +377,7 @@ function appendExpressMappingKey(targetMap, rawKey, mappingItem) {
|
|||||||
* 构建抖音电子面单快递映射表。
|
* 构建抖音电子面单快递映射表。
|
||||||
*
|
*
|
||||||
* @param {Array} expressList 系统快递列表
|
* @param {Array} expressList 系统快递列表
|
||||||
* @param platformCode
|
* @param {string} [platformCode='DY'] 平台编码,默认为 'DY'
|
||||||
* @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表
|
* @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表
|
||||||
*/
|
*/
|
||||||
function buildExpressNameMap(expressList, platformCode = 'DY') {
|
function buildExpressNameMap(expressList, platformCode = 'DY') {
|
||||||
@ -2050,7 +2050,7 @@ class indexService extends MainService {
|
|||||||
*
|
*
|
||||||
* @param {string} appSecret 菠萝派访问令牌
|
* @param {string} appSecret 菠萝派访问令牌
|
||||||
* @param {string|number} platid 菠萝派平台标识
|
* @param {string|number} platid 菠萝派平台标识
|
||||||
* @param isJD
|
* @param {boolean} [isJD=false] 是否为京东平台
|
||||||
* @return {Promise<Array<Object>>} 归一化后的模板数组
|
* @return {Promise<Array<Object>>} 归一化后的模板数组
|
||||||
* @throws {Error} 当配置缺失或接口返回失败时抛出异常
|
* @throws {Error} 当配置缺失或接口返回失败时抛出异常
|
||||||
*/
|
*/
|
||||||
@ -2061,10 +2061,10 @@ class indexService extends MainService {
|
|||||||
throw new Error('菠萝派接口配置缺失');
|
throw new Error('菠萝派接口配置缺失');
|
||||||
}
|
}
|
||||||
const query_data = { templatestype: 'ALL' };
|
const query_data = { templatestype: 'ALL' };
|
||||||
if (platid == 673) {
|
if (platid === 673) {
|
||||||
query_data.BizVersion = '2';
|
query_data.BizVersion = '2';
|
||||||
}
|
}
|
||||||
if (platid == 544) {
|
if (platid === 544) {
|
||||||
platid = 611;
|
platid = 611;
|
||||||
}
|
}
|
||||||
let interface_url = 'https://api.polyapi.com/OpenAPI/do';
|
let interface_url = 'https://api.polyapi.com/OpenAPI/do';
|
||||||
@ -2670,9 +2670,9 @@ class indexService extends MainService {
|
|||||||
* 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。
|
* 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。
|
||||||
*
|
*
|
||||||
* @param {string} platformCode 平台编码
|
* @param {string} platformCode 平台编码
|
||||||
* @param s
|
* @param {string|null} [s=null] 平台密钥或令牌
|
||||||
* @param platid
|
* @param {string|number|null} [platid=null] 平台标识ID
|
||||||
* @param expressCode
|
* @param {string} [expressCode=''] 快递编码
|
||||||
* @return {Promise<Object>} 平台模板响应
|
* @return {Promise<Object>} 平台模板响应
|
||||||
*/
|
*/
|
||||||
async requestPrintPlatformTemplateList(platformCode, s = null, platid = null, expressCode = '') {
|
async requestPrintPlatformTemplateList(platformCode, s = null, platid = null, expressCode = '') {
|
||||||
|
|||||||
@ -45,6 +45,8 @@ const ORDER_LIST_BASE_ATTRIBUTES = [
|
|||||||
'post_status', 'storage_status', 'pick_status', 'pack_status',
|
'post_status', 'storage_status', 'pick_status', 'pack_status',
|
||||||
'inspection_status', 'print_status', 'claim_status',
|
'inspection_status', 'print_status', 'claim_status',
|
||||||
'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status',
|
'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status',
|
||||||
|
'create_channel',
|
||||||
|
'store_id',
|
||||||
];
|
];
|
||||||
|
|
||||||
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
|
const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
|
||||||
@ -53,6 +55,11 @@ const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({
|
|||||||
2: '重货',
|
2: '重货',
|
||||||
3: '冷链',
|
3: '冷链',
|
||||||
});
|
});
|
||||||
|
const CREATE_CHANNEL_LABELS = Object.freeze({
|
||||||
|
MANUAL: '手工单',
|
||||||
|
API: '接口',
|
||||||
|
QM: '奇门',
|
||||||
|
});
|
||||||
const ORDER_TABLE_TYPE_ALIASES = Object.freeze({
|
const ORDER_TABLE_TYPE_ALIASES = Object.freeze({
|
||||||
current: 'current',
|
current: 'current',
|
||||||
history: 'history',
|
history: 'history',
|
||||||
@ -483,6 +490,24 @@ class OrderBaseService extends MainService {
|
|||||||
return ORDER_WEIGHT_TYPE_LABELS[0];
|
return ORDER_WEIGHT_TYPE_LABELS[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将创建来源渠道编码转换为中文展示值。
|
||||||
|
* @param {string} channel 创建来源渠道编码。
|
||||||
|
* @return {string} 中文渠道名称。
|
||||||
|
*/
|
||||||
|
formatCreateChannelLabel(channel) {
|
||||||
|
if (!channel || typeof channel !== 'string') {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const trimmedChannel = channel.trim();
|
||||||
|
if (Object.prototype.hasOwnProperty.call(CREATE_CHANNEL_LABELS, trimmedChannel)) {
|
||||||
|
return CREATE_CHANNEL_LABELS[trimmedChannel];
|
||||||
|
}
|
||||||
|
|
||||||
|
return trimmedChannel;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 规范波次扫描结果,空值时默认返回 0(未扫描)。
|
* 规范波次扫描结果,空值时默认返回 0(未扫描)。
|
||||||
* @param {*} scanResult 扫描结果原始值。
|
* @param {*} scanResult 扫描结果原始值。
|
||||||
@ -528,6 +553,7 @@ class OrderBaseService extends MainService {
|
|||||||
weight_type: this.formatWeightTypeLabel(order.weight_type),
|
weight_type: this.formatWeightTypeLabel(order.weight_type),
|
||||||
wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version),
|
wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version),
|
||||||
wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result),
|
wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result),
|
||||||
|
create_channel: this.formatCreateChannelLabel(order.create_channel),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1125,9 +1151,44 @@ class OrderBaseService extends MainService {
|
|||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const normalizedList = await this.attachOrderExpressNumbers(
|
const normalized = list.map(order => this.normalizeOrderListItem(order));
|
||||||
list.map(order => this.normalizeOrderListItem(order))
|
|
||||||
);
|
// 批量查询货主备注(wms_store_warehouse.store_remask)
|
||||||
|
const storeRemarkMap = new Map();
|
||||||
|
if (normalized.length > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) {
|
||||||
|
const storeIds = [
|
||||||
|
...new Set(
|
||||||
|
normalized
|
||||||
|
.map(row => Number(row.store_id || 0))
|
||||||
|
.filter(id => id > 0)
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if (storeIds.length > 0) {
|
||||||
|
const swRows = await this.ctx.model.StoreWarehouse.findAll({
|
||||||
|
where: {
|
||||||
|
store_id: { [this.app.Sequelize.Op.in]: storeIds },
|
||||||
|
warehouse_id: contextWarehouseId,
|
||||||
|
},
|
||||||
|
attributes: [ 'store_id', 'store_remask' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
for (const sw of (Array.isArray(swRows) ? swRows : [])) {
|
||||||
|
const sid = Number(sw.store_id || 0);
|
||||||
|
if (sid > 0 && !storeRemarkMap.has(sid)) {
|
||||||
|
storeRemarkMap.set(sid, String(sw.store_remask || '').trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const listWithRemark = normalized.map(row => ({
|
||||||
|
...row,
|
||||||
|
store_remark: storeRemarkMap.has(Number(row.store_id || 0))
|
||||||
|
? storeRemarkMap.get(Number(row.store_id || 0))
|
||||||
|
: '',
|
||||||
|
}));
|
||||||
|
|
||||||
|
const normalizedList = await this.attachOrderExpressNumbers(listWithRemark);
|
||||||
|
|
||||||
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
|
const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0;
|
||||||
|
|
||||||
|
|||||||
@ -1749,6 +1749,38 @@ class PendingOrderService extends OrderBaseService {
|
|||||||
throw new Error('订单当前状态不允许取消');
|
throw new Error('订单当前状态不允许取消');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 已同步订单不允许取消,转为拦截处理
|
||||||
|
const syncedOrders = existingOrders.filter(
|
||||||
|
order => String(order.sync_status || '').trim() === 'fin'
|
||||||
|
);
|
||||||
|
if (syncedOrders.length > 0) {
|
||||||
|
const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter(
|
||||||
|
id => Number.isInteger(id) && id > 0
|
||||||
|
);
|
||||||
|
if (syncedOrderIds.length > 0) {
|
||||||
|
const syncNow = new Date();
|
||||||
|
await model.update(
|
||||||
|
{
|
||||||
|
intercept_status: 'requested',
|
||||||
|
updated_at: syncNow,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
where: {
|
||||||
|
id: syncedOrderIds,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
this.ctx.logger.info(
|
||||||
|
`[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const syncedCodes = syncedOrders
|
||||||
|
.map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(', ');
|
||||||
|
throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`);
|
||||||
|
}
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const updateValues = {
|
const updateValues = {
|
||||||
status: PENDING_CANCEL_STATUS,
|
status: PENDING_CANCEL_STATUS,
|
||||||
@ -1916,6 +1948,37 @@ class PendingOrderService extends OrderBaseService {
|
|||||||
|
|
||||||
const firstOrder = normalizedOrders[0];
|
const firstOrder = normalizedOrders[0];
|
||||||
|
|
||||||
|
// 写入取消操作日志(不影响主流程)
|
||||||
|
try {
|
||||||
|
const operator = this.getOrderLogOperator();
|
||||||
|
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
|
||||||
|
if (normalizedOrders.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
|
||||||
|
const operatorInfo = operator || {};
|
||||||
|
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
|
||||||
|
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
const logRows = normalizedOrders.map(order => ({
|
||||||
|
business_type: 'order',
|
||||||
|
business_id: String(order.id),
|
||||||
|
operation_code: 'ORDER_CANCEL',
|
||||||
|
operator_id: operatorId,
|
||||||
|
operator_name: operatorName,
|
||||||
|
external_log_type: 'NONE',
|
||||||
|
warehouse_id: logWarehouseId || null,
|
||||||
|
platform_code: 'SYSTEM',
|
||||||
|
message: '订单取消',
|
||||||
|
created_at: now,
|
||||||
|
})).filter(row => Number(row.business_id) > 0);
|
||||||
|
|
||||||
|
if (logRows.length > 0) {
|
||||||
|
await this.ctx.model.OperationLog.bulkCreate(logRows);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (logErr) {
|
||||||
|
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 写入取消操作日志失败,不影响业务', logErr);
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: firstOrder.id,
|
id: firstOrder.id,
|
||||||
status: firstOrder.status,
|
status: firstOrder.status,
|
||||||
|
|||||||
@ -1287,10 +1287,12 @@ class RecheckOrderService extends OrderBaseService {
|
|||||||
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
|
if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) {
|
||||||
barcodeMap.set(sid, detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean));
|
barcodeMap.set(sid, detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean));
|
||||||
}
|
}
|
||||||
// 从 getStockDetails 提取图片 URL
|
// 从 getStockDetails 提取图片 URL(兼容数组/字符串格式)
|
||||||
const detailImageUrl = String(detail.image_url || '').trim();
|
const imageUrls = Array.isArray(detail.image_url)
|
||||||
if (detailImageUrl) {
|
? detail.image_url.map(u => String(u || '').trim()).filter(Boolean)
|
||||||
imagesByStockId.set(sid, [ detailImageUrl ]);
|
: (detail.image_url ? [ String(detail.image_url).trim() ] : []);
|
||||||
|
if (imageUrls.length > 0) {
|
||||||
|
imagesByStockId.set(sid, imageUrls);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -3684,12 +3686,14 @@ class RecheckOrderService extends OrderBaseService {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// 步骤3:检查是否存在 wms_picking 记录
|
// 步骤3:检查是否存在 wms_picking 记录(仅统计 pending 且未删除的记录)
|
||||||
const pickingRows = await ctx.model.query(
|
const pickingRows = await ctx.model.query(
|
||||||
`SELECT id, storage_id, quantity, space_id
|
`SELECT id, storage_id, quantity, space_id
|
||||||
FROM wms_picking
|
FROM wms_picking
|
||||||
WHERE order_id = :orderId
|
WHERE order_id = :orderId
|
||||||
AND warehouse_id = :warehouseId`,
|
AND warehouse_id = :warehouseId
|
||||||
|
AND status = 'pending'
|
||||||
|
AND deleted_at IS NULL`,
|
||||||
{
|
{
|
||||||
replacements: { orderId, warehouseId },
|
replacements: { orderId, warehouseId },
|
||||||
type: ctx.model.QueryTypes.SELECT,
|
type: ctx.model.QueryTypes.SELECT,
|
||||||
@ -3700,12 +3704,14 @@ class RecheckOrderService extends OrderBaseService {
|
|||||||
const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : [];
|
const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : [];
|
||||||
|
|
||||||
if (normalizedPickingRows.length > 0) {
|
if (normalizedPickingRows.length > 0) {
|
||||||
// 更新 wms_picking.status = 'fin'
|
// 更新 wms_picking.status = 'fin'(仅更新 pending 且未删除的记录)
|
||||||
await ctx.model.query(
|
await ctx.model.query(
|
||||||
`UPDATE wms_picking
|
`UPDATE wms_picking
|
||||||
SET status = 'fin', updated_at = NOW()
|
SET status = 'fin', updated_at = NOW()
|
||||||
WHERE order_id = :orderId
|
WHERE order_id = :orderId
|
||||||
AND warehouse_id = :warehouseId`,
|
AND warehouse_id = :warehouseId
|
||||||
|
AND status = 'pending'
|
||||||
|
AND deleted_at IS NULL`,
|
||||||
{
|
{
|
||||||
replacements: { orderId, warehouseId },
|
replacements: { orderId, warehouseId },
|
||||||
type: ctx.model.QueryTypes.UPDATE,
|
type: ctx.model.QueryTypes.UPDATE,
|
||||||
|
|||||||
@ -5570,9 +5570,9 @@ class WaveService extends OrderBaseService {
|
|||||||
|
|
||||||
const deletedCount = await matchModel.destroy({ where });
|
const deletedCount = await matchModel.destroy({ where });
|
||||||
// 清理后重建
|
// 清理后重建
|
||||||
if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0) {
|
if (Number.isInteger(warehouseId) && warehouseId > 0) {
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId).catch(err => {
|
this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => {
|
||||||
this.ctx.logger.warn('[wave.cleanupWaveStrategyQuickScanMatchedStrategies] 清理后自动扫描失败: %s', err.message);
|
this.ctx.logger.warn('[wave.cleanupWaveStrategyQuickScanMatchedStrategies] 清理后自动扫描失败: %s', err.message);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -77,7 +77,8 @@ class PickService extends MainService {
|
|||||||
const pad2 = value => String(value).padStart(2, '0');
|
const pad2 = value => String(value).padStart(2, '0');
|
||||||
const datePart = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}`;
|
const datePart = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}`;
|
||||||
const timePart = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`;
|
const timePart = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`;
|
||||||
const randomPart = Math.random().toString(36).slice(2, 6).toUpperCase();
|
const randomPart = Math.random().toString(36).slice(2, 6)
|
||||||
|
.toUpperCase();
|
||||||
return `PK${datePart}${timePart}${randomPart}`;
|
return `PK${datePart}${timePart}${randomPart}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -190,16 +191,16 @@ class PickService extends MainService {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null;
|
const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null;
|
||||||
const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null;
|
const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null;
|
||||||
let taskId = Number(
|
let taskId = Number(
|
||||||
(taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id))
|
(taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id))
|
||||||
|| (taskInsertHead && (taskInsertHead.insertId || taskInsertHead.lastID || taskInsertHead.id))
|
|| (taskInsertHead && (taskInsertHead.insertId || taskInsertHead.lastID || taskInsertHead.id))
|
||||||
|| 0
|
|| 0
|
||||||
);
|
);
|
||||||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||||||
const taskIdRows = await ctx.model.query(
|
const taskIdRows = await ctx.model.query(
|
||||||
`
|
`
|
||||||
SELECT id
|
SELECT id
|
||||||
FROM wms_wave_pick_task
|
FROM wms_wave_pick_task
|
||||||
WHERE warehouse_id = :warehouseId
|
WHERE warehouse_id = :warehouseId
|
||||||
@ -207,18 +208,18 @@ class PickService extends MainService {
|
|||||||
ORDER BY id DESC
|
ORDER BY id DESC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
`,
|
`,
|
||||||
{
|
{
|
||||||
replacements: {
|
replacements: {
|
||||||
warehouseId,
|
warehouseId,
|
||||||
taskNo,
|
taskNo,
|
||||||
},
|
},
|
||||||
type: ctx.model.QueryTypes.SELECT,
|
type: ctx.model.QueryTypes.SELECT,
|
||||||
transaction,
|
transaction,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null;
|
const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null;
|
||||||
taskId = Number(taskRow && taskRow.id || 0);
|
taskId = Number(taskRow && taskRow.id || 0);
|
||||||
}
|
}
|
||||||
if (!Number.isInteger(taskId) || taskId <= 0) {
|
if (!Number.isInteger(taskId) || taskId <= 0) {
|
||||||
throw Object.assign(new Error('任务创建失败(未返回任务ID)'), { code: 500 });
|
throw Object.assign(new Error('任务创建失败(未返回任务ID)'), { code: 500 });
|
||||||
}
|
}
|
||||||
|
|||||||
@ -327,147 +327,6 @@ class PrintService extends MainService {
|
|||||||
return lowerPlatformCode;
|
return lowerPlatformCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 按订单ID批量加载波次序号上下文,用于 SPH 发送阶段覆写 printNum。
|
|
||||||
* 数据来源:wms_order_wave_index。
|
|
||||||
* 查询失败时优雅降级为空映射,不阻断发送流程。
|
|
||||||
* @param {Object} payload 入参。
|
|
||||||
* @param {number|string} payload.warehouseId 仓库ID。
|
|
||||||
* @param {Array<number|string>} payload.orderIds 订单ID列表。
|
|
||||||
* @return {Promise<{orderWaveIndexMap:Map<number, {wave_id:number, wave_index:number, platforms_index:number}>,waveTotalOrdersMap:Map<number, number>}>} 波次索引上下文。
|
|
||||||
*/
|
|
||||||
async queryWavePrintNumContextForOrderIds(payload = {}) {
|
|
||||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
|
||||||
const warehouseId = Number(normalizedPayload.warehouseId || 0);
|
|
||||||
const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds);
|
|
||||||
const emptyResult = {
|
|
||||||
orderWaveIndexMap: new Map(),
|
|
||||||
waveTotalOrdersMap: new Map(),
|
|
||||||
};
|
|
||||||
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) {
|
|
||||||
return emptyResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
const orderPrintService = this.service && this.service.systems && this.service.systems.orderPrint;
|
|
||||||
if (!orderPrintService
|
|
||||||
|| typeof orderPrintService.queryWaveOrderIndexMapByOrderIds !== 'function'
|
|
||||||
|| typeof orderPrintService.queryWaveTotalOrderCountMap !== 'function') {
|
|
||||||
this.ctx.logger.warn('[print.send] SPH printNum 覆写依赖服务不可用,跳过波次索引查询', {
|
|
||||||
warehouseId,
|
|
||||||
orderIdsCount: orderIds.length,
|
|
||||||
});
|
|
||||||
return emptyResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const orderWaveIndexMapResult = await orderPrintService.queryWaveOrderIndexMapByOrderIds(orderIds, warehouseId);
|
|
||||||
const orderWaveIndexMap = orderWaveIndexMapResult instanceof Map
|
|
||||||
? orderWaveIndexMapResult
|
|
||||||
: new Map();
|
|
||||||
const waveIds = Array.from(new Set(Array.from(orderWaveIndexMap.values())
|
|
||||||
.map(item => Number(item && item.wave_id || 0))
|
|
||||||
.filter(waveId => Number.isInteger(waveId) && waveId > 0)));
|
|
||||||
const waveTotalOrdersMapResult = await orderPrintService.queryWaveTotalOrderCountMap(waveIds, warehouseId);
|
|
||||||
const waveTotalOrdersMap = waveTotalOrdersMapResult instanceof Map
|
|
||||||
? waveTotalOrdersMapResult
|
|
||||||
: new Map();
|
|
||||||
return {
|
|
||||||
orderWaveIndexMap,
|
|
||||||
waveTotalOrdersMap,
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
this.ctx.logger.warn('[print.send] SPH printNum 覆写波次索引查询失败,回退模板默认值', {
|
|
||||||
warehouseId,
|
|
||||||
orderIdsCount: orderIds.length,
|
|
||||||
reason: error && error.message ? error.message : `${error}`,
|
|
||||||
});
|
|
||||||
return emptyResult;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 将 SPH 发送任务中的 printNum 覆写为波次内序号与波次总单数。
|
|
||||||
* @param {Object} payload 入参。
|
|
||||||
* @param {Object} payload.requestPayload 待发送 payload。
|
|
||||||
* @param {number|string} payload.orderId 当前订单ID。
|
|
||||||
* @param {Map<number, {wave_id:number, wave_index:number, platforms_index:number}>} payload.orderWaveIndexMap 订单波次索引映射。
|
|
||||||
* @param {Map<number, number>} payload.waveTotalOrdersMap 波次总单数映射。
|
|
||||||
* @return {{applied:boolean,orderId:number,waveId:number,curNum:number,sumNum:number,reason:string}} 覆写结果。
|
|
||||||
*/
|
|
||||||
applySphPrintNumByWaveIndex(payload = {}) {
|
|
||||||
const normalizedPayload = payload && typeof payload === 'object' ? payload : {};
|
|
||||||
const requestPayload = normalizedPayload.requestPayload && typeof normalizedPayload.requestPayload === 'object'
|
|
||||||
? normalizedPayload.requestPayload
|
|
||||||
: null;
|
|
||||||
const orderId = Number(normalizedPayload.orderId || 0);
|
|
||||||
const fallbackResult = {
|
|
||||||
applied: false,
|
|
||||||
orderId,
|
|
||||||
waveId: 0,
|
|
||||||
curNum: 0,
|
|
||||||
sumNum: 0,
|
|
||||||
reason: '',
|
|
||||||
};
|
|
||||||
if (!requestPayload) {
|
|
||||||
return {
|
|
||||||
...fallbackResult,
|
|
||||||
reason: 'requestPayload 非对象',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const taskList = Array.isArray(requestPayload.taskList) ? requestPayload.taskList : [];
|
|
||||||
const firstTask = taskList[0] && typeof taskList[0] === 'object' ? taskList[0] : null;
|
|
||||||
if (!firstTask) {
|
|
||||||
return {
|
|
||||||
...fallbackResult,
|
|
||||||
reason: 'taskList[0] 不存在',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if (!Number.isInteger(orderId) || orderId <= 0) {
|
|
||||||
return {
|
|
||||||
...fallbackResult,
|
|
||||||
reason: 'orderId 非法',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const orderWaveIndexMap = normalizedPayload.orderWaveIndexMap instanceof Map
|
|
||||||
? normalizedPayload.orderWaveIndexMap
|
|
||||||
: new Map();
|
|
||||||
const waveTotalOrdersMap = normalizedPayload.waveTotalOrdersMap instanceof Map
|
|
||||||
? normalizedPayload.waveTotalOrdersMap
|
|
||||||
: new Map();
|
|
||||||
const waveOrderIndexInfo = orderWaveIndexMap.get(orderId);
|
|
||||||
const waveId = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_id || 0);
|
|
||||||
const curNum = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_index || 0);
|
|
||||||
const sumNum = Number(waveTotalOrdersMap.get(waveId) || 0);
|
|
||||||
if (!Number.isInteger(waveId) || waveId <= 0 || !Number.isInteger(curNum) || curNum <= 0 || !Number.isInteger(sumNum) || sumNum <= 0) {
|
|
||||||
return {
|
|
||||||
...fallbackResult,
|
|
||||||
waveId,
|
|
||||||
curNum,
|
|
||||||
sumNum,
|
|
||||||
reason: '波次索引信息缺失',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const currentPrintNum = firstTask.printNum && typeof firstTask.printNum === 'object' && !Array.isArray(firstTask.printNum)
|
|
||||||
? firstTask.printNum
|
|
||||||
: {};
|
|
||||||
firstTask.printNum = {
|
|
||||||
...currentPrintNum,
|
|
||||||
curNum,
|
|
||||||
sumNum,
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
applied: true,
|
|
||||||
orderId,
|
|
||||||
waveId,
|
|
||||||
curNum,
|
|
||||||
sumNum,
|
|
||||||
reason: '',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从打印记录 data 中提取订单ID列表。
|
* 从打印记录 data 中提取订单ID列表。
|
||||||
* 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。
|
* 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。
|
||||||
@ -2257,13 +2116,8 @@ class PrintService extends MainService {
|
|||||||
payloadBuilder: normalizedPayload.payloadBuilder,
|
payloadBuilder: normalizedPayload.payloadBuilder,
|
||||||
});
|
});
|
||||||
const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou';
|
const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou';
|
||||||
const isSphPlatform = normalizedPlatformCode === 'sph';
|
|
||||||
const orderBatches = [];
|
const orderBatches = [];
|
||||||
if (isSphPlatform) {
|
if (isKuaishouPlatform) {
|
||||||
for (const order of orders) {
|
|
||||||
orderBatches.push([ order ]);
|
|
||||||
}
|
|
||||||
} else if (isKuaishouPlatform) {
|
|
||||||
for (let index = 0; index < orders.length; index += 10) {
|
for (let index = 0; index < orders.length; index += 10) {
|
||||||
orderBatches.push(orders.slice(index, index + 10));
|
orderBatches.push(orders.slice(index, index + 10));
|
||||||
}
|
}
|
||||||
@ -2271,23 +2125,6 @@ class PrintService extends MainService {
|
|||||||
orderBatches.push(orders);
|
orderBatches.push(orders);
|
||||||
}
|
}
|
||||||
const totalDocumentCount = orders.length;
|
const totalDocumentCount = orders.length;
|
||||||
let sphOrderWaveIndexMap = new Map();
|
|
||||||
let sphWaveTotalOrdersMap = new Map();
|
|
||||||
if (isSphPlatform) {
|
|
||||||
const platformOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, orders);
|
|
||||||
const wavePrintNumContext = await this.queryWavePrintNumContextForOrderIds({
|
|
||||||
warehouseId: normalizedPayload.warehouseId,
|
|
||||||
orderIds: platformOrderIds,
|
|
||||||
});
|
|
||||||
sphOrderWaveIndexMap = wavePrintNumContext.orderWaveIndexMap;
|
|
||||||
sphWaveTotalOrdersMap = wavePrintNumContext.waveTotalOrdersMap;
|
|
||||||
this.ctx.logger.info('[print.send] SPH 波次索引上下文加载完成', {
|
|
||||||
...groupSummary,
|
|
||||||
orderIdsCount: platformOrderIds.length,
|
|
||||||
orderWaveIndexCount: sphOrderWaveIndexMap.size,
|
|
||||||
waveCount: sphWaveTotalOrdersMap.size,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) {
|
for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) {
|
||||||
const batchOrders = orderBatches[batchIndex];
|
const batchOrders = orderBatches[batchIndex];
|
||||||
@ -2313,44 +2150,13 @@ class PrintService extends MainService {
|
|||||||
requestPayload.task.totalDocumentCount = totalDocumentCount;
|
requestPayload.task.totalDocumentCount = totalDocumentCount;
|
||||||
}
|
}
|
||||||
currentTaskCode = await this.reserveUniquePrintTaskCode();
|
currentTaskCode = await this.reserveUniquePrintTaskCode();
|
||||||
if (isSphPlatform
|
if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
|
||||||
&& Array.isArray(requestPayload.taskList)
|
|
||||||
&& requestPayload.taskList[0]
|
|
||||||
&& typeof requestPayload.taskList[0] === 'object'
|
|
||||||
&& !Array.isArray(requestPayload.taskList[0])) {
|
|
||||||
requestPayload.taskList[0].taskID = currentTaskCode;
|
|
||||||
} else if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) {
|
|
||||||
requestPayload.task.taskID = currentTaskCode;
|
requestPayload.task.taskID = currentTaskCode;
|
||||||
}
|
}
|
||||||
if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) {
|
if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) {
|
||||||
generatedTaskCodes.push(currentTaskCode);
|
generatedTaskCodes.push(currentTaskCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isSphPlatform) {
|
|
||||||
const currentOrderId = Number(batchOrderIds[0] || 0);
|
|
||||||
const sphOverrideResult = this.applySphPrintNumByWaveIndex({
|
|
||||||
requestPayload,
|
|
||||||
orderId: currentOrderId,
|
|
||||||
orderWaveIndexMap: sphOrderWaveIndexMap,
|
|
||||||
waveTotalOrdersMap: sphWaveTotalOrdersMap,
|
|
||||||
});
|
|
||||||
if (sphOverrideResult.applied) {
|
|
||||||
this.ctx.logger.info('[print.send] SPH printNum 覆写成功', {
|
|
||||||
...batchSummary,
|
|
||||||
orderId: sphOverrideResult.orderId,
|
|
||||||
waveId: sphOverrideResult.waveId,
|
|
||||||
curNum: sphOverrideResult.curNum,
|
|
||||||
sumNum: sphOverrideResult.sumNum,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
this.ctx.logger.info('[print.send] SPH printNum 覆写跳过,保持模板默认值', {
|
|
||||||
...batchSummary,
|
|
||||||
orderId: sphOverrideResult.orderId,
|
|
||||||
reason: sphOverrideResult.reason,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const payloadSummary = this.summarizeExpressPayload(requestPayload);
|
const payloadSummary = this.summarizeExpressPayload(requestPayload);
|
||||||
this.ctx.logger.info('[print.send] 组装 payload 成功', {
|
this.ctx.logger.info('[print.send] 组装 payload 成功', {
|
||||||
...batchSummary,
|
...batchSummary,
|
||||||
|
|||||||
@ -30,7 +30,7 @@ class DirectInboundService extends MainService {
|
|||||||
/**
|
/**
|
||||||
* 按商品增量添加导入/PDA 入库记录。
|
* 按商品增量添加导入/PDA 入库记录。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {string} data.entry_order_code 入库单号
|
* @param {number} data.entry_order_id 入库单 ID
|
||||||
* @param {number} data.stock_id 商品SKU ID
|
* @param {number} data.stock_id 商品SKU ID
|
||||||
* @param {number} data.quantity 入库数量
|
* @param {number} data.quantity 入库数量
|
||||||
* @param {string} data.inbound_type 入库方式:import 或 pda
|
* @param {string} data.inbound_type 入库方式:import 或 pda
|
||||||
@ -46,13 +46,13 @@ class DirectInboundService extends MainService {
|
|||||||
/**
|
/**
|
||||||
* 提交确认完成导入/PDA 入库,写入库存并触发奇门/API 回传。
|
* 提交确认完成导入/PDA 入库,写入库存并触发奇门/API 回传。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {string} data.entry_order_code 入库单号
|
* @param {number} data.entry_order_id 入库单 ID
|
||||||
* @return {Promise<Object>} 统一成功包装响应
|
* @return {Promise<Object>} 统一成功包装响应
|
||||||
*/
|
*/
|
||||||
async commit(data = {}) {
|
async commit(data = {}) {
|
||||||
const { service } = this;
|
const { service } = this;
|
||||||
const { entry_order_code } = data || {};
|
const { entry_order_id } = data || {};
|
||||||
const result = await service.systems.inboundDirectLog.commit(entry_order_code);
|
const result = await service.systems.inboundDirectLog.commit(entry_order_id);
|
||||||
return this.success('ok', result);
|
return this.success('ok', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -9,9 +9,9 @@ class entryService extends MainService {
|
|||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx);
|
||||||
const _noNeedLogin = '';
|
const _noNeedLogin = '';
|
||||||
const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare';
|
const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList';
|
||||||
const _noNeedLog = 'list,get,getPrintData';
|
const _noNeedLog = 'list,get,getPrintData,reviewEntry,containerList';
|
||||||
const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceivingDetails,quickInbound,receivingCompare';
|
const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList';
|
||||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -64,20 +64,6 @@ class entryService extends MainService {
|
|||||||
return this.success('ok', result);
|
return this.success('ok', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 完成入库单(纯状态变更,不写库存)。
|
|
||||||
* 仅校验状态=PENDING、有明细,然后将 order_status 更新为 COMPLETED。
|
|
||||||
* @param {Object} data 请求体
|
|
||||||
* @param {number} data.id 入库单ID
|
|
||||||
* @return {Promise<Object>} 统一 success 包装
|
|
||||||
*/
|
|
||||||
async completeEntry(data = {}) {
|
|
||||||
const { service } = this;
|
|
||||||
const { id } = data;
|
|
||||||
const result = await service.systems.storage.entry.completeEntry({ id });
|
|
||||||
return this.success('ok', result);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取入库单的导入/PDA 直接入库信息(从 storage.entry 模块暴露)。
|
* 获取入库单的导入/PDA 直接入库信息(从 storage.entry 模块暴露)。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
@ -110,13 +96,13 @@ class entryService extends MainService {
|
|||||||
/**
|
/**
|
||||||
* 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。
|
* 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {string} data.entry_order_code 入库单号
|
* @param {number} data.entry_order_id 入库单 ID
|
||||||
* @return {Promise<Object>} 统一 success 包装
|
* @return {Promise<Object>} 统一 success 包装
|
||||||
*/
|
*/
|
||||||
async commitDirectInbound(data = {}) {
|
async commitDirectInbound(data = {}) {
|
||||||
const { service } = this;
|
const { service } = this;
|
||||||
const { entry_order_code } = data || {};
|
const { entry_order_id } = data || {};
|
||||||
const result = await service.systems.inboundDirectLog.commit(entry_order_code);
|
const result = await service.systems.inboundDirectLog.commit(entry_order_id);
|
||||||
return this.success('ok', result);
|
return this.success('ok', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,19 +119,43 @@ class entryService extends MainService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量绑定入库单明细与收货单明细(system method 包装层)。
|
* 绑定入库单与收货单的主表关系(仅主表绑定,不做明细分配)。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {number} data.entry_order_id 入库单ID
|
* @param {number} data.entry_order_id 入库单 ID
|
||||||
* @param {Array} data.bindings 绑定列表 [{ entry_item_id, receiving_detail_id, allocated_quantity }]
|
* @param {number[]} data.receiving_ids 收货单 ID 列表
|
||||||
* @return {Promise<Object>} 统一 success 包装
|
* @return {Promise<Object>} 统一 success 包装
|
||||||
*/
|
*/
|
||||||
async bindReceivingDetails(data = {}) {
|
async bindReceiving(data = {}) {
|
||||||
const { service } = this;
|
const { ctx } = this;
|
||||||
const { entry_order_id, bindings } = data || {};
|
console.log('[DEBUG] systems keys:', Object.keys(ctx.service.systems));
|
||||||
const result = await service.systems.receiving_entry_match.bindReceivingDetails({ entry_order_id, bindings });
|
console.log('[DEBUG] receiving_entry_match:', typeof ctx.service.systems.receivingEntryMatch);
|
||||||
|
const { entry_order_id, receiving_ids } = data || {};
|
||||||
|
const creator_id = ctx.user ? ctx.user.id || ctx.user.user_id : undefined;
|
||||||
|
const result = await ctx.service.systems.receivingEntryMatch.bindEntryOrderReceiving({
|
||||||
|
entry_order_id,
|
||||||
|
receiving_ids,
|
||||||
|
creator_id,
|
||||||
|
});
|
||||||
return this.success('绑定完成', result);
|
return this.success('绑定完成', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解除入库单与收货单的绑定关系。
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.entry_order_id 入库单 ID
|
||||||
|
* @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表
|
||||||
|
* @return {Promise<Object>} 统一 success 包装
|
||||||
|
*/
|
||||||
|
async unbindReceiving(data = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { entry_order_id, receiving_ids } = data || {};
|
||||||
|
const result = await ctx.service.systems.receivingEntryMatch.unbindEntryOrderReceiving({
|
||||||
|
entry_order_id,
|
||||||
|
receiving_ids,
|
||||||
|
});
|
||||||
|
return this.success('解绑完成', result);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 快捷直入/虚拟入库(system method 包装层)。
|
* 快捷直入/虚拟入库(system method 包装层)。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
@ -156,7 +166,10 @@ class entryService extends MainService {
|
|||||||
const { service } = this;
|
const { service } = this;
|
||||||
const { id } = data;
|
const { id } = data;
|
||||||
const result = await service.systems.storage.entry.quickInbound({ id });
|
const result = await service.systems.storage.entry.quickInbound({ id });
|
||||||
return this.success('ok', result);
|
if (result && result.code === 200) {
|
||||||
|
return this.success(result.message || 'ok', result);
|
||||||
|
}
|
||||||
|
return this.fail(result?.message || '快捷入库失败', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -246,17 +259,88 @@ class entryService extends MainService {
|
|||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* 入库单商品与收货单商品逐行对照视图(system method 包装层)。
|
* 入库单商品与收货单商品逐行对照视图(system method 包装层)。
|
||||||
|
* 支持传入多个收货单ID进行批量对照预览。
|
||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {number} data.entry_order_id 入库单ID
|
* @param {number} data.entry_order_id 入库单ID
|
||||||
* @param {number} data.receiving_id 收货单ID
|
* @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用)
|
||||||
|
* @param {number} [data.receiving_id] 单个收货单ID(向后兼容)
|
||||||
* @return {Promise<Object>} 统一 success 包装
|
* @return {Promise<Object>} 统一 success 包装
|
||||||
*/
|
*/
|
||||||
async receivingCompare(data = {}) {
|
async receivingCompare(data = {}) {
|
||||||
const { service } = this;
|
const { service } = this;
|
||||||
const { entry_order_id, receiving_id } = data || {};
|
const { entry_order_id, receiving_id, receiving_ids } = data || {};
|
||||||
const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id });
|
const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id, receiving_ids });
|
||||||
return this.success('ok', result);
|
return this.success('ok', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询入库单操作日志。warehouseId 由服务端从当前上下文自动注入,前端无需传递。
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.id 入库单ID
|
||||||
|
* @param {number} [data.page=1] 页码
|
||||||
|
* @param {number} [data.pageSize=20] 每页数量
|
||||||
|
* @return {Promise<Object>} 统一 success 包装
|
||||||
|
*/
|
||||||
|
async queryEntryLogs(data = {}) {
|
||||||
|
const { ctx, service } = this;
|
||||||
|
const warehouseId = ctx.user?.store_id;
|
||||||
|
const result = await service.systems.operationLog.queryEntryOrderLogs({
|
||||||
|
id: data.id,
|
||||||
|
warehouseId,
|
||||||
|
page: data.page,
|
||||||
|
pageSize: data.pageSize,
|
||||||
|
});
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询入库单已绑定收货单中匹配指定商品的可绑定收货明细列表。
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.entry_order_id 入库单ID
|
||||||
|
* @param {number} data.stock_id 商品stock_id
|
||||||
|
* @return {Promise<Object>} 统一 success 包装
|
||||||
|
*/
|
||||||
|
async getReceivingDetailsForBind(data = {}) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.storage.entry.getReceivingDetailsForBind(data);
|
||||||
|
if (result && result.code === 200) {
|
||||||
|
return this.success('ok', result.data);
|
||||||
|
}
|
||||||
|
return this.fail(result?.message || '查询失败', result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。
|
||||||
|
* 用于 PDA 上架时选择容器。
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.entry_order_id 入库单ID
|
||||||
|
* @param {number} data.stock_id 商品stock_id
|
||||||
|
* @return {Promise<Object>} 统一 success 包装,data 包含 { list, total }
|
||||||
|
*/
|
||||||
|
async containerList(data = {}) {
|
||||||
|
const { service } = this;
|
||||||
|
const { entry_order_id, stock_id } = data || {};
|
||||||
|
const result = await service.systems.storage.entry.containerList({ entry_order_id, stock_id });
|
||||||
|
if (result && result.code === 200) {
|
||||||
|
return this.success('ok', result.data);
|
||||||
|
}
|
||||||
|
return this.fail(result?.message || '查询失败', result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 审核入库单(CREATED → PENDING)。
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.id 入库单ID
|
||||||
|
* @return {Promise<Object>} 统一 success/fail 包装
|
||||||
|
*/
|
||||||
|
async reviewEntry(data = {}) {
|
||||||
|
const { service } = this;
|
||||||
|
const result = await service.systems.entryOrder.reviewEntry(data);
|
||||||
|
if (result && result.success) {
|
||||||
|
return this.success(result.message, result.data, 200);
|
||||||
|
}
|
||||||
|
return this.fail(result?.message || '审核失败', result, 400);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
module.exports = entryService;
|
module.exports = entryService;
|
||||||
|
|||||||
@ -12,7 +12,7 @@ class InventoryMethodService extends MainService {
|
|||||||
const _noNeedLogin = '';
|
const _noNeedLogin = '';
|
||||||
const _noNeedRight = 'list';
|
const _noNeedRight = 'list';
|
||||||
const _noNeedLog = 'list';
|
const _noNeedLog = 'list';
|
||||||
const _noNeedAuth = 'list';
|
const _noNeedAuth = 'list,quickPutaway';
|
||||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -61,6 +61,20 @@ class InventoryMethodService extends MainService {
|
|||||||
const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch);
|
const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch);
|
||||||
return this.success('ok', result);
|
return this.success('ok', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 收货单快捷入库:将收货单的明细直接转为入库单,相同商品自动合并数量。
|
||||||
|
* 要求货主配置中允许收货单快捷入库,否则直接返回失败。
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.receiving_id 收货单ID(必填)
|
||||||
|
* @return {Promise<Object>} 统一 success 包装,返回创建的入库单信息
|
||||||
|
*/
|
||||||
|
async quickPutaway(data = {}) {
|
||||||
|
const { service } = this;
|
||||||
|
const { receiving_id } = data;
|
||||||
|
const result = await service.systems.storage.inventory.quickPutaway({ receiving_id });
|
||||||
|
return this.success('ok', result);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = InventoryMethodService;
|
module.exports = InventoryMethodService;
|
||||||
|
|||||||
@ -10,9 +10,9 @@ class configService extends MainService {
|
|||||||
constructor(ctx) {
|
constructor(ctx) {
|
||||||
super(ctx);
|
super(ctx);
|
||||||
const _noNeedLogin = '';
|
const _noNeedLogin = '';
|
||||||
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs';
|
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail';
|
||||||
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs';
|
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail';
|
||||||
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs';
|
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail';
|
||||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -21,11 +21,13 @@ class configService extends MainService {
|
|||||||
* @param {Object} data 请求体
|
* @param {Object} data 请求体
|
||||||
* @param {Object} [data.pagination] 分页参数
|
* @param {Object} [data.pagination] 分页参数
|
||||||
* @param {Object} [data.where] 筛选条件
|
* @param {Object} [data.where] 筛选条件
|
||||||
|
* @param {boolean} [data.filterDepleted=false] 是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)
|
||||||
|
* @param {number} [data.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单
|
||||||
* @return {Promise<Object>} 统一成功包装响应
|
* @return {Promise<Object>} 统一成功包装响应
|
||||||
*/
|
*/
|
||||||
async getReceivingList(data) {
|
async getReceivingList(data) {
|
||||||
const { service } = this;
|
const { service } = this;
|
||||||
const { pagination, sort } = data;
|
const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId } = data;
|
||||||
const { where } = this.prepareWhereContext(data, {
|
const { where } = this.prepareWhereContext(data, {
|
||||||
specialFieldMap: {
|
specialFieldMap: {
|
||||||
quickWhere: {
|
quickWhere: {
|
||||||
@ -33,7 +35,7 @@ class configService extends MainService {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort);
|
const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId });
|
||||||
return this.success('ok', result);
|
return this.success('ok', result);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -260,5 +262,23 @@ class configService extends MainService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PDA 扫码定位收货明细(system method 包装层),返回匹配的明细列表。
|
||||||
|
* 同一条码可能匹配到多条收货明细,以列表形式返回所有匹配结果。
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.entry_order_id 入库单ID
|
||||||
|
* @param {string} data.barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID)
|
||||||
|
* @return {Promise<Object>} 统一成功包装响应,含匹配的收货明细列表 { list, total }
|
||||||
|
*/
|
||||||
|
async scanDetail(data) {
|
||||||
|
const { service } = this;
|
||||||
|
const { entry_order_id, barcode } = data;
|
||||||
|
const result = await service.systems.storage.receiving.scanDetail(entry_order_id, barcode);
|
||||||
|
if (result.code !== 200) {
|
||||||
|
return this.fail(result.message);
|
||||||
|
}
|
||||||
|
return this.success('查询成功', result.data);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
module.exports = configService;
|
module.exports = configService;
|
||||||
|
|||||||
@ -778,10 +778,12 @@ class DeliveryOrderService extends Service {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据货主仓库策略解析订单步骤。
|
* 根据货主仓库策略解析订单步骤。
|
||||||
|
* 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, use_status=1),则抛出错误拒绝创建。
|
||||||
*
|
*
|
||||||
* @param {Object} info 当前仓库与货主上下文。
|
* @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。
|
||||||
* @param {Object|null} transaction 数据库事务。
|
* @param {Object|null} transaction 数据库事务。
|
||||||
* @return {Promise<number>} 订单步骤,需审批返回 0,免审批返回 1。
|
* @return {Promise<number>} 订单步骤,需审批返回 0,免审批返回 1。
|
||||||
|
* @throws {Error} 货主未与当前仓库签约时抛出。
|
||||||
*/
|
*/
|
||||||
async resolveOrderStep(info, transaction = null) {
|
async resolveOrderStep(info, transaction = null) {
|
||||||
const { ctx } = this;
|
const { ctx } = this;
|
||||||
@ -805,7 +807,7 @@ class DeliveryOrderService extends Service {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!relation) {
|
if (!relation) {
|
||||||
return DELIVERY_ORDER_STEP.PENDING_REVIEW;
|
throw new Error('货主未与当前仓库签约,无法创建订单');
|
||||||
}
|
}
|
||||||
|
|
||||||
const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse;
|
const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse;
|
||||||
|
|||||||
@ -131,6 +131,26 @@ class entryOrderService extends Service {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 写入操作日志
|
||||||
|
await ctx.service.systems.operationLog.createOperationLog({
|
||||||
|
businessType: 'entry_order',
|
||||||
|
businessId: orderId,
|
||||||
|
operationCode: 'ENTRY_ORDER_CREATE',
|
||||||
|
operator: {
|
||||||
|
id: ctx.user?.employees_id || ctx.user?.id || '',
|
||||||
|
name: ctx.user?.employees_name || '',
|
||||||
|
},
|
||||||
|
extras: {
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
entryOrderCode: orderCode,
|
||||||
|
sourceType: fromCode,
|
||||||
|
totalOrderLines,
|
||||||
|
finalStatus,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
// 提交事务
|
// 提交事务
|
||||||
await transaction.commit();
|
await transaction.commit();
|
||||||
|
|
||||||
@ -172,9 +192,9 @@ class entryOrderService extends Service {
|
|||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 发生异常,回滚事务
|
// 发生异常,回滚事务
|
||||||
await transaction.rollback().catch(e => console.error('回滚事务失败:', e));
|
await transaction.rollback().catch(e => ctx.logger.error(`回滚事务失败: ${e.message}`, e));
|
||||||
|
|
||||||
console.error('addOrder 事务异常:', error);
|
ctx.logger.error(`addOrder 事务异常: ${error.message}`, error);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
message: `系统异常: ${error.message}`,
|
message: `系统异常: ${error.message}`,
|
||||||
@ -825,248 +845,74 @@ class entryOrderService extends Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) {
|
/**
|
||||||
if (orderLines.length < 1) {
|
* 审核入库单(CREATED → PENDING)。
|
||||||
throw new Error('行不能为空');
|
* 只允许已绑定收货单的入库单推进状态,未绑定则拒绝。
|
||||||
}
|
*
|
||||||
const queryData = {
|
* @param {Object} data 请求体
|
||||||
request: {
|
* @param {number} data.id 入库单 ID
|
||||||
entryOrder: {
|
* @return {Promise<Object>} { success, message, data }
|
||||||
entryOrderCode: entryOrder.entry_order_code,
|
*/
|
||||||
ownerCode: entryOrder.qimen_owner_code,
|
async reviewEntry(data = {}) {
|
||||||
warehouseCode: entryOrder.qimen_warehouse_code,
|
|
||||||
entryOrderId: entryOrder.id,
|
|
||||||
entryOrderType: entryOrder.order_type,
|
|
||||||
outBizCode,
|
|
||||||
confirmType: isFin ? 0 : 1,
|
|
||||||
status: isFin ? 'FULFILLED' : 'PARTFULFILLED',
|
|
||||||
freight: 0,
|
|
||||||
operateTime: this.app.formatDate(new Date()),
|
|
||||||
remark: entryOrder.remark,
|
|
||||||
},
|
|
||||||
orderLines,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const Result = await this.app.qimenClient.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData, {
|
|
||||||
ctx: this.ctx,
|
|
||||||
});
|
|
||||||
return Result;
|
|
||||||
}
|
|
||||||
async entryorderConfirm(orderId, isCompleted) {
|
|
||||||
const { app, ctx } = this;
|
const { app, ctx } = this;
|
||||||
const transaction = await app.model.transaction();
|
const orderId = Number(data.id || 0);
|
||||||
|
|
||||||
try {
|
if (!orderId) {
|
||||||
// 锁定数据
|
return { success: false, message: 'id 必填' };
|
||||||
const entryOrder = await app.model.EntryOrder.findOne({
|
}
|
||||||
where: {
|
|
||||||
id: orderId,
|
|
||||||
is_enabled: 1,
|
|
||||||
deleted_at: null,
|
|
||||||
},
|
|
||||||
include: [
|
|
||||||
{
|
|
||||||
model: app.model.EntryItems,
|
|
||||||
as: 'items',
|
|
||||||
lock: transaction.LOCK.UPDATE,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
lock: transaction.LOCK.UPDATE,
|
|
||||||
transaction,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!entryOrder) {
|
const entryOrder = await app.model.EntryOrder.findOne({
|
||||||
await transaction.rollback();
|
where: { id: orderId, is_enabled: 1, deleted_at: null },
|
||||||
return { success: false, message: '入库单不存在' };
|
});
|
||||||
}
|
|
||||||
|
|
||||||
// 状态检查
|
if (!entryOrder) {
|
||||||
const allowedStatuses = [ 'CREATED', 'PENDING' ];
|
return { success: false, message: '入库单不存在' };
|
||||||
if (!allowedStatuses.includes(entryOrder.order_status)) {
|
}
|
||||||
await transaction.rollback();
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: 'INVALID_STATUS',
|
|
||||||
message: `入库单状态[${entryOrder.order_status}]不允许确认`,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const orderLines = [];
|
|
||||||
let totalPlanQty = 0;
|
|
||||||
let totalReceivedQty = 0;
|
|
||||||
let totalConfirmIncrement = 0;
|
|
||||||
let hasItemsToConfirm = false;
|
|
||||||
|
|
||||||
// 第一阶段:计算和验证,不执行更新
|
|
||||||
const pendingUpdates = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < entryOrder.items.length; i++) {
|
|
||||||
const item = entryOrder.items[i];
|
|
||||||
const planQty = item.count || 0;
|
|
||||||
const receivedQty = item.received_quantity || 0;
|
|
||||||
const confirmedQty = item.confirm_quantity || 0;
|
|
||||||
|
|
||||||
// 计算本次确认的增量
|
|
||||||
const confirmIncrement = Math.max(0, receivedQty - confirmedQty);
|
|
||||||
|
|
||||||
if (confirmIncrement > 0) {
|
|
||||||
hasItemsToConfirm = true;
|
|
||||||
|
|
||||||
// 奇门需要的是本次确认的数量(actualQty)
|
|
||||||
const orderLine = {
|
|
||||||
orderLineNo: i + 1,
|
|
||||||
ownerCode: item.owner_code,
|
|
||||||
itemCode: item.item_code,
|
|
||||||
itemId: item.item_id,
|
|
||||||
inventoryType: item.inventory_type,
|
|
||||||
planQty,
|
|
||||||
actualQty: confirmIncrement, // 传本次增量
|
|
||||||
};
|
|
||||||
orderLines.push(orderLine);
|
|
||||||
|
|
||||||
totalConfirmIncrement += confirmIncrement;
|
|
||||||
|
|
||||||
// 记录待更新数据(不执行)
|
|
||||||
pendingUpdates.push({
|
|
||||||
id: item.id,
|
|
||||||
item_id: item.item_id,
|
|
||||||
new_confirm_quantity: confirmedQty + confirmIncrement,
|
|
||||||
old_confirm_quantity: confirmedQty,
|
|
||||||
received_quantity: receivedQty,
|
|
||||||
confirm_increment: confirmIncrement,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
totalPlanQty += planQty;
|
|
||||||
totalReceivedQty += receivedQty;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 没有需要确认的数量
|
|
||||||
if (!hasItemsToConfirm) {
|
|
||||||
await transaction.rollback();
|
|
||||||
return { success: false, message: '没有需要确认的收货数量' };
|
|
||||||
}
|
|
||||||
|
|
||||||
// 判断是否最终完成
|
|
||||||
const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty);
|
|
||||||
let qimenResult = {};
|
|
||||||
// 奇门入库单,数据同步到奇门
|
|
||||||
if (String(entryOrder.source_type) === 'QM') {
|
|
||||||
// 第二阶段:调用奇门接口
|
|
||||||
const Result = await this.qimenEntryorderConfirm(
|
|
||||||
entryOrder,
|
|
||||||
orderLines,
|
|
||||||
isFin,
|
|
||||||
Math.round(new Date() / 1000)
|
|
||||||
);
|
|
||||||
qimenResult = Result.xmlArray.response;
|
|
||||||
// 奇门调用失败,回滚事务
|
|
||||||
if (!qimenResult || String(qimenResult.flag) !== 'success') {
|
|
||||||
await transaction.rollback();
|
|
||||||
console.error('奇门接口调用失败:', qimenResult);
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: 'QIMEN_FAILED',
|
|
||||||
message: '奇门接口调用失败',
|
|
||||||
detail: qimenResult?.message || '未知错误',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 第三阶段:奇门成功,执行数据库更新
|
|
||||||
|
|
||||||
// 1. 更新确认数量
|
|
||||||
for (const update of pendingUpdates) {
|
|
||||||
const result = await app.model.EntryItems.update({
|
|
||||||
confirm_quantity: update.new_confirm_quantity,
|
|
||||||
updated_at: new Date(),
|
|
||||||
}, {
|
|
||||||
where: {
|
|
||||||
id: update.id,
|
|
||||||
confirm_quantity: update.old_confirm_quantity, // 乐观锁,防止并发
|
|
||||||
},
|
|
||||||
transaction,
|
|
||||||
});
|
|
||||||
await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction);
|
|
||||||
if (result[0] === 0) {
|
|
||||||
// 更新失败,可能被并发修改了
|
|
||||||
console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`);
|
|
||||||
// 可以选择重试或抛出异常
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 更新入库单状态
|
|
||||||
let newOrderStatus = entryOrder.order_status;
|
|
||||||
if (isFin) {
|
|
||||||
newOrderStatus = 'COMPLETED';
|
|
||||||
} else if (totalConfirmIncrement > 0) {
|
|
||||||
// CREATED 确认后变为 PENDING,PENDING 确认后保持 PENDING(多次收货确认)
|
|
||||||
newOrderStatus = 'PENDING';
|
|
||||||
}
|
|
||||||
|
|
||||||
const updateResult = await app.model.EntryOrder.update({
|
|
||||||
order_status: newOrderStatus,
|
|
||||||
sync_status: 'SUCCESS',
|
|
||||||
sync_message: JSON.stringify({
|
|
||||||
confirmTime: new Date(),
|
|
||||||
totalPlan: totalPlanQty,
|
|
||||||
totalReceived: totalReceivedQty,
|
|
||||||
totalConfirmIncrement,
|
|
||||||
isFin,
|
|
||||||
pendingUpdatesCount: pendingUpdates.length,
|
|
||||||
qimenResult: qimenResult?.data || {},
|
|
||||||
}),
|
|
||||||
updated_at: new Date(),
|
|
||||||
}, {
|
|
||||||
where: {
|
|
||||||
id: entryOrder.id,
|
|
||||||
order_status: entryOrder.order_status, // 乐观锁
|
|
||||||
},
|
|
||||||
transaction,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (updateResult[0] === 0) {
|
|
||||||
// 入库单状态已被修改,回滚
|
|
||||||
await transaction.rollback();
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
code: 'CONCURRENT_MODIFICATION',
|
|
||||||
message: '入库单已被修改,请刷新后重试',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
// 4. 提交事务
|
|
||||||
await transaction.commit();
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
message: isFin ? '入库单完成确认' : '入库单增量确认成功',
|
|
||||||
data: {
|
|
||||||
entryOrderId: entryOrder.id,
|
|
||||||
entryOrderCode: entryOrder.entry_order_code,
|
|
||||||
orderStatus: newOrderStatus,
|
|
||||||
totalPlan: totalPlanQty,
|
|
||||||
totalReceived: totalReceivedQty,
|
|
||||||
totalConfirmIncrement,
|
|
||||||
isFin,
|
|
||||||
updatedItemsCount: pendingUpdates.length,
|
|
||||||
orderLinesCount: orderLines.length,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
// 发生异常,回滚事务
|
|
||||||
await transaction.rollback().catch(e => {
|
|
||||||
console.error('回滚事务失败:', e);
|
|
||||||
});
|
|
||||||
|
|
||||||
console.error('确认入库单失败:', error);
|
|
||||||
|
|
||||||
|
if (entryOrder.order_status !== 'CREATED') {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
code: 'SYSTEM_ERROR',
|
message: `当前状态[${entryOrder.order_status}]不允许审核,仅 CREATED 可审核`,
|
||||||
message: `系统异常: ${error.message}`,
|
|
||||||
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 校验:必须有绑定的收货单
|
||||||
|
const hasReceiving = await ctx.model.EntryOrderReceiving.findOne({
|
||||||
|
where: { entry_order_id: orderId, deleted_at: null },
|
||||||
|
});
|
||||||
|
if (!hasReceiving) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: '入库单未绑定收货单,请先绑定收货单后再审核',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推进状态
|
||||||
|
await entryOrder.update({
|
||||||
|
order_status: 'PENDING',
|
||||||
|
updated_at: new Date(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// 写操作日志
|
||||||
|
await ctx.service.systems.operationLog.createOperationLog({
|
||||||
|
businessType: 'entry_order',
|
||||||
|
businessId: entryOrder.id,
|
||||||
|
operationCode: 'ENTRY_ORDER_REVIEW',
|
||||||
|
operator: {
|
||||||
|
id: ctx.user?.employees_id || ctx.user?.id || '',
|
||||||
|
name: ctx.user?.employees_name || '',
|
||||||
|
},
|
||||||
|
extras: {
|
||||||
|
warehouseId: entryOrder.warehouse_id,
|
||||||
|
message: '入库单审核通过(CREATED → PENDING)',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '审核成功',
|
||||||
|
data: { id: entryOrder.id, order_status: 'PENDING' },
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -2427,21 +2427,8 @@ class ExpressService extends Service {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// 发件人相关字段统一走接口配置,货主配置仅用于打印链路。
|
// 发件人相关字段统一走接口配置,货主配置仅用于打印链路。
|
||||||
// 三级兜底:express_interface → 仓库 subject_config → 空字符串
|
|
||||||
const storeRow = await this.ctx.model.Store.findByPk(warehouseId, {
|
|
||||||
attributes: [ 'subject_config' ],
|
|
||||||
raw: true,
|
|
||||||
});
|
|
||||||
const subjectConfig = (storeRow && storeRow.subject_config) ? storeRow.subject_config : {};
|
|
||||||
const expressInterfaceConfig = expressInterface ? {
|
const expressInterfaceConfig = expressInterface ? {
|
||||||
...expressInterface,
|
...expressInterface,
|
||||||
sender_name: expressInterface.sender_name || subjectConfig.sender_name || '',
|
|
||||||
sender_tel: expressInterface.sender_tel || subjectConfig.sender_tel || '',
|
|
||||||
province_name: expressInterface.province_name || subjectConfig.province_name || '',
|
|
||||||
city_name: expressInterface.city_name || subjectConfig.city_name || '',
|
|
||||||
district_name: expressInterface.district_name || subjectConfig.district_name || '',
|
|
||||||
town_name: expressInterface.town_name || subjectConfig.town_name || '',
|
|
||||||
address: expressInterface.address || subjectConfig.address || '',
|
|
||||||
} : null;
|
} : null;
|
||||||
|
|
||||||
for (const batch of batches) {
|
for (const batch of batches) {
|
||||||
|
|||||||
@ -729,27 +729,17 @@ class ExpressPlatformService extends MainService {
|
|||||||
inputsite: listByWarehousePlatformCode.site_code || '',
|
inputsite: listByWarehousePlatformCode.site_code || '',
|
||||||
sitecode: listByWarehousePlatformCode.site_code || '',
|
sitecode: listByWarehousePlatformCode.site_code || '',
|
||||||
shipperno: listByWarehousePlatformCode.shipperno || '',
|
shipperno: listByWarehousePlatformCode.shipperno || '',
|
||||||
sender: (() => {
|
sender: {
|
||||||
const senderName = listByWarehousePlatformCode.sender_name || '';
|
company: listByWarehousePlatformCode.shop_name || '',
|
||||||
const senderTel = listByWarehousePlatformCode.sender_tel || '';
|
name: listByWarehousePlatformCode.sender_name || '',
|
||||||
const senderProvince = listByWarehousePlatformCode.province_name || '';
|
phone: listByWarehousePlatformCode.sender_tel || '',
|
||||||
const senderCity = listByWarehousePlatformCode.city_name || '';
|
country: 'CN',
|
||||||
const senderDistrict = listByWarehousePlatformCode.district_name || '';
|
city: listByWarehousePlatformCode.city_name || '',
|
||||||
const senderTown = listByWarehousePlatformCode.town_name || '';
|
province: listByWarehousePlatformCode.province_name || '',
|
||||||
const senderAddress = listByWarehousePlatformCode.address || '';
|
area: listByWarehousePlatformCode.district_name || '',
|
||||||
const fallback = '仓库未配置发件人';
|
town: listByWarehousePlatformCode.town_name || '',
|
||||||
return {
|
address: listByWarehousePlatformCode.address || '',
|
||||||
company: listByWarehousePlatformCode.shop_name || '',
|
}, // 需要实现
|
||||||
name: senderName || fallback,
|
|
||||||
phone: senderTel || (senderName ? '' : fallback),
|
|
||||||
country: 'CN',
|
|
||||||
city: senderCity || fallback,
|
|
||||||
province: senderProvince || fallback,
|
|
||||||
area: senderDistrict || fallback,
|
|
||||||
town: senderTown || fallback,
|
|
||||||
address: senderAddress || fallback,
|
|
||||||
};
|
|
||||||
})(),
|
|
||||||
receiver: {
|
receiver: {
|
||||||
name: order.name || '',
|
name: order.name || '',
|
||||||
company: order.company || '',
|
company: order.company || '',
|
||||||
@ -789,7 +779,6 @@ class ExpressPlatformService extends MainService {
|
|||||||
providercode,
|
providercode,
|
||||||
numpackage,
|
numpackage,
|
||||||
businessplat,
|
businessplat,
|
||||||
paymode,
|
|
||||||
ordertype,
|
ordertype,
|
||||||
businessType,
|
businessType,
|
||||||
codpaymoney,
|
codpaymoney,
|
||||||
@ -817,12 +806,11 @@ class ExpressPlatformService extends MainService {
|
|||||||
const {
|
const {
|
||||||
name,
|
name,
|
||||||
phone,
|
phone,
|
||||||
mobile,
|
|
||||||
province: receiverProvince,
|
province: receiverProvince,
|
||||||
city: receiverCity,
|
city: receiverCity,
|
||||||
address: receiverAddress,
|
address: receiverAddress,
|
||||||
} = receiver;
|
} = receiver;
|
||||||
const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || '仓库未配置发件人';
|
const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || '';
|
||||||
const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || '';
|
const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || '';
|
||||||
const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试';
|
const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试';
|
||||||
|
|
||||||
@ -874,18 +862,18 @@ class ExpressPlatformService extends MainService {
|
|||||||
playload.codpaymoney = '';
|
playload.codpaymoney = '';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(matchedPlatform.platid ===672){
|
if (matchedPlatform.platid === 672) {
|
||||||
if(!order.source_order_codes){
|
if (!order.source_order_codes) {
|
||||||
throw new Error('订单数据错误,缺失平台订单号');
|
throw new Error('订单数据错误,缺失平台订单号');
|
||||||
}
|
}
|
||||||
playload.object_Id = order.source_order_codes.split(",")[0];
|
playload.object_Id = order.source_order_codes.split(',')[0];
|
||||||
if(!order.extend_props.ewaybill_order_code){
|
if (!order.extend_props.ewaybill_order_code) {
|
||||||
throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈');
|
throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈');
|
||||||
}
|
}
|
||||||
playload.oaid = order.extend_props.ewaybill_order_code;
|
playload.oaid = order.extend_props.ewaybill_order_code;
|
||||||
playload.transtype = "0";
|
playload.transtype = '0';
|
||||||
playload.Mallmaskid = order.buyer_nick;
|
playload.Mallmaskid = order.buyer_nick;
|
||||||
playload.mainsubpaymode = "1";
|
playload.mainsubpaymode = '1';
|
||||||
delete playload.plattradeno;
|
delete playload.plattradeno;
|
||||||
}
|
}
|
||||||
playload.ProviderID = listByWarehousePlatformCode.providerid;
|
playload.ProviderID = listByWarehousePlatformCode.providerid;
|
||||||
@ -1233,39 +1221,39 @@ class ExpressPlatformService extends MainService {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
case 'QT':
|
case 'QT':
|
||||||
case 'OTHER':
|
case 'OTHER':
|
||||||
successUpdates = (result.results || []).map(item => {
|
successUpdates = (result.results || []).map(item => {
|
||||||
const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_');
|
const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_');
|
||||||
const waybillCode = String(item.logisticno || item.waybill_code || '').trim();
|
const waybillCode = String(item.logisticno || item.waybill_code || '').trim();
|
||||||
return {
|
return {
|
||||||
warehouse_id,
|
warehouse_id,
|
||||||
order_id,
|
order_id,
|
||||||
business_key,
|
business_key,
|
||||||
|
waybill_code: waybillCode,
|
||||||
|
orderExpressValues: {
|
||||||
waybill_code: waybillCode,
|
waybill_code: waybillCode,
|
||||||
orderExpressValues: {
|
printinfo: item.printinfo,
|
||||||
waybill_code: waybillCode,
|
signature: item.signature,
|
||||||
printinfo: item.printinfo,
|
encryptprintinfo: item.encryptprintinfo,
|
||||||
signature: item.signature,
|
encryptedtoken: item.encryptedtoken,
|
||||||
encryptprintinfo: item.encryptprintinfo,
|
...this.buildOrderExpressVerPatch([ item.ver ]),
|
||||||
encryptedtoken: item.encryptedtoken,
|
create_at: new Date(),
|
||||||
...this.buildOrderExpressVerPatch([ item.ver ]),
|
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
||||||
create_at: new Date(),
|
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
||||||
logistics_code: listByWarehousePlatformCode.logistics_code || '',
|
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
||||||
logistics_interface_id: listByWarehousePlatformCode.id || null,
|
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
||||||
logistics_name: listByWarehousePlatformCode.logistics_name || '',
|
platform_code: listByWarehousePlatformCode.platform_code || '',
|
||||||
logistics_interface_name: listByWarehousePlatformCode.name || '',
|
status: 1,
|
||||||
platform_code: listByWarehousePlatformCode.platform_code || '',
|
retry_count: 0,
|
||||||
status: 1,
|
},
|
||||||
retry_count: 0,
|
orderDeliveryValues: {
|
||||||
},
|
post_status: 'fin',
|
||||||
orderDeliveryValues: {
|
order_flag: '',
|
||||||
post_status: 'fin',
|
},
|
||||||
order_flag: '',
|
};
|
||||||
},
|
});
|
||||||
};
|
break;
|
||||||
});
|
|
||||||
break;
|
|
||||||
default: {
|
default: {
|
||||||
const unmatchedPlatformCode = String(listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code || '').trim();
|
const unmatchedPlatformCode = String(listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code || '').trim();
|
||||||
this.ctx.logger.error('[expressPlatform.polyapi] switch 无匹配 platform_code', {
|
this.ctx.logger.error('[expressPlatform.polyapi] switch 无匹配 platform_code', {
|
||||||
@ -1546,10 +1534,10 @@ class ExpressPlatformService extends MainService {
|
|||||||
// 自动同步回传:快递号分配成功后异步触发订单同步
|
// 自动同步回传:快递号分配成功后异步触发订单同步
|
||||||
try {
|
try {
|
||||||
const settlementEntries = Array.from(settlementRelationMap.entries());
|
const settlementEntries = Array.from(settlementRelationMap.entries());
|
||||||
for (const [key, relation] of settlementEntries) {
|
for (const [ key, relation ] of settlementEntries) {
|
||||||
const successCount = Number(relation && relation.success_count) || 0;
|
const successCount = Number(relation && relation.success_count) || 0;
|
||||||
if (successCount <= 0) continue;
|
if (successCount <= 0) continue;
|
||||||
const [storeId, warehouseId] = key.split(':').map(Number);
|
const [ storeId, warehouseId ] = key.split(':').map(Number);
|
||||||
if (!storeId || !warehouseId) continue;
|
if (!storeId || !warehouseId) continue;
|
||||||
|
|
||||||
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
||||||
@ -1700,28 +1688,18 @@ class ExpressPlatformService extends MainService {
|
|||||||
? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '')
|
? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '')
|
||||||
: '',
|
: '',
|
||||||
product_code: String(listByWarehousePlatformCode.product_type || '').trim(),
|
product_code: String(listByWarehousePlatformCode.product_type || '').trim(),
|
||||||
sender: (() => {
|
sender: {
|
||||||
const senderName = listByWarehousePlatformCode.sender_name || '';
|
address: {
|
||||||
const senderTel = listByWarehousePlatformCode.sender_tel || '';
|
city: listByWarehousePlatformCode.city_name,
|
||||||
const senderProvince = listByWarehousePlatformCode.province_name || '';
|
detail: listByWarehousePlatformCode.address,
|
||||||
const senderCity = listByWarehousePlatformCode.city_name || '';
|
district: listByWarehousePlatformCode.district_name,
|
||||||
const senderDistrict = listByWarehousePlatformCode.district_name || '';
|
province: listByWarehousePlatformCode.province_name,
|
||||||
const senderTown = listByWarehousePlatformCode.town_name || '';
|
town: listByWarehousePlatformCode.town_name || null,
|
||||||
const senderAddress = listByWarehousePlatformCode.address || '';
|
},
|
||||||
const fallback = '仓库未配置发件人';
|
mobile: listByWarehousePlatformCode.sender_tel,
|
||||||
return {
|
name: listByWarehousePlatformCode.sender_name,
|
||||||
address: {
|
phone: listByWarehousePlatformCode.sender_tel,
|
||||||
city: senderCity || fallback,
|
},
|
||||||
detail: senderAddress || fallback,
|
|
||||||
district: senderDistrict || fallback,
|
|
||||||
province: senderProvince || fallback,
|
|
||||||
town: senderTown || null,
|
|
||||||
},
|
|
||||||
mobile: senderTel || (senderName ? '' : fallback),
|
|
||||||
name: senderName || fallback,
|
|
||||||
phone: senderTel || (senderName ? '' : fallback),
|
|
||||||
};
|
|
||||||
})(),
|
|
||||||
trade_order_info_dtos: tradeOrderList,
|
trade_order_info_dtos: tradeOrderList,
|
||||||
brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(),
|
brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(),
|
||||||
need_encrypt: true,
|
need_encrypt: true,
|
||||||
@ -1886,10 +1864,10 @@ class ExpressPlatformService extends MainService {
|
|||||||
orderMetaMap
|
orderMetaMap
|
||||||
);
|
);
|
||||||
const settlementEntries = Array.from(settlementRelationMap.entries());
|
const settlementEntries = Array.from(settlementRelationMap.entries());
|
||||||
for (const [key, relation] of settlementEntries) {
|
for (const [ key, relation ] of settlementEntries) {
|
||||||
const successCount = Number(relation && relation.success_count) || 0;
|
const successCount = Number(relation && relation.success_count) || 0;
|
||||||
if (successCount <= 0) continue;
|
if (successCount <= 0) continue;
|
||||||
const [storeId, warehouseId] = key.split(':').map(Number);
|
const [ storeId, warehouseId ] = key.split(':').map(Number);
|
||||||
if (!storeId || !warehouseId) continue;
|
if (!storeId || !warehouseId) continue;
|
||||||
|
|
||||||
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
||||||
@ -2218,7 +2196,6 @@ class ExpressPlatformService extends MainService {
|
|||||||
*/
|
*/
|
||||||
async pdd(data = {}) {
|
async pdd(data = {}) {
|
||||||
const {
|
const {
|
||||||
matchedPlatform = {},
|
|
||||||
listByWarehousePlatformCode = {},
|
listByWarehousePlatformCode = {},
|
||||||
orders = [],
|
orders = [],
|
||||||
} = data && typeof data === 'object' ? data : {};
|
} = data && typeof data === 'object' ? data : {};
|
||||||
@ -2267,29 +2244,19 @@ class ExpressPlatformService extends MainService {
|
|||||||
accessToken: listByWarehousePlatformCode.token,
|
accessToken: listByWarehousePlatformCode.token,
|
||||||
param_waybill_cloud_print_apply_new_request: {
|
param_waybill_cloud_print_apply_new_request: {
|
||||||
need_encrypt: true,
|
need_encrypt: true,
|
||||||
sender: (() => {
|
sender: {
|
||||||
const senderName = listByWarehousePlatformCode.sender_name || '';
|
address: {
|
||||||
const senderTel = listByWarehousePlatformCode.sender_tel || '';
|
country: '中国',
|
||||||
const senderProvince = listByWarehousePlatformCode.province_name || '';
|
city: listByWarehousePlatformCode.city_name,
|
||||||
const senderCity = listByWarehousePlatformCode.city_name || '';
|
province: listByWarehousePlatformCode.province_name,
|
||||||
const senderDistrict = listByWarehousePlatformCode.district_name || '';
|
district: listByWarehousePlatformCode.district_name,
|
||||||
const senderTown = listByWarehousePlatformCode.town_name || '';
|
town: listByWarehousePlatformCode.town_name || null,
|
||||||
const senderAddress = listByWarehousePlatformCode.address || '';
|
detail: listByWarehousePlatformCode.address,
|
||||||
const fallback = '仓库未配置发件人';
|
},
|
||||||
return {
|
moblie: listByWarehousePlatformCode.sender_tel,
|
||||||
address: {
|
name: listByWarehousePlatformCode.sender_name,
|
||||||
country: '中国',
|
phone: listByWarehousePlatformCode.sender_tel,
|
||||||
city: senderCity || fallback,
|
},
|
||||||
province: senderProvince || fallback,
|
|
||||||
district: senderDistrict || fallback,
|
|
||||||
town: senderTown || null,
|
|
||||||
detail: senderAddress || fallback,
|
|
||||||
},
|
|
||||||
moblie: senderTel || (senderName ? '' : fallback),
|
|
||||||
name: senderName || fallback,
|
|
||||||
phone: senderTel || (senderName ? '' : fallback),
|
|
||||||
};
|
|
||||||
})(),
|
|
||||||
trade_order_info_dtos: tradeOrderList,
|
trade_order_info_dtos: tradeOrderList,
|
||||||
wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express
|
wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express
|
||||||
? (listByWarehousePlatformCode.express.PDD || '')
|
? (listByWarehousePlatformCode.express.PDD || '')
|
||||||
@ -2581,10 +2548,10 @@ class ExpressPlatformService extends MainService {
|
|||||||
// 自动同步回传:快递号分配成功后异步触发订单同步
|
// 自动同步回传:快递号分配成功后异步触发订单同步
|
||||||
try {
|
try {
|
||||||
const settlementEntries = Array.from(settlementRelationMap.entries());
|
const settlementEntries = Array.from(settlementRelationMap.entries());
|
||||||
for (const [key, relation] of settlementEntries) {
|
for (const [ key, relation ] of settlementEntries) {
|
||||||
const successCount = Number(relation && relation.success_count) || 0;
|
const successCount = Number(relation && relation.success_count) || 0;
|
||||||
if (successCount <= 0) continue;
|
if (successCount <= 0) continue;
|
||||||
const [storeId, warehouseId] = key.split(':').map(Number);
|
const [ storeId, warehouseId ] = key.split(':').map(Number);
|
||||||
if (!storeId || !warehouseId) continue;
|
if (!storeId || !warehouseId) continue;
|
||||||
|
|
||||||
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
const contractConfig = await this.service.systems.storeWarehouse.getContractConfig(
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -306,6 +306,19 @@ class operationLogService extends Service {
|
|||||||
return await this.queryLogsByBusinessType(query, 'receiving');
|
return await this.queryLogsByBusinessType(query, 'receiving');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询入库单操作日志。
|
||||||
|
* @param {Object} query 查询参数。
|
||||||
|
* @param {string|number} query.id 入库单ID。
|
||||||
|
* @param {string|number} query.warehouseId 仓库ID。
|
||||||
|
* @param {number} [query.page=1] 页码。
|
||||||
|
* @param {number} [query.pageSize=20] 每页数量。
|
||||||
|
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||||||
|
*/
|
||||||
|
async queryEntryOrderLogs(query = {}) {
|
||||||
|
return await this.queryLogsByBusinessType(query, 'entry_order');
|
||||||
|
}
|
||||||
|
|
||||||
async getMessageDetail(data) {
|
async getMessageDetail(data) {
|
||||||
const { id, type } = data;
|
const { id, type } = data;
|
||||||
const { ctx } = this;
|
const { ctx } = this;
|
||||||
|
|||||||
@ -479,12 +479,19 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte
|
|||||||
id: orderId,
|
id: orderId,
|
||||||
warehouse_id: warehouseId,
|
warehouse_id: warehouseId,
|
||||||
},
|
},
|
||||||
attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes' ],
|
attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ],
|
||||||
|
lock: transaction.LOCK.UPDATE,
|
||||||
raw: true,
|
raw: true,
|
||||||
transaction,
|
transaction,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 防重:如果订单已完成同步,跳过本次出库扣减
|
||||||
|
if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') {
|
||||||
|
service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null;
|
const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null;
|
||||||
const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null;
|
const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null;
|
||||||
const freshOrderItems = await orderItemsModel.findAll({
|
const freshOrderItems = await orderItemsModel.findAll({
|
||||||
@ -543,6 +550,23 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await runTransactionWithLockRetryInternal(service, 'processLocalChannelOrder', async transaction => {
|
await runTransactionWithLockRetryInternal(service, 'processLocalChannelOrder', async transaction => {
|
||||||
|
// 防重:SELECT FOR UPDATE 锁定订单行并检查 sync_status,防止重复出库
|
||||||
|
const lockedOrderRow = await orderModel.findOne({
|
||||||
|
where: {
|
||||||
|
id: orderId,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
},
|
||||||
|
attributes: [ 'id', 'sync_status' ],
|
||||||
|
lock: transaction.LOCK.UPDATE,
|
||||||
|
raw: true,
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (lockedOrderRow && String(lockedOrderRow.sync_status || '').trim() === 'fin') {
|
||||||
|
service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const freshOrderItems = await orderItemsModel.findAll({
|
const freshOrderItems = await orderItemsModel.findAll({
|
||||||
where: {
|
where: {
|
||||||
order_id: orderId,
|
order_id: orderId,
|
||||||
|
|||||||
@ -7,6 +7,7 @@ const OUTBOUND_STATUS = 'fin';
|
|||||||
const OUTBOUND_STEP = 4;
|
const OUTBOUND_STEP = 4;
|
||||||
const ORDER_STATUS_FINISHED = 'finished';
|
const ORDER_STATUS_FINISHED = 'finished';
|
||||||
const MAX_BATCH_SIZE = 500;
|
const MAX_BATCH_SIZE = 500;
|
||||||
|
const STORAGE_STATUS_FIN = 'fin';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 订单自动化出库服务。
|
* 订单自动化出库服务。
|
||||||
@ -119,6 +120,7 @@ class OrderAutoOutboundService extends MainService {
|
|||||||
status: {
|
status: {
|
||||||
[Op.notIn]: [ 'cancel', 'error', 'finished' ],
|
[Op.notIn]: [ 'cancel', 'error', 'finished' ],
|
||||||
},
|
},
|
||||||
|
storage_status: STORAGE_STATUS_FIN,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (rules.require_recheck) {
|
if (rules.require_recheck) {
|
||||||
|
|||||||
@ -424,7 +424,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
|||||||
}
|
}
|
||||||
// 合并 barcodes 数组(Set 去重)
|
// 合并 barcodes 数组(Set 去重)
|
||||||
if (item.barcodes && item.barcodes.length > 0) {
|
if (item.barcodes && item.barcodes.length > 0) {
|
||||||
const merged = new Set([...(existing.barcodes || []), ...item.barcodes]);
|
const merged = new Set([ ...(existing.barcodes || []), ...item.barcodes ]);
|
||||||
existing.barcodes = Array.from(merged);
|
existing.barcodes = Array.from(merged);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@ -1516,7 +1516,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
|||||||
|
|
||||||
if (Array.isArray(dispatchRows) && dispatchRows.length > 0) {
|
if (Array.isArray(dispatchRows) && dispatchRows.length > 0) {
|
||||||
// 合并 current 表与 dispatch 表结果,按 wave_id、id 升序排列
|
// 合并 current 表与 dispatch 表结果,按 wave_id、id 升序排列
|
||||||
const mergedRows = [...currentRows, ...dispatchRows].sort((a, b) => {
|
const mergedRows = [ ...currentRows, ...dispatchRows ].sort((a, b) => {
|
||||||
const waveDiff = (a.wave_id || 0) - (b.wave_id || 0);
|
const waveDiff = (a.wave_id || 0) - (b.wave_id || 0);
|
||||||
if (waveDiff !== 0) return waveDiff;
|
if (waveDiff !== 0) return waveDiff;
|
||||||
return (a.id || 0) - (b.id || 0);
|
return (a.id || 0) - (b.id || 0);
|
||||||
@ -1546,7 +1546,7 @@ class OrderPrintSystemService extends OrderBaseService {
|
|||||||
* 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。
|
* 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。
|
||||||
*
|
*
|
||||||
* @param {number[]} orderIds 订单 ID 列表。
|
* @param {number[]} orderIds 订单 ID 列表。
|
||||||
* @returns {Promise<Array<Object>>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、
|
* @return {Promise<Array<Object>>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、
|
||||||
* logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、
|
* logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、
|
||||||
* warehouse_id、printinfo、signature、encryptprintinfo、ver。
|
* warehouse_id、printinfo、signature、encryptprintinfo、ver。
|
||||||
*/
|
*/
|
||||||
@ -2682,8 +2682,8 @@ ${waveFilterSql}
|
|||||||
is_active: 1,
|
is_active: 1,
|
||||||
delete_at: null,
|
delete_at: null,
|
||||||
},
|
},
|
||||||
order: [['bind_count', 'DESC']],
|
order: [[ 'bind_count', 'DESC' ]],
|
||||||
attributes: ['package_material_name'],
|
attributes: [ 'package_material_name' ],
|
||||||
raw: true,
|
raw: true,
|
||||||
});
|
});
|
||||||
if (topMatch && topMatch.package_material_name) {
|
if (topMatch && topMatch.package_material_name) {
|
||||||
@ -2707,7 +2707,7 @@ ${waveFilterSql}
|
|||||||
let subjectConfig = {};
|
let subjectConfig = {};
|
||||||
if (warehouseId > 0) {
|
if (warehouseId > 0) {
|
||||||
const storeRow = await this.ctx.model.Store.findByPk(warehouseId, {
|
const storeRow = await this.ctx.model.Store.findByPk(warehouseId, {
|
||||||
attributes: ['subject_config'],
|
attributes: [ 'subject_config' ],
|
||||||
raw: true,
|
raw: true,
|
||||||
});
|
});
|
||||||
if (storeRow && storeRow.subject_config) {
|
if (storeRow && storeRow.subject_config) {
|
||||||
|
|||||||
@ -837,6 +837,10 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
const totalCount = pendingOrderIds.length;
|
const totalCount = pendingOrderIds.length;
|
||||||
let processedCount = 0;
|
let processedCount = 0;
|
||||||
|
|
||||||
|
// 按订单维度跟踪已锁定的库存记录,用于缺货订单的原子回滚。
|
||||||
|
// Map<orderId, Array<{ storageId: number, quantity: number }>>
|
||||||
|
const orderLockRecords = new Map();
|
||||||
|
|
||||||
// 对于 storage_status='error' 的重分配订单,先清理旧的 picking 记录并释放已锁定的库存
|
// 对于 storage_status='error' 的重分配订单,先清理旧的 picking 记录并释放已锁定的库存
|
||||||
if (errorRetryOrderIds.length > 0) {
|
if (errorRetryOrderIds.length > 0) {
|
||||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 检测到 error 重试订单,开始清理旧数据', {
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 检测到 error 重试订单,开始清理旧数据', {
|
||||||
@ -1108,6 +1112,19 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
storageRow.id, allocationQuantity, { transaction }
|
storageRow.id, allocationQuantity, { transaction }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity
|
||||||
|
storageRow.available_quantity = currentAvailable;
|
||||||
|
storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity;
|
||||||
|
|
||||||
|
// 回退 remainingQuantity:未分配成功的数量加回去
|
||||||
|
remainingQuantity += allocationQuantity;
|
||||||
|
|
||||||
|
// 回退 allocatedQuantityForItem
|
||||||
|
allocatedQuantityForItem -= allocationQuantity;
|
||||||
|
|
||||||
|
// 回退 allocatedQuantityForOrder
|
||||||
|
allocatedQuantityForOrder -= allocationQuantity;
|
||||||
|
|
||||||
// 回退 storageAllocationMap 中的累加值
|
// 回退 storageAllocationMap 中的累加值
|
||||||
const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0;
|
const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0;
|
||||||
const newStorageQty = prevStorageQty - allocationQuantity;
|
const newStorageQty = prevStorageQty - allocationQuantity;
|
||||||
@ -1117,17 +1134,29 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
storageAllocationMap.set(storageRow.id, newStorageQty);
|
storageAllocationMap.set(storageRow.id, newStorageQty);
|
||||||
}
|
}
|
||||||
|
|
||||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加', {
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加及内存计数器', {
|
||||||
orderId,
|
orderId,
|
||||||
storageId: storageRow.id,
|
storageId: storageRow.id,
|
||||||
allocationQuantity,
|
allocationQuantity,
|
||||||
prevStorageQty,
|
prevStorageQty,
|
||||||
newStorageQty,
|
newStorageQty,
|
||||||
|
rollback: {
|
||||||
|
remainingQuantity,
|
||||||
|
allocatedQuantityForItem,
|
||||||
|
allocatedQuantityForOrder,
|
||||||
|
storageAvailableQuantity: storageRow.available_quantity,
|
||||||
|
storageLockedQuantity: storageRow.locked_quantity,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚
|
||||||
|
const orderLockList = orderLockRecords.get(orderId) || [];
|
||||||
|
orderLockList.push({ storageId: storageRow.id, quantity: allocationQuantity });
|
||||||
|
orderLockRecords.set(orderId, orderLockList);
|
||||||
|
|
||||||
pickingRows.push({
|
pickingRows.push({
|
||||||
order_id: orderId,
|
order_id: orderId,
|
||||||
order_item_id: toNumber(orderItem.id, 0),
|
order_item_id: toNumber(orderItem.id, 0),
|
||||||
@ -1143,6 +1172,12 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (remainingQuantity > 0) {
|
if (remainingQuantity > 0) {
|
||||||
|
// 确保每个明细的缺货原因独立计算,避免候选库位为空时的诊断原因
|
||||||
|
// 被错误地复用到候选库位非空但仍不足的明细上
|
||||||
|
const finalShortageReason = candidateStorageRows.length === 0
|
||||||
|
? shortageReason
|
||||||
|
: (shortageReason || '库存不足');
|
||||||
|
|
||||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备写入缺货条目', {
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备写入缺货条目', {
|
||||||
orderId,
|
orderId,
|
||||||
orderItemId: toNumber(orderItem.id, 0),
|
orderItemId: toNumber(orderItem.id, 0),
|
||||||
@ -1151,12 +1186,14 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
allocatedQuantity: allocatedQuantityForItem,
|
allocatedQuantity: allocatedQuantityForItem,
|
||||||
remainingQuantity,
|
remainingQuantity,
|
||||||
candidateCount: candidateStorageRows.length,
|
candidateCount: candidateStorageRows.length,
|
||||||
|
shortageReason,
|
||||||
|
finalShortageReason,
|
||||||
});
|
});
|
||||||
shortageItems.push({
|
shortageItems.push({
|
||||||
stock_id: stockId,
|
stock_id: stockId,
|
||||||
required_quantity: requiredQuantity,
|
required_quantity: requiredQuantity,
|
||||||
allocated_quantity: allocatedQuantityForItem,
|
allocated_quantity: allocatedQuantityForItem,
|
||||||
reason: shortageReason,
|
reason: finalShortageReason,
|
||||||
});
|
});
|
||||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细存在缺货', {
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细存在缺货', {
|
||||||
orderId,
|
orderId,
|
||||||
@ -1166,6 +1203,7 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
allocatedQuantityForItem,
|
allocatedQuantityForItem,
|
||||||
remainingQuantity,
|
remainingQuantity,
|
||||||
shortageReason,
|
shortageReason,
|
||||||
|
finalShortageReason,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1185,6 +1223,62 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
finalShortageMessage,
|
finalShortageMessage,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 单订单原子性分配:如果本订单有缺货,回滚该订单所有已成功锁定的库存,
|
||||||
|
// 并从 pickingRows 中移除该订单的所有记录,确保同一事务内该订单不留任何 locked_quantity。
|
||||||
|
if (finalShortageMessage) {
|
||||||
|
const orderLocks = orderLockRecords.get(orderId);
|
||||||
|
if (Array.isArray(orderLocks) && orderLocks.length > 0) {
|
||||||
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 开始回滚订单已锁定库存', {
|
||||||
|
orderId,
|
||||||
|
orderLockCount: orderLocks.length,
|
||||||
|
orderLocks,
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const lockRecord of orderLocks) {
|
||||||
|
await ctx.service.systems.storage.index.unlockQuantity(
|
||||||
|
lockRecord.storageId, lockRecord.quantity, { transaction }
|
||||||
|
);
|
||||||
|
|
||||||
|
// 回退 storageAllocationMap 中的累加值
|
||||||
|
const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0;
|
||||||
|
const newStorageQty = prevStorageQty - lockRecord.quantity;
|
||||||
|
if (newStorageQty <= 0) {
|
||||||
|
storageAllocationMap.delete(lockRecord.storageId);
|
||||||
|
} else {
|
||||||
|
storageAllocationMap.set(lockRecord.storageId, newStorageQty);
|
||||||
|
}
|
||||||
|
|
||||||
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已回滚单条库存锁定', {
|
||||||
|
orderId,
|
||||||
|
storageId: lockRecord.storageId,
|
||||||
|
quantity: lockRecord.quantity,
|
||||||
|
prevStorageQty,
|
||||||
|
newStorageQty,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 回退订单级别的已分配数量计数器
|
||||||
|
allocatedQuantityForOrder = 0;
|
||||||
|
|
||||||
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单锁定库存回滚完成,已重置 allocatedQuantityForOrder', {
|
||||||
|
orderId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从 pickingRows 中移除该订单的所有记录。
|
||||||
|
// 使用反向遍历 + splice 避免索引漂移,保持 pickingRows 顺序。
|
||||||
|
for (let pickIdx = pickingRows.length - 1; pickIdx >= 0; pickIdx -= 1) {
|
||||||
|
if (pickingRows[pickIdx].order_id === orderId) {
|
||||||
|
pickingRows.splice(pickIdx, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已从 pickingRows 移除缺货订单记录', {
|
||||||
|
orderId,
|
||||||
|
remainingPickingCount: pickingRows.length,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const orderUpdateValues = finalShortageMessage
|
const orderUpdateValues = finalShortageMessage
|
||||||
? {
|
? {
|
||||||
storage_status: STORAGE_STATUS_ERROR,
|
storage_status: STORAGE_STATUS_ERROR,
|
||||||
@ -1752,14 +1846,12 @@ class OrderStorageAllocationService extends MainService {
|
|||||||
let msg;
|
let msg;
|
||||||
if (isPending) msg = `同步到${channelNames}渠道`;
|
if (isPending) msg = `同步到${channelNames}渠道`;
|
||||||
else if (failed) {
|
else if (failed) {
|
||||||
const reasonMap = { 'express_unallocated': '快递未分配', 'sn_batch_forbidden': 'SN订单不支持批量' };
|
const reasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' };
|
||||||
msg = `同步跳过:${reasonMap[failed.failed_reason] || failed.failed_reason || failed.message || '条件不满足'}`;
|
msg = `同步跳过:${reasonMap[failed.failed_reason] || failed.failed_reason || failed.message || '条件不满足'}`;
|
||||||
}
|
} else if (skipped) {
|
||||||
else if (skipped) {
|
const skipReasonMap = { already_synced: '已同步', not_found: '订单不存在' };
|
||||||
const skipReasonMap = { 'already_synced': '已同步', 'not_found': '订单不存在' };
|
|
||||||
msg = `同步跳过:${skipReasonMap[skipped.skipped_reason] || skipped.skipped_reason || '已同步'}`;
|
msg = `同步跳过:${skipReasonMap[skipped.skipped_reason] || skipped.skipped_reason || '已同步'}`;
|
||||||
}
|
} else msg = '同步跳过';
|
||||||
else msg = `同步跳过`;
|
|
||||||
return {
|
return {
|
||||||
businessType: 'order',
|
businessType: 'order',
|
||||||
businessId: `${orderId}`,
|
businessId: `${orderId}`,
|
||||||
|
|||||||
@ -57,6 +57,7 @@ class PickSystemService extends Service {
|
|||||||
*
|
*
|
||||||
* @param {string} message 错误文案。
|
* @param {string} message 错误文案。
|
||||||
* @param {number} [code=400] 错误码。
|
* @param {number} [code=400] 错误码。
|
||||||
|
* @param {*} [data=null] 附加数据。
|
||||||
* @return {Error} 错误对象。
|
* @return {Error} 错误对象。
|
||||||
*/
|
*/
|
||||||
createBusinessError(message, code = 400, data = null) {
|
createBusinessError(message, code = 400, data = null) {
|
||||||
|
|||||||
@ -2,11 +2,6 @@
|
|||||||
|
|
||||||
const Service = require('egg').Service;
|
const Service = require('egg').Service;
|
||||||
|
|
||||||
const result = {
|
|
||||||
platform: null,
|
|
||||||
count: 0,
|
|
||||||
datas: [],
|
|
||||||
};
|
|
||||||
class PrintDataService extends Service {
|
class PrintDataService extends Service {
|
||||||
|
|
||||||
async getPrintData({ printType, orderId }) {
|
async getPrintData({ printType, orderId }) {
|
||||||
|
|||||||
@ -184,6 +184,172 @@ class ReceivingEntryMatchService extends Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入入库单与收货单的主表级绑定关系(仅主表绑定,不做明细分配)。
|
||||||
|
*
|
||||||
|
* 流程:
|
||||||
|
* 1. 校验入库单状态 = CREATED
|
||||||
|
* 2. 校验每个收货单:存在、同仓库、同货主、已审核、未取消
|
||||||
|
* 3. 逐条写入 EntryOrderReceiving.findOrCreate(主表绑定)
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求参数
|
||||||
|
* @param {number} data.entry_order_id 入库单 ID
|
||||||
|
* @param {number[]} data.receiving_ids 收货单 ID 列表
|
||||||
|
* @param {number} [data.creator_id] 操作人 ID(可选)
|
||||||
|
* @return {Promise<Object>} 绑定结果,含 bound、skipped、summary
|
||||||
|
*/
|
||||||
|
async bindEntryOrderReceiving(data = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const { entry_order_id: entryOrderId, receiving_ids: receivingIds, creator_id: creatorId } = data || {};
|
||||||
|
|
||||||
|
// 参数校验
|
||||||
|
if (!entryOrderId) {
|
||||||
|
throw new Error('entry_order_id 不能为空');
|
||||||
|
}
|
||||||
|
if (!Array.isArray(receivingIds) || receivingIds.length === 0) {
|
||||||
|
throw new Error('receiving_ids 不能为空且必须为数组');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 第1步:查询入库单,校验状态 ==========
|
||||||
|
const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId);
|
||||||
|
if (!entryOrder) {
|
||||||
|
throw new Error('入库单不存在');
|
||||||
|
}
|
||||||
|
// 只允许 CREATED 状态
|
||||||
|
if (entryOrder.order_status !== 'CREATED') {
|
||||||
|
throw new Error(`入库单状态不允许绑定,当前状态: ${entryOrder.order_status},仅 CREATED 状态可操作`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const warehouseId = entryOrder.warehouse_id;
|
||||||
|
|
||||||
|
// ========== 第2步:校验每个收货单的有效性 ==========
|
||||||
|
const validatedReceivings = [];
|
||||||
|
const failedValidations = [];
|
||||||
|
|
||||||
|
for (const receivingId of receivingIds) {
|
||||||
|
const receiving = await ctx.model.Receiving.findOne({
|
||||||
|
where: { id: receivingId, is_deleted: false },
|
||||||
|
attributes: [ 'id', 'receiving_number', 'warehouse_id', 'store_id', 'status', 'is_review' ],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!receiving) {
|
||||||
|
failedValidations.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
error_code: 'RECEIVING_NOT_FOUND',
|
||||||
|
message: '收货单不存在或已删除',
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (receiving.warehouse_id !== warehouseId) {
|
||||||
|
failedValidations.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
receiving_number: receiving.receiving_number,
|
||||||
|
error_code: 'WAREHOUSE_MISMATCH',
|
||||||
|
message: `收货单 ${receiving.receiving_number} 与入库单不属于同一仓库`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (receiving.store_id !== entryOrder.store_id) {
|
||||||
|
failedValidations.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
receiving_number: receiving.receiving_number,
|
||||||
|
error_code: 'OWNER_MISMATCH',
|
||||||
|
message: `收货单 ${receiving.receiving_number} 与入库单货主不一致`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (receiving.status === 'cancelled') {
|
||||||
|
failedValidations.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
receiving_number: receiving.receiving_number,
|
||||||
|
error_code: 'RECEIVING_CANCELLED',
|
||||||
|
message: `收货单 ${receiving.receiving_number} 已取消`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!receiving.is_review) {
|
||||||
|
failedValidations.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
receiving_number: receiving.receiving_number,
|
||||||
|
error_code: 'RECEIVING_NOT_REVIEWED',
|
||||||
|
message: `收货单 ${receiving.receiving_number} 未审核`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
validatedReceivings.push(receiving);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 有校验失败的收货单 → 直接返回失败
|
||||||
|
if (failedValidations.length > 0) {
|
||||||
|
ctx.logger.info(
|
||||||
|
`[ReceivingEntryMatch] bindEntryOrderReceiving 收货单校验失败 entryOrderId=${entryOrderId} failed=${failedValidations.length}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
bound: [],
|
||||||
|
skipped: [],
|
||||||
|
summary: { bound_count: 0, skipped_count: failedValidations.length },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 第3步:逐条写入主表绑定关系 ==========
|
||||||
|
const boundResults = [];
|
||||||
|
const skippedResults = [];
|
||||||
|
|
||||||
|
for (const receiving of validatedReceivings) {
|
||||||
|
try {
|
||||||
|
const [ , created ] = await ctx.model.EntryOrderReceiving.findOrCreate({
|
||||||
|
where: { entry_order_id: entryOrderId, receiving_id: receiving.id },
|
||||||
|
defaults: { entry_order_id: entryOrderId, receiving_id: receiving.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (created) {
|
||||||
|
ctx.logger.info(
|
||||||
|
`[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
ctx.logger.info(
|
||||||
|
`[ReceivingEntryMatch] 主表绑定已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receiving.id}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
boundResults.push({
|
||||||
|
receiving_id: receiving.id,
|
||||||
|
receiving_number: receiving.receiving_number,
|
||||||
|
created,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(
|
||||||
|
`[ReceivingEntryMatch] 主表绑定写入失败 entryOrderId=${entryOrderId} receivingId=${receiving.id}: ${error.message}`,
|
||||||
|
error.stack
|
||||||
|
);
|
||||||
|
skippedResults.push({
|
||||||
|
receiving_id: receiving.id,
|
||||||
|
receiving_number: receiving.receiving_number,
|
||||||
|
error_code: 'BINDING_WRITE_FAILED',
|
||||||
|
message: `写入绑定失败: ${error.message}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.logger.info(
|
||||||
|
`[ReceivingEntryMatch] bindEntryOrderReceiving 主表绑定完成 entryOrderId=${entryOrderId} bound=${boundResults.length} skipped=${skippedResults.length} creatorId=${creatorId || 'N/A'}`
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
bound: boundResults,
|
||||||
|
skipped: skippedResults,
|
||||||
|
summary: {
|
||||||
|
bound_count: boundResults.length,
|
||||||
|
skipped_count: skippedResults.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。
|
* 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。
|
||||||
*
|
*
|
||||||
@ -212,6 +378,7 @@ class ReceivingEntryMatchService extends Service {
|
|||||||
where: {
|
where: {
|
||||||
warehouse_id: warehouseId,
|
warehouse_id: warehouseId,
|
||||||
is_deleted: false,
|
is_deleted: false,
|
||||||
|
is_review: 1,
|
||||||
status: [ 'receiving', 'completed' ],
|
status: [ 'receiving', 'completed' ],
|
||||||
created_at: { [app.Sequelize.Op.gte]: threeDaysAgo },
|
created_at: { [app.Sequelize.Op.gte]: threeDaysAgo },
|
||||||
},
|
},
|
||||||
@ -288,7 +455,7 @@ class ReceivingEntryMatchService extends Service {
|
|||||||
// 如果缓存的收货单没有 details(可能为空),重新加载
|
// 如果缓存的收货单没有 details(可能为空),重新加载
|
||||||
if (!matched.details || matched.details.length === 0) {
|
if (!matched.details || matched.details.length === 0) {
|
||||||
const fullOrder = await ctx.model.Receiving.findOne({
|
const fullOrder = await ctx.model.Receiving.findOne({
|
||||||
where: { id: matched.id, warehouse_id: warehouseId },
|
where: { id: matched.id, warehouse_id: warehouseId, is_deleted: false, is_review: 1 },
|
||||||
attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ],
|
attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ],
|
||||||
include: [{
|
include: [{
|
||||||
model: ctx.model.ReceivingDetail,
|
model: ctx.model.ReceivingDetail,
|
||||||
@ -746,177 +913,247 @@ class ReceivingEntryMatchService extends Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量绑定入库单明细与收货单明细。
|
* 内部公共方法:在事务中提交单条入库明细-收货明细绑定。
|
||||||
* 依次校验入库单状态、商品匹配关系、可用数量,事务写入绑定并确保主级绑定存在。
|
* 包含 FOR UPDATE 行锁、可用量二次校验、绑定写入、主表绑定确保。
|
||||||
* @param {Object} data 请求参数
|
* 被 PDA 上架 addItem 流程调用,用于逐条写入明细绑定。
|
||||||
* @param {number} data.entry_order_id 入库单ID
|
*
|
||||||
* @param {Array} data.bindings 绑定列表
|
* @param {Object} params 绑定参数
|
||||||
* @param {number} data.bindings[].entry_item_id 入库单明细ID
|
* @param {number} params.entryItemId 入库单明细 ID
|
||||||
* @param {number} data.bindings[].receiving_detail_id 收货单明细ID
|
* @param {number} params.receivingDetailId 收货单明细 ID
|
||||||
* @param {number} data.bindings[].allocated_quantity 分配数量
|
* @param {number} params.qty 分配数量
|
||||||
* @return {Promise<Object>} { success: [...], failed: [...], success_count, failed_count }
|
* @param {number} params.expectedSpId 期望的 system_product_id(用于匹配校验,可选)
|
||||||
|
* @param {number} params.entryOrderId 入库单 ID(用于确保主表绑定存在)
|
||||||
|
* @param {Object} params.transaction Sequelize 事务对象
|
||||||
|
* @throws {Object} 结构化错误对象,包含 error_code、message、detail
|
||||||
|
* @return {Promise<void>}
|
||||||
*/
|
*/
|
||||||
|
async _commitBinding({ entryItemId, receivingDetailId, qty, expectedSpId, entryOrderId, transaction } = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
// 1. FOR UPDATE 锁收货明细行
|
||||||
|
const lockedDetail = await ctx.model.query(
|
||||||
|
`SELECT id, actual_quantity, receiving_id, system_product_id
|
||||||
|
FROM wms_receiving_detail
|
||||||
|
WHERE id = :rdId FOR UPDATE`,
|
||||||
|
{
|
||||||
|
replacements: { rdId: receivingDetailId },
|
||||||
|
type: ctx.model.QueryTypes.SELECT,
|
||||||
|
transaction,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!lockedDetail || lockedDetail.length === 0) {
|
||||||
|
throw {
|
||||||
|
error_code: 'RECEIVING_DETAIL_NOT_FOUND',
|
||||||
|
message: '收货明细不存在',
|
||||||
|
detail: { receiving_detail_id: receivingDetailId },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 校验收货明细与入库商品是否匹配(system_product_id)
|
||||||
|
if (expectedSpId !== undefined && lockedDetail[0].system_product_id !== expectedSpId) {
|
||||||
|
throw {
|
||||||
|
error_code: 'RECEIVING_DETAIL_MISMATCH',
|
||||||
|
message: '收货明细与入库商品不匹配',
|
||||||
|
detail: {
|
||||||
|
entry_item_id: entryItemId,
|
||||||
|
receiving_detail_id: receivingDetailId,
|
||||||
|
expected_sp_id: expectedSpId,
|
||||||
|
actual_sp_id: lockedDetail[0].system_product_id,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 查已 committed 的分配量
|
||||||
|
const allocatedSum = await ctx.model.query(
|
||||||
|
`SELECT COALESCE(SUM(allocated_quantity), 0) AS total
|
||||||
|
FROM wms_entry_receiving_binding
|
||||||
|
WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`,
|
||||||
|
{
|
||||||
|
replacements: { rdId: receivingDetailId },
|
||||||
|
type: ctx.model.QueryTypes.SELECT,
|
||||||
|
transaction,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0);
|
||||||
|
if (qty > availableQty) {
|
||||||
|
throw {
|
||||||
|
error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY',
|
||||||
|
message: '分配数量超出可用量',
|
||||||
|
detail: { available_quantity: availableQty, requested_quantity: qty },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 写入明细绑定
|
||||||
|
await ctx.model.EntryReceivingBinding.create({
|
||||||
|
entry_item_id: entryItemId,
|
||||||
|
receiving_detail_id: receivingDetailId,
|
||||||
|
allocated_quantity: qty,
|
||||||
|
status: 'committed',
|
||||||
|
creator_id: ctx.currentUser?.id || 0,
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
|
// 5. 确保主级绑定存在
|
||||||
|
await ctx.model.EntryOrderReceiving.findOrCreate({
|
||||||
|
where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id },
|
||||||
|
defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 批量绑定入库单明细与收货单明细。
|
* 解除入库单与收货单的绑定关系。
|
||||||
* 在事务中对每条绑定使用 FOR UPDATE 行锁防并发超卖,失败项返回结构化错误码。
|
*
|
||||||
|
* 逻辑:
|
||||||
|
* 1. 校验入库单存在,状态必须是 PENDING 或 CREATED(COMPLETED / CANCELLED 不允许解绑)
|
||||||
|
* 2. 逐个收货单:
|
||||||
|
* a. 查 wms_entry_order_receiving 主表绑定是否存在(只查 deleted_at IS NULL)
|
||||||
|
* b. 查 wms_entry_receiving_binding 明细绑定是否存在(status='committed' 且 deleted_at IS NULL)
|
||||||
|
* c. 无明细绑定 → 只软删除主表绑定
|
||||||
|
* d. 有明细绑定 → 事务中软删除明细绑定 + 软删除主表绑定
|
||||||
|
* 3. 不回退入库单状态(PENDING 解绑后仍是 PENDING)
|
||||||
*
|
*
|
||||||
* @param {Object} data 请求参数
|
* @param {Object} data 请求参数
|
||||||
* @param {number} data.entry_order_id 入库单 ID
|
* @param {number} data.entry_order_id 入库单 ID
|
||||||
* @param {Array<{entry_item_id: number, receiving_detail_id: number, allocated_quantity: number}>} data.bindings 绑定列表
|
* @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表
|
||||||
* @return {Promise<{success: Array, failed: Array, success_count: number, failed_count: number}>} 绑定结果
|
* @return {Promise<Object>} { success: Array, failed: Array, success_count: number, failed_count: number }
|
||||||
*/
|
*/
|
||||||
async bindReceivingDetails(data = {}) {
|
async unbindEntryOrderReceiving(data = {}) {
|
||||||
const { ctx } = this;
|
const { ctx } = this;
|
||||||
const { entry_order_id: entryOrderId, bindings = [] } = data || {};
|
const { entry_order_id: entryOrderId, receiving_ids: receivingIds } = data || {};
|
||||||
|
|
||||||
if (!entryOrderId || !Array.isArray(bindings) || bindings.length === 0) {
|
// 参数校验
|
||||||
throw new Error('参数不完整');
|
if (!entryOrderId) {
|
||||||
|
throw new Error('entry_order_id 不能为空');
|
||||||
|
}
|
||||||
|
if (!Array.isArray(receivingIds) || receivingIds.length === 0) {
|
||||||
|
throw new Error('receiving_ids 不能为空且必须为数组');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. 查询入库单,校验状态(必须是 PENDING 或 CREATED)
|
// ---------- 第1步:校验入库单存在且状态允许解绑 ----------
|
||||||
const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId);
|
const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId);
|
||||||
if (!entryOrder || ![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) {
|
if (!entryOrder) {
|
||||||
// 入库单状态不对 → 全部 bindings 标记为 ENTRY_ORDER_STATUS_INVALID
|
return {
|
||||||
const allFailed = bindings.map(b => ({
|
success: [],
|
||||||
entry_item_id: b.entry_item_id,
|
failed: receivingIds.map(rid => ({
|
||||||
receiving_detail_id: b.receiving_detail_id,
|
receiving_id: rid,
|
||||||
allocated_quantity: b.allocated_quantity,
|
error_code: 'ENTRY_ORDER_NOT_FOUND',
|
||||||
error_code: 'ENTRY_ORDER_STATUS_INVALID',
|
message: '入库单不存在',
|
||||||
message: '入库单状态不允许绑定',
|
})),
|
||||||
detail: { order_status: entryOrder ? entryOrder.order_status : null },
|
success_count: 0,
|
||||||
}));
|
failed_count: receivingIds.length,
|
||||||
return { success: [], failed: allFailed, success_count: 0, failed_count: allFailed.length };
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 只允许 PENDING 或 CREATED 状态解绑(COMPLETED / CANCELLED 不允许)
|
||||||
|
if (![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) {
|
||||||
|
return {
|
||||||
|
success: [],
|
||||||
|
failed: receivingIds.map(rid => ({
|
||||||
|
receiving_id: rid,
|
||||||
|
error_code: 'ENTRY_ORDER_STATUS_INVALID',
|
||||||
|
message: `入库单状态不允许解绑,当前状态: ${entryOrder.order_status}`,
|
||||||
|
})),
|
||||||
|
success_count: 0,
|
||||||
|
failed_count: receivingIds.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 第2步:逐个收货单处理解绑 ----------
|
||||||
const success = [];
|
const success = [];
|
||||||
const failed = [];
|
const failed = [];
|
||||||
|
|
||||||
for (const binding of bindings) {
|
for (const receivingId of receivingIds) {
|
||||||
const { entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty } = binding;
|
|
||||||
try {
|
try {
|
||||||
// 2. 查询 entry_item 和对应的 stock_id
|
// 2a. 查主表绑定是否存在
|
||||||
const entryItem = await ctx.model.EntryItems.findByPk(entryItemId);
|
const mainBinding = await ctx.model.EntryOrderReceiving.findOne({
|
||||||
if (!entryItem) {
|
where: {
|
||||||
throw {
|
entry_order_id: entryOrderId,
|
||||||
error_code: 'ENTRY_ITEM_NOT_FOUND',
|
receiving_id: receivingId,
|
||||||
message: '入库明细不存在',
|
deleted_at: null,
|
||||||
detail: { entry_item_id: entryItemId },
|
},
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 通过 stock_id → system_product_id 校验收货单明细匹配
|
|
||||||
const sw = await ctx.model.StockWarehouse.findOne({
|
|
||||||
where: { id: entryItem.stock_id, warehouse_id: entryOrder.warehouse_id },
|
|
||||||
attributes: [ 'system_product_id' ],
|
|
||||||
raw: true,
|
|
||||||
});
|
|
||||||
if (!sw || !sw.system_product_id) {
|
|
||||||
throw {
|
|
||||||
error_code: 'STOCK_NOT_FOUND',
|
|
||||||
message: '商品不存在',
|
|
||||||
detail: { stock_id: entryItem.stock_id },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. 事务:FOR UPDATE 锁行 → 查已分配量 → 写入绑定
|
|
||||||
await ctx.model.transaction(async t => {
|
|
||||||
// 4a. 先锁收货明细行
|
|
||||||
const lockedDetail = await ctx.model.query(
|
|
||||||
`SELECT id, actual_quantity, receiving_id, system_product_id
|
|
||||||
FROM wms_receiving_detail
|
|
||||||
WHERE id = :rdId FOR UPDATE`,
|
|
||||||
{
|
|
||||||
replacements: { rdId: receivingDetailId },
|
|
||||||
type: ctx.model.QueryTypes.SELECT,
|
|
||||||
transaction: t,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
if (!lockedDetail || lockedDetail.length === 0) {
|
|
||||||
throw {
|
|
||||||
error_code: 'RECEIVING_DETAIL_NOT_FOUND',
|
|
||||||
message: '收货明细不存在',
|
|
||||||
detail: { receiving_detail_id: receivingDetailId },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4b. 校验收货明细与入库商品是否匹配(system_product_id)
|
|
||||||
if (lockedDetail[0].system_product_id !== sw.system_product_id) {
|
|
||||||
throw {
|
|
||||||
error_code: 'RECEIVING_DETAIL_MISMATCH',
|
|
||||||
message: '收货明细与入库商品不匹配',
|
|
||||||
detail: {
|
|
||||||
entry_item_id: entryItemId,
|
|
||||||
receiving_detail_id: receivingDetailId,
|
|
||||||
expected_sp_id: sw.system_product_id,
|
|
||||||
actual_sp_id: lockedDetail[0].system_product_id,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4c. 查已 committed 的分配量
|
|
||||||
const allocatedSum = await ctx.model.query(
|
|
||||||
`SELECT COALESCE(SUM(allocated_quantity), 0) AS total
|
|
||||||
FROM wms_entry_receiving_binding
|
|
||||||
WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`,
|
|
||||||
{
|
|
||||||
replacements: { rdId: receivingDetailId },
|
|
||||||
type: ctx.model.QueryTypes.SELECT,
|
|
||||||
transaction: t,
|
|
||||||
}
|
|
||||||
);
|
|
||||||
const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0);
|
|
||||||
if (qty > availableQty) {
|
|
||||||
throw {
|
|
||||||
error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY',
|
|
||||||
message: '分配数量超出可用量',
|
|
||||||
detail: { available_quantity: availableQty, requested_quantity: qty },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4d. 写入绑定
|
|
||||||
await ctx.model.EntryReceivingBinding.create({
|
|
||||||
entry_item_id: entryItemId,
|
|
||||||
receiving_detail_id: receivingDetailId,
|
|
||||||
allocated_quantity: qty,
|
|
||||||
status: 'committed',
|
|
||||||
creator_id: ctx.currentUser?.id || 0,
|
|
||||||
}, { transaction: t });
|
|
||||||
|
|
||||||
// 确保主级绑定存在
|
|
||||||
await ctx.model.EntryOrderReceiving.findOrCreate({
|
|
||||||
where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id },
|
|
||||||
defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id },
|
|
||||||
transaction: t,
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
success.push({ entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty });
|
if (!mainBinding) {
|
||||||
} catch (err) {
|
|
||||||
// 结构化错误对象或普通 Error 统一转为 failed 项
|
|
||||||
if (err.error_code) {
|
|
||||||
failed.push({
|
failed.push({
|
||||||
entry_item_id: entryItemId,
|
receiving_id: receivingId,
|
||||||
receiving_detail_id: receivingDetailId,
|
error_code: 'BINDING_NOT_FOUND',
|
||||||
allocated_quantity: qty,
|
message: '主表绑定不存在',
|
||||||
error_code: err.error_code,
|
});
|
||||||
message: err.message,
|
continue;
|
||||||
detail: err.detail || {},
|
}
|
||||||
|
|
||||||
|
// 2b. 查明细绑定是否存在
|
||||||
|
const detailBindings = await ctx.model.EntryReceivingBinding.findAll({
|
||||||
|
where: {
|
||||||
|
status: 'committed',
|
||||||
|
deleted_at: null,
|
||||||
|
},
|
||||||
|
include: [{
|
||||||
|
model: ctx.model.ReceivingDetail,
|
||||||
|
as: 'receivingDetail',
|
||||||
|
required: true,
|
||||||
|
attributes: [],
|
||||||
|
where: { receiving_id: receivingId },
|
||||||
|
}],
|
||||||
|
attributes: [ 'id', 'receiving_detail_id', 'allocated_quantity' ],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (detailBindings.length === 0) {
|
||||||
|
// 2c. 无明细绑定 → 只软删除主表绑定
|
||||||
|
await mainBinding.destroy();
|
||||||
|
ctx.logger.info(
|
||||||
|
`[ReceivingEntryMatch] 解绑成功(仅主表) entryOrderId=${entryOrderId} receivingId=${receivingId}`
|
||||||
|
);
|
||||||
|
success.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
released_detail_count: 0,
|
||||||
|
message: '已解除主表绑定(无明细绑定)',
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
failed.push({
|
// 2d. 有明细绑定 → 事务:软删除明细绑定 + 软删除主表绑定
|
||||||
entry_item_id: entryItemId,
|
const detailIds = detailBindings.map(d => d.receiving_detail_id);
|
||||||
receiving_detail_id: receivingDetailId,
|
|
||||||
allocated_quantity: qty,
|
await ctx.model.transaction(async t => {
|
||||||
error_code: 'INTERNAL_ERROR',
|
// 软删除所有明细绑定
|
||||||
message: err.message || '未知错误',
|
for (const binding of detailBindings) {
|
||||||
detail: {},
|
await binding.destroy({ transaction: t });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 软删除主表绑定
|
||||||
|
await mainBinding.destroy({ transaction: t });
|
||||||
|
});
|
||||||
|
|
||||||
|
ctx.logger.info(
|
||||||
|
`[ReceivingEntryMatch] 解绑成功(含明细) entryOrderId=${entryOrderId} ` +
|
||||||
|
`receivingId=${receivingId} detailCount=${detailBindings.length} ` +
|
||||||
|
`detailIds=[${detailIds.join(',')}]`
|
||||||
|
);
|
||||||
|
|
||||||
|
success.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
released_detail_ids: detailIds,
|
||||||
|
released_detail_count: detailBindings.length,
|
||||||
|
message: '已解除主表及明细绑定',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(
|
||||||
|
`[ReceivingEntryMatch] 解绑异常 entryOrderId=${entryOrderId} ` +
|
||||||
|
`receivingId=${receivingId}: ${error.message}`,
|
||||||
|
error.stack
|
||||||
|
);
|
||||||
|
failed.push({
|
||||||
|
receiving_id: receivingId,
|
||||||
|
error_code: 'UNBIND_ERROR',
|
||||||
|
message: `解绑过程异常: ${error.message}`,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success, failed, success_count: success.length, failed_count: failed.length };
|
return { success, failed, success_count: success.length, failed_count: failed.length };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = ReceivingEntryMatchService;
|
module.exports = ReceivingEntryMatchService;
|
||||||
|
|||||||
@ -675,10 +675,9 @@ class ShopsService extends Service {
|
|||||||
* @return {Promise<Object>} 会话信息
|
* @return {Promise<Object>} 会话信息
|
||||||
*/
|
*/
|
||||||
async getAuthorizeSessionKey(data = {}) {
|
async getAuthorizeSessionKey(data = {}) {
|
||||||
const { ctx, service } = this;
|
const { ctx } = this;
|
||||||
const authUrl = 'http://61.160.223.183:3012/api';
|
const authUrl = 'http://61.160.223.183:3012/api';
|
||||||
|
|
||||||
const warehouseId = this.getCurrentWarehouseId();
|
|
||||||
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
|
const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId);
|
||||||
const callbackUrl = this.normalizeText(
|
const callbackUrl = this.normalizeText(
|
||||||
data.callbackurl !== undefined ? data.callbackurl : data.callback_url,
|
data.callbackurl !== undefined ? data.callbackurl : data.callback_url,
|
||||||
|
|||||||
@ -31,7 +31,7 @@ class StockWarehouseService extends Service {
|
|||||||
* @param {Object} [options={}] 选项
|
* @param {Object} [options={}] 选项
|
||||||
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
|
* @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id)
|
||||||
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
|
* @param {number} [options.cacheTTL=300] 缓存过期时间(秒)
|
||||||
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, is_images: string, store_id: number, packing_requirements: string, stock_unit: string, image_url: string, barcodes: Array<{id: number, barcode: string}>}>>} 商品详情列表
|
* @return {Promise<Array<{id: number, item_code: string, item_name: string, sku_property: string, quantity: number, locked_quantity: number, is_batch_mgmt: string, is_shelf_life_mgmt: string, is_images: string, store_id: number, packing_requirements: string, stock_unit: string, image_url: string[], barcodes: Array<{id: number, barcode: string}>}>>} 商品详情列表
|
||||||
*/
|
*/
|
||||||
async getStockDetails(stockIds, options = {}) {
|
async getStockDetails(stockIds, options = {}) {
|
||||||
const { ctx, app } = this;
|
const { ctx, app } = this;
|
||||||
@ -99,6 +99,7 @@ class StockWarehouseService extends Service {
|
|||||||
attributes: [ 'file_url' ],
|
attributes: [ 'file_url' ],
|
||||||
required: false,
|
required: false,
|
||||||
}],
|
}],
|
||||||
|
order: [[ 'display_order', 'ASC' ]],
|
||||||
raw: true,
|
raw: true,
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
@ -121,8 +122,11 @@ class StockWarehouseService extends Service {
|
|||||||
for (const row of imageRows) {
|
for (const row of imageRows) {
|
||||||
const sid = Number(row.business_id);
|
const sid = Number(row.business_id);
|
||||||
if (!imageUrlMap.has(sid)) {
|
if (!imageUrlMap.has(sid)) {
|
||||||
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
|
imageUrlMap.set(sid, []);
|
||||||
imageUrlMap.set(sid, url);
|
}
|
||||||
|
const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || '';
|
||||||
|
if (url) {
|
||||||
|
imageUrlMap.get(sid).push(url);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -141,7 +145,7 @@ class StockWarehouseService extends Service {
|
|||||||
store_id: row.store_id != null ? Number(row.store_id) : 0,
|
store_id: row.store_id != null ? Number(row.store_id) : 0,
|
||||||
packing_requirements: row.packing_requirements || '',
|
packing_requirements: row.packing_requirements || '',
|
||||||
stock_unit: row.stock_unit || '',
|
stock_unit: row.stock_unit || '',
|
||||||
image_url: imageUrlMap.get(row.id) || '',
|
image_url: imageUrlMap.get(row.id) || [],
|
||||||
barcodes: barcodeMap.get(row.id) || [],
|
barcodes: barcodeMap.get(row.id) || [],
|
||||||
};
|
};
|
||||||
dbResults.set(row.id, detail);
|
dbResults.set(row.id, detail);
|
||||||
@ -176,6 +180,13 @@ class StockWarehouseService extends Service {
|
|||||||
const cached = cacheHits.get(stockId);
|
const cached = cacheHits.get(stockId);
|
||||||
// 空标记(防穿透缓存)跳过
|
// 空标记(防穿透缓存)跳过
|
||||||
if (cached !== null && cached !== undefined) {
|
if (cached !== null && cached !== undefined) {
|
||||||
|
// 兼容旧缓存格式:image_url 可能是字符串,统一转为数组
|
||||||
|
if (cached && typeof cached.image_url === 'string') {
|
||||||
|
cached.image_url = cached.image_url ? [ cached.image_url ] : [];
|
||||||
|
}
|
||||||
|
if (cached && !Array.isArray(cached.image_url)) {
|
||||||
|
cached.image_url = [];
|
||||||
|
}
|
||||||
result.push(cached);
|
result.push(cached);
|
||||||
}
|
}
|
||||||
} else if (dbResults.has(stockId)) {
|
} else if (dbResults.has(stockId)) {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -171,9 +171,12 @@ async function loadStockAttachments(ctx, stockIds = []) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 提取图片
|
// 提取图片(兼容数组/字符串格式)
|
||||||
if (detail.image_url) {
|
const imageUrls = Array.isArray(detail.image_url)
|
||||||
imagesByStockId.set(stockId, [ String(detail.image_url).trim() ]);
|
? detail.image_url.map(u => String(u || '').trim()).filter(Boolean)
|
||||||
|
: (detail.image_url ? [ String(detail.image_url).trim() ] : []);
|
||||||
|
if (imageUrls.length > 0) {
|
||||||
|
imagesByStockId.set(stockId, imageUrls);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -1394,6 +1397,334 @@ class InventoryService extends Service {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 收货单快捷入库:判断货主配置是否允许收货单快捷入库,不允许直接返回失败;
|
||||||
|
* 允许的话使用收货单的明细创建入库单,相同 stock_id 的合并为一条,汇集总数。
|
||||||
|
* 在 wms_entry_order_receiving 表建立绑定关系,入库单自动审批到 PENDING 状态。
|
||||||
|
*
|
||||||
|
* @param {Object} data 请求体
|
||||||
|
* @param {number} data.receiving_id 收货单ID(必填)
|
||||||
|
* @return {Promise<Object>} code/data/message 结构,data 中包含创建的入库单信息
|
||||||
|
*/
|
||||||
|
async quickPutaway(data = {}) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const receivingId = Number(data.receiving_id || 0);
|
||||||
|
|
||||||
|
// ────────── 1. 参数校验 ──────────
|
||||||
|
if (!receivingId) {
|
||||||
|
return { code: 400, message: 'receiving_id 必填', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const warehouseId = ctx.user.store_id;
|
||||||
|
if (!warehouseId) {
|
||||||
|
return { code: 400, message: '无法获取当前仓库信息', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 2. 加载收货单主表及明细 ──────────
|
||||||
|
const receiving = await ctx.model.Receiving.findOne({
|
||||||
|
where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!receiving) {
|
||||||
|
return { code: 404, message: `收货单不存在或无权访问: receiving_id=${receivingId}`, data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (receiving.status === 'cancelled') {
|
||||||
|
return { code: 400, message: '收货单已作废,不允许快捷入库', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (receiving.status !== 'completed') {
|
||||||
|
return { code: 400, message: `收货单状态不允许快捷入库,当前状态: ${receiving.status},仅 completed 状态可操作`, data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!receiving.is_review) {
|
||||||
|
return { code: 400, message: '收货单未审核,不允许快捷入库', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeId = receiving.store_id;
|
||||||
|
|
||||||
|
// ────────── 3. 检查货主配置:是否允许收货单快捷入库 ──────────
|
||||||
|
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
|
||||||
|
where: { store_id: storeId, warehouse_id: warehouseId, use_status: 1 },
|
||||||
|
attributes: [ 'id', 'policy_config' ],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!storeWarehouse) {
|
||||||
|
return { code: 400, message: '货主仓库签约关系不存在', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const policyConfig = storeWarehouse.policy_config || {};
|
||||||
|
const allowQuickPutaway = Number(policyConfig.allow_receiving_quick_putaway) === 1;
|
||||||
|
|
||||||
|
if (!allowQuickPutaway) {
|
||||||
|
return { code: 400, message: '货主未开启收货单快捷入库功能,请联系管理员开启', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 4. 加载收货单明细 ──────────
|
||||||
|
const receivingDetails = await ctx.model.ReceivingDetail.findAll({
|
||||||
|
where: { receiving_id: receivingId },
|
||||||
|
attributes: [
|
||||||
|
'id', 'system_product_id', 'actual_quantity', 'product_name',
|
||||||
|
'batch_number', 'production_date', 'expiry_date',
|
||||||
|
'storage_status', 'stored_quantity',
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!receivingDetails || receivingDetails.length === 0) {
|
||||||
|
return { code: 400, message: '收货单无明细,无法创建入库单', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 5. 按 stock_id(system_product_id)分组,合并数量 ──────────
|
||||||
|
/** @type {Map<number, {system_product_id: number, total_quantity: number, product_name: string, batch_number: string, production_date: string|null, expiry_date: string|null, detail_ids: number[]}>} */
|
||||||
|
const groupedMap = new Map();
|
||||||
|
|
||||||
|
for (const detail of receivingDetails) {
|
||||||
|
const stockId = Number(detail.system_product_id);
|
||||||
|
if (!stockId) {
|
||||||
|
// 跳过未匹配系统商品的明细
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const qty = Number(detail.actual_quantity) || 0;
|
||||||
|
if (qty <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = groupedMap.get(stockId);
|
||||||
|
if (existing) {
|
||||||
|
existing.total_quantity += qty;
|
||||||
|
existing.detail_ids.push(detail.id);
|
||||||
|
} else {
|
||||||
|
groupedMap.set(stockId, {
|
||||||
|
system_product_id: stockId,
|
||||||
|
total_quantity: qty,
|
||||||
|
product_name: detail.product_name || '',
|
||||||
|
batch_number: detail.batch_number || '',
|
||||||
|
production_date: detail.production_date || null,
|
||||||
|
expiry_date: detail.expiry_date || null,
|
||||||
|
detail_ids: [ detail.id ],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (groupedMap.size === 0) {
|
||||||
|
return { code: 400, message: '收货单中所有明细均未关联系统商品,无法创建入库单', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const groupedItems = Array.from(groupedMap.values());
|
||||||
|
|
||||||
|
// ────────── 6. 批量查询 stock_warehouse 获取 stock_id 对应的商品信息 ──────────
|
||||||
|
const stockIds = groupedItems.map(item => item.system_product_id);
|
||||||
|
const stockRows = await ctx.model.StockWarehouse.findAll({
|
||||||
|
where: { id: { [app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId },
|
||||||
|
attributes: [ 'id', 'item_code', 'item_name', 'stock_unit', 'is_valid' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
const stockMap = new Map();
|
||||||
|
for (const row of stockRows) {
|
||||||
|
stockMap.set(Number(row.id), row);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验所有 stock_id 是否存在且有效
|
||||||
|
const missingStockIds = stockIds.filter(sid => !stockMap.has(sid));
|
||||||
|
if (missingStockIds.length > 0) {
|
||||||
|
return {
|
||||||
|
code: 400,
|
||||||
|
message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`,
|
||||||
|
data: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 7. 开事务,创建入库单及明细 ──────────
|
||||||
|
const transaction = await ctx.model.transaction();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 获取货主和仓库名称快照
|
||||||
|
const storeData = await ctx.service.systems.store.getStoreName(storeId);
|
||||||
|
const storeName = (storeData.code === 200 && storeData.data) ? storeData.data.company_name : '';
|
||||||
|
const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId);
|
||||||
|
const warehouseName = (warehouseData.code === 200 && warehouseData.data) ? warehouseData.data.company_name : '';
|
||||||
|
|
||||||
|
// 生成入库单号
|
||||||
|
const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction);
|
||||||
|
|
||||||
|
// 创建入库单主表(状态直接设为 PENDING)
|
||||||
|
const entryOrder = await ctx.model.EntryOrder.create({
|
||||||
|
entry_order_code: entryOrderCode,
|
||||||
|
order_type: 'SCRK',
|
||||||
|
total_order_lines: groupedItems.length,
|
||||||
|
order_create_time: new Date(),
|
||||||
|
source_type: 'WMS',
|
||||||
|
order_status: 'PENDING',
|
||||||
|
sync_status: 'PENDING',
|
||||||
|
is_enabled: 1,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
store_name: storeName,
|
||||||
|
warehouse_name: warehouseName,
|
||||||
|
remark: `收货单${receiving.receiving_number}快捷入库`,
|
||||||
|
expense_record: 0,
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
|
const entryOrderId = entryOrder.id;
|
||||||
|
|
||||||
|
// 创建入库单明细(按合并后的分组)
|
||||||
|
for (let i = 0; i < groupedItems.length; i++) {
|
||||||
|
const group = groupedItems[i];
|
||||||
|
const stockInfo = stockMap.get(group.system_product_id);
|
||||||
|
|
||||||
|
await ctx.model.EntryItems.create({
|
||||||
|
order_id: entryOrderId,
|
||||||
|
out_biz_code: '',
|
||||||
|
order_line_no: i + 1,
|
||||||
|
owner_code: '',
|
||||||
|
item_code: stockInfo ? stockInfo.item_code : '',
|
||||||
|
item_id: 0,
|
||||||
|
count: group.total_quantity,
|
||||||
|
inventory_type: 'ZP',
|
||||||
|
stock_id: group.system_product_id,
|
||||||
|
received_quantity: 0,
|
||||||
|
confirm_quantity: 0,
|
||||||
|
}, { transaction });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 8. 写入 wms_entry_order_receiving 绑定关系 ──────────
|
||||||
|
await ctx.model.EntryOrderReceiving.create({
|
||||||
|
entry_order_id: entryOrderId,
|
||||||
|
receiving_id: receivingId,
|
||||||
|
}, { transaction });
|
||||||
|
|
||||||
|
// ────────── 9. 更新收货单主表 storage_status ──────────
|
||||||
|
// 快捷入库后收货单进入"等待入库"状态(后续可通过 matchPutaway 补全)
|
||||||
|
const [ affectedRows ] = await ctx.model.Receiving.update({
|
||||||
|
storage_status: 'waiting',
|
||||||
|
updated_at: new Date(),
|
||||||
|
}, {
|
||||||
|
where: { id: receivingId, storage_status: 'none' },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (affectedRows === 0) {
|
||||||
|
await transaction.rollback();
|
||||||
|
return { code: 400, message: '收货单入库状态已变更,可能已被其他操作处理,禁止重复快捷入库', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 10. 更新收货单明细的 storage_status 为 waiting,stored_quantity 为对应用量 ──────────
|
||||||
|
for (const group of groupedItems) {
|
||||||
|
for (const detailId of group.detail_ids) {
|
||||||
|
const detailRow = receivingDetails.find(d => d.id === detailId);
|
||||||
|
if (!detailRow) continue;
|
||||||
|
|
||||||
|
// 该明细的总量和已入库量
|
||||||
|
const detailTotalQty = Number(detailRow.actual_quantity) || 0;
|
||||||
|
// 该明细在本次合并中的贡献量按比例计入(简化:按该明细数量在合并总量中的占比)
|
||||||
|
const detailRatio = group.total_quantity > 0 ? detailTotalQty / group.total_quantity : 0;
|
||||||
|
const thisStoredQty = Math.round(detailRatio * group.total_quantity);
|
||||||
|
|
||||||
|
const newStoredQty = Math.min(detailTotalQty, (Number(detailRow.stored_quantity) || 0) + thisStoredQty);
|
||||||
|
// 明细实际数量表示的是该明细的收货量,合并后该 SKU 的明细可能有多条
|
||||||
|
// 简化:如果该明细被完全用完则设为 all,否则 waiting(等待手工上架)
|
||||||
|
const newStorageStatus = newStoredQty >= detailTotalQty ? 'all' : 'waiting';
|
||||||
|
|
||||||
|
await ctx.model.ReceivingDetail.update({
|
||||||
|
storage_status: newStorageStatus,
|
||||||
|
stored_quantity: newStoredQty,
|
||||||
|
updated_at: new Date(),
|
||||||
|
}, {
|
||||||
|
where: { id: detailId },
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 11. 操作日志 ──────────
|
||||||
|
try {
|
||||||
|
await ctx.service.systems.operationLog.createOperationLog({
|
||||||
|
businessType: 'entry_order',
|
||||||
|
businessId: entryOrderId,
|
||||||
|
operationCode: 'ENTRY_ORDER_QUICK_PUTAWAY',
|
||||||
|
operator: {
|
||||||
|
id: ctx.user?.employees_id || ctx.user?.id,
|
||||||
|
name: ctx.user?.employees_name || '',
|
||||||
|
},
|
||||||
|
extras: {
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
receivingId,
|
||||||
|
entryOrderCode,
|
||||||
|
receivingNumber: receiving.receiving_number,
|
||||||
|
totalLines: groupedItems.length,
|
||||||
|
},
|
||||||
|
transaction,
|
||||||
|
});
|
||||||
|
} catch (logErr) {
|
||||||
|
ctx.logger.warn('[inventory.quickPutaway] 写入操作日志失败,不影响业务', logErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ────────── 12. 提交事务 ──────────
|
||||||
|
await transaction.commit();
|
||||||
|
|
||||||
|
ctx.logger.info(`[inventory.quickPutaway] 快捷入库完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${groupedItems.length}`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
message: '快捷入库成功',
|
||||||
|
data: {
|
||||||
|
entry_order_id: entryOrderId,
|
||||||
|
entry_order_code: entryOrderCode,
|
||||||
|
order_status: 'PENDING',
|
||||||
|
receiving_id: receivingId,
|
||||||
|
total_lines: groupedItems.length,
|
||||||
|
total_quantity: groupedItems.reduce((sum, g) => sum + g.total_quantity, 0),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
await transaction.rollback();
|
||||||
|
ctx.logger.error(`[inventory.quickPutaway] 快捷入库异常 receivingId=${receivingId}: ${error.message}`, error.stack);
|
||||||
|
return { code: 500, message: `系统异常: ${error.message}`, data: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成入库单号。
|
||||||
|
* 格式:SCRK + 年月日 + 4位流水号
|
||||||
|
*
|
||||||
|
* @param {number} warehouseId 仓库ID
|
||||||
|
* @param {number} storeId 货主ID
|
||||||
|
* @param {Object} transaction 数据库事务
|
||||||
|
* @return {Promise<string>} 生成的入库单号
|
||||||
|
*/
|
||||||
|
async _generateEntryOrderCode(warehouseId, storeId, transaction) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const now = new Date();
|
||||||
|
const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
|
||||||
|
const prefix = `SCRK${dateStr}`;
|
||||||
|
|
||||||
|
// 查询当天该仓库+货主下已有的最大入库单号
|
||||||
|
const lastOrder = await ctx.model.EntryOrder.findOne({
|
||||||
|
where: {
|
||||||
|
entry_order_code: { [app.Sequelize.Op.like]: `${prefix}%` },
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
store_id: storeId,
|
||||||
|
},
|
||||||
|
order: [[ 'entry_order_code', 'DESC' ]],
|
||||||
|
attributes: [ 'entry_order_code' ],
|
||||||
|
transaction,
|
||||||
|
raw: true,
|
||||||
|
paranoid: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
let seq = 1;
|
||||||
|
if (lastOrder && lastOrder.entry_order_code) {
|
||||||
|
const seqPart = lastOrder.entry_order_code.slice(prefix.length);
|
||||||
|
const seqNum = parseInt(seqPart, 10);
|
||||||
|
if (!Number.isNaN(seqNum)) {
|
||||||
|
seq = seqNum + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${prefix}${String(seq).padStart(4, '0')}`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = InventoryService;
|
module.exports = InventoryService;
|
||||||
|
|||||||
@ -35,9 +35,12 @@ class ReceivingService extends Service {
|
|||||||
* @param {number} [pageParams.page=1] 页码
|
* @param {number} [pageParams.page=1] 页码
|
||||||
* @param {number} [pageParams.pageSize=20] 每页条数
|
* @param {number} [pageParams.pageSize=20] 每页条数
|
||||||
* @param {Object} [sortParams] 排序参数
|
* @param {Object} [sortParams] 排序参数
|
||||||
|
* @param {Object} [options] 额外选项
|
||||||
|
* @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单
|
||||||
|
* @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单
|
||||||
* @return {Promise<Object>} 列表、分页与汇总信息
|
* @return {Promise<Object>} 列表、分页与汇总信息
|
||||||
*/
|
*/
|
||||||
async getReceivingList(where, pageParams = {}, sortParams = {}) {
|
async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) {
|
||||||
const {
|
const {
|
||||||
ctx,
|
ctx,
|
||||||
app,
|
app,
|
||||||
@ -58,6 +61,7 @@ class ReceivingService extends Service {
|
|||||||
sortField = 'id',
|
sortField = 'id',
|
||||||
sortOrder = 'DESC',
|
sortOrder = 'DESC',
|
||||||
} = sortParams;
|
} = sortParams;
|
||||||
|
const { filterDepleted = false, entry_order_id: entryOrderId } = options;
|
||||||
|
|
||||||
const queryOptions = {
|
const queryOptions = {
|
||||||
where: {
|
where: {
|
||||||
@ -175,14 +179,147 @@ class ReceivingService extends Service {
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// 可选过滤:排除无可再用量的收货单
|
||||||
|
let filteredReceivingIds = null;
|
||||||
|
if (filterDepleted) {
|
||||||
|
const candidateRows = await ctx.model.Receiving.findAll({
|
||||||
|
attributes: [ 'id' ],
|
||||||
|
where: queryOptions.where,
|
||||||
|
include,
|
||||||
|
distinct: true,
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
const candidateIds = candidateRows.map(r => r.id);
|
||||||
|
|
||||||
|
if (candidateIds.length > 0) {
|
||||||
|
// 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组)
|
||||||
|
const detailSums = await ctx.model.ReceivingDetail.findAll({
|
||||||
|
attributes: [
|
||||||
|
'receiving_id',
|
||||||
|
[ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ],
|
||||||
|
],
|
||||||
|
where: { receiving_id: { [Op.in]: candidateIds } },
|
||||||
|
group: [ 'receiving_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
const totalActualMap = {};
|
||||||
|
for (const row of detailSums) {
|
||||||
|
totalActualMap[row.receiving_id] = Number(row.total_actual) || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组)
|
||||||
|
const detailIds = detailSums.length > 0
|
||||||
|
? (await ctx.model.ReceivingDetail.findAll({
|
||||||
|
attributes: [ 'id' ],
|
||||||
|
where: { receiving_id: { [Op.in]: candidateIds } },
|
||||||
|
raw: true,
|
||||||
|
})).map(r => r.id)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const committedByDetailId = {};
|
||||||
|
if (detailIds.length > 0) {
|
||||||
|
const bindingRows = await ctx.model.EntryReceivingBinding.findAll({
|
||||||
|
attributes: [
|
||||||
|
'receiving_detail_id',
|
||||||
|
[ Sequelize.fn('SUM', Sequelize.col('allocated_quantity')), 'committed_sum' ],
|
||||||
|
],
|
||||||
|
where: {
|
||||||
|
receiving_detail_id: { [Op.in]: detailIds },
|
||||||
|
status: 'committed',
|
||||||
|
},
|
||||||
|
group: [ 'receiving_detail_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
for (const row of bindingRows) {
|
||||||
|
committedByDetailId[row.receiving_detail_id] = Number(row.committed_sum) || 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed)
|
||||||
|
const idToDetailIdsMap = {};
|
||||||
|
if (detailIds.length > 0) {
|
||||||
|
const detailIdRows = await ctx.model.ReceivingDetail.findAll({
|
||||||
|
attributes: [ 'id', 'receiving_id' ],
|
||||||
|
where: { id: { [Op.in]: detailIds } },
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
for (const d of detailIdRows) {
|
||||||
|
if (!idToDetailIdsMap[d.receiving_id]) idToDetailIdsMap[d.receiving_id] = [];
|
||||||
|
idToDetailIdsMap[d.receiving_id].push(d.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const remainingByReceivingId = {};
|
||||||
|
for (const receivingId of candidateIds) {
|
||||||
|
const totalActual = totalActualMap[receivingId] || 0;
|
||||||
|
const detailIdList = idToDetailIdsMap[receivingId] || [];
|
||||||
|
const totalCommitted = detailIdList.reduce((sum, did) => sum + (committedByDetailId[did] || 0), 0);
|
||||||
|
remainingByReceivingId[receivingId] = totalActual - totalCommitted;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 过滤:只保留剩余可用量 > 0 的收货单
|
||||||
|
filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0);
|
||||||
|
} else {
|
||||||
|
filteredReceivingIds = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单)
|
||||||
|
let intersectionFilteredIds = null;
|
||||||
|
if (entryOrderId) {
|
||||||
|
// 1. 查该入库单的所有 entry_items → stock_id 集合
|
||||||
|
const entryItemRows = await ctx.model.EntryItems.findAll({
|
||||||
|
where: { order_id: entryOrderId },
|
||||||
|
attributes: [ 'stock_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean));
|
||||||
|
|
||||||
|
if (entrySpIdSet.size === 0) {
|
||||||
|
// 入库单无明细 → 不返回任何收货单
|
||||||
|
intersectionFilteredIds = [];
|
||||||
|
} else {
|
||||||
|
// 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID
|
||||||
|
const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({
|
||||||
|
attributes: [ 'receiving_id' ],
|
||||||
|
where: {
|
||||||
|
system_product_id: { [Op.in]: [ ...entrySpIdSet ] },
|
||||||
|
},
|
||||||
|
group: [ 'receiving_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
intersectionFilteredIds = matchingDetailRows.map(r => r.receiving_id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 合并 filterDepleted 和 entry_order_id 的过滤结果
|
||||||
|
let combinedFilteredIds = null;
|
||||||
|
if (filteredReceivingIds !== null || intersectionFilteredIds !== null) {
|
||||||
|
if (filteredReceivingIds !== null && intersectionFilteredIds !== null) {
|
||||||
|
// 两个过滤都启用 → 取交集
|
||||||
|
const intersectionSet = new Set(intersectionFilteredIds);
|
||||||
|
combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id));
|
||||||
|
} else if (filteredReceivingIds !== null) {
|
||||||
|
combinedFilteredIds = filteredReceivingIds;
|
||||||
|
} else {
|
||||||
|
combinedFilteredIds = intersectionFilteredIds;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果启用了过滤,用过滤后的 ID 做最终查询
|
||||||
|
const finalWhere = combinedFilteredIds !== null
|
||||||
|
? { id: { [Op.in]: combinedFilteredIds } }
|
||||||
|
: queryOptions.where;
|
||||||
|
|
||||||
const [ total, data ] = await Promise.all([
|
const [ total, data ] = await Promise.all([
|
||||||
ctx.model.Receiving.count({
|
ctx.model.Receiving.count({
|
||||||
where: queryOptions.where,
|
where: finalWhere,
|
||||||
include,
|
include,
|
||||||
distinct: true,
|
distinct: true,
|
||||||
}),
|
}),
|
||||||
ctx.model.Receiving.findAll({
|
ctx.model.Receiving.findAll({
|
||||||
...queryOptions,
|
...queryOptions,
|
||||||
|
where: finalWhere,
|
||||||
include,
|
include,
|
||||||
limit: parseInt(pageSize),
|
limit: parseInt(pageSize),
|
||||||
offset: parseInt(offset),
|
offset: parseInt(offset),
|
||||||
@ -217,8 +354,9 @@ class ReceivingService extends Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const processedData = data.map(item => {
|
const processedData = data.map(item => {
|
||||||
const availableQuantity = Math.max(0, item.quantity - item.locked_quantity);
|
// 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量
|
||||||
const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(2) : 0;
|
const availableQuantity = Math.max(0, item.total_quantity || 0);
|
||||||
|
const lockRate = 0;
|
||||||
const itemImages = images
|
const itemImages = images
|
||||||
.filter(row => parseInt(row.business_id) === item.id)
|
.filter(row => parseInt(row.business_id) === item.id)
|
||||||
.map(row => row.file.file_url);
|
.map(row => row.file.file_url);
|
||||||
@ -234,9 +372,9 @@ class ReceivingService extends Service {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const summary = {
|
const summary = {
|
||||||
total_quantity: data.reduce((sum, item) => sum + item.quantity, 0),
|
total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
|
||||||
total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0),
|
total_locked: 0,
|
||||||
total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item.locked_quantity), 0),
|
total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0),
|
||||||
total_items: data.length,
|
total_items: data.length,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -4218,6 +4356,157 @@ class ReceivingService extends Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。
|
||||||
|
* 搜索策略:
|
||||||
|
* 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表;
|
||||||
|
* 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤);
|
||||||
|
* 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息;
|
||||||
|
* 4. 在内存中遍历明细进行精确匹配:
|
||||||
|
* - 若 barcode 为纯数字,优先按明细 ID 精确匹配;
|
||||||
|
* - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码;
|
||||||
|
* 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。
|
||||||
|
* @param {number} entryOrderId 入库单ID
|
||||||
|
* @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID)
|
||||||
|
* @return {Promise<Object>} 包含 code、message 与匹配明细列表 data.list 的结果对象
|
||||||
|
*/
|
||||||
|
async scanDetail(entryOrderId, barcode) {
|
||||||
|
const { ctx, app } = this;
|
||||||
|
const { Op } = app.Sequelize;
|
||||||
|
const warehouseId = ctx.user?.store_id;
|
||||||
|
|
||||||
|
// 参数校验
|
||||||
|
if (!warehouseId) {
|
||||||
|
return { code: 0, message: '用户未绑定仓库', data: null };
|
||||||
|
}
|
||||||
|
if (!entryOrderId || Number(entryOrderId) <= 0) {
|
||||||
|
return { code: 0, message: '入库单ID不能为空', data: null };
|
||||||
|
}
|
||||||
|
if (!barcode || String(barcode).trim() === '') {
|
||||||
|
return { code: 0, message: '扫描条码不能为空', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedBarcode = String(barcode).trim();
|
||||||
|
const normalizedEntryOrderId = Number(entryOrderId);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 验证入库单存在且属于当前仓库
|
||||||
|
const entryOrder = await ctx.model.EntryOrder.findOne({
|
||||||
|
where: {
|
||||||
|
id: normalizedEntryOrderId,
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
},
|
||||||
|
attributes: [ 'id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!entryOrder) {
|
||||||
|
return { code: 0, message: '入库单不存在或无权访问', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表
|
||||||
|
const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({
|
||||||
|
where: { entry_order_id: normalizedEntryOrderId },
|
||||||
|
attributes: [ 'receiving_id' ],
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean);
|
||||||
|
if (receivingIds.length === 0) {
|
||||||
|
return { code: 0, message: '该入库单尚未关联收货单', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 排除已绑定的收货明细(wms_entry_receiving_binding 中有记录且未软删除)
|
||||||
|
const notBoundCondition = app.Sequelize.literal(
|
||||||
|
'NOT EXISTS (SELECT 1 FROM wms_entry_receiving_binding erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)'
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配)
|
||||||
|
const details = await ctx.model.ReceivingDetail.findAll({
|
||||||
|
where: {
|
||||||
|
[Op.and]: [
|
||||||
|
{ receiving_id: { [Op.in]: receivingIds } },
|
||||||
|
notBoundCondition,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (details.length === 0) {
|
||||||
|
return { code: 0, message: '未找到可用的收货明细', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码
|
||||||
|
const stockIdSet = new Set();
|
||||||
|
for (const d of details) {
|
||||||
|
if (d.system_product_id != null) {
|
||||||
|
stockIdSet.add(Number(d.system_product_id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const stockIds = [ ...stockIdSet ];
|
||||||
|
|
||||||
|
/** @type {Map<number, Object>} */
|
||||||
|
const stockDetailMap = new Map();
|
||||||
|
if (stockIds.length > 0) {
|
||||||
|
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
|
||||||
|
for (const sd of stockDetails) {
|
||||||
|
if (sd && sd.id != null) {
|
||||||
|
stockDetailMap.set(sd.id, sd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 在内存中遍历明细,精确匹配,收集所有命中
|
||||||
|
const isNumericBarcode = /^\d+$/.test(normalizedBarcode);
|
||||||
|
const matchedDetails = [];
|
||||||
|
|
||||||
|
for (const detail of details) {
|
||||||
|
// 优先按明细 ID 精确匹配(托盘唛头场景)
|
||||||
|
if (isNumericBarcode && detail.id === Number(normalizedBarcode)) {
|
||||||
|
matchedDetails.push(detail);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 按商品条码精确匹配
|
||||||
|
const stockDetail = stockDetailMap.get(detail.system_product_id);
|
||||||
|
if (stockDetail && Array.isArray(stockDetail.barcodes)) {
|
||||||
|
const barcodeMatch = stockDetail.barcodes.some(
|
||||||
|
bc => bc.barcode === normalizedBarcode
|
||||||
|
);
|
||||||
|
if (barcodeMatch) {
|
||||||
|
matchedDetails.push(detail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matchedDetails.length === 0) {
|
||||||
|
return { code: 0, message: '未找到匹配的收货明细', data: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
const list = matchedDetails.map(matchedDetail => ({
|
||||||
|
detail_id: matchedDetail.id,
|
||||||
|
receiving_id: matchedDetail.receiving_id,
|
||||||
|
barcode: matchedDetail.barcode || '',
|
||||||
|
product_name: matchedDetail.product_name || '',
|
||||||
|
actual_quantity: matchedDetail.actual_quantity || 0,
|
||||||
|
receiving_status: matchedDetail.receiving_status || '',
|
||||||
|
stock: stockDetailMap.get(Number(matchedDetail.system_product_id)) || null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
message: '查询成功',
|
||||||
|
data: {
|
||||||
|
list,
|
||||||
|
total: list.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error);
|
||||||
|
return { code: 500, message: `服务器错误: ${error.message}`, data: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = ReceivingService;
|
module.exports = ReceivingService;
|
||||||
|
|||||||
@ -130,7 +130,7 @@ module.exports = appInfo => {
|
|||||||
'audio/x-m4a': 'audio',
|
'audio/x-m4a': 'audio',
|
||||||
};
|
};
|
||||||
config.cors = {
|
config.cors = {
|
||||||
origin: '*', // 允许所有源,生产环境应指定具体域名
|
origin: (ctx) => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用
|
||||||
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
|
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
|
||||||
exposeHeaders: 'Authorization',
|
exposeHeaders: 'Authorization',
|
||||||
credentials: true, // 允许携带 cookie
|
credentials: true, // 允许携带 cookie
|
||||||
@ -180,6 +180,7 @@ module.exports = appInfo => {
|
|||||||
|
|
||||||
config.jwt = {
|
config.jwt = {
|
||||||
expiresIn: 14400,
|
expiresIn: 14400,
|
||||||
|
renewThreshold: 7200,
|
||||||
secret: 'E5#ex.g@,GfL_8?',
|
secret: 'E5#ex.g@,GfL_8?',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
76
database/migrations/20260629-add-waiting-storage-status.js
Normal file
76
database/migrations/20260629-add-waiting-storage-status.js
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打印迁移阶段对应的数据库连接上下文信息。
|
||||||
|
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||||
|
* @param {'up'|'down'} phase 迁移阶段。
|
||||||
|
* @param {string} table 迁移目标表名。
|
||||||
|
* @return {Promise<void>} 无返回值。
|
||||||
|
*/
|
||||||
|
const logMigrationDbContext = async (queryInterface, phase, table) => {
|
||||||
|
try {
|
||||||
|
const [rows] = await queryInterface.sequelize.query(
|
||||||
|
'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user'
|
||||||
|
);
|
||||||
|
const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {};
|
||||||
|
console.log(
|
||||||
|
`[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}`
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(
|
||||||
|
`[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Migration: 为 wms_receiving 和 wms_receiving_detail 表的 storage_status 列新增 waiting 枚举值
|
||||||
|
*
|
||||||
|
* 正向 SQL:
|
||||||
|
* ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库';
|
||||||
|
* ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库';
|
||||||
|
*
|
||||||
|
* 回滚 SQL:
|
||||||
|
* ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库';
|
||||||
|
* ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库';
|
||||||
|
*/
|
||||||
|
|
||||||
|
const UP_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`;
|
||||||
|
const DOWN_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`;
|
||||||
|
|
||||||
|
const UP_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`;
|
||||||
|
const DOWN_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`;
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
/**
|
||||||
|
* 执行正向迁移,为 storage_status 列新增 waiting 枚举值。
|
||||||
|
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||||
|
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||||
|
* @return {Promise<void>} 无返回值。
|
||||||
|
*/
|
||||||
|
up: async (queryInterface, Sequelize) => {
|
||||||
|
await logMigrationDbContext(queryInterface, 'up', 'wms_receiving');
|
||||||
|
await queryInterface.sequelize.query(UP_SQL_RECEIVING);
|
||||||
|
console.log('[Migration] wms_receiving.storage_status 已新增 waiting 枚举值');
|
||||||
|
|
||||||
|
await logMigrationDbContext(queryInterface, 'up', 'wms_receiving_detail');
|
||||||
|
await queryInterface.sequelize.query(UP_SQL_DETAIL);
|
||||||
|
console.log('[Migration] wms_receiving_detail.storage_status 已新增 waiting 枚举值');
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行回滚迁移,移除 waiting 枚举值,恢复为原有枚举。
|
||||||
|
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||||
|
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||||
|
* @return {Promise<void>} 无返回值。
|
||||||
|
*/
|
||||||
|
down: async (queryInterface, Sequelize) => {
|
||||||
|
await logMigrationDbContext(queryInterface, 'down', 'wms_receiving');
|
||||||
|
await queryInterface.sequelize.query(DOWN_SQL_RECEIVING);
|
||||||
|
console.log('[Migration] wms_receiving.storage_status 已移除 waiting 枚举值');
|
||||||
|
|
||||||
|
await logMigrationDbContext(queryInterface, 'down', 'wms_receiving_detail');
|
||||||
|
await queryInterface.sequelize.query(DOWN_SQL_DETAIL);
|
||||||
|
console.log('[Migration] wms_receiving_detail.storage_status 已移除 waiting 枚举值');
|
||||||
|
},
|
||||||
|
};
|
||||||
309
database/migrations/20260630160000-create-wms-order-stockout.js
Normal file
309
database/migrations/20260630160000-create-wms-order-stockout.js
Normal file
@ -0,0 +1,309 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const MAIN_TABLE = 'wms_order_stockout';
|
||||||
|
const ITEMS_TABLE = 'wms_order_stockout_items';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建奇门出库单主表与明细表。
|
||||||
|
*
|
||||||
|
* - wms_order_stockout:出库单主表(对应奇门 stockout.create 的 <deliveryOrder> 节点)
|
||||||
|
* - wms_order_stockout_items:出库明细表(对应 <orderLine> 节点)
|
||||||
|
*
|
||||||
|
* 幂等:如果表已存在则跳过创建。
|
||||||
|
*/
|
||||||
|
module.exports = {
|
||||||
|
up: async (queryInterface, Sequelize) => {
|
||||||
|
const tables = await queryInterface.showAllTables();
|
||||||
|
|
||||||
|
const exists = name =>
|
||||||
|
tables.some(t => (typeof t === 'string' ? t : t.tableName) === name);
|
||||||
|
|
||||||
|
// ----------------------- 主表 -----------------------
|
||||||
|
if (!exists(MAIN_TABLE)) {
|
||||||
|
await queryInterface.createTable(MAIN_TABLE, {
|
||||||
|
id: {
|
||||||
|
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
stockout_order_code: {
|
||||||
|
type: Sequelize.STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '出库单号(对应奇门 deliveryOrderCode)',
|
||||||
|
},
|
||||||
|
order_type: {
|
||||||
|
type: Sequelize.STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '业务类型(JYCK/HHCK/BFCK/QTCK 等)',
|
||||||
|
},
|
||||||
|
total_order_lines: {
|
||||||
|
type: Sequelize.INTEGER(11),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '单据总行数',
|
||||||
|
},
|
||||||
|
order_create_time: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '订单创建时间(对应奇门 createTime)',
|
||||||
|
},
|
||||||
|
source_type: {
|
||||||
|
type: Sequelize.ENUM('WMS', 'API', 'QM'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'QM',
|
||||||
|
comment: '来源类型',
|
||||||
|
},
|
||||||
|
order_status: {
|
||||||
|
type: Sequelize.ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'CREATED',
|
||||||
|
comment: '订单状态',
|
||||||
|
},
|
||||||
|
sync_status: {
|
||||||
|
type: Sequelize.ENUM('PENDING', 'SUCCESS', 'FAILED'),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 'PENDING',
|
||||||
|
comment: '同步状态',
|
||||||
|
},
|
||||||
|
sync_message: {
|
||||||
|
type: Sequelize.TEXT,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '同步返回信息',
|
||||||
|
},
|
||||||
|
warehouse_id: {
|
||||||
|
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '仓库ID',
|
||||||
|
},
|
||||||
|
store_id: {
|
||||||
|
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '货主ID',
|
||||||
|
},
|
||||||
|
store_name: {
|
||||||
|
type: Sequelize.STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主名称快照',
|
||||||
|
},
|
||||||
|
warehouse_name: {
|
||||||
|
type: Sequelize.STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '仓库名称快照',
|
||||||
|
},
|
||||||
|
qimen_owner_code: {
|
||||||
|
type: Sequelize.STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '奇门货主code(对应 ownerCode)',
|
||||||
|
},
|
||||||
|
qimen_warehouse_code: {
|
||||||
|
type: Sequelize.STRING(100),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '奇门仓库code(对应 warehouseCode)',
|
||||||
|
},
|
||||||
|
remark: {
|
||||||
|
type: Sequelize.STRING(500),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '备注',
|
||||||
|
},
|
||||||
|
extend_props: {
|
||||||
|
type: Sequelize.JSON,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '扩展属性',
|
||||||
|
},
|
||||||
|
is_enabled: {
|
||||||
|
type: Sequelize.TINYINT(1),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 1,
|
||||||
|
comment: '是否启用',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
deleted_at: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '软删除时间',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 唯一索引:(stockout_order_code, warehouse_id, store_id)
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'stockout_order_code', 'warehouse_id', 'store_id' ], {
|
||||||
|
unique: true,
|
||||||
|
name: 'uk_stockout_order_code',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 辅助查询索引
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'order_type' ], {
|
||||||
|
name: 'idx_order_type',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'order_status' ], {
|
||||||
|
name: 'idx_order_status',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'sync_status' ], {
|
||||||
|
name: 'idx_sync_status',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'source_type' ], {
|
||||||
|
name: 'idx_source_type',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'warehouse_id', 'store_id' ], {
|
||||||
|
name: 'idx_warehouse_store',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'order_create_time' ], {
|
||||||
|
name: 'idx_order_create_time',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'is_enabled' ], {
|
||||||
|
name: 'idx_is_enabled',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(MAIN_TABLE, [ 'deleted_at' ], {
|
||||||
|
name: 'idx_deleted_at',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------- 明细表 -----------------------
|
||||||
|
if (!exists(ITEMS_TABLE)) {
|
||||||
|
await queryInterface.createTable(ITEMS_TABLE, {
|
||||||
|
id: {
|
||||||
|
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||||
|
primaryKey: true,
|
||||||
|
autoIncrement: true,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '主键ID',
|
||||||
|
},
|
||||||
|
order_id: {
|
||||||
|
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: false,
|
||||||
|
comment: '出库单ID,外键关联 wms_order_stockout.id',
|
||||||
|
},
|
||||||
|
out_biz_code: {
|
||||||
|
type: Sequelize.STRING(255),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '外部业务编码(幂等键)',
|
||||||
|
},
|
||||||
|
order_line_no: {
|
||||||
|
type: Sequelize.STRING(50),
|
||||||
|
allowNull: false,
|
||||||
|
comment: '订单行号(对应奇门 orderLineNo)',
|
||||||
|
},
|
||||||
|
owner_code: {
|
||||||
|
type: Sequelize.STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '货主编码(对应奇门 ownerCode)',
|
||||||
|
},
|
||||||
|
item_code: {
|
||||||
|
type: Sequelize.STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品编码(对应奇门 itemCode)',
|
||||||
|
},
|
||||||
|
item_id: {
|
||||||
|
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||||
|
allowNull: true,
|
||||||
|
comment: 'WMS商品ID(对应奇门 itemId)',
|
||||||
|
},
|
||||||
|
item_name: {
|
||||||
|
type: Sequelize.STRING(200),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '商品名称',
|
||||||
|
},
|
||||||
|
plan_qty: {
|
||||||
|
type: Sequelize.INTEGER(12),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '计划数量(对应奇门 planQty)',
|
||||||
|
},
|
||||||
|
actual_qty: {
|
||||||
|
type: Sequelize.INTEGER(12),
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: 0,
|
||||||
|
comment: '实发数量',
|
||||||
|
},
|
||||||
|
inventory_type: {
|
||||||
|
type: Sequelize.STRING(50),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存类型(ZP正品/CC残次等)',
|
||||||
|
},
|
||||||
|
stock_id: {
|
||||||
|
type: Sequelize.BIGINT(20),
|
||||||
|
allowNull: true,
|
||||||
|
comment: '库存ID,外键关联 wms_stock_warehouse.id',
|
||||||
|
},
|
||||||
|
extend_props: {
|
||||||
|
type: Sequelize.JSON,
|
||||||
|
allowNull: true,
|
||||||
|
comment: '扩展属性',
|
||||||
|
},
|
||||||
|
created_at: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||||
|
comment: '创建时间',
|
||||||
|
},
|
||||||
|
updated_at: {
|
||||||
|
type: Sequelize.DATE,
|
||||||
|
allowNull: false,
|
||||||
|
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||||
|
comment: '更新时间',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 唯一索引:(order_id, order_line_no)
|
||||||
|
await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id', 'order_line_no' ], {
|
||||||
|
unique: true,
|
||||||
|
name: 'uk_order_line_no',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 辅助索引
|
||||||
|
await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id' ], {
|
||||||
|
name: 'idx_order_id',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(ITEMS_TABLE, [ 'stock_id' ], {
|
||||||
|
name: 'idx_stock_id',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(ITEMS_TABLE, [ 'item_code' ], {
|
||||||
|
name: 'idx_item_code',
|
||||||
|
});
|
||||||
|
await queryInterface.addIndex(ITEMS_TABLE, [ 'out_biz_code' ], {
|
||||||
|
name: 'idx_out_biz_code',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 外键约束
|
||||||
|
await queryInterface.addConstraint(ITEMS_TABLE, {
|
||||||
|
fields: [ 'order_id' ],
|
||||||
|
type: 'foreign key',
|
||||||
|
name: 'fk_items_order_id',
|
||||||
|
references: {
|
||||||
|
table: MAIN_TABLE,
|
||||||
|
field: 'id',
|
||||||
|
},
|
||||||
|
onDelete: 'CASCADE',
|
||||||
|
onUpdate: 'CASCADE',
|
||||||
|
});
|
||||||
|
|
||||||
|
await queryInterface.addConstraint(ITEMS_TABLE, {
|
||||||
|
fields: [ 'stock_id' ],
|
||||||
|
type: 'foreign key',
|
||||||
|
name: 'fk_items_stock_id',
|
||||||
|
references: {
|
||||||
|
table: 'wms_stock_warehouse',
|
||||||
|
field: 'id',
|
||||||
|
},
|
||||||
|
onDelete: 'RESTRICT',
|
||||||
|
onUpdate: 'CASCADE',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
down: async queryInterface => {
|
||||||
|
await queryInterface.dropTable(ITEMS_TABLE);
|
||||||
|
await queryInterface.dropTable(MAIN_TABLE);
|
||||||
|
},
|
||||||
|
};
|
||||||
@ -118,6 +118,7 @@
|
|||||||
| oaid | string | OAID | 设备/终端标识 |
|
| oaid | string | OAID | 设备/终端标识 |
|
||||||
| sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 |
|
| sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 |
|
||||||
| store_id | number | 货主ID | 货主主键 |
|
| store_id | number | 货主ID | 货主主键 |
|
||||||
|
| store_remark | string | 货主备注 | 来自 wms_store_warehouse.store_remask,服务层按 store_id+warehouse_id 聚合填充 |
|
||||||
| warehouse_id | number | 仓库ID | 仓库主键 |
|
| warehouse_id | number | 仓库ID | 仓库主键 |
|
||||||
| from_key | number | 来源键 | 来源系统键值 |
|
| from_key | number | 来源键 | 来源系统键值 |
|
||||||
| items | string | 商品JSON字符串 | 原始商品明细 JSON |
|
| items | string | 商品JSON字符串 | 原始商品明细 JSON |
|
||||||
|
|||||||
@ -467,7 +467,7 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `storage.entry.bindReceivingDetails` | 入库单明细与收货明细逐行绑定(基于 `wms_entry_receiving_binding` 表),关系已改为 `wms_entry_order_receiving` 主表级关联 | 不再需要,入库单与收货单直接通过主表关联 |
|
| `storage.entry.bindReceivingDetails` | 入库单明细与收货明细逐行绑定(基于 `wms_entry_receiving_binding` 表),关系已改为 `wms_entry_order_receiving` 主表级关联 | 不再需要,入库单与收货单直接通过主表关联 |
|
||||||
| `storage.entry.unbindReceivingDetails` | 同上,逐行解绑已无必要 | 不再需要 |
|
| `storage.entry.unbindReceivingDetails` | 同上,逐行解绑已无必要 | 不再需要 |
|
||||||
| `storage.inventory.quickPutaway` | 单一收货单快捷入库,功能受限 | `storage.inventory.matchPutaway`(支持多收货单+多入库单批量匹配入库) |
|
| `storage.inventory.quickPutaway` | 单一收货单快捷转入库单(已重新实现):按 stock_id 合并收货明细创建入库单(SCRK,自动审批到 PENDING),写入主表级绑定 | `storage.entry.commitDirectInbound`(导入/PDA 入库完成确认) |
|
||||||
|
|
||||||
### 14.4 核心方法职责
|
### 14.4 核心方法职责
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"date": "2026-06-24",
|
|
||||||
"type": "addition",
|
|
||||||
"method": "storage.entry.bindReceivingDetails",
|
|
||||||
"summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功",
|
|
||||||
"related": ["storage.entry.get 追加 available_receiving_details 字段"]
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"date": "2026-06-24",
|
|
||||||
"type": "deprecation",
|
|
||||||
"method": "storage.receiving.manualMatchEntryOrder",
|
|
||||||
"summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代",
|
|
||||||
"migration": "使用 storage.entry.get(含 available_receiving_details 元数据)加载可匹配的收货单明细,然后调用 storage.entry.bindReceivingDetails 批量提交绑定"
|
|
||||||
}
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.05.08-system-06",
|
|
||||||
"date": "2026-05-08",
|
|
||||||
"summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel",
|
|
||||||
"methods": [
|
|
||||||
"order.wave.wavePickTaskCancel"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。",
|
|
||||||
"限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。",
|
|
||||||
"事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。"
|
|
||||||
],
|
|
||||||
"type": "added"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.05.13-system-01",
|
|
||||||
"date": "2026-05-13",
|
|
||||||
"summary": "完善 print.send 的 API 文档与返回说明",
|
|
||||||
"methods": [
|
|
||||||
"print.send"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。",
|
|
||||||
"补充 template 的子字段说明:page_width、page_height、template_content。",
|
|
||||||
"补充响应结构:flag、code、message、printId;其中成功时 code=200。",
|
|
||||||
"补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。"
|
|
||||||
],
|
|
||||||
"type": "updated"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.05.20-system-01",
|
|
||||||
"date": "2026-05-20",
|
|
||||||
"summary": "新增订单复核模块方法:order.recheckOrder.scanOrder、order.recheckOrder.confirmRecheck",
|
|
||||||
"methods": [
|
|
||||||
"order.recheckOrder.scanOrder",
|
|
||||||
"order.recheckOrder.confirmRecheck"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"用途:扫码查询订单明细(scanOrder);确认复核并落库 wms_recheck_task(confirmRecheck)。",
|
|
||||||
"scanOrder 返回运单号或车号匹配的订单头、商品明细、运单信息与相关日志;confirmRecheck 将复核结果写入 wms_recheck_task 并返回复核摘要信息(order_id、recheck_status、recheck_time、review_no)。",
|
|
||||||
"变更概要:confirmRecheck 改为按 order_id 进行复核(兼容 id/orderId);scanOrder 返回准确的 order_id 供前端直接使用;新增支持:查找范围包含 wms_wave_pick_task 的车号快照(current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot)。",
|
|
||||||
"规则调整:移除打印状态约束,改为未拣货约束。",
|
|
||||||
"scanOrder 在车号命中场景按波次类型返回不同结构(1/5 groups, 2 orders, 3 pick_groups, 4 box_groups)。"
|
|
||||||
],
|
|
||||||
"type": "added"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,18 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.05.20-system-03",
|
|
||||||
"date": "2026-05-20",
|
|
||||||
"summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志",
|
|
||||||
"methods": [
|
|
||||||
"storeWarehouse.store.queryPrintQuantityLogs"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。",
|
|
||||||
"入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。",
|
|
||||||
"仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。",
|
|
||||||
"返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。"
|
|
||||||
],
|
|
||||||
"type": "added",
|
|
||||||
"module": "storeWarehouse"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.05.28-system-01",
|
|
||||||
"date": "2026-05-28",
|
|
||||||
"summary": "新增包材相关表与在订单快递表新增包材关联字段(wms_package_material / wms_package_supplier / wms_order_express)",
|
|
||||||
"methods": [],
|
|
||||||
"notes": [
|
|
||||||
"新增表 wms_package_material:主要字段 id, warehouse_id, material_code, material_name, material_type, spec, length, width, height, weight, cost_price, status, version, created_at, updated_at;索引:idx_wms_package_material_warehouse_id(warehouse_id),uk_wms_package_material_warehouse_material_code(warehouse_id + material_code 唯一)。",
|
|
||||||
"新增表 wms_package_supplier:主要字段 id, warehouse_id, supplier_code, supplier_name, contact_name, contact_phone, status, version, created_at, updated_at;索引:idx_wms_package_supplier_warehouse_id(warehouse_id),uk_wms_package_supplier_warehouse_supplier_code(warehouse_id + supplier_code 唯一)。",
|
|
||||||
"修改表 wms_order_express:新增可空字段 package_material_id (BIGINT unsigned) 与 package_material_name_snapshot (VARCHAR(128));新增索引 idx_wms_order_express_package_material_id(package_material_id)。",
|
|
||||||
"回滚要点:迁移脚本的 down 实现会移除上述索引与列,并删除新增的两张表(详见 database/migrations/20260528090000-create-wms-package-material-and-supplier.js 与 database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js)。生产回滚前请先迁移或备份依赖数据并通知下游系统。",
|
|
||||||
"兼容性说明:新增列均为可空(nullable),属于向后兼容的增量变更,不会影响现有查询或写入;若服务端或前端存在把 wms_order_express 全量序列化到外部响应的场景,响应中可能会包含这两个可选字段;目前已检查的对外 system 方法文档未声明返回 package_material_id 或 package_material_name_snapshot,因此本次不修改 methods/system.json(无接口契约变化)。",
|
|
||||||
"相关模型文件:新增 app/model/package_material.js、app/model/package_supplier.js;更新 app/model/order_express.js(新增字段与索引定义)。",
|
|
||||||
"验证建议:1) 在预发布环境执行 migrations up/down 并确认幂等性;2) 执行下单→分配快递→打印等关键路径以验证无回归;3) 若需要对外暴露包材字段,请在 methods/system.json 中补充对应接口的 response 字段并在变更记录中说明。"
|
|
||||||
],
|
|
||||||
"type": "updated",
|
|
||||||
"module": "database"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.06.16-system-01",
|
|
||||||
"date": "2026-06-16",
|
|
||||||
"summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段",
|
|
||||||
"methods": [
|
|
||||||
"order.recheckOrder.queryRecheckOrderSingleList"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。",
|
|
||||||
"响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。",
|
|
||||||
"响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。"
|
|
||||||
],
|
|
||||||
"type": "added",
|
|
||||||
"module": "order.recheckOrder"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.06.16-system-02",
|
|
||||||
"date": "2026-06-16",
|
|
||||||
"summary": "order.wave.groupOrderFetchList 响应新增 items_weight(总重量kg)字段",
|
|
||||||
"methods": [
|
|
||||||
"order.wave.groupOrderFetchList"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。",
|
|
||||||
"为 null 时返回 null。"
|
|
||||||
],
|
|
||||||
"type": "updated",
|
|
||||||
"module": "order.wave"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.06.16-system-03",
|
|
||||||
"date": "2026-06-16",
|
|
||||||
"summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段",
|
|
||||||
"methods": [
|
|
||||||
"order.wave.waveStrategyFallbackOrderList"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。",
|
|
||||||
"响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。"
|
|
||||||
],
|
|
||||||
"type": "updated",
|
|
||||||
"module": "order.wave"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.06.16-system-04",
|
|
||||||
"date": "2026-06-16",
|
|
||||||
"summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段",
|
|
||||||
"methods": [
|
|
||||||
"order.wave.singleOrderFetchList"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。",
|
|
||||||
"为 null 时返回 null。"
|
|
||||||
],
|
|
||||||
"type": "updated",
|
|
||||||
"module": "order.wave"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,20 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"version": "2026.06.17-openapi-16",
|
|
||||||
"date": "2026-06-17",
|
|
||||||
"summary": "新增入库单模块(entryorder),支持 create(创建入库单)和 query(查询入库单)两个方法",
|
|
||||||
"methods": [
|
|
||||||
"entryorder.create",
|
|
||||||
"entryorder.query"
|
|
||||||
],
|
|
||||||
"notes": [
|
|
||||||
"新增 entryorder.create:创建入库单接口,支持入库单主信息(entryOrder)和商品明细(orderLines.orderLine)的完整入参;创建渠道固定为 API;itemCode 与 itemId 二选一,优先使用 itemId",
|
|
||||||
"新增 entryorder.query:查询入库单接口,根据 entryOrderCode 查询入库单详情,返回基本信息及商品明细(itemId/itemCode/itemName/planQty/actualQty/inventoryType/orderLineNo)",
|
|
||||||
"查询范围为当前 app_key 绑定的仓库,跨仓库入库单无法查询",
|
|
||||||
"所有方法均支持 timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400",
|
|
||||||
"openapi 通道新增入库单创建和查询能力"
|
|
||||||
],
|
|
||||||
"type": "added",
|
|
||||||
"module": "entryorder"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,14 +1,57 @@
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
"version": "2026.04.07-qimen-01",
|
"version": "2026.07.01-qimen-01",
|
||||||
"date": "2026-04-07",
|
"date": "2026-07-01",
|
||||||
"summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。",
|
"summary": "补充 entryorder.create 的 request body 子结构和 response 结构",
|
||||||
"methods": [
|
"methods": [
|
||||||
"*"
|
"entryorder.create"
|
||||||
],
|
],
|
||||||
"notes": [
|
"notes": [
|
||||||
"methods/qimen.json 仍为单一事实来源(SSOT)。",
|
"补充 request.entryOrder 子结构(entryOrderCode/warehouseCode/ownerCode/orderType)",
|
||||||
"本文件仅记录变更历史与补充说明。"
|
"补充 request.orderLines.orderLine 子结构(itemCode/itemId/itemName/planQty/orderLineNo/inventoryType)",
|
||||||
]
|
"补充 response 结构(entryOrderId/entryOrderCode/createTime/status)",
|
||||||
}
|
"参考代码:systems/entry_order.js addOrder 和 qimenMethods/entryorder.js create 返回值"
|
||||||
|
],
|
||||||
|
"type": "updated",
|
||||||
|
"module": "entryorder"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.04.07-qimen-01",
|
||||||
|
"date": "2026-04-07",
|
||||||
|
"summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。",
|
||||||
|
"methods": [
|
||||||
|
"*"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"methods/qimen.json 仍为单一事实来源(SSOT)。",
|
||||||
|
"本文件仅记录变更历史与补充说明。"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-stockout-create-01",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "stockout.create 重构:从不可用的 deliveryOrder 旧链路迁移到 wms_order_stockout 专用表;返回字段 deliveryOrderId→stockoutOrderId/stockoutOrderCode",
|
||||||
|
"methods": [
|
||||||
|
"stockout.create"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"params 补全 deliveryOrder 和 orderLines 内部全部子字段",
|
||||||
|
"response 从空补充为 stockoutOrderId/stockoutOrderCode",
|
||||||
|
"文档与代码实现(qimenMethods/stockout.js create 方法)对齐"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-stockout-query-01",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "stockout.query 从占位(接口未完善)实现为完整查询:按 deliveryOrderCode 查 wms_order_stockout 主表+明细表",
|
||||||
|
"methods": [
|
||||||
|
"stockout.query"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"params 补全 request.deliveryOrder.deliveryOrderCode(body)",
|
||||||
|
"response 从空补充为 deliveryOrder 主单 + orderLines.orderLine 明细 + totalLines",
|
||||||
|
"文档与代码实现(qimenMethods/stockout.js query 方法)对齐"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@ -1,4 +1,125 @@
|
|||||||
[
|
[
|
||||||
|
{
|
||||||
|
"date": "2026-06-24",
|
||||||
|
"type": "addition",
|
||||||
|
"summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功",
|
||||||
|
"version": "2026-06-24-add-bind-receiving-details",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.bindReceivingDetails"
|
||||||
|
],
|
||||||
|
"notes": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"date": "2026-06-24",
|
||||||
|
"type": "deprecation",
|
||||||
|
"summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代",
|
||||||
|
"version": "2026-06-24-deprecate-manual-match-entry-order",
|
||||||
|
"methods": [
|
||||||
|
"storage.receiving.manualMatchEntryOrder"
|
||||||
|
],
|
||||||
|
"notes": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.16-system-03",
|
||||||
|
"date": "2026-06-16",
|
||||||
|
"summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段",
|
||||||
|
"methods": [
|
||||||
|
"order.wave.waveStrategyFallbackOrderList"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。",
|
||||||
|
"响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。"
|
||||||
|
],
|
||||||
|
"type": "updated",
|
||||||
|
"module": "order.wave"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.16-system-04",
|
||||||
|
"date": "2026-06-16",
|
||||||
|
"summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段",
|
||||||
|
"methods": [
|
||||||
|
"order.wave.singleOrderFetchList"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。",
|
||||||
|
"为 null 时返回 null。"
|
||||||
|
],
|
||||||
|
"type": "updated",
|
||||||
|
"module": "order.wave"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.05.20-system-03",
|
||||||
|
"date": "2026-05-20",
|
||||||
|
"summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志",
|
||||||
|
"methods": [
|
||||||
|
"storeWarehouse.store.queryPrintQuantityLogs"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。",
|
||||||
|
"入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。",
|
||||||
|
"仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。",
|
||||||
|
"返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。"
|
||||||
|
],
|
||||||
|
"type": "added",
|
||||||
|
"module": "storeWarehouse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.05.13-system-01",
|
||||||
|
"date": "2026-05-13",
|
||||||
|
"summary": "完善 print.send 的 API 文档与返回说明",
|
||||||
|
"methods": [
|
||||||
|
"print.send"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。",
|
||||||
|
"补充 template 的子字段说明:page_width、page_height、template_content。",
|
||||||
|
"补充响应结构:flag、code、message、printId;其中成功时 code=200。",
|
||||||
|
"补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.05.08-system-06",
|
||||||
|
"date": "2026-05-08",
|
||||||
|
"summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel",
|
||||||
|
"methods": [
|
||||||
|
"order.wave.wavePickTaskCancel"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。",
|
||||||
|
"限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。",
|
||||||
|
"事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。"
|
||||||
|
],
|
||||||
|
"type": "added"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.07.01-system-01",
|
||||||
|
"date": "2026-07-01",
|
||||||
|
"summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number",
|
||||||
|
"methods": [
|
||||||
|
"storage.directInbound.addItem"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致",
|
||||||
|
"同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id"
|
||||||
|
],
|
||||||
|
"type": "fixed",
|
||||||
|
"module": "storage.directInbound"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.07.01-system-02",
|
||||||
|
"date": "2026-07-01",
|
||||||
|
"summary": "新增 storage.entry.queryEntryLogs 接口文档定义",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.queryEntryLogs"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义",
|
||||||
|
"参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)"
|
||||||
|
],
|
||||||
|
"type": "added",
|
||||||
|
"module": "storage.entry"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"version": "2026.06.18-system-01",
|
"version": "2026.06.18-system-01",
|
||||||
"date": "2026-06-18",
|
"date": "2026-06-18",
|
||||||
@ -4199,5 +4320,332 @@
|
|||||||
],
|
],
|
||||||
"type": "updated",
|
"type": "updated",
|
||||||
"module": "setting.warehouse"
|
"module": "setting.warehouse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.25-system-01",
|
||||||
|
"date": "2026-06-25",
|
||||||
|
"summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.bindReceiving"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。",
|
||||||
|
"入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。",
|
||||||
|
"支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。",
|
||||||
|
"响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。"
|
||||||
|
],
|
||||||
|
"type": "addition"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.25-system-02",
|
||||||
|
"date": "2026-06-25",
|
||||||
|
"summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.bindReceiving"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。",
|
||||||
|
"同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。"
|
||||||
|
],
|
||||||
|
"type": "updated",
|
||||||
|
"module": "storage.entry"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.25-system-03",
|
||||||
|
"date": "2026-06-25",
|
||||||
|
"summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.bindReceiving"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。",
|
||||||
|
"同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.25-system-04",
|
||||||
|
"date": "2026-06-25",
|
||||||
|
"summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.list"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。",
|
||||||
|
"入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。",
|
||||||
|
"同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.26-system-01",
|
||||||
|
"date": "2026-06-26",
|
||||||
|
"summary": "storage.entry.receivingCompare 支持多收货单对照预览",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.receivingCompare"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)",
|
||||||
|
"入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一",
|
||||||
|
"出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary",
|
||||||
|
"向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)",
|
||||||
|
"新增 400 错误码:receiving_ids 或 receiving_id 必填",
|
||||||
|
"移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)"
|
||||||
|
],
|
||||||
|
"type": "enhancement"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.26-system-02",
|
||||||
|
"date": "2026-06-26",
|
||||||
|
"summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明",
|
||||||
|
"methods": [
|
||||||
|
"storage.receiving.getReceivingList",
|
||||||
|
"storage.entry.receivingCompare"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。",
|
||||||
|
"storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.26-system-03",
|
||||||
|
"date": "2026-06-26",
|
||||||
|
"summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表",
|
||||||
|
"methods": [
|
||||||
|
"storage.receiving.getReceivingList"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。",
|
||||||
|
"与现有 filterDepleted 参数可组合使用,二者取交集。",
|
||||||
|
"不传则不过滤,保持原有行为不变。"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.27-system-01",
|
||||||
|
"date": "2026-06-27",
|
||||||
|
"summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.reviewEntry"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增入库单审核接口,支持 CREATED→PENDING 状态流转。",
|
||||||
|
"审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。",
|
||||||
|
"审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。"
|
||||||
|
],
|
||||||
|
"type": "added"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.29-system-01",
|
||||||
|
"date": "2026-06-29",
|
||||||
|
"summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单",
|
||||||
|
"methods": [
|
||||||
|
"storage.inventory.quickPutaway"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。",
|
||||||
|
"核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。",
|
||||||
|
"前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。",
|
||||||
|
"与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。",
|
||||||
|
"返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。"
|
||||||
|
],
|
||||||
|
"type": "addition"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.29-system-02",
|
||||||
|
"date": "2026-06-29",
|
||||||
|
"summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.list"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。",
|
||||||
|
"同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。"
|
||||||
|
],
|
||||||
|
"type": "updated",
|
||||||
|
"module": "storage"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.29-system-03",
|
||||||
|
"date": "2026-06-29",
|
||||||
|
"summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细",
|
||||||
|
"methods": [
|
||||||
|
"storage.receiving.scanDetail"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。",
|
||||||
|
"搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。",
|
||||||
|
"入参:entry_order_id(必填 number)、barcode(必填 string)。",
|
||||||
|
"出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。",
|
||||||
|
"错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。"
|
||||||
|
],
|
||||||
|
"type": "added"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.29-system-04",
|
||||||
|
"date": "2026-06-29",
|
||||||
|
"summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细",
|
||||||
|
"methods": [
|
||||||
|
"storage.receiving.scanDetail"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。",
|
||||||
|
"同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。",
|
||||||
|
"list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。",
|
||||||
|
"补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。",
|
||||||
|
"PDA专用接口,description 更新说明匹配逻辑。"
|
||||||
|
],
|
||||||
|
"type": "updated",
|
||||||
|
"module": "storage.receiving"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-01",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.containerList"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。",
|
||||||
|
"入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。",
|
||||||
|
"出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。",
|
||||||
|
"已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。",
|
||||||
|
"PDA 专用接口,无需额外鉴权(isNeedAuth=false)。"
|
||||||
|
],
|
||||||
|
"type": "added"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-02",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "storage.entry.addDirectInboundItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.addDirectInboundItem"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐",
|
||||||
|
"quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)",
|
||||||
|
"新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)",
|
||||||
|
"新增 allocated_quantity 参数:预分配数量,默认等于 quantity",
|
||||||
|
"space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)",
|
||||||
|
"PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作",
|
||||||
|
"CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架",
|
||||||
|
"批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段",
|
||||||
|
"补充完整错误码列表:超量、可用数量不足、状态校验等"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-03",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "storage.entry.commitDirectInbound 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.commitDirectInbound"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐",
|
||||||
|
"补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存",
|
||||||
|
"补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-04",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐",
|
||||||
|
"methods": [
|
||||||
|
"storage.directInbound.commit"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐",
|
||||||
|
"该方法已标记 deprecated,推荐使用 storage.entry.commitDirectInbound"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-05",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.getDirectInboundItems"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段",
|
||||||
|
"items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)",
|
||||||
|
"items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }",
|
||||||
|
"items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)",
|
||||||
|
"移除 direct_logs(现有响应中已不存在该顶层字段)",
|
||||||
|
"移除 summary(现有响应中已不存在该字段)",
|
||||||
|
"移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段",
|
||||||
|
"新增 receivingBindings 字段说明:入库单层级收货单绑定关系"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-06",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段",
|
||||||
|
"methods": [
|
||||||
|
"storage.directInbound.getItems"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)",
|
||||||
|
"entryOrder 精简为 id / entry_order_code / order_status / store_remask",
|
||||||
|
"items[].count → planned,items[].direct_inbound_quantity → completed",
|
||||||
|
"items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }",
|
||||||
|
"items[].stock 新增",
|
||||||
|
"移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段",
|
||||||
|
"新增 receivingBindings 字段"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-07",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)",
|
||||||
|
"methods": [
|
||||||
|
"storage.entry.containerList"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存",
|
||||||
|
"stock 对象包含 item_code、item_name、sku_property、barcodes 等字段"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-08",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)",
|
||||||
|
"methods": [
|
||||||
|
"storage.receiving.scanDetail"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存",
|
||||||
|
"stock 对象包含 item_code、item_name、sku_property、barcodes 等字段",
|
||||||
|
"完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026.06.30-system-09",
|
||||||
|
"date": "2026-06-30",
|
||||||
|
"summary": "订单列表 list 响应新增 store_remark(货主备注)字段",
|
||||||
|
"methods": [
|
||||||
|
"order.list",
|
||||||
|
"order.reviewOrder.list",
|
||||||
|
"order.pendingOrder.list",
|
||||||
|
"order.expectionOrder.list",
|
||||||
|
"order.entrustOrder.list",
|
||||||
|
"order.deliveryOrder.list",
|
||||||
|
"order.deliveryExpectionOrder.list",
|
||||||
|
"order.archiveOrder.list"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"数据库字段 store_remask,返回给前端的字段名为 store_remark。",
|
||||||
|
"服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。",
|
||||||
|
"货主备注值可能为空字符串(当货主未设置备注时)。",
|
||||||
|
"该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。"
|
||||||
|
],
|
||||||
|
"type": "updated"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"module": "qimen",
|
"module": "qimen",
|
||||||
"description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)",
|
"description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)",
|
||||||
"version": "0.3.0",
|
"version": "0.3.6",
|
||||||
"updatedAt": "2026-03-22",
|
"updatedAt": "2026-06-30",
|
||||||
"headers": [],
|
"headers": [],
|
||||||
"methods": {
|
"methods": {
|
||||||
"groups": [
|
"groups": [
|
||||||
@ -240,7 +240,7 @@
|
|||||||
"list": [
|
"list": [
|
||||||
{
|
{
|
||||||
"method": "entryorder.create",
|
"method": "entryorder.create",
|
||||||
"description": "entryorder.create 接口",
|
"description": "创建入库单。奇门 XML 推送创建入库单及明细,返回入库单 ID、单号、创建时间和状态",
|
||||||
"isNeedAuth": false,
|
"isNeedAuth": false,
|
||||||
"isNeedLogin": false,
|
"isNeedLogin": false,
|
||||||
"headers": [],
|
"headers": [],
|
||||||
@ -299,11 +299,129 @@
|
|||||||
"type": "object",
|
"type": "object",
|
||||||
"required": true,
|
"required": true,
|
||||||
"source": "body",
|
"source": "body",
|
||||||
"description": "request XML 节点"
|
"description": "request XML 节点,包含 entryOrder 和 orderLines 子节点"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.entryOrder",
|
||||||
|
"type": "object",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "入库单头信息"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.entryOrder.entryOrderCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "入库单号(外部系统单号)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.entryOrder.warehouseCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "仓库编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.entryOrder.ownerCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "货主编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.entryOrder.orderType",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "入库单类型:CGRK(采购入库)、JITRK(JIT入库)、THRK(退货入库)、QTRK(其他入库)等"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine",
|
||||||
|
"type": "object|array",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "入库单明细行,单条为 object,多条为 array"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.itemCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "商品编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.itemId",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"source": "body",
|
||||||
|
"description": "商品 ID(StockStore 主键),建议必传以避免编码匹配问题"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.itemName",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "商品名称"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.planQty",
|
||||||
|
"type": "number",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "计划入库数量"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.orderLineNo",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"source": "body",
|
||||||
|
"description": "行号"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.inventoryType",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"source": "body",
|
||||||
|
"description": "库存类型,如 ZP(正品),默认 ZP"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"response": [],
|
"response": [
|
||||||
"errors": []
|
{
|
||||||
|
"name": "entryOrderId",
|
||||||
|
"type": "number",
|
||||||
|
"required": true,
|
||||||
|
"description": "WMS 入库单 ID"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "entryOrderCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "入库单号"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "createTime",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "创建时间"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "status",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "入库单状态:CREATED(已创建)或 PENDING(已审核)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"code": 400,
|
||||||
|
"message": "创建入库单失败:商品未同步推送到仓库 / wms无对应关系"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": 500,
|
||||||
|
"message": "服务器异常"
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"method": "entryorder.query",
|
"method": "entryorder.query",
|
||||||
@ -985,25 +1103,136 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "request.deliveryOrder",
|
"name": "request.deliveryOrder",
|
||||||
|
"type": "object",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "出库单头信息"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.deliveryOrder.deliveryOrderCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "出库单号"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.deliveryOrder.orderType",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.deliveryOrder.warehouseCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "仓库编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.deliveryOrder.createTime",
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"required": false,
|
"required": false,
|
||||||
"source": "body",
|
"source": "body",
|
||||||
"description": "request.deliveryOrder 参数"
|
"description": "订单创建时间"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.deliveryOrder.totalOrderLines",
|
||||||
|
"type": "integer",
|
||||||
|
"required": false,
|
||||||
|
"source": "body",
|
||||||
|
"description": "单据总行数"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.deliveryOrder.remark",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"source": "body",
|
||||||
|
"description": "备注"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "request.orderLines",
|
"name": "request.orderLines",
|
||||||
|
"type": "object",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "出库单明细"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine",
|
||||||
|
"type": "object/array",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "明细行(单条为对象,多条为数组)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.orderLineNo",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "订单行号"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.ownerCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "货主编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.itemCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "商品编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.itemId",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "WMS商品ID"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.itemName",
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"required": false,
|
"required": false,
|
||||||
"source": "body",
|
"source": "body",
|
||||||
"description": "request.orderLines 参数"
|
"description": "商品名称"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.planQty",
|
||||||
|
"type": "integer",
|
||||||
|
"required": true,
|
||||||
|
"source": "body",
|
||||||
|
"description": "计划数量"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "request.orderLines.orderLine.inventoryType",
|
||||||
|
"type": "string",
|
||||||
|
"required": false,
|
||||||
|
"source": "body",
|
||||||
|
"description": "库存类型(ZP正品/CC残次等)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"response": [
|
||||||
|
{
|
||||||
|
"name": "stockoutOrderId",
|
||||||
|
"type": "integer",
|
||||||
|
"required": true,
|
||||||
|
"description": "出库单ID"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "stockoutOrderCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "出库单号"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"response": [],
|
|
||||||
"errors": []
|
"errors": []
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"method": "stockout.query",
|
"method": "stockout.query",
|
||||||
"description": "stockout.query 接口",
|
"description": "stockout.query 接口(查询非订单出库单;按 deliveryOrderCode 查 wms_order_stockout 主表+明细表)",
|
||||||
"isNeedAuth": false,
|
"isNeedAuth": false,
|
||||||
"isNeedLogin": false,
|
"isNeedLogin": false,
|
||||||
"headers": [],
|
"headers": [],
|
||||||
@ -1062,25 +1291,139 @@
|
|||||||
"type": "object",
|
"type": "object",
|
||||||
"required": true,
|
"required": true,
|
||||||
"source": "body",
|
"source": "body",
|
||||||
"description": "request XML 节点"
|
"description": "请求数据"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "request.deliveryOrder",
|
"name": "request.deliveryOrder",
|
||||||
"type": "string",
|
"type": "object",
|
||||||
"required": false,
|
"required": true,
|
||||||
"source": "body",
|
"source": "body",
|
||||||
"description": "request.deliveryOrder 参数"
|
"description": "出库单查询条件"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "request.orderLines",
|
"name": "request.deliveryOrder.deliveryOrderCode",
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"required": false,
|
"required": true,
|
||||||
"source": "body",
|
"source": "body",
|
||||||
"description": "request.orderLines 参数"
|
"description": "出库单号"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"response": [],
|
"response": [
|
||||||
"errors": []
|
{
|
||||||
|
"name": "totalLines",
|
||||||
|
"type": "integer",
|
||||||
|
"required": true,
|
||||||
|
"description": "明细总行数"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder",
|
||||||
|
"type": "object",
|
||||||
|
"required": true,
|
||||||
|
"description": "出库单主单信息"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder.deliveryOrderCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "出库单号"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder.deliveryOrderId",
|
||||||
|
"type": "integer",
|
||||||
|
"required": true,
|
||||||
|
"description": "出库单ID"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder.warehouseCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "仓库编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder.orderType",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "业务类型"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder.status",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "订单状态"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder.createTime",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "创建时间"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "deliveryOrder.remark",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "备注"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines",
|
||||||
|
"type": "object",
|
||||||
|
"required": true,
|
||||||
|
"description": "明细集合"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine",
|
||||||
|
"type": "array",
|
||||||
|
"required": true,
|
||||||
|
"description": "明细行数组"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine[].orderLineNo",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "订单行号"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine[].ownerCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "货主编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine[].itemCode",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "商品编码"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine[].itemId",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "WMS商品ID"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine[].itemName",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "商品名称"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine[].planQty",
|
||||||
|
"type": "integer",
|
||||||
|
"required": true,
|
||||||
|
"description": "计划数量"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "orderLines.orderLine[].inventoryType",
|
||||||
|
"type": "string",
|
||||||
|
"required": true,
|
||||||
|
"description": "库存类型"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"code": 400,
|
||||||
|
"message": "未找到出库单(deliveryOrderCode 对应记录不存在)"
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
|||||||
1266
methods/system.json
1266
methods/system.json
File diff suppressed because it is too large
Load Diff
449
skills/entry-order-test-guide.md
Normal file
449
skills/entry-order-test-guide.md
Normal file
@ -0,0 +1,449 @@
|
|||||||
|
# 入库单推送全流程测试指南
|
||||||
|
|
||||||
|
## 1. 全流程概述
|
||||||
|
|
||||||
|
```
|
||||||
|
奇门推送 entryorder.create → 创建入库单(CREATED)
|
||||||
|
→ bindReceiving(绑定收货单)
|
||||||
|
→ reviewEntry(CREATED→PENDING)
|
||||||
|
→ addItem(PDA上架,传 receiving_detail_id + space_id)
|
||||||
|
→ commit(提交入库+奇门同步→COMPLETED)
|
||||||
|
|
||||||
|
或 quickInbound(虚拟直入,跳过收货单,CREATED→COMPLETED)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 流程说明
|
||||||
|
|
||||||
|
| 阶段 | method | 状态变化 | 说明 |
|
||||||
|
|------|--------|----------|------|
|
||||||
|
| 奇门创建 | `qimen.entryorder.create` | (无)→CREATED | 奇门 XML 推送,创建入库单及明细 |
|
||||||
|
| 绑定收货单 | `storage.entry.bindReceiving` | CREATED→CREATED | 将入库单与收货单关联 |
|
||||||
|
| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING | 审核通过,允许上架,**必须已绑定收货单** |
|
||||||
|
| PDA上架 | `storage.directInbound.addItem` | PENDING→PENDING | PDA扫码上架,传 `receiving_detail_id` + `space_id` |
|
||||||
|
| 提交入库 | `storage.directInbound.commit` | PENDING→COMPLETED | 先奇门同步,再写库存 |
|
||||||
|
| 虚拟直入 | `storage.entry.quickInbound` | CREATED→COMPLETED | 跳过收货单,一键完成入库 |
|
||||||
|
|
||||||
|
## 2. 关键接口列表
|
||||||
|
|
||||||
|
| 步骤 | method | 说明 | 入口 |
|
||||||
|
|------|--------|------|------|
|
||||||
|
| 创建 | `qimen.entryorder.create` | 奇门推送 XML 创建入库单 | /qimen |
|
||||||
|
| 绑定 | `storage.entry.bindReceiving` | 绑定收货单到入库单 | /system |
|
||||||
|
| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING,需已绑定 | /system |
|
||||||
|
| 上架 | `storage.directInbound.addItem` | PDA添加,可选绑定收货明细 | /system |
|
||||||
|
| 提交 | `storage.directInbound.commit` | 同步奇门+写库存→COMPLETED | /system |
|
||||||
|
| 虚拟 | `storage.entry.quickInbound` | 一键虚拟入库 | /system |
|
||||||
|
| 对照 | `storage.entry.receivingCompare` | 入库单 vs 收货单明细对照 | /system |
|
||||||
|
| 查询 | `storage.directInbound.getItems` | 查询直入记录 | /system |
|
||||||
|
| 日志 | `storage.entry.queryEntryLogs` | 查询入库单操作日志 | /system |
|
||||||
|
|
||||||
|
## 3. 踩坑点
|
||||||
|
|
||||||
|
### 3a. 端口
|
||||||
|
|
||||||
|
配置文件(`config/config.local.js`)中端口是 **6060**,不是 Egg.js 默认的 7001。
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 确认端口
|
||||||
|
Select-String -Path "config/config.local.js" -Pattern "port"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3b. app_key 双重角色
|
||||||
|
|
||||||
|
- **签名用**:`config.qimen.appKey`(如 `23535631`),用于奇门请求的 MD5 签名计算
|
||||||
|
- **validateApi 查询匹配用**:请求参数中的 `app_key`(如 `23060081`),用于匹配 `wms_api_app` 表记录
|
||||||
|
- **两个值不同**,签名的 `app_key` 不参与 `wms_api_app` 绑定查询
|
||||||
|
|
||||||
|
### 3c. 奇门签名
|
||||||
|
|
||||||
|
- **签名算法**:`secret + sortedParams + xmlBody + secret` → MD5 → 大写
|
||||||
|
- **签名不验证入站请求**:qimen 入口无 `verifyTopRequest` 校验
|
||||||
|
- **使用已有合约配置**:从 `wms_api_app` 表读取,不要无中生有创建新配置
|
||||||
|
|
||||||
|
### 3d. itemId 必传
|
||||||
|
|
||||||
|
- `itemId` 为空时,按 `item_code + app_key + warehouse_id + store_id` 查询 `StockStore`
|
||||||
|
- `app_key` 不匹配会导致找不到商品
|
||||||
|
- **建议一律传 `itemId`** 以避免匹配问题
|
||||||
|
|
||||||
|
### 3e. 服务器重启
|
||||||
|
|
||||||
|
修改代码后需完全重启:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
taskkill /F /IM node.exe
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
端口被占用排查:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
netstat -ano | findstr :6060
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3f. /system 接口需要 headers
|
||||||
|
|
||||||
|
```http
|
||||||
|
platform: web
|
||||||
|
project: wms
|
||||||
|
Authorization: Bearer <JWT_TOKEN>
|
||||||
|
```
|
||||||
|
|
||||||
|
测试账号:`liufumingren` / `111111`
|
||||||
|
|
||||||
|
获取 token:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
curl -X POST http://localhost:6060/system?method=user.login `
|
||||||
|
-H "platform: web" `
|
||||||
|
-H "project: wms" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d '{"username":"liufumingren","password":"111111"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3g. 先同步后写库
|
||||||
|
|
||||||
|
`quickInbound` 和 `commit` 的执行顺序已改为:
|
||||||
|
|
||||||
|
1. 先调用 `qimenEntrySync` 同步到奇门/ERP
|
||||||
|
2. 同步成功后才写库存
|
||||||
|
3. 同步失败不写库存,只标记为 `FAILED`
|
||||||
|
|
||||||
|
### 3h. 绑定模式
|
||||||
|
|
||||||
|
`addItem` 传 `receiving_detail_id` 时进入绑定模式:
|
||||||
|
|
||||||
|
- **忽略 `quantity` 字段**,实际数量从 `ReceivingDetail.actual_quantity` 取值
|
||||||
|
- **必须传 `space_id`**(库位ID)
|
||||||
|
- **允许超过入库单 `planQty`**,不受计划数量限制
|
||||||
|
|
||||||
|
## 4. 快速测试脚本示例
|
||||||
|
|
||||||
|
### 4.1 准备工作:获取 Token
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$loginBody = @{username="liufumingren";password="111111"} | ConvertTo-Json
|
||||||
|
$loginResp = curl -s -X POST "http://localhost:6060/system?method=user.login" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d $loginBody
|
||||||
|
$token = ($loginResp | ConvertFrom-Json).data.token
|
||||||
|
Write-Host "Token: $token"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 创建入库单(奇门推送)
|
||||||
|
|
||||||
|
```xml
|
||||||
|
POST /qimen?method=entryorder.create&app_key=23060081&customerId=4&v=1.0&format=xml&sign_method=md5×tamp=2026-06-27+10:00:00&sign=XXX
|
||||||
|
|
||||||
|
<request>
|
||||||
|
<entryOrder>
|
||||||
|
<entryOrderCode>TEST-ENTRY-001</entryOrderCode>
|
||||||
|
<warehouseCode>WH001</warehouseCode>
|
||||||
|
<orderType>JYCK</orderType>
|
||||||
|
</entryOrder>
|
||||||
|
<orderLines>
|
||||||
|
<orderLine>
|
||||||
|
<itemCode>SKU001</itemCode>
|
||||||
|
<planQty>100</planQty>
|
||||||
|
</orderLine>
|
||||||
|
</orderLines>
|
||||||
|
</request>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 创建收货单
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$rcvBody = @{
|
||||||
|
delivery_method="truck"
|
||||||
|
loading_method="without_pallet"
|
||||||
|
store_id=1000000
|
||||||
|
} | ConvertTo-Json
|
||||||
|
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.receiving.create" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d $rcvBody
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.4 添加收货明细
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$detailBody = @{
|
||||||
|
receiving_id="<RECEIVING_ID>"
|
||||||
|
item=@{
|
||||||
|
product_name="测试商品"
|
||||||
|
actual_quantity=86
|
||||||
|
}
|
||||||
|
} | ConvertTo-Json
|
||||||
|
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.receiving.addDetail" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d $detailBody
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.5 完成收货 + 审核
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 完成收货
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.receiving.completeReceiving" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d "{`"receiving_id`":`"<RECEIVING_ID>`"}"
|
||||||
|
|
||||||
|
# 审核收货单
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.receiving.reviewReceiving" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d "{`"receiving_id`":`"<RECEIVING_ID>`"}"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.6 绑定入库单 + 审核
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 绑定收货单
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.entry.bindReceiving" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d "{`"entry_id`":`"<ENTRY_ID>`",`"receiving_id`":`"<RECEIVING_ID>`"}"
|
||||||
|
|
||||||
|
# 审核入库单
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.entry.reviewEntry" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d "{`"entry_id`":`"<ENTRY_ID>`"}"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.7 PDA上架 + 提交
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 添加直入记录(绑定模式)
|
||||||
|
$addItemBody = @{
|
||||||
|
entry_id="<ENTRY_ID>"
|
||||||
|
receiving_detail_id="<RECEIVING_DETAIL_ID>"
|
||||||
|
space_id="<SPACE_ID>"
|
||||||
|
item_code="SKU001"
|
||||||
|
} | ConvertTo-Json
|
||||||
|
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.addItem" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d $addItemBody
|
||||||
|
|
||||||
|
# 提交入库
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.commit" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d "{`"entry_id`":`"<ENTRY_ID>`"}"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.8 虚拟直入(跳过收货单)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$quickBody = @{
|
||||||
|
entry_id="<ENTRY_ID>"
|
||||||
|
items=@(
|
||||||
|
@{
|
||||||
|
item_code="SKU001"
|
||||||
|
quantity=50
|
||||||
|
space_id="<SPACE_ID>"
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} | ConvertTo-Json
|
||||||
|
|
||||||
|
curl -s -X POST "http://localhost:6060/system?method=storage.entry.quickInbound" `
|
||||||
|
-H "platform: web" -H "project: wms" `
|
||||||
|
-H "Authorization: Bearer $token" `
|
||||||
|
-H "Content-Type: application/json" `
|
||||||
|
-d $quickBody
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. 数据库关键表
|
||||||
|
|
||||||
|
| 表 | 用途 | 关键字段 |
|
||||||
|
|----|------|----------|
|
||||||
|
| `wms_entry_order` | 入库单主表 | id, entry_order_code, order_status, sync_status |
|
||||||
|
| `wms_entry_items` | 入库单明细 | id, entry_id, item_id, item_code, plan_quantity, actual_quantity |
|
||||||
|
| `wms_receiving` | 收货单主表 | id, receiving_code, status, store_id |
|
||||||
|
| `wms_receiving_detail` | 收货单明细 | id, receiving_id, product_name, actual_quantity |
|
||||||
|
| `wms_entry_order_receiving` | 入库单↔收货单主表绑定 | id, entry_id, receiving_id |
|
||||||
|
| `wms_entry_receiving_binding` | 入库明细↔收货明细绑定 | id, entry_item_id, receiving_detail_id, quantity |
|
||||||
|
| `wms_inbound_direct_log` | PDA直入记录 | id, entry_id, item_code, quantity, space_id, receiving_detail_id |
|
||||||
|
| `wms_api_app` | 奇门应用绑定配置 | id, app_key, app_secret, warehouse_id, store_id |
|
||||||
|
| `wms_operation_log` | 操作日志 | id, target_type, target_id, action, operator, created_at |
|
||||||
|
|
||||||
|
## 6. 状态机速查
|
||||||
|
|
||||||
|
| 状态 | 含义 | 可执行操作 |
|
||||||
|
|------|------|------------|
|
||||||
|
| `CREATED` | 已创建,待绑定/审核 | bindReceiving, reviewEntry, quickInbound, cancel |
|
||||||
|
| `PENDING` | 已审核,待上架 | addItem, commit, cancel |
|
||||||
|
| `COMPLETED` | 已完成 | 不可操作 |
|
||||||
|
| `CANCELLED` | 已取消 | 不可操作 |
|
||||||
|
| `FAILED` | 同步失败 | 重试或取消 |
|
||||||
|
|
||||||
|
## 7. 常见问题排查
|
||||||
|
|
||||||
|
### 7.1 找不到入库单
|
||||||
|
|
||||||
|
- 检查奇门 XML 中 `warehouseCode` 是否匹配 `wms_api_app` 中的 `warehouse_id`
|
||||||
|
- 检查 `app_key` 是否已在 `wms_api_app` 表中配置
|
||||||
|
|
||||||
|
### 7.2 reviewEntry 报错"未绑定收货单"
|
||||||
|
|
||||||
|
- CREATED 状态且未调用 `bindReceiving` 时,审核会被拒绝
|
||||||
|
- 先调用 `bindReceiving` 绑定收货单
|
||||||
|
|
||||||
|
### 7.3 addItem 报错"缺少 space_id"
|
||||||
|
|
||||||
|
- 绑定模式下(传了 `receiving_detail_id`)必须同时传 `space_id`
|
||||||
|
- `space_id` 对应库位表主键
|
||||||
|
|
||||||
|
### 7.4 commit 后库存未变化
|
||||||
|
|
||||||
|
- 检查 `qimenEntrySync` 是否返回成功
|
||||||
|
- 同步失败时标记为 `FAILED` 状态,库存不会写入
|
||||||
|
- 查看 `wms_operation_log` 中的错误信息
|
||||||
|
|
||||||
|
### 7.5 端口被占用
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 查找占用进程
|
||||||
|
netstat -ano | findstr :6060
|
||||||
|
# 强制结束
|
||||||
|
taskkill /F /PID <PID>
|
||||||
|
```
|
||||||
|
|
||||||
|
## 8. 变更历史
|
||||||
|
|
||||||
|
| 日期 | 版本 | 变更内容 |
|
||||||
|
|------|------|----------|
|
||||||
|
| 2026-06-27 | v1.0 | 初始版本,覆盖入库单全流程测试指南 |
|
||||||
|
## 8. 问题清单与修复基准(来自 issues.txt)
|
||||||
|
|
||||||
|
### 问题 1:缺失收货单直接转入库单的快捷入口
|
||||||
|
- **现状**:收货单创建后,必须先手动创建入库单(走奇门或 OpenAPI),再通过 bindReceiving 绑定
|
||||||
|
- **修复后应支持**:storage.receiving.createEntryOrder(receiving_id) → 自动创建入库单并绑定主表关系
|
||||||
|
|
||||||
|
### 问题 2:addItem 状态机校验不完整
|
||||||
|
- **2a**:CREATED + 已绑定收货单 → 应拒绝(当前只强制要求传 receiving_detail_id)
|
||||||
|
- **2b**:PENDING + 已绑定 + 无明细ID → 应拒绝(当前未区分 CREATED/PENDING)
|
||||||
|
- **2c**:PENDING + 无绑定 → 应拒绝(PENDING 只能走 PDA 上架,必须已绑定收货单)
|
||||||
|
- **2d**:CREATED 人工导入 → 应允许超过 planQty(当前非绑定模式不允许超量)
|
||||||
|
|
||||||
|
**修复后校验矩阵:**
|
||||||
|
|
||||||
|
| 状态 | 有绑定 | 携带明细ID | 应允许 | 超 planQty |
|
||||||
|
|------|--------|-----------|--------|-----------|
|
||||||
|
| CREATED | 否 | 否 | ✅ 人工后台导入 | ✅ 允许 |
|
||||||
|
| CREATED | 是 | - | ❌ 拒绝 | - |
|
||||||
|
| PENDING | 否 | - | ❌ 拒绝 | - |
|
||||||
|
| PENDING | 是 | 否 | ❌ 拒绝 | - |
|
||||||
|
| PENDING | 是 | 是 | ✅ PDA上架 | ✅ 允许 |
|
||||||
|
|
||||||
|
### 问题 3:状态机定义
|
||||||
|
`
|
||||||
|
CREATING → CREATED → PENDING → COMPLETED
|
||||||
|
↑ ↓ ↑
|
||||||
|
└── 重试推送 ────────┘ │
|
||||||
|
CANCELLED ←────────┘
|
||||||
|
`
|
||||||
|
- CREATED:等待人工绑定和审核,可走人工后台导入(不限制 planQty),可走虚拟直入
|
||||||
|
- PENDING:已审核,待上架/上架中,必须已绑定收货单,必须携带 receiving_detail_id
|
||||||
|
- COMPLETED:已完成,不可操作
|
||||||
|
|
||||||
|
### 问题 4:entryorderConfirm 增量回传应移除
|
||||||
|
- 统一走 qimenEntrySync 全量同步,actualQty = item.count
|
||||||
|
- 移除 entry_order.js 的 entryorderConfirm 方法
|
||||||
|
|
||||||
|
### 问题 5:completeEntry 应作废
|
||||||
|
- commit 已包含所有实质性工作(写库存、同步奇门、推进 COMPLETED)
|
||||||
|
- completeEntry 无独立存在意义
|
||||||
|
|
||||||
|
### 问题 6:入库单取消
|
||||||
|
- 6a:取消时调用 qimenEntrySync,orderLines 全部 actualQty=0,通知 ERP 关闭
|
||||||
|
- 6b:sync_status=SUCCESS 的入库单不允许取消(已通知 ERP 入库完成)
|
||||||
|
- 允许取消的状态:sync_status != 'SUCCESS' 且 order_status NOT IN ('COMPLETED','CANCELLED')
|
||||||
|
|
||||||
|
## 9. 完整测试场景
|
||||||
|
|
||||||
|
### 场景 A:奇门创建 + 收货单 + PDA上架(完整链路)
|
||||||
|
`
|
||||||
|
1. qimen.entryorder.create → CREATED
|
||||||
|
2. storage.receiving.create → 收货单
|
||||||
|
3. storage.receiving.addDetail → 收货明细
|
||||||
|
4. storage.receiving.completeReceiving → 完成收货
|
||||||
|
5. storage.receiving.reviewReceiving → 审核收货单
|
||||||
|
6. storage.entry.bindReceiving → 绑定入库单↔收货单
|
||||||
|
7. storage.entry.receivingCompare → 对照预览
|
||||||
|
8. storage.entry.reviewEntry → CREATED→PENDING
|
||||||
|
9. storage.directInbound.addItem(receiving_detail_id) → PDA上架+明细绑定
|
||||||
|
10. storage.directInbound.commit → 奇门同步+写库存→COMPLETED
|
||||||
|
`
|
||||||
|
|
||||||
|
### 场景 B:人工后台导入(无收货单)
|
||||||
|
`
|
||||||
|
1. qimen.entryorder.create → CREATED
|
||||||
|
2. storage.directInbound.addItem(无 receiving_detail_id) → 人工导入
|
||||||
|
3. storage.directInbound.commit → 奇门同步+写库存→COMPLETED
|
||||||
|
`
|
||||||
|
|
||||||
|
### 场景 C:虚拟直入
|
||||||
|
`
|
||||||
|
1. qimen.entryorder.create → CREATED
|
||||||
|
2. storage.entry.quickInbound → 奇门同步+写库存→COMPLETED(一步完成)
|
||||||
|
`
|
||||||
|
|
||||||
|
### 场景 D:取消入库单
|
||||||
|
`
|
||||||
|
1. 入库单 CREATED/PENDING 且 sync_status != SUCCESS
|
||||||
|
2. storage.entry.cancel → ①发送 qimenEntrySync(all actualQty=0) → ②更新 order_status=CANCELLED
|
||||||
|
`
|
||||||
|
|
||||||
|
## 10. 数据库校验检查点
|
||||||
|
|
||||||
|
修复完成后,以下 SQL 可用于验证各场景正确性:
|
||||||
|
|
||||||
|
\\\sql
|
||||||
|
-- 验证入库单状态
|
||||||
|
SELECT id, entry_order_code, order_status, sync_status, sync_message FROM wms_entry_order WHERE id = ?;
|
||||||
|
|
||||||
|
-- 验证入库明细收货量
|
||||||
|
SELECT id, item_code, count, received_quantity, confirm_quantity FROM wms_entry_items WHERE order_id = ?;
|
||||||
|
|
||||||
|
-- 验证主表绑定
|
||||||
|
SELECT * FROM wms_entry_order_receiving WHERE entry_order_id = ?;
|
||||||
|
|
||||||
|
-- 验证明细绑定
|
||||||
|
SELECT id, entry_item_id, receiving_detail_id, allocated_quantity, status FROM wms_entry_receiving_binding WHERE entry_item_id IN (SELECT id FROM wms_entry_items WHERE order_id = ?);
|
||||||
|
|
||||||
|
-- 验证直入记录
|
||||||
|
SELECT id, stock_id, quantity, space_id FROM wms_inbound_direct_log WHERE entry_order_id = ?;
|
||||||
|
|
||||||
|
-- 验证库存写入
|
||||||
|
SELECT id, stock_id, batch_no, quantity, receiving_id, production_date, expiry_date FROM wms_storage WHERE entry_order_id = ?;
|
||||||
|
|
||||||
|
-- 验证操作日志
|
||||||
|
SELECT id, business_type, business_id, operation_code, message FROM wms_operation_log WHERE business_id = ? AND business_type = 'entry_order' ORDER BY created_at DESC;
|
||||||
|
\\\
|
||||||
|
|
||||||
|
## 11. 已知操作码清单
|
||||||
|
|
||||||
|
| operationCode | 触发接口 | 说明 |
|
||||||
|
|---------------|---------|------|
|
||||||
|
| ENTRY_ORDER_CREATE | qimen/OpenAPI entryorder.create | 入库单创建 |
|
||||||
|
| ENTRY_ORDER_REVIEW | storage.entry.reviewEntry | 审核通过 CREATED→PENDING |
|
||||||
|
| DIRECT_INBOUND_ADD | storage.directInbound.addItem | 直入记录添加 |
|
||||||
|
| DIRECT_INBOUND_COMMIT | storage.directInbound.commit | 提交入库 COMPLETED |
|
||||||
|
| DIRECT_INBOUND_REMOVE | storage.directInbound.removeItem | 移除直入记录 |
|
||||||
|
| QUICK_INBOUND | storage.entry.quickInbound | 虚拟直入完成 |
|
||||||
|
| QUICK_INBOUND_FAILED | quickInbound/commit 失败 | 同步失败 |
|
||||||
@ -1,71 +0,0 @@
|
|||||||
const mysql = require('mysql2/promise');
|
|
||||||
const path = require('path');
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
function walk(dir) {
|
|
||||||
const result = [];
|
|
||||||
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
||||||
for (const e of entries) {
|
|
||||||
const full = path.join(dir, e.name);
|
|
||||||
if (e.isDirectory()) result.push(...walk(full));
|
|
||||||
else if (e.name.endsWith('.js')) result.push(e.name);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
(async () => {
|
|
||||||
const files = walk('database/migrations');
|
|
||||||
console.log('迁移目录全部 .js 文件:', files.length, '个');
|
|
||||||
|
|
||||||
try {
|
|
||||||
const c = await mysql.createConnection({
|
|
||||||
host: '112.124.21.102',
|
|
||||||
port: 3306,
|
|
||||||
user: 'wms',
|
|
||||||
password: 'P6j3YTHTpirepYWz',
|
|
||||||
database: 'wms',
|
|
||||||
charset: 'utf8mb4',
|
|
||||||
connectTimeout: 10000,
|
|
||||||
});
|
|
||||||
|
|
||||||
// 查迁移相关表
|
|
||||||
const [tables] = await c.query(
|
|
||||||
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms' AND (TABLE_NAME LIKE '%sequelize%' OR TABLE_NAME LIKE '%migration%') ORDER BY TABLE_NAME"
|
|
||||||
);
|
|
||||||
console.log('\n=== 迁移相关表 ===');
|
|
||||||
if (tables.length === 0) console.log(' 无');
|
|
||||||
else tables.forEach(t => console.log(' ' + t.TABLE_NAME));
|
|
||||||
|
|
||||||
// 尝试查 sequelizemeta
|
|
||||||
try {
|
|
||||||
const [rows] = await c.query('SELECT name FROM sequelizemeta ORDER BY name');
|
|
||||||
console.log('\nsequelizemeta 表记录数:', rows.length);
|
|
||||||
rows.forEach(r => console.log(' ' + r.name));
|
|
||||||
} catch (e) {
|
|
||||||
console.log('\nsequelizemeta 表不存在或查询失败:', e.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 尝试查 SequelizeMeta (大写)
|
|
||||||
try {
|
|
||||||
const [rows] = await c.query('SELECT name FROM SequelizeMeta ORDER BY name');
|
|
||||||
console.log('\nSequelizeMeta 表记录数:', rows.length);
|
|
||||||
rows.forEach(r => console.log(' ' + r.name));
|
|
||||||
} catch (e) {
|
|
||||||
console.log('SequelizeMeta 表不存在或查询失败:', e.message);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 表总数
|
|
||||||
const [cnt] = await c.query("SELECT COUNT(*) AS cnt FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms'");
|
|
||||||
console.log('\n生产数据库表总数:', cnt[0].cnt);
|
|
||||||
|
|
||||||
await c.end();
|
|
||||||
|
|
||||||
// 对比
|
|
||||||
if (tables.length > 0) {
|
|
||||||
console.log('\n=== 结论 ===');
|
|
||||||
console.log('请检查上述迁移记录表,对比迁移目录中', files.length, '个文件即可知道未执行迁移。');
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.log('连接错误:', e.code, e.message);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
Binary file not shown.
Binary file not shown.
@ -1478,4 +1478,225 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
|
|||||||
assert.ok(skipLog, '应有订单 53 的日志');
|
assert.ok(skipLog, '应有订单 53 的日志');
|
||||||
assert.ok(skipLog.extras.message.includes('跳过'), `跳过订单应含"跳过",实际: ${skipLog.extras.message}`);
|
assert.ok(skipLog.extras.message.includes('跳过'), `跳过订单应含"跳过",实际: ${skipLog.extras.message}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 场景 5:space_id 无效时内存计数器回退验证
|
||||||
|
// 当 storageRow.space_id 为 0 时,代码应:
|
||||||
|
// 1) 回退 allocatedQuantityForOrder(不应计入已分配量)
|
||||||
|
// 2) 回退 allocatedQuantityForItem
|
||||||
|
// 3) 回退 remainingQuantity(未分配成功的应加回)
|
||||||
|
// 4) 回退 storageAllocationMap
|
||||||
|
// 5) 调用 unlockQuantity 释放数据库锁
|
||||||
|
// 核心 BUG:当前代码没有回退 allocatedQuantityForOrder/allocatedQuantityForItem/remainingQuantity
|
||||||
|
// ============================================================
|
||||||
|
it('should rollback memory counters when storage space_id is invalid (zero)', async () => {
|
||||||
|
const { service, captures, storageRows, stockRows } = createHarness({
|
||||||
|
orders: [
|
||||||
|
{ id: 601, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||||
|
],
|
||||||
|
orderItems: [
|
||||||
|
{ id: 6011, order_id: 601, stock_id: 901, plan_qty: 10, order_line_no: '1' },
|
||||||
|
],
|
||||||
|
stockRows: [
|
||||||
|
{ id: 901, item_code: 'SKU-901', item_name: '测试商品901', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||||
|
],
|
||||||
|
storageRows: [
|
||||||
|
// 库存A:有库存但 space_id = 0 → 无效,分配时应该回退
|
||||||
|
{
|
||||||
|
id: 9001,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 901,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 5,
|
||||||
|
quantity: 5,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-06-20 08:00:00',
|
||||||
|
space_id: 0, // ← 无效 space_id,触发回退逻辑
|
||||||
|
space: null,
|
||||||
|
},
|
||||||
|
// 库存B:有效库存,space_id 有效
|
||||||
|
{
|
||||||
|
id: 9002,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 901,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 10,
|
||||||
|
quantity: 10,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-06-20 09:00:00',
|
||||||
|
space_id: 50,
|
||||||
|
space: {
|
||||||
|
id: 50,
|
||||||
|
space_code: 'VALID-01',
|
||||||
|
custom_name: '有效库位',
|
||||||
|
is_preferred_pick: false,
|
||||||
|
locationType: { id: 1, allow_allocation: 1, is_active: 1 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
policies: {
|
||||||
|
901: { policyConfig: { storage_separation: 1 } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.allocateStorage({
|
||||||
|
allow_storage_location: true,
|
||||||
|
order_ids: [ 601 ],
|
||||||
|
});
|
||||||
|
|
||||||
|
// =============================================================
|
||||||
|
// 核心断言:验证内存计数器回退
|
||||||
|
// =============================================================
|
||||||
|
//
|
||||||
|
// 订单需要 qty=10
|
||||||
|
// 库存A: available=5, space_id=0 → lockQuantity 扣 5 →
|
||||||
|
// 空间无效 → unlockQuantity 释放 5,回退 remainingQuantity(+5)
|
||||||
|
// 库存B: available=10, space_id=50 → Math.min(remainingQuantity=10, 10)=10
|
||||||
|
// → lockQuantity 扣 10 → remainingQuantity=0
|
||||||
|
//
|
||||||
|
// 如果回退正确:库存B 10个全部满足 → storage_status = fin,allocated_quantity = 10
|
||||||
|
// 如果回退不正确(BUG):库存B只锁5个 → storage_status = error,allocated_quantity = 5
|
||||||
|
|
||||||
|
const orderResult = result.data.orders.find(item => item.order_id === 601);
|
||||||
|
assert.ok(orderResult, '返回结果应包含订单601');
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
orderResult.storage_status,
|
||||||
|
'fin',
|
||||||
|
'空间无效库存被回退后,有效库存B应满足全部10个需求,storage_status 应为 fin,' +
|
||||||
|
`实际 storage_status=${orderResult.storage_status}`
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
orderResult.allocated_quantity,
|
||||||
|
10,
|
||||||
|
'allocated_quantity 应为 10(库存B全部满足),' +
|
||||||
|
`实际 allocated_quantity=${orderResult.allocated_quantity}`
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2) 验证 unlockQuantity 被调用(数据库锁释放)
|
||||||
|
const spaceIdInvalidUnlock = captures.storageUnlocks.find(
|
||||||
|
item => item.storageId === 9001
|
||||||
|
);
|
||||||
|
assert.ok(spaceIdInvalidUnlock, 'space_id=0 的库存应调用 unlockQuantity 释放锁');
|
||||||
|
assert.equal(spaceIdInvalidUnlock.quantity, 5, '应释放 5 个锁定数量');
|
||||||
|
|
||||||
|
// 3) 验证有效库存被正确锁定(应为 10 个,因为库存B有10个满足全部需求)
|
||||||
|
const validLock = captures.storageLocks.find(
|
||||||
|
item => item.storageId === 9002
|
||||||
|
);
|
||||||
|
assert.ok(validLock, '有效库存B应被锁定');
|
||||||
|
assert.equal(validLock.quantity, 10, '应从有效库存B锁定 10 个(满足全部需求)');
|
||||||
|
|
||||||
|
// 4) 验证 storageAllocationMap — 无效库存不应在映射中
|
||||||
|
// 因为回退后 newStorageQty=0,会执行 delete
|
||||||
|
assert.equal(
|
||||||
|
storageRows.find(r => r.id === 9001).locked_quantity,
|
||||||
|
0,
|
||||||
|
'无效库存的 locked_quantity 应回退到 0'
|
||||||
|
);
|
||||||
|
|
||||||
|
// 5) 验证 picking rows — 只有有效库存的记录
|
||||||
|
assert.ok(Array.isArray(captures.pickingRows), '应有 picking 记录');
|
||||||
|
assert.equal(captures.pickingRows.length, 1, '应只有 1 条 picking 记录(有效库存)');
|
||||||
|
assert.equal(captures.pickingRows[0].storage_id, 9002, 'picking 应为有效库存B');
|
||||||
|
assert.equal(captures.pickingRows[0].quantity, 10, 'picking 数量应为 10');
|
||||||
|
|
||||||
|
// 6) 验证 stock_warehouse locked_quantity
|
||||||
|
const matchedStock = stockRows.find(r => r.id === 901);
|
||||||
|
assert.ok(matchedStock, '应有对应 stock 记录');
|
||||||
|
});
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 场景 6:space_id 无效时,如果有足够的其他有效库存满足需求,订单应为 fin
|
||||||
|
// ============================================================
|
||||||
|
it('should correctly mark order as fin when other valid storages satisfy demand despite invalid space_id', async () => {
|
||||||
|
const { service, captures, storageRows } = createHarness({
|
||||||
|
orders: [
|
||||||
|
{ id: 602, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 },
|
||||||
|
],
|
||||||
|
orderItems: [
|
||||||
|
{ id: 6021, order_id: 602, stock_id: 902, plan_qty: 5, order_line_no: '1' },
|
||||||
|
],
|
||||||
|
stockRows: [
|
||||||
|
{ id: 902, item_code: 'SKU-902', item_name: '测试商品902', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||||
|
],
|
||||||
|
storageRows: [
|
||||||
|
// 库存A:space_id 无效
|
||||||
|
{
|
||||||
|
id: 9101,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 902,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 3,
|
||||||
|
quantity: 3,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-06-20 08:00:00',
|
||||||
|
space_id: 0,
|
||||||
|
space: null,
|
||||||
|
},
|
||||||
|
// 库存B:有效库存,足够满足全部需求
|
||||||
|
{
|
||||||
|
id: 9102,
|
||||||
|
warehouse_id: 100000,
|
||||||
|
stock_id: 902,
|
||||||
|
is_enabled: 1,
|
||||||
|
delete_at: null,
|
||||||
|
available_quantity: 10,
|
||||||
|
quantity: 10,
|
||||||
|
locked_quantity: 0,
|
||||||
|
production_date: null,
|
||||||
|
inbound_time: '2026-06-20 09:00:00',
|
||||||
|
space_id: 60,
|
||||||
|
space: {
|
||||||
|
id: 60,
|
||||||
|
space_code: 'VALID-02',
|
||||||
|
custom_name: '有效库位2',
|
||||||
|
is_preferred_pick: false,
|
||||||
|
locationType: { id: 1, allow_allocation: 1, is_active: 1 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
policies: {
|
||||||
|
902: { policyConfig: { storage_separation: 1 } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.allocateStorage({
|
||||||
|
allow_storage_location: true,
|
||||||
|
order_ids: [ 602 ],
|
||||||
|
});
|
||||||
|
|
||||||
|
const orderResult = result.data.orders.find(item => item.order_id === 602);
|
||||||
|
assert.ok(orderResult, '返回结果应包含订单602');
|
||||||
|
|
||||||
|
// 订单需要5个,库存A无效(已回退),库存B可满足5个
|
||||||
|
// 如果 remainingQuantity 正确回退:5-3=2 → 回退+3 → 5 → 再扣5 → 0 → fin
|
||||||
|
// 如果 remainingQuantity 未回退:5-3=2 → 再扣2 → 0 → fin(碰巧也能正确)
|
||||||
|
// 所以这个场景两个行为都可能导致 fin,关键验证 unlockedQuantity 被调用
|
||||||
|
assert.equal(orderResult.storage_status, 'fin', '应标记为 fin');
|
||||||
|
assert.equal(orderResult.status, 'success', '应为 success');
|
||||||
|
|
||||||
|
// 验证 unlockQuantity 确实被调用
|
||||||
|
const spaceIdInvalidUnlock = captures.storageUnlocks.find(
|
||||||
|
item => item.storageId === 9101
|
||||||
|
);
|
||||||
|
assert.ok(spaceIdInvalidUnlock, 'space_id=0 的库存应调用 unlockQuantity');
|
||||||
|
assert.equal(spaceIdInvalidUnlock.quantity, 3, '应释放 3 个锁定');
|
||||||
|
|
||||||
|
// 验证有效库存的 locked_quantity
|
||||||
|
assert.equal(storageRows.find(r => r.id === 9101).locked_quantity, 0, '无效库存 locked_quantity 应回退到 0');
|
||||||
|
assert.equal(storageRows.find(r => r.id === 9102).locked_quantity, 5, '有效库存 locked_quantity 应为 5');
|
||||||
|
|
||||||
|
// 验证 picking rows
|
||||||
|
assert.equal(captures.pickingRows.length, 1, '应只有 1 条 picking');
|
||||||
|
assert.equal(captures.pickingRows[0].storage_id, 9102, 'picking 应为有效库存');
|
||||||
|
assert.equal(captures.pickingRows[0].quantity, 5, 'picking 数量应为 5');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user