feat(tasks): ответственный, пресеты, свимлейны, утренний дайджест на почту
wiki-sync / Publish docs/wiki to Gitea wiki (push) Successful in 28s
wiki-sync / Publish docs/wiki to Gitea wiki (push) Successful in 28s
- 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 заархивированы
This commit is contained in:
+26
-1
@@ -84,15 +84,40 @@ class TaskTracker:
|
||||
|
||||
# --- доска (канбан) ---
|
||||
def set_status(self, uid: str, column: str) -> dict[str, Any]:
|
||||
"""Перевести заявку в колонку доски (X-STATUS + STATUS + COMPLETED)."""
|
||||
"""Перевести заявку в колонку доски (X-STATUS + STATUS + COMPLETED).
|
||||
|
||||
Правило: в бэклоге задача может быть без ответственного, в любую другую
|
||||
колонку — только с ответственным.
|
||||
"""
|
||||
from tasktracker import board
|
||||
|
||||
if column not in board.COLUMN_KEYS:
|
||||
return {"error": f"unknown status: {column}"}
|
||||
if column != "backlog":
|
||||
getter = getattr(self.storage, "get_task", None)
|
||||
task = (getter(uid) if getter else None) or {}
|
||||
if task and not (task.get("responsible") or task.get("responsible_name")):
|
||||
return {"error": "responsible required"}
|
||||
state = board.state_for(column)
|
||||
return self.storage.set_task_state(uid, state["x_status"], state["status"],
|
||||
state["completed"])
|
||||
|
||||
def set_responsible(self, uid: str, contact_id: str | None = None,
|
||||
name: str = "", email: str = "") -> dict[str, Any]:
|
||||
"""Назначить ответственного (id контакта + имя и адрес копией).
|
||||
|
||||
Снять ответственного у задачи вне бэклога нельзя: иначе правило
|
||||
«в работу только с ответственным» обходится одним кликом.
|
||||
"""
|
||||
from tasktracker import board
|
||||
|
||||
contact_id = (contact_id or "").strip()
|
||||
if not contact_id:
|
||||
task = self.get(uid) or {}
|
||||
if task and board.column_of(task) != "backlog":
|
||||
return {"error": "ответственного нельзя снять вне бэклога"}
|
||||
return self.storage.set_responsible(uid, contact_id, name, email)
|
||||
|
||||
def set_tags(self, uid: str, tags: list[str] | None) -> dict[str, Any]:
|
||||
"""Заменить теги объектов заявки (CATEGORIES)."""
|
||||
return self.storage.set_tags(uid, list(tags or []))
|
||||
|
||||
+78
-12
@@ -60,25 +60,47 @@ def _contacts_hint() -> list[str]:
|
||||
|
||||
|
||||
def _board(show_all_done: bool = False, *, q: str = "", status: str = "",
|
||||
done_from: str = "", done_to: str = "") -> dict:
|
||||
"""Доска с фильтрами: текст, колонка (статус), диапазон даты закрытия."""
|
||||
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)
|
||||
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)
|
||||
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):
|
||||
data = _board(show_all_done)
|
||||
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)
|
||||
@@ -89,9 +111,11 @@ 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, q: str = "", status: str = "",
|
||||
done_from: str = "", done_to: str = ""):
|
||||
"""JSON доски: колонки → задачи (для будущих клиентов)."""
|
||||
return _board(bool(all_done), q=q, status=status, done_from=done_from, done_to=done_to)
|
||||
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)
|
||||
|
||||
|
||||
# --- чтение ---
|
||||
@@ -235,12 +259,54 @@ async def task_status(uid: str, request: Request):
|
||||
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)
|
||||
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": "Винный город,Глория"}."""
|
||||
|
||||
+157
-21
@@ -180,15 +180,17 @@ def parse_iso_date(raw: str | None) -> date | 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]]:
|
||||
today: date | None = None, resp: str = "",
|
||||
owner_email: str = "", owner_id: str = "",
|
||||
now: datetime | None = None) -> list[dict[str, Any]]:
|
||||
"""Отбор задач для доски: текст, колонка (статус), диапазон даты закрытия.
|
||||
|
||||
Диапазон применяется только к задачам колонки «Выполнено»: для активных
|
||||
задач дата закрытия не существует.
|
||||
"""
|
||||
now = today or date.today()
|
||||
today_date = today or date.today()
|
||||
needle = (query or "").strip().casefold()
|
||||
start, end = window_bounds(done_from, done_to, now)
|
||||
start, end = window_bounds(done_from, done_to, today_date)
|
||||
result: list[dict[str, Any]] = []
|
||||
for task in tasks:
|
||||
if task.get("deleted"):
|
||||
@@ -196,6 +198,9 @@ def filter_tasks(tasks: list[dict[str, Any]], *, query: str = "", column: str =
|
||||
task_column = column_of(task)
|
||||
if column and task_column != column:
|
||||
continue
|
||||
if resp and not responsible_matches(task, resp, owner_email=owner_email,
|
||||
owner_id=owner_id, now=now):
|
||||
continue
|
||||
if needle:
|
||||
haystack = " ".join([
|
||||
str(task.get("summary") or ""),
|
||||
@@ -213,9 +218,58 @@ def filter_tasks(tasks: list[dict[str, Any]], *, query: str = "", column: str =
|
||||
return result
|
||||
|
||||
|
||||
def is_overdue(task: dict[str, Any], today: date | None = None) -> bool:
|
||||
WORKDAY_END_HOUR = 18 # рабочий день заканчивается в 18:00 МСК — после этого срок истёк
|
||||
|
||||
# пресеты фильтра по ответственному
|
||||
RESP_PRESETS = (
|
||||
("me", "Мои"),
|
||||
("delegated", "Делегированные"),
|
||||
("none", "Без ответственного"),
|
||||
("overdue-emp", "Просроченные у сотрудников"),
|
||||
)
|
||||
|
||||
|
||||
def due_deadline(task: dict[str, Any]) -> datetime | None:
|
||||
"""Момент, когда срок задачи истёк: дата DUE + 18:00 МСК."""
|
||||
due = due_date(task)
|
||||
return bool(due and due < (today or date.today()))
|
||||
if due is None:
|
||||
return None
|
||||
return datetime(due.year, due.month, due.day, WORKDAY_END_HOUR, 0, tzinfo=MSK)
|
||||
|
||||
|
||||
def is_overdue(task: dict[str, Any], now: datetime | None = None) -> bool:
|
||||
"""Просрочка: срок истёк после 18:00 дня DUE; без DUE и закрытые — не просрочены."""
|
||||
if task.get("completed") or task.get("deleted"):
|
||||
return False
|
||||
deadline = due_deadline(task)
|
||||
if deadline is None:
|
||||
return False
|
||||
moment = now or datetime.now(MSK)
|
||||
if moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=MSK)
|
||||
return moment > deadline
|
||||
|
||||
|
||||
def responsible_matches(task: dict[str, Any], preset: str, *,
|
||||
owner_email: str = "", owner_id: str = "",
|
||||
now: datetime | None = None) -> bool:
|
||||
"""Проверка пресета «Мои / Делегированные / Без ответственного / Просроченные»."""
|
||||
preset = (preset or "").strip().lower()
|
||||
if not preset:
|
||||
return True
|
||||
contact_id = (task.get("responsible") or "").strip()
|
||||
email = (task.get("responsible_email") or "").strip().lower()
|
||||
is_owner = bool((owner_id and contact_id == owner_id)
|
||||
or (owner_email and email == owner_email.lower()))
|
||||
if preset == "me":
|
||||
return is_owner
|
||||
if preset == "delegated":
|
||||
return bool(contact_id or email) and not is_owner
|
||||
if preset == "none":
|
||||
return not contact_id and not email
|
||||
if preset == "overdue-emp":
|
||||
return is_overdue(task, now) and not is_owner
|
||||
return True
|
||||
|
||||
|
||||
# ─── сортировка ─────────────────────────────────────────────────────────────
|
||||
@@ -239,17 +293,10 @@ 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, 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)
|
||||
def _column_rows(tasks: list[dict[str, Any]], *, start: date, end: date,
|
||||
show_all_done: bool, only_column: str | None,
|
||||
today: date, moment_now: datetime) -> list[dict[str, Any]]:
|
||||
"""Разложить задачи по колонкам (общая часть для доски и свимлейнов)."""
|
||||
buckets: dict[str, list[dict[str, Any]]] = {key: [] for key in COLUMN_KEYS}
|
||||
for task in tasks:
|
||||
if task.get("deleted"):
|
||||
@@ -259,21 +306,110 @@ def build_board(tasks: list[dict[str, Any]], today: date | None = None,
|
||||
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)})
|
||||
|
||||
buckets[column].append({**task, "column": column,
|
||||
"overdue": is_overdue(task, moment_now)})
|
||||
columns = []
|
||||
for key, title in COLUMNS:
|
||||
if only_column and key != only_column:
|
||||
continue
|
||||
items = sort_tasks(buckets[key], now)
|
||||
items = sort_tasks(buckets[key], today)
|
||||
columns.append({"key": key, "title": title, "count": len(items), "tasks": items})
|
||||
return columns
|
||||
|
||||
|
||||
def group_by_person(tasks: list[dict[str, Any]], *, people: list[dict[str, Any]],
|
||||
owner_email: str = "", owner_id: str = "") -> list[dict[str, Any]]:
|
||||
"""Сгруппировать задачи по ответственному для вида «По ответственным».
|
||||
|
||||
Порядок: владелец, сотрудники по алфавиту, затем «Без ответственного».
|
||||
`people` — список сотрудников от вызывающего кода (id, name), чтобы модуль
|
||||
не зависел от базы контактов.
|
||||
"""
|
||||
def key_of(task: dict[str, Any]) -> str:
|
||||
return (task.get("responsible") or "").strip()
|
||||
|
||||
titles: dict[str, str] = {}
|
||||
order: list[str] = []
|
||||
if owner_id:
|
||||
order.append(owner_id)
|
||||
titles[owner_id] = _owner_name(people, owner_id, owner_email) or "Без ответственного"
|
||||
for person in people:
|
||||
pid = (person.get("id") or "").strip()
|
||||
if not pid or pid in order:
|
||||
continue
|
||||
order.append(pid)
|
||||
titles[pid] = (person.get("name") or "").strip() or pid
|
||||
for task in tasks:
|
||||
pid = key_of(task)
|
||||
if pid and pid not in titles:
|
||||
order.append(pid)
|
||||
titles[pid] = (task.get("responsible_name") or pid).strip()
|
||||
|
||||
groups: dict[str, list[dict[str, Any]]] = {pid: [] for pid in order}
|
||||
groups[""] = []
|
||||
for task in tasks:
|
||||
pid = key_of(task)
|
||||
groups.setdefault(pid, []).append(task)
|
||||
|
||||
result = []
|
||||
for pid in order:
|
||||
if not groups.get(pid):
|
||||
continue
|
||||
result.append({"id": pid, "title": titles.get(pid, pid), "tasks": groups[pid]})
|
||||
if groups[""]:
|
||||
result.append({"id": "", "title": "Без ответственного", "tasks": groups[""]})
|
||||
return result
|
||||
|
||||
|
||||
def _owner_name(people: list[dict[str, Any]], owner_id: str, owner_email: str) -> str:
|
||||
for person in people:
|
||||
if (person.get("id") or "") == owner_id:
|
||||
return (person.get("name") or "").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def build_board(tasks: list[dict[str, Any]], today: date | None = None,
|
||||
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,
|
||||
view: str = "columns",
|
||||
people: list[dict[str, Any]] | None = None,
|
||||
owner_email: str = "", owner_id: str = "") -> dict[str, Any]:
|
||||
"""Разложить задачи по колонкам. Возвращает структуру для фрагментов и JSON.
|
||||
|
||||
done_from/done_to — явный диапазон даты закрытия (вместо окна «2 дня»);
|
||||
only_column — показать одну колонку (фильтр по статусу);
|
||||
view="person" — свимлейны по ответственному (та же сетка колонок в группе).
|
||||
"""
|
||||
now = today or date.today()
|
||||
start, end = window_bounds(done_from, done_to, now)
|
||||
moment_now = datetime.now(MSK)
|
||||
rows = _column_rows(tasks, start=start, end=end, show_all_done=show_all_done,
|
||||
only_column=only_column, today=now, moment_now=moment_now)
|
||||
|
||||
groups: list[dict[str, Any]] = []
|
||||
if view == "person":
|
||||
for group in group_by_person(tasks, people=people or [],
|
||||
owner_email=owner_email, owner_id=owner_id):
|
||||
group_rows = _column_rows(group["tasks"], start=start, end=end,
|
||||
show_all_done=show_all_done,
|
||||
only_column=only_column, today=now,
|
||||
moment_now=moment_now)
|
||||
if not any(row["count"] for row in group_rows):
|
||||
continue
|
||||
groups.append({"id": group["id"], "title": group["title"],
|
||||
"columns": group_rows,
|
||||
"total": sum(row["count"] for row in group_rows)})
|
||||
|
||||
return {
|
||||
"columns": columns,
|
||||
"columns": rows,
|
||||
"groups": groups,
|
||||
"view": "person" if view == "person" else "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),
|
||||
"total": sum(c["count"] for c in rows),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -40,6 +40,10 @@ def task_row(task: dict[str, Any]) -> str:
|
||||
done = bool(task.get("completed"))
|
||||
due = task.get("due") or ""
|
||||
due_html = f'<div class="d">срок {html.escape(due)}</div>' if due else ""
|
||||
from tasktracker import people as people_mod
|
||||
_resp = people_mod.assignee(task)
|
||||
resp_html = (f'<div class="rw">{html.escape(_resp["name"] or _resp["email"])}</div>'
|
||||
if _resp["set"] else "")
|
||||
|
||||
toggle_js = _swap_card(
|
||||
f"'/api/task/{uid}/toggle',{{method:'POST',headers:{{'HX-Request':'true'}}}}")
|
||||
@@ -72,6 +76,7 @@ def task_row(task: dict[str, Any]) -> str:
|
||||
</div>
|
||||
</template>
|
||||
{due_html}
|
||||
{resp_html}
|
||||
</div>
|
||||
<span class="del" title="удалить" onclick="event.stopPropagation();{delete_js}">✕</span>
|
||||
</div>'''
|
||||
@@ -136,7 +141,40 @@ def _status_btn(task: dict[str, Any], target: str | None, label: str, title: str
|
||||
f" hx-vals='{vals}' hx-target='#board' hx-swap='outerHTML'>{label}</button>")
|
||||
|
||||
|
||||
def board_card(task: dict[str, Any]) -> str:
|
||||
def _resp_control(task: dict[str, Any], people: list[dict[str, Any]] | None = None) -> str:
|
||||
'''Бейдж ответственного + поповер выбора (Alpine).
|
||||
|
||||
Пустое значение — кнопка «→ кому?»; клик по бейджу открывает карточку
|
||||
контакта (страница контактов с поиском по почте).
|
||||
'''
|
||||
from tasktracker import people as people_mod
|
||||
|
||||
info = people_mod.assignee(task)
|
||||
uid = _url(str(task.get("uid", "")))
|
||||
options = [{"id": (p.get("id") or ""), "name": (p.get("full_name") or p.get("name") or "")}
|
||||
for p in (people or []) if p.get("id")]
|
||||
data = html.escape(json.dumps({"r": False, "sel": info["id"], "people": options},
|
||||
ensure_ascii=False), quote=True)
|
||||
if info["set"]:
|
||||
label = info["name"] or info["email"] or "назначен"
|
||||
href = f'/contacts?q={quote(info["email"] or label)}'
|
||||
badge = (f'<a class="cresp{" own" if info["owner"] else ""}" href="{_esc(href)}"'
|
||||
f' title="ответственный — открыть контакт">{_esc(label)}</a>')
|
||||
else:
|
||||
badge = '<span class="cresp none" title="ответственный не назначен">без ответственного</span>'
|
||||
opts = "".join(f'<option value="{_esc(o["id"])}">{_esc(o["name"])}</option>' for o in options)
|
||||
return (f'<span class="rwrap" x-data="{data}">'
|
||||
f'{badge}'
|
||||
'<button class="rbtn" type="button" x-on:click="r=!r" title="изменить ответственного">✎</button>'
|
||||
'<span class="rpop" x-show="r" x-cloak x-on:click.outside="r=false">'
|
||||
f'<select x-model="sel"><option value="">— без ответственного —</option>{opts}</select>'
|
||||
f'<button class="rbtn ok" hx-post="/api/tasks/{uid}/responsible"'
|
||||
" hx-vals='js:{contact_id: sel}' hx-target='#board' hx-swap='outerHTML'"
|
||||
' x-on:click="r=false">ОК</button>'
|
||||
'</span></span>')
|
||||
|
||||
|
||||
def board_card(task: dict[str, Any], people: list[dict[str, Any]] | None = None) -> str:
|
||||
'''Карточка заявки: тема, теги, срок (просроченный выделен), приоритет, от кого, дата.'''
|
||||
from tasktracker import board as B
|
||||
|
||||
@@ -161,6 +199,7 @@ def board_card(task: dict[str, Any]) -> str:
|
||||
meta.append(f'<span class="ccr">{_esc(task["created"])}</span>')
|
||||
if meta:
|
||||
parts.append('<div class="cmeta">' + "".join(meta) + "</div>")
|
||||
parts.append(f'<div class="crow">{_resp_control(task, people)}</div>')
|
||||
|
||||
buttons = "".join([
|
||||
_status_btn(task, back, "←", "предыдущий статус", disabled=back is None),
|
||||
@@ -175,10 +214,11 @@ def board_card(task: dict[str, Any]) -> str:
|
||||
|
||||
|
||||
def board_column(col: dict[str, Any], show_all_done: bool = False,
|
||||
filters: dict[str, str] | None = None) -> str:
|
||||
filters: dict[str, str] | None = None,
|
||||
people: list[dict[str, Any]] | None = None) -> str:
|
||||
'''Колонка: шапка со счётчиком (+ переключатель «все выполненные») и карточки.'''
|
||||
key = col.get("key", "")
|
||||
cards = "".join(board_card(t) for t in col.get("tasks") or [])
|
||||
cards = "".join(board_card(t, people) for t in col.get("tasks") or [])
|
||||
body = cards or '<div class="cempty">—</div>'
|
||||
toggle = ""
|
||||
if key == "done":
|
||||
@@ -200,8 +240,26 @@ def _qs(filters: dict[str, str] | None, **overrides: Any) -> str:
|
||||
return ("?" + "&".join(parts)) if parts else ""
|
||||
|
||||
|
||||
def _preset_links(filters: dict[str, str]) -> str:
|
||||
'''Пресеты по ответственному и переключатель вида (ссылки с текущими фильтрами).'''
|
||||
from tasktracker.board import RESP_PRESETS
|
||||
|
||||
current = filters.get("resp") or ""
|
||||
chips = []
|
||||
for key, title in RESP_PRESETS:
|
||||
target = "" if key == current else key
|
||||
cls = "preset on" if key == current else "preset"
|
||||
chips.append(f'<a class="{cls}" href="/tasks{_qs(filters, resp=target)}">{_esc(title)}</a>')
|
||||
person_view = (filters.get("view") or "") == "person"
|
||||
toggle_label = "Колонки" if person_view else "По ответственным"
|
||||
toggle_target = "" if person_view else "person"
|
||||
chips.append(f'<a class="preset view" href="/tasks{_qs(filters, view=toggle_target)}">'
|
||||
f'{_esc(toggle_label)}</a>')
|
||||
return '<div class="presets">' + "".join(chips) + "</div>"
|
||||
|
||||
|
||||
def filter_bar(board_data: dict[str, Any]) -> str:
|
||||
"""Панель фильтров доски: текст, статус (колонка), диапазон даты закрытия."""
|
||||
"""Панель фильтров доски: пресеты, текст, статус, диапазон даты закрытия, вид."""
|
||||
from tasktracker.board import COLUMNS
|
||||
|
||||
filters = board_data.get("filters") or {}
|
||||
@@ -211,8 +269,11 @@ def filter_bar(board_data: dict[str, Any]) -> str:
|
||||
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"'
|
||||
_preset_links(filters)
|
||||
+ '<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="hidden" name="resp" value="{_esc(filters.get("resp", ""))}">'
|
||||
f'<input type="hidden" name="view" value="{_esc(filters.get("view", ""))}">'
|
||||
f'<input type="search" name="q" value="{_esc(filters.get("q", ""))}"'
|
||||
' placeholder="Поиск по задачам…">'
|
||||
f'<select name="status">{"".join(options)}</select>'
|
||||
@@ -261,7 +322,20 @@ def board_html(board_data: dict[str, Any], contacts: list[str] | None = None,
|
||||
'''Вся доска (HTMX-корень #board): фильтры + форма быстрого создания + колонки.'''
|
||||
show_all = bool(board_data.get("show_all_done"))
|
||||
filters = board_data.get("filters") or {}
|
||||
columns = "".join(board_column(c, show_all, filters)
|
||||
people = board_data.get("people") or []
|
||||
if board_data.get("view") == "person":
|
||||
lanes = []
|
||||
for group in board_data.get("groups") or []:
|
||||
columns = "".join(board_column(c, show_all, filters, people)
|
||||
for c in group.get("columns") or [])
|
||||
lanes.append(f'<section class="lane"><div class="lane-head">'
|
||||
f'<span class="lane-name">{_esc(group.get("title"))}</span>'
|
||||
f'<span class="cnt">{group.get("total", 0)}</span></div>'
|
||||
f'<div class="board">{columns}</div></section>')
|
||||
body = "".join(lanes) or '<div class="cempty">задач нет</div>'
|
||||
return (f'<div id="board">{filter_bar(board_data)}{quick_form(contacts, error)}'
|
||||
f'<div class="lanes">{body}</div></div>')
|
||||
columns = "".join(board_column(c, show_all, filters, people)
|
||||
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>')
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""people.py — ответственные: владелец, сотрудники, поиск контакта.
|
||||
|
||||
Ответственный хранится в VTODO как `X-RESPONSIBLE` (id контакта) плюс копии
|
||||
имени и адреса. Владелец определяется по `TASK_OWNER_EMAIL` из `.env`
|
||||
проекта; сотрудники — контакты с `is_employee: true`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
ENV_FILE = Path(__file__).resolve().parent.parent / ".env"
|
||||
DEFAULT_OWNER_EMAIL = "e.storozhenko@vinogorod.ru"
|
||||
|
||||
|
||||
def _env(name: str, default: str = "") -> str:
|
||||
value = os.environ.get(name)
|
||||
if value:
|
||||
return value.strip()
|
||||
try:
|
||||
for line in ENV_FILE.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, val = line.partition("=")
|
||||
if key.strip() == name:
|
||||
return val.strip().strip('"').strip("'")
|
||||
except OSError:
|
||||
pass
|
||||
return default
|
||||
|
||||
|
||||
def owner_email() -> str:
|
||||
return (_env("TASK_OWNER_EMAIL", DEFAULT_OWNER_EMAIL) or DEFAULT_OWNER_EMAIL).lower()
|
||||
|
||||
|
||||
def owner_name() -> str:
|
||||
return _env("TASK_OWNER_NAME", "Стороженко Евгений Владимирович")
|
||||
|
||||
|
||||
def _contacts() -> list[dict[str, Any]]:
|
||||
from webui import contacts as contacts_mod
|
||||
|
||||
db = contacts_mod.load()
|
||||
return contacts_mod.visible(db)
|
||||
|
||||
|
||||
def employees() -> list[dict[str, Any]]:
|
||||
"""Контакты, помеченные сотрудниками (звёздочкой в карточке)."""
|
||||
return [c for c in _contacts() if c.get("is_employee")]
|
||||
|
||||
|
||||
def contact_by_id(contact_id: str) -> dict[str, Any] | None:
|
||||
if not contact_id:
|
||||
return None
|
||||
for contact in _contacts():
|
||||
if contact.get("id") == contact_id:
|
||||
return contact
|
||||
return None
|
||||
|
||||
|
||||
def contact_by_email(email: str) -> dict[str, Any] | None:
|
||||
needle = (email or "").strip().lower()
|
||||
if not needle:
|
||||
return None
|
||||
for contact in _contacts():
|
||||
if (contact.get("email") or "").strip().lower() == needle:
|
||||
return contact
|
||||
return None
|
||||
|
||||
|
||||
def owner_contact() -> dict[str, Any] | None:
|
||||
return contact_by_email(owner_email())
|
||||
|
||||
|
||||
def is_owner(task: dict[str, Any]) -> bool:
|
||||
"""Задача «моя»: ответственный — владелец (по id, иначе по адресу)."""
|
||||
email = (task.get("responsible_email") or "").strip().lower()
|
||||
if email:
|
||||
return email == owner_email()
|
||||
contact = contact_by_id(task.get("responsible") or "")
|
||||
if contact is not None:
|
||||
return (contact.get("email") or "").strip().lower() == owner_email()
|
||||
return False
|
||||
|
||||
|
||||
def assignee(task: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Описание ответственного для интерфейса."""
|
||||
contact_id = (task.get("responsible") or "").strip()
|
||||
name = (task.get("responsible_name") or "").strip()
|
||||
email = (task.get("responsible_email") or "").strip()
|
||||
if contact_id:
|
||||
contact = contact_by_id(contact_id)
|
||||
if contact is not None:
|
||||
name = name or (contact.get("full_name") or "")
|
||||
email = email or (contact.get("email") or "")
|
||||
return {"id": contact_id, "name": name, "email": email,
|
||||
"owner": is_owner(task), "set": bool(contact_id or name)}
|
||||
Reference in New Issue
Block a user