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:
@@ -0,0 +1,121 @@
|
||||
"""Тесты блока «Отметки / Автоматически создано» в детализации письма.
|
||||
|
||||
Запуск: .venv/bin/python tests/test_email_entities_ui.py
|
||||
|
||||
Читается реальный архив (read-only), изменения подменяются заглушками —
|
||||
фронтматтер писем и Radicale не затрагиваются.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
os.environ.setdefault("WEBUI_PASSWORD", "test-pass")
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
import webui.app as app_module # noqa: E402
|
||||
from webui import db as dbmod # noqa: E402
|
||||
|
||||
EXAMPLE = "INBOX/2026/10/17425/email.md"
|
||||
|
||||
|
||||
def _client() -> TestClient:
|
||||
c = TestClient(app_module.app)
|
||||
assert c.post("/login", data={"password": "test-pass"}, follow_redirects=False).status_code == 303
|
||||
return c
|
||||
|
||||
|
||||
def _example_exists() -> bool:
|
||||
return (dbmod.EMAIL_ROOT / EXAMPLE).is_file()
|
||||
|
||||
|
||||
def test_detail_shows_all_marks():
|
||||
if not _example_exists():
|
||||
print(" (эталонное письмо отсутствует — пропуск)")
|
||||
return
|
||||
c = _client()
|
||||
html = c.get("/emails", params={"path": EXAMPLE}).text
|
||||
assert 'id="email-ents"' in html
|
||||
assert "Отметки" in html
|
||||
assert 'class="tag' in html and ">meeting<" in html and ">task<" in html
|
||||
assert "2026-11-06 11:00" in html
|
||||
assert "почему так размечено" in html
|
||||
|
||||
|
||||
def test_detail_fragment_contains_block():
|
||||
if not _example_exists():
|
||||
return
|
||||
c = _client()
|
||||
html = c.get(f"/emails/{EXAMPLE}", headers={"HX-Request": "true"}).text
|
||||
assert 'id="email-ents"' in html
|
||||
assert "meeting" in html
|
||||
|
||||
|
||||
def test_split_tags_used_in_list():
|
||||
c = _client()
|
||||
rows = c.get("/emails", params={"folder": "INBOX"}).text
|
||||
# в списке письмо не должно показывать один слипшийся чип «meeting,task»
|
||||
assert "meeting,task" not in rows
|
||||
|
||||
|
||||
def test_entity_api_requires_auth():
|
||||
fresh = TestClient(app_module.app)
|
||||
assert fresh.post("/api/email/entity",
|
||||
data={"path": EXAMPLE, "kind": "event", "action": "disable"}).status_code == 401
|
||||
|
||||
|
||||
def test_entity_api_validation():
|
||||
c = _client()
|
||||
r = c.post("/api/email/entity", data={"path": EXAMPLE, "kind": "note", "action": "disable"})
|
||||
assert r.status_code == 400
|
||||
r = c.post("/api/email/entity", data={"path": EXAMPLE, "kind": "event", "action": "drop"})
|
||||
assert r.status_code == 400
|
||||
r = c.post("/api/email/entity", data={"path": "../../etc/passwd", "kind": "event", "action": "enable"})
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
def test_entity_api_calls_entities_and_returns_fragment():
|
||||
real_disable = app_module.entities.disable
|
||||
calls = {}
|
||||
|
||||
def fake_disable(kind, email_file):
|
||||
calls["kind"] = kind
|
||||
calls["file"] = Path(email_file).name
|
||||
return {"ok": True, "uid": "u-1"}
|
||||
|
||||
app_module.entities.disable = fake_disable
|
||||
try:
|
||||
c = _client()
|
||||
r = c.post("/api/email/entity",
|
||||
data={"path": EXAMPLE, "kind": "event", "action": "disable"},
|
||||
headers={"HX-Request": "true"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert calls == {"kind": "event", "file": "email.md"}
|
||||
assert 'id="email-ents"' in r.text
|
||||
# JSON-клиент получает JSON
|
||||
r = c.post("/api/email/entity",
|
||||
data={"path": EXAMPLE, "kind": "task", "action": "disable"})
|
||||
assert r.status_code == 200 and r.json()["ok"] is True
|
||||
finally:
|
||||
app_module.entities.disable = real_disable
|
||||
|
||||
|
||||
def test_entity_api_error_maps_to_502():
|
||||
real_enable = app_module.entities.enable
|
||||
app_module.entities.enable = lambda kind, email_file: {"error": "Radicale недоступен"}
|
||||
try:
|
||||
c = _client()
|
||||
r = c.post("/api/email/entity",
|
||||
data={"path": EXAMPLE, "kind": "event", "action": "enable"})
|
||||
assert r.status_code == 502 and "Radicale" in r.json()["error"]
|
||||
finally:
|
||||
app_module.entities.enable = real_enable
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for name, fn in sorted(globals().items()):
|
||||
if name.startswith("test_") and callable(fn):
|
||||
fn()
|
||||
print("OK", name)
|
||||
print("all email-entities-ui tests passed")
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Тесты связи письма с автосозданными сущностями (webui/entities.py).
|
||||
|
||||
Запуск: .venv/bin/python tests/test_entities.py
|
||||
|
||||
CalDAV подменяется заглушкой (запоминает PUT/GET/DELETE), письмо — временный
|
||||
email.md с frontmatter. Реальные Radicale и архив не затрагиваются.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
os.environ.setdefault("WEBUI_PASSWORD", "test-pass")
|
||||
|
||||
from webui import entities as E # noqa: E402
|
||||
|
||||
# UID строится из относительного пути письма: слаг + короткий хэш
|
||||
UID = E.email_uid("INBOX/2026/10/17425/email.md")
|
||||
|
||||
EMAIL = """---
|
||||
id: 17425
|
||||
folder: INBOX
|
||||
subject: "Обучение ISpring"
|
||||
from: "Рудакова Анна Евгеньевна <a.rudakova@vinogorod.ru>"
|
||||
date: "2026-10-30 11:57+03:00"
|
||||
Message-ID: "<df5d5b4ba279495a899129d47fca9983@vinogorod.ru>"
|
||||
classification: meeting,task
|
||||
classification_reason: приглашение на встречу + поручение обеспечить явку
|
||||
meeting_datetime: "2026-11-06 11:00"
|
||||
---
|
||||
|
||||
Добрый день!
|
||||
|
||||
Дата и время: 6 ноября 2026 года, 11:00.
|
||||
"""
|
||||
|
||||
|
||||
class FakeCalDAV:
|
||||
"""Подмена сетевого слоя entities: словарь ресурсов по (kind, uid)."""
|
||||
|
||||
def __init__(self):
|
||||
self.store: dict[tuple[str, str], str] = {}
|
||||
self.calls: list[tuple[str, str, str]] = []
|
||||
|
||||
# --- подменяемые функции ---
|
||||
def resource_exists(self, kind, uid):
|
||||
return (kind, uid) in self.store
|
||||
|
||||
def put(self, kind, uid, body):
|
||||
self.calls.append(("PUT", kind, uid))
|
||||
self.store[(kind, uid)] = body
|
||||
return {"ok": True, "etag": "E1"}
|
||||
|
||||
def delete(self, kind, uid):
|
||||
self.calls.append(("DELETE", kind, uid))
|
||||
self.store.pop((kind, uid), None)
|
||||
return {"ok": True}
|
||||
|
||||
def cancel_task(self, uid):
|
||||
self.calls.append(("CANCEL", "task", uid))
|
||||
body = self.store.get(("task", uid))
|
||||
if body is None:
|
||||
return {"ok": True, "note": "задачи уже нет"}
|
||||
self.store[("task", uid)] = body.replace("STATUS:NEEDS-ACTION", "STATUS:CANCELLED")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
def install(monkeypatch_target=FakeCalDAV()):
|
||||
"""Подменить сетевые функции entities заглушкой; вернуть заглушку."""
|
||||
fake = monkeypatch_target
|
||||
E.resource_exists = fake.resource_exists
|
||||
E._put = fake.put
|
||||
E._delete_resource = fake.delete
|
||||
E._cancel_task = fake.cancel_task
|
||||
return fake
|
||||
|
||||
|
||||
def make_email(tmp: Path, text: str = EMAIL) -> Path:
|
||||
# относительный путь (и UID ресурса) считаем от временного каталога
|
||||
E.EMAIL_ROOTS = (tmp,)
|
||||
d = tmp / "INBOX" / "2026" / "10" / "17425"
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
path = d / "email.md"
|
||||
path.write_text(text, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
# ─── разбор и frontmatter ────────────────────────────────────────────────────
|
||||
def test_headers_and_uid():
|
||||
headers = E.headers_of(EMAIL)
|
||||
assert headers["classification"] == "meeting,task"
|
||||
assert headers["meeting_datetime"] == "2026-11-06 11:00"
|
||||
# UID считается от относительного пути письма (как в обработчиках)
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
assert E.email_uid(E.rel_path_of(path)) == UID
|
||||
assert E.email_uid("INBOX/2026/10/17425/email.md") == UID
|
||||
assert UID.startswith("inbox-2026-10-17425-email-md-") # слаг в нижнем регистре + хэш
|
||||
# разные подпапки с одинаковым хвостом пути больше не совпадают
|
||||
assert E.email_uid("INBOX/Контрагенты/ИП/2026/04/6/email.md") != E.email_uid("INBOX/2026/04/6/email.md")
|
||||
assert E.meeting_start(headers) == "2026-11-06 11:00"
|
||||
assert E.meeting_start({"meeting_datetime": "не дата"}) is None
|
||||
|
||||
|
||||
def test_update_frontmatter_adds_and_replaces():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
E.update_frontmatter(path, {"entity_event_uid": "u-1", "entity_event_state": "created"})
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert "entity_event_uid: u-1" in text
|
||||
assert "entity_event_state: created" in text
|
||||
E.update_frontmatter(path, {"entity_event_state": "disabled"})
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert text.count("entity_event_state:") == 1
|
||||
assert "entity_event_state: disabled" in text
|
||||
assert "Добрый день!" in text # тело письма не тронуто
|
||||
|
||||
|
||||
# ─── создание сущностей ──────────────────────────────────────────────────────
|
||||
def test_ensure_creates_event_and_task_with_meeting_time():
|
||||
fake = install()
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
ev = E.ensure("event", path)
|
||||
tk = E.ensure("task", path)
|
||||
assert ev.get("ok") and tk.get("ok"), (ev, tk)
|
||||
event_ics = fake.store[("event", UID)]
|
||||
assert "BEGIN:VEVENT" in event_ics
|
||||
assert "DTSTART:20261106T110000" in event_ics # время встречи из письма
|
||||
assert "SUMMARY:Обучение ISpring" in event_ics
|
||||
task_ics = fake.store[("task", UID)]
|
||||
assert "BEGIN:VTODO" in task_ics
|
||||
# DUE пишется в UTC (Radicale отклоняет «плавающее» время в VTODO): 11:00 MSK = 08:00Z
|
||||
assert "DUE:20261106T080000Z" in task_ics
|
||||
headers = E.headers_of(path.read_text(encoding="utf-8"))
|
||||
assert headers["entity_event_state"] == "created"
|
||||
assert headers["entity_task_state"] == "created"
|
||||
|
||||
|
||||
def test_disabled_is_not_recreated():
|
||||
fake = install()
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
E.update_frontmatter(path, {"entity_event_state": "disabled"})
|
||||
res = E.ensure("event", path)
|
||||
assert res.get("skipped") == "disabled"
|
||||
assert ("event", UID) not in fake.store
|
||||
|
||||
|
||||
def test_disable_event_deletes_resource():
|
||||
fake = install()
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
E.ensure("event", path)
|
||||
res = E.disable("event", path)
|
||||
assert res.get("ok"), res
|
||||
assert ("event", UID) not in fake.store
|
||||
assert ("DELETE", "event", UID) in fake.calls
|
||||
headers = E.headers_of(path.read_text(encoding="utf-8"))
|
||||
assert headers["entity_event_state"] == "disabled"
|
||||
|
||||
|
||||
def test_disable_task_cancels_softly():
|
||||
fake = install()
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
E.ensure("task", path)
|
||||
res = E.disable("task", path)
|
||||
assert res.get("ok"), res
|
||||
assert "STATUS:CANCELLED" in fake.store[("task", UID)]
|
||||
headers = E.headers_of(path.read_text(encoding="utf-8"))
|
||||
assert headers["entity_task_state"] == "disabled"
|
||||
|
||||
|
||||
def test_enable_recreates_after_disable():
|
||||
fake = install()
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
E.ensure("event", path)
|
||||
E.disable("event", path)
|
||||
res = E.enable("event", path)
|
||||
assert res.get("ok"), res
|
||||
assert ("event", UID) in fake.store
|
||||
headers = E.headers_of(path.read_text(encoding="utf-8"))
|
||||
assert headers["entity_event_state"] == "created"
|
||||
|
||||
|
||||
def test_task_control_uses_meeting_time():
|
||||
fake = install()
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
res = E.create_task_control(path)
|
||||
assert res.get("ok") and res["due"] == "2026-11-06 11:00"
|
||||
ics = fake.store[("task", UID)]
|
||||
assert "SUMMARY:Контроль: Обучение ISpring" in ics
|
||||
assert "DUE:20261106T080000Z" in ics
|
||||
headers = E.headers_of(path.read_text(encoding="utf-8"))
|
||||
assert headers["entity_task_state"] == "created"
|
||||
|
||||
|
||||
def test_describe_reports_state_and_existence():
|
||||
fake = install()
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_email(Path(t))
|
||||
E.ensure("event", path)
|
||||
state = E.describe(path)
|
||||
assert state["event"]["exists"] is True
|
||||
assert state["event"]["state"] == "created"
|
||||
assert state["task"]["exists"] is False
|
||||
assert state["task"]["uid"] == UID
|
||||
|
||||
|
||||
def test_next_workday_skip_weekend():
|
||||
from datetime import datetime
|
||||
friday = datetime(2026, 10, 30, 15, 0) # пятница
|
||||
assert E.next_workday_1100(friday) == "2026-11-02 11:00" # понедельник
|
||||
saturday = datetime(2026, 10, 31, 15, 0)
|
||||
assert E.next_workday_1100(saturday) == "2026-11-02 11:00"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for name, fn in sorted(globals().items()):
|
||||
if name.startswith("test_") and callable(fn):
|
||||
fn()
|
||||
print("OK", name)
|
||||
print("all entities tests passed")
|
||||
Reference in New Issue
Block a user