Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(analytics): rework the workspace analytics page and fix its backend api

Jonas Kanindabe58843e510a
diff --git a/internal/handlers/analytics_handler.go b/internal/handlers/analytics_handler.go
index ae3677e..fdaf6cf 100644
--- a/internal/handlers/analytics_handler.go
+++ b/internal/handlers/analytics_handler.go
@@ -4,6 +4,7 @@
package handlers
import (
+ "fmt"
"time"
"github.com/goposta/posta/internal/services/cache"
@@ -57,25 +58,19 @@ func (h *AnalyticsHandler) UserAnalytics(c *okapi.Context, req *AnalyticsRequest
return ok(c, resp)
}
- from, to := parseTimeRange(req.From, req.To)
-
- var daily []repositories.DailyCount
- var breakdown []repositories.StatusBreakdown
- var err error
+ if scope.WorkspaceID == nil {
+ return c.AbortBadRequest("no active workspace")
+ }
+ from, to, err := parseTimeRange(req.From, req.To)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
- if scope.WorkspaceID != nil {
- daily, err = h.repo.WorkspaceDailyCounts(*scope.WorkspaceID, from, to, req.Status)
- if err != nil {
- return c.AbortInternalServerError("failed to fetch analytics")
- }
- breakdown, err = h.repo.WorkspaceStatusBreakdown(*scope.WorkspaceID, from, to)
- } else {
- daily, err = h.repo.DailyCounts(scope.UserID, from, to, req.Status)
- if err != nil {
- return c.AbortInternalServerError("failed to fetch analytics")
- }
- breakdown, err = h.repo.StatusBreakdown(scope.UserID, from, to)
+ daily, err := h.repo.WorkspaceDailyCounts(*scope.WorkspaceID, from, to, req.Status)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch analytics")
}
+ breakdown, err := h.repo.WorkspaceStatusBreakdown(*scope.WorkspaceID, from, to)
if err != nil {
return c.AbortInternalServerError("failed to fetch analytics")
}
@@ -100,7 +95,10 @@ func (h *AnalyticsHandler) AdminAnalytics(c *okapi.Context, req *AnalyticsReques
return ok(c, resp)
}
- from, to := parseTimeRange(req.From, req.To)
+ from, to, err := parseTimeRange(req.From, req.To)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
daily, err := h.repo.AdminDailyCounts(from, to, req.Status)
if err != nil {
@@ -135,34 +133,23 @@ func (h *AnalyticsHandler) UserDashboardAnalytics(c *okapi.Context, req *Dashboa
return ok(c, resp)
}
- from, to := parseTimeRange(req.From, req.To)
-
- var delivery []repositories.DeliveryRatePoint
- var bouncePoints []repositories.BounceRatePoint
- var latency *repositories.LatencyPercentiles
- var err error
+ if scope.WorkspaceID == nil {
+ return c.AbortBadRequest("no active workspace")
+ }
+ from, to, err := parseTimeRange(req.From, req.To)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
- if scope.WorkspaceID != nil {
- delivery, err = h.repo.WorkspaceDeliveryRateTrends(*scope.WorkspaceID, from, to)
- if err != nil {
- return c.AbortInternalServerError("failed to fetch delivery rate trends")
- }
- bouncePoints, err = h.repo.WorkspaceBounceRateTrends(*scope.WorkspaceID, from, to)
- if err != nil {
- return c.AbortInternalServerError("failed to fetch bounce rate trends")
- }
- latency, err = h.repo.WorkspaceLatencyPercentiles(*scope.WorkspaceID, from, to)
- } else {
- delivery, err = h.repo.DeliveryRateTrends(scope.UserID, from, to)
- if err != nil {
- return c.AbortInternalServerError("failed to fetch delivery rate trends")
- }
- bouncePoints, err = h.repo.BounceRateTrends(scope.UserID, from, to)
- if err != nil {
- return c.AbortInternalServerError("failed to fetch bounce rate trends")
- }
- latency, err = h.repo.LatencyPercentilesForUser(scope.UserID, from, to)
+ delivery, err := h.repo.WorkspaceDeliveryRateTrends(*scope.WorkspaceID, from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch delivery rate trends")
}
+ bouncePoints, err := h.repo.WorkspaceBounceRateTrends(*scope.WorkspaceID, from, to)
+ if err != nil {
+ return c.AbortInternalServerError("failed to fetch bounce rate trends")
+ }
+ latency, err := h.repo.WorkspaceLatencyPercentiles(*scope.WorkspaceID, from, to)
if err != nil {
return c.AbortInternalServerError("failed to fetch latency percentiles")
}
@@ -202,15 +189,15 @@ func (h *AnalyticsHandler) UserProviderBreakdown(c *okapi.Context, req *Provider
return ok(c, resp)
}
- from, to := parseTimeRange(req.From, req.To)
-
- var rows []repositories.ProviderBreakdownPoint
- var err error
- if scope.WorkspaceID != nil {
- rows, err = h.repo.WorkspaceProviderBreakdown(*scope.WorkspaceID, from, to)
- } else {
- rows, err = h.repo.ProviderBreakdown(scope.UserID, from, to)
+ if scope.WorkspaceID == nil {
+ return c.AbortBadRequest("no active workspace")
}
+ from, to, err := parseTimeRange(req.From, req.To)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
+ rows, err := h.repo.WorkspaceProviderBreakdown(*scope.WorkspaceID, from, to)
if err != nil {
return c.AbortInternalServerError("failed to fetch provider breakdown")
}
@@ -230,7 +217,10 @@ func (h *AnalyticsHandler) AdminProviderBreakdown(c *okapi.Context, req *Provide
return ok(c, resp)
}
- from, to := parseTimeRange(req.From, req.To)
+ from, to, err := parseTimeRange(req.From, req.To)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
rows, err := h.repo.AdminProviderBreakdown(from, to)
if err != nil {
return c.AbortInternalServerError("failed to fetch provider breakdown")
@@ -250,7 +240,10 @@ func (h *AnalyticsHandler) AdminDashboardAnalytics(c *okapi.Context, req *Dashbo
return ok(c, resp)
}
- from, to := parseTimeRange(req.From, req.To)
+ from, to, err := parseTimeRange(req.From, req.To)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
delivery, err := h.repo.AdminDeliveryRateTrends(from, to)
if err != nil {
@@ -275,19 +268,64 @@ func (h *AnalyticsHandler) AdminDashboardAnalytics(c *okapi.Context, req *Dashbo
return ok(c, resp)
}
-func parseTimeRange(fromStr, toStr string) (time.Time, time.Time) {
- to := time.Now()
- from := to.AddDate(0, 0, -30) // default: last 30 days
+// maxAnalyticsRangeDays caps how far a single report may reach. The series is
+// materialised one entry per day in memory and in the response, so without a cap
+// a caller asking for 1970..2099 would have the server build a 47,000-point
+// array per chart.
+const maxAnalyticsRangeDays = 400
+
+// parseTimeRange resolves the requested window to a UTC half-open-ish range:
+// midnight on the from date through the last instant of the to date.
+//
+// Everything is UTC on purpose. The queries bucket rows with
+// `AT TIME ZONE 'UTC'`, so the boundaries have to agree or the first and last
+// day of a report would be cut at the wrong hour.
+func parseTimeRange(fromStr, toStr string) (time.Time, time.Time, error) {
+ now := time.Now().UTC()
+ to := endOfUTCDay(now)
+ from := startOfUTCDay(now.AddDate(0, 0, -defaultAnalyticsRangeDays+1))
if fromStr != "" {
- if t, err := time.Parse("2006-01-02", fromStr); err == nil {
- from = t
+ t, err := time.ParseInLocation("2006-01-02", fromStr, time.UTC)
+ if err != nil {
+ return time.Time{}, time.Time{}, fmt.Errorf("from must be a date like 2026-01-31")
}
+ from = startOfUTCDay(t)
}
if toStr != "" {
- if t, err := time.Parse("2006-01-02", toStr); err == nil {
- to = t.Add(24*time.Hour - time.Second) // end of day
+ t, err := time.ParseInLocation("2006-01-02", toStr, time.UTC)
+ if err != nil {
+ return time.Time{}, time.Time{}, fmt.Errorf("to must be a date like 2026-01-31")
}
+ to = endOfUTCDay(t)
+ }
+
+ if to.Before(from) {
+ return time.Time{}, time.Time{}, fmt.Errorf("from must not be later than to")
+ }
+ // Counted on the calendar, not by dividing the duration: `to` is the last
+ // instant of its day, and Duration.Hours() is a float64 that rounds
+ // 9599h59m59.999999999s up to exactly 9600, which put the count a day over
+ // and rejected ranges that sat exactly on the cap.
+ if days := int(startOfUTCDay(to).Sub(from)/(24*time.Hour)) + 1; days > maxAnalyticsRangeDays {
+ return time.Time{}, time.Time{}, fmt.Errorf(
+ "the range covers %d days; %d is the maximum", days, maxAnalyticsRangeDays)
}
- return from, to
+
+ return from, to, nil
+}
+
+const defaultAnalyticsRangeDays = 30
+
+func startOfUTCDay(t time.Time) time.Time {
+ u := t.UTC()
+ return time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC)
+}
+
+// endOfUTCDay is the last representable instant of the day, so a range stated
+// inclusively really does include everything sent that day. The previous
+// implementation stopped a second early and quietly dropped anything accepted in
+// the final second.
+func endOfUTCDay(t time.Time) time.Time {
+ return startOfUTCDay(t).AddDate(0, 0, 1).Add(-time.Nanosecond)
}
diff --git a/internal/handlers/analytics_range_test.go b/internal/handlers/analytics_range_test.go
new file mode 100644
index 0000000..d206f23
--- /dev/null
+++ b/internal/handlers/analytics_range_test.go
@@ -0,0 +1,84 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package handlers
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestParseTimeRangeIsUTCAndInclusive(t *testing.T) {
+ from, to, err := parseTimeRange("2026-03-01", "2026-03-31")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if from.Location() != time.UTC || to.Location() != time.UTC {
+ t.Fatalf("boundaries must be UTC to match how rows are bucketed, got %s and %s", from.Location(), to.Location())
+ }
+ if from.Format(time.RFC3339) != "2026-03-01T00:00:00Z" {
+ t.Errorf("from should be midnight UTC, got %s", from.Format(time.RFC3339))
+ }
+ // The old implementation stopped a second early and dropped anything
+ // accepted in the final second of the day.
+ lastSecond := time.Date(2026, 3, 31, 23, 59, 59, 0, time.UTC)
+ if to.Before(lastSecond) {
+ t.Errorf("to (%s) excludes the last second of the day", to.Format(time.RFC3339Nano))
+ }
+ if !to.Before(time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC)) {
+ t.Errorf("to (%s) leaks into the next day", to.Format(time.RFC3339Nano))
+ }
+}
+
+func TestParseTimeRangeDefaultsToThirtyDays(t *testing.T) {
+ from, to, err := parseTimeRange("", "")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ days := int(to.Sub(from).Hours()/24) + 1
+ if days != defaultAnalyticsRangeDays {
+ t.Errorf("default range is %d days, want %d", days, defaultAnalyticsRangeDays)
+ }
+}
+
+// Without a cap, a caller asking for a century would have the server build a
+// point per day, per chart, in memory and in the response.
+func TestParseTimeRangeRejectsAbsurdSpans(t *testing.T) {
+ _, _, err := parseTimeRange("1970-01-01", "2099-01-01")
+ if err == nil {
+ t.Fatal("expected a range that large to be refused")
+ }
+ if !strings.Contains(err.Error(), "maximum") {
+ t.Errorf("the error should say what the limit is, got %q", err)
+ }
+}
+
+func TestParseTimeRangeRejectsBadInput(t *testing.T) {
+ if _, _, err := parseTimeRange("2026-03-10", "2026-03-01"); err == nil {
+ t.Error("expected an inverted range to be refused")
+ }
+ if _, _, err := parseTimeRange("last-tuesday", ""); err == nil {
+ t.Error("expected an unparseable date to be refused")
+ }
+ if _, _, err := parseTimeRange("", "not-a-date"); err == nil {
+ t.Error("expected an unparseable date to be refused")
+ }
+}
+
+// Both sides of the cap. Duration.Hours() is a float64 and rounds
+// 9599h59m59.999999999s to exactly 9600, which put the day count one over and
+// rejected a range sitting exactly on the limit.
+func TestParseTimeRangeCapBoundary(t *testing.T) {
+ today := time.Now().UTC().Format("2006-01-02")
+
+ at := time.Now().UTC().AddDate(0, 0, -(maxAnalyticsRangeDays - 1)).Format("2006-01-02")
+ if _, _, err := parseTimeRange(at, today); err != nil {
+ t.Errorf("a range exactly at the cap should be allowed: %v", err)
+ }
+
+ over := time.Now().UTC().AddDate(0, 0, -maxAnalyticsRangeDays).Format("2006-01-02")
+ if _, _, err := parseTimeRange(over, today); err == nil {
+ t.Error("a range one day past the cap should be refused")
+ }
+}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
index 6065840..d93eb45 100644
--- a/internal/storage/migration/constraints.go
+++ b/internal/storage/migration/constraints.go
@@ -48,6 +48,14 @@ func runConstraints(db *gorm.DB) {
rebuildUniqueIndexes(db)
+ // Every analytics query filters one workspace over a date range and groups by
+ // day. The single-column workspace index makes the server read every email a
+ // workspace ever sent and discard most of them; these carry the range too.
+ db.Exec(`CREATE INDEX IF NOT EXISTS idx_emails_workspace_created
+ ON emails (workspace_id, created_at)`)
+ db.Exec(`CREATE INDEX IF NOT EXISTS idx_bounces_workspace_created
+ ON bounces (workspace_id, created_at)`)
+
// Partial unique index: at most one unresolved notification per user and
// condition. It is what makes a recurring condition update the existing
// inbox item instead of adding a row on every dashboard load, and it holds
diff --git a/internal/storage/repositories/analytics_repo.go b/internal/storage/repositories/analytics_repo.go
index 50bdf2f..fbd0aae 100644
--- a/internal/storage/repositories/analytics_repo.go
+++ b/internal/storage/repositories/analytics_repo.go
@@ -4,9 +4,10 @@
package repositories
import (
- "github.com/goposta/posta/internal/models"
+ "sort"
"time"
+ "github.com/goposta/posta/internal/models"
"gorm.io/gorm"
)
@@ -28,47 +29,11 @@ type StatusBreakdown struct {
Count int64 `json:"count"`
}
-// DailyCounts returns email counts per day for a user within a date range, optionally filtered by status.
-func (r *AnalyticsRepository) DailyCounts(userID uint, from, to time.Time, status string) ([]DailyCount, error) {
- var results []DailyCount
- query := r.db.Table("emails").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, COUNT(*) as count").
- Where("user_id = ? AND workspace_id IS NULL AND created_at >= ? AND created_at <= ?", userID, from, to)
- if status != "" {
- query = query.Where("status = ?", status)
- }
- err := query.Group("date").Order("date ASC").Find(&results).Error
- return results, err
-}
-
-// StatusBreakdown returns counts grouped by status for a user within a date range.
-func (r *AnalyticsRepository) StatusBreakdown(userID uint, from, to time.Time) ([]StatusBreakdown, error) {
- var results []StatusBreakdown
- err := r.db.Table("emails").
- Select("status, COUNT(*) as count").
- Where("user_id = ? AND workspace_id IS NULL AND created_at >= ? AND created_at <= ?", userID, from, to).
- Group("status").
- Find(&results).Error
- return results, err
-}
-
-// HourlyCounts returns email counts per hour for a user on a specific day.
-func (r *AnalyticsRepository) HourlyCounts(userID uint, date time.Time) ([]DailyCount, error) {
- var results []DailyCount
- start := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
- end := start.Add(24 * time.Hour)
- err := r.db.Table("emails").
- Select("TO_CHAR(created_at, 'HH24:00') as date, COUNT(*) as count").
- Where("user_id = ? AND created_at >= ? AND created_at < ?", userID, start, end).
- Group("date").Order("date ASC").Find(&results).Error
- return results, err
-}
-
// AdminDailyCounts returns email counts across all users.
func (r *AnalyticsRepository) AdminDailyCounts(from, to time.Time, status string) ([]DailyCount, error) {
var results []DailyCount
query := r.db.Table("emails").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, COUNT(*) as count").
+ Select("TO_CHAR(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') as date, COUNT(*) as count").
Where("created_at >= ? AND created_at <= ?", from, to)
if status != "" {
query = query.Where("status = ?", status)
@@ -127,25 +92,11 @@ type LatencyPercentiles struct {
Avg float64 `json:"avg"`
}
-// DeliveryRateTrends returns daily delivery rate for a user within a date range.
-func (r *AnalyticsRepository) DeliveryRateTrends(userID uint, from, to time.Time) ([]DeliveryRatePoint, error) {
- var rows []deliveryRow
- err := r.db.Table("emails").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, status, COUNT(*) as count").
- Where("user_id = ? AND workspace_id IS NULL AND created_at >= ? AND created_at <= ? AND status IN ?", userID, from, to, []string{string(models.EmailStatusSent), string(models.EmailStatusFailed)}).
- Group("date, status").Order("date ASC").
- Find(&rows).Error
- if err != nil {
- return nil, err
- }
- return buildDeliveryRatePoints(rows, from, to), nil
-}
-
// AdminDeliveryRateTrends returns daily delivery rate across all users.
func (r *AnalyticsRepository) AdminDeliveryRateTrends(from, to time.Time) ([]DeliveryRatePoint, error) {
var rows []deliveryRow
err := r.db.Table("emails").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, status, COUNT(*) as count").
+ Select("TO_CHAR(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') as date, status, COUNT(*) as count").
Where("created_at >= ? AND created_at <= ? AND status IN ?", from, to, []string{string(models.EmailStatusSent), string(models.EmailStatusFailed)}).
Group("date, status").Order("date ASC").
Find(&rows).Error
@@ -155,30 +106,65 @@ func (r *AnalyticsRepository) AdminDeliveryRateTrends(from, to time.Time) ([]Del
return buildDeliveryRatePoints(rows, from, to), nil
}
-func buildDeliveryRatePoints(rows []deliveryRow, from, to time.Time) []DeliveryRatePoint {
- m := make(map[string]*DeliveryRatePoint)
- start := from.Truncate(24 * time.Hour)
- end := to.Truncate(24 * time.Hour)
+// utcDay is the UTC calendar day an instant falls on.
+//
+// The series has to be built the same way Postgres buckets the rows, and the
+// queries pin their buckets to UTC with `AT TIME ZONE 'UTC'`. time.Truncate is
+// not a substitute: it rounds against the zero time, so on a server west of UTC
+// it lands on the previous day and the report loses its final day.
+func utcDay(t time.Time) time.Time {
+ u := t.UTC()
+ return time.Date(u.Year(), u.Month(), u.Day(), 0, 0, 0, 0, time.UTC)
+}
+
+// dayKeys is the gapless list of UTC day labels covering a range, so a quiet day
+// renders as a zero rather than disappearing from the axis.
+func dayKeys(from, to time.Time) []string {
+ start, end := utcDay(from), utcDay(to)
+ if end.Before(start) {
+ return nil
+ }
+ keys := make([]string, 0, int(end.Sub(start)/(24*time.Hour))+1)
for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
- key := d.Format("2006-01-02")
+ keys = append(keys, d.Format("2006-01-02"))
+ }
+ return keys
+}
+
+// buildDeliveryRatePoints turns grouped rows into a gapless daily series.
+//
+// Rows whose day falls outside the requested range are folded onto the nearest
+// end rather than dropped. That cannot happen while the query and the series
+// agree on UTC, but it used to: when Postgres ran in a non-UTC timezone its
+// buckets drifted past the range and the rows vanished from the report with
+// nothing to show that anything was missing.
+func buildDeliveryRatePoints(rows []deliveryRow, from, to time.Time) []DeliveryRatePoint {
+ keys := dayKeys(from, to)
+ if len(keys) == 0 {
+ return []DeliveryRatePoint{}
+ }
+
+ m := make(map[string]*DeliveryRatePoint, len(keys))
+ for _, key := range keys {
m[key] = &DeliveryRatePoint{Date: key}
}
- for _, r := range rows {
- p, ok := m[r.Date]
+
+ first, last := keys[0], keys[len(keys)-1]
+ for _, row := range rows {
+ p, ok := m[row.Date]
if !ok {
- p = &DeliveryRatePoint{Date: r.Date}
- m[r.Date] = p
+ p = m[clampKey(row.Date, first, last)]
}
- switch r.Status {
+ switch row.Status {
case string(models.EmailStatusSent):
- p.Sent = r.Count
+ p.Sent += row.Count
case string(models.EmailStatusFailed):
- p.Failed = r.Count
+ p.Failed += row.Count
}
}
- result := make([]DeliveryRatePoint, 0, len(m))
- for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
- key := d.Format("2006-01-02")
+
+ result := make([]DeliveryRatePoint, 0, len(keys))
+ for _, key := range keys {
p := m[key]
p.Total = p.Sent + p.Failed
if p.Total > 0 {
@@ -189,25 +175,20 @@ func buildDeliveryRatePoints(rows []deliveryRow, from, to time.Time) []DeliveryR
return result
}
-// BounceRateTrends returns daily bounce counts by type for a user.
-func (r *AnalyticsRepository) BounceRateTrends(userID uint, from, to time.Time) ([]BounceRatePoint, error) {
- var rows []bounceRow
- err := r.db.Table("bounces").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, type, COUNT(*) as count").
- Where("user_id = ? AND workspace_id IS NULL AND created_at >= ? AND created_at <= ?", userID, from, to).
- Group("date, type").Order("date ASC").
- Find(&rows).Error
- if err != nil {
- return nil, err
+// clampKey picks the end of the series an out-of-range day belongs to. Keys are
+// zero-padded ISO dates, so they compare correctly as strings.
+func clampKey(key, first, last string) string {
+ if key < first {
+ return first
}
- return buildBounceRatePoints(rows, from, to), nil
+ return last
}
// AdminBounceRateTrends returns daily bounce counts by type across all users.
func (r *AnalyticsRepository) AdminBounceRateTrends(from, to time.Time) ([]BounceRatePoint, error) {
var rows []bounceRow
err := r.db.Table("bounces").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, type, COUNT(*) as count").
+ Select("TO_CHAR(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') as date, type, COUNT(*) as count").
Where("created_at >= ? AND created_at <= ?", from, to).
Group("date, type").Order("date ASC").
Find(&rows).Error
@@ -218,31 +199,34 @@ func (r *AnalyticsRepository) AdminBounceRateTrends(from, to time.Time) ([]Bounc
}
func buildBounceRatePoints(rows []bounceRow, from, to time.Time) []BounceRatePoint {
- m := make(map[string]*BounceRatePoint)
- start := from.Truncate(24 * time.Hour)
- end := to.Truncate(24 * time.Hour)
- for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
- key := d.Format("2006-01-02")
+ keys := dayKeys(from, to)
+ if len(keys) == 0 {
+ return []BounceRatePoint{}
+ }
+
+ m := make(map[string]*BounceRatePoint, len(keys))
+ for _, key := range keys {
m[key] = &BounceRatePoint{Date: key}
}
- for _, r := range rows {
- p, ok := m[r.Date]
+
+ first, last := keys[0], keys[len(keys)-1]
+ for _, row := range rows {
+ p, ok := m[row.Date]
if !ok {
- p = &BounceRatePoint{Date: r.Date}
- m[r.Date] = p
+ p = m[clampKey(row.Date, first, last)]
}
- switch r.Type {
+ switch row.Type {
case "hard":
- p.Hard = r.Count
+ p.Hard += row.Count
case "soft":
- p.Soft = r.Count
+ p.Soft += row.Count
case "complaint":
- p.Complaint = r.Count
+ p.Complaint += row.Count
}
}
- result := make([]BounceRatePoint, 0, len(m))
- for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
- key := d.Format("2006-01-02")
+
+ result := make([]BounceRatePoint, 0, len(keys))
+ for _, key := range keys {
p := m[key]
p.Total = p.Hard + p.Soft + p.Complaint
result = append(result, *p)
@@ -250,22 +234,6 @@ func buildBounceRatePoints(rows []bounceRow, from, to time.Time) []BounceRatePoi
return result
}
-// LatencyPercentilesForUser returns delivery latency percentiles for a user.
-func (r *AnalyticsRepository) LatencyPercentilesForUser(userID uint, from, to time.Time) (*LatencyPercentiles, error) {
- var result LatencyPercentiles
- err := r.db.Table("emails").
- Select(`
- COALESCE(PERCENTILE_CONT(0.50) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p50,
- COALESCE(PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p75,
- COALESCE(PERCENTILE_CONT(0.90) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p90,
- COALESCE(PERCENTILE_CONT(0.99) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as p99,
- COALESCE(AVG(EXTRACT(EPOCH FROM (sent_at - created_at))), 0) as avg
- `).
- Where("user_id = ? AND workspace_id IS NULL AND status = 'sent' AND sent_at IS NOT NULL AND created_at >= ? AND created_at <= ?", userID, from, to).
- Scan(&result).Error
- return &result, err
-}
-
// AdminLatencyPercentiles returns delivery latency percentiles across all users.
func (r *AnalyticsRepository) AdminLatencyPercentiles(from, to time.Time) (*LatencyPercentiles, error) {
var result LatencyPercentiles
@@ -285,7 +253,7 @@ func (r *AnalyticsRepository) AdminLatencyPercentiles(from, to time.Time) (*Late
func (r *AnalyticsRepository) WorkspaceDailyCounts(workspaceID uint, from, to time.Time, status string) ([]DailyCount, error) {
var results []DailyCount
query := r.db.Table("emails").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, COUNT(*) as count").
+ Select("TO_CHAR(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') as date, COUNT(*) as count").
Where("workspace_id = ? AND created_at >= ? AND created_at <= ?", workspaceID, from, to)
if status != "" {
query = query.Where("status = ?", status)
@@ -307,7 +275,7 @@ func (r *AnalyticsRepository) WorkspaceStatusBreakdown(workspaceID uint, from, t
func (r *AnalyticsRepository) WorkspaceDeliveryRateTrends(workspaceID uint, from, to time.Time) ([]DeliveryRatePoint, error) {
var rows []deliveryRow
err := r.db.Table("emails").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, status, COUNT(*) as count").
+ Select("TO_CHAR(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') as date, status, COUNT(*) as count").
Where("workspace_id = ? AND created_at >= ? AND created_at <= ? AND status IN ?", workspaceID, from, to, []string{string(models.EmailStatusSent), string(models.EmailStatusFailed)}).
Group("date, status").Order("date ASC").
Find(&rows).Error
@@ -320,7 +288,7 @@ func (r *AnalyticsRepository) WorkspaceDeliveryRateTrends(workspaceID uint, from
func (r *AnalyticsRepository) WorkspaceBounceRateTrends(workspaceID uint, from, to time.Time) ([]BounceRatePoint, error) {
var rows []bounceRow
err := r.db.Table("bounces").
- Select("TO_CHAR(created_at, 'YYYY-MM-DD') as date, type, COUNT(*) as count").
+ Select("TO_CHAR(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD') as date, type, COUNT(*) as count").
Where("workspace_id = ? AND created_at >= ? AND created_at <= ?", workspaceID, from, to).
Group("date, type").Order("date ASC").
Find(&rows).Error
@@ -347,10 +315,14 @@ func (r *AnalyticsRepository) WorkspaceLatencyPercentiles(workspaceID uint, from
// ProviderBreakdownPoint represents delivery counts bucketed by recipient mailbox provider.
type ProviderBreakdownPoint struct {
- Provider string `json:"provider"`
- Sent int64 `json:"sent"`
- Failed int64 `json:"failed"`
- Bounced int64 `json:"bounced"`
+ Provider string `json:"provider"`
+ Sent int64 `json:"sent"`
+ Failed int64 `json:"failed"`
+ // Suppressed counts sends Posta blocked before they left, because every
+ // recipient was on the suppression list. It was previously reported as
+ // "bounced", which it is not: nothing was ever handed to the provider, so it
+ // says nothing about how that provider treats your mail.
+ Suppressed int64 `json:"suppressed"`
Total int64 `json:"total"`
DeliveryRate float64 `json:"delivery_rate"`
}
@@ -374,18 +346,6 @@ func (r *AnalyticsRepository) queryProviderRows(where string, args []any) ([]pro
return rows, err
}
-// ProviderBreakdown returns delivery counts bucketed by mailbox provider for a user.
-func (r *AnalyticsRepository) ProviderBreakdown(userID uint, from, to time.Time) ([]ProviderBreakdownPoint, error) {
- rows, err := r.queryProviderRows(
- "user_id = ? AND workspace_id IS NULL AND created_at >= ? AND created_at <= ?",
- []any{userID, from, to},
- )
- if err != nil {
- return nil, err
- }
- return buildProviderBreakdown(rows), nil
-}
-
// WorkspaceProviderBreakdown returns delivery counts by provider for a workspace.
func (r *AnalyticsRepository) WorkspaceProviderBreakdown(workspaceID uint, from, to time.Time) ([]ProviderBreakdownPoint, error) {
rows, err := r.queryProviderRows(
@@ -424,7 +384,7 @@ func buildProviderBreakdown(rows []providerRow) []ProviderBreakdownPoint {
case "failed":
p.Failed += row.Count
case "suppressed":
- p.Bounced += row.Count
+ p.Suppressed += row.Count
}
p.Total += row.Count
}
@@ -436,11 +396,14 @@ func buildProviderBreakdown(rows []providerRow) []ProviderBreakdownPoint {
}
out = append(out, *p)
}
- // Sort by total volume desc for stable rendering.
- for i := 1; i < len(out); i++ {
- for j := i; j > 0 && out[j].Total > out[j-1].Total; j-- {
- out[j], out[j-1] = out[j-1], out[j]
+ // Highest volume first, then by name so equal volumes do not reorder between
+ // requests — map iteration order is random, and a table that reshuffles on
+ // every refresh is hard to read.
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].Total != out[j].Total {
+ return out[i].Total > out[j].Total
}
- }
+ return out[i].Provider < out[j].Provider
+ })
return out
}
diff --git a/internal/storage/repositories/analytics_repo_test.go b/internal/storage/repositories/analytics_repo_test.go
new file mode 100644
index 0000000..bfb0037
--- /dev/null
+++ b/internal/storage/repositories/analytics_repo_test.go
@@ -0,0 +1,178 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package repositories
+
+import (
+ "testing"
+ "time"
+)
+
+func dates(points []DeliveryRatePoint) []string {
+ out := make([]string, 0, len(points))
+ for _, p := range points {
+ out = append(out, p.Date)
+ }
+ return out
+}
+
+// The series is built in UTC because the queries bucket in UTC. It used to use
+// time.Truncate, which rounds against the zero time: on a server west of UTC the
+// whole series shifted a day earlier and the last day of every report was
+// missing.
+func TestSeriesIsUTCRegardlessOfServerZone(t *testing.T) {
+ ny, err := time.LoadLocation("America/New_York")
+ if err != nil {
+ t.Skip("tzdata unavailable")
+ }
+ tokyo, err := time.LoadLocation("Asia/Tokyo")
+ if err != nil {
+ t.Skip("tzdata unavailable")
+ }
+
+ want := []string{"2026-03-08", "2026-03-09", "2026-03-10"}
+ for _, loc := range []*time.Location{time.UTC, ny, tokyo} {
+ from := time.Date(2026, 3, 8, 0, 0, 0, 0, time.UTC).In(loc)
+ to := time.Date(2026, 3, 10, 23, 59, 59, 0, time.UTC).In(loc)
+
+ got := dates(buildDeliveryRatePoints(nil, from, to))
+ if len(got) != len(want) {
+ t.Fatalf("%s: got %v, want %v", loc, got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("%s: got %v, want %v", loc, got, want)
+ }
+ }
+ }
+}
+
+// A row whose bucket falls outside the range used to be dropped without trace.
+// It happened whenever Postgres ran in a non-UTC timezone, and the report simply
+// under-reported with nothing to show anything was missing.
+func TestOutOfRangeRowsAreNotLost(t *testing.T) {
+ from := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)
+ to := time.Date(2026, 3, 3, 23, 59, 59, 0, time.UTC)
+
+ rows := []deliveryRow{
+ {Date: "2026-02-28", Status: "sent", Count: 7}, // before the range
+ {Date: "2026-03-02", Status: "sent", Count: 100}, // inside
+ {Date: "2026-03-04", Status: "failed", Count: 3}, // after the range
+ }
+
+ points := buildDeliveryRatePoints(rows, from, to)
+
+ var sent, failed int64
+ for _, p := range points {
+ sent += p.Sent
+ failed += p.Failed
+ }
+ if sent != 107 || failed != 3 {
+ t.Fatalf("accounted for %d sent and %d failed; want 107 and 3", sent, failed)
+ }
+ if points[0].Sent != 7 {
+ t.Errorf("an earlier row should fold onto the first day, got %d", points[0].Sent)
+ }
+ if points[len(points)-1].Failed != 3 {
+ t.Errorf("a later row should fold onto the last day, got %d", points[len(points)-1].Failed)
+ }
+}
+
+// Quiet days have to appear as zeroes; a chart that silently omits them draws a
+// misleading trend.
+func TestSeriesIsGapless(t *testing.T) {
+ from := time.Date(2026, 1, 30, 0, 0, 0, 0, time.UTC)
+ to := time.Date(2026, 2, 2, 23, 59, 59, 0, time.UTC)
+
+ points := buildDeliveryRatePoints([]deliveryRow{{Date: "2026-02-01", Status: "sent", Count: 5}}, from, to)
+
+ want := []string{"2026-01-30", "2026-01-31", "2026-02-01", "2026-02-02"}
+ got := dates(points)
+ for i := range want {
+ if i >= len(got) || got[i] != want[i] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ }
+ if points[2].DeliveryRate != 100 {
+ t.Errorf("expected 100%% on the day with only sends, got %v", points[2].DeliveryRate)
+ }
+ if points[0].DeliveryRate != 0 || points[0].Total != 0 {
+ t.Errorf("a quiet day should be a zero, got %+v", points[0])
+ }
+}
+
+func TestInvertedRangeYieldsNoSeries(t *testing.T) {
+ from := time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC)
+ to := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)
+
+ if got := buildDeliveryRatePoints(nil, from, to); len(got) != 0 {
+ t.Fatalf("expected an empty series, got %v", dates(got))
+ }
+ if got := buildBounceRatePoints(nil, from, to); len(got) != 0 {
+ t.Fatalf("expected an empty bounce series, got %d points", len(got))
+ }
+}
+
+func TestBounceSeriesTotalsAndFolding(t *testing.T) {
+ from := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)
+ to := time.Date(2026, 3, 2, 23, 59, 59, 0, time.UTC)
+
+ rows := []bounceRow{
+ {Date: "2026-03-01", Type: "hard", Count: 2},
+ {Date: "2026-03-01", Type: "soft", Count: 3},
+ {Date: "2026-03-01", Type: "complaint", Count: 1},
+ {Date: "2026-03-09", Type: "hard", Count: 4}, // out of range
+ }
+
+ points := buildBounceRatePoints(rows, from, to)
+ if points[0].Total != 6 {
+ t.Errorf("expected 6 bounces on the first day, got %d", points[0].Total)
+ }
+ if points[len(points)-1].Hard != 4 {
+ t.Errorf("a later row should fold onto the last day, got %d", points[len(points)-1].Hard)
+ }
+}
+
+// Suppressed sends never reached the provider, so they must not be counted for
+// or against its delivery rate.
+func TestProviderRateExcludesSuppressed(t *testing.T) {
+ out := buildProviderBreakdown([]providerRow{
+ {Provider: "Gmail", Status: "sent", Count: 90},
+ {Provider: "Gmail", Status: "failed", Count: 10},
+ {Provider: "Gmail", Status: "suppressed", Count: 50},
+ })
+
+ if len(out) != 1 {
+ t.Fatalf("expected one provider, got %d", len(out))
+ }
+ g := out[0]
+ if g.Suppressed != 50 {
+ t.Errorf("expected 50 suppressed, got %d", g.Suppressed)
+ }
+ if g.Total != 150 {
+ t.Errorf("total should count everything addressed to the provider, got %d", g.Total)
+ }
+ if g.DeliveryRate != 90 {
+ t.Errorf("delivery rate should be 90%% of what was actually attempted, got %v", g.DeliveryRate)
+ }
+}
+
+// Map iteration is random, so equal-volume providers have to be broken by name
+// or the table reshuffles on every refresh.
+func TestProviderOrderIsStable(t *testing.T) {
+ rows := []providerRow{
+ {Provider: "Yahoo", Status: "sent", Count: 10},
+ {Provider: "Outlook", Status: "sent", Count: 10},
+ {Provider: "Gmail", Status: "sent", Count: 99},
+ }
+ want := []string{"Gmail", "Outlook", "Yahoo"}
+
+ for i := 0; i < 20; i++ {
+ out := buildProviderBreakdown(rows)
+ for j := range want {
+ if out[j].Provider != want[j] {
+ t.Fatalf("run %d: got %s at %d, want %s", i, out[j].Provider, j, want[j])
+ }
+ }
+ }
+}
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 12c77f9..7aab17a 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -694,7 +694,8 @@ export interface ProviderBreakdownPoint {
provider: string
sent: number
failed: number
- bounced: number
+ /** Blocked before sending because every recipient was suppressed. Not a bounce. */
+ suppressed: number
total: number
delivery_rate: number
}
diff --git a/web/src/assets/styles.css b/web/src/assets/styles.css
index c90ba49..18df397 100644
--- a/web/src/assets/styles.css
+++ b/web/src/assets/styles.css
@@ -24,6 +24,16 @@
--danger-50: #fef2f2;
--danger-500: #ef4444;
--danger-600: #dc2626;
+
+ /* Semantic colours for text on a surface. The -500/-600 ramp is tuned for
+ fills and borders, where it works in both themes; as small text several of
+ its steps fall below WCAG AA (success-600 is 3.3:1 on white, warning-600
+ 3.19:1). These are the same meanings picked for legibility instead, and
+ they are redefined per theme. */
+ --success-text: #15803d;
+ --warning-text: #b45309;
+ --danger-text: #dc2626;
+ --info-text: #9333ea;
--danger-700: #b91c1c;
/* Semantic tokens */
@@ -105,7 +115,12 @@
--danger-50: #2d0f0f;
--primary-50: #1e0d30;
- --checkmark-color: #d8b4fe
+ --checkmark-color: #d8b4fe;
+
+ --success-text: #22c55e;
+ --warning-text: #f59e0b;
+ --danger-text: #f87171;
+ --info-text: #c084fc;
}
/* ─── Shared tokens ─── */
diff --git a/web/src/views/analytics/Analytics.vue b/web/src/views/analytics/Analytics.vue
index f7bc791..7004049 100644
--- a/web/src/views/analytics/Analytics.vue
+++ b/web/src/views/analytics/Analytics.vue
@@ -1,801 +1,326 @@
<script setup lang="ts">
-import { ref, computed, onMounted } from 'vue'
-import { analyticsApi } from '../../api/analytics'
-import type { DailyCount, StatusBreakdown, DashboardAnalyticsResponse, ProviderBreakdownPoint } from '../../api/types'
-
-const loading = ref(true)
-const dailyCounts = ref<DailyCount[]>([])
-const statusBreakdown = ref<StatusBreakdown[]>([])
-const dashAnalytics = ref<DashboardAnalyticsResponse | null>(null)
-const providerBreakdown = ref<ProviderBreakdownPoint[]>([])
-
-const fromDate = ref('')
-const toDate = ref('')
-const statusFilter = ref('')
-
-// Set default range: last 30 days
-const now = new Date()
-const thirtyDaysAgo = new Date(now)
-thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)
-fromDate.value = thirtyDaysAgo.toISOString().slice(0, 10)
-toDate.value = now.toISOString().slice(0, 10)
-
-async function loadAnalytics() {
- loading.value = true
+import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
+import { useRoute, useRouter } from "vue-router";
+import { storeToRefs } from "pinia";
+import { analyticsApi } from "../../api/analytics";
+import { useWorkspaceStore } from "../../stores/workspace";
+import { useNotificationStore } from "../../stores/notification";
+import { apiMessage } from "../../composables/apiError";
+import type {
+ DashboardAnalyticsResponse,
+ ProviderBreakdownPoint,
+ StatusBreakdown,
+} from "../../api/types";
+import { delta, isoDay, precedingWindow } from "./chart";
+import AnalyticsHeader from "./AnalyticsHeader.vue";
+import KpiTiles, { type Kpi } from "./KpiTiles.vue";
+import DeliveryTrend from "./DeliveryTrend.vue";
+import StatusMix from "./StatusMix.vue";
+import ProviderTable from "./ProviderTable.vue";
+import BounceTrend from "./BounceTrend.vue";
+import LatencyPanel from "./LatencyPanel.vue";
+
+const route = useRoute();
+const router = useRouter();
+const notify = useNotificationStore();
+const ws = useWorkspaceStore();
+const { currentWorkspaceId } = storeToRefs(ws);
+
+const PRESET_DAYS: Record<string, number> = { "7d": 7, "30d": 30, "90d": 90 };
+
+const preset = ref("30d");
+const from = ref("");
+const to = ref("");
+
+const loading = ref(true);
+const refreshing = ref(false);
+const dash = ref<DashboardAnalyticsResponse | null>(null);
+const statusRows = ref<StatusBreakdown[]>([]);
+const providers = ref<ProviderBreakdownPoint[]>([]);
+// The same three figures for the window immediately before this one, which is
+// what turns "94% delivered" into "94%, down two points".
+const previous = ref<{ sent: number; failed: number; bounces: number; latency: number } | null>(null);
+
+const updatedAt = ref<Date | null>(null);
+const nowTs = ref(Date.now());
+let clockTimer = 0;
+
+function applyPreset(key: string) {
+ preset.value = key;
+ if (key === "custom") return;
+ const days = PRESET_DAYS[key] ?? 30;
+ const end = new Date();
+ const start = new Date();
+ start.setDate(start.getDate() - (days - 1));
+ from.value = isoDay(start);
+ to.value = isoDay(end);
+}
+
+applyPreset("30d");
+
+const priorRange = computed(() => precedingWindow(from.value, to.value));
+
+const totals = computed(() => {
+ const trends = dash.value?.delivery_rate_trends ?? [];
+ let sent = 0;
+ let failed = 0;
+ for (const p of trends) {
+ sent += p.sent;
+ failed += p.failed;
+ }
+ const bounces = (dash.value?.bounce_rate_trends ?? []).reduce(
+ (sum, p) => sum + p.hard + p.soft + p.complaint,
+ 0
+ );
+ const attempts = sent + failed;
+ return {
+ sent,
+ failed,
+ attempts,
+ bounces,
+ deliveryRate: attempts > 0 ? (sent / attempts) * 100 : 0,
+ // Bounces over everything attempted, which is how the dashboard and the
+ // health alerts already define the bounce rate. Dividing by delivered mail
+ // instead would be defensible on its own, but it would make this page
+ // disagree with the number printed on the dashboard.
+ bounceRate: attempts > 0 ? (bounces / attempts) * 100 : 0,
+ latency: dash.value?.latency_percentiles?.p90 ?? 0,
+ };
+});
+
+const comparable = computed(() => previous.value !== null);
+
+const kpis = computed<Kpi[]>(() => {
+ const t = totals.value;
+ const p = previous.value;
+ const priorAttempts = p ? p.sent + p.failed : 0;
+ const priorDelivery = priorAttempts > 0 ? (p!.sent / priorAttempts) * 100 : null;
+ const priorBounce = priorAttempts > 0 ? (p!.bounces / priorAttempts) * 100 : null;
+
+ return [
+ {
+ key: "delivered",
+ label: "Delivered",
+ value: t.sent,
+ kind: "count",
+ hint: `of ${t.attempts.toLocaleString()} attempted`,
+ change: p ? delta(t.sent, p.sent) : null,
+ higherIsBetter: true,
+ },
+ {
+ key: "delivery-rate",
+ label: "Delivery rate",
+ value: t.deliveryRate,
+ kind: "percent",
+ hint: t.attempts > 0 ? `${t.failed.toLocaleString()} failed` : "no sends yet",
+ change: priorDelivery === null ? null : t.deliveryRate - priorDelivery,
+ higherIsBetter: true,
+ },
+ {
+ key: "bounce-rate",
+ label: "Bounce rate",
+ value: t.bounceRate,
+ kind: "percent",
+ hint: `${t.bounces.toLocaleString()} bounced of ${t.attempts.toLocaleString()} attempted`,
+ change: priorBounce === null ? null : t.bounceRate - priorBounce,
+ higherIsBetter: false,
+ },
+ {
+ key: "latency",
+ label: "Time to deliver (p90)",
+ value: t.latency,
+ kind: "latency",
+ hint: "9 in 10 arrive faster",
+ change: p && p.latency > 0 ? delta(t.latency, p.latency) : null,
+ higherIsBetter: false,
+ },
+ ];
+});
+
+const updatedLabel = computed(() => {
+ if (!updatedAt.value) return "";
+ const secs = Math.max(0, Math.floor((nowTs.value - updatedAt.value.getTime()) / 1000));
+ if (secs < 10) return "just now";
+ if (secs < 60) return `${secs}s ago`;
+ const mins = Math.floor(secs / 60);
+ if (mins < 60) return `${mins}m ago`;
+ return `${Math.floor(mins / 60)}h ago`;
+});
+
+const hasData = computed(
+ () => (dash.value?.delivery_rate_trends.length ?? 0) > 0 || statusRows.value.length > 0
+);
+
+async function load(showSpinner: boolean) {
+ if (showSpinner) loading.value = true;
+ else refreshing.value = true;
try {
- const [res, dashRes, provRes] = await Promise.all([
- analyticsApi.user(fromDate.value, toDate.value, statusFilter.value || undefined),
- analyticsApi.dashboardAnalytics(fromDate.value, toDate.value),
- analyticsApi.providerBreakdown(fromDate.value, toDate.value),
- ])
- dailyCounts.value = res.data.data.daily_counts || []
- statusBreakdown.value = res.data.data.status_breakdown || []
- dashAnalytics.value = dashRes.data.data
- providerBreakdown.value = provRes.data.data.providers || []
- } catch (e) {
- console.error('Failed to load analytics', e)
+ const prior = priorRange.value;
+ const [dashRes, statusRes, provRes] = await Promise.all([
+ analyticsApi.dashboardAnalytics(from.value, to.value),
+ analyticsApi.user(from.value, to.value),
+ analyticsApi.providerBreakdown(from.value, to.value),
+ ]);
+
+ dash.value = dashRes.data.data;
+ statusRows.value = statusRes.data.data.status_breakdown || [];
+ providers.value = provRes.data.data.providers || [];
+ updatedAt.value = new Date();
+
+ // The comparison is a nicety, not the report. Load it separately so a slow
+ // or failing prior-window query never blocks the numbers people came for.
+ try {
+ const priorRes = await analyticsApi.dashboardAnalytics(prior.from, prior.to);
+ const d = priorRes.data.data;
+ previous.value = {
+ sent: d.delivery_rate_trends.reduce((s, p) => s + p.sent, 0),
+ failed: d.delivery_rate_trends.reduce((s, p) => s + p.failed, 0),
+ bounces: d.bounce_rate_trends.reduce((s, p) => s + p.hard + p.soft + p.complaint, 0),
+ latency: d.latency_percentiles?.p90 ?? 0,
+ };
+ } catch {
+ previous.value = null;
+ }
+ } catch (e: any) {
+ notify.error(apiMessage(e, "Failed to load analytics"));
} finally {
- loading.value = false
+ loading.value = false;
+ refreshing.value = false;
}
}
-onMounted(loadAnalytics)
-
-const totalEmails = computed(() => dailyCounts.value.reduce((sum, d) => sum + d.count, 0))
-const maxCount = computed(() => Math.max(...dailyCounts.value.map(d => d.count), 1))
+function exportCsv() {
+ const lines: string[] = [];
+ const esc = (v: string | number) => {
+ const s = String(v);
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
+ };
-function barHeight(count: number): string {
- return `${Math.max((count / maxCount.value) * 100, 2)}%`
-}
-
-function statusColor(status: string): string {
- switch (status) {
- case 'sent': return 'var(--success-500, #22c55e)'
- case 'failed': return 'var(--danger-500, #ef4444)'
- case 'pending': return 'var(--warning-500, #f59e0b)'
- case 'queued': return 'var(--info-500, #3b82f6)'
- case 'processing': return 'var(--warning-400, #fbbf24)'
- case 'suppressed': return 'var(--text-muted, #9ca3af)'
- case 'scheduled': return 'var(--primary-500, #6366f1)'
- default: return 'var(--text-muted)'
+ lines.push(`# Posta analytics ${from.value} to ${to.value}`);
+ lines.push("");
+ lines.push("section,key,delivered,failed,other,rate");
+ for (const p of dash.value?.delivery_rate_trends ?? []) {
+ lines.push(["delivery", p.date, p.sent, p.failed, "", p.delivery_rate.toFixed(2)].map(esc).join(","));
+ }
+ for (const p of dash.value?.bounce_rate_trends ?? []) {
+ lines.push(["bounces", p.date, "", "", p.hard + p.soft + p.complaint, ""].map(esc).join(","));
+ }
+ for (const r of statusRows.value) {
+ lines.push(["status", r.status, r.count, "", "", ""].map(esc).join(","));
+ }
+ for (const r of providers.value) {
+ lines.push(["provider", r.provider, r.sent, r.failed, r.suppressed, r.delivery_rate.toFixed(2)].map(esc).join(","));
}
-}
-
-function formatDate(dateStr: string): string {
- const d = new Date(dateStr)
- return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })
-}
-
-const totalBreakdown = computed(() => statusBreakdown.value.reduce((sum, s) => sum + s.count, 0))
-
-function breakdownPercent(count: number): string {
- if (totalBreakdown.value === 0) return '0'
- return ((count / totalBreakdown.value) * 100).toFixed(1)
-}
-
-// Provider-specific colors for the mailbox provider breakdown.
-const providerColors: Record<string, string> = {
- Gmail: '#ea4335',
- 'Google Workspace': '#4285f4',
- Outlook: '#0078d4',
- Yahoo: '#6001d2',
- 'Apple iCloud': '#8e8e93',
- Proton: '#6d4aff',
- AOL: '#00bfff',
- GMX: '#1c4587',
- Zoho: '#f04e23',
- Fastmail: '#2968a6',
- Yandex: '#ffcc00',
- China: '#c20000',
- Other: '#9ca3af',
-}
-
-function providerColor(name: string): string {
- return providerColors[name] ?? '#6366f1'
-}
-
-const providerTotal = computed(() => providerBreakdown.value.reduce((sum, p) => sum + p.total, 0))
-function providerPercent(total: number): string {
- if (providerTotal.value === 0) return '0'
- return ((total / providerTotal.value) * 100).toFixed(1)
+ const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `posta-analytics-${from.value}-to-${to.value}.csv`;
+ a.click();
+ URL.revokeObjectURL(url);
+}
+
+// Mirror the range into the URL so a reload or a shared link opens the same
+// report. Replace rather than push, so the back button still leaves the page.
+function syncUrl() {
+ const query: Record<string, string> = { range: preset.value };
+ if (preset.value === "custom") {
+ query.from = from.value;
+ query.to = to.value;
+ }
+ if (query.range !== route.query.range || query.from !== route.query.from || query.to !== route.query.to) {
+ router.replace({ query });
+ }
}
-function providerRateClass(rate: number, total: number): string {
- if (total === 0) return ''
- if (rate < 75) return 'rate-danger'
- if (rate < 90) return 'rate-warning'
- return ''
+function seedFromUrl() {
+ const r = typeof route.query.range === "string" ? route.query.range : "";
+ const qf = typeof route.query.from === "string" ? route.query.from : "";
+ const qt = typeof route.query.to === "string" ? route.query.to : "";
+ if (r === "custom" && qf && qt) {
+ preset.value = "custom";
+ from.value = qf;
+ to.value = qt;
+ } else if (r && PRESET_DAYS[r]) {
+ applyPreset(r);
+ }
}
-// Delivery rate chart helpers
-const deliveryRateMax = computed(() => {
- if (!dashAnalytics.value) return 1
- return Math.max(...dashAnalytics.value.delivery_rate_trends.map(d => d.total), 1)
-})
-
-function deliveryBarHeight(value: number): string {
- const pct = (value / deliveryRateMax.value) * 100
- return `${Math.max(pct, value > 0 ? 2 : 0)}%`
+function onPreset(key: string) {
+ applyPreset(key);
+ if (key !== "custom") {
+ syncUrl();
+ void load(true);
+ }
}
-// Bounce rate chart helpers
-const bounceMax = computed(() => {
- if (!dashAnalytics.value) return 1
- return Math.max(...dashAnalytics.value.bounce_rate_trends.map(d => d.total), 1)
-})
-
-function bounceBarHeight(value: number): string {
- const pct = (value / bounceMax.value) * 100
- return `${Math.max(pct, value > 0 ? 2 : 0)}%`
+function onCustomDate(which: "from" | "to", value: string) {
+ if (!value) return;
+ if (which === "from") from.value = value;
+ else to.value = value;
+ if (from.value > to.value) {
+ notify.error("The start of the range has to come before its end");
+ return;
+ }
+ syncUrl();
+ void load(true);
}
-const totalBounces = computed(() => {
- if (!dashAnalytics.value) return 0
- return dashAnalytics.value.bounce_rate_trends.reduce((sum, d) => sum + d.total, 0)
-})
+onMounted(() => {
+ seedFromUrl();
+ syncUrl();
+ void load(true);
+ clockTimer = window.setInterval(() => {
+ nowTs.value = Date.now();
+ }, 10_000);
+});
-// Latency formatting
-function formatLatency(seconds: number): string {
- if (seconds < 1) return `${Math.round(seconds * 1000)}ms`
- if (seconds < 60) return `${seconds.toFixed(1)}s`
- return `${(seconds / 60).toFixed(1)}m`
-}
+onBeforeUnmount(() => window.clearInterval(clockTimer));
-// Average delivery rate
-const avgDeliveryRate = computed(() => {
- if (!dashAnalytics.value) return 0
- const points = dashAnalytics.value.delivery_rate_trends.filter(d => d.total > 0)
- if (points.length === 0) return 0
- const totalSent = points.reduce((sum, d) => sum + d.sent, 0)
- const totalAll = points.reduce((sum, d) => sum + d.total, 0)
- return totalAll > 0 ? (totalSent / totalAll) * 100 : 0
-})
+watch(currentWorkspaceId, () => load(true));
</script>
<template>
<div>
- <div class="page-header">
- <h1>Analytics</h1>
- </div>
-
- <!-- Filters -->
- <div class="card" style="margin-bottom: 24px">
- <div class="card-body">
- <div class="filters">
- <div class="form-group">
- <label class="form-label">From</label>
- <input v-model="fromDate" type="date" class="form-input" />
- </div>
- <div class="form-group">
- <label class="form-label">To</label>
- <input v-model="toDate" type="date" class="form-input" />
- </div>
- <div class="form-group">
- <label class="form-label">Status</label>
- <select v-model="statusFilter" class="form-select">
- <option value="">All</option>
- <option value="sent">Sent</option>
- <option value="failed">Failed</option>
- <option value="pending">Pending</option>
- <option value="queued">Queued</option>
- <option value="suppressed">Suppressed</option>
- <option value="scheduled">Scheduled</option>
- </select>
- </div>
- <div class="form-group" style="align-self: flex-end">
- <button class="btn btn-primary" @click="loadAnalytics" :disabled="loading">
- {{ loading ? 'Loading...' : 'Apply' }}
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <div v-if="loading" class="loading-page">
- <div class="spinner"></div>
- </div>
+ <AnalyticsHeader
+ :preset="preset"
+ :from="from"
+ :to="to"
+ :loading="loading"
+ :refreshing="refreshing"
+ :updated-label="updatedLabel"
+ :can-export="hasData"
+ @update:preset="onPreset"
+ @update:from="onCustomDate('from', $event)"
+ @update:to="onCustomDate('to', $event)"
+ @refresh="load(false)"
+ @export="exportCsv"
+ />
+
+ <div v-if="loading" class="loading-page"><div class="spinner"></div></div>
<template v-else>
- <!-- Summary -->
- <div class="stats-grid" style="margin-bottom: 24px">
- <div class="stat-card">
- <div class="stat-header">
- <div class="stat-label">Total in Period</div>
- </div>
- <div class="stat-value">{{ totalEmails }}</div>
- </div>
- <div v-for="s in statusBreakdown" :key="s.status" class="stat-card">
- <div class="stat-header">
- <div class="stat-label" style="text-transform: capitalize">{{ s.status }}</div>
- </div>
- <div class="stat-value">{{ s.count }}</div>
- <div class="stat-sub">{{ breakdownPercent(s.count) }}%</div>
- </div>
- </div>
-
- <!-- Daily Chart -->
- <div class="card" style="margin-bottom: 24px">
- <div class="card-header"><h2>Daily Email Volume</h2></div>
- <div class="card-body">
- <div v-if="dailyCounts.length === 0" class="empty-state">
- <h3>No data</h3>
- <p>No emails found in the selected date range.</p>
- </div>
- <div v-else class="chart-container">
- <div class="chart">
- <div
- v-for="day in dailyCounts"
- :key="day.date"
- class="chart-bar-group"
- :title="`${formatDate(day.date)}: ${day.count} emails`"
- >
- <div class="chart-bar" :style="{ height: barHeight(day.count) }">
- <span v-if="day.count > 0" class="chart-bar-label">{{ day.count }}</span>
- </div>
- <div class="chart-bar-date">{{ formatDate(day.date) }}</div>
- </div>
- </div>
- </div>
- </div>
+ <KpiTiles :kpis="kpis" :comparable="comparable" />
+
+ <div class="stack">
+ <DeliveryTrend :points="dash?.delivery_rate_trends ?? []" />
+ <StatusMix :rows="statusRows" />
+ <ProviderTable :rows="providers" />
+ <BounceTrend :points="dash?.bounce_rate_trends ?? []" />
+ <LatencyPanel
+ v-if="dash?.latency_percentiles"
+ :latency="dash.latency_percentiles"
+ />
</div>
-
- <!-- Status Breakdown -->
- <div class="card">
- <div class="card-header"><h2>Status Breakdown</h2></div>
- <div class="card-body">
- <div v-if="statusBreakdown.length === 0" class="empty-state">
- <h3>No data</h3>
- <p>No emails found in the selected date range.</p>
- </div>
- <div v-else class="breakdown">
- <div v-for="s in statusBreakdown" :key="s.status" class="breakdown-row">
- <div class="breakdown-label">
- <span class="breakdown-dot" :style="{ background: statusColor(s.status) }"></span>
- <span style="text-transform: capitalize">{{ s.status }}</span>
- </div>
- <div class="breakdown-bar-track">
- <div
- class="breakdown-bar-fill"
- :style="{ width: breakdownPercent(s.count) + '%', background: statusColor(s.status) }"
- ></div>
- </div>
- <div class="breakdown-value">{{ s.count }} <span class="breakdown-pct">({{ breakdownPercent(s.count) }}%)</span></div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Deliverability by Provider -->
- <div class="card" style="margin-top: 24px">
- <div class="card-header">
- <h2>Deliverability by Provider <span class="card-header-sub">{{ providerTotal }} recipients in period</span></h2>
- </div>
- <div class="card-body">
- <div v-if="providerBreakdown.length === 0" class="empty-state">
- <h3>No data</h3>
- <p>No recipient data in the selected range.</p>
- </div>
- <div v-else class="provider-table">
- <div class="provider-row provider-head">
- <div class="provider-cell provider-name">Provider</div>
- <div class="provider-cell provider-bar-cell">Volume</div>
- <div class="provider-cell provider-num">Sent</div>
- <div class="provider-cell provider-num">Failed</div>
- <div class="provider-cell provider-num">Rate</div>
- </div>
- <div v-for="p in providerBreakdown" :key="p.provider" class="provider-row">
- <div class="provider-cell provider-name">
- <span class="breakdown-dot" :style="{ background: providerColor(p.provider) }"></span>
- {{ p.provider }}
- </div>
- <div class="provider-cell provider-bar-cell">
- <div class="breakdown-bar-track">
- <div
- class="breakdown-bar-fill"
- :style="{ width: providerPercent(p.total) + '%', background: providerColor(p.provider) }"
- ></div>
- </div>
- <div class="provider-pct">{{ providerPercent(p.total) }}%</div>
- </div>
- <div class="provider-cell provider-num">{{ p.sent }}</div>
- <div class="provider-cell provider-num">{{ p.failed }}</div>
- <div
- class="provider-cell provider-num provider-rate"
- :class="providerRateClass(p.delivery_rate, p.sent + p.failed)"
- >
- {{ (p.sent + p.failed) > 0 ? p.delivery_rate.toFixed(1) + '%' : '—' }}
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Dashboard Analytics: Delivery Rate, Bounce Rate, Latency -->
- <template v-if="dashAnalytics">
- <!-- Delivery Rate Trends -->
- <div class="card" style="margin-top: 24px">
- <div class="card-header">
- <h2>Delivery Rate Trends <span class="card-header-sub">{{ avgDeliveryRate.toFixed(1) }}% avg</span></h2>
- </div>
- <div class="card-body">
- <div v-if="dashAnalytics.delivery_rate_trends.length === 0" class="empty-state">
- <h3>No data</h3>
- <p>No delivery data in the selected range.</p>
- </div>
- <div v-else>
- <div class="trend-chart">
- <div class="trend-chart-bars">
- <div
- v-for="day in dashAnalytics.delivery_rate_trends"
- :key="day.date"
- class="trend-bar-group"
- :title="`${formatDate(day.date)}: ${day.sent} sent, ${day.failed} failed (${day.delivery_rate.toFixed(1)}%)`"
- >
- <div class="trend-bar-stack">
- <div class="trend-bar trend-bar-failed" :style="{ height: deliveryBarHeight(day.failed) }"></div>
- <div class="trend-bar trend-bar-sent" :style="{ height: deliveryBarHeight(day.sent) }"></div>
- </div>
- <div class="trend-rate-label" :class="{ 'rate-warning': day.delivery_rate < 90 && day.total > 0, 'rate-danger': day.delivery_rate < 75 && day.total > 0 }">
- {{ day.total > 0 ? day.delivery_rate.toFixed(0) + '%' : '' }}
- </div>
- <div class="trend-bar-date">{{ formatDate(day.date) }}</div>
- </div>
- </div>
- <div class="trend-chart-legend">
- <span class="trend-legend-item"><span class="trend-legend-dot trend-legend-sent"></span> Sent</span>
- <span class="trend-legend-item"><span class="trend-legend-dot trend-legend-failed"></span> Failed</span>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Bounce Rate Graph -->
- <div class="card" style="margin-top: 24px">
- <div class="card-header">
- <h2>Bounce Rate <span class="card-header-sub">{{ totalBounces }} total bounces</span></h2>
- </div>
- <div class="card-body">
- <div v-if="totalBounces === 0" class="empty-state">
- <h3>No bounces</h3>
- <p>No bounces recorded in the selected range.</p>
- </div>
- <div v-else>
- <div class="trend-chart">
- <div class="trend-chart-bars">
- <div
- v-for="day in dashAnalytics.bounce_rate_trends"
- :key="day.date"
- class="trend-bar-group"
- :title="`${formatDate(day.date)}: ${day.hard} hard, ${day.soft} soft, ${day.complaint} complaint`"
- >
- <div class="trend-bar-stack">
- <div class="trend-bar bounce-bar-complaint" :style="{ height: bounceBarHeight(day.complaint) }"></div>
- <div class="trend-bar bounce-bar-soft" :style="{ height: bounceBarHeight(day.soft) }"></div>
- <div class="trend-bar bounce-bar-hard" :style="{ height: bounceBarHeight(day.hard) }"></div>
- </div>
- <div class="trend-bar-date">{{ formatDate(day.date) }}</div>
- </div>
- </div>
- <div class="trend-chart-legend">
- <span class="trend-legend-item"><span class="trend-legend-dot bounce-legend-hard"></span> Hard</span>
- <span class="trend-legend-item"><span class="trend-legend-dot bounce-legend-soft"></span> Soft</span>
- <span class="trend-legend-item"><span class="trend-legend-dot bounce-legend-complaint"></span> Complaint</span>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Latency Percentiles -->
- <div class="card" style="margin-top: 24px">
- <div class="card-header">
- <h2>Delivery Latency</h2>
- </div>
- <div class="card-body">
- <div v-if="dashAnalytics.latency_percentiles.p50 === 0 && dashAnalytics.latency_percentiles.avg === 0" class="empty-state">
- <h3>No data</h3>
- <p>No delivered emails in the selected range.</p>
- </div>
- <div v-else class="latency-grid">
- <div class="latency-card">
- <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.avg) }}</div>
- <div class="latency-label">Average</div>
- </div>
- <div class="latency-card">
- <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.p50) }}</div>
- <div class="latency-label">p50 (Median)</div>
- </div>
- <div class="latency-card">
- <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.p75) }}</div>
- <div class="latency-label">p75</div>
- </div>
- <div class="latency-card">
- <div class="latency-value">{{ formatLatency(dashAnalytics.latency_percentiles.p90) }}</div>
- <div class="latency-label">p90</div>
- </div>
- <div class="latency-card">
- <div class="latency-value latency-value-tail">{{ formatLatency(dashAnalytics.latency_percentiles.p99) }}</div>
- <div class="latency-label">p99</div>
- </div>
- </div>
- </div>
- </div>
- </template>
</template>
</div>
</template>
<style scoped>
-.filters {
- display: flex;
- gap: 16px;
- flex-wrap: wrap;
- align-items: flex-end;
-}
-
-.filters .form-group {
- min-width: 140px;
-}
-
-.stat-sub {
- font-size: 12px;
- color: var(--text-muted);
- margin-top: 2px;
-}
-
-.chart-container {
- overflow-x: auto;
- padding-bottom: 8px;
-}
-
-.chart {
- display: flex;
- align-items: flex-end;
- gap: 4px;
- height: 220px;
- min-width: fit-content;
-}
-
-.chart-bar-group {
- display: flex;
- flex-direction: column;
- align-items: center;
- flex: 1;
- min-width: 28px;
- max-width: 48px;
- height: 100%;
- justify-content: flex-end;
-}
-
-.chart-bar {
- width: 100%;
- background: var(--primary-500, #6366f1);
- border-radius: 4px 4px 0 0;
- min-height: 2px;
- position: relative;
- transition: height 0.3s ease;
-}
-
-.chart-bar-label {
- position: absolute;
- top: -20px;
- left: 50%;
- transform: translateX(-50%);
- font-size: 10px;
- color: var(--text-muted);
- white-space: nowrap;
-}
-
-.chart-bar-date {
- font-size: 10px;
- color: var(--text-muted);
- margin-top: 6px;
- white-space: nowrap;
- transform: rotate(-45deg);
- transform-origin: top center;
-}
-
-.breakdown {
- display: grid;
- gap: 12px;
-}
-
-.breakdown-row {
- display: flex;
- align-items: center;
- gap: 12px;
-}
-
-.breakdown-label {
- display: flex;
- align-items: center;
- gap: 8px;
- min-width: 110px;
- font-size: 13px;
- font-weight: 500;
- color: var(--text-primary);
-}
-
-.breakdown-dot {
- width: 10px;
- height: 10px;
- border-radius: 50%;
- flex-shrink: 0;
-}
-
-.breakdown-bar-track {
- flex: 1;
- height: 8px;
- background: var(--bg-secondary);
- border-radius: 4px;
- overflow: hidden;
-}
-
-.breakdown-bar-fill {
- height: 100%;
- border-radius: 4px;
- transition: width 0.3s ease;
-}
-
-.breakdown-value {
- min-width: 100px;
- text-align: right;
- font-size: 13px;
- font-weight: 600;
- color: var(--text-primary);
-}
-
-.breakdown-pct {
- font-weight: 400;
- color: var(--text-muted);
-}
-
-/* Card header subtitle */
-.card-header-sub {
- font-weight: 400;
- font-size: 13px;
- color: var(--text-muted);
-}
-
-/* Delivery rate & bounce trend charts */
-.trend-chart {
- padding: 8px 0;
-}
-
-.trend-chart-bars {
- display: flex;
- align-items: flex-end;
- gap: 3px;
- height: 160px;
- padding-bottom: 44px;
- position: relative;
- overflow-x: auto;
-}
-
-.trend-bar-group {
- flex: 1;
- display: flex;
- flex-direction: column;
- align-items: center;
- height: 100%;
- min-width: 24px;
- max-width: 42px;
- position: relative;
-}
-
-.trend-bar-stack {
- flex: 1;
- width: 100%;
- max-width: 32px;
+.stack {
display: flex;
flex-direction: column;
- justify-content: flex-end;
- position: relative;
-}
-
-.trend-bar {
- width: 100%;
- min-width: 0;
- transition: height 0.3s ease;
-}
-
-.trend-bar-sent {
- background: var(--success-500, #22c55e);
- border-radius: 3px 3px 0 0;
-}
-
-.trend-bar-failed {
- background: var(--danger-400, #f87171);
-}
-
-.trend-bar-stack .trend-bar:first-child {
- border-radius: 3px 3px 0 0;
-}
-
-.trend-rate-label {
- font-size: 10px;
- color: var(--success-600, #16a34a);
- font-weight: 600;
- margin-top: 2px;
- white-space: nowrap;
-}
-
-.trend-rate-label.rate-warning {
- color: var(--warning-600, #ca8a04);
-}
-
-.trend-rate-label.rate-danger {
- color: var(--danger-600, #dc2626);
-}
-
-.trend-bar-date {
- position: absolute;
- bottom: -38px;
- font-size: 10px;
- color: var(--text-muted);
- white-space: nowrap;
- transform: rotate(-45deg);
- transform-origin: top center;
-}
-
-.trend-chart-legend {
- display: flex;
- gap: 16px;
- justify-content: center;
- margin-top: 12px;
-}
-
-.trend-legend-item {
- display: flex;
- align-items: center;
- gap: 6px;
- font-size: 12px;
- color: var(--text-muted);
-}
-
-.trend-legend-dot {
- width: 10px;
- height: 10px;
- border-radius: 2px;
-}
-
-.trend-legend-sent { background: var(--success-500, #22c55e); }
-.trend-legend-failed { background: var(--danger-400, #f87171); }
-
-/* Bounce type colors */
-.bounce-bar-hard { background: var(--danger-500, #ef4444); }
-.bounce-bar-soft { background: var(--warning-500, #f59e0b); }
-.bounce-bar-complaint { background: var(--purple-500, #a855f7); }
-.bounce-legend-hard { background: var(--danger-500, #ef4444); }
-.bounce-legend-soft { background: var(--warning-500, #f59e0b); }
-.bounce-legend-complaint { background: var(--purple-500, #a855f7); }
-
-/* Latency percentiles */
-.latency-grid {
- display: grid;
- grid-template-columns: repeat(5, 1fr);
- gap: 12px;
-}
-
-@media (max-width: 768px) {
- .latency-grid {
- grid-template-columns: repeat(3, 1fr);
- }
-}
-
-@media (max-width: 480px) {
- .latency-grid {
- grid-template-columns: repeat(2, 1fr);
- }
-}
-
-.latency-card {
- text-align: center;
- padding: 16px 8px;
- background: var(--bg-secondary);
- border-radius: 8px;
-}
-
-.latency-value {
- font-size: 22px;
- font-weight: 700;
- color: var(--text-primary);
-}
-
-.latency-value-tail {
- color: var(--warning-600, #ca8a04);
-}
-
-.latency-label {
- font-size: 12px;
- color: var(--text-muted);
- margin-top: 4px;
-}
-
-/* Provider breakdown */
-.provider-table {
- display: grid;
- gap: 6px;
-}
-
-.provider-row {
- display: grid;
- grid-template-columns: minmax(140px, 1.4fr) minmax(200px, 3fr) 80px 80px 80px;
- align-items: center;
- gap: 12px;
- padding: 8px 0;
- border-bottom: 1px solid var(--border-color, #e5e7eb);
-}
-
-.provider-row:last-child {
- border-bottom: none;
-}
-
-.provider-head {
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.04em;
- color: var(--text-muted);
- font-weight: 600;
- padding-bottom: 6px;
-}
-
-.provider-cell {
- font-size: 13px;
- color: var(--text-primary);
-}
-
-.provider-name {
- display: flex;
- align-items: center;
- gap: 8px;
- font-weight: 500;
-}
-
-.provider-bar-cell {
- display: flex;
- align-items: center;
- gap: 10px;
-}
-
-.provider-bar-cell .breakdown-bar-track {
- flex: 1;
-}
-
-.provider-pct {
- font-size: 12px;
- color: var(--text-muted);
- min-width: 44px;
- text-align: right;
-}
-
-.provider-num {
- text-align: right;
- font-variant-numeric: tabular-nums;
-}
-
-.provider-rate {
- font-weight: 600;
-}
-
-.provider-rate.rate-warning {
- color: var(--warning-600, #ca8a04);
-}
-
-.provider-rate.rate-danger {
- color: var(--danger-600, #dc2626);
-}
-
-@media (max-width: 640px) {
- .provider-row {
- grid-template-columns: minmax(120px, 1fr) 60px 60px 60px;
- }
- .provider-bar-cell {
- grid-column: 1 / -1;
- order: 99;
- margin-top: 4px;
- }
+ gap: 24px;
}
</style>
diff --git a/web/src/views/analytics/AnalyticsHeader.vue b/web/src/views/analytics/AnalyticsHeader.vue
new file mode 100644
index 0000000..945e735
--- /dev/null
+++ b/web/src/views/analytics/AnalyticsHeader.vue
@@ -0,0 +1,176 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { longDate } from "./chart";
+
+const props = defineProps<{
+ preset: string;
+ from: string;
+ to: string;
+ loading: boolean;
+ refreshing: boolean;
+ updatedLabel: string;
+ canExport: boolean;
+}>();
+
+const emit = defineEmits<{
+ (e: "update:preset", value: string): void;
+ (e: "update:from", value: string): void;
+ (e: "update:to", value: string): void;
+ (e: "refresh"): void;
+ (e: "export"): void;
+}>();
+
+const PRESETS = [
+ { key: "7d", label: "7 days" },
+ { key: "30d", label: "30 days" },
+ { key: "90d", label: "90 days" },
+ { key: "custom", label: "Custom" },
+];
+
+// A relative range does not say where the charts actually start, and every axis
+// label is in the reader's own timezone, so spell the window out.
+const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "local time";
+
+const window = computed(() => `${longDate(props.from)} — ${longDate(props.to)}`);
+
+const custom = computed(() => props.preset === "custom");
+</script>
+
+<template>
+ <div>
+ <div class="page-header">
+ <div>
+ <h1>Analytics</h1>
+ <p class="page-subtitle">
+ {{ window }} · {{ tz }}
+ <span v-if="updatedLabel" class="dot">·</span>
+ <span v-if="updatedLabel">updated {{ updatedLabel }}</span>
+ </p>
+ </div>
+ <div class="header-actions">
+ <button
+ class="btn btn-secondary"
+ :disabled="!canExport"
+ :title="canExport ? 'Download this report as CSV' : 'Nothing to export yet'"
+ @click="emit('export')"
+ >
+ Export CSV
+ </button>
+ <button class="btn btn-secondary" :disabled="loading || refreshing" @click="emit('refresh')">
+ {{ refreshing ? "Refreshing…" : "Refresh" }}
+ </button>
+ </div>
+ </div>
+
+ <div class="range">
+ <div class="chips" role="group" aria-label="Time range">
+ <button
+ v-for="p in PRESETS"
+ :key="p.key"
+ type="button"
+ class="chip"
+ :class="{ active: preset === p.key }"
+ :aria-pressed="preset === p.key"
+ @click="emit('update:preset', p.key)"
+ >
+ {{ p.label }}
+ </button>
+ </div>
+
+ <div v-if="custom" class="custom">
+ <label class="custom-field">
+ <span>From</span>
+ <input
+ :value="from"
+ type="date"
+ class="form-input"
+ :max="to"
+ @change="emit('update:from', ($event.target as HTMLInputElement).value)"
+ />
+ </label>
+ <label class="custom-field">
+ <span>To</span>
+ <input
+ :value="to"
+ type="date"
+ class="form-input"
+ :min="from"
+ @change="emit('update:to', ($event.target as HTMLInputElement).value)"
+ />
+ </label>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.page-subtitle {
+ font-size: 13px;
+ color: var(--text-tertiary);
+ margin-top: 4px;
+}
+
+.dot {
+ opacity: 0.6;
+ margin: 0 2px;
+}
+
+.header-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+
+.range {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ flex-wrap: wrap;
+ margin-bottom: 20px;
+}
+
+.chips {
+ display: flex;
+ gap: 6px;
+}
+
+.chip {
+ padding: 6px 14px;
+ border: 1px solid var(--border-primary);
+ border-radius: 999px;
+ background: var(--bg-primary);
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--text-secondary);
+ cursor: pointer;
+}
+
+.chip:hover {
+ color: var(--text-primary);
+ background: var(--bg-hover);
+}
+
+.chip.active {
+ background: var(--primary-600);
+ border-color: var(--primary-600);
+ color: #fff;
+}
+
+.custom {
+ display: flex;
+ gap: 12px;
+ flex-wrap: wrap;
+}
+
+.custom-field {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.custom-field .form-input {
+ width: auto;
+}
+</style>
diff --git a/web/src/views/analytics/BounceTrend.vue b/web/src/views/analytics/BounceTrend.vue
new file mode 100644
index 0000000..0eb0c25
--- /dev/null
+++ b/web/src/views/analytics/BounceTrend.vue
@@ -0,0 +1,109 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import type { BounceRatePoint } from "../../api/types";
+import { formatNumber, longDate } from "./chart";
+import StackedBars, { type BarPoint, type Series } from "./StackedBars.vue";
+
+const props = defineProps<{ points: BounceRatePoint[] }>();
+
+const series: Series[] = [
+ { key: "hard", label: "Hard", colorVar: "--danger-500" },
+ { key: "soft", label: "Soft", colorVar: "--warning-500" },
+ { key: "complaint", label: "Complaint", colorVar: "--primary-500" },
+];
+
+const bars = computed<BarPoint[]>(() =>
+ props.points.map((p) => ({
+ date: p.date,
+ values: { hard: p.hard, soft: p.soft, complaint: p.complaint },
+ }))
+);
+
+const totals = computed(() => {
+ let hard = 0;
+ let soft = 0;
+ let complaint = 0;
+ for (const p of props.points) {
+ hard += p.hard;
+ soft += p.soft;
+ complaint += p.complaint;
+ }
+ return { hard, soft, complaint, total: hard + soft + complaint };
+});
+</script>
+
+<template>
+ <div class="card">
+ <div class="card-header">
+ <h2>Bounces</h2>
+ <div class="summary">
+ <strong>{{ formatNumber(totals.total) }}</strong> in this window
+ </div>
+ </div>
+
+ <div class="card-body">
+ <div v-if="totals.total === 0" class="empty-state chart-empty">
+ <h3>No bounces</h3>
+ <p>Nothing bounced in this window, which is the result you want.</p>
+ </div>
+
+ <template v-else>
+ <StackedBars :points="bars" :series="series" chart-label="Bounces per day by type">
+ <template #tip="{ point, total }">
+ <strong>{{ longDate(point.date) }}</strong>
+ <span><i class="key" style="background: var(--danger-500)"></i>{{ point.values.hard }} hard</span>
+ <span><i class="key" style="background: var(--warning-500)"></i>{{ point.values.soft }} soft</span>
+ <span><i class="key" style="background: var(--primary-500)"></i>{{ point.values.complaint }} complaint</span>
+ <span class="tip-total">{{ total }} total</span>
+ </template>
+ </StackedBars>
+
+ <div class="legend">
+ <span><i class="key" style="background: var(--danger-500)"></i>Hard — the address does not exist</span>
+ <span><i class="key" style="background: var(--warning-500)"></i>Soft — temporary, may retry</span>
+ <span><i class="key" style="background: var(--primary-500)"></i>Complaint — marked as spam</span>
+ </div>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.summary {
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.summary strong {
+ color: var(--text-secondary);
+ font-size: 13px;
+}
+
+.chart-empty {
+ padding: 36px 16px;
+}
+
+.legend {
+ display: flex;
+ gap: 18px;
+ flex-wrap: wrap;
+ margin-top: 14px;
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.key {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+ margin-right: 6px;
+}
+
+.tip-total {
+ padding-top: 4px;
+ margin-top: 2px;
+ border-top: 1px solid var(--border-secondary);
+ color: var(--text-tertiary);
+}
+</style>
diff --git a/web/src/views/analytics/DeliveryTrend.vue b/web/src/views/analytics/DeliveryTrend.vue
new file mode 100644
index 0000000..2d3852a
--- /dev/null
+++ b/web/src/views/analytics/DeliveryTrend.vue
@@ -0,0 +1,133 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import type { DeliveryRatePoint } from "../../api/types";
+import { formatNumber, longDate, shortDate } from "./chart";
+import StackedBars, { type BarPoint, type Series } from "./StackedBars.vue";
+
+const props = defineProps<{ points: DeliveryRatePoint[] }>();
+
+const series: Series[] = [
+ { key: "sent", label: "Delivered", colorVar: "--success-500" },
+ { key: "failed", label: "Failed", colorVar: "--danger-500" },
+];
+
+const bars = computed<BarPoint[]>(() =>
+ props.points.map((p) => ({ date: p.date, values: { sent: p.sent, failed: p.failed } }))
+);
+
+const totals = computed(() => {
+ let sent = 0;
+ let failed = 0;
+ for (const p of props.points) {
+ sent += p.sent;
+ failed += p.failed;
+ }
+ return { sent, failed, total: sent + failed };
+});
+
+const byDate = computed(() => {
+ const map = new Map<string, DeliveryRatePoint>();
+ for (const p of props.points) map.set(p.date, p);
+ return map;
+});
+
+// The worst day is the one worth naming: an average delivery rate hides the
+// afternoon a route broke.
+const worst = computed(() => {
+ let found: DeliveryRatePoint | null = null;
+ for (const p of props.points) {
+ if (p.total === 0) continue;
+ if (!found || p.delivery_rate < found.delivery_rate) found = p;
+ }
+ return found;
+});
+</script>
+
+<template>
+ <div class="card">
+ <div class="card-header">
+ <h2>Delivery</h2>
+ <div class="summary">
+ <strong>{{ formatNumber(totals.sent) }}</strong> delivered
+ <span class="dot">·</span>
+ <strong>{{ formatNumber(totals.failed) }}</strong> failed
+ <template v-if="worst && worst.delivery_rate < 100">
+ <span class="dot">·</span>
+ <span>worst day {{ worst.delivery_rate.toFixed(0) }}% on {{ shortDate(worst.date) }}</span>
+ </template>
+ </div>
+ </div>
+
+ <div class="card-body">
+ <div v-if="totals.total === 0" class="empty-state chart-empty">
+ <h3>No sends in this window</h3>
+ <p>Delivery appears here once emails start going out.</p>
+ </div>
+
+ <template v-else>
+ <StackedBars :points="bars" :series="series" chart-label="Emails delivered and failed per day">
+ <template #tip="{ point }">
+ <strong>{{ longDate(point.date) }}</strong>
+ <span><i class="key" style="background: var(--success-500)"></i>{{ point.values.sent.toLocaleString() }} delivered</span>
+ <span><i class="key" style="background: var(--danger-500)"></i>{{ point.values.failed.toLocaleString() }} failed</span>
+ <span v-if="byDate.get(point.date)?.total" class="tip-rate">
+ {{ byDate.get(point.date)!.delivery_rate.toFixed(1) }}% delivered
+ </span>
+ </template>
+ </StackedBars>
+
+ <div class="legend">
+ <span><i class="key" style="background: var(--success-500)"></i>Delivered</span>
+ <span><i class="key" style="background: var(--danger-500)"></i>Failed</span>
+ </div>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.summary {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ flex-wrap: wrap;
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.summary strong {
+ color: var(--text-secondary);
+ font-size: 13px;
+}
+
+.dot {
+ opacity: 0.6;
+}
+
+.chart-empty {
+ padding: 36px 16px;
+}
+
+.legend {
+ display: flex;
+ gap: 16px;
+ margin-top: 14px;
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.key {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+ margin-right: 6px;
+}
+
+.tip-rate {
+ padding-top: 4px;
+ margin-top: 2px;
+ border-top: 1px solid var(--border-secondary);
+ color: var(--text-tertiary);
+}
+</style>
diff --git a/web/src/views/analytics/KpiTiles.vue b/web/src/views/analytics/KpiTiles.vue
new file mode 100644
index 0000000..d6b6d08
--- /dev/null
+++ b/web/src/views/analytics/KpiTiles.vue
@@ -0,0 +1,120 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import { formatLatency, formatNumber, formatPercent } from "./chart";
+
+export interface Kpi {
+ key: string;
+ label: string;
+ value: number;
+ kind: "count" | "percent" | "latency";
+ hint: string;
+ // change is the period-over-period move in percentage points for rates and in
+ // percent for counts. null means there was no prior figure to compare against.
+ change: number | null;
+ // higherIsBetter decides whether a rise is coloured as good or bad. Bounce and
+ // latency are the ones where up is the wrong direction.
+ higherIsBetter: boolean;
+}
+
+const props = defineProps<{ kpis: Kpi[]; comparable: boolean }>();
+
+function display(k: Kpi): string {
+ if (k.kind === "percent") return formatPercent(k.value);
+ if (k.kind === "latency") return formatLatency(k.value);
+ return formatNumber(k.value);
+}
+
+function changeLabel(k: Kpi): string {
+ if (k.change === null) return "";
+ const arrow = k.change > 0 ? "↑" : k.change < 0 ? "↓" : "→";
+ const magnitude = Math.abs(k.change);
+ // A rate's move is stated in points, because "the bounce rate rose 50%" is
+ // ambiguous between 2%→3% and 2%→52%.
+ const unit = k.kind === "percent" ? " pts" : "%";
+ return `${arrow} ${magnitude.toFixed(magnitude < 10 ? 1 : 0)}${unit}`;
+}
+
+function tone(k: Kpi): string {
+ if (k.change === null || Math.abs(k.change) < 0.05) return "flat";
+ const improving = k.change > 0 === k.higherIsBetter;
+ return improving ? "good" : "bad";
+}
+
+const tiles = computed(() => props.kpis);
+</script>
+
+<template>
+ <div class="kpis">
+ <div v-for="k in tiles" :key="k.key" class="kpi">
+ <div class="kpi-label">{{ k.label }}</div>
+ <div class="kpi-value">{{ display(k) }}</div>
+ <div class="kpi-foot">
+ <span v-if="comparable && k.change !== null" class="kpi-change" :class="tone(k)">
+ {{ changeLabel(k) }}
+ </span>
+ <span class="kpi-hint">{{ comparable && k.change !== null ? "vs previous period" : k.hint }}</span>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));
+ gap: 16px;
+ margin-bottom: 24px;
+}
+
+.kpi {
+ padding: 16px 18px;
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-lg);
+ background: var(--bg-primary);
+}
+
+.kpi-label {
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--text-tertiary);
+}
+
+.kpi-value {
+ margin-top: 6px;
+ font-size: 26px;
+ font-weight: 700;
+ line-height: 1.1;
+ color: var(--text-primary);
+ font-variant-numeric: tabular-nums;
+}
+
+.kpi-foot {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin-top: 8px;
+ font-size: 12px;
+}
+
+.kpi-change {
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+}
+
+.kpi-change.good {
+ color: var(--success-text);
+}
+
+.kpi-change.bad {
+ color: var(--danger-text);
+}
+
+.kpi-change.flat {
+ color: var(--text-tertiary);
+}
+
+.kpi-hint {
+ color: var(--text-tertiary);
+}
+</style>
diff --git a/web/src/views/analytics/LatencyPanel.vue b/web/src/views/analytics/LatencyPanel.vue
new file mode 100644
index 0000000..15ea918
--- /dev/null
+++ b/web/src/views/analytics/LatencyPanel.vue
@@ -0,0 +1,160 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import type { LatencyPercentiles } from "../../api/types";
+import { formatLatency } from "./chart";
+
+const props = defineProps<{ latency: LatencyPercentiles }>();
+
+// Percentiles read as a shape, not five separate numbers: the gap between p50
+// and p99 is the story. Bars against a shared scale make that gap visible.
+const rows = computed(() => {
+ const l = props.latency;
+ return [
+ { key: "p50", label: "p50", value: l.p50, note: "Half of your mail is out faster than this" },
+ { key: "p75", label: "p75", value: l.p75, note: "" },
+ { key: "p90", label: "p90", value: l.p90, note: "" },
+ { key: "p99", label: "p99", value: l.p99, note: "The slow tail — one send in a hundred waits this long", tail: true },
+ ];
+});
+
+const scale = computed(() => Math.max(props.latency.p99, props.latency.avg, 0.001));
+
+const empty = computed(() => props.latency.p50 === 0 && props.latency.avg === 0);
+
+function width(value: number): string {
+ return `${Math.max((value / scale.value) * 100, value > 0 ? 2 : 0)}%`;
+}
+
+// A long tail relative to the median means a queue that occasionally stalls,
+// which is a different problem from being uniformly slow.
+const tailRatio = computed(() => (props.latency.p50 > 0 ? props.latency.p99 / props.latency.p50 : 0));
+</script>
+
+<template>
+ <div class="card">
+ <div class="card-header">
+ <h2>Time to deliver</h2>
+ <div class="summary">
+ <template v-if="!empty">
+ <strong>{{ formatLatency(latency.avg) }}</strong> average
+ </template>
+ </div>
+ </div>
+
+ <div class="card-body">
+ <div v-if="empty" class="empty-state chart-empty">
+ <h3>No delivered mail</h3>
+ <p>Latency appears once emails complete delivery in this window.</p>
+ </div>
+
+ <template v-else>
+ <p class="lead">
+ How long each email took from accepted to delivered.
+ <template v-if="tailRatio >= 10">
+ The p99 is {{ tailRatio.toFixed(0) }}× the median, which points at a queue that
+ occasionally stalls rather than sending that is uniformly slow.
+ </template>
+ </p>
+
+ <ul class="rows">
+ <li v-for="r in rows" :key="r.key" class="row">
+ <span class="label">{{ r.label }}</span>
+ <div class="track">
+ <div class="fill" :class="{ tail: r.tail }" :style="{ width: width(r.value) }"></div>
+ </div>
+ <span class="value">{{ formatLatency(r.value) }}</span>
+ <span class="note">{{ r.note }}</span>
+ </li>
+ </ul>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.summary {
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.summary strong {
+ color: var(--text-secondary);
+ font-size: 13px;
+}
+
+.chart-empty {
+ padding: 36px 16px;
+}
+
+.lead {
+ margin: 0 0 16px;
+ font-size: 12px;
+ color: var(--text-tertiary);
+ line-height: 1.6;
+ max-width: 70ch;
+}
+
+.rows {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.row {
+ display: grid;
+ grid-template-columns: 34px minmax(80px, 1fr) 70px minmax(0, 1.3fr);
+ align-items: center;
+ gap: 12px;
+}
+
+.label {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-secondary);
+}
+
+.track {
+ height: 8px;
+ border-radius: 4px;
+ background: var(--bg-hover);
+ overflow: hidden;
+}
+
+.fill {
+ height: 100%;
+ border-radius: 4px;
+ background: var(--primary-500);
+}
+
+.fill.tail {
+ background: var(--warning-500);
+}
+
+.value {
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+ color: var(--text-primary);
+ text-align: right;
+}
+
+.note {
+ font-size: 12px;
+ color: var(--text-tertiary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+@media (max-width: 720px) {
+ .row {
+ grid-template-columns: 34px 1fr 70px;
+ }
+
+ .note {
+ display: none;
+ }
+}
+</style>
diff --git a/web/src/views/analytics/ProviderTable.vue b/web/src/views/analytics/ProviderTable.vue
new file mode 100644
index 0000000..613fcec
--- /dev/null
+++ b/web/src/views/analytics/ProviderTable.vue
@@ -0,0 +1,274 @@
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import type { ProviderBreakdownPoint } from "../../api/types";
+import { formatNumber } from "./chart";
+
+const props = defineProps<{ rows: ProviderBreakdownPoint[] }>();
+
+const PROVIDER_COLORS: Record<string, string> = {
+ Gmail: "#ea4335",
+ "Google Workspace": "#4285f4",
+ Outlook: "#0078d4",
+ Yahoo: "#6001d2",
+ "Apple iCloud": "#8e8e93",
+ Proton: "#6d4aff",
+ AOL: "#00bfff",
+ GMX: "#1c4587",
+ Zoho: "#f04e23",
+ Fastmail: "#2968a6",
+ Yandex: "#ffcc00",
+ China: "#c20000",
+ Other: "#9ca3af",
+};
+
+type SortKey = "total" | "delivery_rate" | "failed";
+const sortBy = ref<SortKey>("total");
+
+const total = computed(() => props.rows.reduce((sum, r) => sum + r.total, 0));
+
+const sorted = computed(() =>
+ [...props.rows].sort((a, b) => {
+ if (sortBy.value === "delivery_rate") {
+ // A provider with no attempts has no rate; keep those last rather than
+ // letting a 0% with zero volume top the table.
+ const av = a.sent + a.failed === 0 ? -1 : a.delivery_rate;
+ const bv = b.sent + b.failed === 0 ? -1 : b.delivery_rate;
+ return av - bv;
+ }
+ return b[sortBy.value] - a[sortBy.value];
+ })
+);
+
+// The provider that is actually hurting deliverability: enough volume to matter
+// and a rate below par. Naming it saves the reader scanning the table.
+const problem = computed(() => {
+ let found: ProviderBreakdownPoint | null = null;
+ for (const r of props.rows) {
+ const attempts = r.sent + r.failed;
+ if (attempts < 20 || r.delivery_rate >= 95) continue;
+ if (!found || r.failed > found.failed) found = r;
+ }
+ return found;
+});
+
+function color(name: string): string {
+ return PROVIDER_COLORS[name] ?? "#6366f1";
+}
+
+function share(value: number): number {
+ return total.value === 0 ? 0 : (value / total.value) * 100;
+}
+
+function rateClass(r: ProviderBreakdownPoint): string {
+ if (r.sent + r.failed === 0) return "";
+ if (r.delivery_rate < 75) return "rate-bad";
+ if (r.delivery_rate < 90) return "rate-warn";
+ return "rate-good";
+}
+</script>
+
+<template>
+ <div class="card">
+ <div class="card-header">
+ <h2>Mailbox providers</h2>
+ <div class="summary">
+ <strong>{{ formatNumber(total) }}</strong> recipients
+ <template v-if="problem">
+ <span class="dot">·</span>
+ <span class="warn">
+ {{ problem.provider }} at {{ problem.delivery_rate.toFixed(0) }}%
+ </span>
+ </template>
+ </div>
+ </div>
+
+ <div class="card-body">
+ <div v-if="rows.length === 0" class="empty-state chart-empty">
+ <h3>No recipient data</h3>
+ <p>Provider deliverability appears once mail goes to real mailboxes.</p>
+ </div>
+
+ <template v-else>
+ <p class="lead">
+ Where your mail went, and how each provider treated it. A rate well below the others
+ usually means a reputation problem with that provider specifically, not with your
+ sending overall.
+ </p>
+
+ <div class="sorts">
+ <span>Sort by</span>
+ <button
+ v-for="s in (['total', 'delivery_rate', 'failed'] as const)"
+ :key="s"
+ type="button"
+ class="sort"
+ :class="{ active: sortBy === s }"
+ @click="sortBy = s"
+ >
+ {{ s === "total" ? "Volume" : s === "delivery_rate" ? "Worst rate" : "Failures" }}
+ </button>
+ </div>
+
+ <div class="table-scroll">
+ <table>
+ <thead>
+ <tr>
+ <th>Provider</th>
+ <th>Share</th>
+ <th class="num">Delivered</th>
+ <th class="num">Failed</th>
+ <th class="num" title="Blocked before sending because every recipient was suppressed">Suppressed</th>
+ <th class="num">Rate</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="r in sorted" :key="r.provider">
+ <td>
+ <span class="dot-inline" :style="{ background: color(r.provider) }" aria-hidden="true"></span>
+ {{ r.provider }}
+ </td>
+ <td class="share-cell">
+ <div class="track">
+ <div class="fill" :style="{ width: share(r.total) + '%', background: color(r.provider) }"></div>
+ </div>
+ <span class="share-pct">{{ share(r.total).toFixed(1) }}%</span>
+ </td>
+ <td class="num">{{ r.sent.toLocaleString() }}</td>
+ <td class="num">{{ r.failed.toLocaleString() }}</td>
+ <td class="num">{{ r.suppressed.toLocaleString() }}</td>
+ <td class="num rate" :class="rateClass(r)">
+ {{ r.sent + r.failed > 0 ? r.delivery_rate.toFixed(1) + "%" : "—" }}
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.summary {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.summary strong {
+ color: var(--text-secondary);
+ font-size: 13px;
+}
+
+.dot {
+ opacity: 0.6;
+}
+
+.warn {
+ color: var(--warning-text);
+ font-weight: 500;
+}
+
+.chart-empty {
+ padding: 36px 16px;
+}
+
+.lead {
+ margin: 0 0 14px;
+ font-size: 12px;
+ color: var(--text-tertiary);
+ line-height: 1.6;
+ max-width: 70ch;
+}
+
+.sorts {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 12px;
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.sort {
+ border: 0;
+ background: none;
+ padding: 0;
+ font: inherit;
+ font-size: 12px;
+ color: var(--text-tertiary);
+ cursor: pointer;
+}
+
+.sort:hover {
+ color: var(--text-primary);
+}
+
+.sort.active {
+ color: var(--primary-600);
+ font-weight: 600;
+}
+
+.table-scroll {
+ overflow-x: auto;
+}
+
+.dot-inline {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ margin-right: 8px;
+}
+
+.num {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+
+.share-cell {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 170px;
+}
+
+.track {
+ flex: 1;
+ height: 6px;
+ border-radius: 3px;
+ background: var(--bg-hover);
+ overflow: hidden;
+}
+
+.fill {
+ height: 100%;
+ border-radius: 3px;
+}
+
+.share-pct {
+ min-width: 44px;
+ text-align: right;
+ font-size: 12px;
+ color: var(--text-tertiary);
+ font-variant-numeric: tabular-nums;
+}
+
+.rate {
+ font-weight: 600;
+}
+
+.rate-good {
+ color: var(--success-text);
+}
+
+.rate-warn {
+ color: var(--warning-text);
+}
+
+.rate-bad {
+ color: var(--danger-text);
+}
+</style>
diff --git a/web/src/views/analytics/StackedBars.vue b/web/src/views/analytics/StackedBars.vue
new file mode 100644
index 0000000..2b3fdf5
--- /dev/null
+++ b/web/src/views/analytics/StackedBars.vue
@@ -0,0 +1,196 @@
+<script setup lang="ts">
+import { computed, ref } from "vue";
+import { axisLabels, formatNumber, heightPct, niceMax, shortDate } from "./chart";
+
+// One stacked-bar chart shared by every trend on the page, so they scale, label
+// and behave identically. Series are given bottom-up: the first entry sits at the
+// base of the stack.
+export interface Series {
+ key: string;
+ label: string;
+ colorVar: string;
+}
+
+export interface BarPoint {
+ date: string;
+ values: Record<string, number>;
+}
+
+const props = defineProps<{
+ points: BarPoint[];
+ series: Series[];
+ chartLabel: string;
+}>();
+
+const hovered = ref<number | null>(null);
+
+const totals = computed(() =>
+ props.points.map((p) => props.series.reduce((sum, s) => sum + (p.values[s.key] ?? 0), 0))
+);
+
+const peak = computed(() => niceMax(totals.value));
+const showLabel = computed(() => axisLabels(props.points.length));
+
+// Rendered top-down so the first series ends up at the bottom of the stack.
+const stackOrder = computed(() => [...props.series].reverse());
+</script>
+
+<template>
+ <div class="chart" :aria-label="chartLabel" role="img">
+ <div class="axis" aria-hidden="true">
+ <span>{{ formatNumber(peak) }}</span>
+ <span>{{ formatNumber(Math.round(peak / 2)) }}</span>
+ <span>0</span>
+ </div>
+
+ <div class="plot">
+ <div class="grid" aria-hidden="true"><span></span><span></span><span></span></div>
+
+ <div class="bars">
+ <div
+ v-for="(p, idx) in points"
+ :key="p.date"
+ class="col"
+ :class="{ hovered: hovered === idx }"
+ @mouseenter="hovered = idx"
+ @mouseleave="hovered = null"
+ >
+ <div class="stack">
+ <div
+ v-for="s in stackOrder"
+ :key="s.key"
+ class="bar"
+ :style="{ height: heightPct(p.values[s.key] ?? 0, peak), background: `var(${s.colorVar})` }"
+ ></div>
+ </div>
+
+ <div v-if="hovered === idx" class="tip" role="tooltip">
+ <slot name="tip" :point="p" :index="idx" :total="totals[idx]" />
+ </div>
+
+ <div class="label">{{ showLabel(idx) ? shortDate(p.date) : "" }}</div>
+ </div>
+ </div>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.chart {
+ display: flex;
+ gap: 10px;
+}
+
+.axis {
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ height: 200px;
+ padding-bottom: 20px;
+ font-size: 11px;
+ color: var(--text-tertiary);
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+ min-width: 34px;
+}
+
+.plot {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+}
+
+.grid {
+ position: absolute;
+ inset: 0 0 20px 0;
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+ pointer-events: none;
+}
+
+.grid span {
+ height: 1px;
+ background: var(--border-secondary);
+ opacity: 0.7;
+}
+
+.bars {
+ position: relative;
+ display: flex;
+ align-items: flex-end;
+ gap: 3px;
+ height: 200px;
+}
+
+.col {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+}
+
+.stack {
+ display: flex;
+ flex-direction: column;
+ justify-content: flex-end;
+ height: calc(100% - 20px);
+ border-radius: 3px;
+ overflow: hidden;
+}
+
+.col.hovered .stack {
+ filter: brightness(1.08);
+}
+
+.bar {
+ width: 100%;
+ transition: height 0.2s ease;
+}
+
+.label {
+ height: 20px;
+ line-height: 20px;
+ font-size: 10px;
+ color: var(--text-tertiary);
+ text-align: center;
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.tip {
+ position: absolute;
+ bottom: calc(100% - 12px);
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 5;
+ display: flex;
+ flex-direction: column;
+ gap: 3px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ border: 1px solid var(--border-primary);
+ background: var(--bg-primary);
+ box-shadow: var(--shadow-lg);
+ font-size: 12px;
+ color: var(--text-secondary);
+ white-space: nowrap;
+ pointer-events: none;
+}
+
+.tip :deep(strong) {
+ color: var(--text-primary);
+ font-size: 12px;
+}
+
+.tip :deep(.key) {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+ margin-right: 6px;
+}
+</style>
diff --git a/web/src/views/analytics/StatusMix.vue b/web/src/views/analytics/StatusMix.vue
new file mode 100644
index 0000000..ae92119
--- /dev/null
+++ b/web/src/views/analytics/StatusMix.vue
@@ -0,0 +1,171 @@
+<script setup lang="ts">
+import { computed } from "vue";
+import type { StatusBreakdown } from "../../api/types";
+import { formatNumber } from "./chart";
+
+const props = defineProps<{ rows: StatusBreakdown[] }>();
+
+// What each status means in Posta, so the page explains itself rather than
+// assuming the reader knows the pipeline.
+const MEANING: Record<string, string> = {
+ sent: "Handed off to the receiving server",
+ failed: "The send did not succeed",
+ queued: "Waiting for a worker",
+ processing: "Being sent right now",
+ scheduled: "Held until its send time",
+ suppressed: "Blocked before sending by the suppression list",
+ pending: "Accepted, not yet queued",
+};
+
+const COLOR: Record<string, string> = {
+ sent: "var(--success-500)",
+ failed: "var(--danger-500)",
+ queued: "var(--primary-500)",
+ processing: "var(--warning-500)",
+ scheduled: "var(--primary-400)",
+ suppressed: "var(--text-tertiary)",
+ pending: "var(--warning-500)",
+};
+
+const total = computed(() => props.rows.reduce((sum, r) => sum + r.count, 0));
+
+// Largest first: the shape of the mix is the point, not alphabetical order.
+const sorted = computed(() => [...props.rows].sort((a, b) => b.count - a.count));
+
+function percent(count: number): number {
+ return total.value === 0 ? 0 : (count / total.value) * 100;
+}
+
+function color(status: string): string {
+ return COLOR[status] ?? "var(--text-tertiary)";
+}
+</script>
+
+<template>
+ <div class="card">
+ <div class="card-header">
+ <h2>Status mix</h2>
+ <div class="summary"><strong>{{ formatNumber(total) }}</strong> emails</div>
+ </div>
+
+ <div class="card-body">
+ <div v-if="total === 0" class="empty-state chart-empty">
+ <h3>No emails</h3>
+ <p>Nothing was sent in this window.</p>
+ </div>
+
+ <template v-else>
+ <div class="ribbon" role="img" aria-label="Share of emails by status">
+ <div
+ v-for="r in sorted"
+ :key="r.status"
+ class="ribbon-part"
+ :style="{ width: percent(r.count) + '%', background: color(r.status) }"
+ :title="`${r.status}: ${r.count}`"
+ ></div>
+ </div>
+
+ <ul class="rows">
+ <li v-for="r in sorted" :key="r.status" class="row">
+ <span class="dot" :style="{ background: color(r.status) }" aria-hidden="true"></span>
+ <span class="name">{{ r.status }}</span>
+ <span class="meaning">{{ MEANING[r.status] || "" }}</span>
+ <span class="count">{{ r.count.toLocaleString() }}</span>
+ <span class="pct">{{ percent(r.count).toFixed(1) }}%</span>
+ </li>
+ </ul>
+ </template>
+ </div>
+ </div>
+</template>
+
+<style scoped>
+.summary {
+ font-size: 12px;
+ color: var(--text-tertiary);
+}
+
+.summary strong {
+ color: var(--text-secondary);
+ font-size: 13px;
+}
+
+.chart-empty {
+ padding: 36px 16px;
+}
+
+.ribbon {
+ display: flex;
+ height: 10px;
+ border-radius: 5px;
+ overflow: hidden;
+ background: var(--bg-hover);
+}
+
+.ribbon-part {
+ height: 100%;
+ min-width: 2px;
+}
+
+.rows {
+ list-style: none;
+ margin: 16px 0 0;
+ padding: 0;
+}
+
+.row {
+ display: grid;
+ grid-template-columns: 10px 90px 1fr auto auto;
+ align-items: center;
+ gap: 10px;
+ padding: 9px 0;
+ border-bottom: 1px solid var(--border-secondary);
+ font-size: 13px;
+}
+
+.row:last-child {
+ border-bottom: 0;
+}
+
+.dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+}
+
+.name {
+ font-weight: 600;
+ color: var(--text-primary);
+ text-transform: capitalize;
+}
+
+.meaning {
+ font-size: 12px;
+ color: var(--text-tertiary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.count {
+ font-variant-numeric: tabular-nums;
+ color: var(--text-primary);
+}
+
+.pct {
+ min-width: 52px;
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+ color: var(--text-tertiary);
+}
+
+@media (max-width: 640px) {
+ .row {
+ grid-template-columns: 10px 1fr auto;
+ }
+
+ .meaning {
+ display: none;
+ }
+}
+</style>
diff --git a/web/src/views/analytics/chart.ts b/web/src/views/analytics/chart.ts
new file mode 100644
index 0000000..2ba6c3a
--- /dev/null
+++ b/web/src/views/analytics/chart.ts
@@ -0,0 +1,97 @@
+// Shared helpers for the analytics charts: a readable axis scale, compact
+// numbers, and date formatting. Kept out of the components so every chart on the
+// page rounds and labels the same way.
+
+const NICE_STEPS = [1, 1.25, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10];
+
+// niceMax rounds a peak up to a number a person would choose for an axis, so the
+// top gridline reads 250 rather than 237.
+export function niceMax(values: number[]): number {
+ const max = Math.max(0, ...values);
+ if (max === 0) return 0;
+ const magnitude = Math.pow(10, Math.floor(Math.log10(max)));
+ const ratio = max / magnitude;
+ const step = NICE_STEPS.find((n) => n >= ratio) ?? 10;
+ return Math.round(step * magnitude);
+}
+
+// heightPct keeps a non-zero value visible: a single send in a busy month would
+// otherwise round to an invisible sliver.
+export function heightPct(value: number, peak: number): string {
+ if (peak <= 0) return "0%";
+ const pct = (value / peak) * 100;
+ return `${value > 0 ? Math.max(pct, 1.5) : 0}%`;
+}
+
+export function formatNumber(n: number): string {
+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + "M";
+ if (n >= 10_000) return (n / 1_000).toFixed(1) + "K";
+ return n.toLocaleString();
+}
+
+export function formatPercent(n: number, digits = 1): string {
+ return `${n.toFixed(digits)}%`;
+}
+
+export function formatLatency(seconds: number): string {
+ if (seconds <= 0) return "—";
+ if (seconds < 1) return `${Math.round(seconds * 1000)}ms`;
+ if (seconds < 60) return `${seconds.toFixed(1)}s`;
+ if (seconds < 3600) return `${(seconds / 60).toFixed(1)}m`;
+ return `${(seconds / 3600).toFixed(1)}h`;
+}
+
+// Dates arrive as YYYY-MM-DD. Parsing them bare would be read as UTC midnight and
+// shift a day backwards for anyone west of Greenwich, so anchor them locally.
+function localDate(dateStr: string): Date {
+ return new Date(dateStr.length === 10 ? `${dateStr}T00:00:00` : dateStr);
+}
+
+export function shortDate(dateStr: string): string {
+ return localDate(dateStr).toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
+export function longDate(dateStr: string): string {
+ return localDate(dateStr).toLocaleDateString(undefined, {
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ });
+}
+
+// Thin the axis so labels never collide: always keep the ends, then take an even
+// stride through the middle.
+export function axisLabels(count: number, target = 7): (index: number) => boolean {
+ const stride = Math.max(1, Math.ceil(count / target));
+ return (index: number) => index === 0 || index === count - 1 || index % stride === 0;
+}
+
+export function isoDay(d: Date): string {
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
+}
+
+// Delta between a period and the one before it. Returns null when there is no
+// prior figure to compare against, so the UI can say nothing rather than "+100%".
+export function delta(current: number, previous: number): number | null {
+ if (previous === 0) return current === 0 ? 0 : null;
+ return ((current - previous) / previous) * 100;
+}
+
+// dayCount is inclusive of both ends, matching how the ranges are presented:
+// "7 days" covers today and the six before it.
+export function dayCount(from: string, to: string): number {
+ const start = new Date(`${from}T00:00:00`);
+ const end = new Date(`${to}T00:00:00`);
+ return Math.max(1, Math.round((end.getTime() - start.getTime()) / 86_400_000) + 1);
+}
+
+// precedingWindow is the equally long window ending the day before this one, so
+// a period-over-period comparison is like for like and the two never overlap.
+export function precedingWindow(from: string, to: string): { from: string; to: string } {
+ const days = dayCount(from, to);
+ const priorEnd = new Date(`${from}T00:00:00`);
+ priorEnd.setDate(priorEnd.getDate() - 1);
+ const priorStart = new Date(priorEnd);
+ priorStart.setDate(priorStart.getDate() - (days - 1));
+ return { from: isoDay(priorStart), to: isoDay(priorEnd) };
+}