feat: tasks-card-inline — toggle fix (reload), /api/tasks/reload, /api/tasks/new-form, update_task, /api/task/{uid}/update. fix: radicale update_task
This commit is contained in:
+59
-20
@@ -335,17 +335,16 @@ async def ai_ask(request: Request, _: AuthDep):
|
||||
async def task_create(request: Request, _: AuthDep):
|
||||
"""Создать VTODO из письма (или произвольного текста)."""
|
||||
import json
|
||||
raw = await request.body()
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception:
|
||||
return {"error": "invalid JSON"}
|
||||
summary = (data.get("subject") or data.get("summary") or "Без темы")[:120]
|
||||
description = data.get("body", "")[:500]
|
||||
sender = data.get("from", "")
|
||||
# HTMX шлёт hx-vals как URL-encoded, читаем из формы
|
||||
form = await request.form()
|
||||
form_data = dict(form)
|
||||
summary = str(form_data.get("subject") or form_data.get("summary") or "Без темы")
|
||||
summary = summary[:120]
|
||||
description = (str(form_data.get("body") or ""))[:500]
|
||||
sender = str(form_data.get("from", ""))
|
||||
if sender:
|
||||
description = f"От: {sender}\n{description}"
|
||||
due_str = data.get("due")
|
||||
due_str = str(form_data.get("due") or "") or None
|
||||
res = radicale.create_task(summary, description.strip(), due_str)
|
||||
if res.get("error"):
|
||||
if request.headers.get("hx-request", "").lower() == "true":
|
||||
@@ -365,20 +364,60 @@ def task_toggle(uid: str, request: Request, _: AuthDep,
|
||||
return {"error": res["error"]}
|
||||
new_completed = res["status"] == "COMPLETED"
|
||||
if request.headers.get("hx-request", "").lower() == "true":
|
||||
due_html = f'<div class="d">срок {due}</div>' if due else ""
|
||||
cls = "tk done" if new_completed else "tk"
|
||||
html = f'''<div class="{cls}">
|
||||
<span class="chk" hx-post="/api/task/{uid}/toggle" hx-target="closest .tk" hx-swap="outerHTML"></span>
|
||||
<div class="txt">
|
||||
<div class="t">{summary or "(без темы)"}</div>
|
||||
{due_html}
|
||||
</div>
|
||||
</div>'''
|
||||
from fastapi.responses import HTMLResponse
|
||||
return HTMLResponse(html)
|
||||
return HTMLResponse('<div hx-get="/api/tasks/reload" hx-trigger="load" hx-target="closest .card" hx-swap="innerHTML"></div>')
|
||||
return {"ok": True, "status": res["status"]}
|
||||
|
||||
|
||||
@app.get("/api/tasks/reload")
|
||||
def tasks_reload(request: Request, _: AuthDep):
|
||||
"""HTMX-фрагмент: весь блок задач для главной (создание + инлайн-редактирование)."""
|
||||
tasks = radicale.get_tasks()
|
||||
items = []
|
||||
for t in tasks:
|
||||
due_html = f'<div class="d">срок {t["due"]}</div>' if t.get("due") else ""
|
||||
items.append(f'''<div class="tk {'done' if t['completed'] else ''}">
|
||||
<span class="chk" hx-post="/api/task/{t['uid']}/toggle" hx-target="closest .card" hx-swap="innerHTML"></span>
|
||||
<div class="txt">
|
||||
<div class="t">{t['summary']}</div>
|
||||
{due_html}
|
||||
</div>
|
||||
</div>''')
|
||||
items_html = "".join(items) or '<div class="empty">Задач нет или Radicale недоступен</div>'
|
||||
active = sum(1 for t in tasks if not t["completed"])
|
||||
btn = '<button class="add-task" hx-get="/api/tasks/new-form" hx-target="closest .cbody" hx-swap="beforeend">+ Новая задача</button>'
|
||||
html = f'''<div class="chead">✅ Текущие задачи <span class="cnt">{active}</span></div>
|
||||
<div class="cbody">{items_html}{btn}</div>'''
|
||||
return HTMLResponse(html)
|
||||
|
||||
|
||||
@app.get("/api/tasks/new-form")
|
||||
def task_new_form(_: AuthDep):
|
||||
"""Форма создания задачи (HTMX-фрагмент)."""
|
||||
return HTMLResponse('''<div class="task-form" style="display:flex;gap:4px;padding:6px 10px">
|
||||
<input name="summary" placeholder="Название задачи" style="flex:1;padding:3px 6px;border:1px solid var(--border);border-radius:4px;background:var(--bg2);color:var(--fg)" autofocus>
|
||||
<input name="due" type="date" style="width:130px;padding:3px 6px;border:1px solid var(--border);border-radius:4px;background:var(--bg2);color:var(--fg)">
|
||||
<button class="pb-btn" hx-post="/api/tasks/create" hx-include="closest .task-form input" hx-target="closest .card" hx-swap="innerHTML">✓</button>
|
||||
<button class="pb-btn" hx-get="/api/tasks/reload" hx-target="closest .card" hx-swap="innerHTML">✗</button>
|
||||
</div>''')
|
||||
|
||||
|
||||
@app.put("/api/task/{uid}/update")
|
||||
async def task_update(uid: str, request: Request, _: AuthDep):
|
||||
"""Обновить SUMMARY и/или DUE задачи."""
|
||||
import json
|
||||
raw = await request.body()
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception:
|
||||
return {"error": "invalid JSON"}
|
||||
summary = (data.get("summary") or "")[:120]
|
||||
due = data.get("due", "") or ""
|
||||
res = radicale.update_task(uid, summary, due)
|
||||
if res.get("error"):
|
||||
return {"error": res["error"]}
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# --- Календарь ---
|
||||
@app.get("/api/calendar")
|
||||
def calendar(request: Request, _: AuthDep, year: int = 0, month: int = 0):
|
||||
|
||||
@@ -146,6 +146,57 @@ def toggle_task(uid: str) -> dict:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
def update_task(uid: str, summary: str, due_str: str = "") -> dict:
|
||||
"""Обновить SUMMARY и/или DUE VTODO."""
|
||||
url = f"{RADICALE_BASE}/{RADICALE_USER}/%D0%97%D0%B0%D0%B4%D0%B0%D1%87%D0%B8/{uid}.ics"
|
||||
try:
|
||||
with httpx.Client(auth=(RADICALE_USER, _password()), timeout=5.0) as c:
|
||||
r = c.get(url)
|
||||
if r.status_code == 404:
|
||||
return {"error": "Task not found"}
|
||||
r.raise_for_status()
|
||||
body = r.text
|
||||
old_etag = r.headers.get("etag", "").strip()
|
||||
# меняем SUMMARY
|
||||
new_body_lines = []
|
||||
for line in body.splitlines():
|
||||
if line.startswith("SUMMARY:"):
|
||||
new_body_lines.append(f"SUMMARY:{summary}")
|
||||
elif line.startswith("DUE:") and due_str:
|
||||
from datetime import datetime
|
||||
try:
|
||||
dt = datetime.strptime(due_str, "%Y-%m-%d").strftime("%Y%m%dT235959Z")
|
||||
new_body_lines.append(f"DUE:{dt}")
|
||||
except ValueError:
|
||||
new_body_lines.append(line)
|
||||
else:
|
||||
new_body_lines.append(line)
|
||||
# если due_str задан но DUE нет — добавить перед END:VTODO
|
||||
if due_str:
|
||||
try:
|
||||
from datetime import datetime
|
||||
dt = datetime.strptime(due_str, "%Y-%m-%d").strftime("%Y%m%dT235959Z")
|
||||
has_due = any(ln.startswith("DUE:") for ln in new_body_lines)
|
||||
if not has_due:
|
||||
for i, ln in enumerate(new_body_lines):
|
||||
if ln.strip() == "END:VTODO":
|
||||
new_body_lines.insert(i, f"DUE:{dt}")
|
||||
break
|
||||
except ValueError:
|
||||
pass
|
||||
new_body = "\r\n".join(new_body_lines)
|
||||
put_r = c.put(url, content=new_body,
|
||||
headers={"Content-Type": "text/calendar", "If-Match": old_etag})
|
||||
if put_r.status_code == 412:
|
||||
_CACHE.pop("Задачи:VTODO", None)
|
||||
return {"error": "conflict", "note": "etag mismatch; reload page"}
|
||||
put_r.raise_for_status()
|
||||
_CACHE.pop("Задачи:VTODO", None)
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
def _parse_vtodo(data: str, etag: str) -> dict[str, Any]:
|
||||
props: dict[str, str] = {}
|
||||
for line in data.splitlines():
|
||||
|
||||
Reference in New Issue
Block a user