offers

package
v1.6.0 Latest Latest
Warning

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

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

Documentation

Overview

Package offers is Earn's offers (design expansion phase 6, X17): signup offers readers get by code or link, the retention offer of the hosted cancel page, and referral rewards of single-use codes. Saving an offer creates its coupon and promotion codes in the payment provider; the offer's rules, its results and readers' decisions stay here.

Index

Constants

View Source
const (
	KindSignup    = "signup"
	KindRetention = "retention"
	KindReferral  = "referral"
)

Kinds of offer.

View Source
const RetentionGap = 365 * 24 * time.Hour

RetentionGap is how long after taking a retention offer a paid member can't be offered one again (ROADMAP: one in 12 months).

View Source
const UpgradeBlockAttr = "rc-upgrade"

UpgradeBlockAttr is the Upgrade block's settings attribute (JSON, the composer's: web/src/features/earn/composer/upgrade.ts).

Variables

View Source
var Reasons = []string{"not_reading", "too_expensive", "not_for_me", "switching", "other"}

Reasons are the cancel page's reasons, as the overview sums them.

Functions

func Erasure

func Erasure() erasure.Source

Erasure is the address a single-use offer code was issued to; the code stays for the offer's counts (review 2026-11 DP-1).

func Register

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

Register adds the offers' operations: reading needs earn:view, changing needs earn:edit.

func RegisterJobs

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

RegisterJobs adds the offers job, every 5 minutes.

Types

type CancelOffer

type CancelOffer struct {
	Name   string
	Line   string
	Button string
}

CancelOffer is the retention offer on the page.

type CancelReason

type CancelReason struct {
	Value string
	Label string
}

CancelReason is one of the page's reasons.

type CancelResult

type CancelResult struct {
	View     *CancelView
	Redirect string
}

CancelResult is what deciding did: the page to show, or the provider's address to go to.

type CancelView

type CancelView struct {
	State   string
	Heading string
	Email   string
	Lead    string
	// PastDue: canceling ends access today; BillingURL updates the card.
	PastDue    bool
	BillingURL string
	Reasons    []CancelReason
	Offer      *CancelOffer
	// Keep is the keep button without an offer (none: no button).
	Continue string
	Note     string
	Text     string
	VisitID  string
	Words    map[string]string
}

CancelView is the cancel page in one of its states: ask (the page), kept (took the offer), done (back from the provider), expired (the link) or none (nothing to cancel).

func ExpiredView

func ExpiredView(ctx context.Context) CancelView

ExpiredView is the page of a cancel or billing link that no longer works: past its time, or signed with an earlier instance key. It asks for the member's address to email a new one.

type EndedUpgradeOffer

type EndedUpgradeOffer struct {
	Code string
	Name string
	// EndedOn is the day it ended, when known.
	EndedOn *time.Time
	// Path is the block's element path from mj-body.
	Path []int
}

EndedUpgradeOffer is an offer an email's Upgrade block carries after it ended.

type Offer

type Offer struct {
	ID             string         `json:"id"`
	Name           string         `json:"name"`
	Kind           string         `json:"kind" enum:"signup,retention,referral"`
	DiscountType   string         `json:"discountType" enum:"percent,amount"`
	PercentOff     int            `json:"percentOff,omitempty"`
	AmountOffCents int64          `json:"amountOffCents,omitempty"`
	Currency       string         `json:"currency"`
	Duration       string         `json:"duration" enum:"once,months,forever"`
	Months         int            `json:"months,omitempty"`
	Applies        []OfferApplies `json:"applies"`
	ByCode         bool           `json:"byCode"`
	Code           string         `json:"code"`
	ByLink         bool           `json:"byLink"`
	// Link is the offer link (https://news.acme.io/upgrade?offer=FALL26);
	// LinkHost the same without its scheme.
	Link          string     `json:"link,omitempty"`
	LinkHost      string     `json:"linkHost,omitempty"`
	Limit         *int       `json:"limit,omitempty"`
	EndsAt        *time.Time `json:"endsAt,omitempty"`
	NewOnly       bool       `json:"newOnly"`
	MinPaidMonths int        `json:"minPaidMonths"`
	CodeDays      int        `json:"codeDays"`
	// Status is live or ended; State is what Plans & offers shows: live,
	// at its limit, ended, its coupon missing in the provider, or a draft
	// without one.
	Status      string     `json:"status" enum:"live,ended"`
	State       string     `json:"state" enum:"live,limit,ended,missing,draft"`
	EndedAt     *time.Time `json:"endedAt,omitempty"`
	EndedReason string     `json:"endedReason,omitempty" enum:"date,limit,early"`
	EndedBy     string     `json:"endedBy,omitempty"`
	StartedAt   time.Time  `json:"startedAt"`
	StartedBy   string     `json:"startedBy,omitempty"`
	// Sync is how saving it in the provider went.
	Sync      string       `json:"sync" enum:"draft,synced,failed"`
	SyncError string       `json:"syncError,omitempty"`
	Stripe    OfferStripe  `json:"stripe"`
	Results   OfferResults `json:"results"`
}

Offer is an offer as Plans & offers lists it.

type OfferApplies

type OfferApplies struct {
	TierID string `json:"tierId"`
	Tier   string `json:"tier"`
	// Short is the tier's name without its list's ("Insider").
	Short      string `json:"short"`
	Period     string `json:"period" enum:"month,year"`
	PriceCents int64  `json:"priceCents"`
	Currency   string `json:"currency"`
}

OfferApplies is a tier and period an offer applies to, with its price.

type OfferAppliesInput

type OfferAppliesInput struct {
	TierID string `json:"tierId" format:"uuid"`
	Period string `json:"period" enum:"month,year"`
}

OfferAppliesInput is a tier and period an offer applies to.

type OfferCode

type OfferCode struct {
	Code       string     `json:"code"`
	IssuedTo   string     `json:"issuedTo"`
	IssuedAt   time.Time  `json:"issuedAt"`
	ExpiresAt  time.Time  `json:"expiresAt"`
	RedeemedAt *time.Time `json:"redeemedAt,omitempty"`
	Status     string     `json:"status" enum:"not_redeemed,redeemed,expired"`
}

OfferCode is a referral reward's single-use code.

type OfferDetail

type OfferDetail struct {
	Offer
	Codes []OfferCode `json:"codes"`
	// Choices are the tiers and periods an offer can apply to.
	Choices   []OfferApplies `json:"choices"`
	Account   string         `json:"account"`
	Provider  string         `json:"provider"`
	Connected bool           `json:"connected"`
	CanEdit   bool           `json:"canEdit"`
	Helpers   []string       `json:"helpers"`
	// UpgradeHost is the upgrade page's address without its scheme.
	UpgradeHost string `json:"upgradeHost"`
}

OfferDetail is the offer editor.

type OfferInput

type OfferInput struct {
	Name           string              `json:"name" maxLength:"80"`
	Kind           string              `json:"kind" enum:"signup,retention,referral"`
	DiscountType   string              `json:"discountType" enum:"percent,amount"`
	PercentOff     int                 `json:"percentOff,omitempty"`
	AmountOffCents int64               `json:"amountOffCents,omitempty"`
	Duration       string              `json:"duration" enum:"once,months,forever"`
	Months         int                 `json:"months,omitempty"`
	Applies        []OfferAppliesInput `json:"applies" maxItems:"40"`
	ByCode         bool                `json:"byCode,omitempty"`
	Code           string              `json:"code,omitempty" maxLength:"40"`
	ByLink         bool                `json:"byLink,omitempty"`
	Limit          *int                `json:"limit,omitempty"`
	// EndsOn is the last day of the offer, which ends at 23:59 in the
	// workspace's time zone.
	EndsOn        string `json:"endsOn,omitempty" doc:"YYYY-MM-DD"`
	NewOnly       bool   `json:"newOnly,omitempty"`
	MinPaidMonths int    `json:"minPaidMonths,omitempty"`
	CodeDays      int    `json:"codeDays,omitempty"`
}

OfferInput creates or changes an offer.

type OfferList

type OfferList struct {
	Items []Offer `json:"items"`
	// Account names the provider's account ("Acme Media"); Connected: a
	// provider takes payments.
	Account   string   `json:"account"`
	Provider  string   `json:"provider"`
	Connected bool     `json:"connected"`
	CanEdit   bool     `json:"canEdit"`
	Helpers   []string `json:"helpers"`
}

OfferList is Plans & offers' offers.

type OfferResults

type OfferResults struct {
	// Signup: paid members on the offer, new ones, and their MRR after the
	// discount.
	Redemptions int64 `json:"redemptions"`
	NewMembers  int64 `json:"newMembers"`
	MRRCents    int64 `json:"mrrCents"`
	// Retention: shown on the cancel page, and kept with it.
	Shown      int64    `json:"shown"`
	Accepted   int64    `json:"accepted"`
	AcceptRate *float64 `json:"acceptRate,omitempty"`
	// Referral: codes issued and redeemed.
	CodesIssued   int64 `json:"codesIssued"`
	CodesRedeemed int64 `json:"codesRedeemed"`
}

OfferResults is what an offer did.

type OfferStripe

type OfferStripe struct {
	Mode   string `json:"mode,omitempty"`
	Coupon string `json:"coupon,omitempty"`
	// PromotionCode is the code readers type, as the provider names it
	// (promo_1Q9bX2rT).
	PromotionCode string `json:"promotionCode,omitempty"`
	// Missing: the coupon no longer exists in the provider.
	Missing bool `json:"missing"`
	// CouponURL opens it in the provider's dashboard.
	CouponURL string `json:"couponUrl,omitempty"`
}

OfferStripe is the offer in the payment provider.

type ReferralCode

type ReferralCode struct {
	Code      string
	ClaimURL  string
	ExpiresAt time.Time
}

ReferralCode is an issued single-use code and the link that applies it: the referrer's own upgrade link, the only one the code works with.

type ReferralOffer

type ReferralOffer struct {
	ID   uuid.UUID
	Name string
	// Discount and AppliesTo are in the reader's language: "100% off for 3
	// months", "Insider · monthly".
	Discount  string
	AppliesTo string
	Issued    int64
	Redeemed  int64
}

ReferralOffer is a live referral offer a milestone can reward with.

type Retention

type Retention struct {
	ID       uuid.UUID
	Name     string
	Coupon   string
	Currency string
	Period   string
	// PriceCents is what they'd pay with it, FullCents without; Months is
	// how long (0: once, -1: forever).
	PriceCents int64
	FullCents  int64
	Months     int
}

Retention is the retention offer a paid member gets on the cancel page.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Earn  *earn.Service
	Log   *slog.Logger
	Now   func() time.Time
	// contains filtered or unexported fields
}

Service is the offers domain.

func (*Service) CancelDecide

func (s *Service) CancelDecide(ctx context.Context, ws *store.Workspace, token, visitID, reason, decision, returnURL string) (CancelResult, error)

CancelDecide takes the page's answer: keep (with the offer) or continue to the provider's cancel step. The reason, when given, goes with it.

func (*Service) CancelPage

func (s *Service) CancelPage(ctx context.Context, ws *store.Workspace, token string, done bool) (CancelView, error)

CancelPage is the page for a cancel link. done is the return from the provider's portal. Each visit is counted once per half hour.

func (*Service) CheckoutCode

func (s *Service) CheckoutCode(ctx context.Context, ws *store.Workspace, mode, code string, reader, tier uuid.UUID, period string) string

CheckoutCode implements earn.OfferHook: a signup offer's code, or a referral reward's single-use code while it's unused and unexpired, for the reader it was issued to.

func (*Service) CodeRedeemed

func (s *Service) CodeRedeemed(ctx context.Context, tx pgx.Tx, ws *store.Workspace, code string, at time.Time) error

CodeRedeemed implements earn.OfferCodeRedeemer: a subscription took a single-use code (a code that isn't one changes nothing).

func (*Service) ComposerOffers

func (s *Service) ComposerOffers(ctx context.Context, ws *store.Workspace, tier uuid.UUID) []earn.EarnComposerOffer

ComposerOffers implements earn.ComposerOfferHook: the live signup offers on a tier, each with the period it applies to (the year when it applies to both), as the Upgrade block's settings and card say them.

func (*Service) Create

Create saves a new offer and creates its coupon and codes in the provider. A provider that's down leaves it a draft to save again.

func (*Service) Detail

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

Detail is the offer editor: the offer, its codes and the tiers it can apply to. Opening it checks that the coupon still exists in the provider.

func (*Service) End

End ends an offer now: its code stops working; paid members who used it keep their discount.

func (*Service) EndedUpgradeOffers

func (s *Service) EndedUpgradeOffers(ctx context.Context, ws *store.Workspace, src string) []EndedUpgradeOffer

EndedUpgradeOffers are the offers of an email's Upgrade blocks that no longer work: ended, past their date, at their limit or gone from the provider.

func (*Service) IssueReferralCode

func (s *Service) IssueReferralCode(ctx context.Context, ws *store.Workspace, offerID, contactID uuid.UUID, validDays int) (ReferralCode, error)

IssueReferralCode creates a single-use promotion code of a referral offer in the payment provider for a contact and records it; validDays of 0 uses the offer's own validity.

func (*Service) List

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

List is Plans & offers' offers with their results.

func (*Service) New

New is the editor of a new offer: its choices only.

func (*Service) PeriodFor

func (s *Service) PeriodFor(ctx context.Context, ws *store.Workspace, code string, reader uuid.UUID) string

PeriodFor is the period an offer link opens the page on: the one it applies to, when it applies to one. A code that isn't one counts against the address in UpgradeOffer, once per page, rather than here.

func (*Service) Recreate

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

Recreate creates the offer's coupon again after it was deleted in the provider.

func (*Service) ReferralClaimURL

func (s *Service) ReferralClaimURL(ctx context.Context, ws *store.Workspace, contactID uuid.UUID, code string) string

ReferralClaimURL is the link that applies a referral reward's code: its referrer's personal upgrade link, the only one the code works with.

func (*Service) ReferralOffers

func (s *Service) ReferralOffers(ctx context.Context, ws *store.Workspace) ([]ReferralOffer, error)

ReferralOffers lists the workspace's live referral offers.

func (*Service) RetentionFor

func (s *Service) RetentionFor(ctx context.Context, ws *store.Workspace, mode string, sub store.PaidSubscription) (*Retention, error)

RetentionFor is the retention offer a paid member is eligible for, or nil: the offer applies to their tier and period, they've paid for at least its months, they're not past due or on a discount, and they took no retention offer in the last 12 months.

func (*Service) Tick

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

Tick ends the live offers whose date passed or whose limit is reached. Ending is the system's, so it's audited without a person.

func (*Service) Update

Update changes an offer. A changed discount is a new coupon in the provider (codes already used keep theirs); a changed code, limit or date is a new promotion code. Raising the limit or moving the date of an offer that ended by them brings it back.

func (*Service) UpgradeOffer

func (s *Service) UpgradeOffer(ctx context.Context, ws *store.Workspace, mode, code string, reader uuid.UUID, v *earn.UpgradeView) error

UpgradeOffer implements earn.OfferHook: the offer's lines in the page's language (the view's).

type TickArgs

type TickArgs struct{}

TickArgs is the periodic offers job: offers past their date or at their limit end, and their codes are turned off.

func (TickArgs) InsertOpts

func (TickArgs) InsertOpts() river.InsertOpts

InsertOpts runs on the maintenance queue, once at a time.

func (TickArgs) Kind

func (TickArgs) Kind() string

Kind implements river.JobArgs.

type TickWorker

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

TickWorker runs TickArgs.

func (*TickWorker) Timeout

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

Timeout bounds one run.

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