reports

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0

Documentation

Overview

Package reports builds the campaign report (spec 7.7, honest analytics 5.5) from campaign_counters, its exports and read-only report links, whose public page shows the same aggregate numbers and nothing else.

Index

Constants

View Source
const BacklogAfter = 5 * time.Minute

BacklogAfter is how old the oldest unprocessed provider event must be before the report says part of it is behind.

View Source
const FinalAfter = 72 * time.Hour

FinalAfter is how long after a send ends opens and clicks keep counting before the report calls its results final.

View Source
const HotShare = 20.0

HotShare is the share of clicks (percent) from which a link's bubble is red.

View Source
const LinkThreshold = 5.0

LinkThreshold is the share of clicks (percent) under which a link is grouped as "Other" on the click map.

View Source
const MaxActiveLinks = 10

MaxActiveLinks caps the read-only links a campaign can have at once.

View Source
const Significance = 0.05

Significance is the threshold below which a difference counts as real.

Variables

This section is empty.

Functions

func Register

func Register(h huma.API, s *Service)

Register adds the report operations.

func ZTest

func ZTest(x1, n1, x2, n2 int64) (lift, z, p float64, ok bool)

ZTest is a two-proportion z-test of x1/n1 against x2/n2. It returns the difference p2 - p1 in percentage points, z and the two-sided p-value. ok is false when either sample is empty or the pooled proportion is 0 or 1 (no variance, nothing to test).

Types

type CampaignReport

type CampaignReport struct {
	Campaign     ReportCampaignInfo   `json:"campaign"`
	Headline     ReportHeadline       `json:"headline"`
	Engagement   ReportEngagement     `json:"engagement"`
	ClickMap     ReportClickMap       `json:"clickMap"`
	Mailboxes    []ReportMailboxRow   `json:"mailboxes"`
	Providers    ReportProviderTable  `json:"providers"`
	Bounces      ReportBounceTable    `json:"bounces"`
	Unsubscribes ReportUnsubscribes   `json:"unsubscribes"`
	ABTest       *ReportABTest        `json:"abTest,omitempty"`
	Backlog      *ReportIngestBacklog `json:"backlog,omitempty"`
	// NotSent is set for campaigns that haven't sent anything yet.
	NotSent *ReportNotSent `json:"notSent,omitempty"`
}

CampaignReport is the campaign report (spec 7.7, honest analytics 5.5). It only ever holds aggregate numbers: no contact address or other personal data, so the same document serves the read-only shared link.

type ExportInput

type ExportInput struct {
	// Format: csv returns the file; pdf records the export of the printable
	// report, which the browser saves as a PDF.
	Format string `json:"format" enum:"csv,pdf"`
}

ExportInput asks for an export of the report.

type Limiter

type Limiter struct {
	// Requests per Window per address.
	Requests int
	// Misses (unknown or revoked links) per MissWindow per address.
	Misses     int
	Window     time.Duration
	MissWindow time.Duration
	// contains filtered or unexported fields
}

Limiter is a fixed-window rate limiter per client address for the public report endpoint: a cap on requests, and a much lower cap on lookups of links that don't exist, so guessing tokens is pointless.

func NewLimiter

func NewLimiter() *Limiter

NewLimiter returns the default limits: 60 requests a minute and 20 unknown links per 10 minutes per address.

func (*Limiter) Allow

func (l *Limiter) Allow(key string, now time.Time) bool

Allow counts a request from key and reports whether it may proceed: it is refused over the request cap, or when the address already looked up too many unknown links.

func (*Limiter) Miss

func (l *Limiter) Miss(key string, now time.Time)

Miss records a lookup of an unknown, revoked or expired link.

type ReportABTest

type ReportABTest struct {
	Kind  string `json:"kind" enum:"subject,content,send_time"`
	Label string `json:"label" doc:"subject line, content, send time"`
	// Metric is human_opens or clicks; machine opens never count.
	Metric      string     `json:"metric" enum:"human_opens,clicks"`
	WindowHours float64    `json:"windowHours"`
	DecidedAt   *time.Time `json:"decidedAt,omitempty"`
	// State: decided (a winner went out), testing (the window is open) or
	// no_winner (the window closed without a significant difference).
	State    string            `json:"state" enum:"decided,testing,no_winner"`
	Winner   string            `json:"winner,omitempty"`
	Variants []ReportABVariant `json:"variants"`
	// Lift is the leader's advantage on the metric, in percentage points.
	Lift *float64 `json:"lift,omitempty"`
	// PValue of the two-sided z-test; Confidence is 1 - p, in percent.
	PValue      *float64 `json:"pValue,omitempty"`
	Confidence  *float64 `json:"confidence,omitempty"`
	Significant bool     `json:"significant" doc:"p below 0.05"`
	// Remaining recipients who got the winner, and when.
	Remaining int64      `json:"remaining"`
	RolloutAt *time.Time `json:"rolloutAt,omitempty"`
}

ReportABTest is "A/B test" with the confidence of the result: a two-proportion z-test on the decision metric at the end of the test window.

type ReportABVariant

type ReportABVariant struct {
	Key   string `json:"key"`
	Label string `json:"label" doc:"The subject line, or what differs"`
	// Recipients of the test sample.
	Recipients    int64    `json:"recipients"`
	SamplePercent float64  `json:"samplePercent"`
	HumanOpenRate *float64 `json:"humanOpenRate,omitempty"`
	ClickRate     *float64 `json:"clickRate,omitempty"`
	ComplaintRate *float64 `json:"complaintRate,omitempty"`
	Winner        bool     `json:"winner"`
	// Remaining is how many recipients got the winner after the test.
	Remaining int64 `json:"remaining"`
}

type ReportBacklogProvider

type ReportBacklogProvider struct {
	ProviderID string    `json:"providerId"`
	Name       string    `json:"name"`
	Short      string    `json:"short"`
	Feed       string    `json:"feed" doc:"How its events arrive: SNS, webhook, bounce mailbox"`
	Waiting    int64     `json:"waiting"`
	Since      time.Time `json:"since"`
}

ReportBacklogProvider is one provider whose events haven't been processed.

type ReportBounceDiagnostic

type ReportBounceDiagnostic struct {
	Provider   string `json:"provider"`
	Type       string `json:"type"`
	Code       string `json:"code"`
	Diagnostic string `json:"diagnostic"`
	Count      int64  `json:"count"`
}

ReportBounceDiagnostic is one provider message behind a bounce type.

type ReportBounceReview

type ReportBounceReview struct {
	Type         string                   `json:"type"`
	Label        string                   `json:"label"`
	Count        int64                    `json:"count"`
	Unsuppressed int64                    `json:"unsuppressed"`
	Diagnostics  []ReportBounceDiagnostic `json:"diagnostics"`
}

ReportBounceReview is the Review dialog of a bounce type.

type ReportBounceRow

type ReportBounceRow struct {
	Type  string            `json:"type" enum:"unknown_user,domain_invalid,mailbox_full,deferral_expired,blocked,other"`
	Label string            `json:"label"`
	Tone  string            `json:"tone" enum:"bad,warn,neutral"`
	Count int64             `json:"count"`
	Codes []ReportCodeCount `json:"codes"`
	// Suppression: auto (every address was suppressed when it bounced),
	// retry (soft bounces are retried next send), add (addresses aren't
	// suppressed; a person can add them), review (look at the diagnostics
	// first), suppressed (all of them are on the list now).
	Suppression string `json:"suppression" enum:"auto,retry,add,review,suppressed"`
	// Unsuppressed is how many bounced addresses aren't on the list.
	Unsuppressed int64 `json:"unsuppressed"`
}

ReportBounceRow is one type of the shared bounce taxonomy.

type ReportBounceTable

type ReportBounceTable struct {
	Total int64             `json:"total"`
	Rows  []ReportBounceRow `json:"rows"`
}

ReportBounceTable is "Bounces by type".

type ReportCampaignInfo

type ReportCampaignInfo struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Status string `json:"status" enum:"draft,approval,approved,scheduled,sending,paused,sent,cancelled,failed"`
	// Audience is a readable label ("All subscribers", "Weekly Digest").
	Audience    string     `json:"audience"`
	ScheduledAt *time.Time `json:"scheduledAt,omitempty"`
	StartedAt   *time.Time `json:"startedAt,omitempty"`
	CompletedAt *time.Time `json:"completedAt,omitempty"`
	// Timezone of the schedule, when one was set.
	Timezone string `json:"timezone,omitempty"`
	// Origin is the importer source for history pulled in by migration ("brevo").
	Origin string `json:"origin,omitempty"`
	// Final is true once 72 hours have passed since the send ended; until
	// then opens and clicks are still coming in.
	Final bool `json:"final"`
	// FinalAt is when the results become final (72 h after the send ended).
	FinalAt *time.Time `json:"finalAt,omitempty"`
	// Notes: "A/B subject, winner B", "first send after Brevo migration".
	Notes []string `json:"notes"`
}

ReportCampaignInfo is the header of the report.

type ReportCampaignRef

type ReportCampaignRef struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

ReportCampaignRef points to another campaign.

type ReportClickMap

type ReportClickMap struct {
	// HTML is the campaign's email as sent (rendered in a sandboxed frame).
	HTML string `json:"html"`
	// Available is false when the stored content is missing; the links
	// are still listed.
	Available bool             `json:"available"`
	Total     int64            `json:"total" doc:"All link clicks"`
	Links     []ReportLink     `json:"links"`
	Threshold float64          `json:"threshold" doc:"Links under this share (percent) are grouped as Other"`
	Other     *ReportLinkGroup `json:"other,omitempty"`
}

ReportClickMap is the click map: the email as sent and the clicks per link.

type ReportCodeCount

type ReportCodeCount struct {
	Provider string `json:"provider" doc:"Short name: SES, Postal"`
	Type     string `json:"type" doc:"The provider's event name: Permanent/General, HardFail"`
	Code     string `json:"code" doc:"SMTP reply or provider code: 550 5.1.1"`
	Count    int64  `json:"count"`
}

ReportCodeCount is one provider's original code within a bounce type.

func (ReportCodeCount) CodeText

func (c ReportCodeCount) CodeText() string

CodeText is "SES Permanent/General 550 5.1.1".

type ReportEngagement

type ReportEngagement struct {
	// Available is false when there is no hourly data (imported history).
	Available bool                    `json:"available"`
	Points    []ReportEngagementPoint `json:"points"`
	// Hours of data so far (72 once final).
	Hours int `json:"hours"`
	// Delivered is the base the chart's percentages use.
	Delivered int64 `json:"delivered"`
	// HumanWithin6h is the share of the 72-hour human opens that came in
	// the first 6 hours (percent).
	HumanWithin6h *float64       `json:"humanWithin6h,omitempty"`
	Rollout       *ReportRollout `json:"rollout,omitempty"`
}

ReportEngagement is "Engagement over the first 72 hours": cumulative counts per hour, as shares of delivered on the chart.

type ReportEngagementPoint

type ReportEngagementPoint struct {
	Hour         int   `json:"hour"`
	HumanOpens   int64 `json:"humanOpens"`
	MachineOpens int64 `json:"machineOpens"`
	Clicks       int64 `json:"clicks"`
}

ReportEngagementPoint is the cumulative engagement at an hour after the send.

type ReportExport

type ReportExport struct {
	Filename string
	Body     []byte
}

ReportExport is a file to download.

type ReportHeadline

type ReportHeadline struct {
	Sent            int64                 `json:"sent"`
	SentBy          []ReportProviderCount `json:"sentBy"`
	Delivered       int64                 `json:"delivered"`
	DeliveredRate   *float64              `json:"deliveredRate,omitempty"`
	HumanOpens      int64                 `json:"humanOpens"`
	HumanOpenRate   *float64              `json:"humanOpenRate,omitempty"`
	MachineOpens    int64                 `json:"machineOpens"`
	MachineOpenRate *float64              `json:"machineOpenRate,omitempty"`
	Clicks          int64                 `json:"clicks"`
	ClickRate       *float64              `json:"clickRate,omitempty"`
	ClickToOpen     *float64              `json:"clickToOpen,omitempty"`
	Unsubscribes    int64                 `json:"unsubscribes"`
	UnsubscribeRate *float64              `json:"unsubscribeRate,omitempty"`
	Complaints      int64                 `json:"complaints"`
	ComplaintRate   *float64              `json:"complaintRate,omitempty"`
	Bounces         int64                 `json:"bounces"`
	HardBounces     int64                 `json:"hardBounces"`
	SoftBounces     int64                 `json:"softBounces"`
	BounceRate      *float64              `json:"bounceRate,omitempty"`
	Rejected        int64                 `json:"rejected"`
	// Undelivered were neither delivered nor bounced: deferrals that expired
	// once the send is final, mail still in flight before that.
	Undelivered int64 `json:"undelivered"`
}

ReportHeadline holds the headline tiles. Rates are percentages: delivered and bounces of sent; opens, clicks, unsubscribes and complaints of delivered; click-to-open of human opens.

type ReportIngestBacklog

type ReportIngestBacklog struct {
	Since     time.Time               `json:"since"`
	Minutes   int                     `json:"minutes"`
	Providers []ReportBacklogProvider `json:"providers"`
	// Current names the other providers, whose events are up to date.
	Current []string `json:"current"`
}

ReportIngestBacklog says that part of the report is behind: provider events wait to be processed, so counts they feed are as of Since.

type ReportLink struct {
	ID           string `json:"id"`
	URL          string `json:"url"`
	Label        string `json:"label"`
	Position     int    `json:"position"`
	Clicks       int64  `json:"clicks"`
	UniqueClicks int64  `json:"uniqueClicks"`
	// Share of all link clicks, percent.
	Share float64 `json:"share"`
	// Grouped links fall under "Other" on the map (under the threshold).
	Grouped bool `json:"grouped"`
	// Hot marks the most-clicked links (drawn in red).
	Hot bool `json:"hot"`
}

ReportLink is one tracked link of the email.

type ReportLinkGroup

type ReportLinkGroup struct {
	Share  float64  `json:"share"`
	Links  int      `json:"links"`
	Clicks int64    `json:"clicks"`
	Labels []string `json:"labels" doc:"The most-clicked links in the group, for the caption"`
}

ReportLinkGroup is "Other": the links under the threshold, as one bubble.

type ReportMailboxRow

type ReportMailboxRow struct {
	Key  string `json:"key" enum:"gmail,outlook,yahoo,icloud,other"`
	Name string `json:"name"`
	ReportRates
}

ReportMailboxRow is one mailbox provider (where recipients read it).

type ReportNotSent

type ReportNotSent struct {
	Status      string     `json:"status"`
	ScheduledAt *time.Time `json:"scheduledAt,omitempty"`
	Timezone    string     `json:"timezone,omitempty"`
	Readiness   string     `json:"readiness,omitempty" enum:"ready,warnings,blocked,"`
	// LastReport is the most recent campaign with results.
	LastReport *ReportCampaignRef `json:"lastReport,omitempty"`
}

ReportNotSent is the empty state of a campaign without results.

type ReportPath

type ReportPath struct {
	api.WorkspaceInput
	CampaignID string `path:"campaignId" format:"uuid" doc:"Campaign id"`
}

ReportPath names a campaign of the workspace.

type ReportProviderColumn

type ReportProviderColumn struct {
	ProviderID string `json:"providerId"`
	Name       string `json:"name"`
	Short      string `json:"short"`
	Adapter    string `json:"adapter"`
	Color      string `json:"color" enum:"ses,postal,postmark,other"`
	ReportRates
	// Percent of the planned send routed here.
	Percent float64 `json:"percent"`
	// MedianDeliveryMs is the median time from handing a message over to its
	// delivery event.
	MedianDeliveryMs *int `json:"medianDeliveryMs,omitempty"`
	// Cost in dollars; absent when unknown (history imported from another
	// platform, which ReputeCast didn't pay for).
	Cost *float64 `json:"cost,omitempty" doc:"Dollars"`
	// WarmupDay is the warm-up day the provider was on at the send.
	WarmupDay *int `json:"warmupDay,omitempty"`
	// EngagedFirst is true when the warm-up sent to the most engaged contacts only.
	EngagedFirst bool `json:"engagedFirst"`
}

ReportProviderColumn is one sending provider in the side-by-side table.

type ReportProviderCount

type ReportProviderCount struct {
	ProviderID string `json:"providerId"`
	Short      string `json:"short"`
	Count      int64  `json:"count"`
}

ReportProviderCount is one sending provider's part of a count ("SES 43,182").

type ReportProviderTable

type ReportProviderTable struct {
	Columns []ReportProviderColumn `json:"columns"`
	// Split is true when more than one provider delivered the send.
	Split bool `json:"split"`
}

ReportProviderTable is "Results per sending provider".

type ReportRates

type ReportRates struct {
	Sent            int64    `json:"sent"`
	Delivered       int64    `json:"delivered"`
	DeliveredRate   *float64 `json:"deliveredRate,omitempty"`
	HumanOpenRate   *float64 `json:"humanOpenRate,omitempty"`
	MachineOpenRate *float64 `json:"machineOpenRate,omitempty"`
	ClickRate       *float64 `json:"clickRate,omitempty"`
	BounceRate      *float64 `json:"bounceRate,omitempty"`
	ComplaintRate   *float64 `json:"complaintRate,omitempty"`
	UnsubscribeRate *float64 `json:"unsubscribeRate,omitempty"`
}

ReportRates are a slice of the send's results. Rates as in ReportHeadline.

type ReportRollout

type ReportRollout struct {
	Variant string    `json:"variant"`
	At      time.Time `json:"at"`
	// Hour after the send started.
	Hour float64 `json:"hour"`
}

ReportRollout is the winning A/B variant going out to everyone else.

type ReportShareLink struct {
	ID string `json:"id"`
	// URL is the public link, shown to members who may share reports.
	URL           string     `json:"url"`
	CreatedAt     time.Time  `json:"createdAt"`
	CreatedByName string     `json:"createdByName"`
	ExpiresAt     *time.Time `json:"expiresAt,omitempty"`
	Views         int64      `json:"views"`
	LastViewedAt  *time.Time `json:"lastViewedAt,omitempty"`
}

ReportShareLink is an active read-only link.

type ReportShareList

type ReportShareList struct {
	Items []ReportShareLink `json:"items"`
}

ReportShareList lists a campaign's active links.

type ReportSuppressResult

type ReportSuppressResult struct {
	Added   int `json:"added"`
	Already int `json:"already" doc:"Already on the list"`
}

ReportSuppressResult says how many bounced addresses were suppressed.

type ReportUnsubscribeReason

type ReportUnsubscribeReason struct {
	Key   string  `json:"key" enum:"too_frequent,not_relevant,none,never_signed_up,spam,other"`
	Label string  `json:"label"`
	Count int64   `json:"count"`
	Share float64 `json:"share" doc:"Share of unsubscribes, percent"`
	Tone  string  `json:"tone" enum:"ink,muted,bad"`
}

ReportUnsubscribeReason is one answer on the unsubscribe page.

type ReportUnsubscribes

type ReportUnsubscribes struct {
	Total   int64                     `json:"total"`
	Reasons []ReportUnsubscribeReason `json:"reasons"`
	// ChoseFewer chose "fewer emails" instead of leaving.
	ChoseFewer int64 `json:"choseFewer"`
}

ReportUnsubscribes is "Unsubscribe reasons".

type Service

type Service struct {
	Pool     *pgxpool.Pool
	Q        *store.Queries
	Audit    *audit.Logger
	Box      *secrets.Box
	URLs     publicurl.Builder
	Suppress Suppressor
	// Limits protects the public report endpoint; nil uses defaults.
	Limits *Limiter
	Now    func() time.Time
}

func (*Service) BounceReview

func (s *Service) BounceReview(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID, typeKey string) (ReportBounceReview, error)

BounceReview returns what the providers said for one bounce type, without any address, so a person can decide whether to suppress them.

func (*Service) CreateShare

func (s *Service) CreateShare(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID, in ShareInput) (ReportShareLink, error)

CreateShare makes a read-only link to a campaign's report.

func (*Service) Export

func (s *Service) Export(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID, format string) (ReportExport, error)

Export writes the report as CSV (one section per table) or records a PDF export. Every export is in the audit log.

func (*Service) Report

func (s *Service) Report(ctx context.Context, ws *store.Workspace, id uuid.UUID) (CampaignReport, error)

func (*Service) RevokeShare

func (s *Service) RevokeShare(ctx context.Context, ws *store.Workspace, campaignID, shareID uuid.UUID) error

RevokeShare stops a read-only link from working.

func (*Service) Shared

func (s *Service) Shared(ctx context.Context, token, client string) (SharedCampaignReport, error)

Shared returns the report behind a read-only link, for anyone holding it. client identifies the caller for the rate limits (the client address).

func (*Service) Shares

func (s *Service) Shares(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID) (ReportShareList, error)

Shares lists a campaign's active read-only links.

func (*Service) SuppressBounces

func (s *Service) SuppressBounces(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID, typeKey string) (ReportSuppressResult, error)

SuppressBounces adds the bounced addresses of one type that aren't on the shared suppression list yet, through the suppression service (which writes the audit entry and tells every provider).

type ShareInput

type ShareInput struct {
	// ExpiresInDays makes the link stop working after that many days; 0 or
	// absent keeps it until it is revoked.
	ExpiresInDays int `json:"expiresInDays,omitempty" minimum:"0" maximum:"365" doc:"0 keeps the link until it is revoked"`
}

ShareInput creates a read-only link.

type SharedCampaignReport

type SharedCampaignReport struct {
	Workspace string         `json:"workspace"`
	ExpiresAt *time.Time     `json:"expiresAt,omitempty"`
	Report    CampaignReport `json:"report"`
}

SharedCampaignReport is what a read-only link shows: the report of one campaign and the workspace it belongs to, nothing else.

type Suppressor

type Suppressor interface {
	AddSuppressions(ctx context.Context, ws *store.Workspace, emails []string, note string) (added, already int, err error)
}

Suppressor adds addresses to the shared suppression list (the audience domain's suppression service), writing its own audit entry.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL