Filtere Paperless-Dokumente nach Zusatzfeldern und öffne die Auswahl als großen Dialog mit Filtern links und Treffern rechts.
Deploy Development / deploy (push) Successful in 43s
Test Suite / pytest-backend (push) Successful in 5m37s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 22s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
StommerandClaude Sonnet 5.5 committed 2026-10-24 21:23:29 +02:00
1 parent 9089d830b3
commit f580fb282d
11 files changed
+386 -13

No files matched your search

+3
View File
@@ -282,6 +282,7 @@ class SearchFilters:
added_from: str = "",
added_to: str = "",
asn: str = "",
custom: str = "",
sort: str = "",
cursor: str = "",
):
@@ -298,6 +299,7 @@ class SearchFilters:
"added_from": added_from,
"added_to": added_to,
"asn": asn,
"custom": custom,
"sort": sort,
"cursor": cursor,
}
@@ -445,6 +447,7 @@ _SEARCH_FLAGS = {
"added_from": "added_range",
"added_to": "added_range",
"asn": "asn",
"custom": "custom_fields",
"sort": "sort",
"cursor": "continuation",
}
+3
View File
@@ -26,6 +26,7 @@ PAPERLESS_CAPABILITIES = {
"document_range": True,
"added_range": True,
"asn": True,
"custom_fields": True,
"sort": True,
"continuation": True,
"result_preview": True,
@@ -52,6 +53,7 @@ IMAP_CAPABILITIES = {
"document_range": False,
"added_range": False,
"asn": False,
"custom_fields": False,
"sort": False,
"continuation": True,
"result_preview": False,
@@ -81,6 +83,7 @@ UNSUPPORTED_SEARCH = (
"added_from",
"added_to",
"asn",
"custom",
"sort",
"cursor",
)
+129 -3
View File
@@ -230,7 +230,103 @@ def _paperless_range(options: dict, prefix: str, field: str, label: str, params:
params[f"{field}__date__lte"] = end
def _paperless_params(query: str, options: dict | None) -> dict:
_CUSTOM_KINDS = {
"string": "text",
"url": "text",
"longtext": "text",
"integer": "number",
"float": "number",
"monetary": "number",
"date": "date",
"boolean": "boolean",
"select": "select",
}
_CUSTOM_OPERATORS = {
"text": {"exact", "icontains", "istartswith", "iendswith"},
"number": {"exact", "gt", "gte", "lt", "lte", "range"},
"date": {"exact", "gt", "gte", "lt", "lte", "range"},
"boolean": {"exact"},
"select": {"exact"},
}
_CUSTOM_LIMIT = 5
def _custom_number(value, label: str):
text = str(value).strip().replace(",", ".")
try:
number = float(text)
except ValueError as exc:
raise unprocessable(f"{label}: Der Wert ist keine Zahl.") from exc
if number != number or number in (float("inf"), float("-inf")):
raise unprocessable(f"{label}: Der Wert ist keine Zahl.")
return int(number) if "." not in text else number
def _custom_value(kind: str, op: str, value, field: dict):
label = field["name"]
if op == "exists":
if not isinstance(value, bool):
raise unprocessable(f"{label}: Gesetzt oder leer ist ungültig.")
return value
if op == "range":
if not isinstance(value, (list, tuple)) or len(value) != 2:
raise unprocessable(f"{label}: Der Bereich braucht Anfang und Ende.")
low, high = (_custom_value(kind, "exact", item, field) for item in value)
if low > high:
raise unprocessable(f"{label}: Der Beginn liegt nach dem Ende.")
return [low, high]
if kind == "text":
text = " ".join(str(value or "").split())
if not text or len(text) > 200:
raise unprocessable(f"{label}: Der Text fehlt oder ist zu lang.")
return text
if kind == "number":
return _custom_number(value, label)
if kind == "date":
day = _paperless_day(value, label)
if not day:
raise unprocessable(f"{label}: Das Datum fehlt.")
return day
if kind == "boolean":
if not isinstance(value, bool):
raise unprocessable(f"{label}: Ja oder Nein ist ungültig.")
return value
allowed = {option["id"] for option in field.get("options") or []}
if str(value) not in allowed:
raise unprocessable(f"{label}: Das ist keine Auswahl dieses Feldes.")
return str(value)
def _paperless_custom_query(raw, fields: list[dict]) -> str | None:
"""Paperless-ngx custom_field_query, built only from fields and operators this instance offers."""
if raw in (None, "", []):
return None
if isinstance(raw, str):
try:
raw = json.loads(raw)
except json.JSONDecodeError as exc:
raise unprocessable("Die Filter der Zusatzfelder sind ungültig.") from exc
if not isinstance(raw, list) or len(raw) > _CUSTOM_LIMIT:
raise unprocessable(f"Es sind höchstens {_CUSTOM_LIMIT} Zusatzfeld-Filter möglich.")
known = {field["id"]: field for field in fields}
atoms = []
for row in raw:
if not isinstance(row, dict):
raise unprocessable("Die Filter der Zusatzfelder sind ungültig.")
field = known.get(str(row.get("field") or ""))
if field is None:
raise unprocessable("Das Zusatzfeld gibt es an diesem Zugang nicht.")
kind = _CUSTOM_KINDS[field["type"]]
op = str(row.get("op") or "")
if op != "exists" and op not in _CUSTOM_OPERATORS[kind]:
raise unprocessable(f"{field['name']}: Diese Bedingung gibt es für den Feldtyp nicht.")
atoms.append([field["name"], op, _custom_value(kind, op, row.get("value"), field)])
if not atoms:
return None
return json.dumps(atoms[0] if len(atoms) == 1 else ["AND", atoms], ensure_ascii=False)
def _paperless_params(query: str, options: dict | None, custom_fields: list[dict] | None = None) -> dict:
"""Paperless-ngx document date is the created field, not the upload or modified time."""
options = options or {}
params = {"page_size": str(PAPERLESS_PAGE_SIZE)}
@@ -268,6 +364,9 @@ def _paperless_params(query: str, options: dict | None) -> dict:
params[_PAPERLESS_TAG_MODES[tag_mode]] = ",".join(tag_ids)
_paperless_range(options, "document", "created", "Dokumentdatum", params)
_paperless_range(options, "added", "added", "Hinzugefügt am", params)
custom = _paperless_custom_query(options.get("custom"), custom_fields or [])
if custom:
params["custom_field_query"] = custom
asn = str(options.get("asn") or "").strip()
if asn:
if not asn.isdigit() or len(asn) > 10:
@@ -316,10 +415,10 @@ def _paperless_row(conn, owner_id: UUID, connector_id: UUID | None):
def paperless_documents(conn, owner_id: UUID, query: str, connector_id: UUID | None = None, options: dict | None = None) -> dict:
row = _paperless_row(conn, owner_id, connector_id)
base = row["settings"]["base_url"].rstrip("/")
params = _paperless_params(query, options)
release_for_external(conn)
payload = _paperless_get(base, row["secret"], "/api/documents/", params)
names = _paperless_lookup(row["id"], base, row["secret"])
params = _paperless_params(query, options, names["custom_fields"])
payload = _paperless_get(base, row["secret"], "/api/documents/", params)
assert_still_owned(conn, row["id"], owner_id)
terms = _search_terms(query, (options or {}).get("title"))
items = []
@@ -372,6 +471,7 @@ def paperless_facets(conn, owner_id: UUID, connector_id: UUID) -> dict:
"document_types": names["document_types"],
"storage_paths": names["storage_paths"],
"tags": names["tags"],
"custom_fields": names["custom_fields"],
"tag_mode": "all",
"tag_modes": list(_PAPERLESS_TAG_MODES),
"modes": list(_PAPERLESS_MODES),
@@ -414,6 +514,7 @@ def _paperless_lookup(connector_id, base: str, token: str) -> dict:
"tags": _paperless_names(base, token, "/api/tags/"),
# An instance without storage paths, or a key that may not read them, still searches.
"storage_paths": _paperless_names_or_none(base, token, "/api/storage_paths/"),
"custom_fields": _paperless_custom_fields(base, token),
}
with _lookup_lock:
if len(_lookup_cache) >= _LOOKUP_LIMIT:
@@ -422,6 +523,31 @@ def _paperless_lookup(connector_id, base: str, token: str) -> dict:
return names
def _paperless_custom_fields(base: str, token: str) -> list[dict]:
"""Custom fields the picker can filter on. Types it cannot query, such as document links, are left out."""
found = []
try:
for page in range(1, 6):
payload = _paperless_get(base, token, "/api/custom_fields/", {"page": str(page), "page_size": "100"})
rows = payload.get("results") or []
for item in rows:
kind = item.get("data_type")
if item.get("id") is None or kind not in _CUSTOM_KINDS:
continue
extra = item.get("extra_data") if isinstance(item.get("extra_data"), dict) else {}
options = [
{"id": str(option["id"]), "name": str(option.get("label") or option["id"])[:200]}
for option in extra.get("select_options") or []
if isinstance(option, dict) and option.get("id") is not None
]
found.append({"id": str(item["id"]), "name": str(item.get("name") or item["id"])[:200], "type": kind, "options": options})
if len(rows) < 100:
break
except Problem:
return []
return found
def _paperless_names_or_none(base: str, token: str, path: str) -> list[dict]:
try:
return _paperless_names(base, token, path)