WMS_MAIN/app/service/systems/order_packing.js
liufumingren 52aa76af60 fix: OrderExpress 查询添加仓库隔离 + workbench 业务增强
- _queryOrder: OrderExpress 查询增加 warehouse_id 过滤,避免跨仓库数据泄露
- _queryOrder: 新增订单商品明细查询,关联 stock 详情(带缓存)
- _packOrder: 同一工作台新任务进入时自动关闭上一个未结束任务
- order_packing.js: quickWhere 运单号查询增加 warehouse_id 过滤
- recheckOrder.js: getWaveOrdersBasic 运单查询增加 warehouse_id 过滤
- order_print.js: queryOrderExpressByOrderIds 增加 warehouseId 参数
- waybill.js: toOrder 运单查询在用户已登录时增加 warehouse_id 过滤
2026-07-21 20:53:53 +08:00

395 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
/**
* 打包任务服务层(仓库侧)。
* 负责打包任务列表查询、详情查询等仓库维度的打包管理业务逻辑。
* 数据来源:wms_pack_task 表。
*/
class OrderPackingService extends Service {
/**
* 打包任务列表查询(仓库侧)。
* 按仓库维度(warehouse_id)查询打包任务,支持分页、筛选、排序。
*
* @param {Object} where 筛选条件对象
* @param {Object} [where.status] 任务状态:0=待处理 1=打包中 2=已完成 3=异常
* @param {Object} [where.pack_mode] 打包模式:1=散单 2=团购
* @param {Object} [where.waybill_code] 运单号(模糊匹配)
* @param {Object} [where.wave_no] 波次号(模糊匹配)
* @param {Object} [where.order_id] 订单ID(精确匹配)
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查)
* @param {Object} [where.start_time_start] 开始打包时间起始
* @param {Object} [where.start_time_end] 开始打包时间结束
* @param {Object} pagination 分页参数 { page, pageSize }
* @param {Object} sort 排序参数 { sortField, sortOrder }
* @return {Promise<Object>} 打包任务列表与分页信息
*/
async list(where = {}, pagination = {}, sort = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const page = Math.max(Number(pagination.page) || 1, 1);
const pageSize = Math.max(Number(pagination.pageSize) || 20, 1);
// 仓库上下文
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
return {
code: 400,
message: '用户未绑定仓库,无法查询打包任务',
data: {
list: [],
pagination: { page, pageSize, total: 0, totalPages: 0, hasPrevious: false, hasNext: false },
},
};
}
// 构建查询条件
const queryWhere = { warehouse_id: warehouseId };
// 状态筛选
if (where.status !== undefined && where.status !== null) {
const statusValue = where.status?.value ?? where.status;
if (statusValue !== '' && statusValue !== undefined && statusValue !== null) {
queryWhere.status = Number(statusValue);
}
}
// 打包模式筛选
if (where.pack_mode !== undefined && where.pack_mode !== null) {
const packModeValue = where.pack_mode?.value ?? where.pack_mode;
if (packModeValue !== '' && packModeValue !== undefined && packModeValue !== null) {
queryWhere.pack_mode = Number(packModeValue);
}
}
// 运单号模糊匹配
if (where.waybill_code) {
const waybillValue = where.waybill_code?.value ?? where.waybill_code;
if (waybillValue && String(waybillValue).trim()) {
queryWhere.waybill_code = { [Op.like]: `%${String(waybillValue).trim()}%` };
}
}
// 波次号模糊匹配
if (where.wave_no) {
const waveNoValue = where.wave_no?.value ?? where.wave_no;
if (waveNoValue && String(waveNoValue).trim()) {
queryWhere.wave_no = { [Op.like]: `%${String(waveNoValue).trim()}%` };
}
}
// 订单ID精确匹配
if (where.order_id !== undefined && where.order_id !== null) {
const orderIdValue = where.order_id?.value ?? where.order_id;
if (orderIdValue !== '' && orderIdValue !== undefined && orderIdValue !== null) {
queryWhere.order_id = Number(orderIdValue);
}
}
// 工作台ID精确匹配
if (where.workbench_id !== undefined && where.workbench_id !== null) {
const workbenchIdValue = where.workbench_id?.value ?? where.workbench_id;
if (workbenchIdValue !== '' && workbenchIdValue !== undefined && workbenchIdValue !== null) {
queryWhere.workbench_id = Number(workbenchIdValue);
}
}
// 快捷搜索:支持波次号直接模糊匹配 + 运单号通过 express → order → wave 链路解析
if (where.quickWhere) {
const quickValue = where.quickWhere?.value ?? where.quickWhere;
if (quickValue && String(quickValue).trim()) {
const kw = String(quickValue).trim();
const orConditions = [];
// 1. 波次号直接模糊匹配(用户可能直接搜波次号)
orConditions.push({ wave_no: { [Op.like]: `%${kw}%` } });
// 2. 运单号解析:express → order → wave
// 团购波次 → 按 wave_no 查 packing 表;散单 → 按 order_id 查 packing 表
const expressRecords = await ctx.model.OrderExpress.findAll({
where: {
waybill_code: { [Op.like]: `%${kw}%` },
warehouse_id: warehouseId,
delete_at: null,
},
attributes: [ 'order_id' ],
raw: true,
});
if (expressRecords.length > 0) {
const orderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ];
if (orderIds.length > 0) {
// 查 order_delivery 获取 wave_id
const orderRecords = await ctx.model.OrderDelivery.findAll({
where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id' ],
raw: true,
});
// order_id → wave_id 映射
const orderWaveMap = new Map();
const noWaveOrderIds = [];
orderRecords.forEach(o => {
if (o.wave_id > 0) {
orderWaveMap.set(o.id, o.wave_id);
} else {
noWaveOrderIds.push(o.id);
}
});
// 未匹配到 order_delivery 的 order_id 也按散单处理
const matchedOrderIds = new Set(orderRecords.map(o => o.id));
orderIds.forEach(oid => {
if (!matchedOrderIds.has(oid)) {
noWaveOrderIds.push(oid);
}
});
const waveIds = [ ...new Set(orderWaveMap.values()) ];
if (waveIds.length > 0) {
// 查 wms_wave_batch 获取 wave_type 和 wave_no
const waveRecords = await ctx.model.WaveBatch.findAll({
where: { wave_id: { [Op.in]: waveIds } },
attributes: [ 'wave_id', 'wave_no', 'wave_type' ],
raw: true,
});
// wave_id → { wave_no, wave_type } 映射
const waveMap = new Map();
waveRecords.forEach(w => {
waveMap.set(w.wave_id, { wave_no: w.wave_no, wave_type: w.wave_type });
});
// 分离:团购波次号 / 散单订单ID
const groupBuyWaveNos = [];
const singleOrderIds = [ ...noWaveOrderIds ];
orderRecords.forEach(o => {
const waveInfo = waveMap.get(o.wave_id);
if (waveInfo) {
if (waveInfo.wave_type === 1) {
// 团购 → 按波次号查 packing 表
if (waveInfo.wave_no) {
groupBuyWaveNos.push(waveInfo.wave_no);
}
} else {
// 散单(wave_type=2) → 按 order_id 查 packing 表
singleOrderIds.push(o.id);
}
} else {
// wave_id 在 wms_wave_batch 中不存在,按散单处理
singleOrderIds.push(o.id);
}
});
if (groupBuyWaveNos.length > 0) {
orConditions.push({ wave_no: { [Op.in]: [ ...new Set(groupBuyWaveNos) ] } });
}
if (singleOrderIds.length > 0) {
orConditions.push({ order_id: { [Op.in]: [ ...new Set(singleOrderIds) ] } });
}
} else {
// 所有订单都没有波次(wave_id = 0),全部按散单处理
orConditions.push({ order_id: { [Op.in]: orderIds } });
}
}
}
queryWhere[Op.or] = orConditions;
}
}
// 开始打包时间范围
if (where.start_time_start) {
const startTimeStart = where.start_time_start?.value ?? where.start_time_start;
if (startTimeStart) {
queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.gte]: new Date(startTimeStart) };
}
}
if (where.start_time_end) {
const startTimeEnd = where.start_time_end?.value ?? where.start_time_end;
if (startTimeEnd) {
queryWhere.start_time = { ...(queryWhere.start_time || {}), [Op.lte]: new Date(startTimeEnd) };
}
}
// 排序
const sortField = sort.sortField || 'create_time';
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
const validSortFields = [ 'id', 'order_id', 'warehouse_id', 'workbench_id', 'wave_id', 'pack_quantity', 'pack_mode', 'status', 'start_time', 'end_time', 'create_time', 'update_time' ];
const actualSortField = validSortFields.includes(sortField) ? sortField : 'create_time';
// 查询(含工作台、视频和运单关联)
const { count, rows } = await ctx.model.PackTask.findAndCountAll({
where: queryWhere,
order: [[ actualSortField, sortOrder ]],
limit: pageSize,
offset: (page - 1) * pageSize,
include: [
{
model: ctx.model.Workbench,
as: 'workbench',
attributes: [ 'id', 'name', 'type', 'barcode' ],
},
{
model: ctx.model.PackTaskVideo,
as: 'videos',
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
where: { status: 1 },
required: false,
include: [
{
model: ctx.model.Camera,
as: 'camera',
attributes: [ 'id', 'custom_name', 'channel_name' ],
},
],
},
{
model: ctx.model.OrderExpress,
as: 'expresses',
attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ],
where: { delete_at: null },
required: false,
},
],
});
// 扁平化输出
const list = rows.map(row => {
const plain = row.get({ plain: true });
return {
...plain,
workbench_name: plain.workbench?.name || null,
workbench_type: plain.workbench?.type || null,
workbench_barcode: plain.workbench?.barcode || null,
videos: (plain.videos || []).map(v => ({
id: v.id,
video_url: v.video_url,
camera_id: v.camera_id,
camera_name: v.camera?.custom_name || v.camera?.channel_name || null,
})),
expresses: (plain.expresses || []).map(e => ({
id: e.id,
waybill_code: e.waybill_code,
logistics_code: e.logistics_code,
logistics_name: e.logistics_name,
logistics_interface_name: e.logistics_interface_name || null,
platform_code: e.platform_code || null,
status: e.status,
})),
workbench: undefined,
};
});
const totalPages = Math.ceil(count / pageSize) || 0;
return {
code: 200,
message: 'ok',
data: {
list,
pagination: {
page,
pageSize,
total: count,
totalPages,
hasPrevious: page > 1,
hasNext: page < totalPages,
},
},
};
}
/**
* 打包任务详情查询。
* 按 id + warehouse_id 查询单条打包任务记录。
*
* @param {Object} options 查询参数
* @param {number} options.id 打包任务ID
* @return {Promise<Object>} 打包任务详情
*/
async get(options = {}) {
const { ctx } = this;
const { id } = options;
if (!id) {
return { code: 400, message: '打包任务ID不能为空', data: null };
}
const warehouseId = Number(ctx.user && ctx.user.store_id);
if (!warehouseId) {
return { code: 400, message: '用户未绑定仓库,无法查询打包任务', data: null };
}
const record = await ctx.model.PackTask.findOne({
where: { id: Number(id), warehouse_id: warehouseId },
include: [
{
model: ctx.model.Workbench,
as: 'workbench',
attributes: [ 'id', 'name', 'type', 'barcode' ],
},
{
model: ctx.model.PackTaskVideo,
as: 'videos',
attributes: [ 'id', 'video_url', 'camera_id', 'status' ],
where: { status: 1 },
required: false,
include: [
{
model: ctx.model.Camera,
as: 'camera',
attributes: [ 'id', 'custom_name', 'channel_name' ],
},
],
},
{
model: ctx.model.OrderExpress,
as: 'expresses',
attributes: [ 'id', 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_name', 'platform_code', 'status' ],
where: { delete_at: null },
required: false,
},
],
});
if (!record) {
return { code: 404, message: '打包任务不存在或无权访问', data: null };
}
const plain = record.get({ plain: true });
const data = {
...plain,
workbench_name: plain.workbench?.name || null,
workbench_type: plain.workbench?.type || null,
workbench_barcode: plain.workbench?.barcode || null,
videos: (plain.videos || []).map(v => ({
id: v.id,
video_url: v.video_url,
camera_id: v.camera_id,
camera_name: v.camera?.custom_name || v.camera?.channel_name || null,
})),
expresses: (plain.expresses || []).map(e => ({
id: e.id,
waybill_code: e.waybill_code,
logistics_code: e.logistics_code,
logistics_name: e.logistics_name,
logistics_interface_name: e.logistics_interface_name || null,
platform_code: e.platform_code || null,
status: e.status,
})),
workbench: undefined,
};
return { code: 200, message: 'ok', data };
}
}
module.exports = OrderPackingService;