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:
maksarsanjeev
2026-10-10 03:42:41 +03:00
parent 36326ba0b6
commit 18aed2beb9
8 changed files with 161 additions and 55 deletions
+28 -3
View File
@@ -52,6 +52,7 @@ struct OpsSub: Identifiable, Equatable {
var every: Int var every: Int
var next: String var next: String
var remindDays: Int var remindDays: Int
var client: String
} }
struct OpsRoutine: Identifiable, Equatable { struct OpsRoutine: Identifiable, Equatable {
@@ -76,13 +77,30 @@ final class OpsClient: ObservableObject {
@Published var tasks: [OpsTask] = [] @Published var tasks: [OpsTask] = []
@Published var subs: [OpsSub] = [] @Published var subs: [OpsSub] = []
@Published var routines: [OpsRoutine] = [] @Published var routines: [OpsRoutine] = []
/// Subscriptions per month by company ("" = none), then by currency.
@Published var byClient: [String: [String: Double]] = [:]
var fullLoaded = false var fullLoaded = false
var baseURL: String { var baseURL: String {
(UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines) (UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
} }
/// Read once from the Keychain, updated by Settings. /// 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 } var configured: Bool { !baseURL.isEmpty && !token.isEmpty }
private func request(_ path: String, body: [String: Any]? = nil, timeout: TimeInterval = 8) async -> Any? { 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 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, 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", 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]] { 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 f.numberStyle = .decimal; f.groupingSeparator = " "; f.maximumFractionDigits = v.rounded() == v ? 0 : 2
return f.string(from: NSNumber(value: v)) ?? "\(v)" 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 { static func symbol(_ c: String) -> String {
["RUB": "₽", "USD": "$", "EUR": "€"][c.uppercased()] ?? c ["RUB": "₽", "USD": "$", "EUR": "€"][c.uppercased()] ?? c
} }
@@ -436,7 +461,7 @@ struct OpsRow: View {
var parts: [String] = [] var parts: [String] = []
if overdue, let d = Self.daysLate(item.date) { parts.append("просрочено на \(d) дн.") } else { parts.append(OpsClient.ruDay(item.date)) } 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 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: " · ") return parts.joined(separator: " · ")
} }
+26 -7
View File
@@ -290,7 +290,7 @@ struct OpsCalendar: View {
for t in ts { for t in ts {
if let due = t.due { if let due = t.due {
add(OpsCalItem(kind: "task", ref: t.id, title: t.title, 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) walk(t.children)
} }
@@ -301,7 +301,9 @@ struct OpsCalendar: View {
var first = true var first = true
while d <= end { while d <= end {
add(OpsCalItem(kind: "sub", ref: s.id, title: s.name, 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 first = false
let comp: Calendar.Component = ["day": .day, "week": .weekOfYear, "year": .year][s.period] ?? .month 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) 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))) .padding(.horizontal, 6).background(Capsule().fill(Color.white.opacity(0.06)))
} }
if !task.client.isEmpty { 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))) .padding(.horizontal, 6).background(Capsule().fill(Color(hex: "#A78BFA").opacity(0.14)))
} }
Spacer() Spacer()
@@ -412,22 +414,38 @@ struct OpsSubList: View {
@ObservedObject private var ops = OpsClient.shared @ObservedObject private var ops = OpsClient.shared
private let period = ["day": "день", "week": "нед.", "month": "мес.", "year": "год"] 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 { var body: some View {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .firstTextBaseline) { HStack(alignment: .firstTextBaseline) {
Text("Подписки").font(.system(size: 18, weight: .semibold)) Text("Подписки").font(.system(size: 18, weight: .semibold))
Spacer() Spacer()
if !ops.agenda.monthly.isEmpty { 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 { if ops.subs.isEmpty {
Text("Подписок нет. Запиши ниже: «хостинг 900 ₽ в месяц, списание 20-го»") Text("Подписок нет. Запиши ниже: «Claude Code 20 $ в месяц, списание 25-го, компания Сага»")
.font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) .font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
} }
ScrollView(.vertical, showsIndicators: false) { ScrollView(.vertical, showsIndicators: false) {
VStack(spacing: 2) { VStack(alignment: .leading, spacing: 2) {
ForEach(ops.subs) { s in 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()
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) { HStack(spacing: 10) {
Image(systemName: "creditcard").foregroundColor(Color(hex: "#60A5FA")) Image(systemName: "creditcard").foregroundColor(Color(hex: "#60A5FA"))
Text(s.name).font(.system(size: 13, weight: .medium)) Text(s.name).font(.system(size: 13, weight: .medium))
@@ -448,6 +466,7 @@ struct OpsSubList: View {
} }
} }
} }
}
} }
struct OpsRoutineList: View { struct OpsRoutineList: View {
+2 -2
View File
@@ -108,7 +108,7 @@ async def cmd_tasks(update: Update, ctx):
@owner_only @owner_only
async def cmd_subs(update: Update, ctx): async def cmd_subs(update: Update, ctx):
with lock: 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) await send_long(update, text)
@@ -254,7 +254,7 @@ async def api_tasks(request):
async def api_subs(request): async def api_subs(request):
check_auth(request) check_auth(request)
with lock: 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): async def api_routines(request):
+13 -10
View File
@@ -6,7 +6,7 @@ import os
import subprocess import subprocess
import tempfile import tempfile
from .core import Ops, OpsError, ru_day from .core import Ops, OpsError, client_name, ru_day
INSTRUCTIONS = """Ты — помощник-менеджер системного администратора. Пользователь пишет или говорит INSTRUCTIONS = """Ты — помощник-менеджер системного администратора. Пользователь пишет или говорит
по-русски, коротко и неформально. Твоя задача — превратить сообщение в действия над его базой дел. по-русски, коротко и неформально. Твоя задача — превратить сообщение в действия над его базой дел.
@@ -22,9 +22,10 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
- reopen_task {id} - reopen_task {id}
- start_timer {id} засечь время работы над задачей (предыдущий таймер остановится) - start_timer {id} засечь время работы над задачей (предыдущий таймер остановится)
- stop_timer {} - stop_timer {}
- add_sub {name, amount, next_date, period?, every?, currency?, remind_days?, notes?} - add_sub {name, amount, next_date, client?, period?, every?, currency?, remind_days?, notes?}
period: day | week | month | year (по умолчанию month); currency по умолчанию RUB period: day | week | month | year (по умолчанию month); currency по умолчанию RUB;
- update_sub {id, name?, amount?, next_date?, period?, every?, currency?, remind_days?, notes?, active?} 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?} оплачено: следующая дата сдвинется сама
- add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…) - add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…)
- done_routine {id, note?} - done_routine {id, note?}
@@ -33,7 +34,8 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
Правила: Правила:
- В полях действий даты — строго ГГГГ-ММ-ДД. «завтра», «в пятницу», «15-го» переводи от сегодняшней даты. - В полях действий даты — строго ГГГГ-ММ-ДД. «завтра», «в пятницу», «15-го» переводи от сегодняшней даты.
- В тексте reply даты пиши как ДД.ММ.ГГГГ (например 15.11.2026). - В тексте reply даты пиши как ДД.ММ.ГГГГ (например 15.11.2026).
- client — одно из: saga, planet9, home, или пусто. - client (у задач и подписок) — компания: saga (Сага), planet9 (Planet9, «планета»), home (дом, личное),
другое название — латиницей в нижнем регистре; если не сказано — пусто.
- Если пользователь просто спрашивает (что на сегодня, сколько трачу, что просрочено) — - Если пользователь просто спрашивает (что на сегодня, сколько трачу, что просрочено) —
actions пустой, ответ в reply по данным ниже. actions пустой, ответ в reply по данным ниже.
- Если непонятно, что сделать, — actions пустой, в reply переспроси. - Если непонятно, что сделать, — actions пустой, в reply переспроси.
@@ -57,10 +59,10 @@ def snapshot(ops: Ops) -> str:
f"{t['minutes']}м | {t['status']}{run}") f"{t['minutes']}м | {t['status']}{run}")
walk(t["children"], depth + 1) walk(t["children"], depth + 1)
walk(ops.task_tree(), 0) walk(ops.task_tree(), 0)
lines += ["", "Подписки (id, сумма, период, следующее списание):"] lines += ["", "Подписки (id, сумма, период, следующее списание, компания):"]
for s in ops.subs(active_only=False): for s in ops.subs(active_only=False):
lines.append(f"- #{s['id']} {s['name']} | {s['amount']:g} {s['currency']} | каждые {s['every']} {s['period']} | " 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.append(f"Итого в месяц: {ops.monthly_cost()}")
lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"] lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"]
for r in ops.routines(): 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 " (не шёл)")) done.append(f"⏹ таймер остановлен" + (f": #{t['id']} {t['title']}" if t else " (не шёл)"))
elif op == "add_sub": elif op == "add_sub":
s = ops.add_sub(**_only(args, "name", "amount", "next_date", "period", "every", "currency", s = ops.add_sub(**_only(args, "name", "amount", "next_date", "period", "every", "currency",
"remind_days", "notes")) "remind_days", "notes", "client"))
done.append(f"+ подписка #{s['id']} {s['name']}: {s['amount']:g} {s['currency']}, след. {ru_day(s['next_date'])}") 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": elif op == "update_sub":
s = ops.update_sub(int(a["id"]), **_only(args, "name", "amount", "next_date", "period", "every", 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']}") done.append(f"✎ подписка #{s['id']} {s['name']}")
elif op == "pay_sub": elif op == "pay_sub":
s = ops.pay_sub(int(a["id"]), a.get("amount"), a.get("paid_on")) s = ops.pay_sub(int(a["id"]), a.get("amount"), a.get("paid_on"))
+28 -9
View File
@@ -28,6 +28,13 @@ def add_period(d: date, period: str, every: int = 1) -> date:
raise OpsError(f"неизвестный период: {period}") 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: def ru_day(iso) -> str:
"""2026-11-15 → 15.11.2026 (how dates are shown; storage stays ISO).""" """2026-11-15 → 15.11.2026 (how dates are shown; storage stays ISO)."""
if not iso: if not iso:
@@ -188,7 +195,7 @@ class Ops:
return dict(row) return dict(row)
def add_sub(self, name: str, amount: float, next_date, period: str = "month", every: int = 1, 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(): if not (name or "").strip():
raise OpsError("у подписки нет названия") raise OpsError("у подписки нет названия")
if period not in PERIODS: if period not in PERIODS:
@@ -197,14 +204,15 @@ class Ops:
if not d: if not d:
raise OpsError("нужна дата следующего списания") raise OpsError("нужна дата следующего списания")
cur = self.con.execute( cur = self.con.execute(
"""INSERT INTO subscriptions (name, amount, currency, period, every, next_date, remind_days, notes) """INSERT INTO subscriptions (name, amount, currency, period, every, next_date, remind_days, notes, client)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(name.strip(), float(amount or 0), (currency or "RUB").upper(), period, max(1, int(every or 1)), (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) return self.sub(cur.lastrowid)
def update_sub(self, sub_id: int, **fields) -> dict: 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 = [], [] sets, vals = [], []
for k, v in fields.items(): for k, v in fields.items():
if k not in allowed or v is None: if k not in allowed or v is None:
@@ -213,6 +221,8 @@ class Ops:
v = parse_day(v).isoformat() v = parse_day(v).isoformat()
if k == "period" and v not in PERIODS: if k == "period" and v not in PERIODS:
raise OpsError(f"период может быть только {', '.join(PERIODS)}") raise OpsError(f"период может быть только {', '.join(PERIODS)}")
if k == "client":
v = str(v).strip().lower()
sets.append(f"{k} = ?") sets.append(f"{k} = ?")
vals.append(v) vals.append(v)
if sets: if sets:
@@ -236,14 +246,23 @@ class Ops:
q = "SELECT * FROM subscriptions" + (" WHERE active = 1" if active_only else "") + " ORDER BY next_date" 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 [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]: def monthly_cost(self) -> dict[str, float]:
"""Active subscriptions per month, by currency.""" """Active subscriptions per month, by currency."""
per_month = {"day": 30.44, "week": 4.345, "month": 1, "year": 1 / 12}
out: dict[str, float] = {} out: dict[str, float] = {}
for s in self.subs(): 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()} 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 # MARK: - Routines
def routine(self, rid: int) -> dict: def routine(self, rid: int) -> dict:
@@ -317,7 +336,7 @@ class Ops:
d = date.fromisoformat(s["next_date"]) d = date.fromisoformat(s["next_date"])
if d <= horizon: if d <= horizon:
out[key[bucket(d)]].append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"], 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(): for r in self.routines():
d = date.fromisoformat(r["next_date"]) d = date.fromisoformat(r["next_date"])
if d <= horizon: if d <= horizon:
@@ -346,7 +365,7 @@ class Ops:
d = date.fromisoformat(s["next_date"]) d = date.fromisoformat(s["next_date"])
if d - timedelta(days=s["remind_days"]) <= today and ("sub", s["id"]) not in sent: 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"], 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(): for r in self.routines():
if date.fromisoformat(r["next_date"]) <= today and ("routine", r["id"]) not in sent: 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"]}) out.append({"kind": "routine", "id": r["id"], "title": r["title"], "date": r["next_date"]})
+6 -1
View File
@@ -30,7 +30,8 @@ CREATE TABLE IF NOT EXISTS subscriptions (
next_date TEXT NOT NULL, -- YYYY-MM-DD of the next charge next_date TEXT NOT NULL, -- YYYY-MM-DD of the next charge
remind_days INTEGER NOT NULL DEFAULT 3, remind_days INTEGER NOT NULL DEFAULT 3,
notes TEXT NOT NULL DEFAULT '', 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 ( CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
@@ -71,4 +72,8 @@ def connect(path: str) -> sqlite3.Connection:
con.execute("PRAGMA foreign_keys = ON") con.execute("PRAGMA foreign_keys = ON")
con.execute("PRAGMA journal_mode = WAL") con.execute("PRAGMA journal_mode = WAL")
con.executescript(SCHEMA) 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 return con
+16 -10
View File
@@ -2,7 +2,7 @@
from datetime import date from datetime import date
from html import escape from html import escape
from .core import ru_day from .core import client_name, ru_day
ICON = {"task": "📌", "sub": "💳", "routine": "🔁"} ICON = {"task": "📌", "sub": "💳", "routine": "🔁"}
@@ -23,7 +23,7 @@ def human_day(iso: str, today: date) -> str:
def item_line(it: dict, today: date) -> str: def item_line(it: dict, today: date) -> str:
extra = f" — {it['amount']:g} {it['currency']}" if it["kind"] == "sub" else "" 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)}" 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 "▫️") mark = "⏱" if t["running"] else ("▶️" if t["status"] == "doing" else "▫️")
due = f" · до {ru_day(t['due'])}" if t["due"] else "" due = f" · до {ru_day(t['due'])}" if t["due"] else ""
mins = f" · {t['minutes']} мин" if t["minutes"] 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.append(f"{' ' * depth}{mark} #{t['id']} {escape(t['title'])}{client}{due}{mins}")
out += tree(t["children"], depth + 1) out += tree(t["children"], depth + 1)
return out 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: if not rows:
return "Подписок пока нет. Скажи, например: «хостинг 900 рублей в месяц, списание 15-го»." return "Подписок пока нет. Скажи, например: «Claude Code 20 $ в месяц, списание 25-го, компания Сага»."
lines = [f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / " per = {"day": "день", "week": "нед.", "month": "мес.", "year": "год"}
f"{s['every'] if s['every'] > 1 else ''}{ {'day':'день','week':'нед.','month':'мес.','year':'год'}[s['period']] }" out = []
f" · {human_day(s['next_date'], today)}" for s in rows] for client in sorted({s["client"] for s in rows}, key=lambda c: (c == "", c)):
lines.append("\nВ месяц: " + ", ".join(f"{v:g} {k}" for k, v in monthly.items())) total = ", ".join(f"{v:g} {k}" for k, v in by_client.get(client, {}).items())
return "\n".join(lines) 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: def routines(rows: list, today: date) -> str:
+29
View File
@@ -105,5 +105,34 @@ class Brain(unittest.TestCase):
self.assertEqual(o.routines()[0]["every_days"], 30) 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__": if __name__ == "__main__":
unittest.main() unittest.main()