:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(workflows): add trend charts to the transactional metrics tab (#130558)
Daniel Marchuk0e41da20bc45
diff --git a/products/messaging/backend/facade/contracts.py b/products/messaging/backend/facade/contracts.pyindex 4ccec6f91f8f..c2c49669b95d 100644--- a/products/messaging/backend/facade/contracts.py+++ b/products/messaging/backend/facade/contracts.py@@ -289,6 +289,37 @@ class TransactionalEmailLogDetail:sensitive: bool+class EmailStatsInterval(LabeledStrEnum):+ # One bucket spans five minutes.+ MINUTE = "minute", "Minute"+ HOUR = "hour", "Hour"+ DAY = "day", "Day"+++@frozen+class TransactionalEmailStatsCounts:+ sent: int+ delivered: int+ bounced: int+ complained: int+ failed: int+++@frozen+class TransactionalEmailStatsBucket:+ start: datetime+ counts: TransactionalEmailStatsCounts+++@frozen+class TransactionalEmailStatsOverTime:+ interval: EmailStatsInterval+ timezone: str+ buckets: list[TransactionalEmailStatsBucket]+ # The same stretch of time just before this one. None when retention no longer covers all of it.+ previous: TransactionalEmailStatsCounts | None++@frozenclass TransactionalEmailStatsRow:# The template id or the sending domain.diff --git a/products/messaging/backend/facade/transactional_email_log.py b/products/messaging/backend/facade/transactional_email_log.pyindex 9cf31fbf50f4..539b7181fb31 100644--- a/products/messaging/backend/facade/transactional_email_log.py+++ b/products/messaging/backend/facade/transactional_email_log.py@@ -7,6 +7,7 @@ from products.messaging.backend.services.transactional_email_log import (list_transactional_emails,transactional_email_results,transactional_email_stats,+ transactional_email_stats_over_time,)__all__ = [@@ -16,4 +17,5 @@ __all__ = ["list_transactional_emails","transactional_email_results","transactional_email_stats",+ "transactional_email_stats_over_time",]diff --git a/products/messaging/backend/presentation/views/transactional_email_log.py b/products/messaging/backend/presentation/views/transactional_email_log.pyindex 2c8dafad1b07..fd7e02658dfe 100644--- a/products/messaging/backend/presentation/views/transactional_email_log.py+++ b/products/messaging/backend/presentation/views/transactional_email_log.py@@ -19,6 +19,7 @@ from products.messaging.backend.facade.contracts import (EmailDeliveryStatus,EmailLogEventKind,EmailStatsGroupBy,+ EmailStatsInterval,TransactionalEmailLogEntry,)from products.messaging.backend.facade.transactional_email_log import (@@ -28,6 +29,7 @@ from products.messaging.backend.facade.transactional_email_log import (list_transactional_emails,transactional_email_results,transactional_email_stats,+ transactional_email_stats_over_time,)from products.messaging.backend.presentation.query_concurrency import query_concurrency_slotsfrom products.messaging.backend.presentation.views.message_templates import require_transactional_email_api@@ -140,6 +142,32 @@ class TransactionalEmailStatsSerializer(serializers.Serializer):results = TransactionalEmailStatsRowSerializer(many=True, help_text="One row per group, busiest first.")+class TransactionalEmailStatsCountsSerializer(serializers.Serializer):+ sent = serializers.IntegerField(help_text="Emails that reached the email provider.")+ delivered = serializers.IntegerField(help_text="Emails the recipient's mail server accepted.")+ bounced = serializers.IntegerField(help_text="Emails that bounced.")+ complained = serializers.IntegerField(help_text="Emails the recipient marked as spam.")+ failed = serializers.IntegerField(help_text="Emails that were not sent.")+++class TransactionalEmailStatsBucketSerializer(serializers.Serializer):+ start = serializers.DateTimeField(help_text="When this time bucket starts.")+ counts = TransactionalEmailStatsCountsSerializer(help_text="Sends queued during this bucket.")+++class TransactionalEmailStatsOverTimeSerializer(serializers.Serializer):+ interval = serializers.ChoiceField(+ choices=EmailStatsInterval.choices,+ help_text="The width of each bucket. A `minute` bucket spans five minutes.",+ )+ timezone = serializers.CharField(help_text="The project timezone that the buckets start in.")+ buckets = TransactionalEmailStatsBucketSerializer(many=True, help_text="Every bucket in the period, oldest first.")+ previous = TransactionalEmailStatsCountsSerializer(+ allow_null=True,+ help_text="Totals for the same length of time just before the period. Null when retention no longer covers it.",+ )++class TransactionalEmailResultsQuerySerializer(DateRangeQuerySerializer):workflow_id = serializers.UUIDField(help_text="The workflow behind the transactional email.")event = serializers.CharField(help_text="The event that counts as a conversion, such as `signed_up`.")@@ -190,7 +218,7 @@ class _PageSchema(AutoSchema):class TransactionalEmailLogViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):schema = _PageSchema()scope_object = "hog_flow"- scope_object_read_actions = ["list", "retrieve", "stats", "results"]+ scope_object_read_actions = ["list", "retrieve", "stats", "stats_over_time", "results"]def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:super().initial(request, *args, **kwargs)@@ -291,6 +319,25 @@ class TransactionalEmailLogViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):)return Response(TransactionalEmailStatsSerializer({"results": [asdict(row) for row in rows]}).data)+ @validated_request(+ query_serializer=DateRangeQuerySerializer,+ responses={200: OpenApiResponse(response=TransactionalEmailStatsOverTimeSerializer)},+ summary="Get transactional email delivery stats over time",+ description="Count sends by delivery status per time bucket, with totals for the period before.",+ )+ @action(detail=False, methods=["GET"])+ def stats_over_time(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:+ query = request.validated_query_data+ with query_concurrency_slots(self.team):+ stats = transactional_email_stats_over_time(+ self.team_id,+ self.team.timezone,+ date_from=query.get("date_from"),+ date_to=query.get("date_to"),+ access=self._workflow_access(),+ )+ return Response(TransactionalEmailStatsOverTimeSerializer(asdict(stats)).data)+@validated_request(query_serializer=TransactionalEmailResultsQuerySerializer,responses={diff --git a/products/messaging/backend/services/transactional_email_log.py b/products/messaging/backend/services/transactional_email_log.pyindex f934cb4a29a4..dafd5b1d096d 100644--- a/products/messaging/backend/services/transactional_email_log.py+++ b/products/messaging/backend/services/transactional_email_log.py@@ -10,6 +10,7 @@ from datetime import UTC, datetime, timedeltafrom statistics import medianfrom typing import Any, castfrom uuid import UUID+from zoneinfo import ZoneInfofrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query@@ -24,10 +25,14 @@ from products.messaging.backend.facade.contracts import (EmailDeliveryStatus,EmailLogEventKind,EmailStatsGroupBy,+ EmailStatsInterval,TransactionalEmailLogDetail,TransactionalEmailLogEntry,TransactionalEmailLogEvent,TransactionalEmailResults,+ TransactionalEmailStatsBucket,+ TransactionalEmailStatsCounts,+ TransactionalEmailStatsOverTime,TransactionalEmailStatsRow,)from products.messaging.backend.models.email_status_sql import (@@ -387,6 +392,129 @@ def transactional_email_stats(return stats+_INTERVAL_BUCKET_FUNCTION = {+ EmailStatsInterval.MINUTE: "toStartOfFiveMinutes",+ EmailStatsInterval.HOUR: "toStartOfHour",+ EmailStatsInterval.DAY: "toStartOfDay",+}+++def _stats_interval(span: timedelta) -> EmailStatsInterval:+ if span <= timedelta(hours=2):+ return EmailStatsInterval.MINUTE+ if span <= timedelta(days=2):+ return EmailStatsInterval.HOUR+ return EmailStatsInterval.DAY+++def _bucket_starts(start: datetime, end: datetime, interval: EmailStatsInterval, tz: ZoneInfo) -> list[datetime]:+ """The UTC start of every bucket from the one holding `start` up to `end`, in local time for the bucket edges."""+ local = start.astimezone(tz).replace(second=0, microsecond=0)+ if interval == EmailStatsInterval.DAY:+ day = local.replace(hour=0, minute=0)+ starts = []+ while day.astimezone(UTC) < end:+ starts.append(day.astimezone(UTC))+ # Wall-clock addition keeps each bucket on local midnight across a daylight saving change.+ day += timedelta(days=1)+ return starts+ if interval == EmailStatsInterval.HOUR:+ local, step = local.replace(minute=0), timedelta(hours=1)+ else:+ local, step = local.replace(minute=local.minute - local.minute % 5), timedelta(minutes=5)+ # UTC addition keeps the repeated hour when the clocks go back.+ moment = local.astimezone(UTC)+ starts = []+ while moment < end:+ starts.append(moment)+ moment += step+ return starts+++def _sum_counts(counts: Sequence[TransactionalEmailStatsCounts]) -> TransactionalEmailStatsCounts:+ return TransactionalEmailStatsCounts(+ sent=sum(count.sent for count in counts),+ delivered=sum(count.delivered for count in counts),+ bounced=sum(count.bounced for count in counts),+ complained=sum(count.complained for count in counts),+ failed=sum(count.failed for count in counts),+ )+++def transactional_email_stats_over_time(+ team_id: int,+ timezone: str,+ *,+ date_from: datetime | None = None,+ date_to: datetime | None = None,+ access: WorkflowViewAccess | None = None,+) -> TransactionalEmailStatsOverTime:+ """Delivery counts per time bucket in the team's timezone, with every empty bucket filled in."""+ period = _window(date_from, date_to)+ now = datetime.now(UTC)+ # The window reaches past now for clock skew, which is not time that the previous period can be compared with.+ span = min(period.end, now) - period.start+ interval = _stats_interval(span)+ tz = ZoneInfo(timezone)+ previous_start = period.start - span+ has_full_previous = previous_start >= now - RETENTION++ rows: list[tuple] = []+ if not _sees_no_sends(access):+ params: dict[str, Any] = {+ "start": previous_start if has_full_previous else period.start,+ "end": period.end,+ "period_start": period.start,+ "timezone": timezone,+ }+ access_filter = f"AND {_access_condition('message_function_id', access, params)}" if access is not None else ""+ rows = _execute(+ team_id,+ f"""+ SELECT+ queued_at >= %(period_start)s AS in_period,+ {_INTERVAL_BUCKET_FUNCTION[interval]}(queued_at, %(timezone)s) AS bucket,+ countIf(delivery_status IN ('sent', 'delivered', 'bounced', 'complained')) AS sent,+ countIf(delivery_status IN ('delivered', 'complained')) AS delivered,+ countIf(delivery_status = 'bounced') AS bounced,+ countIf(delivery_status = 'complained') AS complained,+ countIf(delivery_status = 'failed') AS failed+ FROM (+ SELECT {_MESSAGE_COLUMNS}+ FROM {EMAIL_STATUS_EVENTS_TABLE}+ WHERE team_id = %(team_id)s AND created_at >= %(start)s AND created_at < %(end)s+ GROUP BY created_at, message_id+ )+ WHERE delivery_status != '' {access_filter}+ GROUP BY in_period, bucket+ """,+ params,+ _GROUP_AS_READ,+ )++ current: dict[datetime, TransactionalEmailStatsCounts] = {}+ previous: list[TransactionalEmailStatsCounts] = []+ for in_period, bucket, sent, delivered, bounced, complained, failed in rows:+ counts = TransactionalEmailStatsCounts(+ sent=sent, delivered=delivered, bounced=bounced, complained=complained, failed=failed+ )+ if in_period:+ current[bucket.astimezone(UTC)] = counts+ else:+ previous.append(counts)++ empty = TransactionalEmailStatsCounts(sent=0, delivered=0, bounced=0, complained=0, failed=0)+ # A day that starts at 01:00 local time has a bucket the clock arithmetic can't name, so the rows' own keys stay.+ starts = sorted({*_bucket_starts(period.start, min(period.end, now), interval, tz), *current})+ buckets = [TransactionalEmailStatsBucket(start=start, counts=current.get(start, empty)) for start in starts]+ return TransactionalEmailStatsOverTime(+ interval=interval,+ timezone=timezone,+ buckets=buckets,+ previous=_sum_counts(previous) if has_full_previous else None,+ )++def transactional_email_results(team: Team,user: User | None,diff --git a/products/messaging/backend/tests/api/test_transactional_email_log.py b/products/messaging/backend/tests/api/test_transactional_email_log.pyindex c1e0ee65e323..36c3ce6fe61b 100644--- a/products/messaging/backend/tests/api/test_transactional_email_log.py+++ b/products/messaging/backend/tests/api/test_transactional_email_log.py@@ -1,10 +1,13 @@from datetime import UTC, datetime, timedeltafrom uuid import UUID+from zoneinfo import ZoneInfoimport time_machinefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import patch+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import status@@ -18,9 +21,11 @@ from posthog.test.persons import create_personfrom posthog.uuidt import UUIDTfrom products.access_control.backend.facade.testing import create_access_control+from products.messaging.backend.facade.contracts import EmailStatsIntervalfrom products.messaging.backend.models.email_status_sql import EMAIL_STATUS_EVENTS_DATA_TABLEfrom products.messaging.backend.models.message_template import MessageTemplatefrom products.messaging.backend.models.transactional_email_key import TransactionalEmailKey+from products.messaging.backend.services.transactional_email_log import _bucket_startsfrom products.workflows.backend.facade.testing import create_workflow_for_testfrom products.workflows.backend.facade.writes import destroy_workflow@@ -151,6 +156,7 @@ class TestTransactionalEmailLog(ClickhouseTestMixin, APIBaseTest):[("list", ""),("stats", "stats/?group_by=template"),+ ("stats_over_time", "stats_over_time/"),("results", "results/?event=purchase&workflow_id={workflow_id}"),])@@ -204,6 +210,7 @@ class TestTransactionalEmailLog(ClickhouseTestMixin, APIBaseTest):[("list", "", ["hog_flow:read"], "person:read"),("retrieve", "{message_id}/", ["hog_flow:read"], "person:read"),+ ("stats_over_time", "stats_over_time/", ["query:read"], "hog_flow:read"),("results","results/?event=purchase&workflow_id={workflow_id}",@@ -256,6 +263,52 @@ class TestTransactionalEmailLog(ClickhouseTestMixin, APIBaseTest):("other.example.com", 1, 1),]+ def test_counts_sends_over_time_in_the_project_timezone_with_the_period_before(self, _flag):+ self.team.timezone = "Europe/Prague"+ self.team.save()+ # 22:30 UTC on June 12 is already June 13 in Prague.+ self._send(60 * 61 + 30, "[email protected]", [("sent", 1, ""), ("delivered", 2, "")])+ self._send(60 * 26, "[email protected]", [("sent", 1, ""), ("bounced", 2, "hard")])+ self._send(60 * 26, "[email protected]", [("failed", 1, "provider_error")])+ self._send(60 * 24 * 5, "[email protected]", [("sent", 1, ""), ("delivered", 2, "")])++ body = self.client.get(+ self._url("stats_over_time/"), {"date_from": (NOW - timedelta(days=4)).isoformat()}+ ).json()++ assert body["interval"] == "day"+ assert body["timezone"] == "Europe/Prague"+ by_day = {+ bucket["start"]: (bucket["counts"]["sent"], bucket["counts"]["bounced"], bucket["counts"]["failed"])+ for bucket in body["buckets"]+ }+ assert by_day == {+ "2026-06-10T22:00:00Z": (0, 0, 0),+ "2026-06-11T22:00:00Z": (0, 0, 0),+ "2026-06-12T22:00:00Z": (1, 0, 0),+ "2026-06-13T22:00:00Z": (1, 1, 1),+ "2026-06-14T22:00:00Z": (0, 0, 0),+ }+ assert body["previous"]["sent"] == 1++ def test_compares_the_same_length_of_time_when_the_period_ends_now(self, _flag):+ self._send(61, "[email protected]", [("sent", 1, "")])+ self._send(64, "[email protected]", [("sent", 1, "")])++ body = self.client.get(+ self._url("stats_over_time/"), {"date_from": (NOW - timedelta(hours=1)).isoformat()}+ ).json()++ assert body["previous"]["sent"] == 2+ assert sum(bucket["counts"]["sent"] for bucket in body["buckets"]) == 0++ def test_has_no_earlier_period_when_retention_does_not_cover_it(self, _flag):+ body = self.client.get(+ self._url("stats_over_time/"), {"date_from": (NOW - timedelta(days=30)).isoformat()}+ ).json()++ assert body["previous"] is None+def test_counts_who_converted_within_the_window_after_their_first_send(self, _flag):for distinct_id, sent_minutes_ago in [("converted", 600),@@ -380,8 +433,10 @@ class TestTransactionalEmailLog(ClickhouseTestMixin, APIBaseTest):results = self.client.get(self._url("results/"), {"workflow_id": restricted, "event": "purchase"})stats = self.client.get(self._url("stats/"), {"group_by": "sending_domain"}).json()["results"]+ over_time = self.client.get(self._url("stats_over_time/")).json()["buckets"]assert [r["message_id"] for r in listed] == [deleted_id, visible_id]+ assert sum(bucket["counts"]["sent"] for bucket in over_time) == 2assert detail.status_code == status.HTTP_404_NOT_FOUNDassert results.status_code == status.HTTP_404_NOT_FOUNDassert {row["label"] for row in stats} == {"mail.example.com", "old.example.com"}@@ -433,3 +488,28 @@ class TestTransactionalEmailLog(ClickhouseTestMixin, APIBaseTest):assert listed.status_code == status.HTTP_200_OK, listed.json()assert [r["message_id"] for r in listed.json()["results"]] == [granted_id]assert self.client.get(self._url(f"{deleted_id}/")).status_code == status.HTTP_404_NOT_FOUND+++class TestStatsBuckets(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "keeps_the_repeated_hour_when_clocks_go_back",+ datetime(2026, 10, 25, 0, 10, tzinfo=UTC),+ datetime(2026, 10, 25, 2, 0, tzinfo=UTC),+ EmailStatsInterval.HOUR,+ [(10, 25, 0), (10, 25, 1)],+ ),+ (+ "starts_each_day_on_local_midnight_across_a_clock_change",+ datetime(2026, 10, 24, 12, 0, tzinfo=UTC),+ datetime(2026, 10, 26, 12, 0, tzinfo=UTC),+ EmailStatsInterval.DAY,+ [(10, 23, 22), (10, 24, 22), (10, 25, 23)],+ ),+ ]+ )+ def test_bucket_starts(self, _name, start, end, interval, expected):+ starts = _bucket_starts(start, end, interval, ZoneInfo("Europe/Prague"))++ assert [(moment.month, moment.day, moment.hour) for moment in starts] == expecteddiff --git a/products/messaging/frontend/generated/api.schemas.ts b/products/messaging/frontend/generated/api.schemas.tsindex ccc727480ffe..2ecfd7c2cc67 100644--- a/products/messaging/frontend/generated/api.schemas.ts+++ b/products/messaging/frontend/generated/api.schemas.ts@@ -1176,6 +1176,54 @@ export interface TransactionalEmailStatsApi {results: TransactionalEmailStatsRowApi[]}+/**+ * * `minute` - Minute+ * * `hour` - Hour+ * * `day` - Day+ */+export type EmailStatsIntervalEnumApi = (typeof EmailStatsIntervalEnumApi)[keyof typeof EmailStatsIntervalEnumApi]++export const EmailStatsIntervalEnumApi = {+ Minute: 'minute',+ Hour: 'hour',+ Day: 'day',+} as const++export interface TransactionalEmailStatsCountsApi {+ /** Emails that reached the email provider. */+ sent: number+ /** Emails the recipient's mail server accepted. */+ delivered: number+ /** Emails that bounced. */+ bounced: number+ /** Emails the recipient marked as spam. */+ complained: number+ /** Emails that were not sent. */+ failed: number+}++export interface TransactionalEmailStatsBucketApi {+ /** When this time bucket starts. */+ start: string+ /** Sends queued during this bucket. */+ counts: TransactionalEmailStatsCountsApi+}++export interface TransactionalEmailStatsOverTimeApi {+ /** The width of each bucket. A `minute` bucket spans five minutes.+ *+ * * `minute` - Minute+ * * `hour` - Hour+ * * `day` - Day */+ interval: EmailStatsIntervalEnumApi+ /** The project timezone that the buckets start in. */+ timezone: string+ /** Every bucket in the period, oldest first. */+ buckets: TransactionalEmailStatsBucketApi[]+ /** Totals for the same length of time just before the period. Null when retention no longer covers it. */+ previous: TransactionalEmailStatsCountsApi | null+}+export type MessagingCategoriesListParams = {/*** Number of results to return per page.@@ -1339,3 +1387,14 @@ export const TransactionalEmailLogStatsRetrieveGroupBy = {Template: 'template',SendingDomain: 'sending_domain',} as const++export type TransactionalEmailLogStatsOverTimeRetrieveParams = {+ /**+ * Only sends queued at or after this time. Defaults to 7 days ago. The log keeps sends for 30 days.+ */+ date_from?: string+ /**+ * Only sends queued before this time. Defaults to now.+ */+ date_to?: string+}diff --git a/products/messaging/frontend/generated/api.ts b/products/messaging/frontend/generated/api.tsindex 97303b15b61b..b3aff9984455 100644--- a/products/messaging/frontend/generated/api.ts+++ b/products/messaging/frontend/generated/api.ts@@ -48,9 +48,11 @@ import type {TransactionalEmailLogListApi,TransactionalEmailLogListParams,TransactionalEmailLogResultsRetrieveParams,+ TransactionalEmailLogStatsOverTimeRetrieveParams,TransactionalEmailLogStatsRetrieveParams,TransactionalEmailResultsApi,TransactionalEmailStatsApi,+ TransactionalEmailStatsOverTimeApi,WebhookUrlApi,} from './api.schemas'@@ -1125,3 +1127,40 @@ export const transactionalEmailLogStatsRetrieve = async (method: 'GET',})}++export const getTransactionalEmailLogStatsOverTimeRetrieveUrl = (+ projectId: string,+ params?: TransactionalEmailLogStatsOverTimeRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/transactional_email_log/stats_over_time/?${stringifiedParams}`+ : `/api/projects/${projectId}/transactional_email_log/stats_over_time/`+}++/**+ * Count sends by delivery status per time bucket, with totals for the period before.+ * @summary Get transactional email delivery stats over time+ */+export const transactionalEmailLogStatsOverTimeRetrieve = async (+ projectId: string,+ params?: TransactionalEmailLogStatsOverTimeRetrieveParams,+ options?: RequestInit+): Promise<TransactionalEmailStatsOverTimeApi> => {+ return apiMutator<TransactionalEmailStatsOverTimeApi>(+ getTransactionalEmailLogStatsOverTimeRetrieveUrl(projectId, params),+ {+ ...options,+ method: 'GET',+ }+ )+}diff --git a/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTile.stories.tsx b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTile.stories.tsxnew file mode 100644index 000000000000..de9a9284cc07--- /dev/null+++ b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTile.stories.tsx@@ -0,0 +1,37 @@+import { Meta, StoryFn } from '@storybook/react'++import { TransactionalEmailMetricTile } from './TransactionalEmailMetricTile'++const meta: Meta<typeof TransactionalEmailMetricTile> = {+ title: 'Scenes-App/Transactional/Email metric tile',+ component: TransactionalEmailMetricTile,+ parameters: { mockDate: '2026-06-15', testOptions: { snapshotBrowsers: [] } },+}+export default meta++const LABELS = ['2026-06-10', '2026-06-11', '2026-06-12', '2026-06-13', '2026-06-14']++export const RateThatRose: StoryFn = () => (+ <div className="w-72">+ <TransactionalEmailMetricTile+ tile={{+ key: 'bounced',+ title: 'Bounced',+ format: 'rate',+ value: 2.4,+ points: [1, 1.2, 8, 1.1, 1],+ count: 24,+ baseLabel: 'sent',+ bases: [200, 200, 200, 200, 200],+ counts: [2, 2, 16, 2, 2],+ change: 1.2,+ goodDirection: 'down',+ }}+ labels={LABELS}+ interval="day"+ timezone="UTC"+ color="var(--danger)"+ caption="24 of sent"+ />+ </div>+)diff --git a/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTile.tsx b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTile.tsxnew file mode 100644index 000000000000..7019e59ac14c--- /dev/null+++ b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTile.tsx@@ -0,0 +1,93 @@+import { type ReactNode, useMemo } from 'react'++import { createTooltipDateFormatter, useChartTheme } from '@posthog/quill-charts'+import {+ Metric,+ MetricDelta,+ MetricHeader,+ MetricSparkline,+ MetricSubtitle,+ MetricTitle,+ MetricValue,+} from '@posthog/quill-components/metric'++import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { EmailStatsIntervalEnumApi } from 'products/messaging/frontend/generated/api.schemas'++import type { MetricTile } from './emailMetricTiles'++const SPARKLINE_HEIGHT = 160++function formatRate(value: number): string {+ return `${value.toFixed(value < 1 ? 2 : 1)}%`+}++export function TransactionalEmailMetricTile({+ tile,+ labels,+ interval,+ timezone,+ color,+ caption,+}: {+ tile: MetricTile+ labels: string[]+ interval: EmailStatsIntervalEnumApi+ timezone: string+ color: string+ caption: ReactNode+}): JSX.Element {+ const theme = useChartTheme()+ const formatLabel = useMemo(+ () => createTooltipDateFormatter({ interval, timezone, allDays: labels }),+ [interval, timezone, labels]+ )+ const isRate = tile.format === 'rate'+ return (+ <div+ className="flex min-w-0 flex-col rounded border bg-surface-primary py-3"+ data-attr={`transactional-email-metric-${tile.key}`}+ >+ <Metric+ className="px-3"+ value={tile.value ?? 0}+ data={tile.points}+ labels={labels}+ formatLabel={formatLabel}+ restingSubtitle={caption}+ theme={theme}+ color={color}+ change={tile.change === null ? null : { value: tile.change }}+ goodDirection={tile.goodDirection}+ formatChange={+ isRate+ ? (points) => `${points > 0 ? '+' : ''}${points.toFixed(points < 1 && points > -1 ? 2 : 1)} pts`+ : undefined+ }+ formatValue={(value) =>+ tile.value === null ? '–' : isRate ? formatRate(value) : humanFriendlyNumber(value)+ }+ sparklineHeight={SPARKLINE_HEIGHT}+ sparklineTooltip={+ isRate+ ? ({ dataIndex }) => (+ <span className="text-xs">+ {humanFriendlyNumber(tile.counts[dataIndex] ?? 0)} of{' '}+ {humanFriendlyNumber(tile.bases[dataIndex] ?? 0)} {tile.baseLabel}+ </span>+ )+ : undefined+ }+ >+ <MetricHeader>+ <MetricTitle className="min-w-0">{tile.title}</MetricTitle>+ <MetricDelta />+ </MetricHeader>+ <MetricValue className="mt-1" />+ <MetricSubtitle className="mt-1" />+ <MetricSparkline className="-mx-3 mt-2 h-16" />+ </Metric>+ </div>+ )+}diff --git a/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTiles.tsx b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTiles.tsxnew file mode 100644index 000000000000..9823d882d190--- /dev/null+++ b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetricTiles.tsx@@ -0,0 +1,60 @@+import { useValues } from 'kea'+import { useMemo } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'++import { getColorVar } from 'lib/colors'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import { MetricTile, buildMetricTiles } from './emailMetricTiles'+import { transactionalEmailMetricsLogic } from './transactionalEmailMetricsLogic'+import { TransactionalEmailMetricTile } from './TransactionalEmailMetricTile'++const TILE_COLOR: Record<MetricTile['key'], Parameters<typeof getColorVar>[0]> = {+ sent: 'data-color-1',+ delivered: 'success',+ bounced: 'danger',+ complained: 'warning',+}++function caption(tile: MetricTile, failed: number): string {+ if (tile.key === 'sent') {+ return failed > 0 ? `${humanFriendlyNumber(failed)} failed` : 'None failed'+ }+ return `${humanFriendlyNumber(tile.count)} of ${tile.baseLabel}`+}++export function TransactionalEmailMetricTiles(): JSX.Element | null {+ const { statsOverTime, statsOverTimeLoading, statsOverTimeFailed } = useValues(transactionalEmailMetricsLogic)+ const tiles = useMemo(() => (statsOverTime ? buildMetricTiles(statsOverTime) : null), [statsOverTime])+ const labels = useMemo(() => statsOverTime?.buckets.map((bucket) => bucket.start) ?? [], [statsOverTime])+ const failed = statsOverTime?.buckets.reduce((total, bucket) => total + bucket.counts.failed, 0) ?? 0++ if (statsOverTimeLoading) {+ return (+ <div className="grid grid-cols-2 @3xl:grid-cols-4 gap-2">+ {Array.from({ length: 4 }).map((_, index) => (+ <LemonSkeleton key={index} className="h-36" />+ ))}+ </div>+ )+ }+ if (statsOverTimeFailed || !statsOverTime || !tiles) {+ return null+ }+ return (+ <div className="grid grid-cols-2 @3xl:grid-cols-4 gap-2" data-attr="transactional-email-metric-tiles">+ {tiles.map((tile) => (+ <TransactionalEmailMetricTile+ key={tile.key}+ tile={tile}+ labels={labels}+ interval={statsOverTime.interval}+ timezone={statsOverTime.timezone}+ color={tile.value ? getColorVar(TILE_COLOR[tile.key]) : getColorVar('muted')}+ caption={caption(tile, failed)}+ />+ ))}+ </div>+ )+}diff --git a/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetrics.tsx b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetrics.tsxindex 248d140bbe8a..54f5b9b20624 100644--- a/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetrics.tsx+++ b/products/workflows/frontend/Transactional/metrics/TransactionalEmailMetrics.tsx@@ -9,17 +9,18 @@ import { SceneSection } from '~/layout/scenes/components/SceneSection'import { TransactionalEmailMetricsDateRange } from './TransactionalEmailMetricsDateRange'import { transactionalEmailMetricsLogic } from './transactionalEmailMetricsLogic'+import { TransactionalEmailMetricTiles } from './TransactionalEmailMetricTiles'import { TransactionalEmailResults } from './TransactionalEmailResults'import { TransactionalEmailStatsTable } from './TransactionalEmailStatsTable'export function TransactionalEmailMetrics(): JSX.Element {const { templateStats, templateStatsLoading, domainStats, domainStatsLoading, statsFailed } =useValues(transactionalEmailMetricsLogic)- const { loadTemplateStats, loadDomainStats } = useActions(transactionalEmailMetricsLogic)+ const { loadTemplateStats, loadDomainStats, loadStatsOverTime } = useActions(transactionalEmailMetricsLogic)const emptyState = statsFailed ? "The numbers couldn't load" : 'No transactional emails were sent in this period'return (- <div className="flex flex-col gap-4">+ <div className="@container flex flex-col gap-4">{statsFailed && !templateStatsLoading && !domainStatsLoading && (<LemonBannertype="error"@@ -28,6 +29,7 @@ export function TransactionalEmailMetrics(): JSX.Element {onClick: () => {loadTemplateStats()loadDomainStats()+ loadStatsOverTime()},'data-attr': 'transactional-email-metrics-retry',}}@@ -35,10 +37,13 @@ export function TransactionalEmailMetrics(): JSX.Element {The numbers couldn't load. Check your connection and try again.</LemonBanner>)}+ <SceneSection title="All transactional emails" actions={<TransactionalEmailMetricsDateRange />}>+ <TransactionalEmailMetricTiles />+ </SceneSection>+ <SceneDivider /><SceneSectiontitle="By email"description="Delivered and bounced are shares of what was sent. Marked as spam, opened and clicked are shares of what was delivered."- actions={<TransactionalEmailMetricsDateRange />}><TransactionalEmailStatsTableid="by_email"diff --git a/products/workflows/frontend/Transactional/metrics/emailMetricTiles.test.ts b/products/workflows/frontend/Transactional/metrics/emailMetricTiles.test.tsnew file mode 100644index 000000000000..da7a9be86342--- /dev/null+++ b/products/workflows/frontend/Transactional/metrics/emailMetricTiles.test.ts@@ -0,0 +1,47 @@+import type {+ TransactionalEmailStatsCountsApi,+ TransactionalEmailStatsOverTimeApi,+} from 'products/messaging/frontend/generated/api.schemas'++import { buildMetricTiles } from './emailMetricTiles'++function counts(sent: number, bounced = 0): TransactionalEmailStatsCountsApi {+ return { sent, delivered: sent - bounced, bounced, complained: 0, failed: 0 }+}++function stats(+ buckets: TransactionalEmailStatsCountsApi[],+ previous: TransactionalEmailStatsCountsApi | null+): TransactionalEmailStatsOverTimeApi {+ return {+ interval: 'day',+ timezone: 'UTC',+ buckets: buckets.map((bucket, index) => ({ start: `2026-06-0${index + 1}T00:00:00Z`, counts: bucket })),+ previous,+ }+}++describe('emailMetricTiles', () => {+ it('does not plot a day without sends as a 0% rate', () => {+ const delivered = buildMetricTiles(stats([counts(0), counts(100, 10), counts(0), counts(50)], null))[1]+ expect(delivered.points).toEqual([90, 90, 90, 100])+ })++ it.each([+ { name: 'compares a count in percent', previous: counts(100, 5), tile: 0, expected: 100 },+ { name: 'compares a rate in percentage points', previous: counts(100, 5), tile: 2, expected: 5 },+ { name: 'has no comparison without an earlier period', previous: null, tile: 2, expected: null },+ {+ name: 'has no comparison when the earlier period sent nothing',+ previous: counts(0),+ tile: 0,+ expected: null,+ },+ ])('$name', ({ previous, tile, expected }) => {+ expect(buildMetricTiles(stats([counts(200, 20)], previous))[tile].change).toEqual(expected)+ })++ it('shows no rate when nothing was sent', () => {+ expect(buildMetricTiles(stats([counts(0)], null))[1].value).toBeNull()+ })+})diff --git a/products/workflows/frontend/Transactional/metrics/emailMetricTiles.ts b/products/workflows/frontend/Transactional/metrics/emailMetricTiles.tsnew file mode 100644index 000000000000..35191a2358cd--- /dev/null+++ b/products/workflows/frontend/Transactional/metrics/emailMetricTiles.ts@@ -0,0 +1,99 @@+import type {+ TransactionalEmailStatsCountsApi,+ TransactionalEmailStatsOverTimeApi,+} from 'products/messaging/frontend/generated/api.schemas'++export type MetricTileFormat = 'count' | 'rate'++export interface MetricTile {+ key: 'sent' | 'delivered' | 'bounced' | 'complained'+ title: string+ format: MetricTileFormat+ /** The period's value: a count, or a percentage from 0 to 100. Null when there is nothing to divide by. */+ value: number | null+ /** The value for each bucket, in the same unit as `value`. */+ points: number[]+ count: number+ /** What a rate divides by, for the caption. */+ baseLabel: 'sent' | 'delivered' | null+ bases: number[]+ counts: number[]+ /** Percent change for a count, percentage points for a rate. Null when there is nothing to compare with. */+ change: number | null+ goodDirection: 'up' | 'down'+}++function sum(values: number[]): number {+ return values.reduce((total, value) => total + value, 0)+}++function rate(count: number, base: number): number {+ return base > 0 ? (count / base) * 100 : 0+}++/** A rate per bucket. A bucket with nothing to divide by keeps the rate around it, since no sends is not a 0% rate. */+function ratePoints(counts: number[], bases: number[]): number[] {+ const firstKnown = bases.findIndex((base) => base > 0)+ let last = firstKnown >= 0 ? rate(counts[firstKnown], bases[firstKnown]) : 0+ return counts.map((count, index) => {+ if (bases[index] > 0) {+ last = rate(count, bases[index])+ }+ return last+ })+}++function rateTile(+ stats: TransactionalEmailStatsOverTimeApi,+ key: 'delivered' | 'bounced' | 'complained',+ title: string,+ baseKey: 'sent' | 'delivered',+ goodDirection: 'up' | 'down'+): MetricTile {+ const counts = stats.buckets.map((bucket) => bucket.counts[key])+ const bases = stats.buckets.map((bucket) => bucket.counts[baseKey])+ const count = sum(counts)+ const base = sum(bases)+ const previous: TransactionalEmailStatsCountsApi | null = stats.previous+ return {+ key,+ title,+ format: 'rate',+ value: base > 0 ? rate(count, base) : null,+ points: ratePoints(counts, bases),+ count,+ baseLabel: baseKey,+ bases,+ counts,+ change:+ base > 0 && previous && previous[baseKey] > 0+ ? rate(count, base) - rate(previous[key], previous[baseKey])+ : null,+ goodDirection,+ }+}++/** The four summary numbers for the period, with a value per bucket for each trend line. */+export function buildMetricTiles(stats: TransactionalEmailStatsOverTimeApi): MetricTile[] {+ const sent = stats.buckets.map((bucket) => bucket.counts.sent)+ const totalSent = sum(sent)+ const previousSent = stats.previous?.sent ?? 0+ return [+ {+ key: 'sent',+ title: 'Sent',+ format: 'count',+ value: totalSent,+ points: sent,+ count: totalSent,+ baseLabel: null,+ bases: [],+ counts: sent,+ change: previousSent > 0 ? ((totalSent - previousSent) / previousSent) * 100 : null,+ goodDirection: 'up',+ },+ rateTile(stats, 'delivered', 'Delivered', 'sent', 'up'),+ rateTile(stats, 'bounced', 'Bounced', 'sent', 'down'),+ rateTile(stats, 'complained', 'Marked as spam', 'delivered', 'down'),+ ]+}diff --git a/products/workflows/frontend/Transactional/metrics/transactionalEmailMetricsLogic.ts b/products/workflows/frontend/Transactional/metrics/transactionalEmailMetricsLogic.tsindex fffdc9c1c3bb..ee2cada32fcb 100644--- a/products/workflows/frontend/Transactional/metrics/transactionalEmailMetricsLogic.ts+++ b/products/workflows/frontend/Transactional/metrics/transactionalEmailMetricsLogic.ts@@ -7,10 +7,12 @@ import { projectLogic } from 'scenes/projectLogic'import {transactionalEmailLogResultsRetrieve,+ transactionalEmailLogStatsOverTimeRetrieve,transactionalEmailLogStatsRetrieve,} from 'products/messaging/frontend/generated/api'import type {TransactionalEmailResultsApi,+ TransactionalEmailStatsOverTimeApi,TransactionalEmailStatsRowApi,} from 'products/messaging/frontend/generated/api.schemas'@@ -44,6 +46,9 @@ export interface transactionalEmailMetricsLogicValues {resultsLoading: booleanresultsQuery: ResultsQuerystatsFailed: boolean+ statsOverTime: TransactionalEmailStatsOverTimeApi | null+ statsOverTimeFailed: boolean+ statsOverTimeLoading: booleantemplateStats: TransactionalEmailStatsRowApi[] | nulltemplateStatsLoading: booleantemplatesFailed: boolean@@ -96,6 +101,21 @@ export interface transactionalEmailMetricsLogicActions {results: TransactionalEmailResultsApi | nullpayload?: void}+ loadStatsOverTime: (_: void) => void+ loadStatsOverTimeFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadStatsOverTimeSuccess: (+ statsOverTime: TransactionalEmailStatsOverTimeApi | null,+ payload?: void+ ) => {+ statsOverTime: TransactionalEmailStatsOverTimeApi | null+ payload?: void+ }loadTemplateStats: (_: void) => voidloadTemplateStatsFailure: (error: string,@@ -165,8 +185,18 @@ export const transactionalEmailMetricsLogic = kea<transactionalEmailMetricsLogic{loadTemplateStats: () => false,loadDomainStats: () => false,+ loadStatsOverTime: () => false,loadTemplateStatsFailure: () => true,loadDomainStatsFailure: () => true,+ loadStatsOverTimeFailure: () => true,+ },+ ],+ statsOverTimeFailed: [+ false,+ {+ loadStatsOverTime: () => false,+ loadStatsOverTimeSuccess: () => false,+ loadStatsOverTimeFailure: () => true,},],hours: [(24 * 7) as number, { setHours: (_, { hours }) => hours }],@@ -192,6 +222,22 @@ export const transactionalEmailMetricsLogic = kea<transactionalEmailMetricsLogic},},],+ statsOverTime: [+ null as TransactionalEmailStatsOverTimeApi | null,+ {+ loadStatsOverTime: async (_: void, breakpoint) => {+ if (values.currentProjectId === null) {+ return null+ }+ return await latest(+ transactionalEmailLogStatsOverTimeRetrieve(String(values.currentProjectId), {+ date_from: dayjs().subtract(values.hours, 'hour').toISOString(),+ }),+ breakpoint+ )+ },+ },+ ],results: [null as TransactionalEmailResultsApi | null,{@@ -225,6 +271,7 @@ export const transactionalEmailMetricsLogic = kea<transactionalEmailMetricsLogicsetHours: () => {actions.loadTemplateStats()actions.loadDomainStats()+ actions.loadStatsOverTime()if (values.canLoadResults) {actions.loadResults()}@@ -249,6 +296,7 @@ export const transactionalEmailMetricsLogic = kea<transactionalEmailMetricsLogicafterMount(({ actions }) => {actions.loadTemplateStats()actions.loadDomainStats()+ actions.loadStatsOverTime()}),])diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c18b77330b0c..5b6db9a94819 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -37738,6 +37738,20 @@ export namespace Schemas {readonly email_sending_suspension_reason: string;}+ /**+ * * `minute` - Minute+ * * `hour` - Hour+ * * `day` - Day+ */+ export type EmailStatsIntervalEnum = typeof EmailStatsIntervalEnum[keyof typeof EmailStatsIntervalEnum];+++ export const EmailStatsIntervalEnum = {+ Minute: 'minute',+ Hour: 'hour',+ Day: 'day',+ } as const;+export interface EmailStatus {/** The `message_id` that the send returned. */id: string;@@ -114736,6 +114750,41 @@ export namespace Schemas {results: TransactionalEmailStatsRow[];}+ export interface TransactionalEmailStatsCounts {+ /** Emails that reached the email provider. */+ sent: number;+ /** Emails the recipient's mail server accepted. */+ delivered: number;+ /** Emails that bounced. */+ bounced: number;+ /** Emails the recipient marked as spam. */+ complained: number;+ /** Emails that were not sent. */+ failed: number;+ }++ export interface TransactionalEmailStatsBucket {+ /** When this time bucket starts. */+ start: string;+ /** Sends queued during this bucket. */+ counts: TransactionalEmailStatsCounts;+ }++ export interface TransactionalEmailStatsOverTime {+ /** The width of each bucket. A `minute` bucket spans five minutes.+ *+ * * `minute` - Minute+ * * `hour` - Hour+ * * `day` - Day */+ interval: EmailStatsIntervalEnum;+ /** The project timezone that the buckets start in. */+ timezone: string;+ /** Every bucket in the period, oldest first. */+ buckets: TransactionalEmailStatsBucket[];+ /** Totals for the same length of time just before the period. Null when retention no longer covers it. */+ previous: TransactionalEmailStatsCounts | null;+ }+export interface TranslateRequest {/*** The text to translate@@ -136330,6 +136379,17 @@ export namespace Schemas {SendingDomain: 'sending_domain',} as const;+ export type TransactionalEmailLogStatsOverTimeRetrieveParams = {+ /**+ * Only sends queued at or after this time. Defaults to 7 days ago. The log keeps sends for 30 days.+ */+ date_from?: string;+ /**+ * Only sends queued before this time. Defaults to now.+ */+ date_to?: string;+ };+export type TurnSuggestionsStateRetrieveParams = {/*** ID of the PostHog AI conversation (task) to read suggestion outcomes for.