diff --git a/AI_METHOD_ROUTING.md b/AI_METHOD_ROUTING.md index ff632f6..1e75eff 100644 --- a/AI_METHOD_ROUTING.md +++ b/AI_METHOD_ROUTING.md @@ -282,10 +282,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods - 临时清单输出:temp/tmp-service-method-inventory.md -自动生成时间: 2026-09-15T12:58:24.457Z +自动生成时间: 2026-09-15T15:22:29.464Z 扫描范围: app/service/**/*.js -文件数: 211 +文件数: 212 - app/service/api.js (1) - callMethod @@ -613,6 +613,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods - qimenClient, send, sendRequest - app/service/systems/receiving_entry_match.js (29) - matchAfterEntryCompleted, _bindEntryOrderReceiving, bindEntryOrderReceiving, _bindReceivingsWithStorageSync, _bindOneReceivingAndSyncStorage, max, _syncReceivingStorageByEntryItems, _parseLedgerMap, _serializeLedgerMap, min, _buildLegacyBaselineLedger, _bindingAllocationByStock, _recalcReceivingStorageStatus, _reconcileEntryReceivedQuantity, recordLedgerAllocation, setLedgerAllocation, rollbackEntryOrderBindings, _rollbackOneBindingStorage, _getRecentReceivingOrders, _findReceivingByRemark, _compareDetails, _queryEntryOrderLines, buildEntryOrderConfirmRequest, _sendCallback, _sendQimenCallback, _sendOpenApiCallback, _markReceivingPartialStorage, _commitBinding, unbindEntryOrderReceiving +- app/service/systems/receiving_pending_notice.js (14) + - getWarehouseNoticeConfigs, findPendingReceivings, groupByStore, buildRowLine, formatDateOnly, buildTemplateVariables, buildContent, resolveNoticeSendMethod, sendPendingNotice, notifyWarehouse, getRedisClient, acquireDailyLock, releaseDailyLock, execute - app/service/systems/report.js (17) - getDefinition, parseFieldsField, definitionToView, resolveTypeEntry, resolveQuerier, listRegisteredTypes, validateTypeFields, resolveOrderedFields, Date, buildFilename, buildWorkbookSheets, generate, generateBuffer, saveDefinition, findDefinitionById, listDefinitions, deleteDefinition - app/service/systems/report/queries/index.js (0) @@ -739,6 +741,12 @@ rg "class .*Service|module.exports" app/service/qimenMethods + + + + + + diff --git a/app/lib/ptz_client.js b/app/lib/ptz_client.js new file mode 100644 index 0000000..1bede20 --- /dev/null +++ b/app/lib/ptz_client.js @@ -0,0 +1,325 @@ +'use strict'; + +/** + * PTZ(云台控制)客户端模块。 + * 负责组装 RTSP URL 并调用打印服务的云台端点下发控制指令。 + * 与 `lib/osd_client.js` 同风格:独立端点 + 独立请求体,**不带 computerId** + * (打印服务按 rtspUrl 定位摄像头,无需房间路由)。 + * + * 端点与请求体(warehouse_id 为字符串、cameraId 为摄像头ID,与 setOSD 口径一致): + * - /camera/ptzControl :按下(按方向持续转动),松手时必须配对调用 stop + * { warehouse_id, cameraId, rtspUrl, action, speed } + * - /camera/ptzStop :松手(停止转动),action 必须与按下时一致 + * { warehouse_id, cameraId, rtspUrl, action } + * - /camera/ptzPresetGoto :跳转预置点,一次调用即可,无需 stop + * { warehouse_id, cameraId, rtspUrl, presetId } + * - /camera/ptzPresetSet :设置预置点(把当前机位存为指定编号),一次调用即可 + * { warehouse_id, cameraId, rtspUrl, presetId } + * + * 使用方式: + * const PtzClient = require('../lib/ptz_client'); + * const ptzClient = new PtzClient(ctx); + * await ptzClient.control({ camera, warehouseId, action, speed }); + */ + +/** 打印服务云台端点路径 */ +const PTZ_PATH = { + CONTROL: '/camera/ptzControl', + STOP: '/camera/ptzStop', + PRESET_GOTO: '/camera/ptzPresetGoto', + PRESET_SET: '/camera/ptzPresetSet', +}; + +/** 云台方向枚举(与打印服务约定的 8 个位置,顺序固定) */ +const PTZ_ACTION_LIST = [ + { value: 'up', name: '上' }, + { value: 'down', name: '下' }, + { value: 'left', name: '左' }, + { value: 'right', name: '右' }, + { value: 'upleft', name: '左上' }, + { value: 'upright', name: '右上' }, + { value: 'downleft', name: '左下' }, + { value: 'downright', name: '右下' }, +]; + +/** 云台方向值列表 */ +const PTZ_ACTIONS = PTZ_ACTION_LIST.map(item => item.value); + +/** 默认转速 */ +const PTZ_DEFAULT_SPEED = 4; +/** 转速下限 */ +const PTZ_MIN_SPEED = 1; +/** 转速上限 */ +const PTZ_MAX_SPEED = 7; +/** 预置点编号下限 */ +const PTZ_MIN_PRESET_ID = 1; +/** 预置点编号上限 */ +const PTZ_MAX_PRESET_ID = 256; +/** 打印服务请求超时(毫秒) */ +const PTZ_REQUEST_TIMEOUT = 10000; + +class PtzClient { + constructor(ctx) { + this.ctx = ctx; + this.logger = ctx.logger || console; + } + + /** + * 云台方向枚举(供文档/校验共用)。 + * @return {Array} [{ value, name }] + */ + static getActionList() { + return PTZ_ACTION_LIST.map(item => ({ ...item })); + } + + /** + * 组装摄像头 RTSP 地址。 + * 与 `lib/osd_client.js#buildRtspUrl` 保持同口径(打印服务以该地址定位摄像头)。 + * + * @param {Object} camera - 摄像头记录(含 ip/username/password/channel_id) + * @return {string} RTSP URL + */ + buildRtspUrl(camera) { + const ip = camera && camera.ip; + if (!ip) { + throw new Error('摄像头未配置IP地址,无法组装RTSP地址'); + } + + const username = camera.username || 'admin'; + const password = camera.password || ''; + const channelId = camera.channel_id; + const rtspPort = 554; + + return `rtsp://${username}:${password}@${ip}:${rtspPort}/stream${channelId}`; + } + + /** + * 校验并归一化云台方向。 + * + * @param {string} action - 云台方向 + * @param {string} [label] - 报错文案中的字段名 + * @return {string} 归一化后的方向值 + */ + static normalizeAction(action, label = '云台方向') { + const value = String(action === undefined || action === null ? '' : action).trim().toLowerCase(); + if (!value) throw new Error(`${label}不能为空`); + if (!PTZ_ACTIONS.includes(value)) { + throw new Error(`${label}不合法,仅支持:${PTZ_ACTIONS.join('/')}`); + } + return value; + } + + /** + * 校验并归一化云台转速(缺省 4)。 + * + * @param {number|string} speed - 转速 + * @return {number} 归一化后的转速 + */ + static normalizeSpeed(speed) { + if (speed === undefined || speed === null || speed === '') return PTZ_DEFAULT_SPEED; + const value = Number(speed); + if (!Number.isInteger(value) || value < PTZ_MIN_SPEED || value > PTZ_MAX_SPEED) { + throw new Error(`云台转速需为 ${PTZ_MIN_SPEED}-${PTZ_MAX_SPEED} 的整数`); + } + return value; + } + + /** + * 校验并归一化预置点编号。 + * + * @param {number|string} presetId - 预置点编号 + * @return {number} 归一化后的预置点编号 + */ + static normalizePresetId(presetId) { + if (presetId === undefined || presetId === null || presetId === '') { + throw new Error('预置点编号不能为空'); + } + const value = Number(presetId); + if (!Number.isInteger(value) || value < PTZ_MIN_PRESET_ID || value > PTZ_MAX_PRESET_ID) { + throw new Error(`预置点编号需为 ${PTZ_MIN_PRESET_ID}-${PTZ_MAX_PRESET_ID} 的整数`); + } + return value; + } + + /** + * 下发云台指令到打印服务(独立端点,与 setOSD 同风格,不带 computerId)。 + * 请求体统一携带 warehouse_id(字符串)与 cameraId(摄像头ID)。 + * + * @param {Object} options - 指令参数 + * @param {Object} options.camera - 摄像头记录(取 id 作为 cameraId,并用于日志) + * @param {string} options.path - 打印服务端点路径 + * @param {number} options.warehouseId - 仓库ID + * @param {Object} options.data - 请求体业务字段 + * @return {Promise} { success, error, response, request } + */ + async _send(options = {}) { + const { ctx } = this; + const { camera, path: targetPath, warehouseId, data } = options; + + if (!targetPath) throw new Error('打印服务端点路径不能为空'); + if (!camera) throw new Error('摄像头信息不能为空'); + + const warehouseValue = Number(warehouseId); + if (!Number.isInteger(warehouseValue) || warehouseValue <= 0) { + throw new Error('仓库ID不合法'); + } + const cameraValue = Number(camera.id); + if (!Number.isInteger(cameraValue) || cameraValue <= 0) { + throw new Error('摄像头ID不合法'); + } + + const printServiceUrl = ctx.app.config.printService.url; + const targetUrl = `${printServiceUrl}${targetPath}`; + const requestData = { + warehouse_id: String(warehouseValue), + cameraId: cameraValue, + ...data, + }; + + ctx.logger.info('[PTZ] 发送云台指令', { url: targetUrl, body: requestData }); + + let response = null; + let error = null; + try { + const res = await ctx.curl(targetUrl, { + method: 'POST', + contentType: 'json', + data: requestData, + dataType: 'json', + timeout: PTZ_REQUEST_TIMEOUT, + }); + response = { + status: res.status, + headers: res.headers, + data: res.data, + }; + ctx.logger.info('[PTZ] 打印服务回信', { status: res.status, data: res.data }); + } catch (err) { + error = err.message; + ctx.logger.warn('[PTZ] 打印服务请求失败', { + camera_id: camera && camera.id, + url: targetUrl, + error: err.message, + }); + } + + const httpOk = !!response && response.status >= 200 && response.status < 300; + const body = response && response.data; + if (!error && httpOk && body && typeof body === 'object' + && (body.status === 'fail' || body.success === false)) { + error = body.message || body.error || '打印服务返回失败'; + } + + return { + success: !error && httpOk, + error, + response, + request: requestData, + }; + } + + /** + * 按下:按指定方向转动云台。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {string} options.action - 云台方向(up/down/left/right/upleft/upright/downleft/downright) + * @param {number} [options.speed] - 转速(1-7,默认 4) + * @return {Promise} 打印服务响应 + */ + async control(options = {}) { + const { camera, warehouseId, action, speed } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.CONTROL, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + action: PtzClient.normalizeAction(action), + speed: PtzClient.normalizeSpeed(speed), + }, + }); + } + + /** + * 松手:停止云台转动。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {string} options.action - 云台方向(必须与按下时一致) + * @return {Promise} 打印服务响应 + */ + async stop(options = {}) { + const { camera, warehouseId, action } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.STOP, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + action: PtzClient.normalizeAction(action), + }, + }); + } + + /** + * 跳转预置点(一次调用即可,无需 stop)。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {number|string} options.presetId - 预置点编号(1-256) + * @return {Promise} 打印服务响应 + */ + async presetGoto(options = {}) { + const { camera, warehouseId, presetId } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.PRESET_GOTO, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + presetId: PtzClient.normalizePresetId(presetId), + }, + }); + } + + /** + * 设置预置点:把摄像头当前机位保存为指定预置点编号(一次调用即可)。 + * + * @param {Object} options - 参数 + * @param {Object} options.camera - 摄像头记录 + * @param {number} options.warehouseId - 仓库ID + * @param {number|string} options.presetId - 预置点编号(1-256) + * @return {Promise} 打印服务响应 + */ + async presetSet(options = {}) { + const { camera, warehouseId, presetId } = options; + if (!camera) throw new Error('摄像头信息不能为空'); + + return await this._send({ + camera, + path: PTZ_PATH.PRESET_SET, + warehouseId, + data: { + rtspUrl: this.buildRtspUrl(camera), + presetId: PtzClient.normalizePresetId(presetId), + }, + }); + } +} + +module.exports = PtzClient; +module.exports.PTZ_PATH = PTZ_PATH; +module.exports.PTZ_ACTIONS = PTZ_ACTIONS; +module.exports.PTZ_DEFAULT_SPEED = PTZ_DEFAULT_SPEED; +module.exports.PTZ_MAX_SPEED = PTZ_MAX_SPEED; +module.exports.PTZ_MAX_PRESET_ID = PTZ_MAX_PRESET_ID; diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js index e49b41a..10f0967 100644 --- a/app/model/notification_webhook.js +++ b/app/model/notification_webhook.js @@ -43,6 +43,7 @@ module.exports = app => { Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }), Object.freeze({ code: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时的通知(展示车牌号/快递单号登记状态,未登记显示无)' }), Object.freeze({ code: 'receiving_store_unmatched', name: '收货完成未匹配商品提醒', business: 'receiving', description: '收货单完成时存在未匹配商品明细,通知货主核实商品资料' }), + Object.freeze({ code: 'receiving_pending_inbound', name: '收货未入库超时提醒', business: 'receiving', description: '定时扫描创建超时仍未完成入库的收货单:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群' }), Object.freeze({ code: 'entry_order_completed', name: '入库单完成入库', business: 'entry_order', description: '入库单完成入库后的通知,提示货主入库单已完成入库请注意查收' }), Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }), Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }), diff --git a/app/model/store.js b/app/model/store.js index 5a0538c..d387a87 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -45,6 +45,22 @@ module.exports = app => { const ALLOCATE_START_TIME_MIN = '00:00'; const ALLOCATE_START_TIME_MAX = '23:59'; + // 收货未入库提醒:默认关闭,开启后每天按 notice_time 扫描超时未入库的收货单 + const DEFAULT_PENDING_RECEIVING_NOTICE_TIME = '08:30'; + const DEFAULT_PENDING_RECEIVING_MIN_HOURS = 24; + const DEFAULT_PENDING_RECEIVING_MAX_HOURS = 48; + const PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH = 500; + const DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:'; + const DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:'; + const DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE = Object.freeze({ + enabled: false, + notice_time: DEFAULT_PENDING_RECEIVING_NOTICE_TIME, + min_hours: DEFAULT_PENDING_RECEIVING_MIN_HOURS, + max_hours: DEFAULT_PENDING_RECEIVING_MAX_HOURS, + notice_template: DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE, + store_notice_template: DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE, + }); + const DEFAULT_SUBJECT_CONFIG = Object.freeze({ max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, max_wave_quantity: DEFAULT_MAX_WAVE_QUANTITY, @@ -71,6 +87,7 @@ module.exports = app => { cutoff_order_enabled: 1, cutoff_order_time: DEFAULT_CUTOFF_ORDER_TIME, allocate_start_time: DEFAULT_ALLOCATE_START_TIME, + receiving_pending_inbound_notice: DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE, }); const normalizeSubjectConfigText = (value, defaultValue) => { @@ -185,6 +202,117 @@ module.exports = app => { }; }; + /** + * 规范化正整数字段(小于等于 0 或非整数时抛错)。 + * + * @param {*} value 原始值,空值返回默认值。 + * @param {number} defaultValue 默认值。 + * @param {string} fieldName 字段全名(用于报错)。 + * @return {number} 规范化后的正整数。 + */ + const normalizePositiveInteger = (value, defaultValue, fieldName) => { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + + const normalized = Number(value); + if (!Number.isInteger(normalized) || normalized <= 0) { + throw new Error(`${fieldName} 必须是大于 0 的整数`); + } + + return normalized; + }; + + /** + * 规范化通知短语:空值回退默认短语,非字符串转字符串,超长报错。 + * + * @param {*} value 原始短语。 + * @param {string} defaultValue 默认短语。 + * @param {string} fieldName 字段全名(用于报错)。 + * @return {string} 规范化后的短语。 + */ + const normalizeNoticeTemplateText = (value, defaultValue, fieldName) => { + if (value === undefined || value === null) { + return defaultValue; + } + + const normalized = String(value).trim(); + if (!normalized) { + return defaultValue; + } + + if (normalized.length > PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH) { + throw new Error(`${fieldName} 长度不能超过 ${PENDING_RECEIVING_NOTICE_TEMPLATE_MAX_LENGTH} 字符`); + } + + return normalized; + }; + + /** + * 规范化「收货未入库提醒」配置。 + * 字段:enabled(是否启用,默认否) / notice_time(提醒时间 HH:mm,默认 08:30) + * / min_hours(超时下限小时,默认 24) / max_hours(超时上限小时,默认 48) + * / notice_template(仓库客服群通知短语) / store_notice_template(货主群通知短语)。 + * 非法结构(非对象/非法 JSON)回退默认值;时间格式、小时数越界、短语超长抛错。 + * + * @param {Object|string|null|undefined} rawValue 原始配置。 + * @return {Object} 规范化后的配置对象。 + */ + const normalizeReceivingPendingInboundNotice = rawValue => { + if (rawValue === undefined || rawValue === null || rawValue === '') { + return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; + } + + let parsed = rawValue; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { ...DEFAULT_RECEIVING_PENDING_INBOUND_NOTICE }; + } + + const noticeTime = normalizeSubjectConfigText(parsed.notice_time, DEFAULT_PENDING_RECEIVING_NOTICE_TIME); + if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(noticeTime)) { + throw new Error('subject_config.receiving_pending_inbound_notice.notice_time 格式必须为 HH:mm(如 08:30)'); + } + + const minHours = normalizePositiveInteger( + parsed.min_hours, + DEFAULT_PENDING_RECEIVING_MIN_HOURS, + 'subject_config.receiving_pending_inbound_notice.min_hours' + ); + const maxHours = normalizePositiveInteger( + parsed.max_hours, + DEFAULT_PENDING_RECEIVING_MAX_HOURS, + 'subject_config.receiving_pending_inbound_notice.max_hours' + ); + if (minHours >= maxHours) { + throw new Error('subject_config.receiving_pending_inbound_notice.min_hours 必须小于 max_hours'); + } + + return { + enabled: normalizeBooleanFlag(parsed.enabled, 'subject_config.receiving_pending_inbound_notice.enabled') === true, + notice_time: noticeTime, + min_hours: minHours, + max_hours: maxHours, + notice_template: normalizeNoticeTemplateText( + parsed.notice_template, + DEFAULT_PENDING_RECEIVING_NOTICE_TEMPLATE, + 'subject_config.receiving_pending_inbound_notice.notice_template' + ), + store_notice_template: normalizeNoticeTemplateText( + parsed.store_notice_template, + DEFAULT_PENDING_RECEIVING_STORE_NOTICE_TEMPLATE, + 'subject_config.receiving_pending_inbound_notice.store_notice_template' + ), + }; + }; + /** * 规范化主体配置,确保默认值与字段约束一致。 * @@ -345,6 +473,9 @@ module.exports = app => { normalized.inventory_warning_rules = normalizeInventoryWarningRules(parsed.inventory_warning_rules); normalized.auto_outbound_rules = normalizeAutoOutboundRules(parsed.auto_outbound_rules); + normalized.receiving_pending_inbound_notice = normalizeReceivingPendingInboundNotice( + parsed.receiving_pending_inbound_notice + ); const rawDefaultLocationId = parsed.default_location_id; if (rawDefaultLocationId === undefined || rawDefaultLocationId === null || rawDefaultLocationId === '') { diff --git a/app/schedule/notice_receiving_pending_inbound.js b/app/schedule/notice_receiving_pending_inbound.js new file mode 100644 index 0000000..6bbccbe --- /dev/null +++ b/app/schedule/notice_receiving_pending_inbound.js @@ -0,0 +1,54 @@ +'use strict'; + +/** + * 收货未入库提醒定时任务。 + * + * 每 5 分钟在单 worker 中扫描一次:对仓库设置中开启「收货未入库提醒」 + * (`subject_config.receiving_pending_inbound_notice.enabled`)的仓库, + * 在到达其配置的提醒时间(notice_time,默认 08:30)时执行当日提醒。 + * + * - 超时区间同样来自仓库设置:创建时间超过 min_hours(默认 24)且不足 max_hours(默认 48) + * 仍未完成入库的收货单会被提醒;提醒时间与区间均可在仓库设置中调整。 + * - 绑定了货主的收货单通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群。 + * - 提醒时间匹配带 10 分钟宽限(覆盖调度抖动),并用「仓库 + 日期」当日锁保证一天只提醒一次; + * 执行异常会释放当日锁,宽限窗口内的下一轮会重试。 + */ +module.exports = { + schedule: { + interval: '5m', + type: 'worker', + immediate: false, + disable: false, + }, + + /** + * 执行收货未入库提醒扫描。 + * + * @param {Object} ctx Egg 上下文。 + * @return {Promise} 无返回值。 + */ + async task(ctx) { + if (ctx.app._receivingPendingNoticeRunning) { + return; + } + + ctx.app._receivingPendingNoticeRunning = true; + + try { + const summary = await ctx.service.systems.receivingPendingNotice.execute(); + + // 无仓库命中提醒时间时不刷日志,避免每 5 分钟噪音 + if (summary && summary.executedWarehouseCount > 0) { + ctx.logger.info( + `[receiving-pending-notice] 本轮提醒完成:开启仓库 ${summary.checkedWarehouseCount},` + + `执行 ${summary.executedWarehouseCount},未入库 ${summary.pendingCount} 单,` + + `发送 ${summary.sentCount},失败 ${summary.failedCount}` + ); + } + } catch (error) { + ctx.logger.error(`[receiving-pending-notice] 任务执行失败: ${error.message}`); + } finally { + ctx.app._receivingPendingNoticeRunning = false; + } + }, +}; diff --git a/app/service/systemMethods/camera.js b/app/service/systemMethods/camera.js index bd0aded..e4c25b8 100644 --- a/app/service/systemMethods/camera.js +++ b/app/service/systemMethods/camera.js @@ -6,9 +6,9 @@ class CameraService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,detail,setOsd'; + const _noNeedRight = 'list,detail,setOsd,ptzControl,ptzStop,ptzPresetGoto,ptzPresetSet'; const _noNeedLog = '*'; - const _noNeedAuth = 'list,detail,setOsd'; + const _noNeedAuth = 'list,detail,setOsd,ptzControl,ptzStop,ptzPresetGoto,ptzPresetSet'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -47,6 +47,62 @@ class CameraService extends MainService { } catch (e) { return this.fail(e.message); } } + /** + * 云台方向控制(按下) + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.computerId - 打印电脑ID(必填) + * @param {string} data.action - 云台方向(8 个位置,必填) + * @param {number} [data.speed] - 云台转速(1-7,默认 4) + * @return {Promise} 统一响应 + */ + async ptzControl(data) { + try { + return this.success('云台控制成功', await this.service.systems.camera.ptzControl(data)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 云台停止(松手) + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.computerId - 打印电脑ID(必填) + * @param {string} data.action - 云台方向(必须与按下时一致,必填) + * @return {Promise} 统一响应 + */ + async ptzStop(data) { + try { + return this.success('云台已停止', await this.service.systems.camera.ptzStop(data)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 云台预置点跳转 + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.computerId - 打印电脑ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 统一响应 + */ + async ptzPresetGoto(data) { + try { + return this.success('预置点跳转成功', await this.service.systems.camera.ptzPresetGoto(data)); + } catch (e) { return this.fail(e.message); } + } + + /** + * 云台预置点设置 + * @param {Object} data - 入参 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 统一响应 + */ + async ptzPresetSet(data) { + try { + return this.success('预置点设置成功', await this.service.systems.camera.ptzPresetSet(data)); + } catch (e) { return this.fail(e.message); } + } + async delete(data) { try { const { id } = data || {}; diff --git a/app/service/systems/camera.js b/app/service/systems/camera.js index dbd9ce9..120705f 100644 --- a/app/service/systems/camera.js +++ b/app/service/systems/camera.js @@ -164,6 +164,182 @@ class CameraService extends Service { }; } + /** + * 查询本仓库摄像头(云台控制复用,带录像服务器认证信息兜底) + * @param {number|string} id - 摄像头ID + * @param {number} warehouseId - 仓库ID + * @return {Promise} 摄像头记录 + */ + async _findCameraForControl(id, warehouseId) { + const { ctx } = this; + const camera = await ctx.model.Camera.findOne({ + where: { id: parseInt(id), warehouse_id: warehouseId }, + include: [{ + model: ctx.model.CameraServer, + as: 'server', + attributes: [ 'id', 'name', 'username', 'password', 'public_ip', 'internal_ip' ], + required: false, + }], + }); + if (!camera) throw new Error('摄像头不存在或无权操作'); + return camera; + } + + /** + * 校验打印服务响应,失败时抛出业务错误(与 setOsd 同口径) + * @param {Object} result - 打印服务调用结果 + * @return {Object} 原始结果 + */ + _assertPtzSuccess(result) { + if (!result) throw new Error('打印服务无响应'); + if (result.error) { + throw new Error(`打印服务请求失败: ${result.error}`); + } + if (!result.response || result.response.status < 200 || result.response.status >= 300) { + const status = result.response ? result.response.status : '无响应'; + const resData = result.response && result.response.data; + const msg = (resData && resData.message) || (resData && typeof resData === 'string' ? resData : '') || '未知错误'; + throw new Error(`打印服务返回异常(${status}): ${msg}`); + } + return result; + } + + /** + * 云台方向控制(按下):按指定方向转动摄像头,需配对调用 ptzStop 停止 + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {string} data.action - 云台方向(8 个位置,必填) + * @param {number} [data.speed] - 云台转速(1-7,默认 4) + * @return {Promise} 下发结果 + */ + async ptzControl(data) { + const { ctx } = this; + const { id, action, speed } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedAction = PtzClient.normalizeAction(action); + const normalizedSpeed = PtzClient.normalizeSpeed(speed); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.control({ + camera, + warehouseId, + action: normalizedAction, + speed: normalizedSpeed, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + action: normalizedAction, + speed: normalizedSpeed, + print_service_response: result.response, + }; + } + + /** + * 云台停止(松手):停止转动,action 必须与按下时一致 + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {string} data.action - 云台方向(必须与按下时一致,必填) + * @return {Promise} 下发结果 + */ + async ptzStop(data) { + const { ctx } = this; + const { id, action } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedAction = PtzClient.normalizeAction(action); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.stop({ + camera, + warehouseId, + action: normalizedAction, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + action: normalizedAction, + print_service_response: result.response, + }; + } + + /** + * 云台预置点跳转(一次调用即可,无需 stop) + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 下发结果 + */ + async ptzPresetGoto(data) { + const { ctx } = this; + const { id, presetId } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedPresetId = PtzClient.normalizePresetId(presetId); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.presetGoto({ + camera, + warehouseId, + presetId: normalizedPresetId, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + preset_id: normalizedPresetId, + print_service_response: result.response, + }; + } + + /** + * 云台预置点设置:把摄像头当前机位保存为指定预置点(一次调用即可) + * @param {Object} data - 参数 + * @param {number} data.id - 摄像头ID(必填) + * @param {number|string} data.presetId - 预置点编号(1-256,必填) + * @return {Promise} 下发结果 + */ + async ptzPresetSet(data) { + const { ctx } = this; + const { id, presetId } = data || {}; + const warehouseId = ctx.user.store_id; + if (!id) throw new Error('摄像头ID不能为空'); + + const PtzClient = require('../../lib/ptz_client'); + const normalizedPresetId = PtzClient.normalizePresetId(presetId); + + const camera = await this._findCameraForControl(id, warehouseId); + const ptzClient = new PtzClient(ctx); + const result = await ptzClient.presetSet({ + camera, + warehouseId, + presetId: normalizedPresetId, + }); + this._assertPtzSuccess(result); + + return { + camera_id: camera.id, + rtsp_url: result.request.rtspUrl, + preset_id: normalizedPresetId, + print_service_response: result.response, + }; + } + async delete(id) { const { ctx } = this; const warehouseId = ctx.user.store_id; diff --git a/app/service/systems/notice/index.js b/app/service/systems/notice/index.js index 3f6c5ef..4a3170e 100644 --- a/app/service/systems/notice/index.js +++ b/app/service/systems/notice/index.js @@ -28,6 +28,7 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'receiving_reviewed', 'receiving_store_bound', 'receiving_store_unmatched', + 'receiving_pending_inbound', 'entry_order_completed', 'order_cancel_intercepted', 'wave_strategy_quick_scan_failed', @@ -74,6 +75,16 @@ const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({ ]), }), ]), + receiving_pending_inbound: Object.freeze([ + Object.freeze({ + groupType: 'store', + subType: 'receiving', + // 未绑定货主(或无货主收货群)时回退仓库客服群人工跟进 + fallbackTargets: Object.freeze([ + Object.freeze({ groupType: 'warehouse', subType: 'customer_service' }), + ]), + }), + ]), entry_order_completed: Object.freeze([ Object.freeze({ groupType: 'store', diff --git a/app/service/systems/receiving_pending_notice.js b/app/service/systems/receiving_pending_notice.js new file mode 100644 index 0000000..7dbfd9d --- /dev/null +++ b/app/service/systems/receiving_pending_notice.js @@ -0,0 +1,780 @@ +'use strict'; + +const MainService = require('../main'); + +/** 通知事件码(需与 notice 固定订阅、notification_webhook 事件注册保持一致) */ +const NOTICE_EVENT = 'receiving_pending_inbound'; +/** 默认提醒时间(HH:mm) */ +const DEFAULT_NOTICE_TIME = '08:30'; +/** 默认超时下限(小时):创建时间距今超过该值才提醒 */ +const DEFAULT_MIN_HOURS = 24; +/** 默认超时上限(小时):创建时间距今超过该值不再提醒 */ +const DEFAULT_MAX_HOURS = 48; +/** 提醒时间命中宽限(分钟):覆盖 5 分钟调度间隔的抖动,配合当日锁保证一天只提醒一次 */ +const DEFAULT_GRACE_MINUTES = 10; +/** 单条通知最多列出的收货单行数(超出只提示剩余数量,避免消息过长) */ +const MAX_NOTICE_ITEMS = 20; +/** 当日执行锁 key 前缀 */ +const DAILY_LOCK_KEY_PREFIX = 'receiving_pending_notice:lock:'; +/** 当日执行锁 TTL(秒) */ +const DAILY_LOCK_TTL_SECONDS = 24 * 60 * 60; +/** 单小时毫秒数 */ +const HOUR_MS = 60 * 60 * 1000; +/** 通知短语最大长度(与仓库设置校验保持一致) */ +const NOTICE_TEMPLATE_MAX_LENGTH = 500; +/** 默认通知短语(仓库/客服群):短语 + 换行 + 明细(一行一条) */ +const DEFAULT_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:'; +/** 默认通知短语(货主群) */ +const DEFAULT_STORE_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:'; +const TIME_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/; +const TEMPLATE_VARIABLE_PATTERN = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g; + +const RECEIVING_STATUS_LABEL = Object.freeze({ + receiving: '收货中', + completed: '收货完成', + cancelled: '已作废', +}); +const STORAGE_STATUS_LABEL = Object.freeze({ + none: '未入库', + waiting: '待入库', + partial: '部分入库', + all: '已全部入库', +}); + +/** + * 两位补零。 + * @param {number} value 数值 + * @return {string} 补零后的字符串 + */ +function pad2(value) { + return String(value).padStart(2, '0'); +} + +/** + * 生成本地日期键,格式为 `YYYYMMDD`。 + * @param {Date} dateValue 日期对象 + * @return {string} 日期键 + */ +function buildDateKey(dateValue) { + return `${dateValue.getFullYear()}${pad2(dateValue.getMonth() + 1)}${pad2(dateValue.getDate())}`; +} + +/** + * 将 `HH:mm` 转为当日分钟数。 + * @param {string} timeText `HH:mm` 文本 + * @return {number} 分钟数,格式非法返回 -1 + */ +function toMinutes(timeText) { + if (!TIME_PATTERN.test(String(timeText || ''))) { + return -1; + } + + const [ hour, minute ] = String(timeText).split(':'); + return Number(hour) * 60 + Number(minute); +} + +/** + * 规范化正整数,非法或空值回退默认值。 + * @param {*} value 原始值 + * @param {number} fallback 兜底值 + * @return {number} 正整数 + */ +function toPositiveInteger(value, fallback) { + const numberValue = Number(value); + if (!Number.isInteger(numberValue) || numberValue <= 0) { + return fallback; + } + + return numberValue; +} + +/** + * 规范化通知短语:空值回退默认短语,超长截断。 + * @param {*} value 原始短语 + * @param {string} fallback 默认短语 + * @return {string} 规范化后的短语 + */ +function normalizeTemplateText(value, fallback) { + const text = String(value === undefined || value === null ? '' : value).trim(); + if (!text) { + return fallback; + } + + return text.length > NOTICE_TEMPLATE_MAX_LENGTH ? text.slice(0, NOTICE_TEMPLATE_MAX_LENGTH) : text; +} + +/** + * 渲染通知短语:替换支持的变量({warehouse}/{store}/{count}/...),未识别的占位符原样保留。 + * @param {string} template 短语模板 + * @param {Object} variables 变量键值对(键为小写变量名) + * @return {string} 渲染后的短语 + */ +function renderNoticeTemplate(template, variables) { + const source = String(template || ''); + if (!source) { + return ''; + } + + const values = variables && typeof variables === 'object' ? variables : {}; + + return source.replace(TEMPLATE_VARIABLE_PATTERN, (match, name) => { + const key = String(name || '').toLowerCase(); + if (!Object.prototype.hasOwnProperty.call(values, key)) { + return match; + } + + const value = values[key]; + return value === undefined || value === null ? '' : String(value); + }); +} + +/** + * 规范化「收货未入库提醒」配置(读取路径不抛错,非法值回退默认)。 + * @param {Object|string|null} rawConfig 原始配置 + * @return {Object} 规范化配置 + */ +function normalizeNoticeConfig(rawConfig) { + let parsed = rawConfig; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + parsed = null; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + parsed = {}; + } + + const noticeTime = TIME_PATTERN.test(String(parsed.notice_time || '').trim()) + ? String(parsed.notice_time).trim() + : DEFAULT_NOTICE_TIME; + const minHours = toPositiveInteger(parsed.min_hours, DEFAULT_MIN_HOURS); + const rawMaxHours = toPositiveInteger(parsed.max_hours, DEFAULT_MAX_HOURS); + const maxHours = rawMaxHours > minHours ? rawMaxHours : Math.max(DEFAULT_MAX_HOURS, minHours + 1); + + return { + enabled: parsed.enabled === true || parsed.enabled === 1 || parsed.enabled === '1', + noticeTime, + minHours, + maxHours, + noticeTemplate: normalizeTemplateText(parsed.notice_template, DEFAULT_NOTICE_TEMPLATE), + storeNoticeTemplate: normalizeTemplateText(parsed.store_notice_template, DEFAULT_STORE_NOTICE_TEMPLATE), + }; +} + +/** + * 从仓库 subject_config 中读取「收货未入库提醒」配置(兼容 JSON 字符串与缺失字段)。 + * @param {Object|string|null} rawSubject 原始 subject_config + * @return {Object} 规范化配置 + */ +function readNoticeConfigFromSubject(rawSubject) { + let parsed = rawSubject; + if (typeof parsed === 'string') { + try { + parsed = JSON.parse(parsed); + } catch (error) { + parsed = null; + } + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return normalizeNoticeConfig(null); + } + + return normalizeNoticeConfig(parsed.receiving_pending_inbound_notice); +} + +/** + * 判断当前时刻是否命中提醒时间(含宽限窗口,宽限不超过 1 天)。 + * @param {string} noticeTime 提醒时间 `HH:mm` + * @param {Date} now 当前时刻(进程本地时间,与仓库配置口径一致) + * @param {number} graceMinutes 宽限分钟 + * @return {boolean} 是否命中 + */ +function isNoticeTimeHit(noticeTime, now, graceMinutes) { + const targetMinutes = toMinutes(noticeTime); + if (targetMinutes < 0) { + return false; + } + + const grace = Math.max(1, Math.min(24 * 60, Math.floor(Number(graceMinutes) || DEFAULT_GRACE_MINUTES))); + const nowMinutes = now.getHours() * 60 + now.getMinutes(); + const diff = nowMinutes - targetMinutes; + + return (diff >= 0 && diff < grace) || (nowMinutes + 24 * 60 - targetMinutes < grace); +} + +/** + * 格式化时间用于消息展示,优先使用应用内格式化器。 + * @param {Object} ctx Egg 上下文 + * @param {*} value 原始时间值 + * @return {string} `YYYY-MM-DD HH:mm:ss`,非法值返回空串 + */ +function formatDateTime(ctx, value) { + if (!value) { + return ''; + } + + const dateValue = value instanceof Date ? value : new Date(value); + if (Number.isNaN(dateValue.getTime())) { + return ''; + } + + if (ctx && ctx.app && typeof ctx.app.formatDate === 'function') { + return ctx.app.formatDate(dateValue); + } + + return dateValue.toISOString(); +} + +/** + * 收货未入库提醒服务。 + * + * 按仓库设置 `subject_config.receiving_pending_inbound_notice` 扫描「创建时间超过 + * min_hours 且不足 max_hours 仍未完成入库」的收货单: + * - 绑定货主:通知货主收货群(未配群回退仓库客服群,由 notice 固定订阅回退链实现); + * - 未绑定货主:直接通知仓库客服群。 + * 通知时间(notice_time)与超时区间(min_hours / max_hours)均可在仓库设置中配置。 + */ +class ReceivingPendingNoticeService extends MainService { + constructor(ctx) { + super(ctx); + this.memoryDailyLocks = new Set(); + } + + /** + * 读取全部启用仓库的提醒配置。 + * + * @return {Promise>} 仓库配置列表 + */ + async getWarehouseNoticeConfigs() { + const { ctx } = this; + const storeModel = ctx.model && ctx.model.Store; + if (!storeModel || typeof storeModel.findAll !== 'function') { + ctx.logger.warn('[receiving-pending-notice] Store 模型不可用,跳过扫描'); + return []; + } + + const rows = await storeModel.findAll({ + where: { status: 1, deleted_at: null }, + attributes: [ 'id', 'company_name', 'subject_config' ], + order: [[ 'id', 'ASC' ]], + // 取 raw 行:避免模型 getter 对历史脏配置抛错导致整轮扫描中断,缺失字段由 normalizeNoticeConfig 兜默认值 + raw: true, + }); + + return (Array.isArray(rows) ? rows : []) + .map(row => { + const warehouseId = Number(row.id) || 0; + if (warehouseId <= 0) { + return null; + } + + return { + warehouseId, + warehouseName: String(row.company_name || '').trim(), + config: readNoticeConfigFromSubject(row.subject_config), + }; + }) + .filter(item => item && item.config.enabled); + } + + /** + * 查询指定仓库在超时区间内仍未完成入库的收货单。 + * + * @param {number} warehouseId 仓库 ID + * @param {Object} config 规范化后的提醒配置 + * @param {Date} now 当前时刻 + * @return {Promise>} 收货单列表(raw) + */ + async findPendingReceivings(warehouseId, config, now) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const receivingModel = ctx.model && ctx.model.Receiving; + if (!receivingModel || typeof receivingModel.findAll !== 'function') { + return []; + } + + const nowTime = now.getTime(); + + return await receivingModel.findAll({ + where: { + warehouse_id: warehouseId, + is_deleted: false, + status: { [Op.ne]: 'cancelled' }, + // 超过 min_hours 且不足 max_hours + created_at: { + [Op.gte]: new Date(nowTime - config.maxHours * HOUR_MS), + [Op.lte]: new Date(nowTime - config.minHours * HOUR_MS), + }, + [Op.or]: [ + { status: 'receiving' }, + { storage_status: { [Op.ne]: 'all' } }, + ], + }, + attributes: [ + 'id', 'receiving_number', 'store_id', 'store_name', 'status', 'storage_status', + 'created_at', 'delivery_method', 'total_quantity', 'total_boxes', + ], + order: [[ 'created_at', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + } + + /** + * 按货主分组收货单(未绑定货主归入 storeId=0 组)。 + * + * @param {Array} rows 收货单列表 + * @return {Array<{storeId: number, storeName: string, rows: Array}>} 分组结果 + */ + groupByStore(rows) { + const grouped = new Map(); + + for (const row of Array.isArray(rows) ? rows : []) { + const storeId = Number(row && row.store_id) > 0 ? Number(row.store_id) : 0; + if (!grouped.has(storeId)) { + grouped.set(storeId, { + storeId, + storeName: String(row && row.store_name || '').trim(), + rows: [], + }); + } + + grouped.get(storeId).rows.push(row); + } + + return [ ...grouped.values() ]; + } + + /** + * 构造单行收货单展示文本。 + * + * @param {Object} row 收货单记录 + * @param {number} index 序号 + * @param {Object} ctx Egg 上下文 + * @param {boolean} includeStore 是否展示货主(仓库/客服版展示,货主版不展示) + * @return {string} 展示行 + */ + buildRowLine(row, index, ctx, includeStore) { + const number = String(row.receiving_number || row.id || '').trim(); + const createdText = formatDateTime(ctx, row.created_at); + const statusText = String(row.status || '') === 'receiving' + ? RECEIVING_STATUS_LABEL.receiving + : `${RECEIVING_STATUS_LABEL.completed}·${STORAGE_STATUS_LABEL[row.storage_status] || '未入库'}`; + const quantity = Number(row.total_quantity || 0); + const parts = [ + `${index}.${number}`, + includeStore ? `货主:${String(row.store_name || '').trim() || (Number(row.store_id) > 0 ? `ID${row.store_id}` : '未绑定')}` : '', + includeStore && quantity > 0 ? `数量:${quantity}` : '', + createdText ? `创建时间:${createdText}` : '', + `状态:${statusText}`, + ].filter(Boolean); + + return parts.join(' '); + } + + /** + * 格式化日期(YYYY-MM-DD),优先使用应用内格式化器。 + * + * @param {Object} ctx Egg 上下文 + * @param {*} value 原始时间值 + * @return {string} 日期文本 + */ + formatDateOnly(ctx, value) { + const dateValue = value instanceof Date ? value : new Date(value); + if (Number.isNaN(dateValue.getTime())) { + return ''; + } + + if (ctx && ctx.app && typeof ctx.app.formatDate === 'function') { + return ctx.app.formatDate(dateValue, 'YYYY-MM-DD'); + } + + return `${dateValue.getFullYear()}-${pad2(dateValue.getMonth() + 1)}-${pad2(dateValue.getDate())}`; + } + + /** + * 构造通知短语的替换变量(未识别的占位符在渲染时原样保留)。 + * + * 可用变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名(未绑定为「未绑定货主」) + * / {store_id} 货主ID / {count} 本批单数 / {min_hours} / {max_hours} / {date} 提醒日期 + * / {numbers} 本批收货单号(最多 20 个,超出以「等 N 单」结尾)。 + * + * @param {Object} options 变量来源 + * @param {Array} options.rows 收货单列表 + * @param {Object} options.config 规范化后的提醒配置 + * @param {string} options.warehouseName 仓库名称 + * @param {number} options.warehouseId 仓库 ID + * @param {number} options.storeId 货主 ID(0 表示未绑定) + * @param {string} options.storeName 货主名称 + * @param {Date} options.now 当前时刻 + * @param {Object} options.ctx Egg 上下文 + * @return {Object} 变量键值对 + */ + buildTemplateVariables({ rows, config, warehouseName, warehouseId, storeId, storeName, now, ctx }) { + const list = Array.isArray(rows) ? rows : []; + const hasStore = Number(storeId) > 0; + const numbers = list + .slice(0, MAX_NOTICE_ITEMS) + .map(row => String(row && (row.receiving_number || row.id) || '').trim()) + .filter(Boolean); + + return { + warehouse: String(warehouseName || '').trim() || `仓库${warehouseId}`, + warehouse_id: String(warehouseId), + store: hasStore ? (String(storeName || '').trim() || `货主${storeId}`) : '未绑定货主', + store_id: hasStore ? String(storeId) : '0', + count: String(list.length), + min_hours: String(config.minHours), + max_hours: String(config.maxHours), + date: this.formatDateOnly(ctx, now), + numbers: numbers.length > 0 + ? `${numbers.join('、')}${list.length > numbers.length ? ` 等 ${list.length} 单` : ''}` + : '', + }; + } + + /** + * 构造消息正文:短语(模板变量替换)+ 换行 + 明细(一行一条)+ 查看链接。 + * + * 短语来自仓库设置(notice_template 仓库/客服群版、store_notice_template 货主群版), + * 为空时回退默认短语。 + * + * @param {Object} options 构造参数 + * @param {Array} options.rows 收货单列表 + * @param {Object} options.config 规范化后的提醒配置 + * @param {string} options.warehouseName 仓库名称 + * @param {number} options.warehouseId 仓库 ID + * @param {number} options.storeId 货主 ID(0 表示未绑定) + * @param {string} options.storeName 货主名称 + * @param {boolean} options.forStore 是否货主版文案 + * @param {string} options.viewUrl 查看链接 + * @param {Date} options.now 当前时刻 + * @param {Object} options.ctx Egg 上下文 + * @return {string} 消息正文 + */ + buildContent({ rows, config, warehouseName, warehouseId, storeId, storeName, forStore, viewUrl, now, ctx }) { + const list = Array.isArray(rows) ? rows : []; + const template = forStore ? config.storeNoticeTemplate : config.noticeTemplate; + const phrase = renderNoticeTemplate(template, this.buildTemplateVariables({ + rows: list, + config, + warehouseName, + warehouseId, + storeId, + storeName, + now, + ctx, + })); + const lines = [ phrase ]; + + list.slice(0, MAX_NOTICE_ITEMS).forEach((row, index) => { + lines.push(this.buildRowLine(row, index + 1, ctx, !forStore)); + }); + + if (list.length > MAX_NOTICE_ITEMS) { + lines.push(`…… 其余 ${list.length - MAX_NOTICE_ITEMS} 单未列出`); + } + + lines.push(`${forStore ? '详情查看' : '快速查看'}:${viewUrl}`); + + return lines.join('\n'); + } + + /** + * 解析通知发送方法,优先 `send`,其次兼容 `index.send`。 + * + * @return {Function|null} 可执行的发送方法 + */ + resolveNoticeSendMethod() { + const { ctx } = this; + const noticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice; + if (!noticeService) { + return null; + } + + if (typeof noticeService.send === 'function') { + return noticeService.send.bind(noticeService); + } + + if (noticeService.index && typeof noticeService.index.send === 'function') { + return noticeService.index.send.bind(noticeService.index); + } + + return null; + } + + /** + * 发送单个货主批次(或未绑定货主批次)的未入库提醒。 + * + * @param {Object} options 发送参数 + * @param {number} options.warehouseId 仓库 ID + * @param {string} options.warehouseName 仓库名称 + * @param {number} options.storeId 货主 ID,0 表示未绑定货主 + * @param {string} options.storeName 货主名称 + * @param {Array} options.rows 该货主的收货单列表 + * @param {Object} options.config 规范化后的提醒配置 + * @param {Date} options.now 当前时刻 + * @return {Promise} 通知结果 + */ + async sendPendingNotice({ warehouseId, warehouseName, storeId, storeName, rows, config, now }) { + const { ctx, app } = this; + const sendMethod = this.resolveNoticeSendMethod(); + if (typeof sendMethod !== 'function') { + ctx.logger.warn('[receiving-pending-notice] 通知服务不可用,跳过发送'); + return null; + } + + const warehouseFrontendUrl = String(app.config.frontendUrl || '').trim(); + const storeFrontendUrl = String(app.config.storeFrontendUrl || app.config.frontendUrl || '').trim(); + const hasStore = Number(storeId) > 0; + const content = this.buildContent({ + rows, + config, + warehouseName, + warehouseId, + storeId, + storeName, + forStore: false, + viewUrl: `${warehouseFrontendUrl}/storage/receiving`, + now, + ctx, + }); + const storeContent = hasStore + ? this.buildContent({ + rows, + config, + warehouseName, + warehouseId, + storeId, + storeName, + forStore: true, + viewUrl: `${storeFrontendUrl}/storage/receiving_owner`, + now, + ctx, + }) + : undefined; + + return await sendMethod({ + warehouseId, + // 未绑定货主时不带 storeId,由 notice 固定订阅回退到仓库客服群 + storeId: hasStore ? Number(storeId) : undefined, + messageType: 'text', + businessName: 'receiving', + event: NOTICE_EVENT, + channel: 'warehouse', + title: `收货未入库提醒(${rows.length} 单)`, + content, + ...(storeContent ? { storeContent } : {}), + // 幂等键:同仓库+同货主+同一天只落一条消息记录 + businessId: `receiving-pending:${warehouseId}:${hasStore ? Number(storeId) : 0}:${buildDateKey(now)}`, + subject: { + id: warehouseId, + type: 'warehouse', + name: warehouseName, + }, + sender: { + id: null, + name: '系统提醒', + }, + metadata: { + warehouseId, + warehouseName, + storeId: hasStore ? Number(storeId) : null, + storeName: String(storeName || '').trim(), + minHours: config.minHours, + maxHours: config.maxHours, + receivingIds: rows.map(row => Number(row.id)).filter(id => id > 0), + receivingNumbers: rows.map(row => String(row.receiving_number || '')).filter(Boolean), + }, + }); + } + + /** + * 扫描并通知单个仓库的超时未入库收货单。 + * + * @param {Object} options 执行参数 + * @param {number} options.warehouseId 仓库 ID + * @param {string} options.warehouseName 仓库名称 + * @param {Object} options.config 规范化后的提醒配置 + * @param {Date} options.now 当前时刻 + * @return {Promise} 执行汇总 + */ + async notifyWarehouse({ warehouseId, warehouseName, config, now }) { + const { ctx } = this; + const rows = await this.findPendingReceivings(warehouseId, config, now); + const summary = { + warehouseId, + warehouseName, + pendingCount: rows.length, + groupCount: 0, + sentCount: 0, + failedCount: 0, + }; + + if (rows.length === 0) { + ctx.logger.info(`[receiving-pending-notice] 仓库 ${warehouseId} 无超时未入库收货单`); + return summary; + } + + const groups = this.groupByStore(rows); + for (const group of groups) { + const result = await this.sendPendingNotice({ + warehouseId, + warehouseName, + storeId: group.storeId, + storeName: group.storeName, + rows: group.rows, + config, + now, + }); + + summary.groupCount += 1; + if (result && result.success) { + summary.sentCount += 1; + } else { + summary.failedCount += 1; + } + } + + ctx.logger.info( + `[receiving-pending-notice] 仓库 ${warehouseId} 提醒完成:未入库 ${summary.pendingCount} 单,` + + `通知 ${summary.groupCount} 个批次,成功 ${summary.sentCount},失败 ${summary.failedCount}` + ); + + return summary; + } + + /** + * 获取 Redis 缓存客户端。 + * + * @return {Object|null} Redis 客户端或 null + */ + getRedisClient() { + const { app } = this; + try { + return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null; + } catch (error) { + return null; + } + } + + /** + * 申请当日执行锁(Redis NX;Redis 不可用时降级为进程内集合)。 + * + * @param {string} lockKey 锁 key + * @return {Promise} 是否申请成功 + */ + async acquireDailyLock(lockKey) { + const { ctx } = this; + const redisClient = this.getRedisClient(); + + if (redisClient && typeof redisClient.set === 'function') { + try { + const result = await redisClient.set(lockKey, '1', 'EX', DAILY_LOCK_TTL_SECONDS, 'NX'); + if (result === 'OK') { + return true; + } + if (result !== null && result !== undefined) { + return false; + } + } catch (error) { + ctx.logger.warn(`[receiving-pending-notice] 当日锁申请失败,降级进程内锁: ${error.message}`); + } + } + + if (this.memoryDailyLocks.has(lockKey)) { + return false; + } + + this.memoryDailyLocks.add(lockKey); + return true; + } + + /** + * 释放当日执行锁(发送异常时释放,允许宽限窗口内下一轮重试)。 + * + * @param {string} lockKey 锁 key + * @return {Promise} 无返回值 + */ + async releaseDailyLock(lockKey) { + const { ctx } = this; + this.memoryDailyLocks.delete(lockKey); + + const redisClient = this.getRedisClient(); + if (redisClient && typeof redisClient.del === 'function') { + try { + await redisClient.del(lockKey); + } catch (error) { + ctx.logger.warn(`[receiving-pending-notice] 当日锁释放失败: ${error.message}`); + } + } + } + + /** + * 执行一轮收货未入库提醒(供定时任务调用)。 + * + * 命中条件:仓库开启提醒 + 当前时刻落在 notice_time 宽限窗口内 + 当日未执行过。 + * + * @param {Object|null} options 执行参数 + * @param {Date} [options.now] 指定当前时刻(测试用) + * @param {number} [options.graceMinutes] 提醒时间宽限分钟(测试用) + * @return {Promise} 执行汇总 + */ + async execute(options = null) { + const { ctx } = this; + const params = options || {}; + const now = params.now instanceof Date ? params.now : new Date(); + const graceMinutes = Number.isFinite(Number(params.graceMinutes)) && Number(params.graceMinutes) > 0 + ? Number(params.graceMinutes) + : DEFAULT_GRACE_MINUTES; + + const enabledConfigs = await this.getWarehouseNoticeConfigs(); + const dateKey = buildDateKey(now); + const summary = { + checkedWarehouseCount: enabledConfigs.length, + executedWarehouseCount: 0, + pendingCount: 0, + sentCount: 0, + failedCount: 0, + results: [], + }; + + for (const item of enabledConfigs) { + if (!isNoticeTimeHit(item.config.noticeTime, now, graceMinutes)) { + continue; + } + + const lockKey = `${DAILY_LOCK_KEY_PREFIX}${item.warehouseId}:${dateKey}`; + const acquired = await this.acquireDailyLock(lockKey); + if (!acquired) { + continue; + } + + try { + const result = await this.notifyWarehouse({ + warehouseId: item.warehouseId, + warehouseName: item.warehouseName, + config: item.config, + now, + }); + summary.executedWarehouseCount += 1; + summary.pendingCount += result.pendingCount; + summary.sentCount += result.sentCount; + summary.failedCount += result.failedCount; + summary.results.push(result); + } catch (error) { + // 执行失败释放锁,宽限窗口内的下一轮仍可重试 + await this.releaseDailyLock(lockKey); + summary.failedCount += 1; + ctx.logger.error(`[receiving-pending-notice] 仓库 ${item.warehouseId} 提醒执行失败: ${error.message}`); + } + } + + return summary; + } +} + +module.exports = ReceivingPendingNoticeService; diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index 8fbd2a6..2204f51 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -322,6 +322,78 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ required: false, description: '仓库未指定库位入库/上架时使用的默认库位(库位ID)', }), + Object.freeze({ + key: 'receiving_pending_inbound_notice', + name: '收货未入库提醒', + type: 'object', + default: Object.freeze({ + enabled: false, + notice_time: '08:30', + min_hours: 24, + max_hours: 48, + notice_template: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:', + store_notice_template: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:', + }), + required: false, + description: '开启后每天按提醒时间扫描「创建超过 min_hours 且不足 max_hours 仍未完成入库」的收货单,绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群', + item_keys: Object.freeze([ + Object.freeze({ + key: 'enabled', + name: '是否通知收货未入库', + type: 'flag', + default: false, + required: true, + description: '默认否,开启后定时任务才会执行提醒', + }), + Object.freeze({ + key: 'notice_time', + name: '提醒时间', + type: 'string', + default: '08:30', + required: false, + maxLength: 5, + min: '00:00', + max: '23:59', + description: '每日提醒时间,格式 HH:mm,默认 08:30', + }), + Object.freeze({ + key: 'min_hours', + name: '超时下限(小时)', + type: 'integer', + default: 24, + required: false, + min: 1, + description: '收货单创建时间距今超过该小时数才提醒,默认 24', + }), + Object.freeze({ + key: 'max_hours', + name: '超时上限(小时)', + type: 'integer', + default: 48, + required: false, + min: 1, + description: '收货单创建时间距今小于该小时数才提醒,超过则不再提醒,默认 48', + }), + Object.freeze({ + key: 'notice_template', + name: '通知短语(仓库/客服群)', + type: 'string', + default: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:', + required: false, + maxLength: 500, + description: '消息第一行短语,可插入变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名 / {store_id} 货主ID / {count} 单数 / {min_hours} / {max_hours} / {date} 提醒日期 / {numbers} 收货单号;短语后换行逐行列出明细,留空用默认短语', + }), + Object.freeze({ + key: 'store_notice_template', + name: '通知短语(货主群)', + type: 'string', + default: '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:', + required: false, + maxLength: 500, + description: '推送给货主群的消息第一行短语,变量同 notice_template,留空用默认短语', + }), + ]), + }), Object.freeze({ key: INTERNAL_WAVE_STRATEGY_VERSION_KEY, name: '仓库波次策略版本号', diff --git a/methods/changes/system.json b/methods/changes/system.json index 5e8bf7c..63a147a 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,130 @@ [ + { + "version": "2026.09.15-warehouse-pending-receiving-notice-template", + "date": "2026-09-15", + "type": "updated", + "summary": "收货未入库提醒支持自定义通知短语:subject_config.receiving_pending_inbound_notice 新增 notice_template(仓库/客服群短语)与 store_notice_template(货主群短语),支持变量替换({warehouse}/{warehouse_id}/{store}/{store_id}/{count}/{min_hours}/{max_hours}/{date}/{numbers}),消息结构固定为「短语 + 换行 + 明细(一行一条)+ 查看链接」,留空使用默认短语。", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "字段口径:wms_store.subject_config.receiving_pending_inbound_notice.notice_template / store_notice_template,均为 string、最长 500 字符、空值回退默认短语", + "默认短语:仓库/客服群「【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:」;货主群「【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:」", + "可用变量:{warehouse} 仓库名(缺名回退「仓库{id}」)/ {warehouse_id} / {store} 货主名(未绑定为「未绑定货主」)/ {store_id} / {count} 本批单数 / {min_hours} / {max_hours} / {date} 提醒日期 YYYY-MM-DD / {numbers} 本批收货单号(最多 20 个,超出以「等 N 单」结尾);未识别占位符原样保留", + "校验:短语超 500 字符报 400「subject_config.receiving_pending_inbound_notice.notice_template 长度不能超过 500 字符」(store_notice_template 同);空串/null 回退默认短语(模型 app/model/store.js#normalizeReceivingPendingInboundNotice)", + "消息结构:短语 + \\n + 明细行(一行一条,最多 20 行「序号.单号 货主 数量 创建时间 状态」)+ \\n + 快速查看/详情查看链接;不再在结尾追加句号", + "单测:test/app/service/systems/receiving_pending_notice.test.js 新增「短语变量替换 + 明细逐行」「未识别占位符原样保留 + 货主短语缺省回退」两用例(共 11 用例)", + "文档版本 0.3.130 -> 0.3.131,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)" + ] + }, + { + "version": "2026.09.15-warehouse-pending-receiving-notice", + "date": "2026-09-15", + "type": "updated", + "summary": "仓库设置(wms_store.subject_config)新增「收货未入库提醒」配置 receiving_pending_inbound_notice:enabled(是否通知收货未入库,flag,默认 0 关闭)/ notice_time(提醒时间 HH:mm,默认 08:30)/ min_hours(超时下限小时,默认 24)/ max_hours(超时上限小时,默认 48,须大于 min_hours)。开启后由定时任务(app/schedule/notice_receiving_pending_inbound.js,每 5 分钟检查、按仓库配置的提醒时间执行,每天一次)扫描超时未完成入库的收货单并通知:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群。setting.warehouse.getSettings 响应与 setting.warehouse.saveSettings 入参补充该字段文档。", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.saveSettings" + ], + "notes": [ + "字段口径:wms_store.subject_config.receiving_pending_inbound_notice = { enabled, notice_time, min_hours, max_hours };默认 { enabled:false, notice_time:\"08:30\", min_hours:24, max_hours:48 }(默认不通知)", + "模型默认值与校验:app/model/store.js(DEFAULT_SUBJECT_CONFIG + normalizeReceivingPendingInboundNotice);字段元信息:app/service/systems/setting/warehouse.js(WAREHOUSE_SETTING_FIELDS,type=object)", + "校验口径:notice_time 必须为 HH:mm(如 08:30),否则 400「subject_config.receiving_pending_inbound_notice.notice_time 格式必须为 HH:mm(如 08:30)」;min_hours/max_hours 必须为大于 0 的整数,且 min_hours 必须小于 max_hours,否则 400", + "定时任务:app/schedule/notice_receiving_pending_inbound.js(interval 5m、单 worker、进程内防重入)→ app/service/systems/receiving_pending_notice.js#execute;命中口径为「创建时间超过 min_hours 且不足 max_hours」且(status=receiving 或 storage_status<>all)、is_deleted=0、status<>cancelled;货主维度聚合成一条消息(每行一个收货单,最多 20 行)", + "通知事件:新增事件码 receiving_pending_inbound(app/model/notification_webhook.js 注册),固定群订阅 app/service/systems/notice/index.js#FIXED_GROUP_SUBSCRIPTIONS:store:receiving + fallbackTargets warehouse:customer_service(无货主或货主未配收货群时通知仓库客服群)", + "幂等:同一仓库+货主同一自然日只推送一次(Redis 当日锁 receiving_pending_notice:lock:{warehouseId}:{YYYYMMDD},TTL 24h;执行异常释放锁,宽限窗口内下一轮重试),消息 ext_id 含 receiving-pending:{warehouseId}:{storeId}:{YYYYMMDD}", + "单测:test/app/service/systems/receiving_pending_notice.test.js(9 用例:开关关闭/未命中提醒时间不执行、超时窗口查询条件、货主群通知、无货主回退、当日只提醒一次、异常释放锁重试、行数截断、非法配置回退默认)", + "文档版本 0.3.129 -> 0.3.130,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)" + ] + }, + { + "version": "2026.09.15-camera-ptz-camera-id", + "date": "2026-09-15", + "type": "updated", + "summary": "云台(PTZ)四个接口下发给打印服务时请求体统一携带摄像头ID:camera.ptzControl / camera.ptzStop / camera.ptzPresetGoto / camera.ptzPresetSet 的请求体由 { warehouse_id, rtspUrl, … } 改为 { warehouse_id, cameraId, rtspUrl, … }(cameraId 取 wms_camera.id,数值型;warehouse_id 仍为字符串)。接口入参与响应不变。", + "methods": [ + "camera.ptzControl", + "camera.ptzStop", + "camera.ptzPresetGoto", + "camera.ptzPresetSet" + ], + "notes": [ + "变更内容:4 个 PTZ 端点(/camera/ptzControl、/camera/ptzStop、/camera/ptzPresetGoto、/camera/ptzPresetSet)的请求体新增 cameraId 字段,值取摄像头记录主键 wms_camera.id(Number() 归一化后以数值下发),便于打印服务侧按摄像头ID定位/校验设备与日志排查", + "前端入参不变:cameraId 由 WMS 服务端从查询到的摄像头记录自动带入(前端仍只传 id,无需重复传摄像头ID;也无需传 computerId)", + "实现位置:app/lib/ptz_client.js#_send 统一拼接请求体 { warehouse_id: String(warehouseId), cameraId, ...业务字段 },四个入口方法无需各自处理;同时补 camera.id 合法性校验(非正整数报「摄像头ID不合法」)", + "请求体口径(warehouse_id 为字符串、cameraId 为数值):ptzControl { warehouse_id, cameraId, rtspUrl, action, speed };ptzStop { warehouse_id, cameraId, rtspUrl, action };ptzPresetGoto { warehouse_id, cameraId, rtspUrl, presetId };ptzPresetSet { warehouse_id, cameraId, rtspUrl, presetId }", + "响应不变:仍为 { camera_id, rtsp_url, action, speed | preset_id, print_service_response };错误码不变(400/404/500)", + "回归:node run/check-camera-ptz.cjs(68 用例,四个方法的请求体断言均已含 cameraId)全部通过;npx eslint 无告警", + "文档版本 0.3.128 -> 0.3.129,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)", + "AI_METHOD_ROUTING.md 5.7 段「下发通道」条目已同步补充 cameraId" + ] + }, + { + "version": "2026.09.15-camera-ptz-preset-set", + "date": "2026-09-15", + "type": "added", + "summary": "摄像头模块新增 camera.ptzPresetSet(云台预置点设置):把摄像头当前机位保存为指定预置点,入参 id + presetId(1-256),一次调用即可、无需配对 stop。与既有的 camera.ptzPresetGoto(跳转到预置点)构成「存点 / 跳转」一对,写入载体为打印服务端点 POST {printService.url}/camera/ptzPresetSet,请求体 { warehouse_id, rtspUrl, presetId }。", + "methods": [ + "camera.ptzPresetSet" + ], + "notes": [ + "接口口径:与 camera.ptzControl / camera.ptzStop / camera.ptzPresetGoto 完全一致 —— 独立端点(不带 computerId)、扁平请求体、warehouse_id 为字符串、rtspUrl 服务端按摄像头记录组装", + "入参:id(摄像头ID,必填)、presetId(预置点编号,必填,1-256 整数,字符串数字会被归一化);无 speed / action 参数", + "响应:data 为 { camera_id, rtsp_url, preset_id, print_service_response }", + "错误码:400(摄像头ID不能为空 / 预置点编号不能为空或不是 1-256 的整数 / 摄像头未配置IP地址)、404(摄像头不存在或无权操作)、500(打印服务调用失败,含 HTTP 非 2xx 与回包 status=fail / success=false)", + "权限口径:与 camera.setOsd 一致,camera.js#systemInit 已把 ptzPresetSet 加入 _noNeedRight/_noNeedAuth,_noNeedLog 为 *(不写系统日志)", + "代码依据:app/lib/ptz_client.js#PTZ_PATH.PRESET_SET 与 #presetSet(复用 normalizePresetId/_send/buildRtspUrl)、app/service/systems/camera.js#ptzPresetSet(复用 _findCameraForControl/_assertPtzSuccess)、app/service/systemMethods/camera.js#ptzPresetSet", + "回归:node run/check-camera-ptz.cjs(67 用例,新增 presetSet 的端点/请求体/归一化/边界/摄像头不存在 6 项断言)全部通过;npx eslint 无告警", + "文档版本 0.3.127 -> 0.3.128,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run),新增 method 由脚本追加到「摄像头模块」分组尾部", + "AI_METHOD_ROUTING.md 5.7 段表格已补 camera.ptzPresetSet 行,并刷新第 6 节自动清单(systemMethods/camera.js 与 systems/camera.js 方法数 +1)" + ] + }, + { + "version": "2026.09.15-camera-ptz-wms-endpoint", + "date": "2026-09-15", + "type": "updated", + "summary": "云台(PTZ)三接口入参口径变更:camera.ptzControl / camera.ptzStop / camera.ptzPresetGoto 去除 computerId(打印电脑ID)参数,改为打印服务独立端点下发 —— POST {printService.url}/camera/ptzControl、/camera/ptzStop、/camera/ptzPresetGoto,请求体 { warehouse_id, rtspUrl, action, speed | presetId },与 camera.setOsd 同风格(独立端点、不带电脑ID、warehouse_id 为字符串)。响应同步去除 computer_id 字段。", + "methods": [ + "camera.ptzControl", + "camera.ptzStop", + "camera.ptzPresetGoto" + ], + "notes": [ + "变更原因:与 camera.setOsd 对齐 —— 打印服务按 rtspUrl 定位摄像头,无需电脑房间路由;WMS 服务端也推导不出打印电脑ID(wms_print_computer.id 由打印端 /auth/bind 按「仓库+打印台名称」创建,Web 端登录用户仅有 store_id,wms_workbench 只有 device_ids)", + "入参变化:三个接口均删除 computerId(必填);camera.ptzControl 保留 id/action/speed,camera.ptzStop 保留 id/action,camera.ptzPresetGoto 保留 id/presetId", + "下发报文变化:由 POST {printService.url}/sendToRoom 信封 { warehouse, computerId, method: 'camera.ptz.control'|'camera.ptz.stop'|'camera.ptz.presetGoto', data } 改为三个独立端点 + 扁平请求体 { warehouse_id, rtspUrl, action, speed | presetId }", + "响应变化:data 由 { camera_id, computer_id, rtsp_url, action, speed | preset_id, print_service_response } 改为 { camera_id, rtsp_url, action, speed | preset_id, print_service_response }(删除 computer_id)", + "错误码变化:不再返回「打印电脑ID不能为空/不合法」;其余 400(摄像头ID为空、方向不合法、转速越界、预置点越界、摄像头未配置IP)/404/500 口径不变", + "同一日已存在本接口首次登记的变更记录 2026.09.15-camera-ptz-control(type=added,尚未发布);script/update-api-doc.cjs 的变更记录仅支持头部插入新记录、不支持原位追加,故按兜底方案新增带 -wms-endpoint 后缀的独立记录", + "代码依据:app/lib/ptz_client.js#PTZ_PATH(/camera/ptzControl、/camera/ptzStop、/camera/ptzPresetGoto)+ _send(请求体 warehouse_id 转字符串、字段与 setOSD 对齐)、app/service/systems/camera.js(删除 _normalizeComputerId;_findCameraForControl/_assertPtzSuccess 保留;三方法返回值去掉 computer_id)", + "回归:node run/check-camera-ptz.cjs(60 用例,含「请求体不带 computerId」断言)全部通过;npx eslint 无告警", + "文档版本 0.3.126 -> 0.3.127,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run)", + "AI_METHOD_ROUTING.md 5.7 段已同步(删除 computerId 说明、改为独立端点),并刷新第 6 节自动清单" + ] + }, + { + "version": "2026.09.15-camera-ptz-control", + "date": "2026-09-15", + "type": "added", + "summary": "摄像头模块新增云台控制(PTZ)三个接口:camera.ptzControl(按下,按方向持续转动,action 支持 8 个位置 up/down/left/right/upleft/upright/downleft/downright,speed 1-7 默认 4)、camera.ptzStop(松手,action 必须与按下时一致)、camera.ptzPresetGoto(预置点跳转,presetId 1-256,一次调用无需 stop)。服务端按摄像头记录组装 rtspUrl,通过打印服务统一指令信封 POST {printService.url}/sendToRoom 下发 { warehouse, computerId, method, data },computerId 由前端传入。", + "methods": [ + "camera.ptzControl", + "camera.ptzStop", + "camera.ptzPresetGoto" + ], + "notes": [ + "接口口径:method 与打印服务一一对应 —— camera.ptzControl -> camera.ptz.control(data: { rtspUrl, action, speed })、camera.ptzStop -> camera.ptz.stop(data: { rtspUrl, action })、camera.ptzPresetGoto -> camera.ptz.presetGoto(data: { rtspUrl, presetId })", + "action 枚举(8 个位置,与打印服务约定,写入 params[].action.list,顺序固定):up-上、down-下、left-左、right-右、upleft-左上、upright-右上、downleft-左下、downright-右下;大小写不敏感,服务端转小写后校验,非法值报 400", + "参数校验:id 必填;computerId 必填且为正整数;action 必填且属于 8 个方向;speed 可选取 1-7 整数(默认 4);presetId 必填取 1-256 整数(转速/预置点仅约束下发的打印服务指令口径,摄像头端实际生效范围以设备为准)", + "rtspUrl 由服务端组装(rtsp://{username}:{password}@{ip}:554/stream{channel_id}),与 camera.setOsd 同口径,前端无需传;摄像头无 ip 时报 400「摄像头未配置IP地址,无法组装RTSP地址」", + "权限口径:与 camera.setOsd 一致,camera.js#systemInit 已把 ptzControl/ptzStop/ptzPresetGoto 加入 _noNeedRight/_noNeedAuth,且 _noNeedLog 为 *(PTZ 高频调用不写系统日志)", + "响应口径:成功时 data 为 { camera_id, computer_id, rtsp_url, action, speed | preset_id, print_service_response }(print_service_response 为打印服务原始回信,便于前端/排查核对);打印服务 HTTP 非 2xx、或回包 status=fail / success=false 时按 500 抛出并带打印服务 message", + "代码依据:app/lib/ptz_client.js(PTZ_METHOD/PTZ_ACTION_LIST/PTZ_ACTIONS + control/stop/presetGoto + buildRtspUrl 与 osd_client 同口径)、app/service/systems/camera.js(_findCameraForControl/_normalizeComputerId/_assertPtzSuccess + ptzControl/ptzStop/ptzPresetGoto)、app/service/systemMethods/camera.js(三个入口方法 + systemInit 免权限声明)", + "文档版本 0.3.125 -> 0.3.126,updatedAt 2026-09-15;写入通过 script/update-api-doc.cjs(先 --dry-run),新增 method 由脚本追加到「摄像头模块」分组尾部", + "AI_METHOD_ROUTING.md 已同步刷新第 6 节自动清单(app/service/systemMethods/camera.js 由 6 个方法变为 9 个)" + ] + }, { "version": "2026.09.15-returnUnpack.transferByWaybills-ids", "date": "2026-09-15", diff --git a/methods/changes/warehouse.json b/methods/changes/warehouse.json index 759534f..4dcb945 100644 --- a/methods/changes/warehouse.json +++ b/methods/changes/warehouse.json @@ -1,4 +1,40 @@ [ + { + "version": "2026-09-15-warehouse-02", + "date": "2026-09-15", + "type": "changed", + "module": "receiving", + "summary": "收货未入库提醒出站文案改为「短语 + 换行 + 明细(一行一条)」:短语可在仓库设置自定义并插入变量,明细不再拼接在短语同一行,末尾不再追加句号", + "methods": [ + "notify.reply" + ], + "notes": [ + "文案结构(app/service/systems/receiving_pending_notice.js#buildContent):第 1 行 = 短语(模板渲染后),其后换行逐行输出明细(「序号.单号 货主:xx 数量:xx 创建时间:xx 状态:xx」,货主群版不展示货主/数量),最多 20 行,超出补「…… 其余 N 单未列出」,最后一行「快速查看:/详情查看:<链接>」", + "短语来源:仓库设置 subject_config.receiving_pending_inbound_notice.notice_template(仓库/客服群)/ store_notice_template(货主群),留空回退默认短语", + "支持变量:{warehouse}/{warehouse_id}/{store}/{store_id}/{count}/{min_hours}/{max_hours}/{date}/{numbers};未识别的占位符原样保留(便于发现拼写错误),变量渲染不影响未知变量", + "推送协议与路由不变:仍为 notify.reply(type=system)+ 固定订阅 receiving_pending_inbound(store:receiving,未命中回退 warehouse:customer_service)", + "单测:test/app/service/systems/receiving_pending_notice.test.js(11 用例)全部通过;npx eslint 无告警" + ] + }, + { + "version": "2026-09-15-warehouse-01", + "date": "2026-09-15", + "type": "added", + "module": "receiving", + "summary": "新增收货未入库提醒事件 receiving_pending_inbound:定时扫描「创建超时且未完成入库」的收货单,绑定货主的推货主收货群(未配群回退仓库客服群),未绑定货主的推仓库客服群;仓库设置新增 receiving_pending_inbound_notice(是否通知/提醒时间/超时区间,默认关闭)", + "methods": [ + "notify.reply" + ], + "notes": [ + "事件码注册:app/model/notification_webhook.js 新增 receiving_pending_inbound(name=收货未入库超时提醒,business=receiving);notice/index.js DEFAULT_REGISTERED_EVENT_CODES 同步登记", + "固定群订阅(app/service/systems/notice/index.js#FIXED_GROUP_SUBSCRIPTIONS):receiving_pending_inbound = [store:receiving,fallbackTargets=[warehouse:customer_service]];无货主时 store 目标被跳过,回退链命中仓库客服群,内容走仓库版文案", + "推送协议不变:复用 notify.reply(type=system、content、ext_id、group_id、group_name、timestamp),出站消息落 wms_inbox_message(ext_id 含 receiving-pending:{warehouseId}:{storeId}:{YYYYMMDD})", + "触发通道:app/schedule/notice_receiving_pending_inbound.js(interval 5m、type=worker、进程内防重入)→ app/service/systems/receiving_pending_notice.js#execute;按仓库 subject_config.receiving_pending_inbound_notice.notice_time(默认 08:30,宽限 10 分钟)执行,Redis 当日锁保证一天一次", + "扫描口径:wms_receiving 中 warehouse_id=仓库、is_deleted=0、status<>cancelled、created_at 在 (now-max_hours, now-min_hours] 区间,且(status=receiving 或 storage_status<>all);按 store_id 聚合,每批最多列 20 行(超出提示剩余单数)", + "仓库设置字段:wms_store.subject_config.receiving_pending_inbound_notice = { enabled(默认 false), notice_time(默认 08:30), min_hours(默认 24), max_hours(默认 48,须大于 min_hours) };setting.warehouse.getSettings/saveSettings 文档见 methods/system.json(change 2026.09.15-warehouse-pending-receiving-notice)", + "单测:test/app/service/systems/receiving_pending_notice.test.js(9 用例)全部通过;npx eslint 无告警" + ] + }, { "version": "2026.08.01-warehouse-01", "date": "2026-08-01", diff --git a/methods/system.json b/methods/system.json index 74f59d8..3eaf570 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,7 +1,7 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.125", + "version": "0.3.131", "updatedAt": "2026-09-15", "headers": [ { @@ -14441,6 +14441,48 @@ "type": "string", "required": false, "description": "截单时间,格式 HH:mm,默认 18:00,范围 00:00-23:59;作为最后允许自动分配的时间,开始时间晚于截单时间时截单时间视为次日(跨天窗口)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice", + "type": "object", + "required": false, + "description": "收货未入库提醒配置。开启后每天按提醒时间(notice_time)扫描「创建时间超过 min_hours 且不足 max_hours 仍未完成入库」的收货单:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.enabled", + "type": "boolean", + "required": false, + "description": "是否通知收货未入库(flag:0=关闭,1=开启;默认 0 关闭)。开启后收货未入库提醒定时任务才会在提醒时间执行" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_time", + "type": "string", + "required": false, + "description": "提醒时间,格式 HH:mm,默认 08:30,范围 00:00-23:59;定时任务按此时间(含 10 分钟宽限)每天提醒一次" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.min_hours", + "type": "number", + "required": false, + "description": "超时下限(小时):收货单创建时间距今超过该值才提醒,默认 24,须为大于 0 的整数" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.max_hours", + "type": "number", + "required": false, + "description": "超时上限(小时):收货单创建时间距今小于该值才提醒(超过则不再提醒),默认 48,须为大于 min_hours 的整数" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_template", + "type": "string", + "required": false, + "description": "通知短语(消息第一行,仓库/客服群)。支持变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名(未绑定为「未绑定货主」)/ {store_id} 货主ID / {count} 本批单数 / {min_hours} 超时下限 / {max_hours} 超时上限 / {date} 提醒日期(YYYY-MM-DD)/ {numbers} 本批收货单号。未识别的占位符原样保留;短语后换行逐行列出明细(一行一条,最多 20 行),留空使用默认短语" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.store_notice_template", + "type": "string", + "required": false, + "description": "通知短语(消息第一行,货主群)。变量同 notice_template,留空使用默认短语" } ], "errors": [ @@ -14740,6 +14782,55 @@ "required": false, "source": "body.subject_config", "description": "截单时间,格式 HH:mm,默认 18:00,范围 00:00-23:59;作为最后允许自动分配的时间,开始时间晚于截单时间时截单时间视为次日(跨天窗口)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice", + "type": "object", + "required": false, + "source": "body.subject_config", + "description": "收货未入库提醒配置。开启后每天按提醒时间(notice_time)扫描「创建时间超过 min_hours 且不足 max_hours 仍未完成入库」的收货单:绑定货主的通知货主收货群(未配群回退仓库客服群),未绑定货主的通知仓库客服群" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.enabled", + "type": "boolean", + "required": false, + "source": "body.subject_config", + "description": "是否通知收货未入库(flag:0=关闭,1=开启;默认 0 关闭)。开启后收货未入库提醒定时任务才会在提醒时间执行;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_time", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "提醒时间,格式 HH:mm,默认 08:30,范围 00:00-23:59;定时任务按此时间(含 10 分钟宽限)每天提醒一次;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.min_hours", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "超时下限(小时):收货单创建时间距今超过该值才提醒,默认 24,须为大于 0 的整数;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.max_hours", + "type": "number", + "required": false, + "source": "body.subject_config", + "description": "超时上限(小时):收货单创建时间距今小于该值才提醒(超过则不再提醒),默认 48,须为大于 min_hours 的整数;非法值报 400(字段级校验口径与其它 subject_config 字段一致)" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.notice_template", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "通知短语(消息第一行,仓库/客服群)。支持变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名(未绑定为「未绑定货主」)/ {store_id} 货主ID / {count} 本批单数 / {min_hours} 超时下限 / {max_hours} 超时上限 / {date} 提醒日期(YYYY-MM-DD)/ {numbers} 本批收货单号。未识别的占位符原样保留;短语后换行逐行列出明细(一行一条,最多 20 行),留空使用默认短语;最长 500 字符,超长报 400" + }, + { + "name": "subject_config.receiving_pending_inbound_notice.store_notice_template", + "type": "string", + "required": false, + "source": "body.subject_config", + "description": "通知短语(消息第一行,货主群)。变量同 notice_template,留空使用默认短语;最长 500 字符,超长报 400" } ], "response": [ @@ -35516,6 +35607,288 @@ "description": "不存在或无权操作" } ] + }, + { + "method": "camera.ptzControl", + "description": "云台方向控制(按下):按指定方向持续转动摄像头,需配对调用 camera.ptzStop 停止", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "云台方向(必填,8 个位置):up-上 / down-下 / left-左 / right-右 / upleft-左上 / upright-右上 / downleft-左下 / downright-右下;大小写不敏感,服务端统一转小写校验", + "list": [ + { + "value": "up", + "name": "上" + }, + { + "value": "down", + "name": "下" + }, + { + "value": "left", + "name": "左" + }, + { + "value": "right", + "name": "右" + }, + { + "value": "upleft", + "name": "左上" + }, + { + "value": "upright", + "name": "右上" + }, + { + "value": "downleft", + "name": "左下" + }, + { + "value": "downright", + "name": "右下" + } + ] + }, + { + "name": "speed", + "type": "number", + "required": false, + "source": "body", + "description": "云台转速(可选,1-7 的整数,默认 4)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;云台方向不能为空/不合法;云台转速不是 1-7 的整数;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzControl,请求体 { warehouse_id, cameraId, rtspUrl, action, speed }(warehouse_id 为字符串,与 camera.setOsd 口径一致)", + "本接口与 camera.setOsd 同风格:独立端点 + 独立请求体,**不需要也不接收 computerId**(打印服务按 rtspUrl 定位摄像头,无需房间路由)", + "action 枚举(8 个位置,与打印服务约定,顺序固定):up-上、down-下、left-左、right-右、upleft-左上、upright-右上、downleft-左下、downright-右下", + "交互口径:按下调用本接口(持续转动),松手调用 camera.ptzStop(action 必须与按下时一致);长时间无 stop 指令时摄像头端会持续转动,前端需保证 pointerup/pointerleave 兜底停止", + "rtspUrl 由服务端按摄像头记录组装(rtsp://{username}:{password}@{ip}:554/stream{channel_id},与 camera.setOsd 同口径),入参无需传入", + "代码:app/service/systemMethods/camera.js#ptzControl(systemInit 已声明 _noNeedRight/_noNeedAuth/_noNeedLog 含 ptzControl)-> app/service/systems/camera.js#ptzControl -> app/lib/ptz_client.js#control" + ] + }, + { + "method": "camera.ptzStop", + "description": "云台停止(松手):停止转动,action 必须与按下时一致", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "action", + "type": "string", + "required": true, + "source": "body", + "description": "云台方向(必填,必须与按下时的 action 一致):up-上 / down-下 / left-左 / right-右 / upleft-左上 / upright-右上 / downleft-左下 / downright-右下", + "list": [ + { + "value": "up", + "name": "上" + }, + { + "value": "down", + "name": "下" + }, + { + "value": "left", + "name": "左" + }, + { + "value": "right", + "name": "右" + }, + { + "value": "upleft", + "name": "左上" + }, + { + "value": "upright", + "name": "右上" + }, + { + "value": "downleft", + "name": "左下" + }, + { + "value": "downright", + "name": "右下" + } + ] + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;云台方向不能为空/不合法;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzStop,请求体 { warehouse_id, cameraId, rtspUrl, action }(不带 speed)", + "不需要 computerId,与 camera.setOsd / camera.ptzControl 口径一致", + "action 必须与 camera.ptzControl 时传入的值一致,否则摄像头可能无法停止", + "代码:app/service/systemMethods/camera.js#ptzStop -> app/service/systems/camera.js#ptzStop -> app/lib/ptz_client.js#stop" + ] + }, + { + "method": "camera.ptzPresetGoto", + "description": "云台预置点跳转:跳转到指定预置点(一次调用即可,无需 stop)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "presetId", + "type": "number", + "required": true, + "source": "body", + "description": "预置点编号(必填,1-256 的整数)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;预置点编号不能为空/不是 1-256 的整数;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzPresetGoto,请求体 { warehouse_id, cameraId, rtspUrl, presetId }", + "不需要 computerId,与 camera.setOsd / camera.ptzControl 口径一致", + "预置点跳转是一次性动作,不需要配对 stop;预置点需提前在摄像头端配置", + "代码:app/service/systemMethods/camera.js#ptzPresetGoto -> app/service/systems/camera.js#ptzPresetGoto -> app/lib/ptz_client.js#presetGoto" + ] + }, + { + "method": "camera.ptzPresetSet", + "description": "云台预置点设置:把摄像头当前机位保存为指定预置点(一次调用即可)", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "摄像头ID(必填)" + }, + { + "name": "presetId", + "type": "number", + "required": true, + "source": "body", + "description": "预置点编号(必填,1-256 的整数;已存在的编号会被当前机位覆盖)" + } + ], + "response": [], + "errors": [ + { + "code": "400", + "message": "摄像头ID不能为空;预置点编号不能为空/不是 1-256 的整数;摄像头未配置IP地址" + }, + { + "code": "404", + "message": "摄像头不存在或无权操作" + }, + { + "code": "500", + "message": "打印服务调用失败" + } + ], + "notes": [ + "对接打印服务:POST {printService.url}/camera/ptzPresetSet,请求体 { warehouse_id, cameraId, rtspUrl, presetId }(warehouse_id 为字符串,与 camera.setOsd 口径一致)", + "不需要 computerId,与 camera.setOsd / camera.ptzControl 口径一致", + "语义:把摄像头**当前机位**保存为该 presetId 的预置点(同一编号重复设置即覆盖);常用于「先 ptzControl 转到目标位置 → 再 ptzPresetSet 存点 → 以后用 camera.ptzPresetGoto 一键回到该机位」", + "与 camera.ptzPresetGoto 的区别:ptzPresetSet 写(存点)、ptzPresetGoto 读(跳转);两者均是一次性动作,无需配对 stop", + "代码:app/service/systemMethods/camera.js#ptzPresetSet -> app/service/systems/camera.js#ptzPresetSet -> app/lib/ptz_client.js#presetSet" + ] } ] }, diff --git a/methods/warehouse.json b/methods/warehouse.json index 1ba0a29..3ff8de0 100644 --- a/methods/warehouse.json +++ b/methods/warehouse.json @@ -1,8 +1,8 @@ { "module": "warehouse", "description": "仓库开放 API 统一入口(入站方向:外部 → WMS),供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)。出站通知请参阅 warehouse_notify.json。", - "version": "1.2.0", - "updatedAt": "2026-08-07", + "version": "1.2.2", + "updatedAt": "2026-09-15", "http": { "path": "/warehouse", "method": "POST"