Files
brov-macbook/NotchBuddy/Sources/App/OpsOverview.swift
T
maksarsanjeev 18aed2beb9 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>
2026-10-10 03:42:41 +03:00

507 lines
25 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: - «Весь план»: 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..<cells).map { Self.cal.date(byAdding: .day, value: $0, to: start)! }
}
/// Everything dated up to the end of the grid; repeats of subscriptions and routines
/// are projected from their next date.
private func itemsByDay(until end: Date) -> [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 ? "задача" : "задача · \(OpsClient.clientName(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))"
+ (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)
}
}
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(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()
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": "год"]
/// 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"))
}
}
if ops.subs.isEmpty {
Text("Подписок нет. Запиши ниже: «Claude Code 20 $ в месяц, списание 25-го, компания Сага»")
.font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
}
ScrollView(.vertical, showsIndicators: false) {
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()
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)))
}
}
}
}
}
}
}
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)))
}
}
}
}
}
}