import datetime import html import json from typing import Any from .user import User class Analytics: def __init__(self): self.issued_at = datetime.datetime.now() self.users = 0 self.groups: dict[str, int] = {} def add(self, user: User) -> None: self.users += 1 if not user.active_target or user.active_target["kind"] != "group": return group = user.active_target["name"] self.groups[group] = self.groups.get(group, 0) + 1 def toDict(self) -> dict[str, Any]: return { "version": 3, "issued_at": self.issued_at.isoformat(), "users": self.users, "groups": dict(sorted(self.groups.items())), } def append(self) -> None: try: with open("./web/analytics/data-v2.json", "r", encoding="utf-8") as file: history: list[dict[str, Any]] = json.load(file) except (FileNotFoundError, json.JSONDecodeError, OSError): history = [] history.append(self.toDict()) with open("./web/analytics/data-v2.json", "w", encoding="utf-8") as file: json.dump(history[-30:], file, ensure_ascii=False) def text(self) -> str: group_lines = [ f"{html.escape(group)}: {count}" for group, count in sorted(self.groups.items()) ] groups = "\n".join(group_lines) if group_lines else "Нет зарегистрированных групп" return ( f'Аналитика за {self.issued_at.strftime("%d.%m")} 📊\n' f"Пользователи: {self.users}\n\n" f"Группы\n{groups}" )