diff --git a/app/model/video_record_request.js b/app/model/video_record_request.js new file mode 100644 index 0000000..a1b523a --- /dev/null +++ b/app/model/video_record_request.js @@ -0,0 +1,155 @@ +'use strict'; + +/** + * 视频补录请求记录表模型(wms_video_record_request)。 + * + * 站内信查询打包视频 / 退件拆包视频时发现"视频不可用"(无视频记录或全部 failed), + * 登记一条补录请求(状态机 pending → requested → recording → completed / failed), + * 同时向录制服务推送强制录制;后续查询命中可用视频时由业务层回写 completed + video_url。 + * + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, INTEGER, STRING, DATE, ENUM, TINYINT } = app.Sequelize; + + const VideoRecordRequest = app.model.define('video_record_request', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID,0=未知', + }, + biz_type: { + type: ENUM('pack', 'unpack'), + allowNull: false, + comment: '业务类型:pack-打包视频 unpack-退件拆包视频', + }, + biz_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '业务ID:pack=wms_pack_task.id,unpack=wms_return_unpack.id', + }, + waybill_code: { + type: STRING(64), + allowNull: true, + comment: '触发查询的运单号', + }, + group_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群ID(站内信外部群ID,回信必填)', + }, + group_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的群名称', + }, + user_id: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户ID(站内信外部用户ID,回信必填)', + }, + user_name: { + type: STRING(100), + allowNull: true, + comment: '触发查询的用户名称', + }, + source: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '触发来源:inbox-站内信查询', + }, + status: { + type: ENUM('pending', 'requested', 'recording', 'completed', 'failed'), + allowNull: false, + defaultValue: 'pending', + comment: '状态机:pending-待推送 requested-已推送 recording-录制中 completed-已完成 failed-失败', + }, + request_count: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '推送录制服务次数', + }, + last_request_at: { + type: DATE, + allowNull: true, + comment: '最近一次请求录制服务时间(含推送失败)', + }, + print_computer_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '录制电脑ID,关联 wms_print_computer.id', + }, + request_error: { + type: STRING(500), + allowNull: true, + comment: '推送失败原因(无录制电脑/电脑不在线/打印服务异常)', + }, + video_url: { + type: STRING(500), + allowNull: true, + comment: '录制完成后回写的视频地址', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '录制结果是否已通知查询方:0=未通知,1=已通知', + }, + notified_at: { + type: DATE, + allowNull: true, + comment: '录制结果通知时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_video_record_request', + comment: '视频补录请求记录表', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + indexes: [ + { name: 'idx_warehouse_biz', fields: [ 'warehouse_id', 'biz_type', 'biz_id' ] }, + { name: 'idx_waybill_code', fields: [ 'waybill_code' ] }, + { name: 'idx_status_notified_last_request', fields: [ 'status', 'is_notified', 'last_request_at' ] }, + { name: 'idx_deleted_at', fields: [ 'deleted_at' ] }, + ], + }); + + return VideoRecordRequest; +}; diff --git a/app/schedule/notify_video_record_result.js b/app/schedule/notify_video_record_result.js new file mode 100644 index 0000000..f5cfb0d --- /dev/null +++ b/app/schedule/notify_video_record_result.js @@ -0,0 +1,60 @@ +'use strict'; + +/** + * 视频补录状态收敛 + 结果通知定时任务。 + * + * 每分钟在单 worker 中串行执行两段: + * 1) settleStatuses:把「在途且未通知」的补录请求收敛为终态 + * (视频已产出 → completed;录制服务失败 / 超过超时阈值 → failed),只改状态不通知; + * 2) notifyResults:扫「终态且未通知」的记录回信到触发查询的群 + * (有用户信息时定向回原用户),成功后标记 is_notified=1;失败记录额外转仓库客服群人工处理。 + * + * 单轮处理条数由 config.inbox.videoRecordNotifyLimit 控制(默认 10), + * 超时阈值由 config.inbox.videoRecordNotifyTimeoutMs 控制(默认 1 小时)。 + */ +module.exports = { + schedule: { + interval: '1m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行视频补录状态收敛与结果通知。 + * + * 两段串行,顺序不可颠倒: + * 1) settleStatuses:只把在途记录收敛为终态(completed / failed),不通知; + * 2) notifyResults:扫「终态且未通知」的记录回信(成功复用原查询链路文案,失败转人工)。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._videoRecordNotifyRunning) { + return; + } + + ctx.app._videoRecordNotifyRunning = true; + + try { + const settle = await ctx.service.systems.videoRecordRequest.settleStatuses(); + const result = await ctx.service.systems.videoRecordRequest.notifyResults(); + const settleChanged = settle + && (settle.completed > 0 || settle.failed > 0 || settle.timeout > 0 || settle.invalid > 0); + if (settleChanged || (result && (result.notified > 0 || result.skipped > 0))) { + ctx.logger.info( + `[notify-video-record] 本轮完成 settle(scanned=${settle && settle.scanned} completed=${settle && settle.completed} ` + + `failed=${settle && settle.failed} timeout=${settle && settle.timeout} invalid=${settle && settle.invalid}) ` + + `notify(scanned=${result && result.scanned} notified=${result && result.notified} ` + + `completed=${result && result.completed} failed=${result && result.failed} ` + + `timeout=${result && result.timeout} skipped=${result && result.skipped})` + ); + } + } catch (error) { + ctx.logger.error(`[notify-video-record] 任务执行失败: ${error.message}`); + } finally { + ctx.app._videoRecordNotifyRunning = false; + } + }, +}; diff --git a/app/service/inbox/functions.js b/app/service/inbox/functions.js index 80734d4..9313658 100644 --- a/app/service/inbox/functions.js +++ b/app/service/inbox/functions.js @@ -1600,14 +1600,49 @@ class InboxFunctionsService extends Service { } lines.push(''); lines.push('退件录像地址为:'); + const unpackId = Number(unpack.id || 0); if (videos.length > 0) { for (const video of videos) { if (video.video_url) lines.push(String(video.video_url)); } + lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询'); + // 视频已可用:推进补录请求状态为 completed(回写视频地址) + if (unpackId > 0) { + try { + await ctx.service.systems.videoRecordRequest.syncByVideos({ + biz_type: 'unpack', + biz_id: unpackId, + videos, + }); + } catch (err) { + ctx.logger.warn(`[inbox functions] 拆包视频补录状态同步失败 unpack=${unpackId}: ${err.message}`); + } + } + } else if (unpackId > 0) { + // 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询) + let inFlight = false; + try { + const req = await ctx.service.systems.videoRecordRequest.requestUnpackVideo({ + warehouse_id: warehouseId, + unpack_id: unpackId, + waybill_code: waybill, + store_id: Number(unpack.store_id || 0), + group_id: String(ctx.inboxContext?.group_id || '').trim(), + group_name: String(ctx.inboxContext?.group_name || '').trim(), + user_id: String(ctx.inboxContext?.user_id || '').trim(), + user_name: String(ctx.inboxContext?.user_name || '').trim(), + source: 'inbox', + }); + inFlight = Boolean(req && (req.pushed || (req.reused && req.status !== 'failed'))); + } catch (err) { + ctx.logger.warn(`[inbox functions] 拆包视频补录推送失败 unpack=${unpackId}: ${err.message}`); + } + lines.push(inFlight + ? '视频暂不可用,已推送重新录制,请稍等通知录制结果' + : '视频暂不可用,已登记补录,请稍后重试'); } else { lines.push('暂无'); } - lines.push('拆包视频保存会有延迟,可以在稍后发送:查退回+运单号,查询'); message = lines.join('\n'); } else if (result.status === 'received') { message = `包裹${waybill}已收到未拆包,拆包登记后,将自动发送通知拆包信息`; @@ -3080,7 +3115,7 @@ class InboxFunctionsService extends Service { }); this.register('queryPackVideo', { - description: '打包视频查询。传入运单号,查询该运单对应的打包视频:散单按订单查打包记录,团购单按波次查打包记录。有视频返回视频地址;有打包记录无视频提示稍后再试;无打包记录提示无打包记录。仅查询,不创建工单', + description: '打包视频查询。传入运单号,查询该运单对应的打包视频:散单按订单查打包记录,团购单按波次查打包记录。有视频返回视频地址;视频不可用时自动登记补录请求并向录制服务推送强制录制(回复“视频暂不可用,已推送重新录制,请稍等通知录制结果”,推送失败则“视频暂不可用,已登记补录,请稍后重试”);无打包记录提示无打包记录。仅查询,不创建工单', weight: 86, keywords: [ '打包视频', '打包录像', '装箱视频', '打包监控', '录像' ], params: { @@ -3093,6 +3128,11 @@ class InboxFunctionsService extends Service { const storeId = Number(ctx.inboxContext?.store_id || 0); const warehouseId = Number(ctx.inboxContext?.warehouse_id || 0); const groupType = String(ctx.inboxContext?.group_type || '').trim(); + // 触发查询的群/人员:写入补录请求,供后续录制结果回发原群、@原用户 + const inboxGroupId = String(ctx.inboxContext?.group_id || '').trim(); + const inboxGroupName = String(ctx.inboxContext?.group_name || '').trim(); + const inboxUserId = String(ctx.inboxContext?.user_id || '').trim(); + const inboxUserName = String(ctx.inboxContext?.user_name || '').trim(); if (!raw) return { success: false, error: '请提供运单号' }; if (!warehouseId) return { success: false, error: '无法获取仓库信息' }; @@ -3146,9 +3186,11 @@ class InboxFunctionsService extends Service { } const videoLines = []; - const noVideoWbs = []; const noRecordWbs = []; const orderMissingWbs = []; + // 视频不可用已推送重新录制 / 仅登记补录(推送失败) + const reRecordWbs = []; + const reRecordFailedWbs = []; for (const e of validList) { // 第二步:查订单行(优先序列表定位,未命中回退 当前→历史→配送 遍历) @@ -3239,9 +3281,45 @@ class InboxFunctionsService extends Service { .filter(Boolean); if (urls.length === 0) { - noVideoWbs.push(e.waybill_code); + // 视频不可用:登记补录请求并推送录制服务重新录制(录制服务不可用时仅登记,不阻断查询) + let inFlight = 0; + for (const task of packTasks) { + try { + const req = await ctx.service.systems.videoRecordRequest.requestPackVideo({ + warehouse_id: warehouseId, + pack_task_id: task.id, + waybill_code: e.waybill_code, + store_id: Number(e.store_id || 0), + group_id: inboxGroupId, + group_name: inboxGroupName, + user_id: inboxUserId, + user_name: inboxUserName, + source: 'inbox', + }); + if (req && (req.pushed || (req.reused && req.status !== 'failed'))) inFlight += 1; + } catch (err) { + ctx.logger.warn(`[inbox functions] 打包视频补录推送失败 task=${task.id}: ${err.message}`); + } + } + if (inFlight > 0) { + reRecordWbs.push(e.waybill_code); + } else { + reRecordFailedWbs.push(e.waybill_code); + } } else { videoLines.push(`${e.waybill_code}\n${urls.join('\n')}`); + // 视频已可用:推进补录请求状态为 completed(回写视频地址) + for (const task of packTasks) { + try { + await ctx.service.systems.videoRecordRequest.syncByVideos({ + biz_type: 'pack', + biz_id: task.id, + videos, + }); + } catch (err) { + ctx.logger.warn(`[inbox functions] 打包视频补录状态同步失败 task=${task.id}: ${err.message}`); + } + } } } @@ -3250,9 +3328,13 @@ class InboxFunctionsService extends Service { if (videoLines.length > 0) { lines.push(videoLines.join('\n')); } - if (noVideoWbs.length > 0) { - lines.push(noVideoWbs.join('\n')); - lines.push('打包视频可能还未保存,请稍后再试'); + if (reRecordWbs.length > 0) { + lines.push(reRecordWbs.join('\n')); + lines.push('视频暂不可用,已推送重新录制,请稍等通知录制结果'); + } + if (reRecordFailedWbs.length > 0) { + lines.push(reRecordFailedWbs.join('\n')); + lines.push('视频暂不可用,已登记补录,请稍后重试'); } if (noRecordWbs.length > 0) { lines.push(noRecordWbs.join('\n')); @@ -3270,14 +3352,17 @@ class InboxFunctionsService extends Service { ctx.logger.info( `[inbox functions] 打包视频查询: total=${keywords.length} found=${validList.length} ` + - `video=${videoLines.length} noVideo=${noVideoWbs.length} noRecord=${noRecordWbs.length}` + `video=${videoLines.length} reRecord=${reRecordWbs.length} reRecordFailed=${reRecordFailedWbs.length} ` + + `noRecord=${noRecordWbs.length}` ); return { success: true, data: { has_video: videoLines.length, - no_video: noVideoWbs.length, + no_video: reRecordWbs.length + reRecordFailedWbs.length, + re_record: reRecordWbs.length, + re_record_failed: reRecordFailedWbs.length, no_record: noRecordWbs.length, message: lines.join('\n'), direct_reply: true, diff --git a/app/service/systems/video_record_request.js b/app/service/systems/video_record_request.js new file mode 100644 index 0000000..b8d588c --- /dev/null +++ b/app/service/systems/video_record_request.js @@ -0,0 +1,826 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 业务类型:打包视频 */ +const BIZ_TYPE_PACK = 'pack'; +/** 业务类型:退件拆包视频 */ +const BIZ_TYPE_UNPACK = 'unpack'; + +/** + * 补录请求状态机。 + * pending(待推送) → requested(已推送) → recording(录制中) → completed(已完成) / failed(失败) + */ +const STATUS = Object.freeze({ + PENDING: 'pending', + REQUESTED: 'requested', + RECORDING: 'recording', + COMPLETED: 'completed', + FAILED: 'failed', +}); + +/** 在途状态(此状态内的请求不重复推送) */ +const ACTIVE_STATUSES = Object.freeze([ STATUS.PENDING, STATUS.REQUESTED, STATUS.RECORDING ]); + +/** 终态状态(已由 settleStatuses 收敛,等待 notifyResults 回信) */ +const TERMINAL_STATUSES = Object.freeze([ STATUS.COMPLETED, STATUS.FAILED ]); + +/** 超时失败原因前缀:settleStatuses 写入,notifyResults 据此区分回信文案 */ +const TIMEOUT_ERROR_PREFIX = '重新录制超时'; + +/** 幂等复用窗口:窗口内同一业务对象重复查询只复用已有请求,不重复推送(默认 10 分钟) */ +const REUSE_WINDOW_MS = 10 * 60 * 1000; + +/** 推送失败原因字段最大长度 */ +const ERROR_MAX_LENGTH = 500; + +/** + * 转人工通知的目标群:仓库群的客服群(warehouse/customer_service)。 + * 取值需与 app/service/inbox/groups.js 中 warehouse 的 subTypes 一致。 + */ +const MANUAL_HANDLING_SUB_TYPE = 'customer_service'; + +/** + * 视频补录请求服务层。 + * + * 场景:站内信查询"打包视频 / 退件拆包视频"时若视频不可用(无视频记录或全部 failed), + * 由本服务登记补录请求(状态机落库 wms_video_record_request)并向录制服务推送强制录制, + * 推送口径与 order.packing.forceRecord / returnUnpack.forceRecord 完全一致: + * 查录制电脑(wms_print_computer is_recording=true)→ 校验 Redis 在线键 → + * 重置视频记录为 created → POST {printService.url}/record/force。 + */ +class VideoRecordRequestService extends Service { + + /** + * 查询仓库的录制电脑(wms_print_computer is_recording=true)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 录制电脑行,找不到返回 null。 + */ + async _getRecordingComputer(warehouseId) { + const { ctx } = this; + const row = await ctx.model.PrintComputer.findOne({ + where: { warehouse_id: warehouseId, is_recording: true, deleted_at: null }, + attributes: [ 'id', 'name', 'warehouse_id' ], + raw: true, + }); + return row || null; + } + + /** + * 校验录制电脑是否在线(与 forceRecord 相同的 Redis 在线键)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} computerId 录制电脑ID。 + * @return {Promise} 是否在线。 + */ + async _isComputerOnline(warehouseId, computerId) { + const { ctx } = this; + try { + const redisPrinter = ctx.app.redis.get('printer'); + const onlineInfo = await redisPrinter.get(`warehouse:${warehouseId}:printer:${computerId}`); + return Boolean(onlineInfo); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 录制电脑在线校验失败 wh=${warehouseId} cid=${computerId}: ${err.message}`); + return false; + } + } + + /** + * 重置视频记录为 created 并清空 video_url(与 forceRecord 同口径,触发重新录制)。 + * + * @param {string} bizType 业务类型 pack/unpack。 + * @param {number} bizId 业务ID(pack_task_id / unpack_id)。 + * @return {Promise} + */ + async _resetVideoRecords(bizType, bizId) { + const { ctx } = this; + if (bizType === BIZ_TYPE_UNPACK) { + await ctx.model.ReturnUnpackVideo.update( + { status: 'created', video_url: '' }, + { where: { unpack_id: bizId, deleted_at: null } } + ); + return; + } + await ctx.model.PackTaskVideo.update( + { status: 'created', video_url: '' }, + { where: { pack_task_id: bizId, deleted_at: null } } + ); + } + + /** + * 判断已有请求是否处于幂等复用窗口内。 + * + * @param {Object} row 请求记录行。 + * @return {boolean} true=窗口内(不重复推送)。 + */ + _withinReuseWindow(row) { + const base = row.last_request_at || row.updated_at; + if (!base) return false; + return Date.now() - new Date(base).getTime() < REUSE_WINDOW_MS; + } + + /** + * 标记请求推送失败(无录制电脑 / 电脑不在线 / 打印服务异常)。 + * + * @param {Object} params 参数。 + * @param {number} params.requestId 请求记录ID。 + * @param {string} params.error 失败原因。 + * @param {number|null} [params.computerId] 录制电脑ID。 + * @return {Promise} 统一的请求结果对象。 + */ + async _markFailed({ requestId, error, computerId = null }) { + const { ctx } = this; + const message = String(error || '推送强制录制失败').slice(0, ERROR_MAX_LENGTH); + await ctx.model.VideoRecordRequest.update( + { + status: STATUS.FAILED, + request_error: message, + print_computer_id: computerId, + last_request_at: new Date(), + remark: '视频不可用,推送强制录制失败', + }, + { where: { id: requestId } } + ); + return { request_id: requestId, status: STATUS.FAILED, pushed: false, reused: false, error: message }; + } + + /** + * 打包任务视频补录请求。 + * + * @param {Object} params 参数。 + * @param {number} params.warehouse_id 仓库ID。 + * @param {number} params.pack_task_id 打包任务ID(wms_pack_task.id)。 + * @param {string} [params.waybill_code] 触发查询的运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.group_id] 触发查询的群ID。 + * @param {string} [params.group_name] 触发查询的群名称。 + * @param {string} [params.user_id] 触发查询的用户ID。 + * @param {string} [params.user_name] 触发查询的用户名称。 + * @param {string} [params.source] 触发来源。 + * @return {Promise} { request_id, status, pushed, reused, error }。 + */ + async requestPackVideo({ warehouse_id, pack_task_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) { + return this.requestFor({ + biz_type: BIZ_TYPE_PACK, + biz_id: pack_task_id, + warehouse_id, + waybill_code, + store_id, + group_id, + group_name, + user_id, + user_name, + source, + }); + } + + /** + * 退件拆包视频补录请求。 + * + * @param {Object} params 参数。 + * @param {number} params.warehouse_id 仓库ID。 + * @param {number} params.unpack_id 拆包单ID(wms_return_unpack.id)。 + * @param {string} [params.waybill_code] 触发查询的运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.group_id] 触发查询的群ID。 + * @param {string} [params.group_name] 触发查询的群名称。 + * @param {string} [params.user_id] 触发查询的用户ID。 + * @param {string} [params.user_name] 触发查询的用户名称。 + * @param {string} [params.source] 触发来源。 + * @return {Promise} { request_id, status, pushed, reused, error }。 + */ + async requestUnpackVideo({ warehouse_id, unpack_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) { + return this.requestFor({ + biz_type: BIZ_TYPE_UNPACK, + biz_id: unpack_id, + warehouse_id, + waybill_code, + store_id, + group_id, + group_name, + user_id, + user_name, + source, + }); + } + + /** + * 通用补录请求:登记请求记录(状态机起点 pending)→ 推送录制服务 → 推进状态。 + * + * 幂等:同一仓库 + 业务对象在复用窗口内已有在途(pending/requested/recording)请求时直接复用, + * 不重复推送;超窗口或上次 failed 时复活同一条记录重新推送(避免同一业务对象堆积多条记录)。 + * + * @param {Object} params 参数。 + * @param {string} params.biz_type 业务类型 pack/unpack。 + * @param {number} params.biz_id 业务ID。 + * @param {number} params.warehouse_id 仓库ID。 + * @param {string} [params.waybill_code] 触发查询的运单号。 + * @param {number} [params.store_id] 货主ID。 + * @param {string} [params.group_id] 触发查询的群ID。 + * @param {string} [params.group_name] 触发查询的群名称。 + * @param {string} [params.user_id] 触发查询的用户ID。 + * @param {string} [params.user_name] 触发查询的用户名称。 + * @param {string} [params.source] 触发来源。 + * @return {Promise} { request_id, status, pushed, reused, error }。 + */ + async requestFor({ biz_type, biz_id, warehouse_id, waybill_code = '', store_id = 0, group_id = '', group_name = '', user_id = '', user_name = '', source = 'inbox' } = {}) { + const { ctx } = this; + + const bizType = biz_type === BIZ_TYPE_UNPACK ? BIZ_TYPE_UNPACK : BIZ_TYPE_PACK; + const bizId = Number(biz_id || 0); + const warehouseId = Number(warehouse_id || 0); + if (!bizId || !warehouseId) { + return { request_id: null, status: null, pushed: false, reused: false, error: '缺少业务ID或仓库上下文' }; + } + + // 触发查询的群/人员(供后续录制结果回发原群、@原用户) + const groupId = String(group_id || '').slice(0, 100); + const groupName = String(group_name || '').slice(0, 100); + const userId = String(user_id || '').slice(0, 100); + const userName = String(user_name || '').slice(0, 100); + + // 1. 幂等:查该业务对象最近一条请求记录 + const latest = await ctx.model.VideoRecordRequest.findOne({ + where: { warehouse_id: warehouseId, biz_type: bizType, biz_id: bizId, deleted_at: null }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + + if (latest && latest.status !== STATUS.COMPLETED && this._withinReuseWindow(latest)) { + return { + request_id: latest.id, + status: latest.status, + pushed: false, + reused: true, + error: latest.request_error || null, + }; + } + + // 2. 写入请求记录(状态机起点 pending);已有未完成记录则复活复用 + let requestId = latest && latest.status !== STATUS.COMPLETED ? latest.id : null; + if (requestId) { + await ctx.model.VideoRecordRequest.update( + { + status: STATUS.PENDING, + store_id: Number(store_id || 0) || Number(latest.store_id || 0), + waybill_code: String(waybill_code || '') || latest.waybill_code, + group_id: groupId || latest.group_id, + group_name: groupName || latest.group_name, + user_id: userId || latest.user_id, + user_name: userName || latest.user_name, + source: source || latest.source, + print_computer_id: null, + request_error: null, + remark: '视频不可用,重新发起补录', + }, + { where: { id: requestId } } + ); + } else { + const created = await ctx.model.VideoRecordRequest.create({ + warehouse_id: warehouseId, + store_id: Number(store_id || 0), + biz_type: bizType, + biz_id: bizId, + waybill_code: String(waybill_code || ''), + group_id: groupId || null, + group_name: groupName || null, + user_id: userId || null, + user_name: userName || null, + source: source || 'inbox', + status: STATUS.PENDING, + request_count: 0, + remark: '视频不可用,自动发起补录', + }); + requestId = created && created.id; + } + + // 3. 录制电脑存在性 + 在线校验(不满足写入 failed,不阻断业务查询) + const computer = await this._getRecordingComputer(warehouseId); + if (!computer) { + return { ...(await this._markFailed({ requestId, error: '该仓库无录制电脑,无法推送重新录制' })), biz_type: bizType, biz_id: bizId }; + } + const online = await this._isComputerOnline(warehouseId, computer.id); + if (!online) { + return { + ...(await this._markFailed({ requestId, error: '录制电脑不在线,无法推送重新录制', computerId: computer.id })), + biz_type: bizType, + biz_id: bizId, + }; + } + + // 4. 重置视频记录为 created(与 forceRecord 一致) + try { + await this._resetVideoRecords(bizType, bizId); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 重置视频记录失败 biz=${bizType}:${bizId}: ${err.message}`); + } + + // 5. 推送录制服务(打印服务 /record/force) + const printServiceUrl = ctx.app.config.printService.url; + const requestData = bizType === BIZ_TYPE_UNPACK ? { unpack_id: bizId } : { pack_task_id: bizId }; + try { + const res = await ctx.curl(`${printServiceUrl}/record/force`, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: 10000, + }); + if (res.status >= 400) { + return { + ...(await this._markFailed({ requestId, error: `录制服务返回 ${res.status}`, computerId: computer.id })), + biz_type: bizType, + biz_id: bizId, + }; + } + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 推送强制录制失败 biz=${bizType}:${bizId}: ${err.message}`); + return { + ...(await this._markFailed({ requestId, error: `通知录制服务失败: ${err.message}`, computerId: computer.id })), + biz_type: bizType, + biz_id: bizId, + }; + } + + // 6. 推送成功 → 状态推进为 requested(request_count 自增) + await ctx.model.VideoRecordRequest.update( + { + status: STATUS.REQUESTED, + request_count: ctx.app.Sequelize.literal('request_count + 1'), + last_request_at: new Date(), + print_computer_id: computer.id, + request_error: null, + remark: '视频不可用,已推送重新录制', + }, + { where: { id: requestId } } + ); + + ctx.logger.info(`[videoRecordRequest] 已推送重新录制 biz=${bizType}:${bizId} wh=${warehouseId} cid=${computer.id}`); + + return { request_id: requestId, status: STATUS.REQUESTED, pushed: true, reused: false, error: null, biz_type: bizType, biz_id: bizId }; + } + + /** + * 依据视频记录推进请求状态(查询命中视频时调用)。 + * + * 规则:有可用视频(video_url 非空且非 failed)→ completed; + * 有录制中记录 → recording;全部 failed → failed;其余保持不变。 + * + * 结果以视频原表为准,不回写 video_url(同一业务对象可能存在多路视频)。 + * + * @param {Object} params 参数。 + * @param {string} params.biz_type 业务类型 pack/unpack。 + * @param {number} params.biz_id 业务ID。 + * @param {Array} params.videos 视频记录数组(含 video_url/status)。 + * @return {Promise} { status, changed },无在途请求时返回 null。 + */ + async syncByVideos({ biz_type, biz_id, videos } = {}) { + const { ctx } = this; + const bizType = biz_type === BIZ_TYPE_UNPACK ? BIZ_TYPE_UNPACK : BIZ_TYPE_PACK; + const bizId = Number(biz_id || 0); + if (!bizId) return null; + + const list = Array.isArray(videos) ? videos.filter(Boolean) : []; + const { Op } = ctx.app.Sequelize; + + const row = await ctx.model.VideoRecordRequest.findOne({ + where: { + biz_type: bizType, + biz_id: bizId, + status: { [Op.in]: ACTIVE_STATUSES }, + deleted_at: null, + }, + order: [[ 'id', 'DESC' ]], + raw: true, + }); + if (!row) return null; + + const available = list.find(v => v.video_url && v.status !== 'failed'); + let target = null; + if (available) target = STATUS.COMPLETED; + else if (list.some(v => v.status === 'recording')) target = STATUS.RECORDING; + else if (list.length > 0 && list.every(v => v.status === 'failed')) target = STATUS.FAILED; + + if (!target || target === row.status) return { status: row.status, changed: false }; + + const updates = { status: target }; + await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } }); + + return { status: target, changed: true }; + } + + /** + * 状态收敛:把「在途」的补录请求推进为终态(completed / failed),不做任何通知。 + * + * 定时任务的第一步(先收敛状态、再统一通知),与通知步骤解耦: + * - 有可用视频且无仍在录制(或已超时)→ completed(超时窗口内仍缺摄像头时先交付已有的); + * - 视频记录全部 failed → failed(录制服务返回失败); + * - 超过 timeoutMs 仍无可用视频 → failed(超时); + * - 其余(仍在录制中且未超时)→ 本轮不动,等下一轮; + * - 记录缺少 warehouse_id / biz_id(永远无法处理)→ failed,避免每分钟占用扫描窗口。 + * + * 说明:一个打包任务 / 拆包单可能对应多路摄像头视频(多条 wms_*_video 记录), + * 因此以视频原表为准:有可用视频即算成功,权威视频列表由查询链路输出(见 notifyResults)。 + * + * @param {Object} [options] 参数。 + * @param {number} [options.limit] 单轮处理条数上限,默认取 config.inbox.videoRecordNotifyLimit(10)。 + * @param {number} [options.timeoutMs] 超时阈值(毫秒),默认取 config.inbox.videoRecordNotifyTimeoutMs(1 小时)。 + * @return {Promise} { scanned, completed, failed, timeout, invalid, skipped }。 + */ + async settleStatuses(options = {}) { + const { ctx } = this; + const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {}; + const limit = Math.max(1, Number(options.limit) || Number(inboxConfig.videoRecordNotifyLimit) || 10); + const timeoutMs = Math.max( + 0, + Number(options.timeoutMs) || Number(inboxConfig.videoRecordNotifyTimeoutMs) || 60 * 60 * 1000 + ); + const { Op } = ctx.app.Sequelize; + + const rows = await ctx.model.VideoRecordRequest.findAll({ + where: { + status: { [Op.in]: ACTIVE_STATUSES }, + is_notified: 0, + deleted_at: null, + }, + // last_request_at 是组合索引 idx_status_notified_last_request 的第三列,按它排序可避免 filesort + order: [[ 'last_request_at', 'ASC' ], [ 'id', 'ASC' ]], + limit, + raw: true, + }); + + const stat = { scanned: rows.length, completed: 0, failed: 0, timeout: 0, invalid: 0, skipped: 0 }; + + for (const row of rows) { + try { + const warehouseId = Number(row.warehouse_id || 0); + const bizId = Number(row.biz_id || 0); + if (!warehouseId || !bizId) { + // 关键字段缺失 → 永远无法处理,直接收敛为失败,避免每分钟占用扫描窗口 + await ctx.model.VideoRecordRequest.update( + { status: STATUS.FAILED, request_error: '记录缺少仓库/业务对象,无法处理' }, + { where: { id: row.id } } + ); + stat.invalid += 1; + continue; + } + + // 1. 读视频记录(打包/拆包分表) + const videos = row.biz_type === BIZ_TYPE_UNPACK + ? await ctx.model.ReturnUnpackVideo.findAll({ + attributes: [ 'id', 'video_url', 'status' ], + where: { unpack_id: bizId, deleted_at: null }, + raw: true, + }) + : await ctx.model.PackTaskVideo.findAll({ + attributes: [ 'id', 'video_url', 'status' ], + where: { pack_task_id: bizId, deleted_at: null }, + raw: true, + }); + const list = Array.isArray(videos) ? videos : []; + const statusOf = v => String(v.status || ''); + // 多路视频:需"有可用视频 且 无仍在录制",避免只出一路就误判完成 + const hasAvailable = list.some(v => v.video_url && statusOf(v) !== 'failed'); + const hasRecording = list.some(v => statusOf(v) === 'recording'); + const allFailed = list.length > 0 && list.every(v => statusOf(v) === 'failed'); + + // 2. 超时判定(以最近一次请求时间为准) + const base = row.last_request_at || row.updated_at || row.created_at; + const ageMs = base ? Date.now() - new Date(base).getTime() : 0; + const timedOut = timeoutMs > 0 && ageMs >= timeoutMs; + + let updates = null; + if (hasAvailable && (!hasRecording || timedOut)) { + updates = { + status: STATUS.COMPLETED, + request_error: hasRecording ? '部分摄像头仍在录制,已先交付可用视频' : null, + }; + stat.completed += 1; + } else if (allFailed) { + updates = { status: STATUS.FAILED, request_error: '录制服务返回失败' }; + stat.failed += 1; + } else if (timedOut) { + updates = { + status: STATUS.FAILED, + request_error: `${TIMEOUT_ERROR_PREFIX}(${Math.round(timeoutMs / 60000)} 分钟)未产出视频`, + }; + stat.timeout += 1; + } else { + // 仍在录制中且未超时:等下一轮 + stat.skipped += 1; + continue; + } + + await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } }); + ctx.logger.info( + `[videoRecordRequest] 补录状态收敛 id=${row.id} biz=${row.biz_type}:${bizId} status=${updates.status}` + ); + } catch (err) { + stat.skipped += 1; + ctx.logger.warn(`[videoRecordRequest] 补录状态收敛失败 id=${row.id}: ${err.message}`); + } + } + + return stat; + } + + /** + * 补录结果通知:扫描「已收敛为终态且未通知」的补录请求,回信到原群(失败时转人工)。 + * + * 前置条件:状态已由 settleStatuses 收敛为 completed / failed; + * 本方法不再读视频表、也不再做超时判定,只负责取文案 + 回信 + 转人工。 + * + * 处理规则(每轮最多 limit 条,按 last_request_at 升序): + * - status=completed → 复用「原查询链路」文案(queryPackVideo / queryReturn 的输出, + * 含全部视频地址与拆包明细)回信;取不到文案时不标记,下一轮重试; + * - status=failed → 回「已转人工处理」,同时向仓库群的客服群推人工处理通知; + * - 无群信息 → 仍标记 is_notified=1(remark 说明)避免卡死扫描窗口; + * - 回信抛错 → 不标记,下一轮重试。 + * + * 回信对象优先用记录里存下的群/人员(writeOutboundReply 定向回原用户); + * 缺少用户信息时退化为群系统通知(pushSystemNotification)。 + * + * @param {Object} [options] 参数。 + * @param {number} [options.limit] 单轮处理条数上限,默认取 config.inbox.videoRecordNotifyLimit(10)。 + * @return {Promise} { scanned, notified, completed, failed, timeout, skipped }。 + */ + async notifyResults(options = {}) { + const { ctx } = this; + const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {}; + const limit = Math.max(1, Number(options.limit) || Number(inboxConfig.videoRecordNotifyLimit) || 10); + const { Op } = ctx.app.Sequelize; + + const rows = await ctx.model.VideoRecordRequest.findAll({ + where: { + status: { [Op.in]: TERMINAL_STATUSES }, + is_notified: 0, + deleted_at: null, + }, + // last_request_at 是组合索引 idx_status_notified_last_request 的第三列,按它排序可避免 filesort + order: [[ 'last_request_at', 'ASC' ], [ 'id', 'ASC' ]], + limit, + raw: true, + }); + + const stat = { scanned: rows.length, notified: 0, completed: 0, failed: 0, timeout: 0, skipped: 0 }; + + for (const row of rows) { + try { + const waybill = row.waybill_code || '-'; + let content = null; + // 非空表示本条需转人工(failed),由仓库群的客服群邀请真人接手 + let manualReason = null; + + if (row.status === STATUS.COMPLETED) { + // 录制成功:按「原查询链路」取结果文案,与用户自己发一次查询看到的完全一致 + const message = await this._buildResultMessage(row); + if (!message) { + // 取不到结果文案:本轮不标记,下一轮重试 + stat.skipped += 1; + continue; + } + content = message; + stat.completed += 1; + } else { + const isTimeout = String(row.request_error || '').startsWith(TIMEOUT_ERROR_PREFIX); + content = `【视频补录${isTimeout ? '超时' : '失败'}】\n运单号:${waybill}\n已转人工处理,请稍后留意群内回复`; + manualReason = row.request_error || '录制服务返回失败'; + if (isTimeout) stat.timeout += 1; + stat.failed += 1; + } + + // 回信到原群(失败时不标记,下一轮重试;无群信息时标记避免卡住扫描窗口) + const updates = { is_notified: 1, notified_at: new Date() }; + const sent = await this._replyResult(row, content); + if (sent) { + if (manualReason) updates.remark = '已转人工处理'; + await ctx.model.VideoRecordRequest.update(updates, { where: { id: row.id } }); + stat.notified += 1; + ctx.logger.info( + `[videoRecordRequest] 补录结果已通知 id=${row.id} biz=${row.biz_type}:${row.biz_id} status=${row.status}` + ); + // 失败/超时:额外邀请仓库客服群真人接手 + if (manualReason) { + await this._notifyManualHandling(row, manualReason); + } + } else { + await ctx.model.VideoRecordRequest.update( + { ...updates, remark: '无群信息,未推送通知' }, + { where: { id: row.id } } + ); + stat.skipped += 1; + ctx.logger.warn(`[videoRecordRequest] 补录结果无群信息未通知 id=${row.id} waybill=${waybill}`); + } + } catch (err) { + stat.skipped += 1; + ctx.logger.warn(`[videoRecordRequest] 补录结果通知处理失败 id=${row.id}: ${err.message}`); + } + } + + return stat; + } + + /** + * 复用「原查询链路」取结果文案(录制成功后回原链路取值)。 + * + * - 打包:调 inbox.functions `queryPackVideo(keyword=运单号)`,与用户发“打包视频+运单号”同一条链路; + * - 拆包:调 inbox.functions `queryReturn(waybill_code=运单号)`,与用户发“查退回+运单号”同一条链路。 + * + * 这两个函数是站内信函数注册表里的原实现,因此输出(含多路视频地址、拆包明细等)与用户主动查询完全一致; + * 由于可用性/货主鉴权依赖 inboxContext,这里按补录记录里存的群/人员临时还原上下文,用后恢复。 + * + * @param {Object} row 补录请求记录。 + * @return {Promise} 查询链路产出的模板文案,取不到时返回 null。 + */ + async _buildResultMessage(row) { + const { ctx } = this; + const waybill = String(row.waybill_code || '').trim(); + if (!waybill) return null; + + const functionsSvc = ctx.service.inbox && ctx.service.inbox.functions; + if (!functionsSvc || typeof functionsSvc.callFunction !== 'function') { + ctx.logger.warn('[videoRecordRequest] inbox.functions 不可用,无法按原查询链路取结果'); + return null; + } + + const warehouseId = Number(row.warehouse_id || 0); + const groupId = String(row.group_id || '').trim(); + let groupRow = null; + if (groupId) { + try { + groupRow = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_id', 'group_name', 'group_type', 'sub_type' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 查群信息失败 group=${groupId}: ${err.message}`); + } + } + + const prevContext = ctx.inboxContext; + ctx.inboxContext = { + warehouse_id: warehouseId, + store_id: Number(row.store_id || 0) || null, + group_id: groupId || null, + group_name: String(row.group_name || '').trim() || (groupRow && groupRow.group_name) || null, + user_id: String(row.user_id || '').trim() || null, + user_name: String(row.user_name || '').trim() || null, + group_type: (groupRow && groupRow.group_type) || null, + sub_type: (groupRow && groupRow.sub_type) || null, + }; + + try { + const result = row.biz_type === BIZ_TYPE_UNPACK + ? await functionsSvc.callFunction('queryReturn', { waybill_code: waybill }) + : await functionsSvc.callFunction('queryPackVideo', { keyword: waybill }); + if (!result || result.success === false) { + ctx.logger.warn( + `[videoRecordRequest] 原查询链路取结果失败 waybill=${waybill}: ${(result && result.error) || 'unknown'}` + ); + return null; + } + const message = result.data && result.data.message ? String(result.data.message).trim() : ''; + return message || null; + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 原查询链路取结果异常 waybill=${waybill}: ${err.message}`); + return null; + } finally { + ctx.inboxContext = prevContext; + } + } + + /** + * 失败/超时转人工:向仓库群的客服群推系统通知,邀请真人接手。 + * + * 群范围:wms_inbox_group 中同仓库 `group_type='warehouse'` 且 `sub_type='customer_service'`(客服) + * 的未屏蔽群;未命中时不外发,仅记 warn 日志(不退化发送到其他仓库群,避免误扰)。 + * + * @param {Object} row 补录请求记录。 + * @param {string} reason 需人工处理的原因(录制失败 / 超时)。 + * @return {Promise} 已通知的内部群数量。 + */ + async _notifyManualHandling(row, reason) { + const { ctx } = this; + const warehouseId = Number(row.warehouse_id || 0); + const processor = ctx.service.inbox && ctx.service.inbox.processor; + if (!warehouseId || !processor || typeof processor.pushSystemNotification !== 'function') return 0; + + let groups = []; + try { + groups = await ctx.model.InboxGroup.findAll({ + attributes: [ 'group_id', 'group_name', 'sub_type', 'ext_data' ], + where: { + warehouse_id: warehouseId, + group_type: 'warehouse', + sub_type: MANUAL_HANDLING_SUB_TYPE, + is_blocked: 0, + }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 查仓库客服群失败 wh=${warehouseId}: ${err.message}`); + return 0; + } + + if (!Array.isArray(groups) || groups.length === 0) { + ctx.logger.warn( + `[videoRecordRequest] 仓库 ${warehouseId} 未配置客服群(warehouse/${MANUAL_HANDLING_SUB_TYPE}),转人工通知未发出 waybill=${row.waybill_code || '-'}` + ); + return 0; + } + + const bizLabel = row.biz_type === BIZ_TYPE_UNPACK ? '退件拆包视频' : '打包视频'; + const content = [ + '【视频补录需人工处理】', + `运单号:${row.waybill_code || '-'}`, + `类型:${bizLabel}`, + `仓库:${warehouseId}`, + `原因:${reason || '录制未成功'}`, + '请核实录制电脑/摄像头后人工处理,并回原群同步结果', + ].join('\n'); + + let notified = 0; + for (const g of groups) { + if (!g || !g.group_id) continue; + processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: g.group_id, + group_name: g.group_name, + content, + ext_data: g.ext_data || null, + store_id: null, + }); + notified += 1; + } + + ctx.logger.info( + `[videoRecordRequest] 已邀请人工处理 waybill=${row.waybill_code || '-'} groups=${notified} reason=${reason}` + ); + return notified; + } + + /** + * 把补录结果回信到原群。 + * + * 有用户信息时走 writeOutboundReply(定向回原用户);否则退化到 pushSystemNotification(群提醒)。 + * 群名与渠道扩展信息优先从 wms_inbox_group 现查,缺失时用补录记录里的快照值。 + * + * @param {Object} row 补录请求记录。 + * @param {string} content 回信内容。 + * @return {Promise} 是否已发起回信(无群信息时返回 false)。 + */ + async _replyResult(row, content) { + const { ctx } = this; + const warehouseId = Number(row.warehouse_id || 0); + const groupId = String(row.group_id || '').trim(); + const processor = ctx.service.inbox && ctx.service.inbox.processor; + if (!groupId || !processor) return false; + + let groupRow = null; + try { + groupRow = await ctx.model.InboxGroup.findOne({ + attributes: [ 'group_id', 'group_name', 'store_id', 'ext_data' ], + where: { group_id: groupId, warehouse_id: warehouseId }, + raw: true, + }); + } catch (err) { + ctx.logger.warn(`[videoRecordRequest] 查询群信息失败 group=${groupId}: ${err.message}`); + } + + const groupName = String(row.group_name || (groupRow && groupRow.group_name) || '').trim(); + if (!groupName) return false; + + const storeId = Number(row.store_id || 0) || Number(groupRow && groupRow.store_id) || null; + const extData = (groupRow && groupRow.ext_data) || null; + const userId = String(row.user_id || '').trim(); + const userName = String(row.user_name || '').trim(); + + if (userId && userName && typeof processor.writeOutboundReply === 'function') { + await processor.writeOutboundReply({ + warehouse_id: warehouseId, + group_id: groupId, + group_name: groupName, + user_id: userId, + user_name: userName, + store_id: storeId, + ext_data: extData, + ext_id: `video:record:${row.id}`, + }, content, 'ai_reply'); + return true; + } + + processor.pushSystemNotification({ + warehouse_id: warehouseId, + group_id: groupId, + group_name: groupName, + content, + ext_data: extData, + store_id: storeId, + }); + return true; + } +} + +module.exports = VideoRecordRequestService; diff --git a/config/config.default.js b/config/config.default.js index e4e6ec6..e5740ee 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -62,6 +62,10 @@ module.exports = appInfo => { aiFallback: false, // 退回收件登记聚合通知防抖窗口(毫秒):等该时长无新登记后合并推送,默认 5 分钟 returnReceivedNotifyDelayMs: 5 * 60 * 1000, + // 视频补录结果通知:单轮处理条数上限(定时任务每 1 分钟扫一次) + videoRecordNotifyLimit: 10, + // 视频补录结果通知:超时阈值(毫秒),超过仍无录像则按超时回信并终止,避免长期占用扫描窗口 + videoRecordNotifyTimeoutMs: 60 * 60 * 1000, }; config.tencentCloud = { @@ -251,6 +255,12 @@ module.exports = appInfo => { }; // 打印自定义区模板出口域名 config.customAreaBaseUrl = 'https://api.ye4s.com'; + // 仓库前端独立部署:证书部署目录。 + // 保存接口(setting.warehouse.saveFrontCert)已不再写暂存文件,证书/私钥内容直接入库; + // 该目录保留供未来定时任务(Egg schedule 或外部 crontab)从库内 cert_pem/cert_key 读取内容后写 nginx 证书目录使用。 + config.frontConfig = { + certStagingDir: '/data/wms/cert-staging', + }; return { ...config, diff --git a/database/migrations/20260910100000-create-wms-video-record-request.js b/database/migrations/20260910100000-create-wms-video-record-request.js new file mode 100644 index 0000000..3c44f3f --- /dev/null +++ b/database/migrations/20260910100000-create-wms-video-record-request.js @@ -0,0 +1,127 @@ +'use strict'; + +/** + * 创建视频补录请求记录表 wms_video_record_request。 + * + * 背景:站内信查询"打包视频/退件拆包视频"时若视频不可用(无视频记录或全部 failed), + * 除回复用户外还需登记一条补录请求并推送录制服务重新录制,本表用于记录请求与状态机。 + * + * 状态机:pending(待推送) → requested(已推送) → recording(录制中) → completed(已完成) / failed(失败) + * + * 字段:仓库/货主隔离、业务对象(biz_type=pack/unpack + biz_id)、运单号、状态、推送次数、 + * 录制电脑、失败原因、回写视频地址、结果通知标记、备注、软删除 deleted_at(paranoid)。 + * + * 索引:idx_warehouse_biz(按业务对象查在途请求)、idx_waybill_code(按单号追溯)、 + * idx_status(按状态筛选)、idx_deleted_at(软删除优化)。 + */ + +const TABLE_NAME = 'wms_video_record_request'; + +module.exports = { + // eslint-disable-next-line no-unused-vars + async up(queryInterface, Sequelize) { + const { BIGINT, INTEGER, STRING, DATE, ENUM, TINYINT } = Sequelize; + await queryInterface.createTable(TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '货主ID,0=未知', + }, + biz_type: { + type: ENUM('pack', 'unpack'), + allowNull: false, + comment: '业务类型:pack-打包视频 unpack-退件拆包视频', + }, + biz_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '业务ID:pack=wms_pack_task.id,unpack=wms_return_unpack.id', + }, + waybill_code: { + type: STRING(64), + allowNull: true, + comment: '触发查询的运单号', + }, + source: { + type: STRING(20), + allowNull: false, + defaultValue: 'inbox', + comment: '触发来源:inbox-站内信查询', + }, + status: { + type: ENUM('pending', 'requested', 'recording', 'completed', 'failed'), + allowNull: false, + defaultValue: 'pending', + comment: '状态机:pending-待推送 requested-已推送 recording-录制中 completed-已完成 failed-失败', + }, + request_count: { + type: INTEGER.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '推送录制服务次数', + }, + last_request_at: { + type: DATE, + allowNull: true, + comment: '最近一次请求录制服务时间(含推送失败)', + }, + print_computer_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '录制电脑ID,关联 wms_print_computer.id', + }, + request_error: { + type: STRING(500), + allowNull: true, + comment: '推送失败原因(无录制电脑/电脑不在线/打印服务异常)', + }, + video_url: { + type: STRING(500), + allowNull: true, + comment: '录制完成后回写的视频地址', + }, + is_notified: { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '录制结果是否已通知查询方:0=未通知,1=已通知', + }, + notified_at: { + type: DATE, + allowNull: true, + comment: '录制结果通知时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + deleted_at: { type: DATE, allowNull: true, comment: '软删除时间' }, + }); + + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'biz_type', 'biz_id' ], { name: 'idx_warehouse_biz' }); + await queryInterface.addIndex(TABLE_NAME, [ 'waybill_code' ], { name: 'idx_waybill_code' }); + await queryInterface.addIndex(TABLE_NAME, [ 'status' ], { name: 'idx_status' }); + await queryInterface.addIndex(TABLE_NAME, [ 'deleted_at' ], { name: 'idx_deleted_at' }); + }, + + // eslint-disable-next-line no-unused-vars + async down(queryInterface, Sequelize) { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260911100000-add-inbox-fields-to-wms-video-record-request.js b/database/migrations/20260911100000-add-inbox-fields-to-wms-video-record-request.js new file mode 100644 index 0000000..6f13a61 --- /dev/null +++ b/database/migrations/20260911100000-add-inbox-fields-to-wms-video-record-request.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * 视频补录请求表新增「查询来源」字段:触发查询的站内信群与人员。 + * + * 背景:站内信查询打包/拆包视频命中"视频不可用"时写入补录请求, + * 此前只记录了仓库/货主/业务对象,缺少「是谁在哪个群问的」, + * 导致后续「录制结果通知」无法回发到原群并 @ 原用户。 + * + * 新增字段(均可空,兼容历史数据): + * - group_id / group_name:触发查询的群(回信必填) + * - user_id / user_name :触发查询的用户(回信必填,system 场景可空) + * + * 幂等:逐列 describeTable 判断后再 ADD,可重复执行。 + */ + +const TABLE = 'wms_video_record_request'; + +module.exports = { + /** + * 新增群/人员来源字段。 + * + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @param {Object} Sequelize Sequelize 类。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + const columns = await queryInterface.describeTable(TABLE); + + const additions = [ + [ 'group_id', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的群ID(站内信外部群ID,回信必填)' }], + [ 'group_name', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的群名称' }], + [ 'user_id', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的用户ID(站内信外部用户ID,回信必填)' }], + [ 'user_name', { type: Sequelize.STRING(100), allowNull: true, comment: '触发查询的用户名称' }], + ]; + + for (const [ name, definition ] of additions) { + if (!columns[name]) { + await queryInterface.addColumn(TABLE, name, definition); + } + } + }, + + /** + * 回滚:移除群/人员来源字段。 + * + * @param {Object} queryInterface Sequelize QueryInterface 实例。 + * @return {Promise} 无返回值。 + */ + down: async queryInterface => { + const columns = await queryInterface.describeTable(TABLE); + for (const name of [ 'group_id', 'group_name', 'user_id', 'user_name' ]) { + if (columns[name]) { + await queryInterface.removeColumn(TABLE, name); + } + } + }, +}; diff --git a/database/migrations/20260911120000-update-wms-video-record-request-notify-index.js b/database/migrations/20260911120000-update-wms-video-record-request-notify-index.js new file mode 100644 index 0000000..382f2cf --- /dev/null +++ b/database/migrations/20260911120000-update-wms-video-record-request-notify-index.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * 调整视频补录请求表(wms_video_record_request)的定时扫描索引。 + * + * 背景:结果通知定时任务(app/schedule/notify_video_record_result.js,每分钟一次) + * 的取数条件是「在途 + 未通知」: + * + * WHERE status IN ('pending','requested','recording') + * AND is_notified = 0 + * AND deleted_at IS NULL + * ORDER BY id ASC LIMIT 10 + * + * 单列 idx_status 只能命中 status 一层,随后还要回表按 is_notified 过滤; + * 后续若按「超时」维度拆查询,还会用到 last_request_at 范围条件。 + * + * 因此: + * - 新增 idx_status_notified_last_request (status, is_notified, last_request_at) + * - 移除冗余的 idx_status(新索引以 status 为最左前缀,可覆盖原查询场景) + * + * 幂等:先 showIndex 判断存在性再增删,可重复执行。 + */ + +const TABLE_NAME = 'wms_video_record_request'; + +const OLD_INDEX = 'idx_status'; +const NEW_INDEX = 'idx_status_notified_last_request'; + +/** + * 获取指定表的索引名集合。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise>} 索引名集合。 + */ +const getIndexNameSet = async queryInterface => { + const indexes = await queryInterface.showIndex(TABLE_NAME); + return new Set( + (Array.isArray(indexes) ? indexes : []) + .map(index => String(index && index.name ? index.name : '').trim()) + .filter(Boolean) + ); +}; + +module.exports = { + /** + * 执行迁移:新增覆盖扫描条件的组合索引,并移除冗余单列索引。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async up(queryInterface) { + const indexNameSet = await getIndexNameSet(queryInterface); + + if (!indexNameSet.has(NEW_INDEX)) { + await queryInterface.addIndex(TABLE_NAME, { + name: NEW_INDEX, + fields: [ 'status', 'is_notified', 'last_request_at' ], + }); + } + + if (indexNameSet.has(OLD_INDEX)) { + await queryInterface.removeIndex(TABLE_NAME, OLD_INDEX); + } + }, + + /** + * 回滚迁移:恢复单列 idx_status,移除组合索引。 + * + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @return {Promise} 无返回值。 + */ + async down(queryInterface) { + const indexNameSet = await getIndexNameSet(queryInterface); + + if (indexNameSet.has(NEW_INDEX)) { + await queryInterface.removeIndex(TABLE_NAME, NEW_INDEX); + } + + if (!indexNameSet.has(OLD_INDEX)) { + await queryInterface.addIndex(TABLE_NAME, { + name: OLD_INDEX, + fields: [ 'status' ], + }); + } + }, +};