order.packing.list / order.packing.export 新增 where.operator_text(打包员,目标列 wms_pack_task.operator_text,多人姓名逗号拼接快照):
支持 {operator,value,type} 标准结构,value 支持字符串或数组(多值取并集);contains/like 与缺省为 LIKE '%值%'(通配符已转义)、
eq/in 精确、ne 不等、notlike 逐个排除;值为 ''/null/空数组时忽略该条件。
returnUnpack.list / returnUnpack.export 新增 where.unpacker_name(拆包人,目标列 wms_return_unpack.unpacker_name 工号名称快照):
{operator:'like',value} 或直接值为 LIKE '%值%',value 为数组时多值 LIKE 取并集(_resolveConditionValue 的 like 分支增强,标量行为不变);
文本字段循环跳过空值条件,避免生成 unpacker_name IS NULL 的恒空条件。两个 export 与 list 复用同一 _buildListWhere,语义自动对齐。
顺带修复:where.operator_text=null 经 prepareWhereContext 归一为 {operator:'eq',value:null} 后,
原「?.value ?? 原条件对象」写法会 String() 出 '[object Object]' 条件把列表清空,改为「条件对象只取 .value」。
文档:methods/system.json 更新 order.packing.list/export 与 returnUnpack.list/export 共 4 处参数说明(版本 0.3.190→0.3.191),
methods/changes/system.json 追加变更记录 2026.09.26-order-packing-returnUnpack-where-person-filter。
测试:新增 order_packing.list.operatorText(13 例)与 return_unpack.list.unpackerName(6 例),
test/support/where_matcher.js 补充字段级 Op.or/Op.and/Op.not 支持;相关 4 个测试文件 37 passing。
1226 lines
52 KiB
JavaScript
1226 lines
52 KiB
JavaScript
'use strict';
|
||
|
||
const crypto = require('node:crypto');
|
||
const fs = require('node:fs');
|
||
const fsp = require('node:fs/promises');
|
||
const os = require('node:os');
|
||
const path = require('node:path');
|
||
const ExcelJS = require('exceljs');
|
||
const Service = require('egg').Service;
|
||
const { stripWaybillSegmentSuffix, escapeLikeWildcards } = require('../../lib/waybill_code');
|
||
|
||
/** 打包任务导出主表分页拉取大小 */
|
||
const PACK_TASK_EXPORT_PAGE_SIZE = 500;
|
||
/** 打包任务导出关联数据分批拉取大小 */
|
||
const PACK_TASK_EXPORT_BATCH_SIZE = 100;
|
||
|
||
/**
|
||
* 快捷搜索运单号模糊降级的最小关键词长度。
|
||
* 运单号通常较长(如 JDX057941864338),短于该长度的输入(如单字符 "7")没有模糊搜索意义,
|
||
* 且 %短词% 极易误命中海量历史单号(实测 "7" 可命中 24149 行),
|
||
* 违背「不完整短串不得命中订单」的业务约束,因此禁止短词降级进入 %kw% 模糊分支。
|
||
*/
|
||
const QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH = 4;
|
||
|
||
/**
|
||
* 打包任务服务层(仓库侧)。
|
||
* 负责打包任务列表查询、详情查询等仓库维度的打包管理业务逻辑。
|
||
* 数据来源: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}`;
|
||
}
|
||
|
||
/**
|
||
* 创建带业务错误码的异常对象。
|
||
*
|
||
* @param {string} message 错误信息。
|
||
* @param {number} [code=400] 业务错误码。
|
||
* @return {Error} 包含 code 的异常对象。
|
||
*/
|
||
createBusinessError(message, code = 400) {
|
||
const error = new Error(`${message}`);
|
||
error.code = code;
|
||
return error;
|
||
}
|
||
|
||
/**
|
||
* 构建列表筛选条件(list 与 exportPackTask 复用同一套语义,导出会自动获得同一筛选语义)。
|
||
*
|
||
* @param {Object} where 筛选条件对象(与 list 入参一致)。其中 operator_text(打包员/作业人员姓名,
|
||
* 对应 wms_pack_task.operator_text 多人姓名逗号拼接快照列)支持 {operator,value} 标准结构,
|
||
* value 支持字符串或字符串数组(多值取并集):contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义)、
|
||
* eq/in 精确(单值等值、多值 Op.in)、ne 不等于(取首值)、notlike 排除(多值逐个排除)。
|
||
* @param {Object} Op Sequelize Op 对象
|
||
* @param {number} warehouseId 仓库ID
|
||
* @return {Promise<Object>} Sequelize where 条件对象
|
||
*/
|
||
async _buildListWhere(where = {}, Op, warehouseId) {
|
||
const { ctx, app } = this;
|
||
|
||
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 通常为空)。
|
||
// 支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多单号取并集):
|
||
// - operator=contains/like:按下发单号模糊匹配 LIKE '%单号%'(通配符已转义),可命中 '主体-1-1-' 等分段单号;
|
||
// - 其他(缺省/eq):完整单号等值 + 剥离 -1-1- 分段后缀主体等值 + 主体前缀 LIKE '主体-%',
|
||
// 不落入 %短串% 模糊分支(保持「不完整短串不得命中订单」的业务约束)。
|
||
if (where.waybill_code) {
|
||
const waybillValue = where.waybill_code?.value ?? where.waybill_code;
|
||
const waybillOperator = String(where.waybill_code?.operator || '').trim().toLowerCase();
|
||
const waybillList = (Array.isArray(waybillValue) ? waybillValue : [ waybillValue ])
|
||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||
.filter(Boolean);
|
||
|
||
if (waybillList.length > 0) {
|
||
const isContainsWaybill = waybillOperator === 'contains' || waybillOperator === 'like';
|
||
const waybillConditions = [];
|
||
|
||
for (const waybillCode of waybillList) {
|
||
if (isContainsWaybill) {
|
||
waybillConditions.push({
|
||
waybill_code: { [Op.like]: `%${escapeLikeWildcards(waybillCode)}%` },
|
||
});
|
||
continue;
|
||
}
|
||
|
||
// 剥离分段后缀得到主体运单号(JDX057941864338-1-1- → JDX057941864338)
|
||
const baseWaybill = stripWaybillSegmentSuffix(waybillCode);
|
||
const escapedBase = escapeLikeWildcards(baseWaybill);
|
||
// 等值匹配集合:完整单号等值 + 主体单号等值 + 主体单号前缀段(主体相同、分段序号不同)
|
||
waybillConditions.push({ waybill_code: waybillCode });
|
||
if (baseWaybill !== waybillCode) {
|
||
waybillConditions.push({ waybill_code: baseWaybill });
|
||
}
|
||
if (escapedBase) {
|
||
waybillConditions.push({ waybill_code: { [Op.like]: `${escapedBase}-%` } });
|
||
}
|
||
}
|
||
|
||
const expressRecords = await ctx.model.OrderExpress.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
delete_at: null,
|
||
[Op.or]: waybillConditions,
|
||
},
|
||
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;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 波次号筛选:支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集)。
|
||
// - operator=eq / in:精确匹配(单值等值,多值 Op.in);
|
||
// - operator=ne:不等于;
|
||
// - operator=contains / like 与缺省:模糊匹配 LIKE '%值%'(通配符已转义,缺省保持历史模糊行为)。
|
||
if (where.wave_no) {
|
||
const waveNoValue = where.wave_no?.value ?? where.wave_no;
|
||
const waveNoOperator = String(where.wave_no?.operator || '').trim().toLowerCase();
|
||
const waveNoList = (Array.isArray(waveNoValue) ? waveNoValue : [ waveNoValue ])
|
||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||
.filter(Boolean);
|
||
|
||
if (waveNoList.length > 0) {
|
||
if (waveNoOperator === 'eq' || waveNoOperator === 'in') {
|
||
queryWhere.wave_no = waveNoList.length === 1 ? waveNoList[0] : { [Op.in]: waveNoList };
|
||
} else if (waveNoOperator === 'ne') {
|
||
queryWhere.wave_no = { [Op.ne]: waveNoList[0] };
|
||
} else if (waveNoList.length === 1) {
|
||
queryWhere.wave_no = { [Op.like]: `%${escapeLikeWildcards(waveNoList[0])}%` };
|
||
} else {
|
||
const likeConditions = waveNoList.map(
|
||
item => ({ wave_no: { [Op.like]: `%${escapeLikeWildcards(item)}%` } })
|
||
);
|
||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||
{ [Op.or]: likeConditions },
|
||
];
|
||
}
|
||
}
|
||
}
|
||
|
||
// 打包员(作业人员)筛选:wms_pack_task.operator_text 为多人姓名逗号拼接快照(如 '小吴哥,阿猫')。
|
||
// 支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集):
|
||
// - operator=contains / like 与缺省:模糊匹配 LIKE '%值%'(通配符已转义);
|
||
// - operator=eq / in:精确匹配(单值等值,多值 Op.in);
|
||
// - operator=ne:不等于(取首值);
|
||
// - operator=notlike:NOT LIKE '%值%'(多值时逐个排除)。
|
||
// 本函数同时被 list 与 exportPackTask 复用,因此导出 Excel 会自动获得同一筛选语义。
|
||
if (where.operator_text) {
|
||
// 空值识别:仅当条件是对象且 value 为 null/undefined 时视为空(忽略该条件、不过滤),
|
||
// 不得回退到条件对象本身,否则会被 String 化为 '[object Object]' 产生恒空过滤。
|
||
const operatorTextCondition = where.operator_text;
|
||
const isConditionObject = operatorTextCondition
|
||
&& typeof operatorTextCondition === 'object'
|
||
&& !Array.isArray(operatorTextCondition);
|
||
const operatorTextRawValue = isConditionObject ? operatorTextCondition.value : operatorTextCondition;
|
||
const operatorTextOperator = isConditionObject
|
||
? String(operatorTextCondition.operator || '').trim().toLowerCase()
|
||
: '';
|
||
const operatorTextList = (Array.isArray(operatorTextRawValue) ? operatorTextRawValue : [ operatorTextRawValue ])
|
||
.map(item => (item === undefined || item === null ? '' : String(item).trim()))
|
||
.filter(Boolean);
|
||
|
||
if (operatorTextList.length > 0) {
|
||
if (operatorTextOperator === 'eq' || operatorTextOperator === 'in') {
|
||
queryWhere.operator_text = operatorTextList.length === 1
|
||
? operatorTextList[0]
|
||
: { [Op.in]: operatorTextList };
|
||
} else if (operatorTextOperator === 'ne') {
|
||
queryWhere.operator_text = { [Op.ne]: operatorTextList[0] };
|
||
} else if (operatorTextOperator === 'notlike') {
|
||
if (operatorTextList.length === 1) {
|
||
queryWhere.operator_text = { [Op.notLike]: `%${escapeLikeWildcards(operatorTextList[0])}%` };
|
||
} else {
|
||
const notLikeConditions = operatorTextList.map(
|
||
item => ({ operator_text: { [Op.notLike]: `%${escapeLikeWildcards(item)}%` } })
|
||
);
|
||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []), ...notLikeConditions ];
|
||
}
|
||
} else if (operatorTextList.length === 1) {
|
||
queryWhere.operator_text = { [Op.like]: `%${escapeLikeWildcards(operatorTextList[0])}%` };
|
||
} else {
|
||
const likeConditions = operatorTextList.map(
|
||
item => ({ operator_text: { [Op.like]: `%${escapeLikeWildcards(item)}%` } })
|
||
);
|
||
queryWhere[Op.and] = [ ...(queryWhere[Op.and] || []),
|
||
{ [Op.or]: likeConditions },
|
||
];
|
||
}
|
||
}
|
||
}
|
||
|
||
// 订单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 表
|
||
// 业务规则:先剥离包裹序号后缀(如 -1-1-),主体运单号等值匹配为最高优先级;
|
||
// 精确未命中时才降级为模糊 like,保留快捷搜索能力
|
||
const baseKw = stripWaybillSegmentSuffix(kw);
|
||
const escapedKw = escapeLikeWildcards(baseKw);
|
||
const exactWaybillConditions = [
|
||
{ waybill_code: kw },
|
||
...(baseKw !== kw ? [{ waybill_code: baseKw }] : []),
|
||
...(escapedKw ? [{ waybill_code: { [Op.like]: `${escapedKw}-%` } }] : []),
|
||
];
|
||
let expressRecords = await ctx.model.OrderExpress.findAll({
|
||
where: {
|
||
[Op.or]: exactWaybillConditions,
|
||
warehouse_id: warehouseId,
|
||
delete_at: null,
|
||
},
|
||
attributes: [ 'order_id' ],
|
||
raw: true,
|
||
});
|
||
// 精确未命中 → 降级为模糊匹配(兼容快捷搜索输入非完整运单号的场景)
|
||
// 关键词校验:短词(trim 后长度小于 QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH,含纯单字符)
|
||
// 禁止降级进入 %kw% 模糊分支——运单号通常较长,%短词% 极易误命中大量历史单号,
|
||
// 违背「不完整短串不得命中订单」的业务约束,此时运单号解析保持空结果
|
||
if (expressRecords.length === 0 && kw.length >= QUICK_WHERE_WAYBILL_FUZZY_MIN_LENGTH) {
|
||
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);
|
||
|
||
return queryWhere;
|
||
}
|
||
|
||
/**
|
||
* 构建列表排序(list 与 export 复用同一套语义)。
|
||
* @param {Object} sort 排序参数 { sortField, sortOrder }
|
||
* @return {Array} Sequelize order 数组
|
||
*/
|
||
_buildListOrder(sort = {}) {
|
||
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';
|
||
return [[ actualSortField, sortOrder ]];
|
||
}
|
||
/**
|
||
* 打包任务列表查询(仓库侧)。
|
||
* 按仓库维度(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 后过滤)。支持 {operator,value} 标准结构,value 支持字符串或数组:
|
||
* operator=contains/like 时按 LIKE '%单号%' 模糊匹配(可命中分段单号);缺省/eq 时先剥离一单多件分段后缀、主体单号等值匹配 + 主体前缀匹配
|
||
* @param {Object} [where.wave_no] 波次号。支持 {operator,value} 标准结构,value 支持字符串或数组:eq/in 精确、ne 不等、contains/like 与缺省为模糊匹配
|
||
* @param {Object} [where.operator_text] 打包员/作业人员姓名(wms_pack_task.operator_text 快照列,多人姓名逗号拼接)。支持 {operator,value} 标准结构,value 支持字符串或数组:contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除)
|
||
* @param {Object} [where.order_id] 订单ID(精确匹配)
|
||
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
|
||
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查;运单号先剥离分段后缀等值匹配,精确未命中且关键词长度≥4 时才降级模糊,短词禁止降级避免误命中)
|
||
* @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 = await this._buildListWhere(where, Op, warehouseId);
|
||
|
||
|
||
// 排序(与导出复用同一套排序语义)
|
||
const order = this._buildListOrder(sort);
|
||
|
||
// 查询(含工作台、视频和运单关联)
|
||
// 性能优化:count 与 rows 分离。findAndCountAll 携带 hasMany include(videos/expresses)时,
|
||
// count 会生成 COUNT(DISTINCT) + 双 LEFT JOIN(生产实测 520ms),拆开后 count 走单表索引(约 44ms)。
|
||
const count = await ctx.model.PackTask.count({ where: queryWhere });
|
||
const rows = await ctx.model.PackTask.findAll({
|
||
where: queryWhere,
|
||
order,
|
||
limit: pageSize,
|
||
offset: (page - 1) * pageSize,
|
||
include: [
|
||
{
|
||
model: ctx.model.Workbench,
|
||
as: 'workbench',
|
||
attributes: [ 'id', 'name', 'type' ],
|
||
},
|
||
{
|
||
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,
|
||
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,
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 导出打包任务列表(单 Sheet Excel,异步任务内部调用)。
|
||
* 复用 list 的 where/sort 语义;仓库隔离由方法层注入 warehouseId,此处再强制兜底;
|
||
* 分页拉取主表全量数据后批量关联工作台/视频/运单,流式生成 Excel 并上传。
|
||
*
|
||
* @param {Object} options 导出选项。
|
||
* @param {Object} [options.where] 标准化 where 条件(与 list 一致)。
|
||
* @param {Object} [options.sort] 排序参数(与 list 一致)。
|
||
* @param {number} [options.warehouseId] 仓库ID(由方法层从上下文注入)。
|
||
* @param {Function} [options.onProgress] 进度回调。
|
||
* @return {Promise<Object>} 上传结果与统计信息(含 url/cdnUrl/cosUrl/fileKey/current_count/total_count/sheet_count)。
|
||
*/
|
||
async exportPackTask(options = {}) {
|
||
const { ctx, app } = this;
|
||
const { Op } = app.Sequelize;
|
||
const safeOptions = options && typeof options === 'object' && !Array.isArray(options) ? options : {};
|
||
const where = safeOptions.where && typeof safeOptions.where === 'object' ? { ...safeOptions.where } : {};
|
||
const sort = safeOptions.sort && typeof safeOptions.sort === 'object' ? { ...safeOptions.sort } : {};
|
||
const warehouseId = Number(safeOptions.warehouseId || 0);
|
||
const progressHandler = typeof safeOptions.onProgress === 'function'
|
||
? safeOptions.onProgress
|
||
: async () => {};
|
||
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
throw this.createBusinessError('缺少仓库上下文', 400);
|
||
}
|
||
|
||
// 复用 list 的 where/sort 语义,并强制仓库隔离(服务端注入,前端无需传 warehouse_id)
|
||
const queryWhere = await this._buildListWhere(where, Op, warehouseId);
|
||
const order = this._buildListOrder(sort);
|
||
|
||
const totalCount = await ctx.model.PackTask.count({ where: queryWhere });
|
||
|
||
await progressHandler({
|
||
status: 'running',
|
||
progress: totalCount > 0 ? 10 : 85,
|
||
currentCount: 0,
|
||
totalCount,
|
||
message: totalCount > 0 ? `已命中 ${totalCount} 条打包任务,开始导出` : '未命中数据,开始生成空文件',
|
||
});
|
||
|
||
// ---- 分页拉取主表全量数据 ----
|
||
const allTaskRows = [];
|
||
let page = 1;
|
||
while (allTaskRows.length < totalCount) {
|
||
const rows = await ctx.model.PackTask.findAll({
|
||
where: queryWhere,
|
||
order,
|
||
limit: PACK_TASK_EXPORT_PAGE_SIZE,
|
||
offset: (page - 1) * PACK_TASK_EXPORT_PAGE_SIZE,
|
||
raw: true,
|
||
});
|
||
if (!Array.isArray(rows) || rows.length === 0) {
|
||
break;
|
||
}
|
||
allTaskRows.push(...rows);
|
||
page += 1;
|
||
await progressHandler({
|
||
status: 'running',
|
||
progress: Math.min(30, 10 + Math.round((allTaskRows.length / Math.max(totalCount, 1)) * 20)),
|
||
currentCount: allTaskRows.length,
|
||
totalCount,
|
||
message: `正在拉取打包任务列表,已完成 ${allTaskRows.length}/${totalCount}`,
|
||
});
|
||
}
|
||
|
||
// ---- 批量拉取关联数据(工作台 / 视频 / 运单) ----
|
||
const taskIds = allTaskRows
|
||
.map(row => Number(row.id))
|
||
.filter(id => Number.isInteger(id) && id > 0);
|
||
const workbenchIds = [ ...new Set(
|
||
allTaskRows.map(row => Number(row.workbench_id || 0)).filter(id => Number.isInteger(id) && id > 0)
|
||
) ];
|
||
const orderIds = [ ...new Set(
|
||
allTaskRows.map(row => Number(row.order_id || 0)).filter(id => Number.isInteger(id) && id > 0)
|
||
) ];
|
||
|
||
/** @type {Map<number, Object>} */
|
||
const workbenchMap = new Map();
|
||
if (workbenchIds.length > 0) {
|
||
const workbenches = await ctx.model.Workbench.findAll({
|
||
where: { id: { [Op.in]: workbenchIds } },
|
||
attributes: [ 'id', 'name', 'type' ],
|
||
raw: true,
|
||
});
|
||
for (const wb of workbenches) {
|
||
workbenchMap.set(Number(wb.id), wb);
|
||
}
|
||
}
|
||
|
||
/** @type {Map<number, Array<Object>>} */
|
||
const videosMap = new Map();
|
||
if (taskIds.length > 0) {
|
||
for (let idx = 0; idx < taskIds.length; idx += PACK_TASK_EXPORT_BATCH_SIZE) {
|
||
const batchIds = taskIds.slice(idx, idx + PACK_TASK_EXPORT_BATCH_SIZE);
|
||
const videos = await ctx.model.PackTaskVideo.findAll({
|
||
where: { pack_task_id: { [Op.in]: batchIds } },
|
||
attributes: [ 'id', 'pack_task_id', 'video_url', 'camera_id', 'status' ],
|
||
raw: true,
|
||
});
|
||
for (const video of videos) {
|
||
const key = Number(video.pack_task_id);
|
||
if (!videosMap.has(key)) {
|
||
videosMap.set(key, []);
|
||
}
|
||
videosMap.get(key).push(video);
|
||
}
|
||
}
|
||
}
|
||
|
||
/** @type {Map<number, string>} */
|
||
const cameraNameMap = new Map();
|
||
const cameraIds = [ ...new Set(
|
||
Array.from(videosMap.values())
|
||
.flat()
|
||
.map(v => Number(v.camera_id || 0))
|
||
.filter(id => Number.isInteger(id) && id > 0)
|
||
) ];
|
||
if (cameraIds.length > 0) {
|
||
const cameras = await ctx.model.Camera.findAll({
|
||
where: { id: { [Op.in]: cameraIds } },
|
||
attributes: [ 'id', 'custom_name', 'channel_name' ],
|
||
raw: true,
|
||
});
|
||
for (const camera of cameras) {
|
||
cameraNameMap.set(Number(camera.id), camera.custom_name || camera.channel_name || '');
|
||
}
|
||
}
|
||
|
||
/** @type {Map<number, Array<Object>>} */
|
||
const expressesMap = new Map();
|
||
if (orderIds.length > 0) {
|
||
for (let idx = 0; idx < orderIds.length; idx += PACK_TASK_EXPORT_BATCH_SIZE) {
|
||
const batchOrderIds = orderIds.slice(idx, idx + PACK_TASK_EXPORT_BATCH_SIZE);
|
||
const expresses = await ctx.model.OrderExpress.findAll({
|
||
where: {
|
||
order_id: { [Op.in]: batchOrderIds },
|
||
warehouse_id: warehouseId,
|
||
delete_at: null,
|
||
},
|
||
attributes: [ 'id', 'order_id', 'waybill_code' ],
|
||
raw: true,
|
||
});
|
||
for (const express of expresses) {
|
||
const key = Number(express.order_id);
|
||
if (!expressesMap.has(key)) {
|
||
expressesMap.set(key, []);
|
||
}
|
||
expressesMap.get(key).push(express);
|
||
}
|
||
}
|
||
}
|
||
|
||
await progressHandler({
|
||
status: 'running',
|
||
progress: 55,
|
||
currentCount: allTaskRows.length,
|
||
totalCount,
|
||
message: '正在生成 Excel 文件...',
|
||
});
|
||
|
||
// ---- 生成 Excel(流式写入,单 Sheet) ----
|
||
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-pack-task-export-'));
|
||
const now = new Date();
|
||
const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
|
||
const filename = `打包任务导出_${dateToken}.xlsx`;
|
||
const filePath = path.join(tempDir, filename);
|
||
const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({
|
||
filename: filePath,
|
||
useStyles: false,
|
||
useSharedStrings: false,
|
||
});
|
||
|
||
const normalizeCellValue = value => {
|
||
if (value === null || value === undefined) return '';
|
||
if (value instanceof Date) return app.formatDate ? app.formatDate(value) : value.toISOString();
|
||
return value;
|
||
};
|
||
const formatDateTime = value => (value ? app.formatDate(value) : '');
|
||
|
||
const PACK_MODE_TEXT = { 1: '散单', 2: '团购' };
|
||
const STATUS_TEXT = { 0: '待处理', 1: '打包中', 2: '已完成', 3: '异常' };
|
||
|
||
try {
|
||
const sheet = workbook.addWorksheet('打包任务列表');
|
||
sheet.columns = [
|
||
{ header: '任务ID', key: 'id', width: 14 },
|
||
{ header: '订单ID', key: 'order_id', width: 14 },
|
||
{ header: '波次号', key: 'wave_no', width: 18 },
|
||
{ header: '运单号', key: 'waybill_code', width: 22 },
|
||
{ header: '关联运单号', key: 'waybill_codes', width: 30 },
|
||
{ header: '打包模式', key: 'pack_mode_text', width: 10 },
|
||
{ header: '任务状态', key: 'status_text', width: 10 },
|
||
{ header: '打包数量', key: 'pack_quantity', width: 10 },
|
||
{ header: '商品总数量', key: 'item_quantity', width: 12 },
|
||
{ header: '商品种类数', key: 'sku_count', width: 12 },
|
||
{ header: '工作台', key: 'workbench_name', width: 14 },
|
||
{ header: '作业人员', key: 'operator_text', width: 20 },
|
||
{ header: '开始打包时间', key: 'start_time', width: 20 },
|
||
{ header: '结束打包时间', key: 'end_time', width: 20 },
|
||
{ header: '创建时间', key: 'create_time', width: 20 },
|
||
{ header: '视频状态', key: 'has_video_text', width: 10 },
|
||
{ header: '录像可用', key: 'video_enable_text', width: 10 },
|
||
{ header: '备注', key: 'remark', width: 30 },
|
||
];
|
||
|
||
for (const row of allTaskRows) {
|
||
const taskId = Number(row.id);
|
||
const workbench = workbenchMap.get(Number(row.workbench_id || 0));
|
||
const videos = videosMap.get(taskId) || [];
|
||
const expresses = expressesMap.get(Number(row.order_id || 0)) || [];
|
||
const waybillCodes = expresses
|
||
.map(e => e.waybill_code)
|
||
.filter(code => code && String(code).trim())
|
||
.join(', ');
|
||
const hasVideo = videos.length > 0;
|
||
const videoEnable = videos.some(v => v.video_url && v.status !== 'failed');
|
||
|
||
sheet.addRow({
|
||
id: taskId,
|
||
order_id: row.order_id,
|
||
wave_no: normalizeCellValue(row.wave_no),
|
||
waybill_code: normalizeCellValue(row.waybill_code),
|
||
waybill_codes: waybillCodes,
|
||
pack_mode_text: PACK_MODE_TEXT[Number(row.pack_mode)] || '',
|
||
status_text: STATUS_TEXT[Number(row.status)] || '',
|
||
pack_quantity: row.pack_quantity,
|
||
item_quantity: row.item_quantity,
|
||
sku_count: row.sku_count,
|
||
workbench_name: workbench ? normalizeCellValue(workbench.name) : '',
|
||
operator_text: normalizeCellValue(row.operator_text),
|
||
start_time: formatDateTime(row.start_time),
|
||
end_time: formatDateTime(row.end_time),
|
||
create_time: formatDateTime(row.create_time),
|
||
has_video_text: hasVideo ? '有视频' : '无视频',
|
||
video_enable_text: videoEnable ? '可用' : '不可用',
|
||
remark: normalizeCellValue(row.remark),
|
||
}).commit();
|
||
}
|
||
sheet.commit();
|
||
|
||
await workbook.commit();
|
||
|
||
await progressHandler({
|
||
status: 'running',
|
||
progress: 92,
|
||
currentCount: allTaskRows.length,
|
||
totalCount,
|
||
message: '正在上传文件...',
|
||
});
|
||
|
||
// ---- 上传文件 ----
|
||
const uploadService = ctx?.service?.systems?.upload;
|
||
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
|
||
throw new Error('上传服务不可用');
|
||
}
|
||
|
||
const stat = await fsp.stat(filePath);
|
||
const randomToken = crypto.randomBytes(6).toString('hex');
|
||
const uploadKey = `exports/pack_task/${warehouseId}/${Date.now()}_${randomToken}.xlsx`;
|
||
const uploadStream = fs.createReadStream(filePath);
|
||
uploadStream.filename = filename;
|
||
uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
||
uploadStream.fileSize = stat.size;
|
||
|
||
const uploadResult = await uploadService.uploadFile(uploadStream, {
|
||
key: uploadKey,
|
||
category: 'document',
|
||
mimetype: 'xls,xlsx,csv',
|
||
});
|
||
|
||
let fileRecord = null;
|
||
if (typeof uploadService.uploadSuccessNotify === 'function') {
|
||
fileRecord = await uploadService.uploadSuccessNotify({
|
||
url: uploadResult.fileName,
|
||
fileKey: uploadResult.fileName,
|
||
fileName: filename,
|
||
fileType: 'document',
|
||
mimeType: uploadStream.mimeType,
|
||
fileSize: stat.size,
|
||
userId: ctx.userId,
|
||
description: `打包任务导出(仓库${warehouseId}),共${totalCount}条打包任务`,
|
||
});
|
||
}
|
||
|
||
// 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录(兼容 data 包裹),最后才回退 COS key
|
||
const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {};
|
||
const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null;
|
||
const fileUrlFromRecord = resolvedFileRecord
|
||
? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '')
|
||
: '';
|
||
const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || '';
|
||
|
||
const uploadInfo = {
|
||
filename,
|
||
fileKey: safeUploadResult.fileName || uploadKey,
|
||
url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey,
|
||
cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '',
|
||
cosUrl: safeUploadResult.cosUrl || '',
|
||
current_count: allTaskRows.length,
|
||
total_count: totalCount,
|
||
sheet_count: 1,
|
||
};
|
||
|
||
await progressHandler({
|
||
status: 'success',
|
||
progress: 100,
|
||
currentCount: allTaskRows.length,
|
||
totalCount,
|
||
message: '导出任务完成',
|
||
result: uploadInfo,
|
||
});
|
||
|
||
return uploadInfo;
|
||
} catch (error) {
|
||
const workbookStream = workbook.stream;
|
||
if (workbookStream && typeof workbookStream.destroy === 'function') {
|
||
workbookStream.destroy();
|
||
}
|
||
throw error;
|
||
} finally {
|
||
// 清理临时文件(不存在或删除失败均忽略)
|
||
try { await fsp.rm(tempDir, { recursive: true, force: true }); } catch (err) { /* ignore */ }
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 打包任务详情查询。
|
||
* 按 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' ],
|
||
},
|
||
{
|
||
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,
|
||
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),同步更新为已完成
|
||
const wasFinished = record.status === 2;
|
||
if (!wasFinished) {
|
||
updates.status = 2;
|
||
}
|
||
|
||
await record.update(updates);
|
||
|
||
// 任务由未结束转为已完成时,同步更新关联订单打包状态(与 workbench.finishPack 语义一致)
|
||
if (!wasFinished && updates.status === 2 && workbenchService
|
||
&& typeof workbenchService._updateOrderPackStatus === 'function') {
|
||
const isGroupTask = Number(record.pack_mode) === 2;
|
||
const taskWaveId = isGroupTask ? Number(record.wave_id || 0) : 0;
|
||
await workbenchService._updateOrderPackStatus(warehouseId, {
|
||
orderId: Number(record.order_id || 0),
|
||
waveId: taskWaveId,
|
||
packStatus: 2,
|
||
caller: 'OrderPacking.setEndTime',
|
||
});
|
||
}
|
||
|
||
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;
|