WMS_MAIN/app/service/systems/order_express.js
liufumingren 43c60dd934 1
2026-06-09 14:12:02 +08:00

639 lines
21 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;
/**
* 订单快递业务服务。
*
* 负责订单快递记录的读取与称重重量更新。
*/
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} 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;
}
/**
* 根据包材编码查询当前仓库启用中的包材。
* @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' ],
raw: true,
});
if (!orderExpressRow) {
throw this.createBusinessError('订单运单记录不存在', 404);
}
return orderExpressRow;
}
/**
* 规范化并校验称重重量。
*
* 允许最多 3 位小数,且必须大于 0。
*
* @param {number|string} weighingWeight 称重重量。
* @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+(?:\.\d{1,3})?$/.test(normalizedWeightText)) {
throw this.createBusinessError('weighing_weight 格式非法,最多支持 3 位小数', 400);
}
const normalizedWeight = Number(normalizedWeightText);
if (!Number.isFinite(normalizedWeight) || normalizedWeight <= 0) {
throw this.createBusinessError('weighing_weight 必须大于 0', 400);
}
return normalizedWeight;
}
/**
* 读取订单下有效快递记录。
* @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);
}
const where = {
order_id: orderId,
delete_at: null,
};
if (warehouseId !== null && warehouseId !== undefined && warehouseId !== '') {
where.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 : [];
}
/**
* 更新订单运单称重重量。
*
* 支持团购波次批量设置:
* - 散单(wave_id = 0)或非团购波次:仅更新单个订单的运单重量。
* - 团购波次(wave_type = 1):将同一重量批量设置到该波次下所有订单的运单上。
*
* @param {Object} payload 入参对象。
* @param {number|string} payload.orderId 订单ID。
* @param {string} [payload.waybillCode] 运单号,多运单场景必填。
* @param {number|string} payload.weighingWeight 称重重量(kg)。
* @return {Promise<Object>} 单订单返回 {order_id, waybill_code, weighing_weight};
* 团购批量返回 {wave_id, wave_no, weighing_weight, success_count, total_count}。
*/
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
);
}
// 查询订单所属波次
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
throw this.createBusinessError('订单模型未初始化', 500);
}
const orderDeliveryModel = await orderDeliveryFactory.getCurrentModel(warehouseId);
const orderRow = await orderDeliveryModel.findOne({
where: { id: normalizedOrderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id', 'wave_no' ],
raw: true,
});
// 订单不存在 → 兼容前端传入 wave_id 的场景,尝试按波次查询
if (!orderRow) {
return await this._tryWaveCompatibility(
normalizedOrderId, normalizedWaybillCode, normalizedWeight, warehouseId, orderDeliveryModel
);
}
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
);
}
/**
* 更新单个订单运单的称重重量(内部方法)。
*
* @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}>} 更新结果。
*/
async _updateSingleOrderWeight(orderId, waybillCode, weight, 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,
});
return {
order_id: Number(targetRow.order_id),
waybill_code: String(targetRow.waybill_code || '').trim(),
weighing_weight: weight,
};
}
/**
* 批量更新团购波次下所有订单运单的称重重量(内部方法)。
*
* @param {number} waveId 波次ID。
* @param {string} waveNo 波次号。
* @param {number} weight 称重重量。
* @param {number|null} warehouseId 仓库ID。
* @param {Object} orderDeliveryModel 订单 Sequelize 模型实例。
* @return {Promise<{wave_id:number, wave_no:string, weighing_weight:number, success_count:number, total_count:number}>}
* 批量更新结果。
*/
async _updateWaveOrderWeight(waveId, waveNo, weight, warehouseId, orderDeliveryModel) {
// 查询波次下所有订单
const waveOrders = await orderDeliveryModel.findAll({
where: { wave_id: waveId, warehouse_id: warehouseId },
attributes: [ 'id' ],
raw: true,
});
if (!waveOrders || waveOrders.length === 0) {
throw this.createBusinessError('波次下未找到订单', 404);
}
const orderIds = waveOrders.map(o => Number(o.id));
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;
const updateResult = await orderExpressModel.update(
{ weighing_weight: weight },
{
where: {
order_id: { [Op.in]: orderIds },
delete_at: null,
},
}
);
const successCount = Array.isArray(updateResult)
? Number(updateResult[0] || 0)
: Number(updateResult || 0);
if (!Number.isFinite(successCount) || successCount <= 0) {
throw this.createBusinessError('批量更新称重重量失败,波次下无有效运单记录', 500);
}
// 写入操作日志
await this._writeWeighActionLog({
waveId,
waveNo,
weight,
warehouseId,
successCount,
totalCount,
});
return {
wave_id: waveId,
wave_no: waveNo,
weighing_weight: weight,
success_count: successCount,
total_count: totalCount,
};
}
/**
* 写入称重操作日志到 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,
}
);
}
/**
* 兼容处理:当前端将 wave_id 当作 order_id 传入时,尝试按波次 ID 处理。
*
* 先用传入的 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
);
}
/**
* 绑定订单快递记录的包材信息。
* @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);
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);
if (!Number.isFinite(affectedRows) || affectedRows <= 0) {
throw this.createBusinessError('绑定包材失败', 500);
}
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(),
};
}
}
module.exports = OrderExpressService;