audience

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: 36 Imported by: 0

Documentation

Overview

Package audience implements the Audience screens (spec 5.6, 7.9): contacts with saved views and bulk actions, contact profiles with consent history and an activity timeline, lists and custom fields, engagement tiers and the sunset policy, list health, audited CSV export and the shared suppression list.

Index

Constants

View Source
const (
	SourceSubscribePage   = "subscribe_page"
	SourceConfirmLink     = "confirm_link"
	SourcePreferences     = "preference_center"
	SourceUnsubscribePage = "unsubscribe_page"
	SourceOneClick        = "one_click"
)

Consent sources written by the public pages. Form signups use "form:<form slug>" (segments.SourceLabel reads it as "Signup form · …").

View Source
const MaxBulkIDs = 10000

MaxBulkIDs bounds an explicit selection; larger actions use a filter.

View Source
const RestoreDays = 30

RestoreDays is how long a deleted list can be restored.

View Source
const TierRunHour = 3

TierRunHour is the local hour after which the nightly tier run happens.

Variables

View Source
var ErrContactGone = errors.New("audience: contact not found")

ErrContactGone is returned when a link points at a contact that was erased or belongs to another workspace.

View Source
var Frequencies = []string{"all", "weekly", "monthly"}

Frequencies offered in the preference center.

Functions

func ConsentName

func ConsentName(c string) string

ConsentName is how a consent state reads in the UI.

func CountryName

func CountryName(code string) string

CountryName returns the name of a country code, or the code itself.

func MailClient

func MailClient(ua string) string

MailClient names the mail client behind an open's user agent.

func MailboxLabel

func MailboxLabel(provider, detail string) string

MailboxLabel is "Outlook" or "Other · Google Workspace".

func Register

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

Register adds the audience operations.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service, log *slog.Logger)

RegisterJobs adds the tier worker and its hourly schedule.

func TierFor

func TierFor(p SunsetPolicy, lastHumanOpen, lastOpen, lastClick *time.Time, created, now time.Time) string

TierFor assigns a tier in Go, the same way the nightly SQL does, for contacts created between runs (imports).

func TierName

func TierName(t string) string

TierName is how a tier reads in the UI.

Types

type AddSuppressionsInput

type AddSuppressionsInput struct {
	Emails []string `json:"emails" minItems:"1" maxItems:"1000"`
	Note   string   `json:"note,omitempty" maxLength:"300" doc:"Why, shown as the original code"`
}

AddSuppressionsInput adds addresses by hand.

type AudienceIDInput

type AudienceIDInput struct {
	api.WorkspaceInput
	ID string `path:"id" format:"uuid"`
}

type AudienceListInput

type AudienceListInput struct {
	Name        string `json:"name" minLength:"1" maxLength:"100"`
	Description string `json:"description,omitempty" maxLength:"500"`
	DoubleOptIn *bool  `json:"doubleOptIn,omitempty" doc:"New signups confirm by email first (default true)"`
}

AudienceListInput creates or renames a list.

type AudienceListSummary

type AudienceListSummary struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	DoubleOptIn bool   `json:"doubleOptIn"`
	// Subscribed members (the list size); pending members wait for opt-in.
	Subscribed int64     `json:"subscribed"`
	Pending    int64     `json:"pending"`
	CreatedAt  time.Time `json:"createdAt"`
}

AudienceListSummary is a list with its size.

type AudienceSummary

type AudienceSummary struct {
	Contacts        int64                 `json:"contacts"`
	Segments        int64                 `json:"segments"`
	Suppressions    int64                 `json:"suppressions"`
	Tiers           AudienceTierCounts    `json:"tiers"`
	TiersComputedAt *time.Time            `json:"tiersComputedAt,omitempty"`
	Lists           []AudienceListSummary `json:"lists"`
}

AudienceSummary feeds the Audience tab counts and the filter selects.

type AudienceTierCounts

type AudienceTierCounts struct {
	Active  int64 `json:"active"`
	Cooling int64 `json:"cooling"`
	AtRisk  int64 `json:"atRisk"`
	Sunset  int64 `json:"sunset"`
}

AudienceTierCounts are contacts per engagement tier.

type Box

type Box interface {
	Open(ciphertext []byte, ad string) ([]byte, error)
}

Box decrypts provider credentials for pulls.

type ConfirmResult

type ConfirmResult struct {
	ContactID uuid.UUID
	Email     string
	FirstName string
	// Confirmed lists moved from pending to subscribed now.
	Confirmed []uuid.UUID
	// Already means nothing was pending: the link was clicked before.
	Already bool
	// Blocked means the address is suppressed (bounce, complaint…).
	Blocked bool
}

ConfirmResult is the outcome of a confirmation click.

type ContactActivityItem

type ContactActivityItem struct {
	ID       string    `json:"id"`
	Category string    `json:"category" enum:"delivery,engagement,consent"`
	Type     string    `json:"type" doc:"delivered, soft_bounce, open, click… or a consent action"`
	At       time.Time `json:"at"`
	// Subject is the email: "Weekly Digest #141", "Welcome series · step 2".
	Subject  string                   `json:"subject"`
	Variant  string                   `json:"variant,omitempty"`
	Provider *ContactActivityProvider `json:"provider,omitempty"`
	// Imported names the tool that sent the email before the migration ("Brevo").
	Imported   string `json:"imported,omitempty"`
	Failover   bool   `json:"failover"`
	Code       string `json:"code,omitempty" doc:"Provider code: 250 2.6.0, 452 4.2.2"`
	Diagnostic string `json:"diagnostic,omitempty"`
	RouteNote  string `json:"routeNote,omitempty"`
	Machine    bool   `json:"machine"`
	// Client is the mail client of an open ("Outlook on Windows").
	Client             string     `json:"client,omitempty"`
	AfterDeliveryMin   *int64     `json:"afterDeliveryMin,omitempty"`
	RetriedDeliveredAt *time.Time `json:"retriedDeliveredAt,omitempty"`
	URL                string     `json:"url,omitempty"`
	LinkLabel          string     `json:"linkLabel,omitempty"`
	// Consent events.
	List           string `json:"list,omitempty"`
	Source         string `json:"source,omitempty"`
	SourceLabel    string `json:"sourceLabel,omitempty"`
	Detail         string `json:"detail,omitempty"`
	Note           string `json:"note,omitempty"`
	IP             string `json:"ip,omitempty"`
	Actor          string `json:"actor,omitempty"`
	ConsentVersion string `json:"consentVersion,omitempty"`
}

ContactActivityItem is one timeline event: a delivery (with the sending provider that handled it), an engagement or a consent change.

type ContactActivityPage

type ContactActivityPage struct {
	Items      []ContactActivityItem `json:"items"`
	Total      int64                 `json:"total" doc:"Events matching the filter"`
	NextCursor string                `json:"nextCursor,omitempty"`
}

ContactActivityPage is one page of the timeline, newest first.

type ContactActivityProvider

type ContactActivityProvider struct {
	Name    string `json:"name"`
	Adapter string `json:"adapter"`
}

ContactActivityProvider is the sending provider that delivered an email.

type ContactBulkFailure

type ContactBulkFailure struct {
	Email  string `json:"email"`
	Reason string `json:"reason"`
}

ContactBulkFailure is one contact the action couldn't apply to.

type ContactBulkInput

type ContactBulkInput struct {
	Selection
	Action string `json:"action" enum:"add_to_list,add_tag,resend_optin,suppress"`
	ListID string `json:"listId,omitempty" doc:"For add_to_list"`
	Tag    string `json:"tag,omitempty" maxLength:"60" doc:"For add_tag"`
	Reason string `json:"reason,omitempty" maxLength:"300" doc:"For suppress"`
}

type ContactBulkResult

type ContactBulkResult struct {
	Action   string               `json:"action"`
	Matched  int64                `json:"matched"`
	Done     int64                `json:"done"`
	Failed   int64                `json:"failed"`
	Failures []ContactBulkFailure `json:"failures" doc:"Up to 20 examples"`
	// Target names the list or tag ("Re-permission").
	Target string `json:"target,omitempty"`
	Note   string `json:"note,omitempty"`
}

ContactBulkResult reports a bulk action ("Added 2,116 of 2,118 contacts to 'Re-permission'; 2 failed").

type ContactConsentEvent

type ContactConsentEvent struct {
	Action         string    `json:"action"`
	Source         string    `json:"source"`
	SourceLabel    string    `json:"sourceLabel"`
	Detail         string    `json:"detail"`
	Note           string    `json:"note"`
	IP             string    `json:"ip,omitempty"`
	Actor          string    `json:"actor,omitempty"`
	ConsentVersion string    `json:"consentVersion,omitempty"`
	At             time.Time `json:"at"`
}

ContactConsentEvent is one consent event of a list.

type ContactEraseInput

type ContactEraseInput struct {
	Selection
	Confirm int64 `json:"confirm" doc:"The number of contacts, typed to confirm"`
}

ContactEraseInput erases contacts' personal data.

type ContactExportInput

type ContactExportInput struct {
	Selection
}

ContactExportInput selects the contacts to export.

type ContactFilter

type ContactFilter struct {
	Q       string `json:"q,omitempty" maxLength:"200" doc:"Email, name or tag"`
	List    string `json:"list,omitempty" doc:"List id"`
	Tier    string `json:"tier,omitempty" enum:"active,cooling,at_risk,sunset"`
	Mailbox string `json:"mailbox,omitempty" enum:"gmail,outlook,yahoo,icloud,other"`
	Consent string `json:"consent,omitempty" enum:"double,single,pending"`
	Source  string `json:"source,omitempty" maxLength:"80"`
	Tag     string `json:"tag,omitempty" maxLength:"80"`
	Segment string `json:"segment,omitempty" doc:"Segment id"`
	// JoinedAfter is a date (2026-09-01).
	JoinedAfter string `json:"joinedAfter,omitempty" maxLength:"10"`
}

ContactFilter narrows the contacts table. Saved views store it as JSON; list, export and bulk actions accept it.

func (ContactFilter) Empty

func (f ContactFilter) Empty() bool

Empty reports whether the filter matches everyone.

type ContactList

type ContactList struct {
	Items    []ContactListItem `json:"items"`
	Total    int64             `json:"total"`
	Page     int               `json:"page"`
	PageSize int               `json:"pageSize"`
}

ContactList is one page of contacts.

type ContactListConsent

type ContactListConsent struct {
	ListID      string                `json:"listId"`
	Name        string                `json:"name"`
	Status      string                `json:"status" enum:"subscribed,pending,unsubscribed,none"`
	DoubleOptIn bool                  `json:"doubleOptIn"`
	Events      []ContactConsentEvent `json:"events"`
}

ContactListConsent is the consent state and history of one list.

type ContactListItem

type ContactListItem struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
	// Lists the contact is on (subscribed or waiting for opt-in), in list order.
	Lists           []string   `json:"lists"`
	Tier            string     `json:"tier" enum:"active,cooling,at_risk,sunset"`
	Consent         string     `json:"consent" enum:"double,single,pending"`
	MailboxProvider string     `json:"mailboxProvider"`
	MailboxLabel    string     `json:"mailboxLabel" doc:"Outlook, or Other · Google Workspace"`
	LastOpenAt      *time.Time `json:"lastOpenAt,omitempty"`
	LastOpenMachine bool       `json:"lastOpenMachine" doc:"The last open was a machine open (Apple Mail Privacy Protection)"`
	JoinedAt        time.Time  `json:"joinedAt"`
	Source          string     `json:"source"`
	SourceLabel     string     `json:"sourceLabel"`
	Suppressed      bool       `json:"suppressed"`
}

ContactListItem is one row of the contacts table.

type ContactPathInput

type ContactPathInput struct {
	api.WorkspaceInput
	Contact string `path:"contact" format:"uuid"`
}

type ContactProfile

type ContactProfile struct {
	ID              string                     `json:"id"`
	Email           string                     `json:"email"`
	FirstName       string                     `json:"firstName"`
	LastName        string                     `json:"lastName"`
	Name            string                     `json:"name"`
	Tier            string                     `json:"tier" enum:"active,cooling,at_risk,sunset"`
	Consent         string                     `json:"consent" enum:"double,single,pending"`
	MailboxProvider string                     `json:"mailboxProvider"`
	MailboxLabel    string                     `json:"mailboxLabel"`
	JoinedAt        time.Time                  `json:"joinedAt"`
	Source          string                     `json:"source"`
	SourceLabel     string                     `json:"sourceLabel"`
	RoleAddress     bool                       `json:"roleAddress"`
	Suppression     *ContactProfileSuppression `json:"suppression,omitempty"`
	Stats           ContactProfileStats        `json:"stats"`
	Fields          []ContactProfileField      `json:"fields"`
	Tags            []string                   `json:"tags"`
	Lists           []ContactListConsent       `json:"lists"`
	Preferences     ContactProfilePreferences  `json:"preferences"`
	ActivityTotal   int64                      `json:"activityTotal"`
}

ContactProfile is the contact profile screen.

type ContactProfileField

type ContactProfileField struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Value string `json:"value"`
	// Custom fields show their key and type ("mrr custom · number").
	Custom  bool   `json:"custom"`
	Type    string `json:"type" enum:"text,number,date,boolean,select,builtin"`
	Display string `json:"display" enum:",currency"`
}

ContactProfileField is one row of the Fields card.

type ContactProfilePreferences

type ContactProfilePreferences struct {
	Frequency   string     `json:"frequency" enum:"all,weekly,monthly"`
	PausedUntil *time.Time `json:"pausedUntil,omitempty"`
	FewerEmails bool       `json:"fewerEmails"`
}

ContactProfilePreferences is what the subscriber chose in the preference center.

type ContactProfileStats

type ContactProfileStats struct {
	Emails90d  int64 `json:"emails90d"`
	HumanOpens int64 `json:"humanOpens" doc:"Emails opened by a person"`
	// HumanOpenRate is in percent of emails.
	HumanOpenRate   *float64   `json:"humanOpenRate,omitempty"`
	Clicks          int64      `json:"clicks"`
	LastOpenAt      *time.Time `json:"lastOpenAt,omitempty"`
	LastOpenMachine bool       `json:"lastOpenMachine"`
}

ContactProfileStats is the headline row of the profile (last 90 days).

type ContactProfileSuppression

type ContactProfileSuppression struct {
	ID     string    `json:"id"`
	Reason string    `json:"reason"`
	Scope  string    `json:"scope" enum:"all,marketing"`
	At     time.Time `json:"at"`
}

ContactProfileSuppression says the address is on the suppression list.

type ContactSavedView

type ContactSavedView struct {
	ID      string        `json:"id"`
	Name    string        `json:"name"`
	Filters ContactFilter `json:"filters"`
	Count   int64         `json:"count"`
	// Shared views are visible to everyone in the workspace.
	Shared bool `json:"shared"`
}

ContactSavedView is a chip above the contacts table.

type ContactSavedViews

type ContactSavedViews struct {
	All   int64              `json:"all"`
	Items []ContactSavedView `json:"items"`
}

ContactSavedViews is the views row: "All contacts" plus the saved views.

type ContactSuppressInput

type ContactSuppressInput struct {
	Reason string `json:"reason" minLength:"1" maxLength:"300" doc:"Why, for the audit log and the list"`
}

ContactSuppressInput adds a contact to the suppression list by hand.

type ContactUpdate

type ContactUpdate struct {
	FirstName *string        `json:"firstName,omitempty" maxLength:"100"`
	LastName  *string        `json:"lastName,omitempty" maxLength:"100"`
	Company   *string        `json:"company,omitempty" maxLength:"200"`
	Country   *string        `json:"country,omitempty" maxLength:"2"`
	Timezone  *string        `json:"timezone,omitempty" maxLength:"64"`
	Language  *string        `json:"language,omitempty" maxLength:"16"`
	Fields    map[string]any `json:"fields,omitempty" doc:"Custom field key → value; null clears it"`
	Tags      []string       `json:"tags,omitempty" maxItems:"50"`
}

ContactUpdate changes fields and tags. Omitted fields stay as they are; a custom field set to null is cleared.

type ContactViewInput

type ContactViewInput struct {
	Name    string        `json:"name" minLength:"1" maxLength:"80"`
	Filters ContactFilter `json:"filters"`
	// Personal views are only visible to their creator.
	Personal bool `json:"personal,omitempty"`
}

ContactViewInput saves the current filters as a view.

type CustomFieldDef

type CustomFieldDef struct {
	ID        string    `json:"id"`
	Key       string    `json:"key"`
	Label     string    `json:"label"`
	Type      string    `json:"type" enum:"text,number,date,boolean,select"`
	Options   []string  `json:"options"`
	Display   string    `json:"display" enum:",currency"`
	CreatedAt time.Time `json:"createdAt"`
}

type CustomFieldInput

type CustomFieldInput struct {
	Key     string   `json:"key,omitempty" maxLength:"63" doc:"Lowercase letters, digits and _; fixed after creation"`
	Label   string   `json:"label" minLength:"1" maxLength:"80"`
	Type    string   `json:"type,omitempty" enum:"text,number,date,boolean,select"`
	Options []string `json:"options,omitempty" maxItems:"100"`
	Display string   `json:"display,omitempty" enum:",currency"`
}

CustomFieldInput creates or changes a custom field.

type CustomFieldList

type CustomFieldList struct {
	Items []CustomFieldDef `json:"items"`
}

CustomFieldList is the custom fields of a workspace.

type FieldError

type FieldError struct {
	Field   string
	Message string
}

FieldError is a value the contact must correct, worded for them.

func (*FieldError) Error

func (e *FieldError) Error() string

type File

type File struct {
	ContentType        string `header:"Content-Type"`
	ContentDisposition string `header:"Content-Disposition"`
	CacheControl       string `header:"Cache-Control"`
	Body               []byte
}

File is a download (CSV or JSON).

type HealthTierCard

type HealthTierCard struct {
	Tier  string  `json:"tier" enum:"active,cooling,at_risk,sunset"`
	Count int64   `json:"count"`
	Pct   float64 `json:"pct" doc:"Share of all contacts, percent"`
	// DeltaPts is the change in share vs about 30 days ago, in points.
	DeltaPts *float64 `json:"deltaPts,omitempty"`
	// Good says whether the change is good news (more Active, less Sunset).
	Good bool `json:"good"`
}

HealthTierCard is one of the four tier cards.

type HealthTrendWeek

type HealthTrendWeek struct {
	// Day is the workspace-local calendar day of the snapshot (today for the
	// newest column).
	Day     string  `json:"day" format:"date"`
	Active  float64 `json:"active"`
	Cooling float64 `json:"cooling"`
	AtRisk  float64 `json:"atRisk"`
	Sunset  float64 `json:"sunset"`
}

HealthTrendWeek is one column of the tier trend: shares of the list (0–1).

type Items

type Items[T any] struct {
	Items []T `json:"items"`
}

Items wraps a list response.

type ListHealth

type ListHealth struct {
	ComputedAt *time.Time        `json:"computedAt,omitempty"`
	Total      int64             `json:"total"`
	Tiers      []HealthTierCard  `json:"tiers"`
	Trend      []HealthTrendWeek `json:"trend"`
	PolicyWeek int               `json:"policyWeek" doc:"Index of the trend column when the policy started, -1 if none"`
	Policy     SunsetPolicy      `json:"policy"`
	// ReengageFlowID is the automation the policy names, when it exists.
	ReengageFlowID *uuid.UUID `json:"reengageFlowId,omitempty"`
	// WinBackRate is the share of re-engaged contacts who came back, percent.
	WinBackRate *float64           `json:"winBackRate,omitempty"`
	ThisWeek    SunsetThisWeek     `json:"thisWeek"`
	Rows        []ListHealthRow    `json:"rows"`
	Insight     *ListHealthInsight `json:"insight,omitempty"`
}

ListHealth is the List health screen.

type ListHealthInsight

type ListHealthInsight struct {
	Text string `json:"text"`
}

ListHealthInsight is the sentence under the per-list table.

type ListHealthRow

type ListHealthRow struct {
	Kind     string             `json:"kind" enum:"list,view"`
	ID       string             `json:"id"`
	Name     string             `json:"name"`
	Contacts int64              `json:"contacts"`
	Tiers    AudienceTierCounts `json:"tiers"`
	// NetGrowth is joins minus departures over 30 days.
	NetGrowth int64 `json:"netGrowth"`
	// Rates over 30 days, in percent; nil when nothing was sent.
	HumanOpens    *float64 `json:"humanOpens,omitempty"`
	UnsubRate     *float64 `json:"unsubRate,omitempty"`
	ComplaintRate *float64 `json:"complaintRate,omitempty"`
	BounceRate    *float64 `json:"bounceRate,omitempty"`
	// ComplaintHigh flags complaint rates at or above 0.1%.
	ComplaintHigh bool   `json:"complaintHigh"`
	Health        string `json:"health" doc:"Excellent, Good, Needs attention, Re-permission needed"`
	HealthTone    string `json:"healthTone" enum:"ok,warn,bad"`
}

ListHealthRow is one row of "Health per list": a list or a followed view.

type ListImpact

type ListImpact struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Members are the list's subscribers. Elsewhere of them are subscribed
	// to another list and stay subscribed there; the rest become contacts
	// without a subscription.
	Members   int64 `json:"members"`
	Elsewhere int64 `json:"elsewhere"`
	// OtherLists are the other lists those subscribers are on, most shared
	// first (up to three); OtherListCount counts them all.
	OtherLists     []string `json:"otherLists"`
	OtherListCount int      `json:"otherListCount"`
	// Forms, Automations and Campaigns are what deleting the list pauses.
	Forms       []ListImpactItem `json:"forms"`
	Automations []ListImpactItem `json:"automations"`
	Campaigns   []ListImpactItem `json:"campaigns"`
}

ListImpact is what deleting a list affects.

type ListImpactItem

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

ListImpactItem is a form, automation or campaign that uses a list.

type ListRestore

type ListRestore struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// Forms and Automations are live again; Campaigns are back on their
	// schedule.
	Forms       []string `json:"forms"`
	Automations []string `json:"automations"`
	Campaigns   []string `json:"campaigns"`
	// Left were paused by the delete but changed since, or their send time
	// passed: they stay as they are.
	Left []string `json:"left"`
}

ListRestore is what restoring a list turned back on.

type NewContact

type NewContact struct {
	Email     string   `json:"email" minLength:"3" maxLength:"254"`
	FirstName string   `json:"firstName,omitempty" maxLength:"100"`
	LastName  string   `json:"lastName,omitempty" maxLength:"100"`
	Lists     []string `json:"lists" maxItems:"50" doc:"List ids"`
	// Consent: single adds them as subscribed now; double sends a
	// confirmation email and keeps them pending until they click it.
	Consent string   `json:"consent" enum:"single,double"`
	Tags    []string `json:"tags,omitempty" maxItems:"50"`
}

NewContact is the "Add contact" dialog.

type NewContactResult

type NewContactResult struct {
	ID string `json:"id"`
	// ConfirmationSent is true when a double opt-in email went out.
	ConfirmationSent bool   `json:"confirmationSent"`
	ConfirmURL       string `json:"confirmUrl,omitempty" doc:"Shown when no System provider could send the confirmation"`
}

type OptInResendResult

type OptInResendResult struct {
	Sent       bool   `json:"sent"`
	ConfirmURL string `json:"confirmUrl,omitempty"`
}

OptInResendResult is the outcome of resending the opt-in email.

type PreferenceLinkResult

type PreferenceLinkResult struct {
	URL string `json:"url"`
}

PreferenceLinkResult is a link to open.

type PreferencesInput

type PreferencesInput struct {
	// Shown are the lists the page offered; Subscribed the ones left checked.
	Shown      []uuid.UUID
	Subscribed []uuid.UUID
	// Frequency is all, weekly or monthly; empty keeps it.
	Frequency string
	// PauseDays pauses every list for 30 or 90 days; 0 resumes; -1 keeps it.
	PauseDays int
	// FirstName changes the first name when set.
	FirstName *string
}

PreferencesInput is a preference center submission.

type PreferencesResult

type PreferencesResult struct {
	Joined      []uuid.UUID
	Left        []uuid.UUID
	Frequency   string
	PausedUntil *time.Time
	Changed     bool
}

PreferencesResult lists what changed.

type PublicConfirmation

type PublicConfirmation struct {
	At time.Time
	IP *netip.Addr
}

PublicConfirmation is when and from where a contact last confirmed.

type PublicContact

type PublicContact struct {
	ID        uuid.UUID
	Email     string
	FirstName string
	Status    string
	Consent   string
	// Lists maps list ids to the membership status (subscribed, pending, unsubscribed).
	Lists       map[uuid.UUID]string
	Frequency   string
	PausedUntil *time.Time
	Confirmed   *PublicConfirmation
	// LastName and Attributes personalize "view online".
	LastName   string
	Attributes map[string]any
}

PublicContact is what the public pages show about the contact a link was signed for.

func SamplePublicContact

func SamplePublicContact(lists []PublicList) PublicContact

SamplePublicContact is the example subscriber of previews in a workspace without contacts: on every public list.

func (PublicContact) Subscribed

func (p PublicContact) Subscribed(l uuid.UUID) bool

Subscribed reports whether the contact gets list l.

type PublicContactName

type PublicContactName struct {
	Email     string
	FirstName string
}

PublicContactName is a contact's address and first name.

type PublicEvidence

type PublicEvidence struct {
	// Source names the page or form ("form:newsletter-signup", "one_click").
	Source    string
	IP        *netip.Addr
	UserAgent string
	// ConsentText is the exact sentence the contact agreed to; ConsentVersion
	// is its version ("v3").
	ConsentText    string
	ConsentVersion string
	// Note goes on the consent events.
	Note string
	At   time.Time
}

PublicEvidence is what the contact did and from where.

type PublicList

type PublicList struct {
	ID          uuid.UUID
	Name        string
	Description string
	// Public lists are offered in the preference center by default.
	Public     bool
	Subscribed int64
}

PublicList is a list a public page can offer.

type RemoveSuppressionInput

type RemoveSuppressionInput struct {
	Reason string `json:"reason" minLength:"3" maxLength:"300"`
}

RemoveSuppressionInput asks for a reason, which goes to the audit log.

type Selection

type Selection struct {
	IDs []string `json:"ids,omitempty" maxItems:"10000"`
	// AllMatching applies the action to every contact matching Filter.
	AllMatching bool          `json:"allMatching,omitempty"`
	Filter      ContactFilter `json:"filter,omitempty"`
}

Selection is either explicit contact ids or every contact matching a filter.

type Service

type Service struct {
	Pool     *pgxpool.Pool
	Q        *store.Queries
	Audit    *audit.Logger
	Segments *segments.Service
	// Mail sends opt-in confirmations through the System stream.
	Mail  mailer.Sender
	Links *linktoken.Signer
	URLs  publicurl.Builder
	Now   func() time.Time
}

func (*Service) Activity

func (s *Service) Activity(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, filter, cursor string, limit int) (ContactActivityPage, error)

Activity returns a contact's timeline. filter is all, deliveries, engagement or consent.

func (*Service) AddSuppressions

AddSuppressions adds addresses to the shared suppression list by hand.

func (*Service) Bulk

Bulk applies an action to a selection of contacts.

func (*Service) Confirm

func (s *Service) Confirm(ctx context.Context, tx pgx.Tx, ws *store.Workspace, contactID uuid.UUID, ev PublicEvidence) (ConfirmResult, error)

Confirm completes double opt-in for every pending list of a contact inside tx. The consent text the contact agreed to at signup is copied onto the confirmation, so each confirmed list carries its own evidence.

func (*Service) CreateContact

func (s *Service) CreateContact(ctx context.Context, ws *store.Workspace, in NewContact) (NewContactResult, error)

CreateContact adds one contact from the app.

func (*Service) CreateField

func (s *Service) CreateField(ctx context.Context, ws *store.Workspace, in CustomFieldInput) (CustomFieldDef, error)

func (*Service) CreateList

func (*Service) CreateView

func (*Service) DeleteField

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

DeleteField removes a field and its values from every contact.

func (*Service) DeleteList

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

DeleteList deletes a list. Its live signup forms and the live automations it starts pause, and scheduled campaigns sending to it come off the schedule (back to approved when their approval stands, otherwise draft). Contacts, their other lists and suppressions stay. It can be restored for RestoreDays days.

func (*Service) DeleteView

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

func (*Service) Erase

Erase removes personal data of the selected contacts: names, fields, tags, list memberships, consent history and preferences go; the address is replaced. Suppressions stay, so an erased address is never mailed again.

func (*Service) Export

func (s *Service) Export(ctx context.Context, ws *store.Workspace, in ContactExportInput) ([]byte, int, error)

Export writes the selected contacts as CSV: built-in columns, lists and every custom field. Every export is logged with its size and filter.

func (*Service) ExportContact

func (s *Service) ExportContact(ctx context.Context, ws *store.Workspace, id uuid.UUID) ([]byte, string, error)

ExportContact returns a JSON document with all data about one contact. The export is logged.

func (*Service) ExportSuppressions

func (s *Service) ExportSuppressions(ctx context.Context, ws *store.Workspace) ([]byte, int, error)

ExportSuppressions writes the whole list as CSV. Every export is logged.

func (*Service) Fields

func (s *Service) Fields(ctx context.Context, ws *store.Workspace) (CustomFieldList, error)

func (*Service) FindPublicContact

func (s *Service) FindPublicContact(ctx context.Context, q *store.Queries, ws *store.Workspace, email string) (uuid.UUID, bool, error)

FindPublicContact returns the contact behind an address, for "email me a link to my preferences". ok is false for unknown or erased addresses.

func (*Service) Health

func (s *Service) Health(ctx context.Context, ws *store.Workspace) (ListHealth, error)

Health returns tiers, the 12-week trend, the policy and health per list.

func (*Service) ListContacts

func (s *Service) ListContacts(ctx context.Context, ws *store.Workspace, f ContactFilter, page, pageSize int) (ContactList, error)

ListContacts returns one page, most recent activity first.

func (*Service) ListImpact

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

ListImpact reports what deleting a list would affect.

func (*Service) ListSuppressions

func (s *Service) ListSuppressions(ctx context.Context, ws *store.Workspace, f SuppressionFilter, page, pageSize int) (SuppressionList, error)

ListSuppressions returns one page of the shared suppression list. Rows that came in with an import are grouped unless the person searches or opens the group.

func (*Service) LoadPublicContact

func (s *Service) LoadPublicContact(ctx context.Context, q *store.Queries, ws *store.Workspace, contactID uuid.UUID) (PublicContact, error)

LoadPublicContact reads a contact for a public page. Erased contacts and contacts of other workspaces are ErrContactGone.

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

PreferenceLink returns the preference center link of a contact ("Open preference center as Sam"). The link is logged.

func (*Service) PreviewContact

func (s *Service) PreviewContact(ctx context.Context, q *store.Queries, ws *store.Workspace, email string) (uuid.UUID, bool, error)

PreviewContact picks the subscriber the app previews the public pages for: the address asked for, else whoever confirmed a subscription last, else the newest active contact. ok is false for a workspace without contacts.

func (*Service) Profile

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

Profile returns everything the profile screen shows.

func (*Service) PublicContactNames

func (s *Service) PublicContactNames(ctx context.Context, q *store.Queries, ws *store.Workspace, ids []uuid.UUID) (map[uuid.UUID]PublicContactName, error)

PublicContactNames returns the addresses and first names of some contacts of ws (erased contacts and other workspaces' are left out), for lists of signups such as the confirmations waiting to be sent.

func (*Service) PublicLists

func (s *Service) PublicLists(ctx context.Context, q *store.Queries, ws *store.Workspace) ([]PublicList, error)

PublicLists returns the workspace's lists with their size, oldest first.

func (*Service) PullFromProviders

func (s *Service) PullFromProviders(ctx context.Context, ws *store.Workspace, box Box) (SuppressionPullResult, error)

PullFromProviders reads each connected provider's own suppression list (adapters that implement providers.SuppressionSyncer) and adds what the shared list doesn't have yet. Regular two-way sync is the providers domain's job; this is the one-off pull offered by the importer and the suppression list.

func (*Service) RecomputeTiers

func (s *Service) RecomputeTiers(ctx context.Context, wsID uuid.UUID) (TierRun, error)

RecomputeTiers assigns tiers from engagement under the workspace's policy, applies the sunset policy (tag for the re-engagement flow, stop Broadcasts, optional erasure), writes the daily rollups behind List health and refreshes segment counts.

func (*Service) RecordOptInSent

func (s *Service) RecordOptInSent(ctx context.Context, q *store.Queries, contactID uuid.UUID, lists []uuid.UUID, ev PublicEvidence) error

RecordOptInSent notes that the confirmation email went out (or was sent again as a reminder) for the contact's pending lists.

func (*Service) RemoveSuppression

func (s *Service) RemoveSuppression(ctx context.Context, ws *store.Workspace, id uuid.UUID, in RemoveSuppressionInput) error

RemoveSuppression takes one address off the list. Addresses that bounced or complained can only be mailed again after a new opt-in, so their contact goes back to pending.

func (*Service) ResendOptIn

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

ResendOptIn sends the confirmation email again and records it.

func (*Service) RestoreList

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

RestoreList brings back a list deleted in the last RestoreDays days with its memberships, and turns back on what deleting it paused, unless that changed since: forms and automations go live again, campaigns go back on their schedule when their send time hasn't passed.

func (*Service) Resubscribe

func (s *Service) Resubscribe(ctx context.Context, tx pgx.Tx, ws *store.Workspace, contactID uuid.UUID, ev PublicEvidence) ([]uuid.UUID, error)

Resubscribe undoes the latest unsubscribe from the confirmation page ("Changed your mind?"): the lists it left come back and the suppression it added is lifted, inside tx.

func (*Service) SavePolicy

func (s *Service) SavePolicy(ctx context.Context, ws *store.Workspace, p SunsetPolicy) (SunsetPolicy, error)

SavePolicy stores the sunset policy. Tiers change at the next nightly run.

func (*Service) SavePreferences

func (s *Service) SavePreferences(ctx context.Context, tx pgx.Tx, ws *store.Workspace, contactID uuid.UUID, in PreferencesInput, ev PublicEvidence) (PreferencesResult, error)

SavePreferences applies a preference center submission inside tx. The signed link proves the contact reads this mailbox, so joining a list here needs no further confirmation, even after an unsubscribe.

func (*Service) SendConfirmations

func (s *Service) SendConfirmations(ctx context.Context, ws *store.Workspace, ids []uuid.UUID) (int, error)

SendConfirmations emails the double opt-in link to contacts waiting for re-permission (imports). It returns how many went out; without a System provider nothing is sent and the contacts stay pending.

func (*Service) Signup

func (s *Service) Signup(ctx context.Context, tx pgx.Tx, ws *store.Workspace, in SignupInput) (SignupResult, error)

Signup adds or updates a contact from a public form inside tx. A new contact gets the form's fields; an existing contact only gets the fields it left empty, because anyone can type anyone's address into a form. A contact who unsubscribed before must confirm by email even when the form is single opt-in.

func (*Service) Summary

func (s *Service) Summary(ctx context.Context, ws *store.Workspace) (AudienceSummary, error)

Summary returns the counts shown in the Audience header.

func (*Service) SuppressContact

func (s *Service) SuppressContact(ctx context.Context, ws *store.Workspace, id uuid.UUID, in ContactSuppressInput) error

SuppressContact puts a contact's address on the shared suppression list.

func (*Service) Unsubscribe

func (s *Service) Unsubscribe(ctx context.Context, tx pgx.Tx, ws *store.Workspace, contactID uuid.UUID, campaignID *uuid.UUID, ev PublicEvidence) (UnsubscribeResult, error)

Unsubscribe removes the contact from every list and suppresses Broadcasts and Automations to the address (System mail still goes through), inside tx. campaignID names the email the link came from, if any.

func (*Service) UpdateContact

func (s *Service) UpdateContact(ctx context.Context, ws *store.Workspace, id uuid.UUID, in ContactUpdate) (ContactProfile, error)

UpdateContact changes a contact's fields and tags.

func (*Service) UpdateField

func (s *Service) UpdateField(ctx context.Context, ws *store.Workspace, id uuid.UUID, in CustomFieldInput) (CustomFieldDef, error)

UpdateField changes a field's label, options or display. Its key and type are fixed: changing them would change what stored values mean.

func (*Service) UpdateList

UpdateList renames a list or changes its opt-in setting.

func (*Service) UploadSuppressions

func (s *Service) UploadSuppressions(ctx context.Context, ws *store.Workspace, body []byte, fileName, reason, note string) (SuppressionUploadResult, error)

UploadSuppressions reads addresses from a CSV (an "email" column, or the first column) and adds them with the given reason.

func (*Service) Views

Views returns the saved views with their counts, counted in one scan.

type SignupInput

type SignupInput struct {
	Email     string
	FirstName string
	LastName  string
	Company   string
	// Fields are custom field values by key, checked against their type.
	Fields map[string]string
	// Lists to join; each must belong to the workspace.
	Lists []uuid.UUID
	// DoubleOptIn keeps the memberships pending until the confirmation link
	// is clicked.
	DoubleOptIn bool
	Evidence    PublicEvidence
}

SignupInput is a subscription request from a form or the hosted page.

type SignupResult

type SignupResult struct {
	ContactID uuid.UUID
	Email     string
	FirstName string
	Created   bool
	// Pending lists wait for the confirmation click (double opt-in, or a
	// returning contact who had unsubscribed).
	Pending []uuid.UUID
	// Subscribed lists were joined now (single opt-in).
	Subscribed []uuid.UUID
	// Already lists the contact was subscribed to before.
	Already []uuid.UUID
	// Blocked means the address is suppressed for a reason other than an
	// unsubscribe (hard bounce, complaint, spam trap…): nothing changed and
	// no email may go out.
	Blocked bool
}

SignupResult says what happened. Public pages show the same message in every case, so a form never reveals who is already subscribed.

func (SignupResult) NeedsConfirmation

func (r SignupResult) NeedsConfirmation() bool

NeedsConfirmation reports whether a confirmation email should go out.

type SunsetPolicy

type SunsetPolicy struct {
	Enabled bool `json:"enabled"`
	// EnabledAt is the day the policy was switched on (2026-09-01).
	EnabledAt string `json:"enabledAt,omitempty"`
	// ActiveDays: Active until this many days without an open (30).
	ActiveDays int `json:"activeDays" minimum:"1" maximum:"3650"`
	// AtRiskDays: At risk from this many days (91); Cooling is in between.
	AtRiskDays int `json:"atRiskDays" minimum:"2" maximum:"3650"`
	// SunsetDays: Sunset from this many days (181).
	SunsetDays int `json:"sunsetDays" minimum:"3" maximum:"3650"`
	// CountMachineOpens counts Apple Mail prefetches as engagement.
	CountMachineOpens bool `json:"countMachineOpens"`
	// Reengage sends one re-engagement email when a contact enters Sunset
	// (the contact is tagged "sunset"; the automation starts on that tag).
	Reengage           bool   `json:"reengage"`
	ReengageAutomation string `json:"reengageAutomation,omitempty" doc:"Name of the automation that sends it"`
	// StopBroadcasts stops Broadcasts StopAfterDays after entering Sunset if
	// there's still no open. Automations and System mail continue.
	StopBroadcasts bool `json:"stopBroadcasts"`
	StopAfterDays  int  `json:"stopAfterDays" minimum:"1" maximum:"365"`
	// DeleteAfter erases contacts after DeleteAfterMonths in Sunset.
	DeleteAfter       bool `json:"deleteAfter"`
	DeleteAfterMonths int  `json:"deleteAfterMonths" minimum:"1" maximum:"120"`
}

SunsetPolicy decides the engagement tiers and what happens to contacts who stop opening (List health › Sunset policy).

func ParsePolicy

func ParsePolicy(raw json.RawMessage) SunsetPolicy

ParsePolicy reads a workspace's stored policy, filling defaults.

func (SunsetPolicy) Validate

func (p SunsetPolicy) Validate() error

Validate checks that the tier thresholds are in order.

type SunsetThisWeek

type SunsetThisWeek struct {
	Entering int64 `json:"entering" doc:"Contacts entering Sunset"`
	// EnterDay names the day most of them enter, when most fall on one day.
	EnterDay string `json:"enterDay,omitempty"`
	Stopping int64  `json:"stopping" doc:"Contacts whose Broadcasts stop"`
	StopDay  string `json:"stopDay,omitempty"`
}

SunsetThisWeek projects the sunset policy over the next 7 days.

type SuppressionAddResult

type SuppressionAddResult struct {
	Added   int      `json:"added"`
	Already int      `json:"already" doc:"Already on the list"`
	Invalid []string `json:"invalid" doc:"Values that aren't addresses"`
}

SuppressionAddResult reports how many addresses were added.

type SuppressionCountsView

type SuppressionCountsView struct {
	Total       int64 `json:"total"`
	HardBounce  int64 `json:"hardBounce"`
	Complaint   int64 `json:"complaint"`
	Unsubscribe int64 `json:"unsubscribe"`
	Manual      int64 `json:"manual"`
	Other       int64 `json:"other"`
}

SuppressionCountsView is the stat row above the list.

type SuppressionFilter

type SuppressionFilter struct {
	Q      string
	Reason string
	Source string // provider:<id>, import:<id>, manual, preference_center, one_click, api, bounce_mailbox
	Since  string // 7d, 30d
	Import string // show the rows of one import group
}

SuppressionFilter narrows the list.

type SuppressionFilterOption

type SuppressionFilterOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

SuppressionFilterOption is a value of a filter select.

type SuppressionItem

type SuppressionItem struct {
	ID string `json:"id"`
	// Address is masked (r.w···@outlook.com) except role addresses; for an
	// import group it's the source file name.
	Address string `json:"address"`
	Group   bool   `json:"group"`
	// Rows in an import group.
	Rows     int64             `json:"rows"`
	ImportID string            `json:"importId,omitempty"`
	Reasons  []string          `json:"reasons"`
	Source   SuppressionSource `json:"source"`
	// OriginalCode is the provider's code ("550 5.1.1 user unknown") or a note.
	OriginalCode string    `json:"originalCode"`
	At           time.Time `json:"at"`
	// Context is the campaign or flow ("Welcome series · step 1") or a note
	// ("Migration"); empty when there is none.
	Context    string `json:"context"`
	CampaignID string `json:"campaignId,omitempty"`
	Scope      string `json:"scope" enum:"all,marketing"`
}

SuppressionItem is one row of the suppression list, or a group of rows that came in with one import.

type SuppressionList

type SuppressionList struct {
	Items    []SuppressionItem         `json:"items"`
	Total    int64                     `json:"total" doc:"Rows matching, groups counted once"`
	Matching int64                     `json:"matching" doc:"Addresses matching the filter"`
	Page     int                       `json:"page"`
	PageSize int                       `json:"pageSize"`
	Counts   SuppressionCountsView     `json:"counts"`
	Sync     []SuppressionProviderSync `json:"sync"`
	Sources  []SuppressionFilterOption `json:"sources"`
}

SuppressionList is one page of the suppression list.

type SuppressionProviderSync

type SuppressionProviderSync struct {
	ProviderID string     `json:"providerId"`
	Name       string     `json:"name"`
	Adapter    string     `json:"adapter"`
	Status     string     `json:"status" enum:"in_sync,syncing,error,off"`
	At         *time.Time `json:"at,omitempty"`
	Pulled     int64      `json:"pulled"`
	Pushed     int64      `json:"pushed"`
	// Local is set for providers without a suppression API: nothing is
	// pushed; the shared list is checked before mail is handed to them.
	Local bool `json:"local"`
	// PulledNote explains what "pulled" covers for this provider.
	PulledNote string `json:"pulledNote"`
	Detail     string `json:"detail"`
}

SuppressionProviderSync is a sending provider's suppression sync state (kept by the providers domain; shown here).

type SuppressionPullProvider

type SuppressionPullProvider struct {
	Name    string `json:"name"`
	Pulled  int    `json:"pulled"`
	Added   int    `json:"added"`
	Skipped string `json:"skipped,omitempty" doc:"Why nothing was pulled"`
}

SuppressionPullProvider is one provider's part of a pull.

type SuppressionPullResult

type SuppressionPullResult struct {
	Providers []SuppressionPullProvider `json:"providers"`
	Added     int                       `json:"added"`
}

SuppressionPullResult reports suppressions pulled from sending providers.

type SuppressionSource

type SuppressionSource struct {
	// Kind: provider, preference_center, one_click, manual, api,
	// bounce_mailbox, import, provider_sync, csv.
	Kind  string `json:"kind"`
	Label string `json:"label" doc:"Amazon SES, Preference center, Linh Nguyen, Brevo import…"`
	// Adapter is set for providers (ses, postmark, postal…), for the badge colour.
	Adapter string `json:"adapter,omitempty"`
}

SuppressionSource says where a suppression came from.

type SuppressionUploadResult

type SuppressionUploadResult struct {
	SuppressionAddResult
	Rows int `json:"rows"`
}

SuppressionUploadResult reports a CSV upload of addresses.

type TierRun

type TierRun struct {
	Changed           int64 `json:"changed"`
	EnteredSunset     int64 `json:"enteredSunset"`
	LeftSunset        int64 `json:"leftSunset"`
	StoppedBroadcasts int64 `json:"stoppedBroadcasts"`
	Erased            int64 `json:"erased"`
}

TierRun reports what a run changed.

type TiersArgs

type TiersArgs struct {
	// WorkspaceID forces a run for one workspace (tests, "recompute now").
	WorkspaceID uuid.UUID `json:"workspaceId,omitempty"`
}

TiersArgs is the hourly job that recomputes engagement tiers for every workspace whose nightly run (03:00 in its timezone) is due.

func (TiersArgs) InsertOpts

func (TiersArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the maintenance queue, one at a time.

func (TiersArgs) Kind

func (TiersArgs) Kind() string

Kind implements river.JobArgs.

type TiersWorker

type TiersWorker struct {
	river.WorkerDefaults[TiersArgs]
	Svc *Service
	Log *slog.Logger
}

TiersWorker runs TiersArgs.

func (*TiersWorker) Work

func (w *TiersWorker) Work(ctx context.Context, job *river.Job[TiersArgs]) error

Work implements river.Worker.

type UnsubscribeResult

type UnsubscribeResult struct {
	ContactID uuid.UUID
	Email     string
	FirstName string
	// Lists the contact left now.
	Lists []uuid.UUID
	// Already means the contact had unsubscribed before (a repeated
	// one-click POST, a second visit).
	Already bool
}

Jump to

Keyboard shortcuts

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