perf: optimize Activity Log — lazy diff, 30-day default, getById

- List query: exclude changes JSONB from select (only metadata)
- Default to last 30 days when no date filter (avoids full table scan)
- New getById query: fetches full changes JSONB on demand
- ExpandedDiff component: fetches diff only when user expands an entry
- 5-minute staleTime on expanded diffs (cacheable, rarely changes)

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-03-22 22:55:45 +01:00
parent 7a7430851c
commit eacbdb5d47
2 changed files with 54 additions and 8 deletions
+30 -1
View File
@@ -49,10 +49,27 @@ export const auditLogRouter = createTRPCRouter({
];
}
// Default to last 30 days if no date filter to avoid full table scan
if (!startDate && !endDate && !entityId) {
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
where.createdAt = { ...(where.createdAt as Record<string, Date> ?? {}), gte: thirtyDaysAgo };
}
const items = await ctx.db.auditLog.findMany({
where,
include: {
select: {
id: true,
entityType: true,
entityId: true,
entityName: true,
action: true,
userId: true,
source: true,
summary: true,
createdAt: true,
user: { select: { id: true, name: true, email: true } },
// Exclude 'changes' from list query — fetch on demand when expanding
},
orderBy: { createdAt: "desc" },
take: limit + 1,
@@ -68,6 +85,18 @@ export const auditLogRouter = createTRPCRouter({
return { items, nextCursor };
}),
/**
* Get a single audit entry with full changes JSONB (for expand/detail view).
*/
getById: controllerProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
return ctx.db.auditLog.findUniqueOrThrow({
where: { id: input.id },
include: { user: { select: { id: true, name: true, email: true } } },
});
}),
/**
* Get all audit entries for a specific entity (e.g. a project or resource).
*/