Commit Graph

660 Commits

Author SHA1 Message Date
Hartmut 999626cf70 feat(application): extract entitlement use-cases from API router layer
Move core entitlement business logic (syncEntitlement, balance reading,
year summary, set/bulk-set) into packages/application/src/use-cases/entitlement/
using the deps-injection pattern. Audit logging stays in the router support
file; authorization check for getBalance/getBalanceDetail stays in the router
layer. The router support file becomes a thin wiring adapter.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 20:14:35 +02:00
Hartmut 1a8ea11331 feat(db): add deletedAt audit timestamp to soft-deletable models
Add deletedAt DateTime? to User, Client, Role, Resource, and Blueprint
models for GDPR-compliant deactivation audit trail. Soft-delete mutations
now stamp deletedAt: new Date() on deactivation and clear it on
reactivation. Migration and test assertions updated accordingly.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 20:03:38 +02:00
Hartmut f7407bd882 fix(api): add centralized Prisma → TRPCError middleware on protectedProcedure
P2002/P2025/P2003 now map to CONFLICT/NOT_FOUND/BAD_REQUEST with generic
messages. Raw Prisma error details no longer reach the client.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:58:00 +02:00
Hartmut 245b59723a fix(api): update resource-router tests for select-based listStaff queries
Tests expected include: { resourceRoles } but the Prisma select audit
changed the query to select: { ...RESOURCE_LIST_SELECT, resourceRoles }.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:33:58 +02:00
Hartmut db83933ea1 Merge branch 'worktree-agent-aed43cff' 2026-04-09 19:31:50 +02:00
Hartmut 36900a1219 Merge branch 'worktree-agent-a7de1005' 2026-04-09 19:31:11 +02:00
Hartmut 6c7245db93 test(e2e): add Playwright tests for core workflows
Covers auth redirect, resource/project list filtering, timeline render,
sidebar navigation, and staffing panel. Gives deploy confidence for
the main happy paths.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:30:43 +02:00
Hartmut 6f3bdd81e8 perf(api): add explicit Prisma selects on hot read paths
Replaces full model includes with field-scoped selects on the resource
list (listStaff) query. Avoids fetching large JSONB columns
(availability, valueScoreBreakdown) and unused scalar fields (aiSummary,
portfolioUrl, fte, resourceType, postalCode, etc.) when only
identity/rate fields are needed.

Adds RESOURCE_LIST_SELECT constant to packages/api/src/db/selects.ts
covering all fields actually consumed by ResourcesClient, FillOpenDemandModal,
EstimateWizard, EstimateWorkspaceDraftEditor, and ScenarioPlanner.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:24:55 +02:00
Hartmut d737a251b2 fix(api): replace ctx.session.user lookups with ctx.dbUser
Procedures were re-fetching the acting user from DB using the session
email, which breaks if email changes between session creation and request.
ctx.dbUser is populated by protectedProcedure and is always current.

Also removed the now-unused findVacationActor helper function.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:18:39 +02:00
Hartmut d7a35b2d7a feat(web): add React error boundaries and Next.js error.tsx fallbacks
Runtime errors in components now show a friendly "Something went wrong"
screen instead of a white page. Timeline and staffing panel are
individually wrapped. Route-level error.tsx handles server component errors.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 19:16:26 +02:00
Hartmut 070be70848 refactor(application): extract vacation management into application use-cases
Moves approve, reject, cancel, and request vacation business logic
out of the tRPC procedure layer into packages/application, matching
the pattern used by allocation use-cases.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:11:37 +02:00
Hartmut 6bf60c8e07 feat(web): persist list-page filters in URL search params
Resources, projects, and allocations filter state now syncs to/from
URL so filters survive refresh and can be shared via link.
Text inputs are debounced (300ms) to avoid URL churn.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 17:00:30 +02:00
Hartmut 7264f0728a perf(timeline): add useCallback/useMemo to timeline components
Prevents redundant re-renders when parent state changes by stabilising
event handler references and memoising expensive derived data in
TimelineView, TimelineResourcePanel, and TimelineProjectPanel.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 16:54:38 +02:00
Hartmut dda049075f refactor(application): extract vacation management into application use-cases
Moves approve, reject, cancel, and request vacation business logic
out of the tRPC procedure layer into packages/application, matching
the pattern used by allocation use-cases.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 16:49:45 +02:00
Hartmut 485e220c49 fix(api,web): env startup validation, QueryClient defaults, warn on missing REDIS_URL
- Throw at startup in production if REDIS_URL/DATABASE_URL/NEXTAUTH_SECRET missing
- Warn in development when REDIS_URL falls back to localhost
- QueryClient: add gcTime, disable refetchOnWindowFocus, skip retry on 4xx

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 16:42:34 +02:00
Hartmut 3c0179fcec fix(api): wrap audit log writes inside their parent transactions
Prevents mutations from committing without an audit trail if the
auditLog.create call fails after the main write already succeeded.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 16:40:10 +02:00
Hartmut a01f99561d fix(api): fix import paths missed by router reorganisation
- allocation-conflict-procedures: allocation-shared.js → allocation/shared.js
- allocation/index.ts: add missing allocationConflictProcedures spread
- allocation-conflict-check.test.ts: router/allocation.js → allocation/index.js

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:47:16 +02:00
Hartmut 1a8ed97d5e Merge branch 'worktree-agent-a2939317' 2026-04-09 14:44:51 +02:00
Hartmut b2c8d98b25 refactor(api): reorganise allocation router into allocation/ subdirectory
Moves read, assignment-procedures, assignment-mutations, and demand
procedures into allocation/ so the domain boundary is discoverable
without grep.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:44:17 +02:00
Hartmut 75167d6129 fix(merge): resolve post-merge type errors from batch-1 agents
- ScenarioPlanner.Baseline.shortCode: string → string | null (matches Prisma)
- ScenarioPlanner.SimulationResult.chargeabilityTarget: number → number | null
- Remove runtime Zod parse from scenario procedures (typed by Prisma already)
- Float64Array index access: add non-null assertions for noUncheckedIndexedAccess

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:38:32 +02:00
Hartmut 0fcb481350 Merge branch 'worktree-agent-a90e1bc2' 2026-04-09 14:19:18 +02:00
Hartmut b573a1d554 Merge branch 'worktree-agent-a74dc5bc' 2026-04-09 14:18:50 +02:00
Hartmut a2613f6e93 Merge branch 'worktree-agent-a0063a64' 2026-04-09 14:18:47 +02:00
Hartmut 96679f5fec Merge branch 'worktree-agent-acdb74a3' 2026-04-09 14:18:27 +02:00
Hartmut b9fd7fdb03 perf(staffing): replace day-by-day capacity loop with range arithmetic
Eliminates O(resource × allocation × days) iteration in findCapacityWindows
by pre-computing vacation date sets and using direct range overlap math.
Adds performance regression test (50 resources × 20 allocs × 365 days < 500ms).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:17:26 +02:00
Hartmut fbca017eaa test(application): add unit tests for demand fill logic and capacity vacation overlap
Covers fill-demand-requirement status validation, duplicate detection,
fill-open-demand happy path, and vacation overlap edge cases in
capacity analyzer.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:15:00 +02:00
Hartmut 9a42615a21 fix(api): add Zod bounds on financial fields, type vacation router, type scenarioData
- dailyCostCents, hoursPerDay, percentage now validated at API boundary
- vacation router no longer uses ctx.db as any
- scenarioData reads through typed Zod schema

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:08:16 +02:00
Hartmut aebe5bc57d fix(db): add SetNull cascade on Assignment→DemandRequirement + composite indexes
Prevents orphaned Assignment rows when a DemandRequirement is deleted.
Adds (resourceId, status, endDate) and (projectId, status, endDate)
indexes to support capacity range queries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 14:03:11 +02:00
Hartmut f3cb75bfc7 feat(mobile): add mobile summary view for 320-428px viewports (Sprint 4c)
Read-only capacity snapshot with utilization donut, top 5 active projects,
open demand alert banner, and quick-link grid — single-column card layout
optimised for PWA standalone mode.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:37:08 +02:00
Hartmut ab4ec91e02 feat(digest): add weekly capacity digest email cron
Sends a Monday digest to all ADMIN + MANAGER users with:
- Team utilization % for the next 4 weeks
- Overbooked resource count
- Open demand count
- Upcoming vacation count
- Top 5 most utilized resources

Route: GET /api/cron/weekly-digest (secured by CRON_SECRET).
HTML template and plain-text fallback included.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:33:12 +02:00
Hartmut 607af1a857 feat(bench): add Resource Bench Board page
Shows resources with available capacity in a selected date window.
- Filter by date range (with DateRangePresets), min hours/day slider, and free-text search
- Cards show role, chapter, available h/day with color-coded capacity bar
- Links to individual resource profiles
- "Bench" nav entry added to Resources section in AppShell

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:30:44 +02:00
Hartmut 1df208dbcc feat(timeline): add pulse animation for in-flight drag mutations
Allocation bars that have active optimistic overrides (post-drag,
awaiting server confirmation) now pulse subtly via animate-pulse.
The pending set is derived from the existing optimisticAllocations
map keys, requiring no additional state.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:28:46 +02:00
Hartmut 7a5e98e2e9 perf(timeline): add horizontal virtualization for allocation bars
Tracks scroll position via requestAnimationFrame to avoid re-renders
on every pixel. Allocation bars outside the visible horizontal window
(+ 10-column overscan) are skipped during render, reducing DOM nodes
significantly at day zoom (365 days × 40px = 14,600px canvas).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:26:38 +02:00
Hartmut e75d966b8d feat(timeline): add inline allocation editor on double-click
Double-clicking an allocation bar opens an inline editor overlay
with start date, end date, and hours/day fields. Saves via
trpc.allocation.update, closes on Escape or click outside.
Only visible to users with manage permissions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:24:43 +02:00
Hartmut fa54ef4cbd feat(timeline): add keyboard navigation with shortcut overlay
- Arrow left/right scrolls the timeline by 1 day (Shift: 1 week)
- Delete/Backspace deletes selected allocations
- ? toggles a keyboard shortcut overlay
- Floating ? button in bottom-right corner provides persistent access
- (Del) hint added to the FloatingActionBar delete button

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:20:32 +02:00
Hartmut 05f6eba5d8 refactor(staffing): decompose 735-line StaffingPanel into focused components
Splits StaffingPanel.tsx into:
- StaffingSearchForm: skill tags, dates, hours input, submit button
- ScoringExplanation: the 3-column scoring breakdown card
- StaffingResultCard: individual suggestion card with details and assign form
- StaffingResultsList: list orchestration with loading/empty states
- StaffingPanel: thin orchestrator (~100 lines) managing state and tRPC query

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:17:55 +02:00
Hartmut 594ae4f10b feat(allocations): add Excel export button to allocations toolbar
Adds an Export button that downloads visible/filtered allocation rows
as an xlsx file via the existing downloadWorkbookSheets utility.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:14:58 +02:00
Hartmut 7435fdc125 feat(timeline): Sprint 2b — AI staffing suggestions in DemandPopover
Shows top 3 resource suggestions (name, utilization, available h/d) below the
demand details using the existing staffing.getProjectStaffingSuggestions query.
Includes a shimmer loading skeleton while fetching. Each "Fill" button opens
the fill demand modal with the demand pre-loaded.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:11:36 +02:00
Hartmut 16ce6db07e feat(allocations): Sprint 2a — bulk date shift via BatchActionBar
Add "Shift Dates…" action to the batch action bar. Opens a modal with a
signed integer input; on confirm calls the existing timeline.batchShiftAllocations
procedure (allocationIds, daysDelta, mode="move").

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:10:06 +02:00
Hartmut 6831e199c6 feat(ux): Sprint 1 — quick wins: EmptyState, DateRangePresets, debounce, save feedback, scenarios nav
- EmptyState shared component; replace AllocationsClient inline empty state
- DateRangePresets (this month/quarter/3 months/year) integrated into AllocationModal
- Debounce conflict-check inputs in AllocationModal (400ms) using existing useDebounce
- Dashboard layout save feedback via SuccessToast after DB write completes
- Scenarios nav item in Planning sidebar + /scenarios list page

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 13:08:19 +02:00
Hartmut a16c41e739 fix(dashboard): show skeleton instead of default layout until hydration completes
Root cause: useDashboardLayout initialised React state with createDefaultDashboardLayout()
(1 widget), so the wrong default rendered during the ~100–500ms window while React Query
fetched the user session and DB layout after login. On reload within staleTime the cache
hit resolved instantly, masking the bug.

Fix: add isHydrated boolean state that becomes true only once localStorage OR DB
hydration has settled; DashboardClient renders a GridLayoutSkeleton until then.
Also adds router.refresh() in the sign-in handler to bust the Next.js Router Cache
so the post-login navigation always lands on a fresh server component tree.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 10:20:50 +02:00
Hartmut 24435a1824 test(allocation): add conflict check tests for checkConflicts query
Covers: no-conflict baseline, overbooking detection with per-day breakdown,
vacation overlap reporting, edit-mode excludeAssignmentId exclusion,
NOT_FOUND guard, and fallback country-hours capacity path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 10:20:37 +02:00
Hartmut 3e8df09cd8 feat(web): overbooking and vacation conflict warnings in AllocationModal
- New ConflictWarningPanel component: amber box with per-day overbooking
  table (capacity / already booked / new / overage) and sky-blue info box
  for vacation overlap. Overbooking section has an 'I understand' checkbox
  that must be ticked before Save is enabled; vacation overlap is
  informational only.
- AllocationModal: fires allocation.checkConflicts reactively when
  resourceId, dates and hoursPerDay are all set. Shows ConflictWarningPanel
  between form body and footer. Passes allowOverbooking: true to the
  createAssignment mutation when the user acknowledges. Acknowledgment
  resets whenever key fields change.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 10:15:37 +02:00
Hartmut 61e52e9995 feat(api,application): add checkConflicts query and soften overbooking block
- New allocation.checkConflicts managerProcedure: returns per-day overbooking
  breakdown (availableHours, existingHours, requestedHours, overageHours,
  maxOverbookPercent) plus vacation overlap list for the requested period.
  Read-only — used by AllocationModal for pre-submission warnings.
- createAssignment(): replace the hard >5-day overbooking block with a soft
  CONFLICT error. When allowOverbooking: true is passed the assignment is
  created and overbookingAcknowledged is set to true on the record.
- allowOverbooking field added to CreateAssignmentBaseSchema (optional)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 10:13:18 +02:00
Hartmut b944a17572 feat(db,shared): add overbookingAcknowledged field and conflict check types
- Assignment.overbookingAcknowledged Boolean @default(false) — audit trail
  for intentional overbookings
- CreateAssignmentBaseSchema gets allowOverbooking?: boolean flag so callers
  can explicitly opt in to overbooking
- Export AllocationConflictCheckResult, AllocationConflictDay,
  AllocationVacationOverlap types from @capakraken/shared for use in the
  new conflict-check API procedure and AllocationModal

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 10:11:02 +02:00
Hartmut 60d267fa0a feat(api): add SSE subscriber isolation, token pruning and E2E rate-limit guard
- event-bus: wrap each subscriber.fn call in try/catch so one throwing subscriber cannot kill delivery to all others
- event-bus: log Redis parse errors instead of swallowing them silently; add .catch() on Redis publish promise for async fallback to local delivery
- pruning.ts: new runPruning() deletes expired invite tokens, expired password-reset tokens, and read notifications older than 90 days
- settings.runPruning: expose pruning as adminProcedure mutation
- trpc.ts: E2E_TEST_MODE rate-limit bypass is now a no-op in production (NODE_ENV=production); logs a startup warning if misconfigured

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:35:39 +02:00
Hartmut 472d87c829 feat(web): add error boundaries, loading skeletons, render fixes and tree-shaking
- Add error.tsx to all 13 route groups: admin, allocations, analytics, dashboard, estimates, notifications, projects, reports, resources, roles, staffing, timeline, vacations
- Add loading.tsx to 9 routes that were missing them: admin, analytics, dashboard, estimates, notifications, reports, roles, staffing, vacations
- ResourceDetail: wrap vacationStart in useMemo to stabilize query key, remove dead windowEnd variable
- node-renderer.ts: replace barrel import (import * as THREE) with named imports for tree-shaking
- next.config.ts: add framer-motion and @capakraken/shared to optimizePackageImports

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:35:28 +02:00
Hartmut 1204c186ef perf(api): eliminate N+1 queries, add query guards and missing indexes
- Notification fan-out: replace sequential for loops with Promise.all (allocation-effects, notification-broadcast, create-notification)
- Public holiday batch: group resources by location combo, resolve holidays once per group, replace per-holiday delete/findFirst/create with 3 batched queries (~18K → ~5 queries)
- Add take guards to unbounded findMany calls (resource-analytics: 5000, resource-marketplace: 2000, resource-capacity: 1000, chargeability-report: 2000)
- auto-staffing: add select with only needed fields + take: 5000
- schema.prisma: add 5 missing indexes (ManagementLevel.groupId, Blueprint.isActive/target, Comment.parentId, Vacation.requestedById, Resource.managementLevelGroupId)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:35:13 +02:00
Hartmut 1d6d75ecf6 fix(api): wrap critical mutations in transactions and fix TOCTOU race conditions
- applyProjectScenario: wrap assignment loop in db.$transaction to prevent partial updates
- vacation approve/reject: fix TOCTOU race via updateMany with status-guard in WHERE + CONFLICT on count=0
- vacation cancel: wrap vacation.update + entitlement.updateMany in $transaction
- batchApprove: collect mutations, wrap in $transaction, dispatch SSE/notifications after commit
- Fix dead-code bug in createHappyPathDb where $transaction was assigned after return
- Add atomicity and concurrency tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 08:34:59 +02:00
Hartmut b103e79e92 feat(ux): prevent wizard close on backdrop click
AnimatedModal: add disableBackdropClose prop (default false, no impact
on existing consumers). When true, overlay onClick is removed.

ProjectWizard: remove handleBackdropClick — backdrop click no longer
closes the wizard. Only the X button and Cancel close it.

EstimateWizard already had no backdrop-click handler; no change needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 16:09:22 +02:00