Files
email-assistant/tasktracker/api.py
T
hermes c95213e172
wiki-sync / Publish docs/wiki to Gitea wiki (push) Successful in 28s
feat(tasks): ответственный, пресеты, свимлейны, утренний дайджест на почту
- radicale: X-RESPONSIBLE/-NAME/-EMAIL, set_responsible; починена правка задач,
  у которых имя файла ≠ UID (кэш перечитывается при 404, _resource_url помнит href)
- board: просрочка после 18:00 МСК, пресеты resp=, группировка по ответственному
- tasktracker: правило «вне бэклога только с ответственным», set_responsible
- UI доски: бейдж/поповер ответственного, пресеты, переключатель «По ответственным»
- контакты: is_employee (звёздочка, пресет «Сотрудники»), 9 сотрудников отмечены,
  Жигульский/Ферулёв/Чикуров созданы заготовками
- scripts/backfill_responsible.py: владелец проставлен 73 задачам
- scripts/tasks_digest.py + cron 08:00 daily: письмо с разделами, himalaya -a hermes
- tests: test_task_responsible.py (15), test_tasks_digest.py (6)
- openspec changes task-responsible и tasks-digest заархивированы
2026-11-14 01:22:53 +00:00

336 lines
14 KiB
Python

"""api.py — HTTP-слой модуля задач (FastAPI APIRouter).
Монтируется в webui.app одной строкой:
from tasktracker.api import router as tasktracker_router
app.include_router(tasktracker_router)
Авторизация: глобальный middleware webui.app требует cookie `webui_auth` для
всех путей вне /login и /static, включая /api/* (без cookie — 401), поэтому
собственных проверок в роутере нет.
Ответы: HTMX-запросы (HX-Request: true) получают фрагмент карточки задач,
обычные HTTP-клиенты — JSON.
"""
from __future__ import annotations
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
from tasktracker import TaskTracker, board as board_mod, fragments
router = APIRouter()
_tracker = TaskTracker()
def is_htmx(request: Request) -> bool:
return request.headers.get("hx-request", "").lower() == "true"
def _card() -> HTMLResponse:
"""Свежий фрагмент карточки задач (HTML) — только незакрытые."""
return HTMLResponse(fragments.tasks_card(_tracker.list_active(limit=1000)))
def _error(request: Request, message: str, status: int = 400):
if is_htmx(request):
# доска: ошибку показываем ПЛАШКОЙ в форме (htmx не свапает не-2xx ответы,
# иначе нажатие кнопки выглядит как «ничего не произошло»)
if request.headers.get("hx-target") == "#board":
return _board_response(request, error=message)
return HTMLResponse(fragments.tasks_card(_tracker.list_active(limit=1000),
error=message), status_code=status)
return JSONResponse({"error": message}, status_code=status)
# --- доска (канбан) ---
def _contacts_hint() -> list[str]:
"""Подсказки для поля «от кого»: ФИО и компании из базы контактов."""
try:
from webui import contacts as contacts_mod
hints: list[str] = []
for contact in contacts_mod.visible():
for value in (contacts_mod.display_name(contact),
contact.get("company", ""), contact.get("email", "")):
if value and value not in hints:
hints.append(str(value))
return hints[:500]
except Exception: # noqa: BLE001 — база контактов недоступна: форма без подсказок
return []
def _board(show_all_done: bool = False, *, q: str = "", status: str = "",
done_from: str = "", done_to: str = "", resp: str = "",
view: str = "") -> dict:
"""Доска с фильтрами: текст, колонка, дата закрытия, ответственный, вид."""
from tasktracker import people
filters = {
"q": (q or "").strip(),
"status": status if status in board_mod.COLUMN_KEYS else "",
"done_from": done_from if board_mod.parse_iso_date(done_from) else "",
"done_to": done_to if board_mod.parse_iso_date(done_to) else "",
"resp": resp if resp in dict(board_mod.RESP_PRESETS) else "",
"view": "person" if view == "person" else "",
}
start = board_mod.parse_iso_date(filters["done_from"])
end = board_mod.parse_iso_date(filters["done_to"])
owner = people.owner_contact() or {}
owner_email = people.owner_email()
owner_id = (owner.get("id") or "").strip()
employees = [{"id": c.get("id"), "name": c.get("full_name")}
for c in people.employees()]
tasks = board_mod.filter_tasks(_tracker.list(limit=1000), query=filters["q"],
column=filters["status"], done_from=start, done_to=end,
resp=filters["resp"], owner_email=owner_email,
owner_id=owner_id)
board = board_mod.build_board(tasks, show_all_done=show_all_done, done_from=start,
done_to=end, only_column=filters["status"] or None,
filters=filters, view=filters["view"],
people=employees, owner_email=owner_email,
owner_id=owner_id)
board["people"] = employees
board["owner"] = {"id": owner_id, "email": owner_email,
"name": (owner.get("full_name") or people.owner_name())}
return board
def _board_response(request: Request, show_all_done: bool = False, error: str = "",
status: int = 200, filters: dict[str, str] | None = None):
f = filters or {}
data = _board(show_all_done, q=f.get("q", ""), status=f.get("status", ""),
done_from=f.get("done_from", ""), done_to=f.get("done_to", ""),
resp=f.get("resp", ""), view=f.get("view", ""))
if is_htmx(request):
return HTMLResponse(fragments.board_html(data, _contacts_hint(), error),
status_code=status)
if error:
return JSONResponse({"error": error}, status_code=status)
return data
@router.get("/api/tasks/board")
def tasks_board_json(all_done: int = 0, q: str = "", status: str = "",
done_from: str = "", done_to: str = "", resp: str = "",
view: str = ""):
"""JSON доски: колонки → задачи (+ группы по ответственным при view=person)."""
return _board(bool(all_done), q=q, status=status, done_from=done_from,
done_to=done_to, resp=resp, view=view)
# --- чтение ---
@router.get("/api/tasks")
def tasks_json(limit: int = 100):
"""JSON-список задач (для будущего API-клиента)."""
return {"tasks": _tracker.list(limit=limit)}
@router.get("/api/task/{uid}")
def task_json(uid: str):
task = _tracker.get(uid)
if task is None:
return JSONResponse({"error": "Task not found"}, status_code=404)
return task
@router.get("/api/tasks/reload", response_class=HTMLResponse)
def tasks_reload():
"""HTMX-фрагмент: вся карточка задач для главной."""
return _card()
@router.get("/api/tasks/new-form", response_class=HTMLResponse)
def tasks_new_form():
"""HTMX-фрагмент: инлайн-форма создания задачи."""
return HTMLResponse(fragments.new_task_form())
# --- запись ---
@router.post("/api/tasks/create")
async def tasks_create(request: Request):
"""Создать VTODO (из письма или произвольного текста)."""
form = dict(await request.form())
summary = str(form.get("subject") or form.get("summary") or "").strip()
if not summary:
# описание обязательно (spec: «Обязательное описание»)
if is_htmx(request) and request.headers.get("hx-target") == "#board":
return _board_response(request, error="Опишите заявку", status=400)
return _error(request, "summary required")
description = str(form.get("body") or "")
sender = str(form.get("from") or "").strip()
if sender:
# «От: …» первой строкой остаётся для совместимости с привязкой к контактам
description = f"От: {sender}\n{description}"
tags = [t.strip() for t in str(form.get("tags") or "").split(",") if t.strip()]
due = str(form.get("due") or "") or None
priority = str(form.get("priority") or "").strip() or None
try:
ok = _tracker.create(summary, description.strip(), due, priority, sender or None, tags)
except ValueError as exc:
return _error(request, str(exc))
if ok.get("error"):
return _error(request, ok["error"])
if is_htmx(request):
if request.headers.get("hx-target") == "#board":
return _board_response(request)
return _card()
return {"ok": True, "uid": ok.get("uid", ""), "etag": ok.get("etag", "")}
@router.post("/api/task/{uid}/toggle")
def task_toggle(uid: str, request: Request):
"""Переключить NEEDS-ACTION ↔ COMPLETED."""
res = _tracker.toggle(uid)
if res.get("error"):
return _error(request, res["error"])
if is_htmx(request):
return _card()
return {"ok": True, "status": res.get("status", "")}
@router.put("/api/task/{uid}/update")
async def task_update(uid: str, request: Request):
"""Обновить SUMMARY и/или DUE задачи (JSON-тело)."""
import json
try:
data = json.loads(await request.body() or b"{}")
except json.JSONDecodeError:
return _error(request, "invalid JSON")
summary = str(data.get("summary") or "")
due = str(data.get("due") or "")
res = _tracker.update(uid, summary, due)
if res.get("error"):
return _error(request, res["error"])
if is_htmx(request):
return _card()
return {"ok": True}
@router.put("/api/task/{uid}/priority")
async def task_priority(uid: str, request: Request):
"""Установить приоритет 1-5 (JSON-тело или query-параметр priority)."""
import json
priority: object = request.query_params.get("priority")
if priority is None:
try:
body = json.loads(await request.body() or b"{}")
except json.JSONDecodeError:
return _error(request, "invalid JSON")
priority = body.get("priority")
try:
res = _tracker.set_priority(uid, priority) # type: ignore[arg-type]
except ValueError as exc:
return _error(request, str(exc))
if res.get("error"):
return _error(request, res["error"])
if is_htmx(request):
return _card()
return {"ok": True, "priority": str(priority)}
@router.delete("/api/task/{uid}")
def task_delete(uid: str, request: Request):
"""Мягкое удаление задачи (STATUS:CANCELLED + X-DELETED)."""
res = _tracker.delete(uid)
if res.get("error"):
return _error(request, res["error"])
if is_htmx(request):
return _card()
return {"ok": True}
@router.post("/api/tasks/{uid}/status")
async def task_status(uid: str, request: Request):
"""Перевести заявку в колонку доски: {"status": "backlog|accepted|in-progress|review|done"}."""
import json
status = request.query_params.get("status")
if status is None:
ctype = request.headers.get("content-type", "")
if "application/json" in ctype:
try:
status = (json.loads(await request.body() or b"{}") or {}).get("status")
except json.JSONDecodeError:
return _error(request, "invalid JSON")
else:
status = dict(await request.form()).get("status")
status = str(status or "").strip().lower()
if status not in board_mod.COLUMN_KEYS:
return _error(request, f"status must be one of {list(board_mod.COLUMN_KEYS)}")
res = _tracker.set_status(uid, status)
if res.get("error"):
reason = res["error"]
code = 409 if "conflict" in reason else (400 if reason == "responsible required" else 502)
return _error(request, reason, status=code)
if is_htmx(request):
return _board_response(request)
return {"ok": True, "status": status}
@router.post("/api/tasks/{uid}/responsible")
async def task_responsible(uid: str, request: Request):
"""Назначить/снять ответственного.
Тело или query: contact_id (id контакта), name, email. Пустой contact_id —
снять (разрешено только в бэклоге).
"""
import json
from tasktracker import people
payload: dict = {}
ctype = request.headers.get("content-type", "")
if "application/json" in ctype:
try:
payload = json.loads(await request.body() or b"{}") or {}
except json.JSONDecodeError:
return _error(request, "invalid JSON")
else:
payload = dict(await request.form())
payload.update({k: v for k, v in request.query_params.items()})
contact_id = str(payload.get("contact_id") or payload.get("responsible") or "").strip()
name = str(payload.get("name") or "").strip()
email = str(payload.get("email") or "").strip()
if contact_id:
contact = people.contact_by_id(contact_id)
if contact is None:
return _error(request, "contact not found")
name = (contact.get("full_name") or name).strip()
email = (contact.get("email") or email).strip()
res = _tracker.set_responsible(uid, contact_id, name, email)
if res.get("error"):
return _error(request, res["error"], status=400)
if is_htmx(request):
return _board_response(request)
return {"ok": True, "responsible": {"id": contact_id, "name": name, "email": email}}
@router.post("/api/tasks/{uid}/tags")
async def task_tags(uid: str, request: Request):
"""Заменить теги объекта: {"tags": "Винный город,Глория"}."""
import json
tags_value = request.query_params.get("tags")
if tags_value is None:
ctype = request.headers.get("content-type", "")
if "application/json" in ctype:
try:
tags_value = (json.loads(await request.body() or b"{}") or {}).get("tags")
except json.JSONDecodeError:
return _error(request, "invalid JSON")
else:
tags_value = dict(await request.form()).get("tags")
if isinstance(tags_value, list):
tags = [str(t).strip() for t in tags_value]
else:
tags = [t.strip() for t in str(tags_value or "").split(",")]
tags = [t for t in tags if t]
res = _tracker.set_tags(uid, tags)
if res.get("error"):
return _error(request, res["error"], status=502)
if is_htmx(request):
return _board_response(request)
return {"ok": True, "tags": tags}