2026-04-27 16:09:26 +08:00

1335 lines
49 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 OrderBaseService = require('./base');
const PENDING_OUTBOUND_STATUS = 'padding';
const PENDING_CANCEL_STATUS = 'cancel';
const PENDING_CANCEL_STEP = 9;
const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]);
const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]);
class PendingOrderService extends OrderBaseService {
/**
* 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。
*
* @param {Egg.Context} ctx 上下文对象。
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,importOrdersFromExcel';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 待处理订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
return await this.listByModule('pendingOrder', data);
}
/**
* 将待处理订单反审回待审核状态。
* @param {Object} data 请求体。
* @return {Promise<Object>} 更新后的订单信息。
*/
async reverseReviewOrder(data = {}) {
return await this.updateOrderInspectionState(data, 'none');
}
/**
* 将待处理订单批量分配储位。
*
* 该入口仅接受订单相关入参,不再接受 warehouse_id / warehouseId;
* 仓库上下文统一取当前登录用户的 store_id。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 统一 success 包装的储位分配结果。
*/
async allocateStorage(data = {}) {
console.log('[PendingOrderService.allocateStorage] 原始入参', data);
const requestData = this.isPlainObject(data) ? data : {};
const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ].filter(key => Object.prototype.hasOwnProperty.call(requestData, key));
if (forbiddenWarehouseKeys.length > 0) {
console.log('[PendingOrderService.allocateStorage] 检测到禁止传入的仓库字段', {
forbiddenWarehouseKeys,
requestData,
});
throw new Error('待处理订单储位分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文');
}
const normalizedData = {
allow_storage_location: requestData.allow_storage_location
?? requestData.allowStorageLocation
?? requestData.is_allow_storage
?? requestData.isAllowStorage,
order_ids: requestData.order_ids
?? requestData.orderIds
?? requestData.ids
?? requestData.order_id
?? requestData.orderId
?? requestData.id,
};
console.log('[PendingOrderService.allocateStorage] 归一化入参', normalizedData);
try {
console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 前', normalizedData);
const result = await this.service.systems.orderStorageAllocation.allocateStorage(normalizedData);
console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 成功', result);
return this.success('ok', result);
} catch (error) {
console.log('[PendingOrderService.allocateStorage] 调用 orderStorageAllocation.allocateStorage 异常', {
normalizedData,
error,
});
throw error;
}
}
/**
* 将待处理订单批量取消储位分配。
*
* 该入口仅接受订单 ID 相关入参,不再接受 allow_storage_location 相关字段或 warehouse_id / warehouseId;
* 仓库上下文统一取当前登录用户的 store_id。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 统一 success 包装的储位取消分配结果。
*/
async cancelAllocateStorage(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const forbiddenWarehouseKeys = [ 'warehouse_id', 'warehouseId' ].filter(key => Object.prototype.hasOwnProperty.call(requestData, key));
if (forbiddenWarehouseKeys.length > 0) {
console.log('[PendingOrderService.cancelAllocateStorage] 检测到禁止传入的仓库字段', {
forbiddenWarehouseKeys,
});
throw new Error('待处理订单储位取消分配接口不再接受 warehouse_id / warehouseId,请使用当前用户仓库上下文');
}
const normalizedData = {
order_ids: requestData.order_ids
?? requestData.orderIds
?? requestData.ids
?? requestData.order_id
?? requestData.orderId
?? requestData.id,
};
console.log('[PendingOrderService.cancelAllocateStorage] 归一化入参', normalizedData);
try {
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 前', normalizedData);
const result = await this.service.systems.orderStorageAllocation.cancelAllocateStorage(normalizedData);
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 成功', result);
return this.success('ok', result);
} catch (error) {
console.log('[PendingOrderService.cancelAllocateStorage] 调用 orderStorageAllocation.cancelAllocateStorage 异常', {
normalizedData,
error,
});
throw error;
}
}
/**
* 同步待处理订单。
*
* 当前仅接收 `order_ids` 并原样转发到服务层,暂不执行任何实际同步处理;
* 等后续同步逻辑明确后,再在对应 service 中补齐实现。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 统一 success 包装的同步结果。
*/
async syncOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const normalizedData = {
order_ids: requestData.order_ids
?? requestData.orderIds
?? requestData.ids
?? requestData.order_id
?? requestData.orderId
?? requestData.id,
};
console.log('[PendingOrderService.syncOrderIds] 归一化入参', normalizedData);
try {
console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 前', normalizedData);
const result = await this.service.systems.orderStorageAllocation.syncOrderIds(normalizedData);
console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 成功', result);
return this.success('ok', result);
} catch (error) {
console.log('[PendingOrderService.syncOrderIds] 调用 orderStorageAllocation.syncOrderIds 异常', {
normalizedData,
error,
});
throw error;
}
}
/**
* 批量分配待处理订单的快递号,并复用现有运单创建核心链路。
*
* 请求体必须直接传入订单对象数组,订单对象应为来自待处理订单列表或详情的原始订单对象。
* 每个订单对象必须包含 order_id 与 business_key;sys_platform_code 与 logistics_code 为订单对象自带字段,
* 前端无需额外拼装或单独构造,直接原样回传订单对象即可。business_key 可为单个序号,也可为序号数组。
* 其余字段会原样透传给运单创建链路。
*
* @param {Object} data 请求体。
* @param {Array<Object>} data.orders 订单对象数组。
* @return {Promise<Object>} 统一 success 包装的运单创建结果。
*/
async allocateExpressCode(data) {
const { orders } = data || {};
if (!Array.isArray(orders)) {
throw new Error('分配快递号接口仅支持订单对象数组入参');
}
const { service } = this;
const result = await service.systems.express.createWaybillCodePipeline(orders);
return this.success('ok', result);
}
/**
* 将待处理订单批量标记为待出库。
* @param {Object} data 请求体。
* @param {number[]} data.ids 订单ID 数组。
* @return {Promise<Object>} 更新后的订单信息。
*/
async markPendingOutboundOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizePendingOutboundOrderIds(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const existingOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
return this.success('取消成功', {
updated_count: 0,
ids: [],
});
}
if (existingOrders.length !== orderIds.length) {
throw new Error('订单不存在或不属于当前仓库');
}
const now = new Date();
const updateValues = {
outbound_status: PENDING_OUTBOUND_STATUS,
updated_at: now,
};
const updateResult = await model.update(updateValues, {
where,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
outbound_status: order.outbound_status,
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
outbound_status: firstOrder.outbound_status,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
}
/**
* 将待处理订单取消,并关闭到已取消状态。
* 仅允许取消当前仓库内处于待审核、待处理、待处理异常语义的订单。
* @param {Object} data 请求体。
* @param {number[]} data.ids 订单ID 数组。
* @return {Promise<Object>} 更新后的订单信息。
*/
async cancelOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizePendingCancelOrderIds(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const existingOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
return this.success('取消成功', {
updated_count: 0,
ids: [],
});
}
if (existingOrders.length !== orderIds.length) {
throw new Error('订单不存在或不属于当前仓库');
}
const nonCancelableOrder = existingOrders.find(order => !this.isCancelablePendingOrder(order));
if (nonCancelableOrder) {
throw new Error('订单当前状态不允许取消');
}
const now = new Date();
const updateValues = {
status: PENDING_CANCEL_STATUS,
step: PENDING_CANCEL_STEP,
outbound_status: PENDING_OUTBOUND_STATUS,
updated_at: now,
};
const updateResult = await model.update(updateValues, {
where,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const updatedOrders = await model.findAll({
where,
raw: true,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderMap = new Map(updatedOrders.map(order => [ Number(order.id), order ]));
const normalizedOrders = orderIds
.map(orderId => orderMap.get(orderId))
.filter(Boolean)
.map(order => ({
id: order.id,
status: order.status,
step: Number(order.step ?? PENDING_CANCEL_STEP),
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
status: firstOrder.status,
step: firstOrder.step,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
}
/**
* 规范待处理出库订单ID入参,仅接受 ids 数组且元素必须为正整数。
* @param {Object} data 请求体。
* @return {number[]} 订单ID 数组。
*/
normalizePendingOutboundOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids');
if (unexpectedKeys.length > 0) {
throw new Error('待处理出库接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段');
}
if (!Array.isArray(requestData.ids)) {
throw new Error('待处理出库接口仅支持 ids 数组入参');
}
const normalizedIds = requestData.ids.map(value => {
if (!Number.isInteger(value) || value <= 0) {
throw new Error('ids 仅支持正整数数组');
}
return value;
});
return Array.from(new Set(normalizedIds));
}
/**
* 规范待处理取消订单ID入参,仅接受 ids 数组且元素必须为正整数。
* @param {Object} data 请求体。
* @return {number[]} 订单ID 数组。
*/
normalizePendingCancelOrderIds(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const unexpectedKeys = Object.keys(requestData).filter(key => key !== 'ids');
if (unexpectedKeys.length > 0) {
throw new Error('待处理取消接口仅支持 ids 数组入参,不再支持 id、order_id、逗号字符串或其他兼容字段');
}
if (!Array.isArray(requestData.ids)) {
throw new Error('待处理取消接口仅支持 ids 数组入参');
}
const normalizedIds = requestData.ids.map(value => {
if (!Number.isInteger(value) || value <= 0) {
throw new Error('ids 仅支持正整数数组');
}
return value;
});
return Array.from(new Set(normalizedIds));
}
/**
* 判断订单是否允许从待处理模块取消。
* 仅允许处于待审核、待处理、待处理异常语义的订单取消。
* @param {Object} order 订单记录。
* @return {boolean} 是否允许取消。
*/
isCancelablePendingOrder(order = {}) {
const step = Number(order.step);
const status = String(order.status || '').trim().toLowerCase();
const outboundStatus = String(order.outbound_status || '').trim();
if (status === PENDING_CANCEL_STATUS) {
return false;
}
if (!PENDING_CANCEL_ALLOWED_STEPS.has(step)) {
return false;
}
if (PENDING_CANCEL_PENDING_STEPS.has(step) && outboundStatus === PENDING_OUTBOUND_STATUS) {
return false;
}
return true;
}
/**
* 批量修改待处理订单的平台信息。
*
* 用 code 查找 wms_platform 表中对应的平台记录,若存在则将订单的
* sys_platform_code 和 sys_platform_name 更新为该平台的 code 和 name;
* 若不存在则返回错误。只操作当前仓库的当前订单表,不处理其他订单表。
*
* @param {Object} data 请求体。
* @param {number[]} data.order_ids 订单ID 数组。
* @param {string} data.code 平台编码。
* @return {Promise<Object>} 统一 success 包装的更新结果。
*/
async updateOrderPlatform(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const rawOrderIds = requestData.order_ids;
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
throw new Error('order_ids 不能为空');
}
const orderIds = Array.from(new Set(rawOrderIds.map(v => {
const n = Number(v);
if (!Number.isInteger(n) || n <= 0) {
throw new Error('order_ids 仅支持正整数数组');
}
return n;
})));
const code = String(requestData.code || '').trim();
if (!code) {
throw new Error('code 不能为空');
}
const platformList = await this.service.systems.platform.getPlatformList(true, true);
const platform = Array.isArray(platformList)
? platformList.find(item => String(item.code || item.platform_code || '').trim() === code)
: null;
if (!platform) {
throw new Error(`平台编码 ${code} 不存在`);
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const [ affectedRows ] = await model.update({
sys_platform_code: platform.code,
sys_platform_name: String(platform.name || '').trim(),
updated_at: new Date(),
}, { where });
const count = Number(affectedRows || 0);
// 记录操作日志
try {
await this.ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: warehouseId,
operationCode: 'ORDER_UPDATE_PLATFORM',
operator: {
id: this.ctx.user?.employees_id || this.ctx.user?.id,
name: this.ctx.user?.employees_name || '',
},
extras: {
warehouseId,
orderIds,
sys_platform_code: platform.code,
sys_platform_name: String(platform.name || '').trim(),
updated_count: count,
message: `批量修改订单平台:订单ID [${orderIds.join(', ')}],平台 ${platform.code}(${String(platform.name || '').trim()}),共更新 ${count} 条`,
},
beforeChanges: null,
});
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.updateOrderPlatform] 写入操作日志失败,不影响业务', logErr);
}
return this.success('ok', {
updated_count: count,
sys_platform_code: platform.code,
sys_platform_name: String(platform.name || '').trim(),
});
}
/**
* 批量修改待处理订单的快递信息。
*
* 用 express_code 从当前仓库快递列表(带缓存)中查找对应项:
* - 若为自定义映射(is_system_setting=true),则 sys_logistics_code/sys_logistics_name 写系统快递
* 的 express_code/name,logistics_code/logistics_name 写自定义编码和名称;
* - 若为系统快递(is_system_setting=false),则 sys_logistics_code/sys_logistics_name 和
* logistics_code/logistics_name 均写系统快递的 code/name;
* - 未找到则报错。
* 只操作当前仓库的当前订单表,不处理其他订单表。
*
* @param {Object} data 请求体。
* @param {number[]} data.order_ids 订单ID 数组。
* @param {string} data.express_code 快递编码(系统编码或自定义编码)。
* @return {Promise<Object>} 统一 success 包装的更新结果。
*/
async updateOrderExpress(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const rawOrderIds = requestData.order_ids;
if (!Array.isArray(rawOrderIds) || rawOrderIds.length === 0) {
throw new Error('order_ids 不能为空');
}
const orderIds = Array.from(new Set(rawOrderIds.map(v => {
const n = Number(v);
if (!Number.isInteger(n) || n <= 0) {
throw new Error('order_ids 仅支持正整数数组');
}
return n;
})));
const expressCode = String(requestData.express_code || '').trim();
if (!expressCode) {
throw new Error('express_code 不能为空');
}
// 使用带缓存的仓库快递列表
const expressList = await this.service.systems.express.getExpressList();
const expressItem = Array.isArray(expressList)
? expressList.find(item => String(item.code || item.value || '').trim() === expressCode)
: null;
if (!expressItem) {
throw new Error(`快递编码 ${expressCode} 不存在`);
}
let sysLogisticsCode;
let sysLogisticsName;
let logisticsCode;
let logisticsName;
if (expressItem.is_system_setting) {
// 自定义映射:express_code 字段存储对应的系统快递编码
sysLogisticsCode = String(expressItem.express_code || '').trim();
// 系统快递名称从列表中查找
const sysItem = expressList.find(item => !item.is_system_setting && String(item.code || '').trim() === sysLogisticsCode);
sysLogisticsName = sysItem ? String(sysItem.name || '').trim() : sysLogisticsCode;
logisticsCode = expressItem.code;
logisticsName = String(expressItem.alias || expressItem.name || '').trim();
} else {
// 系统快递:logistics_code/name 与 sys 一致
sysLogisticsCode = expressItem.code;
sysLogisticsName = String(expressItem.name || '').trim();
logisticsCode = expressItem.code;
logisticsName = sysLogisticsName;
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const [ affectedRows ] = await model.update({
sys_logistics_code: sysLogisticsCode,
sys_logistics_name: sysLogisticsName,
logistics_code: logisticsCode,
logistics_name: logisticsName,
updated_at: new Date(),
}, { where });
const count = Number(affectedRows || 0);
// 记录操作日志
try {
await this.ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: warehouseId,
operationCode: 'ORDER_UPDATE_EXPRESS',
operator: {
id: this.ctx.user?.employees_id || this.ctx.user?.id,
name: this.ctx.user?.employees_name || '',
},
extras: {
warehouseId,
orderIds,
express_code: expressCode,
sys_logistics_code: sysLogisticsCode,
sys_logistics_name: sysLogisticsName,
logistics_code: logisticsCode,
logistics_name: logisticsName,
updated_count: count,
message: `批量修改订单快递:订单ID [${orderIds.join(', ')}],快递 ${logisticsCode}(${logisticsName}),系统快递 ${sysLogisticsCode}(${sysLogisticsName}),共更新 ${count} 条`,
},
beforeChanges: null,
});
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.updateOrderExpress] 写入操作日志失败,不影响业务', logErr);
}
return this.success('ok', {
updated_count: count,
sys_logistics_code: sysLogisticsCode,
sys_logistics_name: sysLogisticsName,
logistics_code: logisticsCode,
logistics_name: logisticsName,
});
}
/**
* 克隆待处理订单。
*
* 流程:
* 1. 查找原订单,校验可取消状态(step 0/1/2/3);
* 2. 若原订单已分配储位(storage_status='fin'),先清除已分配库存;
* 3. 取消原订单(step->9, status->'cancel')并记录"克隆"日志;
* 4. 以原订单业务数据创建新订单,所有流程状态字段重置为初始落库状态;
* 5. 对新订单记录"克隆创建"日志。
*
* @param {Object} data 请求体。
* @param {number} data.order_id 原订单ID。
* @return {Promise<Object>} 统一 success 包装,含新订单 id。
*/
async cloneOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderId = Number(requestData.order_id || requestData.id);
if (!Number.isInteger(orderId) || orderId <= 0) {
throw new Error('order_id 不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere([ orderId ], warehouseId);
// 1. 查原订单
const existingOrders = await model.findAll({ where, raw: true });
if (!Array.isArray(existingOrders) || existingOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const original = existingOrders[0];
if (!this.isCancelablePendingOrder(original)) {
throw new Error('订单当前状态不允许克隆');
}
// 2. 若已分配储位,先清除库存
if (String(original.storage_status || '').trim() === 'fin') {
try {
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: [ orderId ],
});
} catch (storageErr) {
throw new Error(`清除已分配库存失败:${storageErr.message}`);
}
}
const now = new Date();
// 3. 取消原订单
await model.update({
status: 'cancel',
step: 9,
outbound_status: 'padding',
updated_at: now,
}, { where });
// 记录原订单"克隆"日志
try {
await this.ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: orderId,
operationCode: 'ORDER_CLONE_SOURCE',
operator: {
id: this.ctx.user?.employees_id || this.ctx.user?.id,
name: this.ctx.user?.employees_name || '',
},
extras: {
warehouseId,
message: `订单克隆:原订单 ${orderId} 已取消,将创建新订单`,
},
beforeChanges: null,
});
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 写入原订单克隆日志失败', logErr);
}
// 4. 构造新订单数据 — 保留业务字段,重置所有流程状态
const RESET_FIELDS = {
step: 0,
status: 'created',
inspection_status: 'none',
storage_status: 'none',
post_status: 'none',
pick_status: 'none',
pack_status: 'none',
print_status: 'none',
claim_status: 'none',
outbound_status: 'none',
lock_status: 'none',
intercept_status: 'none',
sync_status: 'padding',
order_flag: '',
wave_id: 0,
delivery_time: null,
operate_time: null,
operator_name: null,
express_code: null,
logistics_area_code: null,
delete_at: null,
create_at: now,
updated_at: now,
};
// 业务字段白名单(从原订单复制)
const COPY_FIELDS = [
'delivery_order_code', 'pre_delivery_order_code', 'pre_delivery_order_id',
'order_type', 'warehouse_code', 'warehouse_id', 'store_id', 'from_key',
'source_platform_code', 'source_platform_name', 'source_order_codes',
'sys_platform_code', 'sys_platform_name',
'place_order_time', 'pay_time', 'pay_no',
'service_code', 'shop_nick', 'seller_nick', 'buyer_nick',
'total_amount', 'item_amount', 'discount_amount', 'freight',
'ar_amount', 'got_amount', 'service_fee',
'logistics_code', 'logistics_name', 'sys_logistics_code', 'sys_logistics_name',
'delivery_type', 'weight_type', 'is_urgency', 'invoice_flag',
'name', 'zip_code', 'tel', 'mobile', 'email',
'country_code', 'province', 'city', 'area', 'town', 'detail_address',
'id_type', 'id_number', 'oaid',
'items', 'items_count', 'items_total', 'items_weight', 'items_hash', 'items_crc',
];
const newOrderData = { ...RESET_FIELDS };
for (const field of COPY_FIELDS) {
if (original[field] !== undefined) {
newOrderData[field] = original[field];
}
}
const newOrder = await model.create(newOrderData);
const newOrderId = Number(newOrder.id || newOrder.dataValues && newOrder.dataValues.id);
// 5. 克隆订单明细
try {
const orderItemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory;
if (orderItemsFactory && typeof orderItemsFactory.getCurrentModel === 'function') {
const itemsModel = await orderItemsFactory.getCurrentModel(warehouseId);
if (itemsModel && typeof itemsModel.findAll === 'function') {
const originalItems = await itemsModel.findAll({
where: { order_id: orderId },
raw: true,
});
if (Array.isArray(originalItems) && originalItems.length > 0) {
const ITEM_COPY_FIELDS = [
'actual_price', 'retail_price', 'ext_code', 'inventory_type',
'item_code', 'item_id', 'item_name', 'order_line_no', 'owner_code',
'plan_qty', 'source_order_code', 'sub_source_order_code',
'extend_props', 'stock_id', 'item_snapshot',
];
const newItems = originalItems.map(item => {
const newItem = { order_id: newOrderId, created_at: now, updated_at: now };
for (const field of ITEM_COPY_FIELDS) {
if (item[field] !== undefined) {
newItem[field] = item[field];
}
}
return newItem;
});
await itemsModel.bulkCreate(newItems);
}
}
}
} catch (itemsErr) {
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 克隆订单明细失败', itemsErr);
throw new Error(`克隆订单明细失败:${itemsErr.message}`);
}
// 6. 记录新订单"克隆创建"日志
try {
await this.ctx.service.systems.operationLog.createOperationLog({
businessType: 'order',
businessId: newOrderId,
operationCode: 'ORDER_CLONE_TARGET',
operator: {
id: this.ctx.user?.employees_id || this.ctx.user?.id,
name: this.ctx.user?.employees_name || '',
},
extras: {
warehouseId,
message: `克隆创建:由原订单 ${orderId} 克隆生成,新订单 ID ${newOrderId}`,
},
beforeChanges: null,
});
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 写入新订单克隆创建日志失败', logErr);
}
return this.success('ok', {
source_order_id: orderId,
new_order_id: newOrderId,
});
}
/**
* 手动创建待处理订单。
*
* 根据货主策略(need_order_approval)自动决定订单初始步骤:
* - need_order_approval=1(默认)→ step=0 待审核
* - need_order_approval=0 → step=1 直接进待处理
*
* @param {Object} data 请求体。
* @param {number} data.store_id 货主ID(必填)。
* @param {string} data.name 收件人姓名(必填)。
* @param {string} [data.mobile] 收件人手机号(mobile/tel 至少一项必填)。
* @param {string} [data.tel] 收件人电话。
* @param {string} data.detail_address 详细地址(必填)。
* @param {string} [data.province] 省份。
* @param {string} [data.city] 城市。
* @param {string} [data.area] 区/县。
* @param {string} [data.town] 镇/街道。
* @param {string} [data.zip_code] 邮编。
* @param {Array<Object>} data.items 订单明细(必填,每项含 item_code 与 plan_qty)。
* @param {string} [data.delivery_order_code] 订单号,不传则自动生成。
* @param {string} [data.logistics_code] 快递编码,不传则读货主默认快递策略。
* @param {string} [data.logistics_name] 快递名称。
* @param {string} [data.sys_platform_code] 系统平台编码,不传则读货主默认平台策略。
* @param {string} [data.source_platform_code] 来源平台编码。
* @param {string} [data.source_order_codes] 来源订单号。
* @param {string} [data.order_type] 订单类型。
* @param {string} [data.is_urgency] 是否紧急(Y/N),默认 N。
* @param {string} [data.invoice_flag] 是否需要发票(Y/N),默认 N。
* @return {Promise<Object>} 统一 success 包装,含新订单 id 与 step 信息。
*/
async createOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
// 1. 参数校验
const storeId = Number(requestData.store_id);
if (!Number.isInteger(storeId) || storeId <= 0) {
throw new Error('store_id(货主ID)不能为空');
}
const name = String(requestData.name || '').trim();
if (!name) {
throw new Error('收件人姓名不能为空');
}
const mobile = String(requestData.mobile || '').trim();
const tel = String(requestData.tel || '').trim();
if (!mobile && !tel) {
throw new Error('收件人手机号或电话至少填写一项');
}
const detailAddress = String(requestData.detail_address || '').trim();
if (!detailAddress) {
throw new Error('详细地址不能为空');
}
const rawItems = requestData.items;
if (!Array.isArray(rawItems) || rawItems.length === 0) {
throw new Error('订单明细 items 不能为空');
}
// 2. 适配明细格式并校验(转为 addOrder 所需的驼峰格式)
const orderLineItems = rawItems.map((item, idx) => {
if (!item || typeof item !== 'object') {
throw new Error(`第${idx + 1}行明细格式无效`);
}
const itemCode = String(item.item_code || '').trim();
if (!itemCode) {
throw new Error(`第${idx + 1}行商品编码 item_code 不能为空`);
}
const planQty = Number(item.plan_qty);
if (!Number.isInteger(planQty) || planQty <= 0) {
throw new Error(`第${idx + 1}行计划数量 plan_qty 必须为正整数`);
}
return {
itemCode,
itemName: String(item.item_name || '').trim(),
planQty,
orderLineNo: String(item.order_line_no || String(idx + 1)).trim(),
actualPrice: Number(item.actual_price) || 0,
};
});
// 3. 自动生成订单号(如未传)
const deliveryOrderCode = String(requestData.delivery_order_code || '').trim()
|| `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`;
// 4. 适配为 addOrder 所需的奇门嵌套格式
const adaptedData = {
request: {
deliveryOrder: {
deliveryOrderCode,
orderType: String(requestData.order_type || '').trim(),
sourcePlatformCode: String(requestData.source_platform_code || requestData.sys_platform_code || '').trim(),
sourcePlatformName: String(requestData.source_platform_name || '').trim(),
createChannel: String(requestData.create_channel || requestData.createChannel || 'MANUAL').trim().toUpperCase() || 'MANUAL',
logisticsCode: String(requestData.logistics_code || '').trim(),
logisticsName: String(requestData.logistics_name || '').trim(),
isUrgency: [ 'Y', 'N' ].includes(requestData.is_urgency) ? requestData.is_urgency : 'N',
invoiceFlag: [ 'Y', 'N' ].includes(requestData.invoice_flag) ? requestData.invoice_flag : 'N',
receiverInfo: {
name,
mobile,
tel,
province: String(requestData.province || '').trim(),
city: String(requestData.city || '').trim(),
area: String(requestData.area || '').trim(),
town: String(requestData.town || '').trim(),
detailAddress,
zipCode: String(requestData.zip_code || '').trim(),
},
},
orderLines: {
orderLine: orderLineItems,
},
},
};
const info = {
storeId,
warehouseId,
appKey: (this.ctx.user && this.ctx.user.app_key) || '',
};
// 5. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志)
const result = await this.service.systems.deliveryOrder.addOrder(adaptedData, info);
if (!result.success) {
throw new Error(result.message || '订单创建失败');
}
// 重复订单视为错误(与原逻辑保持一致)
if (result.message === '订单已存在') {
throw new Error(`订单号 ${deliveryOrderCode} 已存在`);
}
const orderId = result.data && result.data.orderId;
const step = result.data && result.data.step;
const itemsTotal = orderLineItems.reduce((sum, item) => sum + item.planQty, 0);
return this.success('ok', {
order_id: orderId,
delivery_order_code: deliveryOrderCode,
step,
step_label: step === 0 ? '待审核' : (step === 1 ? '待处理' : ''),
items_count: orderLineItems.length,
items_total: itemsTotal,
});
}
/**
* 下载创建订单的 Excel 导入模板。
*
* 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。
* 表头中标注 * 的列为必填项。
* 多行相同订单号的行组成一个完整订单,每行代表一个商品明细。
*
* @return {Promise<Object>} 统一 success 包装,含 base64 字符串与文件名。
*/
async downloadCreateTemplate() {
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('创建订单导入模板');
// 列定义:header 中带 * 表示必填
const columns = [
{ header: '*订单号', key: 'delivery_order_code', width: 24 },
{ header: '*货主ID', key: 'store_id', width: 12 },
{ header: '*收件人姓名', key: 'name', width: 16 },
{ header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 },
{ header: '电话', key: 'tel', width: 16 },
{ header: '*详细地址', key: 'detail_address', width: 36 },
{ header: '省份', key: 'province', width: 12 },
{ header: '城市', key: 'city', width: 12 },
{ header: '区/县', key: 'area', width: 12 },
{ header: '镇/街道', key: 'town', width: 12 },
{ header: '邮编', key: 'zip_code', width: 12 },
{ header: '快递编码', key: 'logistics_code', width: 16 },
{ header: '快递名称', key: 'logistics_name', width: 16 },
{ header: '系统平台编码', key: 'sys_platform_code', width: 16 },
{ header: '来源平台编码', key: 'source_platform_code', width: 16 },
{ header: '来源订单号', key: 'source_order_codes', width: 20 },
{ header: '订单类型', key: 'order_type', width: 14 },
{ header: '是否紧急(Y/N)', key: 'is_urgency', width: 16 },
{ header: '是否需要发票(Y/N)', key: 'invoice_flag', width: 18 },
{ header: '*商品编码', key: 'item_code', width: 20 },
{ header: '商品名称', key: 'item_name', width: 24 },
{ header: '*计划数量', key: 'plan_qty', width: 12 },
{ header: '行号', key: 'order_line_no', width: 10 },
{ header: '实际价格', key: 'actual_price', width: 12 },
];
sheet.columns = columns;
// 表头样式:必填列(含*)背景橙色加粗,可选列灰色加粗
const headerRow = sheet.getRow(1);
headerRow.eachCell((cell, colNumber) => {
const col = columns[colNumber - 1];
const isRequired = col && col.header.startsWith('*');
cell.font = { bold: true, color: { argb: 'FF000000' } };
cell.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: isRequired ? 'FFFFC000' : 'FFD9D9D9' },
};
cell.alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
cell.border = {
top: { style: 'thin' },
left: { style: 'thin' },
bottom: { style: 'thin' },
right: { style: 'thin' },
};
});
headerRow.height = 36;
// 插入一行示例数据
sheet.addRow({
delivery_order_code: 'ORD20260421001',
store_id: 1,
name: '张三',
mobile: '13800138000',
tel: '',
detail_address: 'XX路XX号',
province: '广东省',
city: '深圳市',
area: '南山区',
town: '',
zip_code: '518000',
logistics_code: 'STO',
logistics_name: '申通快递',
sys_platform_code: 'TB',
source_platform_code: '',
source_order_codes: '',
order_type: '',
is_urgency: 'N',
invoice_flag: 'N',
item_code: 'SKU001',
item_name: '商品A',
plan_qty: 2,
order_line_no: '1',
actual_price: 9.90,
});
// 同订单第二个商品(示例)
sheet.addRow({
delivery_order_code: 'ORD20260421001',
store_id: 1,
name: '张三',
mobile: '13800138000',
tel: '',
detail_address: 'XX路XX号',
province: '广东省',
city: '深圳市',
area: '南山区',
town: '',
zip_code: '518000',
logistics_code: 'STO',
logistics_name: '申通快递',
sys_platform_code: 'TB',
source_platform_code: '',
source_order_codes: '',
order_type: '',
is_urgency: 'N',
invoice_flag: 'N',
item_code: 'SKU002',
item_name: '商品B',
plan_qty: 1,
order_line_no: '2',
actual_price: 19.90,
});
// 添加说明工作表
const noteSheet = workbook.addWorksheet('填写说明');
noteSheet.getColumn(1).width = 80;
const notes = [
'【填写说明】',
'1. 带 * 的列为必填项,表头背景为橙色。',
'2. 每一行代表一条商品明细;同一订单的多个商品,订单号(delivery_order_code)必须相同。',
'3. 同一订单的所有行中,订单头信息(收件人、地址等)取第一行的值,后续行可省略但不影响解析。',
'4. mobile 和 tel 至少填写一项。',
'5. 计划数量(plan_qty)必须为正整数。',
'6. 是否紧急、是否需要发票只接受 Y 或 N(大写),不填默认 N。',
'7. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动填充。',
'8. 同一文件内,相同订单号只会创建一次订单,不会重复创建。',
];
notes.forEach((note, i) => {
const row = noteSheet.getRow(i + 1);
row.getCell(1).value = note;
if (i === 0) {
row.getCell(1).font = { bold: true, size: 13 };
}
});
const buffer = await workbook.xlsx.writeBuffer();
const base64 = Buffer.from(buffer).toString('base64');
return this.success('ok', {
base64,
filename: '创建订单导入模板.xlsx',
mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
}
/**
* 通过 Excel 文件批量创建订单。
*
* 接受 base64 编码的 Excel 文件,按订单号分组,每组调用 createOrder 逻辑创建一个订单。
* 每行代表一条商品明细;同一订单号的行组成一个完整订单,订单头信息取每组第一行。
*
* @param {Object} data 请求体。
* @param {string} data.file_base64 base64 编码的 .xlsx 文件内容(必填)。
* @return {Promise<Object>} 统一 success 包装,含成功/失败明细。
*/
async importOrdersFromExcel(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const fileBase64 = String(requestData.file_base64 || '').trim();
if (!fileBase64) {
throw new Error('file_base64 不能为空');
}
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const buffer = Buffer.from(fileBase64, 'base64');
await workbook.xlsx.load(buffer);
const sheet = workbook.getWorksheet(1);
if (!sheet) {
throw new Error('Excel 文件中未找到工作表');
}
// 读取表头(第1行),建立列名->列序号映射
const headerMap = {};
const headerRow = sheet.getRow(1);
headerRow.eachCell((cell, colNumber) => {
const rawHeader = String(cell.value || '').trim().replace(/^\*/, '');
// 归一化 key
const keyMap = {
订单号: 'delivery_order_code',
货主ID: 'store_id',
收件人姓名: 'name',
'手机号(mobile/tel至少填一项)': 'mobile',
手机号: 'mobile',
电话: 'tel',
详细地址: 'detail_address',
省份: 'province',
城市: 'city',
'区/县': 'area',
'镇/街道': 'town',
邮编: 'zip_code',
快递编码: 'logistics_code',
快递名称: 'logistics_name',
系统平台编码: 'sys_platform_code',
来源平台编码: 'source_platform_code',
来源订单号: 'source_order_codes',
订单类型: 'order_type',
'是否紧急(Y/N)': 'is_urgency',
'是否需要发票(Y/N)': 'invoice_flag',
商品编码: 'item_code',
商品名称: 'item_name',
计划数量: 'plan_qty',
行号: 'order_line_no',
实际价格: 'actual_price',
};
const key = keyMap[rawHeader];
if (key) {
headerMap[key] = colNumber;
}
});
// 辅助:从行中取值
const getCellValue = (row, key) => {
const colNum = headerMap[key];
if (!colNum) return undefined;
const cell = row.getCell(colNum);
const val = cell && cell.value;
if (val === null || val === undefined) return '';
return String(val).trim();
};
// 读取所有数据行(从第2行开始),跳过空行
const orderMap = new Map(); // delivery_order_code -> { headerData, items[] }
const orderSequence = []; // 保持顺序
sheet.eachRow((row, rowNumber) => {
if (rowNumber === 1) return; // 跳过表头
const deliveryOrderCode = getCellValue(row, 'delivery_order_code');
if (!deliveryOrderCode) return; // 跳过空行
if (!orderMap.has(deliveryOrderCode)) {
// 首次出现,记录订单头信息
orderMap.set(deliveryOrderCode, {
headerData: {
delivery_order_code: deliveryOrderCode,
store_id: getCellValue(row, 'store_id'),
name: getCellValue(row, 'name'),
mobile: getCellValue(row, 'mobile'),
tel: getCellValue(row, 'tel'),
detail_address: getCellValue(row, 'detail_address'),
province: getCellValue(row, 'province'),
city: getCellValue(row, 'city'),
area: getCellValue(row, 'area'),
town: getCellValue(row, 'town'),
zip_code: getCellValue(row, 'zip_code'),
logistics_code: getCellValue(row, 'logistics_code'),
logistics_name: getCellValue(row, 'logistics_name'),
sys_platform_code: getCellValue(row, 'sys_platform_code'),
source_platform_code: getCellValue(row, 'source_platform_code'),
source_order_codes: getCellValue(row, 'source_order_codes'),
order_type: getCellValue(row, 'order_type'),
is_urgency: getCellValue(row, 'is_urgency'),
invoice_flag: getCellValue(row, 'invoice_flag'),
},
items: [],
});
orderSequence.push(deliveryOrderCode);
}
const itemCode = getCellValue(row, 'item_code');
if (itemCode) {
orderMap.get(deliveryOrderCode).items.push({
item_code: itemCode,
item_name: getCellValue(row, 'item_name'),
plan_qty: getCellValue(row, 'plan_qty'),
order_line_no: getCellValue(row, 'order_line_no'),
actual_price: getCellValue(row, 'actual_price'),
});
}
});
if (orderSequence.length === 0) {
throw new Error('Excel 中未找到有效数据行');
}
// 逐个创建订单
const results = {
total: orderSequence.length,
success_count: 0,
fail_count: 0,
success_orders: [],
fail_orders: [],
};
for (const deliveryOrderCode of orderSequence) {
const { headerData, items } = orderMap.get(deliveryOrderCode);
try {
const createData = {
...headerData,
store_id: Number(headerData.store_id) || 0,
items: items.map((item, idx) => ({
item_code: item.item_code,
item_name: item.item_name || '',
plan_qty: Number(item.plan_qty) || 0,
order_line_no: item.order_line_no || String(idx + 1),
actual_price: Number(item.actual_price) || 0,
})),
};
const result = await this.createOrder(createData);
results.success_count++;
results.success_orders.push({
delivery_order_code: deliveryOrderCode,
order_id: result && result.data && result.data.order_id,
step: result && result.data && result.data.step,
step_label: result && result.data && result.data.step_label,
});
} catch (err) {
results.fail_count++;
results.fail_orders.push({
delivery_order_code: deliveryOrderCode,
error: err.message,
});
}
}
return this.success('ok', results);
}
}
module.exports = PendingOrderService;