698 lines
27 KiB
JavaScript
698 lines
27 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
/**
|
||
* 打包任务服务层(仓库侧)。
|
||
* 负责打包任务列表查询、详情查询等仓库维度的打包管理业务逻辑。
|
||
* 数据来源:wms_pack_task 表。
|
||
*/
|
||
class OrderPackingService extends Service {
|
||
/**
|
||
* 获取仓库的录制电脑 ID(带缓存)。
|
||
* @param {number} warehouseId 仓库ID
|
||
* @return {Promise<number|null>} 录制电脑ID,找不到返回 null
|
||
*/
|
||
async _getRecordingComputerId(warehouseId) {
|
||
const cacheKey = `_recordingComputer_${warehouseId}`;
|
||
if (this[cacheKey] !== undefined) {
|
||
return this[cacheKey];
|
||
}
|
||
const row = await this.ctx.model.PrintComputer.findOne({
|
||
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
});
|
||
this[cacheKey] = row ? row.id : null;
|
||
return this[cacheKey];
|
||
}
|
||
|
||
/**
|
||
* 构建视频完整 URL。
|
||
* 格式:http://w{warehouseId}-c{recordingComputerId}.o.gztbyc.com{videoPath}
|
||
* @param {number} warehouseId 仓库ID
|
||
* @param {number|null} recordingComputerId 录制电脑ID
|
||
* @param {string} videoPath 视频路径
|
||
* @return {string} 完整 URL
|
||
*/
|
||
_buildVideoUrl(warehouseId, recordingComputerId, videoPath) {
|
||
if (!videoPath || !recordingComputerId) {
|
||
return videoPath || '';
|
||
}
|
||
return `http://w${warehouseId}-c${recordingComputerId}.o.gztbyc.com${videoPath}`;
|
||
}
|
||
/**
|
||
* 打包任务列表查询(仓库侧)。
|
||
* 按仓库维度(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] 运单号(通过 wms_order_express 解析 order_id 后过滤,支持 eq/like)
|
||
* @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] 开始打包时间范围,支持 {operator:'between', value:[start,end]}
|
||
* @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法)
|
||
* @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法)
|
||
* @param {Object} [where.end_time] 结束打包时间范围,支持 {operator:'between', value:[start,end]}
|
||
* @param {Object} [where.create_time] 创建时间范围,支持 {operator:'between', value:[start,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);
|
||
}
|
||
}
|
||
|
||
// 运单号筛选:通过 wms_order_express 表解析 order_id,再按 order_id 过滤(wms_pack_task.waybill_code 通常为空)
|
||
if (where.waybill_code) {
|
||
const waybillValue = where.waybill_code?.value ?? where.waybill_code;
|
||
const waybillOperator = (where.waybill_code?.operator || 'like').toLowerCase();
|
||
if (waybillValue && String(waybillValue).trim()) {
|
||
const trimmedValue = String(waybillValue).trim();
|
||
const expressWhere = {
|
||
warehouse_id: warehouseId,
|
||
delete_at: null,
|
||
};
|
||
if (waybillOperator === 'eq') {
|
||
expressWhere.waybill_code = trimmedValue;
|
||
} else {
|
||
expressWhere.waybill_code = { [Op.like]: `%${trimmedValue}%` };
|
||
}
|
||
const expressRecords = await ctx.model.OrderExpress.findAll({
|
||
where: expressWhere,
|
||
attributes: [ 'order_id' ],
|
||
raw: true,
|
||
});
|
||
const matchedOrderIds = [ ...new Set(expressRecords.map(r => r.order_id).filter(Boolean)) ];
|
||
if (matchedOrderIds.length > 0) {
|
||
queryWhere.order_id = { [Op.in]: matchedOrderIds };
|
||
} else {
|
||
// 无匹配运单号 → 强制返回空结果
|
||
queryWhere.id = -1;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 波次号模糊匹配
|
||
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(current + dispatch)
|
||
const orderDeliveryFactory = ctx.model.OrderDeliveryFactory;
|
||
const orderTableModels = [
|
||
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
|
||
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
|
||
];
|
||
const orderRecords = [];
|
||
for (const entry of orderTableModels) {
|
||
try {
|
||
const model = await entry.getModel();
|
||
if (!model) continue;
|
||
const rows = await model.findAll({
|
||
where: { id: { [Op.in]: orderIds }, warehouse_id: warehouseId },
|
||
attributes: [ 'id', 'wave_id' ],
|
||
raw: true,
|
||
});
|
||
orderRecords.push(...rows);
|
||
} catch (_err) { continue; }
|
||
}
|
||
|
||
// 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;
|
||
}
|
||
}
|
||
|
||
// has_video 筛选:1=有视频 2=无视频
|
||
if (where.has_video !== undefined && where.has_video !== null) {
|
||
const hasVideoValue = Number(where.has_video?.value ?? where.has_video);
|
||
if (hasVideoValue === 1) {
|
||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||
app.Sequelize.literal('EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'),
|
||
];
|
||
} else if (hasVideoValue === 2) {
|
||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||
app.Sequelize.literal('NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL)'),
|
||
];
|
||
}
|
||
}
|
||
|
||
// video_enable 筛选:1=录像可用 2=录像不可用
|
||
if (where.video_enable !== undefined && where.video_enable !== null) {
|
||
const videoEnableValue = Number(where.video_enable?.value ?? where.video_enable);
|
||
if (videoEnableValue === 1) {
|
||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||
app.Sequelize.literal("EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"),
|
||
];
|
||
} else if (videoEnableValue === 2) {
|
||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||
app.Sequelize.literal("NOT EXISTS (SELECT 1 FROM wms_pack_task_video WHERE pack_task_id = pack_task.id AND deleted_at IS NULL AND video_url != '' AND status != 'failed')"),
|
||
];
|
||
}
|
||
}
|
||
|
||
// 时间范围筛选:start_time / end_time / create_time
|
||
// 支持 {operator:'between', value:[start,end]} 或直接传 [start,end]
|
||
const applyTimeRangeFilter = (field, cond) => {
|
||
if (!cond) return;
|
||
const operator = String(cond?.operator || '').toLowerCase();
|
||
let range = cond?.value ?? cond;
|
||
if (!Array.isArray(range) && operator === 'between' && range && typeof range === 'object') {
|
||
range = [ range.start ?? range.from ?? range.begin, range.end ?? range.to ?? range.finish ];
|
||
}
|
||
if (!Array.isArray(range)) return;
|
||
const [ startVal, endVal ] = range;
|
||
if (startVal !== undefined && startVal !== null && String(startVal).trim() !== '') {
|
||
queryWhere[field] = { ...(queryWhere[field] || {}), [Op.gte]: new Date(startVal) };
|
||
}
|
||
if (endVal !== undefined && endVal !== null && String(endVal).trim() !== '') {
|
||
queryWhere[field] = { ...(queryWhere[field] || {}), [Op.lte]: new Date(endVal) };
|
||
}
|
||
};
|
||
|
||
// 开始打包时间范围(统一 between 写法 + 兼容旧拆分写法)
|
||
applyTimeRangeFilter('start_time', where.start_time);
|
||
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) };
|
||
}
|
||
}
|
||
|
||
// 结束打包时间范围
|
||
applyTimeRangeFilter('end_time', where.end_time);
|
||
|
||
// 创建时间范围
|
||
applyTimeRangeFilter('create_time', where.create_time);
|
||
|
||
// 排序
|
||
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' ],
|
||
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: { warehouse_id: warehouseId, delete_at: null },
|
||
required: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
// 扁平化输出
|
||
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
|
||
const list = rows.map(row => {
|
||
const plain = row.get({ plain: true });
|
||
const rawVideos = plain.videos || [];
|
||
const { app: appCtx } = this;
|
||
return {
|
||
...plain,
|
||
start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null,
|
||
end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null,
|
||
create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null,
|
||
update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null,
|
||
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
|
||
workbench_name: plain.workbench?.name || null,
|
||
workbench_type: plain.workbench?.type || null,
|
||
workbench_barcode: plain.workbench?.barcode || null,
|
||
has_video: rawVideos.length > 0 ? 1 : 2,
|
||
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
|
||
videos: rawVideos.map(v => ({
|
||
id: v.id,
|
||
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url),
|
||
status: v.status || null,
|
||
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' ],
|
||
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: { warehouse_id: warehouseId, delete_at: null },
|
||
required: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
if (!record) {
|
||
return { code: 404, message: '打包任务不存在或无权访问', data: null };
|
||
}
|
||
|
||
const plain = record.get({ plain: true });
|
||
const recordingComputerId = await this._getRecordingComputerId(warehouseId);
|
||
const rawVideos = plain.videos || [];
|
||
const { app: appCtx } = this;
|
||
const data = {
|
||
...plain,
|
||
start_time: plain.start_time ? appCtx.formatDate(plain.start_time) : null,
|
||
end_time: plain.end_time ? appCtx.formatDate(plain.end_time) : null,
|
||
create_time: plain.create_time ? appCtx.formatDate(plain.create_time) : null,
|
||
update_time: plain.update_time ? appCtx.formatDate(plain.update_time) : null,
|
||
deleted_at: plain.deleted_at ? appCtx.formatDate(plain.deleted_at) : null,
|
||
workbench_name: plain.workbench?.name || null,
|
||
workbench_type: plain.workbench?.type || null,
|
||
workbench_barcode: plain.workbench?.barcode || null,
|
||
has_video: rawVideos.length > 0 ? 1 : 2,
|
||
video_enable: rawVideos.some(v => v.video_url && v.status !== 'failed') ? 1 : 2,
|
||
videos: rawVideos.map(v => ({
|
||
id: v.id,
|
||
video_url: this._buildVideoUrl(warehouseId, recordingComputerId, v.video_url),
|
||
status: v.status || null,
|
||
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 };
|
||
}
|
||
|
||
/**
|
||
* 设置打包任务结束时间。
|
||
* 按 id + warehouse_id 查找任务,更新结束时间。
|
||
* 若任务状态不是已完成(2),则同时将状态更新为已完成。
|
||
* 结束时间超过仓库配置的打包最大时长上限时,自动截断为 开始时间+上限时长
|
||
* (散单 single_order_pack_max_minutes / 团购 group_order_pack_max_minutes,单位分钟)。
|
||
*
|
||
* @param {Object} options 操作参数
|
||
* @param {number} options.id 打包任务ID
|
||
* @param {string} options.end_time 结束时间(ISO 8601 或日期字符串)
|
||
* @return {Promise<Object>} 操作结果
|
||
*/
|
||
async setEndTime(options = {}) {
|
||
const { ctx } = this;
|
||
const { id, end_time } = options;
|
||
|
||
if (!id) {
|
||
return { code: 400, message: '打包任务ID不能为空', data: null };
|
||
}
|
||
if (!end_time) {
|
||
return { code: 400, message: '结束时间不能为空', 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 },
|
||
});
|
||
|
||
if (!record) {
|
||
return { code: 404, message: '打包任务不存在或无权访问', data: null };
|
||
}
|
||
|
||
const newEndTime = new Date(end_time);
|
||
|
||
// 结束时间不能早于开始时间
|
||
if (record.start_time && newEndTime < new Date(record.start_time)) {
|
||
return { code: 400, message: '结束时间不能早于开始时间', data: null };
|
||
}
|
||
|
||
// 结束时间超过仓库配置的打包最大时长上限时,截断为 开始时间+上限时长
|
||
const workbenchService = ctx.service.systems && ctx.service.systems.workbench;
|
||
const finalEndTime = workbenchService && typeof workbenchService.resolvePackTaskEndTime === 'function'
|
||
? await workbenchService.resolvePackTaskEndTime(record, newEndTime)
|
||
: newEndTime;
|
||
|
||
const updates = { end_time: finalEndTime };
|
||
|
||
// 若任务状态不是已完成(2),同步更新为已完成
|
||
if (record.status !== 2) {
|
||
updates.status = 2;
|
||
}
|
||
|
||
await record.update(updates);
|
||
|
||
return {
|
||
code: 200,
|
||
message: '结束时间设置成功',
|
||
data: {
|
||
id: record.id,
|
||
end_time: this.app.formatDate(updates.end_time),
|
||
status: updates.status,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 强制重新录制打包任务视频。
|
||
* 将任务推送到录制电脑,通过打印服务触发重新录制。
|
||
*
|
||
* @param {Object} options 操作参数
|
||
* @param {number} options.id 打包任务ID
|
||
* @return {Promise<Object>} 操作结果 { code, message, data }
|
||
*/
|
||
async forceRecord(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 };
|
||
}
|
||
|
||
// 1. 查找打包任务
|
||
const packTask = await ctx.model.PackTask.findOne({
|
||
where: { id: Number(id), warehouse_id: warehouseId },
|
||
});
|
||
if (!packTask) {
|
||
return { code: 404, message: '打包任务不存在或无权访问', data: null };
|
||
}
|
||
|
||
// 2. 查找仓库的录制电脑
|
||
const recordingComputer = await ctx.model.PrintComputer.findOne({
|
||
where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null },
|
||
raw: true,
|
||
});
|
||
if (!recordingComputer) {
|
||
return { code: 400, message: '该仓库无录制电脑,无法强制录制', data: null };
|
||
}
|
||
|
||
// 3. 检查录制电脑是否在线
|
||
const redisPrinter = ctx.app.redis.get('printer');
|
||
const onlineKey = `warehouse:${warehouseId}:printer:${recordingComputer.id}`;
|
||
const onlineInfo = await redisPrinter.get(onlineKey);
|
||
if (!onlineInfo) {
|
||
return { code: 400, message: '该仓库录制电脑不在线,无法强制录制', data: null };
|
||
}
|
||
|
||
// 4. 重置视频记录状态为 created,触发重新录制
|
||
await ctx.model.PackTaskVideo.update(
|
||
{ status: 'created', video_url: '' },
|
||
{ where: { pack_task_id: Number(id), deleted_at: null } }
|
||
);
|
||
|
||
// 5. 通知打印服务推送强制录制任务
|
||
const printServiceUrl = ctx.app.config.printService.url;
|
||
const requestData = { pack_task_id: Number(id) };
|
||
let printServiceResponse = null;
|
||
let printServiceError = null;
|
||
try {
|
||
const res = await ctx.curl(`${printServiceUrl}/record/force`, {
|
||
method: 'POST',
|
||
contentType: 'json',
|
||
data: requestData,
|
||
dataType: 'json',
|
||
timeout: 10000,
|
||
});
|
||
printServiceResponse = {
|
||
status: res.status,
|
||
headers: res.headers,
|
||
data: res.data,
|
||
};
|
||
} catch (err) {
|
||
printServiceError = err.message;
|
||
ctx.logger.warn(`通知打印服务强制录制 pack_task_id=${id} 失败: ${err.message}`);
|
||
}
|
||
|
||
return {
|
||
code: printServiceError ? 500 : 200,
|
||
message: printServiceError ? `通知打印服务失败: ${printServiceError}` : '强制录制任务已推送',
|
||
data: {
|
||
pack_task_id: Number(id),
|
||
computer_id: recordingComputer.id,
|
||
print_service_url: `${printServiceUrl}/record/force`,
|
||
print_service_request: requestData,
|
||
print_service_response: printServiceResponse,
|
||
print_service_error: printServiceError,
|
||
},
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = OrderPackingService;
|