feat(contacts): слой данных контактов + миграция ФИО (разделение на части)
- webui/contacts.py: чтение contacts.json с кэшем по mtime, фильтрация (регистр, «ё», телефон по цифрам, общий поиск по всем полям), алфавит, сортировка, автодополнение; правка поля под flock (перечитывание файла, manual_fields, atomic write через os.replace, пересборка by_email и index.json) + немедленный push vCard в CardDAV (If-Match), при отказе — caldav.dirty; vCard N собирается из last/first/middle. - scripts/contacts_split_names.py: одноразовая миграция full_name → last_name/first_name/middle_name на qwen3:8b-nothink с проверкой ответа по исходным словам, full_name_raw, бэкап contacts.json.bak-split-<ts>, идемпотентность, отчёт docs/contacts-split-review.md. - Прогон на реальной базе: 195 из 206 разобрано, 11 в отчёт (названия компаний/служб, «Королевский В.Д.», «А.А. Зайцев»), by_email пересобран. - tests/test_contacts.py: 17 тестов (фильтры, алфавит, валидация, правка, конкурентная запись, dirty при отказе CardDAV, vCard N). - change contacts-page: решения по открытым вопросам (авто-деление ФИО, удаление post-MVP, переиспользование /api/tasks/create).
This commit is contained in:
@@ -0,0 +1,238 @@
|
||||
"""Тесты слоя контактов (webui/contacts.py).
|
||||
|
||||
Запуск: .venv/bin/python tests/test_contacts.py
|
||||
|
||||
База и CardDAV подменяются временным каталогом и заглушкой push_to_caldav —
|
||||
реальная логика фильтрации/правки/записи при этом не меняется.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
os.environ.setdefault("WEBUI_PASSWORD", "test-pass")
|
||||
|
||||
from webui import contacts as C # noqa: E402
|
||||
|
||||
SAMPLE = {
|
||||
"version": 1,
|
||||
"contacts": [
|
||||
{"id": "c1", "email": "a.baulin@nsburo.ru", "full_name": "Баулин Александр Александрович",
|
||||
"last_name": "Баулин", "first_name": "Александр", "middle_name": "Александрович",
|
||||
"company": "БЦ «Лангензипен»", "position": "Информационная безопасность",
|
||||
"phone": "+7 (812) 336 63 74 доб. 3540", "phone_secondary": "+7 921 000-00-01"},
|
||||
{"id": "c2", "email": "a.anischenko@mangotele.com", "full_name": "Анищенко Александр",
|
||||
"last_name": "Анищенко", "first_name": "Александр", "middle_name": "",
|
||||
"company": "MANGO OFFICE", "position": "Менеджер по продажам",
|
||||
"phone": "+7 (985) 720-14-01"},
|
||||
{"id": "c3", "email": "s.ivanov@example.com", "full_name": "Иванов Сергей Петрович",
|
||||
"last_name": "Иванов", "first_name": "Сергей", "middle_name": "Петрович",
|
||||
"company": "ООО Купаж", "position": "Директор", "phone": ""},
|
||||
{"id": "c4", "email": "team@libra.example", "full_name": "Команда Libra Hospitality",
|
||||
"company": "Libra Hospitality"},
|
||||
{"id": "c5", "email": "gone@example.com", "full_name": "Удалённый Контакт",
|
||||
"last_name": "Удалённый", "first_name": "Контакт", "deleted": True},
|
||||
# для проверки «ё»/регистра
|
||||
{"id": "c6", "email": "e.fedorova@example.com", "full_name": "Фёдорова Елена",
|
||||
"last_name": "Фёдорова", "first_name": "Елена", "company": "Ёлки-Палки"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def make_db(tmp: Path) -> Path:
|
||||
path = tmp / "contacts.json"
|
||||
path.write_text(json.dumps(SAMPLE, ensure_ascii=False), encoding="utf-8")
|
||||
(tmp / "index.json").write_text("{}", encoding="utf-8")
|
||||
C._cache.update(key=None, db=None, mtime=0.0)
|
||||
return path
|
||||
|
||||
|
||||
def names(items):
|
||||
return [c["id"] for c in items]
|
||||
|
||||
|
||||
# ─── фильтры ─────────────────────────────────────────────────────────────────
|
||||
def test_visible_hides_deleted():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
db = C.load(make_db(Path(t)))
|
||||
assert "c5" not in names(C.visible(db))
|
||||
assert len(C.visible(db)) == 5
|
||||
|
||||
|
||||
def test_search_by_field_and_case():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
assert names(C.search(vis, last_name="БАУЛ")) == ["c1"]
|
||||
assert names(C.search(vis, company="лангензипен")) == ["c1"]
|
||||
assert names(C.search(vis, position="менеджер")) == ["c2"]
|
||||
assert names(C.search(vis, first_name="александр")) == ["c1", "c2"]
|
||||
|
||||
|
||||
def test_search_phone_any_format():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
assert names(C.search(vis, phone="79857201401")) == ["c2"]
|
||||
assert names(C.search(vis, phone="+7 (985) 720")) == ["c2"]
|
||||
assert names(C.search(vis, phone="9210000001")) == ["c1"] # второй телефон
|
||||
|
||||
|
||||
def test_search_yo_normalization():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
assert "c6" in names(C.search(vis, q="федорова"))
|
||||
assert "c6" in names(C.search(vis, company="елки"))
|
||||
|
||||
|
||||
def test_global_search_covers_all_fields():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
assert names(C.search(vis, q="купаж")) == ["c3"]
|
||||
assert names(C.search(vis, q="директор")) == ["c3"]
|
||||
assert names(C.search(vis, q="79857201401")) == ["c2"] # телефон в общем поиске
|
||||
|
||||
|
||||
def test_alphabet_counts_and_off_letters():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
alpha = {a["letter"]: a["count"] for a in C.alphabet(vis)}
|
||||
assert alpha["Б"] == 1 and alpha["А"] == 1 and alpha["И"] == 1
|
||||
assert alpha["Ф"] == 1 # Фёдорова
|
||||
assert alpha["Я"] == 0 # нет таких
|
||||
assert alpha["#"] == 0 # «Команда Libra» попадает под «К», а не «#»
|
||||
letters = [a["letter"] for a in C.alphabet(vis)]
|
||||
assert letters[0] == "А" and "#" in letters
|
||||
|
||||
|
||||
def test_letter_filter():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
assert names(C.search(vis, letter="и")) == ["c3"]
|
||||
assert names(C.search(vis, letter="Ф")) == ["c6"]
|
||||
|
||||
|
||||
def test_sorting():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
assert names(C.sort_contacts(vis, "last_name"))[0] == "c2" # Анищенко
|
||||
assert names(C.sort_contacts(vis, "company"))[0] == "c4" # «Libra Hospitality» (лат. раньше кириллицы)
|
||||
assert names(C.sort_contacts(vis, "last_name", reverse=True))[0] == "c6"
|
||||
|
||||
|
||||
def test_filter_options_for_autocomplete():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
vis = C.visible(C.load(make_db(Path(t))))
|
||||
companies = C.filter_options(vis, "company")
|
||||
assert "MANGO OFFICE" in companies and "" not in companies
|
||||
assert companies == sorted(companies)
|
||||
|
||||
|
||||
# ─── правка ──────────────────────────────────────────────────────────────────
|
||||
def test_validate_field():
|
||||
assert C.validate_field("email", "не-почта")
|
||||
assert C.validate_field("email", "a@b.ru") is None
|
||||
assert C.validate_field("phone", "abc")
|
||||
assert C.validate_field("phone", "+7 (812) 336 63 74 доб. 3540") is None
|
||||
assert C.validate_field("id", "x") # нередактируемое поле
|
||||
assert C.validate_field("company", "я" * 301)
|
||||
|
||||
|
||||
def test_update_field_writes_and_marks_manual(monkeypatch=None):
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_db(Path(t))
|
||||
pushed = {}
|
||||
C.push_to_caldav = lambda contact: (pushed.update(contact=dict(contact)) or {"etag": "E1"})
|
||||
try:
|
||||
res = C.update_field("c3", "phone", "+7 999 111-22-33", path=path)
|
||||
assert res.get("ok"), res
|
||||
assert res["caldav"]["etag"] == "E1"
|
||||
db = json.loads(path.read_text(encoding="utf-8"))
|
||||
contact = [c for c in db["contacts"] if c["id"] == "c3"][0]
|
||||
assert contact["phone"] == "+7 999 111-22-33"
|
||||
assert "phone" in contact["manual_fields"]
|
||||
assert contact["caldav"]["etag"] == "E1"
|
||||
assert "phone" not in (contact.get("caldav") or {}).get("dirty", [])
|
||||
# by_email пересобран и валиден
|
||||
assert all(db["by_email"][(c.get("email") or "").lower()] == i
|
||||
for i, c in enumerate(db["contacts"]))
|
||||
finally:
|
||||
C.push_to_caldav = _orig_push
|
||||
|
||||
|
||||
def test_update_field_rebuilds_full_name():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_db(Path(t))
|
||||
try:
|
||||
res = C.update_field("c2", "middle_name", "Иванович", path=path, push=False)
|
||||
assert res["ok"] and res["full_name"] == "Анищенко Александр Иванович"
|
||||
finally:
|
||||
C.push_to_caldav = _orig_push
|
||||
|
||||
|
||||
def test_update_field_invalid_value_does_not_touch_file():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_db(Path(t))
|
||||
before = path.read_text(encoding="utf-8")
|
||||
res = C.update_field("c1", "email", "не-почта", path=path)
|
||||
assert "error" in res
|
||||
assert path.read_text(encoding="utf-8") == before
|
||||
|
||||
|
||||
def test_update_field_unknown_contact():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_db(Path(t))
|
||||
res = C.update_field("nope", "phone", "+7 000", path=path)
|
||||
assert "error" in res
|
||||
|
||||
|
||||
def test_push_failure_marks_dirty():
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_db(Path(t))
|
||||
C.push_to_caldav = lambda contact: {"error": "Radicale недоступен"}
|
||||
try:
|
||||
res = C.update_field("c1", "company", "Новая компания", path=path)
|
||||
assert res["ok"] and res["caldav"]["dirty"] is True
|
||||
db = json.loads(path.read_text(encoding="utf-8"))
|
||||
contact = [c for c in db["contacts"] if c["id"] == "c1"][0]
|
||||
assert contact["caldav"]["dirty"] is True
|
||||
assert contact["company"] == "Новая компания"
|
||||
finally:
|
||||
C.push_to_caldav = _orig_push
|
||||
|
||||
|
||||
def test_concurrent_write_keeps_external_change():
|
||||
"""Экстрактор записал файл между чтением и правкой — не теряем его контакт."""
|
||||
with tempfile.TemporaryDirectory() as t:
|
||||
path = make_db(Path(t))
|
||||
db = json.loads(path.read_text(encoding="utf-8"))
|
||||
db["contacts"].append({"id": "c99", "email": "new@example.com",
|
||||
"full_name": "Новый Контакт", "last_name": "Новый",
|
||||
"first_name": "Контакт"})
|
||||
path.write_text(json.dumps(db, ensure_ascii=False), encoding="utf-8")
|
||||
try:
|
||||
res = C.update_field("c3", "phone", "+7 900 000-00-00", path=path, push=False)
|
||||
assert res["ok"]
|
||||
after = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert "c99" in [c["id"] for c in after["contacts"]]
|
||||
finally:
|
||||
C.push_to_caldav = _orig_push
|
||||
|
||||
|
||||
def test_vcard_uses_explicit_name_parts():
|
||||
vcard = C.to_vcard(SAMPLE["contacts"][0])
|
||||
assert "N:Баулин;Александр;Александрович;;" in vcard
|
||||
assert "FN:Баулин Александр Александрович" in vcard
|
||||
vcard2 = C.to_vcard(SAMPLE["contacts"][3]) # без частей — разбор по словам
|
||||
assert "N:Hospitality;Команда;Libra;;" in vcard2
|
||||
|
||||
|
||||
_orig_push = C.push_to_caldav
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for name, fn in sorted(globals().items()):
|
||||
if name.startswith("test_") and callable(fn):
|
||||
fn()
|
||||
print("OK", name)
|
||||
print("all contacts tests passed")
|
||||
Reference in New Issue
Block a user