WMS_MAIN/app/service/systems/reportDelivery.js
liufumingren 4bf34410a3 fix(report): 报表投递/通知 ext_data 改为透传群配置,避免渠道来源 source 丢失
deliverByChannel 与 sendNotifyIfConfigured 原自行组装 extData={report_definition_id,biz_date,time_point,file_url},覆盖了群配置 ext_data(含渠道来源 source),桥接因缺少 source 无法投递;现统一改为 extData = groupRow.ext_data || null(与 notice 推送口径一致),仅成员推送(无群)显式传 null。
2026-09-15 18:14:43 +08:00

1527 lines
62 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');
const { scheduleDateOf } = require('../../lib/report/day_window');
const {
validateNotifyTemplate,
renderNotifyTemplate,
formatNotifyTime,
} = require('../../lib/report/notifyTemplate');
/**
* 货主报表定时投递编排服务(systems 层)。
*
* 职责:
* 1. dispatch:分钟级扫描 wms_report_delivery_plan(enabled=1),按 HH:mm + 宽限窗口命中后
* 对每个(货主+报表+数据日期+时间点)幂等生成报表并投递;
* 2. 投递记录状态机与 wms_report_delivery_log.status 一致:
* pending → exporting → delivered / failed / cancelled;
* 3. 失败退避重试(照搬 wms_waybill_allocate_queue 风格:MAX_RETRY=3,
* 退避 = retry_count × 60s);重试扫描条件:status=failed 且 retry_count<3 且 next_retry_at<=now;
* 4. 投递计划/投递记录的增改查(供 systemMethods 薄出口调用)。
*/
const DELIVERY_STATUS = Object.freeze({
PENDING: 'pending',
EXPORTING: 'exporting',
DELIVERED: 'delivered',
FAILED: 'failed',
CANCELLED: 'cancelled',
});
/** 投递渠道(渠道已收敛:仅支持 inbox,wecom/link 已弃用) */
const DELIVERY_CHANNELS = Object.freeze([ 'inbox' ]);
const DEFAULT_CHANNEL = 'inbox';
const DEFAULT_GRACE_MINUTES = 60;
const MAX_RETRY_COUNT = 3;
const RETRY_BASE_DELAY_MS = 60 * 1000;
const EXPORTING_STALE_MS = 30 * 60 * 1000;
const MAX_ERROR_MESSAGE_LENGTH = 500;
const HHMM_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/;
/** 通知模板长度上限(与表结构 STRING(500) 一致) */
const NOTIFY_TEMPLATE_MAX_LENGTH = 500;
/** 计划名称长度上限(与表结构 STRING(100) 一致) */
const PLAN_NAME_MAX_LENGTH = 100;
/** 通知群多选上限 */
const MAX_NOTIFY_GROUP_IDS = 20;
/** 通知成员多选上限 */
const MAX_NOTIFY_MEMBER_IDS = 100;
class ReportDeliveryService extends Service {
// ==================== 计划/记录查询(供 method 层复用) ====================
/**
* 校验并规范化投递时间点(HH:mm 格式、去重、升序排序)。
* @param {Array<string>|string} rawTimes 原始时间点(数组或 JSON 字符串)
* @return {Array<string>} 规范化时间点数组
* @throws {Error} 含非法格式时抛出
*/
normalizeScheduleTimes(rawTimes) {
let list = rawTimes;
if (typeof list === 'string') {
try {
list = JSON.parse(list);
} catch (error) {
throw new Error('schedule_times 必须为 HH:mm 字符串数组');
}
}
if (!Array.isArray(list) || list.length === 0) {
throw new Error('schedule_times 必须为 HH:mm 字符串数组且不能为空');
}
const seen = new Set();
const normalized = [];
for (const item of list) {
const timePoint = String(item || '').trim();
if (!HHMM_PATTERN.test(timePoint)) {
throw new Error(`schedule_times 含非法时间点(需 HH:mm 24 小时制): ${timePoint}`);
}
if (!seen.has(timePoint)) {
seen.add(timePoint);
normalized.push(timePoint);
}
}
normalized.sort();
return normalized;
}
/**
* 解析 JSON 数组字段:数组原样、JSON 字符串解析、null/undefined/'' 返回 null。
* @param {*} value 原始值
* @param {string} label 字段名(错误提示用)
* @return {Array|null} 数组或 null
* @throws {Error} 非数组或 JSON 解析失败时抛出业务可读错误
*/
parseJsonArray(value, label) {
if (value === null || value === undefined || value === '') {
return null;
}
let list = value;
if (typeof value === 'string') {
try {
list = JSON.parse(value);
} catch (error) {
throw new Error(`${label} 必须为数组`);
}
}
if (!Array.isArray(list)) {
throw new Error(`${label} 必须为数组`);
}
return list;
}
/**
* 视图安全的 JSON 数组读取(兼容字符串/数组/null,无法解析时返回 null)。
* @param {*} value 字段原始值
* @return {Array|null} 数组或 null
*/
readJsonArray(value) {
if (Array.isArray(value)) {
return value;
}
if (typeof value === 'string' && value.trim()) {
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed : null;
} catch (error) {
return null;
}
}
return null;
}
/**
* 视图安全的 JSON 对象读取(兼容对象/字符串/null,无法解析时返回 null)。
* @param {*} value 字段原始值
* @return {Object|null} 对象或 null
*/
readJsonObject(value) {
if (value && typeof value === 'object' && !Array.isArray(value)) {
return value;
}
if (typeof value === 'string' && value.trim()) {
try {
const parsed = JSON.parse(value);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
} catch (error) {
return null;
}
}
return null;
}
/**
* 校验并规范化文本通知模板(长度 ≤500 + 标签白名单)。
* 空值/null/空串均视为未启用(返回空字符串)。
* @param {*} value 原始模板值
* @return {string} 规范化后的模板(未配置时为空字符串)
* @throws {Error} 超长或含白名单外标签时抛出业务可读错误
*/
normalizeNotifyTemplate(value) {
if (value === null || value === undefined || value === '') {
return '';
}
const normalized = String(value).trim();
if (!normalized) {
return '';
}
if (normalized.length > NOTIFY_TEMPLATE_MAX_LENGTH) {
throw new Error(`通知模板 notify_template 长度不能超过 ${NOTIFY_TEMPLATE_MAX_LENGTH} 字符`);
}
const check = validateNotifyTemplate(normalized);
if (!check.valid) {
throw new Error(
`通知模板含未知标签(仅支持 {time}/{url}/{report_name}/{biz_date}): ${check.invalidTags.join(', ')}`
);
}
return normalized;
}
/**
* 校验并规范化计划名称(仅展示字段,不参与幂等/关联逻辑)。
* undefined=未传入(不覆盖既有值);null/空串/全空白=显式清空(返回 null);
* 非空时 trim 且长度 ≤ PLAN_NAME_MAX_LENGTH,超长抛出业务可读错误。
* @param {*} value 原始名称值
* @return {string|null|undefined} 规范化名称(未传入返回 undefined,清空返回 null)
* @throws {Error} 非空且超长时抛出业务可读错误
*/
normalizePlanName(value) {
if (value === undefined) {
return undefined;
}
if (value === null || value === '') {
return null;
}
const normalized = String(value).trim();
if (!normalized) {
return null;
}
if (normalized.length > PLAN_NAME_MAX_LENGTH) {
throw new Error(`计划名称 name 长度不能超过 ${PLAN_NAME_MAX_LENGTH} 字符`);
}
return normalized;
}
/**
* 校验并规范化通知群ID列表(wms_inbox_group.id 数组)。
* 元素需为正整数、自动去重并升序排序、上限 MAX_NOTIFY_GROUP_IDS;null/空数组均允许(表示未选择群)。
* @param {*} value 原始值(数组或 JSON 字符串)
* @return {Array<number>|null} 规范化后的正整数数组(去重升序),未选择返回 null
* @throws {Error} 元素非法或超上限时抛出业务可读错误
*/
normalizeNotifyGroupIds(value) {
const list = this.parseJsonArray(value, '通知群 notify_group_ids');
if (list === null) {
return null;
}
if (list.length > MAX_NOTIFY_GROUP_IDS) {
throw new Error(`通知群 notify_group_ids 最多选择 ${MAX_NOTIFY_GROUP_IDS} 个群`);
}
const seen = new Set();
const normalized = [];
for (const item of list) {
const id = Number(item);
if (!Number.isInteger(id) || id <= 0) {
throw new Error(`通知群 notify_group_ids 含非法群ID(需正整数): ${item}`);
}
if (!seen.has(id)) {
seen.add(id);
normalized.push(id);
}
}
normalized.sort((a, b) => a - b);
return normalized;
}
/**
* 校验并规范化通知成员ID列表(外部 IM 用户 ID 字符串数组)。
* 元素需为非空字符串、自动去重、上限 MAX_NOTIFY_MEMBER_IDS;null/空数组均允许(表示未选择成员)。
* @param {*} value 原始值(数组或 JSON 字符串)
* @return {Array<string>|null} 规范化后的字符串数组(去重),未选择返回 null
* @throws {Error} 元素非法或超上限时抛出业务可读错误
*/
normalizeNotifyMemberIds(value) {
const list = this.parseJsonArray(value, '通知成员 notify_member_ids');
if (list === null) {
return null;
}
if (list.length > MAX_NOTIFY_MEMBER_IDS) {
throw new Error(`通知成员 notify_member_ids 最多选择 ${MAX_NOTIFY_MEMBER_IDS} 个成员`);
}
const seen = new Set();
const normalized = [];
for (const item of list) {
const memberId = String(item || '').trim();
if (!memberId) {
throw new Error('通知成员 notify_member_ids 含空成员ID(需非空字符串)');
}
if (!seen.has(memberId)) {
seen.add(memberId);
normalized.push(memberId);
}
}
return normalized;
}
/**
* 校验通知群ID是否全部存在(软删自动排除,不校验 is_blocked:
* 屏蔽属于发送时过滤维度,保存时允许暂被屏蔽的群仍可选中)。
* @param {Array<number>} groupIds 群ID列表
* @return {Promise<void>}
* @throws {Error} 存在无效群ID时抛出(列出不存在或已删除的ID)
*/
async validateNotifyGroupExists(groupIds) {
const { ctx } = this;
const model = ctx.model && ctx.model.InboxGroup;
if (!model || typeof model.findAll !== 'function') {
throw new Error('站内信群模型 InboxGroup 不可用,无法校验通知群配置');
}
const { Op } = ctx.app.Sequelize;
const rows = await model.findAll({
where: { id: { [Op.in]: groupIds } },
attributes: [ 'id' ],
raw: true,
});
const found = new Set((Array.isArray(rows) ? rows : []).map(row => Number(row.id)));
const missing = groupIds.filter(id => !found.has(id));
if (missing.length > 0) {
throw new Error(`通知群 notify_group_ids 含不存在或已删除的群ID: ${missing.join(', ')}`);
}
}
/**
* 保存/更新投递计划(存在则更新,不存在则创建;货主+报表定义ID唯一)。
* @param {Object} options 入参
* @param {number} options.storeId 货主ID
* @param {number|string} options.reportId 报表定义ID
* @param {Array<string>} options.scheduleTimes 投递时间点(HH:mm)
* @param {string} [options.channel='inbox'] 投递渠道(仅支持 inbox)
* @param {number} [options.lateGraceMinutes=60] 补投宽限分钟
* @param {string} [options.remark] 备注
* @param {string|null} [options.name] 计划名称(可空;未传不覆盖,null/空串清空,非空 trim ≤100)
* @param {string} [options.notifyTemplate] 文本通知模板(≤500,白名单标签 {time}/{url}/{report_name}/{biz_date})
* @param {Array<number>|string} [options.notifyGroupIds] 通知群ID数组(wms_inbox_group.id,≤20)
* @param {Array<string>|string} [options.notifyMemberIds] 通知成员ID数组(外部IM用户ID,≤100)
* @return {Promise<Object>} 保存后的计划记录
* @throws {Error} 参数非法或并发首次保存撞唯一索引且降级重查不到记录时抛出业务可读错误
*/
async savePlan({
storeId,
reportId,
scheduleTimes,
channel = DEFAULT_CHANNEL,
lateGraceMinutes = DEFAULT_GRACE_MINUTES,
remark = '',
name,
notifyTemplate,
notifyGroupIds,
notifyMemberIds,
}) {
const { ctx } = this;
const model = ctx.model && ctx.model.ReportDeliveryPlan;
if (!model) {
throw new Error('投递计划模型 ReportDeliveryPlan 不可用');
}
const normalizedStoreId = Number(storeId) || 0;
if (normalizedStoreId <= 0) {
throw new Error('货主ID store_id 不能为空');
}
const normalizedReportId = Number(reportId) || 0;
if (!Number.isInteger(normalizedReportId) || normalizedReportId <= 0) {
throw new Error('报表ID report_id 必须为正整数');
}
// 校验报表定义存在且启用
await ctx.service.systems.report.getDefinition(normalizedReportId);
const normalizedTimes = this.normalizeScheduleTimes(scheduleTimes);
const normalizedChannel = String(channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL;
if (!DELIVERY_CHANNELS.includes(normalizedChannel)) {
throw new Error(`投递渠道仅支持 inbox: ${channel}`);
}
const graceMinutes = Math.max(0, Math.min(1440, Math.floor(Number(lateGraceMinutes) || 0)));
// 计划名称校验(未传入 undefined 时保持既有字段不动,避免更新时误清空)
let normalizedName;
if (name !== undefined) {
normalizedName = this.normalizePlanName(name);
}
// 文本通知配置校验(未传入 undefined 时保持既有字段不动,避免更新时误清空)
let normalizedNotifyTemplate;
let normalizedNotifyGroupIds;
let normalizedNotifyMemberIds;
if (notifyTemplate !== undefined) {
normalizedNotifyTemplate = this.normalizeNotifyTemplate(notifyTemplate);
}
if (notifyGroupIds !== undefined) {
normalizedNotifyGroupIds = this.normalizeNotifyGroupIds(notifyGroupIds);
if (normalizedNotifyGroupIds !== null && normalizedNotifyGroupIds.length > 0) {
await this.validateNotifyGroupExists(normalizedNotifyGroupIds);
}
}
if (notifyMemberIds !== undefined) {
normalizedNotifyMemberIds = this.normalizeNotifyMemberIds(notifyMemberIds);
}
const payload = {
store_id: normalizedStoreId,
report_definition_id: normalizedReportId,
schedule_times: normalizedTimes,
channel: normalizedChannel,
late_grace_minutes: graceMinutes,
remark: String(remark || '').slice(0, 500),
};
if (normalizedName !== undefined) {
payload.name = normalizedName;
}
if (normalizedNotifyTemplate !== undefined) {
payload.notify_template = normalizedNotifyTemplate;
}
if (normalizedNotifyGroupIds !== undefined) {
payload.notify_group_ids = normalizedNotifyGroupIds;
}
if (normalizedNotifyMemberIds !== undefined) {
payload.notify_member_ids = normalizedNotifyMemberIds;
}
const existing = await model.findOne({
where: {
store_id: normalizedStoreId,
report_definition_id: normalizedReportId,
},
});
if (existing) {
await existing.update(payload);
return this.planToView(existing);
}
try {
const created = await model.create(payload);
return this.planToView(created);
} catch (error) {
// 并发首次保存撞 uk_store_report_definition 唯一索引:降级为重查并更新(与 processOne 的 findOrCreate 降级一致)
if (error && error.name === 'SequelizeUniqueConstraintError') {
const winner = await model.findOne({
where: {
store_id: normalizedStoreId,
report_definition_id: normalizedReportId,
},
});
if (winner) {
await winner.update(payload);
return this.planToView(winner);
}
throw new Error('该货主已存在此报表的投递计划,保存冲突,请重试');
}
throw error;
}
}
/**
* 快速复制投递计划到其他货主(货主+报表定义ID唯一,目标已存在同报表定义计划时跳过)。
*
* 规则:
* 1. id 必须为正整数,源计划不存在(含软删)时抛出业务可读错误;
* 2. storeIds 必须为非空数组且元素为正整数,自动去重;
* 与源计划 store_id 相同的项计入 skipped(原因:与源计划货主相同),
* 全部剔除后为空时仍正常返回(created=[],skipped 标注原因);
* 3. 目标货主必须在 wms_store 存在且状态有效(status 为 1 或 2(正常/审核中),
* 软删自动排除),不存在或状态不合法者计入 skipped(原因:货主不存在或状态异常);
* 4. 目标货主已存在同 report_definition_id 的计划(软删排除)时跳过
* (原因:已存在同报表定义计划),不覆盖不报错;
* 5. 新建计划时 notify_group_ids / notify_member_ids 置空(null,通知配置不复制),
* enabled 等其余配置字段原样复制(enabled 保持“复制”语义,复制源计划启停状态);
* 6. 批量创建使用事务包裹,保证一致性;并发撞唯一索引时降级为 skipped 不中断其余创建。
*
* @param {Object} options 入参
* @param {number|string} options.id 源计划ID(正整数)
* @param {Array<number|string>} options.storeIds 目标货主ID数组(元素需正整数,允许 JSON 字符串)
* @return {Promise<{created: Array<{id: number, store_id: number}>, skipped: Array<{store_id: number, reason: string}>}>}
* 复制结果:created 为新建成功的计划(id=新计划ID,store_id=目标货主ID),
* skipped 为跳过项(store_id=目标货主ID,reason=跳过原因)
* @throws {Error} id 非法、源计划不存在、storeIds 非空数组校验失败或元素非法时抛出业务可读错误
*/
async copyPlan({ id, storeIds }) {
const { ctx } = this;
const model = ctx.model && ctx.model.ReportDeliveryPlan;
if (!model) {
throw new Error('投递计划模型 ReportDeliveryPlan 不可用');
}
// 源计划校验(findByPk 受 paranoid 约束,软删自动排除,不存在返回 null)
const normalizedId = Number(id) || 0;
if (!Number.isInteger(normalizedId) || normalizedId <= 0) {
throw new Error('计划ID无效');
}
const source = await model.findByPk(normalizedId);
if (!source) {
throw new Error('计划不存在');
}
// 目标货主数组校验:非空数组、元素为正整数、自动去重(JSON 字符串兼容,与 save 口径一致)
const rawList = this.parseJsonArray(storeIds, '目标货主 store_ids');
if (rawList === null || rawList.length === 0) {
throw new Error('目标货主 store_ids 必须为非空数组');
}
const seen = new Set();
const targetStoreIds = [];
for (const item of rawList) {
const storeId = Number(item) || 0;
if (!Number.isInteger(storeId) || storeId <= 0) {
throw new Error(`目标货主 store_ids 含非法货主ID(需正整数): ${item}`);
}
if (!seen.has(storeId)) {
seen.add(storeId);
targetStoreIds.push(storeId);
}
}
const sourceStoreId = Number(source.store_id) || 0;
const skipped = [];
const candidates = [];
for (const storeId of targetStoreIds) {
if (storeId === sourceStoreId) {
skipped.push({ store_id: storeId, reason: '与源计划货主相同' });
} else {
candidates.push(storeId);
}
}
// 目标货主存在性校验(wms_store status 为 1 或 2(正常/审核中)均有效,软删自动排除)
const validTargets = [];
if (candidates.length > 0) {
const storeModel = ctx.model && ctx.model.Store;
if (!storeModel || typeof storeModel.findAll !== 'function') {
throw new Error('货主模型 Store 不可用,无法校验目标货主');
}
const { Op } = ctx.app.Sequelize;
const storeRows = await storeModel.findAll({
where: { id: { [Op.in]: candidates }, status: { [Op.in]: [ 1, 2 ] } },
attributes: [ 'id' ],
raw: true,
});
const foundSet = new Set((Array.isArray(storeRows) ? storeRows : []).map(row => Number(row.id) || 0));
for (const storeId of candidates) {
if (foundSet.has(storeId)) {
validTargets.push(storeId);
} else {
skipped.push({ store_id: storeId, reason: '货主不存在或状态异常' });
}
}
}
const created = [];
if (validTargets.length > 0) {
// 已存在同报表定义计划的目标货主跳过(软删排除,与唯一索引口径一致)
const { Op } = ctx.app.Sequelize;
const existingRows = await model.findAll({
where: {
store_id: { [Op.in]: validTargets },
report_definition_id: Number(source.report_definition_id) || 0,
},
attributes: [ 'store_id' ],
raw: true,
});
const existingSet = new Set((Array.isArray(existingRows) ? existingRows : []).map(row => Number(row.store_id) || 0));
const toCreate = [];
for (const storeId of validTargets) {
if (existingSet.has(storeId)) {
skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' });
} else {
toCreate.push(storeId);
}
}
if (toCreate.length > 0) {
// 其余配置字段原样复制;通知配置不复制(置空);enabled 原样复制保持“复制”语义
const payload = {
report_definition_id: Number(source.report_definition_id) || 0,
schedule_times: Array.isArray(source.schedule_times) ? source.schedule_times : [],
channel: String(source.channel || DEFAULT_CHANNEL),
late_grace_minutes: Number(source.late_grace_minutes ?? DEFAULT_GRACE_MINUTES),
name: source.name == null ? null : String(source.name),
remark: source.remark == null ? null : String(source.remark),
notify_template: source.notify_template == null ? null : String(source.notify_template),
notify_group_ids: null,
notify_member_ids: null,
enabled: Number(source.enabled ?? 1),
};
const transaction = await ctx.model.transaction();
try {
for (const storeId of toCreate) {
try {
const row = await model.create({ ...payload, store_id: storeId }, { transaction });
created.push({ id: Number(row.id) || 0, store_id: storeId });
} catch (error) {
// 并发下撞 uk_store_report_definition 唯一索引:降级为 skipped,不中断其余创建
if (error && error.name === 'SequelizeUniqueConstraintError') {
skipped.push({ store_id: storeId, reason: '已存在同报表定义计划' });
} else {
throw error;
}
}
}
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
return { created, skipped };
}
/**
* 计划记录转视图对象。
* @param {Object} plan 计划记录(实例或 raw)
* @return {Object} 视图对象
*/
planToView(plan) {
if (!plan) {
return null;
}
return {
id: Number(plan.id) || 0,
store_id: Number(plan.store_id) || 0,
report_definition_id: Number(plan.report_definition_id) || 0,
schedule_times: Array.isArray(plan.schedule_times) ? plan.schedule_times : [],
channel: String(plan.channel || DEFAULT_CHANNEL),
enabled: Number(plan.enabled ?? 1),
late_grace_minutes: Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES),
name: String(plan.name || ''),
remark: String(plan.remark || ''),
notify_template: String(plan.notify_template || ''),
notify_group_ids: this.readJsonArray(plan.notify_group_ids),
notify_member_ids: this.readJsonArray(plan.notify_member_ids),
created_at: plan.created_at || null,
updated_at: plan.updated_at || null,
};
}
/**
* 分页查询投递计划列表。
* @param {Object} [options={}] 入参
* @param {number} [options.storeId] 货主ID
* @param {number|string} [options.reportId] 报表定义ID
* @param {number|string} [options.enabled] 启用状态(0/1)
* @param {Object} [options.pagination={}] 分页 { page, pageSize }
* @param {Object} [options.sort={}] 排序 { sortField, sortOrder }
* @return {Promise<{list: Array<Object>, total: number, page: number, pageSize: number}>} 列表结果,
* 每条计划含 store_name(货主公司全称,货主已删除或不存在时为空串)
*/
async listPlans({ storeId = null, reportId = null, enabled = null, pagination = {}, sort = {} } = {}) {
const { ctx } = this;
const model = ctx.model && ctx.model.ReportDeliveryPlan;
if (!model) {
throw new Error('投递计划模型 ReportDeliveryPlan 不可用');
}
const where = {};
const normalizedStoreId = Number(storeId) || 0;
if (normalizedStoreId > 0) {
where.store_id = normalizedStoreId;
}
const normalizedReportId = Number(reportId) || 0;
if (normalizedReportId > 0) {
where.report_definition_id = normalizedReportId;
}
if (enabled !== null && enabled !== undefined && enabled !== '') {
where.enabled = Number(enabled) ? 1 : 0;
}
const page = Math.max(1, Math.floor(Number(pagination.page) || 1));
const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20)));
const allowedSortFields = [ 'id', 'created_at', 'updated_at', 'store_id', 'report_definition_id' ];
const sortField = String(sort.sortField || sort.sort_field || 'id').trim();
const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC';
const order = allowedSortFields.includes(sortField)
? [[ sortField, sortOrder ]]
: [[ 'id', 'DESC' ]];
const [ rows, total ] = await Promise.all([
model.findAll({
where,
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
}),
model.count({ where }),
]);
const planRows = Array.isArray(rows) ? rows : [];
// 批量查询货主名称(一次 IN 查询避免 N+1):软删除货主自动排除,
// 货主已删除或不存在时 store_name 回退为空串
const storeIds = [ ...new Set(planRows.map(row => Number(row.store_id) || 0).filter(id => id > 0)) ];
const storeNameMap = new Map();
if (storeIds.length > 0) {
const storeModel = ctx.model && ctx.model.Store;
if (storeModel && typeof storeModel.findAll === 'function') {
const { Op } = ctx.app.Sequelize;
const storeRows = await storeModel.findAll({
where: { id: { [Op.in]: storeIds } },
attributes: [ 'id', 'company_name' ],
raw: true,
});
for (const storeRow of Array.isArray(storeRows) ? storeRows : []) {
storeNameMap.set(Number(storeRow.id) || 0, String(storeRow.company_name || ''));
}
}
}
return {
list: planRows.map(row => ({
id: Number(row.id) || 0,
store_id: Number(row.store_id) || 0,
store_name: storeNameMap.get(Number(row.store_id) || 0) || '',
report_definition_id: Number(row.report_definition_id) || 0,
schedule_times: Array.isArray(row.schedule_times) ? row.schedule_times : [],
channel: String(row.channel || DEFAULT_CHANNEL),
enabled: Number(row.enabled ?? 1),
late_grace_minutes: Number(row.late_grace_minutes ?? DEFAULT_GRACE_MINUTES),
name: String(row.name || ''),
remark: String(row.remark || ''),
notify_template: String(row.notify_template || ''),
notify_group_ids: this.readJsonArray(row.notify_group_ids),
notify_member_ids: this.readJsonArray(row.notify_member_ids),
created_at: row.created_at || null,
updated_at: row.updated_at || null,
})),
total: Number(total) || 0,
page,
pageSize,
};
}
/**
* 分页查询投递记录(审计)。
* @param {Object} [options={}] 入参
* @param {number} [options.storeId] 货主ID
* @param {number|string} [options.reportId] 报表定义ID
* @param {string} [options.status] 状态过滤
* @param {Object} [options.pagination={}] 分页 { page, pageSize }
* @param {Object} [options.sort={}] 排序 { sortField, sortOrder }
* @return {Promise<{list: Array<Object>, total: number, page: number, pageSize: number}>} 列表结果
*/
async listLogs({ storeId = null, reportId = null, status = '', pagination = {}, sort = {} } = {}) {
const { ctx } = this;
const model = ctx.model && ctx.model.ReportDeliveryLog;
if (!model) {
throw new Error('投递记录模型 ReportDeliveryLog 不可用');
}
const where = {};
const normalizedStoreId = Number(storeId) || 0;
if (normalizedStoreId > 0) {
where.store_id = normalizedStoreId;
}
const normalizedReportId = Number(reportId) || 0;
if (normalizedReportId > 0) {
where.report_definition_id = normalizedReportId;
}
const normalizedStatus = String(status || '').trim();
if (normalizedStatus && Object.values(DELIVERY_STATUS).includes(normalizedStatus)) {
where.status = normalizedStatus;
}
const page = Math.max(1, Math.floor(Number(pagination.page) || 1));
const pageSize = Math.min(200, Math.max(1, Math.floor(Number(pagination.pageSize) || 20)));
const allowedSortFields = [ 'id', 'created_at', 'updated_at', 'biz_date', 'delivered_at' ];
const sortField = String(sort.sortField || sort.sort_field || 'id').trim();
const sortOrder = String(sort.sortOrder || sort.sort_order || 'desc').trim().toLowerCase() === 'asc' ? 'ASC' : 'DESC';
const order = allowedSortFields.includes(sortField)
? [[ sortField, sortOrder ]]
: [[ 'id', 'DESC' ]];
const [ rows, total ] = await Promise.all([
model.findAll({
where,
order,
offset: (page - 1) * pageSize,
limit: pageSize,
raw: true,
}),
model.count({ where }),
]);
return {
list: (Array.isArray(rows) ? rows : []).map(row => ({
id: Number(row.id) || 0,
warehouse_id: Number(row.warehouse_id) || 0,
store_id: Number(row.store_id) || 0,
report_definition_id: Number(row.report_definition_id) || 0,
report_name: String(row.report_name || ''),
biz_date: row.biz_date || '',
time_point: String(row.time_point || ''),
status: String(row.status || DELIVERY_STATUS.PENDING),
channel: String(row.channel || DEFAULT_CHANNEL),
file_url: String(row.file_url || ''),
retry_count: Number(row.retry_count) || 0,
next_retry_at: row.next_retry_at || null,
error_message: String(row.error_message || ''),
delivered_at: row.delivered_at || null,
notify_targets: this.readJsonObject(row.notify_targets),
created_at: row.created_at || null,
updated_at: row.updated_at || null,
})),
total: Number(total) || 0,
page,
pageSize,
};
}
// ==================== 投递调度 ====================
/**
* 计算当前时刻命中的时间点(含 late_grace_minutes 宽限窗口)。
* 宽限跨零点场景:now 为次日凌晨时,昨日深夜时间点仍可在宽限内命中。
* @param {Array<string>} scheduleTimes 计划时间点(HH:mm)
* @param {Date} now 触发时刻
* @param {number} graceMinutes 宽限分钟
* @return {Array<string>} 命中的时间点
*/
hitTimePoints(scheduleTimes, now, graceMinutes) {
const normalizedGrace = Math.max(0, Math.min(1440, Math.floor(Number(graceMinutes) || 0)));
const nowMinutes = now.getHours() * 60 + now.getMinutes();
const hits = [];
for (const timePoint of scheduleTimes) {
const parts = String(timePoint).split(':');
const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]);
const diff = nowMinutes - timeMinutes;
const wrapDiff = nowMinutes + 24 * 60 - timeMinutes;
if ((diff >= 0 && diff <= normalizedGrace) || wrapDiff <= normalizedGrace) {
hits.push(timePoint);
}
}
return hits;
}
/**
* 计算触发时刻的数据日期(T-1 本地自然日)。
* @param {Date} now 触发时刻
* @return {string} 'YYYY-MM-DD'
*/
bizDateOfTrigger(now) {
return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));
}
/**
* 计算命中时间点对应的数据日期(报表数据截止日 = 时间点所属自然日的 T-1)。
*
* 口径:同一时间点在「正常投递」与「跨零点补投」时必须落在相同 biz_date,
* 保证幂等键 (store_id, report_definition_id, biz_date, time_point) 防重不防漏:
* - 当日命中(timePoint 的 HH:mm <= now 的 HH:mm):时间点属于触发自然日,
* biz_date = 触发日 - 1;
* - 跨零点补投(timePoint 的 HH:mm > now 的 HH:mm,即昨日深夜时间点):
* 时间点属于昨日自然日,biz_date = 昨日 - 1(触发日 - 2),
* 与昨日正常投递口径一致,避免与次日正常投递撞幂等键。
*
* @param {Date} now 触发时刻
* @param {string} timePoint 命中的投递时间点(HH:mm)
* @return {string} 'YYYY-MM-DD'
*/
bizDateOfTimePoint(now, timePoint) {
const parts = String(timePoint).split(':');
const timeMinutes = Number(parts[0]) * 60 + Number(parts[1]);
const nowMinutes = now.getHours() * 60 + now.getMinutes();
const scheduleDayOffset = timeMinutes > nowMinutes ? -2 : -1;
return scheduleDateOf(new Date(now.getFullYear(), now.getMonth(), now.getDate() + scheduleDayOffset));
}
/**
* 解析货主所属仓库:优先首条有效合约(auth_status=2 且未停用),否则回退最早一条合约。
* 假设:货主报表按单仓库生成,取最早合约的仓库维度(供测试复核)。
* @param {number} storeId 货主ID
* @return {Promise<number>} 仓库ID,未找到返回 0
*/
async resolveStoreWarehouse(storeId) {
const { ctx } = this;
const model = ctx.model && ctx.model.StoreWarehouse;
if (!model || typeof model.findAll !== 'function') {
return 0;
}
const normalizedStoreId = Number(storeId) || 0;
if (normalizedStoreId <= 0) {
return 0;
}
const rows = await model.findAll({
where: { store_id: normalizedStoreId },
attributes: [ 'store_id', 'warehouse_id', 'auth_status', 'warehouse_use_status' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
const list = Array.isArray(rows) ? rows : [];
const active = list.find(row => Number(row.auth_status) === 2 && Number(row.warehouse_use_status) !== 0);
const chosen = active || list[0];
return chosen ? Number(chosen.warehouse_id) || 0 : 0;
}
/**
* 投递成功回写(delivered),并落文本通知目标快照(可选)。
* @param {Object} log 投递记录实例
* @param {Object} fileResult 生成结果 { fileKey, url, filename }
* @param {Object|null} [notifyTargets=null] 文本通知目标快照 { group_ids, member_ids, notify_text }
* @return {Promise<void>}
*/
async markDelivered(log, fileResult, notifyTargets = null) {
await log.update({
status: DELIVERY_STATUS.DELIVERED,
// 表结构仅 file_url 一列承载产物地址(无 file_key/task_id 列),url 缺失时退化为 fileKey
file_url: String(fileResult.url || fileResult.fileKey || '').slice(0, 500),
error_message: null,
next_retry_at: null,
delivered_at: new Date(),
notify_targets: notifyTargets || null,
});
}
/**
* 投递失败回写(failed + 退避重试,MAX_RETRY=3,照搬 wms_waybill_allocate_queue 风格)。
* @param {Object} log 投递记录实例
* @param {string} errorMessage 失败原因
* @return {Promise<void>}
*/
async markFailed(log, errorMessage) {
const retryCount = Number(log.retry_count) || 0;
const nextCount = retryCount + 1;
const normalizedMessage = String(errorMessage || '报表投递失败').slice(0, MAX_ERROR_MESSAGE_LENGTH);
await log.update({
status: DELIVERY_STATUS.FAILED,
retry_count: nextCount,
next_retry_at: nextCount >= MAX_RETRY_COUNT
? null
: new Date(Date.now() + nextCount * RETRY_BASE_DELAY_MS),
error_message: normalizedMessage,
});
}
/**
* 置为导出中(exporting),并回填生成报表使用的仓库维度与报表名称快照。
* @param {Object} log 投递记录实例
* @param {number} warehouseId 仓库ID
* @param {string} [reportName=''] 报表名称快照
* @return {Promise<void>}
*/
async markExporting(log, warehouseId, reportName = '') {
await log.update({
status: DELIVERY_STATUS.EXPORTING,
warehouse_id: Number(warehouseId) || 0,
report_name: String(reportName || '').slice(0, 100),
error_message: null,
});
}
/**
* 构建投递通知正文(站内信 inbox 文案)。
* @param {Object} definition 报表定义
* @param {string} bizDate 数据日期
* @param {string} fileUrl 文件链接
* @return {string} 通知正文
*/
buildMessageContent(definition, bizDate, fileUrl) {
const reportName = String((definition && definition.name) || '报表');
return `【${reportName}】${bizDate} 数据报表已生成,点击查看:${fileUrl}`;
}
/**
* 解析计划配置的通知群(notify_group_ids → 有效群行)。
* 过滤口径与 sendNotifyIfConfigured 一致:is_blocked=0、软删自动排除、仓库维度一致。
* @param {Object} options 入参
* @param {Object} options.plan 投递计划
* @param {number} options.warehouseId 仓库ID
* @return {Promise<Array<{id: number, group_id: string, group_name: string, ext_data: Object|null}>>}
* 有效群行列表(未配置群或全部被过滤时返回空数组)
* @throws {Error} 站内信群模型不可用时抛出
*/
async resolveNotifyGroups({ plan, warehouseId }) {
const { ctx } = this;
const groupIds = this.readJsonArray(plan && plan.notify_group_ids) || [];
if (groupIds.length === 0) {
return [];
}
const inboxGroupModel = ctx.model && ctx.model.InboxGroup;
if (!inboxGroupModel || typeof inboxGroupModel.findAll !== 'function') {
throw new Error('站内信群模型 InboxGroup 不可用,无法解析通知群');
}
const { Op } = ctx.app.Sequelize;
const rows = await inboxGroupModel.findAll({
where: {
id: { [Op.in]: groupIds },
warehouse_id: Number(warehouseId) || 0,
is_blocked: 0,
},
attributes: [ 'id', 'group_id', 'group_name', 'ext_data' ],
raw: true,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 按渠道投递(渠道已收敛,仅支持 inbox 站内信群推送)。
*
* 规则:
* 1. 历史计划残留 wecom/link 等已弃用渠道时,按 inbox 兜底执行并记录 warn 日志
* (不直接抛错:避免历史计划在 failed 退避循环中耗尽重试次数后永久卡死);
* 2. 群路由(缺陷 G1 修复):报表文件消息只投递到计划配置的通知群(notify_group_ids),
* 不再投递到任意「货主默认群」,避免未配置投递的群收到推送;
* 未配置通知群的历史计划保持旧行为,回退投递到货主默认站内信群(group_type=store);
* 3. 推送失败(success=false 或消息记录回写 push_status=3)时,立即复用
* ctx.service.inbox.message.retry 重推一次(重置 push_status=0 异步重推,
* ext_id 幂等复用同一条消息记录,不重复写);
* 4. 重推仍失败(retry 自身抛错)时向上抛错,交由上层 failed 退避循环
* (MAX_RETRY=3,退避 = retry_count × 60s);
* 5. 完成后按计划配置附带发送文本通知(与投递渠道独立);
* 6. 幂等键含货主维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}),
* 不同货主的投递消息互不复用;
* 7. 推送体/消息表 ext_data 一律透传目标群配置的 ext_data(与 notice 推送口径一致),
* 不自行组装报表业务字段(会丢失渠道来源 source,导致桥接投递到错误/缺失渠道)。
*
* @param {Object} options 入参
* @param {Object} options.plan 投递计划
* @param {Object} options.definition 报表定义
* @param {Object} options.fileResult 生成结果
* @param {number} options.warehouseId 仓库ID
* @param {number} options.storeId 货主ID
* @param {string} options.bizDate 数据日期
* @param {string} options.timePoint 命中时间点
* @param {Date} [options.now=new Date()] 触发时刻(渲染 {time} 用)
* @return {Promise<Object|null>} 文本通知目标快照(未配置通知时返回 null)
* @throws {Error} 投递失败且重推失败时抛出
*/
async deliverByChannel({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) {
const { ctx } = this;
const rawChannel = String(plan.channel || DEFAULT_CHANNEL).trim().toLowerCase() || DEFAULT_CHANNEL;
const fileUrl = String(fileResult.url || fileResult.fileKey || '');
const reportDefinitionId = Number(plan.report_definition_id) || 0;
// 幂等键含货主维度:不同货主的投递消息不得互相复用/串扰(货主限制不符缺陷)
const idempotentKey = `report:${storeId}:${reportDefinitionId}:${bizDate}:${timePoint}`;
// 渠道收敛:wecom/link 已弃用,历史残留数据按 inbox 兜底执行,避免历史计划投递卡死
if (rawChannel !== 'inbox') {
ctx.logger.warn(
`[reportDelivery] 计划投递渠道 ${rawChannel} 已弃用,按 inbox 兜底投递(store_id=${storeId}, report_definition_id=${reportDefinitionId})`
);
}
// inbox:站内信群推送(唯一渠道)。
// 群路由(缺陷 G1 修复):报表文件消息只投递到计划配置的通知群,不再投递到任意「货主默认群」;
// 未配置通知群的历史计划保持旧行为,回退到货主默认站内信群(group_type=store,取最早一条)。
const configuredGroupIds = this.readJsonArray(plan && plan.notify_group_ids) || [];
let targetGroups;
if (configuredGroupIds.length > 0) {
targetGroups = await this.resolveNotifyGroups({ plan, warehouseId });
if (targetGroups.length === 0) {
throw new Error(`货主 ${storeId} 配置的通知群不可达(不存在、已删除、被屏蔽或仓库不一致),无法投递`);
}
} else {
const inboxGroupModel = ctx.model && ctx.model.InboxGroup;
if (!inboxGroupModel || typeof inboxGroupModel.findOne !== 'function') {
throw new Error('站内信群模型 InboxGroup 不可用');
}
const groupRow = await inboxGroupModel.findOne({
where: {
warehouse_id: warehouseId,
store_id: storeId,
group_type: 'store',
is_blocked: 0,
},
attributes: [ 'group_id', 'group_name', 'ext_data' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
if (!groupRow || !groupRow.group_id) {
throw new Error(`货主 ${storeId} 未配置站内信群,无法投递`);
}
targetGroups = [ groupRow ];
}
const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify;
if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') {
throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用');
}
const pushResults = [];
for (const groupRow of targetGroups) {
const pushResult = await warehouseNotify.pushSystemMessage({
warehouseId,
storeId,
group: {
group_id: groupRow.group_id,
group_name: groupRow.group_name || '货主群',
ext_data: groupRow.ext_data || null,
},
content: this.buildMessageContent(definition, bizDate, fileUrl),
extId: idempotentKey,
// ext_data 必须透传群配置(含渠道来源 source 等):自行组装业务字段会丢失渠道信息,
// 导致桥接按错误/缺失渠道投递(与 notice 推送口径一致:extData = group.ext_data)
extData: groupRow.ext_data || null,
});
pushResults.push(pushResult);
}
// 推送失败判定(双保险):success=false;或消息记录回写 push_status=3(推送链路异常时兜底识别)
const retryService = ctx.service && ctx.service.inbox && ctx.service.inbox.message;
for (const pushResult of pushResults) {
const messageId = (pushResult && Number(pushResult.messageId)) || 0;
let pushFailed = !pushResult || pushResult.success === false;
if (!pushFailed && messageId > 0) {
const InboxMessage = ctx.model && ctx.model.InboxMessage;
if (InboxMessage && typeof InboxMessage.findOne === 'function') {
try {
const row = await InboxMessage.findOne({
where: { id: messageId },
attributes: [ 'push_status' ],
raw: true,
});
if (row && Number(row.push_status) === 3) {
pushFailed = true;
}
} catch (statusErr) {
ctx.logger.warn(`[reportDelivery] 读取消息推送状态失败: ${statusErr.message}`);
}
}
}
if (pushFailed) {
const reason = (pushResult && (pushResult.reason || pushResult.error)) || '站内信推送失败';
// 立即重推一次:复用 inbox.message.retry(重置 push_status=0 并异步重推;ext_id 幂等复用
// 同一条消息记录,不重复写)。retry 自身抛错视为重推失败,向上抛出进入 failed 退避循环
if (messageId > 0 && retryService && typeof retryService.retry === 'function') {
try {
await retryService.retry({ warehouseId, id: messageId });
ctx.logger.warn(`[reportDelivery] 站内信推送失败已受理立即重推(message_id=${messageId}): ${reason}`);
} catch (retryErr) {
const retryReason = retryErr && retryErr.message ? retryErr.message : `${retryErr}`;
throw new Error(`站内信推送失败且重推失败: ${reason} / ${retryReason}`);
}
} else {
throw new Error(reason);
}
}
}
// 文本通知(可选):与投递渠道独立;未配置时返回 null 保持既有行为不变
return this.sendNotifyIfConfigured({
plan,
definition,
fileResult,
warehouseId,
storeId,
bizDate,
timePoint,
now,
});
}
/**
* 按计划配置发送文本通知(模板渲染 + 定向群/成员推送)。
*
* 规则:
* 1. 未配置模板或未选择任何群/成员时直接返回 null(保持既有投递行为不变);
* 2. 通知群(notify_group_ids 内部ID)→ 查 wms_inbox_group 取外部 group_id/group_name,
* 过滤 is_blocked=1、软删自动排除、仓库维度一致;逐群推送(群维度协议字段为单值);
* 3. 通知成员(notify_member_ids 外部IM用户ID)→ 推送体 user_id 直接传数组,不循环拆发;
* 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送;
* 4. {url} 为空时由渲染器替换为兜底文案(生成中占位),不阻断投递;
* 5. 推送失败抛出异常交由上层走失败退避重试(消息落库按 ext_id 幂等防重);
* 6. 幂等键含货主维度(report:notify:{store_id}:...),不同货主的文本通知互不复用;
* 7. ext_data 透传通知群配置的 ext_data(不自行组装业务字段);仅成员推送(无群)时传 null。
*
* @param {Object} options 入参
* @param {Object} options.plan 投递计划
* @param {Object} options.definition 报表定义
* @param {Object} options.fileResult 生成结果
* @param {number} options.warehouseId 仓库ID
* @param {number} options.storeId 货主ID
* @param {string} options.bizDate 数据日期
* @param {string} options.timePoint 命中时间点
* @param {Date} [options.now] 触发时刻
* @return {Promise<Object|null>} 快照 { group_ids, member_ids, notify_text },未配置返回 null
* @throws {Error} 目标不可达或推送失败时抛出
*/
async sendNotifyIfConfigured({ plan, definition, fileResult, warehouseId, storeId, bizDate, timePoint, now = null }) {
const { ctx } = this;
const template = String((plan && plan.notify_template) || '').trim();
if (!template) {
return null;
}
const groupIds = this.readJsonArray(plan && plan.notify_group_ids) || [];
const memberIds = this.readJsonArray(plan && plan.notify_member_ids) || [];
if (groupIds.length === 0 && memberIds.length === 0) {
return null;
}
const reportDefinitionId = Number((plan && plan.report_definition_id) || 0);
const fileUrl = String(fileResult.url || fileResult.fileKey || '');
const reportName = String((definition && definition.name) || '报表');
const notifyText = renderNotifyTemplate(template, {
time: formatNotifyTime(now || new Date()),
url: fileUrl,
reportName,
bizDate,
});
// 目标解析:内部群ID → 外部群信息(is_blocked=0、软删排除、仓库维度一致),
// 复用 resolveNotifyGroups 与渠道投递保持同一解析口径
const groups = groupIds.length > 0
? await this.resolveNotifyGroups({ plan, warehouseId })
: [];
if (groups.length === 0 && memberIds.length === 0) {
throw new Error('文本通知目标不可达(通知群不存在、已删除、被屏蔽或未选择群/成员)');
}
const warehouseNotify = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify;
if (!warehouseNotify || typeof warehouseNotify.pushSystemMessage !== 'function') {
throw new Error('通知推送服务 warehouseNotify.pushSystemMessage 不可用');
}
// 幂等键含货主维度:不同货主的文本通知不得互相复用/串扰(货主限制不符缺陷)
const notifyExtId = `report:notify:${storeId}:${reportDefinitionId}:${bizDate}:${timePoint}`;
// ext_data 不在此处组装:群推送透传群配置的 ext_data(含渠道来源),
// 仅成员推送(无群)时无群配置可取,按 null 透传
const commonOptions = {
warehouseId,
storeId,
userIds: memberIds,
content: notifyText,
extId: notifyExtId,
};
const sentGroupIds = [];
const results = [];
// 群多选:群维度协议字段为单值(group_id/group_name),逐群推送;成员 user_id 数组随群推送整体透传
for (const groupRow of groups) {
results.push(await warehouseNotify.pushSystemMessage({
...commonOptions,
group: {
group_id: groupRow.group_id,
group_name: groupRow.group_name || '货主群',
ext_data: groupRow.ext_data || null,
},
extData: groupRow.ext_data || null,
}));
sentGroupIds.push(Number(groupRow.id));
}
// 仅成员(未选择任何群):单独一次成员推送,user_id 直接传数组不循环拆发(无群配置,ext_data 传 null)
if (memberIds.length > 0 && results.length === 0) {
results.push(await warehouseNotify.pushSystemMessage({ ...commonOptions, extData: null }));
}
const failed = results.filter(result => !result || result.success === false);
if (failed.length > 0) {
const reason = (failed[0] && (failed[0].reason || failed[0].error)) || '文本通知推送失败';
throw new Error(`文本通知推送失败: ${reason}`);
}
return {
group_ids: sentGroupIds,
member_ids: memberIds,
notify_text: notifyText,
};
}
/**
* 处理单个(计划 × 时间点)的幂等生成与投递。
* 货主维度强校验:store_id/report_definition_id 无效时直接抛错,绝不生成跨货主报表。
* @param {Object} options 入参
* @param {Object} options.plan 投递计划
* @param {number} options.storeId 货主ID
* @param {number} options.reportId 报表定义ID
* @param {string} options.timePoint 命中时间点
* @param {string} options.bizDate 数据日期
* @param {Date} options.now 触发时刻
* @return {Promise<string>} 处理结果标记(delivered/failed/skipped)
* @throws {Error} 货主/报表定义维度非法时抛出
*/
async processOne({ plan, storeId, reportId, timePoint, bizDate, now }) {
const { ctx } = this;
const logModel = ctx.model && ctx.model.ReportDeliveryLog;
if (!logModel) {
throw new Error('投递记录模型 ReportDeliveryLog 不可用');
}
// 货主维度强校验:投递报表必须限定货主,避免 store_id 缺失时生成跨货主数据(货主限制不符缺陷)
const normalizedStoreId = Number(storeId) || 0;
const normalizedReportId = Number(reportId) || 0;
if (normalizedStoreId <= 0 || normalizedReportId <= 0) {
throw new Error(`投递计划维度非法(store_id=${storeId}, report_definition_id=${reportId}),拒绝生成报表`);
}
const uniqueWhere = {
store_id: normalizedStoreId,
report_definition_id: normalizedReportId,
biz_date: bizDate,
time_point: timePoint,
};
let log = await logModel.findOne({ where: uniqueWhere });
if (log) {
const status = String(log.status || '');
if (status !== DELIVERY_STATUS.FAILED) {
// 已投递/投递中/取消的记录直接跳过(幂等)
return 'skipped';
}
const retryCount = Number(log.retry_count) || 0;
if (retryCount >= MAX_RETRY_COUNT) {
return 'skipped';
}
const nextRetryAt = log.next_retry_at ? new Date(log.next_retry_at) : null;
if (nextRetryAt && nextRetryAt.getTime() > now.getTime()) {
// 退避未到期
return 'skipped';
}
} else {
try {
[ log ] = await logModel.findOrCreate({
where: uniqueWhere,
defaults: {
...uniqueWhere,
warehouse_id: 0,
report_name: '',
status: DELIVERY_STATUS.PENDING,
channel: String(plan.channel || DEFAULT_CHANNEL),
},
});
} catch (error) {
// 并发撞唯一键时降级为查询
log = await logModel.findOne({ where: uniqueWhere });
}
if (log && String(log.status || '') !== DELIVERY_STATUS.PENDING && String(log.status || '') !== DELIVERY_STATUS.FAILED) {
return 'skipped';
}
}
if (!log) {
return 'skipped';
}
const warehouseId = await this.resolveStoreWarehouse(normalizedStoreId);
if (warehouseId <= 0) {
await this.markFailed(log, `货主 ${normalizedStoreId} 未找到有效合约仓库`);
return 'failed';
}
// 读取报表定义一次(报表名称快照 + 投递通知文案共用,生成步骤内部会再按 id 读取)
const definition = await ctx.service.systems.report.getDefinition(normalizedReportId);
await this.markExporting(log, warehouseId, definition.name);
// 生成上传(失败进入退避重试)
let fileResult;
try {
fileResult = await ctx.service.systems.report.generate({
reportId: normalizedReportId,
storeId: normalizedStoreId,
warehouseId,
params: {
bizDate,
timePoint,
},
});
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.error(`[reportDelivery] 报表生成失败 ${normalizedReportId}/${normalizedStoreId}/${bizDate}/${timePoint}: ${errorMessage}`);
await this.markFailed(log, `报表生成失败: ${errorMessage}`);
return 'failed';
}
// 投递(失败进入退避重试)
try {
const notifyTargets = await this.deliverByChannel({
plan,
definition,
fileResult,
warehouseId,
storeId: normalizedStoreId,
bizDate,
timePoint,
now,
});
await this.markDelivered(log, fileResult, notifyTargets);
return 'delivered';
} catch (error) {
const errorMessage = error && error.message ? error.message : `${error}`;
this.ctx.logger.error(`[reportDelivery] 报表投递失败 ${normalizedReportId}/${normalizedStoreId}/${bizDate}/${timePoint}: ${errorMessage}`);
await this.markFailed(log, `报表投递失败: ${errorMessage}`);
return 'failed';
}
}
/**
* 计划时间点解析:兼容数组与 JSON 字符串(防止手工数据写成字符串)。
* @param {Array<string>|string} value 原始值
* @return {Array<string>} 时间点数组
*/
parseScheduleTimes(value) {
if (Array.isArray(value)) {
return value;
}
if (typeof value === 'string' && value.trim()) {
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed : [];
} catch (error) {
return [];
}
}
return [];
}
/**
* 分钟级投递调度入口(schedule 调用)。
*
* 流程:
* 1. 兜底回退:exporting 超过 EXPORTING_STALE_MS 的记录视为进程中断,置为 failed
* 并重置 retry_count=0、next_retry_at=now,交由重试扫描立即重排(防卡死);
* 2. 计划扫描:对每个命中时间点按「时间点归属自然日 - 1」计算 biz_date
* (跨零点补投落漏跑日),幂等生成并投递;
* 3. 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录直接重试,
* 不依赖计划时间点再次命中。
* @return {Promise<Object>} 本轮扫描汇总 { scanned, delivered, failed, skipped }
*/
async dispatch() {
const { ctx, app } = this;
const planModel = ctx.model && ctx.model.ReportDeliveryPlan;
const logModel = ctx.model && ctx.model.ReportDeliveryLog;
if (!planModel || !logModel) {
return { scanned: 0, delivered: 0, failed: 0, skipped: 0 };
}
const { Op } = app.Sequelize;
const now = new Date();
// 兜底:导出中超过 30 分钟视为进程中断,置为 failed 并重置退避参数(retry_count=0、
// next_retry_at=now)交给重试链路立即重排。不能回退为 pending:既有 pending 会被
// processOne 幂等跳过,且重试扫描只捡 failed,会导致该记录永久卡死(缺陷 D1)。
await logModel.update({
status: DELIVERY_STATUS.FAILED,
retry_count: 0,
next_retry_at: now,
error_message: '报表导出超时中断,已自动重排投递',
updated_at: now,
}, {
where: {
status: DELIVERY_STATUS.EXPORTING,
updated_at: {
[Op.lt]: new Date(now.getTime() - EXPORTING_STALE_MS),
},
},
});
const plans = await planModel.findAll({
where: { enabled: 1 },
order: [[ 'id', 'ASC' ]],
raw: true,
});
const summary = {
scanned: Array.isArray(plans) ? plans.length : 0,
delivered: 0,
failed: 0,
skipped: 0,
};
for (const plan of plans || []) {
const scheduleTimes = this.parseScheduleTimes(plan.schedule_times);
if (scheduleTimes.length === 0) {
continue;
}
const graceMinutes = Number(plan.late_grace_minutes ?? DEFAULT_GRACE_MINUTES);
const hits = this.hitTimePoints(scheduleTimes, now, graceMinutes);
if (hits.length === 0) {
continue;
}
const storeId = Number(plan.store_id) || 0;
const reportId = Number(plan.report_definition_id) || 0;
if (storeId <= 0 || reportId <= 0) {
ctx.logger.warn(`[reportDelivery] 跳过无效计划 id=${plan.id}(store_id=${storeId}, report_definition_id=${reportId})`);
continue;
}
for (const timePoint of hits) {
try {
// 按命中时间点归属自然日计算 biz_date:跨零点补投落在漏跑日(T-2),
// 与次日正常投递的幂等键互不碰撞(缺陷 D2)
const hitBizDate = this.bizDateOfTimePoint(now, timePoint);
const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate: hitBizDate, now });
if (mark === 'delivered') {
summary.delivered += 1;
} else if (mark === 'failed') {
summary.failed += 1;
} else {
summary.skipped += 1;
}
} catch (error) {
summary.failed += 1;
const errorMessage = error && error.message ? error.message : `${error}`;
ctx.logger.error(`[reportDelivery] 处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`);
}
}
}
// 重试扫描:status=failed 且 retry_count<3 且 next_retry_at<=now 的记录
// (不依赖计划时间点再次命中,退避到期即重试)
const failedLogs = await logModel.findAll({
where: {
status: DELIVERY_STATUS.FAILED,
retry_count: { [Op.lt]: MAX_RETRY_COUNT },
next_retry_at: { [Op.lte]: now },
},
order: [[ 'id', 'ASC' ]],
limit: 200,
raw: true,
});
const retryPlans = new Map();
for (const failedLog of failedLogs || []) {
const storeId = Number(failedLog.store_id) || 0;
const reportId = Number(failedLog.report_definition_id) || 0;
const bizDate = String(failedLog.biz_date || '');
const timePoint = String(failedLog.time_point || '');
if (storeId <= 0 || reportId <= 0 || !bizDate || !timePoint) {
continue;
}
const planKey = `${storeId}:${reportId}`;
let plan = retryPlans.get(planKey);
if (plan === undefined) {
plan = await planModel.findOne({
where: {
store_id: storeId,
report_definition_id: reportId,
enabled: 1,
},
raw: true,
});
retryPlans.set(planKey, plan || null);
}
if (!plan) {
// 计划已停用/删除:不再重试
continue;
}
try {
const mark = await this.processOne({ plan, storeId, reportId, timePoint, bizDate, now });
if (mark === 'delivered') {
summary.delivered += 1;
} else if (mark === 'failed') {
summary.failed += 1;
} else {
summary.skipped += 1;
}
} catch (error) {
summary.failed += 1;
const errorMessage = error && error.message ? error.message : `${error}`;
ctx.logger.error(`[reportDelivery] 重试处理异常 ${reportId}/${storeId}/${timePoint}: ${errorMessage}`);
}
}
return summary;
}
}
module.exports = ReportDeliveryService;