- functions 新增 openDoor/registerLicensePlate/enter/departure(规则表+权限分组) - 到货登记表 wms_inbox_arrival_register(含消费字段,离场闭环,货主收货群优先推送) - 回执 extend_props 持久化落库与定时补发送下发(重推兜底回读) - 车牌提取正则兼容异体字(粤/粵) - 售后类型/关键字/函数/回复 v2 模型与迁移 - INBOX V2 HTTP 测试报告与指南
781 lines
28 KiB
JavaScript
781 lines
28 KiB
JavaScript
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
const { parseWhereConditions } = require('../../lib/query_condition_parser');
|
||
|
||
/** 出站推送失败自动重推:默认失败时间窗(毫秒,30 分钟)——仓库未配置时兜底,超窗口的消息不再补推 */
|
||
const DEFAULT_PUSH_RETRY_WINDOW_MS = 30 * 60 * 1000;
|
||
/** 出站推送失败自动重推:默认单轮最多重推条数(定时任务每 3 分钟扫一次) */
|
||
const DEFAULT_PUSH_RETRY_LIMIT = 20;
|
||
/** 出站推送失败自动重推:单轮条数硬上限 */
|
||
const MAX_PUSH_RETRY_LIMIT = 200;
|
||
|
||
/** 仓库设置字段:站内信推送失败自动重发(嵌套对象,与「收货未入库提醒」同结构) */
|
||
const PUSH_RETRY_FIELD = 'inbox_push_retry';
|
||
/** 重发时间范围(分钟)上下限:与仓库设置字段元信息 setting/warehouse.js 保持一致 */
|
||
const PUSH_RETRY_WINDOW_MINUTES_MIN = 1;
|
||
const PUSH_RETRY_WINDOW_MINUTES_MAX = 1440;
|
||
/** 重发时间范围默认值(分钟):仓库未配置时兜底 30 分钟 */
|
||
const DEFAULT_PUSH_RETRY_WINDOW_MINUTES = 30;
|
||
|
||
/**
|
||
* 从仓库设置(wms_store.subject_config)读取「站内信推送失败自动重发」配置。
|
||
*
|
||
* 结构:`subject_config.inbox_push_retry = { enabled, window_minutes }`(同「收货未入库提醒」的嵌套口径)。
|
||
*
|
||
* 兼容 JSON 字符串与缺失字段,**缺省即兜底 = 关闭**(未配置的仓库不重发):
|
||
* - 开关仅显式传入真值(true / 1 / '1' / 'true')才开启,其余情况(缺失/非法/假值)均为关闭;
|
||
* - 时间范围缺省/非法 → 30 分钟(仅接受 1-1440 的整数,单位分钟)。
|
||
*
|
||
* @param {Object|string|null|undefined} rawSubjectConfig 原始 subject_config(raw 查询可能为字符串)。
|
||
* @return {{enabled: boolean, windowMinutes: number}} 规范化后的配置。
|
||
*/
|
||
function readPushRetryConfig(rawSubjectConfig) {
|
||
let parsed = rawSubjectConfig;
|
||
if (typeof parsed === 'string') {
|
||
try {
|
||
parsed = JSON.parse(parsed);
|
||
} catch (error) {
|
||
parsed = null;
|
||
}
|
||
}
|
||
|
||
const section = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
||
? parsed[PUSH_RETRY_FIELD]
|
||
: null;
|
||
|
||
if (!section || typeof section !== 'object' || Array.isArray(section)) {
|
||
return { enabled: false, windowMinutes: DEFAULT_PUSH_RETRY_WINDOW_MINUTES };
|
||
}
|
||
|
||
// 兜底为关闭:只有显式开启才开启(不再把“缺失/无法识别”当作开启)
|
||
const rawEnabled = section.enabled;
|
||
const enabled = [ true, 1, '1', 'true' ].includes(rawEnabled);
|
||
|
||
const rawWindowMinutes = Number(section.window_minutes);
|
||
const windowMinutes = Number.isInteger(rawWindowMinutes)
|
||
&& rawWindowMinutes >= PUSH_RETRY_WINDOW_MINUTES_MIN
|
||
&& rawWindowMinutes <= PUSH_RETRY_WINDOW_MINUTES_MAX
|
||
? rawWindowMinutes
|
||
: DEFAULT_PUSH_RETRY_WINDOW_MINUTES;
|
||
|
||
return { enabled, windowMinutes };
|
||
}
|
||
|
||
/**
|
||
* 站内信消息查询/管理服务。
|
||
* 提供消息列表、详情、对话链、回复、统计等管理功能。
|
||
*/
|
||
class InboxMessageService extends Service {
|
||
/**
|
||
* 消息列表(多条件筛选,分页)。
|
||
* 支持两种参数风格:
|
||
* 1. 扁平风格:{ warehouseId, storeId, keyword, page, pageSize, ... }
|
||
* 2. 结构化风格:{ pagination: { page, pageSize }, where: { field: { operator, value } } }
|
||
* 时间字段使用 app.formatDate 统一格式化输出。
|
||
*
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
|
||
* @param {Object} [params.pagination] 分页对象(结构化风格)。
|
||
* @param {Object} [params.where] 结构化 where 条件,字段映射同 DB 列名。
|
||
* @param {string|string[]} [params.storeId] 货主ID筛选。
|
||
* @param {string|string[]} [params.groupId] 群ID筛选。
|
||
* @param {string} [params.groupName] 群名称模糊搜索。
|
||
* @param {string} [params.userName] 用户名模糊搜索。
|
||
* @param {string} [params.content] 正文/keyword 模糊搜索。
|
||
* @param {string} [params.sourceType] 来源类型:im / api / system。
|
||
* @param {string} [params.direction] 消息方向:inbound / outbound。
|
||
* @param {number} [params.pushStatus] 推送状态:0/1/2/3。
|
||
* @param {string} [params.startDate] 开始日期。
|
||
* @param {string} [params.endDate] 结束日期。
|
||
* @param {number} [params.page=1] 页码。
|
||
* @param {number} [params.pageSize=20] 每页数量。
|
||
* @return {Promise<{list: Array, pagination: Object}>} 分页结果。
|
||
*/
|
||
async list(params = {}) {
|
||
const { ctx } = this;
|
||
const { Op } = ctx.app.Sequelize;
|
||
const { InboxMessage } = ctx.model;
|
||
|
||
const warehouseId = Number(params.warehouseId);
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('warehouseId 无效');
|
||
}
|
||
|
||
// 分页:优先取 pagination 对象,兜底扁平参数
|
||
const pag = params.pagination || {};
|
||
const page = Math.max(1, Number(pag.page || params.page) || 1);
|
||
const pageSize = Math.min(200, Math.max(1, Number(pag.pageSize || params.pageSize) || 20));
|
||
|
||
// 基础条件
|
||
const where = {
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
};
|
||
|
||
// ── 结构化 where(operator 模式)──
|
||
if (params.where && typeof params.where === 'object') {
|
||
const parsed = parseWhereConditions({
|
||
where: params.where,
|
||
app: ctx.app,
|
||
specialFieldMap: {},
|
||
});
|
||
|
||
if (!parsed.ok) {
|
||
throw new Error(`where 参数解析失败: ${parsed.reason}`);
|
||
}
|
||
|
||
// 合并解析出的条件
|
||
if (Array.isArray(parsed.result.dynamicConditions)) {
|
||
Object.assign(where, ...parsed.result.dynamicConditions);
|
||
}
|
||
|
||
// 前端约定:store_id = 0 视为无货主消息 → IS NULL
|
||
if (where.store_id !== undefined && where.store_id !== null) {
|
||
const sid = where.store_id;
|
||
// Sequelize 将 [0] 展开为 IN (0),需转为 IS NULL
|
||
if (Array.isArray(sid) && sid.length === 1 && sid[0] === 0) {
|
||
where.store_id = { [Op.is]: null };
|
||
} else if (sid === 0 || sid === '0') {
|
||
where.store_id = { [Op.is]: null };
|
||
}
|
||
}
|
||
}
|
||
|
||
// ── 扁平参数(向后兼容,结构化 where 已设置的字段会被覆盖)──
|
||
|
||
// 货主ID(-1 = 无货主消息,即 store_id IS NULL)
|
||
const rawStoreId = params.storeId;
|
||
if (rawStoreId === -1 || rawStoreId === '-1') {
|
||
where.store_id = { [Op.is]: null };
|
||
} else {
|
||
const storeIds = this._normalizeIds(rawStoreId);
|
||
if (storeIds.length > 0) {
|
||
where.store_id = { [Op.in]: storeIds };
|
||
}
|
||
}
|
||
|
||
// 群ID
|
||
const groupIds = this._normalizeStrings(params.groupId);
|
||
if (groupIds.length > 0) {
|
||
where.group_id = { [Op.in]: groupIds };
|
||
}
|
||
|
||
// 群名称
|
||
const groupName = String(params.groupName || '').trim();
|
||
if (groupName) {
|
||
where.group_name = { [Op.like]: `%${groupName}%` };
|
||
}
|
||
|
||
// 用户名
|
||
const userName = String(params.userName || '').trim();
|
||
if (userName) {
|
||
where.user_name = { [Op.like]: `%${userName}%` };
|
||
}
|
||
|
||
// 关键词:content + group_name + user_name
|
||
const rawKw = params.content || params.keyword;
|
||
const keyword = Array.isArray(rawKw)
|
||
? String(rawKw.filter(Boolean)[0] || '').trim()
|
||
: String(rawKw || '').trim();
|
||
if (keyword) {
|
||
const like = { [Op.like]: `%${keyword}%` };
|
||
where[Op.or] = [
|
||
{ content: like },
|
||
{ group_name: like },
|
||
{ user_name: like },
|
||
];
|
||
}
|
||
|
||
// 来源类型
|
||
const VALID_SOURCE_TYPES = [ 'im', 'api', 'system' ];
|
||
const sourceType = String(params.sourceType || '').trim();
|
||
if (sourceType && VALID_SOURCE_TYPES.includes(sourceType)) {
|
||
where.source_type = sourceType;
|
||
}
|
||
|
||
// 日期范围(扁平参数兜底,结构化 where 已通过 created_at 处理)
|
||
if (!where.created_at) {
|
||
const startDate = params.startDate || params.start_date;
|
||
const endDate = params.endDate || params.end_date;
|
||
if (startDate || endDate) {
|
||
where.created_at = {};
|
||
if (startDate) where.created_at[Op.gte] = new Date(startDate);
|
||
if (endDate) where.created_at[Op.lte] = new Date(endDate);
|
||
}
|
||
}
|
||
|
||
// 方向
|
||
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
|
||
where.direction = params.direction;
|
||
}
|
||
|
||
// 推送状态
|
||
if (params.pushStatus !== undefined && params.pushStatus !== null && params.pushStatus !== '') {
|
||
const status = Number(params.pushStatus);
|
||
if ([ 0, 1, 2, 3 ].includes(status)) {
|
||
where.push_status = status;
|
||
}
|
||
}
|
||
|
||
const { count: total, rows } = await InboxMessage.findAndCountAll({
|
||
attributes: {
|
||
exclude: [ 'ext_data', 'push_response', 'target_channel' ],
|
||
},
|
||
where,
|
||
order: [[ 'created_at', 'DESC' ]],
|
||
offset: (page - 1) * pageSize,
|
||
limit: pageSize,
|
||
});
|
||
|
||
// 批量查货主备注名称(StoreWarehouse.store_remask)
|
||
const storeIdsInResult = [ ...new Set(rows.map(r => r.store_id).filter(Boolean)) ];
|
||
const storeNameMap = {};
|
||
if (storeIdsInResult.length > 0) {
|
||
const contracts = await ctx.model.StoreWarehouse.findAll({
|
||
attributes: [ 'store_id', 'store_remask' ],
|
||
where: {
|
||
store_id: { [Op.in]: storeIdsInResult },
|
||
warehouse_id: warehouseId,
|
||
},
|
||
raw: true,
|
||
});
|
||
for (const c of contracts) {
|
||
storeNameMap[c.store_id] = c.store_remask || '';
|
||
}
|
||
}
|
||
|
||
const formatDate = ctx.app.formatDate;
|
||
const list = rows.map(row => {
|
||
const obj = row && typeof row.toJSON === 'function' ? row.toJSON() : row;
|
||
return {
|
||
...obj,
|
||
store_name: storeNameMap[obj.store_id] || '',
|
||
created_at: obj.created_at ? formatDate(obj.created_at) : '',
|
||
updated_at: obj.updated_at ? formatDate(obj.updated_at) : '',
|
||
pushed_at: obj.pushed_at ? formatDate(obj.pushed_at) : '',
|
||
};
|
||
});
|
||
|
||
return {
|
||
list,
|
||
pagination: {
|
||
page,
|
||
pageSize,
|
||
total,
|
||
totalPages: Math.ceil(total / pageSize),
|
||
hasPrevious: page > 1,
|
||
hasNext: page * pageSize < total,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将入参统一为数字ID数组。
|
||
* 支持逗号分隔字符串 "1,2,3" 或数组 [1,2,3]。
|
||
* @param {string|string[]|number[]|undefined} val 入参。
|
||
* @return {number[]} 去重后的数字数组。
|
||
*/
|
||
_normalizeIds(val) {
|
||
if (val === undefined || val === null) return [];
|
||
const arr = Array.isArray(val) ? val : String(val).split(',');
|
||
return [ ...new Set(arr.map(Number).filter(v => Number.isFinite(v) && v > 0)) ];
|
||
}
|
||
|
||
/**
|
||
* 将入参统一为字符串数组(去重去空)。
|
||
* @param {string|string[]|undefined} val 入参。
|
||
* @return {string[]} 去重后的非空字符串数组。
|
||
*/
|
||
_normalizeStrings(val) {
|
||
if (val === undefined || val === null) return [];
|
||
const arr = Array.isArray(val) ? val : String(val).split(',');
|
||
return [ ...new Set(arr.map(String).map(s => s.trim()).filter(Boolean)) ];
|
||
}
|
||
|
||
/**
|
||
* 消息详情(含 push_response)。
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||
* @param {number} params.id 消息ID。
|
||
* @return {Promise<Object>} 消息详情。
|
||
*/
|
||
async detail(params = {}) {
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
|
||
const warehouseId = Number(params.warehouseId);
|
||
const id = Number(params.id);
|
||
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('warehouseId 无效');
|
||
}
|
||
if (!Number.isFinite(id) || id <= 0) {
|
||
throw new Error('消息ID无效');
|
||
}
|
||
|
||
const record = await InboxMessage.findOne({
|
||
where: { id, warehouse_id: warehouseId, deleted_at: null },
|
||
});
|
||
|
||
if (!record) {
|
||
throw new Error('消息不存在或无权访问');
|
||
}
|
||
|
||
return record;
|
||
}
|
||
|
||
/**
|
||
* 对话链查询(原消息 + 所有回信),按 parent_id 递归。
|
||
* @param {Object} params 查询参数。
|
||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||
* @param {number} params.id 消息ID。
|
||
* @return {Promise<Array>} 对话链列表。
|
||
*/
|
||
async thread(params = {}) {
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
|
||
const warehouseId = Number(params.warehouseId);
|
||
const id = Number(params.id);
|
||
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('warehouseId 无效');
|
||
}
|
||
if (!Number.isFinite(id) || id <= 0) {
|
||
throw new Error('消息ID无效');
|
||
}
|
||
|
||
// 查找根消息
|
||
const root = await InboxMessage.findOne({
|
||
where: { id, warehouse_id: warehouseId },
|
||
});
|
||
|
||
if (!root) {
|
||
throw new Error('消息不存在或无权访问');
|
||
}
|
||
|
||
// 收集对话链:从根到叶
|
||
const MAX_THREAD_DEPTH = 50;
|
||
const thread = [ root ];
|
||
const visited = new Set([ root.id ]);
|
||
|
||
// 查找所有回信(以 root.id 为 parent_id)
|
||
const replies = await InboxMessage.findAll({
|
||
where: {
|
||
warehouse_id: warehouseId,
|
||
parent_id: root.id,
|
||
deleted_at: null,
|
||
},
|
||
order: [[ 'created_at', 'ASC' ]],
|
||
});
|
||
|
||
for (const reply of replies) {
|
||
if (!visited.has(reply.id) && thread.length < MAX_THREAD_DEPTH) {
|
||
visited.add(reply.id);
|
||
thread.push(reply);
|
||
}
|
||
}
|
||
|
||
// 如果当前消息不是根(有 parent_id),也向上查找原消息
|
||
if (root.parent_id) {
|
||
const parent = await InboxMessage.findOne({
|
||
where: {
|
||
id: root.parent_id,
|
||
warehouse_id: warehouseId,
|
||
deleted_at: null,
|
||
},
|
||
});
|
||
|
||
if (parent && !visited.has(parent.id) && thread.length < MAX_THREAD_DEPTH) {
|
||
visited.add(parent.id);
|
||
thread.unshift(parent);
|
||
}
|
||
}
|
||
|
||
return thread;
|
||
}
|
||
|
||
/**
|
||
* 推送统计(按仓库 + 方向汇总)。
|
||
* @param {Object} params 统计参数。
|
||
* @param {number} params.warehouseId 仓库ID(必填)。
|
||
* @return {Promise<Object>} 统计结果。
|
||
*/
|
||
async stats(params = {}) {
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
const { Op } = ctx.app.Sequelize;
|
||
|
||
const warehouseId = Number(params.warehouseId);
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('warehouseId 无效');
|
||
}
|
||
|
||
const where = {
|
||
warehouse_id: warehouseId,
|
||
};
|
||
|
||
if (params.direction && [ 'inbound', 'outbound' ].includes(params.direction)) {
|
||
where.direction = params.direction;
|
||
}
|
||
|
||
// 按方向统计
|
||
const directionStats = await InboxMessage.findAll({
|
||
attributes: [
|
||
'direction',
|
||
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
|
||
],
|
||
where,
|
||
group: [ 'direction' ],
|
||
raw: true,
|
||
});
|
||
|
||
// 按推送状态统计
|
||
const statusStats = await InboxMessage.findAll({
|
||
attributes: [
|
||
'push_status',
|
||
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.col('id')), 'count' ],
|
||
],
|
||
where,
|
||
group: [ 'push_status' ],
|
||
raw: true,
|
||
});
|
||
|
||
// 最近24小时统计
|
||
const recentWhere = {
|
||
...where,
|
||
created_at: {
|
||
[Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000),
|
||
},
|
||
};
|
||
|
||
const recentCount = await InboxMessage.count({ where: recentWhere });
|
||
|
||
return {
|
||
total_by_direction: directionStats,
|
||
total_by_status: statusStats,
|
||
recent_24h_count: recentCount,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 手动重推失败(push_status=3)的站内信消息。
|
||
* 重置为待推送状态(push_status=0)并触发异步推送;
|
||
* 推送结果回写到同一记录(复用原记录,不新建回执记录)。
|
||
* @param {Object} params 重推参数。
|
||
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
|
||
* @param {number} params.id 消息ID。
|
||
* @return {Promise<Object>} { ok, id, ext_id, message }。
|
||
*/
|
||
async retry(params = {}) {
|
||
const { ctx } = this;
|
||
const { InboxMessage } = ctx.model;
|
||
|
||
const warehouseId = Number(params.warehouseId);
|
||
const id = Number(params.id);
|
||
|
||
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||
throw new Error('warehouseId 无效');
|
||
}
|
||
if (!Number.isFinite(id) || id <= 0) {
|
||
throw new Error('消息ID无效');
|
||
}
|
||
|
||
const record = await InboxMessage.findOne({
|
||
where: { id, warehouse_id: warehouseId, deleted_at: null },
|
||
});
|
||
|
||
if (!record) {
|
||
throw new Error('消息不存在或无权访问');
|
||
}
|
||
if (record.push_status !== 3) {
|
||
throw new Error('仅失败状态的消息可以手动重推');
|
||
}
|
||
|
||
// 重置为待推送状态
|
||
await InboxMessage.update(
|
||
{ push_status: 0, push_response: null, push_started_at: null },
|
||
{ where: { id } }
|
||
);
|
||
|
||
// 触发异步推送(复用原记录回写推送结果)
|
||
setImmediate(() => {
|
||
this._repush(record).catch(async err => {
|
||
ctx.logger.error(`[inbox] 手动重推异步推送异常 id=${id}: ${err.message}`);
|
||
// 推送前校验失败时回写失败状态,避免消息卡在待推送
|
||
try {
|
||
await InboxMessage.update(
|
||
{ push_status: 3, push_response: { error: err.message } },
|
||
{ where: { id } }
|
||
);
|
||
} catch (updateErr) {
|
||
ctx.logger.error(`[inbox] 重推失败状态回写异常 id=${id}: ${updateErr.message}`);
|
||
}
|
||
});
|
||
});
|
||
|
||
return {
|
||
ok: true,
|
||
id: record.id,
|
||
ext_id: record.ext_id,
|
||
message: '已重置为待推送状态,正在异步重推',
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 重推一条已存在的出站消息记录(推送结果回写到该记录本身,不新建记录)。
|
||
*
|
||
* 与直接调用 processor.writeOutboundReply 的区别:
|
||
* - 传 reuse_message_id,让其跳过按 `sys:ack:{ext_id}` 查建,直接复用该记录;
|
||
* - 否则 sys:notice:* 类型(warehouseNotify 系统通知)会被另建一条 sys:ack:sys:notice:*
|
||
* 记录推送,原记录状态永远停留在失败/待推送,重推也无法继续。
|
||
* 本方法推送期间不改动记录状态:推送完成由推送链路回写 2/3,进程中断则保持 3 等下一轮。
|
||
*
|
||
* @param {Object} record 消息记录(InboxMessage 行,Sequelize 实例或 raw 对象)。
|
||
* @return {Promise<void>} 推送完成(结果已回写)。
|
||
*/
|
||
async _repush(record) {
|
||
const { ctx } = this;
|
||
const extId = String(record.ext_id || '');
|
||
// 回执记录 ext_id 形如 sys:ack:{原消息ext_id},反解出原消息 ext_id 以复用推送链路
|
||
const originalExtId = extId.startsWith('sys:ack:') ? extId.slice(8) : extId;
|
||
const hasUser = Boolean(record.user_id && record.user_name);
|
||
|
||
await ctx.service.inbox.processor.writeOutboundReply({
|
||
warehouse_id: Number(record.warehouse_id) || 0,
|
||
ext_id: originalExtId,
|
||
parent_id: record.parent_id || null,
|
||
group_id: record.group_id || '',
|
||
group_name: record.group_name || '',
|
||
user_id: record.user_id || '',
|
||
user_name: record.user_name || '',
|
||
ext_data: record.ext_data || null,
|
||
reuse_message_id: Number(record.id) || 0,
|
||
}, record.content || '', hasUser ? 'ai_reply' : 'system', record.extend_props || null);
|
||
}
|
||
|
||
/**
|
||
* 批量重推「推送失败」的出站消息(供定时任务调用)。
|
||
*
|
||
* 规则:
|
||
* 1. 只处理失败时间(created_at)在窗口内的记录,默认 30 分钟;超窗口不再补推;
|
||
* 2. 逐条串行重推并等待结果回写,单条异常不影响其余记录;
|
||
* 3. 重推期间记录保持失败状态,进程中断时下一轮仍能被扫到(不丢消息);
|
||
* 4. 缺少 warehouse_id / group_id / group_name / content 的记录无法重放,跳过并计数。
|
||
*
|
||
* @param {Object} [params] 查询参数。
|
||
* @param {number} [params.warehouseId] 仓库ID:传入时只处理该仓库的失败消息(定时任务按仓库逐个处理)。
|
||
* @param {number} [params.windowMs] 失败时间窗(毫秒),默认 config.inbox.pushRetryWindowMs。
|
||
* @param {number} [params.limit] 单轮最多重推条数,默认 config.inbox.pushRetryLimit。
|
||
* @return {Promise<Object>} { scanned, retried, succeeded, failed, skipped }。
|
||
*/
|
||
async retryFailed(params = {}) {
|
||
const { ctx } = this;
|
||
const { Op } = ctx.app.Sequelize;
|
||
const { InboxMessage } = ctx.model;
|
||
|
||
const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {};
|
||
const warehouseId = Number(params.warehouseId) > 0 ? Number(params.warehouseId) : 0;
|
||
const configuredWindow = Number(inboxConfig.pushRetryWindowMs);
|
||
const windowMs = Number(params.windowMs) > 0
|
||
? Number(params.windowMs)
|
||
: (configuredWindow > 0 ? configuredWindow : DEFAULT_PUSH_RETRY_WINDOW_MS);
|
||
const configuredLimit = Number(inboxConfig.pushRetryLimit);
|
||
const rawLimit = Number(params.limit) > 0
|
||
? Number(params.limit)
|
||
: (configuredLimit > 0 ? configuredLimit : DEFAULT_PUSH_RETRY_LIMIT);
|
||
const limit = Math.min(MAX_PUSH_RETRY_LIMIT, Math.max(1, Math.trunc(rawLimit)));
|
||
|
||
// 先补早失败的消息(更快接近时间窗边界)
|
||
const where = {
|
||
direction: 'outbound',
|
||
push_status: 3,
|
||
created_at: { [Op.gte]: new Date(Date.now() - windowMs) },
|
||
};
|
||
// 仓库维度(定时任务逐仓处理):只扫该仓库的失败消息
|
||
if (warehouseId > 0) {
|
||
where.warehouse_id = warehouseId;
|
||
}
|
||
|
||
const rows = await InboxMessage.findAll({
|
||
where,
|
||
attributes: [
|
||
'id', 'warehouse_id', 'ext_id', 'parent_id',
|
||
'group_id', 'group_name', 'user_id', 'user_name',
|
||
'ext_data', 'content', 'extend_props',
|
||
],
|
||
order: [[ 'created_at', 'ASC' ], [ 'id', 'ASC' ]],
|
||
limit,
|
||
raw: true,
|
||
});
|
||
|
||
const summary = { scanned: rows.length, retried: 0, succeeded: 0, failed: 0, skipped: 0 };
|
||
|
||
for (const row of rows) {
|
||
// 空文案但含 extend_props 的回执(如开门指令)可重放;两者皆空才跳过
|
||
if (!(Number(row.warehouse_id) > 0) || !row.group_id || !row.group_name
|
||
|| (!row.content && !row.extend_props)) {
|
||
summary.skipped++;
|
||
ctx.logger.warn(`[inbox] 自动重推跳过消息 id=${row.id}(缺少 warehouse_id/group_id/group_name/content+extend_props,无法重放)`);
|
||
continue;
|
||
}
|
||
|
||
try {
|
||
await this._repush(row);
|
||
summary.retried++;
|
||
|
||
const fresh = await InboxMessage.findOne({
|
||
where: { id: row.id },
|
||
attributes: [ 'push_status' ],
|
||
raw: true,
|
||
});
|
||
if (fresh && Number(fresh.push_status) === 2) {
|
||
summary.succeeded++;
|
||
} else {
|
||
summary.failed++;
|
||
}
|
||
|
||
// 已重试次数仅作观测;失败不影响主流程
|
||
try {
|
||
await InboxMessage.increment('retry_count', { where: { id: row.id } });
|
||
} catch (countErr) {
|
||
ctx.logger.warn(`[inbox] 自动重推计数失败 id=${row.id}: ${countErr.message}`);
|
||
}
|
||
} catch (error) {
|
||
summary.failed++;
|
||
ctx.logger.warn(`[inbox] 自动重推异常 id=${row.id}: ${error.message}`);
|
||
}
|
||
}
|
||
|
||
return summary;
|
||
}
|
||
|
||
/**
|
||
* 按仓库设置批量重推「推送失败」的出站消息(定时任务入口)。
|
||
*
|
||
* 流程:
|
||
* 1. 全局总开关(config.inbox.pushRetryEnabled)关闭时直接返回,支持运维应急停发;
|
||
* 2. 先找出「近 1440 分钟(时间范围上限)内存在推送失败消息」的仓库,只对这些仓库读设置,
|
||
* 避免每轮全仓扫描;
|
||
* 3. 逐仓判断仓库设置 `subject_config.inbox_push_retry.enabled`(缺省关闭,仅显式开启才重推):关闭则跳过;
|
||
* 4. 开启的仓库按 `subject_config.inbox_push_retry.window_minutes`(缺省 30 分钟)
|
||
* 调 retryFailed 只补该窗口内的失败消息。
|
||
*
|
||
* @param {Object} [params] 调用参数。
|
||
* @param {number} [params.limit] 单仓单轮最多重推条数,默认 config.inbox.pushRetryLimit。
|
||
* @return {Promise<Object>} { warehouses, enabledWarehouses, disabledWarehouses, skippedWarehouses,
|
||
* scanned, retried, succeeded, failed, skipped, disabledGlobally }。
|
||
*/
|
||
async retryFailedByWarehouse(params = {}) {
|
||
const { ctx } = this;
|
||
const { Op } = ctx.app.Sequelize;
|
||
const { InboxMessage, Store } = ctx.model;
|
||
|
||
const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {};
|
||
const summary = {
|
||
warehouses: 0,
|
||
enabledWarehouses: 0,
|
||
disabledWarehouses: 0,
|
||
skippedWarehouses: 0,
|
||
scanned: 0,
|
||
retried: 0,
|
||
succeeded: 0,
|
||
failed: 0,
|
||
skipped: 0,
|
||
disabledGlobally: false,
|
||
};
|
||
|
||
// 全局总开关:仓库维度开关在仓库设置里
|
||
if (inboxConfig.pushRetryEnabled === false) {
|
||
summary.disabledGlobally = true;
|
||
ctx.logger.warn('[inbox] 自动重推已被全局开关(config.inbox.pushRetryEnabled)关闭');
|
||
return summary;
|
||
}
|
||
|
||
// 候选仓库:时间范围上限内存在失败消息的仓库(去重),只查有失败的仓库
|
||
const maxWindowMs = PUSH_RETRY_WINDOW_MINUTES_MAX * 60 * 1000;
|
||
const warehouseRows = await InboxMessage.findAll({
|
||
where: {
|
||
direction: 'outbound',
|
||
push_status: 3,
|
||
created_at: { [Op.gte]: new Date(Date.now() - maxWindowMs) },
|
||
},
|
||
attributes: [ 'warehouse_id' ],
|
||
group: [ 'warehouse_id' ],
|
||
raw: true,
|
||
});
|
||
const warehouseIds = (Array.isArray(warehouseRows) ? warehouseRows : [])
|
||
.map(row => Number(row && row.warehouse_id) || 0)
|
||
.filter(id => id > 0);
|
||
summary.warehouses = warehouseIds.length;
|
||
|
||
if (warehouseIds.length === 0) {
|
||
return summary;
|
||
}
|
||
|
||
const storeModel = Store;
|
||
if (!storeModel || typeof storeModel.findAll !== 'function') {
|
||
ctx.logger.warn('[inbox] Store 模型不可用,跳过自动重推');
|
||
summary.skippedWarehouses = warehouseIds.length;
|
||
return summary;
|
||
}
|
||
|
||
// 批量取仓库设置(raw 行避免脏配置触发模型 getter 抛错);
|
||
// 不按 status 过滤:wms_store.status 是启用/审核中状态(非仓库标识),
|
||
// 且仓库设置里的开关才是唯一控制项,避免审核中/停用仓库的回信被静默跳过而永久丢失
|
||
const storeRows = await storeModel.findAll({
|
||
where: { id: { [Op.in]: warehouseIds }, deleted_at: null },
|
||
attributes: [ 'id', 'company_name', 'subject_config' ],
|
||
raw: true,
|
||
});
|
||
const configMap = new Map();
|
||
for (const storeRow of Array.isArray(storeRows) ? storeRows : []) {
|
||
const id = Number(storeRow && storeRow.id) || 0;
|
||
if (id > 0) {
|
||
configMap.set(id, storeRow);
|
||
}
|
||
}
|
||
|
||
for (const warehouseId of warehouseIds) {
|
||
const storeRow = configMap.get(warehouseId);
|
||
if (!storeRow) {
|
||
summary.skippedWarehouses++;
|
||
ctx.logger.warn(`[inbox] 自动重推跳过仓库 ${warehouseId}(wms_store 无该仓库记录,无法读取仓库设置)`);
|
||
continue;
|
||
}
|
||
|
||
const retryConfig = readPushRetryConfig(storeRow.subject_config);
|
||
if (!retryConfig.enabled) {
|
||
summary.disabledWarehouses++;
|
||
continue;
|
||
}
|
||
summary.enabledWarehouses++;
|
||
|
||
const result = await this.retryFailed({
|
||
warehouseId,
|
||
windowMs: retryConfig.windowMinutes * 60 * 1000,
|
||
limit: params.limit,
|
||
});
|
||
|
||
summary.scanned += result.scanned;
|
||
summary.retried += result.retried;
|
||
summary.succeeded += result.succeeded;
|
||
summary.failed += result.failed;
|
||
summary.skipped += result.skipped;
|
||
|
||
if (result.scanned > 0) {
|
||
ctx.logger.info(
|
||
`[inbox] 仓库 ${warehouseId}(${String(storeRow.company_name || '').trim() || '-'})自动重推:`
|
||
+ `窗口 ${retryConfig.windowMinutes} 分钟 scanned=${result.scanned} retried=${result.retried} `
|
||
+ `succeeded=${result.succeeded} failed=${result.failed} skipped=${result.skipped}`
|
||
);
|
||
}
|
||
}
|
||
|
||
return summary;
|
||
}
|
||
}
|
||
|
||
module.exports = InboxMessageService;
|