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
- Variables
- func Changes(items []AutomationDiffItem) int
- func DurationText(d *AutomationDuration) string
- func EmailShortRef(name string) string
- func EmitFormSubmitted(ctx context.Context, q *store.Queries, ...) error
- func ExitRefunded(ctx context.Context, q *store.Queries, wsID, contactID, productID uuid.UUID, ...) (int, error)
- func GoalLabel(n AutomationNode, refs *Refs) string
- func IsStoreTrigger(kind string) bool
- func MessageVars(ctx context.Context, q *store.Queries, msg uuid.UUID) map[string]any
- func NewWebhookClient() *http.Client
- func NodeRef(g AutomationGraph, n AutomationNode, refs *Refs) string
- func NodeTitle(g AutomationGraph, n AutomationNode, refs *Refs) string
- func Register(h huma.API, s *Service)
- func RegisterChannelStep(nodeType string, c ChannelStep)
- func RegisterJobs(reg *jobs.Registry, s *Service)
- func Sign(secret []byte, t time.Time, body []byte) string
- func TextIn(l i18n.Lang, t i18n.Text) string
- func TriggerKindLabel(kind string) string
- func TriggerLabel(t *AutomationTrigger, refs *Refs) string
- func TriggerRef(t *AutomationTrigger, refs *Refs) string
- func TypeName(t string) string
- type APIEvent
- type AccessibilityDraft
- type AccessibilityEmail
- type AccessibilityGate
- type AccessibilityVerdict
- type AutomationAlert
- type AutomationAlertAction
- type AutomationCondition
- type AutomationCreated
- type AutomationDetail
- type AutomationDiff
- type AutomationDiffItem
- type AutomationDraftSaved
- type AutomationDuration
- type AutomationEdge
- type AutomationEdgeData
- type AutomationEmailContent
- type AutomationEmailOption
- type AutomationEmailStep
- type AutomationEventResult
- type AutomationFieldOption
- type AutomationFormOption
- type AutomationGoal
- type AutomationGoalCount
- type AutomationGraph
- func (g AutomationGraph) Depths() map[string]int
- func (g AutomationGraph) HasCycle() bool
- func (g AutomationGraph) In(id string) []AutomationEdge
- func (g AutomationGraph) MustJSON() json.RawMessage
- func (g AutomationGraph) Next(id string) string
- func (g AutomationGraph) NextOnPath(id, path string) string
- func (g AutomationGraph) Node(id string) *AutomationNode
- func (g AutomationGraph) Order() []string
- func (g AutomationGraph) Out(id string) []AutomationEdge
- func (g AutomationGraph) Prev(id string) string
- func (g AutomationGraph) Trigger() *AutomationNode
- type AutomationGraphIssue
- type AutomationIDParam
- type AutomationList
- type AutomationListAction
- type AutomationListItem
- type AutomationMilestoneOption
- type AutomationNode
- type AutomationNodeData
- type AutomationNodePosition
- type AutomationOptionItem
- type AutomationOptions
- type AutomationPathCount
- type AutomationProviderSends
- type AutomationPublishCheck
- type AutomationPublishPreview
- type AutomationPublishResult
- type AutomationPushStep
- type AutomationRevenue
- type AutomationRoute
- type AutomationRouteProvider
- type AutomationSMSStep
- type AutomationSendWindow
- type AutomationSplitVariant
- type AutomationStarterTemplate
- type AutomationStats
- type AutomationStatusCounts
- type AutomationStepStats
- type AutomationSummary
- type AutomationTemplates
- type AutomationTrigger
- type AutomationVersionGraph
- type AutomationVersionItem
- type AutomationVersions
- type AutomationWebhook
- type AutomationWebhookCall
- type AutomationWebhookCalls
- type AutomationWhatsAppStep
- type AutomationWhatsAppVar
- type BasicContentChecks
- type ChannelCheck
- type ChannelCoster
- type ChannelIssue
- type ChannelPublishChecker
- type ChannelSend
- type ChannelSent
- type ChannelStep
- type ContentChecker
- type CreateParams
- type DiffContext
- type EmailContent
- type EmailLanguages
- type EmailUpdate
- type EventReminders
- type GateDecision
- type Inserter
- type Mailer
- type MessageEvent
- type NoApproval
- type OutgoingEmail
- type PublishGate
- type PublishRequest
- type QueueOnlyMailer
- type QueuedEmail
- type Refs
- type ScanArgs
- type ScanWorker
- type Service
- func (s *Service) CompareVersions(ctx context.Context, ws *store.Workspace, id uuid.UUID, from, to int) (AutomationDiff, error)
- func (s *Service) CompletePublish(ctx context.Context, ws *store.Workspace, by uuid.UUID, id uuid.UUID, ...) error
- func (s *Service) Create(ctx context.Context, ws *store.Workspace, by *uuid.UUID, p CreateParams) (uuid.UUID, error)
- func (s *Service) CreateEmail(ctx context.Context, ws *store.Workspace, by *uuid.UUID, automation *uuid.UUID, ...) (AutomationEmailOption, error)
- func (s *Service) CreateEventReminders(ctx context.Context, ws *store.Workspace, by *uuid.UUID, in EventReminders) (uuid.UUID, error)
- func (s *Service) Delete(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, ...) error
- func (s *Service) DiscardDraft(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID) error
- func (s *Service) Dispatch(ctx context.Context) (int, error)
- func (s *Service) Duplicate(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID) (uuid.UUID, error)
- func (s *Service) Email(ctx context.Context, ws *store.Workspace, id uuid.UUID, version int) (AutomationEmailContent, error)
- func (s *Service) Get(ctx context.Context, ws *store.Workspace, id uuid.UUID) (AutomationDetail, error)
- func (s *Service) Kick(ctx context.Context)
- func (s *Service) List(ctx context.Context, ws *store.Workspace, status string) (AutomationList, error)
- func (s *Service) Options(ctx context.Context, ws *store.Workspace) (AutomationOptions, error)
- func (s *Service) Pause(ctx context.Context, ws *store.Workspace, by uuid.UUID, id uuid.UUID, ...) error
- func (s *Service) Publish(ctx context.Context, ws *store.Workspace, by uuid.UUID, id uuid.UUID, ...) (AutomationPublishResult, error)
- func (s *Service) PublishPreview(ctx context.Context, ws *store.Workspace, id uuid.UUID) (AutomationPublishPreview, error)
- func (s *Service) RecordMessageEvent(ctx context.Context, q *store.Queries, ev MessageEvent) error
- func (s *Service) RestoreVersion(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, ...) (AutomationDraftSaved, error)
- func (s *Service) Resume(ctx context.Context, ws *store.Workspace, by uuid.UUID, id uuid.UUID) error
- func (s *Service) RunWebhook(ctx context.Context, args WebhookArgs, attempt, maxAttempts int) error
- func (s *Service) SaveDraft(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, ...) (AutomationDraftSaved, error)
- func (s *Service) Scan(ctx context.Context) error
- func (s *Service) SendEvent(ctx context.Context, ws *store.Workspace, ev APIEvent) (AutomationEventResult, error)
- func (s *Service) SetStepSecret(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, ...) error
- func (s *Service) Stats(ctx context.Context, ws *store.Workspace, id uuid.UUID, days int) (AutomationStats, error)
- func (s *Service) Summary(ctx context.Context, ws *store.Workspace, days int) (AutomationSummary, error)
- func (s *Service) Tick(ctx context.Context) (int, error)
- func (s *Service) UpdateEmail(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, ...) (AutomationEmailContent, error)
- func (s *Service) UpdateMeta(ctx context.Context, ws *store.Workspace, by *uuid.UUID, id uuid.UUID, ...) error
- func (s *Service) Version(ctx context.Context, ws *store.Workspace, id uuid.UUID, version int) (AutomationVersionGraph, error)
- func (s *Service) VersionEmails(ctx context.Context, wsID, automationID uuid.UUID, version int32) ([]AccessibilityEmail, error)
- func (s *Service) Versions(ctx context.Context, ws *store.Workspace, id uuid.UUID) (AutomationVersions, error)
- func (s *Service) WebhookCalls(ctx context.Context, ws *store.Workspace, id uuid.UUID, node string, limit int) ([]AutomationWebhookCall, error)
- type TickArgs
- type TickWorker
- type WebhookArgs
- type WebhookFailure
- type WebhookWorker
Constants ¶
const ( StatusDraft = "draft" StatusLive = "live" StatusPaused = "paused" )
Statuses of a flow.
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.
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.
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.
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" )
Trigger kinds.
const ( PathYes = "yes" PathNo = "no" )
Branch paths.
const ( AnswerAny = "any" AnswerIs = "is" AnswerIsNot = "is_not" )
Answer filters of the trigger.
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.
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.
const CodeAccessibilityBlocked = "accessibility_blocked"
CodeAccessibilityBlocked is the problem code of a publish the workspace's accessibility policy stops.
const ListDays = 30
ListDays is the stats window of the list and the canvas.
const NodeSMS = "sms"
NodeSMS is the "Send SMS" step.
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)>".
const TriggerBoughtProduct = "bought_product"
TriggerBoughtProduct is the trigger's kind, and the goal's.
const TriggerPollAnswered = "poll_answered"
TriggerPollAnswered is the trigger's kind.
Variables ¶
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.
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 ¶
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 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 ¶
IsStoreTrigger reports whether a trigger kind is a store's.
func MessageVars ¶
MessageVars is the Liquid data an automation email was queued with (nil: none). The sending engine adds it to the contact's.
func NewWebhookClient ¶
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 RegisterChannelStep ¶
func RegisterChannelStep(nodeType string, c ChannelStep)
RegisterChannelStep plugs a channel's steps in (the app wires it).
func RegisterJobs ¶
RegisterJobs adds the engine's workers and schedules to the job registry.
func TextIn ¶
TextIn writes one of the package's texts (a diff line's TitleText) in a reader's language.
func TriggerKindLabel ¶
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".
Types ¶
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 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"`
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 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"`
}
AutomationEmailStep is a "Send email" step.
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 ¶
func Layout(g AutomationGraph) AutomationGraph
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 ¶
func (g AutomationGraph) In(id string) []AutomationEdge
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 ¶
func (g AutomationGraph) Node(id string) *AutomationNode
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 ¶
func (g AutomationGraph) Out(id string) []AutomationEdge
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 ¶
AutomationNodePosition is a node's top-left corner on the canvas.
type AutomationOptionItem ¶
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"`
}
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 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 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"`
}
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 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"`
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 `` /* 181-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;
// "always" lets them enter again after they leave.
Reentry string `json:"reentry,omitempty" maxLength:"8"`
// 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"`
}
AutomationTrigger says which contacts enter the flow.
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 ¶
func (BasicContentChecks) Check(c EmailContent) string
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
// 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 ¶
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 ¶
func (NoApproval) Check(context.Context, pgx.Tx, PublishRequest) (GateDecision, error)
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)
// 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 ScanArgs ¶
type ScanArgs struct{}
ScanArgs runs the periodic scan (goals, branch wake-ups, date triggers…).
type ScanWorker ¶
type ScanWorker struct {
river.WorkerDefaults[ScanArgs]
S *Service
}
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)
}
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) 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 ¶
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 ¶
func (s *Service) Get(ctx context.Context, ws *store.Workspace, id uuid.UUID) (AutomationDetail, error)
Get returns a flow for the editor.
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 ¶
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) 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 ¶
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) 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) error
Resume restarts a paused flow; delays that ended meanwhile run right away.
func (*Service) RunWebhook ¶
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 ¶
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) 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) 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.
type TickArgs ¶
type TickArgs struct{}
TickArgs enrolls contacts from trigger events and moves due runs.
type TickWorker ¶
type TickWorker struct {
river.WorkerDefaults[TickArgs]
S *Service
}
TickWorker runs Dispatch then Tick.
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.
type WebhookFailure ¶
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.