"""Everything BroV Ops can do with the data. The Telegram bot, the BroV API and the Claude "brain" all go through this class, so the rules live in one place.""" import calendar import sqlite3 from datetime import date, datetime, timedelta, timezone from zoneinfo import ZoneInfo PERIODS = ("day", "week", "month", "year") STATUSES = ("todo", "doing", "done") class OpsError(ValueError): """A request that can't be carried out (shown to the user as is).""" def add_period(d: date, period: str, every: int = 1) -> date: if period == "day": return d + timedelta(days=every) if period == "week": return d + timedelta(weeks=every) if period == "month": m = d.month - 1 + every y, m = d.year + m // 12, m % 12 + 1 return date(y, m, min(d.day, calendar.monthrange(y, m)[1])) if period == "year": y = d.year + every return date(y, d.month, min(d.day, calendar.monthrange(y, d.month)[1])) raise OpsError(f"неизвестный период: {period}") CLIENT_NAMES = {"saga": "Сага", "planet9": "Planet9", "home": "Дом"} def client_name(code: str) -> str: return CLIENT_NAMES.get(code, code) if code else "" def ru_day(iso) -> str: """2026-11-15 → 15.11.2026 (how dates are shown; storage stays ISO).""" if not iso: return "" try: return date.fromisoformat(str(iso)[:10]).strftime("%d.%m.%Y") except ValueError: return str(iso) def parse_day(s) -> date | None: if s in (None, ""): return None try: return date.fromisoformat(str(s)[:10]) except ValueError: raise OpsError(f"не понял дату: {s} (нужно ГГГГ-ММ-ДД)") class Ops: def __init__(self, con: sqlite3.Connection, tz: str = "Europe/Moscow"): self.con = con self.tz = ZoneInfo(tz) def today(self) -> date: return datetime.now(self.tz).date() # MARK: - Tasks def task(self, task_id: int) -> dict: row = self.con.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone() if not row: raise OpsError(f"задачи #{task_id} нет") return dict(row) def add_task(self, title: str, parent_id: int | None = None, due=None, client: str = "", notes: str = "") -> dict: title = (title or "").strip() if not title: raise OpsError("у задачи нет названия") if parent_id is not None: self.task(parent_id) d = parse_day(due) cur = self.con.execute( "INSERT INTO tasks (parent_id, title, due, client, notes) VALUES (?, ?, ?, ?, ?)", (parent_id, title, d.isoformat() if d else None, client or "", notes or "")) return self.task(cur.lastrowid) def update_task(self, task_id: int, **fields) -> dict: allowed = {"title", "notes", "client", "due", "status", "parent_id"} sets, vals = [], [] for k, v in fields.items(): if k not in allowed or v is None: continue if k == "due": d = parse_day(v) v = d.isoformat() if d else None if k == "status" and v not in STATUSES: raise OpsError(f"статус может быть только {', '.join(STATUSES)}") sets.append(f"{k} = ?") vals.append(v) if sets: self.task(task_id) self.con.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?", (*vals, task_id)) if fields.get("status") == "done": 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) def complete_task(self, task_id: int) -> dict: self.task(task_id) self._finish(task_id) return self.task(task_id) def _finish(self, task_id: int): """Done with all subtasks; a running timer stops.""" now = datetime.now(timezone.utc).isoformat(timespec="seconds") ids = [task_id] + [r["id"] for r in self._descendants(task_id)] for i in ids: self.con.execute("UPDATE tasks SET status = 'done', done_at = COALESCE(done_at, ?) WHERE id = ?", (now, i)) self.con.execute("UPDATE time_entries SET stopped = ? WHERE task_id = ? AND stopped IS NULL", (now, i)) def reopen_task(self, task_id: int) -> dict: self.task(task_id) self.con.execute("UPDATE tasks SET status = 'todo', done_at = NULL WHERE id = ?", (task_id,)) return self.task(task_id) def delete_task(self, task_id: int) -> None: self.task(task_id) self.con.execute("DELETE FROM tasks WHERE id = ?", (task_id,)) def _descendants(self, task_id: int) -> list: return self.con.execute(""" WITH RECURSIVE sub(id) AS (SELECT id FROM tasks WHERE parent_id = ? UNION ALL SELECT t.id FROM tasks t JOIN sub ON t.parent_id = sub.id) SELECT tasks.* FROM tasks JOIN sub ON tasks.id = sub.id""", (task_id,)).fetchall() def task_tree(self, include_done: bool = False) -> list[dict]: """Open tasks as a tree: [{…task, minutes, running, children: […]}].""" rows = [dict(r) for r in self.con.execute("SELECT * FROM tasks ORDER BY due IS NULL, due, id")] minutes = self._minutes() running = self.running_task_id() by_parent: dict = {} for r in rows: if not include_done and r["status"] == "done": continue r["minutes"] = minutes.get(r["id"], 0) r["running"] = r["id"] == running by_parent.setdefault(r["parent_id"], []).append(r) def build(parent): out = [] for r in by_parent.get(parent, []): r["children"] = build(r["id"]) out.append(r) return out return build(None) # MARK: - Time tracking def running_task_id(self) -> int | None: row = self.con.execute("SELECT task_id FROM time_entries WHERE stopped IS NULL LIMIT 1").fetchone() return row["task_id"] if row else None def start_timer(self, task_id: int) -> dict: """One timer at a time: starting a task stops the previous one.""" t = self.task(task_id) if t["status"] == "done": raise OpsError(f"задача #{task_id} уже сделана") now = datetime.now(timezone.utc).isoformat(timespec="seconds") self.con.execute("UPDATE time_entries SET stopped = ? WHERE stopped IS NULL", (now,)) self.con.execute("INSERT INTO time_entries (task_id, started) VALUES (?, ?)", (task_id, now)) self.con.execute("UPDATE tasks SET status = 'doing' WHERE id = ?", (task_id,)) return self.task(task_id) def stop_timer(self) -> dict | None: tid = self.running_task_id() if tid is None: return None now = datetime.now(timezone.utc).isoformat(timespec="seconds") self.con.execute("UPDATE time_entries SET stopped = ? WHERE stopped IS NULL", (now,)) return self.task(tid) def _minutes(self) -> dict[int, int]: now = datetime.now(timezone.utc) out: dict[int, float] = {} for r in self.con.execute("SELECT task_id, started, stopped FROM time_entries"): a = datetime.fromisoformat(r["started"]) b = datetime.fromisoformat(r["stopped"]) if r["stopped"] else now out[r["task_id"]] = out.get(r["task_id"], 0) + max(0.0, (b - a).total_seconds() / 60) return {k: int(round(v)) for k, v in out.items()} # 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: row = self.con.execute("SELECT * FROM subscriptions WHERE id = ?", (sub_id,)).fetchone() if not row: raise OpsError(f"подписки #{sub_id} нет") return self._sub_row(row) 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: if not (name or "").strip(): raise OpsError("у подписки нет названия") if period not in PERIODS: raise OpsError(f"период может быть только {', '.join(PERIODS)}") d = parse_day(next_date) if not d: raise OpsError("нужна дата следующего списания") cur = self.con.execute( """INSERT INTO subscriptions (name, amount, currency, period, every, next_date, remind_days, notes, client) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""", (name.strip(), float(amount or 0), (currency or "RUB").upper(), period, max(1, int(every or 1)), d.isoformat(), max(0, int(remind_days if remind_days is not None else 3)), notes or "", (client or "").strip().lower())) return self.sub(cur.lastrowid) def update_sub(self, sub_id: int, **fields) -> dict: allowed = {"name", "amount", "currency", "period", "every", "next_date", "remind_days", "notes", "active", "client", "paid"} sets, vals = [], [] for k, v in fields.items(): if k not in allowed or v is None: continue if k == "next_date": v = parse_day(v).isoformat() if k == "period" and v not in PERIODS: raise OpsError(f"период может быть только {', '.join(PERIODS)}") if k == "client": v = str(v).strip().lower() if k == "paid": continue # applied below, against the (possibly new) date sets.append(f"{k} = ?") vals.append(v) if sets: self.sub(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) def pay_sub(self, sub_id: int, amount: float | None = None, paid_on=None) -> dict: """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) if s["paid"]: return s day = parse_day(paid_on) or self.today() 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"]))) self.con.execute("UPDATE subscriptions SET paid_for = next_date WHERE id = ?", (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]: q = "SELECT * FROM subscriptions" + (" WHERE active = 1" if active_only else "") + " ORDER BY next_date" 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} def monthly_cost(self) -> dict[str, float]: """Active subscriptions per month, by currency.""" out: dict[str, float] = {} for s in self.subs(): out[s["currency"]] = out.get(s["currency"], 0) + s["amount"] * self.PER_MONTH[s["period"]] / s["every"] return {k: round(v, 2) for k, v in out.items()} def monthly_by_client(self) -> dict[str, dict[str, float]]: """Per month by company, then by currency ("" = no company).""" out: dict[str, dict[str, float]] = {} for s in self.subs(): c = out.setdefault(s["client"], {}) c[s["currency"]] = c.get(s["currency"], 0) + s["amount"] * self.PER_MONTH[s["period"]] / s["every"] return {k: {cur: round(v, 2) for cur, v in d.items()} for k, d in out.items()} # MARK: - Routines def routine(self, rid: int) -> dict: row = self.con.execute("SELECT * FROM routines WHERE id = ?", (rid,)).fetchone() if not row: raise OpsError(f"регламента #{rid} нет") return dict(row) def add_routine(self, title: str, every_days: int, next_date=None, notes: str = "") -> dict: if not (title or "").strip(): raise OpsError("у регламентного дела нет названия") n = int(every_days or 0) if n < 1: raise OpsError("периодичность — целое число дней, не меньше 1") d = parse_day(next_date) or self.today() cur = self.con.execute("INSERT INTO routines (title, every_days, next_date, notes) VALUES (?, ?, ?, ?)", (title.strip(), n, d.isoformat(), notes or "")) return self.routine(cur.lastrowid) def done_routine(self, rid: int, note: str = "", done_on=None) -> dict: r = self.routine(rid) day = parse_day(done_on) or self.today() self.con.execute("INSERT INTO routine_log (routine_id, done_on, note) VALUES (?, ?, ?)", (rid, day.isoformat(), note or "")) self.con.execute("UPDATE routines SET next_date = ? WHERE id = ?", ((day + timedelta(days=r["every_days"])).isoformat(), rid)) return self.routine(rid) def routines(self) -> list[dict]: rows = [dict(r) for r in self.con.execute("SELECT * FROM routines WHERE active = 1 ORDER BY next_date")] for r in rows: last = self.con.execute("SELECT done_on FROM routine_log WHERE routine_id = ? ORDER BY done_on DESC LIMIT 1", (r["id"],)).fetchone() r["last_done"] = last["done_on"] if last else None return rows def update_routine(self, rid: int, **fields) -> dict: allowed = {"title", "every_days", "next_date", "notes", "active"} sets, vals = [], [] for k, v in fields.items(): if k not in allowed or v is None: continue if k == "next_date": v = parse_day(v).isoformat() sets.append(f"{k} = ?") vals.append(v) if sets: self.routine(rid) self.con.execute(f"UPDATE routines SET {', '.join(sets)} WHERE id = ?", (*vals, rid)) return self.routine(rid) # MARK: - Agenda def agenda(self, days_ahead: int = 7) -> dict: """What needs attention: overdue, today, the coming week — for the notch and the digest.""" today = self.today() horizon = today + timedelta(days=days_ahead) def bucket(d: date) -> str: return "overdue" if d < today else ("today" if d == today else "soon") out = {"today": today.isoformat(), "overdue": [], "due_today": [], "soon": [], "paid": [], "running": None, "monthly_cost": self.monthly_cost()} 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 <= ?", (horizon.isoformat(),)): d = date.fromisoformat(t["due"]) out[key[bucket(d)]].append({"kind": "task", "id": t["id"], "title": t["title"], "date": t["due"], "client": t["client"]}) for s in self.subs(): d = date.fromisoformat(s["next_date"]) item = {"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"], "amount": s["amount"], "currency": s["currency"], "client": s["client"], "paid": s["paid"], "next_if_repeat": s["next_if_repeat"]} 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(): d = date.fromisoformat(r["next_date"]) if d <= horizon: out[key[bucket(d)]].append({"kind": "routine", "id": r["id"], "title": r["title"], "date": r["next_date"]}) for k in ("overdue", "due_today", "soon"): out[k].sort(key=lambda x: (x["date"], x["kind"], x["id"])) tid = self.running_task_id() if tid is not None: t = self.task(tid) out["running"] = {"id": tid, "title": t["title"], "minutes": self._minutes().get(tid, 0)} return out # MARK: - Reminders def due_reminders(self) -> list[dict]: """Things to remind about today that haven't been reminded about today yet.""" today = self.today() sent = {(r["kind"], r["ref"]) for r in self.con.execute("SELECT kind, ref FROM reminders_sent WHERE day = ?", (today.isoformat(),))} out = [] for t in self.con.execute("SELECT * FROM tasks WHERE status != 'done' AND due IS NOT NULL AND due <= ?", (today.isoformat(),)): if ("task", t["id"]) not in sent: out.append({"kind": "task", "id": t["id"], "title": t["title"], "date": t["due"]}) for s in self.subs(): d = date.fromisoformat(s["next_date"]) 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"], "amount": s["amount"], "currency": s["currency"], "client": s["client"]}) for r in self.routines(): if date.fromisoformat(r["next_date"]) <= today and ("routine", r["id"]) not in sent: out.append({"kind": "routine", "id": r["id"], "title": r["title"], "date": r["next_date"]}) return out def mark_reminded(self, kind: str, ref: int) -> None: self.con.execute("INSERT OR IGNORE INTO reminders_sent (kind, ref, day) VALUES (?, ?, ?)", (kind, ref, self.today().isoformat())) def snooze(self, kind: str, ref: int, days: int = 1) -> None: """Push a task / routine forward; a subscription is only reminded again tomorrow.""" until = (self.today() + timedelta(days=days)).isoformat() if kind == "task": self.update_task(ref, due=until) elif kind == "routine": self.update_routine(ref, next_date=until) self.mark_reminded(kind, ref)