From 36326ba0b6997c85988a0b844938b01ff60b7eee Mon Sep 17 00:00:00 2001 From: maksarsanjeev Date: Sat, 10 Oct 2026 03:33:43 +0300 Subject: [PATCH] =?UTF-8?q?=C2=AB=D0=94=D0=B5=D0=BB=D0=B0=C2=BB:=20today-a?= =?UTF-8?q?t-a-glance=20popover=20and=20the=20=C2=AB=D0=92=D0=B5=D1=81?= =?UTF-8?q?=D1=8C=20=D0=BF=D0=BB=D0=B0=D0=BD=C2=BB=20window?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Popover (click on the Memoji): counters (overdue, today, subscriptions per month), Сейчас / Горит / Сегодня / На неделе (collapsed), ○ to finish, «Оплачено» for charges, ⏱ and «завтра» on hover, the text box to the service's Claude. - «Весь план» button opens a regular window: month calendar (task deadlines, upcoming charges and routine dates with repeats projected forward, overdue days outlined) with the selected day's list; the task tree with subtasks, clients, minutes and the timer; subscriptions with the monthly total; routines with the last time done. Co-Authored-By: Claude Opus 5.5 --- NotchBuddy/Sources/App/Ops.swift | 312 +++++++++++---- NotchBuddy/Sources/App/OpsOverview.swift | 487 +++++++++++++++++++++++ 2 files changed, 724 insertions(+), 75 deletions(-) create mode 100644 NotchBuddy/Sources/App/OpsOverview.swift diff --git a/NotchBuddy/Sources/App/Ops.swift b/NotchBuddy/Sources/App/Ops.swift index e0d5762..2b1be77 100644 --- a/NotchBuddy/Sources/App/Ops.swift +++ b/NotchBuddy/Sources/App/Ops.swift @@ -31,6 +31,37 @@ struct OpsAgenda: Equatable { } } +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] +} + +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 +} + +struct OpsRoutine: Identifiable, Equatable { + var id: Int + var title: String + var everyDays: Int + var next: String + var last: String? +} + @MainActor final class OpsClient: ObservableObject { static let shared = OpsClient() @@ -41,6 +72,11 @@ final class OpsClient: ObservableObject { @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] = [] + var fullLoaded = false var baseURL: String { (UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines) @@ -87,13 +123,40 @@ final class OpsClient: ObservableObject { agenda = a } + func refreshAll() async { + await refresh() + if let arr = await request("/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)) + } + 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) + } + } + 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) + } + } + 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) - await refresh() + if fullLoaded { await refreshAll() } else { await refresh() } } /// A direct action from a button: done / paid / timer / snooze. @@ -101,7 +164,7 @@ final class OpsClient: ObservableObject { 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() + if fullLoaded { await refreshAll() } else { await refresh() } } func done(_ it: OpsItem) async { @@ -113,6 +176,25 @@ final class OpsClient: ObservableObject { } 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 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 @@ -128,66 +210,102 @@ struct BroMenu: View { } } -// MARK: - «Дела» panel +// 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: 8) { + 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 { Task { await ops.refresh() } } label: { - Image(systemName: "arrow.clockwise").font(.system(size: 11)) + 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("Обновить") + .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) + note("Сервис дел не подключён: Настройки → Чат → «Дела (хоумлаб)».", "#B0B5BE") } else if ops.reachable == false { - Text("Сервис дел не отвечает. Ты не дома? Включи сеть «Дом» в 🌐.") - .font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C")) - .fixedSize(horizontal: false, vertical: true) + note("Сервис дел не отвечает. Ты не дома? Включи сеть «Дом» в 🌐.", "#FB923C") } - 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))) + 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: 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 { + 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.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.overdue.isEmpty && ops.agenda.today.isEmpty && ops.agenda.soon.isEmpty { Text("На неделю ничего не горит 👌").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) - .padding(.vertical, 6) + .padding(.vertical, 8).padding(.leading, 6) } } } - .frame(maxHeight: 260) + .frame(maxHeight: 280) if let a = ops.lastAnswer, !a.isEmpty { Text(a).font(.system(size: 11)).foregroundColor(Color(hex: "#B0B5BE")) @@ -198,73 +316,116 @@ struct OpsPanel: View { .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))) + OpsInput(text: $text, focused: $focused) } .padding(12) - .frame(width: 380) + .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.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) } } - - @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) } - } - } } +/// 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 - 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) + 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) { - Text(item.title).font(.system(size: 12, weight: .medium)).lineLimit(1) - Text(subtitle).font(.system(size: 10.5)).foregroundColor(Color(hex: "#6B7079")).lineLimit(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("clock.arrow.circlepath", "Завтра") { + small("moon.zzz", "Перенести на завтра") { 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) } } + 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))) @@ -272,21 +433,22 @@ struct OpsRow: View { } private var subtitle: String { - var parts = [Self.ruDay(item.date)] - if let a = item.amount { parts.append("\(a.formatted()) \(item.currency ?? "")") } + 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) } return parts.joined(separator: " · ") } - /// 2026-11-15 → 15.11.2026 - static func ruDay(_ iso: String) -> String { - let p = iso.prefix(10).split(separator: "-") - return p.count == 3 ? "\(p[2]).\(p[1]).\(p[0])" : iso + 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: 13)).foregroundColor(Color(hex: "#B0B5BE")) + Image(systemName: symbol).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) } .buttonStyle(.plain) .help(help) diff --git a/NotchBuddy/Sources/App/OpsOverview.swift b/NotchBuddy/Sources/App/OpsOverview.swift new file mode 100644 index 0000000..8335ab0 --- /dev/null +++ b/NotchBuddy/Sources/App/OpsOverview.swift @@ -0,0 +1,487 @@ +import SwiftUI +import AppKit + +// MARK: - «Весь план»: the big window of the task manager +// +// Opened from the «Дела» popover. A regular window (not the notch): month calendar with +// task deadlines, upcoming subscription charges and routine dates (recurring ones are +// projected forward), the full task tree, subscriptions and routines. + +@MainActor +enum OpsWindow { + private static var window: NSWindow? + + static func show() { + if let w = window { + NSApp.activate(ignoringOtherApps: true) + w.makeKeyAndOrderFront(nil) + Task { await OpsClient.shared.refreshAll() } + return + } + let w = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1040, height: 680), + styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView], + backing: .buffered, defer: false) + w.title = "Весь план" + w.titlebarAppearsTransparent = true + w.appearance = NSAppearance(named: .darkAqua) + w.backgroundColor = NSColor(calibratedRed: 0.055, green: 0.059, blue: 0.067, alpha: 1) + w.minSize = NSSize(width: 860, height: 560) + w.isReleasedWhenClosed = false + w.contentView = NSHostingView(rootView: OpsOverview()) + w.center() + w.setFrameAutosaveName("BroVOpsOverview") + window = w + NSApp.activate(ignoringOtherApps: true) + w.makeKeyAndOrderFront(nil) + } +} + +enum OpsSection: String, CaseIterable, Identifiable { + case calendar = "Календарь", tasks = "Задачи", subs = "Подписки", routines = "Регламент" + var id: String { rawValue } + var symbol: String { + switch self { + case .calendar: return "calendar" + case .tasks: return "checklist" + case .subs: return "creditcard" + case .routines: return "arrow.triangle.2.circlepath" + } + } +} + +struct OpsOverview: View { + @ObservedObject private var ops = OpsClient.shared + @State private var section: OpsSection = .calendar + @State private var text = "" + @FocusState private var focused: Bool + + var body: some View { + HStack(spacing: 0) { + VStack(alignment: .leading, spacing: 4) { + ForEach(OpsSection.allCases) { s in + Button { section = s } label: { + HStack(spacing: 8) { + Image(systemName: s.symbol).frame(width: 18) + Text(s.rawValue) + Spacer() + if let n = count(s) { Text("\(n)").foregroundColor(Color(hex: "#6B7079")) } + } + .font(.system(size: 13, weight: section == s ? .semibold : .regular)) + .foregroundColor(Color(hex: section == s ? "#F5F6F8" : "#B0B5BE")) + .padding(.horizontal, 10).frame(height: 30) + .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(section == s ? 0.09 : 0))) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + Spacer() + if !ops.agenda.monthly.isEmpty { + Text("Подписки в месяц").font(.system(size: 10.5)).foregroundColor(Color(hex: "#6B7079")) + Text(OpsClient.money(ops.agenda.monthly)).font(.system(size: 13, weight: .semibold)) + } + if ops.reachable == false { + Text("Сервис не отвечает").font(.system(size: 11)).foregroundColor(Color(hex: "#FB923C")) + } + } + .padding(.top, 44).padding(.horizontal, 12).padding(.bottom, 16) + .frame(width: 200) + .background(Color.white.opacity(0.03)) + + VStack(spacing: 10) { + Group { + switch section { + case .calendar: OpsCalendar() + case .tasks: OpsTaskList() + case .subs: OpsSubList() + case .routines: OpsRoutineList() + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + + if let a = ops.lastAnswer, !a.isEmpty { + Text(a).font(.system(size: 11.5)).foregroundColor(Color(hex: "#B0B5BE")) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(8) + .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.05))) + } + OpsInput(text: $text, focused: $focused) + } + .padding(.top, 40).padding(.horizontal, 18).padding(.bottom, 16) + } + .foregroundColor(Color(hex: "#F5F6F8")) + .task { await ops.refreshAll() } + } + + private func count(_ s: OpsSection) -> Int? { + switch s { + case .calendar: return nil + case .tasks: return ops.tasks.isEmpty ? nil : ops.tasks.count + case .subs: return ops.subs.isEmpty ? nil : ops.subs.count + case .routines: return ops.routines.isEmpty ? nil : ops.routines.count + } + } +} + +// MARK: - Calendar + +struct OpsCalItem: Identifiable { + var kind: String // task | sub | routine + var ref: Int + var title: String + var detail: String + var date: String // ISO + var projected: Bool // a future repeat, not the next real date + var id: String { "\(kind)-\(ref)-\(date)" } + + var color: String { + switch kind { case "sub": return "#60A5FA"; case "routine": return "#34D399"; default: return "#D97757" } + } +} + +struct OpsCalendar: View { + @ObservedObject private var ops = OpsClient.shared + @State private var month = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Date()))! + @State private var selected: String = OpsCalendar.iso(Date()) + + private static let cal: Calendar = { var c = Calendar(identifier: .gregorian); c.firstWeekday = 2; return c }() + static func iso(_ d: Date) -> String { + let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian); f.dateFormat = "yyyy-MM-dd"; return f.string(from: d) + } + private static func date(_ iso: String) -> Date? { + let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian); f.dateFormat = "yyyy-MM-dd" + return f.date(from: String(iso.prefix(10))) + } + private static let monthTitle: DateFormatter = { + let f = DateFormatter(); f.locale = Locale(identifier: "ru_RU"); f.dateFormat = "LLLL yyyy"; return f + }() + + var body: some View { + let days = gridDays() + let items = itemsByDay(until: days.last ?? month) + HStack(alignment: .top, spacing: 16) { + VStack(spacing: 8) { + HStack { + Text(Self.monthTitle.string(from: month).capitalized).font(.system(size: 18, weight: .semibold)) + Spacer() + Button { shift(-1) } label: { Image(systemName: "chevron.left") }.buttonStyle(.plain) + Button("Сегодня") { + month = Self.cal.date(from: Self.cal.dateComponents([.year, .month], from: Date()))! + selected = Self.iso(Date()) + } + .buttonStyle(.plain).font(.system(size: 12, weight: .medium)) + Button { shift(1) } label: { Image(systemName: "chevron.right") }.buttonStyle(.plain) + } + .foregroundColor(Color(hex: "#B0B5BE")) + HStack(spacing: 0) { + ForEach(["пн", "вт", "ср", "чт", "пт", "сб", "вс"], id: \.self) { + Text($0).font(.system(size: 11)).foregroundColor(Color(hex: "#6B7079")).frame(maxWidth: .infinity) + } + } + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 4), count: 7), spacing: 4) { + ForEach(days, id: \.self) { d in + dayCell(d, items[Self.iso(d)] ?? []) + } + } + HStack(spacing: 14) { + legend("#D97757", "задачи"); legend("#60A5FA", "списания"); legend("#34D399", "регламент") + Spacer() + } + } + .frame(maxWidth: .infinity) + + VStack(alignment: .leading, spacing: 6) { + Text(dayTitle(selected)).font(.system(size: 14, weight: .semibold)) + let list = items[selected] ?? [] + if list.isEmpty { + Text("Ничего не запланировано").font(.system(size: 12)).foregroundColor(Color(hex: "#6B7079")) + } + ScrollView(.vertical, showsIndicators: false) { + VStack(alignment: .leading, spacing: 4) { + ForEach(list) { it in + HStack(alignment: .top, spacing: 8) { + RoundedRectangle(cornerRadius: 2).fill(Color(hex: it.color)).frame(width: 3, height: 30) + VStack(alignment: .leading, spacing: 2) { + Text(it.title).font(.system(size: 12.5, weight: .medium)) + Text(it.detail + (it.projected ? " · повтор" : "")).font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C")) + } + Spacer() + if !it.projected { + Button(it.kind == "sub" ? "Оплачено" : "Сделано") { + Task { await ops.done(OpsItem(kind: it.kind, ref: it.ref, title: it.title, date: it.date, client: "")) } + } + .buttonStyle(.plain).font(.system(size: 11, weight: .medium)) + .foregroundColor(Color(hex: it.color)) + } + } + .padding(8) + .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04))) + } + } + } + } + .frame(width: 260) + } + } + + private func dayCell(_ d: Date, _ list: [OpsCalItem]) -> some View { + let key = Self.iso(d) + let inMonth = Self.cal.isDate(d, equalTo: month, toGranularity: .month) + let isToday = key == Self.iso(Date()) + let isSel = key == selected + let overdue = key < Self.iso(Date()) && list.contains { $0.kind == "task" } + return VStack(alignment: .leading, spacing: 2) { + Text("\(Self.cal.component(.day, from: d))") + .font(.system(size: 12, weight: isToday ? .bold : .regular)) + .foregroundColor(Color(hex: isToday ? "#D97757" : (inMonth ? "#F5F6F8" : "#4B5058"))) + ForEach(list.prefix(3)) { it in + Text(it.title).font(.system(size: 9.5)).lineLimit(1) + .foregroundColor(Color(hex: it.color).opacity(it.projected ? 0.6 : 1)) + .padding(.horizontal, 3) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoundedRectangle(cornerRadius: 3).fill(Color(hex: it.color).opacity(0.14))) + } + if list.count > 3 { + Text("+\(list.count - 3)").font(.system(size: 9.5)).foregroundColor(Color(hex: "#8E939C")) + } + Spacer(minLength: 0) + } + .padding(5) + .frame(maxWidth: .infinity, minHeight: 74, maxHeight: 74, alignment: .topLeading) + .background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(isSel ? 0.10 : (inMonth ? 0.035 : 0.01)))) + .overlay(RoundedRectangle(cornerRadius: 7).stroke(Color(hex: overdue ? "#F4505E" : "#D97757").opacity(isSel || overdue ? 0.6 : 0), lineWidth: 1)) + .contentShape(Rectangle()) + .onTapGesture { selected = key } + } + + private func legend(_ color: String, _ title: String) -> some View { + HStack(spacing: 5) { + Circle().fill(Color(hex: color)).frame(width: 7, height: 7) + Text(title).font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C")) + } + } + + private func shift(_ n: Int) { + month = Self.cal.date(byAdding: .month, value: n, to: month) ?? month + } + + private func dayTitle(_ iso: String) -> String { + guard let d = Self.date(iso) else { return iso } + let f = DateFormatter(); f.locale = Locale(identifier: "ru_RU"); f.dateFormat = "EEEE, dd.MM.yyyy" + return f.string(from: d).capitalized + } + + /// Monday-first weeks covering the month. + private func gridDays() -> [Date] { + let first = month + let weekday = (Self.cal.component(.weekday, from: first) + 5) % 7 // Monday = 0 + let start = Self.cal.date(byAdding: .day, value: -weekday, to: first)! + let count = Self.cal.range(of: .day, in: .month, for: month)!.count + let cells = Int(ceil(Double(weekday + count) / 7.0)) * 7 + return (0.. [String: [OpsCalItem]] { + var out: [String: [OpsCalItem]] = [:] + func add(_ it: OpsCalItem) { out[it.date, default: []].append(it) } + func walk(_ ts: [OpsTask]) { + 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)) + } + walk(t.children) + } + } + walk(ops.tasks) + for s in ops.subs { + guard var d = Self.date(s.next) else { continue } + 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)) + 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) + } + } + for r in ops.routines { + guard var d = Self.date(r.next) else { continue } + var first = true + while d <= end { + add(OpsCalItem(kind: "routine", ref: r.id, title: r.title, detail: "раз в \(r.everyDays) дн.", + date: Self.iso(d), projected: !first)) + first = false + d = Self.cal.date(byAdding: .day, value: max(1, r.everyDays), to: d) ?? end.addingTimeInterval(1) + } + } + return out + } +} + +// MARK: - Lists + +struct OpsTaskList: View { + @ObservedObject private var ops = OpsClient.shared + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text("Задачи").font(.system(size: 18, weight: .semibold)) + if ops.tasks.isEmpty { + Text("Открытых задач нет. Запиши ниже: «в Planet9 переезд серверной: купить свитч, проверить ИБП»") + .font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) + } + ScrollView(.vertical, showsIndicators: false) { + VStack(alignment: .leading, spacing: 2) { + ForEach(ops.tasks) { OpsTaskRow(task: $0, depth: 0) } + } + } + } + } +} + +struct OpsTaskRow: View { + let task: OpsTask + let depth: Int + @ObservedObject private var ops = OpsClient.shared + @State private var expanded = true + @State private var hovered = false + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 8) { + if !task.children.isEmpty { + Button { withAnimation(.easeOut(duration: 0.12)) { expanded.toggle() } } label: { + Image(systemName: expanded ? "chevron.down" : "chevron.right").font(.system(size: 9, weight: .bold)) + .foregroundColor(Color(hex: "#8E939C")).frame(width: 12) + } + .buttonStyle(.plain) + } else { + Color.clear.frame(width: 12, height: 1) + } + Button { Task { await ops.act(["op": "complete_task", "id": task.id]) } } label: { + Image(systemName: hovered ? "checkmark.circle" : "circle").font(.system(size: 14)) + .foregroundColor(Color(hex: overdue ? "#F4505E" : "#8E939C")) + } + .buttonStyle(.plain).help("Сделано (вместе с подзадачами)") + Text(task.title).font(.system(size: 13, weight: depth == 0 ? .medium : .regular)) + if !task.children.isEmpty { + Text("подзадач: \(task.children.count)").font(.system(size: 10.5)).foregroundColor(Color(hex: "#8E939C")) + .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")) + .padding(.horizontal, 6).background(Capsule().fill(Color(hex: "#A78BFA").opacity(0.14))) + } + Spacer() + if task.minutes > 0 || task.running { + Text("\(task.minutes) мин").font(.system(size: 11)).monospacedDigit() + .foregroundColor(Color(hex: task.running ? "#34D399" : "#8E939C")) + } + if let due = task.due { + Text(OpsClient.ruDay(due)).font(.system(size: 11)).foregroundColor(Color(hex: overdue ? "#F4505E" : "#8E939C")) + } + Button { + Task { await ops.act(task.running ? ["op": "stop_timer"] : ["op": "start_timer", "id": task.id]) } + } label: { + Image(systemName: task.running ? "stop.circle.fill" : "timer").font(.system(size: 13)) + .foregroundColor(Color(hex: task.running ? "#34D399" : "#8E939C")) + } + .buttonStyle(.plain).opacity(hovered || task.running ? 1 : 0) + .help(task.running ? "Остановить таймер" : "Засечь время") + } + .padding(.leading, CGFloat(depth) * 22) + .padding(.horizontal, 8).padding(.vertical, 6) + .background(RoundedRectangle(cornerRadius: 7).fill(Color.white.opacity(hovered ? 0.05 : 0))) + .onHover { hovered = $0 } + if expanded { + ForEach(task.children) { OpsTaskRow(task: $0, depth: depth + 1) } + } + } + } + + private var overdue: Bool { + guard let due = task.due else { return false } + return due < OpsCalendar.iso(Date()) + } +} + +struct OpsSubList: View { + @ObservedObject private var ops = OpsClient.shared + private let period = ["day": "день", "week": "нед.", "month": "мес.", "year": "год"] + + 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")) + } + } + if ops.subs.isEmpty { + Text("Подписок нет. Запиши ниже: «хостинг 900 ₽ в месяц, списание 20-го»") + .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)) + 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))) + } + } + } + } + } +} + +struct OpsRoutineList: View { + @ObservedObject private var ops = OpsClient.shared + + var body: some View { + VStack(alignment: .leading, spacing: 8) { + Text("Регламент").font(.system(size: 18, weight: .semibold)) + if ops.routines.isEmpty { + Text("Регламентных дел нет. Запиши ниже: «бэкап хоумлаба раз в неделю»") + .font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) + } + ScrollView(.vertical, showsIndicators: false) { + VStack(spacing: 2) { + ForEach(ops.routines) { r in + let late = r.next < OpsCalendar.iso(Date()) + HStack(spacing: 10) { + Image(systemName: "arrow.triangle.2.circlepath").foregroundColor(Color(hex: "#34D399")) + Text(r.title).font(.system(size: 13, weight: .medium)) + Spacer() + Text("раз в \(r.everyDays) дн.").font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) + .frame(width: 100, alignment: .trailing) + Text("след. \(OpsClient.ruDay(r.next))").font(.system(size: 12)) + .foregroundColor(Color(hex: late ? "#F4505E" : "#B0B5BE")).frame(width: 120, alignment: .trailing) + Text(r.last.map { "был \(OpsClient.ruDay($0))" } ?? "ещё не было").font(.system(size: 11)) + .foregroundColor(Color(hex: "#6B7079")).frame(width: 110, alignment: .trailing) + Button("Сделано") { Task { await ops.act(["op": "done_routine", "id": r.id]) } } + .buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#34D399")) + } + .padding(.horizontal, 10).padding(.vertical, 8) + .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04))) + } + } + } + } + } +}