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:
@@ -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 ───────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { z } from "zod";
|
||||
import { createTRPCRouter, controllerProcedure } from "../trpc.js";
|
||||
|
||||
// ─── Router ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export const auditLogRouter = createTRPCRouter({
|
||||
/**
|
||||
* Paginated, filterable list of audit log entries.
|
||||
* Cursor-based pagination using createdAt + id.
|
||||
*/
|
||||
list: controllerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
entityType: z.string().optional(),
|
||||
entityId: z.string().optional(),
|
||||
userId: z.string().optional(),
|
||||
action: z.string().optional(),
|
||||
source: z.string().optional(),
|
||||
startDate: z.date().optional(),
|
||||
endDate: z.date().optional(),
|
||||
search: z.string().optional(),
|
||||
limit: z.number().min(1).max(100).default(50),
|
||||
cursor: z.string().optional(), // id of the last item
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const { entityType, entityId, userId, action, source, startDate, endDate, search, limit, cursor } = input;
|
||||
|
||||
const where: Record<string, unknown> = {};
|
||||
|
||||
if (entityType) where.entityType = entityType;
|
||||
if (entityId) where.entityId = entityId;
|
||||
if (userId) where.userId = userId;
|
||||
if (action) where.action = action;
|
||||
if (source) where.source = source;
|
||||
|
||||
if (startDate || endDate) {
|
||||
const createdAt: Record<string, Date> = {};
|
||||
if (startDate) createdAt.gte = startDate;
|
||||
if (endDate) createdAt.lte = endDate;
|
||||
where.createdAt = createdAt;
|
||||
}
|
||||
|
||||
if (search) {
|
||||
where.OR = [
|
||||
{ entityName: { contains: search, mode: "insensitive" } },
|
||||
{ summary: { contains: search, mode: "insensitive" } },
|
||||
{ entityType: { contains: search, mode: "insensitive" } },
|
||||
];
|
||||
}
|
||||
|
||||
const items = await ctx.db.auditLog.findMany({
|
||||
where,
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: limit + 1,
|
||||
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
|
||||
});
|
||||
|
||||
let nextCursor: string | undefined;
|
||||
if (items.length > limit) {
|
||||
const next = items.pop();
|
||||
nextCursor = next?.id;
|
||||
}
|
||||
|
||||
return { items, nextCursor };
|
||||
}),
|
||||
|
||||
/**
|
||||
* Get all audit entries for a specific entity (e.g. a project or resource).
|
||||
*/
|
||||
getByEntity: controllerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
entityType: z.string(),
|
||||
entityId: z.string(),
|
||||
limit: z.number().min(1).max(200).default(50),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
return ctx.db.auditLog.findMany({
|
||||
where: {
|
||||
entityType: input.entityType,
|
||||
entityId: input.entityId,
|
||||
},
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.limit,
|
||||
});
|
||||
}),
|
||||
|
||||
/**
|
||||
* Timeline view: entries grouped by date (YYYY-MM-DD).
|
||||
*/
|
||||
getTimeline: controllerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
startDate: z.date().optional(),
|
||||
endDate: z.date().optional(),
|
||||
limit: z.number().min(1).max(500).default(200),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const where: Record<string, unknown> = {};
|
||||
|
||||
if (input.startDate || input.endDate) {
|
||||
const createdAt: Record<string, Date> = {};
|
||||
if (input.startDate) createdAt.gte = input.startDate;
|
||||
if (input.endDate) createdAt.lte = input.endDate;
|
||||
where.createdAt = createdAt;
|
||||
}
|
||||
|
||||
const entries = await ctx.db.auditLog.findMany({
|
||||
where,
|
||||
include: {
|
||||
user: { select: { id: true, name: true, email: true } },
|
||||
},
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: input.limit,
|
||||
});
|
||||
|
||||
// Group by date string (YYYY-MM-DD)
|
||||
const grouped: Record<string, typeof entries> = {};
|
||||
for (const entry of entries) {
|
||||
const dateKey = entry.createdAt.toISOString().slice(0, 10);
|
||||
if (!grouped[dateKey]) grouped[dateKey] = [];
|
||||
grouped[dateKey].push(entry);
|
||||
}
|
||||
|
||||
return grouped;
|
||||
}),
|
||||
|
||||
/**
|
||||
* Activity summary: counts by entity type, action, and user for a date range.
|
||||
*/
|
||||
getActivitySummary: controllerProcedure
|
||||
.input(
|
||||
z.object({
|
||||
startDate: z.date().optional(),
|
||||
endDate: z.date().optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ ctx, input }) => {
|
||||
const where: Record<string, unknown> = {};
|
||||
|
||||
if (input.startDate || input.endDate) {
|
||||
const createdAt: Record<string, Date> = {};
|
||||
if (input.startDate) createdAt.gte = input.startDate;
|
||||
if (input.endDate) createdAt.lte = input.endDate;
|
||||
where.createdAt = createdAt;
|
||||
}
|
||||
|
||||
// Run aggregation queries in parallel
|
||||
const [byEntityTypeRaw, byActionRaw, byUserRaw, total] = await Promise.all([
|
||||
ctx.db.auditLog.groupBy({
|
||||
by: ["entityType"],
|
||||
where,
|
||||
_count: { id: true },
|
||||
}),
|
||||
ctx.db.auditLog.groupBy({
|
||||
by: ["action"],
|
||||
where,
|
||||
_count: { id: true },
|
||||
}),
|
||||
ctx.db.auditLog.groupBy({
|
||||
by: ["userId"],
|
||||
where,
|
||||
_count: { id: true },
|
||||
orderBy: { _count: { id: "desc" } },
|
||||
take: 20,
|
||||
}),
|
||||
ctx.db.auditLog.count({ where }),
|
||||
]);
|
||||
|
||||
// Convert to simple Record<string, number>
|
||||
const byEntityType: Record<string, number> = {};
|
||||
for (const row of byEntityTypeRaw) {
|
||||
byEntityType[row.entityType] = row._count.id;
|
||||
}
|
||||
|
||||
const byAction: Record<string, number> = {};
|
||||
for (const row of byActionRaw) {
|
||||
byAction[row.action] = row._count.id;
|
||||
}
|
||||
|
||||
// Resolve user names for the top users
|
||||
const userIds = byUserRaw
|
||||
.map((row) => row.userId)
|
||||
.filter((id): id is string => id !== null);
|
||||
|
||||
const users = userIds.length > 0
|
||||
? await ctx.db.user.findMany({
|
||||
where: { id: { in: userIds } },
|
||||
select: { id: true, name: true, email: true },
|
||||
})
|
||||
: [];
|
||||
|
||||
const userMap = new Map(users.map((u) => [u.id, u.name ?? u.email]));
|
||||
|
||||
const byUser = byUserRaw
|
||||
.filter((row) => row.userId !== null)
|
||||
.map((row) => ({
|
||||
name: userMap.get(row.userId!) ?? "Unknown",
|
||||
count: row._count.id,
|
||||
}));
|
||||
|
||||
return { byEntityType, byAction, byUser, total };
|
||||
}),
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { adminProcedure, createTRPCRouter, protectedProcedure } from "../trpc.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
export const blueprintRouter = createTRPCRouter({
|
||||
list: protectedProcedure
|
||||
@@ -35,7 +36,7 @@ export const blueprintRouter = createTRPCRouter({
|
||||
create: adminProcedure
|
||||
.input(CreateBlueprintSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.blueprint.create({
|
||||
const blueprint = await ctx.db.blueprint.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
target: input.target,
|
||||
@@ -45,17 +46,30 @@ export const blueprintRouter = createTRPCRouter({
|
||||
validationRules: input.validationRules as unknown as import("@planarchy/db").Prisma.InputJsonValue,
|
||||
} as unknown as Parameters<typeof ctx.db.blueprint.create>[0]["data"],
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Blueprint",
|
||||
entityId: blueprint.id,
|
||||
entityName: blueprint.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { name: input.name, target: input.target, description: input.description },
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return blueprint;
|
||||
}),
|
||||
|
||||
update: adminProcedure
|
||||
.input(z.object({ id: z.string(), data: UpdateBlueprintSchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const before = await findUniqueOrThrow(
|
||||
ctx.db.blueprint.findUnique({ where: { id: input.id } }),
|
||||
"Blueprint",
|
||||
);
|
||||
|
||||
return ctx.db.blueprint.update({
|
||||
const updated = await ctx.db.blueprint.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.name !== undefined ? { name: input.data.name } : {}),
|
||||
@@ -65,30 +79,71 @@ export const blueprintRouter = createTRPCRouter({
|
||||
...(input.data.validationRules !== undefined ? { validationRules: input.data.validationRules as unknown as import("@planarchy/db").Prisma.InputJsonValue } : {}),
|
||||
} as unknown as Parameters<typeof ctx.db.blueprint.update>[0]["data"],
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Blueprint",
|
||||
entityId: input.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: before as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
/** Dedicated mutation for saving role presets — separate from field defs to avoid Zod depth issues */
|
||||
updateRolePresets: adminProcedure
|
||||
.input(z.object({ id: z.string(), rolePresets: z.array(z.unknown()) }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const before = await findUniqueOrThrow(
|
||||
ctx.db.blueprint.findUnique({ where: { id: input.id } }),
|
||||
"Blueprint",
|
||||
);
|
||||
return ctx.db.blueprint.update({
|
||||
const updated = await ctx.db.blueprint.update({
|
||||
where: { id: input.id },
|
||||
data: { rolePresets: input.rolePresets as unknown as import("@planarchy/db").Prisma.InputJsonValue },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Blueprint",
|
||||
entityId: input.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: { rolePresets: before.rolePresets },
|
||||
after: { rolePresets: input.rolePresets },
|
||||
source: "ui",
|
||||
summary: "Updated role presets",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
delete: adminProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
// Soft delete — mark as inactive
|
||||
return ctx.db.blueprint.update({
|
||||
const deleted = await ctx.db.blueprint.update({
|
||||
where: { id: input.id },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Blueprint",
|
||||
entityId: input.id,
|
||||
entityName: deleted.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return deleted;
|
||||
}),
|
||||
|
||||
batchDelete: adminProcedure
|
||||
@@ -100,6 +155,19 @@ export const blueprintRouter = createTRPCRouter({
|
||||
ctx.db.blueprint.update({ where: { id }, data: { isActive: false } }),
|
||||
),
|
||||
);
|
||||
|
||||
for (const bp of updated) {
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Blueprint",
|
||||
entityId: bp.id,
|
||||
entityName: bp.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
source: "ui",
|
||||
});
|
||||
}
|
||||
|
||||
return { count: updated.length };
|
||||
}),
|
||||
|
||||
@@ -122,9 +190,23 @@ export const blueprintRouter = createTRPCRouter({
|
||||
setGlobal: adminProcedure
|
||||
.input(z.object({ id: z.string(), isGlobal: z.boolean() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.blueprint.update({
|
||||
const updated = await ctx.db.blueprint.update({
|
||||
where: { id: input.id },
|
||||
data: { isGlobal: input.isGlobal },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Blueprint",
|
||||
entityId: input.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { isGlobal: input.isGlobal },
|
||||
source: "ui",
|
||||
summary: input.isGlobal ? "Set blueprint as global" : "Removed global flag from blueprint",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { PROJECT_BRIEF_SELECT } from "../db/selects.js";
|
||||
import { createTRPCRouter, controllerProcedure, managerProcedure } from "../trpc.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
export const calculationRuleRouter = createTRPCRouter({
|
||||
list: controllerProcedure.query(async ({ ctx }) => {
|
||||
@@ -38,7 +39,7 @@ export const calculationRuleRouter = createTRPCRouter({
|
||||
create: managerProcedure
|
||||
.input(CreateCalculationRuleSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.calculationRule.create({
|
||||
const rule = await ctx.db.calculationRule.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
triggerType: input.triggerType,
|
||||
@@ -52,13 +53,26 @@ export const calculationRuleRouter = createTRPCRouter({
|
||||
isActive: input.isActive,
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "CalculationRule",
|
||||
entityId: rule.id,
|
||||
entityName: rule.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: rule as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return rule;
|
||||
}),
|
||||
|
||||
update: managerProcedure
|
||||
.input(UpdateCalculationRuleSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { id, ...data } = input;
|
||||
await findUniqueOrThrow(
|
||||
const before = await findUniqueOrThrow(
|
||||
ctx.db.calculationRule.findUnique({ where: { id } }),
|
||||
"CalculationRule",
|
||||
);
|
||||
@@ -76,20 +90,46 @@ export const calculationRuleRouter = createTRPCRouter({
|
||||
if (data.priority !== undefined) updateData.priority = data.priority;
|
||||
if (data.isActive !== undefined) updateData.isActive = data.isActive;
|
||||
|
||||
return ctx.db.calculationRule.update({
|
||||
const updated = await ctx.db.calculationRule.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "CalculationRule",
|
||||
entityId: id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: before as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
delete: managerProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const rule = await findUniqueOrThrow(
|
||||
ctx.db.calculationRule.findUnique({ where: { id: input.id } }),
|
||||
"CalculationRule",
|
||||
);
|
||||
await ctx.db.calculationRule.delete({ where: { id: input.id } });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "CalculationRule",
|
||||
entityId: input.id,
|
||||
entityName: rule.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: rule as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { CreateClientSchema, UpdateClientSchema } from "@planarchy/shared";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
import { adminProcedure, createTRPCRouter, managerProcedure, protectedProcedure } from "../trpc.js";
|
||||
|
||||
import type { ClientTree } from "@planarchy/shared";
|
||||
@@ -97,7 +98,7 @@ export const clientRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.db.client.create({
|
||||
const created = await ctx.db.client.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
...(input.code ? { code: input.code } : {}),
|
||||
@@ -106,6 +107,19 @@ export const clientRouter = createTRPCRouter({
|
||||
...(input.tags ? { tags: input.tags } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Client",
|
||||
entityId: created.id,
|
||||
entityName: created.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: managerProcedure
|
||||
@@ -123,7 +137,9 @@ export const clientRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.db.client.update({
|
||||
const before = existing as unknown as Record<string, unknown>;
|
||||
|
||||
const updated = await ctx.db.client.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.name !== undefined ? { name: input.data.name } : {}),
|
||||
@@ -134,15 +150,44 @@ export const clientRouter = createTRPCRouter({
|
||||
...(input.data.tags !== undefined ? { tags: input.data.tags } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Client",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
deactivate: managerProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.client.update({
|
||||
const updated = await ctx.db.client.update({
|
||||
where: { id: input.id },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Client",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: { isActive: true },
|
||||
after: { isActive: false },
|
||||
source: "ui",
|
||||
summary: "Deactivated Client",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
delete: adminProcedure
|
||||
@@ -167,7 +212,20 @@ export const clientRouter = createTRPCRouter({
|
||||
message: `Cannot delete client with ${client._count.children} child client(s). Remove children first.`,
|
||||
});
|
||||
}
|
||||
return ctx.db.client.delete({ where: { id: input.id } });
|
||||
await ctx.db.client.delete({ where: { id: input.id } });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Client",
|
||||
entityId: client.id,
|
||||
entityName: client.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: client as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return client;
|
||||
}),
|
||||
|
||||
batchUpdateSortOrder: managerProcedure
|
||||
@@ -181,6 +239,20 @@ export const clientRouter = createTRPCRouter({
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
for (const item of input) {
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Client",
|
||||
entityId: item.id,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { sortOrder: item.sortOrder },
|
||||
source: "ui",
|
||||
summary: "Updated sort order",
|
||||
});
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Prisma } from "@planarchy/db";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
import { adminProcedure, createTRPCRouter, protectedProcedure } from "../trpc.js";
|
||||
|
||||
/** Convert nullable JSON to Prisma-compatible value (null → Prisma.JsonNull). */
|
||||
@@ -52,7 +53,7 @@ export const countryRouter = createTRPCRouter({
|
||||
if (existing) {
|
||||
throw new TRPCError({ code: "CONFLICT", message: `Country code "${input.code}" already exists` });
|
||||
}
|
||||
return ctx.db.country.create({
|
||||
const created = await ctx.db.country.create({
|
||||
data: {
|
||||
code: input.code,
|
||||
name: input.name,
|
||||
@@ -61,6 +62,19 @@ export const countryRouter = createTRPCRouter({
|
||||
},
|
||||
include: { metroCities: true },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Country",
|
||||
entityId: created.id,
|
||||
entityName: created.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: adminProcedure
|
||||
@@ -78,7 +92,9 @@ export const countryRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.db.country.update({
|
||||
const before = existing as unknown as Record<string, unknown>;
|
||||
|
||||
const updated = await ctx.db.country.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.code !== undefined ? { code: input.data.code } : {}),
|
||||
@@ -89,6 +105,20 @@ export const countryRouter = createTRPCRouter({
|
||||
},
|
||||
include: { metroCities: true },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Country",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
// ─── Metro City ─────────────────────────────────────────────
|
||||
@@ -101,18 +131,51 @@ export const countryRouter = createTRPCRouter({
|
||||
"Country",
|
||||
);
|
||||
|
||||
return ctx.db.metroCity.create({
|
||||
const created = await ctx.db.metroCity.create({
|
||||
data: { name: input.name, countryId: input.countryId },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "MetroCity",
|
||||
entityId: created.id,
|
||||
entityName: created.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
updateCity: adminProcedure
|
||||
.input(z.object({ id: z.string(), data: UpdateMetroCitySchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.metroCity.update({
|
||||
const existing = await findUniqueOrThrow(
|
||||
ctx.db.metroCity.findUnique({ where: { id: input.id } }),
|
||||
"Metro city",
|
||||
);
|
||||
const before = existing as unknown as Record<string, unknown>;
|
||||
|
||||
const updated = await ctx.db.metroCity.update({
|
||||
where: { id: input.id },
|
||||
data: { ...(input.data.name !== undefined ? { name: input.data.name } : {}) },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "MetroCity",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
deleteCity: adminProcedure
|
||||
@@ -132,6 +195,18 @@ export const countryRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
await ctx.db.metroCity.delete({ where: { id: input.id } });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "MetroCity",
|
||||
entityId: city.id,
|
||||
entityName: city.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: city as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createTRPCRouter, controllerProcedure, managerProcedure } from "../trpc.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
const ruleInclude = {
|
||||
rules: { orderBy: { sortOrder: "asc" as const } },
|
||||
@@ -50,7 +51,7 @@ export const effortRuleRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
return ctx.db.effortRuleSet.create({
|
||||
const ruleSet = await ctx.db.effortRuleSet.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
...(input.description ? { description: input.description } : {}),
|
||||
@@ -69,13 +70,26 @@ export const effortRuleRouter = createTRPCRouter({
|
||||
},
|
||||
include: ruleInclude,
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "EffortRuleSet",
|
||||
entityId: ruleSet.id,
|
||||
entityName: ruleSet.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { name: input.name, isDefault: input.isDefault, ruleCount: input.rules.length },
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return ruleSet;
|
||||
}),
|
||||
|
||||
update: managerProcedure
|
||||
.input(UpdateEffortRuleSetSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
ctx.db.effortRuleSet.findUnique({ where: { id: input.id } }),
|
||||
const before = await findUniqueOrThrow(
|
||||
ctx.db.effortRuleSet.findUnique({ where: { id: input.id }, include: ruleInclude }),
|
||||
"Effort rule set",
|
||||
);
|
||||
|
||||
@@ -104,7 +118,7 @@ export const effortRuleRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
return ctx.db.effortRuleSet.update({
|
||||
const updated = await ctx.db.effortRuleSet.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.name !== undefined ? { name: input.name } : {}),
|
||||
@@ -113,16 +127,41 @@ export const effortRuleRouter = createTRPCRouter({
|
||||
},
|
||||
include: ruleInclude,
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "EffortRuleSet",
|
||||
entityId: input.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: { name: before.name, isDefault: before.isDefault, ruleCount: before.rules.length },
|
||||
after: { name: updated.name, isDefault: updated.isDefault, ruleCount: updated.rules.length },
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
delete: managerProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const ruleSet = await findUniqueOrThrow(
|
||||
ctx.db.effortRuleSet.findUnique({ where: { id: input.id } }),
|
||||
"Effort rule set",
|
||||
);
|
||||
await ctx.db.effortRuleSet.delete({ where: { id: input.id } });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "EffortRuleSet",
|
||||
entityId: input.id,
|
||||
entityName: ruleSet.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return { id: input.id };
|
||||
}),
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { RESOURCE_BRIEF_SELECT } from "../db/selects.js";
|
||||
import { createTRPCRouter, adminProcedure, managerProcedure, protectedProcedure } from "../trpc.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
/** Types that consume from annual leave balance */
|
||||
const BALANCE_TYPES: VacationType[] = [VacationType.ANNUAL, VacationType.OTHER];
|
||||
@@ -189,12 +190,27 @@ export const entitlementRouter = createTRPCRouter({
|
||||
where: { resourceId_year: { resourceId: input.resourceId, year: input.year } },
|
||||
});
|
||||
if (existing) {
|
||||
return ctx.db.vacationEntitlement.update({
|
||||
const updated = await ctx.db.vacationEntitlement.update({
|
||||
where: { id: existing.id },
|
||||
data: { entitledDays: input.entitledDays },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "VacationEntitlement",
|
||||
entityId: updated.id,
|
||||
entityName: `Entitlement ${input.resourceId} / ${input.year}`,
|
||||
action: "UPDATE",
|
||||
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
|
||||
before: existing as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Updated entitlement from ${existing.entitledDays} to ${input.entitledDays} days (${input.year})`,
|
||||
});
|
||||
|
||||
return updated;
|
||||
}
|
||||
return ctx.db.vacationEntitlement.create({
|
||||
const created = await ctx.db.vacationEntitlement.create({
|
||||
data: {
|
||||
resourceId: input.resourceId,
|
||||
year: input.year,
|
||||
@@ -204,6 +220,20 @@ export const entitlementRouter = createTRPCRouter({
|
||||
pendingDays: 0,
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "VacationEntitlement",
|
||||
entityId: created.id,
|
||||
entityName: `Entitlement ${input.resourceId} / ${input.year}`,
|
||||
action: "CREATE",
|
||||
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Set entitlement to ${input.entitledDays} days (${input.year})`,
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
/**
|
||||
@@ -244,6 +274,18 @@ export const entitlementRouter = createTRPCRouter({
|
||||
updated++;
|
||||
}
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "VacationEntitlement",
|
||||
entityId: `bulk-${input.year}`,
|
||||
entityName: `Bulk Entitlement ${input.year}`,
|
||||
action: "UPDATE",
|
||||
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
|
||||
after: { year: input.year, entitledDays: input.entitledDays, resourceCount: updated } as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Bulk set entitlement to ${input.entitledDays} days for ${updated} resources (${input.year})`,
|
||||
});
|
||||
|
||||
return { updated };
|
||||
}),
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createTRPCRouter, controllerProcedure, managerProcedure } from "../trpc.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
const ruleInclude = {
|
||||
rules: { orderBy: { sortOrder: "asc" as const } },
|
||||
@@ -72,7 +73,7 @@ export const experienceMultiplierRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
return ctx.db.experienceMultiplierSet.create({
|
||||
const set = await ctx.db.experienceMultiplierSet.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
...(input.description ? { description: input.description } : {}),
|
||||
@@ -93,13 +94,26 @@ export const experienceMultiplierRouter = createTRPCRouter({
|
||||
},
|
||||
include: ruleInclude,
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ExperienceMultiplierSet",
|
||||
entityId: set.id,
|
||||
entityName: set.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { name: input.name, isDefault: input.isDefault, ruleCount: input.rules.length },
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return set;
|
||||
}),
|
||||
|
||||
update: managerProcedure
|
||||
.input(UpdateExperienceMultiplierSetSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
ctx.db.experienceMultiplierSet.findUnique({ where: { id: input.id } }),
|
||||
const before = await findUniqueOrThrow(
|
||||
ctx.db.experienceMultiplierSet.findUnique({ where: { id: input.id }, include: ruleInclude }),
|
||||
"Experience multiplier set",
|
||||
);
|
||||
|
||||
@@ -128,7 +142,7 @@ export const experienceMultiplierRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
return ctx.db.experienceMultiplierSet.update({
|
||||
const updated = await ctx.db.experienceMultiplierSet.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.name !== undefined ? { name: input.name } : {}),
|
||||
@@ -137,16 +151,41 @@ export const experienceMultiplierRouter = createTRPCRouter({
|
||||
},
|
||||
include: ruleInclude,
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ExperienceMultiplierSet",
|
||||
entityId: input.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: { name: before.name, isDefault: before.isDefault, ruleCount: before.rules.length },
|
||||
after: { name: updated.name, isDefault: updated.isDefault, ruleCount: updated.rules.length },
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
delete: managerProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const set = await findUniqueOrThrow(
|
||||
ctx.db.experienceMultiplierSet.findUnique({ where: { id: input.id } }),
|
||||
"Experience multiplier set",
|
||||
);
|
||||
await ctx.db.experienceMultiplierSet.delete({ where: { id: input.id } });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ExperienceMultiplierSet",
|
||||
entityId: input.id,
|
||||
entityName: set.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return { id: input.id };
|
||||
}),
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createTRPCRouter } from "../trpc.js";
|
||||
import { allocationRouter } from "./allocation.js";
|
||||
import { assistantRouter } from "./assistant.js";
|
||||
import { auditLogRouter } from "./audit-log.js";
|
||||
import { calculationRuleRouter } from "./calculation-rules.js";
|
||||
import { blueprintRouter } from "./blueprint.js";
|
||||
import { chargeabilityReportRouter } from "./chargeability-report.js";
|
||||
@@ -36,6 +37,7 @@ import { webhookRouter } from "./webhook.js";
|
||||
|
||||
export const appRouter = createTRPCRouter({
|
||||
assistant: assistantRouter,
|
||||
auditLog: auditLogRouter,
|
||||
dashboard: dashboardRouter,
|
||||
dispo: dispoRouter,
|
||||
effortRule: effortRuleRouter,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
import { adminProcedure, createTRPCRouter, protectedProcedure } from "../trpc.js";
|
||||
|
||||
export const managementLevelRouter = createTRPCRouter({
|
||||
@@ -42,7 +43,7 @@ export const managementLevelRouter = createTRPCRouter({
|
||||
if (existing) {
|
||||
throw new TRPCError({ code: "CONFLICT", message: `Group "${input.name}" already exists` });
|
||||
}
|
||||
return ctx.db.managementLevelGroup.create({
|
||||
const created = await ctx.db.managementLevelGroup.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
targetPercentage: input.targetPercentage,
|
||||
@@ -50,6 +51,19 @@ export const managementLevelRouter = createTRPCRouter({
|
||||
},
|
||||
include: { levels: true },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ManagementLevelGroup",
|
||||
entityId: created.id,
|
||||
entityName: created.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
updateGroup: adminProcedure
|
||||
@@ -67,7 +81,9 @@ export const managementLevelRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.db.managementLevelGroup.update({
|
||||
const before = existing as unknown as Record<string, unknown>;
|
||||
|
||||
const updated = await ctx.db.managementLevelGroup.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.name !== undefined ? { name: input.data.name } : {}),
|
||||
@@ -76,6 +92,20 @@ export const managementLevelRouter = createTRPCRouter({
|
||||
},
|
||||
include: { levels: true },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ManagementLevelGroup",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
// ─── Levels ─────────────────────────────────────────────
|
||||
@@ -93,9 +123,22 @@ export const managementLevelRouter = createTRPCRouter({
|
||||
throw new TRPCError({ code: "CONFLICT", message: `Level "${input.name}" already exists` });
|
||||
}
|
||||
|
||||
return ctx.db.managementLevel.create({
|
||||
const created = await ctx.db.managementLevel.create({
|
||||
data: { name: input.name, groupId: input.groupId },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ManagementLevel",
|
||||
entityId: created.id,
|
||||
entityName: created.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
updateLevel: adminProcedure
|
||||
@@ -113,13 +156,29 @@ export const managementLevelRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.db.managementLevel.update({
|
||||
const before = existing as unknown as Record<string, unknown>;
|
||||
|
||||
const updated = await ctx.db.managementLevel.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.name !== undefined ? { name: input.data.name } : {}),
|
||||
...(input.data.groupId !== undefined ? { groupId: input.data.groupId } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ManagementLevel",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
deleteLevel: adminProcedure
|
||||
@@ -139,6 +198,18 @@ export const managementLevelRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
await ctx.db.managementLevel.delete({ where: { id: input.id } });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "ManagementLevel",
|
||||
entityId: level.id,
|
||||
entityName: level.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: level as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { CreateOrgUnitSchema, UpdateOrgUnitSchema } from "@planarchy/shared";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
import { adminProcedure, createTRPCRouter, protectedProcedure } from "../trpc.js";
|
||||
|
||||
import type { OrgUnitTree } from "@planarchy/shared";
|
||||
@@ -93,7 +94,7 @@ export const orgUnitRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.db.orgUnit.create({
|
||||
const created = await ctx.db.orgUnit.create({
|
||||
data: {
|
||||
name: input.name,
|
||||
...(input.shortName !== undefined ? { shortName: input.shortName } : {}),
|
||||
@@ -102,17 +103,32 @@ export const orgUnitRouter = createTRPCRouter({
|
||||
sortOrder: input.sortOrder,
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "OrgUnit",
|
||||
entityId: created.id,
|
||||
entityName: created.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: adminProcedure
|
||||
.input(z.object({ id: z.string(), data: UpdateOrgUnitSchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const existing = await findUniqueOrThrow(
|
||||
ctx.db.orgUnit.findUnique({ where: { id: input.id } }),
|
||||
"Org unit",
|
||||
);
|
||||
|
||||
return ctx.db.orgUnit.update({
|
||||
const before = existing as unknown as Record<string, unknown>;
|
||||
|
||||
const updated = await ctx.db.orgUnit.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.name !== undefined ? { name: input.data.name } : {}),
|
||||
@@ -122,14 +138,43 @@ export const orgUnitRouter = createTRPCRouter({
|
||||
...(input.data.parentId !== undefined ? { parentId: input.data.parentId } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "OrgUnit",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
deactivate: adminProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.orgUnit.update({
|
||||
const updated = await ctx.db.orgUnit.update({
|
||||
where: { id: input.id },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "OrgUnit",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: { isActive: true },
|
||||
after: { isActive: false },
|
||||
source: "ui",
|
||||
summary: "Deactivated OrgUnit",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createTRPCRouter, controllerProcedure, managerProcedure } from "../trpc.js";
|
||||
import { ROLE_BRIEF_SELECT } from "../db/selects.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
const lineSelect = {
|
||||
id: true,
|
||||
@@ -96,7 +97,7 @@ export const rateCardRouter = createTRPCRouter({
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const { lines, ...cardData } = input;
|
||||
|
||||
return ctx.db.rateCard.create({
|
||||
const rateCard = await ctx.db.rateCard.create({
|
||||
data: {
|
||||
name: cardData.name,
|
||||
currency: cardData.currency,
|
||||
@@ -123,17 +124,30 @@ export const rateCardRouter = createTRPCRouter({
|
||||
lines: { select: lineSelect },
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "RateCard",
|
||||
entityId: rateCard.id,
|
||||
entityName: rateCard.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { name: cardData.name, currency: cardData.currency, lineCount: lines.length },
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return rateCard;
|
||||
}),
|
||||
|
||||
update: managerProcedure
|
||||
.input(z.object({ id: z.string(), data: UpdateRateCardSchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const before = await findUniqueOrThrow(
|
||||
ctx.db.rateCard.findUnique({ where: { id: input.id } }),
|
||||
"Rate card",
|
||||
);
|
||||
|
||||
return ctx.db.rateCard.update({
|
||||
const updated = await ctx.db.rateCard.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.name !== undefined ? { name: input.data.name } : {}),
|
||||
@@ -149,15 +163,42 @@ export const rateCardRouter = createTRPCRouter({
|
||||
client: { select: { id: true, name: true, code: true } },
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "RateCard",
|
||||
entityId: input.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: before as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
deactivate: managerProcedure
|
||||
.input(z.object({ id: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.rateCard.update({
|
||||
const deactivated = await ctx.db.rateCard.update({
|
||||
where: { id: input.id },
|
||||
data: { isActive: false },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "RateCard",
|
||||
entityId: input.id,
|
||||
entityName: deactivated.name,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
source: "ui",
|
||||
summary: "Deactivated rate card",
|
||||
});
|
||||
|
||||
return deactivated;
|
||||
}),
|
||||
|
||||
// ─── Line CRUD ─────────────────────────────────────────────────────────────
|
||||
@@ -165,12 +206,12 @@ export const rateCardRouter = createTRPCRouter({
|
||||
addLine: managerProcedure
|
||||
.input(z.object({ rateCardId: z.string(), line: CreateRateCardLineSchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const rateCard = await findUniqueOrThrow(
|
||||
ctx.db.rateCard.findUnique({ where: { id: input.rateCardId } }),
|
||||
"Rate card",
|
||||
);
|
||||
|
||||
return ctx.db.rateCardLine.create({
|
||||
const line = await ctx.db.rateCardLine.create({
|
||||
data: {
|
||||
rateCardId: input.rateCardId,
|
||||
...(input.line.roleId !== undefined ? { roleId: input.line.roleId } : {}),
|
||||
@@ -186,12 +227,25 @@ export const rateCardRouter = createTRPCRouter({
|
||||
},
|
||||
select: lineSelect,
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "RateCardLine",
|
||||
entityId: line.id,
|
||||
entityName: `${rateCard.name} — ${input.line.chapter ?? "line"}`,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { rateCardId: input.rateCardId, costRateCents: input.line.costRateCents, billRateCents: input.line.billRateCents },
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return line;
|
||||
}),
|
||||
|
||||
updateLine: managerProcedure
|
||||
.input(z.object({ lineId: z.string(), data: UpdateRateCardLineSchema }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const before = await findUniqueOrThrow(
|
||||
ctx.db.rateCardLine.findUnique({ where: { id: input.lineId } }),
|
||||
"Rate card line",
|
||||
);
|
||||
@@ -208,22 +262,46 @@ export const rateCardRouter = createTRPCRouter({
|
||||
if (input.data.machineRateCents !== undefined) updateData.machineRateCents = input.data.machineRateCents;
|
||||
if (input.data.attributes !== undefined) updateData.attributes = input.data.attributes as Prisma.InputJsonValue;
|
||||
|
||||
return ctx.db.rateCardLine.update({
|
||||
const updated = await ctx.db.rateCardLine.update({
|
||||
where: { id: input.lineId },
|
||||
data: updateData,
|
||||
select: lineSelect,
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "RateCardLine",
|
||||
entityId: input.lineId,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: before as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
deleteLine: managerProcedure
|
||||
.input(z.object({ lineId: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const line = await findUniqueOrThrow(
|
||||
ctx.db.rateCardLine.findUnique({ where: { id: input.lineId } }),
|
||||
"Rate card line",
|
||||
);
|
||||
|
||||
await ctx.db.rateCardLine.delete({ where: { id: input.lineId } });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "RateCardLine",
|
||||
entityId: input.lineId,
|
||||
action: "DELETE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before: line as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return { deleted: true };
|
||||
}),
|
||||
|
||||
@@ -235,12 +313,12 @@ export const rateCardRouter = createTRPCRouter({
|
||||
lines: z.array(CreateRateCardLineSchema),
|
||||
}))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await findUniqueOrThrow(
|
||||
const rateCard = await findUniqueOrThrow(
|
||||
ctx.db.rateCard.findUnique({ where: { id: input.rateCardId } }),
|
||||
"Rate card",
|
||||
);
|
||||
|
||||
return ctx.db.$transaction(async (tx) => {
|
||||
const result = await ctx.db.$transaction(async (tx) => {
|
||||
await tx.rateCardLine.deleteMany({ where: { rateCardId: input.rateCardId } });
|
||||
|
||||
const created = await Promise.all(
|
||||
@@ -266,6 +344,20 @@ export const rateCardRouter = createTRPCRouter({
|
||||
|
||||
return created;
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "RateCard",
|
||||
entityId: input.rateCardId,
|
||||
entityName: rateCard.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { replacedLineCount: result.length },
|
||||
source: "ui",
|
||||
summary: `Replaced all lines with ${result.length} new lines`,
|
||||
});
|
||||
|
||||
return result;
|
||||
}),
|
||||
|
||||
// ─── Rate resolution ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -4,6 +4,15 @@ import { createAiClient, isAiConfigured, parseAiError } from "../ai-client.js";
|
||||
import { DEFAULT_SUMMARY_PROMPT } from "./resource.js";
|
||||
import { VALUE_SCORE_WEIGHTS } from "@planarchy/shared";
|
||||
import { testSmtpConnection } from "../lib/email.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
/** Fields that must never appear in audit log values */
|
||||
const SENSITIVE_FIELDS = new Set([
|
||||
"azureOpenAiApiKey",
|
||||
"smtpPassword",
|
||||
"azureDalleApiKey",
|
||||
"anonymizationSeed",
|
||||
]);
|
||||
|
||||
export const settingsRouter = createTRPCRouter({
|
||||
getSystemSettings: adminProcedure.query(async ({ ctx }) => {
|
||||
@@ -151,12 +160,39 @@ export const settingsRouter = createTRPCRouter({
|
||||
// Timeline
|
||||
if (input.timelineUndoMaxSteps !== undefined) data.timelineUndoMaxSteps = input.timelineUndoMaxSteps;
|
||||
|
||||
// Fetch current settings for before-snapshot
|
||||
const before = await ctx.db.systemSettings.findUnique({ where: { id: "singleton" } });
|
||||
|
||||
await ctx.db.systemSettings.upsert({
|
||||
where: { id: "singleton" },
|
||||
create: { id: "singleton", ...data },
|
||||
update: data,
|
||||
});
|
||||
|
||||
// Build sanitized snapshots — redact sensitive fields
|
||||
const sanitize = (obj: Record<string, unknown>): Record<string, unknown> => {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
result[key] = SENSITIVE_FIELDS.has(key) ? (value ? "***" : null) : value;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
const sanitizedBefore = before ? sanitize(before as unknown as Record<string, unknown>) : undefined;
|
||||
const sanitizedAfter = sanitize(data);
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "SystemSettings",
|
||||
entityId: "singleton",
|
||||
entityName: "System Settings",
|
||||
action: before ? "UPDATE" : "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
...(sanitizedBefore !== undefined ? { before: sanitizedBefore } : {}),
|
||||
after: sanitizedAfter,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return { ok: true };
|
||||
}),
|
||||
|
||||
@@ -246,8 +282,22 @@ export const settingsRouter = createTRPCRouter({
|
||||
}
|
||||
}),
|
||||
|
||||
testSmtpConnection: adminProcedure.mutation(async () => {
|
||||
return testSmtpConnection();
|
||||
testSmtpConnection: adminProcedure.mutation(async ({ ctx }) => {
|
||||
const result = await testSmtpConnection();
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "SystemSettings",
|
||||
entityId: "singleton",
|
||||
entityName: "SMTP Connection Test",
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: { testResult: result.ok ? "success" : "failed" },
|
||||
source: "ui",
|
||||
summary: result.ok ? "SMTP connection test succeeded" : "SMTP connection test failed",
|
||||
});
|
||||
|
||||
return result;
|
||||
}),
|
||||
|
||||
getAiConfigured: protectedProcedure.query(async ({ ctx }) => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { adminProcedure, createTRPCRouter, managerProcedure, protectedProcedure } from "../trpc.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
export const userRouter = createTRPCRouter({
|
||||
/** Lightweight user list for task assignment (ADMIN + MANAGER) */
|
||||
@@ -111,6 +112,17 @@ export const userRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "User",
|
||||
entityId: user.id,
|
||||
entityName: `${user.name} (${user.email})`,
|
||||
action: "CREATE",
|
||||
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
|
||||
after: user as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return user;
|
||||
}),
|
||||
|
||||
@@ -122,11 +134,31 @@ export const userRouter = createTRPCRouter({
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.user.update({
|
||||
const before = await ctx.db.user.findUniqueOrThrow({
|
||||
where: { id: input.id },
|
||||
select: { id: true, name: true, email: true, systemRole: true },
|
||||
});
|
||||
|
||||
const updated = await ctx.db.user.update({
|
||||
where: { id: input.id },
|
||||
data: { systemRole: input.systemRole },
|
||||
select: { id: true, name: true, email: true, systemRole: true },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "User",
|
||||
entityId: updated.id,
|
||||
entityName: `${updated.name} (${updated.email})`,
|
||||
action: "UPDATE",
|
||||
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
|
||||
before: before as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Changed role from ${before.systemRole} to ${updated.systemRole}`,
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
// ─── Resource Linking ──────────────────────────────────────────────────
|
||||
@@ -242,20 +274,61 @@ export const userRouter = createTRPCRouter({
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const before = await ctx.db.user.findUniqueOrThrow({
|
||||
where: { id: input.userId },
|
||||
select: { id: true, name: true, email: true, permissionOverrides: true },
|
||||
});
|
||||
|
||||
const user = await ctx.db.user.update({
|
||||
where: { id: input.userId },
|
||||
data: { permissionOverrides: input.overrides ?? Prisma.DbNull },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "User",
|
||||
entityId: input.userId,
|
||||
entityName: `${before.name} (${before.email})`,
|
||||
action: "UPDATE",
|
||||
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
|
||||
before: { permissionOverrides: before.permissionOverrides } as unknown as Record<string, unknown>,
|
||||
after: { permissionOverrides: input.overrides } as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: input.overrides
|
||||
? `Set permission overrides (granted: ${input.overrides.granted?.length ?? 0}, denied: ${input.overrides.denied?.length ?? 0})`
|
||||
: "Cleared permission overrides",
|
||||
});
|
||||
|
||||
return user;
|
||||
}),
|
||||
|
||||
resetPermissions: adminProcedure
|
||||
.input(z.object({ userId: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
return ctx.db.user.update({
|
||||
const before = await ctx.db.user.findUniqueOrThrow({
|
||||
where: { id: input.userId },
|
||||
select: { id: true, name: true, email: true, permissionOverrides: true },
|
||||
});
|
||||
|
||||
const updated = await ctx.db.user.update({
|
||||
where: { id: input.userId },
|
||||
data: { permissionOverrides: Prisma.DbNull },
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "User",
|
||||
entityId: input.userId,
|
||||
entityName: `${before.name} (${before.email})`,
|
||||
action: "UPDATE",
|
||||
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
|
||||
before: { permissionOverrides: before.permissionOverrides } as unknown as Record<string, unknown>,
|
||||
after: { permissionOverrides: null } as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: "Reset permission overrides to role defaults",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
getColumnPreferences: protectedProcedure.query(async ({ ctx }) => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod";
|
||||
import { findUniqueOrThrow } from "../db/helpers.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
import { adminProcedure, createTRPCRouter, protectedProcedure } from "../trpc.js";
|
||||
|
||||
export const utilizationCategoryRouter = createTRPCRouter({
|
||||
@@ -48,7 +49,7 @@ export const utilizationCategoryRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
return ctx.db.utilizationCategory.create({
|
||||
const created = await ctx.db.utilizationCategory.create({
|
||||
data: {
|
||||
code: input.code,
|
||||
name: input.name,
|
||||
@@ -57,6 +58,19 @@ export const utilizationCategoryRouter = createTRPCRouter({
|
||||
isDefault: input.isDefault,
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "UtilizationCategory",
|
||||
entityId: created.id,
|
||||
entityName: created.name,
|
||||
action: "CREATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
after: created as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return created;
|
||||
}),
|
||||
|
||||
update: adminProcedure
|
||||
@@ -82,7 +96,9 @@ export const utilizationCategoryRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
return ctx.db.utilizationCategory.update({
|
||||
const before = existing as unknown as Record<string, unknown>;
|
||||
|
||||
const updated = await ctx.db.utilizationCategory.update({
|
||||
where: { id: input.id },
|
||||
data: {
|
||||
...(input.data.code !== undefined ? { code: input.data.code } : {}),
|
||||
@@ -93,5 +109,19 @@ export const utilizationCategoryRouter = createTRPCRouter({
|
||||
...(input.data.isDefault !== undefined ? { isDefault: input.data.isDefault } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "UtilizationCategory",
|
||||
entityId: updated.id,
|
||||
entityName: updated.name,
|
||||
action: "UPDATE",
|
||||
userId: ctx.dbUser?.id,
|
||||
before,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import { sendEmail } from "../lib/email.js";
|
||||
import { anonymizeResource, anonymizeUser, getAnonymizationDirectory } from "../lib/anonymization.js";
|
||||
import { checkVacationConflicts, checkBatchVacationConflicts } from "../lib/vacation-conflicts.js";
|
||||
import { dispatchWebhooks } from "../lib/webhook-dispatcher.js";
|
||||
import { createAuditEntry } from "../lib/audit.js";
|
||||
|
||||
/** Types that consume from annual leave balance */
|
||||
const BALANCE_TYPES = [VacationType.ANNUAL, VacationType.OTHER];
|
||||
@@ -219,6 +220,17 @@ export const vacationRouter = createTRPCRouter({
|
||||
|
||||
emitVacationCreated({ id: vacation.id, resourceId: vacation.resourceId, status: vacation.status });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: vacation.id,
|
||||
entityName: `${vacation.resource?.displayName ?? "Unknown"} - ${vacation.type}`,
|
||||
action: "CREATE",
|
||||
userId: userRecord.id,
|
||||
after: vacation as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
});
|
||||
|
||||
// Create approval tasks for managers when a non-manager submits a vacation request
|
||||
if (status === VacationStatus.PENDING) {
|
||||
const resourceName = vacation.resource?.displayName ?? "Unknown";
|
||||
@@ -291,6 +303,20 @@ export const vacationRouter = createTRPCRouter({
|
||||
});
|
||||
|
||||
emitVacationUpdated({ id: updated.id, resourceId: updated.resourceId, status: updated.status });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: updated.id,
|
||||
entityName: `Vacation ${updated.id}`,
|
||||
action: "UPDATE",
|
||||
...(userRecord?.id ? { userId: userRecord.id } : {}),
|
||||
before: existing as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Approved vacation (was ${existing.status})`,
|
||||
});
|
||||
|
||||
void dispatchWebhooks(ctx.db, "vacation.approved", {
|
||||
id: updated.id,
|
||||
resourceId: updated.resourceId,
|
||||
@@ -361,6 +387,19 @@ export const vacationRouter = createTRPCRouter({
|
||||
},
|
||||
});
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: updated.id,
|
||||
entityName: `Vacation ${updated.id}`,
|
||||
action: "UPDATE",
|
||||
...(userRecord?.id ? { userId: userRecord.id } : {}),
|
||||
before: existing as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Rejected vacation${input.rejectionReason ? `: ${input.rejectionReason}` : ""}`,
|
||||
});
|
||||
|
||||
void notifyVacationStatus(ctx.db, updated.id, updated.resourceId, VacationStatus.REJECTED, input.rejectionReason);
|
||||
|
||||
return updated;
|
||||
@@ -404,6 +443,18 @@ export const vacationRouter = createTRPCRouter({
|
||||
emitVacationUpdated({ id: v.id, resourceId: v.resourceId, status: VacationStatus.APPROVED });
|
||||
void notifyVacationStatus(ctx.db, v.id, v.resourceId, VacationStatus.APPROVED);
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: v.id,
|
||||
entityName: `Vacation ${v.id}`,
|
||||
action: "UPDATE",
|
||||
...(userRecord?.id ? { userId: userRecord.id } : {}),
|
||||
after: { status: VacationStatus.APPROVED } as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: "Batch approved vacation",
|
||||
});
|
||||
|
||||
// Mark approval tasks as DONE
|
||||
await ctx.db.notification.updateMany({
|
||||
where: {
|
||||
@@ -461,6 +512,18 @@ export const vacationRouter = createTRPCRouter({
|
||||
emitVacationUpdated({ id: v.id, resourceId: v.resourceId, status: VacationStatus.REJECTED });
|
||||
void notifyVacationStatus(ctx.db, v.id, v.resourceId, VacationStatus.REJECTED, input.rejectionReason);
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: v.id,
|
||||
entityName: `Vacation ${v.id}`,
|
||||
action: "UPDATE",
|
||||
...(userRecord?.id ? { userId: userRecord.id } : {}),
|
||||
after: { status: VacationStatus.REJECTED, rejectionReason: input.rejectionReason } as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Batch rejected vacation${input.rejectionReason ? `: ${input.rejectionReason}` : ""}`,
|
||||
});
|
||||
|
||||
// Mark approval tasks as DONE
|
||||
await ctx.db.notification.updateMany({
|
||||
where: {
|
||||
@@ -523,6 +586,20 @@ export const vacationRouter = createTRPCRouter({
|
||||
});
|
||||
|
||||
emitVacationUpdated({ id: updated.id, resourceId: updated.resourceId, status: updated.status });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: updated.id,
|
||||
entityName: `Vacation ${updated.id}`,
|
||||
action: "UPDATE",
|
||||
userId: userRecord.id,
|
||||
before: existing as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Cancelled vacation (was ${existing.status})`,
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
|
||||
@@ -687,6 +764,18 @@ export const vacationRouter = createTRPCRouter({
|
||||
}
|
||||
}
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: `public-holidays-${input.year}`,
|
||||
entityName: `Public Holidays ${input.year}${input.federalState ? ` (${input.federalState})` : ""}`,
|
||||
action: "CREATE",
|
||||
userId: adminUser.id,
|
||||
after: { created, holidays: holidays.length, resources: resources.length, year: input.year, federalState: input.federalState } as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Batch created ${created} public holidays for ${resources.length} resources (${input.year})`,
|
||||
});
|
||||
|
||||
return { created, holidays: holidays.length, resources: resources.length };
|
||||
}),
|
||||
|
||||
@@ -729,6 +818,20 @@ export const vacationRouter = createTRPCRouter({
|
||||
});
|
||||
|
||||
emitVacationUpdated({ id: updated.id, resourceId: updated.resourceId, status: updated.status });
|
||||
|
||||
void createAuditEntry({
|
||||
db: ctx.db,
|
||||
entityType: "Vacation",
|
||||
entityId: updated.id,
|
||||
entityName: `Vacation ${updated.id}`,
|
||||
action: "UPDATE",
|
||||
userId: userRecord.id,
|
||||
before: existing as unknown as Record<string, unknown>,
|
||||
after: updated as unknown as Record<string, unknown>,
|
||||
source: "ui",
|
||||
summary: `Updated vacation status to ${input.status}`,
|
||||
});
|
||||
|
||||
return updated;
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user