Files
brov-macbook/NotchBuddy/Sources/App/Ops.swift
T
maksarsanjeev 882632b7ce Subscriptions: «Оплачено?» → paid status → «repeat?»; edit and create everything
- ops: paying marks the current charge paid (paid_for, persisted) instead of jumping to
  the next date; repeat_sub moves to the next period or closes the subscription.
  Paid-and-undecided subscriptions leave reminders and show in agenda['paid'].
  update_sub can set paid; tasks reopen when their status goes back; delete for subs and
  routines (BroV only, /api/delete); /api/tasks?all=1 and /api/subs?all=1.
- Bot: «₽ Оплачено?» on reminders, then «🔁 Да, <date> / Нет, закрыть»; after paying by
  text it asks the same with buttons.
- BroV: «Оплачено?» everywhere; «Оплачено — повторить?» section under the notch;
  «Весь план»: forms to edit or create tasks (title, description, status, due, company),
  subscriptions (amount, currency, period, date, reminder, company, paid, active) and
  routines, delete with confirmation, «+» per list, done tasks on demand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 03:57:18 +03:00

581 lines
27 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 paid = false
var nextIfRepeat: String?
var id: String { "\(kind)-\(ref)" }
}
struct OpsAgenda: Equatable {
var overdue: [OpsItem] = []
var today: [OpsItem] = []
var soon: [OpsItem] = []
/// Subscriptions paid and waiting for «repeat?».
var paid: [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.paid == b.paid
&& a.running?.id == b.running?.id && a.running?.minutes == b.running?.minutes && a.monthly == b.monthly
}
}
struct OpsTask: Identifiable, Equatable {
var id: Int
var parentId: Int?
var title: String
var client: String
var status: String
var due: String?
var minutes: Int
var running: Bool
var children: [OpsTask]
var notes: String = ""
}
struct OpsSub: Identifiable, Equatable {
var id: Int
var name: String
var amount: Double
var currency: String
var period: String
var every: Int
var next: String
var remindDays: Int
var client: String
var paid = false
var nextIfRepeat = ""
var active = true
var notes = ""
}
struct OpsRoutine: Identifiable, Equatable {
var id: Int
var title: String
var everyDays: Int
var next: String
var last: String?
var notes = ""
}
@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?
/// Full lists for «Весь план» (loaded when the window is open).
@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
/// «Весь план» → Задачи: also the finished ones.
@Published var showDone = false {
didSet { Task { await refreshAll() } }
}
var baseURL: String {
(UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
}
/// Read once from the Keychain, updated by Settings.
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? {
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? NSNumber)?.doubleValue,
currency: d["currency"] as? String, paid: d["paid"] as? Bool ?? false,
nextIfRepeat: d["next_if_repeat"] as? String)
}
}
var a = OpsAgenda(overdue: items("overdue"), today: items("due_today"), soon: items("soon"), paid: items("paid"))
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
}
func refreshAll() async {
await refresh()
if let arr = await request(showDone ? "/api/tasks?all=1" : "/api/tasks") as? [[String: Any]] {
func task(_ d: [String: Any]) -> OpsTask {
OpsTask(id: d["id"] as? Int ?? 0, parentId: d["parent_id"] as? Int, title: d["title"] as? String ?? "",
client: d["client"] as? String ?? "", status: d["status"] as? String ?? "todo",
due: d["due"] as? String, minutes: d["minutes"] as? Int ?? 0, running: d["running"] as? Bool ?? false,
children: (d["children"] as? [[String: Any]] ?? []).map(task), notes: d["notes"] as? String ?? "")
}
tasks = arr.map(task)
}
if let j = await request("/api/subs") as? [String: Any] {
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,
client: d["client"] as? String ?? "", paid: d["paid"] as? Bool ?? false,
nextIfRepeat: d["next_if_repeat"] as? String ?? "", active: (d["active"] as? Int ?? 1) == 1,
notes: d["notes"] 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]] {
routines = arr.map { d in
OpsRoutine(id: d["id"] as? Int ?? 0, title: d["title"] as? String ?? "", everyDays: d["every_days"] as? Int ?? 1,
next: d["next_date"] as? String ?? "", last: d["last_done"] as? String, notes: d["notes"] as? String ?? "")
}
}
fullLoaded = true
}
/// 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)
if fullLoaded { await refreshAll() } else { 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")
if fullLoaded { await refreshAll() } else { await refresh() }
}
func delete(_ kind: String, _ id: Int) async {
let r = await request("/api/delete", body: ["kind": kind, "id": id]) as? [String: Any]
if let lines = r?["result"] as? [String] { lastAnswer = lines.joined(separator: "\n") }
SoundEngine.shared.play("close")
await refreshAll()
}
func repeatSub(_ id: Int, _ again: Bool) async {
await act(["op": "repeat_sub", "id": id, "repeat": again])
}
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 }
/// «4 200 ₽ · 200 $»
static func money(_ m: [String: Double]) -> String {
m.sorted { $0.key < $1.key }.map { "\(Self.amount($0.value)) \(Self.symbol($0.key))" }.joined(separator: " · ")
}
static func amount(_ v: Double) -> String {
let f = NumberFormatter()
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
}
/// 2026-11-15 → 15.11.2026
static func ruDay(_ iso: String?) -> String {
guard let iso else { return "" }
let p = iso.prefix(10).split(separator: "-")
return p.count == 3 ? "\(p[2]).\(p[1]).\(p[0])" : iso
}
}
// MARK: - Menu on the Memoji: the task manager
struct BroMenu: View {
@ObservedObject var state: AppState
@ObservedObject private var ops = OpsClient.shared
var body: some View {
OpsPanel(state: state)
.notchPopoverStyle()
.task { await ops.refresh() }
}
}
// MARK: - «Дела» panel (under the notch): today at a glance
struct OpsPanel: View {
@ObservedObject var state: AppState
@ObservedObject private var ops = OpsClient.shared
@State private var text = ""
@State private var showWeek = false
@FocusState private var focused: Bool
private static let dayTitle: DateFormatter = {
let f = DateFormatter(); f.locale = Locale(identifier: "ru_RU"); f.dateFormat = "EE, dd.MM.yyyy"; return f
}()
var body: some View {
VStack(alignment: .leading, spacing: 9) {
HStack(spacing: 6) {
Image(systemName: "checklist").font(.system(size: 12, weight: .semibold))
.foregroundColor(Color(hex: "#D97757"))
Text("Дела").font(.system(size: 14, weight: .semibold))
Text(Self.dayTitle.string(from: Date())).font(.system(size: 11)).foregroundColor(Color(hex: "#6B7079"))
Spacer()
if ops.busy { ProgressView().controlSize(.mini) }
Button {
state.botMenuOpen = false
OpsWindow.show()
} label: {
HStack(spacing: 4) {
Image(systemName: "calendar").font(.system(size: 11))
Text("Весь план").font(.system(size: 11, weight: .medium))
}
.padding(.horizontal, 8).frame(height: 22)
.background(Capsule().fill(Color.white.opacity(0.08)))
}
.buttonStyle(.plain)
.help("Календарь, все задачи, подписки и регламент")
}
.foregroundColor(Color(hex: "#B0B5BE"))
if !ops.configured {
note("Сервис дел не подключён: Настройки → Чат → «Дела (хоумлаб)».", "#B0B5BE")
} else if ops.reachable == false {
note("Сервис дел не отвечает. Ты не дома? Включи сеть «Дом» в 🌐.", "#FB923C")
}
HStack(spacing: 6) {
tile("\(ops.agenda.overdue.count)", "просрочено", "#F4505E", dim: ops.agenda.overdue.isEmpty)
tile("\(ops.agenda.today.count)", "сегодня", "#F5A524", dim: ops.agenda.today.isEmpty)
tile(ops.agenda.monthly.isEmpty ? "—" : OpsClient.money(ops.agenda.monthly), "подписки / мес", "#B0B5BE", dim: true)
}
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading, spacing: 1) {
if let r = ops.agenda.running {
header("СЕЙЧАС", "#34D399")
HStack(spacing: 8) {
Image(systemName: "timer").font(.system(size: 11)).foregroundColor(Color(hex: "#34D399")).frame(width: 16)
Text(r.title).font(.system(size: 12, weight: .medium)).lineLimit(1)
Spacer()
Text("\(r.minutes) мин").font(.system(size: 11)).monospacedDigit().foregroundColor(Color(hex: "#34D399"))
Button { Task { await ops.act(["op": "stop_timer"]) } } label: {
Image(systemName: "stop.circle.fill").font(.system(size: 14)).foregroundColor(Color(hex: "#34D399"))
}
.buttonStyle(.plain).help("Остановить таймер")
}
.padding(.horizontal, 6).padding(.vertical, 6)
.background(RoundedRectangle(cornerRadius: 7).fill(Color(hex: "#34D399").opacity(0.10)))
}
if !ops.agenda.overdue.isEmpty {
header("ГОРИТ", "#F4505E")
ForEach(ops.agenda.overdue) { OpsRow(item: $0, overdue: true) }
}
if !ops.agenda.today.isEmpty {
header("СЕГОДНЯ", "#F5A524")
ForEach(ops.agenda.today) { OpsRow(item: $0) }
}
if !ops.agenda.paid.isEmpty {
header("ОПЛАЧЕНО — ПОВТОРИТЬ?", "#60A5FA")
ForEach(ops.agenda.paid) { PaidRow(item: $0) }
}
if !ops.agenda.soon.isEmpty {
Button { withAnimation(.easeOut(duration: 0.15)) { showWeek.toggle() } } label: {
HStack(spacing: 4) {
Text("НА НЕДЕЛЕ · \(ops.agenda.soon.count)").font(.system(size: 9.5, weight: .bold))
Image(systemName: showWeek ? "chevron.up" : "chevron.down").font(.system(size: 8, weight: .bold))
}
.foregroundColor(Color(hex: "#8E939C"))
.padding(.top, 8).padding(.bottom, 3).padding(.leading, 6)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
if showWeek { ForEach(ops.agenda.soon) { OpsRow(item: $0) } }
}
if ops.configured && ops.reachable == true && ops.agenda.running == nil && ops.agenda.paid.isEmpty
&& ops.agenda.overdue.isEmpty && ops.agenda.today.isEmpty && ops.agenda.soon.isEmpty {
Text("На неделю ничего не горит 👌").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
.padding(.vertical, 8).padding(.leading, 6)
}
}
}
.frame(maxHeight: 280)
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)))
}
OpsInput(text: $text, focused: $focused)
}
.padding(12)
.frame(width: 390)
.foregroundColor(Color(hex: "#F5F6F8"))
.onAppear { focused = true }
}
private func note(_ t: String, _ color: String) -> some View {
Text(t).font(.system(size: 11.5)).foregroundColor(Color(hex: color)).fixedSize(horizontal: false, vertical: true)
}
private func header(_ t: String, _ color: String) -> some View {
Text(t).font(.system(size: 9.5, weight: .bold)).foregroundColor(Color(hex: color))
.padding(.top, 8).padding(.bottom, 3).padding(.leading, 6)
}
private func tile(_ value: String, _ label: String, _ color: String, dim: Bool) -> some View {
VStack(alignment: .leading, spacing: 1) {
Text(value).font(.system(size: 15, weight: .semibold)).lineLimit(1).minimumScaleFactor(0.6)
.foregroundColor(Color(hex: dim ? "#F5F6F8" : color))
Text(label).font(.system(size: 10.5)).foregroundColor(Color(hex: dim ? "#6B7079" : color).opacity(dim ? 1 : 0.85))
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 9).padding(.vertical, 7)
.background(RoundedRectangle(cornerRadius: 9).fill(dim ? Color.white.opacity(0.05) : Color(hex: color).opacity(0.13)))
}
}
/// «Записать или спросить…» → the service's Claude.
struct OpsInput: View {
@Binding var text: String
var focused: FocusState<Bool>.Binding
@ObservedObject private var ops = OpsClient.shared
var body: some View {
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)))
}
private func send() {
let t = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !t.isEmpty else { return }
text = ""
Task { await ops.say(t) }
}
}
/// A paid subscription: «✓ Оплачено» and the question «repeat on <date>?».
struct PaidRow: View {
let item: OpsItem
@ObservedObject private var ops = OpsClient.shared
var body: some View {
HStack(spacing: 8) {
Image(systemName: "checkmark.circle.fill").font(.system(size: 13)).foregroundColor(Color(hex: "#34D399")).frame(width: 16)
VStack(alignment: .leading, spacing: 1) {
Text(item.title).font(.system(size: 12, weight: .medium)).lineLimit(1)
Text("Оплачено · повторить \(OpsClient.ruDay(item.nextIfRepeat))?")
.font(.system(size: 10.5)).foregroundColor(Color(hex: "#34D399")).lineLimit(1)
}
Spacer(minLength: 4)
Button { Task { await ops.repeatSub(item.ref, true) } } label: {
Text("Повторить").font(.system(size: 10.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA"))
.padding(.horizontal, 7).frame(height: 18)
.background(Capsule().fill(Color(hex: "#60A5FA").opacity(0.14)))
}
.buttonStyle(.plain)
Button { Task { await ops.repeatSub(item.ref, false) } } label: {
Text("Нет").font(.system(size: 10.5, weight: .medium)).foregroundColor(Color(hex: "#8E939C"))
.padding(.horizontal, 7).frame(height: 18)
.background(Capsule().fill(Color.white.opacity(0.06)))
}
.buttonStyle(.plain)
.help("Больше не повторять — подписка закроется")
}
.padding(.horizontal, 6).padding(.vertical, 5)
}
}
/// One agenda line: ○ done on the left (₽ «Оплачено» for subscriptions), ⏱ / ⏰ on hover.
struct OpsRow: View {
let item: OpsItem
var overdue = false
@ObservedObject private var ops = OpsClient.shared
@State private var hovered = false
var body: some View {
HStack(spacing: 8) {
if item.kind == "sub" {
Image(systemName: "creditcard").font(.system(size: 11)).foregroundColor(Color(hex: "#60A5FA")).frame(width: 16)
} else {
Button { Task { await ops.done(item) } } label: {
Image(systemName: hovered ? "checkmark.circle" : "circle")
.font(.system(size: 13))
.foregroundColor(Color(hex: overdue ? "#F4505E" : (item.kind == "routine" ? "#34D399" : "#8E939C")))
.frame(width: 16)
}
.buttonStyle(.plain)
.help(item.kind == "routine" ? "Сделано (следующий раз посчитается сам)" : "Сделано")
}
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 4) {
if item.kind == "routine" {
Image(systemName: "arrow.triangle.2.circlepath").font(.system(size: 9)).foregroundColor(Color(hex: "#34D399"))
}
Text(item.title).font(.system(size: 12, weight: .medium)).lineLimit(1)
}
Text(subtitle).font(.system(size: 10.5)).foregroundColor(Color(hex: overdue ? "#F4505E" : "#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("moon.zzz", "Перенести на завтра") {
Task { await ops.act(["op": "snooze", "kind": item.kind, "id": item.ref, "days": 1]) }
}
}
if item.kind == "sub" {
Button { Task { await ops.done(item) } } label: {
Text("Оплачено?").font(.system(size: 10.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA"))
.padding(.horizontal, 7).frame(height: 18)
.background(Capsule().fill(Color(hex: "#60A5FA").opacity(0.14)))
}
.buttonStyle(.plain)
}
}
.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: [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(OpsClient.clientName(item.client)) }
return parts.joined(separator: " · ")
}
static func daysLate(_ iso: String) -> Int? {
let f = DateFormatter(); f.dateFormat = "yyyy-MM-dd"
guard let d = f.date(from: String(iso.prefix(10))) else { return nil }
return Calendar.current.dateComponents([.day], from: d, to: Calendar.current.startOfDay(for: Date())).day
}
private func small(_ symbol: String, _ help: String, _ action: @escaping () -> Void) -> some View {
Button(action: action) {
Image(systemName: symbol).font(.system(size: 12)).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)
}
}
}