feat(entities): метки классификации в детализации письма + автосозданные событие/задача
- db.split_tags(): метки делятся по запятой и пробелу (был один чип «meeting,task») - webui/entities.py: связь письмо↔сущность в frontmatter (entity_<kind>_uid/state), ensure/disable/enable/create_task_control; disable event = DELETE VEVENT, disable task = STATUS:CANCELLED+X-DELETED; task-control только по кнопке - блок «Отметки» + «Автоматически создано» в детализации, роут POST /api/email/entity - handlers: общий UID и ICS-билдеры, запись entity_*, пропуск state: disabled, --backfill --days/--limit, dry-run больше не пишет в Radicale - fix: UID ресурса теперь уникален (транслит-слаг + sha1[:8]) — кириллица выпадала из регулярки, письма из разных подпапок затирали один ресурс (1121 письмо с task/meeting, 554 handled_*, в Radicale 50 задач и 52 события) - fix: DUE в VTODO пишется в UTC — Radicale отклонял плавающее время (400) - tests: test_entities.py 10/10, test_email_entities_ui.py 7/7
This commit is contained in:
+77
-6
@@ -27,7 +27,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Redirect
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.templating import Jinja2Templates
|
||||
|
||||
from . import ai, contacts, db, metrics, move, radicale
|
||||
from . import ai, contacts, db, entities, metrics, move, radicale
|
||||
from tasktracker.api import router as tasktracker_router
|
||||
|
||||
ROOT = Path(__file__).parent
|
||||
@@ -254,7 +254,7 @@ def emails(request: Request, _: AuthDep, folder: str = "INBOX", path: str | None
|
||||
# обогащаем классификацией (тэги) из кэша
|
||||
cls_map = {p: c for p, c in db.classified_paths_cache()}
|
||||
for r in rows:
|
||||
r["tags"] = [t for t in (cls_map.get(r["path"], "") or "").split() if t]
|
||||
r["tags"] = db.split_tags(cls_map.get(r["path"], ""))
|
||||
if q.strip():
|
||||
metrics.observe_search(time.monotonic() - t0)
|
||||
current = db.get_email(path) if path else None
|
||||
@@ -266,19 +266,42 @@ def emails(request: Request, _: AuthDep, folder: str = "INBOX", path: str | None
|
||||
"current": current, "current_path": path, "is_search": is_search,
|
||||
"page": "emails",
|
||||
}
|
||||
if current:
|
||||
ctx.update(_email_entities(current))
|
||||
if is_htmx(request):
|
||||
return fragment(request, "partials/emails_content.html", ctx)
|
||||
return render(request, "emails.html", ctx)
|
||||
|
||||
|
||||
def _email_entities(email: dict) -> dict:
|
||||
"""Отметки классификации и состояние автосозданных сущностей для детализации."""
|
||||
meta = email.get("meta") or {}
|
||||
state = {"event": {"uid": "", "state": "", "exists": False},
|
||||
"task": {"uid": "", "state": "", "exists": False}}
|
||||
rel = email.get("path") or ""
|
||||
email_md = db.EMAIL_ROOT / rel if rel else None
|
||||
if email_md is not None and email_md.is_file():
|
||||
try:
|
||||
state = entities.describe(email_md)
|
||||
except Exception: # noqa: BLE001 — Radicale недоступен: показываем только метки
|
||||
pass
|
||||
return {
|
||||
"tags": db.split_tags(meta.get("classification")),
|
||||
"reason": meta.get("classification_reason") or "",
|
||||
"meeting_at": meta.get("meeting_datetime") or "",
|
||||
"ents": state,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/emails/{relpath:path}", response_class=HTMLResponse)
|
||||
def email_detail(request: Request, relpath: str, _: AuthDep):
|
||||
"""Деталка письма как htmx-фрагмент (для превью-панели)."""
|
||||
em = db.get_email(relpath)
|
||||
if em is None:
|
||||
raise HTTPException(status_code=404)
|
||||
extra = _email_entities(em)
|
||||
if is_htmx(request):
|
||||
ctx = {"current": em, "current_path": relpath, "folders": db.list_folders()}
|
||||
ctx = {"current": em, "current_path": relpath, "folders": db.list_folders(), **extra}
|
||||
return fragment(request, "partials/email_detail.html", ctx)
|
||||
# полная страница (прямой переход)
|
||||
folders = db.list_folders()
|
||||
@@ -287,11 +310,11 @@ def email_detail(request: Request, relpath: str, _: AuthDep):
|
||||
rows = db.list_folder(folder, limit=100)
|
||||
cls_map = {p: c for p, c in db.classified_paths_cache()}
|
||||
for r in rows:
|
||||
r["tags"] = [t for t in (cls_map.get(r["path"], "") or "").split() if t]
|
||||
r["tags"] = db.split_tags(cls_map.get(r["path"], ""))
|
||||
return render(request, "emails.html", {
|
||||
"folders": folders, "folder": folder, "rows": rows, "q": "",
|
||||
"current": em, "current_path": relpath, "is_search": False,
|
||||
"page": "emails",
|
||||
"page": "emails", **extra,
|
||||
})
|
||||
|
||||
|
||||
@@ -322,7 +345,7 @@ def search_page(request: Request, _: AuthDep, q: str = "", folder: str = "",
|
||||
metrics.observe_search(__import__("time").monotonic() - t0)
|
||||
cls_map = {p: c for p, c in db.classified_paths_cache()}
|
||||
for r in rows:
|
||||
r["tags"] = [t for t in (cls_map.get(r["path"], "") or "").split() if t]
|
||||
r["tags"] = db.split_tags(cls_map.get(r["path"], ""))
|
||||
ctx = {"rows": rows, "q": q, "folder": folder, "tag": tag,
|
||||
"df": df, "dt": dt, "att": att, "body": body,
|
||||
"body_fallback": body_fallback, "page": "search"}
|
||||
@@ -496,6 +519,54 @@ async def contact_field(contact_id: str, request: Request, _: AuthDep):
|
||||
return out
|
||||
|
||||
|
||||
# --- Автосозданные сущности письма (событие/задача) ---
|
||||
@app.post("/api/email/entity")
|
||||
async def email_entity(request: Request, _: AuthDep):
|
||||
"""Создать / отключить / включить автосозданную сущность письма."""
|
||||
ctype = request.headers.get("content-type", "")
|
||||
if "application/json" in ctype:
|
||||
try:
|
||||
data = await request.json()
|
||||
except Exception:
|
||||
raise HTTPException(status_code=400, detail="invalid JSON") from None
|
||||
else:
|
||||
data = dict(await request.form())
|
||||
|
||||
rel = str(data.get("path") or "").strip().lstrip("/")
|
||||
kind = str(data.get("kind") or "")
|
||||
action = str(data.get("action") or "")
|
||||
control = str(data.get("control") or "") in ("1", "true", "on", "yes")
|
||||
if kind not in entities.KINDS:
|
||||
return JSONResponse({"error": "kind должен быть event или task"}, status_code=400)
|
||||
if action not in ("create", "disable", "enable"):
|
||||
return JSONResponse({"error": "action должен быть create, disable или enable"},
|
||||
status_code=400)
|
||||
|
||||
email_md = (db.EMAIL_ROOT / rel).resolve()
|
||||
if not str(email_md).startswith(str(db.EMAIL_ROOT_REAL)) or not email_md.is_file():
|
||||
return JSONResponse({"error": f"письмо не найдено: {rel}"}, status_code=404)
|
||||
|
||||
if action == "disable":
|
||||
result = entities.disable(kind, email_md)
|
||||
elif action == "enable":
|
||||
result = entities.enable(kind, email_md)
|
||||
elif control and kind == "task":
|
||||
result = entities.create_task_control(email_md)
|
||||
else:
|
||||
result = entities.ensure(kind, email_md, force=True)
|
||||
|
||||
if result.get("error"):
|
||||
return JSONResponse({"error": result["error"]}, status_code=502)
|
||||
|
||||
if is_htmx(request):
|
||||
email = db.get_email(rel)
|
||||
if email is None:
|
||||
raise HTTPException(status_code=404, detail="email not found")
|
||||
ctx = {"current": email, "current_path": rel, **_email_entities(email)}
|
||||
return fragment(request, "partials/email_entities.html", ctx)
|
||||
return {"ok": True, **{k: v for k, v in result.items() if k != "ok"}}
|
||||
|
||||
|
||||
# --- Календарь ---
|
||||
@app.get("/api/calendar")
|
||||
def calendar(request: Request, _: AuthDep, year: int = 0, month: int = 0):
|
||||
|
||||
Reference in New Issue
Block a user