This commit is contained in:
liufumingren 2026-07-04 21:40:31 +08:00
parent 5d7964132e
commit 7f05b26db2
18 changed files with 794 additions and 881 deletions

View File

@ -1,46 +0,0 @@
'use strict';
/**
* 拣货完成补偿定时任务。
* 每 1 分钟在单 worker 中扫描一次:当 wms_picking 中存在 status='pending' 的遗漏记录,
* 且对应订单已迁移到配送 dispatch 表且 pick_status='fin' 时,补扣库存并写入出库流水。
*
* 补偿判断条件:
* 1. wms_picking.status = 'pending' 且 warehouse_id > 0
* 2. 对应订单在 order_delivery_dispatch 表中 pick_status = 'fin'
* 3. 对应订单不在 order_delivery 主表中(已迁移)
*/
module.exports = {
schedule: {
interval: '1m',
type: 'worker',
immediate: true,
disable: false,
},
/**
* 执行拣货完成补偿任务。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
if (ctx.app._pickCompensationRunning) {
return;
}
ctx.app._pickCompensationRunning = true;
try {
const result = await ctx.service.systems.pickCompensation.executeCompensation();
ctx.logger.info(
`[pick-compensation] 本轮补偿完成,共处理 ${result && result.totalCompensated || 0} 条拣货记录`
);
} catch (error) {
ctx.logger.error(`[pick-compensation] 补偿任务执行失败: ${error.message}`);
} finally {
ctx.app._pickCompensationRunning = false;
}
},
};

View File

@ -1,187 +0,0 @@
'use strict';
const DEFAULT_INTERVAL_MS = 60 * 1000;
const DEFAULT_BATCH_SIZE = 50;
/**
* 归一化打印补偿调度配置。
* @param {Object} app Egg 应用实例。
* @return {{enable:boolean,intervalMs:number,batchSize:number,force:boolean}} 标准化配置。
*/
function getCompensationConfig(app) {
const rawConfig = app && app.config && app.config.printRetryCompensation
? app.config.printRetryCompensation
: {};
const intervalMs = Number.parseInt(rawConfig.intervalMs, 10);
const batchSize = Number.parseInt(rawConfig.batchSize, 10);
return {
enable: Boolean(rawConfig.enable),
intervalMs: Number.isInteger(intervalMs) && intervalMs > 0 ? intervalMs : DEFAULT_INTERVAL_MS,
batchSize: Number.isInteger(batchSize) && batchSize > 0 ? batchSize : DEFAULT_BATCH_SIZE,
force: Boolean(rawConfig.force),
};
}
/**
* 按仓库维度分组打印记录。
* @param {Array<Object>} printRecords 打印记录列表。
* @return {Map<number, Array<number>>} 仓库到打印记录 ID 的映射。
*/
function groupPrintIdsByWarehouse(printRecords = []) {
const groupedMap = new Map();
if (!Array.isArray(printRecords)) {
return groupedMap;
}
for (const printRecord of printRecords) {
const warehouseId = Number(printRecord && printRecord.warehouse_id);
const printId = Number(printRecord && printRecord.id);
if (!Number.isInteger(warehouseId) || warehouseId <= 0 || !Number.isInteger(printId) || printId <= 0) {
continue;
}
const currentPrintIds = groupedMap.get(warehouseId) || [];
currentPrintIds.push(printId);
groupedMap.set(warehouseId, currentPrintIds);
}
return groupedMap;
}
/**
* 自动扫描并触发失败打印补偿任务。
*/
module.exports = {
schedule: {
interval: '30s',
type: 'worker',
immediate: false,
disable: false,
},
/**
* 执行打印失败自动补偿任务。
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
const taskName = 'print-retry-compensation';
const compensationConfig = getCompensationConfig(ctx.app);
if (!compensationConfig.enable) {
return;
}
if (ctx.app._printRetryCompensationRunning) {
ctx.logger.info(`[${taskName}] 任务仍在运行中,跳过本轮调度`);
return;
}
const nowMs = Date.now();
const lastRunAt = Number(ctx.app._printRetryCompensationLastRunAt || 0);
if (lastRunAt > 0 && (nowMs - lastRunAt) < compensationConfig.intervalMs) {
return;
}
ctx.app._printRetryCompensationRunning = true;
ctx.app._printRetryCompensationLastRunAt = nowMs;
let scannedCount = 0;
let invokeCount = 0;
let retriedSuccessCount = 0;
let retriedFailedCount = 0;
let skippedCount = 0;
try {
const { Op } = ctx.app.Sequelize;
const printRecords = await ctx.model.PrintRecord.findAll({
attributes: [ 'id', 'warehouse_id', 'retry_count', 'max_retry_count', 'next_retry_at', 'send_status', 'print_status' ],
where: {
[Op.and]: [
{
[Op.or]: [
{ send_status: 'send_failed' },
{
print_status: {
[Op.in]: [ 'print_failed', 'timeout' ],
},
},
],
},
{
next_retry_at: {
[Op.lte]: new Date(),
},
},
{
retry_count: {
[Op.lt]: ctx.app.Sequelize.col('max_retry_count'),
},
},
],
},
order: [
[ 'next_retry_at', 'ASC' ],
[ 'id', 'ASC' ],
],
limit: compensationConfig.batchSize,
raw: true,
});
scannedCount = Array.isArray(printRecords) ? printRecords.length : 0;
if (scannedCount === 0) {
return;
}
const groupedPrintIds = groupPrintIdsByWarehouse(printRecords);
for (const [ warehouseId, printIds ] of groupedPrintIds.entries()) {
if (!Array.isArray(printIds) || printIds.length === 0) {
continue;
}
invokeCount += 1;
try {
const retryResult = await ctx.service.systemMethods.print.retryFailed({
print_ids: printIds,
warehouse_id: warehouseId,
force: compensationConfig.force,
});
if (!retryResult || retryResult.flag !== 'success') {
ctx.logger.warn(`[${taskName}] 触发补打失败`, {
warehouseId,
printIdsCount: printIds.length,
message: retryResult && retryResult.message ? retryResult.message : '未知错误',
});
continue;
}
retriedSuccessCount += Number(retryResult.success_count || 0);
retriedFailedCount += Number(retryResult.failed_count || 0);
skippedCount += Number(retryResult.skipped_count || 0);
} catch (error) {
ctx.logger.error(`[${taskName}] 触发补打异常`, {
warehouseId,
printIdsCount: printIds.length,
error: error && error.message ? error.message : `${error}`,
});
}
}
ctx.logger.info(`[${taskName}] 任务执行完成`, {
scannedCount,
warehouseGroupCount: groupedPrintIds.size,
invokeCount,
retriedSuccessCount,
retriedFailedCount,
skippedCount,
});
} catch (error) {
ctx.logger.error(`[${taskName}] 执行失败`, {
error: error && error.message ? error.message : `${error}`,
});
} finally {
ctx.app._printRetryCompensationRunning = false;
}
},
};

View File

@ -28,7 +28,6 @@ module.exports = {
let submitSuccessCount = 0;
let reusedRunningTaskCount = 0;
let submitFailedCount = 0;
let cleanupDeletedCount = 0;
try {
const storeRows = await ctx.model.Store.findAll({
@ -124,22 +123,11 @@ module.exports = {
}
}
try {
cleanupDeletedCount = Number(
await ctx.service.systemMethods.order.wave.cleanupWaveStrategyQuickScanMatchedStrategies({ expireHours: 24 })
) || 0;
} catch (cleanupError) {
ctx.logger.warn(`[${FALLBACK_TASK_NAME}] 命中副表清理失败`, {
error: cleanupError && cleanupError.message ? cleanupError.message : `${cleanupError}`,
});
}
ctx.logger.info(`[${FALLBACK_TASK_NAME}] 任务完成`, {
totalWarehouseCount,
submitSuccessCount,
reusedRunningTaskCount,
submitFailedCount,
cleanupDeletedCount,
});
} catch (error) {
ctx.logger.error(`[${FALLBACK_TASK_NAME}] 任务执行失败: ${error && error.message ? error.message : error}`);

View File

@ -247,16 +247,12 @@ class OpenapiOrderService extends MainService {
const qty = Number(item.plan_qty || 0);
if (stockId <= 0 || qty <= 0) continue;
await stockModel.update(
{
locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`),
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{
where: { id: stockId, locked_quantity: { [Op.gte]: qty } },
transaction,
}
);
await ctx.service.systems.stockStore.updateLockedQuantity(stockId, -qty, transaction, {
remark: 'OpenAPI取消订单-释放创建锁',
orderType: 'ORDER_CANCEL',
orderNo: String(orderId),
orderId,
});
}
return;
}
@ -309,22 +305,17 @@ class OpenapiOrderService extends MainService {
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction });
// 释放 wms_stock_warehouse.locked_quantity
const decrementResult = await stockModel.update(
{
locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`),
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{
where: {
id: stockId,
locked_quantity: { [Op.gte]: Number(quantity) },
},
transaction,
const releaseResult = await ctx.service.systems.stockStore.updateLockedQuantity(
stockId, -Number(quantity), transaction, {
remark: 'OpenAPI取消订单-释放储位锁',
orderType: 'ORDER_CANCEL',
orderNo: String(orderId),
orderId,
}
);
if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) {
throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`);
if (!releaseResult.success) {
throw new Error(`库存主记录释放失败: stockId=${stockId}, ${releaseResult.error}`);
}
}

View File

@ -361,16 +361,12 @@ class orderServer extends MainService {
const qty = Number(item.plan_qty || 0);
if (stockId <= 0 || qty <= 0) continue;
await stockModel.update(
{
locked_quantity: app.Sequelize.literal(`locked_quantity - ${qty}`),
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{
where: { id: stockId, locked_quantity: { [Op.gte]: qty } },
transaction,
}
);
await ctx.service.systems.stockStore.updateLockedQuantity(stockId, -qty, transaction, {
remark: '奇门取消订单-释放创建锁',
orderType: 'ORDER_CANCEL',
orderNo: String(orderId),
orderId,
});
}
return;
}
@ -423,22 +419,17 @@ class orderServer extends MainService {
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction });
// 释放 wms_stock_warehouse.locked_quantity
const decrementResult = await stockModel.update(
{
locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`),
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{
where: {
id: stockId,
locked_quantity: { [Op.gte]: Number(quantity) },
},
transaction,
const releaseResult = await ctx.service.systems.stockStore.updateLockedQuantity(
stockId, -Number(quantity), transaction, {
remark: '奇门取消订单-释放储位锁',
orderType: 'ORDER_CANCEL',
orderNo: String(orderId),
orderId,
}
);
if (!Array.isArray(decrementResult) || Number(decrementResult[0] || 0) <= 0) {
throw new Error(`库存主记录锁定数量不足,无法释放: stockId=${stockId}, quantity=${quantity}`);
if (!releaseResult.success) {
throw new Error(`库存主记录释放失败: stockId=${stockId}, ${releaseResult.error}`);
}
}

View File

@ -117,7 +117,8 @@ class stockoutServer extends MainService {
item.stockId,
item.planQty,
transaction,
oversellConfig
oversellConfig,
{ orderType: 'QM_STOCKOUT', orderNo: deliveryOrder.deliveryOrderCode, orderId }
);
if (!lockResult.success) {
throw new Error(

View File

@ -506,9 +506,9 @@ class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,updateRemark,updateAddress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress,batchIntercept,batchInterceptTaskProgress,batchLock,batchLockTaskProgress,batchUnlock,batchUnlockTaskProgress,batchUnintercept,batchUninterceptTaskProgress,manualWaybill';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -2277,8 +2277,7 @@ class PendingOrderService extends OrderBaseService {
/**
* 批量修改待处理订单的收件地址信息。
*
* 地址字段仅允许在未分配快递(post_status = 'none')时修改;
* remark 不受 post_status 限制,可独立或与地址字段同时传入。
* 地址字段仅允许在未分配快递(post_status = 'none')时修改。
* 支持批量操作,返回更新数量和受影响的订单 ID 列表。
*
* @param {Object} data 请求体。
@ -2292,7 +2291,6 @@ class PendingOrderService extends OrderBaseService {
* @param {string} [data.area] 区/县。
* @param {string} [data.town] 镇/街道。
* @param {string} [data.detail_address] 详细地址。
* @param {string} [data.remark] 订单留言/备注,对应 wms_order_delivery.remark,最大500字符。
* @return {Promise<Object>} 统一 success 包装的更新结果,含 updated_count 与 ids。
*/
async updateAddress(data = {}) {
@ -2320,18 +2318,9 @@ class PendingOrderService extends OrderBaseService {
}
}
// 处理 remark 字段(不受 post_status 限制,最大500字符)
let remarkValue = null;
if (requestData.remark !== undefined && requestData.remark !== null) {
const trimmed = String(requestData.remark).trim();
if (trimmed !== '') {
remarkValue = trimmed.substring(0, 500);
}
}
const hasAddressUpdates = Object.keys(addressUpdates).length > 0;
if (!hasAddressUpdates && remarkValue === null) {
throw new Error('至少需要提供一个地址字段或备注进行修改');
if (!hasAddressUpdates) {
throw new Error('至少需要提供一个地址字段进行修改');
}
const model = await this.getOrderModel('order', warehouseId);
@ -2339,7 +2328,6 @@ class PendingOrderService extends OrderBaseService {
const now = new Date();
let addressUpdatedCount = 0;
let remarkUpdatedCount = 0;
// 地址字段更新(受 post_status='none' 限制)
if (hasAddressUpdates) {
@ -2349,19 +2337,9 @@ class PendingOrderService extends OrderBaseService {
addressUpdatedCount = Number(rows || 0);
}
// remark 更新(不受 post_status 限制)
if (remarkValue !== null) {
const remarkUpdate = { remark: remarkValue, updated_at: now };
const [ rows ] = await model.update(remarkUpdate, { where: baseWhere });
remarkUpdatedCount = Number(rows || 0);
}
// 记录操作日志
try {
const updatedFieldNames = [
...Object.keys(addressUpdates).filter(k => k !== 'updated_at'),
...(remarkValue !== null ? [ 'remark' ] : []),
];
const updatedFieldNames = Object.keys(addressUpdates).filter(k => k !== 'updated_at');
await this.ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: logWarehouseId,
@ -2371,10 +2349,9 @@ class PendingOrderService extends OrderBaseService {
warehouseId: logWarehouseId,
orderIds,
updated_fields: updatedFieldNames,
updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount),
updated_count: addressUpdatedCount,
address_updated_count: addressUpdatedCount,
remark_updated_count: remarkUpdatedCount,
message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条,备注更新 ${remarkUpdatedCount} 条`,
message: `批量修改订单收件地址:订单ID [${orderIds.join(', ')}],更新字段 [${updatedFieldNames.join(', ')}],地址更新 ${addressUpdatedCount} 条`,
},
beforeChanges: null,
});
@ -2383,7 +2360,86 @@ class PendingOrderService extends OrderBaseService {
}
return this.success('ok', {
updated_count: Math.max(addressUpdatedCount, remarkUpdatedCount),
updated_count: addressUpdatedCount,
ids: orderIds,
});
}
/**
* 批量修改待处理订单的备注(remark)字段。
*
* 与 updateAddress 中的 remark 更新逻辑相似,
* 但作为独立接口只负责备注修改,不涉及地址字段。
* remark 修改不受 post_status 限制,对所有状态的订单均可生效。
*
* @param {Object} data 请求体。
* @param {Array<number>} data.ids 订单ID数组(必填,正整数数组)。
* @param {string} data.remark 备注内容(必填,最大500字符)。
* @return {Promise<Object>} 统一 success 包装的更新结果,含 updated_count 与 ids。
*/
async updateRemark(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
// 解析订单 ID(仅支持数组)
const rawOrderIds = requestData.ids;
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
throw new Error('ids 不能为空,且必须是正整数数组');
}
const orderIds = Array.from(new Set(rawOrderIds.map(v => {
const n = Number(v);
if (!Number.isInteger(n) || n <= 0) {
throw new Error('ids 仅支持正整数数组');
}
return n;
})));
// 解析 remark
const rawRemark = requestData.remark;
if (rawRemark === undefined || rawRemark === null) {
throw new Error('remark 不能为空');
}
const trimmed = String(rawRemark).trim();
if (trimmed === '') {
throw new Error('remark 不能为空字符串');
}
const remarkValue = trimmed.substring(0, 500);
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const now = new Date();
const [ affectedRows ] = await model.update(
{ remark: remarkValue, updated_at: now },
{ where },
);
const count = Number(affectedRows || 0);
// 记录操作日志
try {
await this.ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: logWarehouseId,
operationCode: 'ORDER_UPDATE_REMARK',
operator,
extras: {
warehouseId: logWarehouseId,
orderIds,
remark: remarkValue,
updated_count: count,
message: `批量修改订单备注:订单ID [${orderIds.join(', ')}],备注内容 [${remarkValue}],共更新 ${count} 条`,
},
beforeChanges: null,
});
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.updateRemark] 写入操作日志失败,不影响业务', logErr);
}
return this.success('ok', {
updated_count: count,
ids: orderIds,
});
}
@ -2834,7 +2890,7 @@ class PendingOrderService extends OrderBaseService {
detailAddress,
zipCode: String(requestData.zip_code || '').trim(),
},
seller_message: String(requestData.remark || '').trim(),
remark: String(requestData.remark || '').trim(),
},
orderLines: {
orderLine: orderLineItems,
@ -5316,23 +5372,19 @@ class PendingOrderService extends OrderBaseService {
}
// 释放 wms_stock_warehouse.locked_quantity
const stockService = ctx.service && ctx.service.systems && ctx.service.systems.stockStore;
for (const [ stockId, quantity ] of stockReleaseMap.entries()) {
const [ affectedCount ] = await stockModel.update(
{
locked_quantity: app.Sequelize.literal(`locked_quantity - ${Number(quantity)}`),
updated_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{
where: {
id: stockId,
locked_quantity: { [Op.gte]: Number(quantity) },
},
transaction,
const releaseResult = await stockService.updateLockedQuantity(
stockId, -Number(quantity), transaction, {
remark: '系统取消订单-释放创建锁',
orderType: 'ORDER_CANCEL',
orderNo: orderIds.join(','),
orderId: 0,
}
);
if (Number(affectedCount || 0) <= 0) {
throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}`);
if (!releaseResult.success) {
throw new Error(`库存主记录锁定数量不足,无法释放创建锁: stockId=${stockId}, quantity=${quantity}, ${releaseResult.error}`);
}
}

View File

@ -38,14 +38,18 @@ class entryService extends MainService {
}
/**
* 查询入库单详情。仅通过入库单 ID 定位。
* @param {Object} data 请求体
* @param {number} data.id 入库单ID(必填)
* @return {Promise<Object>} 统一 success 包装
*/
* 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。
* 返回入库单基本信息(id、entry_order_code、order_status、store_remask)、
* 商品明细列表(含计划数量、已完成入库数量、商品信息、收货单绑定明细),
* 以及收货单绑定关系列表。
* @param {Object} data 请求体
* @param {number} data.id 入库单ID(必填)
* @return {Promise<Object>} 统一 success 包装
*/
async get(data = {}) {
const { service } = this;
const result = await service.systems.storage.entry.get(data);
const { id } = data || {};
const result = await service.systems.storage.entry.get({ id });
return this.success('ok', result);
}
@ -66,16 +70,41 @@ class entryService extends MainService {
/**
* 按商品增量添加导入/PDA 直接入库记录(从 storage.entry 模块暴露)。
* @param {Object} data 请求体
* @param {string} data.entry_order_code 入库单号
* @param {number} data.entry_order_id 入库单ID
* @param {number} [data.stock_id] 商品SKU ID(单条模式)
* @param {number} [data.quantity] 本次入库数量(单条模式)
* @param {string} [data.inbound_type] 入库方式(单条模式)
* @param {Array} [data.items] 商品列表(批量模式)
* @param {string} [data.remark] 备注(单条模式)
* @param {number} [data.space_id] 库位ID(单条模式)
* @param {number} [data.receiving_detail_id] 收货单明细ID(单条模式,可选)
* @param {number} [data.allocated_quantity] 预分配数量(单条模式,可选)
* @return {Promise<Object>} 统一 success 包装
*/
async addItem(data = {}) {
const { service } = this;
const result = await service.systems.inboundDirectLog.addItem(data);
const {
entry_order_id,
stock_id,
quantity,
inbound_type,
items,
remark,
space_id,
receiving_detail_id,
allocated_quantity,
} = data || {};
const result = await service.systems.inboundDirectLog.addItem({
entry_order_id,
stock_id,
quantity,
inbound_type,
items,
remark,
space_id,
receiving_detail_id,
allocated_quantity,
});
return this.success('ok', result);
}
@ -166,20 +195,42 @@ class entryService extends MainService {
* @return {Promise<Object>} 打印数据(扁平键值 + items 明细数组)
*/
async getPrintData(data = {}) {
const { ctx, service } = this;
const { ctx } = this;
const id = Number(data && data.id || 0);
if (!id) {
return this.fail('id 参数不能为空', { code: 400 });
}
try {
const entryResult = await service.systems.storage.entry.get({ id });
if (!entryResult || entryResult.code !== 200 || !entryResult.data || !entryResult.data.entryOrder) {
// 直接查询入库单完整信息(含 items、warehouse、store 等关联),供打印模板使用
const entryOrder = await ctx.model.EntryOrder.findByPk(id, {
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.EntryItems,
as: 'items',
required: false,
},
],
});
if (!entryOrder || entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) {
return this.fail('入库单不存在', { code: 404 });
}
const entryOrder = entryResult.data.entryOrder;
const items = Array.isArray(entryOrder.items) ? entryOrder.items : [];
const entryOrderJSON = entryOrder.toJSON();
const items = Array.isArray(entryOrderJSON.items) ? entryOrderJSON.items : [];
// 查询商品条码和图片(复用 getStockDetails 缓存)
const barcodeMap = new Map();
@ -213,22 +264,22 @@ class entryService extends MainService {
}
const printData = {
entry_order_code: entryOrder.entry_order_code || '',
order_type: entryOrder.order_type || '',
order_status: entryOrder.order_status || '',
purchase_order_code: entryOrder.purchase_order_code || '',
supplier_name: entryOrder.supplier_name || '',
warehouse_name: entryOrder.warehouse_name || '',
store_name: entryOrder.store_name || '',
logistics_name: entryOrder.logistics_name || '',
express_code: entryOrder.express_code || '',
order_create_time: entryOrder.order_create_time || '',
expect_start_time: entryOrder.expect_start_time || '',
remark: entryOrder.remark || '',
total_order_lines: entryOrder.total_order_lines || 0,
entry_order_code: entryOrderJSON.entry_order_code || '',
order_type: entryOrderJSON.order_type || '',
order_status: entryOrderJSON.order_status || '',
purchase_order_code: entryOrderJSON.purchase_order_code || '',
supplier_name: entryOrderJSON.supplier_name || '',
warehouse_name: entryOrderJSON.warehouse_name || '',
store_name: entryOrderJSON.store_name || '',
logistics_name: entryOrderJSON.logistics_name || '',
express_code: entryOrderJSON.express_code || '',
order_create_time: entryOrderJSON.order_create_time || '',
expect_start_time: entryOrderJSON.expect_start_time || '',
remark: entryOrderJSON.remark || '',
total_order_lines: entryOrderJSON.total_order_lines || 0,
items: items.map(item => ({
items_col1: item.warehouse_item_code || item.external_item_code || '',
items_col2: item.warehouse_item_name || '',
items_col1: item.item_code || '',
items_col2: '',
items_col3: (barcodeMap.get(Number(item.stock_id)) || []).join(';') || '',
items_col4: item.count || 0,
items_col5: item.received_quantity || 0,

View File

@ -1221,7 +1221,8 @@ class DeliveryOrderService extends Service {
item.stockId,
item.planQty,
transaction,
oversellConfig
oversellConfig,
{ orderType: 'DELIVERY_ORDER', orderNo: String(orderId), orderId }
);
if (!lockResult.success) {

View File

@ -76,16 +76,21 @@ class InboundDirectLogService extends Service {
raw: true,
});
// 查询该入库单下已有的导入/PDA 入库记录
// 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录)
const directLogs = await ctx.model.InboundDirectLog.findAll({
where: { entry_order_id: entryOrder.id },
where: { entry_order_id: entryOrder.id, deleted_at: null },
order: [[ 'created_at', 'ASC' ]],
});
// 将直接入库记录按 entry_item_id 关联到明细
// 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式)
const itemDirectLogs = {};
for (const log of directLogs) {
const item = entryOrder.items.find(
// 绑定模式下 entry_item_id 已设置,优先用它定位明细行
const itemByEntryItemId = log.entry_item_id
? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id))
: null;
const item = itemByEntryItemId || entryOrder.items.find(
i => String(i.stock_id) === String(log.stock_id)
);
const key = item ? String(item.id) : `stock_${log.stock_id}`;
@ -135,12 +140,17 @@ class InboundDirectLogService extends Service {
const logKey = String(item.id);
const logs = itemDirectLogs[logKey] || [];
const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0);
// 优先使用已持久化的 received_quantity(commit 后由系统写入),
// 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量),
// 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。
const receivedQty = Number(item.received_quantity) || 0;
const completed = receivedQty > 0 ? receivedQty : directInQty;
return {
id: item.id,
stock_id: item.stock_id,
planned: planQty,
completed: directInQty,
completed,
stock: stockMap.get(Number(item.stock_id)) || null,
};
});
@ -345,7 +355,9 @@ class InboundDirectLogService extends Service {
return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } };
}
// 计算该 stock_id 在入库单明细中的计划总数与已收货总数
const totalPlanQty = entryItems.reduce((sum, ei) => sum + (Number(ei.count) || 0), 0);
const totalReceivedQty = entryItems.reduce((sum, ei) => sum + (Number(ei.received_quantity) || 0), 0);
// 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量
const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId };
@ -357,10 +369,10 @@ class InboundDirectLogService extends Service {
});
const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0);
// 绑定模式下跳过入库单计划数量校验(允许超过计划数量)
// 只有 PENDING 非绑定模式限制超量;CREATED 人工导入允许超过
// 绑定模式和非绑定模式均受可入库数量限制
// CREATED 人工导入允许超过计划数量
const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode;
if (!isBindingMode && !isManualImport) {
if (!isManualImport) {
const newTotal = existingTotal + effectiveQuantity;
if (newTotal > totalPlanQty) {
return {
@ -380,9 +392,56 @@ class InboundDirectLogService extends Service {
}
}
// 剩余可入库数 = 计划数 - max(已收货量, 已写入 direct_log 的待入库量)
// 避免多次 addItem 之间 received_quantity 始终为 0 导致的重复入库漏拦截
{
const occupiedQuantity = Math.max(totalReceivedQty, existingTotal);
const remainingQuantity = Math.max(0, totalPlanQty - occupiedQuantity);
if (remainingQuantity <= 0) {
return {
ok: false,
error: {
code: 400,
message: `商品 stock_id=${stockId} 无可入库数量:计划 ${totalPlanQty},已收货 ${totalReceivedQty}`,
},
};
}
if (effectiveQuantity > remainingQuantity) {
effectiveQuantity = remainingQuantity;
}
}
const newTotal = existingTotal + effectiveQuantity;
// 写入记录
// 绑定模式:只由 _bindReceivingDetail 负责写入(status='pending'),避免重复插入两条记录
if (isBindingMode) {
item.allocated_quantity = effectiveQuantity;
const receivingBindResult = await this._bindReceivingDetail(
ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction
);
if (receivingBindResult && receivingBindResult.error) {
return { ok: false, error: { code: 400, message: receivingBindResult.error } };
}
return {
ok: true,
log: {
id: receivingBindResult?.binding_id || 0,
stock_id: stockId,
quantity: effectiveQuantity,
inbound_type: inboundType,
space_id: spaceId,
plan_quantity: totalPlanQty,
existing_before: existingTotal,
existing_after: newTotal,
remaining: Math.max(0, totalPlanQty - newTotal),
receivingBindResult,
},
};
}
// 非绑定模式:直接写入一条无收货明细绑定的入库记录
const log = await ctx.model.InboundDirectLog.create({
warehouse_id: entryOrder.warehouse_id,
store_id: entryOrder.store_id,
@ -398,20 +457,6 @@ class InboundDirectLogService extends Service {
created_at: new Date(),
}, transaction ? { transaction } : {});
// 收货单明细绑定(可选)
let receivingBindResult = null;
if (isBindingMode) {
// 绑定模式:全量绑定,allocated_quantity = effectiveQuantity
item.allocated_quantity = effectiveQuantity;
receivingBindResult = await this._bindReceivingDetail(
ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction
);
} else if (receivingDetailId) {
receivingBindResult = await this._bindReceivingDetail(
ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction
);
}
return {
ok: true,
log: {
@ -424,7 +469,6 @@ class InboundDirectLogService extends Service {
existing_before: existingTotal,
existing_after: newTotal,
remaining: Math.max(0, totalPlanQty - newTotal),
...(receivingBindResult ? { receivingBindResult } : {}),
},
};
}
@ -773,9 +817,9 @@ class InboundDirectLogService extends Service {
return { code: 400, message: '入库单已完成,请勿重复提交', data: null };
}
// 查询该入库单下所有导入/PDA 入库记录
// 查询该入库单下所有未删除的导入/PDA 入库记录
const directLogs = await ctx.model.InboundDirectLog.findAll({
where: { entry_order_id: entryOrder.id },
where: { entry_order_id: entryOrder.id, deleted_at: null },
});
if (!directLogs || directLogs.length === 0) {
@ -847,7 +891,7 @@ class InboundDirectLogService extends Service {
if (detailIds.length > 0) {
const details = await ctx.model.ReceivingDetail.findAll({
where: { id: detailIds },
attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date' ],
attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date', 'actual_quantity' ],
raw: true,
});
const detailById = new Map(details.map(d => [ d.id, d ]));
@ -857,17 +901,55 @@ class InboundDirectLogService extends Service {
}
}
// 按 entry_item_id 汇总 wms_inbound_direct_log 的入库数量
const itemDirectLogQtyMap = {};
for (const log of directLogs) {
if (log.entry_item_id) {
const itemKey = String(log.entry_item_id);
if (!itemDirectLogQtyMap[itemKey]) itemDirectLogQtyMap[itemKey] = 0;
itemDirectLogQtyMap[itemKey] += Number(log.quantity);
}
}
// 逐商品写入库存
// 非绑定模式下同一 stock_id 可能对应多个 entryItem,按顺序:
// 第一个 entryItem 写库存和 received_quantity,后续同 stock_id 的 entryItem 仅写 received_quantity=0
const nonBindingStockProcessed = new Set();
for (const item of entryItems) {
const stockId = item.stock_id;
if (!stockId) continue;
const inboundQty = stockSummary[String(stockId)] || 0;
// 按 entry_item 维度获取该明细的直接入库汇总数量
const itemDirectQty = itemDirectLogQtyMap[String(item.id)] || 0;
const isBinding = itemDirectQty > 0;
const inboundQty = isBinding
? itemDirectQty
: (stockSummary[String(stockId)] || 0);
if (inboundQty <= 0) continue;
// 更新入库明细的 received_quantity(按该明细的计划占比分配)
const planQty = Number(item.count) || 0;
const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty;
// 判断是否为绑定模式:比较收货明细数量与入库记录数量
const bindInfo = bindingDetailMap.get(item.id);
let itemReceivedQty = inboundQty;
if (bindInfo) {
// 收货明细的实际数量
const rdQty = Number(bindInfo.actual_quantity) || 0;
// 该 entry_item 对应的入库记录汇总数量
const logSumQty = itemDirectLogQtyMap[String(item.id)] || 0;
if (rdQty > logSumQty) {
// 收货明细数量 > 入库记录数量 → 部分入库,仅入库实际记录的数量
itemReceivedQty = logSumQty;
} else {
// 收货明细数量 <= 入库记录数量 → 全部入库
itemReceivedQty = rdQty;
}
}
// 非绑定模式:同一 stock_id 只对第一个 entryItem 写入 received_quantity,后续写 0
if (!isBinding && nonBindingStockProcessed.has(String(stockId))) {
itemReceivedQty = 0;
}
// 更新入库明细的 received_quantity
await ctx.model.EntryItems.update({
received_quantity: itemReceivedQty,
}, {
@ -878,9 +960,11 @@ class InboundDirectLogService extends Service {
// 同一 stock_id 只写一次库存
if (processedStockIds.has(String(stockId))) continue;
processedStockIds.add(String(stockId));
if (!isBinding) {
nonBindingStockProcessed.add(String(stockId));
}
// 使用入库单号作为批次号;若有收货绑定则使用收货明细信息
const bindInfo = bindingDetailMap.get(item.id);
const rdReceivingId = bindInfo ? bindInfo.receiving_id : null;
const effectiveBatchNo = bindInfo?.batch_number || eo.entry_order_code;
const rdProductionDate = bindInfo?.production_date || null;

View File

@ -865,27 +865,6 @@ class OrderStorageAllocationService extends MainService {
});
if (Array.isArray(oldPickingRecords) && oldPickingRecords.length > 0) {
// 批量查询旧 picking 记录关联的 wms_storage,获取 stock_id 用于回退 StockWarehouse.locked_quantity
const oldStorageIds = oldPickingRecords
.map(record => toNumber(record.storage_id, 0))
.filter(storageId => storageId > 0);
const oldStorageMap = new Map();
if (oldStorageIds.length > 0) {
const oldStorageRows = await ctx.model.Storage.findAll({
where: { id: { [Op.in]: oldStorageIds }, warehouse_id: warehouseId },
attributes: [ 'id', 'stock_id' ],
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
for (const oldStorageRow of Array.isArray(oldStorageRows) ? oldStorageRows : []) {
const plain = toPlainRecord(oldStorageRow);
if (plain && Number(plain.id) > 0) {
oldStorageMap.set(Number(plain.id), toNumber(plain.stock_id, 0));
}
}
}
for (const record of oldPickingRecords) {
const storageId = toNumber(record.storage_id, 0);
const quantity = toNumber(record.quantity, 0);
@ -893,22 +872,11 @@ class OrderStorageAllocationService extends MainService {
if (storageId > 0 && quantity > 0) {
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction });
// 同步回退 wms_stock_warehouse 的锁定数量
const oldStockId = oldStorageMap.get(storageId) || 0;
if (oldStockId > 0) {
await ctx.model.StockWarehouse.decrement('locked_quantity', {
by: quantity,
where: { id: oldStockId },
transaction,
});
}
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定(含stock_warehouse同步)', {
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已释放旧库存锁定', {
warehouseId,
orderId: toNumber(record.order_id, 0),
storageId,
quantity,
stockId: oldStockId,
});
}
}
@ -1115,14 +1083,7 @@ class OrderStorageAllocationService extends MainService {
await ctx.service.systems.storage.index.lockQuantity(storageRow.id, allocationQuantity, { transaction });
// 同步更新 wms_stock_warehouse 的锁定数量
await ctx.model.StockWarehouse.increment('locked_quantity', {
by: allocationQuantity,
where: { id: storageRow.stock_id },
transaction,
});
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成(含stock_warehouse同步)', {
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库存锁定完成', {
orderId,
orderItemId: toNumber(orderItem.id, 0),
stockId,
@ -1176,13 +1137,6 @@ class OrderStorageAllocationService extends MainService {
storageRow.id, allocationQuantity, { transaction }
);
// 同步回退 wms_stock_warehouse 的锁定数量
await ctx.model.StockWarehouse.decrement('locked_quantity', {
by: allocationQuantity,
where: { id: storageRow.stock_id },
transaction,
});
// 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity
storageRow.available_quantity = currentAvailable;
storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity;
@ -1205,7 +1159,7 @@ class OrderStorageAllocationService extends MainService {
storageAllocationMap.set(storageRow.id, newStorageQty);
}
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加及内存计数器', {
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退内存计数器', {
orderId,
storageId: storageRow.id,
allocationQuantity,
@ -1310,15 +1264,6 @@ class OrderStorageAllocationService extends MainService {
lockRecord.storageId, lockRecord.quantity, { transaction }
);
// 同步回退 wms_stock_warehouse 的锁定数量
if (lockRecord.stockId && lockRecord.stockId > 0) {
await ctx.model.StockWarehouse.decrement('locked_quantity', {
by: lockRecord.quantity,
where: { id: lockRecord.stockId },
transaction,
});
}
// 回退 storageAllocationMap 中的累加值
const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0;
const newStorageQty = prevStorageQty - lockRecord.quantity;
@ -2259,15 +2204,6 @@ class OrderStorageAllocationService extends MainService {
transaction,
});
// 同步减少 wms_stock_warehouse 的锁定数量
if (storageRow.stock_id && storageRow.stock_id > 0) {
await ctx.model.StockWarehouse.decrement('locked_quantity', {
by: quantity,
where: { id: storageRow.stock_id },
transaction,
});
}
// 写入储位解锁流水
await ctx.model.StorageTransaction.create({
transaction_type: 'UNLOCK',

View File

@ -657,6 +657,120 @@ class stockStoreService extends Service {
};
}
/**
* 统一修改 wms_stock_warehouse.locked_quantity 并写入 stock_transaction 流水。
* 所有对 locked_quantity 的写操作必须通过此函数,禁止直接 increment/decrement/update。
*
* @param {number} stockId StockWarehouse.id。
* @param {number} change 变更量,正数为加锁,负数为解锁。
* @param {Object} currentTransaction 数据库事务对象。
* @param {Object} [meta={}] 元信息。
* @param {boolean} [meta.allowOversell=false] 是否允许超卖,为 true 时跳过可用库存校验。
* @param {boolean} [meta.skipTransactionLog=false] 是否跳过流水写入。
* @param {string} [meta.orderType] 订单类型,用于流水。
* @param {string} [meta.orderNo] 订单号。
* @param {number} [meta.orderId] 订单ID。
* @param {string} [meta.remark] 备注。
* @param {string} [meta.operatorId] 操作人ID。
* @param {string} [meta.operatorName] 操作人姓名。
* @return {Promise<{success: boolean, error?: string, data?: Object}>}
*/
async updateLockedQuantity(stockId, change, currentTransaction, meta = {}) {
const { ctx, app } = this;
const absQty = Math.abs(change);
const isLocking = change > 0;
if (!stockId || absQty <= 0) {
return { success: false, error: `参数无效: stockId=${stockId}, change=${change}` };
}
const stockRecord = await ctx.model.StockWarehouse.findOne({
where: { id: stockId, is_valid: 'Y', deleted_at: null },
transaction: currentTransaction,
lock: currentTransaction.LOCK.UPDATE,
attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity' ],
raw: false,
});
if (!stockRecord) {
return { success: false, error: `库存记录不存在或已失效 (ID: ${stockId})` };
}
const beforeQuantity = Number(stockRecord.quantity) || 0;
const beforeLocked = Number(stockRecord.locked_quantity) || 0;
// 加锁校验:可用库存(允许超卖时跳过此校验)
if (isLocking && meta.allowOversell !== true) {
const availableQty = beforeQuantity - beforeLocked;
if (availableQty < absQty) {
return {
success: false,
error: `库存不足,可用 ${availableQty},需求 ${absQty}`,
data: { available: availableQty, required: absQty },
};
}
}
// 解锁校验:锁定库存足够
if (!isLocking && beforeLocked < absQty) {
return {
success: false,
error: `释放数量超过已锁定库存,已锁 ${beforeLocked},尝试释放 ${absQty}`,
};
}
// 执行写操作
await stockRecord.increment('locked_quantity', {
by: change,
transaction: currentTransaction,
silent: true,
});
const afterLocked = beforeLocked + change;
const afterQuantity = beforeQuantity; // locked_quantity 变更不影响 quantity
// 写入流水(除非显式跳过)
const skipLog = meta.skipTransactionLog === true;
if (!skipLog && ctx.service && ctx.service.systems && ctx.service.systems.stockTransaction) {
// transaction_type 字段为 ENUM('INBOUND','OUTBOUND'),锁定/解锁属于出库流程
await ctx.service.systems.stockTransaction.create({
transaction_type: 'OUTBOUND',
warehouse_id: stockRecord.warehouse_id,
store_id: stockRecord.store_id,
stock_id: stockId,
quantity: absQty,
order_type: meta.orderType || null,
order_no: meta.orderNo || null,
order_id: meta.orderId || null,
operator_id: meta.operatorId || String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: meta.operatorName || ctx.user?.employees_name || '',
remark: meta.remark || `库存${isLocking ? '锁定' : '释放'}`,
before_quantity: beforeQuantity,
after_quantity: afterQuantity,
before_locked_quantity: beforeLocked,
after_locked_quantity: afterLocked,
created_at: new Date(),
}, { transaction: currentTransaction });
}
app.logger.info(
`[库存${isLocking ? '锁定' : '释放'}] ID: ${stockId}, ${isLocking ? '+' : '-'}${absQty}, 锁定后: ${afterLocked}`
);
return {
success: true,
data: {
id: stockId,
action: isLocking ? 'lock' : 'unlock',
quantity: absQty,
beforeLocked,
afterLocked,
totalQuantity: afterQuantity,
available: afterQuantity - afterLocked,
},
};
}
/**
* 锁定或释放库存。
*
@ -664,154 +778,57 @@ class stockStoreService extends Service {
* @param {number} quantity 锁定数量,负数表示释放。
* @param {Object|null} transaction 数据库事务。
* @param {Object|null} [oversellConfig=null] 可选预取策略配置,用于避免锁内查DB。
* @param {Object} [meta={}] 可选元信息,透传给 updateLockedQuantity 用于流水记录。
* @return {Promise<Object>} 锁定结果。
*/
async lockItemStorages(stockWarehouseId, quantity, transaction, oversellConfig = null) {
const {
ctx,
app,
} = this;
async lockItemStorages(stockWarehouseId, quantity, transaction, oversellConfig = null, meta = {}) {
const { app } = this;
// 输入验证
const lockQty = parseInt(quantity);
if (!stockWarehouseId || isNaN(lockQty) || lockQty === 0) {
return {
success: false,
error: `参数错误:库存ID无效或数量为0 (ID: ${stockWarehouseId}, Qty: ${quantity})`,
data: null,
};
return { success: false, error: '参数错误:库存ID无效或数量为0', data: null };
}
const isLocking = lockQty > 0; // true=加锁,false=减锁
const isLocking = lockQty > 0;
const absQty = Math.abs(lockQty);
try {
return await this._runWithTransaction(transaction, async currentTransaction => {
// 1. 查询并锁定记录(悲观锁)
const stockRecord = await ctx.model.StockWarehouse.findOne({
where: {
id: stockWarehouseId,
is_valid: 'Y',
deleted_at: null,
},
transaction: currentTransaction,
lock: currentTransaction.LOCK.UPDATE,
attributes: [ 'id', 'store_id', 'warehouse_id', 'quantity', 'locked_quantity', 'gross_weight' ],
raw: false,
const allowOversell = oversellConfig ? oversellConfig.allowOversell : false;
const result = await this.updateLockedQuantity(stockWarehouseId, lockQty, currentTransaction, {
remark: meta.remark || (isLocking ? '出库单创建锁定' : '出库单创建解锁'),
orderType: meta.orderType || null,
orderNo: meta.orderNo || null,
orderId: meta.orderId || null,
allowOversell: isLocking ? allowOversell : undefined,
});
if (!stockRecord) {
return {
success: false,
error: `库存记录不存在或已失效 (ID: ${stockWarehouseId})`,
data: null,
};
if (!result.success) {
return result;
}
if (isLocking) {
const availableQty = stockRecord.quantity - stockRecord.locked_quantity;
if (availableQty < absQty) {
// 优先使用外部预取的 oversellConfig,避免锁内查 DB
let allowOversell = oversellConfig ? oversellConfig.allowOversell : null;
if (allowOversell === null || allowOversell === undefined) {
// 回退:未预取时走原有查询(兼容其他调用方)
const policyConfig = await this.getStoreWarehousePolicyConfigByStockId(stockRecord, currentTransaction);
allowOversell = policyConfig.allowOversell;
}
if (!allowOversell) {
return {
success: false,
error: `库存不足,可用 ${availableQty},需求 ${absQty}`,
data: {
available: availableQty,
required: absQty,
recordId: stockWarehouseId,
},
};
}
}
} else {
if (stockRecord.locked_quantity < absQty) {
return {
success: false,
error: `释放数量超过已锁定库存,已锁 ${stockRecord.locked_quantity},尝试释放 ${absQty}`,
data: null,
};
}
const newLocked = stockRecord.locked_quantity - absQty;
if (newLocked < 0) {
return {
success: false,
error: `释放后锁定库存为负值: ${newLocked}`,
data: null,
};
}
}
if (isLocking) {
await stockRecord.increment('locked_quantity', {
by: absQty,
transaction: currentTransaction,
silent: true,
});
app.logger.info(
`[库存锁定] ID: ${stockWarehouseId}, 增加锁定: +${absQty}, 锁定后: ${stockRecord.locked_quantity + absQty}`
);
} else {
await stockRecord.decrement('locked_quantity', {
by: absQty,
transaction: currentTransaction,
silent: true,
});
app.logger.info(
`[库存释放] ID: ${stockWarehouseId}, 减少锁定: -${absQty}, 锁定后: ${stockRecord.locked_quantity - absQty}`
);
}
await stockRecord.reload({
transaction: currentTransaction,
});
const { beforeLocked, afterLocked, totalQuantity } = result.data;
return {
success: true,
data: {
id: stockWarehouseId,
action: isLocking ? 'lock' : 'unlock',
quantity: absQty,
beforeLocked: isLocking ? stockRecord.locked_quantity - absQty : stockRecord.locked_quantity +
absQty,
afterLocked: stockRecord.locked_quantity,
totalQuantity: stockRecord.quantity,
available: stockRecord.quantity - stockRecord.locked_quantity,
updatedAt: stockRecord.update_at,
beforeLocked,
afterLocked,
totalQuantity,
available: totalQuantity - afterLocked,
},
error: null,
};
});
} catch (error) {
app.logger.error('[lockItemStorages] 系统异常', {
stockWarehouseId,
quantity,
isLocking,
error: error.message,
stack: error.stack,
});
// 根据错误类型返回
app.logger.error('[lockItemStorages] 系统异常', { stockWarehouseId, quantity, isLocking, error: error.message });
if (error.name && error.name.includes('Sequelize')) {
return {
success: false,
error: `数据库操作失败: ${error.message}`,
data: null,
};
return { success: false, error: `数据库操作失败: ${error.message}`, data: null };
}
return {
success: false,
error: `系统错误: ${error.message}`,
data: null,
};
return { success: false, error: `系统错误: ${error.message}`, data: null };
}
}
/**
@ -1238,32 +1255,34 @@ class stockStoreService extends Service {
return failureResult;
}
// 4. 执行出库扣减(同时减少quantity和locked_quantity)
const result = await ctx.model.StockWarehouse.update({
// 4. 执行出库扣减:先调用核心函数处理 locked_quantity,再单独扣减 quantity
const lockResult = await this.updateLockedQuantity(storage.id, -outboundQty, currentTransaction, {
skipTransactionLog: true,
remark: '订单出库',
orderType: 'STOCK_STORE_OUTBOUND',
orderNo: outboundMeta.orderNo,
orderId: outboundMeta.orderId,
});
if (!lockResult.success) {
if (hasExternalTransaction) {
throw new Error(lockResult.error);
}
return lockResult;
}
// 同步扣减 quantity
const qtyResult = await ctx.model.StockWarehouse.update({
quantity: app.Sequelize.literal(`quantity - ${outboundQty}`),
locked_quantity: app.Sequelize.literal(`locked_quantity - ${outboundQty}`),
update_at: app.Sequelize.literal('CURRENT_TIMESTAMP'),
}, {
where: {
id: storage.id,
is_valid: 'Y',
deleted_at: null,
locked_quantity: {
[app.Sequelize.Op.gte]: outboundQty,
},
},
where: { id: storage.id, is_valid: 'Y', deleted_at: null },
transaction: currentTransaction,
});
if (result[0] === 0) {
const failureResult = {
success: false,
error: '出库失败:库存已被其他操作修改',
data: null,
};
if (hasExternalTransaction) {
throw new Error(failureResult.error);
}
if (qtyResult[0] === 0) {
const failureResult = { success: false, error: '出库失败:库存已被其他操作修改', data: null };
if (hasExternalTransaction) throw new Error(failureResult.error);
return failureResult;
}

View File

@ -93,8 +93,8 @@ class EntryService extends Service {
* @return {Object|null} Sequelize.where 条件,无法构建时返回 null
*/
buildEntryStockTransactionExistsCondition(fieldName, condition = {}) {
const { app, ctx } = this;
const db = ctx.model.sequelize;
const { app } = this;
const db = app.model;
const values = this.normalizeFilterValues(condition)
.map(item => (typeof item === 'string' ? item.trim() : item))
.filter(item => item !== '' && item !== undefined && item !== null);
@ -358,12 +358,23 @@ class EntryService extends Service {
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
const kw = String(quickWhereValue).trim();
const receivingDetailId = Number(kw);
const escapedKw = app.model.escape(`%${kw}%`);
const orConditions = [
{ entry_order_code: { [Op.like]: `%${kw}%` } },
{ purchase_order_code: { [Op.like]: `%${kw}%` } },
{ supplier_name: { [Op.like]: `%${kw}%` } },
{ store_name: { [Op.like]: `%${kw}%` } },
{ warehouse_name: { [Op.like]: `%${kw}%` } },
// 搜索收货单号(wms_receiving.receiving_number),通过绑定表关联
Sequelize.where(Sequelize.literal(
`EXISTS (
SELECT 1 FROM wms_entry_order_receiving eor
JOIN wms_receiving r ON r.id = eor.receiving_id
WHERE eor.entry_order_id = wms_entry_order.id
AND eor.deleted_at IS NULL
AND r.receiving_number LIKE ${escapedKw}
)`
), 1),
// 搜索收货单明细 ID(箱唛/托盘唛唯一编码,精确数字匹配);仅当 kw 是有效正数时追加 EXISTS
...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [
Sequelize.where(Sequelize.literal(
@ -501,51 +512,37 @@ class EntryService extends Service {
* @return {Promise<Object>} code/data/message 结构
*/
/**
* 查询入库单详情,含商品信息、条码、入库进度。
* 查询入库单详情(与原 storage.directInbound.getItems 输出格式一致)。
* 返回入库单基本信息、商品明细(含计划数量与已完成数量)、收货单绑定关系。
* @param {Object} data 请求参数
* @param {number} data.id 入库单主键 ID(必填)
* @return {Promise<Object>} code/data/message 结构,data.entryOrder 为扁平化后的入库单详情
* @return {Promise<Object>} code/data/message 结构
* - data.entryOrder: { id, entry_order_code, order_status, store_remask }
* - data.items: [{ id, stock_id, planned, completed, stock, bindings }]
* - data.receivingBindings: [{ id, receiving_id, receiving }]
*/
async get(data = {}) {
const { ctx } = this;
const { ctx, app } = this;
const id = Number(data.id || 0);
const warehouseId = ctx.user.store_id;
if (!id) {
return {
code: 400,
message: 'id 参数不能为空',
data: null,
};
return { code: 400, message: 'id 参数不能为空', data: null };
}
const where = {
id,
warehouse_id: warehouseId,
is_enabled: 1,
deleted_at: null,
};
const entryOrder = await ctx.model.EntryOrder.findOne({
where,
const entryOrder = await ctx.model.EntryOrder.findByPk(id, {
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name' ],
required: false,
},
{
model: ctx.model.EntryItems,
as: 'items',
attributes: [ 'id', 'order_id', 'out_biz_code', 'order_line_no', 'owner_code', 'item_code', 'item_id', 'count', 'inventory_type', 'stock_id', 'received_quantity', 'confirm_quantity' ],
required: false,
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ],
required: false,
},
],
},
{
model: ctx.model.EntryOrderReceiving,
@ -564,99 +561,202 @@ class EntryService extends Service {
});
if (!entryOrder) {
return {
code: 0,
message: '入库单不存在或无权访问',
data: null,
};
return { code: 404, message: '入库单不存在', data: null };
}
const entryOrderJSON = entryOrder.toJSON();
// 收集所有 stock_id,通过 getStockDetails 获取带缓存的商品详情
const stockIdSet = new Set();
if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) {
for (const item of entryOrderJSON.items) {
if (item.stock_id != null) {
stockIdSet.add(Number(item.stock_id));
}
}
// 校验仓库权限
if (entryOrder.warehouse_id !== ctx.user.store_id || !entryOrder.is_enabled) {
return { code: 404, message: '入库单不存在或无权访问', data: null };
}
const stockIds = [ ...stockIdSet ];
// 查询货主商家备注
const storeWarehouse = await ctx.model.StoreWarehouse.findOne({
where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id },
attributes: [ 'store_remask' ],
raw: true,
});
// 查询该入库单下已有的导入/PDA 入库记录(显式过滤软删除,仅统计未删除记录)
const directLogs = await ctx.model.InboundDirectLog.findAll({
where: { entry_order_id: entryOrder.id, deleted_at: null },
order: [[ 'created_at', 'ASC' ]],
});
// 将直接入库记录按 entry_item_id 关联到明细
// 优先使用 entry_item_id 精确匹配(绑定模式),其次回退到 stock_id 匹配(非绑定模式)
const itemDirectLogs = {};
for (const log of directLogs) {
// 绑定模式下 entry_item_id 已设置,优先用它定位明细行
const itemByEntryItemId = log.entry_item_id
? entryOrder.items.find(i => String(i.id) === String(log.entry_item_id))
: null;
const item = itemByEntryItemId || entryOrder.items.find(
i => String(i.stock_id) === String(log.stock_id)
);
const key = item ? String(item.id) : `stock_${log.stock_id}`;
if (!itemDirectLogs[key]) itemDirectLogs[key] = [];
itemDirectLogs[key].push({
id: log.id,
stock_id: log.stock_id,
quantity: log.quantity,
inbound_type: log.inbound_type,
space_id: log.space_id,
remark: log.remark,
operator_id: log.operator_id,
operator_name: log.operator_name,
created_at: log.created_at,
});
}
// 将入库单层级的收货单绑定扁平化
const receivingBindings = (entryOrder.receivingBindings && entryOrder.receivingBindings.length > 0)
? entryOrder.receivingBindings.map(rb => ({
id: rb.id,
receiving_id: rb.receiving_id,
receiving: rb.receiving || null,
}))
: [];
// 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情
const stockIds = [ ...new Set(
(entryOrder.items || [])
.map(item => Number(item.stock_id))
.filter(sid => sid && sid > 0)
) ];
/** @type {Map<number, Object>} */
const stockDetailMap = new Map();
const stockMap = new Map();
if (stockIds.length > 0) {
const warehouseId = ctx.user.store_id;
const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId });
for (const detail of stockDetails) {
stockDetailMap.set(detail.id, detail);
stockMap.set(detail.id, detail);
}
}
// 查询该入库单所有商品的直接入库进度(非收货单途径)
const directInboundMap = {};
if (stockIds.length > 0) {
const directLogRows = await ctx.model.InboundDirectLog.findAll({
attributes: [
'stock_id',
[ ctx.app.Sequelize.fn('SUM', ctx.app.Sequelize.col('quantity')), 'total_quantity' ],
],
// 组装明细(精简字段,突出已入/总数)
const items = (entryOrder.items || []).map(item => {
const planQty = Number(item.count) || 0;
const logKey = String(item.id);
const logs = itemDirectLogs[logKey] || [];
const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0);
// 优先使用已持久化的 received_quantity(commit 后由系统写入),
// 若为 0 则回退到 InboundDirectLog 汇总(尚未提交时的导入量),
// 确保绑定收货明细场景下 completed 口径与 received_quantity 一致。
const receivedQty = Number(item.received_quantity) || 0;
const completed = receivedQty > 0 ? receivedQty : directInQty;
return {
id: item.id,
stock_id: item.stock_id,
planned: planQty,
completed,
stock: stockMap.get(Number(item.stock_id)) || null,
};
});
// 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称
/** @type {Map<number, string>} space_id -> space_name */
const spaceNameMap = new Map();
const allSpaceIds = [ ...new Set(
Object.values(itemDirectLogs)
.flat()
.map(log => log.space_id)
.filter(sid => sid != null)
) ];
if (allSpaceIds.length > 0) {
const spaces = await ctx.model.LocationSpace.findAll({
where: { id: { [app.Sequelize.Op.in]: allSpaceIds } },
attributes: [ 'id', 'custom_name', 'space_code' ],
raw: true,
});
for (const sp of spaces) {
spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || '');
}
}
// 批量查询已绑定的收货明细列表
const entryItemIds = items.map(i => i.id).filter(Boolean);
/** @type {Map<number, Array<Object>>} 按 entry_item_id 分组 */
const bindingsMap = new Map();
if (entryItemIds.length > 0) {
const bindingRows = await ctx.model.InboundDirectLog.findAll({
where: {
entry_order_code: entryOrderJSON.entry_order_code,
stock_id: { [ctx.app.Sequelize.Op.in]: stockIds },
entry_item_id: { [app.Sequelize.Op.in]: entryItemIds },
receiving_detail_id: { [app.Sequelize.Op.ne]: null },
deleted_at: null,
},
group: [ 'stock_id' ],
attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'quantity', 'status' ],
raw: true,
});
for (const row of directLogRows) {
directInboundMap[row.stock_id] = Number(row.total_quantity) || 0;
if (bindingRows.length > 0) {
const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ];
const validDetailIds = new Set();
if (detailIds.length > 0) {
const details = await ctx.model.ReceivingDetail.findAll({
where: { id: { [app.Sequelize.Op.in]: detailIds } },
attributes: [ 'id' ],
raw: true,
});
for (const d of details) {
validDetailIds.add(d.id);
}
}
for (const b of bindingRows) {
const key = b.entry_item_id;
if (!bindingsMap.has(key)) {
bindingsMap.set(key, []);
}
bindingsMap.get(key).push({
detail_id: b.receiving_detail_id,
binding_id: b.id,
allocated_quantity: b.quantity || 0,
});
}
}
}
// 扁平化 items:用 getStockDetails 返回的商品详情替换原有的 stock + barcodes
let flattenedItems;
if (entryOrderJSON.items && Array.isArray(entryOrderJSON.items)) {
flattenedItems = entryOrderJSON.items.map(item => {
const { item_code, item_id, stock_id: itemStockId, ...rest } = item;
const stockDetail = itemStockId != null ? stockDetailMap.get(Number(itemStockId)) || null : null;
const directInboundQty = (stockDetail && directInboundMap[stockDetail.id]) || 0;
const receivedQty = Number(rest.received_quantity) || 0;
const totalCount = Number(rest.count) || 0;
const remaining = Math.max(0, totalCount - receivedQty);
// 将 bindings 挂到对应 item,并补充库位信息
for (const item of items) {
const bindings = bindingsMap.get(item.id) || [];
const logKey = String(item.id);
const directLogsForItem = itemDirectLogs[logKey] || [];
return {
...rest,
stock_id: itemStockId,
external_item_code: item_code,
external_item_id: item_id,
warehouse_item_code: (stockDetail && stockDetail.item_code) || '',
warehouse_item_name: (stockDetail && stockDetail.item_name) || '',
warehouse_item_spec: (stockDetail && stockDetail.sku_property) || '',
warehouse_quantity: (stockDetail && stockDetail.quantity != null) ? stockDetail.quantity : null,
warehouse_locked_quantity: (stockDetail && stockDetail.locked_quantity != null) ? stockDetail.locked_quantity : null,
warehouse_is_batch_mgmt: (stockDetail && stockDetail.is_batch_mgmt != null) ? stockDetail.is_batch_mgmt : null,
warehouse_is_shelf_life_mgmt: (stockDetail && stockDetail.is_shelf_life_mgmt != null) ? stockDetail.is_shelf_life_mgmt : null,
warehouse_image_url: (stockDetail && stockDetail.is_images === 'Y') ? '' : '',
warehouse_is_images: (stockDetail && stockDetail.is_images != null) ? stockDetail.is_images : null,
barcodes: (stockDetail && stockDetail.barcodes) || [],
direct_inbound_quantity: directInboundQty,
remaining_quantity: remaining,
};
});
} else {
flattenedItems = entryOrderJSON.items || [];
if (bindings.length === 0 && directLogsForItem.length > 0) {
const firstWithSpace = directLogsForItem.find(l => l.space_id);
if (firstWithSpace) {
item.bindings = [{
space_id: firstWithSpace.space_id,
space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '',
}];
} else {
item.bindings = [];
}
} else {
const firstWithSpace = directLogsForItem.find(l => l.space_id);
const sid = firstWithSpace ? firstWithSpace.space_id : null;
item.bindings = bindings.map(b => ({
...b,
space_id: sid,
space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '',
}));
}
}
// 为每个 item 补充可匹配的收货单明细及剩余可用量
const enrichedItems = await this.enrichItemsWithAvailableReceivingDetails(flattenedItems, warehouseId);
entryOrderJSON.items = enrichedItems;
return {
code: 200,
message: '查询成功',
data: {
entryOrder: entryOrderJSON,
entryOrder: {
id: entryOrder.id,
entry_order_code: entryOrder.entry_order_code,
order_status: entryOrder.order_status,
store_remask: (storeWarehouse && storeWarehouse.store_remask) || '',
},
items,
receivingBindings,
},
};
}

View File

@ -1302,8 +1302,8 @@ class InventoryService extends Service {
};
}
// 不按批次:按 stock_id + space_id + inventory_type 合并
const groupFields = [ 'stock_id', 'space_id', 'inventory_type', 'warehouse_id', 'store_id' ];
// 不按批次:仅按 stock_id 合并(跨库位、跨库存类型汇总)
const groupFields = [ 'stock_id' ];
const countResult = await ctx.model.Storage.count({
where: baseWhere,
@ -1315,10 +1315,8 @@ class InventoryService extends Service {
where: baseWhere,
attributes: [
'stock_id',
'space_id',
'inventory_type',
'warehouse_id',
'store_id',
[ fn('MIN', col('wms_storage.warehouse_id')), 'warehouse_id' ],
[ fn('MIN', col('wms_storage.store_id')), 'store_id' ],
[ fn('MIN', col('wms_storage.production_date')), 'production_date' ],
[ fn('MIN', col('wms_storage.expiry_date')), 'expiry_date' ],
[ fn('SUM', col('wms_storage.quantity')), 'quantity' ],
@ -1356,12 +1354,6 @@ class InventoryService extends Service {
],
required: false,
},
{
model: ctx.model.LocationSpace,
as: 'space',
attributes: [ 'id', 'space_code', 'custom_name' ],
required: false,
},
],
raw: true,
nest: true,
@ -1700,18 +1692,18 @@ class InventoryService extends Service {
const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
const prefix = `SCRK${dateStr}`;
// 查询当天该仓库+货主下已有的最大入库单号
// 查询当天该仓库下已有的最大入库单号(全局唯一,不区分货主,避免多货主场景下重复)
const lastOrder = await ctx.model.EntryOrder.findOne({
where: {
entry_order_code: { [app.Sequelize.Op.like]: `${prefix}%` },
warehouse_id: warehouseId,
store_id: storeId,
},
order: [[ 'entry_order_code', 'DESC' ]],
attributes: [ 'entry_order_code' ],
transaction,
raw: true,
paranoid: false,
lock: transaction.LOCK.UPDATE,
});
let seq = 1;

View File

@ -1,4 +1,22 @@
[
{
"version": "2026.07.03-system-02",
"date": "2026-07-03",
"type": "added",
"summary": "新增 order.pendingOrder.updateRemark:批量修改待处理订单备注(remark),不受 post_status 限制",
"methods": [
"order.pendingOrder.updateRemark"
],
"notes": [
"新增方法:order.pendingOrder.updateRemark,用于批量修改待处理订单的备注(remark)字段。",
"入参:ids(number[],必填,正整数数组,不能为空)、remark(string,必填,最大500字符)。",
"特性:不受 post_status 限制,可对所有状态的订单生效;纯批量不支持单ID。",
"更新成功后写入操作日志。",
"响应:updated_count(number,实际更新行数)、ids(number[],原样返回请求的ID数组)。",
"错误码:400(ids 不能为空 / ids 仅支持正整数数组 / remark 不能为空)。"
],
"module": "order.pendingOrder"
},
{
"version": "2026.07.03-system-01",
"date": "2026-07-03",
@ -4753,5 +4771,23 @@
"response: warehouse_quantity/warehouse_locked_quantity/warehouse_is_batch_mgmt/warehouse_is_shelf_life_mgmt 补充无匹配时为 null 的说明",
"description: 更新描述以反映实际逻辑流程"
]
},
{
"version": "2026.07.03-system-04",
"date": "2026-07-03",
"type": "modified",
"summary": "order.pendingOrder.updateAddress 移除 remark(备注)修改功能,现在仅支持地址字段批量修改;备注修改已独立为 order.pendingOrder.updateRemark",
"methods": [
"order.pendingOrder.updateAddress"
],
"notes": [
"移除入参 remark 参数定义项。",
"移除 remark 更新逻辑及相关描述,updateAddress 现在仅处理地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)。",
"description 更新:去掉 remark 相关描述,仅描述地址字段修改规则。",
"response updated_count 描述更新:从「取地址更新行数与备注更新行数的最大值」改为单纯描述地址更新行数。",
"errors 更新:移除 remark 相关错误说明('remark 字段不受此限制' 等),修改 '至少需要提供一个地址字段或备注进行修改' 为 '至少需要提供一个地址字段进行修改'。",
"备注修改功能已独立为 order.pendingOrder.updateRemark 方法。"
],
"module": "order.pendingOrder"
}
]

View File

@ -2846,7 +2846,7 @@
]
},
{
"groupName": "订单待处理模块",
"groupName": "待处理订单",
"module": "order.pendingOrder",
"list": [
{
@ -4165,7 +4165,7 @@
},
{
"method": "order.pendingOrder.updateAddress",
"description": "批量修改待处理订单的收件地址信息和备注。地址字段修改仅允许 post_status='none'(未分配快递)的订单;remark 字段修改不受 post_status 限制可对所有订单生效。至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address)或 remark,空值和纯空白会被忽略。更新成功后写入操作日志。",
"description": "批量修改待处理订单的收件地址信息。地址字段修改仅允许 post_status='none'(未分配快递)的订单;至少需要提供一个地址字段(name/mobile/tel/zip_code/province/city/area/town/detail_address),空值和纯空白会被忽略。更新成功后写入操作日志。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -4246,13 +4246,6 @@
"required": false,
"source": "body",
"description": "详细地址"
},
{
"name": "remark",
"type": "string",
"required": false,
"source": "body",
"description": "订单留言/备注,最大500字符。非空时批量覆盖所选订单的 remark 字段,不受 post_status 限制。"
}
],
"response": [
@ -4260,7 +4253,7 @@
"name": "updated_count",
"type": "number",
"required": true,
"description": "实际更新的订单行数(取地址更新行数与备注更新行数的最大值)。remark 字段的更新计数独立于地址字段。"
"description": "实际更新的订单行数(地址更新行数)。仅统计 post_status='none' 的订单地址更新成功数。"
},
{
"name": "ids",
@ -4276,11 +4269,69 @@
},
{
"code": 400,
"message": "至少需要提供一个地址字段或备注进行修改"
"message": "至少需要提供一个地址字段进行修改"
},
{
"code": 400,
"message": "仅允许修改 post_status='none'(未分配快递)的订单(地址字段);若订单已分配快递则地址更新行数为 0,不会报错但实际无更新。remark 字段不受此限制。"
"message": "仅允许修改 post_status='none'(未分配快递)的订单;若订单已分配快递则地址更新行数为 0,不会报错但实际无更新。"
}
]
},
{
"method": "order.pendingOrder.updateRemark",
"description": "批量修改待处理订单的备注(remark)。不受 post_status 限制,可对所有状态的订单生效。更新成功后写入操作日志。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "ids",
"type": "number[]",
"required": true,
"source": "body",
"description": "订单ID 正整数数组,不能为空"
},
{
"name": "remark",
"type": "string",
"required": true,
"source": "body",
"description": "订单备注/留言,最大500字符,必填"
}
],
"response": [
{
"name": "updated_count",
"type": "number",
"required": true,
"description": "实际更新的订单行数"
},
{
"name": "ids",
"type": "number[]",
"required": true,
"description": "请求的订单ID数组(原样返回)"
}
],
"errors": [
{
"code": 400,
"message": "ids 不能为空"
},
{
"code": 400,
"message": "ids 仅支持正整数数组"
},
{
"code": 400,
"message": "remark 不能为空"
}
]
},
@ -20644,14 +20695,12 @@
"_note": "响应结构因 group_by_batch 而异",
"_shelf_life_note": "production_date 和 expiry_date 为库存批次日期字段;is_shelf_life_warning_triggered 表示该库存在商品启用保质期管理且剩余天数小于等于阈值时是否触发效期预警。",
"list_merged": {
"_description": "group_by_batch=false(默认合并模式)",
"_description": "group_by_batch=false(默认合并模式),仅按 stock_id 分组聚合,跨库位、跨库存类型汇总",
"list": [
{
"stock_id": "商品库存ID",
"space_id": "库位ID",
"inventory_type": "库存类型",
"warehouse_id": "仓库ID",
"store_id": "货主ID",
"warehouse_id": "仓库ID(MIN 聚合值)",
"store_id": "货主ID(MIN 聚合值)",
"quantity": "总库存数量(SUM)",
"locked_quantity": "总锁定数量(SUM)",
"available_quantity": "总可用数量(SUM)",
@ -20668,11 +20717,6 @@
"sku_property": "规格",
"stock_unit": "单位",
"store_name": "货主名称(来源于签约表 store_remask,若无签约关系则为 null)"
},
"space": {
"id": "库位ID",
"space_code": "库位编码",
"custom_name": "库位名称"
}
}
],

View File

@ -48,8 +48,6 @@
"debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs",
"doc:api:update": "node ./script/update-api-doc.cjs",
"doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run",
"deploy:init": "node ./script/deploy-init.cjs production",
"deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run",
"deploy:precheck": "node ./script/deploy-precheck.cjs",
"deploy:authcheck": "node ./script/deploy-auth-check.cjs",
"deploy:version": "node ./script/deploy-version.cjs production",

View File

@ -1,138 +0,0 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const {
ensureCommandAvailable,
ensureTempDeployDir,
getNowStamp,
loadDeployConfig,
quoteForBash,
runCommand,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
function parseArgs(argv) {
const options = {
envName: 'production',
dryRun: false,
};
for (const item of argv) {
if (!item) continue;
if (item === '--dry-run') {
options.dryRun = true;
continue;
}
if (!item.startsWith('--')) {
options.envName = item;
}
}
return options;
}
function listConfigSeedFiles() {
const output = runCommand('git', [ 'ls-files', '--cached', 'config' ]);
return output
.split(/\r?\n/)
.map(item => item.trim())
.filter(Boolean)
.filter(item => item.startsWith('config/'))
.filter(item => item !== 'config/config.local.js')
.filter(item => item !== 'config/deploy.config.local.cjs')
.filter(item => item !== 'config/deploy.config.example.cjs');
}
function buildConfigSeedArchive(stamp, files) {
const tempDir = ensureTempDeployDir();
const listPath = path.join(tempDir, `deploy-init-files-${stamp}.txt`);
const archivePath = path.join(tempDir, `deploy-init-${stamp}.tar.gz`);
if (!files || files.length === 0) {
throw new Error('未找到可用于初始化的 config 文件(git tracked)。');
}
fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8');
runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' });
return {
archivePath,
listPath,
};
}
function cleanupLocalTemp(paths) {
for (const filePath of paths) {
if (!filePath) continue;
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
}
}
function main() {
const options = parseArgs(process.argv.slice(2));
ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。');
ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。');
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
const config = loadDeployConfig(options.envName);
const seedFiles = listConfigSeedFiles();
if (options.dryRun) {
console.log(JSON.stringify({
dryRun: true,
envName: options.envName,
deployRoot: config.deployRoot,
seedFileCount: seedFiles.length,
seedFiles,
}, null, 2));
return;
}
const stamp = getNowStamp();
const { archivePath, listPath } = buildConfigSeedArchive(stamp, seedFiles);
const remoteArchive = `${config.incomingDir}/deploy-init-${stamp}.tar.gz`;
try {
const setupScript = [
'set -euo pipefail',
`mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v1'))} ${quoteForBash(path.posix.join(config.deployRoot, 'v2'))}`,
`echo v1 > ${quoteForBash(path.posix.join(config.deployRoot, 'current.md'))}`,
`echo "proxy_pass http://127.0.0.1:6061;" > ${quoteForBash(path.posix.join(config.deployRoot, 'nginx-upstream.conf'))}`,
].join('\n');
runSsh(config, setupScript);
runScp(config, archivePath, remoteArchive);
const remoteScript = [
'set -euo pipefail',
`DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`,
`REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
'CONFIG_DIR="$DEPLOY_ROOT/config"',
'if [ -d "$CONFIG_DIR" ] && [ "$(find "$CONFIG_DIR" -mindepth 1 -maxdepth 1 | wc -l | tr -d \" \" )" -gt 0 ]; then',
' echo DEPLOY_INIT_CONFIG_SKIPPED_EXISTS',
'else',
' mkdir -p "$CONFIG_DIR"',
' tar -xzf "$REMOTE_ARCHIVE" -C "$DEPLOY_ROOT"',
' echo DEPLOY_INIT_CONFIG_CREATED',
'fi',
'rm -f "$REMOTE_ARCHIVE"',
].join('\n');
const output = runSsh(config, remoteScript, { stdio: 'pipe' });
for (const line of output.split(/\r?\n/)) {
if (line.trim()) {
console.log(line.trim());
}
}
} finally {
cleanupLocalTemp([ archivePath, listPath ]);
}
console.log(`首次发布初始化完成: ${options.envName} -> ${config.deployRoot}`);
}
main();