T09: KI-Copilot API + Hybrid Workflow Engine + LLM client + event-triggered workflows

- KI-Copilot: NL query → proposed actions, execute with RBAC, history, audit logging
- LLM client: mock mode (no API key) + OpenAI-compatible mode (AI_MODEL/AI_API_KEY)
- Action mapper: NL intent → API calls (create/update/delete/search company/contact)
- Workflow engine: step types (action/approval/notification/condition), JSONB steps
- Workflow lifecycle: pending → in_progress → completed/rejected/cancelled
- Event-triggered workflows: event bus → auto-start instances
- Code-engine workflows: onboarding on user.created event
- Approval timeout: auto-reject after configured hours
- 5 new tenant-scoped tables with RLS: ai_conversations, ai_messages, workflows, workflow_instances, workflow_step_history
- Migration 0004: all tables + RLS policies + tenant_id + indexes
- 238 tests pass (30 AC + 105 coverage + 103 existing), 84.12% T09 module coverage
- MissingGreenlet fix: safe accessor helpers for async ORM attribute access
This commit is contained in:
leocrm-bot
2026-06-29 02:44:13 +02:00
parent 9678344f0e
commit 851e7999ba
31 changed files with 5884 additions and 3 deletions
+133
View File
@@ -0,0 +1,133 @@
# T07a — Frontend Core SPA — Shell, Auth, Routing, i18n, UI Library, Accessibility
## Project Root
/a0/usr/workdir/dev-projects/leocrm
## Frontend Directory
/a0/usr/workdir/dev-projects/leocrm/frontend/
## Tech Stack (CONFIRMED from architecture.md)
- React 18 + Vite + TypeScript
- React Router v6
- TanStack Query (React Query v5) for server state
- Zustand for client state
- react-i18next for i18n (de/en)
- React Hook Form + Zod for forms
- Tailwind CSS with design tokens from prototype
- Vitest for testing
## Backend API (already running, T01-T03 complete)
- Base URL: http://localhost:8000
- Auth: session cookie (leocrm_session), SameSite=strict
- CORS: http://localhost:5173 (Vite dev) allowed
- Endpoints available: /api/v1/auth/login, /api/v1/auth/logout, /api/v1/auth/me, /api/v1/auth/password-reset/request, /api/v1/auth/password-reset/confirm, /api/v1/users, /api/v1/companies, /api/v1/contacts, /api/v1/notifications, /api/v1/plugins, /health
## Requirements (23)
F-AUTH-01, F-AUTH-02, F-AUTH-03, F-AUTH-05, F-AUTH-07, F-CORE-06, F-CORE-07, F-CORE-08, F-CORE-09, F-CORE-13, F-A11Y-01, F-A11Y-02, F-A11Y-03, F-INT-01, F-NAV-01, F-UI-01 through F-UI-06, F-UI-08, F-TEST-01
## Acceptance Criteria (27)
1. Login page renders with email+password form
2. Login with valid credentials → redirect to Dashboard
3. Login with invalid credentials → error toast shown
4. Password reset request page renders and submits
5. Password reset confirm page renders with token validation
6. App shell renders with sidebar (plugin menu), topbar (tenant switcher, search, notifications, user menu), content area
7. Router navigates between routes without page reload (SPA)
8. Protected routes redirect to /login when not authenticated
9. Tenant switcher shows current tenant and allows switching
10. API client sends session cookie automatically via axios interceptor
11. API client handles 401 → redirect to login
12. API client handles 422 → display validation errors
13. i18n: German locale loads by default
14. i18n: English locale switchable via settings
15. UI Library: Button renders with variants (primary, secondary, danger, ghost)
16. UI Library: Input renders with label, error, helper text
17. UI Library: Modal opens/closes with backdrop click and ESC
18. UI Library: Toast notifications appear and auto-dismiss
19. UI Library: Table renders with sortable headers
20. UI Library: Card, Badge, Avatar, Pagination, EmptyState, Skeleton, ConfirmDialog render correctly
21. Accessibility: All interactive elements have ARIA labels
22. Accessibility: Keyboard navigation works (Tab, Enter, Escape, Arrow keys)
23. Accessibility: 44px minimum touch targets on mobile
24. Accessibility: prefers-reduced-motion respected
25. Vite dev server starts without errors
26. Production build (npm run build) succeeds with 0 errors
27. TypeScript: tsc --noEmit passes with 0 errors
## Files to Create
- frontend/package.json (React 18, Vite, TanStack Query, Zustand, react-i18next, React Hook Form, Zod, Tailwind CSS, Vitest, axios)
- frontend/vite.config.ts
- frontend/tsconfig.json, tsconfig.node.json
- frontend/tailwind.config.js, postcss.config.js
- frontend/index.html
- frontend/src/main.tsx — React entry point with providers
- frontend/src/App.tsx — Router + providers setup
- frontend/src/api/client.ts — axios instance with interceptors (cookie, 401, 422)
- frontend/src/api/hooks.ts — TanStack Query hooks for auth, users, companies, contacts, notifications
- frontend/src/store/authStore.ts — Zustand auth store
- frontend/src/store/uiStore.ts — Zustand UI store (theme, sidebar, locale)
- frontend/src/i18n/index.ts — react-i18next setup
- frontend/src/i18n/locales/de.json, en.json
- frontend/src/components/ui/Button.tsx
- frontend/src/components/ui/Input.tsx
- frontend/src/components/ui/Select.tsx
- frontend/src/components/ui/Modal.tsx
- frontend/src/components/ui/Toast.tsx (ToastContainer + useToast)
- frontend/src/components/ui/Table.tsx
- frontend/src/components/ui/Card.tsx
- frontend/src/components/ui/Badge.tsx
- frontend/src/components/ui/Avatar.tsx
- frontend/src/components/ui/Pagination.tsx
- frontend/src/components/ui/EmptyState.tsx
- frontend/src/components/ui/Skeleton.tsx
- frontend/src/components/ui/ConfirmDialog.tsx
- frontend/src/components/layout/AppShell.tsx — Sidebar + TopBar + ContentArea
- frontend/src/components/layout/Sidebar.tsx — Plugin menu, navigation
- frontend/src/components/layout/TopBar.tsx — Tenant switcher, search, notifications, user menu
- frontend/src/pages/Login.tsx
- frontend/src/pages/PasswordResetRequest.tsx
- frontend/src/pages/PasswordResetConfirm.tsx
- frontend/src/pages/Dashboard.tsx (placeholder)
- frontend/src/pages/Settings.tsx (locale switch, theme)
- frontend/src/routes/index.tsx — Route definitions with guards
- frontend/src/routes/ProtectedRoute.tsx — Auth guard
- frontend/src/hooks/useAuth.ts
- frontend/src/hooks/useTenant.ts
- frontend/src/index.css — Tailwind directives + design tokens
- frontend/src/__tests__/shell/ (AppShell, Router, Sidebar, TopBar tests)
- frontend/src/__tests__/auth/ (Login, PasswordReset tests)
- frontend/src/__tests__/ui/ (Button, Input, Modal, Toast, Table, etc. tests)
- frontend/vitest.config.ts (or merge into vite.config.ts)
- frontend/src/test/setup.ts — Vitest setup (jsdom, i18n, mocks)
## Design Tokens (from prototype)
- Reference: https://webspace.media-on.de/leocrm-prototype-x7k2p9/
- Primary color, secondary, accent, danger, warning, success
- Spacing scale, border radius, shadows
- Typography: font families, sizes, weights
- Define as CSS custom properties in index.css + Tailwind config
## Critical Rules
- Use TypeScript strict mode
- All components must have ARIA labels for interactive elements
- 44px minimum touch targets on mobile (Tailwind min-h-[44px] min-w-[44px])
- prefers-reduced-motion: use Tailwind motion-safe/motion-reduce variants
- Session cookie: axios with withCredentials: true
- 401 handler: redirect to /login, clear auth store
- 422 handler: extract validation errors, display in form
- i18n: German default, English switchable
- No Lorem Ipsum — use real German/English content
- Test with Vitest + jsdom + @testing-library/react
- Coverage target: 80%
## Test Commands
cd /a0/usr/workdir/dev-projects/leocrm/frontend && npx vitest run src/__tests__/ --reporter=verbose
cd /a0/usr/workdir/dev-projects/leocrm/frontend && npm run build
cd /a0/usr/workdir/dev-projects/leocrm/frontend && npx tsc --noEmit
## Deliverables
1. Complete frontend/ directory with all files listed above
2. All 27 ACs covered by tests
3. npm run build succeeds with 0 errors
4. tsc --noEmit passes with 0 errors
5. Report: test results, AC coverage, files, bugs
+121
View File
@@ -0,0 +1,121 @@
# T09 — KI-Copilot API + Hybrid Workflow Engine Backend
## Project Root
/a0/usr/workdir/dev-projects/leocrm
## Backend Directory
/a0/usr/workdir/dev-projects/leocrm/app/
## Tech Stack (existing)
- FastAPI + SQLAlchemy 2.0 + asyncpg + Pydantic v2 + ARQ
- PostgreSQL 18 on localhost:5432 (user/db: leocrm/leocrm + leocrm_test)
- Redis on localhost:6379
- venv at /opt/venv (already activated)
- T01-T03 complete (103 tests pass, commit 7a5a48f)
## Requirements (5)
F-AI-01, F-WF-01, F-CORE-01, F-CORE-06, F-TEST-01
## Acceptance Criteria (22)
### KI-Copilot (7 ACs)
1. POST /api/v1/ai/copilot/query mit NL input → 200 + proposed_actions array
2. POST /api/v1/ai/copilot/execute mit proposed action → 200 + API result (RBAC enforced)
3. POST /api/v1/ai/copilot/execute als viewer mit delete action → 403 (RBAC blocks)
4. GET /api/v1/ai/copilot/history → 200 + paginated conversation history
5. Copilot action logged in audit_log with entity_type=ai_copilot
6. Copilot respects tenant isolation: cross-tenant → 404
7. Copilot respects field-level permissions: hidden fields not in response
### Workflow Engine (15 ACs)
8. POST /api/v1/workflows mit valid steps JSONB → 201 + workflow definition
9. GET /api/v1/workflows → 200 + paginated list
10. GET /api/v1/workflows/{id} → 200 + workflow detail with steps
11. PATCH /api/v1/workflows/{id} → 200, updated
12. DELETE /api/v1/workflows/{id} → 204
13. POST /api/v1/workflows/{id}/instances → 201, instance created with status=pending
14. GET /api/v1/workflows/instances?status=in_progress → 200 + filtered list
15. GET /api/v1/workflows/instances/{id} → 200 + current_step_index + history
16. POST /api/v1/workflows/instances/{id}/advance (approve) → 200, step advanced
17. POST /api/v1/workflows/instances/{id}/advance (reject) → 200, status=rejected, initiator notified
18. POST /api/v1/workflows/instances/{id}/cancel → 200, status=cancelled
19. Event-triggered workflow: publish event → workflow instance auto-starts
20. workflow_step_history entry created on every step transition
21. Code-engine workflow: onboarding workflow runs on user creation
22. Approval step timeout → auto-reject after configured hours (tested with mock timer)
## Files to Create
### KI-Copilot
- app/models/ai_conversation.py — AIConversation, AIMessage models (tenant-scoped)
- app/schemas/ai_copilot.py — CopilotQueryRequest, CopilotAction, CopilotExecuteRequest, CopilotHistoryResponse
- app/services/ai_copilot_service.py — NL→API translation, LLM client, RBAC enforcement, audit logging
- app/routes/ai_copilot.py — POST /query, POST /execute, GET /history
- app/ai/__init__.py
- app/ai/llm_client.py — Configurable LLM client (AI_MODEL, AI_API_KEY env vars)
- app/ai/action_mapper.py — Maps NL intents to API calls
### Workflow Engine
- app/models/workflow.py — Workflow, WorkflowInstance, WorkflowStepHistory models (tenant-scoped)
- app/schemas/workflow.py — WorkflowCreate, WorkflowResponse, InstanceCreate, InstanceResponse, AdvanceRequest
- app/services/workflow_service.py — CRUD workflows, instance lifecycle (start/advance/approve/reject/cancel)
- app/routes/workflows.py — Workflow CRUD + instance endpoints
- app/workflows/__init__.py
- app/workflows/code/__init__.py — Code-engine workflows
- app/workflows/code/onboarding.py — Onboarding workflow (runs on user creation)
- app/workflows/engine.py — Workflow execution engine (step processing, conditions, approvals)
### Tests
- tests/test_ai_copilot.py — 7 AC tests + edge cases
- tests/test_workflows.py — 15 AC tests + edge cases
### Migration
- alembic/versions/0004_ai_workflows.py — ai_conversations, ai_messages, workflows, workflow_instances, workflow_step_history tables (all tenant-scoped with RLS)
## Files to Modify
- app/main.py — Register ai_copilot + workflows routers
- app/models/__init__.py — Add new model imports
- app/routes/__init__.py — Add new router imports
- app/schemas/__init__.py — Add new schema imports
- app/services/__init__.py — Add new service imports
- tests/conftest.py — Add new tables to TRUNCATE list
- app/core/event_bus.py — Add workflow event trigger integration (if not already present)
## LLM Client Design
- Read AI_MODEL and AI_API_KEY from environment
- If not set, use mock/stub mode (returns predefined actions for tests)
- Support OpenAI-compatible API (default)
- NL → proposed API calls: method, path, body, description
- Never execute directly — always return proposed actions for user confirmation
## Workflow Engine Design
- Step types: action, approval, notification, condition
- Workflow definition: JSONB steps array
- Instance lifecycle: pending → in_progress → completed/rejected/cancelled
- Event bus integration: subscribe to events, auto-start workflows with matching trigger
- Code-engine: hardcoded workflows in app/workflows/code/ (onboarding on user.created event)
- Approval timeout: configurable hours, auto-reject via ARQ scheduled job or mock timer in tests
## Critical Rules
- All POST routes MUST have status_code=201 (except execute/advance/cancel which are actions → 200)
- Use set_config() for tenant context, NOT SET LOCAL
- Use .com emails in tests, NOT .test
- All new tables MUST have tenant_id column + RLS policies
- Update tests/conftest.py TRUNCATE list with new tables
- Create Alembic migration 0004 for all new tables
- Copilot MUST enforce RBAC (same middleware, same permissions)
- Copilot MUST respect tenant isolation and field-level permissions
- Audit log entity_type=ai_copilot for all copilot actions
- Workflow mutations MUST be logged in workflow_step_history
- Idempotent where applicable
## Test Commands
cd /a0/usr/workdir/dev-projects/leocrm && python -m pytest tests/test_ai_copilot.py tests/test_workflows.py -v --tb=short
cd /a0/usr/workdir/dev-projects/leocrm && python -m pytest tests/ -v --tb=short (full suite regression)
## Coverage Target
80% for new modules
## Deliverables
1. All files listed above
2. Alembic migration 0004
3. tests/test_ai_copilot.py + tests/test_workflows.py covering all 22 ACs
4. Report: test results, AC coverage, files, bugs