coupons

package
v1.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: AGPL-3.0 Imports: 40 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package coupons is unique discount codes per recipient (M59 G-22): pools of codes uploaded or created in a connected Shopify or WooCommerce store, one code handed to each campaign message and automation email that shows the pool's code ({{ coupons.<slug>.code }}, or the Discount code block), store orders matched to the codes they used, and each pool's numbers.

A code is handed out only when the sending engine sends (liquid.Allocating): one statement per pool and page, the same code again when a page is sent again, the contact's earlier code when the pool gives one per contact. Previews and test sends show the pool's prefix with SAMPLE1; view online and link redirects read the code the message was given.

Codes are sealed at rest (secrets box, "coupon_code:<pool>") with a keyed hash of the upper-cased code for duplicates and order matching; lists never show them, and the CSV export (coupons:manage) is audited. Giving a code out isn't audited: the message holds it.

Index

Constants

View Source
const (
	SourceUpload  = "upload"
	SourceShopify = "shopify"
	SourceWoo     = "woocommerce"
)

Sources of a pool's codes.

View Source
const (
	StatusActive   = "active"
	StatusArchived = "archived"
)

Statuses of a pool.

View Source
const (
	KindPercentage   = "percentage"
	KindFixedAmount  = "fixed_amount"
	KindFreeShipping = "free_shipping"
)

What a store pool's discount takes off.

View Source
const (
	// MaxUploadBytes and MaxUploadCodes bound one upload of codes.
	MaxUploadBytes = 6 << 20
	MaxUploadCodes = 100_000
	// MaxGenerate is the most codes one request creates in a store.
	MaxGenerate = 50_000
)

Limits.

View Source
const (
	FailUnreachable = "unreachable"
	FailNotGranted  = "not_granted"
	FailStoreGone   = "store_gone"
	FailArchived    = "archived"
	FailEnded       = "ended"
	FailUnsupported = "unsupported"
)

Why a batch failed (coupon_batches.error; the pool page says it in the reader's language): the store's refusals (commerce's reasons), the store not answering, or the pool changing under it.

View Source
const IssuePool = "content.coupon_pool"

IssuePool is the composer's check and Send Readiness's row about a Discount code block's pool.

View Source
const Root = "coupons"

Root is the Liquid variable the pools' codes are under.

Variables

This section is empty.

Functions

func CodeHash

func CodeHash(ws uuid.UUID, code string) []byte

CodeHash is the keyed hash of a code within a workspace, upper-cased: a pool keeps a code once, and a store order finds the code it used by it.

func Erasure

func Erasure() erasure.Source

Erasure is the codes contacts were given: erasing a contact clears who got a code and in which message; the code stays given, so it's never handed out again. The data export lists the contact's codes, opened.

func ExpandBlock

func ExpandBlock(b CouponBlock) string

ExpandBlock is the Discount code block as Liquid: the label, the code in a dashed box and the button, centred (ComposerTimedBlocks).

func Register

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

Register adds the discount code operations: pools are seen with campaigns:view; every change and the export need coupons:manage and a person.

func RegisterJobs

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

RegisterJobs adds the workers and the hourly schedule.

Types

type CouponArchiveInput

type CouponArchiveInput struct {
	Confirm bool `json:"confirm,omitempty" doc:"Archive even though live automations send its codes"`
}

CouponArchiveInput confirms archiving a pool live automations use.

type CouponBatch

type CouponBatch struct {
	ID   string `json:"id" format:"uuid"`
	Kind string `json:"kind" enum:"upload,generate"`
	// Reason: the pool's first codes, a member asking for more, or the
	// hourly refill (Automation names the live flow it refilled for).
	Reason     string `json:"reason" enum:"pool,request,refill"`
	Automation string `json:"automation,omitempty"`
	By         string `json:"by,omitempty" doc:"Who asked, by name"`
	Requested  int    `json:"requested"`
	Created    int    `json:"created"`
	// Failed are codes the store refused or the pool had already.
	Failed int    `json:"failed"`
	Status string `json:"status" enum:"running,done,failed"`
	// Error says why the batch failed, or why a running one waits to try
	// again: unreachable, not_granted, read_only, not_connected,
	// unsupported, store_gone, archived or ended.
	Error string `json:"error,omitempty"`
	// WaitingUntil: the store asked ReputeCast to slow down; it goes on then.
	WaitingUntil *time.Time `json:"waitingUntil,omitempty"`
	CreatedAt    time.Time  `json:"createdAt"`
	FinishedAt   *time.Time `json:"finishedAt,omitempty"`
}

CouponBatch is an upload or a request to create codes.

type CouponBlock

type CouponBlock struct {
	Pool      string `json:"pool"`
	Label     string `json:"label"`
	Button    string `json:"button"`
	ButtonURL bool   `json:"buttonUrl"`
}

CouponBlock is the Discount code block's settings.

type CouponCodesFile

type CouponCodesFile struct {
	ContentType        string `header:"Content-Type"`
	ContentDisposition string `header:"Content-Disposition"`
	CacheControl       string `header:"Cache-Control"`
	Body               []byte
}

CouponCodesFile is a pool's codes as CSV.

type CouponCodesResult

type CouponCodesResult struct {
	Added int64 `json:"added"`
	// Duplicates were in the upload twice or in the pool already.
	Duplicates int64 `json:"duplicates"`
	// Invalid aren't 3–64 letters, digits, - or _; InvalidLines are the
	// first three of them.
	Invalid      int64               `json:"invalid"`
	InvalidLines []CouponInvalidLine `json:"invalidLines"`
	Free         int64               `json:"free"`
}

CouponCodesResult is what an upload added.

type CouponGenerateInput

type CouponGenerateInput struct {
	Count int `json:"count" minimum:"1" maximum:"50000"`
}

CouponGenerateInput asks a store pool for more codes.

type CouponInvalidLine

type CouponInvalidLine struct {
	Line int    `json:"line" doc:"1 is the first line"`
	Text string `json:"text" doc:"The line, up to 40 characters"`
}

CouponInvalidLine is a line of an upload that isn't a code.

type CouponPool

type CouponPool struct {
	CouponPoolListItem
	Removed int64            `json:"removed"`
	Tokens  CouponPoolTokens `json:"tokens"`
	// SampleURL is the code's link with the sample code previews show
	// ("" without an address).
	SampleURL string `json:"sampleUrl"`
	// Orders that used the pool's codes; FirstSentAt when it first gave one.
	Orders      int64      `json:"orders"`
	FirstSentAt *time.Time `json:"firstSentAt,omitempty"`
	CreatedBy   string     `json:"createdBy" doc:"Who created the pool, by name"`
	// Batch is the latest request to create codes (running or not);
	// Batches every upload and request, newest first.
	Batch   *CouponBatch    `json:"batch,omitempty"`
	Batches []CouponBatch   `json:"batches"`
	UsedIn  []CouponPoolUse `json:"usedIn"`
	// Refill: a live automation uses the store pool, so the hourly job
	// keeps it topped up; RefillCheckedAt is when it last looked.
	Refill          bool       `json:"refill"`
	RefillCheckedAt *time.Time `json:"refillCheckedAt,omitempty"`
	// Waiting are the flows whose emails wait for a code from the pool.
	Waiting []CouponPoolWaiting `json:"waiting"`
	// Helpers are members who can manage discount codes (who to ask).
	Helpers   []string  `json:"helpers"`
	UpdatedAt time.Time `json:"updatedAt"`
}

CouponPool is a pool's page.

type CouponPoolChange

type CouponPoolChange struct {
	Name          *string             `json:"name,omitempty" maxLength:"200"`
	Settings      *CouponPoolSettings `json:"settings,omitempty"`
	Prefix        *string             `json:"prefix,omitempty" maxLength:"40"`
	OnePerContact *bool               `json:"onePerContact,omitempty"`
	LowAt         *int                `json:"lowAt,omitempty"`
}

CouponPoolChange changes a pool; missing fields stay.

type CouponPoolInput

type CouponPoolInput struct {
	Name          string             `json:"name" maxLength:"200"`
	Slug          string             `json:"slug" maxLength:"64" doc:"1–32 lowercase letters, digits or _; never changes"`
	Source        string             `json:"source" enum:"upload,shopify,woocommerce"`
	StoreID       string             `json:"storeId,omitempty" maxLength:"40"`
	Settings      CouponPoolSettings `json:"settings,omitempty"`
	Prefix        string             `json:"prefix,omitempty" maxLength:"40"`
	OnePerContact *bool              `json:"onePerContact,omitempty" doc:"Default true"`
	LowAt         *int               `json:"lowAt,omitempty" doc:"Default 200"`
}

CouponPoolInput creates a pool.

type CouponPoolList

type CouponPoolList struct {
	Items []CouponPoolListItem `json:"items"`
	// Helpers are members who can manage discount codes (who to ask).
	Helpers []string `json:"helpers"`
}

CouponPoolList is the pools of a workspace, active first.

type CouponPoolListItem

type CouponPoolListItem struct {
	ID     string           `json:"id" format:"uuid"`
	Name   string           `json:"name"`
	Slug   string           `json:"slug" doc:"The name templates use: {{ coupons.<slug>.code }}"`
	Source string           `json:"source" enum:"upload,shopify,woocommerce"`
	Store  *CouponPoolStore `json:"store,omitempty"`
	Status string           `json:"status" enum:"active,archived"`
	Prefix string           `json:"prefix"`
	// Total are the codes the pool holds (not removed); Free nobody got.
	Total        int64  `json:"total"`
	Free         int64  `json:"free"`
	Sent         int64  `json:"sent"`
	Redeemed     int64  `json:"redeemed"`
	RevenueCents int64  `json:"revenueCents" doc:"Orders that used the pool's codes: refunds taken off, cancelled and test orders left out"`
	Currency     string `json:"currency"`
	LowAt        int    `json:"lowAt"`
	Low          bool   `json:"low" doc:"Free codes are under the low mark"`
	// Settings say what a store pool's discount takes off, or where an
	// upload pool's codes apply.
	Settings      CouponPoolSettings `json:"settings"`
	OnePerContact bool               `json:"onePerContact"`
	// Running is the request to create codes in the store under way.
	Running   *CouponBatch `json:"running,omitempty"`
	CreatedAt time.Time    `json:"createdAt"`
}

CouponPoolListItem is one row of Campaigns › Discount codes. Codes are never in it.

type CouponPoolPath

type CouponPoolPath struct {
	api.WorkspaceInput
	Pool string `path:"pool" format:"uuid" doc:"Pool id"`
}

CouponPoolPath names a pool in a workspace.

type CouponPoolSettings

type CouponPoolSettings struct {
	Kind          string   `json:"kind,omitempty" enum:"percentage,fixed_amount,free_shipping," doc:"Store pools: what the discount takes off"`
	Value         int64    `json:"value,omitempty" minimum:"0" doc:"Percent off (1–100) for percentage, cents off for fixed_amount"`
	MinimumCents  int64    `json:"minimumCents,omitempty" minimum:"0" doc:"Store pools: the smallest order the code works on, in cents"`
	CollectionIDs []string `` /* 128-byte string literal not displayed */
	EndsDays      int      `` /* 139-byte string literal not displayed */
	ApplyURL      string   `json:"applyUrl,omitempty" maxLength:"500" doc:"Upload pools: the address that applies a code, with {code} where it goes"`
}

CouponPoolSettings are a pool's settings as stored (coupon_pools.settings) and shown: a store pool's discount, an upload pool's apply address.

type CouponPoolStore

type CouponPoolStore struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Platform  string `json:"platform" enum:"shopify,woocommerce"`
	Domain    string `json:"domain"`
	Connected bool   `json:"connected"`
}

CouponPoolStore is the store a pool's codes are created in.

type CouponPoolTokens

type CouponPoolTokens struct {
	Code string `json:"code" example:"{{ coupons.welcome15.code }}"`
	URL  string `json:"url" example:"{{ coupons.welcome15.url }}"`
}

CouponPoolTokens are the Liquid a template shows the pool's code with.

type CouponPoolUse

type CouponPoolUse struct {
	Kind string `json:"kind" enum:"campaign,automation,template"`
	// ID is the campaign's, the automation's (with EmailID) or the
	// template's.
	ID   string `json:"id"`
	Name string `json:"name"`
	// EmailID and EmailName are the automation's email.
	EmailID   string `json:"emailId,omitempty"`
	EmailName string `json:"emailName,omitempty"`
	// Status is the campaign's or the automation's.
	Status string `json:"status,omitempty"`
	// Lists and Recipients are a campaign's audience.
	Lists      string `json:"lists,omitempty"`
	Recipients int64  `json:"recipients"`
	// Block: the Discount code block shows the code (else Liquid does).
	Block bool `json:"block"`
	// Live: an automation that's live (archiving the pool asks first).
	Live bool `json:"live"`
}

CouponPoolUse is a campaign, automation email or template that shows the pool's codes.

type CouponPoolWaiting

type CouponPoolWaiting struct {
	ID     string `json:"id"`
	Name   string `json:"name"`
	Emails int64  `json:"emails"`
}

CouponPoolWaiting is a flow whose emails wait for one of the pool's codes.

type CouponRemoveResult

type CouponRemoveResult struct {
	Removed int64 `json:"removed"`
}

CouponRemoveResult is how many unused codes were removed.

type CouponSource

type CouponSource struct {
	StoreID  string `json:"storeId"`
	Platform string `json:"platform" enum:"shopify,woocommerce"`
	Name     string `json:"name"`
	Domain   string `json:"domain"`
	Currency string `json:"currency"`
	Can      bool   `json:"can"`
	// Reason and Detail say why a store can't create codes.
	Reason string `json:"reason,omitempty" enum:"not_connected,not_granted,unsupported,read_only,"`
	Detail string `json:"detail,omitempty"`
}

CouponSource is a store as a source of codes for the New pool dialog.

type CouponSourceList

type CouponSourceList struct {
	Items []CouponSource `json:"items"`
}

CouponSourceList is the stores a pool can create codes in.

type GenerateArgs

type GenerateArgs struct {
	BatchID string `json:"batch_id"`
}

GenerateArgs creates a batch's codes in its store (coupons.generate).

func (GenerateArgs) InsertOpts

func (GenerateArgs) InsertOpts() river.InsertOpts

InsertOpts: one job per batch.

func (GenerateArgs) Kind

func (GenerateArgs) Kind() string

Kind implements river.JobArgs.

type GenerateWorker

type GenerateWorker struct {
	river.WorkerDefaults[GenerateArgs]
	S *Service
}

GenerateWorker runs GenerateArgs.

func (*GenerateWorker) Timeout

Timeout leaves the step budget room.

func (*GenerateWorker) Work

Work implements river.Worker: the store's throttle and its background job snooze it; the last failed attempt fails the batch.

type ReadinessLink struct {
	Label i18n.Text
	Href  string
}

ReadinessLink is a row's link: its label and the workspace path it opens.

type ReadinessRow

type ReadinessRow struct {
	Status                      string // pass or block
	Title, Detail, Label, Short i18n.Text
	Links                       []ReadinessLink
}

ReadinessRow is a pool's row in Send Readiness's Content group. Its texts are kept messages: Send Readiness writes them in each reader's language.

type RefillArgs

type RefillArgs struct{}

RefillArgs is the hourly job (coupons.refill): store pools that live automations send keep max(low mark, 1.2 × the last 7 days' use) free codes; pools under their low mark tell coupons:manage holders once; batches and removals left unfinished go on.

func (RefillArgs) InsertOpts

func (RefillArgs) InsertOpts() river.InsertOpts

InsertOpts: one an hour.

func (RefillArgs) Kind

func (RefillArgs) Kind() string

Kind implements river.JobArgs.

type RefillWorker

type RefillWorker struct {
	river.WorkerDefaults[RefillArgs]
	S *Service
}

RefillWorker runs RefillArgs.

func (*RefillWorker) Work

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

Work implements river.Worker.

type RemoveArgs

type RemoveArgs struct {
	PoolID string `json:"pool_id"`
}

RemoveArgs removes a store pool's removed codes from the store too (coupons.remove).

func (RemoveArgs) InsertOpts

func (RemoveArgs) InsertOpts() river.InsertOpts

InsertOpts: one job per pool.

func (RemoveArgs) Kind

func (RemoveArgs) Kind() string

Kind implements river.JobArgs.

type RemoveWorker

type RemoveWorker struct {
	river.WorkerDefaults[RemoveArgs]
	S *Service
}

RemoveWorker runs RemoveArgs.

func (*RemoveWorker) Work

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

Work implements river.Worker.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Log   *slog.Logger
	Now   func() time.Time
	// Jobs queues the jobs that create codes in stores and remove them
	// there; nil leaves them to the hourly job.
	Jobs func() *jobs.Client
	// Discounts opens a connected store's discount creator
	// (internal/commerce); it answers a problem saying why a store can't.
	Discounts func(ctx context.Context, ws *store.Workspace, storeID uuid.UUID) (stores.DiscountCreator, error)
	// Sources lists the workspace's stores and whether each can create
	// discount codes, from what ReputeCast knows (no call to the store).
	Sources func(ctx context.Context, ws *store.Workspace) ([]StoreSource, error)
}

Service is the discount codes domain.

func (*Service) Archive

func (s *Service) Archive(ctx context.Context, ws *store.Workspace, id uuid.UUID, confirm bool) (CouponPool, error)

Archive stops a pool from giving codes. When live automations send its codes it answers 409 unless confirm.

func (*Service) ComposerIssues

func (s *Service) ComposerIssues(ctx context.Context, ws *store.Workspace, _ uuid.UUID, src string) []contentcheck.ContentCheckIssue

ComposerIssues implements campaigns.MoreChecks: a Warn for a pool the email names that doesn't exist or is archived, on the element naming it.

func (*Service) ComposerTokens

func (s *Service) ComposerTokens(ctx context.Context, ws *store.Workspace) []liquid.PersonalizationToken

ComposerTokens are the active pools' tokens for the composer's token menu, labelled in the member's language.

func (*Service) Create

Create adds a pool.

func (*Service) EmailHold

func (s *Service) EmailHold(ctx context.Context, wsID, emailID uuid.UUID, version int, contactID uuid.UUID) (string, error)

EmailHold implements automations.EmailHold: an automation email that shows a pool's code waits while the pool has none for the contact (no_codes), and the pool's low alert fires.

func (*Service) Export

func (s *Service) Export(ctx context.Context, ws *store.Workspace, id uuid.UUID) ([]byte, string, error)

Export is the pool's codes as CSV (code, status, assigned_at, redeemed_at, order), audited with its row count.

func (*Service) Generate

func (s *Service) Generate(ctx context.Context, batchID uuid.UUID) (time.Duration, error)

Generate works on a batch for up to stepBudget: it creates the store's discount once, then adds the codes MaxCodesPerCall at a time, following the store's background job. Only codes the store confirms become free. It returns how long to wait before going on (0: done).

func (*Service) Get

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

Get is a pool's page: its numbers, settings, latest batch and what uses it.

func (*Service) List

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

List is the workspace's pools with their numbers.

func (*Service) PublishChecks

PublishChecks implements automations.EmailPublishChecker: a badge for a pool the flow's emails name that is under its low mark, archived or doesn't exist, in the member's language.

func (*Service) ReadinessRows

func (s *Service) ReadinessRows(ctx context.Context, ws *store.Workspace, campaignID uuid.UUID, html string, recipients int64, at func(time.Time) any) []ReadinessRow

ReadinessRows are the rows of the pools a campaign's HTML shows codes from, for its recipients: Block when an upload pool has fewer free codes than recipients, when a store pool is short (with the batch creating them), when the pool is archived or its store isn't connected. at writes a moment as Send Readiness keeps it (in each reader's time zone).

func (*Service) Redeemed

func (s *Service) Redeemed(ctx context.Context, q *store.Queries, wsID, orderID uuid.UUID, codes []string, at time.Time) error

Redeemed implements commerce.Service.Redeemed: each code an order used redeems the first matching code of the workspace, once per order.

func (*Service) Refill

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

Refill is one pass of the hourly job.

func (*Service) RemoveAtStore

func (s *Service) RemoveAtStore(ctx context.Context, poolID uuid.UUID) error

RemoveAtStore removes a store pool's removed codes in the store, a call's worth at a time; each code removed there loses its store id.

func (*Service) RemoveUnused

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

RemoveUnused removes every code nobody got yet; a store pool's codes are then removed in the store too (RemoveArgs).

func (*Service) RequestCodes

func (s *Service) RequestCodes(ctx context.Context, ws *store.Workspace, id uuid.UUID, count int) (CouponBatch, error)

RequestCodes asks a store pool for count more codes: a batch and its job, audited (coupon_pool.codes_requested).

func (*Service) Roots

func (s *Service) Roots() []string

Roots implements liquid.RecipientData.

func (*Service) SourceList

func (s *Service) SourceList(ctx context.Context, ws *store.Workspace) (CouponSourceList, error)

Sources are the workspace's stores and whether each can create codes.

func (*Service) Update

Update changes a pool. A store pool's discount can't change once it was created in the store.

func (*Service) Upload

func (s *Service) Upload(ctx context.Context, ws *store.Workspace, id uuid.UUID, body []byte) (CouponCodesResult, error)

Upload adds codes to an upload pool from text or a CSV. Codes are sealed and only the counts go in the audit log.

func (*Service) Vars

func (s *Service) Vars(ctx context.Context, wsID uuid.UUID, recipients []liquid.Recipient, _ []string) (map[uuid.UUID]map[string]any, error)

Vars implements liquid.RecipientData: coupons.<slug>.code and .url for every pool the template names. A real send (liquid.Allocating) hands each message its code, one statement per pool; a reader left without one gets liquid.ShortKey and the pool's low alert fires. Otherwise a message reads the code it was given, and a render without a message (preview, test send) shows the prefix and SAMPLE1.

type StoreSource

type StoreSource struct {
	StoreID                uuid.UUID
	Platform, Name, Domain string
	Currency               string
	Can                    bool
	Reason, Detail         string
}

StoreSource is a connected store as a source of codes.

Jump to

Keyboard shortcuts

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