- 新增 systems/apiApp.js 业务层:CRUD + AppKey/Secret 自动生成 + 仓库隔离 - 新增 systemMethods/apiApp.js 入口层:list/detail/create/update/delete/regenerateSecret - 注册 methods/system.json API 文档 + changes 变更记录 - 新增迁移脚本:wms_permission 固定 ID 464-470 + 客服组主管及以上角色授权
321 lines
10 KiB
JavaScript
321 lines
10 KiB
JavaScript
'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', 'hmac', 'sha256' ].includes(String(data.sign_method || '').trim())
|
||
? String(data.sign_method).trim()
|
||
: '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') {
|
||
const val = String(data[field]).trim();
|
||
if (![ 'md5', 'hmac', 'sha256' ].includes(val)) {
|
||
throw new Error('签名方法仅支持 md5/hmac/sha256');
|
||
}
|
||
record[field] = val;
|
||
} 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;
|