approvals

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 35 Imported by: 0

Documentation

Overview

Package approvals implements send approvals (add-on 3.8, 5.12) and the Review & send flow around them (spec 7.5): the workspace policy and its rules, approval requests with a snapshot of what they cover (content and subject, audience definition, route, schedule), invalidation with the exact diff when any of it changes or the audience moves more than 10%, comments, decisions, the send-time recheck, the Owners' emergency bypass, and scheduling or starting the send through the sending engine.

Index

Constants

View Source
const (
	RuleAudienceMin       = "audience_min"
	RuleWarmingProvider   = "warming_provider"
	RuleNewProvider       = "new_provider"
	RuleReadyWithWarnings = "ready_with_warnings"
	RuleAuthorLacksSend   = "author_lacks_send"
	RuleApprovalLists     = "approval_lists"
	RuleAutomationPublish = "automation_publish"
)

Rule keys, in the order of the policy screen.

View Source
const (
	DecisionApprove        = "approve"
	DecisionRequestChanges = "request_changes"
	DecisionReject         = "reject"
)

Decisions.

View Source
const HeldRetry = 15 * time.Minute

HeldRetry is how often a held send is rechecked.

View Source
const InvalidationShare = 10.0

InvalidationShare is how far the audience may move (in percent) before an approval no longer covers it.

View Source
const LargeSend = 1000

LargeSend is the audience size from which sending asks to type the count.

View Source
const RecheckLead = 15 * time.Minute

RecheckLead is how long before a scheduled send Send Readiness runs again.

View Source
const RemindEvery = time.Hour

RemindEvery is how often an author can remind the approvers.

Variables

This section is empty.

Functions

func Initials

func Initials(name string) string

Initials of a name: "Marcus Chen" → "MC".

func InvalidationReason

func InvalidationReason(changes []ApprovalChange) string

InvalidationReason sums up the changes: "subject changed", "audience moved +14% after approval".

func Links(mjmlSrc, html string) []string

Links lists the links of an email in order (MJML when there is one).

func Register

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

Register adds the Review & send and approval operations.

func RouteKey

func RouteKey(shares []readiness.ReadinessRouteShare) string

RouteKey is "ses:90,postal:10" for the route of a run.

func ScheduleText

func ScheduleText(raw json.RawMessage, loc *time.Location) string

ScheduleText is "Nov 4, 09:00", "Send now" or "Best time within 24 h of Nov 4, 09:00".

func Sections

func Sections(mjmlSrc string) []string

Sections is the section outline of the MJML ("header", "hero", "footer").

Types

type ApprovalAudienceRule

type ApprovalAudienceRule struct {
	Enabled bool  `json:"enabled"`
	N       int64 `json:"n" minimum:"1" maximum:"100000000"`
}

ApprovalAudienceRule is the audience-size rule.

type ApprovalAudienceView

type ApprovalAudienceView struct {
	Count int64    `json:"count"`
	Lists []string `json:"lists"`
	// Excluded is "301 suppressed · 0 bounced in 30 days · role addresses".
	Excluded string `json:"excluded"`
	// Current is today's count and ChangePct how far it moved since the request.
	Current   int64   `json:"current"`
	ChangePct float64 `json:"changePct"`
}

ApprovalAudienceView is the audience part of a request.

type ApprovalAuditLine

type ApprovalAuditLine struct {
	Action string    `json:"action"`
	Actor  string    `json:"actor"`
	At     time.Time `json:"at"`
	IP     string    `json:"ip,omitempty"`
}

ApprovalAuditLine is the audit entry behind a decision ("campaign.approved · Marcus Chen · 10:42 · from 198.51.100.40").

type ApprovalAutomationSnapshot

type ApprovalAutomationSnapshot struct {
	Version   int      `json:"version"`
	Migration string   `json:"migration"`
	Changes   []string `json:"changes"`
}

ApprovalAutomationSnapshot is what an automation publish request covers.

type ApprovalBypassInput

type ApprovalBypassInput struct {
	ReviewSendInput
	Reason   string `json:"reason" minLength:"1" maxLength:"1000"`
	Password string `json:"password,omitempty" maxLength:"500"`
}

ApprovalBypassInput is an Owner's emergency bypass of the approval policy.

type ApprovalCampaignView

type ApprovalCampaignView struct {
	ID        string `json:"id"`
	Status    string `json:"status"`
	Subject   string `json:"subject"`
	Preheader string `json:"preheader"`
	From      string `json:"from"`
	Version   int    `json:"version"`
	// CurrentVersion is the campaign's version now: after edits it is past
	// the snapshot's ("What changed · v9 → v10").
	CurrentVersion int        `json:"currentVersion"`
	EditedBy       string     `json:"editedBy,omitempty"`
	EditedAt       *time.Time `json:"editedAt,omitempty"`
	// ScheduledAt is set while the campaign is scheduled.
	ScheduledAt *time.Time `json:"scheduledAt,omitempty"`
}

ApprovalCampaignView is the campaign part of a request.

type ApprovalCan

type ApprovalCan struct {
	Decide       bool   `json:"decide"`
	DecideReason string `json:"decideReason,omitempty"`
	Comment      bool   `json:"comment"`
	Cancel       bool   `json:"cancel"`
	Remind       bool   `json:"remind"`
	Restore      bool   `json:"restore"`
	Schedule     bool   `json:"schedule"`
	IsAuthor     bool   `json:"isAuthor"`
}

ApprovalCan says what the viewer may do on a request.

type ApprovalChange

type ApprovalChange struct {
	Field  string `json:"field" enum:"subject,preheader,link,content,sender,audience,audience_count,route,schedule"`
	Label  string `json:"label"`
	Before string `json:"before"`
	After  string `json:"after"`
}

ApprovalChange is one difference between an approval's snapshot and the campaign.

func Diff

func Diff(s Snapshot, c Current, loc *time.Location) []ApprovalChange

Diff compares a snapshot with the campaign as it stands. loc formats the schedule in the workspace zone.

type ApprovalCommentInput

type ApprovalCommentInput struct {
	Body string `json:"body" minLength:"1" maxLength:"4000"`
}

ApprovalCommentInput adds to the discussion.

type ApprovalCommentView

type ApprovalCommentView struct {
	ID     string         `json:"id"`
	Author ApprovalPerson `json:"author"`
	Body   string         `json:"body"`
	At     time.Time      `json:"at"`
}

ApprovalCommentView is one comment of the discussion.

type ApprovalCounts

type ApprovalCounts struct {
	Pending          int `json:"pending"`
	Approved         int `json:"approved"`
	ChangesRequested int `json:"changesRequested"`
	Rejected         int `json:"rejected"`
	Invalidated      int `json:"invalidated"`
	All              int `json:"all"`
}

ApprovalCounts feeds the inbox tabs.

type ApprovalDecisionInput

type ApprovalDecisionInput struct {
	Decision string `json:"decision" enum:"approve,request_changes,reject"`
	Comment  string `json:"comment,omitempty" maxLength:"2000"`
}

ApprovalDecisionInput is an approver's decision.

type ApprovalDecisionView

type ApprovalDecisionView struct {
	Approver ApprovalPerson `json:"approver"`
	Decision string         `json:"decision" enum:"approve,request_changes,reject"`
	Comment  string         `json:"comment"`
	At       time.Time      `json:"at"`
}

ApprovalDecisionView is one approver's decision.

type ApprovalDetail

type ApprovalDetail struct {
	ApprovalRequestView
	Name       string                      `json:"name"`
	Author     ApprovalPerson              `json:"author"`
	Approvers  []ApprovalPerson            `json:"approvers"`
	Campaign   *ApprovalCampaignView       `json:"campaign,omitempty"`
	Readiness  *ApprovalReadinessView      `json:"readiness,omitempty"`
	Audience   *ApprovalAudienceView       `json:"audience,omitempty"`
	Route      *ApprovalRouteView          `json:"route,omitempty"`
	Schedule   *ApprovalScheduleView       `json:"schedule,omitempty"`
	Automation *ApprovalAutomationSnapshot `json:"automation,omitempty"`
	// ChangesSince lists what changed since the previous request this one
	// follows (empty for a first request).
	ChangesSince []ApprovalChange `json:"changesSince"`
	// Next is the request that followed this one (after an invalidation).
	NextID   string                `json:"nextId,omitempty"`
	Comments []ApprovalCommentView `json:"comments"`
	Held     *ReviewHeld           `json:"held,omitempty"`
	Can      ApprovalCan           `json:"can"`
}

ApprovalDetail is the approval review screen.

type ApprovalFilterOption

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

ApprovalFilterOption is an author or approver to filter by.

type ApprovalList

type ApprovalList struct {
	Items     []ApprovalListItem     `json:"items"`
	Counts    ApprovalCounts         `json:"counts"`
	Authors   []ApprovalFilterOption `json:"authors"`
	Approvers []ApprovalFilterOption `json:"approvers"`
	Policy    ApprovalPolicySummary  `json:"policy"`
	// AllRequests is true for approvers (they see every request).
	AllRequests bool `json:"allRequests"`
	CanManage   bool `json:"canManage"`
}

ApprovalList is the approval inbox.

type ApprovalListItem

type ApprovalListItem struct {
	ID          string `json:"id"`
	SubjectType string `json:"subjectType" enum:"campaign,automation"`
	CampaignID  string `json:"campaignId,omitempty"`
	// AutomationID is set for automation publish requests.
	AutomationID string `json:"automationId,omitempty"`
	Name         string `json:"name"`
	// Rules is "rules: audience ≥ 10,000 · warming-up provider".
	Rules    string         `json:"rules"`
	Author   ApprovalPerson `json:"author"`
	Audience int64          `json:"audience"`
	// AudienceNow is set when the audience moved after approval (15,002 → 17,110).
	AudienceNow *int64 `json:"audienceNow,omitempty"`
	Route       string `json:"route"`
	// Schedule: the snapshot's schedule, or when it was sent.
	ScheduleMode string     `json:"scheduleMode" enum:"now,at,best_time"`
	ScheduleAt   *time.Time `json:"scheduleAt,omitempty"`
	SentAt       *time.Time `json:"sentAt,omitempty"`
	RequestedAt  time.Time  `json:"requestedAt"`
	Status       string     `json:"status" enum:"pending,approved,changes_requested,rejected,invalidated,bypassed,sent,cancelled"`
	DecidedBy    string     `json:"decidedBy,omitempty"`
	DecidedAt    *time.Time `json:"decidedAt,omitempty"`
	// Note is the line under the status ("Marcus Chen: “exclude 180-day unengaged”").
	Note string `json:"note,omitempty"`
}

ApprovalListItem is one row of the approval inbox.

type ApprovalPath

type ApprovalPath struct {
	api.WorkspaceInput
	ApprovalID string `path:"approvalId" format:"uuid"`
}

ApprovalPath is the {workspace}/{approvalId} of approval operations.

type ApprovalPendingItem

type ApprovalPendingItem struct {
	ID          string         `json:"id"`
	Name        string         `json:"name"`
	Author      ApprovalPerson `json:"author"`
	Audience    int64          `json:"audience"`
	RequestedAt time.Time      `json:"requestedAt"`
}

ApprovalPendingItem is a pending request on the policy screen.

type ApprovalPerson

type ApprovalPerson struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Email    string `json:"email"`
	Initials string `json:"initials"`
	Color    string `json:"color"`
	Role     string `json:"role"`
	// Presence is "online" (active in the last 15 minutes) or "active 2 h ago".
	Presence string `json:"presence,omitempty"`
}

ApprovalPerson is a member as approval screens show them.

type ApprovalPolicy

type ApprovalPolicy struct {
	AudienceMin ApprovalAudienceRule `json:"audienceMin"`
	// WarmingProvider: the route includes a provider that is warming up or
	// was connected in the last NewProviderDays days.
	WarmingProvider   bool `json:"warmingProvider"`
	NewProviderDays   int  `json:"newProviderDays" minimum:"1" maximum:"90"`
	ReadyWithWarnings bool `json:"readyWithWarnings"`
	AuthorLacksSend   bool `json:"authorLacksSend"`
	ApprovalLists     bool `json:"approvalLists"`
	ApprovalsRequired int  `json:"approvalsRequired" minimum:"1" maximum:"2"`
	AutomationPublish bool `json:"automationPublish"`
	EmergencyBypass   bool `json:"emergencyBypass"`
}

ApprovalPolicy is the workspace's approval policy.

func ParsePolicy

func ParsePolicy(raw json.RawMessage) ApprovalPolicy

ParsePolicy reads the stored policy. An empty policy is the default of a new workspace (A5 §3.8).

func (ApprovalPolicy) Evaluate

func (p ApprovalPolicy) Evaluate(f RuleFacts) []ApprovalRuleMatch

Evaluate returns the rules that match a send. No match: no approval needed.

func (ApprovalPolicy) RuleLabels

func (p ApprovalPolicy) RuleLabels() []string

RuleLabels are the short phrases of the enabled rules ("audience ≥ 10,000").

type ApprovalPolicyMatches

type ApprovalPolicyMatches struct {
	// Warming is "Postal (mta.acme.io) is warming up, day 9 of 21." or empty.
	Warming string `json:"warming"`
	// LacksSend names the members who can edit but not send.
	LacksSend []string `json:"lacksSend"`
	// LacksSendRoles names their roles ("Content Writers").
	LacksSendRoles []string `json:"lacksSendRoles"`
	// ApprovalLists names the lists marked "Requires approval".
	ApprovalLists []string `json:"approvalLists"`
}

ApprovalPolicyMatches says what each rule matches today.

type ApprovalPolicySummary

type ApprovalPolicySummary struct {
	Rules             []string `json:"rules"`
	ApprovalsRequired int      `json:"approvalsRequired"`
	Approvers         []string `json:"approvers"`
	MedianWaitMinutes *int     `json:"medianWaitMinutes,omitempty"`
}

ApprovalPolicySummary is the "Policy in force" card.

type ApprovalPolicyView

type ApprovalPolicyView struct {
	Policy    ApprovalPolicy        `json:"policy"`
	Approvers []ApprovalPerson      `json:"approvers"`
	Matches   ApprovalPolicyMatches `json:"matches"`
	// BypassCount is how often the emergency bypass was used in 90 days.
	BypassCount int64                 `json:"bypassCount"`
	Pending     []ApprovalPendingItem `json:"pending"`
	CanManage   bool                  `json:"canManage"`
	Reason      string                `json:"reason,omitempty"`
}

ApprovalPolicyView is Settings › Approvals.

type ApprovalPreview

type ApprovalPreview struct {
	Subject   string `json:"subject"`
	Preheader string `json:"preheader"`
	HTML      string `json:"html"`
	Version   int    `json:"version"`
}

ApprovalPreview is the email a request covers.

type ApprovalReadinessView

type ApprovalReadinessView struct {
	Verdict   string                     `json:"verdict" enum:"ready,warnings,blocked"`
	Passed    int                        `json:"passed"`
	Warnings  int                        `json:"warnings"`
	Blocks    int                        `json:"blocks"`
	Total     int                        `json:"total"`
	CheckedAt time.Time                  `json:"checkedAt"`
	Issues    []readiness.ReadinessCheck `json:"issues"`
}

ApprovalReadinessView is the Send Readiness result a request was given on.

type ApprovalRequestInput

type ApprovalRequestInput struct {
	Note string `json:"note,omitempty" maxLength:"2000" doc:"A note for approvers"`
}

ApprovalRequestInput asks for approval.

type ApprovalRequestView

type ApprovalRequestView struct {
	ID          string                 `json:"id"`
	Status      string                 `json:"status" enum:"pending,approved,changes_requested,rejected,invalidated,bypassed,sent,cancelled"`
	SubjectType string                 `json:"subjectType" enum:"campaign,automation"`
	RequestedAt time.Time              `json:"requestedAt"`
	RequestedBy ApprovalPerson         `json:"requestedBy"`
	Note        string                 `json:"note"`
	Version     int                    `json:"version"`
	Given       int                    `json:"given"`
	Needed      int                    `json:"needed"`
	Decisions   []ApprovalDecisionView `json:"decisions"`
	DecidedBy   string                 `json:"decidedBy,omitempty"`
	DecidedAt   *time.Time             `json:"decidedAt,omitempty"`
	// Comment is the latest decision's comment.
	Comment           string                  `json:"comment,omitempty"`
	InvalidatedAt     *time.Time              `json:"invalidatedAt,omitempty"`
	InvalidatedReason string                  `json:"invalidatedReason,omitempty"`
	InvalidatedBy     string                  `json:"invalidatedBy,omitempty"`
	Changes           []ApprovalChange        `json:"changes"`
	Snapshot          ApprovalSnapshotSummary `json:"snapshot"`
	Rules             []ApprovalRuleMatch     `json:"rules"`
	Audit             *ApprovalAuditLine      `json:"audit,omitempty"`
	BypassReason      string                  `json:"bypassReason,omitempty"`
	FollowsID         string                  `json:"followsId,omitempty"`
}

ApprovalRequestView is a request as Review & send and the approval page show it.

type ApprovalRequested

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

ApprovalRequested is the request that was opened.

type ApprovalRouteView

type ApprovalRouteView struct {
	SplitLabel string          `json:"splitLabel"`
	Shares     []ApprovalShare `json:"shares"`
}

ApprovalRouteView is the route part of a request.

type ApprovalRuleMatch

type ApprovalRuleMatch struct {
	Key string `` /* 132-byte string literal not displayed */
	// Label is the sentence ("Audience of 47,912 is at least 10,000"),
	// Short the inbox phrase ("audience ≥ 10,000") and Badge the chip.
	Label string `json:"label"`
	Short string `json:"short"`
	Badge string `json:"badge"`
	// Author is the author's name for "author lacks send" ("You don't hold…"
	// is written by the screen when the author reads it).
	Author string `json:"author,omitempty"`
	Role   string `json:"role,omitempty"`
}

ApprovalRuleMatch is a rule that matched a send.

type ApprovalScheduleView

type ApprovalScheduleView struct {
	Mode     string     `json:"mode" enum:"now,at,best_time"`
	At       *time.Time `json:"at,omitempty"`
	Timezone string     `json:"timezone"`
	Minutes  int        `json:"minutes"`
	// AutoPause is "Bounces 2% · complaints 0.10% per mailbox provider".
	AutoPause string `json:"autoPause"`
}

ApprovalScheduleView is the schedule part of a request.

type ApprovalShare

type ApprovalShare struct {
	ProviderID  string  `json:"providerId"`
	Name        string  `json:"name"`
	Short       string  `json:"short"`
	Label       string  `json:"label,omitempty"`
	Color       string  `json:"color" enum:"ses,postal,postmark,other"`
	Recipients  int64   `json:"recipients"`
	Cost        float64 `json:"cost"`
	PriceLabel  string  `json:"priceLabel"`
	Status      string  `json:"status"`
	StatusLabel string  `json:"statusLabel"`
}

ApprovalShare is one provider of a request's route.

type ApprovalSnapshotSummary

type ApprovalSnapshotSummary struct {
	Version       int    `json:"version"`
	Subject       string `json:"subject"`
	AudienceCount int64  `json:"audienceCount"`
	// RouteLabel is "SES 90 / Postal 10"; RouteText "SES 43,121 · Postal 4,791".
	RouteLabel   string     `json:"routeLabel"`
	RouteText    string     `json:"routeText"`
	SplitLabel   string     `json:"splitLabel"`
	ScheduleText string     `json:"scheduleText"`
	ScheduleMode string     `json:"scheduleMode" enum:"now,at,best_time"`
	ScheduleAt   *time.Time `json:"scheduleAt,omitempty"`
	Timezone     string     `json:"timezone,omitempty"`
}

ApprovalSnapshotSummary is the gist of what a request covers.

type AutomationGate

type AutomationGate struct{ S *Service }

AutomationGate asks for approval before an automation version goes live when the workspace policy says so (automations.PublishGate). Once approved, the approvals domain publishes it with Service.CompletePublish.

func (AutomationGate) Check

Check implements automations.PublishGate, inside the publish transaction.

type CampaignReview

type CampaignReview struct {
	Campaign   ReviewCampaign                `json:"campaign"`
	Run        *readiness.ReadinessRun       `json:"run,omitempty"`
	Stale      bool                          `json:"stale"`
	Running    *readiness.ReadinessProgress  `json:"running,omitempty"`
	Thresholds readiness.ReadinessThresholds `json:"thresholds"`
	Schedule   readiness.ReadinessSchedule   `json:"schedule"`
	TestSends  []ReviewTestSend              `json:"testSends"`
	Approval   ReviewApproval                `json:"approval"`
	Held       *ReviewHeld                   `json:"held,omitempty"`
	Scheduled  *ReviewScheduled              `json:"scheduled,omitempty"`
	Access     ReviewAccess                  `json:"access"`
	// LargeSend is the audience size from which sending asks to type the count.
	LargeSend int64 `json:"largeSend"`
	// PauseSlack is true when a webhook posts campaign.paused to Slack, so a
	// held send is announced there as well as by email.
	PauseSlack bool `json:"pauseSlack"`
	// Timezone is the workspace's.
	Timezone string `json:"timezone"`
}

CampaignReview is the Review & send screen.

type Current

type Current struct {
	Version       int
	ContentHash   string
	Subject       string
	Preheader     string
	SenderID      string
	From          string
	MJML          string
	HTML          string
	Audience      json.RawMessage
	AudienceNames []string
	AudienceCount int64
	RouteKey      string
	SplitLabel    string
	Schedule      json.RawMessage
	Timezone      string
	UpdatedBy     string
}

Current is the campaign as it stands, in snapshot terms.

type HoldDetail

type HoldDetail struct {
	RunID    string                     `json:"run_id"`
	Reason   string                     `json:"reason"`
	Blocks   []readiness.ReadinessCheck `json:"blocks"`
	Blocking []string                   `json:"blocking,omitempty"`
}

HoldDetail is campaign_incidents.detail of a held send. Holds recorded here carry the run and its blocking checks; the sending engine's carry only the titles of what blocked (Blocking).

type ListParams

type ListParams struct {
	Status   string
	Author   string
	Approver string
	Days     int
}

ListParams filter the inbox.

type ReviewAB

type ReviewAB struct {
	Kind          string `json:"kind" enum:"subject,content,send_time"`
	Variants      int    `json:"variants"`
	TestPercent   int    `json:"testPercent"`
	DurationHours int    `json:"durationHours"`
	Label         string `json:"label"`
}

ReviewAB summarises an A/B test ("Subject test · 2 variants · 20% sample").

type ReviewAccess

type ReviewAccess struct {
	CanEdit             bool     `json:"canEdit"`
	CanSend             bool     `json:"canSend"`
	CanApprove          bool     `json:"canApprove"`
	CanManageRouting    bool     `json:"canManageRouting"`
	CanSendTestToOthers bool     `json:"canSendTestToOthers"`
	IsOwner             bool     `json:"isOwner"`
	HasPassword         bool     `json:"hasPassword"`
	Email               string   `json:"email"`
	SendHelpers         []string `json:"sendHelpers"`
}

ReviewAccess is what the viewer may do.

type ReviewApproval

type ReviewApproval struct {
	// Required is true when a rule matches this send by the viewer.
	Required  bool                `json:"required"`
	Rules     []ApprovalRuleMatch `json:"rules"`
	Needed    int                 `json:"needed"`
	Approvers []ApprovalPerson    `json:"approvers"`
	// Request is the open request, or the latest one when none is open.
	Request *ApprovalRequestView `json:"request,omitempty"`
	// Valid is true when an approved request covers the campaign as it is.
	Valid             bool     `json:"valid"`
	CanRequest        bool     `json:"canRequest"`
	RequestReason     string   `json:"requestReason,omitempty"`
	CanBypass         bool     `json:"canBypass"`
	MedianWaitMinutes *int     `json:"medianWaitMinutes,omitempty"`
	PolicyRules       []string `json:"policyRules"`
}

ReviewApproval is the approval side of Review & send.

type ReviewCampaign

type ReviewCampaign struct {
	ID            string     `json:"id"`
	Name          string     `json:"name"`
	Status        string     `json:"status" enum:"draft,approval,approved,scheduled,sending,paused,sent,cancelled,failed"`
	Subject       string     `json:"subject"`
	Preheader     string     `json:"preheader"`
	From          string     `json:"from"`
	ReplyTo       string     `json:"replyTo"`
	Version       int        `json:"version"`
	AutosavedAt   *time.Time `json:"autosavedAt,omitempty"`
	UpdatedAt     time.Time  `json:"updatedAt"`
	UpdatedBy     string     `json:"updatedBy"`
	AudienceLabel string     `json:"audienceLabel"`
	ScheduledAt   *time.Time `json:"scheduledAt,omitempty"`
	StartedAt     *time.Time `json:"startedAt,omitempty"`
	AB            *ReviewAB  `json:"ab,omitempty"`
	// Editable is false once the send started.
	Editable bool `json:"editable"`
}

ReviewCampaign is the campaign as Review & send shows it.

type ReviewHeld

type ReviewHeld struct {
	Since  time.Time                  `json:"since"`
	Reason string                     `json:"reason"`
	Held   int64                      `json:"held"`
	Blocks []readiness.ReadinessCheck `json:"blocks"`
}

ReviewHeld is a scheduled send the send-time recheck held.

type ReviewScheduled

type ReviewScheduled struct {
	By string    `json:"by"`
	At time.Time `json:"at"`
}

ReviewScheduled is who scheduled the campaign and when.

type ReviewSendInput

type ReviewSendInput struct {
	// RunID is the Send Readiness run the person reviewed; the send is
	// refused when the checks ran again or the campaign changed since.
	RunID string `json:"runId" format:"uuid"`
	// Schedule replaces the saved schedule (omit to use it).
	Schedule *readiness.ReadinessSchedule `json:"schedule,omitempty"`
	// Confirm is the recipient count, typed for large sends.
	Confirm string `json:"confirm,omitempty" maxLength:"20"`
	// Acknowledged lists the keys of the warnings the person confirmed.
	Acknowledged []string `json:"acknowledged,omitempty" maxItems:"60"`
}

ReviewSendInput confirms a send from Review & send.

type ReviewSendResult

type ReviewSendResult struct {
	Status      string     `json:"status" enum:"scheduled,sending"`
	ScheduledAt *time.Time `json:"scheduledAt,omitempty"`
	Recipients  int64      `json:"recipients"`
}

ReviewSendResult says what happened.

type ReviewTestSend

type ReviewTestSend struct {
	To       string    `json:"to"`
	At       time.Time `json:"at"`
	By       string    `json:"by"`
	Provider string    `json:"provider"`
	// Delivered names the mailbox provider that accepted it, when known ("Gmail").
	Delivered string `json:"delivered,omitempty"`
}

ReviewTestSend is a recent test email.

type RuleFacts

type RuleFacts struct {
	Recipients int64
	Shares     []RuleShare
	Verdict    string
	Warnings   int
	// AuthorCanSend is whether the person sending holds campaigns:send.
	AuthorCanSend bool
	AuthorName    string
	AuthorRole    string
	// ApprovalLists are the audience's lists marked "Requires approval".
	ApprovalLists []string
	Now           time.Time
}

RuleFacts are what the rules look at.

type RuleShare

type RuleShare struct {
	Short       string
	Recipients  int64
	WarmingUp   bool
	WarmupDay   int
	WarmupDays  int
	ConnectedAt time.Time
}

RuleShare is a provider of the route.

type SendRecheck

type SendRecheck struct {
	// Verdict is "ready", "warnings" or "blocked".
	Verdict string
	// Blocking are the titles of the blocking checks, and why the approval
	// doesn't cover the send when it doesn't.
	Blocking []string
	// Throttles are messages per second per mailbox provider ("outlook": 5);
	// nil keeps the engine's defaults.
	Throttles map[string]float64
	// Audience is the run's final recipient count, RunID the run.
	Audience int64
	RunID    string
}

SendRecheck is Send Readiness as a send starts, in the terms the sending engine asks for (its send-time recheck): the verdict, what blocks and the messages per second Send Readiness set per mailbox provider.

type Service

type Service struct {
	Pool      *pgxpool.Pool
	Q         *store.Queries
	Audit     *audit.Logger
	Log       *slog.Logger
	Now       func() time.Time
	Readiness *readiness.Service
	// Campaigns restores versions ("Restore v9 subject").
	Campaigns *campaigns.Service
	// Sending starts and schedules sends (App.Sending, read at call time).
	Sending func() sending.Starter
	// Automations publishes an automation once its approval is granted.
	Automations *automations.Service
}

Service holds the approvals and Review & send dependencies.

func (*Service) Bypass

Bypass sends without approval: Owners only, with a reason, when the policy allows it. It's logged and every approver is told.

func (*Service) CampaignChanged

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

CampaignChanged re-checks the open approval of a campaign after a change (the composer's and Send Readiness's change hooks call it).

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, ws *store.Workspace, p *authz.Principal, requestID uuid.UUID) error

Cancel withdraws a request (its author, or an Owner).

func (*Service) CheckSendTime

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

CheckSendTime is the recheck when a send starts (add-on 3.8): Send Readiness runs again and the approval must still cover the campaign. It returns an error wrapping sending.ErrNotReady when the send must not start; the campaign is then held and its author and approvers are told. The sending engine calls it before the first batch of a scheduled send.

func (*Service) Comment

func (s *Service) Comment(ctx context.Context, ws *store.Workspace, p *authz.Principal, requestID uuid.UUID, in ApprovalCommentInput) error

Comment adds to a request's discussion (author and approvers).

func (*Service) Decide

func (s *Service) Decide(ctx context.Context, ws *store.Workspace, p *authz.Principal, requestID uuid.UUID, in ApprovalDecisionInput) (uuid.UUID, error)

Decide records an approver's decision. Approving an invalidated request approves the campaign as it stands now (a new request with the diff).

func (*Service) Detail

Detail returns a request for its review screen.

func (*Service) List

List returns the approval inbox: approvers see every request, others their own.

func (*Service) PolicyView

func (s *Service) PolicyView(ctx context.Context, ws *store.Workspace, p *authz.Principal) (ApprovalPolicyView, error)

PolicyView returns the approval policy with what it matches today.

func (*Service) Preview

Preview renders the version a request covers with the personalization fallbacks ("there" for an empty first name).

func (*Service) Remind

func (s *Service) Remind(ctx context.Context, ws *store.Workspace, p *authz.Principal, requestID uuid.UUID) error

Remind notifies the approvers of a pending request again.

func (*Service) RequestApproval

func (s *Service) RequestApproval(ctx context.Context, ws *store.Workspace, p *authz.Principal, campaignID uuid.UUID, in ApprovalRequestInput) (uuid.UUID, error)

RequestApproval asks the workspace's approvers to approve a send.

func (*Service) Restore

func (s *Service) Restore(ctx context.Context, ws *store.Workspace, p *authz.Principal, requestID uuid.UUID) error

Restore puts the campaign back as the snapshot had it (the version, the audience, the route and the schedule), which keeps the approval.

func (*Service) Revalidate

func (s *Service) Revalidate(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID) ([]ApprovalChange, error)

Revalidate compares the open request of a campaign with the campaign and invalidates it when anything it covers changed or the audience moved more than 10%. It returns the invalidated request's changes (none when valid).

func (*Service) Review

func (s *Service) Review(ctx context.Context, ws *store.Workspace, p *authz.Principal, campaignID uuid.UUID) (CampaignReview, error)

Review builds the Review & send screen of a campaign. It re-checks the open approval first, so the screen never shows a stale approval.

func (*Service) SavePolicy

SavePolicy stores the approval policy.

func (*Service) ScheduleApproved

func (s *Service) ScheduleApproved(ctx context.Context, ws *store.Workspace, p *authz.Principal, requestID uuid.UUID, in ReviewSendInput) (ReviewSendResult, error)

ScheduleApproved schedules an approved campaign, as approved (the snapshot's schedule). Its author can do it without campaigns:send.

func (*Service) Send

Send schedules or starts a campaign for a member holding campaigns:send.

func (*Service) SendRecheck

func (s *Service) SendRecheck(ctx context.Context, campaignID uuid.UUID) (SendRecheck, error)

SendRecheck runs Send Readiness for a send that is starting (the run is recorded with the send_time trigger) and checks that the approval, when the send needed one, still covers the campaign. Unlike CheckSendTime it holds nothing and tells nobody: the sending engine does both when the verdict is Blocked, and the review page reads the blocks from this run.

func (*Service) Tick

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

Tick runs the periodic work once.

func (*Service) Unschedule

func (s *Service) Unschedule(ctx context.Context, ws *store.Workspace, p *authz.Principal, campaignID uuid.UUID) error

Unschedule takes a scheduled campaign back. An approved campaign keeps its approval (it can be scheduled again as approved).

type Snapshot

type Snapshot struct {
	Version     int    `json:"version"`
	ContentHash string `json:"content_hash"`
	Subject     string `json:"subject"`
	Preheader   string `json:"preheader"`
	SenderID    string `json:"sender_id,omitempty"`
	From        string `json:"from"`
	// Links lists the email's links in order; Sections its section outline.
	Links    []string `json:"links"`
	Sections []string `json:"sections"`

	Audience       json.RawMessage `json:"audience"`
	AudienceLabels []string        `json:"audience_labels"`
	AudienceCount  int64           `json:"audience_count"`
	// AudienceBaseline is the audience counted the way revalidation counts
	// it, at request time: the audience "moves" against this number.
	AudienceBaseline int64 `json:"audience_baseline,omitempty"`
	Suppressed       int64 `json:"suppressed"`
	Role             int64 `json:"role"`
	Bounced          int64 `json:"bounced"`

	Route      []SnapshotShare `json:"route"`
	RouteKey   string          `json:"route_key"`
	SplitLabel string          `json:"split_label"`
	Minutes    int             `json:"minutes"`
	Cost       float64         `json:"cost"`

	Schedule   json.RawMessage               `json:"schedule"`
	Thresholds readiness.ReadinessThresholds `json:"thresholds"`

	Readiness SnapshotReadiness   `json:"readiness"`
	Rules     []ApprovalRuleMatch `json:"rules"`
	// AuthorRole is the requester's role ("Content Writer").
	AuthorRole string `json:"author_role"`

	Automation *ApprovalAutomationSnapshot `json:"automation,omitempty"`
}

Snapshot is what an approval covers (approval_requests.snapshot): the content and subject, the audience definition and count, the route and the schedule, with the readiness result and estimates it was given on.

func ParseSnapshot

func ParseSnapshot(raw json.RawMessage) Snapshot

ParseSnapshot reads a stored snapshot.

func (Snapshot) Baseline

func (s Snapshot) Baseline() int64

Baseline is the count audience drift is measured against.

type SnapshotReadiness

type SnapshotReadiness struct {
	RunID    string                     `json:"run_id"`
	Verdict  string                     `json:"verdict"`
	Passed   int                        `json:"passed"`
	Warnings int                        `json:"warnings"`
	Blocks   int                        `json:"blocks"`
	Total    int                        `json:"total"`
	RanAt    time.Time                  `json:"ran_at"`
	Issues   []readiness.ReadinessCheck `json:"issues"`
}

SnapshotReadiness is the Send Readiness result an approval was given on.

type SnapshotShare

type SnapshotShare struct {
	ProviderID  string  `json:"provider_id"`
	Name        string  `json:"name"`
	Short       string  `json:"short"`
	Label       string  `json:"label,omitempty"`
	Adapter     string  `json:"adapter"`
	Percent     float64 `json:"percent"`
	Recipients  int64   `json:"recipients"`
	Cost        float64 `json:"cost"`
	PriceLabel  string  `json:"price_label"`
	Status      string  `json:"status"`
	StatusLabel string  `json:"status_label"`
	WarmupDay   int     `json:"warmup_day,omitempty"`
	WarmupDays  int     `json:"warmup_days,omitempty"`
}

SnapshotShare is one provider of the route at request time.

type TickArgs

type TickArgs struct{}

TickArgs is the minute job of Review & send: checks run again 15 minutes before scheduled sends, held sends are rechecked and resumed when a recheck passes, and open approvals are re-checked for audience drift.

func (TickArgs) InsertOpts

func (TickArgs) InsertOpts() river.InsertOpts

InsertOpts implements river.JobArgsWithInsertOpts.

func (TickArgs) Kind

func (TickArgs) Kind() string

Kind implements river.JobArgs.

type TickWorker

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

func (*TickWorker) Timeout

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

Timeout implements river.Worker.

func (*TickWorker) Work

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

Work implements river.Worker.

Jump to

Keyboard shortcuts

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