# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Weeks, months, years, and the per-weekday picture. Every query takes an inclusive span of stored Warsaw day strings, so a daylight-saving change cannot move a boundary -- see ``stats.periods``. Several of them take ``exclude``: the one day carried over from the pre-0.1.0 counter has real totals but no hours, no lengths, and a 22-hour window pretending to be a day. It belongs in a total and nowhere near an average. The exclusion is a bound parameter compared against ``''`` rather than a clause pasted into the statement. No real day is the empty string, so one static query serves both cases -- and the alternative, an f-string holding half a WHERE clause, is a SQL-injection shape even when every input is a module constant. """ from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING from signal_bot.stats.periods import weekday_of from signal_bot.stats.queries_day import DayRow if TYPE_CHECKING: from signal_bot.stats.events import EventStore from signal_bot.stats.periods import Period PERIOD_ROWS = """ SELECT uuid, display_name, COUNT(*) AS messages, SUM(media_count) AS media, SUM(is_command) AS commands, SUM(char_len) AS chars FROM message_events WHERE group_id = ? AND day BETWEEN ? AND ? AND day <> ? GROUP BY uuid ORDER BY messages DESC, display_name ASC """ DAILY_SERIES = """ SELECT day, COUNT(*) AS messages FROM message_events WHERE group_id = ? AND day BETWEEN ? AND ? AND day <> ? GROUP BY day ORDER BY day """ EVERY_DAY = """ SELECT day, COUNT(*) AS messages FROM message_events WHERE group_id = ? AND day <> ? GROUP BY day ORDER BY day """ def period_rows( events: EventStore, group_id: str, period: Period, *, exclude: str | None = None, ) -> list[DayRow]: """Everyone who wrote during a period, most talkative first.""" rows = events.connection.execute( PERIOD_ROWS, (group_id, period.start, period.end, exclude or "") ).fetchall() return [ DayRow( uuid=r["uuid"], display_name=r["display_name"], messages=r["messages"], media=r["media"], commands=r["commands"], chars=r["chars"], ) for r in rows ] def daily_series( events: EventStore, group_id: str, start: str, end: str, *, exclude: str | None = None, ) -> dict[str, int]: """Messages per day across a span, missing days absent rather than zero. The caller decides what a missing day means: for a streak it is silence, for an average it is a day nobody was there to record. """ rows = events.connection.execute(DAILY_SERIES, (group_id, start, end, exclude or "")).fetchall() return {r["day"]: r["messages"] for r in rows} def every_day( events: EventStore, group_id: str, *, exclude: str | None = None, ) -> dict[str, int]: """Messages per day across the whole history.""" rows = events.connection.execute(EVERY_DAY, (group_id, exclude or "")).fetchall() return {r["day"]: r["messages"] for r in rows} def weekday_buckets(days: dict[str, int]) -> dict[int, list[int]]: """Bucket a day series by weekday, 0=Monday through 6=Sunday. Returns the days themselves rather than a mean, so a caller can see how many a figure rests on: "wtorki mają średnio 74" off a single Tuesday is a number that should not be said out loud. """ buckets: dict[int, list[int]] = {} for day, messages in days.items(): buckets.setdefault(weekday_of(day), []).append(messages) return buckets def total_for( events: EventStore, group_id: str, start: str, end: str, *, exclude: str | None = None, ) -> int: """How many messages a span holds.""" return sum(daily_series(events, group_id, start, end, exclude=exclude).values()) @dataclass(frozen=True, slots=True) class Trend: """One period measured against the one before it.""" now: int before: int @property def delta(self) -> int: """Absolute change, which may be negative.""" return self.now - self.before @property def percent(self) -> int | None: """Rounded percentage change, or None when there is no baseline. None rather than 0: "nothing to compare against yet" is a different statement from "no change", and the renderers say each differently. """ if not self.before: return None return round(self.delta / self.before * 100) @property def arrow(self) -> str: """An arrow, or "" when there is nothing to compare against.""" if self.percent is None or self.delta == 0: return "" return "↑" if self.delta > 0 else "↓" def share_of_voice(rows: list[DayRow]) -> list[tuple[str, int]]: """Each person's percentage of the messages, largest first.""" total = sum(row.messages for row in rows) if not total: return [] return [(row.display_name, round(row.messages / total * 100)) for row in rows]