'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} 包材记录。 */ 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} 订单快递记录。 */ 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>} 快递记录列表。 */ 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 : []; } /** * 更新订单运单称重重量。 * * @param {Object} payload 入参对象。 * @param {number|string} payload.orderId 订单ID。 * @param {string} [payload.waybillCode] 运单号。 * @param {number|string} payload.weighingWeight 称重重量。 * @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number}>} 更新结果。 */ 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; const rows = await this.findValidOrderExpressRows(normalizedOrderId, warehouseId); if (rows.length === 0) { throw this.createBusinessError('未找到有效的订单运单记录', 404); } let targetRow = null; if (rows.length === 1) { targetRow = rows[0]; } else { if (!normalizedWaybillCode) { throw this.createBusinessError('多运单订单必须传入 waybill_code', 400); } targetRow = rows.find(row => String(row && row.waybill_code || '').trim() === normalizedWaybillCode) || 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: normalizedWeight, }, { 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); } return { order_id: Number(targetRow.order_id), waybill_code: String(targetRow.waybill_code || '').trim(), weighing_weight: normalizedWeight, }; } /** * 绑定订单快递记录的包材信息。 * @param {Object} payload 入参对象。 * @param {number|string} payload.orderId 订单ID。 * @param {string} payload.waybillCode 运单号。 * @param {string} payload.packageMaterialCode 包材编码。 * @return {Promise} 绑定后的结果快照。 */ 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;