Dealer_Onboarding_Backend/services/auditService.js

112 lines
2.7 KiB
JavaScript

const { query } = require('../config/database');
/**
* Log audit trail for all important actions
*/
const logAudit = async ({ userId, action, entityType, entityId, oldValue = null, newValue = null, ipAddress = null, userAgent = null }) => {
try {
await query(
`INSERT INTO audit_logs
(user_id, action, entity_type, entity_id, old_value, new_value, ip_address, user_agent)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[
userId,
action,
entityType,
entityId,
oldValue ? JSON.stringify(oldValue) : null,
newValue ? JSON.stringify(newValue) : null,
ipAddress,
userAgent
]
);
console.log(`Audit logged: ${action} by user ${userId}`);
} catch (error) {
console.error('Error logging audit:', error);
// Don't throw error - audit logging should not break the main flow
}
};
/**
* Get audit logs for an entity
*/
const getAuditLogs = async (entityType, entityId) => {
try {
const result = await query(
`SELECT al.*, u.full_name as user_name, u.email as user_email
FROM audit_logs al
LEFT JOIN users u ON al.user_id = u.id
WHERE al.entity_type = $1 AND al.entity_id = $2
ORDER BY al.created_at DESC`,
[entityType, entityId]
);
return result.rows;
} catch (error) {
console.error('Error fetching audit logs:', error);
return [];
}
};
/**
* Get all audit logs with filters
*/
const getAllAuditLogs = async ({ userId, action, entityType, startDate, endDate, limit = 100 }) => {
try {
let queryText = `
SELECT al.*, u.full_name as user_name, u.email as user_email
FROM audit_logs al
LEFT JOIN users u ON al.user_id = u.id
WHERE 1=1
`;
const params = [];
let paramCount = 1;
if (userId) {
queryText += ` AND al.user_id = $${paramCount}`;
params.push(userId);
paramCount++;
}
if (action) {
queryText += ` AND al.action = $${paramCount}`;
params.push(action);
paramCount++;
}
if (entityType) {
queryText += ` AND al.entity_type = $${paramCount}`;
params.push(entityType);
paramCount++;
}
if (startDate) {
queryText += ` AND al.created_at >= $${paramCount}`;
params.push(startDate);
paramCount++;
}
if (endDate) {
queryText += ` AND al.created_at <= $${paramCount}`;
params.push(endDate);
paramCount++;
}
queryText += ` ORDER BY al.created_at DESC LIMIT $${paramCount}`;
params.push(limit);
const result = await query(queryText, params);
return result.rows;
} catch (error) {
console.error('Error fetching all audit logs:', error);
return [];
}
};
module.exports = {
logAudit,
getAuditLogs,
getAllAuditLogs
};