feat(tasks): доска задач (канбан) — 5 колонок, X-STATUS, теги объектов, быстрое создание
- tasktracker/board.py: колонки backlog/accepted/in-progress/review/done,
маппинг X-STATUS ↔ STATUS ↔ COMPLETED, окно «сегодня + прошлый рабочий день»,
сортировка (просрочка → срок → приоритет → новизна), OBJECT_TAGS (6 объектов)
- webui/radicale.py: чтение X-STATUS/X-FROM/CATEGORIES/COMPLETED/LAST-MODIFIED,
fallback «От: …» из DESCRIPTION, set_task_state(), set_tags(),
create_task(from_value=, tags=) пишет X-STATUS:backlog
- tasktracker/fragments.py: карточка (теги, просроченный срок, приоритет, от кого,
дата, кнопки ←/→/✓/↩︎), колонка со счётчиком, форма с чипами объектов и datalist
- роуты: GET /tasks (+HTMX-фрагмент #board), GET /api/tasks/board,
POST /api/tasks/{uid}/status, POST /api/tasks/{uid}/tags, расширенный create
- меню «Задачи», CSS доски; тесты tests/test_tasks_board.py 15/15
- живой прогон на Radicale: все переходы колонок, COMPLETED ставится/снимается,
теги заменяются; change tasks-kanban-board заархивирован (Purpose в main-спеке)
This commit is contained in:
+104
-4
@@ -16,7 +16,7 @@ from __future__ import annotations
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
|
||||
from tasktracker import TaskTracker, fragments
|
||||
from tasktracker import TaskTracker, board as board_mod, fragments
|
||||
|
||||
router = APIRouter()
|
||||
_tracker = TaskTracker()
|
||||
@@ -37,6 +37,43 @@ def _error(request: Request, message: str, status: int = 400):
|
||||
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):
|
||||
@@ -69,20 +106,29 @@ def tasks_new_form():
|
||||
async def tasks_create(request: Request):
|
||||
"""Создать VTODO (из письма или произвольного текста)."""
|
||||
form = dict(await request.form())
|
||||
summary = str(form.get("subject") or form.get("summary") or "Без темы")
|
||||
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 "")
|
||||
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)
|
||||
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", "")}
|
||||
|
||||
@@ -147,3 +193,57 @@ def task_delete(uid: str, request: Request):
|
||||
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}
|
||||
|
||||
Reference in New Issue
Block a user