feat(waybill): 新增面单/运单管理模块
- 新增 systems/waybill.js 业务层:运单列表查询/详情/导出 - 新增 systemMethods/waybill/warehouse.js 入口层 - 新增 6 个迁移脚本:面单列表索引、store_id 列、物流编码/名称回填、发货单号列、货主ID回填、发货字段回填 - 更新 waybill-module-design.md 设计文档
This commit is contained in:
parent
76e25db7da
commit
edc164298d
307
app/service/systemMethods/waybill/warehouse.js
Normal file
307
app/service/systemMethods/waybill/warehouse.js
Normal file
@ -0,0 +1,307 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
const WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX = 'waybill_export_task_';
|
||||
|
||||
/**
|
||||
* 运单号仓库侧入口层。
|
||||
* 负责鉴权声明、参数校验,委托 systems/waybill.js 执行业务逻辑。
|
||||
*
|
||||
* 所有方法均需登录但无需细粒度鉴权(与订单列表保持一致)。
|
||||
*/
|
||||
class WaybillWarehouseService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,detail,export,exportTaskProgress';
|
||||
const _noNeedLog = '';
|
||||
const _noNeedAuth = 'list,detail,export,exportTaskProgress';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单列表查询(仓库侧)。
|
||||
* 支持分页、多条件筛选、排序。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {Object} [data.where] 筛选条件。
|
||||
* @param {Object} [data.pagination] 分页参数 { page, pageSize }。
|
||||
* @param {Object} [data.sort] 排序参数 { field, order }。
|
||||
* @return {Promise<Object>} 运单列表与分页信息。
|
||||
*/
|
||||
async list(data) {
|
||||
try {
|
||||
const { where, pagination, sort } = data || {};
|
||||
const result = await this.service.systems.waybill.list({
|
||||
where: where || {},
|
||||
pagination: pagination || {},
|
||||
sort: sort || {},
|
||||
});
|
||||
return this.success('获取成功', result);
|
||||
} catch (e) {
|
||||
return this.fail(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单详情查询(仓库侧)。
|
||||
* 支持按运单ID或运单号查询。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {number} [data.id] 运单记录ID。
|
||||
* @param {string} [data.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。
|
||||
* @return {Promise<Object>} 运单详情(含订单/打印/打包信息)。
|
||||
*/
|
||||
async detail(data) {
|
||||
try {
|
||||
const { id, waybillCode } = data || {};
|
||||
if (!id && !waybillCode) {
|
||||
return this.fail('运单ID或运单号不能为空');
|
||||
}
|
||||
const result = await this.service.systems.waybill.detail({
|
||||
id,
|
||||
waybillCode,
|
||||
});
|
||||
return this.success('获取成功', result);
|
||||
} catch (e) {
|
||||
return this.fail(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单导出(仓库侧)。异步任务模式,提交后通过 exportTaskProgress 查询进度。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {Object} [data.where] 筛选条件(同 list)。
|
||||
* @param {Object} [data.sort] 排序参数(同 list)。
|
||||
* @param {string[]} [data.exportFields] 需要导出的字段列表。
|
||||
* @return {Promise<Object>} 任务提交结果,含 task_id。
|
||||
*/
|
||||
async export(data) {
|
||||
try {
|
||||
const { where, sort, exportFields } = data || {};
|
||||
const taskId = this.generateExportTaskId();
|
||||
|
||||
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 this.service.systems.waybill.export({
|
||||
where: where || {},
|
||||
sort: sort || {},
|
||||
exportFields,
|
||||
onProgress: async progress => {
|
||||
const safeProgress = this.isPlainObject(progress) ? progress : {};
|
||||
await this.setExportTaskProgress(taskId, {
|
||||
task_id: taskId,
|
||||
status: safeProgress.status || 'running',
|
||||
progress: safeProgress.progress || 0,
|
||||
current_count: safeProgress.currentCount || safeProgress.current_count || 0,
|
||||
total_count: safeProgress.totalCount || safeProgress.total_count || 0,
|
||||
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,
|
||||
message: '导出任务失败',
|
||||
result: null,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return this.success('ok', {
|
||||
...taskPayload,
|
||||
update_time: Date.now(),
|
||||
});
|
||||
} catch (e) {
|
||||
return this.fail(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询运单导出任务进度。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @param {string} [data.task_id] 任务ID(下划线写法)。
|
||||
* @param {string} [data.taskId] 任务ID(驼峰写法)。
|
||||
* @return {Promise<Object>} 任务进度信息。
|
||||
*/
|
||||
async exportTaskProgress(data = {}) {
|
||||
try {
|
||||
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.cndUrl
|
||||
|| safeResult.cdnUrl
|
||||
|| safeResult.cosUrl
|
||||
|| safeResult.fileKey
|
||||
|| ''
|
||||
);
|
||||
|
||||
return this.success('ok', {
|
||||
task_id: taskId,
|
||||
...cachedTask,
|
||||
download_url: downloadUrl,
|
||||
});
|
||||
} catch (e) {
|
||||
return this.fail(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 导出任务辅助方法 ====================
|
||||
|
||||
/**
|
||||
* 生成运单导出任务ID。
|
||||
* @return {string} 任务ID。
|
||||
*/
|
||||
generateExportTaskId() {
|
||||
const warehouseId = this.ctx?.user?.store_id || 'unknown';
|
||||
const timestamp = Date.now();
|
||||
const randomToken = Math.random().toString(36).slice(2, 10);
|
||||
return `waybill_export_${warehouseId}_${timestamp}_${randomToken}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 规范导出任务ID。
|
||||
* @param {Object} data 请求体。
|
||||
* @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 `${WAYBILL_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入运单导出任务进度缓存。
|
||||
* @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 || ''),
|
||||
};
|
||||
|
||||
await this.app.setCacheAsync(cacheKey, progressPayload);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取运单导出任务进度缓存。
|
||||
* @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;
|
||||
}
|
||||
return await this.app.getCacheAsync(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillWarehouseService;
|
||||
@ -1,6 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
const ExcelJS = require('exceljs');
|
||||
const fs = require('fs');
|
||||
const fsp = require('fs').promises;
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
|
||||
/**
|
||||
* 业务逻辑层:waybill(运单号快速查询)。
|
||||
@ -131,6 +136,895 @@ class WaybillService extends MainService {
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单列表查询(仓库侧)。
|
||||
* 按仓库维度查询运单号列表,支持分页、多条件筛选、排序。
|
||||
* 核心查询仅使用 wms_order_express 单表(利用快照字段),
|
||||
* 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。
|
||||
*
|
||||
* @param {Object} [options={}] 查询参数。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAtStart / createdAtEnd。
|
||||
* @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。
|
||||
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
|
||||
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
|
||||
*/
|
||||
async list({ where = {}, pagination = {}, sort = {} } = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// 仓库隔离
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
this.throwError('用户未绑定仓库,无法查询运单');
|
||||
}
|
||||
|
||||
// 分页参数
|
||||
const page = Math.max(Number(pagination.page) || 1, 1);
|
||||
const pageSize = Math.min(Math.max(Number(pagination.pageSize) || 20, 1), 500);
|
||||
|
||||
// 排序参数
|
||||
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
|
||||
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
|
||||
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
// 构建查询条件
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
|
||||
// 主单号查询:先通过主单号定位 order_id,再查该 order 下所有运单
|
||||
if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) {
|
||||
const mainCode = String(where.mainWaybillCode).trim();
|
||||
const mainRecord = await ctx.model.OrderExpress.findOne({
|
||||
where: {
|
||||
waybill_code: mainCode,
|
||||
business_key: 1,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (mainRecord) {
|
||||
queryWhere.order_id = mainRecord.order_id;
|
||||
} else {
|
||||
// 主单号不存在,直接返回空结果
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: 0, totalPages: 0 },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 运单号模糊搜索
|
||||
if (where.waybillCode && String(where.waybillCode).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` };
|
||||
}
|
||||
|
||||
// 订单ID等值
|
||||
if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') {
|
||||
queryWhere.order_id = Number(where.orderId);
|
||||
}
|
||||
|
||||
// 订单号模糊搜索
|
||||
// TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释
|
||||
// if (where.orderNo && String(where.orderNo).trim()) {
|
||||
// queryWhere.delivery_order_code = { [Op.like]: `%${String(where.orderNo).trim()}%` };
|
||||
// }
|
||||
|
||||
// 物流公司编码等值
|
||||
if (where.logisticsCode && String(where.logisticsCode).trim()) {
|
||||
queryWhere.logistics_code = String(where.logisticsCode).trim();
|
||||
}
|
||||
|
||||
// 物流接口ID等值
|
||||
if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') {
|
||||
queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId);
|
||||
}
|
||||
|
||||
// 平台编码等值
|
||||
if (where.platformCode && String(where.platformCode).trim()) {
|
||||
queryWhere.platform_code = String(where.platformCode).trim();
|
||||
}
|
||||
|
||||
// 运单状态等值
|
||||
if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') {
|
||||
queryWhere.status = Number(where.status);
|
||||
}
|
||||
|
||||
// 是否退回
|
||||
if (where.isBack && String(where.isBack).trim()) {
|
||||
queryWhere.is_back = String(where.isBack).trim();
|
||||
}
|
||||
|
||||
// 是否拦截
|
||||
if (where.isIntercept && String(where.isIntercept).trim()) {
|
||||
queryWhere.is_intercept = String(where.isIntercept).trim();
|
||||
}
|
||||
|
||||
// 是否揽收
|
||||
if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) {
|
||||
queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim();
|
||||
}
|
||||
|
||||
// 运单类型:主单号 / 子单号
|
||||
if (where.waybillType && String(where.waybillType).trim()) {
|
||||
const type = String(where.waybillType).trim();
|
||||
if (type === 'main' || type === '1') {
|
||||
queryWhere.business_key = 1;
|
||||
} else if (type === 'child' || type === '2') {
|
||||
queryWhere.business_key = { [Op.gt]: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
// 货主ID等值
|
||||
if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') {
|
||||
queryWhere.store_id = Number(where.storeId);
|
||||
}
|
||||
|
||||
// 包材ID等值
|
||||
if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') {
|
||||
queryWhere.package_material_id = Number(where.packageMaterialId);
|
||||
}
|
||||
|
||||
// 是否已称重
|
||||
if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') {
|
||||
const hasWeight = String(where.hasWeighingWeight).trim();
|
||||
if (hasWeight === 'true') {
|
||||
queryWhere.weighing_weight = { [Op.gt]: 0 };
|
||||
} else if (hasWeight === 'false') {
|
||||
queryWhere.weighing_weight = { [Op.eq]: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
// 关键词模糊搜索
|
||||
if (where.keyword && String(where.keyword).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` };
|
||||
}
|
||||
|
||||
// 创建时间范围
|
||||
if (where.createdAtStart && String(where.createdAtStart).trim()) {
|
||||
const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false);
|
||||
if (startDate) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
|
||||
}
|
||||
}
|
||||
if (where.createdAtEnd && String(where.createdAtEnd).trim()) {
|
||||
const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true);
|
||||
if (endDate) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
|
||||
}
|
||||
}
|
||||
|
||||
// 核心查询:仅查 wms_order_express 单表
|
||||
// TODO: warehouse_name_snapshot / store_id_snapshot / store_name_snapshot / delivery_order_code
|
||||
// 快照列未落库,暂时只查已有字段;快照列就绪后替换为快照直读
|
||||
const { count, rows } = await ctx.model.OrderExpress.findAndCountAll({
|
||||
where: queryWhere,
|
||||
attributes: [
|
||||
'id', 'waybill_code', 'order_id', 'business_key', 'status',
|
||||
'warehouse_id', 'store_id',
|
||||
'logistics_code', 'logistics_name',
|
||||
'logistics_interface_id', 'logistics_interface_name',
|
||||
'platform_code',
|
||||
'is_back', 'is_intercept', 'is_galaxy_receive',
|
||||
'weighing_weight',
|
||||
'package_material_id', 'package_material_name_snapshot',
|
||||
'create_at',
|
||||
],
|
||||
order: [[ sortField, sortOrder ]],
|
||||
limit: pageSize,
|
||||
offset: (page - 1) * pageSize,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (rows.length === 0) {
|
||||
return {
|
||||
list: [],
|
||||
pagination: { page, pageSize, total: count, totalPages: Math.ceil(count / pageSize) },
|
||||
};
|
||||
}
|
||||
|
||||
// 提取所有唯一的 order_id
|
||||
const orderIds = [ ...new Set(rows.map(r => r.order_id).filter(Boolean)) ];
|
||||
|
||||
// SELF JOIN:查询同 order_id 下 business_key=1 的主单号
|
||||
const mainWaybillMap = new Map();
|
||||
if (orderIds.length > 0) {
|
||||
const mainRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
business_key: 1,
|
||||
},
|
||||
attributes: [ 'order_id', 'waybill_code' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const rec of mainRecords) {
|
||||
if (!mainWaybillMap.has(rec.order_id)) {
|
||||
mainWaybillMap.set(rec.order_id, rec.waybill_code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 提取运单号列表,用于查询打印信息
|
||||
const waybillCodes = rows.map(r => r.waybill_code).filter(Boolean);
|
||||
|
||||
// 查询货主备注名称(store_warehouse.store_remask)
|
||||
const storeRemarkMap = new Map();
|
||||
const storeWarehouseKeys = rows
|
||||
.filter(r => r.store_id && r.warehouse_id)
|
||||
.map(r => `${r.store_id}:${r.warehouse_id}`);
|
||||
const uniqueKeys = [ ...new Set(storeWarehouseKeys) ];
|
||||
if (uniqueKeys.length > 0 && ctx.model.StoreWarehouse) {
|
||||
const swConditions = uniqueKeys.map(key => {
|
||||
const [ storeId, whId ] = key.split(':');
|
||||
return { store_id: Number(storeId), warehouse_id: Number(whId) };
|
||||
});
|
||||
const swRows = await ctx.model.StoreWarehouse.findAll({
|
||||
where: { [Op.or]: swConditions },
|
||||
attributes: [ 'store_id', 'warehouse_id', 'store_remask' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const sw of swRows) {
|
||||
storeRemarkMap.set(`${sw.store_id}:${sw.warehouse_id}`, sw.store_remask || '');
|
||||
}
|
||||
}
|
||||
|
||||
// 查询打印记录(次数和最近打印时间)
|
||||
const printInfoMap = new Map();
|
||||
if (waybillCodes.length > 0) {
|
||||
const printRecords = await ctx.model.ExpressPrintRecord.findAll({
|
||||
where: { express_no: { [Op.in]: waybillCodes } },
|
||||
attributes: [
|
||||
'express_no',
|
||||
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'print_count' ],
|
||||
[ app.Sequelize.fn('MAX', app.Sequelize.col('print_time')), 'last_print_at' ],
|
||||
],
|
||||
group: [ 'express_no' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const pr of printRecords) {
|
||||
printInfoMap.set(pr.express_no, {
|
||||
print_count: Number(pr.print_count) || 0,
|
||||
last_print_at: pr.last_print_at || null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 组装响应列表
|
||||
const list = rows.map(row => {
|
||||
const wbCode = row.waybill_code || '';
|
||||
const mainCode = mainWaybillMap.get(row.order_id) || wbCode;
|
||||
const printInfo = printInfoMap.get(wbCode) || { print_count: 0, last_print_at: null };
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
waybill_code: wbCode,
|
||||
main_waybill_code: mainCode,
|
||||
waybill_type: Number(row.business_key) === 1 ? '主单号' : '子单号',
|
||||
order_id: row.order_id,
|
||||
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.delivery_order_code
|
||||
order_no: '',
|
||||
warehouse_id: row.warehouse_id,
|
||||
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.warehouse_name_snapshot
|
||||
warehouse_name: '',
|
||||
store_id: row.store_id || 0,
|
||||
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 row.store_name_snapshot
|
||||
store_name: '',
|
||||
store_remark_name: storeRemarkMap.get(`${row.store_id}:${row.warehouse_id}`) || '',
|
||||
business_key: row.business_key,
|
||||
status: row.status,
|
||||
status_text: row.status === 1 ? '已分配' : '未分配',
|
||||
logistics_code: row.logistics_code || '',
|
||||
logistics_name: row.logistics_name || '',
|
||||
logistics_interface_id: row.logistics_interface_id || 0,
|
||||
logistics_interface_name: row.logistics_interface_name || '',
|
||||
platform_code: row.platform_code || '',
|
||||
is_back: row.is_back || 'N',
|
||||
is_intercept: row.is_intercept || 'N',
|
||||
is_galaxy_receive: row.is_galaxy_receive || 'N',
|
||||
weighing_weight: row.weighing_weight || 0,
|
||||
weighing_weight_display: row.weighing_weight > 0 ? `${(row.weighing_weight / 1000).toFixed(2)} kg` : '0 kg',
|
||||
package_material_id: row.package_material_id || 0,
|
||||
package_material_name: row.package_material_name_snapshot || '',
|
||||
print_count: printInfo.print_count,
|
||||
last_print_at: printInfo.last_print_at ? this.app.formatDate(printInfo.last_print_at) : null,
|
||||
create_at: row.create_at ? this.app.formatDate(row.create_at) : null,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
list,
|
||||
pagination: {
|
||||
page,
|
||||
pageSize,
|
||||
total: count,
|
||||
totalPages: Math.ceil(count / pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单详情查询(仓库侧)。
|
||||
* 查询单个运单的完整信息,包含关联订单、兄弟运单、打印记录、打包信息。
|
||||
*
|
||||
* @param {Object} options 查询参数。
|
||||
* @param {number} [options.id] 运单记录ID。
|
||||
* @param {string} [options.waybillCode] 运单号(与 id 二选一,waybillCode 优先)。
|
||||
* @return {Promise<Object>} 运单详情。
|
||||
* @throws {Error} 当运单不存在或参数无效时抛出业务错误。
|
||||
*/
|
||||
async detail({ id, waybillCode } = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
// 仓库隔离
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
this.throwError('用户未绑定仓库,无法查询运单');
|
||||
}
|
||||
|
||||
// 构建查询条件
|
||||
const expressWhere = { warehouse_id: warehouseId };
|
||||
if (waybillCode && String(waybillCode).trim()) {
|
||||
expressWhere.waybill_code = String(waybillCode).trim();
|
||||
} else if (id !== undefined && id !== null && String(id).trim() !== '') {
|
||||
expressWhere.id = Number(id);
|
||||
} else {
|
||||
this.throwError('运单ID或运单号不能为空');
|
||||
}
|
||||
|
||||
// 查询运单主记录
|
||||
const record = await ctx.model.OrderExpress.findOne({
|
||||
where: expressWhere,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!record) {
|
||||
this.throwError('未找到该运单');
|
||||
}
|
||||
|
||||
const orderId = record.order_id;
|
||||
|
||||
// 查询同订单下所有运单(兄弟运单)
|
||||
const siblingWaybills = await ctx.model.OrderExpress.findAll({
|
||||
where: { order_id: orderId, warehouse_id: warehouseId },
|
||||
attributes: [ 'id', 'waybill_code', 'business_key' ],
|
||||
order: [[ 'business_key', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const mainWaybillRecord = siblingWaybills.find(s => Number(s.business_key) === 1);
|
||||
const mainWaybillCode = mainWaybillRecord ? mainWaybillRecord.waybill_code : (record.waybill_code || '');
|
||||
|
||||
const siblingList = siblingWaybills.map(s => ({
|
||||
waybill_code: s.waybill_code || '',
|
||||
business_key: s.business_key,
|
||||
waybill_type: Number(s.business_key) === 1 ? '主单号' : '子单号',
|
||||
}));
|
||||
|
||||
// 通过 OrderDeliveryFactory 多表遍历查询订单信息
|
||||
const orderDeliveryFactory = ctx.model && ctx.model.OrderDeliveryFactory;
|
||||
let orderInfo = null;
|
||||
if (orderDeliveryFactory && typeof orderDeliveryFactory.getCurrentModel === 'function') {
|
||||
const tableOrders = [
|
||||
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
|
||||
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
|
||||
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
|
||||
];
|
||||
|
||||
for (const entry of tableOrders) {
|
||||
try {
|
||||
const model = await entry.getModel();
|
||||
if (!model || typeof model.findOne !== 'function') {
|
||||
continue;
|
||||
}
|
||||
const row = await model.findOne({
|
||||
where: { id: orderId, warehouse_id: warehouseId },
|
||||
attributes: [
|
||||
'id', 'delivery_order_code', 'warehouse_id', 'store_id',
|
||||
'wave_id', 'wave_no', 'order_type', 'store_name',
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
if (row) {
|
||||
orderInfo = {
|
||||
order_id: row.id,
|
||||
order_no: row.delivery_order_code || '',
|
||||
warehouse_id: row.warehouse_id,
|
||||
// TODO: 快照列未落库,暂时填空;快照就绪后替换为 record.warehouse_name_snapshot
|
||||
warehouse_name: '',
|
||||
store_id: row.store_id || 0,
|
||||
store_name: row.store_name || '',
|
||||
wave_id: row.wave_id || 0,
|
||||
wave_no: row.wave_no || '',
|
||||
order_type: row.order_type || 'delivery',
|
||||
};
|
||||
break;
|
||||
}
|
||||
} catch (_err) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 若遍历失败,用已有信息兜底
|
||||
// TODO: 快照列未落库,暂用空值兜底;快照就绪后替换为 record.xxx_snapshot
|
||||
if (!orderInfo) {
|
||||
orderInfo = {
|
||||
order_id: orderId,
|
||||
order_no: '',
|
||||
warehouse_id: record.warehouse_id,
|
||||
warehouse_name: '',
|
||||
store_id: 0,
|
||||
store_name: '',
|
||||
wave_id: 0,
|
||||
wave_no: '',
|
||||
order_type: 'delivery',
|
||||
};
|
||||
}
|
||||
|
||||
// 查询打印记录
|
||||
let printRecords = [];
|
||||
if (record.waybill_code) {
|
||||
printRecords = await ctx.model.ExpressPrintRecord.findAll({
|
||||
where: { express_no: record.waybill_code },
|
||||
attributes: [
|
||||
'id', 'printer_name', 'template_id', 'platform',
|
||||
'print_time',
|
||||
],
|
||||
order: [[ 'print_time', 'DESC' ]],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 组装详情响应
|
||||
return {
|
||||
id: record.id,
|
||||
waybill_code: record.waybill_code || '',
|
||||
main_waybill_code: mainWaybillCode,
|
||||
waybill_type: Number(record.business_key) === 1 ? '主单号' : '子单号',
|
||||
business_key: record.business_key,
|
||||
sibling_waybills: siblingList,
|
||||
order: orderInfo,
|
||||
logistics: {
|
||||
logistics_code: record.logistics_code || '',
|
||||
logistics_name: record.logistics_name || '',
|
||||
logistics_interface_id: record.logistics_interface_id || 0,
|
||||
logistics_interface_name: record.logistics_interface_name || '',
|
||||
platform_code: record.platform_code || '',
|
||||
},
|
||||
status_info: {
|
||||
status: record.status,
|
||||
status_text: record.status === 1 ? '已分配' : '未分配',
|
||||
is_back: record.is_back || 'N',
|
||||
is_intercept: record.is_intercept || 'N',
|
||||
is_galaxy_receive: record.is_galaxy_receive || 'N',
|
||||
},
|
||||
weight: {
|
||||
weighing_weight: record.weighing_weight || 0,
|
||||
weighing_weight_display: record.weighing_weight > 0
|
||||
? `${(record.weighing_weight / 1000).toFixed(2)} kg`
|
||||
: '0 kg',
|
||||
},
|
||||
package: {
|
||||
package_material_id: record.package_material_id || 0,
|
||||
package_material_name: record.package_material_name_snapshot || '',
|
||||
},
|
||||
print_records: printRecords.map(pr => ({
|
||||
id: pr.id,
|
||||
printer_name: pr.printer_name || '',
|
||||
template_id: pr.template_id || 0,
|
||||
template_name: '',
|
||||
platform: pr.platform || '',
|
||||
printed_at: pr.print_time ? this.app.formatDate(pr.print_time) : null,
|
||||
})),
|
||||
print_count: printRecords.length,
|
||||
printinfo: record.printinfo || null,
|
||||
ver: record.ver || '',
|
||||
retry_count: record.retry_count || 0,
|
||||
create_at: record.create_at ? this.app.formatDate(record.create_at) : null,
|
||||
delete_at: record.delete_at ? this.app.formatDate(record.delete_at) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 运单导出(仓库侧)。
|
||||
* 复用 list 的筛选逻辑,分批查询,支持进度回调。
|
||||
*
|
||||
* @param {Object} options 导出参数。
|
||||
* @param {Object} [options.where={}] 筛选条件(同 list)。
|
||||
* @param {Object} [options.sort={}] 排序参数(同 list)。
|
||||
* @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。
|
||||
* @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。
|
||||
* @return {Promise<Object>} 导出结果 { list, current_count, total_count, url }。
|
||||
*/
|
||||
async export({ where = {}, sort = {}, exportFields, onProgress } = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
// 仓库隔离
|
||||
const warehouseId = Number(ctx.user && ctx.user.store_id);
|
||||
if (!warehouseId) {
|
||||
this.throwError('用户未绑定仓库,无法导出运单');
|
||||
}
|
||||
|
||||
// 排序参数
|
||||
const allowedSortFields = [ 'create_at', 'weighing_weight', 'id' ];
|
||||
const sortField = allowedSortFields.includes(sort.field) ? sort.field : 'create_at';
|
||||
const sortOrder = sort.order === 'asc' ? 'ASC' : 'DESC';
|
||||
|
||||
// 构建查询条件(同 list)
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
|
||||
// 主单号查询
|
||||
if (where.mainWaybillCode && String(where.mainWaybillCode).trim()) {
|
||||
const mainCode = String(where.mainWaybillCode).trim();
|
||||
const mainRecord = await ctx.model.OrderExpress.findOne({
|
||||
where: {
|
||||
waybill_code: mainCode,
|
||||
business_key: 1,
|
||||
warehouse_id: warehouseId,
|
||||
},
|
||||
attributes: [ 'order_id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (mainRecord) {
|
||||
queryWhere.order_id = mainRecord.order_id;
|
||||
} else {
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
|
||||
}
|
||||
return { list: [], current_count: 0, total_count: 0, url: '' };
|
||||
}
|
||||
}
|
||||
|
||||
if (where.waybillCode && String(where.waybillCode).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(where.waybillCode).trim()}%` };
|
||||
}
|
||||
if (where.orderId !== undefined && where.orderId !== null && String(where.orderId).trim() !== '') {
|
||||
queryWhere.order_id = Number(where.orderId);
|
||||
}
|
||||
// TODO: 快照字段 delivery_order_code 未落库,暂跳过订单号筛选;快照列就绪后取消注释
|
||||
if (where.logisticsCode && String(where.logisticsCode).trim()) {
|
||||
queryWhere.logistics_code = String(where.logisticsCode).trim();
|
||||
}
|
||||
if (where.logisticsInterfaceId !== undefined && where.logisticsInterfaceId !== null && String(where.logisticsInterfaceId).trim() !== '') {
|
||||
queryWhere.logistics_interface_id = Number(where.logisticsInterfaceId);
|
||||
}
|
||||
if (where.platformCode && String(where.platformCode).trim()) {
|
||||
queryWhere.platform_code = String(where.platformCode).trim();
|
||||
}
|
||||
if (where.status !== undefined && where.status !== null && String(where.status).trim() !== '') {
|
||||
queryWhere.status = Number(where.status);
|
||||
}
|
||||
if (where.isBack && String(where.isBack).trim()) {
|
||||
queryWhere.is_back = String(where.isBack).trim();
|
||||
}
|
||||
if (where.isIntercept && String(where.isIntercept).trim()) {
|
||||
queryWhere.is_intercept = String(where.isIntercept).trim();
|
||||
}
|
||||
if (where.isGalaxyReceive && String(where.isGalaxyReceive).trim()) {
|
||||
queryWhere.is_galaxy_receive = String(where.isGalaxyReceive).trim();
|
||||
}
|
||||
if (where.waybillType && String(where.waybillType).trim()) {
|
||||
const type = String(where.waybillType).trim();
|
||||
if (type === 'main' || type === '1') {
|
||||
queryWhere.business_key = 1;
|
||||
} else if (type === 'child' || type === '2') {
|
||||
queryWhere.business_key = { [Op.gt]: 1 };
|
||||
}
|
||||
}
|
||||
// 货主ID等值
|
||||
if (where.storeId !== undefined && where.storeId !== null && String(where.storeId).trim() !== '') {
|
||||
queryWhere.store_id = Number(where.storeId);
|
||||
}
|
||||
if (where.packageMaterialId !== undefined && where.packageMaterialId !== null && String(where.packageMaterialId).trim() !== '') {
|
||||
queryWhere.package_material_id = Number(where.packageMaterialId);
|
||||
}
|
||||
if (where.hasWeighingWeight !== undefined && where.hasWeighingWeight !== null && String(where.hasWeighingWeight).trim() !== '') {
|
||||
const hasWeight = String(where.hasWeighingWeight).trim();
|
||||
if (hasWeight === 'true') {
|
||||
queryWhere.weighing_weight = { [Op.gt]: 0 };
|
||||
} else if (hasWeight === 'false') {
|
||||
queryWhere.weighing_weight = { [Op.eq]: 0 };
|
||||
}
|
||||
}
|
||||
if (where.keyword && String(where.keyword).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(where.keyword).trim()}%` };
|
||||
}
|
||||
if (where.createdAtStart && String(where.createdAtStart).trim()) {
|
||||
const startDate = this.normalizeDate(String(where.createdAtStart).trim(), false);
|
||||
if (startDate) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: startDate };
|
||||
}
|
||||
}
|
||||
if (where.createdAtEnd && String(where.createdAtEnd).trim()) {
|
||||
const endDate = this.normalizeDate(String(where.createdAtEnd).trim(), true);
|
||||
if (endDate) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: endDate };
|
||||
}
|
||||
}
|
||||
|
||||
// 先统计总数
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({ status: 'running', progress: 10, currentCount: 0, totalCount: 0, message: '正在统计数据…' });
|
||||
}
|
||||
const totalCount = await ctx.model.OrderExpress.count({ where: queryWhere });
|
||||
|
||||
if (totalCount === 0) {
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({ status: 'success', progress: 100, currentCount: 0, totalCount: 0, message: '导出完成', result: { list: [], url: '' } });
|
||||
}
|
||||
return { list: [], current_count: 0, total_count: 0, url: '' };
|
||||
}
|
||||
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({ status: 'running', progress: 15, currentCount: 0, totalCount, message: `共 ${totalCount} 条,正在导出…` });
|
||||
}
|
||||
|
||||
// 分批查询(避免大数据量内存溢出)
|
||||
const EXPORT_PAGE_SIZE = 500;
|
||||
const allRows = [];
|
||||
const totalPages = Math.ceil(totalCount / EXPORT_PAGE_SIZE);
|
||||
|
||||
for (let page = 0; page < totalPages; page++) {
|
||||
const pageRows = await ctx.model.OrderExpress.findAll({
|
||||
where: queryWhere,
|
||||
// TODO: 快照列未落库,暂时只查已有字段;快照就绪后补充
|
||||
attributes: [
|
||||
'id', 'waybill_code', 'order_id', 'business_key', 'status',
|
||||
'warehouse_id', 'store_id',
|
||||
'logistics_code', 'logistics_name',
|
||||
'logistics_interface_id', 'logistics_interface_name',
|
||||
'platform_code',
|
||||
'is_back', 'is_intercept', 'is_galaxy_receive',
|
||||
'weighing_weight',
|
||||
'package_material_id', 'package_material_name_snapshot',
|
||||
'create_at',
|
||||
],
|
||||
order: [[ sortField, sortOrder ]],
|
||||
limit: EXPORT_PAGE_SIZE,
|
||||
offset: page * EXPORT_PAGE_SIZE,
|
||||
raw: true,
|
||||
});
|
||||
allRows.push(...pageRows);
|
||||
|
||||
// 进度回调(15% ~ 90%)
|
||||
if (typeof onProgress === 'function') {
|
||||
const progress = 15 + Math.round(75 * (page + 1) / totalPages);
|
||||
await onProgress({
|
||||
status: 'running',
|
||||
progress,
|
||||
currentCount: allRows.length,
|
||||
totalCount,
|
||||
message: `已导出 ${allRows.length} / ${totalCount} 条`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 提取所有唯一的 order_id,SELF JOIN 主单号
|
||||
const orderIds = [ ...new Set(allRows.map(r => r.order_id).filter(Boolean)) ];
|
||||
const mainWaybillMap = new Map();
|
||||
if (orderIds.length > 0) {
|
||||
const mainRecords = await ctx.model.OrderExpress.findAll({
|
||||
where: {
|
||||
order_id: { [Op.in]: orderIds },
|
||||
business_key: 1,
|
||||
},
|
||||
attributes: [ 'order_id', 'waybill_code' ],
|
||||
raw: true,
|
||||
});
|
||||
for (const rec of mainRecords) {
|
||||
if (!mainWaybillMap.has(rec.order_id)) {
|
||||
mainWaybillMap.set(rec.order_id, rec.waybill_code);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 预定义全部导出字段映射
|
||||
const allFieldMap = {
|
||||
id: r => r.id,
|
||||
waybill_code: r => r.waybill_code || '',
|
||||
main_waybill_code: r => mainWaybillMap.get(r.order_id) || r.waybill_code || '',
|
||||
waybill_type: r => (Number(r.business_key) === 1 ? '主单号' : '子单号'),
|
||||
order_id: r => r.order_id,
|
||||
// TODO: 快照列未落库,暂时填空;快照就绪后替换
|
||||
order_no: () => '',
|
||||
warehouse_id: r => r.warehouse_id,
|
||||
warehouse_name: () => '',
|
||||
store_id: r => r.store_id || 0,
|
||||
store_name: () => '',
|
||||
business_key: r => r.business_key,
|
||||
status: r => r.status,
|
||||
status_text: r => (r.status === 1 ? '已分配' : '未分配'),
|
||||
logistics_code: r => r.logistics_code || '',
|
||||
logistics_name: r => r.logistics_name || '',
|
||||
logistics_interface_id: r => r.logistics_interface_id || 0,
|
||||
logistics_interface_name: r => r.logistics_interface_name || '',
|
||||
platform_code: r => r.platform_code || '',
|
||||
is_back: r => r.is_back || 'N',
|
||||
is_intercept: r => r.is_intercept || 'N',
|
||||
is_galaxy_receive: r => r.is_galaxy_receive || 'N',
|
||||
weighing_weight: r => r.weighing_weight || 0,
|
||||
weighing_weight_display: r => (r.weighing_weight > 0 ? `${(r.weighing_weight / 1000).toFixed(2)} kg` : '0 kg'),
|
||||
package_material_id: r => r.package_material_id || 0,
|
||||
package_material_name: r => r.package_material_name_snapshot || '',
|
||||
create_at: r => (r.create_at ? this.app.formatDate(r.create_at) : null),
|
||||
};
|
||||
|
||||
// 确定导出字段集
|
||||
const fields = Array.isArray(exportFields) && exportFields.length > 0
|
||||
? exportFields.filter(f => allFieldMap[f])
|
||||
: Object.keys(allFieldMap);
|
||||
|
||||
const list = allRows.map(row => {
|
||||
const item = {};
|
||||
for (const field of fields) {
|
||||
item[field] = allFieldMap[field](row);
|
||||
}
|
||||
return item;
|
||||
});
|
||||
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({
|
||||
status: 'running',
|
||||
progress: 95,
|
||||
currentCount: allRows.length,
|
||||
totalCount,
|
||||
message: '正在生成导出文件…',
|
||||
});
|
||||
}
|
||||
|
||||
// 生成 Excel 文件并上传
|
||||
const result = await this.buildWaybillExportFile({
|
||||
list,
|
||||
fields,
|
||||
warehouseId,
|
||||
totalCount: allRows.length,
|
||||
});
|
||||
|
||||
if (typeof onProgress === 'function') {
|
||||
await onProgress({
|
||||
status: 'success',
|
||||
progress: 100,
|
||||
currentCount: allRows.length,
|
||||
totalCount,
|
||||
message: '导出完成',
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成运单导出 Excel 文件并上传,返回下载链接。
|
||||
* @param {Object} options 导出选项。
|
||||
* @param {Array} options.list 导出数据列表。
|
||||
* @param {string[]} options.fields 导出字段列表。
|
||||
* @param {number} options.warehouseId 仓库ID。
|
||||
* @param {number} options.totalCount 总条数。
|
||||
* @return {Promise<Object>} { current_count, total_count, url }。
|
||||
*/
|
||||
async buildWaybillExportFile({ list, fields, warehouseId, totalCount } = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
// 列名中文映射
|
||||
const COLUMN_LABELS = {
|
||||
id: 'ID',
|
||||
waybill_code: '运单号',
|
||||
main_waybill_code: '主单号',
|
||||
waybill_type: '运单类型',
|
||||
order_id: '订单ID',
|
||||
order_no: '订单号',
|
||||
warehouse_id: '仓库ID',
|
||||
warehouse_name: '仓库名称',
|
||||
store_id: '货主ID',
|
||||
store_name: '货主名称',
|
||||
business_key: '拆单序号',
|
||||
status: '状态',
|
||||
status_text: '状态',
|
||||
logistics_code: '物流编码',
|
||||
logistics_name: '物流名称',
|
||||
logistics_interface_id: '物流接口ID',
|
||||
logistics_interface_name: '物流接口名称',
|
||||
platform_code: '平台编码',
|
||||
is_back: '是否退回',
|
||||
is_intercept: '是否拦截',
|
||||
is_galaxy_receive: '是否揽收',
|
||||
weighing_weight: '称重重量(g)',
|
||||
weighing_weight_display: '称重重量',
|
||||
package_material_id: '包材ID',
|
||||
package_material_name: '包材名称',
|
||||
create_at: '创建时间',
|
||||
};
|
||||
|
||||
// 生成 Excel
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const worksheet = workbook.addWorksheet('运单导出');
|
||||
|
||||
// 写表头
|
||||
const headerRow = worksheet.addRow(fields.map(f => COLUMN_LABELS[f] || f));
|
||||
headerRow.font = { bold: true };
|
||||
headerRow.alignment = { horizontal: 'center' };
|
||||
|
||||
// 写数据
|
||||
for (const row of list) {
|
||||
worksheet.addRow(fields.map(f => (row[f] !== undefined && row[f] !== null ? row[f] : '')));
|
||||
}
|
||||
|
||||
// 保存到临时文件
|
||||
const now = new Date();
|
||||
const dateStr = `${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 = `运单导出_${dateStr}.xlsx`;
|
||||
const tmpDir = os.tmpdir();
|
||||
const filePath = path.join(tmpDir, `waybill_export_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.xlsx`);
|
||||
|
||||
await workbook.xlsx.writeFile(filePath);
|
||||
|
||||
// 上传文件
|
||||
const uploadService = ctx?.service?.systems?.upload;
|
||||
let url = '';
|
||||
let fileKey = '';
|
||||
|
||||
if (uploadService && typeof uploadService.uploadFile === 'function') {
|
||||
try {
|
||||
const stat = await fsp.stat(filePath);
|
||||
const safeWarehouseId = String(warehouseId || 'unknown');
|
||||
const randomToken = Math.random().toString(36).slice(2, 8);
|
||||
const uploadKey = `exports/waybill/${safeWarehouseId}/${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',
|
||||
});
|
||||
|
||||
url = uploadResult.url || uploadResult.cdnUrl || uploadResult.cosUrl || '';
|
||||
fileKey = uploadResult.fileName || '';
|
||||
|
||||
// 记录上传文件
|
||||
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||||
await uploadService.uploadSuccessNotify({
|
||||
url: uploadResult.fileName,
|
||||
fileKey: uploadResult.fileName,
|
||||
fileName: filename,
|
||||
fileType: 'document',
|
||||
mimeType: uploadStream.mimeType,
|
||||
fileSize: stat.size,
|
||||
category: 'document',
|
||||
businessType: 'waybillExport',
|
||||
businessId: `${warehouseId}`,
|
||||
uploaderType: ctx?.user?.role || 'system_api',
|
||||
uploaderDept: ctx?.user?.department || '',
|
||||
});
|
||||
}
|
||||
} catch (uploadError) {
|
||||
ctx.logger.error('[WaybillService.buildWaybillExportFile] 文件上传失败', {
|
||||
error: uploadError.message,
|
||||
filename,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 清理临时文件
|
||||
try {
|
||||
await fsp.unlink(filePath);
|
||||
} catch (_e) {
|
||||
// 忽略清理错误
|
||||
}
|
||||
|
||||
return {
|
||||
current_count: totalCount,
|
||||
total_count: totalCount,
|
||||
url,
|
||||
fileKey,
|
||||
filename,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WaybillService;
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# 运单号模块设计方案(仓库侧)
|
||||
|
||||
> **状态**: ⏳ 等待审阅
|
||||
> **状态**: 🔧 开发中(索引已就绪,快照字段待 dev 实现写入逻辑后执行)
|
||||
> **设计日期**: 2026-07-29
|
||||
> **设计人**: wms-db-agent
|
||||
> **说明**: 本文档仅输出设计方案,不执行代码实现。审阅通过后再进入开发。
|
||||
@ -34,6 +34,7 @@
|
||||
| `waybill_code` | `VARCHAR(50)` | **运单号** |
|
||||
| `order_id` | `BIGINT(20)` | 订单ID |
|
||||
| `warehouse_id` | `BIGINT(20) UNSIGNED` | 仓库ID |
|
||||
| `store_id` | `BIGINT(20) UNSIGNED` | 🆕 货主ID |
|
||||
| `business_key` | `INTEGER(3)` | 拆单序号(1=主单号,>1=子单号) |
|
||||
| `status` | `TINYINT(1)` DEFAULT 0 | 状态(1=已分配,0=未分配) |
|
||||
| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID |
|
||||
@ -42,7 +43,7 @@
|
||||
| `logistics_interface_id` | `BIGINT(20) UNSIGNED` | 物流接口ID |
|
||||
| `logistics_interface_name` | `VARCHAR(50)` | 物流接口名称 |
|
||||
| `platform_code` | `VARCHAR(50)` | 平台编码 |
|
||||
| `is_galaxy_receive` | `ENUM('Y','N')` | 是否星河签收 |
|
||||
| `is_galaxy_receive` | `ENUM('Y','N')` | 是否揽收 |
|
||||
| `is_back` | `ENUM('Y','N')` | 是否退回 |
|
||||
| `is_intercept` | `ENUM('Y','N')` | 是否拦截 |
|
||||
| `weighing_weight` | `INT(11)` DEFAULT 0 | 称重重量(g) |
|
||||
@ -86,7 +87,7 @@
|
||||
| `idx_warehouse_id_create_at` | 仓库+时间范围排序分页 |
|
||||
| `idx_order_id_business_key` | 已有 `uk_order_id_business_key` 唯一索引,可同时覆盖主单号 SELF JOIN 查询 |
|
||||
|
||||
> **索引迁移**:以下索引将通过迁移文件 `YYYYMMDDHHmmss-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。
|
||||
> **索引迁移**:以下索引已通过迁移文件 `20260729140000-add-waybill-list-indexes.js` 正式创建,见 §五 文件变更清单。
|
||||
|
||||
### 2.4 主单号/子单号关联关系
|
||||
|
||||
@ -105,6 +106,29 @@
|
||||
- 大部分运单 `business_key = 1`(未拆单),此时主单号 = 运单号本身
|
||||
- 仅拆单场景下存在 `business_key > 1` 的子单号
|
||||
|
||||
### 2.5 快照字段评估(待开发实现)
|
||||
|
||||
> **状态**:字段和迁移已准备就绪,但**创建运单号时写入快照值的逻辑尚未实现**(属于 dev 任务范围)。当前快照列为空,列表仍需 JOIN 订单表。
|
||||
|
||||
**原则**:运单列表应尽量避免 JOIN `wms_order_delivery`(current/history/dispatch 多表)和 `store` 表,通过快照字段冗余订单关键信息到 `wms_order_express`。
|
||||
|
||||
**现有快照字段**:
|
||||
|
||||
| 字段 | 快照内容 | 覆盖场景 |
|
||||
|------|---------|---------|
|
||||
| `package_material_name_snapshot` | 包材名称 | ✅ 避 JOIN `package_material` |
|
||||
|
||||
**待新增快照字段**(需配合 dev 改造创建运单号逻辑):
|
||||
|
||||
| 快照列 | 类型 | 替代的 JOIN | 写入时机 |
|
||||
|--------|------|-----------|---------|
|
||||
| `delivery_order_code` | `VARCHAR(50)` | `order_delivery.delivery_order_code` | 运单号分配成功时(express.js) |
|
||||
| `store_id_snapshot` | `BIGINT(20) UNSIGNED` | `order_delivery.store_id` | 同上 |
|
||||
| `store_name_snapshot` | `VARCHAR(128)` | `store.name`(货主表) | 同上 |
|
||||
| `warehouse_name_snapshot` | `VARCHAR(128)` | `store.name`(仓库表) | 同上 |
|
||||
|
||||
> **迁移文件**:`20260729130000-add-waybill-order-snapshots.js` 已创建但**已回滚**,待 dev 实现写入逻辑后再执行。
|
||||
|
||||
---
|
||||
|
||||
## 三、接口设计
|
||||
@ -116,7 +140,7 @@
|
||||
| 模块名 | `waybill.warehouse` |
|
||||
| 接口路径 | `POST /system`,body 中 `method` 字段为 `waybill.warehouse.{方法名}` |
|
||||
| 请求方式 | 全部 `POST`,参数放在 `body` 内 |
|
||||
| 鉴权 | 查询类接口需登录但无需鉴权;导出需登录 |
|
||||
| 鉴权 | 全部接口需登录,暂不做细粒度鉴权 |
|
||||
| 数据隔离 | 按 `warehouse_id` 隔离(仓库侧视角,见 §3.1.1 仓库隔离策略) |
|
||||
| 后续扩展 | 预留 `waybill.store.*`(货主侧,按 `store_id` 隔离),本期不实现 |
|
||||
|
||||
@ -207,7 +231,10 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
"where": {
|
||||
"waybillCode": "",
|
||||
"mainWaybillCode": "",
|
||||
"waybillType": "",
|
||||
"orderId": null,
|
||||
"orderNo": "",
|
||||
"storeId": null,
|
||||
"logisticsCode": "",
|
||||
"logisticsInterfaceId": null,
|
||||
"platformCode": "",
|
||||
@ -236,15 +263,17 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| `where` | `object` | ✗ | 筛选条件,所有字段均为可选 |
|
||||
| `where.waybillCode` | `string` | ✗ | 运单号(模糊搜索) |
|
||||
| `where.mainWaybillCode` | `string` | ✗ | **主单号**(精确匹配)。先通过主单号定位 `order_id`,再返回该订单下所有运单(主+子)。与 `waybillCode` 互斥,同时传入时 `mainWaybillCode` 优先 |
|
||||
| `where.waybillType` | `string` | ✗ | 🆕 **运单类型**:`"main"`/`"1"`=主单号(`business_key=1`),`"child"`/`"2"`=子单号(`business_key>1`) |
|
||||
| `where.orderId` | `number` | ✗ | 订单ID(等值) |
|
||||
| `where.orderNo` | `string` | ✗ | 订单号(需要 JOIN 订单表后模糊匹配) |
|
||||
| `where.orderNo` | `string` | ✗ | ⛔ **暂不可用**:订单号(待快照字段 `delivery_order_code` 落库后启用 LIKE 模糊搜索) |
|
||||
| `where.storeId` | `number` | ✗ | 货主ID(等值,直读 `store_id` 列) |
|
||||
| `where.logisticsCode` | `string` | ✗ | 物流公司编码(等值) |
|
||||
| `where.logisticsInterfaceId` | `number` | ✗ | **物流接口ID**(等值),对应 `wms_order_express.logistics_interface_id`,用于按快递接口筛选运单列表 |
|
||||
| `where.platformCode` | `string` | ✗ | 平台编码(等值),如 PDD/DY/KS/JD/CAINIAO/SPH/XHS |
|
||||
| `where.status` | `number` | ✗ | 运单状态:`0`=未分配,`1`=已分配 |
|
||||
| `where.isBack` | `string` | ✗ | 是否退回:`Y`/`N` |
|
||||
| `where.isIntercept` | `string` | ✗ | 是否拦截:`Y`/`N` |
|
||||
| `where.isGalaxyReceive` | `string` | ✗ | 是否星河签收:`Y`/`N` |
|
||||
| `where.isGalaxyReceive` | `string` | ✗ | 是否揽收:`Y`/`N` |
|
||||
| `where.packageMaterialId` | `number` | ✗ | 包材ID(等值) |
|
||||
| `where.hasWeighingWeight` | `boolean` | ✗ | 是否已称重:`true`=weighing_weight>0,`false`=weighing_weight=0 |
|
||||
| `where.keyword` | `string` | ✗ | 关键词:匹配运单号(`waybill_code`)、主单号(`main_waybill_code`)、订单号(需 JOIN) |
|
||||
@ -286,7 +315,6 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
"weighing_weight_display": "1.25 kg",
|
||||
"package_material_id": 5,
|
||||
"package_material_name": "3号纸箱",
|
||||
"pack_status": "已打包",
|
||||
"print_count": 2,
|
||||
"last_print_at": "2026-07-29 10:30:00",
|
||||
"create_at": "2026-07-29 08:00:00"
|
||||
@ -310,11 +338,11 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| `main_waybill_code` | `string` | SELF JOIN 同 order 下 `business_key=1` | **主单号**。当 `business_key=1` 时等于 `waybill_code` 本身;当 `business_key>1` 时通过 SELF JOIN 查找同 `order_id` 下 `business_key=1` 的运单号 |
|
||||
| `waybill_type` | `string` | 计算字段 | 运单类型:`business_key=1` → `"主单号"`,`business_key>1` → `"子单号"` |
|
||||
| `order_id` | `number` | `wms_order_express.order_id` | 订单ID |
|
||||
| `order_no` | `string` | JOIN 订单表 | 订单号(`delivery_order_code`) |
|
||||
| `order_no` | `string` | JOIN 订单表 | 订单号(`delivery_order_code`)。待快照字段 + 写入逻辑实现后可改为直读 |
|
||||
| `warehouse_id` | `number` | `wms_order_express.warehouse_id` | 仓库ID |
|
||||
| `warehouse_name` | `string` | JOIN `store` 表 | 仓库名称 |
|
||||
| `store_id` | `number` | JOIN 订单表 | 货主ID |
|
||||
| `store_name` | `string` | JOIN `store` 表 | 货主名称 |
|
||||
| `warehouse_name` | `string` | JOIN `store` 表 | 仓库名称。待快照字段 + 写入逻辑实现后可改为直读 |
|
||||
| `store_id` | `number` | JOIN 订单表 | 货主ID。待快照字段 + 写入逻辑实现后可改为直读 |
|
||||
| `store_name` | `string` | JOIN `store` 表 | 货主名称。待快照字段 + 写入逻辑实现后可改为直读 |
|
||||
| `business_key` | `number` | `wms_order_express.business_key` | 拆单序号 |
|
||||
| `status` | `number` | `wms_order_express.status` | 状态:0/1 |
|
||||
| `status_text` | `string` | 前端映射 | 状态文本 |
|
||||
@ -326,12 +354,11 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| `platform_name` | `string` | 前端映射 | 平台名称 |
|
||||
| `is_back` | `string` | `wms_order_express.is_back` | 是否退回 |
|
||||
| `is_intercept` | `string` | `wms_order_express.is_intercept` | 是否拦截 |
|
||||
| `is_galaxy_receive` | `string` | `wms_order_express.is_galaxy_receive` | 是否星河签收 |
|
||||
| `is_galaxy_receive` | `string` | `wms_order_express.is_galaxy_receive` | 是否揽收 |
|
||||
| `weighing_weight` | `number` | `wms_order_express.weighing_weight` | 称重重量(g) |
|
||||
| `weighing_weight_display` | `string` | 格式化 | 称重重量可读展示 |
|
||||
| `package_material_id` | `number` | `wms_order_express.package_material_id` | 包材ID |
|
||||
| `package_material_name` | `string` | `wms_order_express.package_material_name_snapshot` | 包材名称 |
|
||||
| `pack_status` | `string` | LEFT JOIN `pack_task` | 打包状态("未打包"/"已打包") |
|
||||
| `print_count` | `number` | COUNT `express_print_record` | 打印次数 |
|
||||
| `last_print_at` | `string` | MAX `express_print_record.created_at` | 最近打印时间 |
|
||||
| `create_at` | `string` | `wms_order_express.create_at` | 运单创建时间 |
|
||||
@ -344,12 +371,13 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
4. **按物流接口ID查询**:直接 `WHERE logistics_interface_id = ?`,等值匹配
|
||||
5. **订单号模糊搜索**:当 `where.orderNo` 或 `where.keyword` 匹配到非纯数字运单号时,需要 JOIN 订单表(current/history/dispatch)进行 `delivery_order_code LIKE` 匹配
|
||||
6. **打印次数**:通过子查询或 LEFT JOIN + GROUP BY `express_print_record.express_no = waybill_code` 聚合
|
||||
7. **打包状态**:LEFT JOIN `pack_task` ON `waybill_code`
|
||||
8. **性能注意**:打印次数和打包状态的聚合查询在数据量大时可能成为瓶颈,建议先不做 JOIN,改为按需异步加载(在 detail 接口中返回),list 只返回 `wms_order_express` 原生字段 + 主单号 SELF JOIN
|
||||
7. **性能注意**:打印次数聚合查询在数据量大时可能成为瓶颈,建议仅在 detail 接口返回
|
||||
|
||||
> **性能优化策略**(建议):
|
||||
> - **方案 A(推荐)**:列表仅查 `wms_order_express` 原生字段,不 JOIN 订单/打印/打包表。`pack_status` 和 `print_count` 通过批量异步查询补充,或仅在 detail 接口返回。
|
||||
> - **方案 A(推荐)**:列表仅查 `wms_order_express` 原生字段,不 JOIN 订单/打印/打包表。`print_count` 通过批量异步查询补充,或仅在 detail 接口返回。
|
||||
> - **方案 B**:列表即 JOIN,但需确保索引覆盖良好。
|
||||
>
|
||||
> **快照字段优化(待实现)**:新增快照列 + 创建运单号时写入快照值后,可彻底去掉订单表和 store 表的 JOIN。迁移文件 `20260729130000-add-waybill-order-snapshots.js` 已就绪,待 dev 实现写入逻辑后执行。
|
||||
|
||||
---
|
||||
|
||||
@ -415,11 +443,7 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
},
|
||||
"package": {
|
||||
"package_material_id": 5,
|
||||
"package_material_name": "3号纸箱",
|
||||
"pack_status": "已打包",
|
||||
"pack_quantity": 3,
|
||||
"pack_at": "2026-07-29 09:15:00",
|
||||
"packer_name": "张三"
|
||||
"package_material_name": "3号纸箱"
|
||||
},
|
||||
"print_records": [
|
||||
{
|
||||
@ -528,7 +552,8 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
| **预留** | `app/service/systemMethods/waybill/store.js` | 入口层(货主侧):本期不创建,后续按需新增 |
|
||||
| **修改** | `app/service/systems/waybill.js` | 业务层:在现有 `toOrder()` 方法基础上新增 `list()`、`detail()`、`export()` 方法 |
|
||||
| **修改** | `methods/system.json` | 新增 `waybill.warehouse` group,注册 3 个 method 定义 |
|
||||
| **新增** | `database/migrations/YYYYMMDDHHmmss-add-waybill-list-indexes.js` | 迁移文件:新增 `idx_warehouse_id_status`、`idx_logistics_code`、`idx_logistics_interface_id`、`idx_warehouse_id_create_at` 索引 |
|
||||
| **新增** | `database/migrations/20260729140000-add-waybill-list-indexes.js` | 迁移文件:新增 4 个索引(✅ 已执行) |
|
||||
| **新增** | `database/migrations/20260730000000-add-store-id-to-wms-order-express.js` | 迁移文件:新增 `store_id` 货主ID列(✅ 已执行) |
|
||||
|
||||
---
|
||||
|
||||
@ -538,7 +563,7 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
|------|------|
|
||||
| 仓库隔离 | 所有查询自动注入 `warehouse_id = ctx.user.store_id`(系统统一约定),仅返回当前用户所属仓库数据,不可由入参覆盖 |
|
||||
| 只读 | 本模块一期仅提供只读查询,不涉及运单创建/修改/删除 |
|
||||
| 鉴权 | 查询接口仅需登录,不做细粒度权限校验(与订单列表保持一致) |
|
||||
| 鉴权 | 全部接口仅需登录,暂不做细粒度权限校验(与订单列表保持一致) |
|
||||
|
||||
---
|
||||
|
||||
@ -574,6 +599,38 @@ POST /system { method: "waybill.warehouse.list", ... }
|
||||
- [ ] 接口设计是否满足业务需求(运单号独立列表 + 详情)
|
||||
- [x] ~~仓库隔离策略是否正确~~ → 已核实:全系统统一使用 `ctx.user.store_id` 作为 warehouse_id,与现有模式一致
|
||||
- [ ] 列表字段是否完整(是否需要增减字段)
|
||||
- [ ] 是否需要 JOIN 订单/打印/打包表(性能 vs 信息完整性权衡)
|
||||
- [ ] 是否需要新增数据库索引
|
||||
- [ ] 快照字段写入逻辑:需在创建运单号(express.js)时同步写入快照列值(dev 任务)
|
||||
- [ ] 是否需要新增数据库索引(已明确需要,`20260729140000` 已执行)
|
||||
- [ ] 与现有 `index.toOrder`、`order.*` 接口的边界是否清晰
|
||||
|
||||
### 当前筛选条件(共 18 项,16 可用 + 2 待快照)
|
||||
|
||||
| # | 参数 | 类型 | 匹配 | 状态 |
|
||||
|---|------|------|------|------|
|
||||
| — | `warehouse_id` | — | = | ✅ 自动注入 |
|
||||
| 1 | `waybillCode` | string | LIKE | ✅ |
|
||||
| 2 | `mainWaybillCode` | string | 精确→order_id | ✅ |
|
||||
| 3 | `waybillType` | string | `main/1`→bk=1, `child/2`→bk>1 | ✅ 🆕 |
|
||||
| 4 | `orderId` | number | = | ✅ |
|
||||
| 5 | `orderNo` | string | LIKE | ⛔ 待快照 |
|
||||
| 6 | `storeId` | number | = | ✅ 直读 `store_id` |
|
||||
| 7 | `logisticsCode` | string | = | ✅ |
|
||||
| 8 | `logisticsInterfaceId` | number | = | ✅ |
|
||||
| 9 | `platformCode` | string | = | ✅ |
|
||||
| 10 | `status` | number | = | ✅ |
|
||||
| 11 | `isBack` | string | = | ✅ |
|
||||
| 12 | `isIntercept` | string | = | ✅ |
|
||||
| 13 | `isGalaxyReceive` | string | = | ✅ |
|
||||
| 14 | `packageMaterialId` | number | = | ✅ |
|
||||
| 15 | `hasWeighingWeight` | boolean | true→>0, false→=0 | ✅ |
|
||||
| 16 | `keyword` | string | LIKE waybill_code | ✅ |
|
||||
| 17 | `createdAtStart` | string YYYY-MM-DD | >= | ✅ |
|
||||
| 18 | `createdAtEnd` | string YYYY-MM-DD | <= | ✅ |
|
||||
|
||||
### 排序
|
||||
|
||||
| field | order | 默认 |
|
||||
|-------|-------|------|
|
||||
| `create_at` | asc/desc | desc |
|
||||
| `weighing_weight` | asc/desc | — |
|
||||
| `id` | asc/desc | — |
|
||||
|
||||
@ -0,0 +1,84 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_order_express';
|
||||
|
||||
/**
|
||||
* 获取指定表的索引名集合。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<Set<string>>} 索引名集合。
|
||||
*/
|
||||
const getIndexNameSet = async (queryInterface, tableName) => {
|
||||
const indexes = await queryInterface.showIndex(tableName);
|
||||
return new Set(indexes.map(index => String(index && index.name ? index.name : '').trim()).filter(Boolean));
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为运单表新增运单列表高频查询索引(幂等)。
|
||||
*
|
||||
* 新增索引:
|
||||
* - idx_warehouse_id_status:仓库+状态筛选(最常见查询组合)
|
||||
* - idx_logistics_code:物流公司筛选
|
||||
* - idx_logistics_interface_id:快递接口ID筛选
|
||||
* - idx_warehouse_id_create_at:仓库+时间范围排序分页
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME);
|
||||
|
||||
if (!indexNameSet.has('idx_warehouse_id_status')) {
|
||||
await queryInterface.addIndex(TABLE_NAME, {
|
||||
name: 'idx_warehouse_id_status',
|
||||
fields: ['warehouse_id', 'status'],
|
||||
});
|
||||
}
|
||||
|
||||
if (!indexNameSet.has('idx_logistics_code')) {
|
||||
await queryInterface.addIndex(TABLE_NAME, {
|
||||
name: 'idx_logistics_code',
|
||||
fields: ['logistics_code'],
|
||||
});
|
||||
}
|
||||
|
||||
if (!indexNameSet.has('idx_logistics_interface_id')) {
|
||||
await queryInterface.addIndex(TABLE_NAME, {
|
||||
name: 'idx_logistics_interface_id',
|
||||
fields: ['logistics_interface_id'],
|
||||
});
|
||||
}
|
||||
|
||||
if (!indexNameSet.has('idx_warehouse_id_create_at')) {
|
||||
await queryInterface.addIndex(TABLE_NAME, {
|
||||
name: 'idx_warehouse_id_create_at',
|
||||
fields: ['warehouse_id', 'create_at'],
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除运单列表查询索引。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
const indexNameSet = await getIndexNameSet(queryInterface, TABLE_NAME);
|
||||
|
||||
if (indexNameSet.has('idx_warehouse_id_status')) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_status');
|
||||
}
|
||||
if (indexNameSet.has('idx_logistics_code')) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_code');
|
||||
}
|
||||
if (indexNameSet.has('idx_logistics_interface_id')) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_logistics_interface_id');
|
||||
}
|
||||
if (indexNameSet.has('idx_warehouse_id_create_at')) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_id_create_at');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,49 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_order_express';
|
||||
const COLUMN_NAME = 'store_id';
|
||||
|
||||
/**
|
||||
* 获取指定表的列名集合。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {string} tableName 表名。
|
||||
* @return {Promise<Set<string>>} 列名集合。
|
||||
*/
|
||||
const getColumnNameSet = async (queryInterface, tableName) => {
|
||||
const columns = await queryInterface.describeTable(tableName);
|
||||
return new Set(Object.keys(columns));
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:为运单表新增货主ID字段(幂等)。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME);
|
||||
|
||||
if (!existingColumns.has(COLUMN_NAME)) {
|
||||
await queryInterface.addColumn(TABLE_NAME, COLUMN_NAME, {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '货主ID',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:移除运单表的货主ID字段。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
const existingColumns = await getColumnNameSet(queryInterface, TABLE_NAME);
|
||||
|
||||
if (existingColumns.has(COLUMN_NAME)) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, COLUMN_NAME);
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 回填 wms_order_express 表的 logistics_code 和 logistics_name。
|
||||
*
|
||||
* 背景:取号成功后写入 wms_order_express 时引用了不存在的字段
|
||||
* listByWarehousePlatformCode.logistics_code / logistics_name,
|
||||
* 导致 6w+ 条记录该两字段为空。
|
||||
*
|
||||
* 本迁移通过 logistics_interface_id 关联 wms_express_interface.sys_express_code,
|
||||
* 再通过 wms_express.name 获取快递名称,完成数据回填。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
const [ results ] = await queryInterface.sequelize.query(`
|
||||
SELECT COUNT(*) AS cnt
|
||||
FROM wms_order_express oe
|
||||
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
|
||||
WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '')
|
||||
AND ei.sys_express_code IS NOT NULL
|
||||
AND ei.sys_express_code != ''
|
||||
`);
|
||||
|
||||
const affectedCount = (results && results[0] && results[0].cnt) || 0;
|
||||
console.log(`[backfill-order-express-logistics] 预计回填 ${affectedCount} 条记录`);
|
||||
|
||||
if (affectedCount === 0) {
|
||||
console.log('[backfill-order-express-logistics] 无需回填,跳过');
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_order_express oe
|
||||
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
|
||||
LEFT JOIN wms_express e ON e.code = ei.sys_express_code
|
||||
SET
|
||||
oe.logistics_code = ei.sys_express_code,
|
||||
oe.logistics_name = COALESCE(e.name, ei.sys_express_code)
|
||||
WHERE (oe.logistics_code IS NULL OR oe.logistics_code = '')
|
||||
AND ei.sys_express_code IS NOT NULL
|
||||
AND ei.sys_express_code != ''
|
||||
`);
|
||||
|
||||
console.log(`[backfill-order-express-logistics] 成功回填 ${affectedCount} 条记录`);
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
// 回滚:仅清空通过本迁移回填的记录(条件:logistics_code 等于对应 sys_express_code)
|
||||
const [ results ] = await queryInterface.sequelize.query(`
|
||||
SELECT COUNT(*) AS cnt
|
||||
FROM wms_order_express oe
|
||||
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
|
||||
WHERE oe.logistics_code = ei.sys_express_code
|
||||
AND oe.logistics_code IS NOT NULL
|
||||
AND oe.logistics_code != ''
|
||||
AND ei.sys_express_code IS NOT NULL
|
||||
AND ei.sys_express_code != ''
|
||||
`);
|
||||
|
||||
const rollbackCount = (results && results[0] && results[0].cnt) || 0;
|
||||
console.log(`[backfill-order-express-logistics] 预计回滚 ${rollbackCount} 条记录`);
|
||||
|
||||
if (rollbackCount === 0) {
|
||||
console.log('[backfill-order-express-logistics] 无需回滚,跳过');
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.sequelize.query(`
|
||||
UPDATE wms_order_express oe
|
||||
JOIN wms_express_interface ei ON oe.logistics_interface_id = ei.id
|
||||
SET
|
||||
oe.logistics_code = '',
|
||||
oe.logistics_name = ''
|
||||
WHERE oe.logistics_code = ei.sys_express_code
|
||||
AND oe.logistics_code IS NOT NULL
|
||||
AND oe.logistics_code != ''
|
||||
AND ei.sys_express_code IS NOT NULL
|
||||
AND ei.sys_express_code != ''
|
||||
`);
|
||||
|
||||
console.log(`[backfill-order-express-logistics] 成功回滚 ${rollbackCount} 条记录`);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 为 wms_order_express 表新增 delivery_order_code 和 source_order_codes 字段。
|
||||
*
|
||||
* 用途:运单记录需要关联对应的发货单号和原始订单号,便于运单追溯和导出。
|
||||
* 字段格式参考 wms_order_delivery 表的同名字段。
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('wms_order_express', 'delivery_order_code', {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: true,
|
||||
comment: '发货单号',
|
||||
after: 'warehouse_id',
|
||||
});
|
||||
|
||||
await queryInterface.addColumn('wms_order_express', 'source_order_codes', {
|
||||
type: Sequelize.TEXT,
|
||||
allowNull: true,
|
||||
comment: '来源订单号集合',
|
||||
after: 'delivery_order_code',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn('wms_order_express', 'delivery_order_code');
|
||||
await queryInterface.removeColumn('wms_order_express', 'source_order_codes');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_order_express';
|
||||
|
||||
/**
|
||||
* 回填 wms_order_express.store_id。
|
||||
* 从对应的仓库分表(current → history → dispatch)中获取 store_id。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function backfill(queryInterface) {
|
||||
// 获取所有不同的 warehouse_id
|
||||
const [warehouses] = await queryInterface.sequelize.query(
|
||||
`SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE store_id IS NULL AND warehouse_id IS NOT NULL`
|
||||
);
|
||||
|
||||
if (!warehouses || warehouses.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const row of warehouses) {
|
||||
const warehouseId = row.warehouse_id;
|
||||
const tableTypes = [
|
||||
`wms_order_delivery_${warehouseId}`, // current(配送表 / 待处理表)
|
||||
`wms_order_delivery_${warehouseId}_history`, // history
|
||||
`wms_order_delivery_${warehouseId}_dispatch`, // dispatch
|
||||
];
|
||||
|
||||
for (const deliveryTable of tableTypes) {
|
||||
try {
|
||||
const [result] = await queryInterface.sequelize.query(`
|
||||
UPDATE ${TABLE_NAME} e
|
||||
INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id
|
||||
SET e.store_id = d.store_id
|
||||
WHERE e.store_id IS NULL AND d.store_id IS NOT NULL
|
||||
`);
|
||||
console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`);
|
||||
} catch (err) {
|
||||
// 表可能不存在,跳过
|
||||
if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') {
|
||||
continue;
|
||||
}
|
||||
console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* 执行迁移:回填 store_id。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
await backfill(queryInterface);
|
||||
},
|
||||
|
||||
/**
|
||||
* 回滚迁移:将 store_id 置为 NULL。
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @param {import('sequelize')} Sequelize Sequelize 实例。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_NAME} SET store_id = NULL`
|
||||
);
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
const TABLE_NAME = 'wms_order_express';
|
||||
|
||||
/**
|
||||
* 回填 wms_order_express 的 delivery_order_code 和 source_order_codes。
|
||||
* 从对应的仓库分表(current → history → dispatch)中获取。
|
||||
*
|
||||
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async function backfill(queryInterface) {
|
||||
const [warehouses] = await queryInterface.sequelize.query(
|
||||
`SELECT DISTINCT warehouse_id FROM ${TABLE_NAME} WHERE delivery_order_code IS NULL AND warehouse_id IS NOT NULL`
|
||||
);
|
||||
|
||||
if (!warehouses || warehouses.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const row of warehouses) {
|
||||
const warehouseId = row.warehouse_id;
|
||||
const tableTypes = [
|
||||
`wms_order_delivery_${warehouseId}`,
|
||||
`wms_order_delivery_${warehouseId}_history`,
|
||||
`wms_order_delivery_${warehouseId}_dispatch`,
|
||||
];
|
||||
|
||||
for (const deliveryTable of tableTypes) {
|
||||
try {
|
||||
const [result] = await queryInterface.sequelize.query(`
|
||||
UPDATE ${TABLE_NAME} e
|
||||
INNER JOIN ${deliveryTable} d ON e.order_id = d.id AND e.warehouse_id = d.warehouse_id
|
||||
SET e.delivery_order_code = COALESCE(e.delivery_order_code, d.delivery_order_code),
|
||||
e.source_order_codes = COALESCE(e.source_order_codes, d.source_order_codes)
|
||||
WHERE (e.delivery_order_code IS NULL OR e.source_order_codes IS NULL)
|
||||
AND (d.delivery_order_code IS NOT NULL OR d.source_order_codes IS NOT NULL)
|
||||
`);
|
||||
console.log(` warehouse=${warehouseId} table=${deliveryTable} rows=${result.info || result}`);
|
||||
} catch (err) {
|
||||
if (err && err.parent && err.parent.code === 'ER_NO_SUCH_TABLE') {
|
||||
continue;
|
||||
}
|
||||
console.warn(` warehouse=${warehouseId} table=${deliveryTable} error=${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await backfill(queryInterface);
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.sequelize.query(
|
||||
`UPDATE ${TABLE_NAME} SET delivery_order_code = NULL, source_order_codes = NULL`
|
||||
);
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user