feat: Activity History system — full audit coverage, UI, AI tools

Infrastructure (Phase 1):
- AuditLog schema: add source, entityName, summary fields + index
- createAuditEntry() helper: auto-diff, auto-summary, fire-and-forget
- auditLog query router: list, getByEntity, getTimeline, getActivitySummary

Audit Coverage (Phase 2 — 14 routers, 50+ mutations):
- vacation: create, approve, reject, cancel, batch ops (8 mutations)
- user: create, updateRole, setPermissions, resetPermissions (5 mutations)
- entitlement: set, bulkSet (3 mutations)
- client: create, update, delete, batchUpdateSortOrder
- org-unit: create, update, deactivate
- country: create, update, createCity, updateCity, deleteCity
- management-level: createGroup, updateGroup, createLevel, updateLevel, deleteLevel
- settings: updateSystemSettings (sensitive fields sanitized), testSmtp
- blueprint: create, update, updateRolePresets, delete, batchDelete, setGlobal
- rate-card: create, update, deactivate, addLine, updateLine, deleteLine, replaceLines
- calculation-rules: create, update, delete
- effort-rule: create, update, delete
- experience-multiplier: create, update, delete
- utilization-category: create, update

Admin UI (Phase 3):
- /admin/activity-log page with global searchable timeline
- Filters: entity type, action, user, date range, text search
- Expandable before/after diff view per entry
- Summary cards showing top entity types by change count
- EntityHistory reusable component for entity detail pages
- Sidebar nav link with clock icon

AI Assistant (Phase 4):
- query_change_history tool: "Who changed project X?"
- get_entity_timeline tool: "What happened to resource Y?"

Regression: 283 engine + 37 staffing tests pass. TypeScript clean.

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-03-22 22:39:30 +01:00
parent 3d117708ff
commit 66878f18f4
25 changed files with 2255 additions and 156 deletions
+140
View File
@@ -1351,6 +1351,40 @@ export const TOOL_DEFINITIONS: ToolDef[] = [
},
},
},
{
type: "function",
function: {
name: "query_change_history",
description: "Search the activity history for changes to projects, resources, allocations, vacations, or any entity. Can filter by entity type, entity name, user, date range, or action type.",
parameters: {
type: "object",
properties: {
entityType: { type: "string", description: "Filter by entity type (e.g. 'Project', 'Resource', 'Allocation', 'Vacation', 'Role', 'Estimate')" },
search: { type: "string", description: "Search in entity name or summary text" },
userId: { type: "string", description: "Filter by user ID who made the change" },
daysBack: { type: "integer", description: "How many days back to search. Default: 7" },
action: { type: "string", description: "Filter by action type: CREATE, UPDATE, DELETE, SHIFT, IMPORT" },
limit: { type: "integer", description: "Max results. Default: 20" },
},
},
},
},
{
type: "function",
function: {
name: "get_entity_timeline",
description: "Get the complete change history for a specific entity (project, resource, etc). Shows who made what changes and when.",
parameters: {
type: "object",
properties: {
entityType: { type: "string", description: "Entity type (e.g. 'Project', 'Resource', 'Allocation')" },
entityId: { type: "string", description: "Entity ID" },
limit: { type: "integer", description: "Max results. Default: 50" },
},
required: ["entityType", "entityId"],
},
},
},
];
// ─── Helpers ────────────────────────────────────────────────────────────────
@@ -5339,6 +5373,112 @@ const executors = {
body: updated.body.slice(0, 100),
};
},
async query_change_history(params: {
entityType?: string;
search?: string;
userId?: string;
daysBack?: number;
action?: string;
limit?: number;
}, ctx: ToolContext) {
const limit = Math.min(params.limit ?? 20, 50);
const daysBack = params.daysBack ?? 7;
const startDate = new Date();
startDate.setDate(startDate.getDate() - daysBack);
const where: Record<string, unknown> = {
createdAt: { gte: startDate },
};
if (params.entityType) where.entityType = params.entityType;
if (params.action) where.action = params.action;
if (params.userId) where.userId = params.userId;
if (params.search) {
where.OR = [
{ entityName: { contains: params.search, mode: "insensitive" } },
{ summary: { contains: params.search, mode: "insensitive" } },
{ entityType: { contains: params.search, mode: "insensitive" } },
];
}
const entries = await ctx.db.auditLog.findMany({
where,
include: {
user: { select: { id: true, name: true, email: true } },
},
orderBy: { createdAt: "desc" },
take: limit,
});
if (entries.length === 0) {
return `No changes found in the last ${daysBack} days matching your criteria.`;
}
const lines = entries.map((e) => {
const who = e.user?.name ?? e.user?.email ?? "System";
const when = e.createdAt.toISOString().slice(0, 16).replace("T", " ");
const name = e.entityName ? ` "${e.entityName}"` : "";
const summary = e.summary ? `${e.summary}` : "";
return `[${when}] ${who}: ${e.action} ${e.entityType}${name}${summary}`;
});
return `Found ${entries.length} changes (last ${daysBack} days):\n\n${lines.join("\n")}`;
},
async get_entity_timeline(params: {
entityType: string;
entityId: string;
limit?: number;
}, ctx: ToolContext) {
const limit = Math.min(params.limit ?? 50, 200);
const entries = await ctx.db.auditLog.findMany({
where: {
entityType: params.entityType,
entityId: params.entityId,
},
include: {
user: { select: { id: true, name: true, email: true } },
},
orderBy: { createdAt: "desc" },
take: limit,
});
if (entries.length === 0) {
return `No change history found for ${params.entityType} ${params.entityId}.`;
}
const entityName = entries[0]?.entityName ?? params.entityId;
const lines = entries.map((e) => {
const who = e.user?.name ?? e.user?.email ?? "System";
const when = e.createdAt.toISOString().slice(0, 16).replace("T", " ");
const summary = e.summary ?? e.action;
const source = e.source ? ` (via ${e.source})` : "";
// Include changed fields summary for UPDATE actions
const changes = e.changes as Record<string, unknown> | null;
const diff = changes?.diff as Record<string, { old: unknown; new: unknown }> | undefined;
let diffSummary = "";
if (diff && Object.keys(diff).length > 0) {
const fields = Object.entries(diff)
.slice(0, 3)
.map(([k, v]) => `${k}: ${JSON.stringify(v.old)}${JSON.stringify(v.new)}`)
.join("; ");
diffSummary = `\n Changed: ${fields}`;
if (Object.keys(diff).length > 3) {
diffSummary += ` (+${Object.keys(diff).length - 3} more)`;
}
}
return `[${when}] ${who}${source}: ${summary}${diffSummary}`;
});
return `Change history for ${params.entityType} "${entityName}" (${entries.length} entries):\n\n${lines.join("\n")}`;
},
};
// ─── Executor ───────────────────────────────────────────────────────────────