326 lines
11 KiB
JavaScript
326 lines
11 KiB
JavaScript
// app/service/systems/operation_log.js
|
||
'use strict';
|
||
|
||
const Service = require('egg').Service;
|
||
|
||
const OPERATION_LOG_ATTRIBUTES = [
|
||
'id',
|
||
'operation_code',
|
||
'operator_name',
|
||
'created_at',
|
||
'external_log_type',
|
||
'external_log_id',
|
||
'platform_code',
|
||
'message',
|
||
];
|
||
|
||
class operationLogService extends Service {
|
||
/**
|
||
* 将单条日志参数转换为数据库字段。
|
||
* @param {Object} params 日志参数。
|
||
* @param {string} params.businessType 业务类型。
|
||
* @param {string|number} params.businessId 业务ID。
|
||
* @param {string} params.operationCode 操作编码。
|
||
* @param {Object} [params.operator={}] 操作人信息。
|
||
* @param {Object} [params.extras={}] 扩展字段。
|
||
* @param {Object|null} [params.beforeChanges=null] 操作前快照。
|
||
* @return {Object} 可直接落库的日志数据。
|
||
*/
|
||
buildOperationLogData(params = {}) {
|
||
const { ctx } = this;
|
||
const {
|
||
businessType,
|
||
businessId,
|
||
operationCode,
|
||
operator = {},
|
||
beforeChanges = null,
|
||
extras = {},
|
||
} = params;
|
||
|
||
return {
|
||
business_type: businessType,
|
||
business_id: String(businessId),
|
||
operation_code: operationCode,
|
||
// 使用 nullish 合并符,确保当 operator.id 为 0 时仍然保留 0
|
||
operator_id: operator?.id ?? null,
|
||
operator_name: operator?.name ?? null,
|
||
external_log_type: extras.externalLogType || 'NONE',
|
||
external_log_id: extras.externalLogId ?? null,
|
||
warehouse_id: extras.warehouseId ?? null,
|
||
before_changes: beforeChanges,
|
||
platform_code: ctx.user?.platform_code || 'SYSTEM',
|
||
message: extras.message || null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 规范并校验日志查询入参,强制要求业务ID与仓库ID。
|
||
* @param {Object} query 查询参数。
|
||
* @param {string} businessType 业务类型。
|
||
* @return {{ where: Object, id: string|number, warehouseId: string|number }} 查询条件。
|
||
*/
|
||
buildBusinessLogWhere(query = {}, businessType) {
|
||
const requestQuery = query && typeof query === 'object' ? query : {};
|
||
const {
|
||
id,
|
||
warehouseId,
|
||
} = requestQuery;
|
||
|
||
if (!id) {
|
||
throw new Error('id不能为空');
|
||
}
|
||
|
||
if (!warehouseId) {
|
||
throw new Error('仓库id不能为空');
|
||
}
|
||
|
||
return {
|
||
where: {
|
||
business_type: businessType,
|
||
business_id: id,
|
||
warehouse_id: warehouseId,
|
||
},
|
||
id,
|
||
warehouseId,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 将日志模型结果格式化为接口输出结构。
|
||
* @param {Object[]} rows 日志行数据。
|
||
* @return {Object[]} 格式化后的日志列表。
|
||
*/
|
||
formatOperationLogRows(rows = []) {
|
||
const { app } = this;
|
||
return rows.map(item => {
|
||
const itemTmp = JSON.parse(JSON.stringify(item));
|
||
itemTmp.operation_name = app.getOperationCodeName(item.operation_code);
|
||
itemTmp.platform_name = app.getPlatformName(item.platform_code);
|
||
itemTmp.created_at = app.formatDate(itemTmp.created_at);
|
||
return itemTmp;
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 通用操作日志记录方法
|
||
* @param {Object} params 日志参数
|
||
* @param {string} params.businessType 业务类型: product, order, stock, wave, express, storage
|
||
* @param {string} params.businessId 业务ID
|
||
* @param {string} params.operationCode 操作编码
|
||
* @param {Object} params.operator 操作人信息
|
||
* @param {string} params.operator.id 操作人ID
|
||
* @param {string} params.operator.name 操作人名称
|
||
* @param {string} params.operationAction 操作动作: CREATE, UPDATE, DELETE, OTHER
|
||
* @param {string} params.changeSummary 变更描述
|
||
* @param {Object} params.keyChanges 关键变更字段
|
||
* @param {Object} params.extras 额外参数
|
||
* @param {string} params.extras.externalLogType 外部日志类型
|
||
* @param {number} params.extras.externalLogId 外部日志ID
|
||
* @param {number} params.extras.warehouseId 仓库ID
|
||
* @param {string} params.extras.message 日志信息
|
||
* @param {Object} [params.transaction] 事务对象(可选)
|
||
*
|
||
*/
|
||
async createOperationLog(params = {}) {
|
||
const { ctx } = this;
|
||
const {
|
||
businessType,
|
||
businessId,
|
||
transaction,
|
||
} = params;
|
||
try {
|
||
const logData = this.buildOperationLogData(params);
|
||
|
||
const createOptions = {};
|
||
if (transaction) {
|
||
createOptions.transaction = transaction;
|
||
}
|
||
|
||
const result = await ctx.model.OperationLog.create(logData, createOptions);
|
||
ctx.logger.info(`[OperationLog] 记录操作日志成功,ID: ${result.id}, Business: ${businessType}/${businessId}`);
|
||
return result;
|
||
} catch (error) {
|
||
ctx.logger.error(`[OperationLog] 记录操作日志失败: ${error.message}`, error);
|
||
// 生产环境建议添加降级处理,如写入文件或发送到监控系统
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 批量写入操作日志,优先使用 bulkCreate,失败时自动降级单条写入。
|
||
* @param {Array<Object>} paramsList 日志参数数组。
|
||
* @param {Object} [options={}] 写入选项。
|
||
* @param {Object} [options.transaction] 事务对象(可选)。
|
||
* @return {Promise<Array<Object|null>>} 写入结果数组。
|
||
*/
|
||
async createOperationLogs(paramsList = [], options = {}) {
|
||
const { ctx } = this;
|
||
const requestOptions = options && typeof options === 'object' ? options : {};
|
||
const transaction = requestOptions.transaction;
|
||
const normalizedParamsList = Array.isArray(paramsList) ? paramsList.filter(Boolean) : [];
|
||
|
||
if (normalizedParamsList.length === 0) {
|
||
return [];
|
||
}
|
||
|
||
const operationLogModel = ctx.model && ctx.model.OperationLog;
|
||
if (!operationLogModel || typeof operationLogModel.bulkCreate !== 'function') {
|
||
ctx.logger.warn('[OperationLog] OperationLog.bulkCreate 不可用,降级单条写入');
|
||
return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({
|
||
...item,
|
||
transaction: item && item.transaction ? item.transaction : transaction,
|
||
})));
|
||
}
|
||
|
||
try {
|
||
const rows = normalizedParamsList.map(item => this.buildOperationLogData(item));
|
||
const bulkCreateOptions = {};
|
||
if (transaction) {
|
||
bulkCreateOptions.transaction = transaction;
|
||
}
|
||
return await operationLogModel.bulkCreate(rows, bulkCreateOptions);
|
||
} catch (error) {
|
||
ctx.logger.error(`[OperationLog] 批量记录操作日志失败,降级单条写入: ${error.message}`, error);
|
||
return await Promise.all(normalizedParamsList.map(item => this.createOperationLog({
|
||
...item,
|
||
transaction: item && item.transaction ? item.transaction : transaction,
|
||
})));
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按业务类型查询操作日志分页数据。
|
||
* @param {Object} query 查询参数。
|
||
* @param {string|number} query.id 业务ID。
|
||
* @param {string|number} query.warehouseId 仓库ID。
|
||
* @param {number} [query.page=1] 页码。
|
||
* @param {number} [query.pageSize=20] 每页数量。
|
||
* @param {string} businessType 业务类型。
|
||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||
*/
|
||
async queryLogsByBusinessType(query = {}, businessType) {
|
||
const { ctx } = this;
|
||
const requestQuery = query && typeof query === 'object' ? query : {};
|
||
const {
|
||
page = 1,
|
||
pageSize = 20,
|
||
} = requestQuery;
|
||
const { where } = this.buildBusinessLogWhere(requestQuery, businessType);
|
||
|
||
const currentPage = Number.parseInt(page, 10) || 1;
|
||
const currentPageSize = Number.parseInt(pageSize, 10) || 20;
|
||
const offset = (currentPage - 1) * currentPageSize;
|
||
|
||
const result = await ctx.model.OperationLog.findAndCountAll({
|
||
where,
|
||
order: [[ 'created_at', 'DESC' ]],
|
||
offset,
|
||
attributes: OPERATION_LOG_ATTRIBUTES,
|
||
limit: currentPageSize,
|
||
});
|
||
|
||
const rows = Array.isArray(result.rows) ? result.rows : [];
|
||
|
||
return {
|
||
list: this.formatOperationLogRows(rows),
|
||
pagination: {
|
||
page: currentPage,
|
||
pageSize: currentPageSize,
|
||
total: result.count,
|
||
totalPages: Math.ceil(result.count / currentPageSize),
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 查询库存操作日志。
|
||
* @param {Object} query 查询参数。
|
||
* @param {string|number} query.id 库存业务ID。
|
||
* @param {string|number} query.warehouseId 仓库ID。
|
||
* @param {number} [query.page=1] 页码。
|
||
* @param {number} [query.pageSize=20] 每页数量。
|
||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||
*/
|
||
async queryStockLogs(query = {}) {
|
||
return await this.queryLogsByBusinessType(query, 'stock');
|
||
}
|
||
|
||
/**
|
||
* 查询订单操作日志。
|
||
* @param {Object} query 查询参数。
|
||
* @param {string|number} query.id 订单ID。
|
||
* @param {string|number} query.warehouseId 仓库ID。
|
||
* @param {number} [query.page=1] 页码。
|
||
* @param {number} [query.pageSize=20] 每页数量。
|
||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||
*/
|
||
async queryOrderLogs(query = {}) {
|
||
return await this.queryLogsByBusinessType(query, 'order');
|
||
}
|
||
|
||
/**
|
||
* 查询订单操作日志(不分页,返回全部)。
|
||
* @param {Object} query 查询参数。
|
||
* @param {string|number} query.id 订单ID。
|
||
* @param {string|number} query.warehouseId 仓库ID。
|
||
* @return {Promise<Object[]>} 日志列表。
|
||
*/
|
||
async queryAllOrderLogs(query = {}) {
|
||
return await this.queryAllLogsByBusinessType(query, 'order');
|
||
}
|
||
|
||
/**
|
||
* 按业务类型查询日志全量数据(不分页)。
|
||
* @param {Object} query 查询参数。
|
||
* @param {string|number} query.id 业务ID。
|
||
* @param {string|number} query.warehouseId 仓库ID。
|
||
* @param {string} businessType 业务类型。
|
||
* @return {Promise<Object[]>} 日志列表。
|
||
*/
|
||
async queryAllLogsByBusinessType(query = {}, businessType) {
|
||
const { ctx } = this;
|
||
const requestQuery = query && typeof query === 'object' ? query : {};
|
||
const { where } = this.buildBusinessLogWhere(requestQuery, businessType);
|
||
|
||
const rows = await ctx.model.OperationLog.findAll({
|
||
where,
|
||
order: [[ 'created_at', 'DESC' ]],
|
||
attributes: OPERATION_LOG_ATTRIBUTES,
|
||
raw: true,
|
||
});
|
||
|
||
const normalizedRows = Array.isArray(rows) ? rows : [];
|
||
return this.formatOperationLogRows(normalizedRows);
|
||
}
|
||
|
||
/**
|
||
* 查询收货单操作日志。
|
||
* @param {Object} query 查询参数。
|
||
* @param {string|number} query.id 收货单ID。
|
||
* @param {string|number} query.warehouseId 仓库ID。
|
||
* @param {number} [query.page=1] 页码。
|
||
* @param {number} [query.pageSize=20] 每页数量。
|
||
* @return {Promise<{list: Object[], pagination: Object}>} 分页结果。
|
||
*/
|
||
async queryReceivingLogs(query = {}) {
|
||
return await this.queryLogsByBusinessType(query, 'receiving');
|
||
}
|
||
|
||
async getMessageDetail(data) {
|
||
const { id, type } = data;
|
||
const { ctx } = this;
|
||
let LogModel = null;
|
||
switch (type) {
|
||
case 'QIMEN':
|
||
LogModel = ctx.model.QimenLog;
|
||
break;
|
||
default:
|
||
throw new Error(`不支持的日志类型: ${type}`);
|
||
}
|
||
const result = await LogModel.findOne({ where: { id } });
|
||
return result;
|
||
}
|
||
}
|
||
|
||
module.exports = operationLogService;
|