mirror of
https://gitverse.ru/kpa39l/email-assistant.git
synced 2026-11-27 18:33:08 +00:00
Compare commits
10 Commits
0e4933a53b
...
d6a055a29f
| Author | SHA1 | Date | |
|---|---|---|---|
| d6a055a29f | |||
| 7f08b39487 | |||
| e970ec1602 | |||
| 728cc47780 | |||
| e22b065057 | |||
| e9d91909c6 | |||
| 7c171daedb | |||
| ed024f3822 | |||
| c1cbd4bc46 | |||
| 22c2223840 |
@@ -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")
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""Fix indentation of lines 379-381 in app.py."""
|
||||||
|
path = "webui/app.py"
|
||||||
|
with open(path) as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
|
||||||
|
# Fix lines 379-381: remove 8 leading spaces (they have 16, should have 8)
|
||||||
|
for i in range(378, 382): # 0-indexed: 378 = line 379
|
||||||
|
if i < len(lines):
|
||||||
|
stripped = lines[i].lstrip()
|
||||||
|
current_indent = len(lines[i]) - len(stripped)
|
||||||
|
if current_indent == 16:
|
||||||
|
lines[i] = " " * 8 + stripped
|
||||||
|
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.writelines(lines)
|
||||||
|
|
||||||
|
compile(open(path).read(), path, 'exec')
|
||||||
|
print("OK")
|
||||||
@@ -91,3 +91,14 @@
|
|||||||
|| 2026-10-22 | Задача 7: аутентификация веб-интерфейса (пароль, сессии, login/logout) | ✅ закрыта (dev :8085, Docker, Caddy) | WALKTHROUGH §2026-10-22 |
|
|| 2026-10-22 | Задача 7: аутентификация веб-интерфейса (пароль, сессии, login/logout) | ✅ закрыта (dev :8085, Docker, Caddy) | WALKTHROUGH §2026-10-22 |
|
||||||
|| 2026-10-22 | Клоус Caddy /metrics снаружи (handle → 403) | ✅ закрыта | WALKTHROUGH §2026-10-22 |
|
|| 2026-10-22 | Клоус Caddy /metrics снаружи (handle → 403) | ✅ закрыта | WALKTHROUGH §2026-10-22 |
|
||||||
|| 2026-10-22 | Задача 1: перемещение писем между папками | 🔵 открыта | |
|
|| 2026-10-22 | Задача 1: перемещение писем между папками | 🔵 открыта | |
|
||||||
|
|## 2026-10-24
|
||||||
|
|| Дата | Задача | Статус | Закрыта в |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
|| 2026-10-24 | Фикс чекбокса (reload .card вместо outerHTML) | ✅ закрыта | WALKTHROUGH §2026-10-24 |
|
||||||
|
|| 2026-10-24 | Кнопка «+ Новая задача» (inline-форма через HTMX) | ✅ закрыта | WALKTHROUGH §2026-10-24 |
|
||||||
|
|| 2026-10-24 | Инлайн-редактирование задачи (Alpine, Enter→PUT) | ✅ закрыта | WALKTHROUGH §2026-10-24 |
|
||||||
|
|| 2026-10-24 | Счётчик активных задач (только невыполненные) | ✅ закрыта | WALKTHROUGH §2026-10-24 |
|
||||||
|
|| 2026-10-24 | Карточка задач через hx-trigger=load (всегда с кнопкой) | ✅ закрыта | WALKTHROUGH §2026-10-24 |
|
||||||
|
|| 2026-10-24 | Openspec change tasktracker-module (гриль, proposal, design, spec, tasks) | 🔵 в работе | openspec/changes/tasktracker-module/ |
|
||||||
|
|| 2026-10-24 | Реализация `tasktracker/` модуля (__init__, api, fragments) | 🔵 открыта | |
|
||||||
|
|| 2026-10-24 | update_task/delete_task/set_priority в radicale.py | 🔵 открыта | |
|
||||||
|
|||||||
+31
-2
@@ -549,6 +549,35 @@ vesti, bot-флаг vesti на GtS=True) — судьбу решает поль
|
|||||||
- **index.html**: чекбокс по uid, а не etag
|
- **index.html**: чекбокс по uid, а не etag
|
||||||
|
|
||||||
### Git
|
### Git
|
||||||
```bash
|
|```bash
|
||||||
git add -A && git commit -m "feat: docker, metrics, auth-log, task-6 (VTODO create)" && git push gitverse master
|
git add -A && git commit -m "feat: docker, metrics, auth-log, task-6 (VTODO create)" && git push gitverse master
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 2026-10-24 — Tasks card inline (checkbox fix, create, inline edit, tasktracker spec)
|
||||||
|
|
||||||
|
### Чекбокс (починен)
|
||||||
|
- Проблема: outerHTML .tk ломал DOM при повторном клике
|
||||||
|
- Решение: toggle возвращает `<div hx-get="/api/tasks/reload" ...>` → заменяет весь .card
|
||||||
|
- hx-target="closest .card" hx-swap="innerHTML"
|
||||||
|
|
||||||
|
### Кнопка «+ Новая задача»
|
||||||
|
- Внизу .cbody. Клик → GET /api/tasks/new-form → inline-форма
|
||||||
|
- ✓ → POST /api/tasks/create → reload-заглушка → обновлённый список
|
||||||
|
- ✗ → GET /api/tasks/reload (отмена)
|
||||||
|
|
||||||
|
### Инлайн-редактирование
|
||||||
|
- .t → x-on:click → Alpine x-data (edit:{summary}, editing:bool)
|
||||||
|
- Enter: fetch PUT /api/task/{uid}/update → location.reload()
|
||||||
|
- Escape: отмена
|
||||||
|
- CSS: .t-edit-wrap input, .add-task
|
||||||
|
|
||||||
|
### Карточка задач — hx-trigger=load
|
||||||
|
- Вместо Jinja-рендера в index.html — `<div class="card" hx-get="/api/tasks/reload" hx-trigger="load">`
|
||||||
|
- Всегда свежий список + кнопка + inline edit
|
||||||
|
|
||||||
|
### Openspec tasktracker-module
|
||||||
|
- Гриль-интервью (Q1–10): границы модуля, хранение, API, приоритет, удаление
|
||||||
|
- Решения: отдельный tasktracker/ в корне; CRUD + приоритет 1-5 + срок + мягкое удаление;
|
||||||
|
гибрид Radicale → своя БД; APIRouter монтируется в app.py
|
||||||
|
- Change создан: proposal, design, spec, tasks
|
||||||
|
- Реализация не начата (отложено на след. сессию)
|
||||||
@@ -1 +1 @@
|
|||||||
{"last_notified_ts": "2026-10-02T22:09:25+00:00", "baseline": true}
|
{"last_notified_ts": "2026-10-23T23:45:38+00:00"}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
created: 2026-10-24
|
||||||
|
status: open
|
||||||
|
hash: tasktracker-module-v1
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Design: TaskTracker Module
|
||||||
|
|
||||||
|
## Структура
|
||||||
|
|
||||||
|
```
|
||||||
|
/opt/hermes/email-assistant/tasktracker/
|
||||||
|
__init__.py # TaskTracker class — бизнес-логика
|
||||||
|
api.py # FastAPI APIRouter, монтируется в app.py
|
||||||
|
fragments.py # Константы HTML-фрагментов (для HTMX)
|
||||||
|
```
|
||||||
|
|
||||||
|
## TaskTracker (__init__.py)
|
||||||
|
|
||||||
|
Методы:
|
||||||
|
- `list() -> list[dict]` — все задачи (кроме мягко удалённых)
|
||||||
|
- `get(uid) -> dict` — одна задача
|
||||||
|
- `create(summary, description, due_str, priority) -> dict` — новая
|
||||||
|
- `update(uid, summary, due) -> dict` — изменить
|
||||||
|
- `delete(uid) -> dict` — мягкое удаление (STATUS:CANCELLED)
|
||||||
|
- `toggle(uid) -> dict` — NEEDS-ACTION ↔ COMPLETED
|
||||||
|
- `set_priority(uid, priority) -> dict` — 1-5
|
||||||
|
|
||||||
|
Хранение: через import radicale (webui/radicale.py). Когда появится своя БД — замена storage layer.
|
||||||
|
|
||||||
|
## API (api.py)
|
||||||
|
|
||||||
|
| Method | Path | Description |
|
||||||
|
|--------|------|-------------|
|
||||||
|
| POST | /api/tasks/create | Создать (JSON/form) |
|
||||||
|
| POST | /api/task/{uid}/toggle | Переключить |
|
||||||
|
| PUT | /api/task/{uid}/update | Обновить summary/due |
|
||||||
|
| PUT | /api/task/{uid}/priority | Установить приоритет |
|
||||||
|
| DELETE | /api/task/{uid} | Мягко удалить |
|
||||||
|
| GET | /api/tasks/reload | HTML-фрагмент карточки |
|
||||||
|
| GET | /api/tasks/new-form | HTML-фрагмент формы создания |
|
||||||
|
| GET | /api/tasks | JSON-список (для будущего API-клиента) |
|
||||||
|
|
||||||
|
HTMX-эндпоинты (reload, new-form) возвращают HTML.
|
||||||
|
Остальные — JSON, но для HTMX возвращают reload-заглушку.
|
||||||
|
|
||||||
|
## Связь с app.py
|
||||||
|
|
||||||
|
```python
|
||||||
|
from tasktracker.api import router as tasktracker_router
|
||||||
|
app.include_router(tasktracker_router)
|
||||||
|
```
|
||||||
|
|
||||||
|
`app.py` больше не импортирует `radicale` напрямую для задач.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Proposal: Выделение TaskTracker в отдельный модуль
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
Сейчас функциональность задач (CRUD, toggle, приоритет, срок, инлайн-редактирование)
|
||||||
|
размазана по `webui/radicale.py` (CalDAV-клиент), `webui/app.py` (маршруты + HTML-генерация)
|
||||||
|
и `webui/templates/` (шаблоны). Нет границы — изменить логику задач значит менять app.py.
|
||||||
|
|
||||||
|
Пользователю нужен:
|
||||||
|
- Отдельный модуль `tasktracker/` в корне проекта
|
||||||
|
- Чёткий API (FastAPI router), монтируемый в app.py одной строкой
|
||||||
|
- Возможность в будущем заменить Radicale на другое хранилище без переписывания UI
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
|
||||||
|
1. Создать `tasktracker/` — каталог модуля
|
||||||
|
2. `__init__.py` — класс TaskTracker с методами list, get, create, update, delete, toggle, set_priority
|
||||||
|
3. `api.py` — APIRouter с эндпоинтами, возвращает JSON (для API) и HTML (для HTMX)
|
||||||
|
4. `fragments.py` — строковые HTML-шаблоны для HTMX-фрагментов (reload, new-form, task-row)
|
||||||
|
5. Убрать дублирующийся код из `app.py`, заменить на `app.include_router(tasktracker.api.router)`
|
||||||
|
6. Обновить `index.html` — карточка задач грузится через /api/tasks/reload
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
hash: "tasktracker-module-v1"
|
||||||
|
date: 2026-10-24
|
||||||
|
---
|
||||||
|
|
||||||
|
# TaskTracker Module Spec
|
||||||
|
|
||||||
|
## Requirement: Module isolation
|
||||||
|
|
||||||
|
- DI: `tasktracker/` is top-level dir, self-contained
|
||||||
|
- app.py imports only `tasktracker.api.router` → `app.include_router()`
|
||||||
|
- No direct `import radicale` for tasks outside tasktracker
|
||||||
|
|
||||||
|
## Requirement: CRUD operations
|
||||||
|
|
||||||
|
### Scenario: Create task
|
||||||
|
- POST /api/tasks/create (summary, due?, priority?, description?)
|
||||||
|
- Returns: reload stub (HTMX) or JSON {ok, uid}
|
||||||
|
|
||||||
|
### Scenario: Toggle task
|
||||||
|
- POST /api/task/{uid}/toggle
|
||||||
|
- Radicale: NEEDS-ACTION ↔ COMPLETED
|
||||||
|
- Returns: reload stub or JSON
|
||||||
|
|
||||||
|
### Scenario: Update task summary/due
|
||||||
|
- PUT /api/task/{uid}/update {summary, due?}
|
||||||
|
- Radicale: GET+PUT SUMMARY/DUE
|
||||||
|
- Returns: JSON {ok}
|
||||||
|
|
||||||
|
### Scenario: Delete task
|
||||||
|
- DELETE /api/task/{uid}
|
||||||
|
- Soft delete: STATUS:CANCELLED + X-DELETED
|
||||||
|
- Returns: JSON {ok}; HTMX: reload stub
|
||||||
|
|
||||||
|
### Scenario: Set priority
|
||||||
|
- PUT /api/task/{uid}/priority {priority: 1-5}
|
||||||
|
- Radicale: GET+PUT PRIORITY
|
||||||
|
- Returns: JSON {ok}
|
||||||
|
|
||||||
|
## Requirement: HTML fragments
|
||||||
|
|
||||||
|
- GET /api/tasks/reload → full card HTML (chead + cbody + add-task button + inline edit)
|
||||||
|
- GET /api/tasks/new-form → inline create form HTML
|
||||||
|
- All fragments use Alpine.js for inline editing, HTMX for submission
|
||||||
|
|
||||||
|
## Storage
|
||||||
|
|
||||||
|
- Current: webui.radicale module (CalDAV VTODO)
|
||||||
|
- Future: own SQLite table (tasks)
|
||||||
|
- Switch: replace `tasktracker/__init__.py` storage import, API unchanged
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Tasks: TaskTracker Module
|
||||||
|
|
||||||
|
| # | Задача | Статус |
|
||||||
|
|---|--------|--------|
|
||||||
|
| 1 | Создать `tasktracker/__init__.py` с классом TaskTracker (методы list, create, update, delete, toggle, set_priority) | 🔵 |
|
||||||
|
| 2 | Создать `tasktracker/api.py` с APIRouter (перенести эндпоинты из app.py) | 🔵 |
|
||||||
|
| 3 | Создать `tasktracker/fragments.py` (HTML-строки: reload, new-form) | 🔵 |
|
||||||
|
| 4 | Добавить delete_task/set_priority в radicale.py | 🔵 |
|
||||||
|
| 5 | Подключить router в app.py, убрать дубликаты | 🔵 |
|
||||||
|
| 6 | Проверить: создание, toggle, inline-edit, удаление | 🔵 |
|
||||||
+76
-22
@@ -335,48 +335,102 @@ async def ai_ask(request: Request, _: AuthDep):
|
|||||||
async def task_create(request: Request, _: AuthDep):
|
async def task_create(request: Request, _: AuthDep):
|
||||||
"""Создать VTODO из письма (или произвольного текста)."""
|
"""Создать VTODO из письма (или произвольного текста)."""
|
||||||
import json
|
import json
|
||||||
raw = await request.body()
|
# HTMX шлёт hx-vals как URL-encoded, читаем из формы
|
||||||
try:
|
form = await request.form()
|
||||||
data = json.loads(raw)
|
form_data = dict(form)
|
||||||
except Exception:
|
summary = str(form_data.get("subject") or form_data.get("summary") or "Без темы")
|
||||||
return {"error": "invalid JSON"}
|
summary = summary[:120]
|
||||||
summary = (data.get("subject") or data.get("summary") or "Без темы")[:120]
|
description = (str(form_data.get("body") or ""))[:500]
|
||||||
description = data.get("body", "")[:500]
|
sender = str(form_data.get("from", ""))
|
||||||
sender = data.get("from", "")
|
|
||||||
if sender:
|
if sender:
|
||||||
description = f"От: {sender}\n{description}"
|
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)
|
res = radicale.create_task(summary, description.strip(), due_str)
|
||||||
if res.get("error"):
|
if res.get("error"):
|
||||||
if request.headers.get("hx-request", "").lower() == "true":
|
if request.headers.get("hx-request", "").lower() == "true":
|
||||||
return HTMLResponse(f'<button class="pb-btn" disabled style="color:var(--urgent)" title="{res["error"]}">✗</button>')
|
return HTMLResponse(f'<button class="pb-btn" disabled style="color:var(--urgent)" title="{res["error"]}">✗</button>')
|
||||||
return {"error": res["error"]}
|
return {"error": res["error"]}
|
||||||
if request.headers.get("hx-request", "").lower() == "true":
|
if request.headers.get("hx-request", "").lower() == "true":
|
||||||
return HTMLResponse('<button class="pb-btn" disabled title="Задача создана" style="font-size:16px">✅</button>')
|
# после создания — сразу отдать свежий список задач
|
||||||
|
return _render_tasks_card()
|
||||||
return {"ok": True, "uid": res.get("uid", ""), "etag": res.get("etag", "")}
|
return {"ok": True, "uid": res.get("uid", ""), "etag": res.get("etag", "")}
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/task/{uid}/toggle")
|
@app.post("/api/task/{uid}/toggle")
|
||||||
def task_toggle(uid: str, request: Request, _: AuthDep,
|
def task_toggle(uid: str, request: Request, _: AuthDep):
|
||||||
summary: str = Form(default=""), due: str = Form(default="")):
|
"""Toggle COMPLETED/NEEDS-ACTION. HTMX returns fresh card."""
|
||||||
"""Переключить COMPLETED ↔ NEEDS-ACTION. Для HTMX возвращает HTML-фрагмент .tk."""
|
|
||||||
res = radicale.toggle_task(uid)
|
res = radicale.toggle_task(uid)
|
||||||
if res.get("error"):
|
if res.get("error"):
|
||||||
return {"error": res["error"]}
|
return {"error": res["error"]}
|
||||||
new_completed = res["status"] == "COMPLETED"
|
|
||||||
if request.headers.get("hx-request", "").lower() == "true":
|
if request.headers.get("hx-request", "").lower() == "true":
|
||||||
due_html = f'<div class="d">срок {due}</div>' if due else ""
|
return _render_tasks_card()
|
||||||
cls = "tk done" if new_completed else "tk"
|
return {"ok": True, "status": res["status"]}
|
||||||
html = f'''<div class="{cls}">
|
|
||||||
<span class="chk" hx-post="/api/task/{uid}/toggle" hx-target="closest .tk" hx-swap="outerHTML"></span>
|
|
||||||
|
@app.get("/api/tasks/reload")
|
||||||
|
def tasks_reload(request: Request, _: AuthDep):
|
||||||
|
"""HTMX-фрагмент: весь блок задач для главной."""
|
||||||
|
return _render_tasks_card()
|
||||||
|
|
||||||
|
|
||||||
|
def _render_tasks_card() -> HTMLResponse:
|
||||||
|
"""Собрать HTML карточки задач (chead + cbody + кнопка + инлайн-редактирование)."""
|
||||||
|
import json as _json
|
||||||
|
tasks = radicale.get_tasks(limit=100)
|
||||||
|
items = []
|
||||||
|
for t in tasks:
|
||||||
|
due_html = f'<div class="d">срок {t["due"]}</div>' if t.get("due") else ""
|
||||||
|
sid = "'" + t["summary"].replace("'", "\\'") + "'"
|
||||||
|
xdata = '{{edit:{},editing:false}}'.format(sid)
|
||||||
|
items.append(f'''<div class="tk {'done' if t['completed'] else ''}" x-data="{xdata}">
|
||||||
|
<a class="chk" href="#" hx-post="/api/task/{t['uid']}/toggle" hx-target="closest .card" hx-swap="innerHTML" onclick="event.preventDefault()"></a>
|
||||||
<div class="txt">
|
<div class="txt">
|
||||||
<div class="t">{summary or "(без темы)"}</div>
|
<div class="t" x-on:click="edit={sid};editing=true">{t['summary']}</div>
|
||||||
|
<template x-if="editing">
|
||||||
|
<div class="t-edit-wrap">
|
||||||
|
<input x-model="edit" x-on:keyup.enter="fetch('/api/task/{t['uid']}/update',{{method:'PUT',headers:{{'Content-Type':'application/json'}},body:JSON.stringify({{summary:edit}})}}).then(()=>location.reload())" x-on:keyup.escape="editing=false;edit=''">
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
{due_html}
|
{due_html}
|
||||||
</div>
|
</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" hx-trigger="click" onclick="this.style.display=\'none\'">+ Новая задача</button>'
|
||||||
|
html = f'''<div class="chead">✅ Текущие задачи <span class="cnt">{active}</span></div>
|
||||||
|
<div class="cbody">
|
||||||
|
{items_html}
|
||||||
|
<button class="add-task" hx-get="/api/tasks/new-form" hx-target="closest .cbody" hx-swap="beforeend">+ Новая задача</button>
|
||||||
</div>'''
|
</div>'''
|
||||||
from fastapi.responses import HTMLResponse
|
return HTMLResponse(html)
|
||||||
return HTMLResponse(html)
|
|
||||||
return {"ok": True, "status": res["status"]}
|
|
||||||
|
@app.get("/api/tasks/new-form")
|
||||||
|
def task_new_form(_: AuthDep):
|
||||||
|
"""Форма создания задачи (HTMX-фрагмент)."""
|
||||||
|
return HTMLResponse('''<div class="task-form" x-data="{s:'',d:''}" style="display:flex;gap:4px;padding:6px 10px">
|
||||||
|
<input x-model="s" placeholder="Название задачи" style="flex:1;padding:3px 6px;border:1px solid var(--border);border-radius:4px;background:var(--bg2);color:var(--fg)" autofocus required>
|
||||||
|
<input x-model="d" 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-vals='{"summary":s,"due":d}' 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}
|
||||||
|
|
||||||
|
|
||||||
# --- Календарь ---
|
# --- Календарь ---
|
||||||
|
|||||||
@@ -146,6 +146,57 @@ def toggle_task(uid: str) -> dict:
|
|||||||
return {"error": str(e)}
|
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]:
|
def _parse_vtodo(data: str, etag: str) -> dict[str, Any]:
|
||||||
props: dict[str, str] = {}
|
props: dict[str, str] = {}
|
||||||
for line in data.splitlines():
|
for line in data.splitlines():
|
||||||
|
|||||||
@@ -182,22 +182,27 @@ body.f3 .c3{flex:1}
|
|||||||
.card .cbody{flex:1;overflow-y:auto;padding:4px 0}
|
.card .cbody{flex:1;overflow-y:auto;padding:4px 0}
|
||||||
.card .cbody::-webkit-scrollbar{width:5px}
|
.card .cbody::-webkit-scrollbar{width:5px}
|
||||||
.card .cbody::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
|
.card .cbody::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}
|
||||||
|
.add-task{background:none;border:1px dashed var(--fg3);color:var(--fg2);cursor:pointer;font-size:12px;padding:6px 14px;border-radius:6px;margin:6px 10px;width:calc(100% - 20px);display:block}
|
||||||
|
.add-task:hover{border-color:var(--accent);color:var(--fg)}
|
||||||
|
|
||||||
.tk{display:flex;gap:8px;padding:8px 14px;border-bottom:1px solid var(--border);
|
.tk{display:flex;gap:8px;padding:8px 14px;border-bottom:1px solid var(--border);
|
||||||
cursor:pointer;align-items:flex-start}
|
cursor:pointer;align-items:flex-start}
|
||||||
.tk:hover{background:var(--hover)}
|
.tk:hover{background:var(--hover)}
|
||||||
.tk .chk{width:15px;height:15px;border:1.5px solid var(--fg3);border-radius:4px;
|
.tk .chk{width:15px;height:15px;border:1.5px solid var(--fg3);border-radius:4px;
|
||||||
flex-shrink:0;margin-top:2px;cursor:pointer}
|
flex-shrink:0;margin-top:2px;cursor:pointer;display:inline-flex;text-decoration:none;color:inherit;align-items:center;justify-content:center}
|
||||||
.tk .txt{flex:1;min-width:0}
|
.tk .txt{flex:1;min-width:0}
|
||||||
.tk .txt .t{font-size:12.5px}
|
.tk .txt .t{font-size:12.5px}
|
||||||
.tk .txt .d{font-size:11px;color:var(--fg3);margin-top:1px}
|
.tk .txt .d{font-size:11px;color:var(--fg3);margin-top:1px}
|
||||||
.tk.done .t{text-decoration:line-through;color:var(--fg3)}
|
.tk.done .t{text-decoration:line-through;color:var(--fg3)}
|
||||||
.tk.done .chk{background:var(--accent);border-color:var(--accent)}
|
.tk.done .chk{background:var(--accent);border-color:var(--accent)}
|
||||||
.tk.done .chk::after{content:'\u2713';color:var(--bg);font-size:11px;line-height:15px;text-align:center;width:100%;display:block}
|
.tk.done .chk::after{content:'\u2713';color:var(--bg);font-size:11px;line-height:15px;text-align:center;width:100%;display:block;pointer-events:none}
|
||||||
/* кнопка «Создать задачу» */
|
/* кнопка «Создать задачу» */
|
||||||
.pb-btn{background:none;border:1px solid var(--border);color:var(--fg);cursor:pointer;font-size:16px;padding:3px 8px;border-radius:6px;line-height:1}
|
.pb-btn{background:none;border:1px solid var(--border);color:var(--fg);cursor:pointer;font-size:16px;padding:3px 8px;border-radius:6px;line-height:1}
|
||||||
.pb-btn:hover{background:var(--hover);border-color:var(--accent)}
|
.pb-btn:hover{background:var(--hover);border-color:var(--accent)}
|
||||||
.pb-btn:disabled{opacity:0.4;cursor:default}
|
.pb-btn:disabled{opacity:0.4;cursor:default}
|
||||||
|
.add-task{background:none;border:1px dashed var(--fg3);color:var(--fg2);cursor:pointer;font-size:12px;padding:6px 14px;border-radius:6px;margin:6px 10px;width:calc(100% - 20px)}
|
||||||
|
.add-task:hover{border-color:var(--accent);color:var(--fg)}
|
||||||
|
.t-edit-wrap input{width:100%;padding:2px 4px;border:1px solid var(--accent);border-radius:4px;background:var(--bg);color:var(--fg);font:inherit;font-size:12.5px}
|
||||||
|
|
||||||
.em{display:flex;gap:8px;padding:8px 14px;border-bottom:1px solid var(--border);
|
.em{display:flex;gap:8px;padding:8px 14px;border-bottom:1px solid var(--border);
|
||||||
cursor:pointer;align-items:flex-start}
|
cursor:pointer;align-items:flex-start}
|
||||||
|
|||||||
@@ -56,21 +56,9 @@
|
|||||||
|
|
||||||
<!-- КАРТОЧКИ -->
|
<!-- КАРТОЧКИ -->
|
||||||
<div class="grid">
|
<div class="grid">
|
||||||
<div class="card">
|
<div class="card" hx-get="/api/tasks/reload" hx-trigger="load" hx-swap="innerHTML">
|
||||||
<div class="chead">✅ Текущие задачи <span class="cnt">{{ tasks|selectattr('completed','false')|list|length }}</span></div>
|
<div class="chead">✅ Текущие задачи <span class="cnt">0</span></div>
|
||||||
<div class="cbody">
|
<div class="cbody"><div class="empty">Загрузка...</div></div>
|
||||||
{% for t in tasks %}
|
|
||||||
<div class="tk {{ 'done' if t.completed else '' }}">
|
|
||||||
<span class="chk" hx-post="/api/task/{{ t.uid }}/toggle" hx-target="closest .tk" hx-swap="outerHTML" hx-vals='{"summary":{{ t.summary|tojson|safe }},"due":{{ (t.due or "")|tojson|safe }}}'></span>
|
|
||||||
<div class="txt">
|
|
||||||
<div class="t">{{ t.summary }}</div>
|
|
||||||
{% if t.due %}<div class="d">срок {{ t.due }}</div>{% endif %}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% else %}
|
|
||||||
<div class="empty">Задач нет или Radicale недоступен</div>
|
|
||||||
{% endfor %}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
|
|||||||
Reference in New Issue
Block a user