liufumingren aca6867d57 feat(order,return): 打包任务列表新增打包员筛选、拆包单列表新增拆包人筛选
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。
2026-09-26 19:03:48 +08:00

371 lines
14 KiB
JavaScript
Raw Permalink 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 MainService = require('../../main');
const PACKING_EXPORT_TASK_CACHE_KEY_PREFIX = 'packing_export_task_';
const PACKING_EXPORT_TASK_CACHE_TTL_SECONDS = 1800;
/**
* 系统方法层:order.packing(打包任务接口包装层)。
* 主要职责:统一包装系统方法接口,处理权限、日志等公共逻辑,调用底层 service 实现业务功能。
* 注意:当前实现仅为包装层,实际业务逻辑完全依赖底层 service 的方法实现。
*/
class OrderPackingMethodService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
// 免权限方法列表:export/exportTaskProgress 免权限(异步任务模式,与 order.export 口径一致,无 wms_permission 记录)
const _noNeedRight = 'list,get,export,exportTaskProgress';
// 免日志方法列表:导出与进度查询不记录操作日志(与订单导出口径一致)
const _noNeedLog = 'list,get,export,exportTaskProgress';
// 免鉴权(仓库有效期检查)方法列表:导出与进度查询不检查仓库有效期(与订单导出口径一致)
const _noNeedAuth = 'list,get,export,exportTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
/**
* 打包任务列表查询(仓库侧 system method 包装层)。
* 按仓库维度查询打包任务,支持分页、筛选、排序。
*
* @param {Object} data 请求体
* @param {Object} [data.pagination] 分页参数 { page, pageSize }
* @param {Object} [data.where] 筛选条件。
* 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、
* order_id(订单ID)、workbench_id(工作台ID)、operator_text(打包员/作业人员姓名)、
* quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、
* start_time(开始打包时间范围,{operator:'between', value:[start,end]})、end_time(结束打包时间范围)、create_time(创建时间范围);
* start_time_start / start_time_end 为开始时间范围的兼容旧写法。
* 运单号与波次号字段支持 {operator, value} 标准结构且 value 支持数组:
* operator=contains/like 时按 LIKE '%值%' 模糊匹配(waybill_code 可命中 '主体-1-1-' 等分段单号),wave_no 另支持 eq/in 精确、ne 不等;
* waybill_code 缺省/eq 时为「完整单号等值 + 剥离分段后缀主体等值 + 主体前缀」精确匹配。
* operator_text(打包员/作业人员姓名)支持 {operator,value} 标准结构且 value 支持数组:
* contains/like 与缺省为模糊 LIKE '%值%'(通配符已转义、多值取并集)、eq/in 精确、ne 不等于(取首值)、notlike 排除(多值逐个排除)。
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
* @return {Promise<Object>} 统一成功包装响应
*/
async list(data = {}) {
const { service } = this;
const { pagination, sort } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
const result = await service.systems.orderPacking.list(where, pagination, sort);
return this.success('ok', result);
}
/**
* 打包任务详情查询(仓库侧 system method 包装层)。
*
* @param {Object} data 请求体
* @param {number} data.id 打包任务ID
* @return {Promise<Object>} 统一成功包装响应
*/
async get(data = {}) {
const { service } = this;
const { id } = data;
const result = await service.systems.orderPacking.get({ id });
return this.success('ok', result);
}
/**
* 设置打包任务结束时间(仓库侧 system method 包装层)。
* 若任务状态不是已完成,则同步更新状态为已完成。
* 前端默认值逻辑:已有结束时间→当前时间;无结束时间→开始时间+5分钟。
* 结束时间超过仓库配置的打包最大时长上限时,自动截断为上限时间。
*
* @param {Object} data 请求体
* @param {number} data.id 打包任务ID
* @param {string} data.end_time 结束时间(ISO 8601 或日期字符串)
* @return {Promise<Object>} 统一成功包装响应
*/
async setEndTime(data = {}) {
const { service } = this;
const { id, end_time } = data;
const result = await service.systems.orderPacking.setEndTime({ id, end_time });
return this.success('ok', result);
}
/**
* 强制重新录制打包任务视频(仓库侧 system method 包装层)。
* 将该任务推送到录制电脑,通过打印服务触发重新录制。
*
* @param {Object} data 请求体
* @param {number} data.id 打包任务ID
* @return {Promise<Object>} 统一成功包装响应
*/
async forceRecord(data = {}) {
const { service } = this;
const { id } = data;
const result = await service.systems.orderPacking.forceRecord({ id });
return this.success('ok', result);
}
/**
* 提交打包任务导出任务(异步任务模式,与 order.export 口径一致)。
* 入参 where/sort 与 list 完全一致;提交后立即返回 task_id,
* 后台异步生成单 Sheet Excel(打包任务列表)并上传,
* 通过 exportTaskProgress 查询进度与下载链接。
*
* @param {Object} data 请求体。
* @param {Object} [data.where] 筛选条件(与 list 的 where 语义一致)。
* @param {Object} [data.sort] 排序参数(与 list 的 sort 语义一致)。
* @return {Promise<Object>} 统一成功包装响应(含 task_id/status/progress 等任务信息)。
*/
async export(data = {}) {
const { service } = this;
const { sort } = data;
const { where } = this.prepareWhereContext(data, {
specialFieldMap: {
quickWhere: {
bucket: 'quick',
},
},
});
// 仓库隔离:由服务端从当前上下文自动注入,禁止前端传入
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id || 0);
const enforcedWhere = { ...where };
if (warehouseId > 0) {
enforcedWhere.warehouse_id = { operator: 'eq', value: warehouseId };
}
const taskId = this.generateExportTaskId(warehouseId);
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 service.systems.orderPacking.exportPackTask({
where: enforcedWhere,
sort,
warehouseId,
onProgress: async progress => {
const safeProgress = this.isPlainObject(progress) ? progress : {};
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: safeProgress.status || 'running',
progress: safeProgress.progress,
current_count: safeProgress.currentCount,
total_count: safeProgress.totalCount,
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,
current_count: 0,
total_count: 0,
message: '打包任务导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询打包任务导出任务进度(与 order.exportTaskProgress 口径一致)。
*
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @return {Promise<Object>} 统一成功包装响应
* (含 task_id/status/progress/current_count/total_count/message/error/download_url/update_time)。
*/
async exportTaskProgress(data = {}) {
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.cdnUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
/**
* 生成打包任务导出任务ID。
* @param {number|string} [warehouseId=''] 仓库ID(缺省兜底取当前上下文 store_id)。
* @return {string} 导出任务ID。
*/
generateExportTaskId(warehouseId = '') {
const normalizedWarehouseId = warehouseId || this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `packing_export_${normalizedWarehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化打包任务导出任务ID。
* @param {Object} data 请求体。
* @param {string} [data.task_id] 任务ID(下划线写法)。
* @param {string} [data.taskId] 任务ID(驼峰写法)。
* @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 `${PACKING_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入打包任务导出任务进度缓存(Redis TTL 30 分钟)。
* @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 || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, PACKING_EXPORT_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[order.packing.export] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取打包任务导出任务进度缓存。
* @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;
}
try {
const cached = await this.app.getCacheAsync(cacheKey);
if (!this.isPlainObject(cached)) {
return null;
}
return cached;
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[order.packing.export] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = OrderPackingMethodService;