feat(storage): 拦截锁定库存改造,拦截确认库存移入 intercept_locked_quantity 不归还可用,可用数量统一口径 quantity-locked-intercept,负库存入库平账冲销 GAP 挂账

This commit is contained in:
liufumingren 2026-09-03 17:00:37 +08:00
parent ff84a99306
commit 25442ba215
11 changed files with 1107 additions and 93 deletions

View File

@ -72,6 +72,12 @@ module.exports = app => {
defaultValue: 0,
comment: '锁定数量',
},
intercept_locked_quantity: {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '拦截锁定数量',
},
available_quantity: {
type: INTEGER(12),
allowNull: false,
@ -257,9 +263,15 @@ module.exports = app => {
};
// 实例方法
/**
* 计算当前记录的可用数量(统一口径)。
*
* 可用数量口径:可用数量 = 库存数量 - 锁定数量 - 拦截锁定数量。
*
* @return {number} 可用数量。
*/
Storage.prototype.getAvailableQuantity = function() {
return this.quantity - this.locked_quantity;
return this.quantity - this.locked_quantity - Number(this.intercept_locked_quantity || 0);
};
Storage.prototype.isAvailable = function() {

View File

@ -70,6 +70,16 @@ module.exports = app => {
allowNull: true,
comment: '变更后锁定数量',
},
before_intercept_locked_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '变更前拦截锁定数量',
},
after_intercept_locked_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '变更后拦截锁定数量',
},
batch_no: {
type: STRING(100),
allowNull: true,

View File

@ -3733,7 +3733,7 @@ class RecheckOrderService extends OrderBaseService {
* 每个订单的拦截处理:
* 1. 更新 wms_order_delivery:intercept_status = intercepted_at_warehouse、step=4、outbound_status=fin
* 2. 同步更新运单表:is_intercept='Y'、is_back='Y'(库内拦截确认,货物在库内需退回)
* 3. 释放储位分配(cancelAllocateStorage,归还库存)
* 3. 释放储位分配(cancelAllocateStorage 拦截模式:库存不归还可用,移入拦截锁定字段 intercept_locked_quantity)
* 4. 释放订单锁(lock_status='none')
* 5. 写入操作日志(ORDER_INTERCEPT_CONFIRM)
* 全部订单处理完后,按成功订单 ID 汇总批量创建售后工单 + 通知快递群。
@ -3840,10 +3840,11 @@ class RecheckOrderService extends OrderBaseService {
);
}
// 拦截成功后释放储位分配(归还库存)
// 拦截成功后释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)
try {
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: [ orderId ],
interceptMode: true,
});
} catch (allocErr) {
ctx.logger.warn(
@ -3940,7 +3941,7 @@ class RecheckOrderService extends OrderBaseService {
* 3. 检查是否存在关联的未完结售后工单(wms_after_sale),若有则调用 handleWorkOrder 写入
* "库内拦截成功"步骤并将工单置为 completed
* 4. 同步更新 wms_order_delivery 的 intercept_status 为 intercepted_at_warehouse,
* 并释放储位分配与订单锁(仅订单级状态更新,不标记订单下其他面单)
* 并释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)与订单锁(仅订单级状态更新,不标记订单下其他面单)
*
* 注:库内拦截确认需标记退回 is_back='Y';发起拦截链路仅写 is_intercept,不写 is_back。
*
@ -4063,10 +4064,11 @@ class RecheckOrderService extends OrderBaseService {
{ where: orderWhere }
);
// 释放储位分配
// 释放储位分配(拦截模式:库存移入拦截锁定,不归还可用)
try {
await service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: [ orderId ],
interceptMode: true,
});
} catch (allocErr) {
ctx.logger.warn(

View File

@ -993,6 +993,19 @@ class InboundDirectLogService extends Service {
await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true });
await stockRecord.reload({ transaction });
// 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据)
if (beforeQuantity <= 0) {
const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity);
await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, inboundQty, {
transaction,
maxOffset: nonNegativeDelta,
orderNo: eo.entry_order_code || 'DIRECT_INBOUND',
orderId: eo.id,
operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''),
operatorName: ctx.user?.employees_name || '',
});
}
const afterQuantity = Number(stockRecord.quantity) || 0;
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
@ -1048,6 +1061,8 @@ class InboundDirectLogService extends Service {
let sAfterQty = 0;
let sBeforeLockedQty = 0;
let sAfterLockedQty = 0;
let sBeforeInterceptQty = 0;
let sAfterInterceptQty = 0;
if (sRecord) {
if (Number(sRecord.stock_id) !== Number(stockId)) {
@ -1060,6 +1075,8 @@ class InboundDirectLogService extends Service {
sAfterQty = sBeforeQty + qty;
sBeforeLockedQty = Number(sRecord.locked_quantity) || 0;
sAfterLockedQty = sBeforeLockedQty;
sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0;
sAfterInterceptQty = sBeforeInterceptQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${qty}`),
@ -1120,6 +1137,8 @@ class InboundDirectLogService extends Service {
after_quantity: sAfterQty,
before_locked_quantity: sBeforeLockedQty,
after_locked_quantity: sAfterLockedQty,
before_intercept_locked_quantity: sBeforeInterceptQty,
after_intercept_locked_quantity: sAfterInterceptQty,
batch_no: effectiveBatchNo,
inventory_type: inventoryType,
order_type: 'entry_order',

View File

@ -1142,6 +1142,7 @@ class OrderStorageAllocationService extends MainService {
});
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0);
await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction });
@ -1166,6 +1167,8 @@ class OrderStorageAllocationService extends MainService {
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity + allocationQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICKING_LOCK',
@ -2104,17 +2107,24 @@ class OrderStorageAllocationService extends MainService {
*
* 入参仅支持订单 ID 相关字段:
* - `order_ids` / `orderIds` / `ids` / `order_id` / `orderId` / `id`
* - `interceptMode`(可选,布尔值):拦截确认模式,默认 false。
* - false(普通取消):pending 行解除锁定(可用数量 +q)、fin 行返还实物(可用数量 +q),既有行为不变;
* - true(拦截确认):pending 行作业锁迁移为拦截锁(locked -q、intercept +q、available 不变),
* fin 行实物返还并拦截锁定(quantity +q、intercept +q、available 不变),流水 order_type 记为
* INTERCEPT_LOCK 且记录 order_id 与 before/after_intercept_locked_quantity 快照。
*
* 取消分配时仅处理当前用户仓库中已完成储位分配的订单;
* 未分配订单或非完成状态订单会进入 skipped_orders。
*
* @param {Object} data 请求体。
* @param {boolean} [data.interceptMode] 拦截确认模式开关。
* @return {Promise<Object>} 取消分配结果。
*/
async cancelAllocateStorage(data = {}) {
const { ctx, app } = this;
const { orderIds, forbiddenWarehouseKeys } = normalizeCancelStorageAllocationRequest(data);
const warehouseId = toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
const interceptMode = normalizeBooleanFlag(data && data.interceptMode, false);
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 规范化入参', {
warehouseId,
@ -2277,6 +2287,11 @@ class OrderStorageAllocationService extends MainService {
const pendingStorageQuantityMap = new Map();
const finStorageQuantityMap = new Map();
const storageIdSet = new Set();
// 拦截模式(interceptMode)按 (order_id, storage_id) 维度记录数量,供拦截锁迁移与按单回落使用
const interceptPendingQuantityMap = new Map();
const interceptFinQuantityMap = new Map();
// 拦截模式拣货行元信息(space_id/stock_id),供缺行补建 storage 使用
const interceptPickingMetaMap = new Map();
for (const pickingRow of Array.isArray(pickingRows) ? pickingRows : []) {
const plainPicking = toPlainRecord(pickingRow);
@ -2296,10 +2311,19 @@ class OrderStorageAllocationService extends MainService {
// 按状态分流:pending 记录解除锁定(实物不动);
// fin 记录(已拣货)返还实物数量,锁定已在拣货完成时扣减,不再重复扣除
const pickingStatus = String(plainPicking?.status || '').trim();
const interceptPairKey = `${orderId}:${storageId}`;
if (!interceptPickingMetaMap.has(interceptPairKey)) {
interceptPickingMetaMap.set(interceptPairKey, {
space_id: toNumber(plainPicking?.space_id, 0),
stock_id: toNumber(plainPicking?.stock_id, 0),
});
}
if (pickingStatus === 'fin') {
finStorageQuantityMap.set(storageId, (finStorageQuantityMap.get(storageId) || 0) + quantity);
interceptFinQuantityMap.set(interceptPairKey, (interceptFinQuantityMap.get(interceptPairKey) || 0) + quantity);
} else {
pendingStorageQuantityMap.set(storageId, (pendingStorageQuantityMap.get(storageId) || 0) + quantity);
interceptPendingQuantityMap.set(interceptPairKey, (interceptPendingQuantityMap.get(interceptPairKey) || 0) + quantity);
}
}
@ -2364,97 +2388,376 @@ class OrderStorageAllocationService extends MainService {
const storageUnlockSummary = [];
const storageReturnSummary = [];
// pending 记录:解除锁定,实物库存不动
for (const [ storageId, quantity ] of pendingStorageQuantityMap.entries()) {
if (quantity <= 0) {
continue;
if (interceptMode) {
// ── 拦截模式:库存不归还可用,移入拦截锁定字段(intercept_locked_quantity) ──
const interceptUnlockSummaryMap = new Map();
const interceptReturnSummaryMap = new Map();
// 按 storage 累计本批次已迁移的锁定/拦截锁定/实物数量变化,保证同库存多订单时流水快照准确
const interceptLockedDeltaMap = new Map();
const interceptLockedChangeMap = new Map();
const interceptQuantityChangeMap = new Map();
// 仓库默认库位(缺行补建时使用):优先仓库配置 default_location_id,未设置兜底 1
let fallbackDefaultSpaceId = 1;
try {
const deliveryOrderService = ctx.service && ctx.service.systems && ctx.service.systems.deliveryOrder;
const subjectConfig = deliveryOrderService && typeof deliveryOrderService.getStoreSubjectConfig === 'function'
? await deliveryOrderService.getStoreSubjectConfig(warehouseId)
: null;
const configuredLocationId = Number(subjectConfig && subjectConfig.default_location_id || 0);
if (Number.isInteger(configuredLocationId) && configuredLocationId > 0) {
fallbackDefaultSpaceId = configuredLocationId;
}
} catch (defaultSpaceErr) {
ctx.logger.warn(
`[order_storage_allocation.cancelAllocateStorage] 读取仓库默认库位失败,兜底库位 1: ${defaultSpaceErr.message}`
);
}
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
// pending 记录:作业锁迁移为拦截锁(locked -q、intercept +q、quantity 不变、available 不变)
for (const [ pairKey, quantity ] of interceptPendingQuantityMap.entries()) {
if (quantity <= 0) {
continue;
}
const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0));
if (orderId <= 0 || storageId <= 0) {
continue;
}
let storageRow = storageMap.get(storageId);
const orderRow = orderMap.get(orderId) || {};
const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim()
|| 'INTERCEPT_CONFIRM';
const pickingMeta = interceptPickingMetaMap.get(pairKey) || {};
if (!storageRow) {
// 拦截确认缺行补建:货物在库,直接以拦截锁定入账(quantity=q、intercept=q、available=0)
const created = await storageModel.create({
warehouse_id: warehouseId,
store_id: toNumber(orderRow.store_id, 0) || null,
space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId,
stock_id: toNumber(pickingMeta.stock_id, 0) || 0,
batch_no: String(orderNo).slice(0, 100),
inventory_type: 'ZP',
quantity,
locked_quantity: 0,
intercept_locked_quantity: quantity,
available_quantity: 0,
inbound_time: now,
inbound_order_no: String(orderNo).slice(0, 100),
is_enabled: 1,
created_at: now,
updated_at: now,
}, { transaction });
const plainCreated = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
storageMap.set(Number(plainCreated.id), plainCreated);
storageRow = plainCreated;
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行', {
orderId,
storageId,
createdStorageId: plainCreated.id,
quantity,
spaceId: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId,
});
// 直接写拦截锁定流水(补建行:before=0 → after=quantity)
await ctx.model.StorageTransaction.create({
transaction_type: 'LOCK',
warehouse_id: warehouseId,
store_id: plainCreated.store_id,
stock_id: plainCreated.stock_id,
storage_id: plainCreated.id,
space_id: plainCreated.space_id,
quantity,
before_quantity: quantity,
after_quantity: quantity,
before_locked_quantity: 0,
after_locked_quantity: 0,
before_intercept_locked_quantity: 0,
after_intercept_locked_quantity: quantity,
batch_no: plainCreated.batch_no,
inventory_type: 'ZP',
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(缺行补建并拦截锁定)',
}, { transaction });
interceptUnlockSummaryMap.set(Number(plainCreated.id), (interceptUnlockSummaryMap.get(Number(plainCreated.id)) || 0) + quantity);
continue; // 补建行已直接入账,跳过既有迁移逻辑
}
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0)
+ (interceptLockedDeltaMap.get(storageId) || 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0)
+ (interceptLockedChangeMap.get(storageId) || 0);
await ctx.service.systems.storage.index.interceptLockQuantity(storageId, quantity, {
transaction,
});
interceptLockedDeltaMap.set(storageId, (interceptLockedDeltaMap.get(storageId) || 0) - quantity);
interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + quantity);
// 写入拦截锁定流水(作业锁迁移为拦截锁,记录拦截快照)
await ctx.model.StorageTransaction.create({
transaction_type: 'LOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity,
before_quantity: storageRow.quantity,
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity - quantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity + quantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(作业锁迁移为拦截锁)',
}, { transaction });
interceptUnlockSummaryMap.set(storageId, (interceptUnlockSummaryMap.get(storageId) || 0) + quantity);
}
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
// fin 记录(已拣货):实物返还并拦截锁定(quantity +q、intercept +q、available 不变)
for (const [ pairKey, returnQuantity ] of interceptFinQuantityMap.entries()) {
if (returnQuantity <= 0) {
continue;
}
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, {
transaction,
});
const [ orderId, storageId ] = pairKey.split(':').map(part => toNumber(part, 0));
if (orderId <= 0 || storageId <= 0) {
continue;
}
// 写入储位解锁流水
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity,
before_quantity: storageRow.quantity,
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity - quantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICKING_UNLOCK',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(库存解锁)',
}, { transaction });
let storageRow = storageMap.get(storageId);
const orderRow = orderMap.get(orderId) || {};
const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim()
|| 'INTERCEPT_CONFIRM';
const pickingMeta = interceptPickingMetaMap.get(pairKey) || {};
storageUnlockSummary.push({
storage_id: storageId,
unlocked_quantity: quantity,
});
}
if (!storageRow) {
// 拦截确认缺行补建:实物返还并拦截锁定(quantity=q、intercept=q、available=0)
const created = await storageModel.create({
warehouse_id: warehouseId,
store_id: toNumber(orderRow.store_id, 0) || null,
space_id: toNumber(pickingMeta.space_id, 0) || fallbackDefaultSpaceId,
stock_id: toNumber(pickingMeta.stock_id, 0) || 0,
batch_no: String(orderNo).slice(0, 100),
inventory_type: 'ZP',
quantity: returnQuantity,
locked_quantity: 0,
intercept_locked_quantity: returnQuantity,
available_quantity: 0,
inbound_time: now,
inbound_order_no: String(orderNo).slice(0, 100),
is_enabled: 1,
created_at: now,
updated_at: now,
}, { transaction });
const plainCreated = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
storageMap.set(Number(plainCreated.id), plainCreated);
storageRow = plainCreated;
// fin 记录(已拣货):返还实物数量,锁定已在拣货完成时扣减,不再重复扣除
for (const [ storageId, returnQuantity ] of finStorageQuantityMap.entries()) {
if (returnQuantity <= 0) {
continue;
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式缺行补建库存行(fin)', {
orderId,
storageId,
createdStorageId: plainCreated.id,
returnQuantity,
});
// 直接写拦截锁定流水(补建行:before=0 → after=returnQuantity)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: plainCreated.store_id,
stock_id: plainCreated.stock_id,
storage_id: plainCreated.id,
space_id: plainCreated.space_id,
quantity: returnQuantity,
before_quantity: returnQuantity,
after_quantity: returnQuantity,
before_locked_quantity: 0,
after_locked_quantity: 0,
before_intercept_locked_quantity: 0,
after_intercept_locked_quantity: returnQuantity,
batch_no: plainCreated.batch_no,
inventory_type: 'ZP',
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(缺行补建实物返还并拦截锁定)',
}, { transaction });
interceptReturnSummaryMap.set(Number(plainCreated.id), (interceptReturnSummaryMap.get(Number(plainCreated.id)) || 0) + returnQuantity);
continue; // 补建行已直接入账,跳过既有返还逻辑
}
const beforeQuantity = toNumber(storageRow.quantity, 0)
+ (interceptQuantityChangeMap.get(storageId) || 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0)
+ (interceptLockedChangeMap.get(storageId) || 0);
await ctx.service.systems.storage.index.interceptReceiveQuantity(storageId, returnQuantity, {
transaction,
});
interceptQuantityChangeMap.set(storageId, (interceptQuantityChangeMap.get(storageId) || 0) + returnQuantity);
interceptLockedChangeMap.set(storageId, (interceptLockedChangeMap.get(storageId) || 0) + returnQuantity);
// 写入拦截锁定流水(实物返还并拦截锁定,记录拦截快照)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: returnQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity + returnQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity + returnQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(已拣货实物返还并拦截锁定)',
}, { transaction });
interceptReturnSummaryMap.set(storageId, (interceptReturnSummaryMap.get(storageId) || 0) + returnQuantity);
}
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
for (const [ storageId, quantity ] of interceptUnlockSummaryMap.entries()) {
storageUnlockSummary.push({ storage_id: storageId, unlocked_quantity: quantity });
}
for (const [ storageId, quantity ] of interceptReturnSummaryMap.entries()) {
storageReturnSummary.push({ storage_id: storageId, returned_quantity: quantity });
}
} else {
// ── 普通取消模式:解除锁定/返还实物,回到可用数量(既有行为不变) ──
// pending 记录:解除锁定,实物库存不动
for (const [ storageId, quantity ] of pendingStorageQuantityMap.entries()) {
if (quantity <= 0) {
continue;
}
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
}
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0);
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, {
transaction,
});
// 写入储位解锁流水
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity,
before_quantity: storageRow.quantity,
after_quantity: storageRow.quantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity - quantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICKING_UNLOCK',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(库存解锁)',
}, { transaction });
storageUnlockSummary.push({
storage_id: storageId,
unlocked_quantity: quantity,
});
}
const beforeQuantity = toNumber(storageRow.quantity, 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
// fin 记录(已拣货):返还实物数量,锁定已在拣货完成时扣减,不再重复扣除
for (const [ storageId, returnQuantity ] of finStorageQuantityMap.entries()) {
if (returnQuantity <= 0) {
continue;
}
await ctx.service.systems.storage.index.updateQuantity(storageId, returnQuantity, 0, {
transaction,
});
const storageRow = storageMap.get(storageId);
if (!storageRow) {
throw new Error(`库存记录不存在: ${storageId}`);
}
// 写入库存返还流水(实物数量增加,锁定不变)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: returnQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity + returnQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICK_RETURN',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(已拣货返还库存)',
}, { transaction });
const beforeQuantity = toNumber(storageRow.quantity, 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0);
storageReturnSummary.push({
storage_id: storageId,
returned_quantity: returnQuantity,
});
await ctx.service.systems.storage.index.updateQuantity(storageId, returnQuantity, 0, {
transaction,
});
// 写入库存返还流水(实物数量增加,锁定不变)
await ctx.model.StorageTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: returnQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity + returnQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'PICK_RETURN',
order_no: 'CANCEL_BATCH',
order_id: 0,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '取消分配储位(已拣货返还库存)',
}, { transaction });
storageReturnSummary.push({
storage_id: storageId,
returned_quantity: returnQuantity,
});
}
}
const cancelPickingIds = [];
@ -2561,6 +2864,237 @@ class OrderStorageAllocationService extends MainService {
throw error;
}
}
/**
* 按订单 ID 释放拦截锁定数量(拦截锁回落到可用数量)。
*
* 依据 wms_storage_transaction 中 order_type='INTERCEPT_LOCK' 与
* order_type='INTERCEPT_UNLOCK' 的流水按 (storage_id, order_id) 汇总净拦截量,
* 净量大于 0 时逐库存行调用 interceptUnlockQuantity 释放拦截锁:
* `intercept_locked_quantity -q`、`available_quantity +q`,`quantity` 与 `locked_quantity` 不变,
* 并写入 INTERCEPT_UNLOCK 流水记录拦截快照(order_id 与订单对应)。
* 释放量与流水均以订单维度记录,重复调用幂等(净量归零后不再释放)。
*
* 使用场景:
* - 批量解除拦截(batchUnintercept 后台任务);
* - 退货登记完成(return_received.create)。
*
* @param {Array<number|string>} orderIds 订单 ID 数组。
* @param {Object} [options={}] 执行上下文参数。
* @param {number|string} [options.warehouseId] 仓库 ID,缺省取当前用户仓库上下文。
* @param {Object} [options.transaction] 外部事务对象,缺省内部创建事务。
* @param {string} [options.scene='INTERCEPT_UNLOCK'] 释放场景标识(写入流水 order_no)。
* @param {string} [options.remark='解除拦截(拦截锁回落到可用数量)'] 流水备注。
* @param {string} [options.operatorId] 操作人工号 ID,缺省取当前用户上下文。
* @param {string} [options.operatorName] 操作人名称,缺省取当前用户上下文。
* @return {Promise<Object>} 释放结果,含 order_ids、released_quantity、storage_release_summary。
*/
async releaseInterceptLocksByOrderIds(orderIds = [], options = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const normalizedOrderIds = Array.from(new Set(
(Array.isArray(orderIds) ? orderIds : [])
.map(orderId => toNumber(orderId, 0))
.filter(orderId => orderId > 0)
));
if (normalizedOrderIds.length === 0) {
return {
order_ids: [],
released_quantity: 0,
storage_release_summary: [],
};
}
const warehouseId = toNumber(options.warehouseId, 0) > 0
? toNumber(options.warehouseId, 0)
: toNumber(ctx.user?.store_id ?? ctx.user?.warehouse_id, 0);
if (warehouseId <= 0) {
throw new Error('缺少仓库上下文');
}
const scene = String(options.scene || 'INTERCEPT_UNLOCK').trim() || 'INTERCEPT_UNLOCK';
const remark = String(options.remark || '解除拦截(拦截锁回落到可用数量)').trim();
const operatorId = String(options.operatorId ?? ctx.user?.employees_id ?? ctx.user?.id ?? '');
const operatorName = String(
options.operatorName ?? ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? ''
);
const externalTransaction = options.transaction || null;
const transaction = externalTransaction || await ctx.model.transaction();
try {
const groupAttributes = [
'storage_id',
'order_id',
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
];
// 汇总本批次订单的拦截锁定流水(按 storage_id + order_id 分组)
const lockRows = await ctx.model.StorageTransaction.findAll({
attributes: groupAttributes,
where: {
warehouse_id: warehouseId,
order_type: 'INTERCEPT_LOCK',
order_id: { [Op.in]: normalizedOrderIds },
},
group: [ 'storage_id', 'order_id' ],
transaction,
raw: true,
});
const netQuantityMap = new Map();
for (const row of Array.isArray(lockRows) ? lockRows : []) {
const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`;
netQuantityMap.set(pairKey, toNumber(row.total_quantity, 0));
}
if (netQuantityMap.size === 0) {
if (!externalTransaction) {
await transaction.commit();
}
return {
order_ids: normalizedOrderIds,
released_quantity: 0,
storage_release_summary: [],
};
}
const storageIdSet = new Set();
for (const pairKey of netQuantityMap.keys()) {
const storageId = toNumber(pairKey.split(':')[1], 0);
if (storageId > 0) {
storageIdSet.add(storageId);
}
}
// 汇总已释放的拦截解锁流水(同一订单维度),净量 = 锁定 - 已释放,保证幂等
const unlockRows = await ctx.model.StorageTransaction.findAll({
attributes: groupAttributes,
where: {
warehouse_id: warehouseId,
order_type: 'INTERCEPT_UNLOCK',
order_id: { [Op.in]: normalizedOrderIds },
storage_id: { [Op.in]: Array.from(storageIdSet) },
},
group: [ 'storage_id', 'order_id' ],
transaction,
raw: true,
});
for (const row of Array.isArray(unlockRows) ? unlockRows : []) {
const pairKey = `${toNumber(row.order_id, 0)}:${toNumber(row.storage_id, 0)}`;
netQuantityMap.set(pairKey, (netQuantityMap.get(pairKey) || 0) - toNumber(row.total_quantity, 0));
}
// 行锁查询库存,并维护每库存行的剩余可释放拦截量,防止多订单同库存行超释
const storageRows = await ctx.model.Storage.findAll({
where: {
id: { [Op.in]: Array.from(storageIdSet) },
warehouse_id: warehouseId,
},
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
const storageMap = new Map();
const remainingInterceptByStorage = new Map();
for (const row of Array.isArray(storageRows) ? storageRows : []) {
const storageId = toNumber(row.id, 0);
storageMap.set(storageId, row);
remainingInterceptByStorage.set(storageId, toNumber(row.intercept_locked_quantity, 0));
}
const storageReleaseSummary = [];
let releasedQuantity = 0;
// 已释放拦截量(按 storage 累计),保证同库存行多订单时流水 before/after 快照准确
const releasedInterceptByStorage = new Map();
for (const [ pairKey, netQuantity ] of netQuantityMap.entries()) {
if (netQuantity <= 0) {
continue;
}
const pairParts = pairKey.split(':');
const orderId = toNumber(pairParts[0], 0);
const storageId = toNumber(pairParts[1], 0);
if (orderId <= 0 || storageId <= 0) {
continue;
}
const storageRow = storageMap.get(storageId);
if (!storageRow) {
continue;
}
const storageRemaining = remainingInterceptByStorage.get(storageId) || 0;
const releaseQuantity = Math.min(netQuantity, storageRemaining);
if (releaseQuantity <= 0) {
continue;
}
const beforeQuantity = toNumber(storageRow.quantity, 0);
const beforeLockedQuantity = toNumber(storageRow.locked_quantity, 0);
const beforeInterceptLockedQuantity = toNumber(storageRow.intercept_locked_quantity, 0)
- (releasedInterceptByStorage.get(storageId) || 0);
await ctx.service.systems.storage.index.interceptUnlockQuantity(storageId, releaseQuantity, {
transaction,
});
// 写入拦截解锁流水(记录拦截快照,order_id 与订单对应)
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: warehouseId,
store_id: storageRow.store_id,
stock_id: storageRow.stock_id,
storage_id: storageId,
space_id: storageRow.space_id,
quantity: releaseQuantity,
before_quantity: beforeQuantity,
after_quantity: beforeQuantity,
before_locked_quantity: beforeLockedQuantity,
after_locked_quantity: beforeLockedQuantity,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity - releaseQuantity,
batch_no: storageRow.batch_no,
inventory_type: storageRow.inventory_type,
order_type: 'INTERCEPT_UNLOCK',
order_no: scene,
order_id: orderId,
operator_id: operatorId,
operator_name: operatorName,
remark,
}, { transaction });
remainingInterceptByStorage.set(storageId, storageRemaining - releaseQuantity);
releasedInterceptByStorage.set(storageId, (releasedInterceptByStorage.get(storageId) || 0) + releaseQuantity);
releasedQuantity += releaseQuantity;
storageReleaseSummary.push({
storage_id: storageId,
order_id: orderId,
released_quantity: releaseQuantity,
});
}
if (!externalTransaction) {
await transaction.commit();
}
return {
order_ids: normalizedOrderIds,
released_quantity: releasedQuantity,
storage_release_summary: storageReleaseSummary,
};
} catch (error) {
if (!externalTransaction) {
await transaction.rollback();
}
throw error;
}
}
/**
* 分拣缺货补货需求计算。
*

View File

@ -673,7 +673,7 @@ class stockStoreService extends Service {
* @param {string} [meta.remark] 备注。
* @param {string} [meta.operatorId] 操作人ID。
* @param {string} [meta.operatorName] 操作人姓名。
* @return {Promise<{success: boolean, error?: string, data?: Object}>}
* @return {Promise<{success: boolean, error?: string, data?: Object}>} 修改结果,失败时携带错误信息。
*/
async updateLockedQuantity(stockId, change, currentTransaction, meta = {}) {
const { ctx, app } = this;
@ -914,6 +914,21 @@ class stockStoreService extends Service {
const afterQuantity = Number(updatedRecord.quantity) || 0;
const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0;
// 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据)
if (beforeQuantity <= 0) {
const nonNegativeDelta = Math.max(0, afterQuantity) - Math.max(0, beforeQuantity);
const offsetQty = await ctx.service.systems.storage.index.offsetGapOnInbound(storage.id, inboundQty, {
transaction: currentTransaction,
maxOffset: nonNegativeDelta,
orderNo: 'STOCK_STORE_INBOUND',
operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''),
operatorName: ctx.user?.employees_name || '',
});
if (offsetQty > 0) {
app.logger.info(`[入库] 负库存回填平账,冲销 GAP 挂账 ${offsetQty} 件 stockId=${storage.id}`);
}
}
await ctx.service.systems.stockTransaction.create({
transaction_type: 'INBOUND',
warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id,
@ -1601,8 +1616,8 @@ class stockStoreService extends Service {
* @param {Object} sortParams - 排序参数
* @param {string} sortParams.sortField - 排序字段,默认'create_at'
* @param {string} sortParams.sortOrder - 排序方式,默认'DESC'
* @param externalWarehouseId
* @param externalStoreId
* @param {number} externalWarehouseId - 外部传入的仓库ID,缺省取当前用户仓库上下文
* @param {number} externalStoreId - 外部传入的货主ID,缺省不按货主过滤
* @return {Promise<Object>} 返回查询结果
*/
async getWarehouseStock(where, pageParams = {}, sortParams = {}, externalWarehouseId = 0, externalStoreId = 0) {
@ -3914,7 +3929,7 @@ class stockStoreService extends Service {
where: storageWhere,
attributes: [
'id', 'stock_id', 'space_id', 'batch_no', 'inventory_type',
'quantity', 'locked_quantity', 'available_quantity',
'quantity', 'locked_quantity', 'intercept_locked_quantity', 'available_quantity',
'production_date', 'expiry_date', 'inbound_time',
'inbound_order_no', 'supplier_batch_no', 'created_at',
],
@ -3953,16 +3968,20 @@ class stockStoreService extends Service {
const existing = mergedMap.get(spaceKey);
existing.quantity += Number(s.quantity) || 0;
existing.locked_quantity += Number(s.locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity;
existing.intercept_locked_quantity += Number(s.intercept_locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity
- existing.intercept_locked_quantity;
} else {
const quantity = Number(s.quantity) || 0;
const lockedQuantity = Number(s.locked_quantity) || 0;
const interceptLockedQuantity = Number(s.intercept_locked_quantity) || 0;
mergedMap.set(spaceKey, {
space_id: s.space_id,
inventory_type: s.inventory_type,
quantity,
locked_quantity: lockedQuantity,
available_quantity: quantity - lockedQuantity,
intercept_locked_quantity: interceptLockedQuantity,
available_quantity: quantity - lockedQuantity - interceptLockedQuantity,
space: s.space,
});
}
@ -4070,7 +4089,7 @@ class stockStoreService extends Service {
where: storageWhere,
attributes: [
'id', 'space_id', 'inventory_type',
'quantity', 'locked_quantity', 'created_at',
'quantity', 'locked_quantity', 'intercept_locked_quantity', 'created_at',
],
include: [{
model: app.model.LocationSpace,
@ -4099,10 +4118,13 @@ class stockStoreService extends Service {
const existing = mergedMap.get(key);
existing.quantity += Number(plain.quantity) || 0;
existing.locked_quantity += Number(plain.locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity;
existing.intercept_locked_quantity += Number(plain.intercept_locked_quantity) || 0;
existing.available_quantity = existing.quantity - existing.locked_quantity
- existing.intercept_locked_quantity;
} else {
const quantity = Number(plain.quantity) || 0;
const lockedQuantity = Number(plain.locked_quantity) || 0;
const interceptLockedQuantity = Number(plain.intercept_locked_quantity) || 0;
mergedMap.set(key, {
id: plain.id,
space_id: plain.space_id,
@ -4110,7 +4132,8 @@ class stockStoreService extends Service {
inventory_type: plain.inventory_type,
quantity,
locked_quantity: lockedQuantity,
available_quantity: quantity - lockedQuantity,
intercept_locked_quantity: interceptLockedQuantity,
available_quantity: quantity - lockedQuantity - interceptLockedQuantity,
production_date: null,
expiry_date: null,
inbound_time: null,

View File

@ -1718,6 +1718,19 @@ class EntryService extends Service {
await stockRecord.increment('quantity', { by: planQty, transaction, silent: true });
await stockRecord.reload({ transaction });
// 负库存回填:按 SW 非负增量冲销 GAP 补建行挂账(平账,拦截锁定回归真实数据)
if (beforeQuantity <= 0) {
const nonNegativeDelta = Math.max(0, Number(stockRecord.quantity) || 0) - Math.max(0, beforeQuantity);
await ctx.service.systems.storage.index.offsetGapOnInbound(stockId, planQty, {
transaction,
maxOffset: nonNegativeDelta,
orderNo: eo.entry_order_code || 'QUICK_INBOUND',
orderId: eo.id,
operatorId: String(ctx.user?.employees_id || ctx.user?.id || ''),
operatorName: ctx.user?.employees_name || '',
});
}
const afterQuantity = Number(stockRecord.quantity) || 0;
const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0;
@ -1759,12 +1772,16 @@ class EntryService extends Service {
let storageAfterQty = 0;
let storageBeforeLockedQty = 0;
let storageAfterLockedQty = 0;
let storageBeforeInterceptQty = 0;
let storageAfterInterceptQty = 0;
if (storageRecord) {
storageBeforeQty = Number(storageRecord.quantity) || 0;
storageAfterQty = storageBeforeQty + planQty;
storageBeforeLockedQty = Number(storageRecord.locked_quantity) || 0;
storageAfterLockedQty = storageBeforeLockedQty;
storageBeforeInterceptQty = Number(storageRecord.intercept_locked_quantity) || 0;
storageAfterInterceptQty = storageBeforeInterceptQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${planQty}`),
@ -1820,6 +1837,8 @@ class EntryService extends Service {
after_quantity: storageAfterQty,
before_locked_quantity: storageBeforeLockedQty,
after_locked_quantity: storageAfterLockedQty,
before_intercept_locked_quantity: storageBeforeInterceptQty,
after_intercept_locked_quantity: storageAfterInterceptQty,
batch_no: batchNo,
inventory_type: inventoryType,
order_type: 'entry_order',

View File

@ -113,8 +113,24 @@ class IndexService extends Service {
});
}
/**
* 更新库存数量、锁定数量与拦截锁定数量,并按统一口径重算可用数量。
*
* 可用数量统一口径:
* `available_quantity = quantity - locked_quantity - intercept_locked_quantity`。
*
* @param {number} id 库存记录 ID。
* @param {number} quantityChange 库存数量变化量(正数为增加,负数为减少)。
* @param {number} [lockedChange=0] 锁定数量变化量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @param {number} [options.interceptLockedChange=0] 拦截锁定数量变化量(正数为拦截锁定,负数为释放;
* 允许结果为负值:差异对账场景下 storage 比 stock 少的差异以负拦截锁定入账,可用数量等量回补)。
* @return {Promise<Object>} 更新后的库存记录。
*/
async updateQuantity(id, quantityChange, lockedChange = 0, options = {}) {
const { ctx } = this;
const interceptLockedChange = Number((options && options.interceptLockedChange) || 0);
const applyUpdate = async transaction => {
const storage = await ctx.model.Storage.findByPk(id, {
transaction,
@ -127,19 +143,35 @@ class IndexService extends Service {
const newQuantity = storage.quantity + quantityChange;
const newLocked = storage.locked_quantity + lockedChange;
const newInterceptLocked = Number(storage.intercept_locked_quantity || 0) + interceptLockedChange;
if (newQuantity < 0) {
throw new Error('库存数量不能为负数');
}
if (newLocked < 0 || newLocked > newQuantity) {
if (newLocked < 0) {
throw new Error('锁定数量无效');
}
// 拦截锁定允许为负(差异对账:storage 比 stock 少的差异以负值入账,可用数量回补);
// 上界仍禁止超过库存数量;锁定数量仍禁止为负
if (newInterceptLocked > newQuantity) {
throw new Error('拦截锁定数量无效');
}
// 总和上界:锁定与拦截锁定之和不能超过库存数量;
// 等价于锁定后可用不为负(available ≥ 0)。
// 负拦截锁(差异对账补回)时锁定量可超过 quantity,但总和上限口径不变,
// 保证补回的可用数量可真实被锁定使用。
if (newLocked + newInterceptLocked > newQuantity) {
throw new Error('锁定数量与拦截锁定数量之和不能超过库存数量');
}
const updateData = {
quantity: newQuantity,
locked_quantity: newLocked,
available_quantity: newQuantity - newLocked,
intercept_locked_quantity: newInterceptLocked,
available_quantity: newQuantity - newLocked - newInterceptLocked,
updated_at: new Date(),
};
@ -175,10 +207,28 @@ class IndexService extends Service {
return await this.updateQuantity(id, 0, quantity, options);
}
/**
* 解除指定库存记录的锁定数量(锁定数量减少,可用数量等量增加)。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要解除锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async unlockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, -quantity, options);
}
/**
* 从可用数量中分配锁定指定数量(锁定数量增加,可用数量等量减少)。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要分配锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async allocateQuantity(id, quantity, options = {}) {
const { ctx } = this;
const storage = await ctx.model.Storage.findByPk(id, {
@ -196,6 +246,180 @@ class IndexService extends Service {
return await this.updateQuantity(id, 0, quantity, options);
}
/**
* 将作业锁定数量迁移为拦截锁定数量(拦截确认专用,pending 拣货行)。
*
* 库存总量与可用数量均不变,仅将锁定类型从 `locked_quantity` 迁移到 `intercept_locked_quantity`:
* `locked_quantity -q`、`intercept_locked_quantity +q`、`quantity` 与 `available_quantity` 不变。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要迁移为拦截锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async interceptLockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, -quantity, {
...options,
interceptLockedChange: quantity,
});
}
/**
* 实物返还并拦截锁定(拦截确认专用,fin 已拣货行)。
*
* 库存总量与拦截锁定数量等量增加,可用数量不变:
* `quantity +q`、`intercept_locked_quantity +q`、`locked_quantity` 与 `available_quantity` 不变。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要返还并拦截锁定的数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async interceptReceiveQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, quantity, 0, {
...options,
interceptLockedChange: quantity,
});
}
/**
* 释放拦截锁定数量,使其回落到可用数量(解除拦截/退货登记专用)。
*
* 库存总量与作业锁定数量不变,拦截锁定数量减少、可用数量等量增加:
* `intercept_locked_quantity -q`、`available_quantity +q`、`quantity` 与 `locked_quantity` 不变。
*
* @param {number} id 库存记录 ID。
* @param {number} quantity 需要释放的拦截锁定数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @return {Promise<Object>} 更新后的库存记录。
*/
async interceptUnlockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, 0, {
...options,
interceptLockedChange: -quantity,
});
}
/**
* 入库回填平账:负库存入库时,按入库量冲销该商品的 GAP 补建行挂账。
*
* 背景:差异对账(INTERCEPT_GAP)对无行/截断差异会补建 GAP- 前缀库存行承载拦截锁定;
* 当负库存商品真实入库回填时,将补建行挂账按入库量冲销(quantity/intercept 同减),
* 账归真实入库数据,避免补建挂账与真实入库叠加造成虚账。
*
* 冲销口径:每行冲销量 m = min(入库量, 行 quantity, 行 intercept_locked_quantity);
* available 按统一口径重算(quantity 与 intercept 同减,available 不变);
* 写 INTERCEPT_GAP(UNLOCK 方向)冲销流水,保留快照可追溯。
*
* 冲销上限:差异基准为 max(SW.quantity, 0),只有 SW 在非负区间的增量才会收窄差异;
* SW 在负数区间回填(如 -10→0)不改变基准,不冲销。因此调用方应传入
* options.maxOffset = max(0, 入库后SW) - max(0, 入库前SW),缺省时按入库量冲销(兼容)。
*
* @param {number} stockId 商品SKU ID(wms_stock_warehouse.id)。
* @param {number} qty 本次入库数量。
* @param {Object} [options={}] 执行上下文与事务参数。
* @param {Object} [options.transaction] Sequelize 事务对象。
* @param {number} [options.maxOffset] 冲销上限(推荐传 SW 非负区间增量,缺省=入库量)。
* @param {string} [options.orderNo] 入库单号/来源标识(流水追溯)。
* @param {number} [options.orderId] 关联订单/入库单 ID。
* @param {string} [options.operatorId] 操作人 ID。
* @param {string} [options.operatorName] 操作人名。
* @return {Promise<number>} 实际冲销量。
*/
async offsetGapOnInbound(stockId, qty, options = {}) {
const { ctx, app } = this;
const inboundQty = Number(qty) || 0;
if (!stockId || inboundQty <= 0) return 0;
const maxOffset = options.maxOffset !== undefined && options.maxOffset !== null
? Math.max(0, Number(options.maxOffset) || 0)
: inboundQty;
if (maxOffset <= 0) return 0;
const apply = async transaction => {
const gapRows = await ctx.model.Storage.findAll({
where: {
stock_id: stockId,
is_enabled: 1,
delete_at: null,
[app.Sequelize.Op.or]: [
{ batch_no: { [app.Sequelize.Op.like]: 'GAP-%' } },
{ inbound_order_no: { [app.Sequelize.Op.like]: 'GAP-%' } },
],
},
order: [[ 'id', 'ASC' ]],
lock: transaction ? transaction.LOCK.UPDATE : undefined,
transaction,
});
let remain = inboundQty;
let offsetTotal = 0;
let offsetBudget = maxOffset;
for (const row of gapRows) {
if (remain <= 0 || offsetBudget <= 0) break;
const gapQty = Number(row.quantity) || 0;
const gapIntercept = Number(row.intercept_locked_quantity) || 0;
const offsetQty = Math.min(remain, offsetBudget, Math.min(gapQty, gapIntercept));
if (offsetQty <= 0) continue;
const newQty = gapQty - offsetQty;
const newIntercept = gapIntercept - offsetQty;
const lockedQty = Number(row.locked_quantity) || 0;
await row.update({
quantity: newQty,
intercept_locked_quantity: newIntercept,
available_quantity: newQty - lockedQty - newIntercept,
updated_at: new Date(),
}, { transaction });
// 冲销流水(UNLOCK 方向,快照守恒:after = before - offsetQty)
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',
warehouse_id: row.warehouse_id,
store_id: row.store_id,
stock_id: stockId,
storage_id: row.id,
space_id: row.space_id,
quantity: offsetQty,
before_quantity: gapQty,
after_quantity: newQty,
before_locked_quantity: lockedQty,
after_locked_quantity: lockedQty,
before_intercept_locked_quantity: gapIntercept,
after_intercept_locked_quantity: newIntercept,
batch_no: row.batch_no,
inventory_type: row.inventory_type,
order_type: 'INTERCEPT_GAP',
order_no: String(options.orderNo || 'INBOUND_GAP_OFFSET').slice(0, 255),
order_id: Number(options.orderId || 0) || null,
operator_id: options.operatorId || null,
operator_name: options.operatorName || '',
remark: '入库回填平账(冲销差异挂账)',
created_at: new Date(),
}, { transaction });
remain -= offsetQty;
offsetBudget -= offsetQty;
offsetTotal += offsetQty;
}
return offsetTotal;
};
if (options.transaction) {
return await apply(options.transaction);
}
return await ctx.model.transaction(async transaction => {
return await apply(transaction);
});
}
async getStockSummary(warehouseId) {
const { ctx, app } = this;

View File

@ -272,6 +272,8 @@ class InventoryService extends Service {
const totalSnapshotQuantity = Number(data.totalSnapshotQuantity) || 0;
const totalSnapshotLockedQuantity = Number(data.totalSnapshotLockedQuantity) || 0;
// 拦截锁定快照:wms_stock_warehouse 层无该字段,取源库位行值(移库不动拦截锁,before=after)
const sourceInterceptLockedQuantity = Number(data.srcRecord?.intercept_locked_quantity) || 0;
await ctx.model.StorageTransaction.create({
transaction_type: 'TRANSFER_OUT',
@ -293,6 +295,8 @@ class InventoryService extends Service {
after_quantity: totalSnapshotQuantity,
before_locked_quantity: totalSnapshotLockedQuantity,
after_locked_quantity: totalSnapshotLockedQuantity,
before_intercept_locked_quantity: sourceInterceptLockedQuantity,
after_intercept_locked_quantity: sourceInterceptLockedQuantity,
source_order_codes: null,
created_at: new Date(),
}, {
@ -319,6 +323,8 @@ class InventoryService extends Service {
after_quantity: totalSnapshotQuantity,
before_locked_quantity: totalSnapshotLockedQuantity,
after_locked_quantity: totalSnapshotLockedQuantity,
before_intercept_locked_quantity: sourceInterceptLockedQuantity,
after_intercept_locked_quantity: sourceInterceptLockedQuantity,
source_order_codes: null,
created_at: new Date(),
}, {
@ -2251,6 +2257,8 @@ class InventoryService extends Service {
let sAfterQty = 0;
let sBeforeLockedQty = 0;
let sAfterLockedQty = 0;
let sBeforeInterceptQty = 0;
let sAfterInterceptQty = 0;
if (sRecord) {
if (Number(sRecord.stock_id) !== Number(sid)) {
@ -2263,6 +2271,8 @@ class InventoryService extends Service {
sAfterQty = sBeforeQty + qty;
sBeforeLockedQty = Number(sRecord.locked_quantity) || 0;
sAfterLockedQty = sBeforeLockedQty;
sBeforeInterceptQty = Number(sRecord.intercept_locked_quantity) || 0;
sAfterInterceptQty = sBeforeInterceptQty;
await ctx.model.Storage.update({
quantity: app.Sequelize.literal(`quantity + ${qty}`),
@ -2322,6 +2332,8 @@ class InventoryService extends Service {
after_quantity: sAfterQty,
before_locked_quantity: sBeforeLockedQty,
after_locked_quantity: sAfterLockedQty,
before_intercept_locked_quantity: sBeforeInterceptQty,
after_intercept_locked_quantity: sAfterInterceptQty,
batch_no: batchNo,
inventory_type: inventoryType,
order_type: 'entry_order',

View File

@ -0,0 +1,75 @@
'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: add intercept_locked_quantity to wms_storage
* - intercept_locked_quantity: INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量'
*
* Idempotent: uses queryInterface.describeTable to only add if missing.
*
* Raw SQL (MySQL 8+ supports IF NOT EXISTS):
* ALTER TABLE `wms_storage`
* ADD COLUMN IF NOT EXISTS `intercept_locked_quantity` INT(12) NOT NULL DEFAULT 0 COMMENT '拦截锁定数量';
*
* If MySQL < 8 (no IF NOT EXISTS), use INFORMATION_SCHEMA checks before ALTER.
*/
module.exports = {
/**
* 执行正向迁移,按需新增库存拦截锁定数量字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const table = 'wms_storage';
await logMigrationDbContext(queryInterface, 'up', table);
const columns = await queryInterface.describeTable(table);
if (!columns.intercept_locked_quantity) {
await queryInterface.addColumn(table, 'intercept_locked_quantity', {
type: Sequelize.INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '拦截锁定数量',
});
}
},
/**
* 执行回滚迁移,按需删除库存拦截锁定数量字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const table = 'wms_storage';
await logMigrationDbContext(queryInterface, 'down', table);
const columns = await queryInterface.describeTable(table);
if (columns.intercept_locked_quantity) {
await queryInterface.removeColumn(table, 'intercept_locked_quantity');
}
},
};

View File

@ -0,0 +1,84 @@
'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: add intercept locked quantity snapshots to wms_storage_transaction
* - before_intercept_locked_quantity: INT NULL COMMENT '变更前拦截锁定数量'
* - after_intercept_locked_quantity: INT NULL COMMENT '变更后拦截锁定数量'
*
* 与既有 before/after_locked_quantity 快照字段保持一致:
* 可空(NULL)、无默认值,由写入逻辑维护。
*
* Idempotent: uses queryInterface.describeTable to only add if missing.
*/
module.exports = {
/**
* 执行正向迁移,按需新增拦截锁定数量快照字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const table = 'wms_storage_transaction';
await logMigrationDbContext(queryInterface, 'up', table);
const columns = await queryInterface.describeTable(table);
if (!columns.before_intercept_locked_quantity) {
await queryInterface.addColumn(table, 'before_intercept_locked_quantity', {
type: Sequelize.INTEGER,
allowNull: true,
comment: '变更前拦截锁定数量',
});
}
if (!columns.after_intercept_locked_quantity) {
await queryInterface.addColumn(table, 'after_intercept_locked_quantity', {
type: Sequelize.INTEGER,
allowNull: true,
comment: '变更后拦截锁定数量',
});
}
},
/**
* 执行回滚迁移,按需删除拦截锁定数量快照字段。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
const table = 'wms_storage_transaction';
await logMigrationDbContext(queryInterface, 'down', table);
const columns = await queryInterface.describeTable(table);
if (columns.before_intercept_locked_quantity) {
await queryInterface.removeColumn(table, 'before_intercept_locked_quantity');
}
if (columns.after_intercept_locked_quantity) {
await queryInterface.removeColumn(table, 'after_intercept_locked_quantity');
}
},
};