Files
CapaKraken/packages/api/src/trpc.ts
T
Hartmut fbeab5cd79 feat: Sprint 5 — AI insights, webhooks/Slack, PWA, performance monitoring
AI-Powered Insights (G9):
- Rule-based anomaly detection: budget burn rate, staffing gaps, utilization,
  timeline overruns across all active projects
- AI narrative generation via existing Azure OpenAI integration
- Cached in project dynamicFields to avoid regeneration
- New /analytics/insights page with anomaly feed + project summaries
- Sidebar nav: "AI Insights" under Analytics

Webhook System + Slack (G10):
- Webhook model in Prisma (url, secret, events, isActive)
- HMAC-SHA256 signed payloads with 5s timeout fire-and-forget dispatch
- Slack-aware: routes hooks.slack.com URLs through Slack formatter
- 6 events integrated: allocation.created/updated/deleted, project.created/
  status_changed, vacation.approved
- Admin UI: /admin/webhooks with CRUD, test button, event checkboxes
- webhook router: list, getById, create, update, delete, test

PWA Support (G11):
- manifest.json with standalone display, brand-colored icons (192+512px)
- Service worker: cache-first for static, network-first for API, offline fallback
- ServiceWorkerRegistration component with 60-min update checks
- InstallPrompt banner with 30-day dismissal memory
- Apple Web App meta tags + viewport theme color

Performance Monitoring (A15):
- Pino structured logging (JSON prod, pretty dev) via LOG_LEVEL env
- tRPC logging middleware on all protectedProcedure calls
- Request ID (UUID) per call for log correlation
- Slow query warnings (>500ms) at warn level
- GET /api/perf endpoint: memory, uptime, SSE connections, node version

Fix: renamed scenario.apply to scenario.applyScenario (tRPC reserved word)

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-03-20 06:57:20 +01:00

173 lines
6.1 KiB
TypeScript

import { prisma } from "@planarchy/db";
import { resolvePermissions, PermissionKey, SystemRole } from "@planarchy/shared";
import { initTRPC, TRPCError } from "@trpc/server";
import { ZodError } from "zod";
import { loggingMiddleware } from "./middleware/logging.js";
// Minimal Session type to avoid next-auth peer-dep in this package
interface Session {
user?: { email?: string | null; name?: string | null; image?: string | null } | null;
expires: string;
}
// ─── Context ──────────────────────────────────────────────────────────────────
export interface TRPCContext {
session: Session | null;
db: typeof prisma;
dbUser: { id: string; systemRole: string; permissionOverrides: unknown } | null;
roleDefaults: Record<string, PermissionKey[]> | null;
requestId?: string;
}
// Cache role defaults for 60 seconds to avoid DB hit on every request
let _roleDefaultsCache: Record<string, PermissionKey[]> | null = null;
let _roleDefaultsCacheTime = 0;
const ROLE_DEFAULTS_TTL = 60_000;
export async function loadRoleDefaults(): Promise<Record<string, PermissionKey[]>> {
const now = Date.now();
if (_roleDefaultsCache && now - _roleDefaultsCacheTime < ROLE_DEFAULTS_TTL) {
return _roleDefaultsCache;
}
const configs = await prisma.systemRoleConfig.findMany({
select: { role: true, defaultPermissions: true },
});
const map: Record<string, PermissionKey[]> = {};
for (const c of configs) {
map[c.role] = c.defaultPermissions as PermissionKey[];
}
_roleDefaultsCache = map;
_roleDefaultsCacheTime = now;
return map;
}
/** Invalidate the role defaults cache (call after updating SystemRoleConfig) */
export function invalidateRoleDefaultsCache(): void {
_roleDefaultsCache = null;
_roleDefaultsCacheTime = 0;
}
export function createTRPCContext(opts: {
session: Session | null;
dbUser?: { id: string; systemRole: string; permissionOverrides: unknown } | null;
roleDefaults?: Record<string, PermissionKey[]> | null;
}): TRPCContext {
return {
session: opts.session,
db: prisma,
dbUser: opts.dbUser ?? null,
roleDefaults: opts.roleDefaults ?? null,
};
}
// ─── tRPC Init ───────────────────────────────────────────────────────────────
const t = initTRPC.context<TRPCContext>().create({
errorFormatter({ shape, error }) {
return {
...shape,
data: {
...shape.data,
zodError:
error.cause instanceof ZodError ? error.cause.flatten() : null,
},
};
},
});
// ─── Procedures ──────────────────────────────────────────────────────────────
export const createTRPCRouter = t.router;
export const createCallerFactory = t.createCallerFactory;
/**
* Public procedure — no authentication required.
*/
export const publicProcedure = t.procedure;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const withLogging = t.middleware(loggingMiddleware as any);
/**
* Protected procedure — requires authenticated session AND a valid DB user record.
* This prevents stale sessions from accessing data after the DB user is deleted.
*/
export const protectedProcedure = t.procedure.use(withLogging).use(({ ctx, next }) => {
if (!ctx.session?.user) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "Authentication required" });
}
if (!ctx.dbUser) {
throw new TRPCError({ code: "UNAUTHORIZED", message: "User account not found" });
}
return next({
ctx: {
...ctx,
session: ctx.session,
user: ctx.session.user,
dbUser: ctx.dbUser,
},
});
});
/**
* Manager procedure — requires MANAGER or ADMIN role.
*/
export const managerProcedure = protectedProcedure.use(({ ctx, next }) => {
const user = ctx.dbUser;
if (!user) throw new TRPCError({ code: "UNAUTHORIZED" });
const allowedRoles: string[] = [SystemRole.ADMIN, SystemRole.MANAGER];
if (!allowedRoles.includes(user.systemRole)) {
throw new TRPCError({ code: "FORBIDDEN", message: "Manager or Admin role required" });
}
const permissions = resolvePermissions(
user.systemRole as SystemRole,
user.permissionOverrides as import("@planarchy/shared").PermissionOverrides | null,
ctx.roleDefaults ?? undefined,
);
return next({ ctx: { ...ctx, user, permissions } });
});
/**
* Controller procedure — requires CONTROLLER, MANAGER, or ADMIN role.
* Grants read-only access to financial and export data.
*/
export const controllerProcedure = protectedProcedure.use(({ ctx, next }) => {
const user = ctx.dbUser;
if (!user) throw new TRPCError({ code: "UNAUTHORIZED" });
const allowed: SystemRole[] = [SystemRole.ADMIN, SystemRole.MANAGER, SystemRole.CONTROLLER];
if (!allowed.includes(user.systemRole as SystemRole)) {
throw new TRPCError({ code: "FORBIDDEN", message: "Controller access required" });
}
const permissions = resolvePermissions(
user.systemRole as SystemRole,
user.permissionOverrides as import("@planarchy/shared").PermissionOverrides | null,
ctx.roleDefaults ?? undefined,
);
return next({ ctx: { ...ctx, user, permissions } });
});
/**
* Admin procedure — requires ADMIN role only.
*/
export const adminProcedure = protectedProcedure.use(({ ctx, next }) => {
const user = ctx.dbUser;
if (!user || user.systemRole !== SystemRole.ADMIN) {
throw new TRPCError({ code: "FORBIDDEN", message: "Admin role required" });
}
const permissions = resolvePermissions(SystemRole.ADMIN, null, ctx.roleDefaults ?? undefined);
return next({ ctx: { ...ctx, user, permissions } });
});
/**
* requirePermission — throws FORBIDDEN if the ctx lacks the given permission.
*/
export function requirePermission(
ctx: { permissions: Set<PermissionKey> },
key: PermissionKey
): void {
if (!ctx.permissions.has(key)) {
throw new TRPCError({ code: "FORBIDDEN", message: `Permission required: ${key}` });
}
}