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:
2026-10-24 06:02:07 +00:00
parent 0e4933a53b
commit 22c2223840
4 changed files with 198 additions and 21 deletions
+87
View File
@@ -0,0 +1,87 @@
"""Fix indentation in app.py - rewrite broken toggle/reload/new-form/update section."""
import re
path = "webui/app.py"
with open(path) as f:
content = f.read()
# The broken section: from @app.post toggle to end of task_update
# Find the toggle endpoint
start_marker = '@app.post("/api/task/{uid}/toggle")'
end_marker = '# --- Календарь ---'
start_idx = content.index(start_marker)
end_idx = content.index(end_marker, start_idx)
# Replacement section (clean, correct indentation)
new_code = '''@app.post("/api/task/{uid}/toggle")
def task_toggle(uid: str, request: Request, _: AuthDep):
"""Toggle COMPLETED/NEEDS-ACTION. HTMX returns reload stub."""
res = radicale.toggle_task(uid)
if res.get("error"):
return {"error": res["error"]}
if request.headers.get("hx-request", "").lower() == "true":
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 card: list + create button."""
tasks = radicale.get_tasks()
items = []
for t in tasks:
due_html = f'<div class="d">\\u0441\\u0440\\u043e\\u043a {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">\\u0417\\u0430\\u0434\\u0430\\u0447 \\u043d\\u0435\\u0442 \\u0438\\u043b\\u0438 Radicale \\u043d\\u0435\\u0434\\u043e\\u0441\\u0442\\u0443\\u043f\\u0435\\u043d</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">+ \\u041d\\u043e\\u0432\\u0430\\u044f \\u0437\\u0430\\u0434\\u0430\\u0447\\u0430</button>'
html = f'''<div class="chead">\\u2705 \\u0422\\u0435\\u043a\\u0443\\u0449\\u0438\\u0435 \\u0437\\u0430\\u0434\\u0430\\u0447\\u0438 <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 create-task form fragment."""
return HTMLResponse('''<div class="task-form" style="display:flex;gap:4px;padding:6px 10px">
<input name="summary" placeholder="\\u041d\\u0430\\u0437\\u0432\\u0430\\u043d\\u0438\\u0435 \\u0437\\u0430\\u0434\\u0430\\u0447\\u0438" style="flex:1;padding:3px 6px;border:1px solid var(--border);border-radius:4px;background:var(--bg2);color:var(--fg)" autfocus>
<input name="due" tye="date" yle="width:130px;padding:3px 6px;border:1px solid var(-border);borderradis:4px;backround:var(--bg2);olor:var(--fg)">
<button cass="pb-btn" hx-pst="/api/tasks/rete" hx-incude="closest .task-form input" hx-target="losest .card" hx-swap="innerHTML">✓</button>
<button class="p-btn" hx-et="/api/tasks/relod" hx-tart="closest .card" hx-swa="innerHTML">✗</buton>
</div>''')
@app.put("/api/task/{uid}/update")
async def task_update(uid: str, request: Request, _: AuthDep):
"""Update SUMMARY and/or DUE of a task."""
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}
'''
content = content[:start_idx] + new_code + content[end_idx:]
with open(path, "w") as f:
f.write(content)
# Verify syntax
compile(open(path).read(), path, 'exec')
print("OK - syntax valid")
+1 -1
View File
@@ -1 +1 @@
{"last_notified_ts": "2026-10-02T22:09:25+00:00", "baseline": true}
{"last_notified_ts": "2026-10-23T23:45:38+00:00"}
+59 -20
View File
@@ -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):
+51
View File
@@ -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():