Commit Graph

99 Commits

Author SHA1 Message Date
m
d76ffec758 fix: wire all missing routes in router.go
Register routes for reports, time entries, invoices, billing rates,
and document templates. All handlers and services already existed but
were not connected in the router.

Permission mapping:
- Reports, invoices, billing rates: PermManageBilling (partners+owners)
- Templates create/update/delete: PermCreateCase
- Time entries, template read/render: all authenticated users
2026-03-30 13:11:17 +02:00
m
4b0ccac384 fix: auto-strip /api/ prefix in api client + document convention
The api client now calls normalizePath() to strip accidental /api/
prefixes. This prevents the recurring /api/api/ double-prefix bug.
Added convention note to .claude/CLAUDE.md so future workers know.
2026-03-30 13:05:02 +02:00
m
3030ef1e8b fix: add all missing type exports (TimeEntry, Invoice, reports, notifications, audit) 2026-03-30 11:52:10 +02:00
m
2578060638 fix: add missing TEMPLATE_CATEGORY_LABELS export to types.ts 2026-03-30 11:43:36 +02:00
m
8f91feee0e feat: UPC deadline determination — event-driven proceeding timeline wizard 2026-03-30 11:38:08 +02:00
m
a89ef26ebd feat: UPC deadline determination — event-driven model with proceeding timeline
Full event-driven deadline determination system ported from youpc.org:

Backend:
- DetermineService: walks proceeding event tree, calculates cascading
  dates with holiday adjustment and conditional logic
- GET /api/proceeding-types/{code}/timeline — full event tree structure
- POST /api/deadlines/determine — calculate timeline with conditions
- POST /api/cases/{caseID}/deadlines/batch — batch-create deadlines
- DeadlineRule model: added is_spawn, spawn_label fields
- GetFullTimeline: recursive CTE following cross-type spawn branches
- Conditional deadlines: condition_rule_id toggles alt_duration/rule_code
  (e.g. Reply changes from RoP.029b to RoP.029a when CCR is filed)
- Seed SQL with full UPC event trees (INF, REV, CCR, APM, APP, AMD)

Frontend:
- DeadlineWizard: interactive proceeding timeline with step-by-step flow
  1. Select proceeding type (visual cards)
  2. Enter trigger event date
  3. Toggle conditional branches (CCR, Appeal, Amend)
  4. See full calculated timeline with color-coded urgency
  5. Batch-create all deadlines on a selected case
- Visual timeline tree with party icons, rule codes, duration badges
- Kept existing DeadlineCalculator as "Schnell" quick mode

Also resolved merge conflicts across 6 files (auth, router, handlers)
merging role-based permissions + audit trail features.
2026-03-30 11:33:59 +02:00
m
6b8c6f761d feat: HL tenant + email domain auto-assignment 2026-03-30 11:29:53 +02:00
m
93a25e3d72 feat: AI features — drafting, strategy, similar cases (P2) 2026-03-30 11:29:41 +02:00
m
81c2bb29b9 feat: reporting dashboard with charts (P1) 2026-03-30 11:29:35 +02:00
m
9f18fbab80 feat: document templates with auto-fill (P1) 2026-03-30 11:29:23 +02:00
m
ae55d9814a feat: time tracking + billing (P1) 2026-03-30 11:29:10 +02:00
m
642877ae54 feat: document templates with auto-fill from case data (P1)
- Database: kanzlai.document_templates table with RLS policies
- Seed: 4 system templates (Klageerwiderung UPC, Berufungsschrift,
  Mandatsbestätigung, Kostenrechnung)
- Backend: TemplateService (CRUD + render), TemplateHandler with
  endpoints: GET/POST /api/templates, GET/PUT/DELETE /api/templates/{id},
  POST /api/templates/{id}/render?case_id=X
- Template variables: case.*, party.*, tenant.*, user.*, date.*, deadline.*
- Frontend: /vorlagen page with category filters, template detail/editor,
  render flow (select case -> preview -> copy/download), variable toolbar
- Quick action: "Schriftsatz erstellen" button on case detail page
- Also: resolved merge conflicts between audit-trail and role-based branches,
  added missing Notification/AuditLog types to frontend
2026-03-30 11:26:25 +02:00
m
fdb4ac55a1 feat: frontend AI tab — KI-Strategie, KI-Entwurf, Aehnliche Faelle
New "KI" tab on case detail page with three sub-panels:
- KI-Strategie: one-click strategic analysis with next steps, risks, timeline
- KI-Entwurf: document drafting with template selection, language, instructions
- Aehnliche Faelle: UPC similar case search with relevance scores

Components: CaseStrategy, DocumentDrafter, SimilarCaseFinder
Types: StrategyRecommendation, DocumentDraft, SimilarCase, etc.
2026-03-30 11:26:01 +02:00
m
dd683281e0 feat: AI-powered features — document drafting, case strategy, similar case finder (P2)
Backend:
- DraftDocument: Claude generates legal documents from case data + template type
  (14 template types: Klageschrift, UPC claims, Abmahnung, etc.)
- CaseStrategy: Opus-powered strategic analysis with next steps, risk assessment,
  and timeline optimization (structured tool output)
- FindSimilarCases: queries youpc.org Supabase for UPC cases, Claude ranks by
  relevance with explanations and key holdings

Endpoints: POST /api/ai/draft-document, /case-strategy, /similar-cases
All rate-limited (5 req/min) and permission-gated (PermAIExtraction).
YouPC database connection is optional (YOUPC_DATABASE_URL env var).
2026-03-30 11:25:52 +02:00
m
bfd5e354ad fix: resolve merge conflicts from P0 role-based + audit trail branches
Combine role-based permissions (VerifyAccess/GetUserRole) with audit trail
(IP/user-agent context capture) in auth middleware and tenant resolver.
2026-03-30 11:25:41 +02:00
m
118bae1ae3 feat: HL tenant setup + email domain auto-assignment
- Create pre-configured Hogan Lovells tenant with demo flag and
  auto_assign_domains: ["hoganlovells.com"]
- Add POST /api/tenants/auto-assign endpoint: checks email domain
  against tenant settings, auto-assigns user as associate if match
- Add AutoAssignByDomain to TenantService
- Update registration flow: after signup, check auto-assign before
  showing tenant creation form. Skip tenant creation if auto-assigned.
- Add DemoBanner component shown when tenant.settings.demo is true
- Extend GET /api/me to return is_demo flag from tenant settings
2026-03-30 11:24:52 +02:00
m
fdef5af32e feat: reporting dashboard — case stats, deadline compliance, workload, billing (P1)
Backend:
- ReportingService with aggregation queries (CTEs, FILTER clauses)
- 4 API endpoints: /api/reports/{cases,deadlines,workload,billing}
- Date range filtering via ?from=&to= query params

Frontend:
- /berichte page with 4 tabs: Akten, Fristen, Auslastung, Abrechnung
- recharts: bar/pie/line charts for all report types
- Date range picker, CSV export, print-friendly view
- Sidebar nav entry with BarChart3 icon

Also resolves merge conflicts between role-based, notification, and
audit trail branches, and adds missing TS types (AuditLogResponse,
Notification, NotificationPreferences).
2026-03-30 11:24:45 +02:00
m
34dcbb74fe fix: resolve merge conflicts from role-based permissions + audit trail branches
Combines auth context keys (user role, IP, user-agent), tenant resolver
(GetUserRole-based access verification), middleware (deferred tenant
resolution + request info capture), and router (audit log + notifications
+ assignments).
2026-03-30 11:24:43 +02:00
m
238811727d feat: time tracking + billing — hourly rates, time entries, invoices (P1)
Database: time_entries, billing_rates, invoices tables with RLS.
Backend: CRUD services+handlers for time entries, billing rates, invoices.
  - Time entries: list/create/update/delete, summary by case/user/month
  - Billing rates: upsert with auto-close previous, current rate lookup
  - Invoices: create with auto-number (RE-YYYY-NNN), status transitions
    (draft->sent->paid, cancellation), link time entries on invoice create
API: 11 new endpoints under /api/time-entries, /api/billing-rates, /api/invoices
Frontend: Zeiterfassung tab on case detail, /abrechnung overview with filters,
  /abrechnung/rechnungen list+detail with status actions, billing rates settings
Also: resolved merge conflicts between audit-trail and role-based branches,
  added missing types (Notification, AuditLogResponse, NotificationPreferences)
2026-03-30 11:24:36 +02:00
m
8e65463130 feat: role-based permissions — owner/partner/associate/paralegal/secretary (P0) 2026-03-30 11:09:05 +02:00
m
a307b29db8 feat: email notifications + deadline reminder system (P0) 2026-03-30 11:08:53 +02:00
m
5e88384fab feat: append-only audit trail for all mutations (P0) 2026-03-30 11:08:41 +02:00
m
0a0ec016d8 feat: role-based permissions (owner/partner/associate/paralegal/secretary)
Backend:
- auth/permissions.go: full permission matrix with RequirePermission/RequireRole
  middleware, CanEditCase, CanDeleteDocument helpers
- auth/context.go: add user role to request context
- auth/middleware.go: resolve role alongside tenant in auth flow
- auth/tenant_resolver.go: verify membership + resolve role for X-Tenant-ID
- handlers/case_assignments.go: CRUD for case-level user assignments
- handlers/tenant_handler.go: UpdateMemberRole, GetMe (/api/me) endpoints
- handlers/documents.go: permission-based delete (own vs all)
- router/router.go: permission-wrapped routes for all endpoints
- services/case_assignment_service.go: assign/unassign with tenant validation
- services/tenant_service.go: UpdateMemberRole with owner protection
- models/case_assignment.go: CaseAssignment model

Database:
- user_tenants.role: CHECK constraint (owner/partner/associate/paralegal/secretary)
- case_assignments table: case_id, user_id, role (lead/team/viewer)
- Migrated existing admin->partner, member->associate

Frontend:
- usePermissions hook: fetches /api/me, provides can() helper
- TeamSettings: 5-role dropdown, role change, permission-gated invite
- CaseAssignments: new component for case-level team management
- Sidebar: conditionally hides AI/Settings based on permissions
- Cases page: hides "Neue Akte" button for non-authorized roles
- Case detail: new "Mitarbeiter" tab for assignment management
2026-03-30 11:04:57 +02:00
m
ac20c03f01 feat: email notifications + deadline reminder system
Database:
- notification_preferences table (user_id, tenant_id, reminder days, email/digest toggles)
- notifications table (type, entity link, read/sent tracking, dedup index)

Backend:
- NotificationService with background goroutine checking reminders hourly
- CheckDeadlineReminders: finds deadlines due in N days per user prefs, creates notifications
- Overdue deadline detection and notification
- Daily digest at 8am: compiles pending notifications into one email
- SendEmail via `m mail send` CLI command
- Deduplication: same notification type + entity + day = skip
- API: GET/PATCH notifications, unread count, mark read/all-read
- API: GET/PUT notification-preferences with upsert

Frontend:
- NotificationBell in header with unread count badge (polls every 30s)
- Dropdown panel with notification list, type-colored dots, time-ago, entity links
- Mark individual/all as read
- NotificationSettings in Einstellungen page: reminder day toggles, email toggle, digest toggle
2026-03-30 11:03:17 +02:00
m
c324a2b5c7 fix: critical security hardening — tenant isolation, CORS, error masking, input validation 2026-03-30 11:02:52 +02:00
m
b36247dfb9 feat: append-only audit trail for all mutations (P0)
- Database: kanzlai.audit_log table with RLS, append-only policies
  (no UPDATE/DELETE), indexes for entity, user, and time queries
- Backend: AuditService.Log() with context-based tenant/user/IP/UA
  extraction, wired into all 7 services (case, deadline, appointment,
  document, note, party, tenant)
- API: GET /api/audit-log with entity_type, entity_id, user_id,
  from/to date, and pagination filters
- Frontend: Protokoll tab on case detail page with chronological
  audit entries, diff preview, and pagination

Required by § 50 BRAO and DSGVO Art. 5(2).
2026-03-30 11:02:28 +02:00
m
c15d5b72f2 fix: critical security hardening — tenant isolation, CORS, error leaking, input validation
1. Tenant isolation bypass (CRITICAL): TenantResolver now verifies user
   has access to X-Tenant-ID via user_tenants lookup before setting context.
   Added VerifyAccess method to TenantLookup interface and TenantService.

2. Consolidated tenant resolution: Removed duplicate resolveTenant() from
   helpers.go and tenant resolution from auth middleware. TenantResolver is
   now the single source of truth. Deadlines and AI handlers use
   auth.TenantFromContext() instead of direct DB queries.

3. CalDAV credential masking: tenant settings responses now mask CalDAV
   passwords with "********" via maskSettingsPassword helper. Applied to
   GetTenant, ListTenants, and UpdateSettings responses.

4. CORS + security headers: New middleware/security.go with CORS
   (restricted to FRONTEND_ORIGIN) and security headers (X-Frame-Options,
   X-Content-Type-Options, HSTS, Referrer-Policy, X-XSS-Protection).

5. Internal error leaking: All writeError(w, 500, err.Error()) replaced
   with internalError() that logs via slog and returns generic "internal
   error" to client. Same for jsonError in tenant handler.

6. Input validation: Max length on title (500), description (10000),
   case_number (100), search (200). Pagination clamped to max 100.
   Content-Disposition filename sanitized against header injection.

Regression test added for tenant access denial (403 on unauthorized
X-Tenant-ID). All existing tests pass, go vet clean.
2026-03-30 11:01:14 +02:00
m
82878dffd5 docs: full system roadmap — from MVP to complete Kanzleimanagement 2026-03-28 02:35:20 +01:00
m
ac04930667 feat: comprehensive KanzlAI-mGMT system roadmap
Full system vision document covering 23 features across 4 priority tiers:
- P0 (must-have): audit trail, conflict checks, roles/permissions,
  notifications, time tracking, RVG calculator, invoicing, DATEV export
- P1 (should-have): document templates, beA integration, full-text search,
  Wiedervorlagen, email integration, reporting
- P2 (differentiator): patent family tracking, claim charts, UPC case law
  intelligence via mLex, AI document drafting, AI strategy analysis
- P3 (nice-to-have): client portal, PWA, multi-language, EDA

Includes data model designs (24 new tables), API specifications,
implementation phases, competitive analysis, and risk register.
2026-03-28 02:30:39 +01:00
m
909f14062c docs: comprehensive MVP audit — security, architecture, UX, competitive analysis 2026-03-28 02:26:39 +01:00
m
4b86dfa4ad feat: update AUDIT.md with sub-agent findings
Added 7 additional issues from deep-dive agents:
- Race condition in HolidayService cache (critical)
- Rate limiter X-Forwarded-For bypass (critical)
- German umlaut typos throughout frontend
- Silent error swallowing in createEvent
- Missing React error boundaries
- No RLS policies at database level
- Updated priority roadmap with new items
2026-03-28 02:23:50 +01:00
m
60f1f4ef4a feat: comprehensive MVP audit — security, architecture, UX, competitive analysis
Structured assessment covering code quality, security (critical tenant isolation
bypass found), architecture, UX gaps, testing coverage, deployment, and
competitive positioning vs RA-MICRO/ADVOWARE/AnNoText/Actaport.

Includes prioritized roadmap (P0-P3) with actionable items.
2026-03-28 02:22:07 +01:00
m
7c7ae396f4 feat: Phase D — case detail refactor to URL-based nested routes 2026-03-25 19:32:41 +01:00
m
433a0408f2 feat: Phase C — detail pages for deadlines, appointments, events, creation forms 2026-03-25 19:32:17 +01:00
m
cabea83784 feat: Phase B — interactive dashboard, breadcrumbs, clickable navigation 2026-03-25 19:31:59 +01:00
m
8863878b39 feat: Phase A backend — notes CRUD, detail endpoints, dashboard fix 2026-03-25 19:31:54 +01:00
m
84b178edbf feat: Phase B — interactive dashboard, breadcrumbs, clickable navigation
- Breadcrumb component: reusable nav with items array (label+href)
- DeadlineTrafficLights: buttons → Links to /fristen?status={filter}
- CaseOverviewGrid: static metrics → clickable Links to /cases?status={filter}
- UpcomingTimeline: items → clickable Links to /fristen/{id} or /termine/{id}
  with case number links and hover chevron
- QuickActions: swap CalDAV Sync for "Neuer Termin" → /termine/neu,
  fix "Frist eintragen" → /fristen/neu
- AISummaryCard: add RefreshCw button with spinning animation
- RecentActivityList: new component showing recent case events
- DeadlineList: accept initialStatus prop, add this_week/ok filters
- fristen/page.tsx: read searchParams.status for initial filter
- Add breadcrumbs to dashboard, fristen, cases, termine pages
- Add RecentActivity type, update DashboardData type
2026-03-25 19:29:13 +01:00
m
7094212dcf feat: Phase C frontend detail pages for deadlines, appointments, events
- Deadline detail page (/fristen/[id]) with status badge, due date,
  case context, complete button, and notes
- Appointment detail page (/termine/[id]) with datetime, location,
  type badge, case link, description, and notes
- Case event detail page (/cases/[id]/ereignisse/[eventId]) with
  event type icon, description, metadata, and notes
- Standalone deadline creation (/fristen/neu) with case dropdown
- Standalone appointment creation (/termine/neu) with optional case
- Reusable Breadcrumb component for navigation hierarchy
- Reusable NotesList component with inline create/edit/delete
- Added Note and RecentActivity types to lib/types.ts
2026-03-25 19:29:12 +01:00
m
9787450d91 feat: refactor case detail from useState tabs to URL-based nested routes
Refactors the monolithic cases/[id]/page.tsx into Next.js nested routes
with a shared layout for the case header and tab navigation bar.

Route structure:
- cases/[id]/layout.tsx — case header + tab bar (active tab from URL)
- cases/[id]/page.tsx — redirects to ./verlauf
- cases/[id]/verlauf/page.tsx — timeline tab
- cases/[id]/fristen/page.tsx — deadlines tab
- cases/[id]/dokumente/page.tsx — documents tab (with upload)
- cases/[id]/parteien/page.tsx — parties tab
- cases/[id]/notizen/page.tsx — notes tab (new, uses NotesList)

New shared components:
- Breadcrumb.tsx — reusable breadcrumb navigation
- NotesList.tsx — reusable notes CRUD (inline create/edit/delete)
- Note type added to types.ts

Benefits: deep linking, browser back/forward, bookmarkable tabs.
2026-03-25 19:28:29 +01:00
m
1e88dffd82 feat: Phase A backend — notes CRUD, detail endpoints, dashboard fix
- Create kanzlai.notes table (polymorphic FK with CHECK constraint,
  partial indexes, RLS)
- Add Note model, NoteService (ListByParent, Create, Update, Delete),
  and NoteHandler with endpoints: GET/POST /api/notes, PUT/DELETE /api/notes/{id}
- Add GET /api/deadlines/{deadlineID} detail endpoint
- Add GET /api/appointments/{id} detail endpoint
- Add GET /api/case-events/{id} detail endpoint (new CaseEventHandler)
- Fix dashboard query: add case_id to upcoming_deadlines SELECT,
  add id and case_id to recent_activity SELECT
- Register all new routes in router.go
2026-03-25 19:26:21 +01:00
m
9ad58e1ba3 docs: design document for dashboard redesign + detail pages 2026-03-25 18:51:44 +01:00
m
0712d9a367 docs: design document for dashboard redesign + detail pages (t-kz-060)
Comprehensive design covering:
- Dashboard interactivity (click-to-filter traffic lights, clickable timeline,
  fixed quick actions, AI summary refresh)
- New detail pages (deadline, appointment, case event)
- Notes system with polymorphic table design
- Case detail URL-based tab navigation
- Breadcrumb navigation system
- Backend API additions and data model changes
- Phased implementation plan for coders
2026-03-25 18:49:48 +01:00
m
cd31e76d07 fix: TenantSwitcher shows dropdown for single tenant, wider name display 2026-03-25 18:40:15 +01:00
m
f42b7ddec7 fix: add array guards to all frontend components consuming API responses 2026-03-25 18:35:28 +01:00
m
50bfa3deb4 fix: add array guards to all frontend components consuming API responses
Prevents "M.forEach is not a function" crashes when API returns error
objects or unexpected shapes instead of arrays. Guards all useQuery
consumers with Array.isArray checks and safe defaults for object props.

Files fixed: DeadlineList, AppointmentList, TenantSwitcher,
DeadlineTrafficLights, UpcomingTimeline, CaseOverviewGrid,
AISummaryCard, TeamSettings, and all page-level components
(dashboard, cases, fristen, termine, ai/extract).
2026-03-25 18:34:11 +01:00
m
e635efa71e fix: remove remaining /api/ double-prefix from template literal API calls
Previous fix missed backtick template strings. Fixed 7 more api.*()
calls in appointments, deadlines, settings, and einstellungen pages.
2026-03-25 18:20:35 +01:00
m
12e0407025 test: comprehensive E2E and API test suite for full KanzlAI stack 2026-03-25 16:21:32 +01:00
m
325fbeb5de test: comprehensive E2E and API test suite for full KanzlAI stack
Backend (Go):
- Expanded integration_test.go: health, auth middleware (expired/invalid/wrong-secret JWT),
  tenant CRUD, case CRUD (create/list/get/update/delete + filters + validation),
  deadline CRUD (create/list/update/complete/delete), appointment CRUD,
  dashboard (verifies all sections), deadline calculator (valid/invalid/unknown type),
  proceeding types & rules, document endpoints, AI extraction (no-key path),
  and full critical path E2E (auth -> case -> deadline -> appointment -> dashboard -> complete)
- New handler unit tests: case (10), appointment (11), dashboard (1), calculate (5),
  document (10), AI (4) — all testing validation, auth guards, and error paths without DB
- Total: ~80 backend tests (unit + integration)

Frontend (TypeScript/Vitest):
- Installed vitest 2.x, @testing-library/react, @testing-library/jest-dom, jsdom 24, msw
- vitest.config.ts with jsdom env, esbuild JSX automatic, path aliases
- API client tests (13): URL construction, no double /api/, auth header, tenant header,
  POST/PUT/PATCH/DELETE methods, error handling, 204 responses
- DeadlineTrafficLights tests (5): renders cards, correct counts, zero state, onFilter callback
- CaseOverviewGrid tests (4): renders categories, counts, header, zero state
- LoginPage tests (8): form rendering, mode toggle, password login, redirect, error display,
  magic link, registration link
- Total: 30 frontend tests

Makefile: test-frontend target now runs vitest instead of placeholder echo.
2026-03-25 16:19:00 +01:00
m
19bea8d058 fix: remove /api/ double-prefix from all frontend API calls
Frontend api.ts baseUrl is already "/api", so paths like
"/api/cases" produced "/api/api/cases". Stripped the redundant
prefix from all component calls. Rewrite destination correctly
adds /api/ back for the Go backend.
2026-03-25 16:05:50 +01:00
m
661135d137 fix: exclude /api/ routes from Next.js auth middleware
The middleware was intercepting API proxy requests and redirecting
to /login. API routes should pass through to the Go backend which
handles its own JWT auth.
2026-03-25 15:58:42 +01:00