feat: projekte und suche im backend

Projekte pro Benutzer mit Name und Farbe, Clips optional einem Projekt
zugeordnet. Löschen eines Projekts verschiebt seine Clips nach "ohne
Projekt". Clip-Liste filtert nach Projekt und sucht Teiltexte in Titel
und Inhalt, unabhängig von Groß-/Kleinschreibung (auch Umlaute).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dbildhauerandClaude Opus 5.5 committed 2026-10-25 13:15:05 +01:00
1 parent 848cff35b3
commit ff2860f7be
13 files changed
+711 -9

No files matched your search

+46 -5
View File
@@ -1,15 +1,20 @@
from typing import Any
from sqlalchemy import delete, func, select, update
from sqlalchemy import delete, func, or_, select, update
from sqlalchemy.orm import Session
from app.config import get_settings
from app.languages import LANGUAGES
from app.models import Clip, ClipKind, utcnow
from app.services.projects import require_project
from app.services.users import UserError
# Changing only these fields does not count as an edit (no new updated_at)
_META_FIELDS = frozenset({"pinned"})
_META_FIELDS = frozenset({"pinned", "project_id"})
# Filter value for clips without a project
NO_PROJECT = "none"
SEARCH_MAX_LENGTH = 200
class ClipConflict(Exception):
@@ -40,15 +45,43 @@ def _normalize(kind: ClipKind, title: str | None, content: str, language: str |
return title, language
def list_clips(db: Session, user_id: int, limit: int, offset: int) -> tuple[list[Clip], int]:
def _filters(user_id: int, project: int | str | None, query: str | None) -> list:
conditions = [Clip.user_id == user_id]
if project == NO_PROJECT:
conditions.append(Clip.project_id.is_(None))
elif project is not None:
conditions.append(Clip.project_id == project)
needle = (query or "").strip().casefold()
if needle:
# Substring match via instr(): no LIKE wildcards to escape, finds "config" in "getConfig"
conditions.append(
or_(
func.instr(func.lc_casefold(Clip.title), needle) > 0,
func.instr(func.lc_casefold(Clip.content), needle) > 0,
)
)
return conditions
def list_clips(
db: Session,
user_id: int,
limit: int,
offset: int,
*,
project: int | str | None = None,
query: str | None = None,
) -> tuple[list[Clip], int]:
"""Clips of the user, optionally only those of a project (or NO_PROJECT) matching a query."""
conditions = _filters(user_id, project, query)
items = db.scalars(
select(Clip)
.where(Clip.user_id == user_id)
.where(*conditions)
.order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc())
.limit(limit)
.offset(offset)
)
total = db.scalar(select(func.count()).select_from(Clip).where(Clip.user_id == user_id))
total = db.scalar(select(func.count()).select_from(Clip).where(*conditions))
return list(items), total or 0
@@ -65,10 +98,14 @@ def create_clip(
title: str | None = None,
language: str | None = None,
pinned: bool = False,
project_id: int | None = None,
) -> Clip:
title, language = _normalize(kind, title, content, language)
if project_id is not None:
require_project(db, user_id, project_id)
clip = Clip(
user_id=user_id,
project_id=project_id,
kind=kind,
title=title,
content=content,
@@ -93,8 +130,12 @@ def update_clip(
content = changes.get("content", clip.content)
language = changes.get("language", clip.language)
title, language = _normalize(kind, title, content, language)
project_id = changes.get("project_id", clip.project_id)
if "project_id" in changes and project_id is not None:
require_project(db, user_id, project_id)
values: dict[str, Any] = {
"project_id": project_id,
"kind": kind,
"title": title,
"content": content,
+123
View File
@@ -0,0 +1,123 @@
import unicodedata
from sqlalchemy import delete, func, select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.models import PROJECT_COLORS, Clip, Project, utcnow
from app.services.users import UserError
NAME_MAX_LENGTH = 100
MAX_PROJECTS_PER_USER = 200
class ProjectNotFound(LookupError):
"""The project does not exist or belongs to another user."""
def _validate_name(name: str) -> tuple[str, str]:
name = " ".join(name.split())
if not name:
raise UserError("Der Projektname darf nicht leer sein.")
if len(name) > NAME_MAX_LENGTH:
raise UserError(f"Der Projektname ist zu lang (höchstens {NAME_MAX_LENGTH} Zeichen).")
if any(unicodedata.category(ch).startswith("C") for ch in name):
raise UserError("Der Projektname enthält ungültige Zeichen.")
return name, name.casefold()
def _validate_color(color: str) -> str:
if color not in PROJECT_COLORS:
raise UserError("Unbekannte Farbe.")
return color
def _duplicate() -> UserError:
return UserError("Ein Projekt mit diesem Namen gibt es schon.")
def list_projects(db: Session, user_id: int) -> list[tuple[Project, int]]:
"""Projects of the user, sorted by name, each with its number of clips."""
clip_count = (
select(func.count(Clip.id))
.where(Clip.project_id == Project.id, Clip.user_id == user_id)
.scalar_subquery()
)
rows = db.execute(
select(Project, clip_count)
.where(Project.user_id == user_id)
.order_by(Project.name_key, Project.id)
)
return [(project, count) for project, count in rows]
def get_project(db: Session, user_id: int, project_id: int) -> Project | None:
return db.scalar(select(Project).where(Project.id == project_id, Project.user_id == user_id))
def require_project(db: Session, user_id: int, project_id: int) -> Project:
project = get_project(db, user_id, project_id)
if project is None:
raise ProjectNotFound(project_id)
return project
def count_clips(db: Session, user_id: int, project_id: int) -> int:
return (
db.scalar(
select(func.count(Clip.id)).where(
Clip.user_id == user_id, Clip.project_id == project_id
)
)
or 0
)
def create_project(db: Session, user_id: int, *, name: str, color: str = "blue") -> Project:
name, name_key = _validate_name(name)
color = _validate_color(color)
existing = db.scalar(select(func.count(Project.id)).where(Project.user_id == user_id))
if (existing or 0) >= MAX_PROJECTS_PER_USER:
raise UserError(f"Höchstens {MAX_PROJECTS_PER_USER} Projekte möglich.")
project = Project(user_id=user_id, name=name, name_key=name_key, color=color)
db.add(project)
try:
db.commit()
except IntegrityError:
db.rollback()
raise _duplicate() from None
return project
def update_project(
db: Session, project: Project, *, name: str | None = None, color: str | None = None
) -> Project:
if name is not None:
project.name, project.name_key = _validate_name(name)
if color is not None:
project.color = _validate_color(color)
project.updated_at = utcnow()
try:
db.commit()
except IntegrityError:
db.rollback()
raise _duplicate() from None
db.refresh(project)
return project
def delete_project(db: Session, user_id: int, project_id: int) -> bool:
"""Delete a project; its clips stay and move to "no project"."""
# Bump versions so open editors holding the old project notice the change
db.execute(
update(Clip)
.where(Clip.user_id == user_id, Clip.project_id == project_id)
.values(project_id=None, version=Clip.version + 1)
.execution_options(synchronize_session=False)
)
result = db.execute(delete(Project).where(Project.id == project_id, Project.user_id == user_id))
if result.rowcount == 0:
db.rollback()
return False
db.commit()
return True