GuDingZiChan/backend/src/controllers/operationLogController.ts
2026-03-10 16:19:47 +08:00

112 lines
2.6 KiB
TypeScript

import { Request, Response } from 'express'
import prisma from '../utils/prisma'
import { successResponse, errorResponse } from '../utils/response'
// 获取操作日志列表
export const getOperationLogList = async (req: Request, res: Response) => {
try {
const {
page = 1,
pageSize = 20,
operationType,
username,
startDate,
endDate
} = req.query
const where: any = {}
if (operationType) {
where.operation_type = operationType
}
if (username) {
where.username = { contains: username as string }
}
if (startDate || endDate) {
where.created_at = {}
if (startDate) {
where.created_at.gte = new Date(startDate as string)
}
if (endDate) {
const end = new Date(endDate as string)
end.setHours(23, 59, 59, 999)
where.created_at.lte = end
}
}
const skip = (Number(page) - 1) * Number(pageSize)
const [list, total] = await Promise.all([
prisma.operationLog.findMany({
where,
skip,
take: Number(pageSize),
orderBy: { created_at: 'desc' },
include: {
user: {
select: {
id: true,
username: true,
name: true
}
}
}
}),
prisma.operationLog.count({ where })
])
successResponse(res, {
list,
total,
page: Number(page),
pageSize: Number(pageSize)
}, '获取成功')
} catch (error: any) {
errorResponse(res, error.message || '获取操作日志失败')
}
}
// 获取操作类型列表
export const getOperationTypes = async (req: Request, res: Response) => {
try {
const types = await prisma.operationLog.findMany({
select: { operation_type: true },
distinct: ['operation_type']
})
const typeList = types.map(t => t.operation_type)
successResponse(res, typeList, '获取成功')
} catch (error: any) {
errorResponse(res, error.message || '获取操作类型失败')
}
}
// 记录操作日志(工具函数)
export const logOperation = async (
userId: number | null,
username: string,
operationType: string,
details: string,
equipmentId?: number,
equipmentCode?: string,
ipAddress?: string
) => {
try {
await prisma.operationLog.create({
data: {
user_id: userId,
username,
operation_type: operationType,
equipment_id: equipmentId || null,
equipment_code: equipmentCode || null,
operation_details: details,
ip_address: ipAddress || null
}
})
} catch (error) {
console.error('记录操作日志失败:', error)
}
}