refactor: complete v2 refactoring plan (Phases 1-5)

Phase 1 — Quick Wins: centralize formatMoney/formatCents, extract
findUniqueOrThrow helper (19 routers), shared Prisma select constants,
useInvalidatePlanningViews hook, status badge consolidation, composite
DB indexes.

Phase 2 — Timeline Split: extract TimelineContext, TimelineResourcePanel,
TimelineProjectPanel; split 28-dep useMemo into 3 focused memos.
TimelineView.tsx reduced from 1,903 to 538 lines.

Phase 3 — Query Performance: server-side filtering for getEntriesView,
remove availability from timeline resource select, SSE event debouncing
(50ms batch window).

Phase 4 — Estimate Workspace: extract 7 tab components and 3 editor
components. EstimateWorkspaceClient 1,298→306 lines,
EstimateWorkspaceDraftEditor 1,205→581 lines.

Phase 5 — Package Cleanup: split commit-dispo-import-batch (1,112→573
lines), extract shared pagination helper with 11 tests.

All tests pass: 209 API, 254 engine, 67 application.

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-03-14 23:03:42 +01:00
parent 4dabb9d4ce
commit ad0855902b
65 changed files with 7108 additions and 4740 deletions
+286 -141
View File
@@ -1,11 +1,22 @@
import { createAiClient, isAiConfigured } from "../ai-client.js";
import { listAssignmentBookings } from "@planarchy/application";
import { BlueprintTarget, CreateResourceSchema, FieldType, PermissionKey, ResourceRoleSchema, SkillEntrySchema, UpdateResourceSchema, VALUE_SCORE_WEIGHTS, inferStateFromPostalCode } from "@planarchy/shared";
import {
isChargeabilityActualBooking,
isChargeabilityRelevantProject,
listAssignmentBookings,
recomputeResourceValueScores,
} from "@planarchy/application";
import { BlueprintTarget, CreateResourceSchema, FieldType, PermissionKey, ResourceRoleSchema, ResourceType, SkillEntrySchema, UpdateResourceSchema, inferStateFromPostalCode } from "@planarchy/shared";
import type { WeekdayAvailability } from "@planarchy/shared";
import { computeValueScore } from "@planarchy/staffing";
import { computeChargeability } from "@planarchy/engine";
import { assertBlueprintDynamicFields } from "./blueprint-validation.js";
import { buildDynamicFieldWhereClauses } from "./custom-field-filters.js";
import {
anonymizeResource,
anonymizeResources,
anonymizeSearchMatches,
getAnonymizationDirectory,
resolveResourceIdsByDisplayedEids,
} from "../lib/anonymization.js";
export const DEFAULT_SUMMARY_PROMPT = `You are writing a short professional profile for an internal resource planning tool.
@@ -18,16 +29,40 @@ Artist profile:
Write a 23 sentence professional bio. Be specific, use skill names. No fluff.`;
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { findUniqueOrThrow } from "../db/helpers.js";
import { adminProcedure, controllerProcedure, createTRPCRouter, managerProcedure, protectedProcedure, requirePermission } from "../trpc.js";
import { ROLE_BRIEF_SELECT } from "../db/selects.js";
function parseResourceCursor(cursor: string | undefined): { displayName: string; id: string } | null {
if (!cursor) return null;
try {
const decoded = JSON.parse(cursor) as { displayName?: string; id?: string };
if (typeof decoded.displayName === "string" && typeof decoded.id === "string") {
return { displayName: decoded.displayName, id: decoded.id };
}
} catch {
return null;
}
return null;
}
export const resourceRouter = createTRPCRouter({
list: protectedProcedure
.input(
z.object({
chapter: z.string().optional(),
chapters: z.array(z.string()).optional(),
isActive: z.boolean().optional().default(true),
search: z.string().optional(),
eids: z.array(z.string()).optional(),
countryIds: z.array(z.string()).optional(),
excludedCountryIds: z.array(z.string()).optional(),
includeWithoutCountry: z.boolean().optional().default(true),
resourceTypes: z.array(z.nativeEnum(ResourceType)).optional(),
excludedResourceTypes: z.array(z.nativeEnum(ResourceType)).optional(),
includeWithoutResourceType: z.boolean().optional().default(true),
rolledOff: z.boolean().optional(),
departed: z.boolean().optional(),
page: z.number().int().min(1).default(1),
limit: z.number().int().min(1).max(500).default(50),
includeRoles: z.boolean().optional().default(false),
@@ -42,31 +77,192 @@ export const resourceRouter = createTRPCRouter({
}),
)
.query(async ({ ctx, input }) => {
const { chapter, isActive, search, eids, page, limit, includeRoles, cursor, customFieldFilters } = input;
const {
chapter,
chapters,
isActive,
search,
eids,
countryIds,
excludedCountryIds,
includeWithoutCountry,
resourceTypes,
excludedResourceTypes,
includeWithoutResourceType,
rolledOff,
departed,
page,
limit,
includeRoles,
cursor,
customFieldFilters,
} = input;
const parsedCursor = parseResourceCursor(cursor);
const cfConditions = buildDynamicFieldWhereClauses(customFieldFilters).map((dynamicFields) => ({ dynamicFields }));
type WhereClause = Record<string, unknown>;
const andClauses: WhereClause[] = [];
const chapterFilters = Array.from(
new Set([
...(chapter ? [chapter] : []),
...(chapters ?? []),
]),
);
const directory = await getAnonymizationDirectory(ctx.db);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const where: any = {
...(eids ? {} : { isActive }),
...(eids ? { eid: { in: eids } } : {}),
...(chapter ? { chapter } : {}),
...(search
? {
OR: [
{ displayName: { contains: search, mode: "insensitive" as const } },
{ eid: { contains: search, mode: "insensitive" as const } },
{ email: { contains: search, mode: "insensitive" as const } },
],
}
: {}),
...(cfConditions.length > 0 ? { AND: cfConditions } : {}),
};
if (!eids) {
andClauses.push({ isActive });
}
if (eids && !directory) {
andClauses.push({ eid: { in: eids } });
}
if (chapterFilters.length === 1) {
andClauses.push({ chapter: chapterFilters[0] });
} else if (chapterFilters.length > 1) {
andClauses.push({ chapter: { in: chapterFilters } });
}
if (search && !directory) {
andClauses.push({
OR: [
{ displayName: { contains: search, mode: "insensitive" as const } },
{ eid: { contains: search, mode: "insensitive" as const } },
{ email: { contains: search, mode: "insensitive" as const } },
],
});
}
if (countryIds && countryIds.length > 0) {
const countryClauses: WhereClause[] = [{ countryId: { in: countryIds } }];
if (includeWithoutCountry) {
countryClauses.push({ countryId: null });
}
andClauses.push(countryClauses.length === 1 ? countryClauses[0]! : { OR: countryClauses });
}
if (excludedCountryIds && excludedCountryIds.length > 0) {
andClauses.push({ NOT: { countryId: { in: excludedCountryIds } } });
}
if (!includeWithoutCountry) {
andClauses.push({ NOT: { countryId: null } });
}
if (resourceTypes && resourceTypes.length > 0) {
const resourceTypeClauses: WhereClause[] = [{ resourceType: { in: resourceTypes } }];
if (includeWithoutResourceType) {
resourceTypeClauses.push({ resourceType: null });
}
andClauses.push(
resourceTypeClauses.length === 1 ? resourceTypeClauses[0]! : { OR: resourceTypeClauses },
);
}
if (excludedResourceTypes && excludedResourceTypes.length > 0) {
andClauses.push({ NOT: { resourceType: { in: excludedResourceTypes } } });
}
if (!includeWithoutResourceType) {
andClauses.push({ NOT: { resourceType: null } });
}
if (rolledOff !== undefined) {
andClauses.push({ rolledOff });
}
if (departed !== undefined) {
andClauses.push({ departed });
}
andClauses.push(...cfConditions);
const where = andClauses.length > 0 ? { AND: andClauses } : {};
if (directory) {
const rawResources = await (includeRoles
? ctx.db.resource.findMany({
where,
include: {
resourceRoles: {
include: { role: { select: ROLE_BRIEF_SELECT } },
},
},
orderBy: [{ displayName: "asc" }, { id: "asc" }],
})
: ctx.db.resource.findMany({
where,
orderBy: [{ displayName: "asc" }, { id: "asc" }],
}));
const directoryResources = rawResources.map((resource) => ({
id: resource.id,
eid: resource.eid,
displayName: resource.displayName,
email: resource.email,
}));
const requestedIds = eids
? resolveResourceIdsByDisplayedEids(directoryResources, directory, eids)
: [];
const requestedIdSet = requestedIds.length > 0 ? new Set(requestedIds) : null;
const filteredResources = rawResources.filter((resource) => {
const alias = directory.byResourceId.get(resource.id);
if (requestedIdSet && !requestedIdSet.has(resource.id)) {
return false;
}
if (eids && eids.length > 0 && requestedIds.length === 0) {
return false;
}
if (search && !anonymizeSearchMatches(
{
id: resource.id,
eid: resource.eid,
displayName: resource.displayName,
email: resource.email,
},
alias,
search,
)) {
return false;
}
return true;
});
const anonymizedResources = anonymizeResources(filteredResources, directory).sort((left, right) => {
const displayNameCompare = left.displayName.localeCompare(right.displayName);
if (displayNameCompare !== 0) {
return displayNameCompare;
}
return left.id.localeCompare(right.id);
});
const total = anonymizedResources.length;
const afterCursor = parsedCursor
? anonymizedResources.filter(
(resource) =>
resource.displayName > parsedCursor.displayName ||
(resource.displayName === parsedCursor.displayName && resource.id > parsedCursor.id),
)
: anonymizedResources;
const skip = cursor ? 0 : (page - 1) * limit;
const paged = afterCursor.slice(skip, skip + limit + 1);
const hasMore = paged.length > limit;
const resources = hasMore ? paged.slice(0, limit) : paged;
const nextCursor = hasMore
? JSON.stringify({
displayName: resources[resources.length - 1]!.displayName,
id: resources[resources.length - 1]!.id,
})
: null;
return { resources, total, page, limit, nextCursor };
}
const skip = cursor ? 0 : (page - 1) * limit;
const orderBy = [{ displayName: "asc" as const }, { id: "asc" as const }];
// Apply cursor filter directly on where to avoid exactOptionalPropertyTypes issues
const whereWithCursor = cursor ? { ...where, id: { gt: cursor } } : where;
const whereWithCursor = parsedCursor
? {
AND: [
...((where as { AND?: WhereClause[] }).AND ?? []),
{
OR: [
{ displayName: { gt: parsedCursor.displayName } },
{ displayName: parsedCursor.displayName, id: { gt: parsedCursor.id } },
],
},
],
}
: where;
const baseQuery = { where: whereWithCursor, skip, take: limit + 1, orderBy };
const [rawResources, total] = await Promise.all([
@@ -75,7 +271,7 @@ export const resourceRouter = createTRPCRouter({
...baseQuery,
include: {
resourceRoles: {
include: { role: { select: { id: true, name: true, color: true } } },
include: { role: { select: ROLE_BRIEF_SELECT } },
},
},
})
@@ -85,7 +281,12 @@ export const resourceRouter = createTRPCRouter({
const hasMore = rawResources.length > limit;
const resources = hasMore ? rawResources.slice(0, limit) : rawResources;
const nextCursor = hasMore ? resources[resources.length - 1]!.id : null;
const nextCursor = hasMore
? JSON.stringify({
displayName: resources[resources.length - 1]!.displayName,
id: resources[resources.length - 1]!.id,
})
: null;
return { resources, total, page, limit, nextCursor };
}),
@@ -93,33 +294,42 @@ export const resourceRouter = createTRPCRouter({
getById: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const resource = await ctx.db.resource.findUnique({
where: { id: input.id },
include: {
blueprint: true,
resourceRoles: {
include: { role: { select: { id: true, name: true, color: true } } },
const resource = await findUniqueOrThrow(
ctx.db.resource.findUnique({
where: { id: input.id },
include: {
blueprint: true,
resourceRoles: {
include: { role: { select: ROLE_BRIEF_SELECT } },
},
areaRole: { select: { id: true, name: true } },
},
areaRole: { select: { id: true, name: true } },
user: { select: { email: true } },
},
});
}),
"Resource",
);
if (!resource) {
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
}
return resource;
const directory = await getAnonymizationDirectory(ctx.db);
return {
...anonymizeResource(resource, directory),
isOwnedByCurrentUser: Boolean(resource.userId && ctx.dbUser?.id && resource.userId === ctx.dbUser.id),
};
}),
getByEid: protectedProcedure
.input(z.object({ eid: z.string() }))
.query(async ({ ctx, input }) => {
const resource = await ctx.db.resource.findUnique({ where: { eid: input.eid } });
const directory = await getAnonymizationDirectory(ctx.db);
let resource = await ctx.db.resource.findUnique({ where: { eid: input.eid } });
if (!resource && directory) {
const resourceId = directory.byAliasEid.get(input.eid.trim().toLowerCase());
if (resourceId) {
resource = await ctx.db.resource.findUnique({ where: { id: resourceId } });
}
}
if (!resource) {
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
}
return resource;
return anonymizeResource(resource, directory);
}),
create: managerProcedure
@@ -194,7 +404,7 @@ export const resourceRouter = createTRPCRouter({
: undefined,
} as unknown as Parameters<typeof ctx.db.resource.create>[0]["data"],
include: {
resourceRoles: { include: { role: { select: { id: true, name: true, color: true } } } },
resourceRoles: { include: { role: { select: ROLE_BRIEF_SELECT } } },
},
});
@@ -215,10 +425,10 @@ export const resourceRouter = createTRPCRouter({
.input(z.object({ id: z.string(), data: UpdateResourceSchema.extend({ roles: z.array(ResourceRoleSchema).optional() }) }))
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_RESOURCES);
const existing = await ctx.db.resource.findUnique({ where: { id: input.id } });
if (!existing) {
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
}
const existing = await findUniqueOrThrow(
ctx.db.resource.findUnique({ where: { id: input.id } }),
"Resource",
);
const nextBlueprintId = input.data.blueprintId ?? existing.blueprintId ?? undefined;
const nextDynamicFields = (input.data.dynamicFields ?? existing.dynamicFields ?? {}) as Record<string, unknown>;
@@ -275,7 +485,7 @@ export const resourceRouter = createTRPCRouter({
...(input.data.fte !== undefined ? { fte: input.data.fte } : {}),
} as unknown as Parameters<typeof ctx.db.resource.update>[0]["data"],
include: {
resourceRoles: { include: { role: { select: { id: true, name: true, color: true } } } },
resourceRoles: { include: { role: { select: ROLE_BRIEF_SELECT } } },
},
});
@@ -415,10 +625,10 @@ export const resourceRouter = createTRPCRouter({
)
.mutation(async ({ ctx, input }) => {
requirePermission(ctx, PermissionKey.MANAGE_RESOURCES);
const existing = await ctx.db.resource.findUnique({ where: { id: input.resourceId } });
if (!existing) {
throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
}
await findUniqueOrThrow(
ctx.db.resource.findUnique({ where: { id: input.resourceId } }),
"Resource",
);
await ctx.db.resource.update({
where: { id: input.resourceId },
@@ -693,7 +903,8 @@ export const resourceRouter = createTRPCRouter({
.filter((r): r is NonNullable<typeof r> => r !== null)
.sort((a, b) => a.displayName.localeCompare(b.displayName));
return results;
const directory = await getAnonymizationDirectory(ctx.db);
return anonymizeResources(results, directory);
}),
// ─── Self-service ────────────────────────────────────────────────────────────
@@ -706,7 +917,8 @@ export const resourceRouter = createTRPCRouter({
where: { email },
select: { resource: { select: { id: true, displayName: true, eid: true, chapter: true } } },
});
return user?.resource ?? null;
const directory = await getAnonymizationDirectory(ctx.db);
return user?.resource ? anonymizeResource(user.resource, directory) : null;
}),
// ─── Value Score ─────────────────────────────────────────────────────────────
@@ -740,83 +952,12 @@ export const resourceRouter = createTRPCRouter({
take: input.limit,
});
return resources;
const directory = await getAnonymizationDirectory(ctx.db);
return anonymizeResources(resources, directory);
}),
recomputeValueScores: adminProcedure.mutation(async ({ ctx }) => {
const [resources, settings] = await Promise.all([
ctx.db.resource.findMany({
where: { isActive: true },
select: {
id: true,
skills: true,
lcrCents: true,
chargeabilityTarget: true,
},
}),
ctx.db.systemSettings.findUnique({ where: { id: "singleton" } }),
]);
const bookings = await listAssignmentBookings(ctx.db, {
startDate: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000),
endDate: new Date(),
resourceIds: resources.map((resource) => resource.id),
});
const defaultWeights = {
skillDepth: VALUE_SCORE_WEIGHTS.SKILL_DEPTH,
skillBreadth: VALUE_SCORE_WEIGHTS.SKILL_BREADTH,
costEfficiency: VALUE_SCORE_WEIGHTS.COST_EFFICIENCY,
chargeability: VALUE_SCORE_WEIGHTS.CHARGEABILITY,
experience: VALUE_SCORE_WEIGHTS.EXPERIENCE,
};
const weights = (settings?.scoreWeights as unknown as typeof defaultWeights) ?? defaultWeights;
const maxLcrCents = resources.reduce((max, r) => Math.max(max, r.lcrCents), 0);
const now = new Date();
type SkillRow = { skill: string; category?: string; proficiency: number; yearsExperience?: number; isMainSkill?: boolean };
const totalWorkDays = 90 * (5 / 7); // approx working days
const availableHours = totalWorkDays * 8;
const updates = resources.map((resource) => {
const resourceBookings = bookings.filter((booking) => booking.resourceId === resource.id);
const bookedHours = resourceBookings.reduce((sum, booking) => {
const days = Math.max(
0,
(new Date(booking.endDate).getTime() - new Date(booking.startDate).getTime()) /
(1000 * 60 * 60 * 24) +
1,
);
return sum + booking.hoursPerDay * days;
}, 0);
const currentChargeability = availableHours > 0 ? Math.min(100, (bookedHours / availableHours) * 100) : 0;
const skills = (resource.skills as unknown as SkillRow[]) ?? [];
const breakdown = computeValueScore(
{
skills: skills as unknown as import("@planarchy/shared").SkillEntry[],
lcrCents: resource.lcrCents,
chargeabilityTarget: resource.chargeabilityTarget,
currentChargeability,
maxLcrCents,
},
weights,
);
return ctx.db.resource.update({
where: { id: resource.id },
data: {
valueScore: breakdown.total,
valueScoreBreakdown: breakdown as unknown as import("@planarchy/db").Prisma.InputJsonValue,
valueScoreUpdatedAt: now,
},
});
});
await ctx.db.$transaction(updates);
const updated = updates.length;
return { updated };
return recomputeResourceValueScores(ctx.db);
}),
listWithUtilization: controllerProcedure
@@ -825,6 +966,7 @@ export const resourceRouter = createTRPCRouter({
startDate: z.string().datetime().optional(),
endDate: z.string().datetime().optional(),
chapter: z.string().optional(),
includeProposed: z.boolean().default(false),
limit: z.number().int().min(1).max(500).default(100),
}),
)
@@ -872,6 +1014,7 @@ export const resourceRouter = createTRPCRouter({
endDate: end,
resourceIds: resources.map((resource) => resource.id),
});
const directory = await getAnonymizationDirectory(ctx.db);
return resources.map((r) => {
const avail = r.availability as Record<string, number>;
@@ -882,7 +1025,11 @@ export const resourceRouter = createTRPCRouter({
let bookedHours = 0;
let isOverbooked = false;
const resourceBookings = bookings.filter((booking) => booking.resourceId === r.id);
const resourceBookings = bookings.filter(
(booking) =>
booking.resourceId === r.id &&
(input.includeProposed || booking.status !== "PROPOSED"),
);
for (const a of resourceBookings) {
const days =
(new Date(a.endDate).getTime() - new Date(a.startDate).getTime()) /
@@ -895,19 +1042,19 @@ export const resourceRouter = createTRPCRouter({
const utilizationPercent =
availableHours > 0 ? Math.round((bookedHours / availableHours) * 100) : 0;
return {
return anonymizeResource({
...r,
bookingCount: resourceBookings.length,
bookedHours: Math.round(bookedHours),
availableHours: Math.round(availableHours),
utilizationPercent,
isOverbooked,
};
}, directory);
});
}),
getChargeabilityStats: controllerProcedure
.input(z.object({ resourceId: z.string().optional() }))
.input(z.object({ includeProposed: z.boolean().default(false), resourceId: z.string().optional() }))
.query(async ({ ctx, input }) => {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), 1);
@@ -932,26 +1079,24 @@ export const resourceRouter = createTRPCRouter({
endDate: end,
resourceIds: resources.map((resource) => resource.id),
});
const directory = await getAnonymizationDirectory(ctx.db);
return resources.map((r) => {
const avail = r.availability as unknown as WeekdayAvailability;
const resourceBookings = bookings.filter((booking) => booking.resourceId === r.id);
// Actual: CONFIRMED or ACTIVE allocations on non-DRAFT, non-CANCELLED projects
const actualAllocs = resourceBookings.filter(
(a) =>
(a.status === "CONFIRMED" || a.status === "ACTIVE") &&
a.project.status !== "DRAFT" &&
a.project.status !== "CANCELLED",
const actualAllocs = resourceBookings.filter((booking) =>
isChargeabilityActualBooking(booking, input.includeProposed),
);
// Expected: all non-CANCELLED assignment-like bookings, all project statuses
const expectedAllocs = resourceBookings;
const expectedAllocs = resourceBookings.filter((booking) =>
isChargeabilityRelevantProject(booking.project, true),
);
const actual = computeChargeability(avail, actualAllocs, start, end);
const expected = computeChargeability(avail, expectedAllocs, start, end);
return {
return anonymizeResource({
id: r.id,
eid: r.eid,
displayName: r.displayName,
@@ -960,7 +1105,7 @@ export const resourceRouter = createTRPCRouter({
actualChargeability: actual.chargeability,
expectedChargeability: expected.chargeability,
availableHours: actual.availableHours,
};
}, directory);
});
}),