import SwiftUI import AppKit // MARK: - BroV Ops (the homelab manager) in the notch // // The service runs on the homelab VM (ops/ in this repo): tasks with subtasks and a // timer, subscriptions and payments, routines. BroV talks to its small HTTP API on the // home network (or through the "Дом" tunnel). Click on the Memoji → menu → «Дела». struct OpsItem: Identifiable, Equatable { var kind: String // task | sub | routine var ref: Int var title: String var date: String var client: String var amount: Double? var currency: String? var id: String { "\(kind)-\(ref)" } } struct OpsAgenda: Equatable { var overdue: [OpsItem] = [] var today: [OpsItem] = [] var soon: [OpsItem] = [] var running: (id: Int, title: String, minutes: Int)? var monthly: [String: Double] = [:] static func == (a: OpsAgenda, b: OpsAgenda) -> Bool { a.overdue == b.overdue && a.today == b.today && a.soon == b.soon && a.running?.id == b.running?.id && a.running?.minutes == b.running?.minutes && a.monthly == b.monthly } } @MainActor final class OpsClient: ObservableObject { static let shared = OpsClient() static let urlKey = "opsURL" static let tokenKey = "brov-ops-token" @Published var agenda = OpsAgenda() @Published var reachable: Bool? = nil // nil = not configured @Published var busy = false @Published var lastAnswer: String? 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 configured: Bool { !baseURL.isEmpty && !token.isEmpty } private func request(_ path: String, body: [String: Any]? = nil, timeout: TimeInterval = 8) async -> Any? { guard configured, let url = URL(string: baseURL + path) else { reachable = nil; return nil } var req = URLRequest(url: url, timeoutInterval: timeout) req.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") if let body { req.httpMethod = "POST" req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpBody = try? JSONSerialization.data(withJSONObject: body) } do { let (data, resp) = try await URLSession.shared.data(for: req) guard (resp as? HTTPURLResponse)?.statusCode == 200 else { reachable = false; return nil } reachable = true return try JSONSerialization.jsonObject(with: data) } catch { reachable = false return nil } } func refresh() async { guard let j = await request("/api/agenda") as? [String: Any] else { return } func items(_ key: String) -> [OpsItem] { (j[key] as? [[String: Any]] ?? []).compactMap { d in guard let kind = d["kind"] as? String, let ref = d["id"] as? Int else { return nil } return OpsItem(kind: kind, ref: ref, title: d["title"] as? String ?? "", date: d["date"] as? String ?? "", client: d["client"] as? String ?? "", amount: d["amount"] as? Double, currency: d["currency"] as? String) } } var a = OpsAgenda(overdue: items("overdue"), today: items("due_today"), soon: items("soon")) if let r = j["running"] as? [String: Any], let id = r["id"] as? Int { a.running = (id, r["title"] as? String ?? "", r["minutes"] as? Int ?? 0) } a.monthly = j["monthly_cost"] as? [String: Double] ?? [:] agenda = a } /// Free text → the service's Claude brain (same as Telegram). func say(_ text: String) async { busy = true defer { busy = false } let r = await request("/api/say", body: ["text": text], timeout: 120) as? [String: Any] lastAnswer = r?["answer"] as? String ?? (reachable == false ? "Сервис дел не отвечает." : nil) await refresh() } /// A direct action from a button: done / paid / timer / snooze. func act(_ body: [String: Any]) async { let r = await request("/api/action", body: body) as? [String: Any] if let lines = r?["result"] as? [String] { lastAnswer = lines.joined(separator: "\n") } SoundEngine.shared.play("pop") await refresh() } func done(_ it: OpsItem) async { switch it.kind { case "task": await act(["op": "complete_task", "id": it.ref]) case "sub": await act(["op": "pay_sub", "id": it.ref]) default: await act(["op": "done_routine", "id": it.ref]) } } var attentionCount: Int { agenda.overdue.count + agenda.today.count } } // MARK: - Menu on the Memoji struct BroMenu: View { @ObservedObject var state: AppState @ObservedObject private var ops = OpsClient.shared @ObservedObject private var coffee = Coffee.shared @State private var page = 0 // 0 = menu, 1 = «Дела» var body: some View { Group { if page == 1 { OpsPanel(state: state, back: { withAnimation(.easeOut(duration: 0.15)) { page = 0 } }) } else { VStack(alignment: .leading, spacing: 2) { FuncRow(symbol: "checklist", color: "#D97757", title: "Дела", subtitle: opsSubtitle, hint: ops.attentionCount > 0 ? "\(ops.attentionCount)" : nil) { withAnimation(.easeOut(duration: 0.15)) { page = 1 } } if let r = ops.agenda.running { FuncRow(symbol: "stop.circle", color: "#F4505E", title: "Стоп таймер", subtitle: "\(r.title) · \(r.minutes) мин", hint: nil) { Task { await ops.act(["op": "stop_timer"]) } } } Divider().padding(.vertical, 4) FuncRow(symbol: "eyedropper", color: "#F472B6", title: "Пипетка", subtitle: "цвет пикселя во всех форматах", hint: nil) { state.botMenuOpen = false ColorPicking.start(state: state) } FuncRow(symbol: "character.bubble", color: "#60A5FA", title: "Переводчик", subtitle: "выделенный текст RU ↔ EN", hint: "⌥`") { state.botMenuOpen = false TranslatorRun.start(state: state) } FuncRow(symbol: coffee.on ? "cup.and.saucer.fill" : "cup.and.saucer", color: "#D97757", title: coffee.on ? "Кофе: включён" : "Кофе-режим", subtitle: coffee.on ? "Мак не засыпает — нажми, чтобы выключить" : "не давать Маку засыпать", hint: nil) { coffee.toggle() } } .padding(8) .frame(width: 290) } } .notchPopoverStyle() .task { await ops.refresh() } } private var opsSubtitle: String { guard ops.configured else { return "подключи сервис в Настройках → Чат" } if ops.reachable == false { return "сервис не отвечает" } let a = ops.agenda if a.overdue.isEmpty && a.today.isEmpty { return a.soon.isEmpty ? "ничего не горит" : "на неделе: \(a.soon.count)" } return [a.overdue.isEmpty ? nil : "просрочено \(a.overdue.count)", a.today.isEmpty ? nil : "сегодня \(a.today.count)"].compactMap { $0 }.joined(separator: " · ") } } // MARK: - «Дела» panel struct OpsPanel: View { @ObservedObject var state: AppState let back: () -> Void @ObservedObject private var ops = OpsClient.shared @State private var text = "" @FocusState private var focused: Bool var body: some View { VStack(alignment: .leading, spacing: 8) { HStack(spacing: 6) { Button(action: back) { Image(systemName: "chevron.left").font(.system(size: 11, weight: .semibold)) } .buttonStyle(.plain) Text("Дела").font(.system(size: 14, weight: .semibold)) Spacer() if ops.busy { ProgressView().controlSize(.mini) } Button { Task { await ops.refresh() } } label: { Image(systemName: "arrow.clockwise").font(.system(size: 11)) } .buttonStyle(.plain) .help("Обновить") } .foregroundColor(Color(hex: "#B0B5BE")) if !ops.configured { Text("Сервис дел не подключён. Настройки → Чат → «Дела (хоумлаб)»: адрес и токен из /etc/brov-ops/config.env на ВМ.") .font(.system(size: 11.5)).foregroundColor(Color(hex: "#B0B5BE")) .fixedSize(horizontal: false, vertical: true) } else if ops.reachable == false { Text("Сервис дел не отвечает. Ты не дома? Включи сеть «Дом» в 🌐.") .font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C")) .fixedSize(horizontal: false, vertical: true) } if let r = ops.agenda.running { HStack(spacing: 8) { Image(systemName: "timer").foregroundColor(Color(hex: "#34D399")) Text(r.title).font(.system(size: 12, weight: .semibold)).lineLimit(1) Text("\(r.minutes) мин").font(.system(size: 11)).monospacedDigit().foregroundColor(Color(hex: "#8E939C")) Spacer() Button("Стоп") { Task { await ops.act(["op": "stop_timer"]) } } .buttonStyle(.plain).font(.system(size: 11, weight: .medium)).foregroundColor(Color(hex: "#F4505E")) } .padding(8) .background(RoundedRectangle(cornerRadius: 8).fill(Color(hex: "#34D399").opacity(0.10))) } ScrollView(.vertical, showsIndicators: false) { VStack(alignment: .leading, spacing: 2) { section("ПРОСРОЧЕНО", ops.agenda.overdue, "#F4505E") section("СЕГОДНЯ", ops.agenda.today, "#F5A524") section("НА НЕДЕЛЕ", ops.agenda.soon, "#8E939C") if ops.configured && ops.reachable == true && ops.agenda.overdue.isEmpty && ops.agenda.today.isEmpty && ops.agenda.soon.isEmpty { Text("На неделю ничего не горит 👌").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) .padding(.vertical, 6) } } } .frame(maxHeight: 260) if let a = ops.lastAnswer, !a.isEmpty { Text(a).font(.system(size: 11)).foregroundColor(Color(hex: "#B0B5BE")) .textSelection(.enabled) .fixedSize(horizontal: false, vertical: true) .padding(8) .frame(maxWidth: .infinity, alignment: .leading) .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.05))) } HStack(spacing: 6) { TextField("Записать: «продлить домен до 15.11, 1200 ₽»", text: $text) .textFieldStyle(.plain) .font(.system(size: 12.5)) .focused($focused) .onSubmit(send) Button(action: send) { Image(systemName: "arrow.up").font(.system(size: 10, weight: .bold)) .foregroundColor(Color(hex: "#0B0C0E")) .frame(width: 20, height: 20) .background(Circle().fill(Color(hex: text.isEmpty ? "#5F646D" : "#D97757"))) } .buttonStyle(.plain) .disabled(text.isEmpty || ops.busy || !ops.configured) } .padding(.horizontal, 10).padding(.vertical, 7) .background(RoundedRectangle(cornerRadius: 10).fill(Color.white.opacity(0.07))) } .padding(12) .frame(width: 380) .foregroundColor(Color(hex: "#F5F6F8")) .onAppear { focused = true } } private func send() { let t = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !t.isEmpty else { return } text = "" Task { await ops.say(t) } } @ViewBuilder private func section(_ title: String, _ items: [OpsItem], _ color: String) -> some View { if !items.isEmpty { Text(title).font(.system(size: 9.5, weight: .bold)).foregroundColor(Color(hex: color)) .padding(.top, 6).padding(.bottom, 2) ForEach(items) { OpsRow(item: $0) } } } } struct OpsRow: View { let item: OpsItem @ObservedObject private var ops = OpsClient.shared @State private var hovered = false private var icon: String { switch item.kind { case "sub": return "creditcard"; case "routine": return "arrow.triangle.2.circlepath"; default: return "pin" } } var body: some View { HStack(spacing: 8) { Image(systemName: icon).font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C")).frame(width: 14) VStack(alignment: .leading, spacing: 1) { Text(item.title).font(.system(size: 12, weight: .medium)).lineLimit(1) Text(subtitle).font(.system(size: 10.5)).foregroundColor(Color(hex: "#6B7079")).lineLimit(1) } Spacer(minLength: 4) if hovered { if item.kind == "task" { small("timer", "Засечь время") { Task { await ops.act(["op": "start_timer", "id": item.ref]) } } } small("clock.arrow.circlepath", "Завтра") { Task { await ops.act(["op": "snooze", "kind": item.kind, "id": item.ref, "days": 1]) } } } small(item.kind == "sub" ? "rublesign.circle" : "checkmark.circle", item.kind == "sub" ? "Оплачено" : "Сделано") { Task { await ops.done(item) } } } .padding(.horizontal, 6).padding(.vertical, 5) .background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(hovered ? 0.06 : 0))) .onHover { hovered = $0 } } private var subtitle: String { var parts = [item.date] if let a = item.amount { parts.append("\(a.formatted()) \(item.currency ?? "")") } if !item.client.isEmpty { parts.append(item.client) } return parts.joined(separator: " · ") } private func small(_ symbol: String, _ help: String, _ action: @escaping () -> Void) -> some View { Button(action: action) { Image(systemName: symbol).font(.system(size: 13)).foregroundColor(Color(hex: "#B0B5BE")) } .buttonStyle(.plain) .help(help) } } // MARK: - Settings struct OpsSettingsBox: View { @State private var url = UserDefaults.standard.string(forKey: OpsClient.urlKey) ?? "" @State private var token = Keychain.load(key: OpsClient.tokenKey) ?? "" @State private var status: String? var body: some View { GroupBox("Дела (хоумлаб)") { VStack(alignment: .leading, spacing: 8) { Text("Сервис дел на виртуалке хоумлаба: задачи, подписки, регламент. Адрес вида http://192.168.10.50:8787, токен — API_TOKEN из /etc/brov-ops/config.env на ВМ (хранится в Связке ключей).") .font(.system(size: 11)).foregroundColor(.secondary) .fixedSize(horizontal: false, vertical: true) TextField("Адрес сервиса", text: $url).textFieldStyle(.roundedBorder) SecureField("Токен", text: $token).textFieldStyle(.roundedBorder) HStack { Button("Сохранить и проверить") { UserDefaults.standard.set(url.trimmingCharacters(in: .whitespacesAndNewlines), forKey: OpsClient.urlKey) let t = token.trimmingCharacters(in: .whitespacesAndNewlines) Keychain.save(key: OpsClient.tokenKey, value: t) OpsClient.shared.token = t Task { await OpsClient.shared.refresh() status = OpsClient.shared.reachable == true ? "✓ Подключено" : "✗ Не отвечает или неверный токен" } } .buttonStyle(.borderedProminent) if let status { Text(status).font(.system(size: 11)).foregroundColor(.secondary) } } } .padding(6) } } }