feat: AI assistant (HartBOT), demand filling, budget-per-role, project favorites, and UX improvements

AI Assistant (HartBOT):
- Chat panel with inline layout, session persistence, message history (up-arrow recall)
- OpenAI function calling with 20+ tools (search, navigate, create/cancel allocations, update status)
- RBAC-aware tool filtering, fuzzy search with word-level matching
- Navigation actions (router.push) and data invalidation after mutations
- Country/metro city/org unit/role filtering on resource search

Demand Filling Enhancements:
- Two-phase fill modal: plan multiple resources, then confirm & assign all at once
- Availability preview per resource (available/partial/conflict days, existing bookings)
- Coverage bar showing demand hours distribution across assigned resources
- Fill demand from project detail page (new Assign button per demand)
- Fixed: filled demands no longer shown on timeline, demand bars no longer overlap

Budget per Role:
- DemandRequirement.budgetCents field (schema + API + UI)
- Project wizard step 3: budget input per role with allocation summary bar
- Project detail: allocated vs booked budget per demand
- Fill demand modal: role budget display with cost estimates
- AllocationModal: budget field for demand editing

Project Favorites:
- User.favoriteProjectIds (JSONB) with toggle API
- Star button on projects list and detail page (optimistic updates)
- "My Projects" dashboard widget (favorites + responsible person projects)

Project Management:
- Edit project from detail page (ProjectModal integration)
- Edit demands from detail page (AllocationModal integration)
- Admin-only project deletion (cascades assignments + demands)
- Create user accounts from admin panel

Timeline Fixes:
- Country multi-select filter with backend support
- URL param sync for same-page navigation (AI assistant integration)
- Demand lane stacking (no more overlapping bars)
- Single-day booking resize handles (always visible, min 6px)
- Single-day resize allowed (start === end)
- "All Clients" toggle (select all / deselect all)

Other Fixes:
- crypto.randomUUID fallback for non-secure contexts
- Chat message limit raised (200 max, client sends last 40)
- Status dropdown portal (no longer clipped by table overflow)
- Cents display restored in budget views (2 decimal places)
- Allocations grouped view with project sub-groups (collapsed by default)
- Server-side resource search for project wizard (no 500 limit)

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-03-16 15:31:48 +01:00
parent f5551e33c7
commit b0e55786c3
44 changed files with 4516 additions and 609 deletions
+129
View File
@@ -82,6 +82,7 @@ function toDemandRequirementUpdateInput(input: AllocationEntryUpdateInput) {
...(input.role !== undefined ? { role: input.role } : {}),
...(input.roleId !== undefined ? { roleId: input.roleId } : {}),
...(input.headcount !== undefined ? { headcount: input.headcount } : {}),
...(input.budgetCents !== undefined ? { budgetCents: input.budgetCents } : {}),
...(input.status !== undefined ? { status: input.status } : {}),
...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
};
@@ -298,6 +299,134 @@ export const allocationRouter = createTRPCRouter({
);
}),
/**
* Check a resource's availability for a date range.
* Returns working days, existing allocations, conflict days, and available capacity.
*/
checkResourceAvailability: protectedProcedure
.input(z.object({
resourceId: z.string(),
startDate: z.coerce.date(),
endDate: z.coerce.date(),
hoursPerDay: z.number().min(0.5).max(24).default(8),
}))
.query(async ({ ctx, input }) => {
const resource = await ctx.db.resource.findUnique({
where: { id: input.resourceId },
select: {
id: true, displayName: true, eid: true, fte: true,
country: { select: { dailyWorkingHours: true } },
},
});
if (!resource) throw new TRPCError({ code: "NOT_FOUND", message: "Resource not found" });
const dailyCapacity = (resource.country?.dailyWorkingHours ?? 8) * (resource.fte ?? 1);
// Get existing assignments in the date range
const existingAssignments = await ctx.db.assignment.findMany({
where: {
resourceId: input.resourceId,
status: { not: "CANCELLED" },
startDate: { lte: input.endDate },
endDate: { gte: input.startDate },
},
select: {
id: true, startDate: true, endDate: true, hoursPerDay: true, status: true,
project: { select: { name: true, shortCode: true } },
},
orderBy: { startDate: "asc" },
});
// Get vacations in the date range
const vacations = await ctx.db.vacation.findMany({
where: {
resourceId: input.resourceId,
status: "APPROVED",
startDate: { lte: input.endDate },
endDate: { gte: input.startDate },
},
select: { startDate: true, endDate: true, isHalfDay: true },
});
// Calculate day-by-day availability
let totalWorkingDays = 0;
let availableDays = 0;
let conflictDays = 0;
let partialDays = 0;
let totalAvailableHours = 0;
const requestedHpd = input.hoursPerDay;
const d = new Date(input.startDate);
const end = new Date(input.endDate);
while (d <= end) {
const dow = d.getDay();
if (dow !== 0 && dow !== 6) {
totalWorkingDays++;
// Check vacation
const isVacation = vacations.some((v) => {
const vs = new Date(v.startDate); vs.setHours(0, 0, 0, 0);
const ve = new Date(v.endDate); ve.setHours(0, 0, 0, 0);
const dc = new Date(d); dc.setHours(0, 0, 0, 0);
return dc >= vs && dc <= ve;
});
if (isVacation) {
conflictDays++;
d.setDate(d.getDate() + 1);
continue;
}
// Sum existing hours on this day
let bookedHours = 0;
for (const a of existingAssignments) {
const as2 = new Date(a.startDate); as2.setHours(0, 0, 0, 0);
const ae = new Date(a.endDate); ae.setHours(0, 0, 0, 0);
const dc = new Date(d); dc.setHours(0, 0, 0, 0);
if (dc >= as2 && dc <= ae) {
bookedHours += a.hoursPerDay;
}
}
const remainingCapacity = Math.max(0, dailyCapacity - bookedHours);
if (remainingCapacity >= requestedHpd) {
availableDays++;
totalAvailableHours += requestedHpd;
} else if (remainingCapacity > 0) {
partialDays++;
totalAvailableHours += remainingCapacity;
} else {
conflictDays++;
}
}
d.setDate(d.getDate() + 1);
}
const totalRequestedHours = totalWorkingDays * requestedHpd;
return {
resource: { id: resource.id, name: resource.displayName, eid: resource.eid },
dailyCapacity,
totalWorkingDays,
availableDays,
partialDays,
conflictDays,
totalAvailableHours: Math.round(totalAvailableHours * 10) / 10,
totalRequestedHours,
coveragePercent: totalRequestedHours > 0
? Math.round((totalAvailableHours / totalRequestedHours) * 100)
: 0,
existingAssignments: existingAssignments.map((a) => ({
project: a.project.name,
code: a.project.shortCode,
hoursPerDay: a.hoursPerDay,
start: a.startDate.toISOString().slice(0, 10),
end: a.endDate.toISOString().slice(0, 10),
status: a.status,
})),
};
}),
createDemandRequirement: managerProcedure
.input(CreateDemandRequirementSchema)
.mutation(async ({ ctx, input }) => {
File diff suppressed because it is too large Load Diff
+197
View File
@@ -0,0 +1,197 @@
/**
* AI Assistant router — provides a chat endpoint that uses OpenAI Function Calling
* to answer questions about Planarchy data and modify resources/projects.
*/
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { resolvePermissions, type PermissionOverrides, type SystemRole } from "@planarchy/shared";
import { createTRPCRouter, protectedProcedure } from "../trpc.js";
import { createAiClient, isAiConfigured, parseAiError } from "../ai-client.js";
import { TOOL_DEFINITIONS, executeTool, type ToolContext, type ToolAction } from "./assistant-tools.js";
const MAX_TOOL_ITERATIONS = 8;
const SYSTEM_PROMPT = `Du bist der Planarchy-Assistent — ein hilfreicher AI-Assistent für Ressourcenplanung und Projektmanagement in einer 3D-Produktionsumgebung.
Deine Fähigkeiten:
- Fragen über Ressourcen, Projekte, Allokationen, Budget, Urlaub, Estimates, Org-Struktur beantworten
- Chargeability-Analysen, Urlaubsübersichten, Budget-Analysen
- Ressourcen/Projekte aktualisieren, Allokationen erstellen/stornieren (nur mit Berechtigung + expliziter Bestätigung)
- Den User zu relevanten Seiten navigieren (Timeline, Dashboard, etc. mit Filtern)
Wichtige Regeln:
- Antworte in der Sprache des Users (Deutsch oder Englisch)
- Geldbeträge: intern in Cent, konvertiere zu EUR für den User
- Vor Datenänderungen: kurze Zusammenfassung + Bestätigung einholen
- Sei KURZ und DIREKT. Keine langen Erklärungen wenn nicht nötig. Antworte knapp und präzise.
- Rufe Tools PARALLEL auf wenn möglich (z.B. search_resources + list_allocations gleichzeitig)
- Fasse Ergebnisse kompakt zusammen — keine unnötigen Wiederholungen der Tool-Ergebnisse
- Wenn eine Suche keine Treffer ergibt, versuche einzelne Wörter aus der Anfrage als Suchbegriffe. Die Tools unterstützen automatisch wort-basierte Fuzzy-Suche — zeige dem User die Vorschläge wenn welche gefunden werden
Datenmodell:
- Ressourcen: EID, FTE (0-1), LCR (EUR/h), Chargeability-Target, Skills, Chapter, OrgUnit
- Projekte: ShortCode, Budget (Cent), Win-Probability, Status (DRAFT/ACTIVE/ON_HOLD/COMPLETED/CANCELLED)
- Allokationen (Assignments): resourceId + projectId, hoursPerDay, dailyCostCents, Zeitraum, Status (PROPOSED/CONFIRMED/ACTIVE/COMPLETED/CANCELLED)
- Chargeability = gebuchte/verfügbare Stunden × 100%
- Urlaub: Typen VACATION/SICK/PARENTAL/SPECIAL/PUBLIC_HOLIDAY, Status PENDING/APPROVED/REJECTED/CANCELLED
`;
/** Map tool names to the permission required to use them */
const TOOL_PERMISSION_MAP: Record<string, string> = {
update_resource: "manageResources",
update_project: "manageProjects",
create_allocation: "manageAllocations",
cancel_allocation: "manageAllocations",
update_allocation_status: "manageAllocations",
};
/** Tools that require cost visibility */
const COST_TOOLS = new Set(["get_budget_status", "get_chargeability"]);
export const assistantRouter = createTRPCRouter({
chat: protectedProcedure
.input(z.object({
messages: z.array(z.object({
role: z.enum(["user", "assistant"]),
content: z.string(),
})).min(1).max(200),
pageContext: z.string().optional(),
}))
.mutation(async ({ ctx, input }) => {
// 1. Load AI settings
const settings = await ctx.db.systemSettings.findUnique({
where: { id: "singleton" },
});
if (!isAiConfigured(settings)) {
throw new TRPCError({
code: "PRECONDITION_FAILED",
message: "AI is not configured. Please set up OpenAI credentials in Admin → Settings.",
});
}
const client = createAiClient(settings!);
const userRole = ctx.dbUser?.systemRole ?? "USER";
// Use configured token limit, but ensure a reasonable minimum for multi-tool responses
const maxTokens = Math.max(settings?.aiMaxCompletionTokens ?? 2500, 1500);
const temperature = settings?.aiTemperature ?? 0.7;
const model = settings?.azureOpenAiDeployment ?? "gpt-4o-mini";
// 2. Resolve granular permissions
const permissions = resolvePermissions(
userRole as SystemRole,
(ctx.dbUser?.permissionOverrides as PermissionOverrides | null) ?? null,
);
const permissionList = [...permissions];
// 3. Build system prompt with user context
let contextBlock = `\n\nAktueller User: ${ctx.session?.user?.name ?? "Unknown"} (Rolle: ${userRole})`;
contextBlock += `\nBerechtigungen: ${permissionList.length > 0 ? permissionList.join(", ") : "Nur Lese-Zugriff auf eigene Daten"}`;
if (input.pageContext) {
contextBlock += `\nAktuelle Seite: ${input.pageContext}`;
contextBlock += `\nHinweis: Beziehe dich bevorzugt auf den Kontext der aktuellen Seite wenn die Frage des Users dazu passt.`;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const openaiMessages: any[] = [
{ role: "system", content: SYSTEM_PROMPT + contextBlock },
...input.messages.slice(-20).map((m) => ({
role: m.role,
content: m.content,
})),
];
// 4. Filter tools based on granular permissions
const availableTools = TOOL_DEFINITIONS.filter((t) => {
const toolName = t.function.name;
// Check write permission
const requiredPerm = TOOL_PERMISSION_MAP[toolName];
if (requiredPerm && !permissions.has(requiredPerm as import("@planarchy/shared").PermissionKey)) {
return false;
}
// Hide cost/budget tools if user lacks viewCosts
if (COST_TOOLS.has(toolName) && !permissions.has("viewCosts" as import("@planarchy/shared").PermissionKey)) {
return false;
}
return true;
});
// 5. Function calling loop
const toolCtx: ToolContext = { db: ctx.db, userRole, permissions };
const collectedActions: ToolAction[] = [];
for (let i = 0; i < MAX_TOOL_ITERATIONS; i++) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let response: any;
try {
response = await client.chat.completions.create({
model,
messages: openaiMessages,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
tools: availableTools as any,
max_completion_tokens: maxTokens,
temperature,
});
} catch (err) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: `AI error: ${parseAiError(err)}`,
});
}
const choice = response.choices?.[0];
if (!choice) {
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "No response from AI" });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const msg = choice.message as any;
// If the AI wants to call tools
if (msg.tool_calls && msg.tool_calls.length > 0) {
openaiMessages.push(msg);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
for (const toolCall of msg.tool_calls as Array<{ id: string; function: { name: string; arguments: string } }>) {
const result = await executeTool(
toolCall.function.name,
toolCall.function.arguments,
toolCtx,
);
// Collect any actions (e.g. navigation)
if (result.action) {
collectedActions.push(result.action);
}
openaiMessages.push({
role: "tool",
tool_call_id: toolCall.id,
content: result.content,
});
}
continue;
}
// AI returned a text response — we're done
return {
content: (msg.content as string) ?? "I couldn't generate a response.",
role: "assistant" as const,
...(collectedActions.length > 0 ? { actions: collectedActions } : {}),
};
}
// Exceeded max iterations
return {
content: "I had to stop after too many tool calls. Please try a simpler question.",
role: "assistant" as const,
...(collectedActions.length > 0 ? { actions: collectedActions } : {}),
};
}),
});
+4
View File
@@ -1,8 +1,10 @@
import { createTRPCRouter } from "../trpc.js";
import { allocationRouter } from "./allocation.js";
import { assistantRouter } from "./assistant.js";
import { calculationRuleRouter } from "./calculation-rules.js";
import { blueprintRouter } from "./blueprint.js";
import { chargeabilityReportRouter } from "./chargeability-report.js";
import { computationGraphRouter } from "./computation-graph.js";
import { clientRouter } from "./client.js";
import { countryRouter } from "./country.js";
import { dashboardRouter } from "./dashboard.js";
@@ -26,6 +28,7 @@ import { utilizationCategoryRouter } from "./utilization-category.js";
import { vacationRouter } from "./vacation.js";
export const appRouter = createTRPCRouter({
assistant: assistantRouter,
dashboard: dashboardRouter,
effortRule: effortRuleRouter,
experienceMultiplier: experienceMultiplierRouter,
@@ -51,6 +54,7 @@ export const appRouter = createTRPCRouter({
rateCard: rateCardRouter,
chargeabilityReport: chargeabilityReportRouter,
calculationRule: calculationRuleRouter,
computationGraph: computationGraphRouter,
});
export type AppRouter = typeof appRouter;
+38 -1
View File
@@ -10,7 +10,7 @@ import { paginate, paginateCursor, PaginationInputSchema, CursorInputSchema } fr
import { assertBlueprintDynamicFields } from "./blueprint-validation.js";
import { buildDynamicFieldWhereClauses } from "./custom-field-filters.js";
import { loadProjectPlanningReadModel } from "./project-planning-read-model.js";
import { controllerProcedure, createTRPCRouter, managerProcedure, protectedProcedure, requirePermission } from "../trpc.js";
import { adminProcedure, controllerProcedure, createTRPCRouter, managerProcedure, protectedProcedure, requirePermission } from "../trpc.js";
export const projectRouter = createTRPCRouter({
list: protectedProcedure
@@ -309,4 +309,41 @@ export const projectRouter = createTRPCRouter({
return { projects, nextCursor: result.nextCursor };
}),
delete: adminProcedure
.input(z.object({ id: z.string() }))
.mutation(async ({ ctx, input }) => {
const project = await ctx.db.project.findUnique({
where: { id: input.id },
select: { id: true, name: true, shortCode: true },
});
if (!project) throw new TRPCError({ code: "NOT_FOUND", message: "Project not found" });
// Delete all related records in a transaction
await ctx.db.$transaction(async (tx) => {
// Delete assignments (which reference demandRequirements)
await tx.assignment.deleteMany({ where: { projectId: input.id } });
// Delete demand requirements
await tx.demandRequirement.deleteMany({ where: { projectId: input.id } });
// Unlink calculation rules
await tx.calculationRule.updateMany({
where: { projectId: input.id },
data: { projectId: null },
});
// Delete the project
await tx.project.delete({ where: { id: input.id } });
// Audit log
await tx.auditLog.create({
data: {
entityType: "Project",
entityId: input.id,
action: "DELETE",
...(ctx.dbUser?.id ? { userId: ctx.dbUser.id } : {}),
changes: { before: { id: project.id, name: project.name, shortCode: project.shortCode } } as never,
},
});
});
return { id: input.id, name: project.name };
}),
});
+16 -12
View File
@@ -48,6 +48,7 @@ type TimelineEntriesFilters = {
clientIds?: string[] | undefined;
chapters?: string[] | undefined;
eids?: string[] | undefined;
countryCodes?: string[] | undefined;
};
function getAssignmentResourceIds(
@@ -66,23 +67,25 @@ async function loadTimelineEntriesReadModel(
db: TimelineEntriesDbClient,
input: TimelineEntriesFilters,
) {
const { startDate, endDate, resourceIds, projectIds, clientIds, chapters, eids } = input;
const { startDate, endDate, resourceIds, projectIds, clientIds, chapters, eids, countryCodes } = input;
// When resource-level filters are active (resourceIds, chapters, or eids),
// When resource-level filters are active (resourceIds, chapters, eids, or countryCodes),
// resolve matching resource IDs so we can push the filter to the DB query.
const effectiveResourceIds = await (async () => {
if (resourceIds && resourceIds.length > 0) return resourceIds;
const hasChapters = chapters && chapters.length > 0;
const hasEids = eids && eids.length > 0;
if (!hasChapters && !hasEids) return undefined;
const hasCountry = countryCodes && countryCodes.length > 0;
if (!hasChapters && !hasEids && !hasCountry) return undefined;
const andConditions: Record<string, unknown>[] = [];
if (hasChapters) andConditions.push({ chapter: { in: chapters } });
if (hasEids) andConditions.push({ eid: { in: eids } });
if (hasCountry) andConditions.push({ country: { code: { in: countryCodes } } });
const matching = await db.resource.findMany({
where: {
...(hasChapters && hasEids
? { AND: [{ chapter: { in: chapters } }, { eid: { in: eids } }] }
: hasChapters
? { chapter: { in: chapters } }
: { eid: { in: eids! } }),
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
where: (andConditions.length === 1 ? andConditions[0]! : { AND: andConditions }) as any,
select: { id: true },
});
return matching.map((r) => r.id);
@@ -288,6 +291,7 @@ export const timelineRouter = createTRPCRouter({
clientIds: z.array(z.string()).optional(),
chapters: z.array(z.string()).optional(),
eids: z.array(z.string()).optional(),
countryCodes: z.array(z.string()).optional(),
}),
)
.query(async ({ ctx, input }) => {
@@ -306,6 +310,7 @@ export const timelineRouter = createTRPCRouter({
clientIds: z.array(z.string()).optional(),
chapters: z.array(z.string()).optional(),
eids: z.array(z.string()).optional(),
countryCodes: z.array(z.string()).optional(),
}),
)
.query(async ({ ctx, input }) => {
@@ -736,9 +741,8 @@ export const timelineRouter = createTRPCRouter({
"Project",
);
// Use wide date range to catch all assignments (including those extending beyond project dates)
const bookings = await listAssignmentBookings(ctx.db, {
startDate: project.startDate,
endDate: project.endDate,
projectIds: [project.id],
});
+27
View File
@@ -113,6 +113,33 @@ export const userRouter = createTRPCRouter({
return { updatedAt: updated.updatedAt };
}),
// ─── Favorite Projects ──────────────────────────────────────────────────
getFavoriteProjectIds: protectedProcedure.query(async ({ ctx }) => {
const user = await ctx.db.user.findUnique({
where: { id: ctx.dbUser!.id },
select: { favoriteProjectIds: true },
});
return ((user?.favoriteProjectIds as string[] | null) ?? []) as string[];
}),
toggleFavoriteProject: protectedProcedure
.input(z.object({ projectId: z.string() }))
.mutation(async ({ ctx, input }) => {
const user = await ctx.db.user.findUnique({
where: { id: ctx.dbUser!.id },
select: { favoriteProjectIds: true },
});
const current = ((user?.favoriteProjectIds as string[] | null) ?? []) as string[];
const next = current.includes(input.projectId)
? current.filter((id) => id !== input.projectId)
: [...current, input.projectId];
await ctx.db.user.update({
where: { id: ctx.dbUser!.id },
data: { favoriteProjectIds: next as unknown as Prisma.InputJsonValue },
});
return { favoriteProjectIds: next, added: !current.includes(input.projectId) };
}),
setPermissions: adminProcedure
.input(
z.object({