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
+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 "Готово."