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>
This commit is contained in:
maksarsanjeev
2026-10-10 03:57:18 +03:00
parent 011c709acf
commit 882632b7ce
9 changed files with 628 additions and 65 deletions
+74 -10
View File
@@ -15,6 +15,8 @@ struct OpsItem: Identifiable, Equatable {
var client: String var client: String
var amount: Double? var amount: Double?
var currency: String? var currency: String?
var paid = false
var nextIfRepeat: String?
var id: String { "\(kind)-\(ref)" } var id: String { "\(kind)-\(ref)" }
} }
@@ -22,11 +24,13 @@ struct OpsAgenda: Equatable {
var overdue: [OpsItem] = [] var overdue: [OpsItem] = []
var today: [OpsItem] = [] var today: [OpsItem] = []
var soon: [OpsItem] = [] var soon: [OpsItem] = []
/// Subscriptions paid and waiting for «repeat?».
var paid: [OpsItem] = []
var running: (id: Int, title: String, minutes: Int)? var running: (id: Int, title: String, minutes: Int)?
var monthly: [String: Double] = [:] var monthly: [String: Double] = [:]
static func == (a: OpsAgenda, b: OpsAgenda) -> Bool { static func == (a: OpsAgenda, b: OpsAgenda) -> Bool {
a.overdue == b.overdue && a.today == b.today && a.soon == b.soon 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 && a.running?.id == b.running?.id && a.running?.minutes == b.running?.minutes && a.monthly == b.monthly
} }
} }
@@ -41,6 +45,7 @@ struct OpsTask: Identifiable, Equatable {
var minutes: Int var minutes: Int
var running: Bool var running: Bool
var children: [OpsTask] var children: [OpsTask]
var notes: String = ""
} }
struct OpsSub: Identifiable, Equatable { struct OpsSub: Identifiable, Equatable {
@@ -53,6 +58,10 @@ struct OpsSub: Identifiable, Equatable {
var next: String var next: String
var remindDays: Int var remindDays: Int
var client: String var client: String
var paid = false
var nextIfRepeat = ""
var active = true
var notes = ""
} }
struct OpsRoutine: Identifiable, Equatable { struct OpsRoutine: Identifiable, Equatable {
@@ -61,6 +70,7 @@ struct OpsRoutine: Identifiable, Equatable {
var everyDays: Int var everyDays: Int
var next: String var next: String
var last: String? var last: String?
var notes = ""
} }
@MainActor @MainActor
@@ -80,6 +90,10 @@ final class OpsClient: ObservableObject {
/// Subscriptions per month by company ("" = none), then by currency. /// Subscriptions per month by company ("" = none), then by currency.
@Published var byClient: [String: [String: Double]] = [:] @Published var byClient: [String: [String: Double]] = [:]
var fullLoaded = false var fullLoaded = false
/// «Весь план» → Задачи: also the finished ones.
@Published var showDone = false {
didSet { Task { await refreshAll() } }
}
var baseURL: String { var baseURL: String {
(UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines) (UserDefaults.standard.string(forKey: Self.urlKey) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
@@ -129,11 +143,12 @@ final class OpsClient: ObservableObject {
(j[key] as? [[String: Any]] ?? []).compactMap { d in (j[key] as? [[String: Any]] ?? []).compactMap { d in
guard let kind = d["kind"] as? String, let ref = d["id"] as? Int else { return nil } 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 ?? "", 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, client: d["client"] as? String ?? "", amount: (d["amount"] as? NSNumber)?.doubleValue,
currency: d["currency"] as? String) 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")) 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 { 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.running = (id, r["title"] as? String ?? "", r["minutes"] as? Int ?? 0)
} }
@@ -143,12 +158,12 @@ final class OpsClient: ObservableObject {
func refreshAll() async { func refreshAll() async {
await refresh() await refresh()
if let arr = await request("/api/tasks") as? [[String: Any]] { if let arr = await request(showDone ? "/api/tasks?all=1" : "/api/tasks") as? [[String: Any]] {
func task(_ d: [String: Any]) -> OpsTask { func task(_ d: [String: Any]) -> OpsTask {
OpsTask(id: d["id"] as? Int ?? 0, parentId: d["parent_id"] as? Int, title: d["title"] as? String ?? "", 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", 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, 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)) children: (d["children"] as? [[String: Any]] ?? []).map(task), notes: d["notes"] as? String ?? "")
} }
tasks = arr.map(task) tasks = arr.map(task)
} }
@@ -157,7 +172,9 @@ final class OpsClient: ObservableObject {
OpsSub(id: d["id"] as? Int ?? 0, name: d["name"] as? String ?? "", amount: (d["amount"] as? NSNumber)?.doubleValue ?? 0, 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", currency: d["currency"] as? String ?? "RUB", period: d["period"] as? String ?? "month",
every: d["every"] as? Int ?? 1, next: d["next_date"] as? String ?? "", remindDays: d["remind_days"] as? Int ?? 3, every: d["every"] as? Int ?? 1, next: d["next_date"] as? String ?? "", remindDays: d["remind_days"] as? Int ?? 3,
client: d["client"] as? String ?? "") 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 byClient = (j["by_client"] as? [String: [String: Any]] ?? [:]).mapValues { m in
m.compactMapValues { ($0 as? NSNumber)?.doubleValue } m.compactMapValues { ($0 as? NSNumber)?.doubleValue }
@@ -166,7 +183,7 @@ final class OpsClient: ObservableObject {
if let arr = await request("/api/routines") as? [[String: Any]] { if let arr = await request("/api/routines") as? [[String: Any]] {
routines = arr.map { d in routines = arr.map { d in
OpsRoutine(id: d["id"] as? Int ?? 0, title: d["title"] as? String ?? "", everyDays: d["every_days"] as? Int ?? 1, 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) next: d["next_date"] as? String ?? "", last: d["last_done"] as? String, notes: d["notes"] as? String ?? "")
} }
} }
fullLoaded = true fullLoaded = true
@@ -189,6 +206,17 @@ final class OpsClient: ObservableObject {
if fullLoaded { await refreshAll() } else { await refresh() } 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 { func done(_ it: OpsItem) async {
switch it.kind { switch it.kind {
case "task": await act(["op": "complete_task", "id": it.ref]) case "task": await act(["op": "complete_task", "id": it.ref])
@@ -310,6 +338,10 @@ struct OpsPanel: View {
header("СЕГОДНЯ", "#F5A524") header("СЕГОДНЯ", "#F5A524")
ForEach(ops.agenda.today) { OpsRow(item: $0) } 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 { if !ops.agenda.soon.isEmpty {
Button { withAnimation(.easeOut(duration: 0.15)) { showWeek.toggle() } } label: { Button { withAnimation(.easeOut(duration: 0.15)) { showWeek.toggle() } } label: {
HStack(spacing: 4) { HStack(spacing: 4) {
@@ -323,7 +355,7 @@ struct OpsPanel: View {
.buttonStyle(.plain) .buttonStyle(.plain)
if showWeek { ForEach(ops.agenda.soon) { OpsRow(item: $0) } } if showWeek { ForEach(ops.agenda.soon) { OpsRow(item: $0) } }
} }
if ops.configured && ops.reachable == true && ops.agenda.running == nil 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 { && ops.agenda.overdue.isEmpty && ops.agenda.today.isEmpty && ops.agenda.soon.isEmpty {
Text("На неделю ничего не горит 👌").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) Text("На неделю ничего не горит 👌").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
.padding(.vertical, 8).padding(.leading, 6) .padding(.vertical, 8).padding(.leading, 6)
@@ -404,6 +436,38 @@ struct OpsInput: View {
} }
} }
/// 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. /// One agenda line: ○ done on the left (₽ «Оплачено» for subscriptions), ⏱ / ⏰ on hover.
struct OpsRow: View { struct OpsRow: View {
let item: OpsItem let item: OpsItem
@@ -445,7 +509,7 @@ struct OpsRow: View {
} }
if item.kind == "sub" { if item.kind == "sub" {
Button { Task { await ops.done(item) } } label: { Button { Task { await ops.done(item) } } label: {
Text("Оплачено").font(.system(size: 10.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA")) Text("Оплачено?").font(.system(size: 10.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA"))
.padding(.horizontal, 7).frame(height: 18) .padding(.horizontal, 7).frame(height: 18)
.background(Capsule().fill(Color(hex: "#60A5FA").opacity(0.14))) .background(Capsule().fill(Color(hex: "#60A5FA").opacity(0.14)))
} }
+279
View File
@@ -0,0 +1,279 @@
import SwiftUI
// MARK: - Edit / create forms for «Весь план» (tasks, subscriptions, routines)
//
// Everything goes through the service's /api/action (the same checked operations Claude
// uses); deletion through /api/delete, only by an explicit click and a confirmation.
enum OpsEdit: Identifiable {
case task(OpsTask?), sub(OpsSub?), routine(OpsRoutine?)
var id: String {
switch self {
case .task(let t): return "task-\(t?.id ?? 0)"
case .sub(let s): return "sub-\(s?.id ?? 0)"
case .routine(let r): return "routine-\(r?.id ?? 0)"
}
}
}
struct OpsEditSheet: View {
let edit: OpsEdit
@Environment(\.dismiss) private var dismiss
var body: some View {
Group {
switch edit {
case .task(let t): TaskForm(task: t, close: { dismiss() })
case .sub(let s): SubForm(sub: s, close: { dismiss() })
case .routine(let r): RoutineForm(routine: r, close: { dismiss() })
}
}
.frame(width: 440)
.padding(18)
.preferredColorScheme(.dark)
}
}
// MARK: - Shared bits
enum OpsDate {
private static let f: DateFormatter = {
let f = DateFormatter(); f.calendar = Calendar(identifier: .gregorian); f.dateFormat = "yyyy-MM-dd"; return f
}()
static func date(_ iso: String?) -> Date? { iso.flatMap { f.date(from: String($0.prefix(10))) } }
static func iso(_ d: Date) -> String { f.string(from: d) }
}
/// Company: none, the three known ones, or any other name.
struct ClientPicker: View {
@Binding var client: String
private let known = ["", "saga", "planet9", "home"]
@State private var custom = false
var body: some View {
HStack {
Picker("Компания", selection: Binding(
get: { custom || !known.contains(client) ? "other" : client },
set: { v in
if v == "other" { custom = true; if known.contains(client) { client = "" } }
else { custom = false; client = v }
})) {
Text("—").tag("")
Text("Сага").tag("saga")
Text("Planet9").tag("planet9")
Text("Дом").tag("home")
Text("Другая…").tag("other")
}
if custom || !known.contains(client) {
TextField("название", text: $client).textFieldStyle(.roundedBorder).frame(width: 140)
}
}
}
}
struct FormButtons: View {
let isNew: Bool
let canSave: Bool
let save: () -> Void
let delete: () -> Void
let close: () -> Void
@State private var confirm = false
var body: some View {
HStack {
if !isNew {
Button("Удалить", role: .destructive) { confirm = true }
.confirmationDialog("Удалить без возможности вернуть?", isPresented: $confirm) {
Button("Удалить", role: .destructive) { delete() }
Button("Отмена", role: .cancel) {}
}
}
Spacer()
Button("Отмена", action: close).keyboardShortcut(.cancelAction)
Button(isNew ? "Создать" : "Сохранить", action: save)
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
.disabled(!canSave)
}
.padding(.top, 6)
}
}
// MARK: - Task
struct TaskForm: View {
let task: OpsTask?
let close: () -> Void
@ObservedObject private var ops = OpsClient.shared
@State private var title = ""
@State private var notes = ""
@State private var status = "todo"
@State private var hasDue = false
@State private var due = Date()
@State private var client = ""
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text(task == nil ? "Новая задача" : "Задача #\(task!.id)").font(.system(size: 16, weight: .semibold))
TextField("Что сделать", text: $title).textFieldStyle(.roundedBorder)
Text("Описание").font(.system(size: 11)).foregroundColor(.secondary)
TextEditor(text: $notes).font(.system(size: 12.5)).frame(height: 90)
.overlay(RoundedRectangle(cornerRadius: 6).stroke(Color.white.opacity(0.12)))
Picker("Статус", selection: $status) {
Text("Не начата").tag("todo"); Text("В работе").tag("doing"); Text("Сделана").tag("done")
}
.pickerStyle(.segmented)
HStack {
Toggle("Срок", isOn: $hasDue)
if hasDue { DatePicker("", selection: $due, displayedComponents: .date).labelsHidden() }
Spacer()
}
ClientPicker(client: $client)
FormButtons(isNew: task == nil, canSave: !title.trimmingCharacters(in: .whitespaces).isEmpty,
save: save, delete: { Task { await ops.delete("task", task!.id); close() } }, close: close)
}
.onAppear {
guard let t = task else { return }
title = t.title; notes = t.notes; status = t.status; client = t.client
if let d = OpsDate.date(t.due) { hasDue = true; due = d }
}
}
private func save() {
var body: [String: Any] = ["title": title, "notes": notes, "client": client.lowercased(),
"due": hasDue ? OpsDate.iso(due) : ""]
Task {
if let t = task {
body["op"] = "update_task"; body["id"] = t.id; body["status"] = status
await ops.act(body)
} else {
body["op"] = "add_task"
if !hasDue { body.removeValue(forKey: "due") }
await ops.act(body)
if status != "todo", let new = ops.tasks.flatMap({ [$0] + $0.children }).max(by: { $0.id < $1.id }) {
await ops.act(["op": "update_task", "id": new.id, "status": status])
}
}
close()
}
}
}
// MARK: - Subscription
struct SubForm: View {
let sub: OpsSub?
let close: () -> Void
@ObservedObject private var ops = OpsClient.shared
@State private var name = ""
@State private var amount = ""
@State private var currency = "RUB"
@State private var period = "month"
@State private var every = 1
@State private var next = Date()
@State private var remind = 3
@State private var client = ""
@State private var paid = false
@State private var active = true
@State private var notes = ""
private var amountValue: Double? { Double(amount.replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: " ", with: "")) }
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text(sub == nil ? "Новая подписка" : "Подписка #\(sub!.id)").font(.system(size: 16, weight: .semibold))
TextField("Название (Claude Code, домен sanjeev.ru…)", text: $name).textFieldStyle(.roundedBorder)
HStack {
TextField("Сумма", text: $amount).textFieldStyle(.roundedBorder).frame(width: 110)
Picker("", selection: $currency) { Text("₽").tag("RUB"); Text("$").tag("USD"); Text("€").tag("EUR") }
.labelsHidden().frame(width: 70)
Text("каждые").foregroundColor(.secondary)
Stepper("\(every)", value: $every, in: 1...36).frame(width: 70)
Picker("", selection: $period) {
Text("день").tag("day"); Text("нед.").tag("week"); Text("мес.").tag("month"); Text("год").tag("year")
}
.labelsHidden().frame(width: 80)
}
HStack {
Text("Следующее списание").foregroundColor(.secondary)
DatePicker("", selection: $next, displayedComponents: .date).labelsHidden()
Spacer()
}
Stepper("Напомнить за \(remind) дн.", value: $remind, in: 0...60)
ClientPicker(client: $client)
HStack(spacing: 18) {
Toggle("Оплачено (текущее списание)", isOn: $paid)
Toggle("Активна", isOn: $active)
}
TextField("Заметка", text: $notes).textFieldStyle(.roundedBorder)
FormButtons(isNew: sub == nil, canSave: !name.trimmingCharacters(in: .whitespaces).isEmpty && amountValue != nil,
save: save, delete: { Task { await ops.delete("sub", sub!.id); close() } }, close: close)
}
.onAppear {
guard let s = sub else { return }
name = s.name; amount = OpsClient.amount(s.amount).replacingOccurrences(of: " ", with: ""); currency = s.currency
period = s.period; every = s.every; next = OpsDate.date(s.next) ?? Date(); remind = s.remindDays
client = s.client; paid = s.paid; active = s.active; notes = s.notes
}
}
private func save() {
var body: [String: Any] = ["name": name, "amount": amountValue ?? 0, "currency": currency, "period": period,
"every": every, "next_date": OpsDate.iso(next), "remind_days": remind,
"client": client.lowercased(), "notes": notes]
Task {
if let s = sub {
body["op"] = "update_sub"; body["id"] = s.id; body["paid"] = paid; body["active"] = active ? 1 : 0
await ops.act(body)
} else {
body["op"] = "add_sub"
await ops.act(body)
if paid, let new = ops.subs.max(by: { $0.id < $1.id }) {
await ops.act(["op": "update_sub", "id": new.id, "paid": true])
}
}
close()
}
}
}
// MARK: - Routine
struct RoutineForm: View {
let routine: OpsRoutine?
let close: () -> Void
@ObservedObject private var ops = OpsClient.shared
@State private var title = ""
@State private var everyDays = 7
@State private var next = Date()
@State private var notes = ""
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text(routine == nil ? "Новое регламентное дело" : "Регламент #\(routine!.id)").font(.system(size: 16, weight: .semibold))
TextField("Что делать (бэкап NAS, обновления…)", text: $title).textFieldStyle(.roundedBorder)
Stepper("Раз в \(everyDays) дн.", value: $everyDays, in: 1...365)
HStack {
Text("Следующий раз").foregroundColor(.secondary)
DatePicker("", selection: $next, displayedComponents: .date).labelsHidden()
Spacer()
}
TextField("Заметка", text: $notes).textFieldStyle(.roundedBorder)
FormButtons(isNew: routine == nil, canSave: !title.trimmingCharacters(in: .whitespaces).isEmpty,
save: save, delete: { Task { await ops.delete("routine", routine!.id); close() } }, close: close)
}
.onAppear {
guard let r = routine else { return }
title = r.title; everyDays = r.everyDays; next = OpsDate.date(r.next) ?? Date(); notes = r.notes
}
}
private func save() {
var body: [String: Any] = ["title": title, "every_days": everyDays, "next_date": OpsDate.iso(next), "notes": notes]
Task {
if let r = routine { body["op"] = "update_routine"; body["id"] = r.id } else { body["op"] = "add_routine" }
await ops.act(body)
close()
}
}
}
+106 -16
View File
@@ -36,6 +36,46 @@ enum OpsWindow {
} }
} }
/// Which form is open in «Весь план».
@MainActor
final class OpsUI: ObservableObject {
static let shared = OpsUI()
@Published var edit: OpsEdit?
func open(kind: String, ref: Int) {
let ops = OpsClient.shared
func find(_ ts: [OpsTask]) -> OpsTask? {
for t in ts { if t.id == ref { return t }; if let c = find(t.children) { return c } }
return nil
}
switch kind {
case "task": if let t = find(ops.tasks) { edit = .task(t) }
case "sub": if let s = ops.subs.first(where: { $0.id == ref }) { edit = .sub(s) }
default: if let r = ops.routines.first(where: { $0.id == ref }) { edit = .routine(r) }
}
}
}
/// Section title with «+ new».
struct ListHeader<Extra: View>: View {
let title: String
let add: () -> Void
@ViewBuilder var extra: () -> Extra
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 10) {
Text(title).font(.system(size: 18, weight: .semibold))
Button(action: add) {
Image(systemName: "plus").font(.system(size: 12, weight: .bold))
.frame(width: 22, height: 22).background(Circle().fill(Color.white.opacity(0.08)))
}
.buttonStyle(.plain).help("Создать")
Spacer()
extra()
}
}
}
enum OpsSection: String, CaseIterable, Identifiable { enum OpsSection: String, CaseIterable, Identifiable {
case calendar = "Календарь", tasks = "Задачи", subs = "Подписки", routines = "Регламент" case calendar = "Календарь", tasks = "Задачи", subs = "Подписки", routines = "Регламент"
var id: String { rawValue } var id: String { rawValue }
@@ -51,6 +91,7 @@ enum OpsSection: String, CaseIterable, Identifiable {
struct OpsOverview: View { struct OpsOverview: View {
@ObservedObject private var ops = OpsClient.shared @ObservedObject private var ops = OpsClient.shared
@ObservedObject private var ui = OpsUI.shared
@State private var section: OpsSection = .calendar @State private var section: OpsSection = .calendar
@State private var text = "" @State private var text = ""
@FocusState private var focused: Bool @FocusState private var focused: Bool
@@ -111,6 +152,7 @@ struct OpsOverview: View {
} }
.foregroundColor(Color(hex: "#F5F6F8")) .foregroundColor(Color(hex: "#F5F6F8"))
.task { await ops.refreshAll() } .task { await ops.refreshAll() }
.sheet(item: $ui.edit) { OpsEditSheet(edit: $0) }
} }
private func count(_ s: OpsSection) -> Int? { private func count(_ s: OpsSection) -> Int? {
@@ -205,9 +247,11 @@ struct OpsCalendar: View {
Text(it.title).font(.system(size: 12.5, weight: .medium)) Text(it.title).font(.system(size: 12.5, weight: .medium))
Text(it.detail + (it.projected ? " · повтор" : "")).font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C")) Text(it.detail + (it.projected ? " · повтор" : "")).font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C"))
} }
.contentShape(Rectangle())
.onTapGesture { OpsUI.shared.open(kind: it.kind, ref: it.ref) }
Spacer() Spacer()
if !it.projected { if !it.projected && !(it.kind == "sub" && ops.subs.first(where: { $0.id == it.ref })?.paid == true) {
Button(it.kind == "sub" ? "Оплачено" : "Сделано") { Button(it.kind == "sub" ? "Оплачено?" : "Сделано") {
Task { await ops.done(OpsItem(kind: it.kind, ref: it.ref, title: it.title, date: it.date, client: "")) } 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)) .buttonStyle(.plain).font(.system(size: 11, weight: .medium))
@@ -330,7 +374,9 @@ struct OpsTaskList: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
Text("Задачи").font(.system(size: 18, weight: .semibold)) ListHeader(title: "Задачи", add: { OpsUI.shared.edit = .task(nil) }) {
Toggle("Показывать сделанные", isOn: $ops.showDone).toggleStyle(.checkbox).font(.system(size: 12))
}
if ops.tasks.isEmpty { if ops.tasks.isEmpty {
Text("Открытых задач нет. Запиши ниже: «в Planet9 переезд серверной: купить свитч, проверить ИБП»") Text("Открытых задач нет. Запиши ниже: «в Planet9 переезд серверной: купить свитч, проверить ИБП»")
.font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) .font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
@@ -363,12 +409,20 @@ struct OpsTaskRow: View {
} else { } else {
Color.clear.frame(width: 12, height: 1) Color.clear.frame(width: 12, height: 1)
} }
Button { Task { await ops.act(["op": "complete_task", "id": task.id]) } } label: { Button {
Image(systemName: hovered ? "checkmark.circle" : "circle").font(.system(size: 14)) Task { await ops.act(["op": isDone ? "reopen_task" : "complete_task", "id": task.id]) }
.foregroundColor(Color(hex: overdue ? "#F4505E" : "#8E939C")) } label: {
Image(systemName: isDone ? "checkmark.circle.fill" : (hovered ? "checkmark.circle" : "circle")).font(.system(size: 14))
.foregroundColor(Color(hex: isDone ? "#34D399" : (overdue ? "#F4505E" : "#8E939C")))
} }
.buttonStyle(.plain).help("Сделано (вместе с подзадачами)") .buttonStyle(.plain).help(isDone ? "Вернуть в работу" : "Сделано (вместе с подзадачами)")
Text(task.title).font(.system(size: 13, weight: depth == 0 ? .medium : .regular)) Text(task.title).font(.system(size: 13, weight: depth == 0 ? .medium : .regular))
.strikethrough(isDone).foregroundColor(Color(hex: isDone ? "#6B7079" : "#F5F6F8"))
.onTapGesture { OpsUI.shared.edit = .task(task) }
.help("Нажми, чтобы изменить")
if !task.notes.isEmpty {
Image(systemName: "text.alignleft").font(.system(size: 10)).foregroundColor(Color(hex: "#6B7079"))
}
if !task.children.isEmpty { if !task.children.isEmpty {
Text("подзадач: \(task.children.count)").font(.system(size: 10.5)).foregroundColor(Color(hex: "#8E939C")) Text("подзадач: \(task.children.count)").font(.system(size: 10.5)).foregroundColor(Color(hex: "#8E939C"))
.padding(.horizontal, 6).background(Capsule().fill(Color.white.opacity(0.06))) .padding(.horizontal, 6).background(Capsule().fill(Color.white.opacity(0.06)))
@@ -385,6 +439,12 @@ struct OpsTaskRow: View {
if let due = task.due { if let due = task.due {
Text(OpsClient.ruDay(due)).font(.system(size: 11)).foregroundColor(Color(hex: overdue ? "#F4505E" : "#8E939C")) Text(OpsClient.ruDay(due)).font(.system(size: 11)).foregroundColor(Color(hex: overdue ? "#F4505E" : "#8E939C"))
} }
Button {
OpsUI.shared.edit = .task(task)
} label: {
Image(systemName: "pencil").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
}
.buttonStyle(.plain).opacity(hovered ? 1 : 0).help("Изменить")
Button { Button {
Task { await ops.act(task.running ? ["op": "stop_timer"] : ["op": "start_timer", "id": task.id]) } Task { await ops.act(task.running ? ["op": "stop_timer"] : ["op": "start_timer", "id": task.id]) }
} label: { } label: {
@@ -404,8 +464,10 @@ struct OpsTaskRow: View {
} }
} }
private var isDone: Bool { task.status == "done" }
private var overdue: Bool { private var overdue: Bool {
guard let due = task.due else { return false } guard !isDone, let due = task.due else { return false }
return due < OpsCalendar.iso(Date()) return due < OpsCalendar.iso(Date())
} }
} }
@@ -421,9 +483,7 @@ struct OpsSubList: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .firstTextBaseline) { ListHeader(title: "Подписки", add: { OpsUI.shared.edit = .sub(nil) }) {
Text("Подписки").font(.system(size: 18, weight: .semibold))
Spacer()
if !ops.agenda.monthly.isEmpty { if !ops.agenda.monthly.isEmpty {
Text("всего в месяц: " + OpsClient.money(ops.agenda.monthly)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) Text("всего в месяц: " + OpsClient.money(ops.agenda.monthly)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE"))
} }
@@ -449,15 +509,17 @@ struct OpsSubList: View {
HStack(spacing: 10) { HStack(spacing: 10) {
Image(systemName: "creditcard").foregroundColor(Color(hex: "#60A5FA")) Image(systemName: "creditcard").foregroundColor(Color(hex: "#60A5FA"))
Text(s.name).font(.system(size: 13, weight: .medium)) Text(s.name).font(.system(size: 13, weight: .medium))
.onTapGesture { OpsUI.shared.edit = .sub(s) }.help("Нажми, чтобы изменить")
Spacer() Spacer()
Text("\(OpsClient.amount(s.amount)) \(OpsClient.symbol(s.currency)) / \(s.every > 1 ? "\(s.every) " : "")\(period[s.period] ?? s.period)") 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) .font(.system(size: 12)).frame(width: 150, alignment: .trailing)
Text(OpsClient.ruDay(s.next)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) Text(OpsClient.ruDay(s.next)).font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE"))
.frame(width: 90, alignment: .trailing) .frame(width: 90, alignment: .trailing)
Text("напомнить за \(s.remindDays) дн.").font(.system(size: 11)).foregroundColor(Color(hex: "#6B7079")) SubStatus(sub: s).frame(width: 250, alignment: .trailing)
.frame(width: 120, alignment: .trailing) Button { OpsUI.shared.edit = .sub(s) } label: {
Button("Оплачено") { Task { await ops.act(["op": "pay_sub", "id": s.id]) } } Image(systemName: "pencil").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
.buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA")) }
.buttonStyle(.plain).help("Изменить")
} }
.padding(.horizontal, 10).padding(.vertical, 8) .padding(.horizontal, 10).padding(.vertical, 8)
.background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04))) .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04)))
@@ -474,7 +536,7 @@ struct OpsRoutineList: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
Text("Регламент").font(.system(size: 18, weight: .semibold)) ListHeader(title: "Регламент", add: { OpsUI.shared.edit = .routine(nil) }) { EmptyView() }
if ops.routines.isEmpty { if ops.routines.isEmpty {
Text("Регламентных дел нет. Запиши ниже: «бэкап хоумлаба раз в неделю»") Text("Регламентных дел нет. Запиши ниже: «бэкап хоумлаба раз в неделю»")
.font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C")) .font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
@@ -486,6 +548,7 @@ struct OpsRoutineList: View {
HStack(spacing: 10) { HStack(spacing: 10) {
Image(systemName: "arrow.triangle.2.circlepath").foregroundColor(Color(hex: "#34D399")) Image(systemName: "arrow.triangle.2.circlepath").foregroundColor(Color(hex: "#34D399"))
Text(r.title).font(.system(size: 13, weight: .medium)) Text(r.title).font(.system(size: 13, weight: .medium))
.onTapGesture { OpsUI.shared.edit = .routine(r) }.help("Нажми, чтобы изменить")
Spacer() Spacer()
Text("раз в \(r.everyDays) дн.").font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE")) Text("раз в \(r.everyDays) дн.").font(.system(size: 12)).foregroundColor(Color(hex: "#B0B5BE"))
.frame(width: 100, alignment: .trailing) .frame(width: 100, alignment: .trailing)
@@ -495,6 +558,10 @@ struct OpsRoutineList: View {
.foregroundColor(Color(hex: "#6B7079")).frame(width: 110, alignment: .trailing) .foregroundColor(Color(hex: "#6B7079")).frame(width: 110, alignment: .trailing)
Button("Сделано") { Task { await ops.act(["op": "done_routine", "id": r.id]) } } Button("Сделано") { Task { await ops.act(["op": "done_routine", "id": r.id]) } }
.buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#34D399")) .buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#34D399"))
Button { OpsUI.shared.edit = .routine(r) } label: {
Image(systemName: "pencil").font(.system(size: 12)).foregroundColor(Color(hex: "#8E939C"))
}
.buttonStyle(.plain).help("Изменить")
} }
.padding(.horizontal, 10).padding(.vertical, 8) .padding(.horizontal, 10).padding(.vertical, 8)
.background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04))) .background(RoundedRectangle(cornerRadius: 8).fill(Color.white.opacity(0.04)))
@@ -504,3 +571,26 @@ struct OpsRoutineList: View {
} }
} }
} }
/// «Оплачено?» → «✓ Оплачено · повторить <date>? Повторить / Нет».
struct SubStatus: View {
let sub: OpsSub
@ObservedObject private var ops = OpsClient.shared
var body: some View {
HStack(spacing: 8) {
if sub.paid {
Text("✓ Оплачено").font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#34D399"))
Button("Повторить \(OpsClient.ruDay(sub.nextIfRepeat))") { Task { await ops.repeatSub(sub.id, true) } }
.buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA"))
Button("Нет") { Task { await ops.repeatSub(sub.id, false) } }
.buttonStyle(.plain).font(.system(size: 11.5)).foregroundColor(Color(hex: "#8E939C"))
.help("Больше не повторять — подписка закроется")
} else {
Text("напомнить за \(sub.remindDays) дн.").font(.system(size: 11)).foregroundColor(Color(hex: "#6B7079"))
Button("Оплачено?") { Task { await ops.act(["op": "pay_sub", "id": sub.id]) } }
.buttonStyle(.plain).font(.system(size: 11.5, weight: .medium)).foregroundColor(Color(hex: "#60A5FA"))
}
}
}
}
+43 -10
View File
@@ -125,16 +125,27 @@ async def cmd_stop(update: Update, ctx):
await update.message.reply_text(f"⏹ Остановил: {t['title']}" if t else "Таймер не шёл.") await update.message.reply_text(f"⏹ Остановил: {t['title']}" if t else "Таймер не шёл.")
def repeat_buttons(sub: dict) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[
InlineKeyboardButton(f"🔁 Да, {ru_day(sub['next_if_repeat'])}", callback_data=f"rep:sub:{sub['id']}:1"),
InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]])
async def think(update: Update, text: str): async def think(update: Update, text: str):
msg = await update.effective_message.reply_text("🤔 думаю…") msg = await update.effective_message.reply_text("🤔 думаю…")
paid: list = []
try: try:
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"]) answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"], paid)
except OpsError as e: except OpsError as e:
answer = f"Не получилось: {e}" answer = f"Не получилось: {e}"
except Exception as e: # Claude timeout, CLI missing… except Exception as e: # Claude timeout, CLI missing…
log.exception("brain") log.exception("brain")
answer = f"Ошибка: {e.__class__.__name__}" answer = f"Ошибка: {e.__class__.__name__}"
await msg.edit_text(answer[:4000]) await msg.edit_text(answer[:4000])
for sid in paid: # paid by text: ask «repeat?» with buttons
s = locked(ops.sub, sid)
if s["paid"] and s["active"]:
await update.effective_message.reply_text(f"₽ {s['name']} оплачена. Повторить?", reply_markup=repeat_buttons(s))
@owner_only @owner_only
@@ -168,7 +179,7 @@ async def on_voice(update: Update, ctx):
def reminder_buttons(it: dict) -> InlineKeyboardMarkup: def reminder_buttons(it: dict) -> InlineKeyboardMarkup:
kind, ref = it["kind"], it["id"] kind, ref = it["kind"], it["id"]
first = {"task": "✓ Сделано", "sub": "₽ Оплачено", "routine": "✓ Сделано"}[kind] first = {"task": "✓ Сделано", "sub": "₽ Оплачено?", "routine": "✓ Сделано"}[kind]
return InlineKeyboardMarkup([[InlineKeyboardButton(first, callback_data=f"done:{kind}:{ref}"), return InlineKeyboardMarkup([[InlineKeyboardButton(first, callback_data=f"done:{kind}:{ref}"),
InlineKeyboardButton("⏰ Завтра", callback_data=f"snooze:{kind}:{ref}")]]) InlineKeyboardButton("⏰ Завтра", callback_data=f"snooze:{kind}:{ref}")]])
@@ -177,16 +188,22 @@ async def on_button(update: Update, ctx):
q = update.callback_query q = update.callback_query
if not q or q.message.chat.id != owner(): if not q or q.message.chat.id != owner():
return return
action, kind, ref = q.data.split(":") parts = q.data.split(":")
ref = int(ref) action, kind, ref = parts[0], parts[1], int(parts[2])
markup = None
try: try:
with lock: with lock:
if action == "done": if action == "rep":
s = ops.repeat_sub(ref, parts[3] == "1")
note = (f"🔁 Следующее списание {ru_day(s['next_date'])}" if s["active"]
else "✓ Закрыта, больше не повторяется")
elif action == "done":
if kind == "task": if kind == "task":
note = f"✓ Сделано: {ops.complete_task(ref)['title']}" note = f"✓ Сделано: {ops.complete_task(ref)['title']}"
elif kind == "sub": elif kind == "sub":
s = ops.pay_sub(ref) s = ops.pay_sub(ref)
note = f"₽ Оплачено: {s['name']}, следующее списание {ru_day(s['next_date'])}" note = f"₽ Оплачено. Повторить {ru_day(s['next_if_repeat'])}?"
markup = repeat_buttons(s)
else: else:
r = ops.done_routine(ref) r = ops.done_routine(ref)
note = f"✓ {r['title']}: следующий раз {ru_day(r['next_date'])}" note = f"✓ {r['title']}: следующий раз {ru_day(r['next_date'])}"
@@ -196,7 +213,7 @@ async def on_button(update: Update, ctx):
except OpsError as e: except OpsError as e:
note = f"Не получилось: {e}" note = f"Не получилось: {e}"
await q.answer() await q.answer()
await q.edit_message_text(q.message.text + "\n\n" + note) await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup)
# MARK: - Reminders # MARK: - Reminders
@@ -248,13 +265,14 @@ async def api_agenda(request):
async def api_tasks(request): async def api_tasks(request):
check_auth(request) check_auth(request)
return ok(locked(ops.task_tree)) return ok(locked(ops.task_tree, request.query.get("all") == "1"))
async def api_subs(request): async def api_subs(request):
check_auth(request) check_auth(request)
with lock: with lock:
return ok({"subs": ops.subs(), "monthly_cost": ops.monthly_cost(), "by_client": ops.monthly_by_client()}) return ok({"subs": ops.subs(active_only=request.query.get("all") != "1"), "monthly_cost": ops.monthly_cost(),
"by_client": ops.monthly_by_client()})
async def api_routines(request): async def api_routines(request):
@@ -288,6 +306,21 @@ async def api_action(request):
return ok({"ok": not any(r.startswith("✗") for r in result), "result": result}) return ok({"ok": not any(r.startswith("✗") for r in result), "result": result})
async def api_delete(request):
"""Delete by an explicit click in BroV (Claude never deletes)."""
check_auth(request)
body = await request.json()
kind, ref = str(body.get("kind")), int(body.get("id"))
fn = {"task": ops.delete_task, "sub": ops.delete_sub, "routine": ops.delete_routine}.get(kind)
if not fn:
raise web.HTTPBadRequest(text="kind")
try:
locked(fn, ref)
except OpsError as e:
return ok({"ok": False, "result": [str(e)]})
return ok({"ok": True, "result": ["🗑 удалено"]})
async def api_health(request): async def api_health(request):
return ok({"ok": True}) return ok({"ok": True})
@@ -297,7 +330,7 @@ def make_api() -> web.Application:
app.add_routes([web.get("/api/health", api_health), web.get("/api/agenda", api_agenda), app.add_routes([web.get("/api/health", api_health), web.get("/api/agenda", api_agenda),
web.get("/api/tasks", api_tasks), web.get("/api/subs", api_subs), web.get("/api/tasks", api_tasks), web.get("/api/subs", api_subs),
web.get("/api/routines", api_routines), web.post("/api/say", api_say), web.get("/api/routines", api_routines), web.post("/api/say", api_say),
web.post("/api/action", api_action)]) web.post("/api/action", api_action), web.post("/api/delete", api_delete)])
return app return app
+24 -9
View File
@@ -26,7 +26,9 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
period: day | week | month | year (по умолчанию month); currency по умолчанию RUB; period: day | week | month | year (по умолчанию month); currency по умолчанию RUB;
client — компания, за которую платится подписка («компания сага», «для планеты») client — компания, за которую платится подписка («компания сага», «для планеты»)
- update_sub {id, name?, amount?, next_date?, client?, period?, every?, currency?, remind_days?, notes?, active?} - update_sub {id, name?, amount?, next_date?, client?, period?, every?, currency?, remind_days?, notes?, active?}
- pay_sub {id, amount?, paid_on?} оплачено: следующая дата сдвинется сама - pay_sub {id, amount?, paid_on?} отметить текущее списание оплаченным (статус «Оплачено»)
- repeat_sub {id, repeat} после оплаты: repeat=true — следующее списание через период,
repeat=false — подписка больше не нужна (закрыть)
- add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…) - add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…)
- done_routine {id, note?} - done_routine {id, note?}
- update_routine {id, title?, every_days?, next_date?, notes?, active?} - update_routine {id, title?, every_days?, next_date?, notes?, active?}
@@ -40,11 +42,13 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
actions пустой, ответ в reply по данным ниже. actions пустой, ответ в reply по данным ниже.
- Если непонятно, что сделать, — actions пустой, в reply переспроси. - Если непонятно, что сделать, — actions пустой, в reply переспроси.
- Ничего не удаляй. Не выдумывай id — бери только из данных ниже. - Ничего не удаляй. Не выдумывай id — бери только из данных ниже.
- После pay_sub добавляй repeat_sub, только если пользователь сам сказал, продлевать или нет
(«оплатил и продлеваем», «больше не нужна»); иначе в reply спроси, повторять ли.
- reply — 1–3 строки, без markdown-заголовков. - reply — 1–3 строки, без markdown-заголовков.
""" """
ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer", ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer",
"add_sub", "update_sub", "pay_sub", "add_routine", "done_routine", "update_routine"} "add_sub", "update_sub", "pay_sub", "repeat_sub", "add_routine", "done_routine", "update_routine"}
def snapshot(ops: Ops) -> str: def snapshot(ops: Ops) -> str:
@@ -62,7 +66,8 @@ def snapshot(ops: Ops) -> str:
lines += ["", "Подписки (id, сумма, период, следующее списание, компания):"] lines += ["", "Подписки (id, сумма, период, следующее списание, компания):"]
for s in ops.subs(active_only=False): for s in ops.subs(active_only=False):
lines.append(f"- #{s['id']} {s['name']} | {s['amount']:g} {s['currency']} | каждые {s['every']} {s['period']} | " lines.append(f"- #{s['id']} {s['name']} | {s['amount']:g} {s['currency']} | каждые {s['every']} {s['period']} | "
f"{s['next_date']} | {s['client'] or '-'} | {'активна' if s['active'] else 'выкл'}") f"{s['next_date']} | {s['client'] or '-'} | {'активна' if s['active'] else 'выкл'}"
f"{' | ОПЛАЧЕНО, ждёт решения о повторе' if s['paid'] and s['active'] else ''}")
lines.append(f"Итого в месяц: {ops.monthly_cost()}") lines.append(f"Итого в месяц: {ops.monthly_cost()}")
lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"] lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"]
for r in ops.routines(): for r in ops.routines():
@@ -95,9 +100,11 @@ def parse_plan(text: str) -> dict:
return plan return plan
def apply_plan(ops: Ops, plan: dict) -> list[str]: def apply_plan(ops: Ops, plan: dict, paid: list | None = None) -> list[str]:
"""Carries out the actions in order; returns one human line per action.""" """Carries out the actions in order; returns one human line per action. `paid` collects
subscriptions paid here and still waiting for «repeat?»."""
done, keys = [], {} done, keys = [], {}
paid = paid if paid is not None else []
for a in plan.get("actions", []): for a in plan.get("actions", []):
op = a.get("op") if isinstance(a, dict) else None op = a.get("op") if isinstance(a, dict) else None
if op not in ALLOWED: if op not in ALLOWED:
@@ -135,11 +142,18 @@ def apply_plan(ops: Ops, plan: dict) -> list[str]:
+ (f", компания {client_name(s['client'])}" if s["client"] else "")) + (f", компания {client_name(s['client'])}" if s["client"] else ""))
elif op == "update_sub": elif op == "update_sub":
s = ops.update_sub(int(a["id"]), **_only(args, "name", "amount", "next_date", "period", "every", s = ops.update_sub(int(a["id"]), **_only(args, "name", "amount", "next_date", "period", "every",
"currency", "remind_days", "notes", "active", "client")) "currency", "remind_days", "notes", "active", "client", "paid"))
done.append(f"✎ подписка #{s['id']} {s['name']}") done.append(f"✎ подписка #{s['id']} {s['name']}")
elif op == "pay_sub": elif op == "pay_sub":
s = ops.pay_sub(int(a["id"]), a.get("amount"), a.get("paid_on")) s = ops.pay_sub(int(a["id"]), a.get("amount"), a.get("paid_on"))
done.append(f"₽ оплачено: {s['name']}, следующее списание {ru_day(s['next_date'])}") paid.append(s["id"])
done.append(f"₽ Оплачено: {s['name']}. Повторить {ru_day(s['next_if_repeat'])}?")
elif op == "repeat_sub":
s = ops.repeat_sub(int(a["id"]), bool(a.get("repeat", True)))
if s["id"] in paid:
paid.remove(s["id"])
done.append(f"🔁 {s['name']}: следующее списание {ru_day(s['next_date'])}" if s["active"]
else f"✓ {s['name']}: закрыта, больше не повторяется")
elif op == "add_routine": elif op == "add_routine":
r = ops.add_routine(**_only(args, "title", "every_days", "next_date", "notes")) r = ops.add_routine(**_only(args, "title", "every_days", "next_date", "notes"))
done.append(f"+ регламент #{r['id']} {r['title']}: раз в {r['every_days']} дн., след. {ru_day(r['next_date'])}") done.append(f"+ регламент #{r['id']} {r['title']}: раз в {r['every_days']} дн., след. {ru_day(r['next_date'])}")
@@ -158,13 +172,14 @@ def _only(d: dict, *keys) -> dict:
return {k: d[k] for k in keys if k in d} return {k: d[k] for k in keys if k in d}
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku") -> str: def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku",
paid: list | None = None) -> str:
"""One message in, one answer out (actions taken + Claude's reply). The database lock """One message in, one answer out (actions taken + Claude's reply). The database lock
is held only while reading the state and applying the actions, not while Claude thinks.""" is held only while reading the state and applying the actions, not while Claude thinks."""
with lock: with lock:
prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip() prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip()
plan = parse_plan(ask_claude(prompt, claude_bin, model)) plan = parse_plan(ask_claude(prompt, claude_bin, model))
with lock: with lock:
lines = apply_plan(ops, plan) lines = apply_plan(ops, plan, paid)
reply = str(plan.get("reply", "")).strip() reply = str(plan.get("reply", "")).strip()
return "\n".join(([reply] if reply else []) + lines) or "Готово." return "\n".join(([reply] if reply else []) + lines) or "Готово."
+51 -13
View File
@@ -101,6 +101,8 @@ class Ops:
self.con.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?", (*vals, task_id)) self.con.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?", (*vals, task_id))
if fields.get("status") == "done": if fields.get("status") == "done":
self._finish(task_id) self._finish(task_id)
elif fields.get("status") in ("todo", "doing"):
self.con.execute("UPDATE tasks SET done_at = NULL WHERE id = ?", (task_id,))
return self.task(task_id) return self.task(task_id)
def complete_task(self, task_id: int) -> dict: def complete_task(self, task_id: int) -> dict:
@@ -188,11 +190,17 @@ class Ops:
# MARK: - Subscriptions and payments # MARK: - Subscriptions and payments
def _sub_row(self, row) -> dict:
s = dict(row)
s["paid"] = s.get("paid_for") == s["next_date"]
s["next_if_repeat"] = add_period(date.fromisoformat(s["next_date"]), s["period"], s["every"]).isoformat()
return s
def sub(self, sub_id: int) -> dict: def sub(self, sub_id: int) -> dict:
row = self.con.execute("SELECT * FROM subscriptions WHERE id = ?", (sub_id,)).fetchone() row = self.con.execute("SELECT * FROM subscriptions WHERE id = ?", (sub_id,)).fetchone()
if not row: if not row:
raise OpsError(f"подписки #{sub_id} нет") raise OpsError(f"подписки #{sub_id} нет")
return dict(row) return self._sub_row(row)
def add_sub(self, name: str, amount: float, next_date, period: str = "month", every: int = 1, def add_sub(self, name: str, amount: float, next_date, period: str = "month", every: int = 1,
currency: str = "RUB", remind_days: int = 3, notes: str = "", client: str = "") -> dict: currency: str = "RUB", remind_days: int = 3, notes: str = "", client: str = "") -> dict:
@@ -212,7 +220,8 @@ class Ops:
return self.sub(cur.lastrowid) return self.sub(cur.lastrowid)
def update_sub(self, sub_id: int, **fields) -> dict: def update_sub(self, sub_id: int, **fields) -> dict:
allowed = {"name", "amount", "currency", "period", "every", "next_date", "remind_days", "notes", "active", "client"} allowed = {"name", "amount", "currency", "period", "every", "next_date", "remind_days", "notes", "active", "client",
"paid"}
sets, vals = [], [] sets, vals = [], []
for k, v in fields.items(): for k, v in fields.items():
if k not in allowed or v is None: if k not in allowed or v is None:
@@ -223,28 +232,54 @@ class Ops:
raise OpsError(f"период может быть только {', '.join(PERIODS)}") raise OpsError(f"период может быть только {', '.join(PERIODS)}")
if k == "client": if k == "client":
v = str(v).strip().lower() v = str(v).strip().lower()
if k == "paid":
continue # applied below, against the (possibly new) date
sets.append(f"{k} = ?") sets.append(f"{k} = ?")
vals.append(v) vals.append(v)
if sets: if sets:
self.sub(sub_id) self.sub(sub_id)
self.con.execute(f"UPDATE subscriptions SET {', '.join(sets)} WHERE id = ?", (*vals, sub_id)) self.con.execute(f"UPDATE subscriptions SET {', '.join(sets)} WHERE id = ?", (*vals, sub_id))
if fields.get("paid") is not None: # status edited by hand: the current charge paid or not
self.con.execute("UPDATE subscriptions SET paid_for = CASE WHEN ? THEN next_date END WHERE id = ?",
(1 if fields["paid"] else 0, sub_id))
return self.sub(sub_id) return self.sub(sub_id)
def pay_sub(self, sub_id: int, amount: float | None = None, paid_on=None) -> dict: def pay_sub(self, sub_id: int, amount: float | None = None, paid_on=None) -> dict:
"""Records the payment and moves the next charge one period forward.""" """Marks the current charge paid (status «Оплачено») and records the payment. The
next charge appears only after «repeat?» is answered (repeat_sub)."""
s = self.sub(sub_id) s = self.sub(sub_id)
if s["paid"]:
return s
day = parse_day(paid_on) or self.today() day = parse_day(paid_on) or self.today()
self.con.execute("INSERT INTO payments (sub_id, paid_on, amount) VALUES (?, ?, ?)", self.con.execute("INSERT INTO payments (sub_id, paid_on, amount) VALUES (?, ?, ?)",
(sub_id, day.isoformat(), float(amount if amount is not None else s["amount"]))) (sub_id, day.isoformat(), float(amount if amount is not None else s["amount"])))
nxt = add_period(date.fromisoformat(s["next_date"]), s["period"], s["every"]) self.con.execute("UPDATE subscriptions SET paid_for = next_date WHERE id = ?", (sub_id,))
while nxt <= day: # paid late or far ahead: the next charge is still in the future
nxt = add_period(nxt, s["period"], s["every"])
self.con.execute("UPDATE subscriptions SET next_date = ? WHERE id = ?", (nxt.isoformat(), sub_id))
return self.sub(sub_id) return self.sub(sub_id)
def repeat_sub(self, sub_id: int, repeat: bool = True) -> dict:
"""After a payment: repeat → the next charge one period later (back to «Оплачено?»),
don't → the subscription is closed (kept, paid, inactive)."""
s = self.sub(sub_id)
if not repeat:
self.con.execute("UPDATE subscriptions SET active = 0 WHERE id = ?", (sub_id,))
return self.sub(sub_id)
nxt = add_period(date.fromisoformat(s["next_date"]), s["period"], s["every"])
while nxt < self.today(): # several periods behind: the next charge is still ahead
nxt = add_period(nxt, s["period"], s["every"])
self.con.execute("UPDATE subscriptions SET next_date = ?, active = 1 WHERE id = ?", (nxt.isoformat(), sub_id))
return self.sub(sub_id)
def delete_sub(self, sub_id: int) -> None:
self.sub(sub_id)
self.con.execute("DELETE FROM subscriptions WHERE id = ?", (sub_id,))
def delete_routine(self, rid: int) -> None:
self.routine(rid)
self.con.execute("DELETE FROM routines WHERE id = ?", (rid,))
def subs(self, active_only: bool = True) -> list[dict]: def subs(self, active_only: bool = True) -> list[dict]:
q = "SELECT * FROM subscriptions" + (" WHERE active = 1" if active_only else "") + " ORDER BY next_date" q = "SELECT * FROM subscriptions" + (" WHERE active = 1" if active_only else "") + " ORDER BY next_date"
return [dict(r) for r in self.con.execute(q)] return [self._sub_row(r) for r in self.con.execute(q)]
PER_MONTH = {"day": 30.44, "week": 4.345, "month": 1, "year": 1 / 12} PER_MONTH = {"day": 30.44, "week": 4.345, "month": 1, "year": 1 / 12}
@@ -324,7 +359,7 @@ class Ops:
def bucket(d: date) -> str: def bucket(d: date) -> str:
return "overdue" if d < today else ("today" if d == today else "soon") return "overdue" if d < today else ("today" if d == today else "soon")
out = {"today": today.isoformat(), "overdue": [], "due_today": [], "soon": [], out = {"today": today.isoformat(), "overdue": [], "due_today": [], "soon": [], "paid": [],
"running": None, "monthly_cost": self.monthly_cost()} "running": None, "monthly_cost": self.monthly_cost()}
key = {"overdue": "overdue", "today": "due_today", "soon": "soon"} key = {"overdue": "overdue", "today": "due_today", "soon": "soon"}
for t in self.con.execute("SELECT * FROM tasks WHERE status != 'done' AND due IS NOT NULL AND due <= ?", for t in self.con.execute("SELECT * FROM tasks WHERE status != 'done' AND due IS NOT NULL AND due <= ?",
@@ -334,9 +369,12 @@ class Ops:
"client": t["client"]}) "client": t["client"]})
for s in self.subs(): for s in self.subs():
d = date.fromisoformat(s["next_date"]) d = date.fromisoformat(s["next_date"])
if d <= horizon: item = {"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"], "amount": s["amount"],
out[key[bucket(d)]].append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"], "currency": s["currency"], "client": s["client"], "paid": s["paid"], "next_if_repeat": s["next_if_repeat"]}
"amount": s["amount"], "currency": s["currency"], "client": s["client"]}) if s["paid"]:
out["paid"].append(item) # paid, waiting for «repeat?»
elif d <= horizon:
out[key[bucket(d)]].append(item)
for r in self.routines(): for r in self.routines():
d = date.fromisoformat(r["next_date"]) d = date.fromisoformat(r["next_date"])
if d <= horizon: if d <= horizon:
@@ -363,7 +401,7 @@ class Ops:
out.append({"kind": "task", "id": t["id"], "title": t["title"], "date": t["due"]}) out.append({"kind": "task", "id": t["id"], "title": t["title"], "date": t["due"]})
for s in self.subs(): for s in self.subs():
d = date.fromisoformat(s["next_date"]) d = date.fromisoformat(s["next_date"])
if d - timedelta(days=s["remind_days"]) <= today and ("sub", s["id"]) not in sent: if not s["paid"] and d - timedelta(days=s["remind_days"]) <= today and ("sub", s["id"]) not in sent:
out.append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"], out.append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"],
"amount": s["amount"], "currency": s["currency"], "client": s["client"]}) "amount": s["amount"], "currency": s["currency"], "client": s["client"]})
for r in self.routines(): for r in self.routines():
+4 -1
View File
@@ -31,7 +31,8 @@ CREATE TABLE IF NOT EXISTS subscriptions (
remind_days INTEGER NOT NULL DEFAULT 3, remind_days INTEGER NOT NULL DEFAULT 3,
notes TEXT NOT NULL DEFAULT '', notes TEXT NOT NULL DEFAULT '',
active INTEGER NOT NULL DEFAULT 1, active INTEGER NOT NULL DEFAULT 1,
client TEXT NOT NULL DEFAULT '' -- company it's paid for: saga / planet9 / home / … client TEXT NOT NULL DEFAULT '', -- company it's paid for: saga / planet9 / home / …
paid_for TEXT -- = next_date once that charge is paid (until «repeat?» is answered)
); );
CREATE TABLE IF NOT EXISTS payments ( CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
@@ -76,4 +77,6 @@ def connect(path: str) -> sqlite3.Connection:
cols = {r["name"] for r in con.execute("PRAGMA table_info(subscriptions)")} cols = {r["name"] for r in con.execute("PRAGMA table_info(subscriptions)")}
if "client" not in cols: if "client" not in cols:
con.execute("ALTER TABLE subscriptions ADD COLUMN client TEXT NOT NULL DEFAULT ''") con.execute("ALTER TABLE subscriptions ADD COLUMN client TEXT NOT NULL DEFAULT ''")
if "paid_for" not in cols:
con.execute("ALTER TABLE subscriptions ADD COLUMN paid_for TEXT")
return con return con
+2 -1
View File
@@ -66,8 +66,9 @@ def subs(rows: list, by_client: dict, today: date) -> str:
out.append(f"\n<b>{escape(client_name(client) or 'Без компании')}</b> — {total} в мес.") out.append(f"\n<b>{escape(client_name(client) or 'Без компании')}</b> — {total} в мес.")
for s in (x for x in rows if x["client"] == client): for s in (x for x in rows if x["client"] == client):
every = f"{s['every']} " if s["every"] > 1 else "" every = f"{s['every']} " if s["every"] > 1 else ""
status = f" · ✓ оплачено, повторить {ru_day(s['next_if_repeat'])}?" if s["paid"] else ""
out.append(f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / {every}{per[s['period']]}" out.append(f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / {every}{per[s['period']]}"
f" · {human_day(s['next_date'], today)}") f" · {human_day(s['next_date'], today)}{status}")
return "\n".join(out).strip() return "\n".join(out).strip()
+45 -5
View File
@@ -46,13 +46,52 @@ class Tasks(unittest.TestCase):
class Subs(unittest.TestCase): class Subs(unittest.TestCase):
def test_pay_moves_next_date_past_today(self): def test_paid_then_repeat_or_close(self):
o = fresh() o = fresh()
long_ago = (o.today() - timedelta(days=70)).isoformat() due = (o.today() + timedelta(days=2)).isoformat()
s = o.add_sub("Хостинг", 900, long_ago) s = o.add_sub("Claude", 20, due, currency="USD", client="saga")
self.assertFalse(s["paid"])
self.assertEqual([x["id"] for x in o.agenda()["soon"]], [s["id"]])
s = o.pay_sub(s["id"]) s = o.pay_sub(s["id"])
self.assertGreater(date.fromisoformat(s["next_date"]), o.today()) self.assertTrue(s["paid"]) # status persists
self.assertTrue(o.sub(s["id"])["paid"])
self.assertEqual(o.pay_sub(s["id"])["id"], s["id"]) # paying twice records once
self.assertEqual(o.con.execute("SELECT COUNT(*) FROM payments").fetchone()[0], 1) self.assertEqual(o.con.execute("SELECT COUNT(*) FROM payments").fetchone()[0], 1)
a = o.agenda()
self.assertEqual([x["id"] for x in a["paid"]], [s["id"]])
self.assertEqual(a["soon"], [])
self.assertEqual([x for x in o.due_reminders() if x["kind"] == "sub"], [])
s = o.repeat_sub(s["id"], True)
self.assertEqual(s["next_date"], add_period(date.fromisoformat(due), "month").isoformat())
self.assertFalse(s["paid"])
o.pay_sub(s["id"])
s = o.repeat_sub(s["id"], False)
self.assertFalse(s["active"])
self.assertEqual(o.subs(), [])
def test_late_repeat_jumps_past_today(self):
o = fresh()
s = o.add_sub("Хостинг", 900, (o.today() - timedelta(days=70)).isoformat())
o.pay_sub(s["id"])
s = o.repeat_sub(s["id"])
self.assertGreaterEqual(date.fromisoformat(s["next_date"]), o.today())
def test_edit_everything(self):
o = fresh()
t = o.add_task("x")
o.update_task(t["id"], title="Новое", notes="тело", status="done", due="2026-12-01", client="home")
self.assertEqual(o.task(t["id"])["status"], "done")
o.update_task(t["id"], status="todo")
self.assertIsNone(o.task(t["id"])["done_at"])
s = o.add_sub("y", 1, "2026-12-01")
o.update_sub(s["id"], paid=True)
self.assertTrue(o.sub(s["id"])["paid"])
o.update_sub(s["id"], paid=False, amount=5, next_date="2026-12-05")
self.assertEqual((o.sub(s["id"])["paid"], o.sub(s["id"])["amount"]), (False, 5))
o.delete_sub(s["id"])
r = o.add_routine("z", 3)
o.delete_routine(r["id"])
self.assertEqual((o.subs(active_only=False), o.routines()), ([], []))
def test_monthly_cost(self): def test_monthly_cost(self):
o = fresh() o = fresh()
@@ -91,7 +130,8 @@ class Brain(unittest.TestCase):
{"op": "delete_everything"}, {"op": "delete_everything"},
{"op": "add_sub", "name": "Домен", "amount": 1200, "next_date": "2026-11-15", "period": "year"} {"op": "add_sub", "name": "Домен", "amount": 1200, "next_date": "2026-11-15", "period": "year"}
], "reply": "Записал"}''') ], "reply": "Записал"}''')
lines = brain.apply_plan(o, plan) paid = []
lines = brain.apply_plan(o, plan, paid)
self.assertTrue(lines[1].startswith("+ задача #2 Купить свитч (подзадача #1)")) self.assertTrue(lines[1].startswith("+ задача #2 Купить свитч (подзадача #1)"))
self.assertTrue(lines[2].startswith("✗")) self.assertTrue(lines[2].startswith("✗"))
self.assertEqual(o.subs()[0]["name"], "Домен") self.assertEqual(o.subs()[0]["name"], "Домен")