|
| 1 | +from typing import Literal |
| 2 | + |
| 3 | +from mailtrap.http import HttpClient |
| 4 | +from mailtrap.models.stats import SendingStatGroup |
| 5 | +from mailtrap.models.stats import SendingStats |
| 6 | +from mailtrap.models.stats import StatsFilterParams |
| 7 | + |
| 8 | +GroupKey = Literal["domains", "categories", "email_service_providers", "date"] |
| 9 | + |
| 10 | +_GROUP_KEYS = { |
| 11 | + "domains": "sending_domain_id", |
| 12 | + "categories": "category", |
| 13 | + "email_service_providers": "email_service_provider", |
| 14 | + "date": "date", |
| 15 | +} |
| 16 | + |
| 17 | + |
| 18 | +class StatsApi: |
| 19 | + def __init__(self, client: HttpClient) -> None: |
| 20 | + self._client = client |
| 21 | + |
| 22 | + def get(self, account_id: int, params: StatsFilterParams) -> SendingStats: |
| 23 | + """Get aggregated sending stats.""" |
| 24 | + response = self._client.get( |
| 25 | + self._base_path(account_id), |
| 26 | + params=params.api_query_params, |
| 27 | + ) |
| 28 | + return SendingStats(**response) |
| 29 | + |
| 30 | + def by_domain( |
| 31 | + self, account_id: int, params: StatsFilterParams |
| 32 | + ) -> list[SendingStatGroup]: |
| 33 | + """Get sending stats grouped by domains.""" |
| 34 | + return self._grouped_stats(account_id, "domains", params) |
| 35 | + |
| 36 | + def by_category( |
| 37 | + self, account_id: int, params: StatsFilterParams |
| 38 | + ) -> list[SendingStatGroup]: |
| 39 | + """Get sending stats grouped by categories.""" |
| 40 | + return self._grouped_stats(account_id, "categories", params) |
| 41 | + |
| 42 | + def by_email_service_provider( |
| 43 | + self, account_id: int, params: StatsFilterParams |
| 44 | + ) -> list[SendingStatGroup]: |
| 45 | + """Get sending stats grouped by email service providers.""" |
| 46 | + return self._grouped_stats(account_id, "email_service_providers", params) |
| 47 | + |
| 48 | + def by_date( |
| 49 | + self, account_id: int, params: StatsFilterParams |
| 50 | + ) -> list[SendingStatGroup]: |
| 51 | + """Get sending stats grouped by date.""" |
| 52 | + return self._grouped_stats(account_id, "date", params) |
| 53 | + |
| 54 | + def _grouped_stats( |
| 55 | + self, account_id: int, group: GroupKey, params: StatsFilterParams |
| 56 | + ) -> list[SendingStatGroup]: |
| 57 | + response = self._client.get( |
| 58 | + f"{self._base_path(account_id)}/{group}", params=params.api_query_params |
| 59 | + ) |
| 60 | + group_key = _GROUP_KEYS[group] |
| 61 | + |
| 62 | + return [ |
| 63 | + SendingStatGroup( |
| 64 | + name=group_key, |
| 65 | + value=item[group_key], |
| 66 | + stats=SendingStats(**item["stats"]), |
| 67 | + ) |
| 68 | + for item in response |
| 69 | + ] |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def _base_path(account_id: int) -> str: |
| 73 | + return f"/api/accounts/{account_id}/stats" |
0 commit comments