Compare commits

..

2 Commits

Author SHA1 Message Date
liufumingren
0c3aae0322 fix(receiving): 修复获取收货单时重复定义属性的问题 2026-04-30 19:23:26 +08:00
liufumingren
5ce689d771 1
Co-authored-by: Copilot <copilot@github.com>
2026-04-30 19:20:31 +08:00
22 changed files with 2534 additions and 282 deletions

View File

@ -39,6 +39,8 @@ module.exports = app => {
Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }), Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }),
Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }), Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }),
Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }), Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }),
Object.freeze({ code: 'receiving_rejected', name: '收货驳回', business: 'receiving', description: '收货单被驳回并恢复为收货中后的通知' }),
Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }),
Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }), Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }),
Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }),
Object.freeze({ Object.freeze({

View File

@ -1,6 +1,6 @@
// app/model/receiving.js // app/model/receiving.js
module.exports = app => { module.exports = app => {
const { STRING, INTEGER, DATE, TEXT, BOOLEAN, ENUM } = app.Sequelize; const { STRING, INTEGER, BIGINT, DATE, TEXT, BOOLEAN, ENUM, TINYINT } = app.Sequelize;
const Receiving = app.model.define('wms_receiving', { const Receiving = app.model.define('wms_receiving', {
id: { id: {
@ -108,6 +108,22 @@ module.exports = app => {
type: DATE, type: DATE,
comment: '收货结束时间', comment: '收货结束时间',
}, },
is_review: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否已审核:0-未审核,1-已审核',
},
reviewer_name: {
type: STRING(50),
allowNull: true,
comment: '审核人姓名',
},
reviewer_employee_id: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '审核人员工ID,关联 wms_account_store_employee.id',
},
is_deleted: { is_deleted: {
type: BOOLEAN, type: BOOLEAN,
defaultValue: false, defaultValue: false,

View File

@ -25,6 +25,14 @@ module.exports = app => {
required: false, required: false,
description: '收货上架时是否自动推荐库位', description: '收货上架时是否自动推荐库位',
}), }),
Object.freeze({
key: 'allow_receiving_quick_putaway',
name: '收货单快捷入库',
type: 'flag',
default: 0,
required: false,
description: '控制该货主在当前仓库下是否允许使用收货单快捷入库',
}),
Object.freeze({ Object.freeze({
key: 'allow_mix_batch', key: 'allow_mix_batch',
name: '允许混批', name: '允许混批',

View File

@ -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'; const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs';
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct'; const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs';
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct'; const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
} }
@ -128,13 +128,13 @@ class configService extends MainService {
} }
/** /**
* 保存收货单(兼容接口)。 * 保存收货单。
* @param {Object} data 请求体 * @param {Object} data 请求体
* @return {Promise<Object>} 统一成功包装响应 * @return {Promise<Object>} 统一成功包装响应
*/ */
async saveReceiving(data) { async save(data) {
const { service } = this; const { service } = this;
const result = await service.systems.storage.receiving.saveReceiving(data); const result = await service.systems.storage.receiving.save(data);
return this.success('ok', result); return this.success('ok', result);
} }
@ -206,5 +206,61 @@ class configService extends MainService {
const result = await service.systems.storage.receiving.completeReceiving(data); const result = await service.systems.storage.receiving.completeReceiving(data);
return this.success('ok', result); return this.success('ok', result);
} }
/**
* 驳回收货单:将已完成收货单恢复为收货中,记录审核人信息与驳回理由。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @param {string} [data.remark] 驳回理由(覆盖原备注)
* @return {Promise<Object>} 统一成功包装响应
*/
async rejectReceiving(data) {
const { service } = this;
const result = await service.systems.storage.receiving.rejectReceiving(data);
return this.success('ok', result);
}
/**
* 批量审核收货单。
* @param {Object} data 请求体
* @param {number[]} data.ids 收货单ID数组
* @return {Promise<Object>} 统一成功包装响应
*/
async reviewReceiving(data) {
const { service } = this;
const { ids } = data || {};
const result = await service.systems.storage.receiving.reviewReceiving({ ids });
return this.success('ok', result);
}
/**
* 查询收货单操作日志(分页)。
* @param {Object} data 请求体
* @param {number|string} [data.id] 收货单ID
* @param {number|string} [data.receiving_id] 收货单ID(兼容字段)
* @param {number} [data.page] 页码
* @param {number} [data.pageSize] 每页数量
* @param {Object} [data.pagination] 分页对象,支持 page/pageSize
* @return {Promise<Object>} 统一成功包装响应
*/
async queryReceivingLogs(data = {}) {
const { ctx, service } = this;
const requestData = data && typeof data === 'object' ? data : {};
const pagination = requestData.pagination && typeof requestData.pagination === 'object'
? requestData.pagination
: {};
const result = await service.systems.operationLog.queryReceivingLogs({
id: requestData.id || requestData.receiving_id,
page: requestData.page || pagination.page,
pageSize: requestData.pageSize || pagination.pageSize || pagination.page_size,
warehouseId: ctx.user.store_id,
});
return this.success('ok', {
data: result,
code: 200,
});
}
} }
module.exports = configService; module.exports = configService;

View File

@ -193,36 +193,6 @@ class warehouseService extends MainService {
this.fail(error.message); this.fail(error.message);
} }
} }
async createRack() {
const { ctx } = this;
const params = ctx.request.body;
// 验证参数
ctx.validate({
warehouse_id: { type: 'int', required: true },
zone_code: { type: 'string', required: true },
zone_name: { type: 'string', required: true },
parent_id: { type: 'int', required: false },
x: { type: 'int', required: true },
y: { type: 'int', required: true },
z: { type: 'int', required: false, default: 0 },
length: { type: 'int', required: true },
width: { type: 'int', required: true },
height: { type: 'int', required: true },
rack_columns: { type: 'int', required: true },
rack_rows: { type: 'int', required: true },
rack_levels: { type: 'int', required: true },
direction: { type: 'enum', values: [ 'north', 'south', 'east', 'west' ], required: false },
color: { type: 'string', required: false },
});
try {
const rack = await ctx.service.location.createRackWithSpaces(params);
ctx.success(rack, '货架创建成功');
} catch (error) {
this.fail(error.message, 400);
}
}
/** /**
* 获取拣货路径 * 获取拣货路径

View File

@ -3,6 +3,70 @@
const Service = require('egg').Service; const Service = require('egg').Service;
class LocationZoneService extends Service { class LocationZoneService extends Service {
async collectZoneSubtree(rootId, transaction) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const zoneIds = [ Number(rootId) ];
const zones = [];
let parentIds = [ Number(rootId) ];
while (parentIds.length > 0) {
const children = await ctx.model.LocationZone.findAll({
where: {
parent_id: {
[Op.in]: parentIds,
},
deleted_at: null,
},
raw: true,
transaction,
});
if (!Array.isArray(children) || children.length === 0) {
break;
}
zones.push(...children);
parentIds = children
.map(item => Number(item && item.id))
.filter(childId => Number.isFinite(childId) && childId > 0);
zoneIds.push(...parentIds);
}
return {
zoneIds,
zones,
};
}
async assertSpacesNotOccupied(spaceIds, transaction) {
if (!Array.isArray(spaceIds) || spaceIds.length === 0) {
return;
}
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const stockCount = await ctx.model.Storage.count({
where: {
space_id: {
[Op.in]: spaceIds,
},
delete_at: null,
is_enabled: 1,
[Op.or]: [
{ quantity: { [Op.gt]: 0 } },
{ locked_quantity: { [Op.gt]: 0 } },
{ available_quantity: { [Op.gt]: 0 } },
],
},
transaction,
});
if (stockCount > 0) {
throw new Error('删除范围内库位有库存,禁止删除,请先移库');
}
}
/** /**
* 获取所有仓库级别的分区列表 * 获取所有仓库级别的分区列表
* @param {number|string} warehouseId 仓库ID * @param {number|string} warehouseId 仓库ID
@ -759,53 +823,57 @@ class LocationZoneService extends Service {
if (!zone) { if (!zone) {
throw new Error('分区不存在'); throw new Error('分区不存在');
} }
// 检查是否有子分区
const childrenCount = await ctx.model.LocationZone.count({ await ctx.model.transaction(async transaction => {
where: {
parent_id: id,
deleted_at: null,
},
});
if (zone.zone_type === 'rack') {
// 货架执行删除前,按真实库存判断是否可删。
const { Op } = ctx.app.Sequelize; const { Op } = ctx.app.Sequelize;
const { zoneIds, zones } = await this.collectZoneSubtree(id, transaction);
const rackZoneIds = [ zone, ...zones ]
.filter(item => item && item.zone_type === 'rack')
.map(item => Number(item.id))
.filter(zoneId => Number.isFinite(zoneId) && zoneId > 0);
const spaceZoneIds = zone.zone_type === 'rack'
? zoneIds
: rackZoneIds;
const spaces = await ctx.model.LocationSpace.findAll({ const spaces = await ctx.model.LocationSpace.findAll({
where: { where: {
zone_id: id, zone_id: {
[Op.in]: spaceZoneIds,
},
deleted_at: null, deleted_at: null,
}, },
attributes: [ 'id' ], attributes: [ 'id' ],
raw: true, raw: true,
transaction,
}); });
const spaceIds = (Array.isArray(spaces) ? spaces : []) const spaceIds = (Array.isArray(spaces) ? spaces : [])
.map(space => Number(space && space.id)) .map(space => Number(space && space.id))
.filter(spaceId => Number.isFinite(spaceId) && spaceId > 0); .filter(spaceId => Number.isFinite(spaceId) && spaceId > 0);
await this.assertSpacesNotOccupied(spaceIds, transaction);
if (spaceIds.length > 0) { if (spaceIds.length > 0) {
const stockCount = await ctx.model.Storage.count({ await ctx.model.LocationSpace.destroy({
where: { where: {
space_id: { id: {
[Op.in]: spaceIds, [Op.in]: spaceIds,
}, },
delete_at: null, },
is_enabled: 1, transaction,
quantity: { });
[Op.gt]: 0, }
await ctx.model.LocationZone.destroy({
where: {
id: {
[Op.in]: zoneIds,
}, },
}, },
transaction,
});
}); });
if (stockCount > 0) {
throw new Error('货架库位有库存,禁止删除,请先移库');
}
}
}
if (childrenCount > 0) {
throw new Error('请先删除或转移所有子分区');
}
// 执行软删除
await zone.destroy();
return { return {
success: true, success: true,
message: '删除成功', message: '删除成功',

View File

@ -160,6 +160,19 @@ class operationLogService extends Service {
return await this.queryLogsByBusinessType(query, 'order'); return await this.queryLogsByBusinessType(query, 'order');
} }
/**
* 查询收货单操作日志。
* @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 queryReceivingLogs(query = {}) {
return await this.queryLogsByBusinessType(query, 'receiving');
}
async getMessageDetail(data) { async getMessageDetail(data) {
const { id, type } = data; const { id, type } = data;
const { ctx } = this; const { ctx } = this;

View File

@ -208,8 +208,9 @@ class InventoryService extends Service {
* *
* 流程: * 流程:
* 1. 校验收货单状态(必须 completed) * 1. 校验收货单状态(必须 completed)
* 2. 校验所有明细已匹配系统商品(system_product_id 不为空) * 2. 校验收货单已审核(is_review = 1)
* 3. 校验未全部入库(storage_status !== 'all') * 3. 校验所有明细已匹配系统商品(system_product_id 不为空)
* 4. 校验未全部入库(storage_status !== 'all')
* 4. 事务内: * 4. 事务内:
* a. 创建入库单(EntryOrder)和入库明细(EntryItems) * a. 创建入库单(EntryOrder)和入库明细(EntryItems)
* b. 逐条锁定 StockWarehouse 行,增加 quantity * b. 逐条锁定 StockWarehouse 行,增加 quantity
@ -257,6 +258,35 @@ class InventoryService extends Service {
await transaction.rollback(); await transaction.rollback();
return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null }; return { code: 400, message: `收货单状态为 ${receiving.status},须完成收货后才能入库`, data: null };
} }
if (Number(receiving.is_review) !== 1) {
await transaction.rollback();
return { code: 400, message: '收货单未审核,审核通过后才能入库', data: null };
}
const storeRelation = await ctx.model.StoreWarehouse.findOne({
where: {
warehouse_id: warehouseId,
store_id: Number(receiving.store_id || 0),
use_status: 1,
},
attributes: [ 'id', 'policy_config', 'store_remask' ],
lock: transaction.LOCK.UPDATE,
transaction,
});
if (!storeRelation) {
await transaction.rollback();
return { code: 404, message: '收货单绑定的货主与当前仓库不存在有效签约关系', data: null };
}
const policyConfig = storeRelation.policy_config && typeof storeRelation.policy_config === 'object'
? storeRelation.policy_config
: {};
if (Number(policyConfig.allow_receiving_quick_putaway) !== 1) {
const storeName = String(storeRelation.store_remask || receiving.store_name || receiving.store_id || '当前货主');
await transaction.rollback();
return { code: 400, message: `货主${storeName}不允许快速上架,如需开启请到:货主->策略配置调整`, data: null };
}
if (receiving.storage_status === 'all') { if (receiving.storage_status === 'all') {
await transaction.rollback(); await transaction.rollback();
@ -640,6 +670,16 @@ class InventoryService extends Service {
return { code: 404, message: '未找到符合条件的收货单', data: null }; return { code: 404, message: '未找到符合条件的收货单', data: null };
} }
const unreviewedReceiving = receivings.find(item => Number(item.is_review) !== 1);
if (unreviewedReceiving) {
await transaction.rollback();
return {
code: 400,
message: `收货单 ${unreviewedReceiving.receiving_number || unreviewedReceiving.id} 未审核,审核通过后才能入库`,
data: null,
};
}
// ────────── 4. 查询并锁定入库单 ────────── // ────────── 4. 查询并锁定入库单 ──────────
const entryOrders = await ctx.model.EntryOrder.findAll({ const entryOrders = await ctx.model.EntryOrder.findAll({
where: { where: {

File diff suppressed because it is too large Load Diff

View File

@ -6788,6 +6788,93 @@
} }
] ]
}, },
{
"method": "storage.receiving.rejectReceiving",
"description": "驳回收货单:将已完成(completed)的收货单批量恢复为收货中(receiving),记录驳回人信息和驳回理由。若任意一张收货单状态非 completed,则整批拒绝操作。驳回人信息(reviewer_name、reviewer_employee_id)自动取当前登录用户上下文,无需传入.",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "ids",
"type": "array",
"required": true,
"source": "body",
"description": "收货单ID数组,所有收货单必须属于当前仓库且状态为 completed,否则整批拒绝"
},
{
"name": "remark",
"type": "string",
"required": false,
"source": "body",
"description": "驳回理由,覆盖收货单原备注字段;不传则保留原备注"
}
],
"response": [
{
"name": "count",
"type": "number",
"description": "成功驳回的收货单数量"
}
],
"errors": [
{
"code": "0",
"description": "ids 为空、部分单据不存在/无权访问,或存在非 completed 状态的收货单"
},
{
"code": "500",
"description": "服务器错误"
}
]
},
{
"method": "storage.receiving.reviewReceiving",
"description": "批量审核收货单:校验所有单据满足条件(收货完成、全部匹配、未入库、已绑定货主、未审核)后统一审核,任意一张不符合则整批失败回滚。审核人信息自动取当前登录用户上下文,无需传入.",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "ids",
"type": "array",
"required": true,
"source": "body",
"description": "收货单ID数组,所有单据必须满足:status=completed、detail_status=all_matched、storage_status=none、store_id 已绑定、is_review=0,否则整批拒绝"
}
],
"response": [
{
"name": "count",
"type": "number",
"description": "成功审核的收货单数量"
}
],
"errors": [
{
"code": "0",
"description": "ids 为空、单据不存在/无权访问,或不满足审核条件(含并发冲突)"
},
{
"code": "500",
"description": "服务器错误,事务已回滚"
}
]
},
{ {
"method": "storage.receiving.create", "method": "storage.receiving.create",
"description": "storage.receiving.create 接口", "description": "storage.receiving.create 接口",
@ -7008,7 +7095,7 @@
"errors": [ "errors": [
{ {
"code": "400", "code": "400",
"description": "用户未绑定仓库、明细ID/商品ID为空,或收货单状态不允许绑定/改绑" "description": "用户未绑定仓库、明细ID/商品ID为空,收货单状态不允许绑定/改绑,或收货单已审核禁止绑定/改绑"
}, },
{ {
"code": "404", "code": "404",
@ -7020,6 +7107,81 @@
} }
] ]
}, },
{
"method": "storage.receiving.queryReceivingLogs",
"description": "按收货单ID查询操作日志列表(分页),仅返回当前仓库上下文数据",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "id",
"type": "number|string",
"required": false,
"source": "body",
"description": "收货单ID(与 receiving_id 二选一)"
},
{
"name": "receiving_id",
"type": "number|string",
"required": false,
"source": "body",
"description": "收货单ID(兼容字段,与 id 二选一)"
},
{
"name": "page",
"type": "number",
"required": false,
"source": "body",
"description": "页码(兼容顶层分页入参)"
},
{
"name": "pageSize",
"type": "number",
"required": false,
"source": "body",
"description": "每页数量(兼容顶层分页入参)"
},
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "分页参数,支持 page / pageSize"
}
],
"response": [
{
"name": "list",
"type": "array",
"required": true,
"description": "日志列表"
},
{
"name": "pagination",
"type": "object",
"required": true,
"description": "分页信息,包含 page、pageSize、total、totalPages"
}
],
"errors": [
{
"code": "400",
"description": "收货单ID为空或仓库上下文缺失"
},
{
"code": "500",
"description": "查询失败"
}
]
},
{ {
"method": "storage.receiving.addItem", "method": "storage.receiving.addItem",
"description": "storage.receiving.addItem 接口", "description": "storage.receiving.addItem 接口",
@ -7085,8 +7247,8 @@
"errors": [] "errors": []
}, },
{ {
"method": "storage.receiving.saveReceiving", "method": "storage.receiving.save",
"description": "storage.receiving.saveReceiving 接口", "description": "修改收货单基础信息。按收货单ID更新当前仓库下收货单的基础字段。",
"isNeedAuth": true, "isNeedAuth": true,
"isNeedLogin": true, "isNeedLogin": true,
"headers": [ "headers": [
@ -7097,9 +7259,125 @@
"description": "Bearer token" "description": "Bearer token"
} }
], ],
"params": [], "params": [
"response": [], {
"errors": [] "name": "id",
"type": "number",
"required": true,
"source": "body",
"description": "收货单ID,按该ID修改当前仓库下的收货单"
},
{
"name": "delivery_method",
"type": "string",
"required": false,
"source": "body",
"description": "到货方式:truck/express/air_freight/sea_freight/other;不传则保持原值"
},
{
"name": "loading_method",
"type": "string",
"required": false,
"source": "body",
"description": "装卸方式:with_pallet/without_pallet;不传则保持原值"
},
{
"name": "license_plate",
"type": "string",
"required": false,
"source": "body",
"description": "车牌号;当 delivery_method=truck 时可更新,其他到货方式会被清空或忽略"
},
{
"name": "tracking_number",
"type": "string",
"required": false,
"source": "body",
"description": "物流单号;当 delivery_method 为 express/air_freight/sea_freight 时可更新,truck/other 场景会被清空或忽略"
},
{
"name": "store_id",
"type": "number",
"required": false,
"source": "body",
"description": "货主ID;若传入,会校验当前仓库下签约关系并同步更新货主名称;传 0/null 可清空货主"
},
{
"name": "total_boxes",
"type": "number",
"required": false,
"source": "body",
"description": "总箱数,默认 0"
},
{
"name": "total_pallets",
"type": "number",
"required": false,
"source": "body",
"description": "总托盘数,默认 0"
},
{
"name": "remark",
"type": "string",
"required": false,
"source": "body",
"description": "备注信息"
},
{
"name": "status",
"type": "string",
"required": false,
"source": "body",
"description": "收货单状态;不传则保持原值"
},
{
"name": "video_device_id",
"type": "string",
"required": false,
"source": "body",
"description": "录像设备ID"
}
],
"response": [
{
"name": "code",
"type": "number",
"required": true,
"description": "业务状态码;200 表示修改成功"
},
{
"name": "id",
"type": "number",
"required": true,
"description": "修改的收货单ID"
},
{
"name": "receiving_number",
"type": "string",
"required": true,
"description": "收货单号"
},
{
"name": "message",
"type": "string",
"required": true,
"description": "结果描述;成功时通常为收货单修改成功"
}
],
"errors": [
{
"code": "400",
"description": "收货单ID不能为空、已取消的收货单不允许修改或用户未绑定仓库"
},
{
"code": "404",
"description": "收货单不存在/无权访问,或指定货主不存在/未与当前仓库建立有效签约关系"
},
{
"code": "0",
"description": "修改失败,如字段枚举不合法或数据库写入异常"
}
]
}, },
{ {
"method": "storage.receiving.get", "method": "storage.receiving.get",
@ -7788,7 +8066,7 @@
"list": [ "list": [
{ {
"method": "storage.inventory.quickPutaway", "method": "storage.inventory.quickPutaway",
"description": "收货单快捷入库上架。从收货单直接生成入库单并写入库存表,要求收货单已完成且所有明细已匹配系统商品", "description": "收货单快捷入库上架。从收货单直接生成入库单并写入库存表,要求收货单已完成、已审核、货主已开启快捷入库策略且所有明细已匹配系统商品",
"isNeedAuth": true, "isNeedAuth": true,
"isNeedLogin": true, "isNeedLogin": true,
"params": [ "params": [
@ -7829,10 +8107,22 @@
"code": 400, "code": 400,
"message": "收货单状态须为已完成" "message": "收货单状态须为已完成"
}, },
{
"code": 400,
"message": "收货单未审核,审核通过后才能入库"
},
{
"code": 400,
"message": "货主xxxx不允许快速上架,如需开启请到:货主->策略配置调整"
},
{ {
"code": 400, "code": 400,
"message": "商品未匹配系统商品" "message": "商品未匹配系统商品"
}, },
{
"code": 404,
"message": "收货单绑定的货主与当前仓库不存在有效签约关系"
},
{ {
"code": 400, "code": 400,
"message": "已全部入库无需重复操作" "message": "已全部入库无需重复操作"
@ -7849,7 +8139,7 @@
}, },
{ {
"method": "storage.inventory.matchPutaway", "method": "storage.inventory.matchPutaway",
"description": "收货单与入库单匹配入库。接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完成后根据入库单来源(QM/API)自动触发回传", "description": "收货单与入库单匹配入库。接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,要求收货单已完成且已审核,完成后根据入库单来源(QM/API)自动触发回传",
"isNeedAuth": true, "isNeedAuth": true,
"isNeedLogin": true, "isNeedLogin": true,
"params": [ "params": [
@ -7902,6 +8192,10 @@
"code": 404, "code": 404,
"message": "收货单不存在或无权访问" "message": "收货单不存在或无权访问"
}, },
{
"code": 400,
"message": "收货单未审核,审核通过后才能入库"
},
{ {
"code": 404, "code": 404,
"message": "入库单不存在或无权访问" "message": "入库单不存在或无权访问"
@ -9771,129 +10065,6 @@
"response": [], "response": [],
"errors": [] "errors": []
}, },
{
"method": "warehouse.createRack",
"description": "warehouse.createRack 接口",
"isNeedAuth": true,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "height",
"type": "number",
"required": true,
"source": "body",
"description": "height 参数"
},
{
"name": "length",
"type": "number",
"required": true,
"source": "body",
"description": "length 参数"
},
{
"name": "rack_columns",
"type": "number",
"required": true,
"source": "body",
"description": "rack_columns 参数"
},
{
"name": "rack_levels",
"type": "number",
"required": true,
"source": "body",
"description": "rack_levels 参数"
},
{
"name": "rack_rows",
"type": "number",
"required": true,
"source": "body",
"description": "rack_rows 参数"
},
{
"name": "warehouse_id",
"type": "number",
"required": true,
"source": "body",
"description": "warehouse_id 参数"
},
{
"name": "width",
"type": "number",
"required": true,
"source": "body",
"description": "width 参数"
},
{
"name": "x",
"type": "number",
"required": true,
"source": "body",
"description": "x 参数"
},
{
"name": "y",
"type": "number",
"required": true,
"source": "body",
"description": "y 参数"
},
{
"name": "zone_code",
"type": "string",
"required": true,
"source": "body",
"description": "zone_code 参数"
},
{
"name": "zone_name",
"type": "string",
"required": true,
"source": "body",
"description": "zone_name 参数"
},
{
"name": "color",
"type": "string",
"required": false,
"source": "body",
"description": "color 参数"
},
{
"name": "direction",
"type": "string",
"required": false,
"source": "body",
"description": "direction 参数"
},
{
"name": "parent_id",
"type": "number",
"required": false,
"source": "body",
"description": "parent_id 参数"
},
{
"name": "z",
"type": "number",
"required": false,
"source": "body",
"description": "z 参数"
}
],
"response": [],
"errors": []
},
{ {
"method": "warehouse.getPickPath", "method": "warehouse.getPickPath",
"description": "warehouse.getPickPath 接口", "description": "warehouse.getPickPath 接口",

View File

@ -3,5 +3,5 @@
"offset": 18973, "offset": 18973,
"processedCount": 7, "processedCount": 7,
"completedAt": "2026-04-27T13:30:41.800Z", "completedAt": "2026-04-27T13:30:41.800Z",
"updatedAt": "2026-04-29T09:42:51.811Z" "updatedAt": "2026-04-30T11:23:00.124Z"
} }

View File

@ -146,6 +146,17 @@ async function completeReceiving(token, receivingId) {
assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`);
} }
async function reviewReceiving(token, receivingId) {
const res = await invokeSystemMethod('storage.receiving.reviewReceiving', {
ids: [ receivingId ],
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200, `审核收货单HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `审核收货单失败: ${res.body.message}`);
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 200, `审核收货单业务失败: ${JSON.stringify(res.body)}`);
}
// ──── 创建测试入库单(直接数据库插入) ──── // ──── 创建测试入库单(直接数据库插入) ────
async function createTestEntryOrder(sequelize, { warehouseId, storeId, items }) { async function createTestEntryOrder(sequelize, { warehouseId, storeId, items }) {
const code = `TEST-ENTRY-${Date.now()}`; const code = `TEST-ENTRY-${Date.now()}`;
@ -204,7 +215,41 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 1. 精确匹配:收货量 = 入库计划量 // 1. 未审核拒绝
// ──────────────────────────────────────────────────────
it('should reject matchPutaway for unreviewed receiving', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
const entryOrder = await createTestEntryOrder(sequelize, {
warehouseId: TEST_WAREHOUSE_ID,
storeId: TEST_STORE_ID,
items: [{
id: products[0].id,
item_code: products[0].item_code,
quantity: 2,
}],
});
const res = await matchPutaway(authToken, [ receivingId ], [ entryOrder.id ]);
console.log('[UNREVIEWED] matchPutaway 响应:', JSON.stringify(res.body, null, 2));
assert.equal(res.status, 200, `matchPutaway HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `matchPutaway flag失败: ${res.body.message}`);
const resultData = res.body?.data?.data || res.body?.data || {};
const resCode = Number(resultData.code || res.body?.code || 0);
assert.equal(resCode, 400, `未审核收货单应返回 400, 实际: ${resCode}`);
const message = String(resultData.message || res.body?.message || '');
assert.ok(message.includes('未审核'), `message 应包含"未审核", 实际: ${message}`);
});
// ──────────────────────────────────────────────────────
// 2. 精确匹配:收货量 = 入库计划量
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should match putaway when receiving equals entry order (exact match)', async function() { it('should match putaway when receiving equals entry order (exact match)', async function() {
this.timeout(60000); this.timeout(60000);
@ -222,6 +267,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
console.log(`[EXACT] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`); console.log(`[EXACT] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, qty=${quantities[i]}`);
} }
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量与收货完全一致) // 2. 创建入库单(数量与收货完全一致)
const entryOrder = await createTestEntryOrder(sequelize, { const entryOrder = await createTestEntryOrder(sequelize, {
@ -280,7 +326,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 2. 收货 > 入库计划(部分匹配,有剩余) // 3. 收货 > 入库计划(部分匹配,有剩余)
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should handle receiving > entry order (partial match with surplus)', async function() { it('should handle receiving > entry order (partial match with surplus)', async function() {
this.timeout(60000); this.timeout(60000);
@ -299,6 +345,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
console.log(`[SURPLUS] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`); console.log(`[SURPLUS] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`);
} }
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量 10, 5 — 小于收货量) // 2. 创建入库单(数量 10, 5 — 小于收货量)
const entryOrder = await createTestEntryOrder(sequelize, { const entryOrder = await createTestEntryOrder(sequelize, {
@ -355,7 +402,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 3. 收货 < 入库计划(收货不足) // 4. 收货 < 入库计划(收货不足)
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should handle receiving < entry order (insufficient receiving)', async function() { it('should handle receiving < entry order (insufficient receiving)', async function() {
this.timeout(60000); this.timeout(60000);
@ -374,6 +421,7 @@ describe('test/app/controller/system.storage.inventory.matchPutaway.test.js', ()
console.log(`[INSUF] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`); console.log(`[INSUF] 明细 ${i + 1}: detailId=${detailId}, product=${products[i].item_name}, rcvQty=${rcvQuantities[i]}`);
} }
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 2. 创建入库单(数量 10, 8 — 大于收货量) // 2. 创建入库单(数量 10, 8 — 大于收货量)
const entryOrder = await createTestEntryOrder(sequelize, { const entryOrder = await createTestEntryOrder(sequelize, {

View File

@ -104,6 +104,39 @@ async function bindStore(token, receivingId) {
assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`);
} }
async function setQuickPutawayPolicy(enabled) {
const [ rows ] = await sequelize.query(
'SELECT id, policy_config FROM wms_store_warehouse WHERE store_id = :storeId AND warehouse_id = :warehouseId AND use_status = 1 LIMIT 1',
{
replacements: {
storeId: TEST_STORE_ID,
warehouseId: TEST_WAREHOUSE_ID,
},
}
);
assert.ok(Array.isArray(rows) && rows.length === 1, '未找到可用的货主仓库签约关系');
let policyConfig = {};
const rawPolicyConfig = rows[0].policy_config;
if (rawPolicyConfig && typeof rawPolicyConfig === 'string') {
policyConfig = JSON.parse(rawPolicyConfig);
} else if (rawPolicyConfig && typeof rawPolicyConfig === 'object') {
policyConfig = { ...rawPolicyConfig };
}
policyConfig.allow_receiving_quick_putaway = enabled ? 1 : 0;
await sequelize.query(
'UPDATE wms_store_warehouse SET policy_config = :policyConfig, updated_at = NOW() WHERE id = :id',
{
replacements: {
id: rows[0].id,
policyConfig: JSON.stringify(policyConfig),
},
}
);
}
// ──── 添加明细 + 修改明细 + 绑定商品 ──── // ──── 添加明细 + 修改明细 + 绑定商品 ────
async function addAndFillDetail(token, receivingId, product, qty) { async function addAndFillDetail(token, receivingId, product, qty) {
// addDetail // addDetail
@ -154,7 +187,7 @@ async function completeReceiving(token, receivingId) {
{ {
replacements: { replacements: {
status: 'completed', status: 'completed',
storageStatus: 'partial', storageStatus: 'none',
receivingId, receivingId,
}, },
} }
@ -162,6 +195,17 @@ async function completeReceiving(token, receivingId) {
} }
} }
async function reviewReceiving(token, receivingId) {
const res = await invokeSystemMethod('storage.receiving.reviewReceiving', {
ids: [ receivingId ],
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200, `审核收货单HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `审核收货单失败: ${res.body.message}`);
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 200, `审核收货单业务失败: ${JSON.stringify(res.body)}`);
}
// ──── 快捷入库 ──── // ──── 快捷入库 ────
async function quickPutaway(token, receivingId) { async function quickPutaway(token, receivingId) {
return invokeSystemMethod('storage.inventory.quickPutaway', { return invokeSystemMethod('storage.inventory.quickPutaway', {
@ -196,13 +240,63 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 1. 部分匹配拒绝 // 1. 未审核拒绝
// ──────────────────────────────────────────────────────
it('should reject quickPutaway for unreviewed receiving', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(false);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
const res = await quickPutaway(authToken, receivingId);
console.log('[UNREVIEWED] quickPutaway 响应:', JSON.stringify(res.body, null, 2));
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 400, `未审核收货单应返回 400, 实际: ${resCode}`);
const message = String(res.body?.data?.message || res.body?.message || '');
assert.ok(message.includes('未审核'), `message 应包含"未审核", 实际: ${message}`);
});
// ──────────────────────────────────────────────────────
// 2. 货主策略未开启拒绝
// ──────────────────────────────────────────────────────
it('should reject quickPutaway when store policy disallows receiving quick putaway', async function() {
this.timeout(60000);
const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(false);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
const res = await quickPutaway(authToken, receivingId);
console.log('[POLICY] quickPutaway 响应:', JSON.stringify(res.body, null, 2));
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 400, `未开启快捷入库策略应返回 400, 实际: ${resCode}`);
const message = String(res.body?.data?.message || res.body?.message || '');
assert.ok(message.includes('货主'), `message 应包含"货主", 实际: ${message}`);
assert.ok(message.includes('不允许快速上架'), `message 应包含"不允许快速上架", 实际: ${message}`);
assert.ok(message.includes('货主->策略配置调整'), `message 应包含"货主->策略配置调整", 实际: ${message}`);
});
// ──────────────────────────────────────────────────────
// 3. 部分匹配拒绝
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should reject quickPutaway for partially matched receiving', async function() { it('should reject quickPutaway for partially matched receiving', async function() {
this.timeout(60000); this.timeout(60000);
const receivingId = await createReceiving(authToken); const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId); await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[PARTIAL] 收货单 ID: ${receivingId}`); console.log(`[PARTIAL] 收货单 ID: ${receivingId}`);
// 添加 3 条明细 // 添加 3 条明细
@ -221,6 +315,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 完成收货 // 完成收货
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 快捷入库 → 应被拒绝 // 快捷入库 → 应被拒绝
const res = await quickPutaway(authToken, receivingId); const res = await quickPutaway(authToken, receivingId);
@ -233,13 +328,14 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 2. 全匹配成功 // 4. 全匹配成功
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should complete quickPutaway for fully matched receiving', async function() { it('should complete quickPutaway for fully matched receiving', async function() {
this.timeout(60000); this.timeout(60000);
const receivingId = await createReceiving(authToken); const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId); await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[FULL] 收货单 ID: ${receivingId}`); console.log(`[FULL] 收货单 ID: ${receivingId}`);
// 添加 2 条明细,全部绑定商品 // 添加 2 条明细,全部绑定商品
@ -254,6 +350,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 完成收货 // 完成收货
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 快捷入库 // 快捷入库
const res = await quickPutaway(authToken, receivingId); const res = await quickPutaway(authToken, receivingId);
@ -302,7 +399,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 3. 数据库行锁冲突 → 409 // 5. 数据库行锁冲突 → 409
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should return 409 when stock row is locked by concurrent transaction', async function() { it('should return 409 when stock row is locked by concurrent transaction', async function() {
this.timeout(120000); this.timeout(120000);
@ -316,9 +413,11 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 先准备好收货单数据 // 先准备好收货单数据
const receivingId = await createReceiving(authToken); const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId); await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
const detailId = await addAndFillDetail(authToken, receivingId, products[0], 1); const detailId = await addAndFillDetail(authToken, receivingId, products[0], 1);
await bindDetailProduct(authToken, detailId, products[0].id); await bindDetailProduct(authToken, detailId, products[0].id);
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 开事务锁行 // 开事务锁行
lockTx = await sequelize.transaction(); lockTx = await sequelize.transaction();
@ -356,13 +455,14 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 4. 无锁冲突正常入库 // 6. 无锁冲突正常入库
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should complete quickPutaway without lock contention', async function() { it('should complete quickPutaway without lock contention', async function() {
this.timeout(60000); this.timeout(60000);
const receivingId = await createReceiving(authToken); const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId); await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[NOLOCK] 收货单 ID: ${receivingId}`); console.log(`[NOLOCK] 收货单 ID: ${receivingId}`);
// 添加 2 条明细,全部绑定 // 添加 2 条明细,全部绑定
@ -377,6 +477,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
// 完成收货 → 快捷入库 // 完成收货 → 快捷入库
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
const res = await quickPutaway(authToken, receivingId); const res = await quickPutaway(authToken, receivingId);
console.log('[NOLOCK] quickPutaway 响应:', JSON.stringify(res.body, null, 2)); console.log('[NOLOCK] quickPutaway 响应:', JSON.stringify(res.body, null, 2));
@ -402,13 +503,14 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
}); });
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
// 5. 空批次回退 + 批次日期落库存 // 7. 空批次回退 + 批次日期落库存
// ────────────────────────────────────────────────────── // ──────────────────────────────────────────────────────
it('should fallback to receiving number when batch is empty and persist batch dates into storage', async function() { it('should fallback to receiving number when batch is empty and persist batch dates into storage', async function() {
this.timeout(60000); this.timeout(60000);
const receivingId = await createReceiving(authToken); const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId); await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[BATCH] 收货单 ID: ${receivingId}`); console.log(`[BATCH] 收货单 ID: ${receivingId}`);
const firstDetailId = await addAndFillDetail(authToken, receivingId, products[0], 2); const firstDetailId = await addAndFillDetail(authToken, receivingId, products[0], 2);
@ -428,6 +530,7 @@ describe('test/app/controller/system.storage.inventory.quickPutaway.test.js', ()
await bindDetailProduct(authToken, secondDetailId, products[0].id); await bindDetailProduct(authToken, secondDetailId, products[0].id);
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', { const detailRes = await invokeSystemMethod('storage.receiving.getReceivingDetail', {
id: receivingId, id: receivingId,

View File

@ -336,6 +336,18 @@ describe('test/app/controller/system.storage.receiving.test.js', () => {
const detailId = Number(addDetailRes.body?.data?.data?.selectId || addDetailRes.body?.data?.selectId || 0); const detailId = Number(addDetailRes.body?.data?.data?.selectId || addDetailRes.body?.data?.selectId || 0);
assert.ok(detailId > 0, '新增收货单明细后未返回有效 detail_id'); assert.ok(detailId > 0, '新增收货单明细后未返回有效 detail_id');
const detailChangeRes = await invokeSystemMethod('storage.receiving.detailChange', {
id: detailId,
receiving_id: createdId,
product_name: '审核前绑定测试商品',
barcode: `IDR-BC-${Date.now().toString().slice(-6)}`,
actual_quantity: 1,
box_quantity: 1,
pallet_quantity: 0,
}, switched.token, EXTRA_HEADERS);
assert.equal(detailChangeRes.status, 200);
assert.equal(detailChangeRes.body.flag, 'success');
const sortedProducts = [ ...systemProducts ].sort((left, right) => Number(left.id) - Number(right.id)); const sortedProducts = [ ...systemProducts ].sort((left, right) => Number(left.id) - Number(right.id));
const firstProduct = sortedProducts[0]; const firstProduct = sortedProducts[0];
const secondProduct = sortedProducts[1]; const secondProduct = sortedProducts[1];

View File

@ -16,6 +16,7 @@ const TEST_WAREHOUSE_ID = 100000;
const dbConfig = require('../../../database/config'); const dbConfig = require('../../../database/config');
const env = process.env.NODE_ENV || 'development'; const env = process.env.NODE_ENV || 'development';
const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0]; const config = dbConfig[env] || dbConfig.development || Object.values(dbConfig)[0];
let sequelize;
// ──── switchToWarehouseRole ──── // ──── switchToWarehouseRole ────
async function switchToWarehouseRole(token) { async function switchToWarehouseRole(token) {
@ -103,6 +104,39 @@ async function bindStore(token, receivingId) {
assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`); assert.equal(res.body.flag, 'success', `绑定货主失败: ${res.body.message}`);
} }
async function setQuickPutawayPolicy(enabled) {
const [ rows ] = await sequelize.query(
'SELECT id, policy_config FROM wms_store_warehouse WHERE store_id = :storeId AND warehouse_id = :warehouseId AND use_status = 1 LIMIT 1',
{
replacements: {
storeId: TEST_STORE_ID,
warehouseId: TEST_WAREHOUSE_ID,
},
}
);
assert.ok(Array.isArray(rows) && rows.length === 1, '未找到可用的货主仓库签约关系');
let policyConfig = {};
const rawPolicyConfig = rows[0].policy_config;
if (rawPolicyConfig && typeof rawPolicyConfig === 'string') {
policyConfig = JSON.parse(rawPolicyConfig);
} else if (rawPolicyConfig && typeof rawPolicyConfig === 'object') {
policyConfig = { ...rawPolicyConfig };
}
policyConfig.allow_receiving_quick_putaway = enabled ? 1 : 0;
await sequelize.query(
'UPDATE wms_store_warehouse SET policy_config = :policyConfig, updated_at = NOW() WHERE id = :id',
{
replacements: {
id: rows[0].id,
policyConfig: JSON.stringify(policyConfig),
},
}
);
}
// ──── 添加明细 + 修改明细 ──── // ──── 添加明细 + 修改明细 ────
async function addAndFillDetail(token, receivingId, product, qty) { async function addAndFillDetail(token, receivingId, product, qty) {
const addRes = await invokeSystemMethod('storage.receiving.addDetail', { const addRes = await invokeSystemMethod('storage.receiving.addDetail', {
@ -146,6 +180,16 @@ async function completeReceiving(token, receivingId) {
assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`); assert.equal(res.body.flag, 'success', `完成收货失败: ${res.body.message}`);
} }
async function reviewReceiving(token, receivingId) {
const res = await invokeSystemMethod('storage.receiving.reviewReceiving', {
ids: [ receivingId ],
}, token, EXTRA_HEADERS);
assert.equal(res.status, 200, `审核收货单HTTP失败: ${JSON.stringify(res.body)}`);
assert.equal(res.body.flag, 'success', `审核收货单失败: ${res.body.message}`);
const resCode = Number(res.body?.data?.code || res.body?.code || 0);
assert.equal(resCode, 200, `审核收货单业务失败: ${JSON.stringify(res.body)}`);
}
// ──── 快捷入库 ──── // ──── 快捷入库 ────
async function quickPutaway(token, receivingId) { async function quickPutaway(token, receivingId) {
return invokeSystemMethod('storage.inventory.quickPutaway', { return invokeSystemMethod('storage.inventory.quickPutaway', {
@ -156,7 +200,6 @@ async function quickPutaway(token, receivingId) {
describe('test/app/controller/system.storage.transaction.test.js', () => { describe('test/app/controller/system.storage.transaction.test.js', () => {
let authToken; let authToken;
let products; let products;
let sequelize;
before(async function() { before(async function() {
this.timeout(30000); this.timeout(30000);
@ -191,6 +234,7 @@ describe('test/app/controller/system.storage.transaction.test.js', () => {
// === 准备阶段 === // === 准备阶段 ===
const receivingId = await createReceiving(authToken); const receivingId = await createReceiving(authToken);
await bindStore(authToken, receivingId); await bindStore(authToken, receivingId);
await setQuickPutawayPolicy(true);
console.log(`[TX] 收货单 ID: ${receivingId}`); console.log(`[TX] 收货单 ID: ${receivingId}`);
const quantities = [ 7, 3 ]; const quantities = [ 7, 3 ];
@ -203,6 +247,7 @@ describe('test/app/controller/system.storage.transaction.test.js', () => {
} }
await completeReceiving(authToken, receivingId); await completeReceiving(authToken, receivingId);
await reviewReceiving(authToken, receivingId);
// 记录入库前的 transaction 最大 ID,用于过滤 // 记录入库前的 transaction 最大 ID,用于过滤
const [ beforeRows ] = await sequelize.query( const [ beforeRows ] = await sequelize.query(

View File

@ -0,0 +1,73 @@
'use strict';
const assert = require('node:assert/strict');
const StorageReceivingService = require('../../../../../app/service/systemMethods/storage/receiving');
function createHarness(storeId = 100321) {
const calls = {};
const ctx = {
app: {
config: {},
},
user: {
store_id: storeId,
},
service: {
systems: {
operationLog: {
async queryReceivingLogs(query) {
calls.queryReceivingLogs = query;
return {
list: [{ id: 1 }],
pagination: {
page: Number(query.page || 1),
pageSize: Number(query.pageSize || 20),
total: 1,
totalPages: 1,
},
};
},
},
},
},
};
return {
service: new StorageReceivingService(ctx),
calls,
};
}
describe('test/app/service/systemMethods/storage/queryReceivingLogs.test.js', () => {
it('should inject current store_id and support pagination object', async () => {
const { service, calls } = createHarness(100321);
const result = await service.queryReceivingLogs({
receiving_id: 99,
pagination: {
page: 3,
pageSize: 15,
},
});
assert.deepEqual(calls.queryReceivingLogs, {
id: 99,
page: 3,
pageSize: 15,
warehouseId: 100321,
});
assert.equal(result.flag, 'success');
assert.equal(result.message, 'ok');
assert.equal(result.code, 200);
assert.deepEqual(result.data, {
list: [{ id: 1 }],
pagination: {
page: 3,
pageSize: 15,
total: 1,
totalPages: 1,
},
});
});
});

View File

@ -0,0 +1,198 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const LocationZoneService = require('../../../../app/service/systems/location_zone');
function createHarness(options = {}) {
const calls = {
transactionCalls: 0,
zoneDestroyQueries: [],
spaceDestroyQueries: [],
storageCountQueries: [],
};
const zoneRows = (options.zones || []).map(item => ({
...item,
deleted_at: item.deleted_at || null,
}));
const spaceRows = (options.spaces || []).map(item => ({
...item,
deleted_at: item.deleted_at || null,
}));
const storageRows = (options.storages || []).map(item => ({
delete_at: null,
is_enabled: 1,
quantity: 0,
locked_quantity: 0,
available_quantity: 0,
...item,
}));
const ctx = {
logger: {
error() {},
},
app: {
Sequelize: {
Op,
},
},
model: {
async transaction(handler) {
calls.transactionCalls += 1;
const transaction = {
async commit() {},
async rollback() {},
};
if (typeof handler === 'function') {
return await handler(transaction);
}
return transaction;
},
LocationZone: {
async findOne({ where = {} }) {
return zoneRows.find(row => (
Number(row.id) === Number(where.id) &&
(where.deleted_at !== null ? row.deleted_at === null : true)
)) || null;
},
async findAll({ where = {}, raw = false }) {
let rows = zoneRows.filter(row => row.deleted_at === null);
if (where.parent_id && where.parent_id[Op.in]) {
const parentIds = where.parent_id[Op.in].map(item => Number(item));
rows = rows.filter(row => parentIds.includes(Number(row.parent_id)));
} else if (Object.prototype.hasOwnProperty.call(where, 'parent_id')) {
rows = rows.filter(row => Number(row.parent_id) === Number(where.parent_id));
}
return raw ? rows.map(row => ({ ...row })) : rows.map(row => ({ ...row }));
},
async destroy({ where = {} }) {
calls.zoneDestroyQueries.push(where);
const ids = where.id && where.id[Op.in]
? where.id[Op.in].map(item => Number(item))
: [];
zoneRows.forEach(row => {
if (ids.includes(Number(row.id))) {
row.deleted_at = new Date();
}
});
return ids.length;
},
},
LocationSpace: {
async findAll({ where = {}, raw = false }) {
let rows = spaceRows.filter(row => row.deleted_at === null);
if (where.zone_id && where.zone_id[Op.in]) {
const zoneIds = where.zone_id[Op.in].map(item => Number(item));
rows = rows.filter(row => zoneIds.includes(Number(row.zone_id)));
} else if (Object.prototype.hasOwnProperty.call(where, 'zone_id')) {
rows = rows.filter(row => Number(row.zone_id) === Number(where.zone_id));
}
return raw ? rows.map(row => ({ ...row })) : rows.map(row => ({ ...row }));
},
async destroy({ where = {} }) {
calls.spaceDestroyQueries.push(where);
const ids = where.id && where.id[Op.in]
? where.id[Op.in].map(item => Number(item))
: [];
spaceRows.forEach(row => {
if (ids.includes(Number(row.id))) {
row.deleted_at = new Date();
}
});
return ids.length;
},
},
Storage: {
async count({ where = {} }) {
calls.storageCountQueries.push(where);
const spaceIds = where.space_id && where.space_id[Op.in]
? where.space_id[Op.in].map(item => Number(item))
: [];
return storageRows.filter(row => {
if (!spaceIds.includes(Number(row.space_id))) {
return false;
}
if (row.delete_at !== null) {
return false;
}
if (Number(row.is_enabled) !== 1) {
return false;
}
return Number(row.quantity) > 0 || Number(row.locked_quantity) > 0 || Number(row.available_quantity) > 0;
}).length;
},
},
},
};
return {
service: new LocationZoneService(ctx),
zoneRows,
spaceRows,
calls,
};
}
describe('test/app/service/systems/location_zone.deleteZone.test.js', () => {
it('should cascade soft delete descendant racks and spaces when deleting an area', async () => {
const { service, zoneRows, spaceRows, calls } = createHarness({
zones: [
{ id: 10, parent_id: 1, zone_type: 'area' },
{ id: 11, parent_id: 10, zone_type: 'rack' },
{ id: 12, parent_id: 11, zone_type: 'obstacle' },
],
spaces: [
{ id: 101, zone_id: 11 },
{ id: 102, zone_id: 11 },
],
});
const result = await service.deleteZone(10);
assert.equal(result.success, true);
assert.equal(result.message, '删除成功');
assert.equal(calls.transactionCalls, 1);
assert.deepEqual(calls.spaceDestroyQueries[0].id[Op.in], [ 101, 102 ]);
assert.deepEqual(calls.zoneDestroyQueries[0].id[Op.in], [ 10, 11, 12 ]);
assert.equal(zoneRows.every(row => row.deleted_at instanceof Date), true);
assert.equal(spaceRows.every(row => row.deleted_at instanceof Date), true);
});
it('should reject deleting a rack when any affected space still has stock', async () => {
const { service, zoneRows, spaceRows, calls } = createHarness({
zones: [
{ id: 20, parent_id: 2, zone_type: 'rack' },
],
spaces: [
{ id: 201, zone_id: 20 },
],
storages: [
{ id: 1, space_id: 201, quantity: 3 },
],
});
await assert.rejects(async () => {
await service.deleteZone(20);
}, /删除范围内库位有库存,禁止删除,请先移库/);
assert.equal(calls.transactionCalls, 1);
assert.equal(calls.spaceDestroyQueries.length, 0);
assert.equal(calls.zoneDestroyQueries.length, 0);
assert.equal(zoneRows[0].deleted_at, null);
assert.equal(spaceRows[0].deleted_at, null);
});
});

View File

@ -106,4 +106,35 @@ describe('test/app/service/systems/operation_log.queryOrderLogs.test.js', () =>
assert.equal(result.list[0].platform_name, 'platform:pda'); assert.equal(result.list[0].platform_name, 'platform:pda');
assert.equal(result.list[0].created_at, 'formatted:2026-04-19 12:00:00'); assert.equal(result.list[0].created_at, 'formatted:2026-04-19 12:00:00');
}); });
it('should query receiving logs with business_type receiving', async () => {
const { service, calls } = createServiceHarness({
count: 5,
rows: [{
id: 3,
operation_code: 'RECEIVING_REVIEW',
operator_name: 'Alice',
created_at: '2026-04-19 13:00:00',
external_log_type: 'NONE',
external_log_id: null,
platform_code: 'web',
message: 'reviewed',
}],
});
const result = await service.queryReceivingLogs({
id: 501,
warehouseId: 100000,
page: 1,
pageSize: 20,
});
assert.deepEqual(calls.findAndCountAllArgs.where, {
business_type: 'receiving',
business_id: 501,
warehouse_id: 100000,
});
assert.equal(result.pagination.total, 5);
assert.equal(result.list[0].operation_name, 'name:RECEIVING_REVIEW');
});
}); });

View File

@ -0,0 +1,102 @@
'use strict';
const assert = require('node:assert/strict');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createHarness(overrides = {}) {
const calls = {
stockWarehouseFindOne: 0,
};
const receivingDetail = {
id: 1001,
receiving_id: 5001,
receiving: {
id: 5001,
warehouse_id: 100000,
store_id: 1000000,
store_name: '测试货主',
status: 'completed',
is_review: 1,
...(overrides.receiving || {}),
},
};
const ctx = {
user: {
store_id: 100000,
employees_id: 9001,
employees_name: '测试员',
id: 9001,
},
logger: {
error() {},
warn() {},
info() {},
},
service: {
systems: {
operationLog: {
async createOperationLog() {},
},
},
},
};
const app = {
model: {
ReceivingDetail: {
async findOne() {
return receivingDetail;
},
},
StockWarehouse: {
async findOne() {
calls.stockWarehouseFindOne += 1;
return null;
},
},
},
};
ctx.app = app;
const service = new ReceivingService(ctx);
return {
service,
calls,
};
}
describe('test/app/service/systems/storage.receiving.bindDetailProduct.test.js', () => {
it('should reject binding when receiving is already reviewed', async () => {
const { service, calls } = createHarness();
const result = await service.bindDetailProduct({
detail_id: 1001,
system_product_id: 2001,
});
assert.equal(result.code, 400);
assert.match(String(result.message || ''), /已审核/);
assert.equal(calls.stockWarehouseFindOne, 0);
});
it('should reject binding when receiving is cancelled', async () => {
const { service, calls } = createHarness({
receiving: {
is_review: 0,
status: 'cancelled',
},
});
const result = await service.bindDetailProduct({
detail_id: 1001,
system_product_id: 2001,
});
assert.equal(result.code, 400);
assert.match(String(result.message || ''), /已作废/);
assert.equal(calls.stockWarehouseFindOne, 0);
});
});

View File

@ -0,0 +1,159 @@
'use strict';
const assert = require('node:assert/strict');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createReceivingRow(overrides = {}) {
return {
id: 501,
warehouse_id: 100000,
receiving_number: 'RCV-501',
status: 'completed',
is_review: 0,
storage_status: 'none',
creator_snapshot: JSON.stringify({
id: 3001,
employees_id: 3001,
name: '创建人A',
}),
...overrides,
};
}
function createHarness(options = {}) {
const rows = (options.rows || []).map(item => ({ ...item }));
const noticeCalls = [];
const operationLogs = [];
const updateCalls = [];
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
store_name: '测试仓库',
employees_id: 9001,
employees_name: '审核员A',
id: 9001,
},
logger: {
warn() {},
error() {},
info() {},
},
service: {
systems: {
operationLog: {
async createOperationLog(payload) {
operationLogs.push(payload);
},
},
notice: {
async send(payload) {
noticeCalls.push(payload);
return { success: true };
},
},
},
},
model: {
Sequelize: {
Op: {
in: 'in',
},
},
Receiving: {
async findAll() {
return rows;
},
async update(values) {
updateCalls.push({ ...values });
rows.forEach(row => Object.assign(row, values));
return [ rows.length ];
},
},
},
};
return {
service: new ReceivingService(ctx),
rows,
noticeCalls,
operationLogs,
updateCalls,
};
}
describe('test/app/service/systems/storage.receiving.reject.test.js', () => {
it('should send one reject notice per receiving with creator info and identifiers', async () => {
const { service, noticeCalls, operationLogs, updateCalls } = createHarness({
rows: [
createReceivingRow({ id: 501, receiving_number: 'RCV-501' }),
createReceivingRow({
id: 502,
receiving_number: 'RCV-502',
creator_snapshot: JSON.stringify({
id: 3002,
employees_id: 3002,
name: '创建人B',
}),
}),
],
});
const result = await service.rejectReceiving({
ids: [ 501, 502 ],
remark: '资料不完整',
});
assert.equal(result.code, 200);
assert.equal(result.message, '驳回成功');
assert.equal(updateCalls.length, 1);
assert.equal(Object.prototype.hasOwnProperty.call(updateCalls[0], 'is_review'), false);
assert.equal(operationLogs.length, 2);
assert.equal(noticeCalls.length, 2);
const firstNotice = noticeCalls.find(item => Number(item.businessId) === 501);
const secondNotice = noticeCalls.find(item => Number(item.businessId) === 502);
assert.ok(firstNotice);
assert.ok(secondNotice);
assert.equal(firstNotice.event, 'receiving_rejected');
assert.match(String(firstNotice.title || ''), /RCV-501|501/);
assert.match(String(firstNotice.content || ''), /收货单ID:501/);
assert.match(String(firstNotice.content || ''), /收货单号:RCV-501/);
assert.match(String(firstNotice.content || ''), /收货创建人:创建人A/);
assert.deepEqual(firstNotice.metadata.receiving_ids, [ 501 ]);
assert.deepEqual(firstNotice.metadata.receiving_numbers, [ 'RCV-501' ]);
assert.deepEqual(firstNotice.metadata.receiving_creators, [
{ id: 3001, employees_id: 3001, name: '创建人A' },
]);
assert.deepEqual(firstNotice.metadata.receivings, [
{
id: 501,
receiving_number: 'RCV-501',
creator: { id: 3001, employees_id: 3001, name: '创建人A' },
},
]);
assert.equal(secondNotice.event, 'receiving_rejected');
assert.match(String(secondNotice.title || ''), /RCV-502|502/);
assert.match(String(secondNotice.content || ''), /收货单ID:502/);
assert.match(String(secondNotice.content || ''), /收货单号:RCV-502/);
assert.match(String(secondNotice.content || ''), /收货创建人:创建人B/);
assert.deepEqual(secondNotice.metadata.receiving_ids, [ 502 ]);
assert.deepEqual(secondNotice.metadata.receiving_numbers, [ 'RCV-502' ]);
assert.deepEqual(secondNotice.metadata.receiving_creators, [
{ id: 3002, employees_id: 3002, name: '创建人B' },
]);
assert.deepEqual(secondNotice.metadata.receivings, [
{
id: 502,
receiving_number: 'RCV-502',
creator: { id: 3002, employees_id: 3002, name: '创建人B' },
},
]);
});
});

View File

@ -0,0 +1,151 @@
'use strict';
const assert = require('node:assert/strict');
const { Op } = require('sequelize');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createReceivingRow(overrides = {}) {
return {
id: 101,
warehouse_id: 100000,
receiving_number: 'RCV202604300001',
status: 'completed',
detail_status: 'all_matched',
storage_status: 'none',
store_id: 200001,
is_review: 0,
...overrides,
};
}
function createHarness(options = {}) {
const rows = (options.rows || []).map(item => ({ ...item }));
const calls = {
updateArgs: [],
transactionCommitCount: 0,
transactionRollbackCount: 0,
operationLogs: [],
};
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
async commit() {
calls.transactionCommitCount += 1;
},
async rollback() {
calls.transactionRollbackCount += 1;
},
};
const ctx = {
app: {
Sequelize: {
Op,
},
},
user: {
store_id: 100000,
employees_id: 9001,
employees_name: '审核员A',
id: 9001,
},
logger: {
info() {},
warn() {},
error() {},
},
service: {
systems: {
operationLog: {
async createOperationLog(payload) {
calls.operationLogs.push(payload);
},
},
},
},
model: {
Sequelize: {
Op,
},
async transaction() {
return transaction;
},
Receiving: {
async findAll() {
return rows;
},
async update(values, optionsArg = {}) {
calls.updateArgs.push({
values: { ...values },
where: optionsArg.where,
});
const affectedRows = options.updatedRows !== undefined
? Number(options.updatedRows)
: rows.length;
if (affectedRows > 0) {
rows.slice(0, affectedRows).forEach(row => {
Object.assign(row, values);
});
}
return [ affectedRows ];
},
},
},
};
const service = new ReceivingService(ctx);
service.sendReviewNotice = async () => ({ success: true, data: { sentCount: 0, failedCount: 0, matchedHookCount: 0 } });
service.uploadReviewExcelReport = async receiving => ({
fileKey: `${receiving.receiving_number}.xlsx`,
url: `https://cdn.example.com/${receiving.receiving_number}.xlsx`,
});
return {
service,
rows,
calls,
};
}
describe('test/app/service/systems/storage.receiving.review.test.js', () => {
it('should review completed receivings even when legacy is_review is null', async () => {
const { service, rows, calls } = createHarness({
rows: [ createReceivingRow({ id: 201, receiving_number: 'RCV-201', is_review: null }) ],
});
const result = await service.reviewReceiving({ ids: [ 201 ] });
assert.equal(result.code, 200);
assert.equal(result.message, '审核成功');
assert.equal(Number(rows[0].is_review), 1);
assert.equal(rows[0].reviewer_name, '审核员A');
assert.equal(Number(rows[0].reviewer_employee_id), 9001);
assert.equal(calls.transactionCommitCount, 1);
assert.equal(calls.transactionRollbackCount, 0);
assert.equal(calls.updateArgs.length, 1);
assert.deepEqual(calls.updateArgs[0].where[Op.or], [
{ is_review: 0 },
{ is_review: null },
]);
});
it('should fail when affected rows are fewer than requested ids', async () => {
const { service, rows, calls } = createHarness({
rows: [ createReceivingRow({ id: 301, receiving_number: 'RCV-301', is_review: null }) ],
updatedRows: 0,
});
const result = await service.reviewReceiving({ ids: [ 301 ] });
assert.equal(result.code, 0);
assert.match(String(result.message || ''), /审核状态已变化/);
assert.equal(rows[0].is_review, null);
assert.equal(calls.transactionCommitCount, 0);
assert.equal(calls.transactionRollbackCount, 1);
});
});

View File

@ -0,0 +1,162 @@
'use strict';
const assert = require('node:assert/strict');
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
function createReceivingRow(overrides = {}) {
return {
id: 101,
warehouse_id: 100000,
receiving_number: 'RCV202604300001',
status: 'receiving',
delivery_method: 'truck',
license_plate: '粤A12345',
loading_method: 'without_pallet',
remark: 'old remark',
store_id: 200001,
store_name: '旧货主',
total_boxes: 1,
total_pallets: 0,
tracking_number: null,
video_device_id: null,
is_deleted: false,
...overrides,
};
}
function createHarness(options = {}) {
const receivingRow = createReceivingRow(options.receiving || {});
const calls = {
transactionCommitCount: 0,
transactionRollbackCount: 0,
updateArgs: [],
operationLogs: [],
};
const transaction = {
LOCK: {
UPDATE: 'UPDATE',
},
async commit() {
calls.transactionCommitCount += 1;
},
async rollback() {
calls.transactionRollbackCount += 1;
},
};
const storeRelation = options.storeRelation === undefined
? { store_id: 300001, store_remask: '新货主' }
: options.storeRelation;
const ctx = {
app: {
config: {},
},
user: {
store_id: 100000,
employees_id: 9001,
employees_name: '测试员A',
id: 9001,
},
logger: {
warn() {},
error() {},
info() {},
},
service: {
systems: {
operationLog: {
async createOperationLog(payload) {
calls.operationLogs.push(payload);
},
},
},
},
model: {
async transaction() {
return transaction;
},
Receiving: {
async findOne({ where = {} }) {
if (Number(where.id) !== Number(receivingRow.id) || Number(where.warehouse_id) !== Number(receivingRow.warehouse_id) || receivingRow.is_deleted) {
return null;
}
return receivingRow;
},
async update(values, optionsArg = {}) {
calls.updateArgs.push({
values: { ...values },
where: optionsArg.where,
});
Object.assign(receivingRow, values);
return [ 1 ];
},
},
StoreWarehouse: {
async findOne() {
return storeRelation;
},
},
},
};
return {
service: new ReceivingService(ctx),
receivingRow,
calls,
};
}
describe('test/app/service/systems/storage.receiving.save.test.js', () => {
it('should update receiving by id', async () => {
const { service, receivingRow, calls } = createHarness();
const result = await service.save({
id: 101,
delivery_method: 'express',
tracking_number: 'YT123456789',
loading_method: 'with_pallet',
remark: 'new remark',
store_id: 300001,
total_boxes: 8,
total_pallets: 2,
video_device_id: 'CAM-01',
});
assert.equal(result.code, 200);
assert.equal(result.id, 101);
assert.equal(result.receiving_number, 'RCV202604300001');
assert.equal(result.message, '收货单修改成功');
assert.equal(receivingRow.delivery_method, 'express');
assert.equal(receivingRow.license_plate, null);
assert.equal(receivingRow.tracking_number, 'YT123456789');
assert.equal(receivingRow.loading_method, 'with_pallet');
assert.equal(receivingRow.remark, 'new remark');
assert.equal(receivingRow.store_id, 300001);
assert.equal(receivingRow.store_name, '新货主');
assert.equal(receivingRow.total_boxes, 8);
assert.equal(receivingRow.total_pallets, 2);
assert.equal(receivingRow.video_device_id, 'CAM-01');
assert.equal(calls.transactionCommitCount, 1);
assert.equal(calls.transactionRollbackCount, 0);
assert.equal(calls.operationLogs.length, 1);
});
it('should reject invalid store relation', async () => {
const { service, receivingRow, calls } = createHarness({
storeRelation: null,
});
const result = await service.save({
id: 101,
store_id: 999999,
});
assert.equal(result.code, 404);
assert.match(String(result.message || ''), /货主不存在|签约关系/);
assert.equal(receivingRow.store_id, 200001);
assert.equal(calls.transactionCommitCount, 0);
assert.equal(calls.transactionRollbackCount, 1);
});
});