From 118bae1ae30ef73f60a84965bfc3db873e4fd0d3 Mon Sep 17 00:00:00 2001 From: m Date: Mon, 30 Mar 2026 11:24:52 +0200 Subject: [PATCH] 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 --- backend/internal/handlers/tenant_handler.go | 80 +++++++++++++++++++ backend/internal/services/tenant_service.go | 48 +++++++++++ frontend/src/app/(app)/layout.tsx | 2 + frontend/src/app/(auth)/register/page.tsx | 72 ++++++++++++----- frontend/src/components/layout/DemoBanner.tsx | 17 ++++ frontend/src/lib/hooks/usePermissions.ts | 1 + frontend/src/lib/types.ts | 1 + 7 files changed, 203 insertions(+), 18 deletions(-) create mode 100644 frontend/src/components/layout/DemoBanner.tsx diff --git a/backend/internal/handlers/tenant_handler.go b/backend/internal/handlers/tenant_handler.go index 6341b1d..8c77ac3 100644 --- a/backend/internal/handlers/tenant_handler.go +++ b/backend/internal/handlers/tenant_handler.go @@ -356,6 +356,71 @@ func (h *TenantHandler) UpdateMemberRole(w http.ResponseWriter, r *http.Request) jsonResponse(w, map[string]string{"status": "updated"}, http.StatusOK) } +// AutoAssign handles POST /api/tenants/auto-assign — checks if the user's email domain +// matches any tenant's auto_assign_domains and assigns them if so. +func (h *TenantHandler) AutoAssign(w http.ResponseWriter, r *http.Request) { + userID, ok := auth.UserFromContext(r.Context()) + if !ok { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + var req struct { + Email string `json:"email"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + jsonError(w, "invalid request body", http.StatusBadRequest) + return + } + if req.Email == "" { + jsonError(w, "email is required", http.StatusBadRequest) + return + } + + // Extract domain from email + parts := splitEmail(req.Email) + if parts == "" { + jsonError(w, "invalid email format", http.StatusBadRequest) + return + } + + result, err := h.svc.AutoAssignByDomain(r.Context(), userID, parts) + if err != nil { + slog.Error("auto-assign failed", "error", err) + jsonError(w, "internal error", http.StatusInternalServerError) + return + } + + if result == nil { + jsonResponse(w, map[string]any{"assigned": false}, http.StatusOK) + return + } + + jsonResponse(w, map[string]any{ + "assigned": true, + "tenant_id": result.ID, + "name": result.Name, + "slug": result.Slug, + "role": result.Role, + "settings": result.Settings, + }, http.StatusOK) +} + +// splitEmail extracts the domain part from an email address. +func splitEmail(email string) string { + at := -1 + for i, c := range email { + if c == '@' { + at = i + break + } + } + if at < 0 || at >= len(email)-1 { + return "" + } + return email[at+1:] +} + // GetMe handles GET /api/me — returns the current user's ID and role in the active tenant. func (h *TenantHandler) GetMe(w http.ResponseWriter, r *http.Request) { userID, ok := auth.UserFromContext(r.Context()) @@ -370,11 +435,26 @@ func (h *TenantHandler) GetMe(w http.ResponseWriter, r *http.Request) { // Get user's permissions for frontend UI perms := auth.GetRolePermissions(role) + // Check if tenant is in demo mode + isDemo := false + if tenant, err := h.svc.GetByID(r.Context(), tenantID); err == nil && tenant != nil { + var settings map[string]json.RawMessage + if json.Unmarshal(tenant.Settings, &settings) == nil { + if demoRaw, ok := settings["demo"]; ok { + var demo bool + if json.Unmarshal(demoRaw, &demo) == nil { + isDemo = demo + } + } + } + } + jsonResponse(w, map[string]any{ "user_id": userID, "tenant_id": tenantID, "role": role, "permissions": perms, + "is_demo": isDemo, }, http.StatusOK) } diff --git a/backend/internal/services/tenant_service.go b/backend/internal/services/tenant_service.go index e0f5cea..e3eea33 100644 --- a/backend/internal/services/tenant_service.go +++ b/backend/internal/services/tenant_service.go @@ -240,6 +240,54 @@ func (s *TenantService) UpdateMemberRole(ctx context.Context, tenantID, userID u return nil } +// AutoAssignByDomain finds a tenant with a matching auto_assign_domains setting +// and adds the user as a member. Returns the tenant and role, or nil if no match. +func (s *TenantService) AutoAssignByDomain(ctx context.Context, userID uuid.UUID, emailDomain string) (*models.TenantWithRole, error) { + // Find tenant where settings.auto_assign_domains contains this domain + var tenant models.Tenant + err := s.db.GetContext(ctx, &tenant, + `SELECT id, name, slug, settings, created_at, updated_at + FROM tenants + WHERE settings->'auto_assign_domains' ? $1 + LIMIT 1`, + emailDomain, + ) + if err != nil { + return nil, nil // no match — not an error + } + + // Check if already a member + var exists bool + err = s.db.GetContext(ctx, &exists, + `SELECT EXISTS(SELECT 1 FROM user_tenants WHERE user_id = $1 AND tenant_id = $2)`, + userID, tenant.ID, + ) + if err != nil { + return nil, fmt.Errorf("check membership: %w", err) + } + if exists { + // Already a member — return the existing membership + role, err := s.GetUserRole(ctx, userID, tenant.ID) + if err != nil { + return nil, fmt.Errorf("get existing role: %w", err) + } + return &models.TenantWithRole{Tenant: tenant, Role: role}, nil + } + + // Add as member (associate by default for auto-assigned users) + role := "associate" + _, err = s.db.ExecContext(ctx, + `INSERT INTO user_tenants (user_id, tenant_id, role) VALUES ($1, $2, $3)`, + userID, tenant.ID, role, + ) + if err != nil { + return nil, fmt.Errorf("auto-assign user: %w", err) + } + + s.audit.Log(ctx, "create", "auto_membership", &tenant.ID, map[string]any{"domain": emailDomain}, map[string]any{"user_id": userID, "role": role}) + return &models.TenantWithRole{Tenant: tenant, Role: role}, nil +} + // RemoveMember removes a user from a tenant. Cannot remove the last owner. func (s *TenantService) RemoveMember(ctx context.Context, tenantID, userID uuid.UUID) error { // Check if the user being removed is an owner diff --git a/frontend/src/app/(app)/layout.tsx b/frontend/src/app/(app)/layout.tsx index 8740d7d..b102bd9 100644 --- a/frontend/src/app/(app)/layout.tsx +++ b/frontend/src/app/(app)/layout.tsx @@ -1,5 +1,6 @@ import { Sidebar } from "@/components/layout/Sidebar"; import { Header } from "@/components/layout/Header"; +import { DemoBanner } from "@/components/layout/DemoBanner"; export const dynamic = "force-dynamic"; @@ -12,6 +13,7 @@ export default function AppLayout({
+
{children}
diff --git a/frontend/src/app/(auth)/register/page.tsx b/frontend/src/app/(auth)/register/page.tsx index afa4a0a..6bd691d 100644 --- a/frontend/src/app/(auth)/register/page.tsx +++ b/frontend/src/app/(auth)/register/page.tsx @@ -5,12 +5,22 @@ import { api } from "@/lib/api"; import { useRouter } from "next/navigation"; import { useState } from "react"; +interface AutoAssignResponse { + assigned: boolean; + tenant_id?: string; + name?: string; + slug?: string; + role?: string; + settings?: Record; +} + export default function RegisterPage() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [firmName, setFirmName] = useState(""); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); + const [showFirmName, setShowFirmName] = useState(true); const router = useRouter(); const supabase = createClient(); @@ -34,8 +44,30 @@ export default function RegisterPage() { return; } - // 2. Create tenant via backend (the backend adds the user as owner) if (data.session) { + // 2. Check if email domain matches an existing tenant for auto-assignment + try { + const result = await api.post("/tenants/auto-assign", { email }); + if (result.assigned && result.tenant_id) { + // Auto-assigned — store tenant and go to dashboard + localStorage.setItem("kanzlai_tenant_id", result.tenant_id); + router.push("/"); + router.refresh(); + return; + } + } catch { + // Auto-assign failed — fall through to manual tenant creation + } + + // 3. No auto-assignment — create tenant manually + if (!firmName) { + // Show firm name field if not yet visible + setShowFirmName(true); + setError("Bitte geben Sie einen Kanzleinamen ein"); + setLoading(false); + return; + } + try { await api.post("/tenants", { name: firmName }); } catch (err: unknown) { @@ -68,23 +100,27 @@ export default function RegisterPage() {
-
- - setFirmName(e.target.value)} - required - className="mt-1 block w-full rounded-md border border-neutral-300 px-3 py-2 text-sm placeholder-neutral-400 focus:border-neutral-900 focus:outline-none focus:ring-1 focus:ring-neutral-900" - placeholder="Muster & Partner Rechtsanwaelte" - /> -
+ {showFirmName && ( +
+ + setFirmName(e.target.value)} + className="mt-1 block w-full rounded-md border border-neutral-300 px-3 py-2 text-sm placeholder-neutral-400 focus:border-neutral-900 focus:outline-none focus:ring-1 focus:ring-neutral-900" + placeholder="Muster & Partner Rechtsanwaelte" + /> +

+ Leer lassen, falls Sie zu einer bestehenden Kanzlei eingeladen wurden +

+
+ )}
+ ); +} diff --git a/frontend/src/lib/hooks/usePermissions.ts b/frontend/src/lib/hooks/usePermissions.ts index 57e43fe..978dea6 100644 --- a/frontend/src/lib/hooks/usePermissions.ts +++ b/frontend/src/lib/hooks/usePermissions.ts @@ -25,5 +25,6 @@ export function usePermissions() { isLoading, userId: data?.user_id ?? null, tenantId: data?.tenant_id ?? null, + isDemo: data?.is_demo ?? false, }; } diff --git a/frontend/src/lib/types.ts b/frontend/src/lib/types.ts index a842be4..e011b9f 100644 --- a/frontend/src/lib/types.ts +++ b/frontend/src/lib/types.ts @@ -202,6 +202,7 @@ export interface UserInfo { tenant_id: string; role: UserRole; permissions: string[]; + is_demo: boolean; } export type UserRole = "owner" | "partner" | "associate" | "paralegal" | "secretary";