feat(5.2): add User Preferences API with full-stack implementation
Backend: - Create app/models/user_preference.py with TenantMixin (user_id, key, value JSONB) - Create app/routes/user_preferences.py with GET/PUT/DELETE endpoints + RBAC - Add user_preferences:read/write to CORE_PERMISSIONS - Add user_preferences to legacy role permissions (admin/editor/viewer) - Register route in app/main.py and app/routes/__init__.py - Create alembic migration 0028_user_preferences - Add UserPreference model to conftest.py for test schema - Fix pre-existing conftest seed (Contact industry field removed in migration 0027) Frontend: - Create frontend/src/api/userPreferences.ts with React Query hooks - Create frontend/src/hooks/useUserPreferences.ts syncing with uiStore - Add i18n entries for de.json and en.json Tests: - 13 tests covering CRUD, tenant isolation, CSRF, unauthenticated access - All tests passing
This commit is contained in:
@@ -41,6 +41,8 @@ CORE_PERMISSIONS: list[dict[str, str]] = [
|
||||
{"key": "attachments:delete", "label": "Attachments: Delete", "category": "core", "module": "attachments"},
|
||||
{"key": "workflows:read", "label": "Workflows: Read", "category": "core", "module": "workflows"},
|
||||
{"key": "workflows:write", "label": "Workflows: Write", "category": "core", "module": "workflows"},
|
||||
{"key": "user_preferences:read", "label": "User Preferences: Read", "category": "core", "module": "user_preferences"},
|
||||
{"key": "user_preferences:write", "label": "User Preferences: Write", "category": "core", "module": "user_preferences"},
|
||||
{"key": "sequences:read", "label": "Sequences: Read", "category": "core", "module": "sequences"},
|
||||
{"key": "sequences:write", "label": "Sequences: Write", "category": "core", "module": "sequences"},
|
||||
{"key": "addresses:read", "label": "Addresses: Read", "category": "core", "module": "addresses"},
|
||||
|
||||
@@ -162,12 +162,14 @@ async def resolve_permissions(
|
||||
"sequences:read", "sequences:write", "addresses:read", "addresses:write",
|
||||
"taxes:read", "taxes:write", "currencies:read", "currencies:write",
|
||||
"notifications:read", "notifications:write", "import_export:read",
|
||||
"import_export:write"}
|
||||
"import_export:write",
|
||||
"user_preferences:read", "user_preferences:write"}
|
||||
elif legacy_role == "viewer":
|
||||
allowed |= {"contacts:read", "contacts:read", "users:read", "roles:read",
|
||||
"audit:read", "attachments:read", "workflows:read", "sequences:read",
|
||||
"addresses:read", "taxes:read", "currencies:read",
|
||||
"notifications:read", "import_export:read"}
|
||||
"notifications:read", "import_export:read",
|
||||
"user_preferences:read", "user_preferences:write"}
|
||||
|
||||
# Load group permissions
|
||||
ug_q = select(UserGroup).where(
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.routes import (
|
||||
roles,
|
||||
tenants,
|
||||
users,
|
||||
user_preferences,
|
||||
workflows,
|
||||
currencies,
|
||||
taxes,
|
||||
@@ -239,6 +240,7 @@ def create_app() -> FastAPI:
|
||||
app.include_router(plugins.router)
|
||||
app.include_router(ai_copilot.router)
|
||||
app.include_router(workflows.router)
|
||||
app.include_router(user_preferences.router)
|
||||
app.include_router(currencies.router)
|
||||
app.include_router(taxes.router)
|
||||
app.include_router(sequences.router)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""User Preference model — per-user UI settings stored as key/value JSONB, tenant-scoped."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, String, UniqueConstraint
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.db import Base, TenantMixin
|
||||
|
||||
|
||||
class UserPreference(Base, TenantMixin):
|
||||
"""Per-user preference entry — stores a single UI preference as JSONB value.
|
||||
|
||||
Keys are arbitrary strings (e.g. 'sidebar_collapsed', 'theme', 'active_tab').
|
||||
Values are JSONB to support complex preference structures.
|
||||
"""
|
||||
|
||||
__tablename__ = "user_preferences"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"user_id",
|
||||
"key",
|
||||
name="uq_user_prefs_tenant_user_key",
|
||||
),
|
||||
Index(
|
||||
"ix_user_prefs_tenant_user",
|
||||
"tenant_id",
|
||||
"user_id",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||
)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PGUUID(as_uuid=True),
|
||||
ForeignKey("users.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
key: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
value: Mapped[Any] = mapped_column(JSONB, nullable=False, default=dict)
|
||||
@@ -20,5 +20,6 @@ from app.routes import (
|
||||
roles, # noqa: F401
|
||||
tenants, # noqa: F401
|
||||
users, # noqa: F401
|
||||
user_preferences, # noqa: F401
|
||||
workflows, # noqa: F401
|
||||
)
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
"""User Preferences routes — per-user UI settings via API, tenant-scoped with RBAC."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.db import get_db
|
||||
from app.deps import require_permission
|
||||
from app.models.user_preference import UserPreference
|
||||
|
||||
router = APIRouter(prefix="/api/v1/user/preferences", tags=["user-preferences"])
|
||||
|
||||
|
||||
# ─── Schemas ───
|
||||
|
||||
|
||||
class PreferenceValue(BaseModel):
|
||||
"""Arbitrary JSON value for a preference key."""
|
||||
|
||||
value: Any = Field(..., description="JSON value for the preference key")
|
||||
|
||||
|
||||
class PreferenceResponse(BaseModel):
|
||||
"""Single preference entry response."""
|
||||
|
||||
key: str
|
||||
value: Any
|
||||
updated_at: str | None = None
|
||||
|
||||
|
||||
class PreferenceListResponse(BaseModel):
|
||||
"""All preferences for the current user."""
|
||||
|
||||
preferences: list[PreferenceResponse]
|
||||
|
||||
|
||||
# ─── Helpers ───
|
||||
|
||||
|
||||
def _pref_to_response(p: UserPreference) -> PreferenceResponse:
|
||||
"""Convert UserPreference model to response schema."""
|
||||
updated_at = None
|
||||
try:
|
||||
updated_at = p.updated_at.isoformat() if p.updated_at else None
|
||||
except Exception:
|
||||
pass
|
||||
return PreferenceResponse(
|
||||
key=p.key,
|
||||
value=p.value,
|
||||
updated_at=updated_at,
|
||||
)
|
||||
|
||||
|
||||
# ─── Endpoints ───
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_user_preferences(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict[str, Any] = Depends(
|
||||
require_permission("user_preferences:read")
|
||||
),
|
||||
) -> PreferenceListResponse:
|
||||
"""Get all preferences for the current user."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
|
||||
result = await db.execute(
|
||||
select(UserPreference)
|
||||
.where(
|
||||
UserPreference.tenant_id == tenant_id,
|
||||
UserPreference.user_id == user_id,
|
||||
UserPreference.deleted_at.is_(None),
|
||||
)
|
||||
.order_by(UserPreference.key)
|
||||
)
|
||||
prefs = result.scalars().all()
|
||||
return PreferenceListResponse(
|
||||
preferences=[_pref_to_response(p) for p in prefs]
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{key}")
|
||||
async def get_user_preference(
|
||||
key: str,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict[str, Any] = Depends(
|
||||
require_permission("user_preferences:read")
|
||||
),
|
||||
) -> PreferenceResponse:
|
||||
"""Get a single preference by key."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
|
||||
result = await db.execute(
|
||||
select(UserPreference).where(
|
||||
UserPreference.tenant_id == tenant_id,
|
||||
UserPreference.user_id == user_id,
|
||||
UserPreference.key == key,
|
||||
UserPreference.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
pref = result.scalar_one_or_none()
|
||||
if pref is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail={
|
||||
"detail": f"Preference '{key}' not found",
|
||||
"code": "not_found",
|
||||
},
|
||||
)
|
||||
return _pref_to_response(pref)
|
||||
|
||||
|
||||
@router.put("/{key}")
|
||||
async def upsert_user_preference(
|
||||
key: str,
|
||||
body: PreferenceValue,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict[str, Any] = Depends(
|
||||
require_permission("user_preferences:write")
|
||||
),
|
||||
) -> PreferenceResponse:
|
||||
"""Create or update a preference by key (upsert)."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
|
||||
result = await db.execute(
|
||||
select(UserPreference).where(
|
||||
UserPreference.tenant_id == tenant_id,
|
||||
UserPreference.user_id == user_id,
|
||||
UserPreference.key == key,
|
||||
UserPreference.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
pref = result.scalar_one_or_none()
|
||||
|
||||
if pref is None:
|
||||
pref = UserPreference(
|
||||
tenant_id=tenant_id,
|
||||
user_id=user_id,
|
||||
key=key,
|
||||
value=body.value,
|
||||
)
|
||||
db.add(pref)
|
||||
else:
|
||||
pref.value = body.value
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(pref)
|
||||
return _pref_to_response(pref)
|
||||
|
||||
|
||||
@router.delete("/{key}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_user_preference(
|
||||
key: str,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: dict[str, Any] = Depends(
|
||||
require_permission("user_preferences:write")
|
||||
),
|
||||
):
|
||||
"""Delete a preference by key (soft-delete)."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
|
||||
result = await db.execute(
|
||||
select(UserPreference).where(
|
||||
UserPreference.tenant_id == tenant_id,
|
||||
UserPreference.user_id == user_id,
|
||||
UserPreference.key == key,
|
||||
UserPreference.deleted_at.is_(None),
|
||||
)
|
||||
)
|
||||
pref = result.scalar_one_or_none()
|
||||
if pref is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail={
|
||||
"detail": f"Preference '{key}' not found",
|
||||
"code": "not_found",
|
||||
},
|
||||
)
|
||||
|
||||
# Soft-delete via TenantMixin's deleted_at
|
||||
from datetime import UTC, datetime
|
||||
|
||||
pref.deleted_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
return None
|
||||
Reference in New Issue
Block a user