liufumingren eb100b056d 1
2026-06-07 01:52:06 +08:00

2247 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 OrderBaseService = require('./base');
const PENDING_OUTBOUND_STATUS = 'padding';
const PENDING_CANCEL_STATUS = 'cancel';
const PENDING_CANCEL_STEP = 9;
const PENDING_OUTBOUND_STEP = 4;
const PENDING_CANCEL_ALLOWED_STEPS = new Set([ 0, 1, 2, 3 ]);
const PENDING_CANCEL_PENDING_STEPS = new Set([ 1, 2 ]);
const ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX = 'order:pending:allocate_storage:request:';
const ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS = 60 * 60 * 2;
const ALLOCATE_STORAGE_PROGRESS_MAP = Object.freeze({
submitted: 5,
running: 50,
success: 100,
failed: 100,
not_found: 0,
unknown: 0,
});
class PendingOrderService extends OrderBaseService {
/**
* 初始化待处理订单系统方法的免登录、免权限、免日志和免鉴权配置。
*
* @param {Egg.Context} ctx 上下文对象。
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress';
const _noNeedLog = 'list,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,parseAddress';
const _noNeedAuth = 'list,pendingOrder,reverseReviewOrder,markPendingOutboundOrder,cancelOrder,allocateExpressCode,allocateStorage,allocateStorageProgress,cancelAllocateStorage,syncOrderIds,updateOrderPlatform,updateOrderExpress,cloneOrder,createOrder,downloadCreateTemplate,parseAddress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 待处理订单列表。
* @param {Object} data 请求体。
* @return {Promise<Object>} 列表与分页信息。
*/
async list(data = {}) {
return await this.listByModule('pendingOrder', data);
}
/**
* 查询待处理订单详情。
*
* 仅返回订单头、商品明细与运单信息;
* 待处理详情不再返回 logs 字段,也不触发操作日志查询。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 订单头、商品明细和运单信息。
*/
async detail(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizeOrderIds(requestData);
const tableType = this.resolveOrderTableType(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
if (orderIds.length !== 1) {
throw new Error('订单详情仅支持查询单个订单');
}
const orderId = orderIds[0];
const orderModel = await this.getOrderModelByTableType(tableType, warehouseId);
const orderWhere = this.buildOrderWhere([ orderId ], warehouseId);
const order = await orderModel.findOne({
where: orderWhere,
raw: true,
});
if (!order) {
throw new Error('订单不存在或不属于当前仓库');
}
const orderItemsModel = await this.getOrderItemsModelByTableType(tableType, warehouseId);
const orderItems = await orderItemsModel.findAll({
where: {
order_id: orderId,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
const orderItemImagesByStockId = await this.getOrderItemImagesByStockIds(orderItems);
const orderItemsWithImages = this.attachImagesToOrderItems(orderItems, orderItemImagesByStockId);
const expresses = await this.getOrderExpressesByOrderId(orderId);
return {
detail: order,
items: orderItemsWithImages,
expresses,
};
}
/**
* 将待处理订单反审回待审核状态。
* @param {Object} data 请求体。
* @return {Promise<Object>} 更新后的订单信息。
*/
async reverseReviewOrder(data = {}) {
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = this.getWarehouseId();
const orderIds = this.normalizeOrderIds(requestData);
if (orderIds.length === 0) {
throw new Error('订单ID不能为空');
}
const model = await this.getOrderModel('order', warehouseId);
const where = this.buildOrderWhere(orderIds, warehouseId);
const step = this.resolveReviewStep('none');
const now = new Date();
const canUseTransaction = this.ctx.model && typeof this.ctx.model.transaction === 'function';
const transaction = canUseTransaction ? await this.ctx.model.transaction() : null;
const dbQueryOptions = transaction ? { transaction } : {};
try {
const targetOrders = await model.findAll({
attributes: [ 'id', 'wave_id', 'wave_no' ],
where,
raw: true,
...dbQueryOptions,
});
if (!Array.isArray(targetOrders) || targetOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const targetOrderIds = targetOrders
.map(order => Number(order && order.id || 0))
.filter(id => Number.isInteger(id) && id > 0);
await this.assertOrdersWithoutWaybill(targetOrderIds, transaction);
const affectedWaveIds = [ ...new Set(targetOrders
.map(order => Number(order && order.wave_id || 0))
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ];
const updateValues = {
inspection_status: 'none',
step,
updated_at: now,
};
if (affectedWaveIds.length > 0) {
updateValues.wave_id = 0;
updateValues.wave_no = '';
}
const updateResult = await model.update(updateValues, {
where,
...dbQueryOptions,
});
const affectedRows = Array.isArray(updateResult) ? Number(updateResult[0] || 0) : Number(updateResult || 0);
if (affectedRows <= 0) {
throw new Error('订单不存在或不属于当前仓库');
}
if (affectedWaveIds.length > 0) {
await this.syncWavesAfterReverseReview({
warehouseId,
waveIds: affectedWaveIds,
orderModel: model,
transaction: transaction || undefined,
});
}
const updatedOrders = await model.findAll({
where,
raw: true,
...dbQueryOptions,
});
if (!Array.isArray(updatedOrders) || updatedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
if (transaction) {
await transaction.commit();
}
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,
inspection_status: order.inspection_status,
step: Number(order.step ?? step),
updated_at: order.updated_at,
}));
if (normalizedOrders.length === 0) {
throw new Error('订单不存在或不属于当前仓库');
}
const firstOrder = normalizedOrders[0];
return {
id: firstOrder.id,
inspection_status: firstOrder.inspection_status,
step: firstOrder.step,
updated_at: firstOrder.updated_at,
updated_count: affectedRows,
ids: normalizedOrders.map(order => order.id),
};
} catch (error) {
if (transaction) {
await transaction.rollback();
}
throw error;
}
}
/**
* 校验订单是否已分配运单号。
*
* 若任一订单存在非空运单号,直接抛出业务异常,阻止反审。
*
* @param {Array<number>} orderIds 订单ID集合。
* @param {Object} transaction Sequelize 事务对象。
* @return {Promise<void>} 无返回值。
*/
async assertOrdersWithoutWaybill(orderIds = [], transaction) {
const normalizedOrderIds = Array.isArray(orderIds)
? orderIds
.map(orderId => Number(orderId || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0)
: [];
if (normalizedOrderIds.length === 0) {
return;
}
const orderExpressModel = this.ctx.model && this.ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return;
}
const expressRows = await orderExpressModel.findAll({
attributes: [ 'order_id', 'waybill_code' ],
where: {
order_id: normalizedOrderIds,
},
raw: true,
transaction,
});
const assignedOrderIds = [ ...new Set((Array.isArray(expressRows) ? expressRows : [])
.filter(row => String(row && row.waybill_code || '').trim())
.map(row => Number(row && row.order_id || 0))
.filter(orderId => Number.isInteger(orderId) && orderId > 0)) ];
if (assignedOrderIds.length > 0) {
const displayOrderIds = assignedOrderIds.slice(0, 10).join(',');
throw new Error(`订单[${displayOrderIds}]已分配运单号,禁止反审`);
}
}
/**
* 反审后同步波次统计与索引。
*
* 同一事务内重建目标波次索引,并回写波次总单量/处理量。
*
* @param {Object} params 同步参数。
* @param {number|string} params.warehouseId 仓库ID。
* @param {Array<number|string>} params.waveIds 受影响波次ID集合。
* @param {Object} params.orderModel 订单模型。
* @param {Object} params.transaction Sequelize 事务对象。
* @return {Promise<void>} 无返回值。
*/
async syncWavesAfterReverseReview({ warehouseId, waveIds, orderModel, transaction } = {}) {
const normalizedWarehouseId = Number(warehouseId || 0);
const normalizedWaveIds = Array.isArray(waveIds)
? [ ...new Set(waveIds
.map(waveId => Number(waveId || 0))
.filter(waveId => Number.isInteger(waveId) && waveId > 0)) ]
: [];
if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) {
return;
}
const waveService = this.service.systemMethods.order.wave;
const remainingCountMap = await waveService.replaceOrderWaveIndexByWaveIds({
warehouseId: normalizedWarehouseId,
waveIds: normalizedWaveIds,
orderModel,
transaction,
});
const updatedWaveIds = [];
const emptiedWaveIds = [];
for (const waveId of normalizedWaveIds) {
const remainingCount = Number(remainingCountMap.get(waveId) || 0);
if (remainingCount > 0) {
updatedWaveIds.push(waveId);
} else {
emptiedWaveIds.push(waveId);
}
}
for (const waveId of updatedWaveIds) {
const remainingCount = Number(remainingCountMap.get(waveId) || 0);
const updateWaveSql = `
UPDATE wms_wave_batch
SET total_orders = :remainingCount,
processed_orders = LEAST(processed_orders, :remainingCount),
update_time = NOW()
WHERE warehouse_id = :warehouseId
AND wave_id = :waveId
`;
await this.ctx.model.query(updateWaveSql, {
replacements: {
warehouseId: normalizedWarehouseId,
waveId,
remainingCount,
},
transaction,
});
}
if (emptiedWaveIds.length > 0) {
const emptyWaveSql = `
UPDATE wms_wave_batch
SET total_orders = 0,
processed_orders = 0,
wave_status = -1,
update_time = NOW()
WHERE warehouse_id = :warehouseId
AND wave_id IN (:waveIds)
`;
await this.ctx.model.query(emptyWaveSql, {
replacements: {
warehouseId: normalizedWarehouseId,
waveIds: emptiedWaveIds,
},
transaction,
});
}
}
/**
* 将待处理订单批量分配储位。
*
* 该入口仅接受订单相关入参,不再接受 warehouse_id / warehouseId;
* 仓库上下文统一取当前登录用户的 store_id。
*
* @param {Object} data 请求体。
* @return {Promise<Object>} 统一 success 包装的受理结果,包含 request_id 与 warehouse_id。
*/
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);
const warehouseId = this.getWarehouseId();
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
const requestId = `storage_alloc_${warehouseId ?? 'unknown'}_${timestamp}_${randomToken}`;
const taskProgressState = {
total_count: 0,
processed_count: 0,
progress: 0,
};
await this.setAllocateStorageTaskProgress(requestId, {
status: 'submitted',
total_count: taskProgressState.total_count,
processed_count: taskProgressState.processed_count,
progress: taskProgressState.progress,
});
setImmediate(async () => {
try {
await this.setAllocateStorageTaskProgress(requestId, {
status: 'running',
total_count: taskProgressState.total_count,
processed_count: taskProgressState.processed_count,
progress: taskProgressState.progress,
});
const allocationRequest = {
allow_storage_location: normalizedData.allow_storage_location,
order_ids: normalizedData.order_ids,
progress_callback: async progressPayload => {
const safeProgressPayload = this.isPlainObject(progressPayload) ? progressPayload : {};
const totalCount = this.normalizeAllocateStorageTaskCount(
safeProgressPayload.total_count
?? safeProgressPayload.totalCount
?? taskProgressState.total_count,
taskProgressState.total_count
);
const processedCount = this.normalizeAllocateStorageTaskCount(
safeProgressPayload.processed_count
?? safeProgressPayload.processedCount
?? taskProgressState.processed_count,
taskProgressState.processed_count
);
taskProgressState.total_count = Math.max(taskProgressState.total_count, totalCount);
taskProgressState.processed_count = Math.min(
taskProgressState.total_count,
Math.max(taskProgressState.processed_count, processedCount)
);
taskProgressState.progress = this.normalizeAllocateStorageTaskProgress(
safeProgressPayload.progress,
'running',
taskProgressState.total_count,
taskProgressState.processed_count
);
await this.setAllocateStorageTaskProgress(requestId, {
status: 'running',
total_count: taskProgressState.total_count,
processed_count: taskProgressState.processed_count,
progress: taskProgressState.progress,
});
},
};
console.log('[PendingOrderService.allocateStorage] 后台开始处理储位分配', {
request_id: requestId,
allocationRequest: {
allow_storage_location: allocationRequest.allow_storage_location,
order_ids: allocationRequest.order_ids,
},
});
const result = await this.service.systems.orderStorageAllocation.allocateStorage(allocationRequest);
if (taskProgressState.total_count > 0) {
taskProgressState.processed_count = taskProgressState.total_count;
}
taskProgressState.progress = 100;
await this.setAllocateStorageTaskProgress(requestId, {
status: 'success',
total_count: taskProgressState.total_count,
processed_count: taskProgressState.processed_count,
progress: taskProgressState.progress,
result,
});
// 写操作日志(不影响主流程)
try {
const operator = this.getOrderLogOperator();
const warehouseId = this.getWarehouseId();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
const orderIds = Array.isArray(normalizedData.order_ids)
? normalizedData.order_ids
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
// 从 result 中提取分配结果信息
const resultData = result && result.data ? result.data : (result || {});
const allocatedIds = Array.isArray(resultData.allocated_order_ids) ? resultData.allocated_order_ids : [];
const shortageIds = Array.isArray(resultData.shortage_order_ids) ? resultData.shortage_order_ids : [];
const allocatedSet = new Set(allocatedIds.map(Number));
const shortageSet = new Set(shortageIds.map(Number));
if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
const operatorInfo = operator || {};
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
const now = new Date();
const logRows = orderIds.map(orderId => {
const oid = Number(orderId);
const allocated = allocatedSet.has(oid);
const shortage = shortageSet.has(oid);
const operationCode = allocated
? 'ORDER_STORAGE_ALLOCATE_SUCCESS'
: shortage
? 'ORDER_STORAGE_ALLOCATE_FAILED'
: 'ORDER_STORAGE_ALLOCATE_SUCCESS';
const msg = allocated
? '储位分配成功'
: shortage
? '储位分配失败:库存不足'
: '储位分配完成';
return {
business_type: 'order',
business_id: String(oid),
operation_code: operationCode,
operator_id: operatorId,
operator_name: operatorName,
external_log_type: 'NONE',
warehouse_id: logWarehouseId || null,
platform_code: 'SYSTEM',
message: msg,
created_at: now,
};
}).filter(row => Number(row.business_id) > 0);
if (logRows.length > 0) {
await this.ctx.model.OperationLog.bulkCreate(logRows);
}
}
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入成功操作日志失败,不影响业务', logErr);
}
console.log('[PendingOrderService.allocateStorage] 后台储位分配处理成功', {
request_id: requestId,
normalizedData,
result,
});
} catch (error) {
await this.setAllocateStorageTaskProgress(requestId, {
status: 'failed',
total_count: taskProgressState.total_count,
processed_count: taskProgressState.processed_count,
progress: taskProgressState.progress,
error: error && error.message ? error.message : String(error),
});
// 写操作日志(不影响主流程)
try {
const operator = this.getOrderLogOperator();
const warehouseId = this.getWarehouseId();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
const orderIds = Array.isArray(normalizedData.order_ids)
? normalizedData.order_ids
: (normalizedData.order_ids ? [ normalizedData.order_ids ] : []);
if (orderIds.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
const operatorInfo = operator || {};
const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null;
const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system';
const errorMsg = error && error.message ? error.message : String(error);
const now = new Date();
const logRows = orderIds.map(orderId => {
const oid = Number(orderId);
return {
business_type: 'order',
business_id: String(oid),
operation_code: 'ORDER_STORAGE_ALLOCATE_FAILED',
operator_id: operatorId,
operator_name: operatorName,
external_log_type: 'NONE',
warehouse_id: logWarehouseId || null,
platform_code: 'SYSTEM',
message: `储位分配失败:${errorMsg}`,
created_at: now,
};
}).filter(row => Number(row.business_id) > 0);
if (logRows.length > 0) {
await this.ctx.model.OperationLog.bulkCreate(logRows);
}
}
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.allocateStorage] 写入失败操作日志失败,不影响业务', logErr);
}
console.log('[PendingOrderService.allocateStorage] 后台储位分配处理异常', {
request_id: requestId,
normalizedData,
error_message: error?.message,
error_stack: error?.stack,
});
}
});
return this.success('ok', {
request_id: requestId,
warehouse_id: warehouseId,
message: '请求已提交,后端处理中',
});
}
/**
* 查询待处理订单储位分配任务进度。
*
* @param {Object} data 请求体。
* @param {string} data.request_id 请求ID(下划线写法)。
* @param {string} data.requestId 请求ID(驼峰写法)。
* @return {Promise<Object>} 统一响应,包含任务状态或结果。
*/
async allocateStorageProgress(data = {}) {
const requestId = this.normalizeAllocateStorageRequestId(data);
if (!requestId) {
return this.fail('request_id 参数不能为空', {}, 400);
}
const cachedProgress = await this.getAllocateStorageTaskProgress(requestId);
if (!cachedProgress) {
return this.success('ok', {
request_id: requestId,
status: 'not_found',
progress: ALLOCATE_STORAGE_PROGRESS_MAP.not_found,
total_count: 0,
processed_count: 0,
});
}
const normalizedStatus = String(cachedProgress.status || 'unknown').trim() || 'unknown';
const normalizedCounts = this.normalizeAllocateStorageTaskCounts(cachedProgress, normalizedStatus);
const normalizedProgress = this.normalizeAllocateStorageTaskProgress(
cachedProgress.progress,
normalizedStatus,
normalizedCounts.total_count,
normalizedCounts.processed_count
);
return this.success('ok', {
request_id: requestId,
...cachedProgress,
status: normalizedStatus,
progress: normalizedProgress,
total_count: normalizedCounts.total_count,
processed_count: normalizedCounts.processed_count,
});
}
/**
* 规范任务进度值,兼容历史缓存中缺失 progress 字段的场景。
*
* @param {number|string|null|undefined} progress 原始进度值。
* @param {string} status 任务状态。
* @param {number} totalCount 总任务数。
* @param {number} processedCount 已处理任务数。
* @return {number} 归一化后的进度百分比(0-100)。
*/
normalizeAllocateStorageTaskProgress(progress, status = 'unknown', totalCount = 0, processedCount = 0) {
const parsed = Number(progress);
if (Number.isFinite(parsed)) {
return Math.min(100, Math.max(0, Math.round(parsed)));
}
if (String(status || 'unknown').trim() === 'success') {
return 100;
}
const normalizedTotalCount = this.normalizeAllocateStorageTaskCount(totalCount, 0);
const normalizedProcessedCount = this.normalizeAllocateStorageTaskCount(processedCount, 0);
if (normalizedTotalCount > 0) {
return Math.round(Math.min(normalizedTotalCount, normalizedProcessedCount) / normalizedTotalCount * 100);
}
const normalizedStatus = String(status || 'unknown').trim() || 'unknown';
if (Object.prototype.hasOwnProperty.call(ALLOCATE_STORAGE_PROGRESS_MAP, normalizedStatus)) {
return ALLOCATE_STORAGE_PROGRESS_MAP[normalizedStatus];
}
return ALLOCATE_STORAGE_PROGRESS_MAP.unknown;
}
/**
* 规范任务计数字段。
*
* @param {number|string|null|undefined} value 原始计数值。
* @param {number} defaultValue 默认值。
* @return {number} 归一化后的非负整数。
*/
normalizeAllocateStorageTaskCount(value, defaultValue = 0) {
const parsed = Number(value);
if (!Number.isFinite(parsed)) {
return Math.max(0, Math.round(Number(defaultValue) || 0));
}
return Math.max(0, Math.round(parsed));
}
/**
* 规范任务总量与处理量,兼容历史缓存与别名字段。
*
* @param {Object} payload 原始缓存载荷。
* @param {string} status 任务状态。
* @return {{ total_count: number, processed_count: number }} 归一化后的计数信息。
*/
normalizeAllocateStorageTaskCounts(payload = {}, status = 'unknown') {
const safePayload = this.isPlainObject(payload) ? payload : {};
const totalCount = this.normalizeAllocateStorageTaskCount(
safePayload.total_count
?? safePayload.totalCount
?? safePayload.total,
0
);
let processedCount = this.normalizeAllocateStorageTaskCount(
safePayload.processed_count
?? safePayload.processedCount
?? safePayload.processed,
0
);
if (totalCount > 0) {
processedCount = Math.min(totalCount, processedCount);
} else {
processedCount = 0;
}
if (String(status || 'unknown').trim() === 'success' && totalCount > 0) {
processedCount = totalCount;
}
return {
total_count: totalCount,
processed_count: processedCount,
};
}
/**
* 规范待处理订单储位分配请求ID。
*
* @param {Object} data 请求体。
* @param {string} data.request_id 请求ID(下划线写法)。
* @param {string} data.requestId 请求ID(驼峰写法)。
* @return {string} 归一化后的请求ID。
*/
normalizeAllocateStorageRequestId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.request_id || normalizedData.requestId || '').trim();
}
/**
* 获取待处理订单储位分配任务缓存键。
*
* @param {string} requestId 请求ID。
* @return {string} 缓存键。
*/
getAllocateStorageTaskCacheKey(requestId = '') {
const normalizedRequestId = String(requestId || '').trim();
if (!normalizedRequestId) {
return '';
}
return `${ALLOCATE_STORAGE_TASK_CACHE_KEY_PREFIX}${normalizedRequestId}`;
}
/**
* 写入待处理订单储位分配任务进度。
*
* @param {string} requestId 请求ID。
* @param {Object} payload 任务状态与结果。
* @return {Promise<void>} 无返回值。
*/
async setAllocateStorageTaskProgress(requestId = '', payload = {}) {
const cacheKey = this.getAllocateStorageTaskCacheKey(requestId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const normalizedStatus = String(safePayload.status || 'unknown').trim() || 'unknown';
const normalizedCounts = this.normalizeAllocateStorageTaskCounts(safePayload, normalizedStatus);
const normalizedProgress = this.normalizeAllocateStorageTaskProgress(
safePayload.progress,
normalizedStatus,
normalizedCounts.total_count,
normalizedCounts.processed_count
);
const progressPayload = {
...safePayload,
status: normalizedStatus,
progress: normalizedProgress,
total_count: normalizedCounts.total_count,
processed_count: normalizedCounts.processed_count,
request_id: String(requestId || '').trim(),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, ALLOCATE_STORAGE_TASK_CACHE_TTL_SECONDS);
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateStorage] 写入任务进度缓存失败: %s', error && error.message ? error.message : error);
}
}
/**
* 读取待处理订单储位分配任务进度。
*
* @param {string} requestId 请求ID。
* @return {Promise<Object|null>} 任务缓存结果。
*/
async getAllocateStorageTaskProgress(requestId = '') {
const cacheKey = this.getAllocateStorageTaskCacheKey(requestId);
if (!cacheKey || typeof this.app.getCacheAsync !== 'function') {
return null;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
this.ctx.logger.warn('[pendingOrder.allocateStorage] 读取任务进度缓存失败: %s', error && error.message ? error.message : error);
return null;
}
}
/**
* 将待处理订单批量取消储位分配。
*
* 该入口仅接受订单 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);
try {
if (this.ctx.model && this.ctx.model.OperationLog) {
const operator = this.getOrderLogOperator() || {};
const operatorId = operator.id != null ? String(operator.id) : null;
const operatorName = operator.name ? String(operator.name) : 'system';
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
const resultData = result && result.data ? result.data : {};
const cancellableOrderIds = Array.isArray(resultData.cancellable_order_ids) ? resultData.cancellable_order_ids : [];
const now = new Date();
const logRows = [];
for (const orderId of cancellableOrderIds) {
const normalizedOrderId = Number(orderId);
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
continue;
}
logRows.push({
business_type: 'order',
business_id: String(normalizedOrderId),
operation_code: 'ORDER_STORAGE_UNALLOCATE_SUCCESS',
operator_id: operatorId,
operator_name: operatorName,
external_log_type: 'NONE',
warehouse_id: logWarehouseId,
platform_code: 'SYSTEM',
message: '取消储位分配成功',
created_at: now,
});
}
if (logRows.length > 0) {
await this.ctx.model.OperationLog.bulkCreate(logRows);
}
}
} catch (logError) {
this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配日志失败,不影响主流程', logError);
}
return this.success('ok', result);
} catch (error) {
try {
if (this.ctx.model && this.ctx.model.OperationLog) {
const rawOrderIds = Array.isArray(normalizedData.order_ids)
? normalizedData.order_ids
: (normalizedData.order_ids != null ? [ normalizedData.order_ids ] : []);
const orderIds = [ ...new Set(rawOrderIds.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)) ];
if (orderIds.length > 0) {
const operator = this.getOrderLogOperator() || {};
const operatorId = operator.id != null ? String(operator.id) : null;
const operatorName = operator.name ? String(operator.name) : 'system';
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
const errorMessage = error && error.message ? error.message : String(error);
const now = new Date();
const logRows = orderIds.map(orderId => ({
business_type: 'order',
business_id: String(orderId),
operation_code: 'ORDER_STORAGE_UNALLOCATE_FAILED',
operator_id: operatorId,
operator_name: operatorName,
external_log_type: 'NONE',
warehouse_id: logWarehouseId,
platform_code: 'SYSTEM',
message: `取消储位分配失败:${errorMessage}`,
created_at: now,
}));
await this.ctx.model.OperationLog.bulkCreate(logRows);
}
}
} catch (logError) {
this.ctx.logger.warn('[PendingOrderService.cancelAllocateStorage] 写入取消储位分配失败日志失败,不影响主流程', logError);
}
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 isBusinessIdOne = businessKey => {
const businessKeys = Array.isArray(businessKey) ? businessKey : [ businessKey ];
return businessKeys.some(item => Number(item) === 1);
};
const orderIds = [ ...new Set(
orders
.map(order => Number(order && (order.order_id || order.id)))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
) ];
const rollbackOrderIds = [ ...new Set(
orders
.filter(order => isBusinessIdOne(order && order.business_key))
.map(order => Number(order && (order.order_id || order.id)))
.filter(orderId => Number.isFinite(orderId) && orderId > 0)
) ];
const { service } = this;
try {
const result = await service.systems.express.createWaybillCodePipeline(orders);
return this.success('ok', result);
} catch (error) {
try {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
const orderDeliveryModel = orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function'
? await orderDeliveryFactory.getCurrentModel()
: null;
if (rollbackOrderIds.length > 0) {
await this.service.systems.express.markWaybillAsyncOrdersAsError(
orderDeliveryModel,
rollbackOrderIds,
error && error.message ? `${error.message}` : `${error}`
);
} else {
this.ctx.logger.info('[PendingOrderService.allocateExpressCode] 未命中 business_id=1 订单,跳过 post_status 失败回写', {
totalOrderCount: orderIds.length,
});
}
} catch (markError) {
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 通过统一 helper 回写订单失败状态失败,不影响主流程', markError);
}
try {
const operationLogService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.operationLog;
if (orderIds.length > 0 && operationLogService && typeof operationLogService.createOperationLogs === 'function') {
const operator = this.getOrderLogOperator() || {};
const logWarehouseId = this.getOrderLogWarehouseId(this.getWarehouseId()) || null;
const errorMessage = error && error.message ? String(error.message) : String(error);
const payloads = orderIds.map(orderId => ({
businessType: 'order',
businessId: String(orderId),
operationCode: 'ORDER_EXPRESS_ALLOCATE_FAILED',
operator,
extras: {
message: `分配快递失败:${errorMessage}`,
warehouseId: logWarehouseId,
externalLogType: 'NONE',
},
}));
await operationLogService.createOperationLogs(payloads);
}
} catch (logError) {
this.ctx.logger.warn('[PendingOrderService.allocateExpressCode] 写入分配快递失败日志失败,不影响主流程', logError);
}
throw error;
}
}
/**
* 将待处理订单批量标记为待出库。
* @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,
step: PENDING_OUTBOUND_STEP,
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 ordersWithWave = existingOrders.filter(order => Number(order.wave_id) > 0);
if (ordersWithWave.length > 0) {
try {
const { Op } = this.app.Sequelize;
const WaveBatch = this.ctx.model.WaveBatch;
const waveOrderIds = ordersWithWave
.map(order => Number(order.id))
.filter(orderId => Number.isInteger(orderId) && orderId > 0);
if (waveOrderIds.length > 0) {
await model.update(
{
wave_id: 0,
wave_no: '',
updated_at: now,
},
{
where: {
id: {
[Op.in]: waveOrderIds,
},
warehouse_id: warehouseId,
},
}
);
}
if (WaveBatch) {
const waveIdCountMap = new Map();
for (const order of ordersWithWave) {
const waveId = Number(order.wave_id);
if (!Number.isInteger(waveId) || waveId <= 0) {
continue;
}
waveIdCountMap.set(waveId, (waveIdCountMap.get(waveId) || 0) + 1);
}
for (const [ waveId, canceledCount ] of waveIdCountMap.entries()) {
await WaveBatch.decrement('total_orders', {
by: canceledCount,
where: {
wave_id: waveId,
warehouse_id: warehouseId,
total_orders: {
[Op.gt]: 0,
},
},
});
const wave = await WaveBatch.findOne({
where: {
wave_id: waveId,
warehouse_id: warehouseId,
},
attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
raw: true,
});
if (!wave) {
continue;
}
const totalOrders = Number(wave.total_orders);
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
if (normalizedTotalOrders <= 0) {
await WaveBatch.update(
{
total_orders: 0,
wave_status: -1,
update_time: now,
},
{
where: {
wave_id: waveId,
warehouse_id: warehouseId,
},
}
);
} else {
await WaveBatch.update(
{
update_time: now,
},
{
where: {
wave_id: waveId,
warehouse_id: warehouseId,
},
}
);
}
}
}
} catch (waveErr) {
this.ctx.logger.warn('[PendingOrderService.cancelOrder] 清理波次关联失败,不影响订单取消', waveErr);
}
}
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 operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
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: logWarehouseId,
operationCode: 'ORDER_UPDATE_PLATFORM',
operator,
extras: {
warehouseId: logWarehouseId,
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 operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
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: logWarehouseId,
operationCode: 'ORDER_UPDATE_EXPRESS',
operator,
extras: {
warehouseId: logWarehouseId,
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 operator = this.getOrderLogOperator();
const logWarehouseId = this.getOrderLogWarehouseId(warehouseId);
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,
extras: {
warehouseId: logWarehouseId,
message: `订单克隆:原订单 ${orderId} 已取消,将创建新订单`,
},
beforeChanges: null,
});
} catch (logErr) {
this.ctx.logger.warn('[PendingOrderService.cloneOrder] 写入原订单克隆日志失败', logErr);
}
// 4. 构造新订单数据 — 保留业务字段,重置所有流程状态
const RESET_FIELDS = {
step: 0,
status: 'created',
inspection_status: 'none',
recheck_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,
extras: {
warehouseId: logWarehouseId,
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,
});
}
/**
* 智能地址解析:使用 DeepSeek 将用户输入的地址字符串解析为结构化地址。
* @param {Object} data 请求数据。
* @param {string} data.address 原始地址字符串(必填)。
* @return {Promise<Object>} 解析结果,成功返回 province/city/area/town/detailAddress/name/mobile 等,失败返回错误。
*/
async parseAddress(data = {}) {
const address = String(data.address || '').trim();
if (!address) {
return this.fail('地址字符串不能为空');
}
const apiKey = this.config.deepseek.apiKey;
const baseUrl = this.config.deepseek.baseUrl || 'https://api.deepseek.com';
if (!apiKey) {
return this.fail('DeepSeek API Key 未配置');
}
try {
const prompt = `你是一个专业的中文地址解析助手,拥有丰富的中国地理知识。请解析以下地址字符串。
规则:
1. 提取字段:province(省)、city(市)、area(区/县)、town(乡镇/街道)、detailAddress(详细地址)、name(收件人)、mobile(手机号)
2. **利用你的中国地理知识**:如果地址包含村/镇/街道/社区名称,请检索你的知识库推测它所属的省市区。例如:
- "和丰一社" + 常见于广东地区村组命名 → 推测为广东省 东莞市/广州市等
- 根据地址中的方言特征、命名习惯推测所在区域
3. 如果实在无法确定,province填"暂未识别",city和area同理填"暂未识别"
4. detailAddress去除省市区部分,只保留街道/村/门牌号
5. 只返回纯JSON,不含解释或markdown
地址字符串: "${address}"
请返回JSON:`;
const result = await this.ctx.curl(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
headers: {
Authorization: `Bearer ${apiKey}`,
},
data: {
model: 'deepseek-chat',
messages: [
{ role: 'system', content: '你是一个专业的地址解析助手,只返回JSON格式结果。' },
{ role: 'user', content: prompt },
],
temperature: 0,
max_tokens: 500,
},
timeout: 15000,
});
if (result.status !== 200 || !result.data) {
return this.fail('地址解析服务请求失败');
}
const content = result.data.choices?.[0]?.message?.content || '';
// 清理可能的 markdown 代码块标记
let jsonStr = content.trim();
jsonStr = jsonStr.replace(/^```json\s*/i, '').replace(/\s*```$/i, '');
jsonStr = jsonStr.replace(/^```\s*/i, '').replace(/\s*```$/i, '');
try {
const parsed = JSON.parse(jsonStr);
const province = String(parsed.province || '').trim();
const city = String(parsed.city || '').trim();
const area = String(parsed.area || '').trim();
const town = String(parsed.town || '').trim();
if (!province || province === '暂未识别' || province === '其他') {
return this.fail('地址解析失败:省市区无法识别,请补充更多地址信息后重试');
}
return this.success('地址解析成功', {
province,
city,
area,
town,
detailAddress: String(parsed.detailAddress || '').trim(),
name: String(parsed.name || '').trim(),
mobile: String(parsed.mobile || '').trim(),
});
} catch (parseError) {
this.ctx.logger.warn('[parseAddress] JSON解析失败,原始返回: %s', content);
return this.fail('地址解析结果格式异常,请重试');
}
} catch (error) {
this.ctx.logger.error('[parseAddress] DeepSeek请求异常: %s', error.message);
return this.fail(`地址解析失败: ${error.message}`);
}
}
/**
* 手动创建待处理订单。
*
* 根据货主策略(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_id 与 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 province = String(requestData.province || '').trim();
if (!province) {
throw new Error('省份不能为空');
}
const city = String(requestData.city || '').trim();
if (!city) {
throw new Error('城市不能为空');
}
const area = String(requestData.area || '').trim();
if (!area) {
throw new Error('区县不能为空');
}
const rawItems = requestData.items;
if (!Array.isArray(rawItems) || rawItems.length === 0) {
throw new Error('订单明细 items 不能为空');
}
// 2. 批量查询商品信息(利用 getItemInfoWithCache 的 Redis 缓存)
const itemIds = rawItems
.map(item => Number(item && item.item_id))
.filter(id => Number.isInteger(id) && id > 0);
const itemInfoMap = new Map();
for (const itemId of itemIds) {
const info = await this.service.systems.stockStore.getItemInfoWithCache(itemId);
if (info && !info.__isNull) {
itemInfoMap.set(itemId, info);
}
}
// 3. 适配明细格式并校验(转为 addOrder 所需的驼峰格式)
const orderLineItems = rawItems.map((item, idx) => {
if (!item || typeof item !== 'object') {
throw new Error(`第${idx + 1}行明细格式无效`);
}
const itemId = Number(item.item_id);
if (!Number.isInteger(itemId) || itemId <= 0) {
throw new Error(`第${idx + 1}行商品 item_id 必须为正整数`);
}
const planQty = Number(item.plan_qty);
if (!Number.isInteger(planQty) || planQty <= 0) {
throw new Error(`第${idx + 1}行计划数量 plan_qty 必须为正整数`);
}
return {
itemCode: String(item.item_code || '').trim()
|| String(itemInfoMap.get(itemId)?.item_code || '').trim(),
itemId,
itemName: String(item.item_name || '').trim()
|| String(itemInfoMap.get(itemId)?.item_name || '').trim()
|| '商品',
planQty,
orderLineNo: String(item.order_line_no || String(idx + 1)).trim(),
actualPrice: Number(item.actual_price) || 0,
};
});
// 4. 自动生成订单号(如未传)
const deliveryOrderCode = String(requestData.delivery_order_code || '').trim()
|| `SYS${Date.now()}${Math.floor(Math.random() * 9000) + 1000}`;
// 5. 适配为 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',
shopNick: String(requestData.shop_nick || requestData.shopNick || '').trim(),
receiverInfo: {
name,
mobile,
tel,
province,
city,
area,
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) || '',
};
// 6. 委托 addOrder 执行完整逻辑(库存预占、平台快递解析、入队列、操作日志)
const result = await this.service.systems.deliveryOrder.addOrder(adaptedData, info);
if (!result.success) {
throw new Error(result.message || '订单创建失败');
}
// 重复订单视为错误(与原逻辑保持一致)
if (result.message === '订单已存在' || (result.data && result.data.deliveryOrderId)) {
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,
});
}
/**
* 下载创建订单导入模板。
*
* 返回 base64 编码的 Excel 文件内容,前端解码后作为 .xlsx 文件下载。
*
* @return {Promise<Object>} 统一 success 包装,含 base64 字符串与文件名。
*/
async downloadCreateTemplate() {
const ExcelJS = require('exceljs');
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('创建订单导入模板');
const columns = [
// 必填
{ header: '*订单号', key: 'delivery_order_code', width: 24 },
{ header: '*收件人姓名', key: 'name', width: 16 },
{ header: '*手机号(mobile/tel至少填一项)', key: 'mobile', width: 28 },
{ header: '*详细地址', key: 'detail_address', width: 36 },
{ header: '*商品编码', key: 'item_code', width: 20 },
{ header: '*计划数量', key: 'plan_qty', width: 12 },
// 非必填
{ header: '货主ID', key: 'store_id', width: 12 },
{ header: '电话', key: 'tel', width: 16 },
{ 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_name', width: 24 },
{ header: '行号', key: 'order_line_no', width: 10 },
{ header: '实际价格', key: 'actual_price', width: 12 },
{ header: '店铺名称', key: 'shop_nick', width: 20 },
];
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,
shop_nick: '',
});
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,
shop_nick: '',
});
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. 快递编码、系统平台编码不填时,系统会读取货主默认策略自动补充;不填货主ID时,系统会从当前登录用户的上下文自动获取。',
'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',
});
}
}
module.exports = PendingOrderService;