audience

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: AGPL-3.0 Imports: 48 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 (
	LanguageFromImport      = "import"
	LanguageFromForm        = "form"
	LanguageFromPreferences = "preference_center"
	LanguageFromAPI         = "api"
	LanguageFromTeam        = "team"
)

Where a contact's language came from (contacts.language_source).

View Source
const (
	LanguageFilterNone       = "none"
	LanguageFilterNotOffered = "not_offered"
)

Values of the Contacts filter besides a language's code.

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 BrowserLanguage

func BrowserLanguage(header string) string

BrowserLanguage is the first language of an Accept-Language header, normalized ("es-MX,es;q=0.9,en;q=0.8" → "es-MX"), or "" when it names none ReputeCast knows.

func BrowserLanguages

func BrowserLanguages(header string) []string

BrowserLanguages are the languages of an Accept-Language header, normalized, most preferred first; tags ReputeCast doesn't know are left out.

func ClosestLanguage

func ClosestLanguage(v string) string

ClosestLanguage is the catalog language a value that isn't one most likely means ("Spanosh", "Spanglish!" and "Span" → es), or "".

func ConsentName

func ConsentName(c string) string

ConsentName is how a consent state reads in the UI, in English.

func ConsentNameIn

func ConsentNameIn(l i18n.Lang, c string) string

ConsentNameIn is how a consent state reads in a reader's language: "Double opt-in".

func CountryName

func CountryName(code string) string

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

func CountryNameIn

func CountryNameIn(l i18n.Lang, code string) string

CountryNameIn is a country's name in a reader's language, as Intl.DisplayNames names it on the web ("United States", "Hoa Kỳ"); the code itself when it isn't a country.

func EmailProblemIn

func EmailProblemIn(l i18n.Lang, problem string) string

EmailProblemIn is emailaddr.Check's problem in a reader's language, for other packages that show it (the import preview's invalid rows).

func FillLanguage

func FillLanguage(ctx context.Context, q *store.Queries, contactID uuid.UUID, browser, form string, at time.Time) error

FillLanguage sets a signup's language from the browser when the contact has none, inside the caller's transaction. form names the form ("Newsletter signup", or "" for the hosted subscribe page). It never overwrites a language the contact already has.

func KeptIn

func KeptIn(l i18n.Lang, texts json.RawMessage, column, english string) string

KeptIn writes a stored English text for a reader: the message kept for that column in their language, or the English when the reader reads English, the row kept no message or its catalog no longer has it.

func KeptTexts

func KeptTexts(texts map[string]i18n.Text) json.RawMessage

KeptTexts is a texts column holding these messages, by the name of the column whose English each one wrote: "detail", "note" (consent events), "context", "original_code" (suppressions). Messages without an ID are left out; nil when none is left, which stores {}.

func MailClient

func MailClient(ua string) string

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

func MailClientIn

func MailClientIn(l i18n.Lang, ua string) string

MailClientIn names the mail client in a reader's language: "Outlook on Windows"; names (Gmail, Thunderbird) stay as they are.

func MailboxLabel

func MailboxLabel(provider, detail string) string

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

func NormalizeLanguage

func NormalizeLanguage(raw, loc string) (string, error)

NormalizeLanguage turns what an import, the API or a person sends into a BCP 47 code: "Spanish", "es_MX" and "ES" become es and es-MX. An empty value clears the language. A value that isn't a language answers 422 at loc, with the closest match when there is one (meta "closest").

func NormalizeLanguageIn

func NormalizeLanguageIn(rl i18n.Lang, raw, loc string) (string, error)

NormalizeLanguageIn is NormalizeLanguage with its problem in a reader's language.

func PartnerSource

func PartnerSource(l i18n.Lang, name string) string

PartnerSource names a contact who joined on a partner's page, in a reader's language: "Partner · Ops Weekly".

func RecordLanguageSource

func RecordLanguageSource(ctx context.Context, q *store.Queries, contactID uuid.UUID, source, name string, at time.Time, by *uuid.UUID) error

RecordLanguageSource notes where a contact's language came from, after a query that sets several fields wrote it.

func ReferralSource

func ReferralSource(l i18n.Lang, name string) string

ReferralSource names a contact who joined through a referral, in a reader's language: "Referral · Sam Rivera". name is the referrer's.

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 SetLanguageFrom

func SetLanguageFrom(ctx context.Context, q *store.Queries, contactID uuid.UUID, code, source, name string, at time.Time) error

SetLanguageFrom records a language set by an import, the API, an integration or the preference center, inside the caller's transaction.

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, in English.

func TierNameIn

func TierNameIn(l i18n.Lang, t string) string

TierNameIn is how a tier reads in a reader's language: "At risk".

Types

type ActivitySource

type ActivitySource interface {
	ContactActivity(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, before *time.Time, beforeID string, limit int) ([]ContactActivityItem, int64, error)
}

ActivitySource adds events another domain keeps to the timeline (poll answers and survey responses): the ones before the cursor, newest first, and how many there are in all.

type ActivitySources

type ActivitySources []ActivitySource

ActivitySources are several domains' events as one source (poll answers, purchases); nil entries are skipped.

func (ActivitySources) ContactActivity

func (ss ActivitySources) ContactActivity(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, before *time.Time, beforeID string, limit int) ([]ContactActivityItem, int64, error)

ContactActivity implements ActivitySource.

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"`
	// Origin is what fills the list: "store" for a connected store's
	// customers who accepted marketing (X20), empty otherwise.
	Origin string `json:"origin,omitempty"`
}

AudienceListSummary is a list with its size.

type AudiencePaidTier

type AudiencePaidTier struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Short string `json:"short"`
	Top   bool   `json:"top"`
}

AudiencePaidTier is a tier the Paid status filter offers, lowest first.

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"`
	// PaidTiers are the Earn tiers of the Paid status filter, lowest first;
	// empty without tiers or without earn:view (no Paid filter or column).
	PaidTiers []AudiencePaidTier `json:"paidTiers"`
}

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 ChannelFilter

type ChannelFilter struct {
	// Phone is "yes" for contacts with a number, "no" for those without.
	Phone string `json:"phone,omitempty" enum:"yes,no"`
	// PhoneCountry is the number's country (GB).
	PhoneCountry string `json:"phoneCountry,omitempty" maxLength:"2"`
	// SMSConsent is "any" (SMS consent on some list), "none", or a list id.
	SMSConsent string `json:"smsConsent,omitempty" maxLength:"40"`
}

ChannelFilter narrows contacts by their phone number and SMS consent.

type ChannelQuery

type ChannelQuery struct {
	Phone        string `query:"phone" enum:"yes,no," doc:"yes: contacts with a phone number; no: without one"`
	PhoneCountry string `query:"phoneCountry" maxLength:"2" doc:"The phone number's country (GB)"`
	SMSConsent   string `query:"smsConsent" maxLength:"40" doc:"any: SMS consent on some list; none: on none; or a list id"`
}

ChannelQuery is the same filter as query parameters.

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"`
	// Language is the language version delivered ("en"), set on deliveries
	// the send recorded a version for, when the workspace has several
	// languages. LanguageReason says why a
	// contact got another language than theirs, whose name is
	// ContactLanguageName ("Portuguese").
	Language            string `json:"language,omitempty"`
	LanguageReason      string `json:"languageReason,omitempty" enum:",match,no_language,not_offered,missing,draft,held,requested"`
	ContactLanguageName string `json:"contactLanguageName,omitempty"`
	// ConsentLanguage is the language the consent text was shown in.
	ConsentLanguage string `json:"consentLanguage,omitempty"`
	// Poll answers and survey responses (types poll_answer, survey_started
	// and survey_response; design expansion, X11): the question, the answer,
	// the one it replaced and the comment; how many of a survey's questions
	// were answered, and until when the response can change.
	Question      string     `json:"question,omitempty"`
	Answer        string     `json:"answer,omitempty"`
	Previous      string     `json:"previous,omitempty"`
	Comment       string     `json:"comment,omitempty"`
	Answered      int        `json:"answered,omitempty"`
	Questions     int        `json:"questions,omitempty"`
	EditableUntil *time.Time `json:"editableUntil,omitempty"`
	// Store orders and abandoned checkouts (types store_order and
	// checkout_abandoned; design expansion, X20).
	Store *ContactActivityStore `json:"store,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 ContactActivityStore

type ContactActivityStore struct {
	Name     string   `json:"name"`
	Platform string   `json:"platform" enum:"shopify,woocommerce"`
	Order    string   `json:"order,omitempty"`
	Total    int64    `json:"total"`
	Currency string   `json:"currency"`
	Items    []string `json:"items"`
	Accepted bool     `json:"accepted"`
	Credited string   `json:"credited,omitempty"`
	Flow     string   `json:"flow,omitempty"`
}

ContactActivityStore is a store order or an abandoned checkout on the timeline: the store, the order's name, its total and items, whether the buyer accepted marketing, the email it was credited to and the flow the checkout entered.

type ContactBulkFailure

type ContactBulkFailure struct {
	Email  string `json:"email"`
	Reason string `json:"reason"`
	// Code says why for screens that word it themselves: suppressed (on the
	// suppression list) or refused (the System provider refused the email).
	Code string `json:"code" enum:"suppressed,refused"`
}

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"`
	// ConsentText is the exact text the contact agreed to, when it was
	// recorded ("Also send me the Weekly Digest" at a product checkout).
	ConsentText string `json:"consentText,omitempty"`
	// Language is the language the consent text was shown in ("es").
	Language string    `json:"language,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"`
	// Language is a workspace language's code (its regional codes match),
	// "none" for contacts with no language or "not_offered" for languages
	// the workspace doesn't offer.
	Language string `json:"language,omitempty" maxLength:"16"`
	// Score, band and growth source (scoregrowth.go).
	ScoreGrowthFilter
	// Check is the latest address check's result, or never checked.
	Check string `json:"check,omitempty" enum:"valid,invalid,risky,unknown,never"`
	// Members of the website (website.go).
	WebsiteFilter
	// Paid status (Earn, paid.go).
	PaidFilter
	// Push subscribed and WhatsApp consent (X22, pushwhatsapp.go).
	PushWhatsAppFilter
	// Buyers of digital products (products.go).
	ProductsFilter
	// Store customers and what they spent (storefilter.go).
	StoreFilter
	// The phone and SMS consent (channels.go).
	ChannelFilter
}

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 ContactLanguage

type ContactLanguage struct {
	// Code is the stored code ("es-MX"), "" when the contact has none.
	Code string `json:"code"`
	// Name is the language's English name ("Spanish"), "" when unknown.
	Name string `json:"name"`
	// Offered reports whether the workspace has the language; Gets is the
	// language the contact gets instead when it hasn't (the fallback).
	Offered bool   `json:"offered"`
	Gets    string `json:"gets"`
	// Source is where it came from; SourceName names the import, form,
	// integration or team member ("Brevo", "Newsletter signup", "Zapier").
	Source     string     `json:"source" enum:"import,form,preference_center,api,team,"`
	SourceName string     `json:"sourceName"`
	Browser    bool       `json:"browser" doc:"A signup form read it from the browser"`
	SetAt      *time.Time `json:"setAt,omitempty"`
	// Options are the select's choices: the contact's own language first
	// when the workspace doesn't offer it, then the workspace's languages.
	Options []ContactLanguageOption `json:"options"`
}

ContactLanguage is the profile's language field: the code, where it came from, and whether the workspace offers it.

type ContactLanguageOption

type ContactLanguageOption struct {
	// Code is what choosing it stores: the workspace language, or the
	// contact's own regional code when it belongs to that language.
	Code string `json:"code"`
	Name string `json:"name"`
	// Offered is false for the contact's own language when the workspace
	// doesn't offer it.
	Offered bool `json:"offered"`
}

ContactLanguageOption is a choice of the profile's language select.

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"`
	// Score is null while the workspace has no scoring; ScoreBand is its band.
	Score     *int   `json:"score,omitempty"`
	ScoreBand string `json:"scoreBand,omitempty" enum:"cold,warm,hot"`
	// Paid is the contact's paid status (Earn), for callers with earn:view.
	Paid *ContactPaid `json:"paid,omitempty"`
	// Phone is the number as people read it (+1 312 555 0123), when there is one.
	Phone string `json:"phone,omitempty"`
}

ContactListItem is one row of the contacts table.

type ContactPaid

type ContactPaid struct {
	Tier     string `json:"tier" doc:"The tier's short name (Insider)"`
	Status   string `json:"status" enum:"trialing,active,past_due,complimentary,gift,ended"`
	MemberID string `json:"memberId"`
	// EndedAt is when access ended (status ended).
	EndedAt *time.Time `json:"endedAt,omitempty"`
}

ContactPaid is a contact's paid status in the contacts table: the tier's short name for the chip, the status for the Paid column, and the paid subscription that opens the paid member.

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"`
	// Language is the contact's language with where it came from.
	Language ContactLanguage `json:"language"`
}

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        `` /* 134-byte string literal not displayed */
	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
	// Code names the problem for pages that show it in another language:
	// email, pick_list, list_gone, number, date, boolean, select (with
	// Options), too_long, frequency, language.
	Code    string
	Options []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"`
	// Language is a BCP 47 code ("es-MX"); "Spanish" and "es_MX" are
	// normalized, and a value that isn't a language answers 422 with the
	// closest match.
	Language string `json:"language,omitempty" maxLength:"40"`
}

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 PaidFilter

type PaidFilter struct {
	// Paid is a paid status: with_access (any paid tier, or the tier in
	// PaidTier and above), trialing, past_due, complimentary, gift, ended
	// (access ended, none now) or free (no paid access).
	Paid     string `json:"paid,omitempty" enum:"with_access,trialing,past_due,complimentary,gift,ended,free"`
	PaidTier string `json:"paidTier,omitempty" doc:"With paid=with_access: a tier's id, for that tier and above"`
}

PaidFilter narrows contacts by paid status. Saved views keep it.

type PaidQuery

type PaidQuery struct {
	Paid     string `query:"paid" enum:"with_access,trialing,past_due,complimentary,gift,ended,free,"`
	PaidTier string `query:"paidTier" doc:"With paid=with_access: a tier's id, for that tier and above"`
}

PaidQuery is the same filter as query parameters.

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
	// Language is the "Email language" choice, one of the workspace's
	// languages; nil keeps it. A regional code of the same language stays
	// (es-MX choosing Español keeps es-MX).
	Language *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
	// LanguageChanged is true when the Email language changed.
	LanguageChanged bool
}

PreferencesResult lists what changed.

type ProductsFilter

type ProductsFilter struct {
	// Bought keeps the buyers: "any" for any product, or a product's id.
	Bought string `json:"bought,omitempty" maxLength:"40" doc:"Buyers of a product (its id), or of any product (any)"`
}

ProductsFilter narrows contacts by what they bought.

type ProductsQuery

type ProductsQuery struct {
	Bought string `query:"bought" maxLength:"40" doc:"Only contacts who bought a product: any, or the product's id"`
}

ProductsQuery is the same filter as query parameters.

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
	// Language is the contact's language ("es-MX", "" for none): the pages
	// reached from an email show in it.
	Language string
}

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
	// Language is the language the page or form, and so its consent text,
	// was shown in ("es"); consent evidence keeps it.
	Language string
	// Note goes on the consent events. NoteText is the message it came from
	// when the note is ReputeCast's own words, kept so readers in another
	// language see it in theirs (KeptIn); leave it empty for text people
	// typed.
	Note     string
	NoteText i18n.Text
	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 PushWhatsAppFilter

type PushWhatsAppFilter struct {
	PushSubscribed  bool `json:"pushSubscribed,omitempty"`
	WhatsAppConsent bool `json:"whatsAppConsent,omitempty"`
}

PushWhatsAppFilter narrows contacts by push and WhatsApp.

type PushWhatsAppQuery

type PushWhatsAppQuery struct {
	PushSubscribed  bool `query:"pushSubscribed" doc:"Only contacts with a linked push subscription"`
	WhatsAppConsent bool `query:"whatsAppConsent" doc:"Only contacts with WhatsApp consent on a list"`
}

PushWhatsAppQuery is the same filter as query parameters.

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 ScoreGrowthFilter

type ScoreGrowthFilter struct {
	// Band is a score band, or "none" for contacts without a score.
	Band string `json:"band,omitempty" enum:"cold,warm,hot,none"`
	// ScoreFrom and ScoreTo are a range of scores (0–100), both included.
	ScoreFrom string `json:"scoreFrom,omitempty" maxLength:"3"`
	ScoreTo   string `json:"scoreTo,omitempty" maxLength:"3"`
	// GrowthSource is a source key from Audience › Growth ("form:<id>",
	// "api_key:<id>", "integration:<id>:<workflow>", "person"…).
	GrowthSource    string `json:"growthSource,omitempty" maxLength:"200"`
	UTMSource       string `json:"utmSource,omitempty" maxLength:"200"`
	UTMMedium       string `json:"utmMedium,omitempty" maxLength:"200"`
	UTMCampaign     string `json:"utmCampaign,omitempty" maxLength:"200"`
	ReferringDomain string `json:"referringDomain,omitempty" maxLength:"255"`
	// Sort orders the table: by last activity (default) or score, highest first.
	Sort string `json:"sort,omitempty" enum:"activity,score"`
}

ScoreGrowthFilter narrows contacts by their score and by how they first joined. Saved views keep it with the rest of the filter.

type ScoreGrowthQuery

type ScoreGrowthQuery struct {
	Band            string `query:"band" enum:"cold,warm,hot,none,"`
	ScoreFrom       string `query:"scoreFrom" maxLength:"3"`
	ScoreTo         string `query:"scoreTo" maxLength:"3"`
	GrowthSource    string `query:"growthSource" maxLength:"200"`
	UTMSource       string `query:"utmSource" maxLength:"200"`
	UTMMedium       string `query:"utmMedium" maxLength:"200"`
	UTMCampaign     string `query:"utmCampaign" maxLength:"200"`
	ReferringDomain string `query:"referringDomain" maxLength:"255"`
	Sort            string `query:"sort" enum:"activity,score,"`
}

ScoreGrowthQuery is the same filter as query parameters.

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
	// Answers adds poll answers and survey responses to the timeline (nil:
	// none).
	Answers ActivitySource
	// SourceNames names sources a label can't (Grow: "Referral · Sam
	// Rivera", "Partner · Ops Weekly"); nil: none.
	SourceNames SourceNamer
}

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) AddSuppressionsKept

func (s *Service) AddSuppressionsKept(ctx context.Context, ws *store.Workspace, emails []string, note string, text i18n.Text) (SuppressionAddResult, error)

AddSuppressionsKept adds addresses with a note in ReputeCast's own words (a report's "Hard · unknown user bounces on Weekly Digest #142"), keeping its message so readers in another language see the note in theirs.

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) SelectionIDs

func (s *Service) SelectionIDs(ctx context.Context, ws *store.Workspace, sel Selection) ([]uuid.UUID, error)

SelectionIDs resolves a selection to the contact ids the caller can see (their list scope included). The verification domain's bulk checks of a list, a tier, a segment, a selection or a saved view use it.

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
	// BrowserLanguage is the browser's first language ("es-MX"): it becomes
	// the contact's language when they have none. FormName names the form
	// it came through ("Newsletter signup"; empty for the subscribe page).
	BrowserLanguage string
	FormName        string
}

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 SourceNamer

type SourceNamer func(ctx context.Context, ws uuid.UUID, contacts []uuid.UUID, sources []string) map[uuid.UUID]string

SourceNamer names contacts' sources: by contact, for the contacts whose source it knows. sources[i] is contacts[i]'s.

type StoreFilter

type StoreFilter struct {
	// StoreCustomer is a store's id, or "any": its customers (who ordered,
	// or whom the store's sync knows).
	StoreCustomer string `json:"storeCustomer,omitempty" maxLength:"36"`
	// SpentFrom and SpentTo are a range of the total spent in the stores, in
	// the stores' currency ("100", "250.50"), both included.
	SpentFrom string `json:"spentFrom,omitempty" maxLength:"12"`
	SpentTo   string `json:"spentTo,omitempty" maxLength:"12"`
}

StoreFilter narrows contacts by the connected stores: a store's customers, and what they spent there (orders less refunds).

type StoreQuery

type StoreQuery struct {
	StoreCustomer string `query:"storeCustomer" maxLength:"36" doc:"A store's id, or any"`
	SpentFrom     string `query:"spentFrom" maxLength:"12" doc:"Total spent in the stores, at least"`
	SpentTo       string `query:"spentTo" maxLength:"12" doc:"Total spent in the stores, at most"`
}

StoreQuery is the same filter as query parameters.

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(l i18n.Lang) error

Validate checks that the tier thresholds are in order; its problems are in the reader's language.

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
	// AppliesTo is all (every stream, transactional mail included) or
	// marketing (Broadcasts and Automations only: unsubscribes and role
	// addresses).
	AppliesTo string
}

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
}

type WebsiteFilter

type WebsiteFilter struct {
	// SignedIn keeps the members: contacts who signed in to the website.
	SignedIn bool `json:"signedIn,omitempty"`
}

WebsiteFilter narrows contacts by the website.

type WebsiteQuery

type WebsiteQuery struct {
	SignedIn bool `query:"signedIn" doc:"Only contacts who signed in to the website"`
}

WebsiteQuery is the same filter as query parameters.

Jump to

Keyboard shortcuts

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