feat(inbox): 新增出站推送失败自动重推定时任务

新增 app/schedule/retry_inbox_push.js:每 3 分钟扫描「push_status=3 且失败时间在 2 小时内」的
出站消息并重推(config.inbox.pushRetryWindowMs / pushRetryLimit,单轮默认 20 条、硬上限 200),
成功即停、失败下一轮继续、超出窗口不再补推;worker 单进程执行 + app._inboxPushRetryRunning
重入锁,scanned>0 才写日志。

- inbox.message 新增 retryFailed():按 created_at ASC 逐条串行重推(先补更接近窗口边界的),
  缺 warehouse_id/group_id/group_name/content 的记录跳过并告警,retry_count 递增仅作观测
- inbox.message 新增 _repush():复用原记录重推(reuse_message_id),ext_id 剥离 sys:ack: 前缀,
  有用户信息走 ai_reply、系统通知走 system;重推期间不改记录状态,进程中断时下一轮仍能扫到
- processor.writeOutboundReply 支持 reuse_message_id:重推时跳过按 sys:ack:{ext_id} 查建记录,
  推送结果回写到原记录本身,修复系统通知(sys:notice:*)重推会另建记录、原记录状态永远停留在
  失败/待推送的问题;状态回写由 ext_id 改为按记录 id(对既有调用路径等价)
- 手动重推 retry() 改走 _repush,入参与响应文案不变,methods/system.json 无需变更

失败主因是桥接离线(回调 HTTP 200 但 body code=503:wx offline / qiwe offline),属可自愈的
临时故障;此前仅支持人工单条重推,生产已积压 2441 条未送达的客户回信与系统通知。

单测 test/inbox/retry_inbox_push.test.js 18 例(纯 mock,覆盖调度配置/重入/异常兜底/扫描条件/
窗口与上限/复用原记录/跳过与容错);AI_METHOD_ROUTING.md 方法清单已刷新(inbox/message.js 7 → 9)。
This commit is contained in:
liufumingren 2026-09-15 22:38:38 +08:00
parent 74e53d4d87
commit e666abc0a2
5 changed files with 256 additions and 55 deletions

View File

@ -254,6 +254,23 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 事件注册表:`app/service/openapi/callbackRegistry.js#CALLBACK_EVENTS`(5 条,每条含 `name`/`label`/`description`/`request`,`request` 为奇门同层级报文模板),回调调试页 `GET /docs/api/openapi/callback-test`(`app/controller/openapiCallback.js`)直接消费该注册表,并按注册表自动预填完整报文体 `{ request: {...} }`
- 完整协议文档:`docs/openapi-callback-events.md`
## 5.7 camera(摄像头 OSD / 云台 PTZ)能力速查
| method | 实现文件 | 函数 | 登录 | 鉴权/权限 |
|---|---|---|---|---|
| camera.setOsd | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/osd_client.js | setOsd | 需登录 | 免权限(systemInit 声明 setOsd) |
| camera.ptzControl | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzControl / control | 需登录 | 免权限(systemInit 声明 ptzControl) |
| camera.ptzStop | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzStop / stop | 需登录 | 免权限(systemInit 声明 ptzStop) |
| camera.ptzPresetGoto | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzPresetGoto / presetGoto | 需登录 | 免权限(systemInit 声明 ptzPresetGoto) |
| camera.ptzPresetSet | app/service/systemMethods/camera.js → app/service/systems/camera.js → app/lib/ptz_client.js | ptzPresetSet / presetSet | 需登录 | 免权限(systemInit 声明 ptzPresetSet) |
- 云台方向 action 枚举(8 个位置,服务端转小写校验,非法值报 400):`up` 上、`down` 下、`left` 左、`right` 右、`upleft` 左上、`upright` 右上、`downleft` 左下、`downright` 右下(常量见 `app/lib/ptz_client.js#PTZ_ACTION_LIST`,文档已写入 `methods/system.json#camera.ptzControl.params[].action.list`)
- 交互口径:按下 `camera.ptzControl`(参数 `id`/`action`,可选 `speed` 1-7 默认 4)→ 松手 `camera.ptzStop`(`action` 必须与按下时一致);预置点存点 `camera.ptzPresetSet`(`presetId` 1-256,把当前机位存为该编号,重复设置即覆盖)与跳转 `camera.ptzPresetGoto`(`presetId` 1-256)均是一次性动作,无需 stop
- 下发通道:**独立端点,与 setOSD 同风格,不需要 computerId** —— `POST {printService.url}/camera/ptzControl` / `/camera/ptzStop` / `/camera/ptzPresetGoto` / `/camera/ptzPresetSet`,请求体依次为 `{ warehouse_id, cameraId, rtspUrl, action, speed }` / `{ warehouse_id, cameraId, rtspUrl, action }` / `{ warehouse_id, cameraId, rtspUrl, presetId }` / `{ warehouse_id, cameraId, rtspUrl, presetId }`(`warehouse_id` 为字符串、`cameraId` 为数值型 `wms_camera.id`;`_send` 统一拼接)
- `rtspUrl` 由服务端组装(`rtsp://{username}:{password}@{ip}:554/stream{channel_id}`,与 `osd_client.buildRtspUrl` 同口径),前端不传
- 失败口径:参数非法 → 400(`摄像头ID不能为空`/`云台方向不合法,仅支持:…`/`云台转速需为 1-7 的整数`/`预置点编号…`);摄像头不存在或跨仓库 → 404;打印服务 HTTP 非 2xx 或回包 `status=fail`/`success=false` → 500 `打印服务请求失败: …`
- 接口文档:`methods/system.json` 分组「摄像头模块」(module=camera),变更记录见 `methods/changes/system.json` 版本 `2026.09.15-camera-ptz-control`(首次登记)、`2026.09.15-camera-ptz-wms-endpoint`(改独立端点)、`2026.09.15-camera-ptz-preset-set`(新增存点)、`2026.09.15-camera-ptz-camera-id`(请求体带 cameraId)
## method结束
## 6. 全量 Service Method 能力清单(自动扫描)
@ -265,10 +282,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 临时清单输出:temp/tmp-service-method-inventory.md
<!-- SERVICE_METHOD_INVENTORY:BEGIN -->
自动生成时间: 2026-09-15T05:49:02.545Z
自动生成时间: 2026-09-15T12:58:24.457Z
扫描范围: app/service/**/*.js
文件数: 210
文件数: 211
- app/service/api.js (1)
- callMethod
@ -290,8 +307,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- resolveActiveGroups, isFunctionAvailable, getFunctionList, buildFunctionListText
- app/service/inbox/index.js (5)
- list, detail, thread, reply, stats
- app/service/inbox/message.js (7)
- list, _normalizeIds, _normalizeStrings, detail, thread, stats, retry
- app/service/inbox/message.js (9)
- list, _normalizeIds, _normalizeStrings, detail, thread, stats, retry, _repush, retryFailed
- app/service/inbox/processor.js (15)
- _loadGroupInfo, isStaleMessage, process, handleApiMessage, tryBindGroup, writeOutboundReply, isBlocked, invalidateBlockCache, getApiAppCallbackConfig, getApiAppCallbackUrl, pushSystemNotification, extractWarehouseId, extractStoreId, getWarehouseIdFromContext, getStoreIdFromContext
- app/service/inbox/receiver.js (1)
@ -352,8 +369,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- workList, _resolveAfterSaleBlockRoleGroups, workCount, auditList, detail, create, _resolveRedundantFields, transfer, handleWorkOrder, batchSetPendingFeedback, batchClose, registerClaim, export, exportTaskProgress, generateAfterSaleNo, _getCurrentDatePart, _buildOperatorSnapshot, generateExportTaskId, normalizeExportTaskId, getExportTaskCacheKey, setExportTaskProgress, getExportTaskProgress
- app/service/systemMethods/apiApp.js (6)
- list, detail, create, update, delete, regenerateSecret
- app/service/systemMethods/camera.js (6)
- list, detail, create, update, setOsd, delete
- app/service/systemMethods/camera.js (10)
- list, detail, create, update, setOsd, ptzControl, ptzStop, ptzPresetGoto, ptzPresetSet, delete
- app/service/systemMethods/cameraServer.js (5)
- list, detail, create, update, delete
- app/service/systemMethods/comboGoods.js (5)
@ -506,8 +523,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- normalizeTypeFilter, normalizePermissionSet, toApiPermissionIds, serializePermissionSet, getPermissionIdsForRoles, assignPermissions, removePermissionsFromAllRoles
- app/service/systems/auth/user.js (66)
- getMenuTypeWhereByPlatform, getCurrentAccountId, getWechatBindCacheKey, getWechatBindCodeCacheKey, getWechatBindScanCacheKey, getWechatLoginClientCacheKey, getWechatLoginCodeCacheKey, getWechatLoginEventChannel, createWechatBindCodeCandidate, createUniqueSixCode, createWechatBindCode, createWechatLoginCode, createWechatLoginClientCode, parseWechatBindCode, formatBindWechatData, formatLoginWechatData, getRemainingSecondsByExpiresAt, setWechatBindCache, setWechatBindCodeCache, setWechatBindScanCache, getWechatBindScanCache, setWechatLoginClientCache, setWechatLoginCodeCache, findYe4sBindingByAccountId, getWechatBindEventChannel, getWechatLongPollTimeoutMs, shouldUseWechatBindLongPoll, publishWechatBindEvent, waitForWechatBindEvent, refreshWechatBindState, login, loginByYe4sCode, waitForLoginCodeRefresh, isTransientWechatLoginError, extractYe4sUserIdFromLoginEvent, waitForWechatLoginEvent, loginByYe4sUserId, tryBuildWechatLoginTokenFromState, refreshWechatLoginState, getLoginWechatCode, getBindWechatCode, getBindWechatCodeByAccountId, getUserByTempCode, bindAccountByTempCode, unbindWechat, unbindWechatByAccountId, buildLoginResult, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
- app/service/systems/camera.js (6)
- list, detail, create, update, setOsd, delete
- app/service/systems/camera.js (12)
- list, detail, create, update, setOsd, _findCameraForControl, _assertPtzSuccess, ptzControl, ptzStop, ptzPresetGoto, ptzPresetSet, delete
- app/service/systems/cameraServer.js (5)
- list, detail, create, update, delete
- app/service/systems/comboGoods.js (15)
@ -554,6 +571,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- finalizeSuccessfulQimenSync, syncQmOrders, syncManualOrders, flushDeferredOrderSyncNotices, syncApiOrders, syncStockoutOrders, buildStockoutConfirmRequest, notifyStockoutExternal, resolveOpenApiAppByStore
- app/service/systems/order_auto_outbound.js (7)
- getEnabledAutoOutboundWarehouses, normalizeSubjectConfigForAutoOutbound, buildAutoOutboundWhere, findAutoOutboundOrders, findOrderIdsWithWeigh, processWarehouseAutoOutbound, executeAutoOutbound
- app/service/systems/order_delivery_archive.js (17)
- getArchiveDefaults, buildArchiveOptions, NOW, buildArchiveThresholds, normalizeWarehouseIds, listDispatchWarehouseIds, getArchiveModels, buildCandidateWhere, buildQueryOptions, buildHistoryOrderRow, buildHistoryItemRow, getArchiveErrorInfo, rollbackQuietly, archiveDispatchBatch, archiveDispatchOrdersForWarehouse, resolveFailureCursor, archiveDispatchOrdersToHistory
- app/service/systems/order_delivery_migration.js (15)
- syncOutboundOrdersToDelivery, retryTimeoutOutboundOrdersToDelivery, syncOutboundOrdersByStatus, normalizeWarehouseIds, listCurrentWarehouseIds, normalizeOutboundStatuses, buildMigrationQueryOptions, getOutboundMigrationErrorInfo, markOutboundOrdersTimeout, buildDispatchKey, buildDispatchRow, buildDispatchItemRow, getMigrationModels, buildTargetOrderIdMap, syncOutboundOrdersForWarehouse
- app/service/systems/order_export.js (14)
@ -710,6 +729,14 @@ rg "class .*Service|module.exports" app/service/qimenMethods

View File

@ -0,0 +1,54 @@
'use strict';
/**
* 站内信出站推送失败自动重推定时任务。
*
* 每 3 分钟在单 worker 中扫描一次「推送失败(push_status=3)且失败时间在窗口内」的出站消息
* (窗口默认 2 小时,超窗口的消息不再补推,避免陈旧回信/通知打扰用户),逐条复用原记录重推:
* 推送结果仍回写到同一条记录(成功 2 / 失败 3),成功后不再被扫到,失败则由下一轮继续重试,
* 直到推送成功或滑出时间窗。
*
* 典型失败原因是桥接离线(回调 HTTP 200 但 body code=503,如 wx offline / qiwe offline),
* 属可自愈的临时故障:桥接恢复后靠本任务补发,无需人工介入。
*
* 单轮最多重推条数与失败时间窗由 config.inbox 控制:
* - pushRetryWindowMs:失败时间窗(毫秒,默认 2 小时)
* - pushRetryLimit:单轮最多重推条数(默认 20,硬上限 200)
*/
module.exports = {
schedule: {
interval: '3m',
type: 'worker',
immediate: false,
disable: false,
},
/**
* 执行出站推送失败消息重推。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
if (ctx.app._inboxPushRetryRunning) {
return;
}
ctx.app._inboxPushRetryRunning = true;
try {
const result = await ctx.service.inbox.message.retryFailed();
// 无待重推记录时不刷日志,避免每 3 分钟噪音
if (result && result.scanned > 0) {
ctx.logger.info(
`[retry-inbox-push] 本轮重推 scanned=${result.scanned} retried=${result.retried} ` +
`succeeded=${result.succeeded} failed=${result.failed} skipped=${result.skipped}`
);
}
} catch (error) {
ctx.logger.error(`[retry-inbox-push] 任务执行失败: ${error.message}`);
} finally {
ctx.app._inboxPushRetryRunning = false;
}
},
};

View File

@ -3,6 +3,13 @@
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../lib/query_condition_parser');
/** 出站推送失败自动重推:默认失败时间窗(毫秒)——超窗口的消息不再补推,避免陈旧消息打扰用户 */
const DEFAULT_PUSH_RETRY_WINDOW_MS = 2 * 60 * 60 * 1000;
/** 出站推送失败自动重推:默认单轮最多重推条数(定时任务每 3 分钟扫一次) */
const DEFAULT_PUSH_RETRY_LIMIT = 20;
/** 出站推送失败自动重推:单轮条数硬上限 */
const MAX_PUSH_RETRY_LIMIT = 200;
/**
* 站内信消息查询/管理服务。
* 提供消息列表、详情、对话链、回复、统计等管理功能。
@ -402,7 +409,8 @@ class InboxMessageService extends Service {
/**
* 手动重推失败(push_status=3)的站内信消息。
* 重置为待推送状态(push_status=0)并触发异步推送。
* 重置为待推送状态(push_status=0)并触发异步推送;
* 推送结果回写到同一记录(复用原记录,不新建回执记录)。
* @param {Object} params 重推参数。
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {number} params.id 消息ID。
@ -439,28 +447,9 @@ class InboxMessageService extends Service {
{ where: { id } }
);
// 回执记录 ext_id 形如 sys:ack:{原消息ext_id},反解出原消息 ext_id 以复用推送链路
const extId = String(record.ext_id || '');
const originalExtId = extId.startsWith('sys:ack:') ? extId.slice(8) : extId;
const hasUser = Boolean(record.user_id && record.user_name);
const pushData = {
warehouse_id: warehouseId,
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,
};
// 触发异步推送
// 触发异步推送(复用原记录回写推送结果)
setImmediate(() => {
ctx.service.inbox.processor.writeOutboundReply(
pushData,
record.content || '',
hasUser ? 'ai_reply' : 'system'
).catch(async err => {
this._repush(record).catch(async err => {
ctx.logger.error(`[inbox] 手动重推异步推送异常 id=${id}: ${err.message}`);
// 推送前校验失败时回写失败状态,避免消息卡在待推送
try {
@ -481,6 +470,124 @@ class InboxMessageService extends Service {
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');
}
/**
* 批量重推「推送失败」的出站消息(供定时任务调用)。
*
* 规则:
* 1. 只处理失败时间(created_at)在窗口内的记录,默认 2 小时;超窗口不再补推;
* 2. 逐条串行重推并等待结果回写,单条异常不影响其余记录;
* 3. 重推期间记录保持失败状态,进程中断时下一轮仍能被扫到(不丢消息);
* 4. 缺少 warehouse_id / group_id / group_name / content 的记录无法重放,跳过并计数。
*
* @param {Object} [params] 查询参数。
* @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 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)));
// 先补早失败的消息(更快接近 2 小时窗口边界)
const rows = await InboxMessage.findAll({
where: {
direction: 'outbound',
push_status: 3,
created_at: { [Op.gte]: new Date(Date.now() - windowMs) },
},
attributes: [
'id', 'warehouse_id', 'ext_id', 'parent_id',
'group_id', 'group_name', 'user_id', 'user_name',
'ext_data', 'content',
],
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) {
if (!(Number(row.warehouse_id) > 0) || !row.group_id || !row.group_name || !row.content) {
summary.skipped++;
ctx.logger.warn(`[inbox] 自动重推跳过消息 id=${row.id}(缺少 warehouse_id/group_id/group_name/content,无法重放)`);
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;
}
}
module.exports = InboxMessageService;

View File

@ -465,10 +465,13 @@ class InboxProcessorService extends Service {
* @param {string} data.user_id 用户ID(必填)。
* @param {string} data.group_name 群名称(必填)。
* @param {string} data.user_name 用户名称(必填)。
* @param {number} [data.reuse_message_id] 复用已有消息记录作为推送记录(重推场景):
* 传入时跳过按 `sys:ack:{ext_id}` 查建,直接把推送结果回写到该记录;
* 不传(0)时保持原行为(按 ext_id 幂等查建回执记录)。
* @param {string} replyContent 回复内容。
* @param {string} [source='ai_reply'] 回调 source 类型:ai_reply / bind_confirm / balance / error / system。
* system 类型不要求 user_id/user_name。
* @return {Promise<void>}
* @return {Promise<void>} 无返回值,推送结果回写到消息记录(push_status 2/3)。
*/
async writeOutboundReply(data, replyContent, source = 'ai_reply') {
const { ctx } = this;
@ -478,6 +481,7 @@ class InboxProcessorService extends Service {
const extId = String(data.ext_id || '');
const parentId = Number(data.parent_id || 0);
const isSystem = source === 'system';
const reuseMessageId = Number(data.reuse_message_id || 0);
// 强制入参校验(system 类型不要求 user_id/user_name)
const groupId = String(data.group_id || ctx.inboxContext?.group_id || '').trim();
@ -506,28 +510,33 @@ class InboxProcessorService extends Service {
const ackExtId = `sys:ack:${extId}`;
const callbackConfig = await this.getApiAppCallbackConfig(warehouseId);
// 重推(reuse_message_id>0):直接复用原记录,避免按 sys:ack: 前缀另建一条记录——
// 那样会让原记录(如 sys:notice:* 系统通知)状态永远停留在失败/待推送,且每次重推都新建记录
// 声明在 try 之外:异常兜底回写失败状态时仍需定位到该记录
let outboundId = reuseMessageId > 0 ? reuseMessageId : 0;
try {
let outboundId = null;
const existAck = await InboxMessage.findOne({
where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false,
});
if (existAck) {
outboundId = existAck.id;
} else {
const created = await InboxMessage.create({
ext_id: ackExtId, warehouse_id: warehouseId,
store_id: Number(data.store_id) || ctx.inboxContext?.store_id || null,
direction: 'outbound', parent_id: parentId || null,
source_type: 'system', source_extra: null,
target_type: 'api',
group_id: groupId,
user_id: isSystem ? null : userId,
group_name: groupName,
user_name: isSystem ? null : userName,
content: replyContent,
ext_data: outboundExtData, flags: {},
if (!outboundId) {
const existAck = await InboxMessage.findOne({
where: { ext_id: ackExtId }, attributes: [ 'id' ], paranoid: false,
});
outboundId = created.id;
if (existAck) {
outboundId = existAck.id;
} else {
const created = await InboxMessage.create({
ext_id: ackExtId, warehouse_id: warehouseId,
store_id: Number(data.store_id) || ctx.inboxContext?.store_id || null,
direction: 'outbound', parent_id: parentId || null,
source_type: 'system', source_extra: null,
target_type: 'api',
group_id: groupId,
user_id: isSystem ? null : userId,
group_name: groupName,
user_name: isSystem ? null : userName,
content: replyContent,
ext_data: outboundExtData, flags: {},
});
outboundId = created.id;
}
}
const callbackUrl = callbackConfig.url;
@ -596,7 +605,7 @@ class InboxProcessorService extends Service {
push_response: { http_status: curlResult.status, body: curlResult.data || null },
pushed_at: ctx.app.Sequelize.literal('CURRENT_TIMESTAMP'),
},
{ where: { ext_id: ackExtId } }
{ where: { id: outboundId } }
);
// 同步更新原入站消息的推送状态
@ -620,7 +629,7 @@ class InboxProcessorService extends Service {
error: curlResult ? '回调返回非200或code非200' : '回调无响应',
},
},
{ where: { ext_id: ackExtId } }
{ where: { id: outboundId } }
);
}
} else {
@ -630,7 +639,7 @@ class InboxProcessorService extends Service {
push_status: 3,
push_response: { error: '未配置回调地址(wms_api_app.callback_url为空)' },
},
{ where: { ext_id: ackExtId } }
{ where: { id: outboundId } }
);
ctx.logger.info(`[inbox processor] 仓库 ${warehouseId} 未配置回调地址,回写失败状态 ext_id=${extId}`);
}
@ -641,7 +650,7 @@ class InboxProcessorService extends Service {
try {
await InboxMessage.update(
{ push_status: 3, push_response: { error: error.message } },
{ where: { ext_id: ackExtId } }
{ where: { id: outboundId } }
);
} catch (updateErr) {
ctx.logger.error('[inbox processor] 更新推送状态失败: ' + updateErr.message);

View File

@ -66,6 +66,10 @@ module.exports = appInfo => {
videoRecordNotifyLimit: 10,
// 视频补录结果通知:超时阈值(毫秒),超过仍无录像则按超时回信并终止,避免长期占用扫描窗口
videoRecordNotifyTimeoutMs: 60 * 60 * 1000,
// 出站推送失败自动重推:失败时间窗(毫秒),仅重推窗口内失败的消息(默认 2 小时),超窗口不再补推
pushRetryWindowMs: 2 * 60 * 60 * 1000,
// 出站推送失败自动重推:单轮最多重推条数(定时任务每 3 分钟扫一次)
pushRetryLimit: 20,
};
config.tencentCloud = {