diff --git a/src/components/AuditLogViewer.js b/src/components/AuditLogViewer.js
index da8467c..508806c 100644
--- a/src/components/AuditLogViewer.js
+++ b/src/components/AuditLogViewer.js
@@ -280,7 +280,7 @@ export default function AuditLogViewer() {
{/* Statistics */}
- {stats && (
+ {stats && stats.total > 0 && (
Total Events
@@ -289,22 +289,22 @@ export default function AuditLogViewer() {
Top Action
- {stats.actionBreakdown[0]?.action || "N/A"}
+ {stats.actionBreakdown && stats.actionBreakdown[0]?.action || "N/A"}
- {stats.actionBreakdown[0]?.count || 0}
+ {stats.actionBreakdown && stats.actionBreakdown[0]?.count || 0}
Active Users
- {stats.userBreakdown.length}
+ {stats.userBreakdown ? stats.userBreakdown.length : 0}
Resource Types
- {stats.resourceBreakdown.length}
+ {stats.resourceBreakdown ? stats.resourceBreakdown.length : 0}
diff --git a/src/lib/auditLog.js b/src/lib/auditLog.js
index 5db20ed..00f32c6 100644
--- a/src/lib/auditLog.js
+++ b/src/lib/auditLog.js
@@ -177,7 +177,7 @@ export async function getAuditLogs({
SELECT
al.*,
u.name as user_name,
- u.email as user_email
+ u.username as user_email
FROM audit_logs al
LEFT JOIN users u ON al.user_id = u.id
WHERE 1=1
@@ -291,7 +291,7 @@ export async function getAuditLogStats({
// Dynamic import to avoid Edge Runtime issues
const { default: db } = await import("./db.js");
- let baseQuery = "FROM audit_logs WHERE 1=1";
+ let baseQuery = "FROM audit_logs al WHERE 1=1";
const params = [];
if (startDate) {
@@ -310,34 +310,48 @@ export async function getAuditLogStats({
// Actions breakdown
const actionsStmt = db.prepare(`
- SELECT action, COUNT(*) as count
+ SELECT al.action, COUNT(*) as count
${baseQuery}
- GROUP BY action
+ GROUP BY al.action
ORDER BY count DESC
`);
const actionsResult = actionsStmt.all(...params);
// Users breakdown
- const usersStmt = db.prepare(`
+ let usersQuery = `
SELECT
al.user_id,
u.name as user_name,
- u.email as user_email,
+ u.username as user_email,
COUNT(*) as count
- ${baseQuery}
+ FROM audit_logs al
LEFT JOIN users u ON al.user_id = u.id
- GROUP BY al.user_id, u.name, u.email
+ WHERE 1=1
+ `;
+
+ if (startDate) {
+ usersQuery += " AND al.timestamp >= ?";
+ }
+
+ if (endDate) {
+ usersQuery += " AND al.timestamp <= ?";
+ }
+
+ usersQuery += `
+ GROUP BY al.user_id, u.name, u.username
ORDER BY count DESC
LIMIT 10
- `);
+ `;
+
+ const usersStmt = db.prepare(usersQuery);
const usersResult = usersStmt.all(...params);
// Resource types breakdown
const resourcesStmt = db.prepare(`
- SELECT resource_type, COUNT(*) as count
+ SELECT al.resource_type, COUNT(*) as count
${baseQuery}
- WHERE resource_type IS NOT NULL
- GROUP BY resource_type
+ WHERE al.resource_type IS NOT NULL
+ GROUP BY al.resource_type
ORDER BY count DESC
`);
const resourcesResult = resourcesStmt.all(...params);