liufumingren 948f600689 feat(inbox): 回调推送、出站文档、搜索增强、日志与推送状态完善
出站回调:
- 新增 warehouse_notify.json 文档(notify.ping/notify.reply),与 warehouse.json 互跳
- 回调体统一 { method, code, data },method 放 query,body 为业务数据
- MD5 签名: sign=MD5(appSecret+timestamp+bodyJson)
- 回调响应: {code:200} 成功,非200/非code:200 视为失败
- docs 页面支持模拟推送调试

搜索增强(searchStock/searchWarehouseStock):
- 直接查 stock_warehouse,不再依赖 stock_store
- 新增字段: gross_weight/box_spec/packing_requirements/prohibited_type
- 管理标识: is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt
- 条码关联: wms_stock_barcodes
- 图片: wms_file_reference(business_type=stock)+wms_file,返回数组
- id 修正为 stock_warehouse.id

推送状态完善:
- handleApiMessage 增加 push_status 更新(2成功/3失败)
- 未配回调地址 → push_status=3 + error 原因
- 回调异常 catch 也更新 push_status=3 + 写日志
- 出站日志写入 wms_warehouse_log 表(WN-前缀)

消息列表:
- keyword 兼容 content/keyword,支持数组
- keyword 搜索 content/group_name/user_name 三列
- 支持 where+operator 结构化查询(parseWhereConditions)
- storeId=-1 查询无货主消息; storeId=0→IS NULL
- 日期范围: startDate/endDate

其他:
- silent 动作: AI 识别无需回复时跳过回执
- ai_enabled 灰度开关(群级)
- bindCode 文档修正
- store_name 改用 StoreWarehouse.store_remask
2026-08-08 00:17:38 +08:00

315 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { randomBytes } = require('node:crypto');
const { Service } = require('egg');
class ApiAppService extends Service {
/**
* 生成唯一的 AppKey。
* 格式:AK{yyyyMMddHHmmss}{random8}
* @return {string} AppKey
*/
generateAppKey() {
const now = new Date();
const timestamp = [
now.getFullYear(),
String(now.getMonth() + 1).padStart(2, '0'),
String(now.getDate()).padStart(2, '0'),
String(now.getHours()).padStart(2, '0'),
String(now.getMinutes()).padStart(2, '0'),
String(now.getSeconds()).padStart(2, '0'),
].join('');
return `AK${timestamp}${randomBytes(4).toString('hex')}`;
}
/**
* 生成 AppSecret。
* @return {string} 64 字符十六进制密钥。
*/
generateAppSecret() {
return randomBytes(32).toString('hex');
}
/**
* 获取默认的仓库渠道接口类型 ID。
* 查找 interface_type 中 interface_code = 'OPEN_API_WAREHOUSE' 的记录。
* @return {Promise<number>} 接口类型 ID,找不到时返回 0。
*/
async getDefaultInterfaceTypeId() {
const row = await this.ctx.model.InterfaceType.findOne({
attributes: [ 'id' ],
where: { interface_code: 'OPEN_API_WAREHOUSE', is_enabled: 1 },
raw: true,
});
return row ? Number(row.id) : 0;
}
/**
* 查询当前仓库的 API 应用列表(分页)。
* @param {Object} data 查询参数。
* @param {number} [data.page=1] 页码。
* @param {number} [data.pageSize=20] 每页数量。
* @param {string} [data.app_name] 应用名称(模糊搜索)。
* @param {number} [data.is_enabled] 启用状态。
* @return {Promise<Object>} 分页结果。
*/
async list(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const page = Math.max(1, Number(data.page) || 1);
const pageSize = Math.min(100, Math.max(1, Number(data.pageSize) || 20));
// 仅查询仓库开放接口类型的应用,排除货主/奇门等类型
const where = {
warehouse_id: warehouseId,
interface_type_id: await this.getDefaultInterfaceTypeId(),
};
if (data.app_name) {
where.app_name = { [this.app.Sequelize.Op.like]: `%${String(data.app_name).trim()}%` };
}
if (data.is_enabled !== undefined && data.is_enabled !== null && data.is_enabled !== '') {
where.is_enabled = Number(data.is_enabled);
}
const total = await ctx.model.ApiApp.count({ where });
const list = await ctx.model.ApiApp.findAll({
attributes: [
'id', 'app_name', 'warehouse_id', 'self_app_key', 'self_app_secret',
'self_ip_whitelist', 'callback_url', 'interface_type_id',
'rate_limit', 'sign_method', 'is_enabled', 'created_at', 'updated_at',
],
where,
offset: (page - 1) * pageSize,
limit: pageSize,
order: [[ 'id', 'DESC' ]],
raw: true,
});
// 脱敏:只返回 secret 前 8 位
const maskedList = list.map(item => ({
...item,
self_app_secret: item.self_app_secret
? String(item.self_app_secret).substring(0, 8) + '****'
: '',
}));
return {
list: maskedList,
pagination: {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
hasNext: page * pageSize < total,
hasPrevious: page > 1,
},
};
}
/**
* 创建仓库 API 应用,自动生成 AppKey 和 AppSecret。
* @param {Object} data 创建参数。
* @param {string} data.app_name 应用名称(必填)。
* @param {number|string} [data.interface_type_id] 接口类型 ID,不传则查 WH_CHANNEL。
* @param {Array<string>} [data.self_ip_whitelist] IP 白名单。
* @param {string} [data.callback_url] 回调地址。
* @param {number} [data.rate_limit=1000] 速率限制。
* @param {string} [data.sign_method='md5'] 签名方法。
* @return {Promise<Object>} 创建结果(含完整 secret,仅创建时返回)。
*/
async create(data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
if (!warehouseId) {
throw new Error('无法获取当前仓库ID');
}
const appName = String(data.app_name || '').trim();
if (!appName) {
throw new Error('应用名称不能为空');
}
if (appName.length > 200) {
throw new Error('应用名称不能超过200个字符');
}
const interfaceTypeId = data.interface_type_id
? Number(data.interface_type_id)
: await this.getDefaultInterfaceTypeId();
const appKey = this.generateAppKey();
const appSecret = this.generateAppSecret();
const payload = {
app_name: appName,
warehouse_id: warehouseId,
interface_type_id: interfaceTypeId,
self_app_key: appKey,
self_app_secret: appSecret,
self_ip_whitelist: Array.isArray(data.self_ip_whitelist) ? data.self_ip_whitelist : null,
callback_url: String(data.callback_url || '').trim() || null,
rate_limit: Number(data.rate_limit) || 1000,
sign_method: 'md5',
is_enabled: 1,
};
const record = await ctx.model.ApiApp.create(payload);
this.ctx.logger.info('[apiApp] 创建仓库API应用成功', {
warehouseId,
appId: record.id,
appName,
appKey,
});
return {
id: record.id,
app_name: record.app_name,
warehouse_id: record.warehouse_id,
interface_type_id: record.interface_type_id,
self_app_key: record.self_app_key,
self_app_secret: record.self_app_secret,
self_ip_whitelist: record.self_ip_whitelist,
callback_url: record.callback_url,
rate_limit: record.rate_limit,
sign_method: record.sign_method,
is_enabled: record.is_enabled,
created_at: record.created_at,
updated_at: record.updated_at,
};
}
/**
* 更新仓库 API 应用。
* @param {number|string} id 应用 ID。
* @param {Object} data 更新字段。
* @param {string} [data.app_name] 应用名称。
* @param {Array<string>} [data.self_ip_whitelist] IP 白名单。
* @param {string} [data.callback_url] 回调地址。
* @param {number} [data.rate_limit] 速率限制。
* @param {string} [data.sign_method] 签名方法。
* @param {number} [data.is_enabled] 启用状态。
* @return {Promise<Object>} 更新后的记录(脱敏)。
*/
async update(id, data = {}) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const record = await ctx.model.ApiApp.findOne({
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() },
});
if (!record) {
throw new Error('API应用不存在或不属于当前仓库');
}
const updatableFields = [ 'app_name', 'self_ip_whitelist', 'callback_url', 'rate_limit', 'sign_method', 'is_enabled' ];
for (const field of updatableFields) {
if (data[field] !== undefined && data[field] !== null) {
if (field === 'sign_method') {
throw new Error('签名方法当前仅支持 md5,不允许修改');
} else if (field === 'is_enabled') {
record[field] = Number(data[field]);
} else if (field === 'rate_limit') {
const val = Number(data[field]);
record[field] = val > 0 && val <= 100000 ? val : record[field];
} else if (field === 'app_name') {
const val = String(data[field]).trim();
if (!val) throw new Error('应用名称不能为空');
if (val.length > 200) throw new Error('应用名称不能超过200个字符');
record[field] = val;
} else {
record[field] = data[field];
}
}
}
await record.save();
this.ctx.logger.info('[apiApp] 更新仓库API应用成功', {
warehouseId,
appId: record.id,
});
return {
id: record.id,
app_name: record.app_name,
warehouse_id: record.warehouse_id,
interface_type_id: record.interface_type_id,
self_app_key: record.self_app_key,
self_app_secret: record.self_app_secret
? String(record.self_app_secret).substring(0, 8) + '****'
: '',
self_ip_whitelist: record.self_ip_whitelist,
callback_url: record.callback_url,
rate_limit: record.rate_limit,
sign_method: record.sign_method,
is_enabled: record.is_enabled,
created_at: record.created_at,
updated_at: record.updated_at,
};
}
/**
* 删除仓库 API 应用(软删除:is_enabled=0)。
* @param {number|string} id 应用 ID。
* @return {Promise<void>} 无返回值。
*/
async delete(id) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const record = await ctx.model.ApiApp.findOne({
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() },
});
if (!record) {
throw new Error('API应用不存在或不属于当前仓库');
}
record.is_enabled = 0;
await record.save();
this.ctx.logger.info('[apiApp] 停用仓库API应用成功', {
warehouseId,
appId: record.id,
});
}
/**
* 重新生成 AppSecret。
* @param {number|string} id 应用 ID。
* @return {Promise<Object>} 包含新 secret 的结果(仅此次返回完整 secret)。
*/
async regenerateSecret(id) {
const { ctx } = this;
const warehouseId = Number(ctx.user && ctx.user.store_id || 0);
const record = await ctx.model.ApiApp.findOne({
where: { id: Number(id), warehouse_id: warehouseId, interface_type_id: await this.getDefaultInterfaceTypeId() },
});
if (!record) {
throw new Error('API应用不存在或不属于当前仓库');
}
const newSecret = this.generateAppSecret();
record.self_app_secret = newSecret;
await record.save();
this.ctx.logger.info('[apiApp] 重新生成AppSecret成功', {
warehouseId,
appId: record.id,
});
return {
id: record.id,
app_name: record.app_name,
self_app_key: record.self_app_key,
self_app_secret: newSecret,
};
}
}
module.exports = ApiAppService;