Subscriptions belong to a company; BroV owns its Keychain token
- ops: subscriptions get a client (company) column (migrated in place); the brain fills it from «компания сага / для планеты»; /subs and «Весь план» group by company with per-company monthly totals; the company shows in agenda rows and the calendar. - BroV: the API token handed over in ops-token.import is saved by BroV itself, so the Keychain item belongs to BroV and macOS stops asking for the password. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+2
-2
@@ -108,7 +108,7 @@ async def cmd_tasks(update: Update, ctx):
|
||||
@owner_only
|
||||
async def cmd_subs(update: Update, ctx):
|
||||
with lock:
|
||||
text = fmt.subs(ops.subs(), ops.monthly_cost(), ops.today())
|
||||
text = fmt.subs(ops.subs(), ops.monthly_by_client(), ops.today())
|
||||
await send_long(update, text)
|
||||
|
||||
|
||||
@@ -254,7 +254,7 @@ async def api_tasks(request):
|
||||
async def api_subs(request):
|
||||
check_auth(request)
|
||||
with lock:
|
||||
return ok({"subs": ops.subs(), "monthly_cost": ops.monthly_cost()})
|
||||
return ok({"subs": ops.subs(), "monthly_cost": ops.monthly_cost(), "by_client": ops.monthly_by_client()})
|
||||
|
||||
|
||||
async def api_routines(request):
|
||||
|
||||
+13
-10
@@ -6,7 +6,7 @@ import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from .core import Ops, OpsError, ru_day
|
||||
from .core import Ops, OpsError, client_name, ru_day
|
||||
|
||||
INSTRUCTIONS = """Ты — помощник-менеджер системного администратора. Пользователь пишет или говорит
|
||||
по-русски, коротко и неформально. Твоя задача — превратить сообщение в действия над его базой дел.
|
||||
@@ -22,9 +22,10 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
|
||||
- reopen_task {id}
|
||||
- start_timer {id} засечь время работы над задачей (предыдущий таймер остановится)
|
||||
- stop_timer {}
|
||||
- add_sub {name, amount, next_date, period?, every?, currency?, remind_days?, notes?}
|
||||
period: day | week | month | year (по умолчанию month); currency по умолчанию RUB
|
||||
- update_sub {id, name?, amount?, next_date?, period?, every?, currency?, remind_days?, notes?, active?}
|
||||
- add_sub {name, amount, next_date, client?, period?, every?, currency?, remind_days?, notes?}
|
||||
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?} оплачено: следующая дата сдвинется сама
|
||||
- add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…)
|
||||
- done_routine {id, note?}
|
||||
@@ -33,7 +34,8 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
|
||||
Правила:
|
||||
- В полях действий даты — строго ГГГГ-ММ-ДД. «завтра», «в пятницу», «15-го» переводи от сегодняшней даты.
|
||||
- В тексте reply даты пиши как ДД.ММ.ГГГГ (например 15.11.2026).
|
||||
- client — одно из: saga, planet9, home, или пусто.
|
||||
- client (у задач и подписок) — компания: saga (Сага), planet9 (Planet9, «планета»), home (дом, личное),
|
||||
другое название — латиницей в нижнем регистре; если не сказано — пусто.
|
||||
- Если пользователь просто спрашивает (что на сегодня, сколько трачу, что просрочено) —
|
||||
actions пустой, ответ в reply по данным ниже.
|
||||
- Если непонятно, что сделать, — actions пустой, в reply переспроси.
|
||||
@@ -57,10 +59,10 @@ def snapshot(ops: Ops) -> str:
|
||||
f"{t['minutes']}м | {t['status']}{run}")
|
||||
walk(t["children"], depth + 1)
|
||||
walk(ops.task_tree(), 0)
|
||||
lines += ["", "Подписки (id, сумма, период, следующее списание):"]
|
||||
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']} | {'активна' if s['active'] else 'выкл'}")
|
||||
f"{s['next_date']} | {s['client'] or '-'} | {'активна' if s['active'] else 'выкл'}")
|
||||
lines.append(f"Итого в месяц: {ops.monthly_cost()}")
|
||||
lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"]
|
||||
for r in ops.routines():
|
||||
@@ -128,11 +130,12 @@ def apply_plan(ops: Ops, plan: dict) -> list[str]:
|
||||
done.append(f"⏹ таймер остановлен" + (f": #{t['id']} {t['title']}" if t else " (не шёл)"))
|
||||
elif op == "add_sub":
|
||||
s = ops.add_sub(**_only(args, "name", "amount", "next_date", "period", "every", "currency",
|
||||
"remind_days", "notes"))
|
||||
done.append(f"+ подписка #{s['id']} {s['name']}: {s['amount']:g} {s['currency']}, след. {ru_day(s['next_date'])}")
|
||||
"remind_days", "notes", "client"))
|
||||
done.append(f"+ подписка #{s['id']} {s['name']}: {s['amount']:g} {s['currency']}, след. {ru_day(s['next_date'])}"
|
||||
+ (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"))
|
||||
"currency", "remind_days", "notes", "active", "client"))
|
||||
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"))
|
||||
|
||||
+28
-9
@@ -28,6 +28,13 @@ def add_period(d: date, period: str, every: int = 1) -> date:
|
||||
raise OpsError(f"неизвестный период: {period}")
|
||||
|
||||
|
||||
CLIENT_NAMES = {"saga": "Сага", "planet9": "Planet9", "home": "Дом"}
|
||||
|
||||
|
||||
def client_name(code: str) -> str:
|
||||
return CLIENT_NAMES.get(code, code) if code else ""
|
||||
|
||||
|
||||
def ru_day(iso) -> str:
|
||||
"""2026-11-15 → 15.11.2026 (how dates are shown; storage stays ISO)."""
|
||||
if not iso:
|
||||
@@ -188,7 +195,7 @@ class Ops:
|
||||
return dict(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 = "") -> dict:
|
||||
currency: str = "RUB", remind_days: int = 3, notes: str = "", client: str = "") -> dict:
|
||||
if not (name or "").strip():
|
||||
raise OpsError("у подписки нет названия")
|
||||
if period not in PERIODS:
|
||||
@@ -197,14 +204,15 @@ class Ops:
|
||||
if not d:
|
||||
raise OpsError("нужна дата следующего списания")
|
||||
cur = self.con.execute(
|
||||
"""INSERT INTO subscriptions (name, amount, currency, period, every, next_date, remind_days, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
"""INSERT INTO subscriptions (name, amount, currency, period, every, next_date, remind_days, notes, client)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(name.strip(), float(amount or 0), (currency or "RUB").upper(), period, max(1, int(every or 1)),
|
||||
d.isoformat(), max(0, int(remind_days if remind_days is not None else 3)), notes or ""))
|
||||
d.isoformat(), max(0, int(remind_days if remind_days is not None else 3)), notes or "",
|
||||
(client or "").strip().lower()))
|
||||
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"}
|
||||
allowed = {"name", "amount", "currency", "period", "every", "next_date", "remind_days", "notes", "active", "client"}
|
||||
sets, vals = [], []
|
||||
for k, v in fields.items():
|
||||
if k not in allowed or v is None:
|
||||
@@ -213,6 +221,8 @@ class Ops:
|
||||
v = parse_day(v).isoformat()
|
||||
if k == "period" and v not in PERIODS:
|
||||
raise OpsError(f"период может быть только {', '.join(PERIODS)}")
|
||||
if k == "client":
|
||||
v = str(v).strip().lower()
|
||||
sets.append(f"{k} = ?")
|
||||
vals.append(v)
|
||||
if sets:
|
||||
@@ -236,14 +246,23 @@ class Ops:
|
||||
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)]
|
||||
|
||||
PER_MONTH = {"day": 30.44, "week": 4.345, "month": 1, "year": 1 / 12}
|
||||
|
||||
def monthly_cost(self) -> dict[str, float]:
|
||||
"""Active subscriptions per month, by currency."""
|
||||
per_month = {"day": 30.44, "week": 4.345, "month": 1, "year": 1 / 12}
|
||||
out: dict[str, float] = {}
|
||||
for s in self.subs():
|
||||
out[s["currency"]] = out.get(s["currency"], 0) + s["amount"] * per_month[s["period"]] / s["every"]
|
||||
out[s["currency"]] = out.get(s["currency"], 0) + s["amount"] * self.PER_MONTH[s["period"]] / s["every"]
|
||||
return {k: round(v, 2) for k, v in out.items()}
|
||||
|
||||
def monthly_by_client(self) -> dict[str, dict[str, float]]:
|
||||
"""Per month by company, then by currency ("" = no company)."""
|
||||
out: dict[str, dict[str, float]] = {}
|
||||
for s in self.subs():
|
||||
c = out.setdefault(s["client"], {})
|
||||
c[s["currency"]] = c.get(s["currency"], 0) + s["amount"] * self.PER_MONTH[s["period"]] / s["every"]
|
||||
return {k: {cur: round(v, 2) for cur, v in d.items()} for k, d in out.items()}
|
||||
|
||||
# MARK: - Routines
|
||||
|
||||
def routine(self, rid: int) -> dict:
|
||||
@@ -317,7 +336,7 @@ class Ops:
|
||||
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"]})
|
||||
"amount": s["amount"], "currency": s["currency"], "client": s["client"]})
|
||||
for r in self.routines():
|
||||
d = date.fromisoformat(r["next_date"])
|
||||
if d <= horizon:
|
||||
@@ -346,7 +365,7 @@ class Ops:
|
||||
d = date.fromisoformat(s["next_date"])
|
||||
if 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"]})
|
||||
"amount": s["amount"], "currency": s["currency"], "client": s["client"]})
|
||||
for r in self.routines():
|
||||
if date.fromisoformat(r["next_date"]) <= today and ("routine", r["id"]) not in sent:
|
||||
out.append({"kind": "routine", "id": r["id"], "title": r["title"], "date": r["next_date"]})
|
||||
|
||||
+6
-1
@@ -30,7 +30,8 @@ CREATE TABLE IF NOT EXISTS subscriptions (
|
||||
next_date TEXT NOT NULL, -- YYYY-MM-DD of the next charge
|
||||
remind_days INTEGER NOT NULL DEFAULT 3,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
active INTEGER NOT NULL DEFAULT 1
|
||||
active INTEGER NOT NULL DEFAULT 1,
|
||||
client TEXT NOT NULL DEFAULT '' -- company it's paid for: saga / planet9 / home / …
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
id INTEGER PRIMARY KEY,
|
||||
@@ -71,4 +72,8 @@ def connect(path: str) -> sqlite3.Connection:
|
||||
con.execute("PRAGMA foreign_keys = ON")
|
||||
con.execute("PRAGMA journal_mode = WAL")
|
||||
con.executescript(SCHEMA)
|
||||
# Databases created before subscriptions had a company.
|
||||
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 ''")
|
||||
return con
|
||||
|
||||
+16
-10
@@ -2,7 +2,7 @@
|
||||
from datetime import date
|
||||
from html import escape
|
||||
|
||||
from .core import ru_day
|
||||
from .core import client_name, ru_day
|
||||
|
||||
ICON = {"task": "📌", "sub": "💳", "routine": "🔁"}
|
||||
|
||||
@@ -23,7 +23,7 @@ def human_day(iso: str, today: date) -> str:
|
||||
|
||||
def item_line(it: dict, today: date) -> str:
|
||||
extra = f" — {it['amount']:g} {it['currency']}" if it["kind"] == "sub" else ""
|
||||
client = f" [{it['client']}]" if it.get("client") else ""
|
||||
client = f" [{client_name(it['client'])}]" if it.get("client") else ""
|
||||
return f"{ICON[it['kind']]} {escape(it['title'])}{client}{extra} · {human_day(it['date'], today)}"
|
||||
|
||||
|
||||
@@ -49,20 +49,26 @@ def tree(nodes: list, depth: int = 0) -> list[str]:
|
||||
mark = "⏱" if t["running"] else ("▶️" if t["status"] == "doing" else "▫️")
|
||||
due = f" · до {ru_day(t['due'])}" if t["due"] else ""
|
||||
mins = f" · {t['minutes']} мин" if t["minutes"] else ""
|
||||
client = f" [{t['client']}]" if t["client"] else ""
|
||||
client = f" [{client_name(t['client'])}]" if t["client"] else ""
|
||||
out.append(f"{' ' * depth}{mark} #{t['id']} {escape(t['title'])}{client}{due}{mins}")
|
||||
out += tree(t["children"], depth + 1)
|
||||
return out
|
||||
|
||||
|
||||
def subs(rows: list, monthly: dict, today: date) -> str:
|
||||
def subs(rows: list, by_client: dict, today: date) -> str:
|
||||
"""Grouped by company, each with its monthly total."""
|
||||
if not rows:
|
||||
return "Подписок пока нет. Скажи, например: «хостинг 900 рублей в месяц, списание 15-го»."
|
||||
lines = [f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / "
|
||||
f"{s['every'] if s['every'] > 1 else ''}{ {'day':'день','week':'нед.','month':'мес.','year':'год'}[s['period']] }"
|
||||
f" · {human_day(s['next_date'], today)}" for s in rows]
|
||||
lines.append("\nВ месяц: " + ", ".join(f"{v:g} {k}" for k, v in monthly.items()))
|
||||
return "\n".join(lines)
|
||||
return "Подписок пока нет. Скажи, например: «Claude Code 20 $ в месяц, списание 25-го, компания Сага»."
|
||||
per = {"day": "день", "week": "нед.", "month": "мес.", "year": "год"}
|
||||
out = []
|
||||
for client in sorted({s["client"] for s in rows}, key=lambda c: (c == "", c)):
|
||||
total = ", ".join(f"{v:g} {k}" for k, v in by_client.get(client, {}).items())
|
||||
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 ""
|
||||
out.append(f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / {every}{per[s['period']]}"
|
||||
f" · {human_day(s['next_date'], today)}")
|
||||
return "\n".join(out).strip()
|
||||
|
||||
|
||||
def routines(rows: list, today: date) -> str:
|
||||
|
||||
@@ -105,5 +105,34 @@ class Brain(unittest.TestCase):
|
||||
self.assertEqual(o.routines()[0]["every_days"], 30)
|
||||
|
||||
|
||||
class Company(unittest.TestCase):
|
||||
def test_sub_company_and_totals(self):
|
||||
o = fresh()
|
||||
o.add_sub("Claude Code", 20, "2026-10-25", currency="USD", client="Saga")
|
||||
o.add_sub("Домен", 1200, "2026-11-15", period="year")
|
||||
self.assertEqual(o.subs()[0]["client"], "saga")
|
||||
self.assertEqual(o.monthly_by_client(), {"saga": {"USD": 20.0}, "": {"RUB": 100.0}})
|
||||
text = fmt.subs(o.subs(), o.monthly_by_client(), date(2026, 10, 10))
|
||||
self.assertIn("<b>Сага</b>", text)
|
||||
self.assertIn("Без компании", text)
|
||||
plan = {"actions": [{"op": "update_sub", "id": 2, "client": "home"}]}
|
||||
brain.apply_plan(o, plan)
|
||||
self.assertEqual(o.sub(2)["client"], "home")
|
||||
|
||||
def test_old_database_gets_the_column(self):
|
||||
import sqlite3, tempfile
|
||||
path = tempfile.mktemp(suffix=".db")
|
||||
con = sqlite3.connect(path)
|
||||
con.execute("CREATE TABLE subscriptions (id INTEGER PRIMARY KEY, name TEXT NOT NULL, amount REAL NOT NULL DEFAULT 0, "
|
||||
"currency TEXT NOT NULL DEFAULT 'RUB', period TEXT NOT NULL DEFAULT 'month', every INTEGER NOT NULL DEFAULT 1, "
|
||||
"next_date TEXT NOT NULL, remind_days INTEGER NOT NULL DEFAULT 3, notes TEXT NOT NULL DEFAULT '', "
|
||||
"active INTEGER NOT NULL DEFAULT 1)")
|
||||
con.execute("INSERT INTO subscriptions (name, next_date) VALUES ('old', '2026-11-01')")
|
||||
con.commit(); con.close()
|
||||
o = Ops(connect(path))
|
||||
self.assertEqual(o.subs()[0]["client"], "")
|
||||
os.remove(path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user