refactor(storage.receiving): 导出功能 storeId 改为从 ctx.user.store_id 获取 warehouseId;新增导出相关接口文档
This commit is contained in:
parent
000597fecc
commit
fb2c00027e
@ -13,9 +13,9 @@ class configService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress';
|
||||
const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress';
|
||||
const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress';
|
||||
const _noNeedRight = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
|
||||
const _noNeedLog = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
|
||||
const _noNeedAuth = 'getReceivingList,getStoreReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail,export,exportTaskProgress,storeExport,storeExportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -333,39 +333,19 @@ class configService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。
|
||||
* 提交收货单导出任务(仓库维度,复用 getReceivingList 的筛选语义与排序规则)。
|
||||
* 导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致)
|
||||
* @param {Object} [data.where] 筛选条件(与 getReceivingList 一致)
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
|
||||
*/
|
||||
async export(data = {}) {
|
||||
const { ctx, app, service } = this;
|
||||
|
||||
// 从平台激活上下文获取 store_id
|
||||
const platformRows = await app.model.query(
|
||||
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||
{
|
||||
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||
}
|
||||
|
||||
const storeId = platformRows[0].store_id;
|
||||
const { service } = this;
|
||||
const { sort = {} } = data;
|
||||
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
quickWhere: { bucket: 'quick' },
|
||||
},
|
||||
});
|
||||
|
||||
@ -394,7 +374,6 @@ class configService extends MainService {
|
||||
|
||||
const result = await service.systems.storage.receiving.exportReceivingList({
|
||||
where,
|
||||
storeId,
|
||||
sort,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
@ -490,13 +469,15 @@ class configService extends MainService {
|
||||
|
||||
/**
|
||||
* 生成收货单导出任务ID。
|
||||
* @param {string} [prefix=''] 任务类型前缀(如 'store')
|
||||
* @return {string} 导出任务ID
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
generateExportTaskId(prefix = '') {
|
||||
const storeId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `receiving_export_${storeId}_${timestamp}_${randomToken}`;
|
||||
const typePrefix = prefix ? `${prefix}_` : '';
|
||||
return `receiving_${typePrefix}export_${storeId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -579,5 +560,121 @@ class configService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交货主侧收货单导出任务(复用 getStoreReceivingList 的筛选语义与排序规则)。
|
||||
* 以当前平台激活的货主 store_id 为维度导出。导出分为两个 sheet:Sheet1=收货单列表,Sheet2=收货单明细。
|
||||
* @param {Object} data 请求体
|
||||
* @param {Object} [data.where] 筛选条件(与 getStoreReceivingList 一致)
|
||||
* @param {Object} [data.sort] 排序参数
|
||||
* @return {Promise<Object>} 统一成功包装响应,data 为导出任务信息
|
||||
*/
|
||||
async storeExport(data = {}) {
|
||||
const { ctx, app, service } = this;
|
||||
|
||||
// 从平台激活上下文获取 store_id
|
||||
const platformRows = await app.model.query(
|
||||
'SELECT apa.employee_id, ase.store_id FROM wms_account_platform_active apa ' +
|
||||
'INNER JOIN wms_account_store_employee ase ON ase.id = apa.employee_id AND ase.status = 1 ' +
|
||||
'WHERE apa.account_id = :accountId AND apa.platform_code = :platformCode LIMIT 1',
|
||||
{
|
||||
replacements: { accountId: ctx.userId, platformCode: ctx.platformCode || 'web' },
|
||||
type: app.Sequelize.QueryTypes.SELECT,
|
||||
}
|
||||
);
|
||||
|
||||
if (!platformRows || platformRows.length === 0 || !platformRows[0].store_id) {
|
||||
return this.fail('未获取到货主平台激活上下文,请先切换至货主角色');
|
||||
}
|
||||
|
||||
const storeId = platformRows[0].store_id;
|
||||
const { sort = {} } = data;
|
||||
|
||||
const { where } = this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const taskId = this.generateExportTaskId('store');
|
||||
const taskPayload = {
|
||||
task_id: taskId,
|
||||
status: 'submitted',
|
||||
progress: 0,
|
||||
message: '货主侧收货单导出任务已提交',
|
||||
result: null,
|
||||
error: '',
|
||||
};
|
||||
|
||||
await this.setExportTaskProgress(taskId, taskPayload);
|
||||
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'running',
|
||||
progress: 5,
|
||||
message: '货主侧收货单导出任务执行中',
|
||||
result: null,
|
||||
error: '',
|
||||
});
|
||||
|
||||
const result = await service.systems.storage.receiving.exportStoreReceivingList({
|
||||
where,
|
||||
storeId,
|
||||
sort,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress,
|
||||
message: safeProgress.message || '货主侧收货单导出任务执行中',
|
||||
result: safeProgress.result || null,
|
||||
error: '',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
message: '货主侧收货单导出任务完成',
|
||||
result,
|
||||
error: '',
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = error && error.message ? error.message : `${error}`;
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: 'failed',
|
||||
progress: 100,
|
||||
message: '货主侧收货单导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询货主侧收货单导出任务进度。
|
||||
* 复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。
|
||||
* @param {Object} data 请求体
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async storeExportTaskProgress(data = {}) {
|
||||
return this.exportTaskProgress(data);
|
||||
}
|
||||
|
||||
}
|
||||
module.exports = configService;
|
||||
|
||||
@ -4727,14 +4727,14 @@ class ReceivingService extends Service {
|
||||
const { Op } = Sequelize;
|
||||
const safeOptions = options && typeof options === 'object' ? options : {};
|
||||
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
|
||||
const storeId = Number(safeOptions.storeId);
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
|
||||
const progressHandler = typeof safeOptions.onProgress === 'function'
|
||||
? safeOptions.onProgress
|
||||
: async () => {};
|
||||
|
||||
if (!storeId) {
|
||||
throw new Error('货主ID不能为空,无法导出');
|
||||
if (!warehouseId) {
|
||||
throw new Error('用户未绑定仓库,无法导出');
|
||||
}
|
||||
|
||||
const sortField = sort.sortField || 'created_at';
|
||||
@ -4744,24 +4744,27 @@ class ReceivingService extends Service {
|
||||
];
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
|
||||
|
||||
// 构建 where 条件(与 getStoreReceivingList 一致)
|
||||
// 构建 where 条件(与 getReceivingList 一致,按仓库维度)
|
||||
const queryOptions = {
|
||||
where: { [Op.and]: [{ store_id: storeId }] },
|
||||
where: { [Op.and]: [{ warehouse_id: warehouseId }] },
|
||||
};
|
||||
|
||||
const normalizedWhere = { ...where };
|
||||
const parsed = parseWhereConditions({
|
||||
where: normalizedWhere,
|
||||
app,
|
||||
specialFieldMap: {
|
||||
quickWhere: { bucket: 'quick' },
|
||||
},
|
||||
});
|
||||
let parsedResult = ctx.whereParsed;
|
||||
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
|
||||
const parsed = parseWhereConditions({
|
||||
where: normalizedWhere,
|
||||
app,
|
||||
specialFieldMap: {
|
||||
quickWhere: { bucket: 'quick' },
|
||||
},
|
||||
});
|
||||
|
||||
if (!parsed.ok) {
|
||||
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
|
||||
if (!parsed.ok) {
|
||||
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
|
||||
}
|
||||
parsedResult = parsed.result;
|
||||
}
|
||||
const parsedResult = parsed.result;
|
||||
|
||||
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
|
||||
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||||
@ -5089,7 +5092,438 @@ class ReceivingService extends Service {
|
||||
|
||||
const stat = await fsp.stat(filePath);
|
||||
const randomToken = crypto.randomBytes(6).toString('hex');
|
||||
const uploadKey = `exports/receiving/${storeId}/${Date.now()}_${randomToken}.xlsx`;
|
||||
const uploadKey = `exports/receiving/${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}条收货单`,
|
||||
});
|
||||
}
|
||||
|
||||
// 清理临时文件
|
||||
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (_) { /* ignore */ }
|
||||
|
||||
const uploadInfo = fileRecord || uploadResult;
|
||||
const fileUrl = typeof uploadInfo === 'object' && uploadInfo.url
|
||||
? uploadInfo.url
|
||||
: (typeof uploadResult === 'object' ? uploadResult.fileName : '');
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 100,
|
||||
message: '导出完成',
|
||||
result: { url: fileUrl, fileKey: uploadKey, total: totalCount },
|
||||
});
|
||||
|
||||
return {
|
||||
url: fileUrl,
|
||||
fileKey: uploadKey,
|
||||
total: totalCount,
|
||||
totalDetails: allReceivingIds.reduce((sum, rid) => sum + (detailsMap.get(rid) || []).length, 0),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 导出货主侧收货单列表(双 sheet:收货单列表 + 收货单明细)。
|
||||
* 复用 getStoreReceivingList 的筛选与排序语义,以货主 store_id 过滤,分页拉取全量数据后生成 Excel 并上传。
|
||||
* @param {Object} options 导出选项
|
||||
* @param {Object} [options.where] 筛选条件(与 getStoreReceivingList 一致)
|
||||
* @param {number} options.storeId 货主ID
|
||||
* @param {Object} [options.sort] 排序参数
|
||||
* @param {Function} [options.onProgress] 进度回调
|
||||
* @return {Promise<Object>} 上传结果与统计信息
|
||||
*/
|
||||
async exportStoreReceivingList(options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Sequelize } = app;
|
||||
const { Op } = Sequelize;
|
||||
const safeOptions = options && typeof options === 'object' ? options : {};
|
||||
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
|
||||
const storeId = Number(safeOptions.storeId);
|
||||
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
|
||||
const progressHandler = typeof safeOptions.onProgress === 'function'
|
||||
? safeOptions.onProgress
|
||||
: async () => {};
|
||||
|
||||
if (!storeId) {
|
||||
throw new Error('货主ID不能为空,无法导出');
|
||||
}
|
||||
|
||||
const sortField = sort.sortField || 'created_at';
|
||||
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
const validSortFields = [
|
||||
'id', 'receiving_number', 'status', 'created_at', 'updated_at', 'store_id', 'warehouse_id',
|
||||
];
|
||||
const actualSortField = validSortFields.includes(sortField) ? sortField : 'created_at';
|
||||
|
||||
// 构建 where 条件(与 getStoreReceivingList 一致,按货主维度)
|
||||
const queryOptions = {
|
||||
where: { [Op.and]: [{ store_id: storeId }] },
|
||||
};
|
||||
|
||||
const normalizedWhere = { ...where };
|
||||
let parsedResult = ctx.whereParsed;
|
||||
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
|
||||
const parsed = parseWhereConditions({
|
||||
where: normalizedWhere,
|
||||
app,
|
||||
specialFieldMap: {
|
||||
quickWhere: { bucket: 'quick' },
|
||||
},
|
||||
});
|
||||
|
||||
if (!parsed.ok) {
|
||||
throw new Error(`筛选条件解析失败: ${parsed.reason}`);
|
||||
}
|
||||
parsedResult = parsed.result;
|
||||
}
|
||||
|
||||
const dynamicConditions = [ ...(parsedResult.dynamicConditions || []) ];
|
||||
const quickWhereRaw = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||||
|| normalizedWhere.quickWhere;
|
||||
|
||||
if (quickWhereRaw && quickWhereRaw.value && String(quickWhereRaw.value).trim() !== '') {
|
||||
const quickValue = String(quickWhereRaw.value).trim();
|
||||
dynamicConditions.push({
|
||||
[Op.or]: {
|
||||
store_name: { [Op.like]: `%${quickValue}%` },
|
||||
receiving_number: { [Op.like]: `%${quickValue}%` },
|
||||
tracking_number: { [Op.like]: `%${quickValue}%` },
|
||||
creator_snapshot: { [Op.like]: `%${quickValue}%` },
|
||||
license_plate: { [Op.like]: `%${quickValue}%` },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (dynamicConditions.length > 0) {
|
||||
queryOptions.where[Op.and].push({ [Op.and]: dynamicConditions });
|
||||
}
|
||||
|
||||
// ---- 分页拉取收货单列表 ----
|
||||
const RECEIVING_EXPORT_PAGE_SIZE = 200;
|
||||
const RECEIVING_ITEMS_FETCH_BATCH_SIZE = 50;
|
||||
|
||||
const totalCount = await ctx.model.Receiving.count({
|
||||
where: queryOptions.where,
|
||||
distinct: true,
|
||||
});
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: totalCount > 0 ? 10 : 85,
|
||||
message: totalCount > 0 ? `已命中 ${totalCount} 条收货单,开始导出` : '未命中数据,开始生成空文件',
|
||||
});
|
||||
|
||||
const allReceivingOrders = [];
|
||||
let page = 1;
|
||||
let fetchedCount = 0;
|
||||
|
||||
while (fetchedCount < totalCount) {
|
||||
const rows = await ctx.model.Receiving.findAll({
|
||||
where: queryOptions.where,
|
||||
order: [[ actualSortField, sortOrder ]],
|
||||
limit: RECEIVING_EXPORT_PAGE_SIZE,
|
||||
offset: (page - 1) * RECEIVING_EXPORT_PAGE_SIZE,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
allReceivingOrders.push(...rows);
|
||||
fetchedCount += rows.length;
|
||||
page += 1;
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(30, 10 + Math.round((fetchedCount / Math.max(totalCount, 1)) * 20)),
|
||||
message: `正在拉取收货单列表,已完成 ${fetchedCount}/${totalCount}`,
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 批量拉取收货单明细 ----
|
||||
const allReceivingIds = allReceivingOrders.map(r => Number(r.id)).filter(Boolean);
|
||||
/** @type {Map<number, Array<Object>>} receiving_id → details */
|
||||
const detailsMap = new Map();
|
||||
|
||||
if (allReceivingIds.length > 0) {
|
||||
const batchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
|
||||
const totalBatches = Math.ceil(allReceivingIds.length / batchSize);
|
||||
|
||||
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += batchSize) {
|
||||
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + batchSize);
|
||||
|
||||
const details = await ctx.model.ReceivingDetail.findAll({
|
||||
where: { receiving_id: { [Op.in]: batchIds } },
|
||||
order: [[ 'receiving_id', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
for (const detail of details) {
|
||||
const rid = Number(detail.receiving_id);
|
||||
if (!detailsMap.has(rid)) {
|
||||
detailsMap.set(rid, []);
|
||||
}
|
||||
detailsMap.get(rid).push(detail);
|
||||
}
|
||||
|
||||
const currentBatch = Math.floor(batchIdx / batchSize) + 1;
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(50, 30 + Math.round((currentBatch / totalBatches) * 20)),
|
||||
message: `正在拉取收货单明细,已完成批次 ${currentBatch}/${totalBatches}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 55,
|
||||
message: '正在生成 Excel 文件...',
|
||||
});
|
||||
|
||||
// ---- 生成 Excel(流式写入,两个 Sheet) ----
|
||||
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-receiving-store-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 statusLabelMap = {
|
||||
receiving: '收货中',
|
||||
completed: '已完成',
|
||||
cancelled: '已作废',
|
||||
};
|
||||
|
||||
const detailStatusLabelMap = {
|
||||
all_matched: '全部匹配',
|
||||
partial_matched: '部分匹配',
|
||||
unmatched: '未匹配',
|
||||
};
|
||||
|
||||
const storageStatusLabelMap = {
|
||||
none: '未入库',
|
||||
waiting: '等待入库',
|
||||
partial: '部分入库',
|
||||
all: '全部入库',
|
||||
};
|
||||
|
||||
const deliveryMethodLabelMap = {
|
||||
truck: '货车',
|
||||
express: '快递',
|
||||
air_freight: '空运',
|
||||
sea_freight: '海运',
|
||||
other: '其他',
|
||||
};
|
||||
|
||||
const loadingMethodLabelMap = {
|
||||
with_pallet: '带托盘',
|
||||
without_pallet: '不带托盘',
|
||||
};
|
||||
|
||||
// Sheet 1: 收货单列表
|
||||
const sheet1 = workbook.addWorksheet('收货单列表');
|
||||
const receivingColumns = [
|
||||
{ header: '收货单ID', key: 'id', width: 10 },
|
||||
{ header: '收货单号', key: 'receiving_number', width: 22 },
|
||||
{ header: '货主', key: 'store_name', width: 20 },
|
||||
{ header: '收货状态', key: 'status_label', width: 12 },
|
||||
{ header: '明细匹配状态', key: 'detail_status_label', width: 14 },
|
||||
{ header: '入库状态', key: 'storage_status_label', width: 12 },
|
||||
{ header: '来货方式', key: 'delivery_method_label', width: 12 },
|
||||
{ header: '车牌号', key: 'license_plate', width: 14 },
|
||||
{ header: '快递单号', key: 'tracking_number', width: 22 },
|
||||
{ header: '装卸方式', key: 'loading_method_label', width: 12 },
|
||||
{ header: '总商品种类', key: 'total_items', width: 12 },
|
||||
{ header: '总数量', key: 'total_quantity', width: 12 },
|
||||
{ header: '总箱数', key: 'total_boxes', width: 10 },
|
||||
{ header: '总托盘数', key: 'total_pallets', width: 10 },
|
||||
{ header: '审核状态', key: 'is_review_label', width: 10 },
|
||||
{ header: '创建人', key: 'creator_name', width: 14 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
{ header: '收货开始时间', key: 'receiving_start_time', width: 20 },
|
||||
{ header: '收货结束时间', key: 'receiving_end_time', width: 20 },
|
||||
{ header: '创建时间', key: 'created_at', width: 20 },
|
||||
{ header: '更新时间', key: 'updated_at', width: 20 },
|
||||
];
|
||||
sheet1.columns = receivingColumns;
|
||||
|
||||
for (const row of allReceivingOrders) {
|
||||
let creatorName = '';
|
||||
try {
|
||||
if (row.creator_snapshot) {
|
||||
const snapshot = JSON.parse(row.creator_snapshot);
|
||||
creatorName = snapshot.name || '';
|
||||
}
|
||||
} catch (_) { /* ignore */ }
|
||||
|
||||
sheet1.addRow({
|
||||
id: row.id,
|
||||
receiving_number: normalizeCellValue(row.receiving_number),
|
||||
store_name: normalizeCellValue(row.store_name),
|
||||
status_label: statusLabelMap[row.status] || row.status || '',
|
||||
detail_status_label: detailStatusLabelMap[row.detail_status] || row.detail_status || '',
|
||||
storage_status_label: storageStatusLabelMap[row.storage_status] || row.storage_status || '',
|
||||
delivery_method_label: deliveryMethodLabelMap[row.delivery_method] || row.delivery_method || '',
|
||||
license_plate: normalizeCellValue(row.license_plate),
|
||||
tracking_number: normalizeCellValue(row.tracking_number),
|
||||
loading_method_label: loadingMethodLabelMap[row.loading_method] || row.loading_method || '',
|
||||
total_items: row.total_items,
|
||||
total_quantity: row.total_quantity,
|
||||
total_boxes: row.total_boxes,
|
||||
total_pallets: row.total_pallets,
|
||||
is_review_label: row.is_review === 1 ? '已审核' : '未审核',
|
||||
creator_name: creatorName,
|
||||
remark: normalizeCellValue(row.remark),
|
||||
receiving_start_time: normalizeCellValue(row.receiving_start_time),
|
||||
receiving_end_time: normalizeCellValue(row.receiving_end_time),
|
||||
created_at: normalizeCellValue(row.created_at),
|
||||
updated_at: normalizeCellValue(row.updated_at),
|
||||
}).commit();
|
||||
}
|
||||
sheet1.commit();
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 70,
|
||||
message: '正在写入收货单明细...',
|
||||
});
|
||||
|
||||
// Sheet 2: 收货单明细
|
||||
const sheet2 = workbook.addWorksheet('收货单明细');
|
||||
const detailColumns = [
|
||||
{ header: '收货单号', key: 'receiving_number', width: 22 },
|
||||
{ header: '收货单ID', key: 'receiving_id', width: 12 },
|
||||
{ header: '明细ID', key: 'detail_id', width: 10 },
|
||||
{ header: '商品名称', key: 'product_name', width: 28 },
|
||||
{ header: '商品条码', key: 'barcode', width: 20 },
|
||||
{ header: '系统商品ID', key: 'system_product_id', width: 14 },
|
||||
{ header: '实际收货数量', key: 'actual_quantity', width: 14 },
|
||||
{ header: '箱数', key: 'box_quantity', width: 10 },
|
||||
{ header: '托盘数', key: 'pallet_quantity', width: 10 },
|
||||
{ header: '收货状态', key: 'receiving_status_label', width: 12 },
|
||||
{ header: '入库状态', key: 'storage_status_label', width: 12 },
|
||||
{ header: '已入库数量', key: 'stored_quantity', width: 12 },
|
||||
{ header: '批次号', key: 'batch_number', width: 16 },
|
||||
{ header: '生产日期', key: 'production_date', width: 14 },
|
||||
{ header: '到期日期', key: 'expiry_date', width: 14 },
|
||||
{ header: '备注', key: 'remark', width: 30 },
|
||||
{ header: '创建时间', key: 'created_at', width: 20 },
|
||||
];
|
||||
sheet2.columns = detailColumns;
|
||||
|
||||
const receivingCodeMap = new Map();
|
||||
for (const row of allReceivingOrders) {
|
||||
receivingCodeMap.set(Number(row.id), row.receiving_number || '');
|
||||
}
|
||||
|
||||
const detailReceivingStatusLabelMap = {
|
||||
pending: '待收货',
|
||||
receiving: '收货中',
|
||||
completed: '已完成',
|
||||
cancelled: '已作废',
|
||||
};
|
||||
|
||||
const detailStorageStatusLabelMap = {
|
||||
none: '未入库',
|
||||
waiting: '等待入库',
|
||||
partial: '部分入库',
|
||||
all: '全部入库',
|
||||
};
|
||||
|
||||
const itemBatchSize = RECEIVING_ITEMS_FETCH_BATCH_SIZE;
|
||||
let itemWrittenCount = 0;
|
||||
const totalReceivingOrders = allReceivingIds.length;
|
||||
|
||||
for (let batchIdx = 0; batchIdx < allReceivingIds.length; batchIdx += itemBatchSize) {
|
||||
const batchIds = allReceivingIds.slice(batchIdx, batchIdx + itemBatchSize);
|
||||
|
||||
for (const rid of batchIds) {
|
||||
const receivingNumber = receivingCodeMap.get(rid) || '';
|
||||
const details = detailsMap.get(rid) || [];
|
||||
|
||||
for (const detail of details) {
|
||||
sheet2.addRow({
|
||||
receiving_number: receivingNumber,
|
||||
receiving_id: rid,
|
||||
detail_id: detail.id,
|
||||
product_name: normalizeCellValue(detail.product_name),
|
||||
barcode: normalizeCellValue(detail.barcode),
|
||||
system_product_id: normalizeCellValue(detail.system_product_id),
|
||||
actual_quantity: detail.actual_quantity,
|
||||
box_quantity: detail.box_quantity,
|
||||
pallet_quantity: detail.pallet_quantity,
|
||||
receiving_status_label: detailReceivingStatusLabelMap[detail.receiving_status] || detail.receiving_status || '',
|
||||
storage_status_label: detailStorageStatusLabelMap[detail.storage_status] || detail.storage_status || '',
|
||||
stored_quantity: detail.stored_quantity,
|
||||
batch_number: normalizeCellValue(detail.batch_number),
|
||||
production_date: normalizeCellValue(detail.production_date),
|
||||
expiry_date: normalizeCellValue(detail.expiry_date),
|
||||
remark: normalizeCellValue(detail.remark),
|
||||
created_at: normalizeCellValue(detail.created_at),
|
||||
}).commit();
|
||||
}
|
||||
|
||||
itemWrittenCount += 1;
|
||||
}
|
||||
|
||||
const currentBatch = Math.floor(batchIdx / itemBatchSize) + 1;
|
||||
const totalBatches = Math.ceil(totalReceivingOrders / itemBatchSize);
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: Math.min(90, 70 + Math.round((currentBatch / totalBatches) * 20)),
|
||||
message: `正在写入收货单明细,已完成 ${itemWrittenCount}/${totalReceivingOrders} 条收货单`,
|
||||
});
|
||||
}
|
||||
sheet2.commit();
|
||||
|
||||
await workbook.commit();
|
||||
|
||||
await progressHandler({
|
||||
status: 'running',
|
||||
progress: 92,
|
||||
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/receiving/store/${storeId}/${Date.now()}_${randomToken}.xlsx`;
|
||||
const uploadStream = fs.createReadStream(filePath);
|
||||
uploadStream.filename = filename;
|
||||
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||||
|
||||
@ -27761,6 +27761,328 @@
|
||||
"message": "服务器扫描查询失败"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "storage.receiving.export",
|
||||
"description": "提交收货单导出任务(仓库维度,异步)。导出为 Excel 文件,包含两个 Sheet:Sheet1=收货单列表(ID/单号/货主/状态/明细匹配状态/入库状态/来货方式/车牌号/快递单号/装卸方式/商品种类/总数量/总箱数/总托盘数/审核状态/创建人/备注/收货时间/创建时间/更新时间),Sheet2=收货单明细(收货单号/收货单ID/明细ID/商品名称/商品条码/系统商品ID/实收数量/箱数/托盘数/收货状态/入库状态/已入库数量/批次号/生产日期/到期日期/备注/创建时间)。筛选和排序规则与 getReceivingList 一致,按当前仓库维度(ctx.user.store_id)过滤。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "where",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "筛选条件(与 getReceivingList 一致),支持 quickWhere(模糊搜索收货单号/货主名称/快递单号/创建人/车牌号)等字段"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "排序参数,支持 sortField(id/receiving_number/status/created_at/updated_at/store_id/warehouse_id)和 sortOrder(ASC/DESC),默认按 created_at DESC"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "导出任务ID,用于轮询进度"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "任务进度,0-100"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态描述"
|
||||
},
|
||||
{
|
||||
"name": "result",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)"
|
||||
},
|
||||
{
|
||||
"name": "error",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "错误信息(failed 时返回)"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "状态更新时间戳(毫秒)"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 0,
|
||||
"message": "用户未绑定仓库"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "storage.receiving.exportTaskProgress",
|
||||
"description": "查询收货单导出任务进度(仓库维度)。提交导出任务后,通过 task_id 轮询此接口获取实时进度和最终下载地址。任务缓存 TTL 为 30 分钟。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出任务ID(下划线写法),与 taskId 二选一"
|
||||
},
|
||||
{
|
||||
"name": "taskId",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出任务ID(驼峰写法),与 task_id 二选一"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "导出任务ID"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败 / not_found-任务不存在"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "任务进度,0-100"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态描述"
|
||||
},
|
||||
{
|
||||
"name": "result",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)"
|
||||
},
|
||||
{
|
||||
"name": "error",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "错误信息(failed 时返回)"
|
||||
},
|
||||
{
|
||||
"name": "download_url",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "Excel 文件下载地址(success 时有效)"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "状态更新时间戳(毫秒)"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"method": "storage.receiving.storeExport",
|
||||
"description": "提交货主侧收货单导出任务(货主维度,异步)。以当前平台激活的货主 store_id 为维度导出。导出为 Excel 文件,包含两个 Sheet:Sheet1=收货单列表,Sheet2=收货单明细(字段同 export)。筛选和排序规则与 getStoreReceivingList 一致,需当前用户已切换至货主角色。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "where",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "筛选条件(与 getStoreReceivingList 一致),支持 quickWhere(模糊搜索收货单号/货主名称/快递单号/创建人/车牌号)等字段"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "排序参数,支持 sortField(id/receiving_number/status/created_at/updated_at/store_id/warehouse_id)和 sortOrder(ASC/DESC),默认按 created_at DESC"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "导出任务ID,用于轮询进度"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "任务进度,0-100"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态描述"
|
||||
},
|
||||
{
|
||||
"name": "result",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)"
|
||||
},
|
||||
{
|
||||
"name": "error",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "错误信息(failed 时返回)"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "状态更新时间戳(毫秒)"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 0,
|
||||
"message": "未获取到货主平台激活上下文,请先切换至货主角色"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "storage.receiving.storeExportTaskProgress",
|
||||
"description": "查询货主侧收货单导出任务进度。复用 exportTaskProgress 的缓存查询逻辑,任务 ID 前缀不同。任务缓存 TTL 为 30 分钟。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "Bearer token"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出任务ID(下划线写法),与 taskId 二选一"
|
||||
},
|
||||
{
|
||||
"name": "taskId",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "导出任务ID(驼峰写法),与 task_id 二选一"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "导出任务ID"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态:submitted-已提交 / running-执行中 / success-成功 / failed-失败 / not_found-任务不存在"
|
||||
},
|
||||
{
|
||||
"name": "progress",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "任务进度,0-100"
|
||||
},
|
||||
{
|
||||
"name": "message",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "任务状态描述"
|
||||
},
|
||||
{
|
||||
"name": "result",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "导出结果(success 时包含 url/cdnUrl/cosUrl/fileKey 等下载地址信息)"
|
||||
},
|
||||
{
|
||||
"name": "error",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "错误信息(failed 时返回)"
|
||||
},
|
||||
{
|
||||
"name": "download_url",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "Excel 文件下载地址(success 时有效)"
|
||||
},
|
||||
{
|
||||
"name": "update_time",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "状态更新时间戳(毫秒)"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user