feat: Kontakt-Ordner mit Drag&Drop Baum (wie KI-Chat Sidebar)

- Backend: ContactFolder model (hierarchisch, parent_id, sort_order)
- Migration 0022: contact_folders Tabelle + folder_id FK auf contacts
- CRUD Routes: /api/v1/contact-folders (list, create, update, delete, reorder)
- Move Contact API: /api/v1/contact-folders/contacts/{id}/move
- folder_id Filter in contacts list API
- Frontend: ContactFolderTree mit Baum-Struktur, Drag&Drop, Kontext-Menü
- Kontakt-Personen-Icon statt Ordner-Symbol
- ContactList Items draggable (List/Table/Cards View)
- React Query Hooks für Folder CRUD + Move Contact
- Alle 266 Frontend-Tests passing
This commit is contained in:
Agent Zero
2026-07-20 01:33:44 +02:00
parent 4bc11efc25
commit 29202325a6
17 changed files with 942 additions and 8 deletions
+2
View File
@@ -29,6 +29,7 @@ from app.routes import (
audit,
auth,
companies,
contact_folders,
contacts,
groups,
health,
@@ -230,6 +231,7 @@ def create_app() -> FastAPI:
app.include_router(notifications.router)
app.include_router(companies.router)
app.include_router(contacts.router)
app.include_router(contact_folders.router)
app.include_router(import_export.router)
app.include_router(plugins.router)
app.include_router(ai_copilot.router)
+2
View File
@@ -7,6 +7,7 @@ from app.models.audit import AuditLog, DeletionLog
from app.models.auth import ApiToken, PasswordResetToken
from app.models.company import Company
from app.models.contact import Contact, ContactPerson
from app.models.contact_folder import ContactFolder
from app.models.currency import Currency
from app.models.group import Group, UserGroup
from app.models.notification import Notification, NotificationPreference, NotificationType
@@ -38,6 +39,7 @@ __all__ = [
"Company",
"Contact",
"ContactPerson",
"ContactFolder",
"Currency",
"TaxRate",
"Sequence",
+8
View File
@@ -142,6 +142,14 @@ class Contact(Base, TenantMixin):
PGUUID(as_uuid=True), ForeignKey("contactpersons.id", ondelete="SET NULL"), nullable=True
)
# ── Folder assignment ──
folder_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("contact_folders.id", ondelete="SET NULL"),
nullable=True,
index=True,
)
# ── Custom fields ──
custom: Mapped[dict | None] = mapped_column(JSON, nullable=True, default=dict)
+57
View File
@@ -0,0 +1,57 @@
"""ContactFolder model — hierarchical folders for organizing contacts.
Supports nested folders via parent_id, per-user ownership, and sort_order
for manual ordering via drag & drop.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, func
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.db import Base, TenantMixin
class ContactFolder(Base, TenantMixin):
"""Hierarchical folder for organizing contacts.
Folders are tenant-scoped and user-owned. A folder with parent_id=NULL
is a root folder. sort_order controls display order within the same parent.
"""
__tablename__ = "contact_folders"
__table_args__ = (
Index("ix_contact_folders_tenant_parent", "tenant_id", "parent_id"),
Index("ix_contact_folders_user", "user_id"),
)
id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
)
name: Mapped[str] = mapped_column(String(255), nullable=False)
parent_id: Mapped[uuid.UUID | None] = mapped_column(
PGUUID(as_uuid=True),
ForeignKey("contact_folders.id", ondelete="CASCADE"),
nullable=True,
)
user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default="0")
# ── Relationships ──
parent: Mapped[ContactFolder | None] = relationship(
"ContactFolder",
remote_side="ContactFolder.id",
back_populates="children",
)
children: Mapped[list[ContactFolder]] = relationship(
"ContactFolder",
back_populates="parent",
cascade="all, delete-orphan",
order_by="ContactFolder.sort_order",
)
+109
View File
@@ -0,0 +1,109 @@
"""Contact folder routes — CRUD, move contacts, reorder."""
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.deps import require_permission
from app.schemas.contact_folder import (
ContactFolderCreate,
ContactFolderUpdate,
MoveContactRequest,
)
from app.services import contact_folder_service
router = APIRouter(prefix="/api/v1/contact-folders", tags=["contact-folders"])
@router.get("")
async def list_folders(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("contacts:read")),
):
"""List all contact folders for the current user."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
return await contact_folder_service.list_folders(db, tenant_id, user_id)
@router.post("", status_code=status.HTTP_201_CREATED)
async def create_folder(
body: ContactFolderCreate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Create a new contact folder."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
return await contact_folder_service.create_folder(
db, tenant_id, user_id, body.name, body.parent_id
)
@router.put("/{folder_id}")
async def update_folder(
folder_id: str,
body: ContactFolderUpdate,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Update a contact folder (name, parent, sort_order)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
data = body.model_dump(exclude_none=True)
try:
return await contact_folder_service.update_folder(
db, tenant_id, user_id, folder_id, data
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.delete("/{folder_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_folder(
folder_id: str,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Delete a contact folder. Contacts are unassigned."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
try:
await contact_folder_service.delete_folder(db, tenant_id, user_id, folder_id)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
@router.put("/{folder_id}/reorder")
async def reorder_folders(
folder_id: str,
body: list[dict],
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Batch reorder folders. Body: [{id, sort_order, parent_id?}, ...]."""
tenant_id = uuid.UUID(current_user["tenant_id"])
user_id = uuid.UUID(current_user["user_id"])
await contact_folder_service.reorder_folders(db, tenant_id, user_id, body)
return {"ok": True}
@router.put("/contacts/{contact_id}/move")
async def move_contact(
contact_id: str,
body: MoveContactRequest,
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("contacts:write")),
):
"""Move a contact to a folder (or unassign with folder_id=null)."""
tenant_id = uuid.UUID(current_user["tenant_id"])
try:
return await contact_folder_service.move_contact(
db, tenant_id, contact_id, body.folder_id
)
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
+4 -2
View File
@@ -29,17 +29,19 @@ async def list_contacts(
page_size: int = Query(20, ge=1, le=100),
search: str | None = Query(None),
type: str | None = Query(None, pattern="^(company|person)$"),
folder_id: str | None = Query(None),
sort_by: str = Query("displayname"),
sort_order: str = Query("asc", pattern="^(asc|desc)$"),
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("contacts:read")),
):
"""List contacts with pagination, FTS search, type filter, sorting."""
"""List contacts with pagination, FTS search, type/folder filter, sorting."""
tenant_id = uuid.UUID(current_user["tenant_id"])
return await contact_service.list_contacts(
db, tenant_id,
page=page, page_size=page_size, search=search,
contact_type=type, sort_by=sort_by, sort_order=sort_order,
contact_type=type, folder_id=folder_id,
sort_by=sort_by, sort_order=sort_order,
resolved_perms=current_user,
)
+4
View File
@@ -141,6 +141,8 @@ class ContactCreate(BaseModel):
image: str | None = None
# Custom
custom: dict | None = None
# Folder assignment
folder_id: str | None = None
# Contact persons (optional inline create)
contact_persons: list[ContactPersonCreate] | None = None
@@ -208,6 +210,7 @@ class ContactUpdate(BaseModel):
tags: str | None = Field(None, max_length=500)
image: str | None = None
custom: dict | None = None
folder_id: str | None = None
default_person_id: str | None = None
admin_contactperson_id: str | None = None
@@ -278,6 +281,7 @@ class ContactResponse(BaseModel):
tags: str | None = None
image: str | None = None
custom: dict | None = None
folder_id: str | None = None
default_person_id: str | None = None
admin_contactperson_id: str | None = None
created_at: str | None = None
+33
View File
@@ -0,0 +1,33 @@
"""Contact folder schemas — CRUD for hierarchical contact folders."""
from __future__ import annotations
from pydantic import BaseModel, Field
class ContactFolderCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=255)
parent_id: str | None = None
class ContactFolderUpdate(BaseModel):
name: str | None = Field(None, min_length=1, max_length=255)
parent_id: str | None = None
sort_order: int | None = None
class ContactFolderResponse(BaseModel):
id: str
name: str
parent_id: str | None = None
user_id: str
sort_order: int = 0
class ContactFolderTreeResponse(ContactFolderResponse):
children: list["ContactFolderTreeResponse"] = Field(default_factory=list)
contact_count: int = 0
class MoveContactRequest(BaseModel):
folder_id: str | None = None
+194
View File
@@ -0,0 +1,194 @@
"""Contact folder service — CRUD, tree building, move contacts."""
from __future__ import annotations
import uuid
from typing import Any
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.models.contact import Contact
from app.models.contact_folder import ContactFolder
def _serialize_folder(f: ContactFolder, contact_count: int = 0) -> dict:
return {
"id": str(f.id),
"name": f.name,
"parent_id": str(f.parent_id) if f.parent_id else None,
"user_id": str(f.user_id),
"sort_order": f.sort_order,
"contact_count": contact_count,
}
async def list_folders(
db: AsyncSession, tenant_id: uuid.UUID, user_id: uuid.UUID
) -> list[dict]:
"""List all folders for a user (flat list, frontend builds tree)."""
result = await db.execute(
select(ContactFolder)
.where(ContactFolder.tenant_id == tenant_id)
.where(ContactFolder.user_id == user_id)
.where(ContactFolder.deleted_at.is_(None))
.order_by(ContactFolder.parent_id, ContactFolder.sort_order, ContactFolder.name)
)
folders = result.scalars().all()
# Count contacts per folder
folder_ids = [f.id for f in folders]
counts: dict[uuid.UUID, int] = {}
if folder_ids:
count_result = await db.execute(
select(Contact.folder_id, func.count(Contact.id))
.where(Contact.folder_id.in_(folder_ids))
.where(Contact.deleted_at.is_(None))
.group_by(Contact.folder_id)
)
for fid, cnt in count_result:
counts[fid] = cnt
return [
{**_serialize_folder(f), "contact_count": counts.get(f.id, 0)}
for f in folders
]
async def create_folder(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID,
name: str,
parent_id: str | None = None,
) -> dict:
"""Create a new contact folder."""
parent_uuid = uuid.UUID(parent_id) if parent_id else None
# Determine sort_order: max + 1 among siblings
max_order_result = await db.execute(
select(func.max(ContactFolder.sort_order))
.where(ContactFolder.tenant_id == tenant_id)
.where(ContactFolder.user_id == user_id)
.where(ContactFolder.parent_id == parent_uuid if parent_uuid else ContactFolder.parent_id.is_(None))
)
max_order = max_order_result.scalar() or 0
folder = ContactFolder(
tenant_id=tenant_id,
user_id=user_id,
name=name,
parent_id=parent_uuid,
sort_order=max_order + 1,
)
db.add(folder)
await db.commit()
await db.refresh(folder)
return _serialize_folder(folder)
async def update_folder(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID,
folder_id: str,
data: dict,
) -> dict:
"""Update a contact folder (name, parent_id, sort_order)."""
result = await db.execute(
select(ContactFolder)
.where(ContactFolder.id == uuid.UUID(folder_id))
.where(ContactFolder.tenant_id == tenant_id)
.where(ContactFolder.user_id == user_id)
.where(ContactFolder.deleted_at.is_(None))
)
folder = result.scalar_one_or_none()
if not folder:
raise ValueError("Folder not found")
if "name" in data and data["name"]:
folder.name = data["name"]
if "parent_id" in data:
new_parent = data["parent_id"]
folder.parent_id = uuid.UUID(new_parent) if new_parent else None
if "sort_order" in data and data["sort_order"] is not None:
folder.sort_order = data["sort_order"]
await db.commit()
await db.refresh(folder)
return _serialize_folder(folder)
async def delete_folder(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID,
folder_id: str,
) -> None:
"""Delete a contact folder. Contacts are unassigned (folder_id SET NULL)."""
result = await db.execute(
select(ContactFolder)
.where(ContactFolder.id == uuid.UUID(folder_id))
.where(ContactFolder.tenant_id == tenant_id)
.where(ContactFolder.user_id == user_id)
.where(ContactFolder.deleted_at.is_(None))
)
folder = result.scalar_one_or_none()
if not folder:
raise ValueError("Folder not found")
# Unassign contacts in this folder (and subfolders via CASCADE on folder delete)
await db.execute(
update(Contact)
.where(Contact.folder_id == folder.id)
.values(folder_id=None)
)
await db.delete(folder)
await db.commit()
async def move_contact(
db: AsyncSession,
tenant_id: uuid.UUID,
contact_id: str,
folder_id: str | None,
) -> dict:
"""Move a contact to a folder (or unassign with folder_id=None)."""
result = await db.execute(
select(Contact)
.where(Contact.id == uuid.UUID(contact_id))
.where(Contact.tenant_id == tenant_id)
.where(Contact.deleted_at.is_(None))
)
contact = result.scalar_one_or_none()
if not contact:
raise ValueError("Contact not found")
contact.folder_id = uuid.UUID(folder_id) if folder_id else None
await db.commit()
await db.refresh(contact)
return {"id": str(contact.id), "folder_id": str(contact.folder_id) if contact.folder_id else None}
async def reorder_folders(
db: AsyncSession,
tenant_id: uuid.UUID,
user_id: uuid.UUID,
folder_orders: list[dict],
) -> None:
"""Batch update sort_order for folders. Each item: {id, sort_order, parent_id?}."""
for item in folder_orders:
fid = uuid.UUID(item["id"])
await db.execute(
update(ContactFolder)
.where(ContactFolder.id == fid)
.where(ContactFolder.tenant_id == tenant_id)
.where(ContactFolder.user_id == user_id)
.values(
sort_order=item.get("sort_order", 0),
parent_id=uuid.UUID(item["parent_id"]) if item.get("parent_id") else None,
)
)
await db.commit()
+6 -1
View File
@@ -90,6 +90,7 @@ def _serialize_contact(c: Contact) -> dict:
"tags": c.tags,
"image": c.image,
"custom": c.custom,
"folder_id": str(c.folder_id) if c.folder_id else None,
"default_person_id": str(c.default_person_id) if c.default_person_id else None,
"admin_contactperson_id": str(c.admin_contactperson_id) if c.admin_contactperson_id else None,
"created_at": c.created_at.isoformat() if c.created_at else None,
@@ -137,11 +138,12 @@ async def list_contacts(
page_size: int = 20,
search: str | None = None,
contact_type: str | None = None,
folder_id: str | None = None,
sort_by: str = "displayname",
sort_order: str = "asc",
resolved_perms: dict | None = None,
) -> dict:
"""List contacts with pagination, FTS search, type filter, sorting."""
"""List contacts with pagination, FTS search, type/folder filter, sorting."""
base = select(Contact).where(
Contact.tenant_id == tenant_id,
Contact.deleted_at.is_(None),
@@ -150,6 +152,9 @@ async def list_contacts(
if contact_type:
base = base.where(Contact.type == contact_type)
if folder_id:
base = base.where(Contact.folder_id == uuid.UUID(folder_id))
if search:
base = base.where(
Contact.search_tsv.op("@@")(func.plainto_tsquery("german", search))