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 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: " · ")
}
+39 -20
View File
@@ -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)))
}
}
}