Subscriptions: «Оплачено?» → paid status → «repeat?»; edit and create everything

- ops: paying marks the current charge paid (paid_for, persisted) instead of jumping to
  the next date; repeat_sub moves to the next period or closes the subscription.
  Paid-and-undecided subscriptions leave reminders and show in agenda['paid'].
  update_sub can set paid; tasks reopen when their status goes back; delete for subs and
  routines (BroV only, /api/delete); /api/tasks?all=1 and /api/subs?all=1.
- Bot: «₽ Оплачено?» on reminders, then «🔁 Да, <date> / Нет, закрыть»; after paying by
  text it asks the same with buttons.
- BroV: «Оплачено?» everywhere; «Оплачено — повторить?» section under the notch;
  «Весь план»: forms to edit or create tasks (title, description, status, due, company),
  subscriptions (amount, currency, period, date, reminder, company, paid, active) and
  routines, delete with confirmation, «+» per list, done tasks on demand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-10 03:57:18 +03:00
parent 011c709acf
commit 882632b7ce
9 changed files with 628 additions and 65 deletions
+43 -10
View File
@@ -125,16 +125,27 @@ async def cmd_stop(update: Update, ctx):
await update.message.reply_text(f"⏹ Остановил: {t['title']}" if t else "Таймер не шёл.")
def repeat_buttons(sub: dict) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[
InlineKeyboardButton(f"🔁 Да, {ru_day(sub['next_if_repeat'])}", callback_data=f"rep:sub:{sub['id']}:1"),
InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]])
async def think(update: Update, text: str):
msg = await update.effective_message.reply_text("🤔 думаю…")
paid: list = []
try:
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"])
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"], paid)
except OpsError as e:
answer = f"Не получилось: {e}"
except Exception as e: # Claude timeout, CLI missing…
log.exception("brain")
answer = f"Ошибка: {e.__class__.__name__}"
await msg.edit_text(answer[:4000])
for sid in paid: # paid by text: ask «repeat?» with buttons
s = locked(ops.sub, sid)
if s["paid"] and s["active"]:
await update.effective_message.reply_text(f"₽ {s['name']} оплачена. Повторить?", reply_markup=repeat_buttons(s))
@owner_only
@@ -168,7 +179,7 @@ async def on_voice(update: Update, ctx):
def reminder_buttons(it: dict) -> InlineKeyboardMarkup:
kind, ref = it["kind"], it["id"]
first = {"task": "✓ Сделано", "sub": "₽ Оплачено", "routine": "✓ Сделано"}[kind]
first = {"task": "✓ Сделано", "sub": "₽ Оплачено?", "routine": "✓ Сделано"}[kind]
return InlineKeyboardMarkup([[InlineKeyboardButton(first, callback_data=f"done:{kind}:{ref}"),
InlineKeyboardButton("⏰ Завтра", callback_data=f"snooze:{kind}:{ref}")]])
@@ -177,16 +188,22 @@ async def on_button(update: Update, ctx):
q = update.callback_query
if not q or q.message.chat.id != owner():
return
action, kind, ref = q.data.split(":")
ref = int(ref)
parts = q.data.split(":")
action, kind, ref = parts[0], parts[1], int(parts[2])
markup = None
try:
with lock:
if action == "done":
if action == "rep":
s = ops.repeat_sub(ref, parts[3] == "1")
note = (f"🔁 Следующее списание {ru_day(s['next_date'])}" if s["active"]
else "✓ Закрыта, больше не повторяется")
elif action == "done":
if kind == "task":
note = f"✓ Сделано: {ops.complete_task(ref)['title']}"
elif kind == "sub":
s = ops.pay_sub(ref)
note = f"₽ Оплачено: {s['name']}, следующее списание {ru_day(s['next_date'])}"
note = f"₽ Оплачено. Повторить {ru_day(s['next_if_repeat'])}?"
markup = repeat_buttons(s)
else:
r = ops.done_routine(ref)
note = f"✓ {r['title']}: следующий раз {ru_day(r['next_date'])}"
@@ -196,7 +213,7 @@ async def on_button(update: Update, ctx):
except OpsError as e:
note = f"Не получилось: {e}"
await q.answer()
await q.edit_message_text(q.message.text + "\n\n" + note)
await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup)
# MARK: - Reminders
@@ -248,13 +265,14 @@ async def api_agenda(request):
async def api_tasks(request):
check_auth(request)
return ok(locked(ops.task_tree))
return ok(locked(ops.task_tree, request.query.get("all") == "1"))
async def api_subs(request):
check_auth(request)
with lock:
return ok({"subs": ops.subs(), "monthly_cost": ops.monthly_cost(), "by_client": ops.monthly_by_client()})
return ok({"subs": ops.subs(active_only=request.query.get("all") != "1"), "monthly_cost": ops.monthly_cost(),
"by_client": ops.monthly_by_client()})
async def api_routines(request):
@@ -288,6 +306,21 @@ async def api_action(request):
return ok({"ok": not any(r.startswith("✗") for r in result), "result": result})
async def api_delete(request):
"""Delete by an explicit click in BroV (Claude never deletes)."""
check_auth(request)
body = await request.json()
kind, ref = str(body.get("kind")), int(body.get("id"))
fn = {"task": ops.delete_task, "sub": ops.delete_sub, "routine": ops.delete_routine}.get(kind)
if not fn:
raise web.HTTPBadRequest(text="kind")
try:
locked(fn, ref)
except OpsError as e:
return ok({"ok": False, "result": [str(e)]})
return ok({"ok": True, "result": ["🗑 удалено"]})
async def api_health(request):
return ok({"ok": True})
@@ -297,7 +330,7 @@ def make_api() -> web.Application:
app.add_routes([web.get("/api/health", api_health), web.get("/api/agenda", api_agenda),
web.get("/api/tasks", api_tasks), web.get("/api/subs", api_subs),
web.get("/api/routines", api_routines), web.post("/api/say", api_say),
web.post("/api/action", api_action)])
web.post("/api/action", api_action), web.post("/api/delete", api_delete)])
return app
+24 -9
View File
@@ -26,7 +26,9 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
period: day | week | month | year (по умолчанию month); currency по умолчанию RUB;
client — компания, за которую платится подписка («компания сага», «для планеты»)
- update_sub {id, name?, amount?, next_date?, client?, period?, every?, currency?, remind_days?, notes?, active?}
- pay_sub {id, amount?, paid_on?} оплачено: следующая дата сдвинется сама
- pay_sub {id, amount?, paid_on?} отметить текущее списание оплаченным (статус «Оплачено»)
- repeat_sub {id, repeat} после оплаты: repeat=true — следующее списание через период,
repeat=false — подписка больше не нужна (закрыть)
- add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…)
- done_routine {id, note?}
- update_routine {id, title?, every_days?, next_date?, notes?, active?}
@@ -40,11 +42,13 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
actions пустой, ответ в reply по данным ниже.
- Если непонятно, что сделать, — actions пустой, в reply переспроси.
- Ничего не удаляй. Не выдумывай id — бери только из данных ниже.
- После pay_sub добавляй repeat_sub, только если пользователь сам сказал, продлевать или нет
(«оплатил и продлеваем», «больше не нужна»); иначе в reply спроси, повторять ли.
- reply — 1–3 строки, без markdown-заголовков.
"""
ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer",
"add_sub", "update_sub", "pay_sub", "add_routine", "done_routine", "update_routine"}
"add_sub", "update_sub", "pay_sub", "repeat_sub", "add_routine", "done_routine", "update_routine"}
def snapshot(ops: Ops) -> str:
@@ -62,7 +66,8 @@ def snapshot(ops: Ops) -> str:
lines += ["", "Подписки (id, сумма, период, следующее списание, компания):"]
for s in ops.subs(active_only=False):
lines.append(f"- #{s['id']} {s['name']} | {s['amount']:g} {s['currency']} | каждые {s['every']} {s['period']} | "
f"{s['next_date']} | {s['client'] or '-'} | {'активна' if s['active'] else 'выкл'}")
f"{s['next_date']} | {s['client'] or '-'} | {'активна' if s['active'] else 'выкл'}"
f"{' | ОПЛАЧЕНО, ждёт решения о повторе' if s['paid'] and s['active'] else ''}")
lines.append(f"Итого в месяц: {ops.monthly_cost()}")
lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"]
for r in ops.routines():
@@ -95,9 +100,11 @@ def parse_plan(text: str) -> dict:
return plan
def apply_plan(ops: Ops, plan: dict) -> list[str]:
"""Carries out the actions in order; returns one human line per action."""
def apply_plan(ops: Ops, plan: dict, paid: list | None = None) -> list[str]:
"""Carries out the actions in order; returns one human line per action. `paid` collects
subscriptions paid here and still waiting for «repeat?»."""
done, keys = [], {}
paid = paid if paid is not None else []
for a in plan.get("actions", []):
op = a.get("op") if isinstance(a, dict) else None
if op not in ALLOWED:
@@ -135,11 +142,18 @@ def apply_plan(ops: Ops, plan: dict) -> list[str]:
+ (f", компания {client_name(s['client'])}" if s["client"] else ""))
elif op == "update_sub":
s = ops.update_sub(int(a["id"]), **_only(args, "name", "amount", "next_date", "period", "every",
"currency", "remind_days", "notes", "active", "client"))
"currency", "remind_days", "notes", "active", "client", "paid"))
done.append(f"✎ подписка #{s['id']} {s['name']}")
elif op == "pay_sub":
s = ops.pay_sub(int(a["id"]), a.get("amount"), a.get("paid_on"))
done.append(f"₽ оплачено: {s['name']}, следующее списание {ru_day(s['next_date'])}")
paid.append(s["id"])
done.append(f"₽ Оплачено: {s['name']}. Повторить {ru_day(s['next_if_repeat'])}?")
elif op == "repeat_sub":
s = ops.repeat_sub(int(a["id"]), bool(a.get("repeat", True)))
if s["id"] in paid:
paid.remove(s["id"])
done.append(f"🔁 {s['name']}: следующее списание {ru_day(s['next_date'])}" if s["active"]
else f"✓ {s['name']}: закрыта, больше не повторяется")
elif op == "add_routine":
r = ops.add_routine(**_only(args, "title", "every_days", "next_date", "notes"))
done.append(f"+ регламент #{r['id']} {r['title']}: раз в {r['every_days']} дн., след. {ru_day(r['next_date'])}")
@@ -158,13 +172,14 @@ def _only(d: dict, *keys) -> dict:
return {k: d[k] for k in keys if k in d}
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku") -> str:
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku",
paid: list | None = None) -> str:
"""One message in, one answer out (actions taken + Claude's reply). The database lock
is held only while reading the state and applying the actions, not while Claude thinks."""
with lock:
prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip()
plan = parse_plan(ask_claude(prompt, claude_bin, model))
with lock:
lines = apply_plan(ops, plan)
lines = apply_plan(ops, plan, paid)
reply = str(plan.get("reply", "")).strip()
return "\n".join(([reply] if reply else []) + lines) or "Готово."
+51 -13
View File
@@ -101,6 +101,8 @@ class Ops:
self.con.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?", (*vals, task_id))
if fields.get("status") == "done":
self._finish(task_id)
elif fields.get("status") in ("todo", "doing"):
self.con.execute("UPDATE tasks SET done_at = NULL WHERE id = ?", (task_id,))
return self.task(task_id)
def complete_task(self, task_id: int) -> dict:
@@ -188,11 +190,17 @@ class Ops:
# MARK: - Subscriptions and payments
def _sub_row(self, row) -> dict:
s = dict(row)
s["paid"] = s.get("paid_for") == s["next_date"]
s["next_if_repeat"] = add_period(date.fromisoformat(s["next_date"]), s["period"], s["every"]).isoformat()
return s
def sub(self, sub_id: int) -> dict:
row = self.con.execute("SELECT * FROM subscriptions WHERE id = ?", (sub_id,)).fetchone()
if not row:
raise OpsError(f"подписки #{sub_id} нет")
return dict(row)
return self._sub_row(row)
def add_sub(self, name: str, amount: float, next_date, period: str = "month", every: int = 1,
currency: str = "RUB", remind_days: int = 3, notes: str = "", client: str = "") -> dict:
@@ -212,7 +220,8 @@ class Ops:
return self.sub(cur.lastrowid)
def update_sub(self, sub_id: int, **fields) -> dict:
allowed = {"name", "amount", "currency", "period", "every", "next_date", "remind_days", "notes", "active", "client"}
allowed = {"name", "amount", "currency", "period", "every", "next_date", "remind_days", "notes", "active", "client",
"paid"}
sets, vals = [], []
for k, v in fields.items():
if k not in allowed or v is None:
@@ -223,28 +232,54 @@ class Ops:
raise OpsError(f"период может быть только {', '.join(PERIODS)}")
if k == "client":
v = str(v).strip().lower()
if k == "paid":
continue # applied below, against the (possibly new) date
sets.append(f"{k} = ?")
vals.append(v)
if sets:
self.sub(sub_id)
self.con.execute(f"UPDATE subscriptions SET {', '.join(sets)} WHERE id = ?", (*vals, sub_id))
if fields.get("paid") is not None: # status edited by hand: the current charge paid or not
self.con.execute("UPDATE subscriptions SET paid_for = CASE WHEN ? THEN next_date END WHERE id = ?",
(1 if fields["paid"] else 0, sub_id))
return self.sub(sub_id)
def pay_sub(self, sub_id: int, amount: float | None = None, paid_on=None) -> dict:
"""Records the payment and moves the next charge one period forward."""
"""Marks the current charge paid (status «Оплачено») and records the payment. The
next charge appears only after «repeat?» is answered (repeat_sub)."""
s = self.sub(sub_id)
if s["paid"]:
return s
day = parse_day(paid_on) or self.today()
self.con.execute("INSERT INTO payments (sub_id, paid_on, amount) VALUES (?, ?, ?)",
(sub_id, day.isoformat(), float(amount if amount is not None else s["amount"])))
nxt = add_period(date.fromisoformat(s["next_date"]), s["period"], s["every"])
while nxt <= day: # paid late or far ahead: the next charge is still in the future
nxt = add_period(nxt, s["period"], s["every"])
self.con.execute("UPDATE subscriptions SET next_date = ? WHERE id = ?", (nxt.isoformat(), sub_id))
self.con.execute("UPDATE subscriptions SET paid_for = next_date WHERE id = ?", (sub_id,))
return self.sub(sub_id)
def repeat_sub(self, sub_id: int, repeat: bool = True) -> dict:
"""After a payment: repeat → the next charge one period later (back to «Оплачено?»),
don't → the subscription is closed (kept, paid, inactive)."""
s = self.sub(sub_id)
if not repeat:
self.con.execute("UPDATE subscriptions SET active = 0 WHERE id = ?", (sub_id,))
return self.sub(sub_id)
nxt = add_period(date.fromisoformat(s["next_date"]), s["period"], s["every"])
while nxt < self.today(): # several periods behind: the next charge is still ahead
nxt = add_period(nxt, s["period"], s["every"])
self.con.execute("UPDATE subscriptions SET next_date = ?, active = 1 WHERE id = ?", (nxt.isoformat(), sub_id))
return self.sub(sub_id)
def delete_sub(self, sub_id: int) -> None:
self.sub(sub_id)
self.con.execute("DELETE FROM subscriptions WHERE id = ?", (sub_id,))
def delete_routine(self, rid: int) -> None:
self.routine(rid)
self.con.execute("DELETE FROM routines WHERE id = ?", (rid,))
def subs(self, active_only: bool = True) -> list[dict]:
q = "SELECT * FROM subscriptions" + (" WHERE active = 1" if active_only else "") + " ORDER BY next_date"
return [dict(r) for r in self.con.execute(q)]
return [self._sub_row(r) for r in self.con.execute(q)]
PER_MONTH = {"day": 30.44, "week": 4.345, "month": 1, "year": 1 / 12}
@@ -324,7 +359,7 @@ class Ops:
def bucket(d: date) -> str:
return "overdue" if d < today else ("today" if d == today else "soon")
out = {"today": today.isoformat(), "overdue": [], "due_today": [], "soon": [],
out = {"today": today.isoformat(), "overdue": [], "due_today": [], "soon": [], "paid": [],
"running": None, "monthly_cost": self.monthly_cost()}
key = {"overdue": "overdue", "today": "due_today", "soon": "soon"}
for t in self.con.execute("SELECT * FROM tasks WHERE status != 'done' AND due IS NOT NULL AND due <= ?",
@@ -334,9 +369,12 @@ class Ops:
"client": t["client"]})
for s in self.subs():
d = date.fromisoformat(s["next_date"])
if d <= horizon:
out[key[bucket(d)]].append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"],
"amount": s["amount"], "currency": s["currency"], "client": s["client"]})
item = {"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"], "amount": s["amount"],
"currency": s["currency"], "client": s["client"], "paid": s["paid"], "next_if_repeat": s["next_if_repeat"]}
if s["paid"]:
out["paid"].append(item) # paid, waiting for «repeat?»
elif d <= horizon:
out[key[bucket(d)]].append(item)
for r in self.routines():
d = date.fromisoformat(r["next_date"])
if d <= horizon:
@@ -363,7 +401,7 @@ class Ops:
out.append({"kind": "task", "id": t["id"], "title": t["title"], "date": t["due"]})
for s in self.subs():
d = date.fromisoformat(s["next_date"])
if d - timedelta(days=s["remind_days"]) <= today and ("sub", s["id"]) not in sent:
if not s["paid"] and d - timedelta(days=s["remind_days"]) <= today and ("sub", s["id"]) not in sent:
out.append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"],
"amount": s["amount"], "currency": s["currency"], "client": s["client"]})
for r in self.routines():
+4 -1
View File
@@ -31,7 +31,8 @@ CREATE TABLE IF NOT EXISTS subscriptions (
remind_days INTEGER NOT NULL DEFAULT 3,
notes TEXT NOT NULL DEFAULT '',
active INTEGER NOT NULL DEFAULT 1,
client TEXT NOT NULL DEFAULT '' -- company it's paid for: saga / planet9 / home / …
client TEXT NOT NULL DEFAULT '', -- company it's paid for: saga / planet9 / home / …
paid_for TEXT -- = next_date once that charge is paid (until «repeat?» is answered)
);
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY,
@@ -76,4 +77,6 @@ def connect(path: str) -> sqlite3.Connection:
cols = {r["name"] for r in con.execute("PRAGMA table_info(subscriptions)")}
if "client" not in cols:
con.execute("ALTER TABLE subscriptions ADD COLUMN client TEXT NOT NULL DEFAULT ''")
if "paid_for" not in cols:
con.execute("ALTER TABLE subscriptions ADD COLUMN paid_for TEXT")
return con
+2 -1
View File
@@ -66,8 +66,9 @@ def subs(rows: list, by_client: dict, today: date) -> str:
out.append(f"\n<b>{escape(client_name(client) or 'Без компании')}</b> — {total} в мес.")
for s in (x for x in rows if x["client"] == client):
every = f"{s['every']} " if s["every"] > 1 else ""
status = f" · ✓ оплачено, повторить {ru_day(s['next_if_repeat'])}?" if s["paid"] else ""
out.append(f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / {every}{per[s['period']]}"
f" · {human_day(s['next_date'], today)}")
f" · {human_day(s['next_date'], today)}{status}")
return "\n".join(out).strip()