From 18aed2beb9a73960ec43803c831e40baf36e97cd Mon Sep 17 00:00:00 2001 From: maksarsanjeev Date: Sat, 10 Oct 2026 03:42:41 +0300 Subject: [PATCH] Subscriptions belong to a company; BroV owns its Keychain token MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- NotchBuddy/Sources/App/Ops.swift | 31 +++++++++++-- NotchBuddy/Sources/App/OpsOverview.swift | 59 ++++++++++++++++-------- ops/brovops/app.py | 4 +- ops/brovops/brain.py | 23 +++++---- ops/brovops/core.py | 37 +++++++++++---- ops/brovops/db.py | 7 ++- ops/brovops/fmt.py | 26 +++++++---- ops/tests/test_core.py | 29 ++++++++++++ 8 files changed, 161 insertions(+), 55 deletions(-) diff --git a/NotchBuddy/Sources/App/Ops.swift b/NotchBuddy/Sources/App/Ops.swift index 2b1be77..8dfad96 100644 --- a/NotchBuddy/Sources/App/Ops.swift +++ b/NotchBuddy/Sources/App/Ops.swift @@ -52,6 +52,7 @@ struct OpsSub: Identifiable, Equatable { var every: Int var next: String var remindDays: Int + var client: String } struct OpsRoutine: Identifiable, Equatable { @@ -76,13 +77,30 @@ final class OpsClient: ObservableObject { @Published var tasks: [OpsTask] = [] @Published var subs: [OpsSub] = [] @Published var routines: [OpsRoutine] = [] + /// Subscriptions per month by company ("" = none), then by currency. + @Published var byClient: [String: [String: Double]] = [:] var fullLoaded = false var baseURL: String { (UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines) } /// Read once from the Keychain, updated by Settings. - var token: String = Keychain.load(key: OpsClient.tokenKey) ?? "" + var token: String = OpsClient.loadToken() + + /// A token handed over in ~/Library/Application Support/BroV/ops-token.import (by the + /// installer) is saved by BroV itself — so BroV owns the Keychain item and macOS never + /// asks for the password — and the file is deleted. + private static func loadToken() -> String { + let file = FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/Application Support/BroV/ops-token.import") + if let t = try? String(contentsOf: file, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines), + !t.isEmpty { + Keychain.save(key: tokenKey, value: t) + try? FileManager.default.removeItem(at: file) + return t + } + return Keychain.load(key: tokenKey) ?? "" + } var configured: Bool { !baseURL.isEmpty && !token.isEmpty } private func request(_ path: String, body: [String: Any]? = nil, timeout: TimeInterval = 8) async -> Any? { @@ -138,7 +156,11 @@ final class OpsClient: ObservableObject { subs = (j["subs"] as? [[String: Any]] ?? []).map { d in OpsSub(id: d["id"] as? Int ?? 0, name: d["name"] as? String ?? "", amount: (d["amount"] as? NSNumber)?.doubleValue ?? 0, currency: d["currency"] as? String ?? "RUB", period: d["period"] as? String ?? "month", - every: d["every"] as? Int ?? 1, next: d["next_date"] as? String ?? "", remindDays: d["remind_days"] as? Int ?? 3) + every: d["every"] as? Int ?? 1, next: d["next_date"] as? String ?? "", remindDays: d["remind_days"] as? Int ?? 3, + client: d["client"] as? String ?? "") + } + byClient = (j["by_client"] as? [String: [String: Any]] ?? [:]).mapValues { m in + m.compactMapValues { ($0 as? NSNumber)?.doubleValue } } } if let arr = await request("/api/routines") as? [[String: Any]] { @@ -186,6 +208,9 @@ final class OpsClient: ObservableObject { f.numberStyle = .decimal; f.groupingSeparator = " "; f.maximumFractionDigits = v.rounded() == v ? 0 : 2 return f.string(from: NSNumber(value: v)) ?? "\(v)" } + static func clientName(_ c: String) -> String { + ["saga": "Сага", "planet9": "Planet9", "home": "Дом"][c] ?? c + } static func symbol(_ c: String) -> String { ["RUB": "₽", "USD": "$", "EUR": "€"][c.uppercased()] ?? c } @@ -436,7 +461,7 @@ struct OpsRow: View { var parts: [String] = [] if overdue, let d = Self.daysLate(item.date) { parts.append("просрочено на \(d) дн.") } else { parts.append(OpsClient.ruDay(item.date)) } if let a = item.amount { parts.append("\(OpsClient.amount(a)) \(OpsClient.symbol(item.currency ?? ""))") } - if !item.client.isEmpty { parts.append(item.client) } + if !item.client.isEmpty { parts.append(OpsClient.clientName(item.client)) } return parts.joined(separator: " · ") } diff --git a/NotchBuddy/Sources/App/OpsOverview.swift b/NotchBuddy/Sources/App/OpsOverview.swift index 8335ab0..d71c555 100644 --- a/NotchBuddy/Sources/App/OpsOverview.swift +++ b/NotchBuddy/Sources/App/OpsOverview.swift @@ -290,7 +290,7 @@ struct OpsCalendar: View { for t in ts { if let due = t.due { add(OpsCalItem(kind: "task", ref: t.id, title: t.title, - detail: t.client.isEmpty ? "задача" : "задача · \(t.client)", date: due, projected: false)) + detail: t.client.isEmpty ? "задача" : "задача · \(OpsClient.clientName(t.client))", date: due, projected: false)) } walk(t.children) } @@ -301,7 +301,9 @@ struct OpsCalendar: View { var first = true while d <= end { add(OpsCalItem(kind: "sub", ref: s.id, title: s.name, - detail: "\(OpsClient.amount(s.amount)) \(OpsClient.symbol(s.currency))", date: Self.iso(d), projected: !first)) + detail: "\(OpsClient.amount(s.amount)) \(OpsClient.symbol(s.currency))" + + (s.client.isEmpty ? "" : " · \(OpsClient.clientName(s.client))"), + date: Self.iso(d), projected: !first)) first = false let comp: Calendar.Component = ["day": .day, "week": .weekOfYear, "year": .year][s.period] ?? .month d = Self.cal.date(byAdding: comp, value: max(1, s.every), to: d) ?? end.addingTimeInterval(1) @@ -372,7 +374,7 @@ struct OpsTaskRow: View { .padding(.horizontal, 6).background(Capsule().fill(Color.white.opacity(0.06))) } if !task.client.isEmpty { - Text(task.client).font(.system(size: 10.5)).foregroundColor(Color(hex: "#A78BFA")) + Text(OpsClient.clientName(task.client)).font(.system(size: 10.5)).foregroundColor(Color(hex: "#A78BFA")) .padding(.horizontal, 6).background(Capsule().fill(Color(hex: "#A78BFA").opacity(0.14))) } Spacer() @@ -412,37 +414,54 @@ struct OpsSubList: View { @ObservedObject private var ops = OpsClient.shared private let period = ["day": "день", "week": "нед.", "month": "мес.", "year": "год"] + /// Companies with subscriptions; "" (no company) last. + private var companies: [String] { + Array(Set(ops.subs.map(\.client))).sorted { ($0.isEmpty ? 1 : 0, $0) < ($1.isEmpty ? 1 : 0, $1) } + } + var body: some View { VStack(alignment: .leading, spacing: 8) { HStack(alignment: .firstTextBaseline) { Text("Подписки").font(.system(size: 18, weight: .semibold)) Spacer() if !ops.agenda.monthly.isEmpty { - Text("в месяц: " + OpsClient.money(ops.agenda.monthly)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) + Text("всего в месяц: " + OpsClient.money(ops.agenda.monthly)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) } } if ops.subs.isEmpty { - Text("Подписок нет. Запиши ниже: «хостинг 900 ₽ в месяц, списание 20-го»") + Text("Подписок нет. Запиши ниже: «Claude Code 20 $ в месяц, списание 25-го, компания Сага»") .font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) } ScrollView(.vertical, showsIndicators: false) { - VStack(spacing: 2) { - ForEach(ops.subs) { s in - HStack(spacing: 10) { - Image(systemName: "creditcard").foregroundColor(Color(hex: "#60A5FA")) - Text(s.name).font(.system(size: 13, weight: .medium)) + VStack(alignment: .leading, spacing: 2) { + ForEach(companies, id: \.self) { c in + HStack(alignment: .firstTextBaseline) { + Text(c.isEmpty ? "Без компании" : OpsClient.clientName(c)) + .font(.system(size: 13, weight: .semibold)) + .foregroundColor(Color(hex: c.isEmpty ? "#8E939C" : "#A78BFA")) Spacer() - Text("\(OpsClient.amount(s.amount)) \(OpsClient.symbol(s.currency)) / \(s.every > 1 ? "\(s.every) " : "")\(period[s.period] ?? s.period)") - .font(.system(size: 12)).frame(width: 150, alignment: .trailing) - Text(OpsClient.ruDay(s.next)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) - .frame(width: 90, alignment: .trailing) - Text("напомнить за \(s.remindDays) дн.").font(.system(size: 11)).foregroundColor(Color(hex: "#6B7079")) - .frame(width: 120, alignment: .trailing) - Button("Оплачено") { Task { await ops.act(["op": "pay_sub", "id": s.id]) } } - .buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA")) + if let m = ops.byClient[c], !m.isEmpty { + Text(OpsClient.money(m) + " / мес").font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) + } + } + .padding(.top, 10).padding(.bottom, 2).padding(.horizontal, 4) + ForEach(ops.subs.filter { $0.client == c }) { s in + HStack(spacing: 10) { + Image(systemName: "creditcard").foregroundColor(Color(hex: "#60A5FA")) + Text(s.name).font(.system(size: 13, weight: .medium)) + Spacer() + Text("\(OpsClient.amount(s.amount)) \(OpsClient.symbol(s.currency)) / \(s.every > 1 ? "\(s.every) " : "")\(period[s.period] ?? s.period)") + .font(.system(size: 12)).frame(width: 150, alignment: .trailing) + Text(OpsClient.ruDay(s.next)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) + .frame(width: 90, alignment: .trailing) + Text("напомнить за \(s.remindDays) дн.").font(.system(size: 11)).foregroundColor(Color(hex: "#6B7079")) + .frame(width: 120, alignment: .trailing) + Button("Оплачено") { Task { await ops.act(["op": "pay_sub", "id": s.id]) } } + .buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA")) + } + .padding(.horizontal, 10).padding(.vertical, 8) + .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04))) } - .padding(.horizontal, 10).padding(.vertical, 8) - .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04))) } } } diff --git a/ops/brovops/app.py b/ops/brovops/app.py index 63510a7..2e91f82 100644 --- a/ops/brovops/app.py +++ b/ops/brovops/app.py @@ -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): diff --git a/ops/brovops/brain.py b/ops/brovops/brain.py index c59b1f6..adbc22f 100644 --- a/ops/brovops/brain.py +++ b/ops/brovops/brain.py @@ -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")) diff --git a/ops/brovops/core.py b/ops/brovops/core.py index 8f1871f..7cd388a 100644 --- a/ops/brovops/core.py +++ b/ops/brovops/core.py @@ -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"]}) diff --git a/ops/brovops/db.py b/ops/brovops/db.py index 53098cf..711def0 100644 --- a/ops/brovops/db.py +++ b/ops/brovops/db.py @@ -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 diff --git a/ops/brovops/fmt.py b/ops/brovops/fmt.py index 7fc0eaa..38d9d6f 100644 --- a/ops/brovops/fmt.py +++ b/ops/brovops/fmt.py @@ -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{escape(client_name(client) or 'Без компании')} — {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: diff --git a/ops/tests/test_core.py b/ops/tests/test_core.py index 3c34012..d6ca623 100644 --- a/ops/tests/test_core.py +++ b/ops/tests/test_core.py @@ -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("Сага", 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()