scoring

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Overview

Package scoring implements contact scoring (audience-insights brief §3.1, M23): rules that add or take points for human opens, clicks, form submissions, API events, soft bounces, list unsubscribes and field conditions, with caps, decay after weeks without activity and the Cold, Warm and Hot bands; the score and its breakdown on the contact profile; the impact preview of an edited rule; recalculation in the background; and the "Score crosses…" automation trigger.

The score measures interest. It never stops or starts mail by itself: engagement tiers protect deliverability, and only automations the team builds on the score act on it.

Index

Constants

View Source
const (
	KindOpen        = "open"        // human open of any email, or of a list's emails
	KindClick       = "click"       // click on any link, or a link whose address contains some text
	KindForm        = "form"        // submitted a chosen form
	KindAPIEvent    = "api_event"   // an API event by name
	KindSoftBounce  = "soft_bounce" // not delivered after the retries
	KindUnsubscribe = "unsubscribe" // unsubscribed from a list (any, or one)
	KindField       = "field"       // a field condition, counted while it is true
)

Rule kinds: the events a rule counts, and field conditions.

View Source
const (
	CapNone        = "none"
	CapOnce        = "once"
	CapOnceDay     = "once_day"
	CapOnceWeek    = "once_week"
	CapOnceMonth   = "once_month"
	CapPointsDay   = "points_day"
	CapPointsWeek  = "points_week"
	CapPointsMonth = "points_month"
	CapWhileTrue   = "while_true" // field conditions
)

Cap kinds. "once" counts the first matching event of the look-back; once_* count one event per calendar day, week (from Monday) or month in the workspace timezone; points_* add at most N points per such period.

View Source
const (
	OpIsOneOf = "is_one_of"
	OpIsNot   = "is_not"
	OpIsSet   = "is_set"
)

Field condition operators.

View Source
const (
	BandCold = "cold"
	BandWarm = "warm"
	BandHot  = "hot"
)

Bands, in order. Their names are fixed so segments and triggers read the same everywhere; only the two thresholds move.

View Source
const (
	MaxScore     = 100
	LookbackDays = 180
	// KeepDays is how long score events are kept: the 180 days that count
	// plus 90 so the profile can draw the last 90 days of the score.
	KeepDays = LookbackDays + 90
	MaxRules = 50
)

MaxScore is the highest score. LookbackDays is how far back events count.

View Source
const (
	CauseActivity   = "activity"    // an open, a click, a form, an API event, a bounce or an unsubscribe
	CauseDecay      = "decay"       // weeks without a human open or click, or events leaving the look-back
	CauseField      = "field"       // a field condition turned true or false (nightly)
	CauseRuleChange = "rule_change" // a recalculation the save dialog let start automations
)

Trigger causes, kept in the trigger event's payload.

View Source
const NightlyHour = 3

NightlyHour is when the nightly run happens in each workspace's timezone: with the tier job, at 03:00.

Variables

View Source
var (
	DefaultDecay = ScoringDecay{Enabled: true, AfterWeeks: 4, Percent: 10}
	DefaultBands = ScoringBands{WarmFrom: 20, HotFrom: 50}
)

DefaultDecay and DefaultBands are the brief's defaults.

View Source
var BuiltinFields = []string{"country", "language", "company"}

BuiltinFields are the contact fields a condition can use besides custom fields.

Functions

func BandSince

func BandSince(res Result, bands ScoringBands) *time.Time

BandSince is when the score last entered its current band, judging by the replay's steps with the fields part added (nil when it never left the band it started in).

func Bands

func Bands(ctx context.Context, q *store.Queries, wsID uuid.UUID, contacts []uuid.UUID) (out map[uuid.UUID]ContactBand, ok bool, err error)

Bands reads the live score and band of many contacts at once (the conditional-content renderer reads its recipients' with it at send time). ok is false when the workspace has no scoring: nobody has a band.

func Describe

func Describe(r ScoringRule, n refNames) string

Describe says a rule in words, in English, for the audit log: "Click on a link containing acme.io/pricing". The app writes its own sentence.

func Erasure

func Erasure() erasure.Source

Erasure is the contact's score and the events that made it; the nightly job would drop them for an erased contact anyway (review 2026-11 DP-1).

func Register

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

Register adds the scoring operations. member answers "is this contact in that segment" for the profile's "Where it counts".

func RegisterJobs

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

RegisterJobs adds the scoring workers and their schedules.

func RegisterUses

func RegisterUses(f UseFinder)

RegisterUses adds a finder to Scoring's "Used by" card.

func RulesChanged

func RulesChanged(a, b ScoringConfig) bool

RulesChanged reports whether two configurations count differently (anything but the bands): then every contact needs a recalculation.

func Total

func Total(events, fields int) int

Total adds a fields part to an events part, kept between 0 and MaxScore.

Types

type ContactBand

type ContactBand struct {
	Score int
	Band  string
}

ContactBand is a contact's live score and band.

type ContactScore

type ContactScore struct {
	// Configured is false while the workspace has no rules: no score ("—").
	Configured bool         `json:"configured"`
	Score      int          `json:"score"`
	Band       string       `json:"band" enum:"cold,warm,hot"`
	BandSince  *time.Time   `json:"bandSince,omitempty"`
	Bands      ScoringBands `json:"bands"`
	// Recalculating is true while a recalculation runs: the score shown is
	// the previous one.
	Recalculating bool                `json:"recalculating"`
	LastChange    *ContactScoreChange `json:"lastChange,omitempty"`
	Breakdown     []ContactScoreRule  `json:"breakdown"`
	Decay         ContactScoreDecay   `json:"decay"`
	JoinedAt      time.Time           `json:"joinedAt"`
	Line          []ContactScorePoint `json:"line"`
	Uses          []ContactScoreUse   `json:"uses"`
}

ContactScore is the profile's score card.

type ContactScoreCause

type ContactScoreCause struct {
	Kind string `json:"kind" enum:"open,click,form,api_event,soft_bounce,unsubscribe,decay"`
	// EmailName is the campaign or automation of an open, click or bounce.
	EmailName string `json:"emailName,omitempty"`
	// LinkLabel and URL say which link a click was on.
	LinkLabel string `json:"linkLabel,omitempty"`
	URL       string `json:"url,omitempty"`
	FormName  string `json:"formName,omitempty"`
	EventName string `json:"eventName,omitempty"`
	ListName  string `json:"listName,omitempty"`
}

ContactScoreCause is what made the last change: an event, or decay.

type ContactScoreChange

type ContactScoreChange struct {
	At         time.Time         `json:"at"`
	Delta      int               `json:"delta"`
	Before     int               `json:"before"`
	After      int               `json:"after"`
	BeforeBand string            `json:"beforeBand" enum:"cold,warm,hot"`
	AfterBand  string            `json:"afterBand" enum:"cold,warm,hot"`
	Cause      ContactScoreCause `json:"cause"`
}

ContactScoreChange is the last change of a score.

type ContactScoreDecay

type ContactScoreDecay struct {
	Enabled bool `json:"enabled"`
	// Lost is what decay took (0 or negative).
	Lost int `json:"lost"`
	// QuietWeeks is how many weeks the contact has been without a human
	// open or click.
	QuietWeeks int `json:"quietWeeks"`
	// LastActivity is the last human open or click, and which.
	LastActivity     *time.Time `json:"lastActivity,omitempty"`
	LastActivityKind string     `json:"lastActivityKind,omitempty" doc:"open or click"`
	// LastOpen is the last human open, which the decay row names ("None ·
	// last human open Tue 7 Oct").
	LastOpen *time.Time `json:"lastOpen,omitempty"`
}

ContactScoreDecay is the decay row.

type ContactScorePoint

type ContactScorePoint struct {
	Day   string `json:"day" doc:"YYYY-MM-DD in the workspace timezone"`
	Score *int   `json:"score,omitempty"`
}

ContactScorePoint is the score at the end of a day (nil before the contact joined).

type ContactScoreRule

type ContactScoreRule struct {
	Number int         `json:"number" doc:"The rule's number on Scoring"`
	Rule   ScoringRule `json:"rule"`
	// Points is what the rule changed the score by.
	Points int `json:"points"`
	// Count is how many events matched (opens, clicks…); 1 for a true condition.
	Count int `json:"count"`
	// CapReached is the start of the latest period whose cap stopped points.
	CapReached *time.Time `json:"capReached,omitempty"`
	// AtMax is true when the 100 limit stopped some points.
	AtMax bool `json:"atMax"`
	// Latest is the last matching event.
	Latest *time.Time `json:"latest,omitempty"`
	// ZeroEmail and ZeroAt explain a zero: the email of a soft bounce that
	// was delivered after a retry, and when.
	ZeroEmail string     `json:"zeroEmail,omitempty"`
	ZeroAt    *time.Time `json:"zeroAt,omitempty"`
	FormName  string     `json:"formName,omitempty"`
	ListName  string     `json:"listName,omitempty"`
}

ContactScoreRule is one row of the breakdown.

type ContactScoreUse

type ContactScoreUse struct {
	Kind string `json:"kind" enum:"segment,automation,block"`
	ID   string `json:"id"`
	Name string `json:"name"`
	// In is true when the contact is in the segment, or entered the automation.
	In bool `json:"in"`
	// Threshold and Direction are an automation's trigger; CrossedAt is when
	// the contact last crossed it, LiveSince when the automation went live.
	Threshold int        `json:"threshold,omitempty"`
	Direction string     `json:"direction,omitempty"`
	CrossedAt *time.Time `json:"crossedAt,omitempty"`
	LiveSince *time.Time `json:"liveSince,omitempty"`
	Href      string     `json:"href,omitempty"`
}

ContactScoreUse is a place the score counts for this contact.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine replays events under one configuration in one timezone.

func NewEngine

func NewEngine(cfg ScoringConfig, loc *time.Location) *Engine

NewEngine compiles a configuration. Calendar caps (a day, a week from Monday, a month) follow loc, the workspace timezone.

func (*Engine) Config

func (e *Engine) Config() ScoringConfig

Config returns the configuration the engine runs.

func (*Engine) Replay

func (e *Engine) Replay(events []Event, now time.Time, fieldsPart int) Result

Replay scores events at time now. Events outside (now−180 days, now] are left out; events must be in time order. fieldsPart is the sum of the contact's true field conditions.

type Event

type Event struct {
	At   time.Time
	Kind string // open, click, form, api_event, soft_bounce, unsubscribe
	// Ref is the link (click), form id, API event name or list id (unsubscribe).
	Ref string
	// Lists are the lists the email went to (open, click).
	Lists []uuid.UUID
	// Counted is false for a soft bounce delivered after a retry.
	Counted bool
	// Message is the email the event is about (open, click, soft bounce).
	Message uuid.UUID
}

Event is one thing a contact did that rules can count.

type FieldError

type FieldError struct {
	Location string
	Key      string
	Args     map[string]any
}

FieldError is a rule that can't be saved, with where and why. Message is a key of the scoring catalog with its arguments, so the API can say it in the reader's language.

func (*FieldError) Error

func (e *FieldError) Error() string

type NightlyArgs

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

NightlyArgs applies decay, field conditions and the look-back in every workspace whose 03:00 run is due.

func (NightlyArgs) InsertOpts

func (NightlyArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the maintenance queue, once per half hour at most.

func (NightlyArgs) Kind

func (NightlyArgs) Kind() string

Kind implements river.JobArgs.

type NightlyResult

type NightlyResult struct {
	Rescored      int
	FieldsChanged int
	Pruned        int64
}

NightlyResult says what a nightly run changed.

type RecalcArgs

type RecalcArgs struct {
	RecalcID uuid.UUID `json:"recalcId"`
}

RecalcArgs recalculates every contact of a workspace after a rule change.

func (RecalcArgs) InsertOpts

func (RecalcArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the default queue; a failed attempt is retried twice.

func (RecalcArgs) Kind

func (RecalcArgs) Kind() string

Kind implements river.JobArgs.

type Refs

type Refs struct {
	Lists  map[uuid.UUID]bool
	Forms  map[uuid.UUID]bool
	Fields map[string]string // custom field key → type
}

Refs are what a configuration may point at in its workspace.

type Result

type Result struct {
	// EventsPart is the score from events after caps and decay (0–100).
	EventsPart int
	// FieldsPart is the sum of the true field conditions' points.
	FieldsPart int
	// Score is EventsPart + FieldsPart, kept between 0 and 100.
	Score int
	// ActiveAt is the last human open or click in the look-back.
	ActiveAt *time.Time
	// NextCheck is when the score changes next without new activity: the
	// next decay step, or the oldest event leaving the look-back.
	NextCheck *time.Time
	Rules     []RuleTally // one per enabled event rule, in rule order
	// DecayLost is what decay took (0 or negative).
	DecayLost int
	Steps     []Step
	// Events are the replayed events (in the look-back), in time order.
	Events []Event
}

Result is a replay's outcome at its end time.

func (Result) ChangedAt

func (r Result) ChangedAt() *time.Time

ChangedAt is when the score last changed, if it ever did.

type RuleTally

type RuleTally struct {
	RuleID string
	// Points is what the rule actually changed the score by: within its
	// cap, the score's 0–100 range and after nothing else.
	Points int
	// Count is how many events matched; Counted how many changed the score.
	Count   int
	Counted int
	// Zero counts matching events that gave nothing because they don't
	// count (a soft bounce delivered after a retry).
	Zero     int
	LastZero *Event
	// CapReached is the start of the latest period where the cap stopped
	// points (or the first event, for "once").
	CapReached *time.Time
	// AtMax is true when 100 stopped some of its points.
	AtMax  bool
	First  *time.Time
	Latest *time.Time
}

RuleTally is what one rule added in a replay.

type ScoreTrigger

type ScoreTrigger struct {
	Direction string `json:"direction"` // rises, falls
	Threshold int    `json:"threshold"`
}

ScoreTrigger is the part of an automation's "Score crosses…" trigger the scorer needs (internal/automations owns the trigger).

func (ScoreTrigger) Crosses

func (t ScoreTrigger) Crosses(from, to int) bool

Crosses reports whether a change from one score to another crosses t.

type ScoringBandCounts

type ScoringBandCounts struct {
	Cold int64 `json:"cold"`
	Warm int64 `json:"warm"`
	Hot  int64 `json:"hot"`
}

ScoringBandCounts are contacts per band.

type ScoringBandMove

type ScoringBandMove struct {
	From  string `json:"from" enum:"cold,warm,hot"`
	To    string `json:"to" enum:"cold,warm,hot"`
	Count int64  `json:"count"`
}

ScoringBandMove is how many contacts went from one band to another.

type ScoringBands

type ScoringBands struct {
	WarmFrom int `json:"warmFrom" minimum:"1" maximum:"99"`
	HotFrom  int `json:"hotFrom" minimum:"2" maximum:"100"`
}

ScoringBands are the two thresholds: Warm from, Hot from.

func AppliedBands

func AppliedBands(ctx context.Context, q *store.Queries, wsID uuid.UUID) (ScoringBands, bool, error)

AppliedBands returns the thresholds live scores fall into, and whether the workspace has scoring at all.

func (ScoringBands) Band

func (b ScoringBands) Band(score int) string

Band names a score's band under the thresholds.

type ScoringBucket

type ScoringBucket struct {
	From     int   `json:"from"`
	To       int   `json:"to"`
	Contacts int64 `json:"contacts"`
}

ScoringBucket is one bar of the spread: contacts with a score from From to To (the last bucket is 90–100).

type ScoringChanges

type ScoringChanges struct {
	Setup bool  `json:"setup"`
	Rules []int `json:"rules"`
	Decay bool  `json:"decay"`
	Bands bool  `json:"bands"`
}

ScoringChanges is what a save changed, as data: the numbers of the rules added, changed or deleted, and whether decay or the bands moved.

type ScoringConfig

type ScoringConfig struct {
	Rules []ScoringRule `json:"rules" maxItems:"50"`
	Decay ScoringDecay  `json:"decay"`
	Bands ScoringBands  `json:"bands"`
}

ScoringConfig is a workspace's whole scoring set-up, saved as one version.

func ParseConfig

func ParseConfig(raw []byte) (ScoringConfig, error)

ParseConfig reads a stored version.

func (ScoringConfig) Clone

func (c ScoringConfig) Clone() ScoringConfig

Clone copies a configuration, so a draft can change without touching it.

func (*ScoringConfig) Normalize

func (c *ScoringConfig) Normalize()

Normalize fills ids and defaults and trims text; it doesn't validate.

func (ScoringConfig) Validate

func (c ScoringConfig) Validate(refs Refs) error

Validate checks a normalized configuration against its workspace.

type ScoringDecay

type ScoringDecay struct {
	Enabled    bool `json:"enabled"`
	AfterWeeks int  `json:"afterWeeks" minimum:"1" maximum:"52"`
	Percent    int  `json:"percent" minimum:"1" maximum:"100"`
}

ScoringDecay takes a share of the score each week after a stretch without a human open or click.

type ScoringEventOption

type ScoringEventOption struct {
	Name  string `json:"name"`
	Count int64  `json:"count"`
}

type ScoringFieldOption

type ScoringFieldOption struct {
	Key     string   `json:"key"`
	Label   string   `json:"label"`
	Type    string   `json:"type"`
	Options []string `json:"options"`
}

type ScoringFlowImpact

type ScoringFlowImpact struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Direction string `json:"direction" enum:"rises,falls"`
	Threshold int    `json:"threshold"`
	// Crossed is how many contacts cross it only because of the change.
	Crossed int64 `json:"crossed"`
	// Started is how many of them the automation started for (0 unless the
	// save dialog said to start it).
	Started int64 `json:"started"`
}

ScoringFlowImpact is a "Score crosses…" automation and the contacts who cross its threshold because of a change.

type ScoringFormOption

type ScoringFormOption struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Kind string `json:"kind" enum:"embedded,popup,hosted"`
}

type ScoringImpact

type ScoringImpact struct {
	Contacts int64 `json:"contacts"`
	// Current is today's spread (live scores), Spread the spread after the edit.
	Current     []ScoringBucket   `json:"current"`
	Spread      []ScoringBucket   `json:"spread"`
	BandsBefore ScoringBandCounts `json:"bandsBefore"`
	BandsAfter  ScoringBandCounts `json:"bandsAfter"`
	// Changed is how many contacts change band; Moves says which way.
	Changed int64             `json:"changed"`
	Moves   []ScoringBandMove `json:"moves"`
	// Flows are the live "Score crosses…" automations and how many
	// contacts would cross their threshold because of the edit.
	Flows []ScoringFlowImpact `json:"automations"`
	// FieldMatches counts the contacts each field condition matches today,
	// by rule id ("1,532 contacts match today").
	FieldMatches map[string]int64 `json:"fieldMatches"`
	// Rescored is how many contacts the preview replayed.
	Rescored int64 `json:"rescored"`
	// Estimated is true when a large replay was sampled.
	Estimated  bool `json:"estimated"`
	DurationMs int  `json:"durationMs"`
}

ScoringImpact is how an edit would move contacts.

type ScoringListOption

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

ScoringListOption, ScoringFormOption, ScoringFieldOption and ScoringEventOption are what the rule editor offers.

type ScoringOptions

type ScoringOptions struct {
	Lists     []ScoringListOption  `json:"lists"`
	Forms     []ScoringFormOption  `json:"forms"`
	Fields    []ScoringFieldOption `json:"fields"`
	APIEvents []ScoringEventOption `json:"apiEvents"`
}

ScoringOptions are the rule editor's choices.

type ScoringPage

type ScoringPage struct {
	// Configured is false until the workspace saves its first rules.
	Configured     bool          `json:"configured"`
	Version        int           `json:"version"`
	AppliedVersion int           `json:"appliedVersion"`
	Config         ScoringConfig `json:"config"`
	SetUpBy        string        `json:"setUpBy"`
	SetUpAt        *time.Time    `json:"setUpAt,omitempty"`
	// Contacts is how many contacts the spread counts.
	Contacts  int64              `json:"contacts"`
	Spread    []ScoringBucket    `json:"spread"`
	Bands     ScoringBandCounts  `json:"bands"`
	ByTier    []ScoringTierRow   `json:"byTier"`
	UsedBy    []ScoringUse       `json:"usedBy"`
	Recalc    *ScoringRecalcInfo `json:"recalculation,omitempty"`
	Options   ScoringOptions     `json:"options"`
	Suggested []ScoringRule      `json:"suggested"`
	// Helpers are who can change scoring, for the read-only note ("Ask
	// Sofia Rossi, Marcus Chen or Linh Nguyen"): who set it up, then the
	// Admins and Owners who hold scoring:edit.
	Helpers []string `json:"helpers"`
	// TierExample is an Active contact who opens but never clicks and is
	// Cold, for the note under Bands by tier.
	TierExample *ScoringTierExample `json:"tierExample,omitempty"`
}

ScoringPage is Audience › Scoring.

type ScoringPreviewInput

type ScoringPreviewInput struct {
	Config ScoringConfig `json:"config"`
}

ScoringPreviewInput is an edited, unsaved set-up.

type ScoringRecalcInfo

type ScoringRecalcInfo struct {
	ID               string                `json:"id"`
	Status           string                `json:"status" enum:"running,finished,failed,superseded"`
	Reason           string                `json:"reason" enum:"setup,rules,retry"`
	Total            int64                 `json:"total"`
	Done             int64                 `json:"done"`
	StartAutomations bool                  `json:"startAutomations"`
	StartedAt        time.Time             `json:"startedAt"`
	StartedBy        string                `json:"startedBy"`
	FinishedAt       *time.Time            `json:"finishedAt,omitempty"`
	FailedAt         *time.Time            `json:"failedAt,omitempty"`
	Label            string                `json:"label"`
	Changes          ScoringChanges        `json:"changes"`
	Summary          *ScoringRecalcSummary `json:"summary,omitempty"`
	// RemainingSeconds estimates the time left from the pace so far.
	RemainingSeconds *int `json:"remainingSeconds,omitempty"`
}

ScoringRecalcInfo is the latest recalculation.

type ScoringRecalcSummary

type ScoringRecalcSummary struct {
	// Changed is how many contacts changed band.
	Changed int64               `json:"changed"`
	Moves   []ScoringBandMove   `json:"moves"`
	Bands   ScoringBandCounts   `json:"bands"`
	Flows   []ScoringFlowImpact `json:"automations"`
}

ScoringRecalcSummary says what a finished recalculation changed.

type ScoringRule

type ScoringRule struct {
	ID   string `json:"id" maxLength:"40" doc:"Kept across versions; new rules get one when saved"`
	Kind string `json:"kind" enum:"open,click,form,api_event,soft_bounce,unsubscribe,field"`
	// ListID limits opens to a list's emails, or unsubscribes to one list.
	ListID string `json:"listId,omitempty" maxLength:"40"`
	// Contains limits clicks to links whose address contains this text.
	Contains string `json:"contains,omitempty" maxLength:"200"`
	FormID   string `json:"formId,omitempty" maxLength:"40"`
	Event    string `json:"event,omitempty" maxLength:"100"`
	// Field, Op and Values make a field condition: a custom field's key, or
	// country, language or company.
	Field   string         `json:"field,omitempty" maxLength:"64"`
	Op      string         `json:"op,omitempty" enum:"is_one_of,is_not,is_set"`
	Values  []string       `json:"values,omitempty" maxItems:"20"`
	Points  int            `json:"points" minimum:"-50" maximum:"50"`
	Cap     ScoringRuleCap `json:"cap"`
	Enabled bool           `json:"enabled"`
}

ScoringRule is one rule: what counts, the points it gives (or takes) and its cap.

func SuggestedRules

func SuggestedRules(betaForm uuid.UUID, plan bool) []ScoringRule

SuggestedRules are the eight rules the empty state offers (brief §4). The form and the field are filled in for the workspace when they exist: the first form whose name says "beta", and a select field called plan.

func (ScoringRule) IsEvent

func (r ScoringRule) IsEvent() bool

IsEvent reports whether a rule counts events (not a field condition).

type ScoringRuleCap

type ScoringRuleCap struct {
	Kind string `json:"kind" enum:"none,once,once_day,once_week,once_month,points_day,points_week,points_month,while_true"`
	// Points is the most a points_* cap adds in its period.
	Points int `json:"points,omitempty" minimum:"0" maximum:"1000"`
}

ScoringRuleCap limits what a rule adds.

type ScoringSaveInput

type ScoringSaveInput struct {
	Config ScoringConfig `json:"config"`
	// BaseVersion is the version the editor opened; a newer one means
	// someone else saved in between.
	BaseVersion int `json:"baseVersion" minimum:"0"`
	// StartAutomations answers the save dialog: start "Score crosses…"
	// automations for contacts who cross only because the rules changed.
	// Not starting them is the default (and recommended).
	StartAutomations bool `json:"startAutomations,omitempty"`
}

ScoringSaveInput saves the whole set-up: rules, decay and bands.

type ScoringTierExample

type ScoringTierExample struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Score int    `json:"score"`
}

ScoringTierExample names one contact (workspace content) and its score.

type ScoringTierRow

type ScoringTierRow struct {
	Tier     string `json:"tier" enum:"active,cooling,at_risk,sunset"`
	Contacts int64  `json:"contacts"`
	Hot      int64  `json:"hot"`
	Warm     int64  `json:"warm"`
	Cold     int64  `json:"cold"`
}

ScoringTierRow is one engagement tier split by band.

type ScoringUse

type ScoringUse struct {
	Kind string `json:"kind" enum:"automation,segment,block"`
	ID   string `json:"id"`
	Name string `json:"name"`
	// Status is an automation's (live, paused, draft), or the status of a
	// block's email (draft, approval, approved, scheduled).
	Status string `json:"status,omitempty"`
	By     string `json:"by,omitempty"`
	// Since is when an automation went live.
	Since *time.Time `json:"since,omitempty"`
	// Entered is how many contacts an automation started for.
	Entered int64 `json:"entered"`
	// Direction, Threshold and OnceInDays are an automation's trigger.
	Direction  string `json:"direction,omitempty"`
	Threshold  int    `json:"threshold,omitempty"`
	OnceInDays int    `json:"onceInDays,omitempty"`
	// Contacts is a segment's last count, or a block's recipients.
	Contacts *int64 `json:"contacts,omitempty"`
	// Conditions are a segment's conditions, for its one-line summary, or
	// the score conditions of a block's Visibility rule, written the same way
	// ({"field": "score_band", "op": "is", "value": "hot"}).
	Conditions json.RawMessage `json:"conditions,omitempty"`
	// Show is a block's Visibility: shown only to contacts who match, or to
	// everyone except them.
	Show string `json:"show,omitempty" enum:"only,except"`
	// Where says where a block is ("Weekly Digest #143 (draft)"); Of is
	// the total its count is out of.
	Where string `json:"where,omitempty"`
	Of    *int64 `json:"of,omitempty"`
	Href  string `json:"href,omitempty"`
}

ScoringUse is something that reads the score: an automation, a segment or (phase 3) a conditional block.

type SegmentMembership

type SegmentMembership func(ctx context.Context, ws *store.Workspace, segment, contact uuid.UUID) (bool, error)

SegmentMembership reports whether a contact is in a segment (the segments domain answers it; scoring can't import it).

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	// Jobs returns the River client (created after the services are wired);
	// nil runs recalculations in the request, as tests do.
	Jobs func() *jobs.Client
	Log  *slog.Logger
	Now  func() time.Time
}

Service is the scoring domain.

func (*Service) ContactScore

func (s *Service) ContactScore(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, member SegmentMembership) (ContactScore, error)

ContactScore returns a contact's score with its breakdown, replayed under the applied rules.

func (*Service) NightlyWorkspace

func (s *Service) NightlyWorkspace(ctx context.Context, wsID uuid.UUID, tz string) (NightlyResult, error)

NightlyWorkspace applies decay steps and events leaving the look-back, re-evaluates field conditions for every contact, and prunes old events.

func (*Service) Page

func (s *Service) Page(ctx context.Context, ws *store.Workspace) (ScoringPage, error)

Page returns everything Audience › Scoring shows.

func (*Service) Preview

Preview computes the impact of an edited set-up.

func (*Service) Recalculate

func (s *Service) Recalculate(ctx context.Context, id uuid.UUID) error

Recalculate runs (or resumes) a recalculation.

func (*Service) Retry

func (s *Service) Retry(ctx context.Context, ws *store.Workspace) (ScoringPage, error)

Retry starts a failed recalculation again where it stopped.

func (*Service) RunNightly

func (s *Service) RunNightly(ctx context.Context, only uuid.UUID) error

RunNightly runs the nightly step in every workspace where it is due (or in one workspace, forced).

func (*Service) Save

Save stores a new version of the set-up, audits what changed and starts a recalculation when the rules or decay changed. Moving only the bands applies at once: scores don't change, only which band they fall in.

func (*Service) Tick

func (s *Service) Tick(ctx context.Context) error

Tick scores what happened since the last tick in every workspace.

func (*Service) TickWorkspace

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

TickWorkspace runs one tick for one workspace (tests and the demo).

type Step

type Step struct {
	At     time.Time
	Before int
	After  int
	// Event is the index in the replayed events, -1 for decay.
	Event int
	Rules []string
}

Step is one change of the events part: an event's rules, or decay.

type TickArgs

type TickArgs struct{}

TickArgs scores new activity in every workspace with scoring.

func (TickArgs) InsertOpts

func (TickArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the events queue, once per period. Ticks that overlap are harmless: the event copy is idempotent and each takes its own dirty contacts.

func (TickArgs) Kind

func (TickArgs) Kind() string

Kind implements river.JobArgs.

type UseFinder

type UseFinder func(ctx context.Context, q *store.Queries, ws *store.Workspace) ([]ScoringUse, error)

UseFinder lists the things of one kind that read the score. Conditional content (phase 3) registers one for its blocks, from its package's init: it reads through q, as Scoring's page does.

Jump to

Keyboard shortcuts

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