Compare commits

..

No commits in common. "1571de341cb5a7d385f2bfa4ecbb8f6b4922d274" and "aff7a4fe22cb798a25763d0e718004eb833f76a3" have entirely different histories.

21 changed files with 76 additions and 3626 deletions

View File

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

View File

@ -1,325 +0,0 @@
'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<Object>} [{ 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<Object>} { 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<Object>} 打印服务响应
*/
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<Object>} 打印服务响应
*/
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<Object>} 打印服务响应
*/
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<Object>} 打印服务响应
*/
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;

View File

@ -43,7 +43,6 @@ 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: '订单取消失败并触发拦截执行后的通知' }),

View File

@ -45,22 +45,6 @@ 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,
@ -87,7 +71,6 @@ 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) => {
@ -202,117 +185,6 @@ 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'
),
};
};
/**
* 规范化主体配置,确保默认值与字段约束一致。
*
@ -473,9 +345,6 @@ 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 === '') {

View File

@ -1,384 +0,0 @@
// app/schedule/archive_dispatch_orders_to_history.js
'use strict';
/**
* 配送表订单归档到历史表定时任务。
*
* 默认每日凌晨 06:00:00(cron:秒 分 时 日 月 周)在单 worker 中执行一次,
* 把 `wms_order_delivery_{仓库}_dispatch` 中创建时间距今超过 4 个月
* (或迁移进配送表时间距今超过 3 个月)的订单,连同商品明细一起归档到
* `_history` 分表,并同步更新订单索引表 `wms_order_id_location_{仓库}` 的位置指针。
*
* cron / 开关从 config.orderDeliveryArchive 读取(config.default.js 提供默认值),
* 本地环境可在 config.local.js 覆盖为短间隔以便快速验证,不影响生产 06:00 触发时间。
*
* 中断与重跑安全(本任务每日只跑一轮,必须具备"断了也能接着跑"的性质):
* 1. 单批一个事务:写入历史表 + 更新位置指针 + 删除源行 全部成功或全部回滚,
* 不会出现"历史表有数据但配送表没删"的中间态;
* 2. 已迁移的行在提交时即从配送表删除,重新执行时查询不会命中 → 天然幂等续跑;
* 3. 单批失败(死锁等重试耗尽)只跳过该批并推进游标,不中断整轮,未迁移的行留待下一轮;
* 4. 跨进程互斥用 Redis 锁(NX + TTL),进程被杀后锁到期自动释放,下一轮可继续;
* 5. 每批进度写入 Redis(progress key),日志与进度缓存均可观察"跑到哪、迁了多少"。
*/
/** 执行记录缓存 key(最近一次执行) */
const EXECUTION_LOG_CACHE_KEY = 'schedule:archive_dispatch_to_history:last_execution';
/** 执行记录缓存 TTL(秒) */
const EXECUTION_LOG_CACHE_TTL = 300;
/** 执行历史缓存 key(保留最近 N 次) */
const EXECUTION_LOG_HISTORY_CACHE_KEY = 'schedule:archive_dispatch_to_history:history';
/** 执行历史保留条数 */
const EXECUTION_LOG_HISTORY_MAX = 20;
/** 执行历史缓存 TTL(秒) */
const EXECUTION_LOG_HISTORY_TTL = 86400;
/** 跨进程互斥锁 key */
const LOCK_CACHE_KEY = 'schedule:archive_dispatch_to_history:lock';
/** 进度缓存 key(供人工观察断点位置) */
const PROGRESS_CACHE_KEY = 'schedule:archive_dispatch_to_history:progress';
/** 进度缓存 TTL(秒):保留 2 天,便于次日对比上一轮跑到哪里 */
const PROGRESS_CACHE_TTL = 2 * 24 * 60 * 60;
/** 默认 cron:每日凌晨 06:00 */
const DEFAULT_CRON = '0 0 6 * * *';
/** 默认互斥锁 TTL(秒),需覆盖单轮最长执行时间 */
const DEFAULT_LOCK_TTL_SECONDS = 30 * 60;
/**
* 获取 Redis cache 客户端。
*
* @param {Object} app Egg 应用实例。
* @return {Object|null} Redis 客户端或 null。
*/
function getCacheRedisClient(app) {
if (!app || !app.redis || typeof app.redis.get !== 'function') {
return null;
}
try {
return app.redis.get('cache') || null;
} catch (error) {
return null;
}
}
/**
* 获取互斥锁(SET NX EX)。
*
* @param {Object} ctx Egg 上下文。
* @param {number} ttlSeconds 锁 TTL(秒)。
* @return {Promise<boolean>} 是否获取成功;Redis 不可用时返回 true(退化为进程内防重入)。
*/
async function acquireLock(ctx, ttlSeconds) {
const redis = getCacheRedisClient(ctx.app);
if (!redis || typeof redis.set !== 'function') {
ctx.logger.warn('[archive-dispatch-to-history] Redis 不可用,跨进程互斥降级为进程内防重入');
return true;
}
try {
const result = await redis.set(LOCK_CACHE_KEY, String(process.pid || ''), 'EX', ttlSeconds, 'NX');
return result === 'OK';
} catch (error) {
ctx.logger.warn(`[archive-dispatch-to-history] 获取互斥锁失败(按未加锁继续): ${error.message}`);
return true;
}
}
/**
* 释放互斥锁。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async function releaseLock(ctx) {
const redis = getCacheRedisClient(ctx.app);
if (!redis || typeof redis.del !== 'function') {
return;
}
try {
await redis.del(LOCK_CACHE_KEY);
} catch (error) {
ctx.logger.warn(`[archive-dispatch-to-history] 释放互斥锁失败(等待 TTL 过期): ${error.message}`);
}
}
/**
* 写入进度缓存。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} payload 进度内容。
* @return {Promise<void>} 无返回值。
*/
async function writeProgress(ctx, payload) {
try {
if (ctx.app && typeof ctx.app.setCacheAsync === 'function') {
await ctx.app.setCacheAsync(PROGRESS_CACHE_KEY, {
...payload,
updated_at: new Date().toISOString(),
}, PROGRESS_CACHE_TTL);
}
} catch (error) {
ctx.logger.warn(`[archive-dispatch-to-history] 写入进度缓存失败: ${error.message}`);
}
}
/**
* 读取上一轮进度缓存(用于识别"上一轮被中断")。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<Object|null>} 上一轮进度。
*/
async function readProgress(ctx) {
try {
if (ctx.app && typeof ctx.app.getCacheAsync === 'function') {
const cached = await ctx.app.getCacheAsync(PROGRESS_CACHE_KEY);
return cached && typeof cached === 'object' ? cached : null;
}
} catch (error) {
ctx.logger.warn(`[archive-dispatch-to-history] 读取进度缓存失败: ${error.message}`);
}
return null;
}
/**
* 将本次执行日志写入缓存。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} logEntry 日志条目。
* @return {Promise<void>} 无返回值。
*/
async function writeExecutionLogToCache(ctx, logEntry) {
try {
if (ctx.app && typeof ctx.app.setCacheAsync === 'function') {
await ctx.app.setCacheAsync(EXECUTION_LOG_CACHE_KEY, logEntry, EXECUTION_LOG_CACHE_TTL);
}
} catch (error) {
ctx.logger.warn(`[archive-dispatch-to-history] 写入执行日志缓存失败: ${error.message}`);
}
}
/**
* 将本次执行日志追加到历史记录缓存(保留最近 N 次)。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} logEntry 日志条目。
* @return {Promise<void>} 无返回值。
*/
async function appendExecutionHistory(ctx, logEntry) {
try {
if (typeof ctx.app.getCacheAsync !== 'function' || typeof ctx.app.setCacheAsync !== 'function') {
return;
}
const rawHistory = await ctx.app.getCacheAsync(EXECUTION_LOG_HISTORY_CACHE_KEY);
const history = Array.isArray(rawHistory) ? rawHistory : [];
history.unshift(logEntry);
await ctx.app.setCacheAsync(
EXECUTION_LOG_HISTORY_CACHE_KEY,
history.slice(0, EXECUTION_LOG_HISTORY_MAX),
EXECUTION_LOG_HISTORY_TTL
);
} catch (error) {
ctx.logger.warn(`[archive-dispatch-to-history] 写入执行历史缓存失败: ${error.message}`);
}
}
/**
* 提取错误详情,方便定位问题位置。
*
* @param {Error} error 错误对象。
* @return {Object} 错误详情。
*/
function extractErrorDetail(error) {
if (!error) return {};
const detail = {
name: error.name || '',
message: error.message || '',
code: error.code || '',
};
if (error.parent) {
detail.parent = {
name: error.parent.name || '',
message: error.parent.message || '',
code: error.parent.code || '',
sql: error.parent.sql || '',
};
}
if (error.stack) {
detail.stack_top = error.stack.split('\n').slice(0, 4).map(line => line.trim());
}
return detail;
}
/**
* 每日凌晨 06:00 归档配送表超期订单到历史表。
*
* @param {Object} app Egg 应用实例。
* @return {Object} 定时任务定义(含 schedule 与 task)。
*/
module.exports = app => {
const archiveConfig = (app.config && app.config.orderDeliveryArchive) || {};
const archiveCron = typeof archiveConfig.cron === 'string' && archiveConfig.cron
? archiveConfig.cron
: DEFAULT_CRON;
const lockTtlSeconds = Number(archiveConfig.lockTtlSeconds) > 0
? Number(archiveConfig.lockTtlSeconds)
: DEFAULT_LOCK_TTL_SECONDS;
return {
schedule: {
cron: archiveCron,
type: 'worker',
immediate: false,
disable: archiveConfig.enable === false,
},
/**
* 执行配送表订单归档。
*
* 任务失败只记录错误日志,不向上抛出,避免 schedule 崩溃;
* 未归档完成的订单保留在配送表,下一轮(或人工重跑)继续。
*
* @param {Object} ctx Egg 上下文。
* @return {Promise<void>} 无返回值。
*/
async task(ctx) {
const scheduleName = 'archive_dispatch_orders_to_history';
if (ctx.app._archiveDispatchOrdersToHistoryRunning) {
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`);
return;
}
const previousProgress = await readProgress(ctx);
if (previousProgress && previousProgress.status === 'running') {
ctx.logger.warn(
`[${scheduleName}] 检测到上一轮未正常结束(status=running, started_at=${previousProgress.started_at || '-'}),本轮按断点续跑:已迁移订单已从配送表移除,不会重复处理`
);
}
const lockAcquired = await acquireLock(ctx, lockTtlSeconds);
if (!lockAcquired) {
ctx.logger.info(`[${scheduleName}] 未获取到互斥锁,判定其他进程正在执行,本轮跳过`);
return;
}
ctx.app._archiveDispatchOrdersToHistoryRunning = true;
const startedAt = Date.now();
const startedAtIso = new Date(startedAt).toISOString();
let status = 'success';
let errorMessage = '';
let errorDetail = null;
let result = null;
await writeProgress(ctx, {
status: 'running',
started_at: startedAtIso,
trigger: 'schedule',
pid: process.pid,
});
try {
result = await ctx.service.systems.orderDeliveryArchive.archiveDispatchOrdersToHistory({}, {
onBatch: async batch => {
await writeProgress(ctx, {
status: 'running',
started_at: startedAtIso,
trigger: 'schedule',
pid: process.pid,
warehouse_id: batch.warehouseId,
batch_index: batch.batchIndex,
last_id: batch.lastId,
total_selected: batch.summary.selectedCount,
total_archived: batch.summary.archivedCount,
total_items_archived: batch.summary.itemsArchivedCount,
failed_batches: batch.summary.failedBatches,
});
},
});
if (result.totalFailedBatches > 0) {
status = 'partial_failure';
errorMessage = `failedBatches=${result.totalFailedBatches}, failedRows=${result.totalFailedCount}`;
ctx.logger.warn(
`[${scheduleName}] 本轮存在 ${result.totalFailedBatches} 个失败批次(共 ${result.totalFailedCount} 条订单未迁移),已跳过并保留在配送表,下一轮继续`
);
}
if (result.backlogRemaining) {
status = status === 'success' ? 'partial_budget_exhausted' : status;
ctx.logger.warn(
`[${scheduleName}] 单轮时长上限用尽,仍有仓库未处理完(elapsedMs=${result.elapsedMs}),剩余订单将在下一轮继续归档`
);
}
ctx.logger.info(
`[${scheduleName}] 本轮完成 archived=${result.totalArchived} alreadyArchived=${result.totalAlreadyArchived} itemsArchived=${result.totalItemsArchived} selected=${result.totalSelected} failedBatches=${result.totalFailedBatches} elapsedMs=${result.elapsedMs}`
);
} catch (error) {
status = 'error';
errorMessage = error.message;
errorDetail = extractErrorDetail(error);
ctx.logger.error(`[${scheduleName}] 归档失败: ${error.message}`, errorDetail);
} finally {
ctx.app._archiveDispatchOrdersToHistoryRunning = false;
await releaseLock(ctx);
}
const logEntry = {
executed_at: new Date().toISOString(),
duration_ms: Date.now() - startedAt,
status,
error_message: errorMessage,
error_detail: errorDetail,
total_selected: result ? result.totalSelected : 0,
total_archived: result ? result.totalArchived : 0,
total_already_archived: result ? result.totalAlreadyArchived : 0,
total_items_archived: result ? result.totalItemsArchived : 0,
total_failed_batches: result ? result.totalFailedBatches : 0,
total_failed_count: result ? result.totalFailedCount : 0,
backlog_remaining: result ? Boolean(result.backlogRemaining) : false,
warehouse_ids: result ? result.warehouseIds : [],
warehouses: result
? result.results.map(item => ({
warehouse_id: item.warehouseId,
batches: item.batches,
archived: item.archivedCount,
items_archived: item.itemsArchivedCount,
failed_batches: item.failedBatches,
last_id: item.lastId,
stop_reason: item.stopReason,
}))
: [],
};
await writeExecutionLogToCache(ctx, logEntry);
await appendExecutionHistory(ctx, logEntry);
await writeProgress(ctx, {
status,
started_at: startedAtIso,
finished_at: new Date().toISOString(),
trigger: 'schedule',
pid: process.pid,
elapsed_ms: logEntry.duration_ms,
total_archived: logEntry.total_archived,
total_failed_batches: logEntry.total_failed_batches,
backlog_remaining: logEntry.backlog_remaining,
warehouses: logEntry.warehouses,
});
ctx.logger.info(
`[${scheduleName}] 执行日志已写入缓存 key=${EXECUTION_LOG_CACHE_KEY} history=${EXECUTION_LOG_HISTORY_CACHE_KEY} progress=${PROGRESS_CACHE_KEY}`
);
},
};
};

View File

@ -1,54 +0,0 @@
'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<void>} 无返回值。
*/
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;
}
},
};

View File

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

View File

@ -3,13 +3,6 @@
const Service = require('egg').Service;
const { parseWhereConditions } = require('../../lib/query_condition_parser');
/** 出站推送失败自动重推:默认失败时间窗(毫秒)——超窗口的消息不再补推,避免陈旧消息打扰用户 */
const DEFAULT_PUSH_RETRY_WINDOW_MS = 2 * 60 * 60 * 1000;
/** 出站推送失败自动重推:默认单轮最多重推条数(定时任务每 3 分钟扫一次) */
const DEFAULT_PUSH_RETRY_LIMIT = 20;
/** 出站推送失败自动重推:单轮条数硬上限 */
const MAX_PUSH_RETRY_LIMIT = 200;
/**
* 站内信消息查询/管理服务。
* 提供消息列表、详情、对话链、回复、统计等管理功能。
@ -409,8 +402,7 @@ class InboxMessageService extends Service {
/**
* 手动重推失败(push_status=3)的站内信消息。
* 重置为待推送状态(push_status=0)并触发异步推送;
* 推送结果回写到同一记录(复用原记录,不新建回执记录)。
* 重置为待推送状态(push_status=0)并触发异步推送。
* @param {Object} params 重推参数。
* @param {number} params.warehouseId 仓库ID(必填,服务端上下文注入)。
* @param {number} params.id 消息ID。
@ -447,9 +439,28 @@ class InboxMessageService extends Service {
{ where: { id } }
);
// 触发异步推送(复用原记录回写推送结果)
// 回执记录 ext_id 形如 sys:ack:{原消息ext_id},反解出原消息 ext_id 以复用推送链路
const extId = String(record.ext_id || '');
const originalExtId = extId.startsWith('sys:ack:') ? extId.slice(8) : extId;
const hasUser = Boolean(record.user_id && record.user_name);
const pushData = {
warehouse_id: warehouseId,
ext_id: originalExtId,
parent_id: record.parent_id || null,
group_id: record.group_id || '',
group_name: record.group_name || '',
user_id: record.user_id || '',
user_name: record.user_name || '',
ext_data: record.ext_data || null,
};
// 触发异步推送
setImmediate(() => {
this._repush(record).catch(async err => {
ctx.service.inbox.processor.writeOutboundReply(
pushData,
record.content || '',
hasUser ? 'ai_reply' : 'system'
).catch(async err => {
ctx.logger.error(`[inbox] 手动重推异步推送异常 id=${id}: ${err.message}`);
// 推送前校验失败时回写失败状态,避免消息卡在待推送
try {
@ -470,124 +481,6 @@ class InboxMessageService extends Service {
message: '已重置为待推送状态,正在异步重推',
};
}
/**
* 重推一条已存在的出站消息记录(推送结果回写到该记录本身,不新建记录)。
*
* 与直接调用 processor.writeOutboundReply 的区别:
* - 传 reuse_message_id,让其跳过按 `sys:ack:{ext_id}` 查建,直接复用该记录;
* - 否则 sys:notice:* 类型(warehouseNotify 系统通知)会被另建一条 sys:ack:sys:notice:*
* 记录推送,原记录状态永远停留在失败/待推送,重推也无法继续。
* 本方法推送期间不改动记录状态:推送完成由推送链路回写 2/3,进程中断则保持 3 等下一轮。
*
* @param {Object} record 消息记录(InboxMessage 行,Sequelize 实例或 raw 对象)。
* @return {Promise<void>} 推送完成(结果已回写)。
*/
async _repush(record) {
const { ctx } = this;
const extId = String(record.ext_id || '');
// 回执记录 ext_id 形如 sys:ack:{原消息ext_id},反解出原消息 ext_id 以复用推送链路
const originalExtId = extId.startsWith('sys:ack:') ? extId.slice(8) : extId;
const hasUser = Boolean(record.user_id && record.user_name);
await ctx.service.inbox.processor.writeOutboundReply({
warehouse_id: Number(record.warehouse_id) || 0,
ext_id: originalExtId,
parent_id: record.parent_id || null,
group_id: record.group_id || '',
group_name: record.group_name || '',
user_id: record.user_id || '',
user_name: record.user_name || '',
ext_data: record.ext_data || null,
reuse_message_id: Number(record.id) || 0,
}, record.content || '', hasUser ? 'ai_reply' : 'system');
}
/**
* 批量重推「推送失败」的出站消息(供定时任务调用)。
*
* 规则:
* 1. 只处理失败时间(created_at)在窗口内的记录,默认 2 小时;超窗口不再补推;
* 2. 逐条串行重推并等待结果回写,单条异常不影响其余记录;
* 3. 重推期间记录保持失败状态,进程中断时下一轮仍能被扫到(不丢消息);
* 4. 缺少 warehouse_id / group_id / group_name / content 的记录无法重放,跳过并计数。
*
* @param {Object} [params] 查询参数。
* @param {number} [params.windowMs] 失败时间窗(毫秒),默认 config.inbox.pushRetryWindowMs。
* @param {number} [params.limit] 单轮最多重推条数,默认 config.inbox.pushRetryLimit。
* @return {Promise<Object>} { scanned, retried, succeeded, failed, skipped }。
*/
async retryFailed(params = {}) {
const { ctx } = this;
const { Op } = ctx.app.Sequelize;
const { InboxMessage } = ctx.model;
const inboxConfig = (ctx.app.config && ctx.app.config.inbox) || {};
const configuredWindow = Number(inboxConfig.pushRetryWindowMs);
const windowMs = Number(params.windowMs) > 0
? Number(params.windowMs)
: (configuredWindow > 0 ? configuredWindow : DEFAULT_PUSH_RETRY_WINDOW_MS);
const configuredLimit = Number(inboxConfig.pushRetryLimit);
const rawLimit = Number(params.limit) > 0
? Number(params.limit)
: (configuredLimit > 0 ? configuredLimit : DEFAULT_PUSH_RETRY_LIMIT);
const limit = Math.min(MAX_PUSH_RETRY_LIMIT, Math.max(1, Math.trunc(rawLimit)));
// 先补早失败的消息(更快接近 2 小时窗口边界)
const rows = await InboxMessage.findAll({
where: {
direction: 'outbound',
push_status: 3,
created_at: { [Op.gte]: new Date(Date.now() - windowMs) },
},
attributes: [
'id', 'warehouse_id', 'ext_id', 'parent_id',
'group_id', 'group_name', 'user_id', 'user_name',
'ext_data', 'content',
],
order: [[ 'created_at', 'ASC' ], [ 'id', 'ASC' ]],
limit,
raw: true,
});
const summary = { scanned: rows.length, retried: 0, succeeded: 0, failed: 0, skipped: 0 };
for (const row of rows) {
if (!(Number(row.warehouse_id) > 0) || !row.group_id || !row.group_name || !row.content) {
summary.skipped++;
ctx.logger.warn(`[inbox] 自动重推跳过消息 id=${row.id}(缺少 warehouse_id/group_id/group_name/content,无法重放)`);
continue;
}
try {
await this._repush(row);
summary.retried++;
const fresh = await InboxMessage.findOne({
where: { id: row.id },
attributes: [ 'push_status' ],
raw: true,
});
if (fresh && Number(fresh.push_status) === 2) {
summary.succeeded++;
} else {
summary.failed++;
}
// 已重试次数仅作观测;失败不影响主流程
try {
await InboxMessage.increment('retry_count', { where: { id: row.id } });
} catch (countErr) {
ctx.logger.warn(`[inbox] 自动重推计数失败 id=${row.id}: ${countErr.message}`);
}
} catch (error) {
summary.failed++;
ctx.logger.warn(`[inbox] 自动重推异常 id=${row.id}: ${error.message}`);
}
}
return summary;
}
}
module.exports = InboxMessageService;

View File

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

View File

@ -6,9 +6,9 @@ class CameraService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,detail,setOsd,ptzControl,ptzStop,ptzPresetGoto,ptzPresetSet';
const _noNeedRight = 'list,detail,setOsd';
const _noNeedLog = '*';
const _noNeedAuth = 'list,detail,setOsd,ptzControl,ptzStop,ptzPresetGoto,ptzPresetSet';
const _noNeedAuth = 'list,detail,setOsd';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -47,62 +47,6 @@ 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<Object>} 统一响应
*/
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<Object>} 统一响应
*/
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<Object>} 统一响应
*/
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<Object>} 统一响应
*/
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 || {};

View File

@ -164,182 +164,6 @@ class CameraService extends Service {
};
}
/**
* 查询本仓库摄像头(云台控制复用,带录像服务器认证信息兜底)
* @param {number|string} id - 摄像头ID
* @param {number} warehouseId - 仓库ID
* @return {Promise<Object>} 摄像头记录
*/
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<Object>} 下发结果
*/
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<Object>} 下发结果
*/
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<Object>} 下发结果
*/
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<Object>} 下发结果
*/
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;

View File

@ -28,7 +28,6 @@ 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',
@ -75,16 +74,6 @@ 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',

View File

@ -1,795 +0,0 @@
'use strict';
const MainService = require('../main');
/** 单批处理条数(与 current → dispatch 迁移保持一致,单批一个事务) */
const MAX_BATCH_SIZE = 1000;
/** 归档门槛:订单创建时间(create_at)距今超过该月数即归档 */
const DEFAULT_ARCHIVE_AFTER_MONTHS = 4;
/** 归档门槛:订单迁移进配送表(dispath_time)距今超过该月数即归档 */
const DEFAULT_DISPATCH_STAY_MONTHS = 3;
/** 单仓库单轮最多处理的批次数(异常情况下防止死循环) */
const DEFAULT_MAX_BATCHES_PER_WAREHOUSE = 200;
/** 单轮总时长上限(毫秒):超过后停止本轮,剩余订单下一轮继续 */
const DEFAULT_MAX_RUN_MS = 30 * 60 * 1000;
/** 单批查询超时(毫秒) */
const DEFAULT_QUERY_TIMEOUT_MS = 60 * 1000;
/** 单批事务遇到死锁/锁等待时的最大尝试次数 */
const DEFAULT_BATCH_MAX_ATTEMPTS = 3;
/** 重试基础退避毫秒数(按尝试次数线性放大) */
const BATCH_RETRY_BASE_DELAY_MS = 50;
/** 历史表位置标识(写入订单索引表 wms_order_id_location_{仓库}.location) */
const HISTORY_LOCATION = 'history';
/** 配送域分表名匹配(仅 _dispatch 参与归档) */
const DISPATCH_TABLE_PATTERN = /^wms_order_delivery_(\d+)_dispatch$/;
/** 可重试的数据库锁错误码 */
const RETRYABLE_DATABASE_ERROR_CODES = new Set([ 1205, 1213, 'ER_LOCK_WAIT_TIMEOUT', 'ER_LOCK_DEADLOCK' ]);
/**
* 按自然月回退时间(与 MySQL DATE_SUB(NOW(), INTERVAL n MONTH) 语义一致:
* 目标月份天数不足时取该月最后一天,如 3/31 回退 1 个月 → 2/28)。
*
* @param {Date} baseDate 基准时间。
* @param {number} months 回退月数(正整数)。
* @return {Date} 回退后的时间。
*/
function subtractMonths(baseDate, months) {
const base = baseDate instanceof Date ? baseDate : new Date(baseDate);
const normalizedMonths = Math.max(0, Math.floor(Number(months) || 0));
if (normalizedMonths === 0) {
return new Date(base.getTime());
}
const day = base.getDate();
const target = new Date(base.getTime());
// 先落到 1 号再回退月份,避免 9/30 回退 1 个月时被 JS 进位成 10/30
target.setDate(1);
target.setMonth(target.getMonth() - normalizedMonths);
const daysInTargetMonth = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
target.setDate(Math.min(day, daysInTargetMonth));
return target;
}
/**
* 规范化正整数配置项。
*
* @param {*} value 原始值。
* @param {number} fallback 回退值。
* @return {number} 规范化结果。
*/
function normalizePositiveNumber(value, fallback) {
const parsed = Number(value);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
/**
* 配送表订单归档到历史表的同步服务。
*
* 归档链路(单批一个事务,全部成功或全部回滚):
* 1. 从 `wms_order_delivery_{仓库}_dispatch` 按主键游标取候选订单
* (create_at 距今 > 4 个月,或 dispath_time 距今 > 3 个月);
* 2. 复制订单行到 `_history`(剔除历史表不存在的 dispatch_lane / dispath_time,
* 写入 archive_time = 当前时刻),id 原样复制(多表共用 id 契约);
* 3. 同步复制商品明细 `wms_order_items_{仓库}_dispatch` → `_history`;
* 4. 更新订单索引表 `wms_order_id_location_{仓库}` 的 location 为 history;
* 5. 硬删除 dispatch 源行(先子表后主表)。
*
* 幂等与可续跑:每批提交后源行已消失,重跑查询不会命中;若历史表已存在同 id
* 记录(上一轮中断或人工补数的残留),则跳过写入但仍清理源行,保证重复执行安全。
*/
class OrderDeliveryArchiveService extends MainService {
/**
* 读取归档任务默认参数(config.orderDeliveryArchive 优先)。
*
* @return {Object} 归档参数。
*/
getArchiveDefaults() {
const config = (this.app && this.app.config && this.app.config.orderDeliveryArchive) || {};
return {
archiveAfterMonths: normalizePositiveNumber(config.archiveAfterMonths, DEFAULT_ARCHIVE_AFTER_MONTHS),
dispatchStayMonths: normalizePositiveNumber(config.dispatchStayMonths, DEFAULT_DISPATCH_STAY_MONTHS),
batchSize: Math.min(
normalizePositiveNumber(config.batchSize, MAX_BATCH_SIZE),
MAX_BATCH_SIZE
),
maxBatchesPerWarehouse: normalizePositiveNumber(
config.maxBatchesPerWarehouse,
DEFAULT_MAX_BATCHES_PER_WAREHOUSE
),
maxRunMs: normalizePositiveNumber(config.maxRunMs, DEFAULT_MAX_RUN_MS),
queryTimeoutMs: normalizePositiveNumber(config.queryTimeoutMs, DEFAULT_QUERY_TIMEOUT_MS),
batchMaxAttempts: normalizePositiveNumber(config.batchMaxAttempts, DEFAULT_BATCH_MAX_ATTEMPTS),
};
}
/**
* 合并调用方参数与默认参数。
*
* @param {Object} options 调用方参数。
* @return {Object} 合并后的参数。
*/
buildArchiveOptions(options = {}) {
const defaults = this.getArchiveDefaults();
const source = this.isPlainObject(options) ? options : {};
return {
archiveAfterMonths: normalizePositiveNumber(source.archiveAfterMonths, defaults.archiveAfterMonths),
dispatchStayMonths: normalizePositiveNumber(source.dispatchStayMonths, defaults.dispatchStayMonths),
batchSize: Math.min(normalizePositiveNumber(source.batchSize, defaults.batchSize), MAX_BATCH_SIZE),
maxBatchesPerWarehouse: normalizePositiveNumber(source.maxBatchesPerWarehouse, defaults.maxBatchesPerWarehouse),
maxRunMs: normalizePositiveNumber(source.maxRunMs, defaults.maxRunMs),
queryTimeoutMs: normalizePositiveNumber(source.queryTimeoutMs, defaults.queryTimeoutMs),
batchMaxAttempts: normalizePositiveNumber(source.batchMaxAttempts, defaults.batchMaxAttempts),
};
}
/**
* 构造归档时间门槛。
*
* 使用应用进程时钟(而非数据库 NOW()):dispath_time / create_at 均由应用以
* `new Date()` 写入,两者同源比较可避免数据库时区与服务时区不一致带来的偏差。
*
* @param {Date} [now] 基准时间,默认当前时间。
* @param {Object} options 归档参数。
* @return {{ now: Date, createThreshold: Date, dispatchThreshold: Date }} 门槛集合。
*/
buildArchiveThresholds(now = new Date(), options = {}) {
const resolved = this.buildArchiveOptions(options);
const baseTime = now instanceof Date ? now : new Date();
return {
now: baseTime,
createThreshold: subtractMonths(baseTime, resolved.archiveAfterMonths),
dispatchThreshold: subtractMonths(baseTime, resolved.dispatchStayMonths),
};
}
/**
* 规范化仓库ID列表。
*
* @param {Object} data 请求参数。
* @return {Array<number>} 仓库ID列表。
*/
normalizeWarehouseIds(data = {}) {
if (!this.isPlainObject(data)) {
return [];
}
const candidateValues = Array.isArray(data.warehouseIds)
? data.warehouseIds
: [ data.warehouseId ?? data.warehouse_id ].filter(value => value !== undefined && value !== null && value !== '');
return Array.from(new Set(candidateValues
.map(value => Number(value))
.filter(value => Number.isFinite(value) && value > 0)))
.sort((left, right) => left - right);
}
/**
* 获取当前库中存在配送分表的仓库ID列表。
*
* @return {Promise<Array<number>>} 仓库ID列表。
*/
async listDispatchWarehouseIds() {
const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!factory || typeof factory.listManagedTableNames !== 'function') {
return [];
}
const tableNames = await factory.listManagedTableNames();
return Array.from(new Set((Array.isArray(tableNames) ? tableNames : [])
.map(tableName => {
const matched = DISPATCH_TABLE_PATTERN.exec(String(tableName || ''));
return matched ? Number(matched[1]) : null;
})
.filter(value => Number.isFinite(value) && value > 0)))
.sort((left, right) => left - right);
}
/**
* 获取归档所需的模型集合。
*
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object>} 模型集合。
*/
async getArchiveModels(warehouseId) {
const orderFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
const itemsFactory = this.ctx.model && this.ctx.model.OrderItemsFactory;
if (!orderFactory
|| typeof orderFactory.getDispatchModel !== 'function'
|| typeof orderFactory.getHistoryModel !== 'function') {
throw new Error('订单工厂未初始化,无法获取配送表/历史表模型');
}
if (!itemsFactory
|| typeof itemsFactory.getDispatchModel !== 'function'
|| typeof itemsFactory.getHistoryModel !== 'function') {
throw new Error('订单商品工厂未初始化,无法获取配送表/历史表模型');
}
return {
dispatchOrderModel: await orderFactory.getDispatchModel(warehouseId),
historyOrderModel: await orderFactory.getHistoryModel(warehouseId),
dispatchItemModel: await itemsFactory.getDispatchModel(warehouseId),
historyItemModel: await itemsFactory.getHistoryModel(warehouseId),
};
}
/**
* 构造候选订单查询条件。
*
* 仅取 _dispatch 分表内满足下列任一条件的订单:
* - 创建时间距今超过 archiveAfterMonths(默认 4 个月);
* - 迁移进配送表时间(dispath_time)距今超过 dispatchStayMonths(默认 3 个月)。
*
* 注意:dispath_time 为 NULL 的存量订单由上述 OR 的另一分支(create_at)兜底,
* 无需显式 IS NULL 判断 —— SQL 三值逻辑下 `dispath_time < ?` 对 NULL 结果为
* UNKNOWN,天然不会命中。
*
* 游标条件用主键 id(条件列 create_at / dispath_time 均无索引),
* 避免生产大表上的全表扫描 + filesort。
*
* @param {number} warehouseId 仓库ID。
* @param {number} lastId 上一批处理到的最大 id(0 表示从头开始)。
* @param {Object} thresholds 归档时间门槛。
* @return {Object} Sequelize where 条件。
*/
buildCandidateWhere(warehouseId, lastId, thresholds) {
const { Op } = this.ctx.app.Sequelize;
const normalizedLastId = Number(lastId);
return {
warehouse_id: warehouseId,
id: Number.isFinite(normalizedLastId) && normalizedLastId > 0
? { [Op.gt]: normalizedLastId }
: { [Op.gt]: 0 },
[Op.or]: [
{ dispath_time: { [Op.lt]: thresholds.dispatchThreshold } },
{ create_at: { [Op.lt]: thresholds.createThreshold } },
],
};
}
/**
* 构造 Sequelize 查询参数(事务 + 超时)。
*
* @param {Object|null} transaction 事务对象。
* @param {number} [queryTimeoutMs] 查询超时时间。
* @return {Object} Sequelize 查询参数。
*/
buildQueryOptions(transaction, queryTimeoutMs) {
const queryOptions = {};
if (transaction) {
queryOptions.transaction = transaction;
}
const normalizedTimeoutMs = Number(queryTimeoutMs);
if (Number.isFinite(normalizedTimeoutMs) && normalizedTimeoutMs > 0) {
queryOptions.timeout = normalizedTimeoutMs;
}
return queryOptions;
}
/**
* 构造写入历史表的订单行。
*
* 历史表比配送表少两列,必须剔除,否则 Sequelize 属性映射会静默丢弃/报错:
* - dispatch_lane:配送域车道,仅 dispatch 分表存在;
* - dispath_time:迁移进配送表的时间,仅 dispatch 分表存在
* (迁出/迁入时刻统一由 archive_time 表达)。
*
* @param {Object} row 配送表订单行。
* @param {Date} archiveTime 归档时间。
* @return {Object} 可写入历史表的订单行。
*/
buildHistoryOrderRow(row, archiveTime) {
const payload = { ...(row || {}) };
delete payload.dispatch_lane;
delete payload.dispath_time;
payload.archive_time = archiveTime;
return payload;
}
/**
* 构造写入历史表的商品明细行。
*
* 商品配送表与历史表列完全一致(历史表仅多 archive_time),无需剔除字段。
*
* @param {Object} row 配送表商品明细行。
* @param {Date} archiveTime 归档时间。
* @return {Object} 可写入历史表的商品明细行。
*/
buildHistoryItemRow(row, archiveTime) {
return {
...(row || {}),
archive_time: archiveTime,
};
}
/**
* 识别可重试的数据库锁错误。
*
* @param {Error} error 运行时错误。
* @return {{ retryable: boolean, category: string, message: string }} 分类结果。
*/
getArchiveErrorInfo(error) {
const errorMessage = String((error && error.message) || '');
const errorName = String((error && error.name) || '');
const parentError = error && error.parent ? error.parent : null;
const errorCode = parentError && (parentError.code || parentError.errno)
? parentError.code || parentError.errno
: error && (error.code || error.errno);
const normalizedMessage = errorMessage.toLowerCase();
if (errorName === 'SequelizeTimeoutError' || errorName === 'TimeoutError' || errorCode === 'ETIMEDOUT') {
return { retryable: true, category: 'timeout', message: errorMessage };
}
if (errorName === 'SequelizeDatabaseError') {
if (normalizedMessage.includes('lock wait timeout')) {
return { retryable: true, category: 'lock_wait_timeout', message: errorMessage };
}
if (RETRYABLE_DATABASE_ERROR_CODES.has(errorCode) || normalizedMessage.includes('deadlock')) {
return { retryable: true, category: 'deadlock', message: errorMessage };
}
}
return { retryable: false, category: 'other', message: errorMessage };
}
/**
* 回滚事务(忽略回滚自身异常,避免掩盖原始错误)。
*
* @param {Object} transaction 事务对象。
* @return {Promise<void>} 无返回值。
*/
async rollbackQuietly(transaction) {
if (!transaction || typeof transaction.rollback !== 'function') {
return;
}
try {
await transaction.rollback();
} catch (error) {
this.ctx.logger.warn(`[archive-dispatch-to-history] 事务回滚失败: ${error.message}`);
}
}
/**
* 单批归档:查询候选 → 写历史表 → 更新位置指针 → 删除源行,全部在一个事务内完成。
*
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [params] 单批参数。
* @param {number} [params.lastId] 上一批处理到的最大 id。
* @param {number} [params.batchSize] 单批条数。
* @param {Object} [params.thresholds] 归档时间门槛。
* @param {Object} [options] 归档参数。
* @return {Promise<Object>} 单批结果。
*/
async archiveDispatchBatch(warehouseId, params = {}, options = {}) {
const resolved = this.buildArchiveOptions(options);
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw new Error('仓库ID不能为空');
}
const batchSize = Math.min(normalizePositiveNumber(params.batchSize, resolved.batchSize), MAX_BATCH_SIZE);
const lastId = Number(params.lastId) > 0 ? Number(params.lastId) : 0;
const thresholds = params.thresholds || this.buildArchiveThresholds(new Date(), resolved);
const archiveTime = new Date();
const { Op } = this.ctx.app.Sequelize;
// 序列表初始化可能执行 DDL(隐式提交),必须在事务外完成:
// 位置指针与历史表写入必须同事务原子完成,无索引表宁可整批失败重试。
await this.ctx.model.OrderDeliveryFactory.ensureLocationSequenceTable(normalizedWarehouseId);
const transaction = await this.ctx.model.transaction();
try {
const models = await this.getArchiveModels(normalizedWarehouseId);
// 加行锁读取候选:归档会删除源行,锁住候选可避免与并发修改(如拦截确认)
// 交错导致"归档了旧值、删掉了新值"。
const candidateRows = await models.dispatchOrderModel.findAll({
where: this.buildCandidateWhere(normalizedWarehouseId, lastId, thresholds),
order: [[ 'id', 'ASC' ]],
limit: batchSize,
raw: true,
lock: transaction.LOCK.UPDATE,
...this.buildQueryOptions(transaction, resolved.queryTimeoutMs),
});
const rows = Array.isArray(candidateRows) ? candidateRows : [];
const orderIds = Array.from(new Set(rows
.map(row => Number(row && row.id))
.filter(value => Number.isFinite(value) && value > 0)));
if (orderIds.length === 0) {
await transaction.commit();
return {
warehouseId: normalizedWarehouseId,
lastId,
maxCandidateId: lastId,
selectedCount: 0,
archivedCount: 0,
alreadyArchivedCount: 0,
itemsSelectedCount: 0,
itemsArchivedCount: 0,
hasMore: false,
};
}
const maxCandidateId = Math.max(...orderIds);
// 幂等保护:历史表已存在同 id 记录(上一轮中断残留 / 人工补数)时不再重复写入,
// 但仍清理源行,保证本任务重复执行或跨轮次执行结果一致。
const existingHistoryRows = await models.historyOrderModel.findAll({
where: { id: { [Op.in]: orderIds } },
attributes: [ 'id' ],
raw: true,
...this.buildQueryOptions(transaction, resolved.queryTimeoutMs),
});
const existingHistoryIdSet = new Set((Array.isArray(existingHistoryRows) ? existingHistoryRows : [])
.map(row => Number(row && row.id)));
const rowsToArchive = rows.filter(row => !existingHistoryIdSet.has(Number(row.id)));
// 商品明细:按 order_id 一并搬迁(子表同步迁入)
const dispatchItems = await models.dispatchItemModel.findAll({
where: { order_id: { [Op.in]: orderIds } },
order: [[ 'id', 'ASC' ]],
raw: true,
...this.buildQueryOptions(transaction, resolved.queryTimeoutMs),
});
const itemRows = Array.isArray(dispatchItems) ? dispatchItems : [];
const itemIds = Array.from(new Set(itemRows
.map(row => Number(row && row.id))
.filter(value => Number.isFinite(value) && value > 0)));
let itemsToArchive = itemRows;
if (itemIds.length > 0) {
const existingHistoryItems = await models.historyItemModel.findAll({
where: { id: { [Op.in]: itemIds } },
attributes: [ 'id' ],
raw: true,
...this.buildQueryOptions(transaction, resolved.queryTimeoutMs),
});
const existingItemIdSet = new Set((Array.isArray(existingHistoryItems) ? existingHistoryItems : [])
.map(row => Number(row && row.id)));
itemsToArchive = itemRows.filter(row => !existingItemIdSet.has(Number(row.id)));
}
if (rowsToArchive.length > 0) {
await models.historyOrderModel.bulkCreate(
rowsToArchive.map(row => this.buildHistoryOrderRow(row, archiveTime)),
this.buildQueryOptions(transaction, resolved.queryTimeoutMs)
);
}
if (itemsToArchive.length > 0) {
await models.historyItemModel.bulkCreate(
itemsToArchive.map(row => this.buildHistoryItemRow(row, archiveTime)),
this.buildQueryOptions(transaction, resolved.queryTimeoutMs)
);
}
// 订单索引表位置指针 dispatch → history,与历史表写入同事务,
// 保证「订单去向」与数据所在表位原子一致。
const locationFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!locationFactory || typeof locationFactory.updateOrderLocation !== 'function') {
throw new Error('订单工厂缺少 updateOrderLocation,无法同步订单索引表位置');
}
for (const orderId of orderIds) {
await locationFactory.updateOrderLocation(orderId, normalizedWarehouseId, HISTORY_LOCATION, transaction);
}
// 删除源行:先子表后主表
if (itemIds.length > 0) {
await models.dispatchItemModel.destroy({
where: { id: { [Op.in]: itemIds } },
...this.buildQueryOptions(transaction, resolved.queryTimeoutMs),
});
}
await models.dispatchOrderModel.destroy({
where: { id: { [Op.in]: orderIds } },
...this.buildQueryOptions(transaction, resolved.queryTimeoutMs),
});
await transaction.commit();
return {
warehouseId: normalizedWarehouseId,
lastId: maxCandidateId,
maxCandidateId,
selectedCount: orderIds.length,
archivedCount: rowsToArchive.length,
alreadyArchivedCount: orderIds.length - rowsToArchive.length,
itemsSelectedCount: itemIds.length,
itemsArchivedCount: itemsToArchive.length,
hasMore: rows.length >= batchSize,
};
} catch (error) {
await this.rollbackQuietly(transaction);
throw error;
}
}
/**
* 归档指定仓库的配送表订单(按主键游标循环分批,直到无候选或达到限额)。
*
* @param {number|string} warehouseId 仓库ID。
* @param {Object} [options] 归档参数。
* @param {Function} [options.onBatch] 单批完成回调(用于上报进度)。
* @param {Function} [options.shouldStop] 外部中断判断回调。
* @return {Promise<Object>} 仓库归档汇总。
*/
async archiveDispatchOrdersForWarehouse(warehouseId, options = {}) {
const resolved = this.buildArchiveOptions(options);
const normalizedWarehouseId = Number(warehouseId);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
throw new Error('仓库ID不能为空');
}
const thresholds = options.thresholds || this.buildArchiveThresholds(new Date(), resolved);
const deadlineAt = options.deadlineAt > 0 ? Number(options.deadlineAt) : 0;
const onBatch = typeof options.onBatch === 'function' ? options.onBatch : null;
const shouldStop = typeof options.shouldStop === 'function' ? options.shouldStop : null;
const summary = {
warehouseId: normalizedWarehouseId,
batches: 0,
selectedCount: 0,
archivedCount: 0,
alreadyArchivedCount: 0,
itemsArchivedCount: 0,
failedBatches: 0,
failedCount: 0,
lastId: Number(options.lastId) > 0 ? Number(options.lastId) : 0,
stopReason: '',
};
for (let batchIndex = 0; batchIndex < resolved.maxBatchesPerWarehouse; batchIndex++) {
if (shouldStop && shouldStop()) {
summary.stopReason = 'external_stop';
break;
}
if (deadlineAt > 0 && Date.now() >= deadlineAt) {
summary.stopReason = 'run_budget_exhausted';
break;
}
let batchResult = null;
let lastError = null;
for (let attempt = 1; attempt <= resolved.batchMaxAttempts; attempt++) {
try {
batchResult = await this.archiveDispatchBatch(normalizedWarehouseId, {
lastId: summary.lastId,
batchSize: resolved.batchSize,
thresholds,
}, resolved);
break;
} catch (error) {
lastError = error;
const errorInfo = this.getArchiveErrorInfo(error);
if (!errorInfo.retryable || attempt >= resolved.batchMaxAttempts) {
break;
}
this.ctx.logger.warn(
`[archive-dispatch-to-history] 仓库 ${normalizedWarehouseId} 第 ${batchIndex + 1} 批遇到 ${errorInfo.category},`
+ `重试 ${attempt}/${resolved.batchMaxAttempts}: ${errorInfo.message}`
);
await new Promise(resolve => setTimeout(resolve, BATCH_RETRY_BASE_DELAY_MS * attempt));
}
}
if (!batchResult) {
// 单批彻底失败:记录后越过该批(游标推进到候选范围内已知的最大 id),
// 避免整轮卡死在同一批;未迁移的行保留在配送表,下一轮继续尝试。
summary.failedBatches += 1;
summary.stopReason = 'batch_failure';
this.ctx.logger.error(
`[archive-dispatch-to-history] 仓库 ${normalizedWarehouseId} 第 ${batchIndex + 1} 批归档失败,已跳过该批: `
+ `${lastError ? lastError.message : 'unknown error'}`
);
const skippedLastId = await this.resolveFailureCursor(normalizedWarehouseId, summary.lastId, thresholds, resolved);
summary.failedCount += skippedLastId.failedCount;
summary.lastId = skippedLastId.lastId;
if (!skippedLastId.advanced) {
break;
}
continue;
}
summary.batches += 1;
summary.selectedCount += batchResult.selectedCount;
summary.archivedCount += batchResult.archivedCount;
summary.alreadyArchivedCount += batchResult.alreadyArchivedCount;
summary.itemsArchivedCount += batchResult.itemsArchivedCount;
summary.lastId = batchResult.lastId;
if (onBatch) {
await onBatch({ ...batchResult, batchIndex: batchIndex + 1, summary: { ...summary } });
}
// 未取满一批(hasMore=false)说明候选已清空;取满但下一轮可能仍有候选,继续循环
if (batchResult.selectedCount === 0 || !batchResult.hasMore) {
summary.stopReason = 'no_more_candidates';
break;
}
}
if (!summary.stopReason) {
summary.stopReason = 'max_batches_reached';
}
return summary;
}
/**
* 单批失败后推进游标:取该批候选范围内的最大 id,返回下一次查询起点。
*
* @param {number} warehouseId 仓库ID。
* @param {number} lastId 当前游标。
* @param {Object} thresholds 归档时间门槛。
* @param {Object} options 归档参数。
* @return {Promise<{ lastId: number, failedCount: number, advanced: boolean }>} 游标结果。
*/
async resolveFailureCursor(warehouseId, lastId, thresholds, options) {
try {
const models = await this.getArchiveModels(warehouseId);
const rows = await models.dispatchOrderModel.findAll({
where: this.buildCandidateWhere(warehouseId, lastId, thresholds),
attributes: [ 'id' ],
order: [[ 'id', 'ASC' ]],
limit: options.batchSize,
raw: true,
...this.buildQueryOptions(null, options.queryTimeoutMs),
});
const idList = (Array.isArray(rows) ? rows : [])
.map(row => Number(row && row.id))
.filter(value => Number.isFinite(value) && value > 0);
if (idList.length === 0) {
return { lastId, failedCount: 0, advanced: false };
}
return {
lastId: Math.max(...idList),
failedCount: idList.length,
advanced: true,
};
} catch (error) {
this.ctx.logger.error(`[archive-dispatch-to-history] 推进失败游标时查询失败: ${error.message}`);
return { lastId, failedCount: 0, advanced: false };
}
}
/**
* 归档全部(或指定)仓库的配送表订单。
*
* 每批一个事务、失败仅推进游标不中断整体,因此任务中断后重新执行即可续跑:
* 已迁移的行已从配送表删除,不会重复处理。
*
* @param {Object} [data] 请求参数。
* @param {number|Array<number|string>} [data.warehouseId] 单个仓库ID或仓库ID列表。
* @param {Array<number|string>} [data.warehouseIds] 仓库ID列表。
* @param {Object} [options] 归档参数(可覆盖 config.orderDeliveryArchive)。
* @param {Function} [options.onBatch] 单批完成回调。
* @param {Function} [options.onWarehouseDone] 单仓库完成回调。
* @return {Promise<Object>} 归档汇总结果。
*/
async archiveDispatchOrdersToHistory(data = {}, options = {}) {
const resolved = this.buildArchiveOptions(options);
const requestData = this.isPlainObject(data) ? data : {};
const explicitWarehouseIds = this.normalizeWarehouseIds(requestData);
const warehouseIds = explicitWarehouseIds.length > 0
? explicitWarehouseIds
: await this.listDispatchWarehouseIds();
const startedAt = Date.now();
const deadlineAt = startedAt + resolved.maxRunMs;
const thresholds = this.buildArchiveThresholds(new Date(startedAt), resolved);
const results = [];
let totalSelected = 0;
let totalArchived = 0;
let totalAlreadyArchived = 0;
let totalItemsArchived = 0;
let totalFailedBatches = 0;
let totalFailedCount = 0;
for (const warehouseId of warehouseIds) {
if (Date.now() >= deadlineAt) {
results.push({
warehouseId,
batches: 0,
selectedCount: 0,
archivedCount: 0,
alreadyArchivedCount: 0,
itemsArchivedCount: 0,
failedBatches: 0,
failedCount: 0,
lastId: 0,
stopReason: 'run_budget_exhausted',
});
continue;
}
const warehouseResult = await this.archiveDispatchOrdersForWarehouse(warehouseId, {
...resolved,
thresholds,
deadlineAt,
onBatch: options.onBatch,
shouldStop: options.shouldStop,
});
results.push(warehouseResult);
totalSelected += warehouseResult.selectedCount;
totalArchived += warehouseResult.archivedCount;
totalAlreadyArchived += warehouseResult.alreadyArchivedCount;
totalItemsArchived += warehouseResult.itemsArchivedCount;
totalFailedBatches += warehouseResult.failedBatches;
totalFailedCount += warehouseResult.failedCount;
if (typeof options.onWarehouseDone === 'function') {
await options.onWarehouseDone(warehouseResult);
}
}
const backlogRemaining = results.some(result => result.stopReason === 'run_budget_exhausted');
return {
warehouseIds,
batchSize: resolved.batchSize,
archiveAfterMonths: resolved.archiveAfterMonths,
dispatchStayMonths: resolved.dispatchStayMonths,
thresholds: {
createThreshold: thresholds.createThreshold.toISOString(),
dispatchThreshold: thresholds.dispatchThreshold.toISOString(),
},
elapsedMs: Date.now() - startedAt,
totalSelected,
totalArchived,
totalAlreadyArchived,
totalItemsArchived,
totalFailedBatches,
totalFailedCount,
backlogRemaining,
results,
};
}
}
module.exports = OrderDeliveryArchiveService;

View File

@ -1,780 +0,0 @@
'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<Array<{warehouseId: number, warehouseName: string, config: Object}>>} 仓库配置列表
*/
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<Array<Object>>} 收货单列表(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<Object>} rows 收货单列表
* @return {Array<{storeId: number, storeName: string, rows: Array<Object>}>} 分组结果
*/
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<Object>} 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<Object>} 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<Object>} options.rows 该货主的收货单列表
* @param {Object} options.config 规范化后的提醒配置
* @param {Date} options.now 当前时刻
* @return {Promise<Object|null>} 通知结果
*/
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<Object>} 执行汇总
*/
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<boolean>} 是否申请成功
*/
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<void>} 无返回值
*/
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<Object>} 执行汇总
*/
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;

View File

@ -976,9 +976,7 @@ class ReportDeliveryService extends Service {
* (MAX_RETRY=3,退避 = retry_count × 60s);
* 5. 完成后按计划配置附带发送文本通知(与投递渠道独立);
* 6. 幂等键含货主维度(report:{store_id}:{report_definition_id}:{biz_date}:{time_point}),
* 不同货主的投递消息互不复用;
* 7. 推送体/消息表 ext_data 一律透传目标群配置的 ext_data(与 notice 推送口径一致),
* 不自行组装报表业务字段(会丢失渠道来源 source,导致桥接投递到错误/缺失渠道)。
* 不同货主的投递消息互不复用。
*
* @param {Object} options 入参
* @param {Object} options.plan 投递计划
@ -1055,9 +1053,12 @@ class ReportDeliveryService extends Service {
},
content: this.buildMessageContent(definition, bizDate, fileUrl),
extId: idempotentKey,
// ext_data 必须透传群配置(含渠道来源 source 等):自行组装业务字段会丢失渠道信息,
// 导致桥接按错误/缺失渠道投递(与 notice 推送口径一致:extData = group.ext_data)
extData: groupRow.ext_data || null,
extData: {
report_definition_id: reportDefinitionId,
biz_date: bizDate,
time_point: timePoint,
file_url: fileUrl,
},
});
pushResults.push(pushResult);
}
@ -1127,8 +1128,7 @@ class ReportDeliveryService extends Service {
* 选择群时成员数组随每个群推送携带,未选择群时单独做一次仅成员推送;
* 4. {url} 为空时由渲染器替换为兜底文案(生成中占位),不阻断投递;
* 5. 推送失败抛出异常交由上层走失败退避重试(消息落库按 ext_id 幂等防重);
* 6. 幂等键含货主维度(report:notify:{store_id}:...),不同货主的文本通知互不复用;
* 7. ext_data 透传通知群配置的 ext_data(不自行组装业务字段);仅成员推送(无群)时传 null。
* 6. 幂等键含货主维度(report:notify:{store_id}:...),不同货主的文本通知互不复用。
*
* @param {Object} options 入参
* @param {Object} options.plan 投递计划
@ -1181,14 +1181,18 @@ class ReportDeliveryService extends Service {
// 幂等键含货主维度:不同货主的文本通知不得互相复用/串扰(货主限制不符缺陷)
const notifyExtId = `report:notify:${storeId}:${reportDefinitionId}:${bizDate}:${timePoint}`;
// ext_data 不在此处组装:群推送透传群配置的 ext_data(含渠道来源),
// 仅成员推送(无群)时无群配置可取,按 null 透传
const commonOptions = {
warehouseId,
storeId,
userIds: memberIds,
content: notifyText,
extId: notifyExtId,
extData: {
report_definition_id: reportDefinitionId,
biz_date: bizDate,
time_point: timePoint,
file_url: fileUrl,
},
};
const sentGroupIds = [];
@ -1202,13 +1206,12 @@ class ReportDeliveryService extends Service {
group_name: groupRow.group_name || '货主群',
ext_data: groupRow.ext_data || null,
},
extData: groupRow.ext_data || null,
}));
sentGroupIds.push(Number(groupRow.id));
}
// 仅成员(未选择任何群):单独一次成员推送,user_id 直接传数组不循环拆发(无群配置,ext_data 传 null)
// 仅成员(未选择任何群):单独一次成员推送,user_id 直接传数组不循环拆发
if (memberIds.length > 0 && results.length === 0) {
results.push(await warehouseNotify.pushSystemMessage({ ...commonOptions, extData: null }));
results.push(await warehouseNotify.pushSystemMessage(commonOptions));
}
const failed = results.filter(result => !result || result.success === false);

View File

@ -322,78 +322,6 @@ 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: '仓库波次策略版本号',

View File

@ -66,10 +66,6 @@ module.exports = appInfo => {
videoRecordNotifyLimit: 10,
// 视频补录结果通知:超时阈值(毫秒),超过仍无录像则按超时回信并终止,避免长期占用扫描窗口
videoRecordNotifyTimeoutMs: 60 * 60 * 1000,
// 出站推送失败自动重推:失败时间窗(毫秒),仅重推窗口内失败的消息(默认 2 小时),超窗口不再补推
pushRetryWindowMs: 2 * 60 * 60 * 1000,
// 出站推送失败自动重推:单轮最多重推条数(定时任务每 3 分钟扫一次)
pushRetryLimit: 20,
};
config.tencentCloud = {
@ -257,30 +253,6 @@ module.exports = appInfo => {
sleepMinMs: 100,
sleepMaxMs: 500,
};
// 配送表(dispatch) → 历史表(history) 归档定时任务配置
// 每日凌晨 06:00 把配送表超期订单(连同商品明细)迁入历史表,并更新订单索引表位置指针
config.orderDeliveryArchive = {
// 开关:false 时不注册本定时任务
enable: true,
// 触发 cron(秒 分 时 日 月 周):默认每日凌晨 06:00;本地环境可在 config.local.js 覆盖为短间隔
cron: '0 0 6 * * *',
// 归档门槛一:订单创建时间(create_at)距今超过该月数即归档(dispath_time 为 NULL 的存量单只靠此条)
archiveAfterMonths: 4,
// 归档门槛二:迁移进配送表时间(dispath_time)距今超过该月数即归档
dispatchStayMonths: 3,
// 单批条数(单批一个事务:写历史表 + 更新位置指针 + 删源行)
batchSize: 1000,
// 单仓库单轮最多批次数(异常情况下防死循环)
maxBatchesPerWarehouse: 200,
// 单轮总时长上限(毫秒):用尽后停止本轮,剩余订单下一轮继续(避免闯入业务高峰)
maxRunMs: 30 * 60 * 1000,
// 单批查询超时(毫秒)
queryTimeoutMs: 60 * 1000,
// 单批事务遇到死锁/锁等待的最大尝试次数
batchMaxAttempts: 3,
// 跨进程互斥锁 TTL(秒),需覆盖单轮最长执行时间;进程被杀后锁到期自动释放
lockTtlSeconds: 30 * 60,
};
// 打印自定义区模板出口域名
config.customAreaBaseUrl = 'https://api.ye4s.com';
// 仓库前端独立部署:证书部署目录。

View File

@ -1,130 +1,4 @@
[
{
"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",

View File

@ -1,40 +1,4 @@
[
{
"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",

View File

@ -1,7 +1,7 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.3.131",
"version": "0.3.125",
"updatedAt": "2026-09-15",
"headers": [
{
@ -14441,48 +14441,6 @@
"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": [
@ -14782,55 +14740,6 @@
"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": [
@ -35607,288 +35516,6 @@
"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"
]
}
]
},

View File

@ -1,8 +1,8 @@
{
"module": "warehouse",
"description": "仓库开放 API 统一入口(入站方向:外部 → WMS),供仓库级外部适配器(企微/钉钉/飞书/IM 等)调用,HTTP POST /warehouse,使用 MD5 签名鉴权(interface_type_id=3)。出站通知请参阅 warehouse_notify.json。",
"version": "1.2.2",
"updatedAt": "2026-09-15",
"version": "1.2.0",
"updatedAt": "2026-08-07",
"http": {
"path": "/warehouse",
"method": "POST"