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:
+33
-7
@@ -433,10 +433,12 @@ def contacts_page(request: Request, _: AuthDep, q: str = "", company: str = "",
|
||||
last_name: str = "", first_name: str = "", middle_name: str = "",
|
||||
phone: str = "", email: str = "", position: str = "",
|
||||
letter: str = DEFAULT_LETTER, page: int = 1, per_page: int = 50,
|
||||
sort: str = "last_name", dir: str = "asc", cid: str = ""):
|
||||
sort: str = "last_name", dir: str = "asc", cid: str = "",
|
||||
emp: str = ""):
|
||||
"""Страница контактов: фильтры + алфавит (c1), таблица с пагинацией (c2), карточка (c3).
|
||||
|
||||
По умолчанию открывается буква «А»; `letter=all` — весь список.
|
||||
По умолчанию открывается буква «А»; `letter=all` — весь список;
|
||||
`emp=1` — пресет «Сотрудники».
|
||||
"""
|
||||
import math
|
||||
db_all = contacts.load()
|
||||
@@ -446,10 +448,10 @@ def contacts_page(request: Request, _: AuthDep, q: str = "", company: str = "",
|
||||
"phone": phone, "email": email, "position": position}
|
||||
# "all"/"все" — без фильтра по букве; иначе буква из указателя
|
||||
letter_eff = "" if (letter or "").strip().lower() in ("all", "все") else (letter or "").strip()
|
||||
found = contacts.search(everyone, letter=letter_eff, **filters)
|
||||
found = contacts.search(everyone, letter=letter_eff, emp=emp, **filters)
|
||||
found = contacts.sort_contacts(found, sort, reverse=(dir == "desc"))
|
||||
# алфавит считается без учёта запроса q и выбранной буквы — иначе «прыгает»
|
||||
alpha_source = contacts.search(everyone, **{**filters, "q": ""})
|
||||
alpha_source = contacts.search(everyone, emp=emp, **{**filters, "q": ""})
|
||||
|
||||
per_page = per_page if per_page in PER_PAGE_OPTIONS else 50
|
||||
pages = max(1, math.ceil(len(found) / per_page))
|
||||
@@ -458,6 +460,8 @@ def contacts_page(request: Request, _: AuthDep, q: str = "", company: str = "",
|
||||
|
||||
letter_q = letter_eff or "all"
|
||||
params = {k: v for k, v in {**filters, "letter": letter_q}.items() if v}
|
||||
if emp:
|
||||
params["emp"] = emp
|
||||
if sort != "last_name":
|
||||
params["sort"] = sort
|
||||
if dir != "asc":
|
||||
@@ -473,6 +477,7 @@ def contacts_page(request: Request, _: AuthDep, q: str = "", company: str = "",
|
||||
"companies": contacts.filter_options(everyone, "company"),
|
||||
"positions": contacts.filter_options(everyone, "position"),
|
||||
"sort": sort, "dir": dir, "letter": letter_eff, "filters": filters,
|
||||
"emp": emp,
|
||||
"page": "contacts", # подсветка раздела в боковой панели
|
||||
}
|
||||
if cid:
|
||||
@@ -529,6 +534,26 @@ async def contact_field(contact_id: str, request: Request, _: AuthDep):
|
||||
return out
|
||||
|
||||
|
||||
@app.post("/api/contact/{contact_id}/employee")
|
||||
async def contact_employee(contact_id: str, request: Request, _: AuthDep):
|
||||
"""Включить/выключить признак «сотрудник»: {"value": true|false}."""
|
||||
import json
|
||||
|
||||
try:
|
||||
data = json.loads(await request.body() or b"{}")
|
||||
except json.JSONDecodeError:
|
||||
raise HTTPException(status_code=400, detail="invalid JSON") from None
|
||||
value = data.get("value")
|
||||
if value is None:
|
||||
current = contacts.by_id(contact_id) or {}
|
||||
value = not current.get("is_employee")
|
||||
res = contacts.set_employee(contact_id, bool(value))
|
||||
if res.get("error"):
|
||||
status = 404 if "не найден" in str(res["error"]) else 400
|
||||
return JSONResponse({"error": res["error"]}, status_code=status)
|
||||
return {"ok": True, "is_employee": res["is_employee"]}
|
||||
|
||||
|
||||
# --- Автосозданные сущности письма (событие/задача) ---
|
||||
@app.post("/api/email/entity")
|
||||
async def email_entity(request: Request, _: AuthDep):
|
||||
@@ -579,12 +604,13 @@ async def email_entity(request: Request, _: AuthDep):
|
||||
|
||||
@app.get("/tasks", response_class=HTMLResponse)
|
||||
def tasks_page(request: Request, _: AuthDep, all_done: int = 0, q: str = "",
|
||||
status: str = "", done_from: str = "", done_to: str = ""):
|
||||
"""Доска задач (канбан): форма создания, фильтры (текст/статус/дата закрытия)."""
|
||||
status: str = "", done_from: str = "", done_to: str = "",
|
||||
resp: str = "", view: str = ""):
|
||||
"""Доска задач (канбан): форма создания, фильтры, пресеты, вид по ответственным."""
|
||||
from tasktracker.api import _board, _contacts_hint
|
||||
|
||||
data = _board(show_all_done=bool(all_done), q=q, status=status,
|
||||
done_from=done_from, done_to=done_to)
|
||||
done_from=done_from, done_to=done_to, resp=resp, view=view)
|
||||
if is_htmx(request):
|
||||
return HTMLResponse(tfrag.board_html(data, _contacts_hint()))
|
||||
return render(request, "tasks.html", {
|
||||
|
||||
+35
-2
@@ -123,11 +123,18 @@ def _match(contact: dict[str, Any], field: str, needle: str) -> bool:
|
||||
|
||||
|
||||
def search(contacts: list[dict[str, Any]], *, q: str = "", letter: str = "",
|
||||
**filters: str) -> list[dict[str, Any]]:
|
||||
"""Отфильтровать список контактов (регистронезависимо, телефон — по цифрам)."""
|
||||
emp: str = "", **filters: str) -> list[dict[str, Any]]:
|
||||
"""Отфильтровать список контактов (регистронезависимо, телефон — по цифрам).
|
||||
|
||||
`emp` — пресет «Сотрудники»: непустое значение оставляет только контакты
|
||||
с `is_employee: true`.
|
||||
"""
|
||||
qn = norm(q)
|
||||
only_employees = bool((emp or "").strip())
|
||||
result = []
|
||||
for c in contacts:
|
||||
if only_employees and not c.get("is_employee"):
|
||||
continue
|
||||
if letter and letter_of(c) != letter.upper():
|
||||
continue
|
||||
if qn:
|
||||
@@ -216,6 +223,32 @@ def save(db: dict[str, Any], path: Path | str | None = None,
|
||||
_cache.update(key=str(p), db=db, mtime=p.stat().st_mtime)
|
||||
|
||||
|
||||
def set_employee(contact_id: str, value: bool, *,
|
||||
path: Path | str | None = None) -> dict[str, Any]:
|
||||
"""Включить/выключить признак «сотрудник» (звёздочка в карточке).
|
||||
|
||||
Признак живёт только в `contacts.json`: в vCard он не пишется (клиенты его
|
||||
не понимают), поэтому CardDAV не трогаем. Поле добавляется в
|
||||
`manual_fields`, чтобы экстрактор его не перетирал.
|
||||
"""
|
||||
p = Path(path or CONTACTS_JSON)
|
||||
lock_path = p.with_suffix(".lock")
|
||||
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(lock_path, "w", encoding="utf-8") as lock_file:
|
||||
fcntl.flock(lock_file, fcntl.LOCK_EX)
|
||||
db = load(p, force=True)
|
||||
contact = by_id(contact_id, db)
|
||||
if contact is None:
|
||||
return {"error": f"контакт {contact_id} не найден"}
|
||||
contact["is_employee"] = bool(value)
|
||||
manual = contact.setdefault("manual_fields", [])
|
||||
if "is_employee" not in manual:
|
||||
manual.append("is_employee")
|
||||
save(db, p)
|
||||
fcntl.flock(lock_file, fcntl.LOCK_UN)
|
||||
return {"ok": True, "is_employee": bool(value), "contact": contact}
|
||||
|
||||
|
||||
def update_field(contact_id: str, field: str, value: str, *,
|
||||
path: Path | str | None = None, push: bool = True) -> dict[str, Any]:
|
||||
"""Изменить одно поле контакта: валидация → файл под flock → CardDAV."""
|
||||
|
||||
+53
-12
@@ -198,7 +198,9 @@ def create_task(summary: str, description: str = "", due_str: str | None = None,
|
||||
|
||||
|
||||
def _resource_url(uid: str) -> str:
|
||||
"""URL ресурса задачи: сначала href из последнего REPORT (истинный путь)."""
|
||||
"""URL ресурса задачи: сначала ранее найденный href, затем из REPORT."""
|
||||
if uid in _RESOLVED:
|
||||
return _RESOLVED[uid]
|
||||
key = f"{TASKS_COLLECTION}:VTODO"
|
||||
for item in (_CACHE.get(key) or {}).get("items") or []:
|
||||
if item.get("uid") == uid and item.get("href"):
|
||||
@@ -236,21 +238,35 @@ def get_task(uid: str) -> dict[str, Any] | None:
|
||||
|
||||
|
||||
def _load_for_update(uid: str) -> tuple[str, str] | dict:
|
||||
"""GET задачи → (body, etag) для последующего PUT с If-Match. При ошибке — {'error': ...}."""
|
||||
try:
|
||||
"""GET задачи → (body, etag) для последующего PUT с If-Match. При ошибке — {'error': ...}.
|
||||
|
||||
Кэш списка сбрасывается после каждой записи (`_put_for_update`), поэтому при
|
||||
404 кэш перечитывается один раз: иначе задача, у которой имя файла не
|
||||
совпадает с UID (все задачи из писем), становится «нередактируемой».
|
||||
"""
|
||||
key = f"{TASKS_COLLECTION}:VTODO"
|
||||
|
||||
def _try_get() -> tuple[httpx.Response | None, str]:
|
||||
with httpx.Client(auth=(RADICALE_USER, _password()), timeout=5.0) as c:
|
||||
r, url = None, ""
|
||||
response, url = None, ""
|
||||
for candidate in _lookup_urls(uid):
|
||||
r = c.get(candidate)
|
||||
if r.status_code != 404:
|
||||
response = c.get(candidate)
|
||||
if response.status_code != 404:
|
||||
url = candidate
|
||||
break
|
||||
if r is None or r.status_code == 404:
|
||||
return {"error": "Task not found"}
|
||||
r.raise_for_status()
|
||||
# запомнить фактический ресурс, чтобы PUT шёл туда же
|
||||
_RESOLVED[uid] = url
|
||||
return r.text, r.headers.get("etag", "").strip()
|
||||
return response, url
|
||||
|
||||
try:
|
||||
r, url = _try_get()
|
||||
if r is not None and r.status_code == 404:
|
||||
_CACHE.pop(key, None)
|
||||
_fetch_items(TASKS_COLLECTION, "VTODO")
|
||||
r, url = _try_get()
|
||||
if r is None or r.status_code == 404:
|
||||
return {"error": "Task not found"}
|
||||
r.raise_for_status()
|
||||
_RESOLVED[uid] = url
|
||||
return r.text, r.headers.get("etag", "").strip()
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
@@ -359,6 +375,9 @@ def _parse_vtodo(data: str, etag: str) -> dict[str, Any]:
|
||||
"completed": complete, "status": status, "priority": priority,
|
||||
"description": description,
|
||||
"x_status": props.get("X-STATUS", "").strip().lower(),
|
||||
"responsible": props.get("X-RESPONSIBLE", "").strip(),
|
||||
"responsible_name": _unescape(props.get("X-RESPONSIBLE-NAME", "")).strip(),
|
||||
"responsible_email": _unescape(props.get("X-RESPONSIBLE-EMAIL", "")).strip(),
|
||||
"from_value": from_value,
|
||||
"tags": tags,
|
||||
"due_raw": due or "",
|
||||
@@ -445,6 +464,28 @@ def set_task_state(uid: str, x_status: str, status: str,
|
||||
return _put_for_update(uid, new_body, etag)
|
||||
|
||||
|
||||
def set_responsible(uid: str, contact_id: str | None, name: str = "",
|
||||
email: str = "") -> dict:
|
||||
"""Записать ответственного: X-RESPONSIBLE (id контакта) + имя и адрес копией.
|
||||
|
||||
Пустой contact_id — свойства удаляются (задача без ответственного).
|
||||
"""
|
||||
loaded = _load_for_update(uid)
|
||||
if isinstance(loaded, dict):
|
||||
return loaded
|
||||
body, etag = loaded
|
||||
contact_id = (contact_id or "").strip()
|
||||
if contact_id:
|
||||
new_body = _set_prop(body, "X-RESPONSIBLE", _esc(contact_id))
|
||||
new_body = _set_prop(new_body, "X-RESPONSIBLE-NAME", _esc(name or ""))
|
||||
new_body = _set_prop(new_body, "X-RESPONSIBLE-EMAIL", _esc(email or ""))
|
||||
else:
|
||||
new_body = _del_prop(body, "X-RESPONSIBLE")
|
||||
new_body = _del_prop(new_body, "X-RESPONSIBLE-NAME")
|
||||
new_body = _del_prop(new_body, "X-RESPONSIBLE-EMAIL")
|
||||
return _put_for_update(uid, new_body, etag)
|
||||
|
||||
|
||||
def set_tags(uid: str, tags: list[str]) -> dict:
|
||||
"""Заменить набор тегов объекта (CATEGORIES); пустой список — свойство удаляется."""
|
||||
loaded = _load_for_update(uid)
|
||||
|
||||
@@ -517,3 +517,34 @@ select.qi{width:72px}
|
||||
cursor:pointer;font-size:12px;line-height:1;padding:3px 7px}
|
||||
.sbtn:hover:not(:disabled){border-color:var(--accent);color:var(--fg)}
|
||||
.sbtn:disabled{opacity:.35;cursor:default}
|
||||
|
||||
/* ─── ответственный и пресеты доски ─────────────────────────────────────── */
|
||||
.crow{display:flex;align-items:center;gap:6px;margin-top:5px}
|
||||
.rwrap{position:relative;display:inline-flex;align-items:center;gap:4px}
|
||||
.cresp{font-size:11px;padding:1px 7px;border-radius:10px;background:var(--hover);
|
||||
color:var(--fg2);text-decoration:none;max-width:170px;overflow:hidden;
|
||||
text-overflow:ellipsis;white-space:nowrap}
|
||||
.cresp.own{background:var(--sel);color:var(--accent)}
|
||||
.cresp.none{opacity:.55;font-style:italic}
|
||||
.rbtn{background:none;border:1px solid var(--border);border-radius:6px;color:var(--fg3);
|
||||
font-size:11px;padding:0 5px;line-height:16px;cursor:pointer}
|
||||
.rbtn:hover{background:var(--hover);color:var(--fg)}
|
||||
.rpop{position:absolute;top:20px;left:0;z-index:40;display:flex;gap:4px;
|
||||
background:var(--bg2);border:1px solid var(--border);border-radius:8px;
|
||||
padding:5px;box-shadow:0 6px 18px rgba(0,0,0,.35)}
|
||||
.rpop select{background:var(--bg);color:var(--fg);border:1px solid var(--border);
|
||||
border-radius:6px;font-size:11.5px;padding:2px 4px;max-width:190px}
|
||||
.presets{display:flex;flex-wrap:wrap;gap:6px;padding:6px 12px 0}
|
||||
.preset{font-size:11.5px;padding:3px 9px;border-radius:12px;border:1px solid var(--border);
|
||||
color:var(--fg2);text-decoration:none;white-space:nowrap}
|
||||
.preset:hover{background:var(--hover);color:var(--fg)}
|
||||
.preset.on{background:var(--sel);color:var(--accent);border-color:var(--accent)}
|
||||
.preset.view{margin-left:auto;border-style:dashed}
|
||||
.lanes{display:flex;flex-direction:column;gap:14px;padding:8px 12px}
|
||||
.lane{border:1px solid var(--border);border-radius:10px;overflow:hidden}
|
||||
.lane-head{display:flex;align-items:center;gap:8px;padding:6px 10px;
|
||||
background:var(--bg2);border-bottom:1px solid var(--border);font-size:12.5px}
|
||||
.lane-name{font-weight:600}
|
||||
.rw{font-size:11px;color:var(--fg3);margin-top:2px}
|
||||
.pb-btn.est{color:#f5c451;border-color:#f5c451}
|
||||
.btn.on{background:var(--sel);color:var(--accent);border-color:var(--accent)}
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
{% if current.get('caldav', {}).get('dirty') %}<span class="dirty" title="правка не ушла в CardDAV">не синхронизировано</span>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<button class="pb-btn{% if current.get('is_employee') %} est{% endif %}"
|
||||
title="{% if current.get('is_employee') %}Сотрудник — снять отметку{% else %}Отметить сотрудником{% endif %}"
|
||||
onclick="CTEmployee(this, {{ (current.get('id') or '')|tojson|forceescape }})">★</button>
|
||||
<button class="pb-btn" title="Создать задачу из переписки с контактом"
|
||||
onclick="CTTask(this, {{ (current.get('id') or '')|tojson|forceescape }})">📋</button>
|
||||
</div>
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
<div class="cfa">
|
||||
<button type="submit" class="btn">Найти</button>
|
||||
<a class="btn" href="/contacts">Сбросить</a>
|
||||
<a class="btn{% if emp %} on{% endif %}" href="/contacts?emp=1&letter=all">★ Сотрудники</a>
|
||||
</div>
|
||||
<input type="hidden" name="letter" value="{{ letter_param }}">
|
||||
<input type="hidden" name="per_page" value="{{ per_page }}">
|
||||
@@ -130,6 +131,14 @@
|
||||
}
|
||||
}).catch(function (e) { data.err = 'ошибка: ' + e; });
|
||||
};
|
||||
window.CTEmployee = function (el, id) {
|
||||
fetch('/api/contact/' + encodeURIComponent(id) + '/employee', {method: 'POST'})
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function () {
|
||||
fetch('/contacts/' + encodeURIComponent(id)).then(function (r) { return r.text(); })
|
||||
.then(function (h) { var c3 = document.getElementById('c3'); if (c3) { c3.innerHTML = h; } });
|
||||
});
|
||||
};
|
||||
(function () {
|
||||
var list = document.getElementById('clist'), top = document.getElementById('ctop');
|
||||
if (!list || !top) return;
|
||||
|
||||
Reference in New Issue
Block a user