feat(tasks): фильтры доски (статус/текст/дата закрытия); превью письма на всю ширину
- tasktracker/board.py: filter_tasks (текст, колонка, диапазон даты закрытия), window_bounds/parse_iso_date, build_board(done_from, done_to, only_column, filters) - tasktracker/fragments.py: панель фильтров .bfilters + сохранение фильтров в переключателе «все / за 2 дня» - /tasks и /api/tasks/board принимают q, status, done_from, done_to - CSS: max-width превью ограничен #contacts-cols (на странице письма .c3 снова тянется на всю ширину) - тесты: фильтры уровня board и HTTP; Purpose в спеке home-tasks - openspec: changes tasks-board-filters, email-preview-full-width
This commit is contained in:
+19
-4
@@ -59,8 +59,22 @@ def _contacts_hint() -> list[str]:
|
||||
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(show_all_done: bool = False, *, q: str = "", status: str = "",
|
||||
done_from: str = "", done_to: str = "") -> dict:
|
||||
"""Доска с фильтрами: текст, колонка (статус), диапазон даты закрытия."""
|
||||
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 "",
|
||||
}
|
||||
start = board_mod.parse_iso_date(filters["done_from"])
|
||||
end = board_mod.parse_iso_date(filters["done_to"])
|
||||
tasks = board_mod.filter_tasks(_tracker.list(limit=1000), query=filters["q"],
|
||||
column=filters["status"], done_from=start, done_to=end)
|
||||
return 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)
|
||||
|
||||
|
||||
def _board_response(request: Request, show_all_done: bool = False, error: str = "", status: int = 200):
|
||||
@@ -74,9 +88,10 @@ def _board_response(request: Request, show_all_done: bool = False, error: str =
|
||||
|
||||
|
||||
@router.get("/api/tasks/board")
|
||||
def tasks_board_json(all_done: int = 0):
|
||||
def tasks_board_json(all_done: int = 0, q: str = "", status: str = "",
|
||||
done_from: str = "", done_to: str = ""):
|
||||
"""JSON доски: колонки → задачи (для будущих клиентов)."""
|
||||
return _board(bool(all_done))
|
||||
return _board(bool(all_done), q=q, status=status, done_from=done_from, done_to=done_to)
|
||||
|
||||
|
||||
# --- чтение ---
|
||||
|
||||
+74
-5
@@ -156,6 +156,63 @@ def in_done_window(task: dict[str, Any], today: date | None = None) -> bool:
|
||||
return start <= moment <= end
|
||||
|
||||
|
||||
def window_bounds(done_from: date | None = None, done_to: date | None = None,
|
||||
today: date | None = None) -> tuple[date, date]:
|
||||
"""Границы окна «Выполнено»: явный диапазон дат или прошлый рабочий день — сегодня.
|
||||
|
||||
Явный диапазон нужен фильтру на доске: владелец ищет закрытые задачи по
|
||||
дате закрытия, не ограничиваясь двумя днями.
|
||||
"""
|
||||
start, end = done_window(today)
|
||||
return (done_from or start, done_to or end)
|
||||
|
||||
|
||||
def parse_iso_date(raw: str | None) -> date | None:
|
||||
"""'2026-11-01' → date; пустое или битое значение → None."""
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def filter_tasks(tasks: list[dict[str, Any]], *, query: str = "", column: str = "",
|
||||
done_from: date | None = None, done_to: date | None = None,
|
||||
today: date | None = None) -> list[dict[str, Any]]:
|
||||
"""Отбор задач для доски: текст, колонка (статус), диапазон даты закрытия.
|
||||
|
||||
Диапазон применяется только к задачам колонки «Выполнено»: для активных
|
||||
задач дата закрытия не существует.
|
||||
"""
|
||||
now = today or date.today()
|
||||
needle = (query or "").strip().casefold()
|
||||
start, end = window_bounds(done_from, done_to, now)
|
||||
result: list[dict[str, Any]] = []
|
||||
for task in tasks:
|
||||
if task.get("deleted"):
|
||||
continue
|
||||
task_column = column_of(task)
|
||||
if column and task_column != column:
|
||||
continue
|
||||
if needle:
|
||||
haystack = " ".join([
|
||||
str(task.get("summary") or ""),
|
||||
str(task.get("description") or ""),
|
||||
str(task.get("from_value") or ""),
|
||||
" ".join(str(tag) for tag in task.get("tags") or []),
|
||||
]).casefold()
|
||||
if needle not in haystack:
|
||||
continue
|
||||
if task_column == "done" and (done_from or done_to):
|
||||
moment = done_date(task)
|
||||
if moment is None or not (start <= moment <= end):
|
||||
continue
|
||||
result.append(task)
|
||||
return result
|
||||
|
||||
|
||||
def is_overdue(task: dict[str, Any], today: date | None = None) -> bool:
|
||||
due = due_date(task)
|
||||
return bool(due and due < (today or date.today()))
|
||||
@@ -183,27 +240,39 @@ def sort_tasks(tasks: list[dict[str, Any]], today: date | None = None) -> list[d
|
||||
|
||||
# ─── доска ──────────────────────────────────────────────────────────────────
|
||||
def build_board(tasks: list[dict[str, Any]], today: date | None = None,
|
||||
show_all_done: bool = False) -> dict[str, Any]:
|
||||
"""Разложить задачи по колонкам. Возвращает структуру для фрагментов и JSON."""
|
||||
show_all_done: bool = False, done_from: date | None = None,
|
||||
done_to: date | None = None, only_column: str | None = None,
|
||||
filters: dict[str, str] | None = None) -> dict[str, Any]:
|
||||
"""Разложить задачи по колонкам. Возвращает структуру для фрагментов и JSON.
|
||||
|
||||
done_from/done_to — явный диапазон даты закрытия (вместо окна «2 дня»);
|
||||
only_column — показать одну колонку (фильтр по статусу).
|
||||
"""
|
||||
now = today or date.today()
|
||||
start, end = window_bounds(done_from, done_to, now)
|
||||
buckets: dict[str, list[dict[str, Any]]] = {key: [] for key in COLUMN_KEYS}
|
||||
for task in tasks:
|
||||
if task.get("deleted"):
|
||||
continue
|
||||
column = column_of(task)
|
||||
if column == "done" and not show_all_done and not in_done_window(task, now):
|
||||
continue
|
||||
if column == "done" and not show_all_done:
|
||||
moment = done_date(task)
|
||||
if moment is None or not (start <= moment <= end):
|
||||
continue
|
||||
buckets[column].append({**task, "column": column, "overdue": is_overdue(task, now)})
|
||||
|
||||
columns = []
|
||||
for key, title in COLUMNS:
|
||||
if only_column and key != only_column:
|
||||
continue
|
||||
items = sort_tasks(buckets[key], now)
|
||||
columns.append({"key": key, "title": title, "count": len(items), "tasks": items})
|
||||
start, end = done_window(now)
|
||||
return {
|
||||
"columns": columns,
|
||||
"show_all_done": show_all_done,
|
||||
"only_column": only_column or "",
|
||||
"done_window": {"from": start.isoformat(), "to": end.isoformat()},
|
||||
"filters": filters or {"q": "", "status": "", "done_from": "", "done_to": ""},
|
||||
"total": sum(c["count"] for c in columns),
|
||||
}
|
||||
|
||||
|
||||
@@ -174,7 +174,8 @@ def board_card(task: dict[str, Any]) -> str:
|
||||
+ f'<div class="cbtns">{buttons}</div></div>')
|
||||
|
||||
|
||||
def board_column(col: dict[str, Any], show_all_done: bool = False) -> str:
|
||||
def board_column(col: dict[str, Any], show_all_done: bool = False,
|
||||
filters: dict[str, str] | None = None) -> str:
|
||||
'''Колонка: шапка со счётчиком (+ переключатель «все выполненные») и карточки.'''
|
||||
key = col.get("key", "")
|
||||
cards = "".join(board_card(t) for t in col.get("tasks") or [])
|
||||
@@ -183,7 +184,7 @@ def board_column(col: dict[str, Any], show_all_done: bool = False) -> str:
|
||||
if key == "done":
|
||||
label = "за 2 дня" if show_all_done else "все"
|
||||
target = 0 if show_all_done else 1
|
||||
toggle = (f'<button class="dtoggle" hx-get="/tasks?all_done={target}"'
|
||||
toggle = (f'<button class="dtoggle" hx-get="/tasks{_qs(filters, all_done=target)}"'
|
||||
" hx-target='#board' hx-swap='outerHTML'>" + label + "</button>")
|
||||
return (f'<div class="tcol" data-column="{key}">'
|
||||
f'<div class="cchead"><span>{_esc(col.get("title", key))}</span>'
|
||||
@@ -191,6 +192,39 @@ def board_column(col: dict[str, Any], show_all_done: bool = False) -> str:
|
||||
f'<div class="cbody-col">{body}</div></div>')
|
||||
|
||||
|
||||
def _qs(filters: dict[str, str] | None, **overrides: Any) -> str:
|
||||
"""Query-string из текущих фильтров доски (+ переопределения), без пустых."""
|
||||
merged: dict[str, Any] = {**(filters or {}), **overrides}
|
||||
parts = [f"{key}={quote(str(value), safe='')}"
|
||||
for key, value in merged.items() if value not in (None, "", 0, "0", False)]
|
||||
return ("?" + "&".join(parts)) if parts else ""
|
||||
|
||||
|
||||
def filter_bar(board_data: dict[str, Any]) -> str:
|
||||
"""Панель фильтров доски: текст, статус (колонка), диапазон даты закрытия."""
|
||||
from tasktracker.board import COLUMNS
|
||||
|
||||
filters = board_data.get("filters") or {}
|
||||
status = filters.get("status") or ""
|
||||
options = ['<option value="">все статусы</option>']
|
||||
for key, title in COLUMNS:
|
||||
selected = " selected" if key == status else ""
|
||||
options.append(f'<option value="{key}"{selected}>{_esc(title)}</option>')
|
||||
return (
|
||||
'<form class="bfilters" hx-get="/tasks" hx-target="#board" hx-swap="outerHTML"'
|
||||
' hx-trigger="input changed delay:400ms, search, submit" hx-push-url="true">'
|
||||
f'<input type="search" name="q" value="{_esc(filters.get("q", ""))}"'
|
||||
' placeholder="Поиск по задачам…">'
|
||||
f'<select name="status">{"".join(options)}</select>'
|
||||
'<label class="bdate">закрыта с'
|
||||
f' <input type="date" name="done_from" value="{_esc(filters.get("done_from", ""))}"></label>'
|
||||
'<label class="bdate">по'
|
||||
f' <input type="date" name="done_to" value="{_esc(filters.get("done_to", ""))}"></label>'
|
||||
f'<a class="breset" href="/tasks">сбросить</a>'
|
||||
"</form>"
|
||||
)
|
||||
|
||||
|
||||
def object_chips() -> str:
|
||||
'''Ряд чипов объектов: клик включает/выключает тег (Alpine).'''
|
||||
from tasktracker.board import OBJECT_TAGS
|
||||
@@ -224,7 +258,10 @@ def quick_form(contacts: list[str] | None = None, error: str = "") -> str:
|
||||
|
||||
def board_html(board_data: dict[str, Any], contacts: list[str] | None = None,
|
||||
error: str = "") -> str:
|
||||
'''Вся доска (HTMX-корень #board): форма быстрого создания + пять колонок.'''
|
||||
'''Вся доска (HTMX-корень #board): фильтры + форма быстрого создания + колонки.'''
|
||||
show_all = bool(board_data.get("show_all_done"))
|
||||
columns = "".join(board_column(c, show_all) for c in board_data.get("columns") or [])
|
||||
return f'<div id="board">{quick_form(contacts, error)}<div class="board">{columns}</div></div>'
|
||||
filters = board_data.get("filters") or {}
|
||||
columns = "".join(board_column(c, show_all, filters)
|
||||
for c in board_data.get("columns") or [])
|
||||
return (f'<div id="board">{filter_bar(board_data)}{quick_form(contacts, error)}'
|
||||
f'<div class="board">{columns}</div></div>')
|
||||
|
||||
Reference in New Issue
Block a user