feat(returnUnpack): 拆包单异步导出

This commit is contained in:
liufumingren 2026-08-30 07:28:08 +08:00
parent 0a54f8028b
commit 05177d00f7
2 changed files with 719 additions and 15 deletions

View File

@ -2,6 +2,9 @@
const MainService = require('../main');
const RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX = 'return_unpack_export_task_';
const RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/**
* 系统方法层:returnUnpack(退回拆包模块接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、where 解析等公共逻辑,
@ -12,12 +15,13 @@ class ReturnUnpackMethodService extends MainService {
super(ctx);
// 免登录方法列表:空(全部需要登录)
const _noNeedLogin = '';
// 免权限方法列表:空(全部走 API 权限校验;detail 走固定 ID 548 客服授权,与设计一致)
const _noNeedRight = '';
// 免日志方法列表:空(全部记录日志)
const _noNeedLog = '';
// 免鉴权(仓库有效期检查)方法列表:空(全部检查有效期)
const _noNeedAuth = '';
// 免权限方法列表:export/exportTaskProgress 免权限(异步任务模式,与 order.export 口径一致,无 wms_permission 记录);
// 其余走 API 权限校验(detail 走固定 ID 548 客服授权,与设计一致)
const _noNeedRight = 'export,exportTaskProgress';
// 免日志方法列表:导出与进度查询不记录操作日志(与订单导出口径一致)
const _noNeedLog = 'export,exportTaskProgress';
// 免鉴权(仓库有效期检查)方法列表:导出与进度查询不检查仓库有效期(与订单导出口径一致)
const _noNeedAuth = 'export,exportTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -247,6 +251,262 @@ class ReturnUnpackMethodService extends MainService {
return this._call(() => this.service.systems.returnUnpack.detail(Number(id)), '查询详情失败');
}
/**
* 提交退回拆包导出任务(异步任务模式,与 order.export 口径一致)。
* 入参 where/sort 与 list 完全一致;提交后立即返回 task_id,
* 后台异步生成双 Sheet Excel(正常退回运单号列表 + 明细表)并上传,
* 通过 exportTaskProgress 查询进度与下载链接。
*
* @param {Object} data 请求体。
* @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。
* @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。
* @return {Promise<Object>} 统一成功包装响应(含 task_id/status/progress 等任务信息)。
*/
async export(data = {}) {
const { service } = this;
const { sort } = data;
const { where } = this.prepareWhereContext(data, {});
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
const enforcedWhere = { ...where };
if (warehouseId > 0) {
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
}
const taskId = this.generateExportTaskId(warehouseId);
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
current_count: 0,
total_count: 0,
message: '退回拆包导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 5,
current_count: 0,
total_count: 0,
message: '退回拆包导出任务执行中',
result: null,
error: '',
});
const result = await service.systems.returnUnpack.exportUnpack({
where: enforcedWhere,
sort,
warehouseId,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount,
total_count: safeProgress.totalCount,
message: safeProgress.message || '退回拆包导出任务执行中',
result: safeProgress.result || null,
error: '',
});
},
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
current_count: result.current_count || 0,
total_count: result.total_count || 0,
message: '退回拆包导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
current_count: 0,
total_count: 0,
message: '退回拆包导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询退回拆包导出任务进度(与 order.exportTaskProgress 口径一致)。
*
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {Promise<Object>} 统一成功包装响应
* (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。
*/
async exportTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const cachedTask = await this.getExportTaskProgress(taskId);
if (!cachedTask) {
return this.success('ok', {
task_id: taskId,
status: 'not_found',
progress: 0,
current_count: 0,
total_count: 0,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
/**
* 生成退回拆包导出任务ID。
* @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。
* @return {string} 导出任务ID。
*/
generateExportTaskId(warehouseId = '') {
const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `return_unpack_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化退回拆包导出任务ID。
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {string} 归一化后的任务ID。
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取退回拆包导出任务缓存键。
* @param {string} taskId 任务ID。
* @return {string} 缓存键。
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${RETURN_UNPACK_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入退回拆包导出任务进度缓存(Redis TTL 30 分钟)。
* @param {string} taskId 任务ID。
* @param {Object} payload 任务状态载荷。
* @return {Promise<void>} 无返回值。
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const normalizeCount = value => {
const numericValue = Number(value);
return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0;
};
const progressPayload = {
task_id: String(taskId || '').trim(),
status: String(safePayload.status || 'submitted').trim() || 'submitted',
progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0,
current_count: normalizeCount(safePayload.current_count),
total_count: normalizeCount(safePayload.total_count),
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, RETURN_UNPACK_EXPORT_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[returnUnpack.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取退回拆包导出任务进度缓存。
* @param {string} taskId 任务ID。
* @return {Promise<Object|null>} 任务缓存,未命中返回 null。
*/
async getExportTaskProgress(taskId = '') {
const cacheKey = this.getExportTaskCacheKey(taskId);
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) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[returnUnpack.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
/**
* 删除拆包单(删,后台管理,不限制状态)。
*

View File

@ -1,7 +1,18 @@
'use strict';
const crypto = require('node:crypto');
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const ExcelJS = require('exceljs');
const Service = require('egg').Service;
/** 退回拆包导出主表分页拉取大小 */
const RETURN_UNPACK_EXPORT_PAGE_SIZE = 500;
/** 退回拆包导出明细分批拉取大小 */
const RETURN_UNPACK_DETAIL_BATCH_SIZE = 100;
/**
* 退回拆包模块业务逻辑层。
* 负责 wms_return_unpack(主表)/ wms_return_unpack_detail(明细)/ wms_return_unpack_video(视频)/
@ -950,6 +961,431 @@ class ReturnUnpackService extends Service {
};
}
/**
* 导出退回拆包数据(双 Sheet:正常退回运单号列表 + 明细表)。
* 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouse_id,此处再强制兑底;
* 分页拉取主表全量数据后批量关联明细/货主名称/快递类型,流式生成 Excel 并上传。
*
* @param {Object} options 导出选项。
* @param {Object} [options.where] 标准化 where 条件(与 list 一致)。
* @param {Object} [options.sort] 排序参数(与 list 一致)。
* @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。
* @param {Function} [options.onProgress] 进度回调。
* @return {Promise<Object>} 上传结果与统计信息(含 url/cdnUrl/cosUrl/fileKey/current_count/total_count/total_details/sheet_count,
* url 优先取上传服务返回的完整 URL,兜底取落库记录 file_url/fileUrl,最后才回退 COS key)。
*/
async exportUnpack(options = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {};
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
const warehouseId = Number(safeOptions.warehouseId || 0);
const progressHandler = typeof safeOptions.onProgress === 'function'
? safeOptions.onProgress
: async () => {};
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
throw this.createBusinessError('缺少仓库上下文', 400);
}
// 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id)
const queryWhere = this._buildListWhere(where, Op);
queryWhere.warehouse_id = warehouseId;
const order = this._buildListOrder(sort, 'return_unpack');
const totalCount = await ctx.model.ReturnUnpack.count({ where: queryWhere });
await progressHandler({
status: 'running',
progress: totalCount > 0 ? 10 : 85,
currentCount: 0,
totalCount,
message: totalCount > 0 ? `已命中 ${totalCount} 条拆包单,开始导出` : '未命中数据,开始生成空文件',
});
// ---- 分页拉取主表全量数据 ----
const allUnpackRows = [];
let page = 1;
while (allUnpackRows.length < totalCount) {
const rows = await ctx.model.ReturnUnpack.findAll({
where: queryWhere,
order,
limit: RETURN_UNPACK_EXPORT_PAGE_SIZE,
offset: (page - 1) * RETURN_UNPACK_EXPORT_PAGE_SIZE,
raw: true,
});
if (!Array.isArray(rows) || rows.length === 0) {
break;
}
allUnpackRows.push(...rows);
page += 1;
await progressHandler({
status: 'running',
progress: Math.min(30, 10 + Math.round((allUnpackRows.length / Math.max(totalCount, 1)) * 20)),
currentCount: allUnpackRows.length,
totalCount,
message: `正在拉取拆包单列表,已完成 ${allUnpackRows.length}/${totalCount}`,
});
}
// ---- 批量拉取明细(按 unpack_id 分批) ----
const unpackIds = allUnpackRows
.map(row => Number(row.id))
.filter(id => Number.isInteger(id) && id > 0);
/** @type {Map<number, Array<Object>>} */
const detailsMap = new Map();
if (unpackIds.length > 0) {
const totalBatches = Math.ceil(unpackIds.length / RETURN_UNPACK_DETAIL_BATCH_SIZE);
for (let batchIdx = 0; batchIdx < unpackIds.length; batchIdx += RETURN_UNPACK_DETAIL_BATCH_SIZE) {
const batchIds = unpackIds.slice(batchIdx, batchIdx + RETURN_UNPACK_DETAIL_BATCH_SIZE);
const details = await ctx.model.ReturnUnpackDetail.findAll({
where: { unpack_id: { [Op.in]: batchIds } },
order: [[ 'unpack_id', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
for (const detail of details) {
const key = Number(detail.unpack_id);
if (!detailsMap.has(key)) {
detailsMap.set(key, []);
}
detailsMap.get(key).push(detail);
}
const currentBatch = Math.floor(batchIdx / RETURN_UNPACK_DETAIL_BATCH_SIZE) + 1;
await progressHandler({
status: 'running',
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
currentCount: allUnpackRows.length,
totalCount,
message: `正在拉取拆包明细,已完成批次 ${currentBatch}/${totalBatches}`,
});
}
}
const totalDetails = allUnpackRows.reduce(
(sum, row) => sum + (detailsMap.get(Number(row.id)) || []).length,
0
);
// ---- 批量解析货主名称与快递类型 ----
const storeNameMap = await this._resolveStoreNameMap(allUnpackRows, Op);
const expressNameMap = await this._resolveExpressNameMap(allUnpackRows, Op);
await progressHandler({
status: 'running',
progress: 55,
currentCount: allUnpackRows.length,
totalCount,
message: '正在生成 Excel 文件...',
});
// ---- 生成 Excel(流式写入,两个 Sheet) ----
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-return-unpack-export-'));
const now = new Date();
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const filename = `退回拆包导出_${dateToken}.xlsx`;
const filePath = path.join(tempDir, filename);
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
filename: filePath,
useStyles: false,
useSharedStrings: false,
});
const normalizeCellValue = value => {
if (value === null || value === undefined) return '';
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
return value;
};
const formatDateOnly = value => (value ? app.formatDate(value, 'YYYY-MM-DD') : '');
const formatDateTime = value => (value ? app.formatDate(value) : '');
try {
// Sheet 1: 正常退回运单号列表
const sheet1 = workbook.addWorksheet('正常退回运单号列表');
const mainColumns = [
{ header: '货主', key: 'store_name', width: 20 },
{ header: '快递号', key: 'waybill_code', width: 22 },
{ header: '商品类数', key: 'total_items', width: 12 },
{ header: '商品总数', key: 'total_quantity', width: 12 },
{ header: '记录人员', key: 'unpacker_name', width: 14 },
{ header: '记录日期', key: 'unpack_date', width: 14 },
{ header: '开始时间', key: 'start_time', width: 20 },
{ header: '结束时间', key: 'end_time', width: 20 },
{ header: '是否原单', key: 'is_original_return', width: 10 },
{ header: '快递类型', key: 'express', width: 14 },
{ header: '自定义店铺', key: 'shop_name', width: 20 },
{ header: '平台单号', key: 'source_order_codes', width: 24 },
];
sheet1.columns = mainColumns;
for (const row of allUnpackRows) {
const storeId = Number(row.store_id || 0);
const expressId = Number(row.order_express_id || 0);
sheet1.addRow({
store_name: normalizeCellValue(storeId > 0 ? (storeNameMap.get(storeId) || '') : ''),
waybill_code: normalizeCellValue(row.waybill_code),
total_items: row.total_items,
total_quantity: row.total_quantity,
unpacker_name: normalizeCellValue(row.unpacker_name),
unpack_date: formatDateOnly(row.unpack_date),
start_time: formatDateTime(row.start_time),
end_time: formatDateTime(row.end_time),
is_original_return: row.order_express_id ? '是' : '否',
express: normalizeCellValue(expressId > 0 ? (expressNameMap.get(expressId) || '') : ''),
shop_name: normalizeCellValue(row.shop_name),
source_order_codes: normalizeCellValue(row.source_order_codes),
}).commit();
}
sheet1.commit();
await progressHandler({
status: 'running',
progress: 70,
currentCount: allUnpackRows.length,
totalCount,
message: '正在写入拆包明细...',
});
// Sheet 2: 明细表
const sheet2 = workbook.addWorksheet('明细表');
const detailColumns = [
{ header: '货主', key: 'store_name', width: 20 },
{ header: '快递号', key: 'waybill_code', width: 22 },
{ header: '商品名称', key: 'item_name', width: 24 },
{ header: '商品编码', key: 'item_code', width: 18 },
{ header: '条码', key: 'barcode', width: 20 },
{ header: '颜色', key: 'color', width: 12 },
{ header: '规格', key: 'spec', width: 20 },
{ header: '数量', key: 'quantity', width: 10 },
{ header: '是否残次', key: 'is_damaged', width: 10 },
{ header: '记录人员ID', key: 'unpacker_id', width: 14 },
{ header: '记录日期', key: 'unpack_date', width: 14 },
{ header: '备注', key: 'remark', width: 30 },
{ header: '是否原单', key: 'is_original_return', width: 10 },
{ header: '快递类型', key: 'express', width: 14 },
{ header: '自定义店铺', key: 'shop_name', width: 20 },
{ header: '平台单号', key: 'source_order_codes', width: 24 },
];
sheet2.columns = detailColumns;
let detailWrittenCount = 0;
for (const row of allUnpackRows) {
const storeId = Number(row.store_id || 0);
const expressId = Number(row.order_express_id || 0);
const storeName = storeId > 0 ? (storeNameMap.get(storeId) || '') : '';
const expressName = expressId > 0 ? (expressNameMap.get(expressId) || '') : '';
const details = detailsMap.get(Number(row.id)) || [];
for (const detail of details) {
sheet2.addRow({
store_name: normalizeCellValue(storeName),
waybill_code: normalizeCellValue(row.waybill_code),
item_name: normalizeCellValue(detail.item_name),
item_code: normalizeCellValue(detail.item_code),
barcode: normalizeCellValue(detail.barcode),
color: this._extractDetailColor(detail),
spec: normalizeCellValue(detail.spec),
quantity: detail.quantity,
is_damaged: detail.product_status === 'damaged' ? '是' : '否',
unpacker_id: row.unpacker_id,
unpack_date: formatDateOnly(row.unpack_date),
remark: normalizeCellValue(detail.remark),
is_original_return: row.order_express_id ? '是' : '否',
express: normalizeCellValue(expressName),
shop_name: normalizeCellValue(row.shop_name),
source_order_codes: normalizeCellValue(row.source_order_codes),
}).commit();
}
detailWrittenCount += 1;
if (detailWrittenCount % RETURN_UNPACK_DETAIL_BATCH_SIZE === 0 || detailWrittenCount === allUnpackRows.length) {
await progressHandler({
status: 'running',
progress: Math.min(90, 70 + Math.round((detailWrittenCount / Math.max(allUnpackRows.length, 1)) * 20)),
currentCount: allUnpackRows.length,
totalCount,
message: `正在写入拆包明细,已完成 ${detailWrittenCount}/${allUnpackRows.length} 条拆包单`,
});
}
}
sheet2.commit();
await workbook.commit();
await progressHandler({
status: 'running',
progress: 92,
currentCount: allUnpackRows.length,
totalCount,
message: '正在上传文件...',
});
// ---- 上传文件 ----
const uploadService = ctx?.service?.systems?.upload;
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
throw new Error('上传服务不可用');
}
const stat = await fsp.stat(filePath);
const randomToken = crypto.randomBytes(6).toString('hex');
const uploadKey = `exports/return_unpack/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
const uploadStream = fs.createReadStream(filePath);
uploadStream.filename = filename;
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
uploadStream.fileSize = stat.size;
const uploadResult = await uploadService.uploadFile(uploadStream, {
key: uploadKey,
category: 'document',
mimetype: 'xls,xlsx,csv',
});
let fileRecord = null;
if (typeof uploadService.uploadSuccessNotify === 'function') {
fileRecord = await uploadService.uploadSuccessNotify({
url: uploadResult.fileName,
fileKey: uploadResult.fileName,
fileName: filename,
fileType: 'document',
mimeType: uploadStream.mimeType,
fileSize: stat.size,
userId: ctx.userId,
description: `退回拆包导出(仓库${warehouseId}),共${totalCount}条拆包单`,
});
}
// 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key
const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {};
const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null;
const fileUrlFromRecord = resolvedFileRecord
? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '')
: '';
const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || '';
const uploadInfo = {
filename,
fileKey: safeUploadResult.fileName || uploadKey,
url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey,
cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '',
cosUrl: safeUploadResult.cosUrl || '',
current_count: allUnpackRows.length,
total_count: totalCount,
total_details: totalDetails,
sheet_count: 2,
};
await progressHandler({
status: 'success',
progress: 100,
currentCount: allUnpackRows.length,
totalCount,
message: '导出任务完成',
result: uploadInfo,
});
return uploadInfo;
} catch (error) {
const workbookStream = workbook.stream;
if (workbookStream && typeof workbookStream.destroy === 'function') {
workbookStream.destroy();
}
throw error;
} finally {
// 清理临时文件(不存在或删除失败均忽略)
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ }
}
}
/**
* 批量解析货主名称映射(store_id → wms_store.company_name)。
* @param {Array<Object>} rows 主表行数组。
* @param {Object} Op Sequelize Op 对象。
* @return {Promise<Map<number, string>>} store_id → 货主名称映射。
*/
async _resolveStoreNameMap(rows = [], Op) {
const { ctx } = this;
const storeIds = [ ...new Set(
(Array.isArray(rows) ? rows : [])
.map(row => Number(row && row.store_id || 0))
.filter(id => Number.isInteger(id) && id > 0)
) ];
/** @type {Map<number, string>} */
const nameMap = new Map();
if (storeIds.length === 0) {
return nameMap;
}
try {
const stores = await ctx.model.Store.findAll({
where: { id: { [Op.in]: storeIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
for (const store of stores) {
nameMap.set(Number(store.id), store.company_name ? String(store.company_name) : '');
}
} catch (err) {
ctx.logger.warn(`[returnUnpack.export] 批量解析货主名称失败: ${err.message}`);
}
return nameMap;
}
/**
* 批量解析快递类型映射(order_express_id → wms_order_express.logistics_name)。
* @param {Array<Object>} rows 主表行数组。
* @param {Object} Op Sequelize Op 对象。
* @return {Promise<Map<number, string>>} order_express_id → 快递类型映射。
*/
async _resolveExpressNameMap(rows = [], Op) {
const { ctx } = this;
const expressIds = [ ...new Set(
(Array.isArray(rows) ? rows : [])
.map(row => Number(row && row.order_express_id || 0))
.filter(id => Number.isInteger(id) && id > 0)
) ];
/** @type {Map<number, string>} */
const nameMap = new Map();
if (expressIds.length === 0) {
return nameMap;
}
try {
const expresses = await ctx.model.OrderExpress.findAll({
where: { id: { [Op.in]: expressIds } },
attributes: [ 'id', 'logistics_name' ],
raw: true,
});
for (const express of expresses) {
nameMap.set(Number(express.id), express.logistics_name ? String(express.logistics_name) : '');
}
} catch (err) {
ctx.logger.warn(`[returnUnpack.export] 批量解析快递类型失败: ${err.message}`);
}
return nameMap;
}
/**
* 从明细快照/规格中提取颜色(优先 product_snapshot.sku_property,兜底 spec 字段)。
* 颜色约定以「颜色:xxx」形式出现在 SKU 规格串中,未命中返回空字符串。
* @param {Object} detail 明细行。
* @return {string} 颜色文本,未命中返回空字符串。
*/
_extractDetailColor(detail = {}) {
let spec = detail && detail.spec ? String(detail.spec) : '';
const snapshot = detail && detail.product_snapshot;
if (snapshot) {
try {
const parsed = typeof snapshot === 'string' ? JSON.parse(snapshot) : snapshot;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && parsed.sku_property) {
spec = String(parsed.sku_property);
}
} catch (err) {
// 快照解析失败时退回 spec 字段
}
}
const normalized = String(spec || '').trim();
if (!normalized) {
return '';
}
const match = normalized.match(/颜色[::]\s*([^;;,,]+)/);
return match && match[1] ? String(match[1]).trim() : '';
}
/**
* 查询拆包单详情:主表 + 明细 + 视频 + 退回收到单 + 原订单详情(原单退回时)。
*
@ -1741,11 +2177,13 @@ class ReturnUnpackService extends Service {
/**
* 生成拆包单号(原子取号)。
* 格式:RP + YYYYMMDD + 6位序号(如 RP20260813000001)。
* 取号基于序列表 wms_number_sequence 的单条 upsert 原子递增:
* INSERT ... VALUES (LAST_INSERT_ID(:seed + 1)) ON DUPLICATE KEY UPDATE
* current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1)
* 取号基于序列表 wms_number_sequence 的 upsert 原子递增(唯一键 uk_warehouse_biz_date 串行化并发事务):
* INSERT ... VALUES (:seed + 1) ON DUPLICATE KEY UPDATE
* current_seq = GREATEST(current_seq, :seed) + 1
* 其中 :seed 为当日主表已有最大序号,保证历史数据对齐(首日启用不撞已有单号);
* 同事务(同连接)内回读 LAST_INSERT_ID() 取回本次分配序号,并发下无撞号。
* upsert 后通过带锁当前读(SELECT ... FOR UPDATE)回读 current_seq,
* 避免 REPEATABLE READ 快照读读到旧值导致撞号或跳号。
* 注意:不再依赖 LAST_INSERT_ID() 回读,因为 fresh INSERT 时其会被序列表自增主键覆盖。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<string>} 拆包单号。
@ -1774,25 +2212,31 @@ class ReturnUnpackService extends Service {
);
const seed = Number(seedRows && seedRows[0] && seedRows[0].max_seq) || 0;
// 原子取号:单条 upsert 内递增并设置连接级 LAST_INSERT_ID
// 原子取号:单条 upsert 内按唯一键串行化并发事务递增 current_seq
await ctx.model.query(
`INSERT INTO wms_number_sequence (warehouse_id, biz_type, date_part, current_seq, created_at, updated_at)
VALUES (:warehouseId, :bizType, :datePart, LAST_INSERT_ID(:seed + 1), NOW(), NOW())
ON DUPLICATE KEY UPDATE current_seq = LAST_INSERT_ID(GREATEST(current_seq, :seed) + 1), updated_at = NOW()`,
VALUES (:warehouseId, :bizType, :datePart, :seed + 1, NOW(), NOW())
ON DUPLICATE KEY UPDATE current_seq = GREATEST(current_seq, :seed) + 1, updated_at = NOW()`,
{
replacements: { warehouseId, bizType, datePart, seed },
transaction,
}
);
// 带锁当前读回读:同事务已通过 upsert 持有该行排他锁(或经唯一键冲突等待串行化),
// FOR UPDATE 返回本事务最新写入值或最新提交版本,不受旧快照影响
const rows = await ctx.model.query(
'SELECT LAST_INSERT_ID() AS seq',
`SELECT current_seq
FROM wms_number_sequence
WHERE warehouse_id = :warehouseId AND biz_type = :bizType AND date_part = :datePart
FOR UPDATE`,
{
replacements: { warehouseId, bizType, datePart },
type: ctx.model.QueryTypes.SELECT,
transaction,
}
);
return Number(rows && rows[0] && rows[0].seq) || 1;
return Number(rows && rows[0] && rows[0].current_seq) || 1;
});
if (sequence > 999999) {