liufumingren b5e5d4d588 feat(storeWarehouse,report,notice,order): 签约导出与代开户备注兜底、报表meta下线、入库完成通知与编码规范化
- storeWarehouse: 货主签约列表异步导出 export/exportTaskProgress(26列中文表头Excel+进度回写);openAccount 代开户未传 store_remask(或传空)时默认取公司全称前50字符填充,保证货主名称在列表/导出中始终有值

- report: 下线 report.meta(破坏性),窗口参数改由 definition.typeList、勾选字段经 definition.list 提供;报表投递目标货主状态放宽为 1/2(正常/审核中);reportDelivery 实体展示名称兼容下划线/驼峰并优雅回退 ID

- notice/order: 入库单完成通知货主(entry_order_completed,固定订阅回退链:收货组→售后组→仓库异常群);入库明细 itemId 规范化(非法值降级按 item_code 精确/归一化条码匹配,剥离中文后缀,多命中报错防错配);库存预警定时任务与 webhook 模型调整

- storage: 快捷直入/入库单基本信息等相关小改(inbound_direct_log、storage/entry、storage/inventory)

- docs: methods/system 0.3.62→0.3.63、openapi/qimen 同步,AI_METHOD_ROUTING 与 report-config-guide 同步,methods/changes/*.json 补变更记录
2026-08-31 17:17:48 +08:00

267 lines
8.7 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 MainService = require('../main');
const ReportDeliveryPlanMethodService = require('./report/deliveryPlan');
const ReportDeliveryLogMethodService = require('./report/deliveryLog');
const ReportDefinitionMethodService = require('./report/definition');
const REPORT_GENERATE_TASK_CACHE_KEY_PREFIX = 'report_generate_task_';
const REPORT_GENERATE_TASK_CACHE_TTL_SECONDS = 1800;
/**
* 系统方法层:report(配置驱动通用报表接口包装层)。
* 仅做出口包装与导出任务编排,业务逻辑下沉 systems/report。
*/
class ReportMethodService extends MainService {
/**
* 初始化 report 方法层:配置免鉴权清单,并挂载子目录服务实例。
* report.js 与 report/ 子目录同名并存时,egg 会把子目录服务作为静态属性挂在类构造器上,
* ctx 层实例化后静态属性不可见,需按 storeWarehouse 同款模式在实例上显式挂载,
* 保证 /system 网关可按 report.deliveryPlan.* / report.deliveryLog.* 路径解析。
* @param {Egg.Context} ctx Egg 上下文对象。
*/
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'generate,generateTaskProgress';
const _noNeedLog = 'generate,generateTaskProgress';
const _noNeedAuth = 'generate,generateTaskProgress';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
// 显式挂载子目录服务实例(与 storeWarehouse.js 挂载 store/warehouse 的模式一致)
this.deliveryPlan = new ReportDeliveryPlanMethodService(ctx);
this.deliveryLog = new ReportDeliveryLogMethodService(ctx);
this.definition = new ReportDefinitionMethodService(ctx);
}
/**
* 提交报表导出异步任务(手动导出)。
* warehouse_id 由服务端从登录上下文自动注入,前端无需传递。
* @param {Object} data 请求体
* @param {number} data.report_id 报表定义ID(必填,兼容 reportId)
* @param {number} [data.reportId] 报表定义ID(驼峰写法,优先级高于 report_id)
* @param {number} [data.store_id] 货主ID(可选,货主维度报表时传入)
* @param {Object} [data.params] 查询器业务参数(如 bizDate)
* @return {Promise<Object>} 统一 success 包装,data 为导出任务信息
*/
async generate(data = {}) {
const { service } = this;
const {
report_id: reportIdSnake,
reportId: reportIdCamel,
store_id: storeIdSnake,
storeId: storeIdCamel,
params = {},
} = data;
const reportId = Number(reportIdCamel ?? reportIdSnake ?? 0) || 0;
if (!Number.isInteger(reportId) || reportId <= 0) {
return this.fail('报表ID report_id 必须为正整数');
}
// 服务端注入仓库维度(禁止前端传 warehouse_id)
const warehouseId = Number(this.ctx.user && this.ctx.user.store_id) || 0;
const storeId = Number(storeIdCamel ?? storeIdSnake ?? 0) || 0;
const taskId = this.generateExportTaskId();
const taskPayload = {
task_id: taskId,
status: 'submitted',
progress: 0,
message: '导出任务已提交',
result: null,
error: '',
};
await this.setExportTaskProgress(taskId, taskPayload);
setImmediate(async () => {
try {
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'running',
progress: 10,
message: '导出任务执行中',
result: null,
error: '',
});
const result = await service.systems.report.generate({
reportId,
storeId: storeId > 0 ? storeId : null,
warehouseId,
params,
});
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'success',
progress: 100,
message: '导出任务完成',
result,
error: '',
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
await this.setExportTaskProgress(taskId, {
task_id: taskId,
status: 'failed',
progress: 100,
message: '导出任务失败',
result: null,
error: errorMessage,
});
}
});
return this.success('ok', {
...taskPayload,
update_time: Date.now(),
});
}
/**
* 查询报表导出任务进度。
* @param {Object} data 请求体
* @param {string} [data.task_id] 任务ID(下划线写法)
* @param {string} [data.taskId] 任务ID(驼峰写法)
* @return {Promise<Object>} 统一 success 包装
*/
async generateTaskProgress(data = {}) {
const taskId = this.normalizeExportTaskId(data);
if (!taskId) {
return this.success('ok', {
task_id: '',
status: 'not_found',
progress: 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,
message: '任务不存在',
result: null,
error: '',
download_url: '',
update_time: Date.now(),
});
}
const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {};
const downloadUrl = String(
safeResult.url
|| safeResult.cndUrl
|| safeResult.cosUrl
|| safeResult.fileKey
|| ''
);
return this.success('ok', {
task_id: taskId,
...cachedTask,
download_url: downloadUrl,
});
}
// ==================== 导出任务辅助方法(局部实现,不新增公共代码) ====================
/**
* 生成报表导出任务ID。
* @return {string} 导出任务ID
*/
generateExportTaskId() {
const warehouseId = this.ctx?.user?.store_id || 'unknown';
const timestamp = Date.now();
const randomToken = Math.random().toString(36).slice(2, 10);
return `report_generate_${warehouseId}_${timestamp}_${randomToken}`;
}
/**
* 归一化导出任务ID。
* @param {Object} data 请求体
* @return {string} 归一化后的任务ID
*/
normalizeExportTaskId(data = {}) {
const normalizedData = this.isPlainObject(data) ? data : {};
return String(normalizedData.task_id || normalizedData.taskId || '').trim();
}
/**
* 获取导出任务缓存键。
* @param {string} taskId 任务ID
* @return {string} 缓存键
*/
getExportTaskCacheKey(taskId = '') {
const normalizedTaskId = String(taskId || '').trim();
if (!normalizedTaskId) {
return '';
}
return `${REPORT_GENERATE_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`;
}
/**
* 写入导出任务进度缓存。
* @param {string} taskId 任务ID
* @param {Object} payload 任务状态载荷
* @return {Promise<void>} 无返回值
*/
async setExportTaskProgress(taskId = '', payload = {}) {
const cacheKey = this.getExportTaskCacheKey(taskId);
if (!cacheKey || typeof this.app.setCacheAsync !== 'function') {
return;
}
const safePayload = this.isPlainObject(payload) ? payload : {};
const 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,
message: String(safePayload.message || ''),
result: safePayload.result ?? null,
error: String(safePayload.error || ''),
update_time: Date.now(),
};
try {
await this.app.setCacheAsync(cacheKey, progressPayload, REPORT_GENERATE_TASK_CACHE_TTL_SECONDS);
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.warn(`[report.generate] 写入导出任务缓存失败: ${errorMessage}`);
}
}
/**
* 读取导出任务进度缓存。
* @param {string} taskId 任务ID
* @return {Promise<Object|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(`[report.generateTaskProgress] 读取导出任务缓存失败: ${errorMessage}`);
return null;
}
}
}
module.exports = ReportMethodService;