WMS_MAIN/app/service/systems/order_express.js

2237 lines
82 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const { isInterceptedOrderStatus } = require('../../lib/intercept_guard');
/**
* 订单快递业务服务。
*
* 负责订单快递记录的读取与称重重量更新。
*/
class OrderExpressService extends Service {
/**
* 创建带业务错误码的异常对象。
* @param {string} message 错误信息。
* @param {number} [code=400] 业务错误码。
* @return {Error} 包含 code 的异常对象。
*/
createBusinessError(message, code = 400) {
const error = new Error(`${message}`);
error.code = code;
return error;
}
/**
* 规范化并校验订单ID。
* @param {number|string} orderId 订单ID。
* @return {number} 合法订单ID。
*/
normalizeOrderId(orderId) {
const normalizedOrderId = Number(orderId || 0);
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
throw this.createBusinessError('order_id 必填且必须为正整数', 400);
}
return normalizedOrderId;
}
/**
* 规范化并校验运单号。
* @param {string} waybillCode 运单号。
* @return {string} 合法运单号。
*/
normalizeWaybillCode(waybillCode) {
const normalizedWaybillCode = String(waybillCode || '').trim();
if (!normalizedWaybillCode) {
throw this.createBusinessError('参数错误', 400);
}
return normalizedWaybillCode;
}
/**
* 规范化并校验包材编码。
* @param {string} packageMaterialCode 包材编码。
* @return {string} 合法包材编码。
*/
normalizePackageMaterialCode(packageMaterialCode) {
const normalizedCode = String(packageMaterialCode || '').trim().toUpperCase();
if (!normalizedCode) {
throw this.createBusinessError('参数错误', 400);
}
return normalizedCode;
}
/**
* 规范化并校验包材ID。
* @param {number|string} packageMaterialId 包材ID。
* @return {number} 合法包材ID。
*/
normalizePackageMaterialId(packageMaterialId) {
const normalizedId = Number(packageMaterialId || 0);
if (!Number.isFinite(normalizedId) || normalizedId <= 0) {
throw this.createBusinessError('参数错误', 400);
}
return normalizedId;
}
/**
* 规范化并校验绑定包材场景的订单ID。
* @param {number|string} orderId 订单ID。
* @return {number} 合法订单ID。
*/
normalizeBindOrderId(orderId) {
const normalizedOrderId = Number(orderId || 0);
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
throw this.createBusinessError('参数错误', 400);
}
return normalizedOrderId;
}
/**
* 获取当前仓库 ID。
* @return {number} 当前仓库 ID。
*/
getCurrentWarehouseId() {
const warehouseId = Number(this.ctx && this.ctx.user ? this.ctx.user.store_id : 0);
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw this.createBusinessError('参数错误', 400);
}
return warehouseId;
}
/**
* 根据包材ID查询当前仓库启用中的包材。
* @param {number} packageMaterialId 包材ID。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<Object>} 包材记录。
*/
async findActivePackageMaterialById(packageMaterialId, warehouseId) {
const packageMaterialModel = this.ctx.model && this.ctx.model.PackageMaterial;
if (!packageMaterialModel || typeof packageMaterialModel.findOne !== 'function') {
throw this.createBusinessError('包材模型未初始化', 500);
}
const materialRow = await packageMaterialModel.findOne({
where: {
warehouse_id: warehouseId,
id: packageMaterialId,
status: 1,
},
attributes: [ 'id', 'material_code', 'material_name', 'warehouse_id', 'status' ],
raw: true,
});
if (!materialRow) {
throw this.createBusinessError('包材ID不存在', 404);
}
return materialRow;
}
/**
* 根据包材编码查询当前仓库启用中的包材。
* @param {string} packageMaterialCode 包材编码。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<Object>} 包材记录。
*/
async findActivePackageMaterialByCode(packageMaterialCode, warehouseId) {
const packageMaterialModel = this.ctx.model && this.ctx.model.PackageMaterial;
if (!packageMaterialModel || typeof packageMaterialModel.findOne !== 'function') {
throw this.createBusinessError('包材模型未初始化', 500);
}
const materialRow = await packageMaterialModel.findOne({
where: {
warehouse_id: warehouseId,
material_code: packageMaterialCode,
status: 1,
},
attributes: [ 'id', 'material_code', 'material_name', 'warehouse_id', 'status' ],
raw: true,
});
if (!materialRow) {
throw this.createBusinessError('包材编码不存在', 404);
}
return materialRow;
}
/**
* 根据订单号与运单号查询有效订单快递记录。
* @param {number} orderId 订单 ID。
* @param {string} waybillCode 运单号。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<Object>} 订单快递记录。
*/
async findValidOrderExpressByOrderAndWaybill(orderId, waybillCode, warehouseId) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') {
throw this.createBusinessError('订单快递模型未初始化', 500);
}
const orderExpressRow = await orderExpressModel.findOne({
where: {
order_id: orderId,
waybill_code: waybillCode,
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id' ],
raw: true,
});
if (!orderExpressRow) {
throw this.createBusinessError('订单运单记录不存在', 404);
}
return orderExpressRow;
}
/**
* 查询订单拦截状态(依次查询 current → dispatch 分表)。
* @param {number} orderId 订单 ID。
* @param {number} warehouseId 仓库 ID。
* @return {Promise<string>} 拦截状态,查询失败时返回 'none'。
*/
async findOrderInterceptStatus(orderId, warehouseId) {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return 'none';
}
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
if (row) {
return String(row.intercept_status || '').trim() || 'none';
}
} catch (_err) { continue; }
}
return 'none';
}
/**
* 断言订单未进入拦截流程,否则抛出业务异常。
* @param {number} orderId 订单 ID。
* @param {number} warehouseId 仓库 ID。
* @param {string} [actionText='继续作业'] 被阻断的作业文案。
* @return {Promise<void>} 无返回值。
*/
async assertOrderNotIntercepted(orderId, warehouseId, actionText = '继续作业') {
const interceptStatus = await this.findOrderInterceptStatus(orderId, warehouseId);
if (isInterceptedOrderStatus(interceptStatus)) {
throw this.createBusinessError(`订单已被拦截,无法${actionText}`, 400);
}
}
/**
* 读取订单的波次范围与打包状态(依次查询 current → history → dispatch 分表)。
*
* 序列表定位优先:命中时先查对应分表,未命中(存量订单)按原遍历顺序回退。
*
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} { id, wave_scope, pack_status },未命中时返回 null。
*/
async findOrderWaveAndPackStatus(orderId, warehouseId) {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return null;
}
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
try {
if (typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_scope', 'pack_status' ],
raw: true,
});
if (row) return row;
} catch (_err) { continue; }
}
return null;
}
/**
* 读取仓库「散单称重是否需要打包」配置。
*
* 配置来源:wms_store.subject_config.single_weigh_require_pack(默认关闭)。
* 走 deliveryOrder.getStoreSubjectConfig 公共读取链路(带缓存);配置缺失、
* 读取失败或值非法时按「关闭」处理,保证称重主流程可用。
*
* @param {number|null} warehouseId 仓库ID。
* @return {Promise<boolean>} 是否要求散单称重前已完成打包。
*/
async isSingleWeighRequirePack(warehouseId) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return false;
}
try {
const deliveryOrderService = this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.deliveryOrder;
if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') {
return false;
}
const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(normalizedWarehouseId);
return !!(subjectConfig && subjectConfig.single_weigh_require_pack === true);
} catch (error) {
this.ctx.logger.warn(
'[OrderExpressService.isSingleWeighRequirePack] 读取仓库配置失败,按关闭处理: %s',
error.message
);
return false;
}
}
/**
* 散单称重前置校验:开启「散单称重是否需要打包」时,未打包订单禁止称重。
*
* 适用范围:订单波次范围 wave_scope 不属于 1(大团购)/ 3(小团购)时生效,
* 即未分配波次、散单、单品单件等按散单处理的订单;团购订单不校验。
* 订单未命中(分表无记录)时跳过校验,由后续称重逻辑自行报错。
*
* @param {number} orderId 订单ID。
* @param {number|null} warehouseId 仓库ID,缺失时跳过校验。
* @return {Promise<void>} 无返回值;未打包时抛出业务异常。
*/
async assertSingleOrderPackedForWeigh(orderId, warehouseId) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return;
}
const requirePack = await this.isSingleWeighRequirePack(normalizedWarehouseId);
if (!requirePack) {
return;
}
const orderRow = await this.findOrderWaveAndPackStatus(orderId, normalizedWarehouseId);
if (!orderRow) {
return;
}
const waveScope = Number(orderRow.wave_scope || 0);
if (waveScope === 1 || waveScope === 3) {
return;
}
const packStatus = String(orderRow.pack_status || '').trim();
if (packStatus !== 'fin') {
throw this.createBusinessError(this.buildWeighPackBlockedMessage(packStatus), 400);
}
}
/**
* 构造「散单称重需先打包」拦截文案,供各称重入口复用(保证提示语一致)。
* @param {string} packStatus 打包状态原值。
* @return {string} 拦截提示文案:打包中(padding)返回「订单打包中」,其余未完成状态返回「订单未打包」。
*/
buildWeighPackBlockedMessage(packStatus) {
return packStatus === 'padding' ? '订单打包中' : '订单未打包';
}
/**
* 规范化并校验称重重量。
*
* 必须为正整数(单位 g),且必须大于 0。
*
* @param {number|string} weighingWeight 称重重量(g)。
* @return {number} 合法重量数值。
*/
normalizeWeighingWeight(weighingWeight) {
if (weighingWeight === null || weighingWeight === undefined || String(weighingWeight).trim() === '') {
throw this.createBusinessError('weighing_weight 必填', 400);
}
const normalizedWeightText = String(weighingWeight).trim();
if (!/^\d+$/.test(normalizedWeightText)) {
throw this.createBusinessError('weighing_weight 格式非法,必须为正整数(单位 g)', 400);
}
const normalizedWeight = Number(normalizedWeightText);
if (!Number.isFinite(normalizedWeight) || normalizedWeight <= 0) {
throw this.createBusinessError('weighing_weight 必须大于 0', 400);
}
return normalizedWeight;
}
/**
* 读取订单下有效快递记录。
*
* 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
* 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时直接抛业务错误拒绝读取。
*
* @param {number} orderId 订单ID。
* @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。
* @return {Promise<Array<Object>>} 快递记录列表。
*/
async findValidOrderExpressRows(orderId, warehouseId) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
throw this.createBusinessError('订单快递模型未初始化', 500);
}
if (warehouseId === null || warehouseId === undefined || warehouseId === '') {
throw this.createBusinessError('缺少仓库上下文,禁止读取订单运单记录', 400);
}
const where = {
order_id: orderId,
delete_at: null,
warehouse_id: warehouseId,
};
const rows = await orderExpressModel.findAll({
where,
attributes: [ 'id', 'order_id', 'waybill_code', 'weighing_weight' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 回写订单表的 packages_weight(所有包裹总重量 = 该订单全部有效运单称重之和)。
*
* 称重主流程的补充回写动作,失败仅告警不阻断称重流程。
*
* @param {number} orderId 订单ID。
* @param {number|null} warehouseId 仓库ID,缺失时跳过回写。
* @param {Object|null} [orderDeliveryModel] 已知的订单分表模型;缺省时按 current → dispatch → history 自动定位。
* @return {Promise<number>} 计算出的包裹总重量(g),失败返回 0。
*/
async _syncOrderPackagesWeight(orderId, warehouseId, orderDeliveryModel = null) {
const { ctx } = this;
const normalizedOrderId = Number(orderId || 0);
if (normalizedOrderId <= 0 || !warehouseId) {
return 0;
}
try {
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.sum !== 'function') {
return 0;
}
const sumResult = await orderExpressModel.sum('weighing_weight', {
where: {
order_id: normalizedOrderId,
delete_at: null,
warehouse_id: warehouseId,
},
});
const packagesWeight = Number.isFinite(Number(sumResult)) && Number(sumResult) > 0
? Math.round(Number(sumResult))
: 0;
let targetModel = orderDeliveryModel;
if (!targetModel || typeof targetModel.update !== 'function') {
const factory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!factory || typeof factory.getCurrentModel !== 'function') {
return packagesWeight;
}
const tableOrders = [
{ label: 'current', getModel: () => factory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => factory.getDispatchModel(warehouseId) },
{ label: 'history', getModel: () => factory.getHistoryModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.update !== 'function') continue;
const found = await model.findOne({
where: { id: normalizedOrderId, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
if (found) {
targetModel = model;
break;
}
} catch (_err) { continue; }
}
}
if (targetModel && typeof targetModel.update === 'function') {
await targetModel.update(
{ packages_weight: packagesWeight },
{ where: { id: normalizedOrderId, warehouse_id: warehouseId } }
);
}
return packagesWeight;
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[order_express._syncOrderPackagesWeight] 回写包裹总重量失败 orderId=${normalizedOrderId}: ${err && err.message}`
);
return 0;
}
}
/**
* 批量回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部有效运单称重之和)。
*
* 一次聚合查询 + 逐订单 UPDATE,失败仅告警不阻断称重流程。
*
* @param {number[]} orderIds 波次内参与称重的订单ID列表。
* @param {number} warehouseId 仓库ID。
* @param {Object} orderDeliveryModel 订单分表模型(波次订单所在分表)。
* @return {Promise<void>} 无返回值。
*/
async _syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel) {
const { ctx } = this;
const normalizedOrderIds = (Array.isArray(orderIds) ? orderIds : [])
.map(id => Number(id || 0))
.filter(id => id > 0);
if (normalizedOrderIds.length === 0 || !warehouseId) {
return;
}
try {
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return;
}
const { Op } = this.app.Sequelize;
const rows = await orderExpressModel.findAll({
where: {
order_id: { [Op.in]: normalizedOrderIds },
delete_at: null,
warehouse_id: warehouseId,
},
attributes: [ 'order_id', 'weighing_weight' ],
raw: true,
});
const sumMap = new Map();
for (const row of (Array.isArray(rows) ? rows : [])) {
const oid = Number(row && row.order_id || 0);
if (oid <= 0) continue;
sumMap.set(oid, (sumMap.get(oid) || 0) + Number(row.weighing_weight || 0));
}
if (orderDeliveryModel && typeof orderDeliveryModel.update === 'function') {
for (const oid of normalizedOrderIds) {
await orderDeliveryModel.update(
{ packages_weight: Math.round(sumMap.get(oid) || 0) },
{ where: { id: oid, warehouse_id: warehouseId } }
);
}
}
} catch (err) {
ctx.logger && ctx.logger.warn && ctx.logger.warn(
`[order_express._syncWavePackagesWeight] 批量回写包裹总重量失败: ${err && err.message}`
);
}
}
/**
* 更新订单运单称重重量。
*
* 支持团购波次批量设置:
* - 散单(wave_id = 0)或非团购波次:仅更新单个订单的运单重量。
* - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。
*
* @param {Object} payload 入参对象。
* @param {number|string} payload.orderId 订单ID。
* @param {string} [payload.waybillCode] 运单号,多运单场景必填。
* @param {number|string} payload.weighingWeight 称重重量(g)。
* @return {Promise<Object>} 单订单返回 {order_id, waybill_code, weighing_weight, items_weight};
* 团购批量返回 {wave_id, wave_no, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。
*/
async updateWeighingWeight(payload = {}) {
const requestData = payload && typeof payload === 'object' ? payload : {};
const {
orderId,
waybillCode = '',
weighingWeight,
} = requestData;
const normalizedOrderId = this.normalizeOrderId(orderId);
const normalizedWeight = this.normalizeWeighingWeight(weighingWeight);
const normalizedWaybillCode = String(waybillCode || '').trim();
const warehouseId = this.ctx && this.ctx.user ? this.ctx.user.store_id : null;
// 无法获取仓库ID时降级为单个订单逻辑
if (!warehouseId) {
return await this._updateSingleOrderWeight(
normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId
);
}
// 先查运单表校验运单是否存在(强制同仓校验:订单ID + 仓库ID)
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: {
order_id: normalizedOrderId,
delete_at: null,
warehouse_id: warehouseId,
},
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ],
raw: true,
});
if (!expressRow) {
throw this.createBusinessError('运单号不存在', 404);
}
// 拦截流程中的订单不允许称重
await this.assertOrderNotIntercepted(normalizedOrderId, warehouseId, '称重');
// 依次查询多个订单表获取波次信息:current → history → dispatch
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
throw this.createBusinessError('订单模型未初始化', 500);
}
const orderTableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
// 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(normalizedOrderId, warehouseId);
if (preferredLocation) {
orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
let orderRow = null;
let orderDeliveryModel = null;
for (const entry of orderTableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') {
continue;
}
const row = await model.findOne({
where: { id: normalizedOrderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id', 'wave_no' ],
raw: true,
});
if (row) {
orderRow = row;
orderDeliveryModel = model;
break;
}
} catch (_err) {
// 该表可能不存在,继续尝试下一张表
continue;
}
}
// 所有表都找不到 → 兼容前端传入 wave_id 的场景,尝试按波次查询
if (!orderRow) {
const fallbackModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
return await this._tryWaveCompatibility(
normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId, fallbackModel
);
}
const waveId = Number(orderRow.wave_id || 0);
// 散单 → 走单个订单逻辑
if (waveId === 0) {
return await this._updateSingleOrderWeight(
normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId
);
}
// 查询波次类型
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') {
throw this.createBusinessError('波次模型未初始化', 500);
}
const waveRow = await waveBatchModel.findOne({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
raw: true,
});
// 波次记录缺失或非团购波次 → 降级为单个订单逻辑
if (!waveRow || Number(waveRow.wave_type) !== 1) {
return await this._updateSingleOrderWeight(
normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId
);
}
// 团购波次 → 批量设置同一重量
return await this._updateWaveOrderWeight(
waveId, String(waveRow.wave_no || ''), normalizedWeight, warehouseId, orderDeliveryModel, normalizedOrderId
);
}
/**
* 通过运单号更新称重重量(运单号模式,order_id=0 时使用)。
*
* 从运单号反查 wms_order_express,再定位订单和波次:
* - 散单或非团购波次:仅更新该运单的称重重量。
* - 团购波次(wave_type=1):按 wave_no + business_key 批量设置同一重量,
* 并返回含拆单汇总信息的结构。
*
* @param {Object} payload 入参对象。
* @param {string} payload.waybillCode 运单号(必填)。
* @param {number|string} payload.weighingWeight 称重重量(g)。
* @return {Promise<Object>} 单运单返回 {order_id, waybill_code, weighing_weight, items_weight};
* 团购批量返回 {wave_id, wave_no, order_id, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。
*/
async updateWeighingWeightByWaybill(payload = {}) {
const requestData = payload && typeof payload === 'object' ? payload : {};
const { waybillCode, weighingWeight } = requestData;
const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode);
const normalizedWeight = this.normalizeWeighingWeight(weighingWeight);
const warehouseId = this.getCurrentWarehouseId();
// 按运单号 + 仓库ID 查 wms_order_express
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: normalizedWaybillCode,
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key' ],
raw: true,
});
if (!expressRow) {
throw this.createBusinessError('运单号不存在', 404);
}
const orderId = Number(expressRow.order_id || 0);
// 拦截流程中的订单不允许称重
await this.assertOrderNotIntercepted(orderId, warehouseId, '称重');
// 依次查询多个订单表获取波次信息:current → history → dispatch
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
throw this.createBusinessError('订单模型未初始化', 500);
}
const orderTableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
// 序列表定位优先:命中则先查对应分表,未命中(存量订单)按原顺序回退遍历
try {
if (orderDeliveryFactory && typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
orderTableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
let orderRow = null;
let orderDeliveryModel = null;
for (const entry of orderTableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') {
continue;
}
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id', 'wave_no' ],
raw: true,
});
if (row) {
orderRow = row;
orderDeliveryModel = model;
break;
}
} catch (_err) {
// 该表可能不存在,继续尝试下一张表
continue;
}
}
if (!orderRow) {
throw this.createBusinessError('运单号对应的订单不存在', 404);
}
const waveId = Number(orderRow.wave_id || 0);
// 散单 → 走单个运单逻辑
if (waveId === 0) {
return await this._updateSingleOrderWeight(
orderId, normalizedWaybillCode, normalizedWeight, warehouseId
);
}
// 查询波次类型
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') {
throw this.createBusinessError('波次模型未初始化', 500);
}
const waveRow = await waveBatchModel.findOne({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
raw: true,
});
// 非团购波次 → 降级为单运单逻辑
if (!waveRow || Number(waveRow.wave_type) !== 1) {
return await this._updateSingleOrderWeight(
orderId, normalizedWaybillCode, normalizedWeight, warehouseId
);
}
// 团购波次 → 按 wave_id 批量设置波次下全部运单
return await this._updateWaveAllOrdersWeight(
waveId,
String(waveRow.wave_no || ''),
normalizedWeight,
warehouseId,
orderDeliveryModel,
orderId
);
}
/**
* 批量更新团购波次下所有订单运单的称重重量(内部方法,运单号模式入口)。
*
* 查询波次下全部订单,按 order_id 批量更新所有运单的 weighing_weight,
* 不区分 business_key。与 _updateWaveOrderWeight 功能等价但调用入口不同。
*
* @param {number} waveId 波次ID。
* @param {string} waveNo 波次号。
* @param {number} weight 称重重量。
* @param {number} warehouseId 仓库ID。
* @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。
* @param {number} orderId 触发更新的运单对应订单ID。
* @return {Promise<{wave_id:number, wave_no:string, order_id:number, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>}
* 团购批量更新结果,含拆单汇总信息及触发订单ID。
*/
async _updateWaveAllOrdersWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) {
// 查询波次下所有订单
const waveOrders = await orderDeliveryModel.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
if (!waveOrders || waveOrders.length === 0) {
throw this.createBusinessError('波次下未找到订单', 404);
}
// 波次内拦截订单不参与批量称重
const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
const orderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => !isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
if (interceptedWaveOrderIds.length > 0) {
this.ctx.logger.info(
`[order_express._updateWaveAllOrdersWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}`
);
}
// 批量更新波次下全部运单的称重重量
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.update !== 'function') {
throw this.createBusinessError('运单模型未初始化', 500);
}
const { Op } = this.app.Sequelize;
// 强制同仓校验:批量更新称重重量必须同时限定订单ID与仓库ID
const updateWhere = {
order_id: { [Op.in]: orderIds },
delete_at: null,
warehouse_id: warehouseId,
};
// 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判
const matchingCount = await orderExpressModel.count({ where: updateWhere });
if (matchingCount === 0) {
throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500);
}
await orderExpressModel.update(
{ weighing_weight: weight },
{ where: updateWhere }
);
const successCount = matchingCount;
// 写入操作日志
await this._writeWeighActionLog({
waveId,
waveNo,
weight,
warehouseId,
successCount,
totalCount: orderIds.length,
});
// 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和)
await this._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel);
// 构建拆单汇总信息(按触发订单 ID 汇总)
const summary = await this._buildWaveWeighingSummary(waveId, orderId, warehouseId, weight);
// 从订单表读取当前 items_weight(只读,不做 UPDATE)
const orderRow = await orderDeliveryModel.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'items_weight' ],
raw: true,
});
const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0;
return {
wave_id: waveId,
wave_no: waveNo,
order_id: orderId,
weighing_weight: weight,
total_weight: summary.total_weight,
split_count: summary.split_count,
splits: summary.splits,
store_name: summary.store_name,
sys_logistics_name: summary.sys_logistics_name,
items_weight: itemsWeight,
};
}
/**
* 构建团购波次称重拆单汇总信息(内部方法)。
*
* 查询指定订单下所有运单记录,按 business_key 分组汇总称重重量,
* 并获取货主名称与系统快递名称。
*
* @param {number} waveId 波次ID。
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @param {number} currentWeight 本次设置的称重重量。
* @return {Promise<{total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string}>}
* 拆单汇总信息。
*/
async _buildWaveWeighingSummary(waveId, orderId, warehouseId, currentWeight) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return {
total_weight: currentWeight,
split_count: 0,
splits: [],
store_name: '',
sys_logistics_name: '',
};
}
// 查询指定订单下所有有效运单记录(强制同仓校验:订单ID + 仓库ID)
const expressRows = await orderExpressModel.findAll({
where: {
order_id: orderId,
delete_at: null,
warehouse_id: warehouseId,
},
attributes: [ 'business_key', 'weighing_weight', 'waybill_code' ],
raw: true,
});
// 按 business_key 分组汇总称重重量
const splitMap = new Map();
for (const row of expressRows) {
const bk = row.business_key === null || row.business_key === undefined
? '__null__'
: String(row.business_key);
if (!splitMap.has(bk)) {
splitMap.set(bk, {
business_key: row.business_key,
weighing_weight: 0,
waybill_code: row.waybill_code || null,
});
}
const entry = splitMap.get(bk);
entry.weighing_weight = entry.weighing_weight + Number(row.weighing_weight || 0);
// 优先取非空的 waybill_code 作为该拆单的代表运单号
if (!entry.waybill_code && row.waybill_code) {
entry.waybill_code = row.waybill_code;
}
}
const splits = [ ...splitMap.values() ];
const totalWeight = splits.reduce((sum, s) => sum + s.weighing_weight, 0);
// split_count:仅统计 waybill_code 不为空的 business_key
const splitCount = splits.filter(s => s.waybill_code !== null).length;
// 获取货主名称
const storeName = await this._getStoreName([ orderId ], warehouseId);
// 获取系统快递名称
const sysLogisticsName = await this._getWaveSysLogisticsName([ orderId ], warehouseId);
return {
total_weight: totalWeight,
split_count: splitCount,
splits,
store_name: storeName,
sys_logistics_name: sysLogisticsName,
};
}
/**
* 获取波次下第一个订单的货主名称(shop_nick)。
*
* @param {number[]} orderIds 订单ID列表。
* @param {number} warehouseId 仓库ID。
* @return {Promise<string>} 货主名称(shop_nick),获取失败时返回空字符串。
*/
async _getStoreName(orderIds, warehouseId) {
try {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return '';
}
const { Op } = this.app.Sequelize;
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const orderRow = await model.findOne({
where: {
id: { [Op.in]: orderIds },
warehouse_id: warehouseId,
shop_nick: { [Op.ne]: null },
},
attributes: [ 'shop_nick' ],
raw: true,
});
if (orderRow) return String(orderRow.shop_nick || '').trim();
} catch (_err) { continue; }
}
return '';
} catch (_err) {
return '';
}
}
/**
* 获取波次下订单的系统快递名称。
*
* 取波次下第一个有值的 sys_logistics_name。
*
* @param {number[]} orderIds 订单ID列表。
* @param {number} warehouseId 仓库ID。
* @return {Promise<string>} 系统快递名称,获取失败时返回空字符串。
*/
async _getWaveSysLogisticsName(orderIds, warehouseId) {
try {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return '';
}
const { Op } = this.app.Sequelize;
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const orderRow = await model.findOne({
where: {
id: { [Op.in]: orderIds },
warehouse_id: warehouseId,
sys_logistics_name: { [Op.ne]: null },
},
attributes: [ 'sys_logistics_name' ],
raw: true,
});
if (orderRow) return String(orderRow.sys_logistics_name || '').trim();
} catch (_err) { continue; }
}
return '';
} catch (_err) {
return '';
}
}
/**
* 更新单个订单运单的称重重量(内部方法)。
*
* @param {number} orderId 订单ID。
* @param {string} waybillCode 运单号。
* @param {number} weight 称重重量。
* @param {number|null} warehouseId 仓库ID。
* @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number, items_weight:number}>} 更新结果。
*/
async _updateSingleOrderWeight(orderId, waybillCode, weight, warehouseId) {
// 散单称重前置校验:开启「散单称重是否需要打包」后,未打包订单禁止称重
await this.assertSingleOrderPackedForWeigh(orderId, warehouseId);
const rows = await this.findValidOrderExpressRows(orderId, warehouseId);
if (rows.length === 0) {
throw this.createBusinessError('未找到有效的订单运单记录', 404);
}
let targetRow = null;
if (rows.length === 1) {
targetRow = rows[0];
} else {
if (!waybillCode) {
throw this.createBusinessError('多运单订单必须传入 waybill_code', 400);
}
targetRow = rows.find(
row => String(row && row.waybill_code || '').trim() === waybillCode
) || null;
if (!targetRow) {
throw this.createBusinessError('waybill_code 未匹配到该订单下的运单记录', 404);
}
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
const updateResult = await orderExpressModel.update(
{ weighing_weight: weight },
{ where: { id: Number(targetRow.id) } }
);
const affectedRows = Array.isArray(updateResult)
? Number(updateResult[0] || 0)
: Number(updateResult || 0);
if (!Number.isFinite(affectedRows) || affectedRows <= 0) {
throw this.createBusinessError('更新称重重量失败', 500);
}
// 写入操作日志
await this._writeWeighActionLog({
orderId: Number(targetRow.order_id),
waybillCode: String(targetRow.waybill_code || '').trim(),
weight,
warehouseId,
});
// 回写订单表 packages_weight:所有包裹总重量 = 该订单全部有效运单称重之和
const packagesWeight = await this._syncOrderPackagesWeight(Number(targetRow.order_id), warehouseId);
// 从订单表读取当前 items_weight(只读,不做 UPDATE)
// 依次查 current / dispatch 两张表
let itemsWeight = 0;
if (warehouseId) {
try {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') {
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const orderRow = await model.findOne({
where: { id: Number(targetRow.order_id), warehouse_id: warehouseId },
attributes: [ 'items_weight' ],
raw: true,
});
if (orderRow) { itemsWeight = Number(orderRow.items_weight || 0); break; }
} catch (_err) { continue; }
}
}
} catch (_err) {
// 查询失败时静默降级为 0
}
}
return {
order_id: Number(targetRow.order_id),
waybill_code: String(targetRow.waybill_code || '').trim(),
weighing_weight: weight,
packages_weight: packagesWeight,
items_weight: itemsWeight,
};
}
/**
* 批量更新团购波次下所有订单运单的称重重量(内部方法)。
*
* @param {number} waveId 波次ID。
* @param {string} waveNo 波次号。
* @param {number} weight 称重重量。
* @param {number|null} warehouseId 仓库ID。
* @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。
* @param {number} [orderId] 触发更新的订单ID,未传时取波次下第一个订单。
* @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, total_weight:number, split_count:number, splits:Array<{business_key:string|null, weighing_weight:number, waybill_code:string|null}>, store_name:string, sys_logistics_name:string, items_weight:number}>}
* 团购批量更新结果,含拆单汇总信息。
*/
async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel, orderId) {
// 查询波次下所有订单
const waveOrders = await orderDeliveryModel.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
if (!waveOrders || waveOrders.length === 0) {
throw this.createBusinessError('波次下未找到订单', 404);
}
// 波次内拦截订单不参与批量称重
const interceptedWaveOrderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
const orderIds = (Array.isArray(waveOrders) ? waveOrders : [])
.filter(o => !isInterceptedOrderStatus(o && o.intercept_status))
.map(o => Number(o.id));
if (interceptedWaveOrderIds.length > 0) {
this.ctx.logger.info(
`[order_express._updateWaveOrderWeight] 波次内拦截订单不参与称重: ${interceptedWaveOrderIds.join(',')}`
);
}
const totalCount = orderIds.length;
// 批量更新所有订单的运单称重重量
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.update !== 'function') {
throw this.createBusinessError('运单模型未初始化', 500);
}
const { Op } = this.app.Sequelize;
// 强制同仓校验:批量更新称重重量必须同时限定订单ID与仓库ID
const updateWhere = {
order_id: { [Op.in]: orderIds },
delete_at: null,
warehouse_id: warehouseId,
};
// 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判
const matchingCount = await orderExpressModel.count({ where: updateWhere });
if (matchingCount === 0) {
throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500);
}
await orderExpressModel.update(
{ weighing_weight: weight },
{ where: updateWhere }
);
const successCount = matchingCount;
// 写入操作日志
await this._writeWeighActionLog({
waveId,
waveNo,
weight,
warehouseId,
successCount,
totalCount,
});
// 回写波次内各订单的 packages_weight(所有包裹总重量 = 各订单全部运单称重之和)
await this._syncWavePackagesWeight(orderIds, warehouseId, orderDeliveryModel);
// 构建拆单汇总信息(按触发订单 ID 汇总,未传时取波次下第一个订单)
const scopeOrderId = (Number.isFinite(Number(orderId)) && Number(orderId) > 0)
? Number(orderId)
: orderIds[0];
const summary = await this._buildWaveWeighingSummary(waveId, scopeOrderId, warehouseId, weight);
// 从订单表读取当前 items_weight(只读,不做 UPDATE)
const orderRow = await orderDeliveryModel.findOne({
where: { id: scopeOrderId, warehouse_id: warehouseId },
attributes: [ 'items_weight' ],
raw: true,
});
const itemsWeight = orderRow ? Number(orderRow.items_weight || 0) : 0;
return {
wave_id: waveId,
wave_no: waveNo,
weighing_weight: weight,
total_weight: summary.total_weight,
split_count: summary.split_count,
splits: summary.splits,
store_name: summary.store_name,
sys_logistics_name: summary.sys_logistics_name,
items_weight: itemsWeight,
};
}
/**
* 写入称重操作日志到 wms_wave_pick_action_log(内部方法)。
*
* @param {Object} params 日志参数。
* @param {number} [params.orderId] 订单ID(单订单称重场景)。
* @param {string} [params.waybillCode] 运单号(单订单称重场景)。
* @param {number} [params.waveId] 波次ID(团购批量称重场景)。
* @param {string} [params.waveNo] 波次号(团购批量称重场景)。
* @param {number} params.weight 称重重量。
* @param {number} params.warehouseId 仓库ID。
* @param {number} [params.successCount] 批量更新成功数。
* @param {number} [params.totalCount] 批量更新总数。
* @return {Promise<void>} 无返回值。
*/
async _writeWeighActionLog(params = {}) {
const {
orderId,
waybillCode,
waveId,
waveNo,
weight,
warehouseId,
successCount,
totalCount,
} = params;
const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {};
const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0);
const operatorName = String(
ctxUser.employees_name || ctxUser.name || 'system'
).trim();
const isBatch = waveId !== undefined && waveId !== null;
const tag = isBatch ? 'weigh_batch' : 'weigh';
const requestId = `${tag}_${warehouseId}_${isBatch ? waveId : orderId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
await this.ctx.model.query(
`INSERT INTO wms_wave_pick_action_log (
task_id,
warehouse_id,
wave_id,
order_id,
sku_id,
location_id,
box_no,
cart_id,
qty_delta,
action_type,
request_id,
operator_id,
device_id,
seq_no,
snapshot
) VALUES (
:taskId,
:warehouseId,
:waveId,
:orderId,
:skuId,
:locationId,
:boxNo,
:cartId,
:qtyDelta,
:actionType,
:requestId,
:operatorId,
:deviceId,
:seqNo,
:snapshot
)`,
{
replacements: {
taskId: 0,
warehouseId: warehouseId || 0,
waveId: isBatch ? waveId : null,
orderId: isBatch ? null : (orderId || 0),
skuId: null,
locationId: null,
boxNo: null,
cartId: null,
qtyDelta: 0,
actionType: isBatch ? 'weigh_batch' : 'weigh',
requestId,
operatorId,
deviceId: null,
seqNo: 1,
snapshot: JSON.stringify(isBatch
? {
wave_id: waveId,
wave_no: waveNo || '',
weighing_weight: weight,
success_count: successCount,
total_count: totalCount,
operator_name: operatorName,
}
: {
order_id: orderId,
waybill_code: waybillCode || '',
weighing_weight: weight,
operator_name: operatorName,
}),
},
type: this.ctx.model.QueryTypes.INSERT,
}
);
// 写入 order_operation_log
try {
const operationLogService = this.ctx
&& this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.operationLog;
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
const logPayloads = [];
if (isBatch && waveId) {
logPayloads.push({
businessType: 'order',
businessId: `wave_${waveId}`,
operationCode: 'ORDER_WEIGH',
operator: { id: String(operatorId || ''), name: operatorName },
extras: {
message: `波次 ${waveNo || waveId} 批量称重 ${weight}g,成功 ${successCount}/${totalCount}`,
warehouseId,
waveId,
waveNo: waveNo || '',
weighingWeight: weight,
successCount,
totalCount,
},
});
} else if (orderId) {
logPayloads.push({
businessType: 'order',
businessId: `${orderId}`,
operationCode: 'ORDER_WEIGH',
operator: { id: String(operatorId || ''), name: operatorName },
extras: {
message: `订单称重 ${weight}g`,
warehouseId,
orderId,
waybillCode: waybillCode || '',
weighingWeight: weight,
},
});
}
if (logPayloads.length > 0) {
await operationLogService.createOperationLogs(logPayloads);
}
}
} catch (e) {
this.ctx.logger.warn('[order_express._writeWeighActionLog] 写入 operation_log 失败,不影响主流程', {
error: e && e.message,
waveId,
orderId,
});
}
}
/**
* 先用传入的 ID 在 wms_wave_batch 中查找波次:
* - 波次不存在 → 抛出"订单不存在"错误。
* - 波次存在且 wave_type = 1(团购)→ 走团购批量称重逻辑。
* - 波次存在但 wave_type ≠ 1 → 无法确定具体订单,抛出错误提示传入正确的 order_id。
*
* @param {number} waveIdLike 可能是 wave_id 的数值。
* @param {string} waybillCode 运单号(兼容参数,本路径不使用)。
* @param {number} weight 称重重量。
* @param {number|null} warehouseId 仓库ID。
* @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。
* @return {Promise<Object>} 团购批量更新结果。
* @throws {Error} 波次不存在或非团购波次时抛出业务错误。
*/
async _tryWaveCompatibility(waveIdLike, waybillCode, weight, warehouseId, orderDeliveryModel) {
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
if (!waveBatchModel || typeof waveBatchModel.findOne !== 'function') {
throw this.createBusinessError('订单不存在', 404);
}
const waveRow = await waveBatchModel.findOne({
where: { wave_id: waveIdLike, warehouse_id: warehouseId },
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
raw: true,
});
// 波次也不存在 → 报订单不存在
if (!waveRow) {
throw this.createBusinessError('订单不存在', 404);
}
// 非团购波次 → 无法确定具体订单,提示前端传入正确的 order_id
if (Number(waveRow.wave_type) !== 1) {
throw this.createBusinessError(
`传入的 ID ${waveIdLike} 对应波次(wave_no: ${waveRow.wave_no}),非团购波次,请传入正确的 order_id`,
400
);
}
// 团购波次 → 批量设置同一重量
return await this._updateWaveOrderWeight(
waveIdLike,
String(waveRow.wave_no || ''),
weight,
warehouseId,
orderDeliveryModel
);
}
/**
* 写入或更新商品结构-包材绑定关系记录。
*
* 若订单的 items_hash 不存在则跳过;关系表写入失败不影响主流程。
*
* @param {Object} params 绑定上下文参数。
* @param {number} params.orderId 订单ID。
* @param {string} params.waybillCode 运单号。
* @param {number} params.packageMaterialId 包材ID。
* @param {string} params.packageMaterialCode 包材编码。
* @param {string} params.packageMaterialName 包材名称。
* @param {number} params.warehouseId 仓库ID。
* @return {Promise<void>}
*/
async _upsertPackageMaterialItemRelation({ orderId, waybillCode, packageMaterialId, packageMaterialCode, packageMaterialName, warehouseId }) {
const { ctx } = this;
try {
// 1. 查订单的 items_hash / items_crc(依次查 current / dispatch 两张表)
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') return;
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
let orderRow = null;
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'items_hash', 'items_crc' ],
raw: true,
});
if (row) { orderRow = row; break; }
} catch (_err) { continue; }
}
if (!orderRow || !orderRow.items_hash) return;
const { items_hash: itemsHash, items_crc: itemsCrc } = orderRow;
// 2. 查关系表
const relationModel = ctx.model && ctx.model.PackageMaterialItemRelation;
if (!relationModel) return;
const existing = await relationModel.findOne({
where: {
warehouse_id: warehouseId,
items_hash: itemsHash,
items_crc: itemsCrc,
package_material_id: packageMaterialId,
delete_at: null,
},
raw: true,
});
// 3. 查包材完整快照
const packageMaterialModel = ctx.model && ctx.model.PackageMaterial;
const materialRow = packageMaterialModel
? await packageMaterialModel.findOne({ where: { id: packageMaterialId }, raw: true })
: null;
const snapshot = {
package_material_code: String(packageMaterialCode || '').trim(),
package_material_name: String(packageMaterialName || '').trim(),
package_material_spec: String(materialRow && materialRow.spec || '').trim(),
package_material_type: String(materialRow && materialRow.material_type || '').trim(),
length: Number(materialRow && materialRow.length || 0),
width: Number(materialRow && materialRow.width || 0),
height: Number(materialRow && materialRow.height || 0),
weight: Number(materialRow && materialRow.weight || 0),
};
const userId = ctx.user && ctx.user.id ? Number(ctx.user.id) : null;
const now = new Date();
if (existing) {
await relationModel.update({
bind_count: (Number(existing.bind_count) || 0) + 1,
last_order_id: orderId,
last_waybill_code: waybillCode,
last_bind_user_id: userId,
last_bind_at: now,
is_active: 1,
...snapshot,
}, {
where: { id: existing.id },
});
} else {
await relationModel.create({
warehouse_id: warehouseId,
items_hash: itemsHash,
items_crc: itemsCrc,
package_material_id: packageMaterialId,
bind_count: 1,
last_order_id: orderId,
last_waybill_code: waybillCode,
last_bind_user_id: userId,
last_bind_at: now,
is_active: 1,
...snapshot,
});
}
} catch (err) {
// 关系表写入失败不影响主流程
ctx && ctx.logger && ctx.logger.error(`[packageMaterialRelation] upsert failed: ${err.message}`);
}
}
/**
* 绑定订单快递记录的包材信息。
* @param {Object} payload 入参对象。
* @param {number|string} payload.orderId 订单ID。
* @param {string} payload.waybillCode 运单号。
* @param {string} payload.packageMaterialCode 包材编码。
* @return {Promise<Object>} 绑定后的结果快照。
*/
async bindExpressPackageMaterial(payload = {}) {
const requestData = payload && typeof payload === 'object' ? payload : {};
const {
orderId,
waybillCode,
packageMaterialCode,
} = requestData;
const normalizedOrderId = this.normalizeBindOrderId(orderId);
const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode);
const normalizedPackageMaterialCode = this.normalizePackageMaterialCode(packageMaterialCode);
const warehouseId = this.getCurrentWarehouseId();
const materialRow = await this.findActivePackageMaterialByCode(normalizedPackageMaterialCode, warehouseId);
const orderExpressRow = await this.findValidOrderExpressByOrderAndWaybill(normalizedOrderId, normalizedWaybillCode, warehouseId);
// 拦截流程中的订单不允许绑定包材
await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材');
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
const updateResult = await orderExpressModel.update({
package_material_id: Number(materialRow.id),
package_material_name_snapshot: String(materialRow.material_name || '').trim(),
}, {
where: {
id: Number(orderExpressRow.id),
delete_at: null,
},
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id);
if (!Number.isFinite(affectedRows) || affectedRows <= 0) {
if (!isSameMaterial) {
throw this.createBusinessError('绑定包材失败', 500);
}
// 同一包材幂等:跳过 update 报错,继续走关系表
}
await this._upsertPackageMaterialItemRelation({
orderId: normalizedOrderId,
waybillCode: normalizedWaybillCode,
packageMaterialId: Number(materialRow.id),
packageMaterialCode: String(materialRow.material_code || '').trim(),
packageMaterialName: String(materialRow.material_name || '').trim(),
warehouseId,
});
return {
order_id: Number(orderExpressRow.order_id),
waybill_code: String(orderExpressRow.waybill_code || '').trim(),
package_material_id: Number(materialRow.id),
package_material_name_snapshot: String(materialRow.material_name || '').trim(),
package_material_code: String(materialRow.material_code || '').trim(),
};
}
/**
* 根据运单号绑定包材。
*
* 仅凭运单号即可绑定包材,无需传入订单ID。
* 先按运单号 + 仓库ID 查询有效运单记录,再按包材ID查询启用中的包材,
* 最后更新运单记录的包材字段。
*
* 支持团购波次自动感知:
* - 非团购订单(wave_id=0 或 wave_type≠1):仅绑定当前运单的包材,行为与旧版一致。
* - 团购波次(wave_type=1):自动将同一波次下、相同快递业务键(business_key)的
* 所有运单批量绑定相同的包材,实现一键补齐。
*
* @param {Object} [payload={}] 请求参数。
* @param {string} payload.waybillCode 运单号。
* @param {number|string} payload.packageMaterialId 包材ID。
* @return {Promise<Object>} 单条绑定返回 {order_id, waybill_code, package_material_id, package_material_name_snapshot, package_material_code};
* 团购批量绑定返回 {wave_id, wave_no, business_key, order_id, waybill_code, package_material_id, package_material_code, package_material_name_snapshot, bind_count, bound_waybills, store_name, sys_logistics_name}。
*/
async bindExpressPackageMaterialByWaybill(payload = {}) {
const requestData = payload && typeof payload === 'object' ? payload : {};
const {
waybillCode,
packageMaterialId,
} = requestData;
const normalizedWaybillCode = this.normalizeWaybillCode(waybillCode);
const normalizedPackageMaterialId = this.normalizePackageMaterialId(packageMaterialId);
const warehouseId = this.getCurrentWarehouseId();
// 按运单号 + 仓库ID 查询有效运单记录
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findOne !== 'function') {
throw this.createBusinessError('运单模型未初始化', 500);
}
const orderExpressRow = await orderExpressModel.findOne({
where: {
waybill_code: normalizedWaybillCode,
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'id', 'order_id', 'waybill_code', 'warehouse_id', 'delete_at', 'package_material_id', 'business_key' ],
raw: true,
});
if (!orderExpressRow) {
throw this.createBusinessError('运单号不存在', 404);
}
// 拦截流程中的订单不允许绑定包材
await this.assertOrderNotIntercepted(Number(orderExpressRow.order_id), warehouseId, '绑定包材');
// 查询启用中的包材
const materialRow = await this.findActivePackageMaterialById(normalizedPackageMaterialId, warehouseId);
// --- 团购波次自动感知 ---
// 依次查询 current / dispatch 表获取波次信息
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') {
try {
const orderTableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
let orderRow = null;
for (const entry of orderTableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: Number(orderExpressRow.order_id), warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id', 'wave_no' ],
raw: true,
});
if (row) { orderRow = row; break; }
} catch (_err) { continue; }
}
if (orderRow) {
const waveId = Number(orderRow.wave_id || 0);
if (waveId > 0) {
// 查询波次类型
const waveBatchModel = this.ctx.model && this.ctx.model.WaveBatch;
if (waveBatchModel && typeof waveBatchModel.findOne === 'function') {
const waveRow = await waveBatchModel.findOne({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
raw: true,
});
// 团购波次(wave_type=1)→ 按业务键分类批量绑定
if (waveRow && Number(waveRow.wave_type) === 1) {
return await this._bindWavePackageMaterialByBusinessKey({
waveId,
waveNo: String(waveRow.wave_no || ''),
businessKey: orderExpressRow.business_key ?? null,
packageMaterialId: Number(materialRow.id),
packageMaterialCode: String(materialRow.material_code || '').trim(),
packageMaterialName: String(materialRow.material_name || '').trim(),
warehouseId,
triggerOrderId: Number(orderExpressRow.order_id),
triggerWaybillCode: normalizedWaybillCode,
});
}
}
}
}
} catch (_waveErr) {
// 波次查询失败时静默降级为单条绑定,保证向后兼容
this.ctx && this.ctx.logger && this.ctx.logger.warn(
`[bindExpressPackageMaterialByWaybill] 团购波次检测失败,降级为单条绑定: ${_waveErr.message}`
);
}
}
// 非团购 → 单条绑定(保持现有逻辑)
return await this._bindSingleExpressPackageMaterial({
orderExpressRow,
materialRow,
normalizedWaybillCode,
warehouseId,
});
}
/**
* 单条运单包材绑定(内部方法)。
*
* 更新单条运单记录的包材字段,并写入包材-商品结构关系表。
*
* @param {Object} params 绑定上下文参数。
* @param {Object} params.orderExpressRow 运单记录。
* @param {Object} params.materialRow 包材记录。
* @param {string} params.normalizedWaybillCode 规范化后的运单号。
* @param {number} params.warehouseId 仓库ID。
* @return {Promise<Object>} 绑定后的结果快照,包含 order_id、waybill_code、package_material_id、package_material_name_snapshot、package_material_code。
*/
async _bindSingleExpressPackageMaterial({ orderExpressRow, materialRow, normalizedWaybillCode, warehouseId }) {
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
// 更新运单记录的包材字段
const updateResult = await orderExpressModel.update({
package_material_id: Number(materialRow.id),
package_material_name_snapshot: String(materialRow.material_name || '').trim(),
}, {
where: {
id: Number(orderExpressRow.id),
delete_at: null,
},
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
const isSameMaterial = Number(orderExpressRow.package_material_id) === Number(materialRow.id);
if (!Number.isFinite(affectedRows) || affectedRows <= 0) {
if (!isSameMaterial) {
throw this.createBusinessError('绑定包材失败', 500);
}
// 同一包材幂等:跳过 update 报错,继续走关系表
}
await this._upsertPackageMaterialItemRelation({
orderId: Number(orderExpressRow.order_id),
waybillCode: normalizedWaybillCode,
packageMaterialId: Number(materialRow.id),
packageMaterialCode: String(materialRow.material_code || '').trim(),
packageMaterialName: String(materialRow.material_name || '').trim(),
warehouseId,
});
// 写入包材绑定操作日志(单条绑定)
try {
const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {};
const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0);
const operatorName = String(ctxUser.employees_name || ctxUser.name || 'system').trim() || 'system';
const opLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (opLogService && typeof opLogService.createOperationLogs === 'function') {
await opLogService.createOperationLogs([{
businessType: 'order',
businessId: `${Number(orderExpressRow.order_id || 0)}`,
operationCode: 'ORDER_PACKAGE_MATERIAL_BIND',
operator: { id: String(operatorId || ''), name: operatorName },
extras: {
message: `订单绑定包材 ${String(materialRow.material_name || materialRow.material_code || '').trim()}`,
warehouseId,
orderId: Number(orderExpressRow.order_id || 0),
waybillCode: normalizedWaybillCode,
packageMaterialId: Number(materialRow.id),
packageMaterialName: String(materialRow.material_name || '').trim(),
},
}]);
}
} catch (e) {
this.ctx.logger.warn('[order_express._bindSingleExpressPackageMaterial] 写入 operation_log 失败', {
error: e && e.message,
orderId: Number(orderExpressRow.order_id || 0),
});
}
return {
order_id: Number(orderExpressRow.order_id),
waybill_code: String(orderExpressRow.waybill_code || '').trim(),
package_material_id: Number(materialRow.id),
package_material_name_snapshot: String(materialRow.material_name || '').trim(),
package_material_code: String(materialRow.material_code || '').trim(),
};
}
/**
* 团购波次按快递业务键分类批量绑定包材(内部方法)。
*
* 查询波次下所有订单,再按触发运单的 business_key 筛选出同分类的运单,
* 批量更新包材字段并写入关系表。
*
* @param {Object} params 批量绑定上下文参数。
* @param {number} params.waveId 波次ID。
* @param {string} params.waveNo 波次号。
* @param {string|null} params.businessKey 快递业务键,用于分类过滤。
* @param {number} params.packageMaterialId 包材ID。
* @param {string} params.packageMaterialCode 包材编码。
* @param {string} params.packageMaterialName 包材名称。
* @param {number} params.warehouseId 仓库ID。
* @param {number} params.triggerOrderId 触发绑定的订单ID。
* @param {string} params.triggerWaybillCode 触发绑定的运单号。
* @return {Promise<Object>} 团购批量绑定结果,含 wave_id、wave_no、business_key、order_id、waybill_code、package_material_id、package_material_code、package_material_name_snapshot、bind_count、bound_waybills、store_name、sys_logistics_name。
*/
async _bindWavePackageMaterialByBusinessKey({
waveId,
waveNo,
businessKey,
packageMaterialId,
packageMaterialCode,
packageMaterialName,
warehouseId,
triggerOrderId,
triggerWaybillCode,
}) {
// 1. 查询波次下所有订单(current + dispatch 两张表)
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
throw this.createBusinessError('订单模型未初始化', 500);
}
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
const orderIdSet = new Set();
const excludedInterceptedOrderIds = [];
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findAll !== 'function') continue;
const rows = await model.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id', 'intercept_status' ],
raw: true,
});
if (Array.isArray(rows)) {
rows.forEach(r => {
const orderId = Number(r.id);
if (isInterceptedOrderStatus(r && r.intercept_status)) {
excludedInterceptedOrderIds.push(orderId);
return;
}
orderIdSet.add(orderId);
});
}
} catch (_err) { continue; }
}
if (excludedInterceptedOrderIds.length > 0) {
this.ctx.logger.info(
`[bindExpressPackageMaterialByWaybill] 波次内拦截订单不参与批量绑定: ${excludedInterceptedOrderIds.join(',')}`
);
}
if (orderIdSet.size === 0) {
throw this.createBusinessError('波次下未找到订单', 404);
}
const orderIds = Array.from(orderIdSet);
// 2. 查询这些订单下相同 business_key 的所有有效运单
const { Op } = this.app.Sequelize;
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
throw this.createBusinessError('运单模型未初始化', 500);
}
// business_key 为 null 时需特殊处理 Sequelize 查询
const businessKeyWhere = (businessKey === null || businessKey === undefined)
? { [Op.is]: null }
: businessKey;
// 强制同仓校验:按订单ID批量查询运单必须同时限定仓库ID
const expressRows = await orderExpressModel.findAll({
where: {
order_id: { [Op.in]: orderIds },
business_key: businessKeyWhere,
delete_at: null,
warehouse_id: warehouseId,
},
attributes: [ 'id', 'order_id', 'waybill_code', 'business_key', 'package_material_id' ],
raw: true,
});
if (!expressRows || expressRows.length === 0) {
// 波次下无同 business_key 运单 → 降级为仅绑定触发运单
const orderExpressRow = await orderExpressModel.findOne({
where: { waybill_code: triggerWaybillCode, warehouse_id: warehouseId, delete_at: null },
attributes: [ 'id', 'order_id', 'waybill_code', 'package_material_id' ],
raw: true,
});
if (!orderExpressRow) {
throw this.createBusinessError('运单号不存在', 404);
}
const materialRow = {
id: packageMaterialId,
material_code: packageMaterialCode,
material_name: packageMaterialName,
};
return await this._bindSingleExpressPackageMaterial({
orderExpressRow,
materialRow,
normalizedWaybillCode: triggerWaybillCode,
warehouseId,
});
}
const expressIds = expressRows.map(r => Number(r.id));
// 3. 先验证匹配记录是否存在,避免 MySQL 因值未变返回 affected_rows=0 导致误判
const matchingCount = await orderExpressModel.count({
where: { id: { [Op.in]: expressIds }, delete_at: null },
});
if (matchingCount === 0) {
throw this.createBusinessError('批量绑定包材失败,无有效运单记录', 500);
}
// 4. 批量更新包材字段
await orderExpressModel.update(
{
package_material_id: packageMaterialId,
package_material_name_snapshot: packageMaterialName,
},
{
where: { id: { [Op.in]: expressIds }, delete_at: null },
}
);
// 5. 逐条写入包材-商品结构关系表(失败不影响主流程)
for (const row of expressRows) {
await this._upsertPackageMaterialItemRelation({
orderId: Number(row.order_id),
waybillCode: String(row.waybill_code || '').trim(),
packageMaterialId,
packageMaterialCode,
packageMaterialName,
warehouseId,
});
}
// 6. 写入操作日志
await this._writePackageMaterialActionLog({
waveId,
waveNo,
businessKey,
packageMaterialCode,
packageMaterialName,
warehouseId,
bindCount: expressRows.length,
totalOrderCount: orderIds.length,
});
// 7. 获取货主名称与系统快递名称
const storeName = await this._getStoreName(orderIds, warehouseId);
const sysLogisticsName = await this._getWaveSysLogisticsName(orderIds, warehouseId);
// 8. 构建返回结构
return {
wave_id: waveId,
wave_no: waveNo,
business_key: businessKey,
order_id: triggerOrderId,
waybill_code: triggerWaybillCode,
package_material_id: packageMaterialId,
package_material_code: packageMaterialCode,
package_material_name_snapshot: packageMaterialName,
bind_count: expressRows.length,
bound_waybills: expressRows.map(r => ({
order_id: Number(r.order_id),
waybill_code: String(r.waybill_code || '').trim(),
})),
store_name: storeName,
sys_logistics_name: sysLogisticsName,
};
}
/**
* 写入包材绑定操作日志到 wms_wave_pick_action_log(内部方法)。
*
* @param {Object} params 日志参数。
* @param {number} params.waveId 波次ID。
* @param {string} params.waveNo 波次号。
* @param {string|null} params.businessKey 快递业务键。
* @param {string} params.packageMaterialCode 包材编码。
* @param {string} params.packageMaterialName 包材名称。
* @param {number} params.warehouseId 仓库ID。
* @param {number} params.bindCount 绑定运单数。
* @param {number} params.totalOrderCount 波次下订单总数。
* @return {Promise<void>} 无返回值。
*/
async _writePackageMaterialActionLog({
waveId,
waveNo,
businessKey,
packageMaterialCode,
packageMaterialName,
warehouseId,
bindCount,
totalOrderCount,
}) {
const ctxUser = this.ctx && this.ctx.user ? this.ctx.user : {};
const operatorId = Number(ctxUser.employees_id || ctxUser.id || 0);
const operatorName = String(
ctxUser.employees_name || ctxUser.name || 'system'
).trim();
const requestId = `bind_pm_${warehouseId}_${waveId}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
await this.ctx.model.query(
`INSERT INTO wms_wave_pick_action_log (
task_id,
warehouse_id,
wave_id,
order_id,
sku_id,
location_id,
box_no,
cart_id,
qty_delta,
action_type,
request_id,
operator_id,
device_id,
seq_no,
snapshot
) VALUES (
:taskId,
:warehouseId,
:waveId,
:orderId,
:skuId,
:locationId,
:boxNo,
:cartId,
:qtyDelta,
:actionType,
:requestId,
:operatorId,
:deviceId,
:seqNo,
:snapshot
)`,
{
replacements: {
taskId: 0,
warehouseId: warehouseId || 0,
waveId,
orderId: null,
skuId: null,
locationId: null,
boxNo: null,
cartId: null,
qtyDelta: 0,
actionType: 'bind_package_material',
requestId,
operatorId,
deviceId: null,
seqNo: 1,
snapshot: JSON.stringify({
wave_id: waveId,
wave_no: waveNo || '',
business_key: businessKey,
package_material_code: packageMaterialCode,
package_material_name: packageMaterialName,
bind_count: bindCount,
total_order_count: totalOrderCount,
operator_name: operatorName,
}),
},
type: this.ctx.model.QueryTypes.INSERT,
}
);
// 写入 order_operation_log
try {
const operationLogService = this.ctx
&& this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.operationLog;
if (operationLogService && typeof operationLogService.createOperationLogs === 'function') {
await operationLogService.createOperationLogs([{
businessType: 'order',
businessId: `wave_${waveId}`,
operationCode: 'ORDER_PACKAGE_MATERIAL_BIND',
operator: { id: String(operatorId || ''), name: operatorName },
extras: {
message: `波次 ${waveNo || waveId} 绑定包材 ${packageMaterialName || packageMaterialCode},绑定量 ${bindCount}`,
warehouseId,
waveId,
waveNo: waveNo || '',
packageMaterialCode,
packageMaterialName,
bindCount,
businessKey,
},
}]);
}
} catch (e) {
this.ctx.logger.warn('[order_express._writePackageMaterialActionLog] 写入 operation_log 失败,不影响主流程', {
error: e && e.message,
waveId,
});
}
}
}
module.exports = OrderExpressService;