automations

package
v1.3.0 Latest Latest
Warning

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

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

Documentation

Overview

Package automations implements visual flows (spec 7.10): the React Flow graph and its validation, versions with a diff and publish, the runs engine on River and per-step stats. The sending and approvals domains plug in through Mailer and PublishGate.

Index

Constants

View Source
const (
	StatusDraft  = "draft"
	StatusLive   = "live"
	StatusPaused = "paused"
)

Statuses of a flow.

View Source
const (
	NodePush     = "push"
	NodeWhatsApp = "whatsapp"
)

NodePush and NodeWhatsApp are the "Send push" and "Send WhatsApp" steps (design expansion phase 8, X22): internal/push and internal/whatsapp send them through the same registry.

View Source
const (
	// CondSMSConsent: the contact has SMS consent on the condition's list
	// (any list when it names none).
	CondSMSConsent = "sms_consent"
	// CondSMSClicked: the contact clicked a link of the step's text (any
	// text of the flow when it names no step), within the window.
	CondSMSClicked = "sms_clicked"
	// CondSMSReplied: the contact replied to the step's text.
	CondSMSReplied = "sms_replied"
)

Channel conditions of branches, filters and goals.

View Source
const (
	NodeTrigger = "trigger"
	NodeDelay   = "delay"
	NodeEmail   = "email"
	NodeBranch  = "branch"
	NodeFilter  = "filter"
	NodeSplit   = "split"
	NodeWebhook = "webhook"
	NodeList    = "list"
	NodeGoal    = "goal"
	NodeExit    = "exit"
)

Node types, as named in the step palette.

View Source
const (
	TriggerJoinedList    = "joined_list"
	TriggerFormSubmitted = "form_submitted"
	TriggerTagAdded      = "tag_added"
	TriggerAPIEvent      = "api_event"
	TriggerDateField     = "date_field"
	// TriggerScoreCrosses starts when a contact's score rises to a
	// threshold or falls below it (contact scoring, see scoretrigger.go).
	TriggerScoreCrosses = "score_crosses"
	// TriggerMilestoneReached starts when a referrer reaches a referral
	// milestone (Grow), once per contact per milestone.
	TriggerMilestoneReached = "milestone_reached"
	// TriggerSegmentEntered and TriggerSegmentLeft start when a contact
	// enters or leaves a segment (review 2026-11 AT-10, from AU-16's
	// segment_member_events).
	TriggerSegmentEntered = "segment_entered"
	TriggerSegmentLeft    = "segment_left"
	// TriggerLinkClicked starts on a person's settled click in a campaign
	// or an automation email (AT-10).
	TriggerLinkClicked = "link_clicked"
)

Trigger kinds.

View Source
const (
	PathYes = "yes"
	PathNo  = "no"
)

Branch paths.

View Source
const (
	AnswerAny   = "any"
	AnswerIs    = "is"
	AnswerIsNot = "is_not"
)

Answer filters of the trigger.

View Source
const (
	// MigrationFinish lets contacts finish on the version they started; new
	// entrants start on the new one. The old version retires when empty.
	MigrationFinish = "finish"
	// MigrationMove moves contacts to the new version at their current step.
	MigrationMove = "move"
)

Migration choices for contacts already in a flow when a version is published.

View Source
const (
	TriggerOrderPlaced       = "order_placed"
	TriggerFirstOrder        = "first_order"
	TriggerAbandonedCheckout = "abandoned_checkout"

	// ConditionPlacedOrder is the goal "Placed an order".
	ConditionPlacedOrder = "placed_order"
)

Store triggers and the "Placed an order" goal (design expansion phase 7, Shopify and WooCommerce; internal/commerce writes the events).

  • Order placed: a contact's order, filtered by product, collection, a minimum total and "first order only".
  • First order: a contact's first order in the store.
  • Abandoned checkout: a checkout with no order after 1 to 24 hours. Only contacts who accepted marketing in the store enter (a filter that can't be removed: internal/commerce only sends their events), and the skip rule keeps out anyone who got an abandoned-cart email in the last 7 days. Placing the order exits the flow through the "Placed an order" goal.
View Source
const CodeAccessibilityBlocked = "accessibility_blocked"

CodeAccessibilityBlocked is the problem code of a publish the workspace's accessibility policy stops.

View Source
const ListDays = 30

ListDays is the stats window of the list and the canvas.

View Source
const NodeSMS = "sms"

NodeSMS is the "Send SMS" step.

View Source
const SignatureHeader = "X-ReputeCast-Signature"

SignatureHeader carries the HMAC-SHA256 signature of a webhook body: "t=<unix seconds>,v1=<hex of HMAC(secret, t + "." + body)>".

View Source
const TriggerBoughtProduct = "bought_product"

TriggerBoughtProduct is the trigger's kind, and the goal's.

View Source
const TriggerPollAnswered = "poll_answered"

TriggerPollAnswered is the trigger's kind.

Variables

View Source
var ErrBlockedAddress = errors.New("the address is private or internal")

ErrBlockedAddress is returned when a webhook would reach a private, loopback, link-local or otherwise internal address.

View Source
var ErrRevisionConflict = errors.New("revision conflict")

ErrRevisionConflict means someone saved the draft since the editor loaded it.

Functions

func Changes

func Changes(items []AutomationDiffItem) int

Changes counts the diff items that are changes (not the unchanged line).

func DurationText

func DurationText(d *AutomationDuration) string

DurationText reads "10 minutes", "1 day", "2 weeks".

func EmailShortRef

func EmailShortRef(name string) string

EmailShortRef is the last segment of the prefix: "Welcome · step 1" → "step 1".

func EmitFormSubmitted

func EmitFormSubmitted(ctx context.Context, q *store.Queries, workspaceID, contactID, formID uuid.UUID) error

EmitFormSubmitted queues a "form submitted" trigger event. The forms domain calls it inside the transaction that records the submission (after double opt-in when the form asks for it). List joins and new tags need no call: database triggers queue them.

func EmitLinkClicked

func EmitLinkClicked(ctx context.Context, q *store.Queries, ws, contact uuid.UUID, ref, url string, at time.Time) error

EmitLinkClicked queues a "Clicked a link" trigger event for a person's settled click in a campaign or an automation email (review 2026-11 AT-10), when a live flow of the workspace starts on one. ref is "campaign:<id>" or "email:<id>".

func Erasure

func Erasure() erasure.Source

Erasure ends the contact's runs and drops what their triggers carried (order details, API event payloads); runs stay for the flows' counts (review 2026-11 DP-1).

func ExitRefunded

func ExitRefunded(ctx context.Context, q *store.Queries, wsID, contactID, productID uuid.UUID, now time.Time) (int, error)

ExitRefunded makes a refunded buyer leave the "Bought a product" flows of that product, or of any product, they're in. It runs in the transaction that records the refund.

func GoalLabel

func GoalLabel(n AutomationNode, refs *Refs) string

GoalLabel is the short goal name for the automations list.

func IsStoreTrigger

func IsStoreTrigger(kind string) bool

IsStoreTrigger reports whether a trigger kind is a store's.

func MessageVars

func MessageVars(ctx context.Context, q *store.Queries, msg uuid.UUID) map[string]any

MessageVars is the Liquid data an automation email was queued with (nil: none). The sending engine adds it to the contact's.

func NewWebhookClient

func NewWebhookClient() *http.Client

NewWebhookClient returns the HTTP client webhook steps use: public addresses only, short timeouts, at most 3 redirects, no proxy from the environment (a proxy would hide the destination from the check).

func NodeRef

func NodeRef(g AutomationGraph, n AutomationNode, refs *Refs) string

NodeRef is how other text refers to a step: an email by its prefix ("Step 2"), anything else by its label or title.

func NodeTitle

func NodeTitle(g AutomationGraph, n AutomationNode, refs *Refs) string

NodeTitle is the bold line on the canvas node.

func Register

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

Register adds the automations operations.

func RegisterChannelStep

func RegisterChannelStep(nodeType string, c ChannelStep)

RegisterChannelStep plugs a channel's steps in (the app wires it).

func RegisterJobs

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

RegisterJobs adds the engine's workers and schedules to the job registry.

func Sign

func Sign(secret []byte, t time.Time, body []byte) string

Sign computes the signature header value for a body.

func TextIn

func TextIn(l i18n.Lang, t i18n.Text) string

TextIn writes one of the package's texts (a diff line's TitleText) in a reader's language.

func TriggerKindLabel

func TriggerKindLabel(kind string) string

TriggerKindLabel names a trigger kind ("Joined list").

func TriggerLabel

func TriggerLabel(t *AutomationTrigger, refs *Refs) string

TriggerLabel is the list's trigger column: "Joined list · Weekly Digest".

func TriggerRef

func TriggerRef(t *AutomationTrigger, refs *Refs) string

TriggerRef is what a trigger points at, for "Joined list · Weekly Digest".

func TypeName

func TypeName(t string) string

TypeName is the step type as the palette names it.

func WatchInterval

func WatchInterval(ms *int32) time.Duration

WatchInterval is how often a watched segment is evaluated (review 2026-11 AT-15): every 10 minutes, or twenty times as long as its last evaluation took when that is longer (a 90-second segment every 30 minutes), at most every 2 hours.

Types

type APIEvent

type APIEvent struct {
	Event      string
	Email      string
	ContactID  string
	Properties map[string]any
}

APIEvent is an event sent through the API for one contact.

type AccessibilityDraft

type AccessibilityDraft struct {
	Version     int
	LiveVersion *int
	Emails      []AccessibilityEmail
}

AccessibilityDraft is the version being published.

type AccessibilityEmail

type AccessibilityEmail struct {
	NodeID  string
	EmailID uuid.UUID
	Version int
	// Step names the step the way the publish dialog does ("Step 3 B").
	Step string
	MJML string
	HTML string
}

AccessibilityEmail is an email step of a version, as the checks see it.

type AccessibilityGate

type AccessibilityGate interface {
	CheckDraft(ctx context.Context, ws *store.Workspace, d AccessibilityDraft) (AccessibilityVerdict, error)
}

AccessibilityGate checks a version's emails before it's published.

type AccessibilityVerdict

type AccessibilityVerdict struct {
	// Checks are the dialog's accessibility badges.
	Checks []AutomationPublishCheck
	// Blocked is set when the workspace blocks publishing with serious
	// issues; Blocker says what to fix.
	Blocked bool
	Blocker string
}

AccessibilityVerdict is what the publish dialog shows.

type AutomationAlert

type AutomationAlert struct {
	ID           string                  `json:"id"`
	AutomationID string                  `json:"automationId"`
	Automation   string                  `json:"automation"`
	Kind         string                  `json:"kind" enum:"sending_held,step_failing"`
	NodeID       string                  `json:"nodeId,omitempty"`
	Title        string                  `json:"title"`
	Detail       string                  `json:"detail"`
	Since        time.Time               `json:"since"`
	Failures     int64                   `json:"failures"`
	Actions      []AutomationAlertAction `json:"actions"`
}

AutomationAlert is a flow problem shown above the list: sending held because no provider on the Automations route is healthy, or a step that keeps failing.

type AutomationAlertAction

type AutomationAlertAction struct {
	Label string `json:"label" example:"Open the step"`
	// Kind says where it goes: the step on the canvas, its delivery log, the
	// providers page or routing.
	Kind   string `json:"kind" enum:"open_step,step_log,providers,routing"`
	NodeID string `json:"nodeId,omitempty"`
}

AutomationAlertAction is a button on an alert card.

type AutomationCondition

type AutomationCondition struct {
	Kind string `json:"kind" enum:"opened,clicked,field,tag,list,event,bought_product,sms_consent,sms_clicked,sms_replied,placed_order"`
	// Opened / clicked: the email step (empty = any email in this flow), the
	// window and whether machine opens (Apple Mail Privacy Protection) count.
	Step        string              `json:"step,omitempty" maxLength:"40"`
	Within      *AutomationDuration `json:"within,omitempty"`
	HumanOnly   bool                `json:"humanOnly,omitempty"`
	URLContains string              `json:"urlContains,omitempty" maxLength:"200"`
	// Field: compare a contact field.
	Field string `json:"field,omitempty" maxLength:"64"`
	Op    string `json:"op,omitempty" maxLength:"16" doc:"equals, not_equals, contains, is_set, is_not_set, is_one_of (comma-separated values)"`
	Value string `json:"value,omitempty" maxLength:"200"`
	Tag   string `json:"tag,omitempty" maxLength:"64"`
	// List: member of this list (subscribed).
	ListID string `json:"listId,omitempty" maxLength:"40"`
	// Event: an API event arrived for the contact.
	Event string `json:"event,omitempty" maxLength:"100"`
	// Bought a product (products.go): the product, or any when empty.
	ProductID string `json:"productId,omitempty" maxLength:"40"`
	// Placed an order: in this store (any connected store when empty),
	// since the contact entered the flow.
	Store string `json:"store,omitempty" maxLength:"40"`
}

AutomationCondition is what a branch asks, a filter keeps or a goal waits for.

type AutomationContactRun

type AutomationContactRun struct {
	RunID        string `json:"runId"`
	AutomationID string `json:"automationId"`
	Name         string `json:"name"`
	// Status: active (in the flow), completed, exited, goal or failed.
	Status string `json:"status" enum:"active,completed,exited,goal,failed"`
	// Step is where they are, or where they finished.
	Step       string     `json:"step"`
	NodeID     string     `json:"nodeId"`
	ExitReason string     `json:"exitReason,omitempty"`
	EnteredAt  time.Time  `json:"enteredAt"`
	StepSince  time.Time  `json:"stepSince"`
	FinishedAt *time.Time `json:"finishedAt,omitempty"`
}

AutomationContactRun is one flow a contact is in or went through.

type AutomationContactRuns

type AutomationContactRuns struct {
	Items []AutomationContactRun `json:"items"`
}

AutomationContactRuns lists a contact's flows.

type AutomationCreated

type AutomationCreated struct {
	ID string `json:"id"`
}

AutomationCreated is the result of a create or duplicate.

type AutomationDetail

type AutomationDetail struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Status      string `json:"status" enum:"draft,live,paused"`
	TemplateKey string `json:"templateKey,omitempty"`
	LiveVersion *int   `json:"liveVersion,omitempty"`
	// DraftVersion is the version the canvas edits; Revision guards
	// concurrent edits (send it back with each save).
	DraftVersion int             `json:"draftVersion"`
	Revision     int64           `json:"revision"`
	PublishedAt  *time.Time      `json:"publishedAt,omitempty"`
	PublishedBy  string          `json:"publishedBy,omitempty"`
	PausedAt     *time.Time      `json:"pausedAt,omitempty"`
	PausedBy     string          `json:"pausedBy,omitempty"`
	PauseReason  string          `json:"pauseReason,omitempty"`
	Graph        AutomationGraph `json:"graph"`
	// LiveNodeIDs are the steps of the live version (others are "new in vN").
	LiveNodeIDs []string `json:"liveNodeIds"`
	// PublishedNodeIDs are steps that were in any published version (others
	// have "no stats until published").
	PublishedNodeIDs []string               `json:"publishedNodeIds"`
	Changes          int                    `json:"changes" doc:"Unpublished changes, as counted by the version diff"`
	Issues           []AutomationGraphIssue `json:"issues"`
	Route            AutomationRoute        `json:"route"`
	InFlow           int64                  `json:"inFlow"`
	// Overdue counts, while the flow is paused, the contacts whose wait
	// ended meanwhile: resuming asks what happens to them (AT-4).
	Overdue   int64     `json:"overdue"`
	UpdatedAt time.Time `json:"updatedAt"`
}

AutomationDetail is a flow as the editor needs it: its settings, the draft graph and what the canvas marks on it.

type AutomationDiff

type AutomationDiff struct {
	From    int                  `json:"from"`
	To      int                  `json:"to"`
	Items   []AutomationDiffItem `json:"items"`
	Changes int                  `json:"changes"`
}

type AutomationDiffItem

type AutomationDiffItem struct {
	Kind    string   `json:"kind" enum:"added,changed,removed,unchanged"`
	Title   string   `json:"title"`
	Detail  string   `json:"detail,omitempty"`
	NodeIDs []string `json:"nodeIds"`
	// TitleText and DetailText are the title and detail as texts, for
	// readers in other languages (TextIn writes them).
	TitleText  i18n.Text `json:"-"`
	DetailText i18n.Text `json:"-"`
}

AutomationDiffItem is one line of a version diff: what was added, changed or removed, and a last line listing what stayed the same.

func Diff

func Diff(from, to AutomationGraph, dc DiffContext) []AutomationDiffItem

Diff compares two versions of a flow, step by step: steps keep their ids across versions, so a step is changed when its settings differ, added or removed when its id appears or disappears, and rewired when it now leads somewhere else. Positions on the canvas don't count as changes.

type AutomationDraftSaved

type AutomationDraftSaved struct {
	DraftVersion int                    `json:"draftVersion"`
	Revision     int64                  `json:"revision"`
	Changes      int                    `json:"changes" doc:"Unpublished changes compared with the live version"`
	Issues       []AutomationGraphIssue `json:"issues"`
}

AutomationDraftSaved is the result of a save.

type AutomationDuration

type AutomationDuration struct {
	Amount int    `json:"amount" minimum:"0" maximum:"100000"`
	Unit   string `json:"unit" enum:"minutes,hours,days,weeks"`
}

AutomationDuration is a delay or a time window.

func (AutomationDuration) Duration

func (d AutomationDuration) Duration() time.Duration

type AutomationEdge

type AutomationEdge struct {
	ID     string             `json:"id" minLength:"1" maxLength:"80"`
	Source string             `json:"source" minLength:"1" maxLength:"40"`
	Target string             `json:"target" minLength:"1" maxLength:"40"`
	Data   AutomationEdgeData `json:"data"`
}

AutomationEdge connects one step to the next.

type AutomationEdgeData

type AutomationEdgeData struct {
	// Path is "yes" or "no" after a branch, the variant key after a split.
	Path string `json:"path,omitempty" maxLength:"16"`
}

AutomationEdgeData says which path out of a branch or split the edge is.

type AutomationEmailContent

type AutomationEmailContent struct {
	ID            string `json:"id"`
	Name          string `json:"name"`
	Version       int    `json:"version"`
	LatestVersion int    `json:"latestVersion"`
	Subject       string `json:"subject"`
	Preheader     string `json:"preheader"`
	HTML          string `json:"html"`
	Text          string `json:"text"`
}

AutomationEmailContent is one version of an email, for previews.

type AutomationEmailOption

type AutomationEmailOption struct {
	ID            string    `json:"id"`
	Name          string    `json:"name"`
	LatestVersion int       `json:"latestVersion"`
	Subject       string    `json:"subject"`
	UpdatedAt     time.Time `json:"updatedAt"`
}

AutomationEmailOption is an email a send step can use.

type AutomationEmailPreview

type AutomationEmailPreview struct {
	Subject   string `json:"subject"`
	Preheader string `json:"preheader"`
	HTML      string `json:"html"`
	// Contact is who it was personalized as ("Maya Patel"), empty for none.
	Contact  string   `json:"contact"`
	Problems []string `json:"problems"`
}

AutomationEmailPreview is the email as the contact gets it.

type AutomationEmailPreviewInput

type AutomationEmailPreviewInput struct {
	Version   int    `json:"version,omitempty" minimum:"0" doc:"Defaults to the latest version"`
	ContactID string `json:"contactId,omitempty" format:"uuid" doc:"Personalize as this contact; without one the fallbacks show"`
}

AutomationEmailPreviewInput picks the version and the contact.

type AutomationEmailStep

type AutomationEmailStep struct {
	EmailID      string `json:"emailId,omitempty" maxLength:"40"`
	EmailVersion int    `json:"emailVersion,omitempty" minimum:"0"`
	Subject      string `json:"subject,omitempty" maxLength:"250"`
	// Route is empty for the Automations route, or a sending provider id to override it.
	Route      string                `json:"route,omitempty" maxLength:"40"`
	SendWindow *AutomationSendWindow `json:"sendWindow,omitempty"`
	// SkipRecentHours skips the email when the contact got any email in the last N hours (0 = off).
	SkipRecentHours int `json:"skipRecentHours,omitempty" minimum:"0" maximum:"720"`
	// SkipListID skips the email for members of this list.
	SkipListID string `json:"skipListId,omitempty" maxLength:"40"`
	// OverCap is what happens when the contact is over the workspace's
	// marketing cap (review 2026-11 AT-9): "wait" (default) until they're
	// under it, or "skip" the email.
	OverCap string `json:"overCap,omitempty" enum:"wait,skip,"`
}

AutomationEmailStep is a "Send email" step.

type AutomationEmailTestInput

type AutomationEmailTestInput struct {
	AutomationEmailPreviewInput
	To []string `json:"to" minItems:"1" maxItems:"10"`
	// AutomationID is the flow the test is for, for the audit log.
	AutomationID string `json:"automationId,omitempty" maxLength:"40"`
}

AutomationEmailTestInput is where a test goes and who it's personalized as.

type AutomationEmailTestResult

type AutomationEmailTestResult struct {
	Sent     []string `json:"sent"`
	Provider string   `json:"provider"`
}

AutomationEmailTestResult says where the test went.

type AutomationEventResult

type AutomationEventResult struct {
	Accepted  bool   `json:"accepted"`
	ContactID string `json:"contactId"`
	Flows     int    `json:"flows" doc:"Live automations triggered by this event"`
}

AutomationEventResult says which contact the event was recorded for.

type AutomationFieldOption

type AutomationFieldOption struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Type  string `json:"type"`
}

AutomationFieldOption is a contact field a condition or date trigger can use.

type AutomationFormOption

type AutomationFormOption struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	Slug string `json:"slug"`
}

AutomationFormOption is a signup form a trigger can listen to.

type AutomationGoal

type AutomationGoal struct {
	Label   string   `json:"label" example:"Clicked docs"`
	Percent *float64 `json:"percent,omitempty" doc:"Contacts who reached the goal, % of those who entered in the window"`
}

AutomationGoal is the list's goal column: "Clicked docs · 24%".

type AutomationGoalCount

type AutomationGoalCount struct {
	Name  string `json:"name" example:"welcome"`
	Count int64  `json:"count"`
}

AutomationGoalCount is goals reached by one flow.

type AutomationGraph

type AutomationGraph struct {
	Nodes []AutomationNode `json:"nodes" maxItems:"200"`
	Edges []AutomationEdge `json:"edges" maxItems:"400"`
}

AutomationGraph is an automation as React Flow stores it: typed nodes with a position and data, connected by edges. Branch and split edges name the path they take ("yes"/"no", or the variant key).

func Layout

Layout returns g with every node positioned.

func ParseGraph

func ParseGraph(raw []byte) (AutomationGraph, error)

ParseGraph decodes a stored graph. A null or empty document is an empty graph.

func (AutomationGraph) Depths

func (g AutomationGraph) Depths() map[string]int

Depths returns each node's distance from the trigger (longest path), used to stagger the canvas entrance and to order steps.

func (AutomationGraph) HasCycle

func (g AutomationGraph) HasCycle() bool

HasCycle reports whether the graph loops back on itself.

func (AutomationGraph) In

In returns the edges entering id.

func (AutomationGraph) MustJSON

func (g AutomationGraph) MustJSON() json.RawMessage

MustJSON encodes a graph for storage.

func (AutomationGraph) Next

func (g AutomationGraph) Next(id string) string

Next returns the single next node of a non-branching step ("" at the end).

func (AutomationGraph) NextOnPath

func (g AutomationGraph) NextOnPath(id, path string) string

NextOnPath returns the node reached through path out of a branch or split.

func (AutomationGraph) Node

Node returns the node with id, or nil.

func (AutomationGraph) Order

func (g AutomationGraph) Order() []string

Order returns node ids breadth-first from the trigger, then any node not reachable from it, so lists read top to bottom like the canvas.

func (AutomationGraph) Out

Out returns the edges leaving id in the order they were drawn.

func (AutomationGraph) Prev

func (g AutomationGraph) Prev(id string) string

Prev returns the first node that leads to id ("" when none).

func (AutomationGraph) Trigger

func (g AutomationGraph) Trigger() *AutomationNode

Trigger returns the trigger node, or nil.

type AutomationGraphIssue

type AutomationGraphIssue struct {
	NodeID   string `json:"nodeId,omitempty"`
	EdgeID   string `json:"edgeId,omitempty"`
	Code     string `json:"code"`
	Severity string `json:"severity" enum:"error,warning"`
	Message  string `json:"message"`
}

AutomationGraphIssue is a problem that blocks publishing (severity "error") or is worth a look ("warning").

func Errors

func Errors(issues []AutomationGraphIssue) []AutomationGraphIssue

Errors returns only blocking issues.

func Validate

func Validate(g AutomationGraph, refs *Refs) []AutomationGraphIssue

Validate checks the structure (one trigger, every step reachable, every branch path connected, no loops) and each step's settings. refs may be nil to skip reference checks. Its messages are in English; validate writes them in a reader's language.

type AutomationIDParam

type AutomationIDParam struct {
	api.WorkspaceInput
	ID string `path:"id" doc:"Automation id" maxLength:"40"`
}

type AutomationList

type AutomationList struct {
	Items  []AutomationListItem   `json:"items"`
	Counts AutomationStatusCounts `json:"counts"`
	Route  AutomationRoute        `json:"route"`
	Alerts []AutomationAlert      `json:"alerts"`
	// Days is the stats window of the list (30).
	Days int `json:"days"`
}

AutomationList is the automations screen.

type AutomationListAction

type AutomationListAction struct {
	Kind   string `json:"kind" enum:"add_list,remove_list,add_tag,remove_tag,unsubscribe_all"`
	ListID string `json:"listId,omitempty" maxLength:"40"`
	Tag    string `json:"tag,omitempty" maxLength:"64"`
}

AutomationListAction adds or removes a list or tag.

type AutomationListItem

type AutomationListItem struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Status      string `json:"status" enum:"draft,live,paused"`
	LiveVersion *int   `json:"liveVersion,omitempty"`
	// DraftVersion is the version being edited (equals the live version when
	// there are no unpublished changes).
	DraftVersion int        `json:"draftVersion"`
	PublishedAt  *time.Time `json:"publishedAt,omitempty"`
	PausedAt     *time.Time `json:"pausedAt,omitempty"`
	PausedBy     string     `json:"pausedBy,omitempty"`
	PauseReason  string     `json:"pauseReason,omitempty"`
	// Trigger reads "Joined list · Weekly Digest".
	Trigger string `json:"trigger"`
	// Steps counts the steps of the live version (the draft for flows never published).
	Steps int `json:"steps"`
	// Stats over the list window; absent for flows that were never published.
	Entered    *int64          `json:"entered,omitempty"`
	InFlow     *int64          `json:"inFlow,omitempty"`
	Completed  *float64        `json:"completed,omitempty" doc:"% of entrants who finished the flow (goal or end)"`
	HumanOpens *float64        `json:"humanOpens,omitempty" doc:"Human opens, % of delivered"`
	Goal       *AutomationGoal `json:"goal,omitempty"`
	// UnpublishedChanges is true when a draft differs from the live version.
	UnpublishedChanges bool `json:"unpublishedChanges"`
	// Revenue is the store orders credited to the flow's emails over the
	// list window; absent when the workspace has no store.
	Revenue *AutomationRevenue `json:"revenue,omitempty"`
	// Channels are the channels the flow's steps send on (email, sms),
	// for the row's icons; ChannelCost is what its texts cost over the
	// list window (design expansion phase 8).
	Channels    []string `json:"channels"`
	ChannelCost *float64 `json:"channelCost,omitempty"`
}

AutomationListItem is one row of the automations list.

type AutomationMilestoneOption

type AutomationMilestoneOption struct {
	ID        string `json:"id"`
	ProgramID string `json:"programId"`
	ListName  string `json:"listName" example:"Weekly Digest" doc:"The list of the milestone's referral program"`
	Count     int    `json:"count" example:"3"`
	Reward    string `json:"reward" example:"The Acme Field Guide"`
	Name      string `json:"name" example:"3 referrals · The Acme Field Guide"`
}

AutomationMilestoneOption is a referral milestone a "Reached a milestone" trigger can start on.

type AutomationNode

type AutomationNode struct {
	ID       string                 `json:"id" minLength:"1" maxLength:"40" pattern:"^[A-Za-z0-9_-]+$"`
	Type     string                 `json:"type" enum:"trigger,delay,email,branch,filter,split,webhook,list,goal,exit,sms,push,whatsapp"`
	Position AutomationNodePosition `json:"position"`
	Data     AutomationNodeData     `json:"data"`
}

AutomationNode is one step of a flow.

func (AutomationNode) Paths

func (n AutomationNode) Paths() []string

Paths returns the paths a branch or split must connect.

func (AutomationNode) Terminal

func (n AutomationNode) Terminal() bool

Terminal reports whether a step ends the flow.

type AutomationNodeData

type AutomationNodeData struct {
	// Label is a short name used where the step is referenced (diffs, stats, goals).
	Label     string                   `json:"label,omitempty" maxLength:"80"`
	Trigger   *AutomationTrigger       `json:"trigger,omitempty"`
	Delay     *AutomationDuration      `json:"delay,omitempty"`
	Email     *AutomationEmailStep     `json:"email,omitempty"`
	Condition *AutomationCondition     `json:"condition,omitempty" doc:"Branch, filter and goal condition"`
	Variants  []AutomationSplitVariant `json:"variants,omitempty" maxItems:"5"`
	Webhook   *AutomationWebhook       `json:"webhook,omitempty"`
	Action    *AutomationListAction    `json:"action,omitempty"`
	// SMS is a "Send SMS" step (channels.go).
	SMS *AutomationSMSStep `json:"sms,omitempty"`
	// Push and WhatsApp are "Send push" and "Send WhatsApp" steps (X22).
	Push     *AutomationPushStep     `json:"push,omitempty"`
	WhatsApp *AutomationWhatsAppStep `json:"whatsapp,omitempty"`
}

AutomationNodeData holds a step's settings; which block is set depends on the type.

type AutomationNodePosition

type AutomationNodePosition struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

AutomationNodePosition is a node's top-left corner on the canvas.

type AutomationOptionItem

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

AutomationOptionItem is a choice in a step's settings.

type AutomationOptions

type AutomationOptions struct {
	Lists     []AutomationOptionItem    `json:"lists"`
	Forms     []AutomationFormOption    `json:"forms"`
	Fields    []AutomationFieldOption   `json:"fields"`
	Emails    []AutomationEmailOption   `json:"emails"`
	Providers []AutomationRouteProvider `json:"providers"`
	Tags      []string                  `json:"tags"`
	Events    []string                  `json:"events"`
	// ScoreBands are the applied score thresholds, for the "Score
	// crosses…" trigger; null while the workspace has no scoring (X13).
	ScoreBands *scoring.ScoringBands `json:"scoreBands,omitempty"`
	// Products are the digital products, for "Bought a product" (X19):
	// published first, then the others that ever sold.
	Products []AutomationOptionItem `json:"products"`
	// Milestones are the referral milestones the "Reached a milestone"
	// trigger can start on (Grow).
	Milestones []AutomationMilestoneOption `json:"milestones"`
	// Segments and Campaigns are what "Enters a segment" and "Clicked a
	// link" can start on (review 2026-11 AT-10).
	Segments  []AutomationSegmentOption `json:"segments"`
	Campaigns []AutomationOptionItem    `json:"campaigns"`
}

AutomationOptions are the choices the step settings offer.

type AutomationPathCount

type AutomationPathCount struct {
	Path  string `json:"path" example:"yes"`
	Count int64  `json:"count"`
}

AutomationPathCount is how many contacts took one path out of a branch or split.

type AutomationProviderSends

type AutomationProviderSends struct {
	ProviderID string `json:"providerId"`
	Provider   string `json:"provider"`
	Short      string `json:"short"`
	Sent       int64  `json:"sent"`
	// Fallback is true for the Automations route's fallback provider.
	Fallback bool `json:"fallback"`
	// LastDay is the last day it sent in the window.
	LastDay string `json:"lastDay,omitempty" format:"date" example:"2026-10-02"`
}

AutomationProviderSends is how many automation emails a provider sent.

type AutomationPublishCheck

type AutomationPublishCheck struct {
	Status string `json:"status" enum:"ok,warn,bad"`
	Label  string `json:"label"`
}

AutomationPublishCheck is one pre-publish check badge.

type AutomationPublishPreview

type AutomationPublishPreview struct {
	Name            string                   `json:"name"`
	FromVersion     *int                     `json:"fromVersion,omitempty"`
	ToVersion       int                      `json:"toVersion"`
	LivePublishedAt *time.Time               `json:"livePublishedAt,omitempty"`
	LivePublishedBy string                   `json:"livePublishedBy,omitempty"`
	Items           []AutomationDiffItem     `json:"items"`
	Changes         int                      `json:"changes"`
	InFlow          int64                    `json:"inFlow"`
	FinishEstimate  string                   `json:"finishEstimate" example:"about 9 days"`
	MoveImpact      string                   `json:"moveImpact"`
	Checks          []AutomationPublishCheck `json:"checks"`
	CanPublish      bool                     `json:"canPublish"`
	Blocker         string                   `json:"blocker,omitempty"`
	// Requires are permissions the flow's channel steps need that the
	// viewer lacks: publishing asks for approval instead ("This flow has an
	// SMS step. Publishing needs sms:send.").
	Requires []string `json:"requires"`
	// ChannelSteps counts the flow's steps by channel ("sms": 1).
	ChannelSteps map[string]int `json:"channelSteps"`
}

AutomationPublishPreview is the publish dialog: the diff, what happens to contacts already in the flow, and the pre-publish checks.

type AutomationPublishResult

type AutomationPublishResult struct {
	Status     string `json:"status" enum:"published,approval_required"`
	Version    int    `json:"version"`
	ApprovalID string `json:"approvalId,omitempty"`
	Message    string `json:"message,omitempty"`
}

AutomationPublishResult says whether the version went live or is waiting for approval.

type AutomationPushStep

type AutomationPushStep struct {
	Title   string `json:"title,omitempty" maxLength:"200"`
	Message string `json:"message,omitempty" maxLength:"500"`
	// Link is what the notification opens; Button an optional button to it.
	Link   string `json:"link,omitempty" maxLength:"2000"`
	Button string `json:"button,omitempty" maxLength:"40"`
	// ExpiryMinutes is how long the push services keep it for an offline
	// browser (default 4 hours).
	ExpiryMinutes int `json:"expiryMinutes,omitempty" minimum:"0" maximum:"40320"`
	// Outside quiet hours: "wait" for the window (default) or "skip".
	Outside string `json:"outside,omitempty" enum:"wait,skip,"`
}

AutomationPushStep is a "Send push" step: a notification to the contact's linked browser subscriptions. It's skipped when the contact has none.

type AutomationRevenue

type AutomationRevenue struct {
	Orders   int64  `json:"orders"`
	Revenue  int64  `json:"revenue" doc:"In minor units of the currency"`
	Currency string `json:"currency"`
}

AutomationRevenue is the store orders credited to a flow's emails.

type AutomationRoute

type AutomationRoute struct {
	Label    string                    `json:"label" example:"SES, failover Postmark"`
	Healthy  bool                      `json:"healthy" doc:"A provider on the route can send right now"`
	Primary  []AutomationRouteProvider `json:"primary"`
	Fallback *AutomationRouteProvider  `json:"fallback,omitempty"`
}

AutomationRoute summarizes the Automations route: "SES, failover Postmark".

type AutomationRouteProvider

type AutomationRouteProvider struct {
	ID      string `json:"id"`
	Name    string `json:"name" example:"Amazon SES"`
	Short   string `json:"short" example:"SES"`
	Adapter string `json:"adapter"`
	Status  string `json:"status" doc:"healthy, degraded, down, sandbox, warming_up or paused"`
	Detail  string `json:"detail,omitempty"`
	Weight  int    `json:"weight,omitempty"`
	// DownSince and DownReason (outage or auth) are set while the provider is down.
	DownSince  *time.Time `json:"downSince,omitempty"`
	DownReason string     `json:"downReason,omitempty"`
	// LastErrorStatus is the HTTP status of its last failed call (401).
	LastErrorStatus int `json:"lastErrorStatus,omitempty"`
}

AutomationRouteProvider is a sending provider on the Automations route.

type AutomationSMSStep

type AutomationSMSStep struct {
	// Body is the text between the rules' brand prefix and opt-out text,
	// with personalization tokens and links.
	Body string `json:"body,omitempty" maxLength:"1000"`
	// ConsentListID is the list whose SMS consent the step needs: contacts
	// without it are skipped. The rule can't be removed.
	ConsentListID string `json:"consentListId,omitempty" maxLength:"40"`
	// Outside quiet hours: "wait" for the window (default) or "skip".
	Outside string `json:"outside,omitempty" enum:"wait,skip,"`
	// SkipRecentHours skips the text when the contact got a text in the
	// last N hours (0 = off).
	SkipRecentHours int `json:"skipRecentHours,omitempty" minimum:"0" maximum:"720"`
	// NoOptOut leaves the rules' opt-out text out of this step's text
	// (it's on by default in steps; the rules can require it).
	NoOptOut bool `json:"noOptOut,omitempty"`
}

AutomationSMSStep is a "Send SMS" step.

type AutomationSegmentOption

type AutomationSegmentOption struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	// CheckMinutes is how often the segment is evaluated: 10, or longer for
	// a segment whose evaluation takes long; EvalSeconds is how long the
	// last one took, when it was evaluated.
	CheckMinutes int `json:"checkMinutes"`
	EvalSeconds  int `json:"evalSeconds,omitempty"`
}

AutomationSegmentOption is a segment an "Enters a segment" trigger can start on, with how often it is checked (review 2026-11 AT-15).

type AutomationSendWindow

type AutomationSendWindow struct {
	Enabled bool   `json:"enabled"`
	Start   string `json:"start" maxLength:"5" doc:"HH:MM, recipient-local"`
	End     string `json:"end" maxLength:"5"`
}

AutomationSendWindow holds email until the recipient's local time is inside it.

type AutomationSequenceStep

type AutomationSequenceStep struct {
	NodeID       string `json:"nodeId"`
	Sent         int64  `json:"sent"`
	Delivered    int64  `json:"delivered"`
	OpenedHuman  int64  `json:"openedHuman"`
	Clicked      int64  `json:"clicked"`
	Unsubscribed int64  `json:"unsubscribed"`
	// Next counts the contacts who reached the next email (or emails,
	// after a branch); absent for the last one.
	Next *int64 `json:"next,omitempty"`
}

AutomationSequenceStep is one email of a flow's sequence.

type AutomationSplitVariant

type AutomationSplitVariant struct {
	Key    string `json:"key" minLength:"1" maxLength:"4"`
	Weight int    `json:"weight" minimum:"0" maximum:"100"`
}

AutomationSplitVariant is one arm of an A/B split.

type AutomationStarterTemplate

type AutomationStarterTemplate struct {
	Key  string `json:"key" enum:"welcome-series,re-engagement,onboarding,abandoned-cart"`
	Name string `json:"name"`
	// Summary is the card text in the list's "Starter templates" section.
	Summary string `json:"summary"`
	// Outline is the card text in the empty state ("Joined list → wait 10 min → …").
	Outline string `json:"outline"`
	// Steps counts the steps the template creates.
	Steps int `json:"steps"`
	// Preview lists the step types along the main path, for the dot strip.
	Preview []string `json:"preview"`
}

AutomationStarterTemplate is one of the starter flows offered on the automations list and in the empty state. Each opens as a draft; every step is editable.

func Templates

func Templates() []AutomationStarterTemplate

Templates lists the starter templates, in English.

type AutomationStats

type AutomationStats struct {
	Days  int       `json:"days"`
	Since time.Time `json:"since"`
	// Entered counts contacts who entered through the trigger in the window.
	Entered int64                 `json:"entered"`
	InFlow  int64                 `json:"inFlow"`
	Steps   []AutomationStepStats `json:"steps"`
	// Sequence is the flow's emails in order with how many go on to the
	// next one (review 2026-11 AT-13).
	Sequence []AutomationSequenceStep `json:"sequence"`
}

AutomationStats is the live stats of a flow, per step.

type AutomationStatusCounts

type AutomationStatusCounts struct {
	All    int64 `json:"all"`
	Live   int64 `json:"live"`
	Paused int64 `json:"paused"`
	Drafts int64 `json:"drafts"`
}

AutomationStatusCounts feeds the All · Live · Paused · Drafts filters.

type AutomationStepContact

type AutomationStepContact struct {
	RunID     string `json:"runId"`
	ContactID string `json:"contactId"`
	Email     string `json:"email"`
	Name      string `json:"name"`
	// Since is when they reached the step; Until when they move on (a
	// delay or a window), empty when they wait for something else.
	Since time.Time  `json:"since"`
	Until *time.Time `json:"until,omitempty"`
	// Wait is what they wait for: delay, branch, window, webhook, cap; empty
	// while they're about to move on.
	Wait      string    `json:"wait" enum:"delay,branch,window,webhook,cap,"`
	EnteredAt time.Time `json:"enteredAt"`
}

AutomationStepContact is one contact at a step.

type AutomationStepContacts

type AutomationStepContacts struct {
	Total int64                   `json:"total"`
	Items []AutomationStepContact `json:"items"`
	// Next is the cursor of the next page; empty on the last.
	Next string `json:"next,omitempty"`
}

AutomationStepContacts is a page of the contacts at a step.

type AutomationStepStats

type AutomationStepStats struct {
	NodeID string `json:"nodeId"`
	// Entered counts arrivals; InFlowNow counts contacts at the step right now.
	Entered      int64                     `json:"entered"`
	InFlowNow    int64                     `json:"inFlowNow"`
	Completed    int64                     `json:"completed" doc:"Moved on to the next step"`
	Exited       int64                     `json:"exited" doc:"Finished the flow at this step"`
	Dropped      int64                     `json:"dropped" doc:"Left early: filtered out, unsubscribed or removed"`
	GoalReached  int64                     `json:"goalReached"`
	Skipped      int64                     `json:"skipped" doc:"Emails skipped by a rule, or because the contact paused email on the preference center"`
	Failed       int64                     `json:"failed" doc:"Webhook calls that failed"`
	Sent         int64                     `json:"sent"`
	Delivered    int64                     `json:"delivered"`
	Bounced      int64                     `json:"bounced"`
	Complained   int64                     `json:"complained"`
	Opened       int64                     `json:"opened"`
	OpenedHuman  int64                     `json:"openedHuman"`
	Clicked      int64                     `json:"clicked"`
	Unsubscribed int64                     `json:"unsubscribed"`
	Paths        []AutomationPathCount     `json:"paths"`
	Providers    []AutomationProviderSends `json:"providers"`
}

AutomationStepStats is one step's numbers over the stats window.

type AutomationSummary

type AutomationSummary struct {
	Days       int                       `json:"days"`
	InFlow     int64                     `json:"inFlow"`
	LiveCount  int64                     `json:"liveCount"`
	Sent       int64                     `json:"sent"`
	SentBy     []AutomationProviderSends `json:"sentBy"`
	HumanOpens *float64                  `json:"humanOpens,omitempty"`
	Clicks     *float64                  `json:"clicks,omitempty"`
	Goals      int64                     `json:"goals"`
	GoalsBy    []AutomationGoalCount     `json:"goalsBy"`
}

AutomationSummary is the KPI row above the list.

type AutomationTemplates

type AutomationTemplates struct {
	Templates []AutomationStarterTemplate `json:"templates"`
}

AutomationTemplates lists the starter templates.

type AutomationTrigger

type AutomationTrigger struct {
	Kind string `` /* 223-byte string literal not displayed */
	// Joined list: the list, whether to wait for double opt-in, and whether
	// contacts added by an import count.
	ListID         string `json:"listId,omitempty" maxLength:"40"`
	ConfirmedOnly  bool   `json:"confirmedOnly,omitempty"`
	IncludeImports bool   `json:"includeImports,omitempty"`
	FormID         string `json:"formId,omitempty" maxLength:"40"`
	Tag            string `json:"tag,omitempty" maxLength:"64"`
	Event          string `json:"event,omitempty" maxLength:"100"`
	// Date field: the contact field, days before (negative) or after the date,
	// whether it repeats every year, and the local time ("09:00").
	Field      string `json:"field,omitempty" maxLength:"64"`
	OffsetDays int    `json:"offsetDays,omitempty" minimum:"-365" maximum:"365"`
	Yearly     bool   `json:"yearly,omitempty"`
	At         string `json:"at,omitempty" maxLength:"5"`
	// Reentry: "once" (default) lets a contact through the flow one time (a
	// yearly date trigger: once a year); "always" lets them enter again
	// after they leave; "days" at most once every ReentryDays days
	// (review 2026-11 AT-6).
	Reentry     string `json:"reentry,omitempty" maxLength:"8"`
	ReentryDays int    `json:"reentryDays,omitempty" minimum:"0" maximum:"3650"`
	// ExitOnLeave ends a Joined list flow's runs when the contact leaves
	// the list (AT-8).
	ExitOnLeave bool `json:"exitOnLeave,omitempty"`
	// ContactTime fires a date trigger at At in each contact's own time
	// zone, the workspace's when they have none (AT-7).
	ContactTime bool `json:"contactTime,omitempty"`
	// Enters or leaves a segment: the segment (AT-10).
	SegmentID string `json:"segmentId,omitempty" maxLength:"40"`
	// Clicked a link: in a campaign ("campaign:<id>") or an automation
	// email ("email:<id>"), any of them when empty, and optionally only
	// links whose address contains URLContains (AT-10).
	Source      string `json:"source,omitempty" maxLength:"60"`
	URLContains string `json:"urlContains,omitempty" maxLength:"200"`
	// Score crosses: the score rises to Threshold or more, or falls below
	// it, at most once per contact in OnceInDays days (0: no limit).
	Direction  string `json:"direction,omitempty" enum:"rises,falls"`
	Threshold  int    `json:"threshold,omitempty" minimum:"0" maximum:"100"`
	OnceInDays int    `json:"onceInDays,omitempty" minimum:"0" maximum:"3650"`
	// Answered a poll or survey (polls.go): the poll or survey ("poll:<id>",
	// "survey:<id>"), the answers that start it (keys, with is or is not),
	// and whether a changed answer starts it again.
	Poll     string `json:"poll,omitempty" maxLength:"60"`
	AnswerOp string `json:"answerOp,omitempty" enum:"any,is,is_not"`
	Answers  []int  `json:"answers,omitempty" maxItems:"11"`
	OnChange bool   `json:"onChange,omitempty"`
	// Bought a product (products.go): the product, or any when empty.
	ProductID string `json:"productId,omitempty" maxLength:"40"`
	// Reached a milestone (Grow): the referral program and its milestone,
	// or any of its milestones when the milestone is empty (any program's
	// when both are).
	ProgramID   string `json:"programId,omitempty" maxLength:"40"`
	MilestoneID string `json:"milestoneId,omitempty" maxLength:"40"`
	// Store triggers (stores.go): the connected store; Order placed's
	// filters (products, collections, a minimum total in minor units, the
	// contact's first order only); Abandoned checkout's delay (1 to 24 hours)
	// and skip rule (no entry for N days after an abandoned-cart email).
	Store       string   `json:"store,omitempty" maxLength:"40"`
	Products    []string `json:"products,omitempty" maxItems:"20"`
	Collections []string `json:"collections,omitempty" maxItems:"20"`
	MinTotal    int64    `json:"minTotal,omitempty" minimum:"0"`
	FirstOnly   bool     `json:"firstOnly,omitempty"`
	AfterHours  int      `json:"afterHours,omitempty" minimum:"0" maximum:"24"`
	SkipDays    *int     `json:"skipDays,omitempty" minimum:"0" maximum:"30"`
	// Also holds up to two more triggers, any of which enrols (review
	// 2026-11 AT-11). Re-entry and leaving with the list are the first
	// trigger's; the others never carry their own Also.
	Also []AutomationTrigger `json:"also,omitempty" maxItems:"2"`
}

AutomationTrigger says which contacts enter the flow.

func (*AutomationTrigger) Triggers

func (t *AutomationTrigger) Triggers() []AutomationTrigger

Triggers returns a flow's triggers: the first, then those in its Also.

type AutomationVersionGraph

type AutomationVersionGraph struct {
	Version int             `json:"version"`
	Graph   AutomationGraph `json:"graph"`
}

AutomationVersionGraph is one version's graph (read-only).

type AutomationVersionItem

type AutomationVersionItem struct {
	Version     int        `json:"version"`
	Status      string     `json:"status" enum:"draft,live,retiring,retired" doc:"retiring: replaced, but contacts are still finishing on it"`
	CreatedAt   time.Time  `json:"createdAt"`
	CreatedBy   string     `json:"createdBy"`
	PublishedAt *time.Time `json:"publishedAt,omitempty"`
	PublishedBy string     `json:"publishedBy,omitempty"`
	RetiredAt   *time.Time `json:"retiredAt,omitempty"`
	Summary     string     `json:"summary"`
	// FromCreation is true when the summary says how the flow was created
	// (from a template, a blank canvas or a page) rather than what changed.
	FromCreation bool  `json:"fromCreation,omitempty"`
	InFlow       int64 `json:"inFlow"`
}

AutomationVersionItem is one row of the version history.

type AutomationVersions

type AutomationVersions struct {
	Name     string                  `json:"name"`
	Versions []AutomationVersionItem `json:"versions"`
}

AutomationVersions is the version history of a flow.

type AutomationWebhook

type AutomationWebhook struct {
	Name      string `json:"name,omitempty" maxLength:"80"`
	URL       string `json:"url,omitempty" maxLength:"2000"`
	Method    string `json:"method,omitempty" maxLength:"6"`
	HasSecret bool   `json:"hasSecret,omitempty" readOnly:"true"`
	// Demo marks a step of the demo data: it is never called (its address is
	// fictional), until someone points it at another URL.
	Demo bool `json:"demo,omitempty" readOnly:"true"`
}

AutomationWebhook is an outgoing HTTP call. The signing secret is stored separately and never returned; HasSecret says whether one is set.

type AutomationWebhookCall

type AutomationWebhookCall struct {
	ID         string    `json:"id"`
	Version    int       `json:"version"`
	URL        string    `json:"url"`
	StatusCode int       `json:"statusCode"`
	Error      string    `json:"error,omitempty"`
	DurationMs int       `json:"durationMs"`
	Attempt    int       `json:"attempt"`
	CalledAt   time.Time `json:"calledAt"`
}

AutomationWebhookCall is one entry of a webhook step's delivery log.

type AutomationWebhookCalls

type AutomationWebhookCalls struct {
	Calls []AutomationWebhookCall `json:"calls"`
}

AutomationWebhookCalls lists a webhook step's recent calls.

type AutomationWhatsAppStep

type AutomationWhatsAppStep struct {
	// Mode is "template" (default) or "text".
	Mode string `json:"mode,omitempty" enum:"template,text,"`
	// Template and Language name an approved template; Variables fill its
	// {{n}} from contact fields with fallbacks.
	Template  string                  `json:"template,omitempty" maxLength:"512"`
	Language  string                  `json:"language,omitempty" maxLength:"16"`
	Variables []AutomationWhatsAppVar `json:"variables,omitempty" maxItems:"20"`
	// Text is free text, sent only inside the window.
	Text string `json:"text,omitempty" maxLength:"1000"`
	// OutsideWindow, for free text: "skip" (default), or "template" to
	// send FallbackTemplate instead.
	OutsideWindow    string `json:"outsideWindow,omitempty" enum:"skip,template,"`
	FallbackTemplate string `json:"fallbackTemplate,omitempty" maxLength:"512"`
	// ConsentListID is the list whose WhatsApp consent the step needs:
	// contacts without it are skipped. The rule can't be removed.
	ConsentListID string `json:"consentListId,omitempty" maxLength:"40"`
	// Outside quiet hours: "wait" for the window (default) or "skip".
	Outside string `json:"outside,omitempty" enum:"wait,skip,"`
}

AutomationWhatsAppStep is a "Send WhatsApp" step: an approved template (any time), or free text inside the 24-hour customer service window.

type AutomationWhatsAppVar

type AutomationWhatsAppVar struct {
	Key string `json:"key" maxLength:"8"`
	// Source is "field" or "text".
	Source   string `json:"source" enum:"field,text"`
	Field    string `json:"field,omitempty" maxLength:"64"`
	Text     string `json:"text,omitempty" maxLength:"500"`
	Fallback string `json:"fallback,omitempty" maxLength:"500"`
}

AutomationWhatsAppVar maps a template variable to a contact field or a fixed text.

type BasicContentChecks

type BasicContentChecks struct{}

BasicContentChecks covers what every automation email needs.

func (BasicContentChecks) Check

Check implements ContentChecker.

type ChannelCheck

type ChannelCheck struct {
	WorkspaceID  uuid.UUID
	AutomationID uuid.UUID
	RunID        uuid.UUID
	ContactID    uuid.UUID
	EnteredAt    time.Time
	Condition    AutomationCondition
}

ChannelCheck asks a channel condition about a run's contact.

type ChannelCoster

type ChannelCoster interface {
	CostSince(ctx context.Context, workspaceID uuid.UUID, automationIDs []uuid.UUID, since time.Time) (map[uuid.UUID]float64, error)
}

ChannelCoster is a channel step that can say what its messages cost: the automations list shows each flow's cost over its window.

type ChannelIssue

type ChannelIssue struct {
	Code    string
	Message string
	// Text is Message's message, read in each reader's language.
	Text i18n.Text
}

ChannelIssue is a problem with a channel step's settings.

type ChannelPublishChecker

type ChannelPublishChecker interface {
	PublishChecks(ctx context.Context, workspaceID uuid.UUID, nodes []AutomationNode) ([]AutomationPublishCheck, error)
}

ChannelPublishChecker is a channel step that adds badges to the publish dialog (brief §6): for SMS, quiet hours and the senders' registration in the countries its steps text. Its badges warn; they don't block.

type ChannelSend

type ChannelSend struct {
	WorkspaceID  uuid.UUID
	AutomationID uuid.UUID
	Version      int
	RunID        uuid.UUID
	ContactID    uuid.UUID
	Node         AutomationNode
	Now          time.Time
	// Waited is true when the run already waited for this step's window.
	Waited bool
}

ChannelSend is a channel step reached by a run.

type ChannelSent

type ChannelSent struct {
	// MessageID is the queued message.
	MessageID uuid.UUID
	// Wait holds the run until then (outside quiet hours).
	Wait *time.Time
	// Skipped says why the contact got nothing: no_consent, no_phone,
	// suppressed, recent, quiet_hours, no_route…
	Skipped string
}

ChannelSent is what a channel step did.

type ChannelStep

type ChannelStep interface {
	// Send queues the step's message for the run's contact, in the run's
	// transaction.
	Send(ctx context.Context, tx pgx.Tx, in ChannelSend) (ChannelSent, error)
	// Condition answers a channel condition; sentAt is when the step's
	// message went (the window of an engagement condition starts there).
	Condition(ctx context.Context, tx pgx.Tx, in ChannelCheck) (met bool, sentAt time.Time, err error)
	// Permission is what publishing a flow with this step needs, on top
	// of publishing automations.
	Permission() authz.Permission
	// Validate checks a step's settings for the canvas, beyond what the
	// engine checks itself.
	Validate(n AutomationNode) []ChannelIssue
}

ChannelStep sends one channel's steps.

type ContentChecker

type ContentChecker interface {
	Check(c EmailContent) string
}

ContentChecker runs the content checks of Send Readiness on an email. It returns "" when the email passes, otherwise the first problem in a few words ("no unsubscribe link").

type CreateParams

type CreateParams struct {
	Name     string
	Template string
	// ListID is the list a list-triggered template starts on (the
	// welcome-series prompt); empty takes the workspace's first list.
	ListID string
	// StoreID is the store a store-triggered template starts on
	// (abandoned-cart); empty takes the workspace's first connected store.
	StoreID string
}

CreateParams starts a flow from a template or a blank canvas.

type DiffContext

type DiffContext struct {
	FromRefs  *Refs
	ToRefs    *Refs
	ToVersion int
	Loc       *time.Location
	// Failures of webhook steps, by node id.
	Failures map[string]WebhookFailure
	// Check runs content checks on an email version: "" when it passes,
	// otherwise the first problem ("no unsubscribe link").
	Check func(emailID string, version int) string
	// Lang is the language the lines are written in (English when unset).
	Lang i18n.Lang
	// InFlow counts the contacts in the flow now, for who a changed
	// trigger affects (review 2026-11 AT-12); nil when unknown.
	InFlow *int64
	// contains filtered or unexported fields
}

DiffContext carries the facts the diff mentions besides the two graphs.

type EmailContent

type EmailContent struct {
	Subject, Preheader, MJML, HTML, Text string
}

EmailContent is the content of one email version.

func BlankEmail

func BlankEmail(name, subject string) EmailContent

BlankEmail is the content of a new email made from the step panel.

func DemoEmail

func DemoEmail(subject, preheader, heading, cta string, body ...string) EmailContent

DemoEmail renders seeded demo emails with the starter layout.

type EmailLanguages

type EmailLanguages interface {
	AutomationEmailStates(ctx context.Context, q *store.Queries, ws *store.Workspace, emailID uuid.UUID, version int) ([]languages.AutomationEmailState, error)
	CopyForward(ctx context.Context, q *store.Queries, wsID, emailID uuid.UUID, from, to int) error
}

EmailLanguages is what flows ask of the content languages domain (internal/languages): the language versions of an email version, and carrying them to the email's next version when it's edited.

type EmailUpdate

type EmailUpdate struct {
	Subject   string
	Preheader string
	HTML      string
	Text      string
}

EmailUpdate is new content for an email; it becomes the next version.

type EventReminders

type EventReminders struct {
	// Name is the flow's name ("DMARC live reminders").
	Name  string
	Title string
	// Field is the contact date field registrations write.
	Field string
	// At is the session's start, "HH:MM" in the workspace's time zone.
	At string
	// Link is the joining link the reminders carry.
	Link string
	// When is the session's date and time as the emails write it.
	When string
}

EventReminders describes the session the reminders are for.

type GateDecision

type GateDecision struct {
	// Required stops the publish: an approval request was created instead.
	Required   bool
	ApprovalID uuid.UUID
	// Message explains who must approve ("Waiting for Marcus Chen or Linh Nguyen").
	Message string
}

GateDecision tells the publish whether to go ahead.

type Inserter

type Inserter interface {
	Insert(ctx context.Context, args river.JobArgs, opts *river.InsertOpts) (*rivertype.JobInsertResult, error)
	InsertTx(ctx context.Context, tx pgx.Tx, args river.JobArgs, opts *river.InsertOpts) (*rivertype.JobInsertResult, error)
}

Inserter enqueues River jobs; *jobs.Client satisfies it. It may be nil (OpenAPI generation, some tests): the periodic jobs pick work up anyway.

type Mailer

type Mailer interface {
	QueueAutomationEmail(ctx context.Context, tx pgx.Tx, m OutgoingEmail) (QueuedEmail, error)
}

Mailer queues automation emails. QueueAutomationEmail runs inside the engine's transaction and must not do network I/O: implementations record the message (a messages row with stream "automation", automation_id and automation_node set) and schedule their own delivery. internal/app wires in the sending engine's implementation (automationMailer).

type MessageEvent

type MessageEvent struct {
	MessageID uuid.UUID
	// Type: delivered, bounced, complained, opened, clicked, unsubscribed.
	Type string
	// Machine marks opens by mail privacy proxies (Apple Mail).
	Machine bool
	At      time.Time
}

MessageEvent is a delivery or engagement event of an automation email.

type NoApproval

type NoApproval struct{}

NoApproval publishes right away.

func (NoApproval) Check

Check implements PublishGate.

type OutgoingEmail

type OutgoingEmail struct {
	WorkspaceID  uuid.UUID
	AutomationID uuid.UUID
	Version      int
	NodeID       string
	RunID        uuid.UUID
	ContactID    uuid.UUID
	// To is the contact's address; MailboxProvider their mailbox provider key.
	To              string
	MailboxProvider string
	EmailID         uuid.UUID
	EmailVersion    int
	Subject         string
	// Route is empty for the Automations route, or a provider id that
	// overrides it for this step.
	Route string
	// Context is what the trigger passed to the flow's emails (a store's
	// checkout or order): the sending engine keeps it with the message.
	Context map[string]string
}

OutgoingEmail is one "Send email" step for one contact.

type PublishGate

type PublishGate interface {
	Check(ctx context.Context, tx pgx.Tx, req PublishRequest) (GateDecision, error)
}

PublishGate is the approvals seam (add-on §3.8). Check runs inside the publish transaction. When approval is required, the approvals domain creates an approval_requests row in tx and returns Required; once approved it calls Service.CompletePublish.

type PublishRequest

type PublishRequest struct {
	WorkspaceID  uuid.UUID
	AutomationID uuid.UUID
	Name         string
	Version      int
	Migration    string
	By           uuid.UUID
	Changes      []AutomationDiffItem
	// Missing are permissions the flow's channel steps need that the
	// publisher lacks (sms:send for a "Send SMS" step): publishing goes
	// for approval by someone who holds them.
	Missing []authz.Permission
}

PublishRequest is what the approval gate sees.

type QueueOnlyMailer

type QueueOnlyMailer struct{}

QueueOnlyMailer records the message as queued on a provider picked from the Automations route, or as held when no provider can send. Nothing is delivered until the sending domain replaces it.

func (QueueOnlyMailer) QueueAutomationEmail

func (QueueOnlyMailer) QueueAutomationEmail(ctx context.Context, tx pgx.Tx, m OutgoingEmail) (QueuedEmail, error)

QueueAutomationEmail implements Mailer.

type QueuedEmail

type QueuedEmail struct {
	MessageID uuid.UUID
	// ProviderID is the sending provider chosen (uuid.Nil when held).
	ProviderID uuid.UUID
	// Held is true when no provider on the route can send right now: the
	// message waits and goes out once one is healthy.
	Held bool
}

QueuedEmail is what the mailer did with an email.

type Refs

type Refs struct {
	Lists      map[string]string // id → name
	Forms      map[string]string // id → slug
	Emails     map[string]int    // id → latest version
	EmailNames map[string]string // id → name
	Fields     map[string]string // key → type
	Providers  map[string]string // id → name
	Polls      map[string]string // "poll:<id>" or "survey:<id>" → name
	Products   map[string]string // id → name
	// Milestones are Grow's referral milestones: "3 referrals · The Acme
	// Field Guide".
	Milestones map[string]string
	Stores     map[string]string // store id → name (connected stores)
	Segments   map[string]string // id → name (AT-10)
	// Sources are what a "Clicked a link" trigger can listen to:
	// "campaign:<id>" and "email:<id>" → name.
	Sources map[string]string
	// contains filtered or unexported fields
}

Refs are the workspace objects steps may point to; Validate reports steps that reference something missing (a deleted list, form, email or field).

type RemoveRunInput

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

RemoveRunInput says why a contact is taken out of a flow.

type ResumeInput

type ResumeInput struct {
	Overdue     string `json:"overdue,omitempty" enum:"send,skip,spread," doc:"Defaults to send"`
	SpreadHours int    `json:"spreadHours,omitempty" minimum:"0" maximum:"72"`
}

ResumeInput says what happens to contacts whose wait ended while the flow was paused (review 2026-11 AT-4): "send" moves them on now, within warm-up caps and quiet hours as always; "skip" skips the email they missed; "spread" moves them on evenly over SpreadHours.

type ScanArgs

type ScanArgs struct{}

ScanArgs runs the periodic scan (goals, branch wake-ups, date triggers…).

func (ScanArgs) Kind

func (ScanArgs) Kind() string

Kind implements river.JobArgs.

type ScanWorker

type ScanWorker struct {
	river.WorkerDefaults[ScanArgs]
	S *Service
}

func (*ScanWorker) Work

func (w *ScanWorker) Work(ctx context.Context, _ *river.Job[ScanArgs]) error

Work implements river.Worker.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Log   *slog.Logger
	// Jobs returns the River client used to wake the engine; nil or a nil
	// client means "wait for the next periodic tick".
	Jobs func() Inserter
	// Mailer queues automation emails (QueueOnlyMailer by default).
	Mailer Mailer
	// Gate decides whether publishing needs approval (NoApproval by default).
	Gate PublishGate
	// Checks runs content checks on emails before publishing.
	Checks ContentChecker
	// Accessibility checks the emails before publishing; nil skips it.
	Accessibility AccessibilityGate
	// HTTP calls webhook steps; nil uses NewWebhookClient (public addresses only).
	HTTP *http.Client
	Now  func() time.Time

	// Languages are the emails' language versions (internal/languages);
	// nil leaves them out.
	Languages EmailLanguages

	// StoreRevenue is the store orders credited to flows since a time
	// (internal/commerce; the list's revenue column). Nil without stores.
	StoreRevenue func(ctx context.Context, wsID uuid.UUID, ids []uuid.UUID, since time.Time) map[uuid.UUID]AutomationRevenue
	// StoreEmail is a store-triggered starter's email in the store's
	// voice, with its checkout items or product grid (internal/commerce).
	// Nil without stores: the starter's plain email.
	StoreEmail func(ctx context.Context, wsID, storeID uuid.UUID, key string) (EmailContent, bool)
	// SegmentMembers evaluates a saved segment (internal/segments), for
	// the segment triggers (review 2026-11 AT-10). Nil: segments aren't
	// watched.
	SegmentMembers func(ctx context.Context, wsID, segmentID uuid.UUID) ([]uuid.UUID, error)
	// Mail sends test emails through the System route and URLs builds the
	// links they carry (AT-3).
	Mail func() mailer.Sender
	URLs publicurl.Builder
}

Service holds the automations domain dependencies.

func (*Service) CompareVersions

func (s *Service) CompareVersions(ctx context.Context, ws *store.Workspace, id uuid.UUID, from, to int) (AutomationDiff, error)

CompareVersions diffs two versions; zeros mean live → draft.

func (*Service) CompletePublish

func (s *Service) CompletePublish(ctx context.Context, ws *store.Workspace, by uuid.UUID, id uuid.UUID, version int, migration string) error

CompletePublish publishes a version once its approval is granted. The approvals domain calls it with the approver's decision in place.

func (*Service) ContactRuns

func (s *Service) ContactRuns(ctx context.Context, ws *store.Workspace, contact uuid.UUID) (AutomationContactRuns, error)

ContactRuns lists the flows a contact is in or went through, the ones in progress first.

func (*Service) Create

func (s *Service) Create(ctx context.Context, ws *store.Workspace, by *uuid.UUID, p CreateParams) (uuid.UUID, error)

Create makes a draft flow. Templates also create their emails, in their creator's language (they're written for the emails' readers).

func (*Service) CreateEmail

func (s *Service) CreateEmail(ctx context.Context, ws *store.Workspace, by *uuid.UUID, automation *uuid.UUID, name, subject string) (AutomationEmailOption, error)

CreateEmail makes a new email for a send step.

func (*Service) CreateEventReminders

func (s *Service) CreateEventReminders(ctx context.Context, ws *store.Workspace, by *uuid.UUID, in EventReminders) (uuid.UUID, error)

CreateEventReminders makes the draft flow and its two emails, in their creator's language (they're written for the event's registrants).

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, canPublish bool) error

Delete removes a flow; contacts in it leave right away.

func (*Service) DiscardDraft

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

DiscardDraft throws away unpublished changes.

func (*Service) Dispatch

func (s *Service) Dispatch(ctx context.Context) (int, error)

Dispatch enrolls contacts from pending trigger events. It returns how many runs it started.

func (*Service) Duplicate

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

Duplicate copies a flow's draft into a new draft flow.

func (*Service) Email

func (s *Service) Email(ctx context.Context, ws *store.Workspace, id uuid.UUID, version int) (AutomationEmailContent, error)

Email returns one version of an email (the latest when version is 0).

func (*Service) Get

Get returns a flow for the editor.

func (*Service) Kick

func (s *Service) Kick(ctx context.Context)

Kick wakes the engine soon (a store event was queued).

func (*Service) List

func (s *Service) List(ctx context.Context, ws *store.Workspace, status string) (AutomationList, error)

List returns every flow with its 30-day performance, filtered by status.

func (*Service) Options

func (s *Service) Options(ctx context.Context, ws *store.Workspace) (AutomationOptions, error)

Options lists lists, forms, fields, emails, providers, tags and API events.

func (*Service) Pause

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

Pause stops a live flow: nobody new enters, contacts stay where they are and nothing is sent until it resumes.

func (*Service) PreviewEmail

PreviewEmail renders an automation email as a contact gets it, its links pointing nowhere.

func (*Service) Publish

func (s *Service) Publish(ctx context.Context, ws *store.Workspace, by uuid.UUID, id uuid.UUID, version int, migration string) (AutomationPublishResult, error)

Publish makes the draft the live version, after the approval gate.

func (*Service) PublishPreview

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

PublishPreview prepares the publish dialog.

func (*Service) RecordMessageEvent

func (s *Service) RecordMessageEvent(ctx context.Context, q *store.Queries, ev MessageEvent) error

RecordMessageEvent adds an automation email's delivery or engagement to its step's stats. The tracking and ingest domains call it for messages with stream "automation": once per message for delivered, bounced, complained and unsubscribed, and only for the first open and first click (stats count unique opens and clicks).

func (*Service) RemoveRun

func (s *Service) RemoveRun(ctx context.Context, ws *store.Workspace, id, run uuid.UUID, in RemoveRunInput) error

RemoveRun takes a contact out of a flow now: they get none of its remaining steps. Audited with the reason.

func (*Service) RestoreVersion

func (s *Service) RestoreVersion(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, version int) (AutomationDraftSaved, error)

RestoreVersion makes an earlier version the draft.

func (*Service) Resume

func (s *Service) Resume(ctx context.Context, ws *store.Workspace, by uuid.UUID, id uuid.UUID, in ResumeInput) error

Resume restarts a paused flow.

func (*Service) RunWebhook

func (s *Service) RunWebhook(ctx context.Context, args WebhookArgs, attempt, maxAttempts int) error

RunWebhook makes one webhook call for a run waiting at a webhook step, logs it, and lets the contact move on: a failing webhook never blocks the flow. Transient failures (network errors, 429, 5xx) are retried by River up to webhookAttempts times first.

func (*Service) SaveDraft

func (s *Service) SaveDraft(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, g AutomationGraph, revision int64) (AutomationDraftSaved, error)

SaveDraft stores the canvas. The first change to a published flow starts a new draft version; later saves update it. Positions alone don't count as a change for the audit log.

func (*Service) Scan

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

Scan does the periodic work besides moving runs: wakes branch waits whose email was opened, moves contacts who reached a goal, fires date triggers, re-enqueues lost webhook calls, releases held email when the route recovers, retires empty versions and trims old rows.

func (*Service) SendEvent

func (s *Service) SendEvent(ctx context.Context, ws *store.Workspace, ev APIEvent) (AutomationEventResult, error)

SendEvent records an API event ("workspace.created") for a contact. Flows triggered by it enroll the contact on the next engine tick (seconds), and goals and branches waiting for it see it.

func (*Service) SetStepSecret

func (s *Service) SetStepSecret(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, node, secret string) error

SetStepSecret stores (or with an empty secret, clears) a webhook step's signing secret. It is sealed at rest and never returned.

func (*Service) Stats

func (s *Service) Stats(ctx context.Context, ws *store.Workspace, id uuid.UUID, days int) (AutomationStats, error)

Stats returns per-step stats for the last N days, across versions (steps keep their ids, so a step's numbers carry over when a new version is published).

func (*Service) StepContacts

func (s *Service) StepContacts(ctx context.Context, ws *store.Workspace, id uuid.UUID, node, cursor string, limit int) (AutomationStepContacts, error)

StepContacts lists the contacts at a step, the latest to arrive first.

func (*Service) Summary

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

Summary returns the KPI row: contacts in flows now and the last N days.

func (*Service) TestEmail

TestEmail sends an automation email through the System route with "[Test]" before its subject; it counts in no stats. Without the campaigns:send permission a member can send tests only to their own address, as with campaigns.

func (*Service) Tick

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

Tick moves every due run forward. It returns how many runs it processed.

func (*Service) UpdateEmail

func (s *Service) UpdateEmail(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, u EmailUpdate) (AutomationEmailContent, error)

UpdateEmail saves new content as the email's next version. Steps keep the version they point at until someone picks the new one, so a live flow never changes what it sends without a publish. Content edited as HTML drops the MJML source (the composer reopens it in HTML mode).

func (*Service) UpdateMeta

func (s *Service) UpdateMeta(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, name, description string) error

UpdateMeta renames a flow or changes its description.

func (*Service) Version

func (s *Service) Version(ctx context.Context, ws *store.Workspace, id uuid.UUID, version int) (AutomationVersionGraph, error)

Version returns the graph of one version.

func (*Service) VersionEmails

func (s *Service) VersionEmails(ctx context.Context, wsID, automationID uuid.UUID, version int32) ([]AccessibilityEmail, error)

VersionEmails lists the email steps of an automation version with their content and step names.

func (*Service) Versions

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

Versions lists every version, newest first.

func (*Service) WebhookCalls

func (s *Service) WebhookCalls(ctx context.Context, ws *store.Workspace, id uuid.UUID, node string, limit int) ([]AutomationWebhookCall, error)

WebhookCalls returns the latest calls of a webhook step.

type TickArgs

type TickArgs struct{}

TickArgs enrolls contacts from trigger events and moves due runs.

func (TickArgs) Kind

func (TickArgs) Kind() string

Kind implements river.JobArgs.

type TickWorker

type TickWorker struct {
	river.WorkerDefaults[TickArgs]
	S *Service
}

TickWorker runs Dispatch then Tick.

func (*TickWorker) Timeout

func (w *TickWorker) Timeout(*river.Job[TickArgs]) time.Duration

Timeout keeps one tick from overlapping the next for long.

func (*TickWorker) Work

func (w *TickWorker) Work(ctx context.Context, _ *river.Job[TickArgs]) error

Work implements river.Worker. Runs move on even when starting new ones failed (review 2026-11 EN-1).

type WebhookArgs

type WebhookArgs struct {
	RunID        uuid.UUID `json:"run_id" river:"unique"`
	AutomationID uuid.UUID `json:"automation_id"`
	Version      int       `json:"version"`
	NodeID       string    `json:"node_id" river:"unique"`
}

WebhookArgs calls one webhook step for one run.

func (WebhookArgs) Kind

func (WebhookArgs) Kind() string

Kind implements river.JobArgs.

type WebhookFailure

type WebhookFailure struct {
	URL      string
	Status   int
	Since    time.Time
	Failures int64
}

WebhookFailure is what the diff says about a removed webhook that was failing.

type WebhookWorker

type WebhookWorker struct {
	river.WorkerDefaults[WebhookArgs]
	S *Service
}

WebhookWorker calls webhook steps.

func (*WebhookWorker) NextRetry

func (w *WebhookWorker) NextRetry(job *river.Job[WebhookArgs]) time.Time

NextRetry backs off 30 s, 2 min, 8 min.

func (*WebhookWorker) Work

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

Work implements river.Worker.

Jump to

Keyboard shortcuts

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