Files
brov-macbook/ops/brovops/fmt.py
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

79 lines
3.6 KiB
Python

"""Plain-text rendering for Telegram (HTML parse mode)."""
from datetime import date
from html import escape
from .core import client_name, ru_day
ICON = {"task": "📌", "sub": "💳", "routine": "🔁"}
def human_day(iso: str, today: date) -> str:
d = date.fromisoformat(iso)
delta = (d - today).days
if delta == 0:
return "сегодня"
if delta == 1:
return "завтра"
if delta == -1:
return "вчера"
if delta < 0:
return f"просрочено на {-delta} дн."
return d.strftime("%d.%m.%Y")
def item_line(it: dict, today: date) -> str:
extra = f" — {it['amount']:g} {it['currency']}" if it["kind"] == "sub" else ""
client = f" [{client_name(it['client'])}]" if it.get("client") else ""
return f"{ICON[it['kind']]} {escape(it['title'])}{client}{extra} · {human_day(it['date'], today)}"
def agenda(a: dict) -> str:
today = date.fromisoformat(a["today"])
out = []
if a["running"]:
out.append(f"⏱ Сейчас: <b>{escape(a['running']['title'])}</b> ({a['running']['minutes']} мин)")
for key, title in (("overdue", "🔥 Просрочено"), ("due_today", "📅 Сегодня"), ("soon", "🗓 Ближайшая неделя")):
if a[key]:
out.append(f"\n<b>{title}</b>")
out += [item_line(it, today) for it in a[key]]
if not (a["overdue"] or a["due_today"] or a["soon"]):
out.append("На ближайшую неделю ничего не горит 👌")
if a["monthly_cost"]:
out.append("\nПодписки в месяц: " + ", ".join(f"{v:g} {k}" for k, v in a["monthly_cost"].items()))
return "\n".join(out).strip()
def tree(nodes: list, depth: int = 0) -> list[str]:
out = []
for t in nodes:
mark = "⏱" if t["running"] else ("▶️" if t["status"] == "doing" else "▫️")
due = f" · до {ru_day(t['due'])}" if t["due"] else ""
mins = f" · {t['minutes']} мин" if t["minutes"] else ""
client = f" [{client_name(t['client'])}]" if t["client"] else ""
out.append(f"{' ' * depth}{mark} #{t['id']} {escape(t['title'])}{client}{due}{mins}")
out += tree(t["children"], depth + 1)
return out
def subs(rows: list, by_client: dict, today: date) -> str:
"""Grouped by company, each with its monthly total."""
if not rows:
return "Подписок пока нет. Скажи, например: «Claude Code 20 $ в месяц, списание 25-го, компания Сага»."
per = {"day": "день", "week": "нед.", "month": "мес.", "year": "год"}
out = []
for client in sorted({s["client"] for s in rows}, key=lambda c: (c == "", c)):
total = ", ".join(f"{v:g} {k}" for k, v in by_client.get(client, {}).items())
out.append(f"\n<b>{escape(client_name(client) or 'Без компании')}</b> — {total} в мес.")
for s in (x for x in rows if x["client"] == client):
every = f"{s['every']} " if s["every"] > 1 else ""
out.append(f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / {every}{per[s['period']]}"
f" · {human_day(s['next_date'], today)}")
return "\n".join(out).strip()
def routines(rows: list, today: date) -> str:
if not rows:
return "Регламентных дел пока нет. Скажи: «бэкап NAS раз в неделю»."
return "\n".join(f"🔁 #{r['id']} {escape(r['title'])} · раз в {r['every_days']} дн. · {human_day(r['next_date'], today)}"
+ (f" · последний раз {ru_day(r['last_done'])}" if r["last_done"] else "") for r in rows)