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
+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 } : {}),
};
}),
});