WMS_MAIN/app/service/systems/order_review.js
liufumingren a8200a3a35 feat(order): 订单拦截全链路阻断与作业排除
- 新增 app/lib/intercept_guard 共享守卫:除 none 外所有拦截状态一律视为已拦截
- 分配波次(singleFetchByIds)/抓取波次(createWavePickTask) 排除拦截订单并回传清单
- 分配储位(allocatePicking)/分配快递(createWaybillCodePipeline、batchAllocateExpress) 跳过拦截订单并回报
- 打印组装(getWavePlatformPrintData/getOrderPrintData/getPrintDataByWaybillCodes) 剔除拦截订单,打印回写/波次反查/标记均排除
- 拣货完成(wavePickTaskComplete) 拦截报错;复核(assertOrderCanRecheck/批量快捷复核) 补全拦截状态
- 打包/称重(workbench、order.updateExpressWeighingWeight) 拦截阻断,波次批量操作排除拦截单
- 绑定包材(order_express) 拦截阻断,波次批量绑定排除拦截单
2026-08-17 21:58:43 +08:00

494 lines
15 KiB
JavaScript

'use strict';
const OrderBaseService = require('../systemMethods/order/base');
/**
* 订单复核数据聚合服务。
*
* 负责根据运单号反查订单,并输出复核最小数据集。
*/
class OrderReviewService extends OrderBaseService {
/**
* 创建带业务错误码的异常对象。
* @param {string} message 错误信息。
* @param {number} [code=400] 业务错误码。
* @return {Error} 异常对象。
*/
createBusinessError(message, code = 400) {
const error = new Error(`${message}`);
error.code = code;
return error;
}
/**
* 规范化运单号。
* @param {string} waybillCode 运单号。
* @return {string} 规范化后的运单号。
*/
normalizeWaybillCode(waybillCode) {
const normalizedWaybillCode = String(waybillCode || '').trim();
if (!normalizedWaybillCode) {
throw this.createBusinessError('参数错误', 400);
}
return normalizedWaybillCode;
}
/**
* 判断是否为锁定状态。
* @param {string} lockStatus 锁定状态。
* @return {boolean} 是否锁定。
*/
isLockedStatus(lockStatus) {
return String(lockStatus || '').trim() !== 'none';
}
/**
* 判断是否为拦截状态(除 none 外一律视为已拦截)。
* @param {string} interceptStatus 拦截状态。
* @return {boolean} 是否拦截。
*/
isInterceptStatus(interceptStatus) {
return this.isInterceptedOrderStatus(interceptStatus);
}
/**
* 将模型记录转换为普通对象。
* @param {*} record 模型记录。
* @return {Object|null} 普通对象。
*/
toPlainRecord(record) {
if (!record) {
return null;
}
if (typeof record.get === 'function') {
return record.get({ plain: true });
}
return record;
}
/**
* 解析订单商品快照。
* @param {*} itemSnapshot 商品快照字段。
* @return {Object} 解析后的快照对象。
*/
parseItemSnapshot(itemSnapshot) {
if (!itemSnapshot) {
return {};
}
if (typeof itemSnapshot === 'object') {
return itemSnapshot;
}
if (typeof itemSnapshot === 'string') {
try {
const parsed = JSON.parse(itemSnapshot);
return parsed && typeof parsed === 'object' ? parsed : {};
} catch (error) {
return {};
}
}
return {};
}
/**
* 根据运单号读取有效快递记录。
* @param {string} waybillCode 运单号。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} 快递记录。
*/
async findOrderExpressByWaybill(waybillCode, warehouseId) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') {
throw this.createBusinessError('订单快递模型未初始化', 500);
}
const expressRow = await orderExpressModel.findOne({
where: {
waybill_code: waybillCode,
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (!expressRow) {
throw this.createBusinessError('运单不存在', 404);
}
return expressRow;
}
/**
* 根据订单ID读取订单头。
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} 订单头。
*/
async findOrderById(orderId, warehouseId) {
const orderModel = await this.getOrderModelByTableType('current', warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
const orderRow = await orderModel.findOne({
where: orderWhere,
attributes: [
'id',
'warehouse_id',
'wave_id',
'wave_no',
'items_weight',
'items_total',
'items_count',
'lock_status',
'intercept_status',
],
raw: true,
});
if (!orderRow) {
throw this.createBusinessError('订单不存在', 404);
}
return orderRow;
}
/**
* 读取订单明细。
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object[]>} 明细列表。
*/
async findOrderItems(orderId, warehouseId) {
const orderItemsModel = await this.getOrderItemsModelByTableType('current', warehouseId);
const rows = await orderItemsModel.findAll({
where: {
order_id: orderId,
},
attributes: [
'id',
'order_id',
'item_id',
'item_code',
'item_name',
'plan_qty',
'stock_id',
'item_snapshot',
],
order: [[ 'id', 'ASC' ]],
raw: true,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 批量读取商品条码映射。
* @param {number[]} stockIds 商品ID列表。
* @return {Promise<Map<number, string[]>>} 条码映射。
*/
async loadBarcodesByStockIds(stockIds = []) {
const uniqueStockIds = Array.from(new Set((Array.isArray(stockIds) ? stockIds : [])
.map(item => Number(item))
.filter(item => Number.isFinite(item) && item > 0)));
const barcodeMap = new Map();
if (uniqueStockIds.length === 0) {
return barcodeMap;
}
const stockBarcodeModel = this.ctx.model && this.ctx.model.StockBarcode;
if (!stockBarcodeModel || typeof stockBarcodeModel.findAll !== 'function') {
return barcodeMap;
}
const barcodeRows = await stockBarcodeModel.findAll({
where: {
stock_id: {
[this.app.Sequelize.Op.in]: uniqueStockIds,
},
},
attributes: [ 'stock_id', 'barcode' ],
raw: true,
});
for (const item of Array.isArray(barcodeRows) ? barcodeRows : []) {
const stockId = Number(item && item.stock_id || 0);
const barcode = String(item && item.barcode || '').trim();
if (!stockId || !barcode) {
continue;
}
if (!barcodeMap.has(stockId)) {
barcodeMap.set(stockId, []);
}
barcodeMap.get(stockId).push(barcode);
}
return barcodeMap;
}
/**
* 批量读取商品图片映射。
* @param {number[]} stockIds 商品ID列表。
* @return {Promise<Map<number, string[]>>} 图片映射。
*/
async loadImagesByStockIds(stockIds = []) {
const uniqueStockIds = Array.from(new Set((Array.isArray(stockIds) ? stockIds : [])
.map(item => Number(item))
.filter(item => Number.isFinite(item) && item > 0)));
const imageMap = new Map();
if (uniqueStockIds.length === 0) {
return imageMap;
}
const fileReferenceModel = this.ctx.model && this.ctx.model.FileReference;
const fileModel = this.ctx.model && this.ctx.model.File;
if (!fileReferenceModel || typeof fileReferenceModel.findAll !== 'function' || !fileModel) {
return imageMap;
}
const imageRows = await fileReferenceModel.findAll({
where: {
business_type: 'stock',
business_id: {
[this.app.Sequelize.Op.in]: uniqueStockIds,
},
},
include: [{
model: fileModel,
as: 'file',
attributes: [ 'file_url' ],
required: false,
}],
});
for (const item of Array.isArray(imageRows) ? imageRows : []) {
const row = this.toPlainRecord(item);
const stockId = Number(row && row.business_id || 0);
const imageUrl = String(
row && row.file && row.file.file_url
|| row && row.file_url
|| row && row.url
|| row && row.file_path
|| ''
).trim();
if (!stockId || !imageUrl) {
continue;
}
if (!imageMap.has(stockId)) {
imageMap.set(stockId, []);
}
imageMap.get(stockId).push(imageUrl);
}
return imageMap;
}
/**
* 查询波次信息。
* @param {number} waveId 波次ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} 波次信息。
*/
async findWaveById(waveId, warehouseId) {
const normalizedWaveId = Number(waveId || 0);
if (!Number.isFinite(normalizedWaveId) || normalizedWaveId <= 0) {
return null;
}
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') {
return null;
}
return await waveBatchModel.findOne({
where: {
wave_id: normalizedWaveId,
warehouse_id: warehouseId,
},
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
raw: true,
});
}
/**
* 读取团购波次拦截列表。
* @param {Object} order 当前命中订单。
* @return {Promise<Object[]>} 拦截列表。
*/
async buildGroupInterceptList(order = {}) {
const waveId = Number(order && order.wave_id || 0);
const warehouseId = Number(order && order.warehouse_id || 0);
if (!waveId || !warehouseId) {
return [];
}
const orderModel = await this.getOrderModelByTableType('current', warehouseId);
const interceptRows = await orderModel.findAll({
where: {
wave_id: waveId,
warehouse_id: warehouseId,
intercept_status: {
[this.app.Sequelize.Op.ne]: 'none',
},
},
attributes: [ 'id', 'intercept_status', 'lock_status' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
const normalizedRows = Array.isArray(interceptRows) ? interceptRows : [];
if (normalizedRows.length === 0) {
return [];
}
const orderIds = normalizedRows
.map(item => Number(item && item.id || 0))
.filter(item => Number.isFinite(item) && item > 0);
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
let waybillRows = [];
if (orderExpressModel && typeof orderExpressModel.findAll === 'function' && orderIds.length > 0) {
waybillRows = await orderExpressModel.findAll({
where: {
order_id: {
[this.app.Sequelize.Op.in]: orderIds,
},
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'order_id', 'waybill_code' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
}
const firstWaybillMap = new Map();
for (const row of Array.isArray(waybillRows) ? waybillRows : []) {
const orderId = Number(row && row.order_id || 0);
const waybillCode = String(row && row.waybill_code || '').trim();
if (!orderId || !waybillCode || firstWaybillMap.has(orderId)) {
continue;
}
firstWaybillMap.set(orderId, waybillCode);
}
return normalizedRows.map(item => {
const orderId = Number(item && item.id || 0);
return {
order_id: orderId,
waybill_code: firstWaybillMap.get(orderId) || null,
intercept_status: String(item && item.intercept_status || '').trim() || 'none',
lock_status: String(item && item.lock_status || '').trim() || 'none',
};
});
}
/**
* 根据运单号拉取复核最小数据集。
* @param {Object} payload 入参。
* @param {string} payload.waybillCode 运单号。
* @return {Promise<Object>} 复核数据。
*/
async pullReviewDataByWaybill(payload = {}) {
const requestData = payload && typeof payload === 'object' ? payload : {};
const { waybillCode } = requestData;
const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode);
const warehouseId = Number(this.getWarehouseId() || 0);
if (!warehouseId) {
throw this.createBusinessError('参数错误', 400);
}
const expressRow = await this.findOrderExpressByWaybill(normalizedWaybillCode, warehouseId);
const orderId = Number(expressRow && expressRow.order_id || 0);
if (!orderId) {
throw this.createBusinessError('订单不存在', 404);
}
const orderRow = await this.findOrderById(orderId, warehouseId);
const itemRows = await this.findOrderItems(orderId, warehouseId);
const stockIds = itemRows
.map(item => Number(item && item.stock_id || 0))
.filter(item => Number.isFinite(item) && item > 0);
const barcodeMap = await this.loadBarcodesByStockIds(stockIds);
const imageMap = await this.loadImagesByStockIds(stockIds);
const details = itemRows.map(item => {
const snapshot = this.parseItemSnapshot(item && item.item_snapshot);
const stockId = Number(item && item.stock_id || 0);
const barcodes = barcodeMap.get(stockId) || [];
const images = imageMap.get(stockId) || [];
return {
order_item_id: Number(item && item.id || 0),
item_id: Number(item && item.item_id || 0) || null,
stock_id: stockId || null,
sku_code: String(item && item.item_code || snapshot.item_code || '').trim() || null,
item_name: String(item && item.item_name || snapshot.item_name || '').trim() || null,
should_review_qty: Number(item && item.plan_qty || 0),
image: images[0] || null,
images,
barcode: barcodes[0] || null,
barcodes,
};
});
const lockStatus = String(orderRow && orderRow.lock_status || '').trim() || 'none';
const interceptStatus = String(orderRow && orderRow.intercept_status || '').trim() || 'none';
const warnings = [];
if (this.isLockedStatus(lockStatus)) {
warnings.push('订单处于锁定状态,请确认后再复核');
}
if (this.isInterceptStatus(interceptStatus)) {
warnings.push('订单处于拦截状态,请先处理拦截');
}
const waveRow = await this.findWaveById(orderRow && orderRow.wave_id, warehouseId);
const isGroupOrder = Number(waveRow && waveRow.wave_type || 0) === 1;
const interceptList = isGroupOrder
? await this.buildGroupInterceptList(orderRow)
: [];
const totalPieceCount = Number(orderRow && orderRow.items_total || 0);
const totalSkuCount = Number(orderRow && orderRow.items_count || 0);
const fallbackSkuCount = details.reduce((count, item) => {
const skuCode = String(item && item.sku_code || '').trim();
return skuCode ? count + 1 : count;
}, 0);
const fallbackPieceCount = details.reduce((count, item) => count + Number(item && item.should_review_qty || 0), 0);
return {
order_id: Number(orderRow && orderRow.id || 0),
waybill_code: String(expressRow && expressRow.waybill_code || normalizedWaybillCode).trim(),
wave_no: String(orderRow && orderRow.wave_no || '').trim() || null,
total_weight: orderRow && orderRow.items_weight != null ? Number(orderRow.items_weight) : null,
total_piece_count: totalPieceCount > 0 ? totalPieceCount : fallbackPieceCount,
total_sku_count: totalSkuCount > 0 ? totalSkuCount : fallbackSkuCount,
lock_status: lockStatus,
intercept_status: interceptStatus,
is_group_order: isGroupOrder,
warnings,
intercept_list: interceptList,
details,
};
}
}
module.exports = OrderReviewService;