d9217db2d9
- radicale._unfold(): разворот folding в _parse_vtodo/_parse_vevent
(Radicale складывает строки по 75 байт; UID длиннее обрезался,
POST /api/tasks/{uid}/status уходил на несуществующий ресурс → 502,
а htmx не свапает не-2xx → «нажал →, ничего не произошло»)
- tasktracker.api._error(): для HX-Target #board ошибка показывается
плашкой в форме, а не молчаливым 502
- тест test_parse_vtodo_unfolds_long_uid
254 lines
9.9 KiB
Python
254 lines
9.9 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()))
|
|
|
|
|
|
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(), 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):
|
|
return board_mod.build_board(_tracker.list(limit=1000), show_all_done=show_all_done)
|
|
|
|
|
|
def _board_response(request: Request, show_all_done: bool = False, error: str = "", status: int = 200):
|
|
data = _board(show_all_done)
|
|
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):
|
|
"""JSON доски: колонки → задачи (для будущих клиентов)."""
|
|
return _board(bool(all_done))
|
|
|
|
|
|
# --- чтение ---
|
|
@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"):
|
|
return _error(request, res["error"], status=502 if "conflict" not in res["error"] else 409)
|
|
if is_htmx(request):
|
|
return _board_response(request)
|
|
return {"ok": True, "status": status}
|
|
|
|
|
|
@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}
|