Documentation
¶
Overview ¶
Package gifts is Earn's gift subscriptions (design expansion phase 6, X17): gift options (a tier for a fixed period at a one-time price), the hosted gift page and its one payment through the provider, delivery on the date the buyer picked, redemption without a card, the reminders, and Earn › Gifts. A gift is never revenue in MRR: its sale is income of the day it's paid, and its access is like complimentary access.
Index ¶
- Constants
- Variables
- func Erasure() erasure.Source
- func NormalizeCode(code string) string
- func Register(h huma.API, s *Service)
- func RegisterJobs(reg *jobs.Registry, s *Service)
- func TextIn(l i18n.Lang, key string, args i18n.Args) string
- type BuyInput
- type GiftCounts
- type GiftDeliveryInput
- type GiftEmail
- type GiftEndingWarning
- type GiftEvent
- type GiftLink
- type GiftList
- type GiftMonthsCount
- type GiftNumbers
- type GiftOption
- type GiftOptionInput
- type GiftPage
- type GiftPageInput
- type GiftRow
- type GiftTier
- type GiftsFile
- type GiftsView
- type Join
- type PageOption
- type PageView
- type RedeemInput
- type RedeemView
- type Service
- func (s *Service) Buy(ctx context.Context, ws *store.Workspace, in BuyInput) (string, *PageView, error)
- func (s *Service) ChangeDelivery(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, ...) (GiftRow, error)
- func (s *Service) CheckoutCompleted(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, ...) (bool, map[string]any, error)
- func (s *Service) CheckoutFailed(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, ...) (bool, map[string]any, error)
- func (s *Service) CopyLink(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (GiftLink, error)
- func (s *Service) CreateOption(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (GiftOption, error)
- func (s *Service) DeleteOption(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) error
- func (s *Service) Export(ctx context.Context, ws *store.Workspace, filter, search string) ([]byte, int, error)
- func (s *Service) List(ctx context.Context, ws *store.Workspace, filter, search string, pageNo int) (GiftList, error)
- func (s *Service) Page(ctx context.Context, ws *store.Workspace, in BuyInput, canceled bool) (PageView, error)
- func (s *Service) Redeem(ctx context.Context, ws *store.Workspace, code string, in RedeemInput) (RedeemView, error)
- func (s *Service) RedeemHost(ctx context.Context, ws *store.Workspace, code string) string
- func (s *Service) RedeemPage(ctx context.Context, ws *store.Workspace, code string) (RedeemView, error)
- func (s *Service) RedeemURL(ctx context.Context, ws *store.Workspace, code string) string
- func (s *Service) Refunded(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, ...) (bool, map[string]any, error)
- func (s *Service) Resend(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (GiftRow, error)
- func (s *Service) Row(ctx context.Context, ws *store.Workspace, id uuid.UUID) (GiftRow, error)
- func (s *Service) SetPage(ctx context.Context, ws *store.Workspace, p *authz.Principal, in GiftPageInput) (GiftPage, error)
- func (s *Service) Thanks(ctx context.Context, ws *store.Workspace, session string) (ThanksView, error)
- func (s *Service) Tick(ctx context.Context) error
- func (s *Service) UpdateOption(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, ...) (GiftOption, error)
- func (s *Service) View(ctx context.Context, ws *store.Workspace, p *authz.Principal) (GiftsView, error)
- type Signup
- type ThanksView
- type TickArgs
- type TickWorker
Constants ¶
const ( StatusCheckout = "checkout" StatusPaid = "paid" StatusDelivered = "delivered" StatusRedeemed = "redeemed" StatusExpired = "expired" StatusRefunded = "refunded" StatusAbandoned = "abandoned" )
A gift's status: checkout (not paid yet), paid (waiting for its delivery date), delivered (not redeemed yet), redeemed, expired (the link ran out), refunded, abandoned (checkout never finished).
const ( RemindAfter = 7 * 24 * time.Hour EndingBefore = 7 * 24 * time.Hour MessageKeep = 30 * 24 * time.Hour MessageMax = 300 AbandonAfter = 24 * time.Hour MaxDeliverOut = 366 * 24 * time.Hour )
Reminder: "Your gift" goes again to a recipient who hasn't redeemed a week after delivery; "Gift ending" a week before the access ends; messages are kept until the gift ends plus 30 days.
const PageSize = 20
PageSize is the table's page.
Variables ¶
var ErrNoGift = errors.New("gifts: no such gift")
ErrNoGift means no gift has the code.
ErrUnavailable means gifts can't be bought now: the gift page is off, it has no options, or no provider takes payments.
var LinkMonths = []int{3, 6, 12}
LinkMonths are the redemption windows the Gifts tab offers.
Functions ¶
func Erasure ¶
Erasure is gifts the contact bought or received: their side's name and address go, with the message and the gift's event details; amounts and dates stay for revenue (review 2026-11 DP-1). A gift still to be sent whose recipient is erased goes to the buyer, as an in-person gift does.
func NormalizeCode ¶
NormalizeCode reads a code as typed or linked: upper case, the groups joined by dashes.
func Register ¶
Register adds the gifts' operations: reading needs earn:view, the options and the gift page earn:edit, and changing a gift earn:manage.
func RegisterJobs ¶
RegisterJobs adds the gifts job, every minute: a gift goes out at the minute its buyer picked.
Types ¶
type BuyInput ¶
type BuyInput struct {
Option string
To string // email, person
RecipientName string
RecipientEmail string
When string // now, date
Date, Time string // 2026-12-24, 08:00
Timezone string
Message string
BuyerName string
BuyerEmail string
}
BuyInput is the gift page's form.
type GiftCounts ¶
type GiftCounts struct {
All int64 `json:"all"`
Scheduled int64 `json:"scheduled"`
NotRedeemed int64 `json:"notRedeemed"`
Redeemed int64 `json:"redeemed"`
Expired int64 `json:"expired"`
Refunded int64 `json:"refunded"`
}
GiftCounts are the table's filters' counts.
type GiftDeliveryInput ¶
type GiftDeliveryInput struct {
Date string `json:"date" format:"date" doc:"The day, in the time zone"`
Time string `json:"time" pattern:"^[0-2][0-9]:[0-5][0-9]$" doc:"The time of day, 24-hour"`
Timezone string `json:"timezone,omitempty" doc:"An IANA time zone; the buyer's is the default"`
// NotifyBuyer sends the buyer their receipt again with the new date.
NotifyBuyer bool `json:"notifyBuyer,omitempty"`
}
GiftDeliveryInput moves a scheduled gift.
type GiftEmail ¶
type GiftEmail struct {
Email string `json:"email" enum:"gift_purchased,gift_payment_failed,gift_received,gift_ending"`
TemplateID string `json:"templateId,omitempty"`
Template string `json:"template"`
Name string `json:"name"`
Status string `json:"status" enum:"live,draft,missing"`
LiveVersion int `json:"liveVersion"`
DraftVersion int `json:"draftVersion"`
}
GiftEmail is one of the three gift emails and its template's state.
type GiftEndingWarning ¶
type GiftEndingWarning struct {
Due time.Time `json:"due"`
Buyer string `json:"buyer"`
InPerson bool `json:"inPerson"`
Recipient string `json:"recipient"`
TemplateID string `json:"templateId,omitempty"`
}
GiftEndingWarning: gift-ending isn't published, and the first reminder is due on Due, for the gift Buyer gave (in person, or to Recipient).
type GiftEvent ¶
type GiftEvent struct {
GiftID string `json:"gift_id"`
Mode string `json:"mode"`
Tier string `json:"tier,omitempty"`
Months int `json:"months"`
AmountCents int64 `json:"amount_cents"`
Currency string `json:"currency"`
BuyerEmail string `json:"buyer_email"`
InPerson bool `json:"in_person"`
DeliverAt *time.Time `json:"deliver_at,omitempty"`
// Redeemed: who, and until when.
ContactID string `json:"contact_id,omitempty"`
Email string `json:"email,omitempty"`
AccessEndsAt *time.Time `json:"access_ends_at,omitempty"`
OccurredAt time.Time `json:"occurred_at"`
RecipientName string `json:"recipient_name,omitempty"`
}
GiftEvent is the data of the gift.purchased and gift.redeemed webhooks.
type GiftList ¶
type GiftList struct {
Items []GiftRow `json:"items"`
Counts GiftCounts `json:"counts"`
Status string `json:"status"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
// Total is how many gifts the filter shows.
Total int64 `json:"total"`
}
GiftList is a page of the Gifts table.
type GiftMonthsCount ¶
GiftMonthsCount is how many gifts of a length sold.
type GiftNumbers ¶
type GiftNumbers struct {
Sold int64 `json:"sold"`
SoldCents int64 `json:"soldCents"`
// ByMonths splits the sales by length: 7 for a year, 4 for 3 months.
ByMonths []GiftMonthsCount `json:"byMonths"`
// Of the gifts sold, those delivered, redeemed and still waiting.
Delivered int64 `json:"delivered"`
Redeemed int64 `json:"redeemed"`
Waiting int64 `json:"waiting"`
// Scheduled gifts, and the next delivery (in its buyer's time zone).
Scheduled int64 `json:"scheduled"`
NextAt *time.Time `json:"nextAt,omitempty"`
NextTimezone string `json:"nextTimezone,omitempty"`
// Paid members with gift access now (never counted in MRR).
WithAccess int64 `json:"withAccess"`
}
GiftNumbers are the tab's numbers of the last 30 days.
type GiftOption ¶
type GiftOption struct {
ID string `json:"id"`
TierID string `json:"tierId"`
Tier string `json:"tier"`
// Short is the tier's name without its list's ("Insider").
Short string `json:"short"`
Months int `json:"months"`
AmountCents int64 `json:"amountCents"`
Currency string `json:"currency"`
// Sold in the last 30 days, and for how much.
Sold int64 `json:"sold"`
SoldCents int64 `json:"soldCents"`
}
GiftOption is a gift readers can buy: a tier for a period at a price.
type GiftOptionInput ¶
type GiftOptionInput struct {
TierID string `json:"tierId" format:"uuid"`
Months int `json:"months" minimum:"1" maximum:"36" doc:"How long the gift lasts"`
AmountCents int64 `json:"amountCents" minimum:"1" doc:"The one-time price, in the workspace currency"`
}
GiftOptionInput is a gift option as the editor sends it.
type GiftPage ¶
type GiftPage struct {
On bool `json:"on"`
URL string `json:"url"`
Host string `json:"host"`
// LinkMonths is how long a gift link works after delivery.
LinkMonths int `json:"linkMonths"`
// Who last turned it on or off, and when.
ChangedBy string `json:"changedBy,omitempty"`
ChangedAt *time.Time `json:"changedAt,omitempty"`
}
GiftPage is the gift page's switch, address and redemption window.
type GiftPageInput ¶
type GiftPageInput struct {
On bool `json:"on"`
LinkMonths int `json:"linkMonths" enum:"3,6,12" doc:"How long a gift link works after delivery"`
}
GiftPageInput turns the gift page on or off and sets how long gift links work.
type GiftRow ¶
type GiftRow struct {
ID string `json:"id"`
// BoughtAt is when it was paid.
BoughtAt time.Time `json:"boughtAt"`
Buyer string `json:"buyer"`
BuyerEmail string `json:"buyerEmail"`
InPerson bool `json:"inPerson"`
// Recipient's name and email (none in person).
RecipientName string `json:"recipientName"`
RecipientEmail string `json:"recipientEmail"`
Tier string `json:"tier"`
Short string `json:"short"`
Months int `json:"months"`
AmountCents int64 `json:"amountCents"`
Currency string `json:"currency"`
// Status as the table shows it.
Status string `json:"status" enum:"scheduled,not_redeemed,redeemed,expired,refunded"`
// DeliverAt is when a scheduled gift goes out (nil: at once), in the
// buyer's Timezone; DeliveredAt when it went.
DeliverAt *time.Time `json:"deliverAt,omitempty"`
Timezone string `json:"timezone"`
DeliveredAt *time.Time `json:"deliveredAt,omitempty"`
// RemindAt is when "Your gift" goes again if it isn't redeemed;
// RemindedAt when it went.
RemindAt *time.Time `json:"remindAt,omitempty"`
RemindedAt *time.Time `json:"remindedAt,omitempty"`
// LinkExpiresAt is when the redeem link stops working.
LinkExpiresAt *time.Time `json:"linkExpiresAt,omitempty"`
RedeemedAt *time.Time `json:"redeemedAt,omitempty"`
// RedeemedBy is set when someone other than the recipient redeemed
// (an in-person gift, or a passed-on link).
RedeemedBy string `json:"redeemedBy,omitempty"`
AccessEnds *time.Time `json:"accessEnds,omitempty"`
RefundedAt *time.Time `json:"refundedAt,omitempty"`
// EmailStatus is how the last "Your gift" email went: sent, or why not.
EmailStatus string `json:"emailStatus"`
// PaymentURL opens the payment in the provider's dashboard.
PaymentURL string `json:"paymentUrl,omitempty"`
}
GiftRow is a gift in the table.
type GiftTier ¶
type GiftTier struct {
ID string `json:"id"`
Name string `json:"name"`
Short string `json:"short"`
MonthlyCents int64 `json:"monthlyCents"`
YearlyCents int64 `json:"yearlyCents"`
}
GiftTier is a tier an option can give, with its monthly price (the option editor suggests the same price).
type GiftsFile ¶
type GiftsFile struct {
ContentType string `header:"Content-Type"`
ContentDisposition string `header:"Content-Disposition"`
CacheControl string `header:"Cache-Control"`
Body []byte
}
GiftsFile is a CSV download.
type GiftsView ¶
type GiftsView struct {
// Mode is the mode gifts are sold in (live once the live key is in);
// "" without a payment provider.
Mode string `json:"mode" enum:"live,test,"`
Connected bool `json:"connected"`
Provider string `json:"provider"`
Currency string `json:"currency"`
Numbers GiftNumbers `json:"numbers"`
Options []GiftOption `json:"options"`
Page GiftPage `json:"page"`
// Tiers can be given (the option editor's choices).
Tiers []GiftTier `json:"tiers"`
// ListNames are the lists a recipient joins (the first option's tier's).
ListNames []string `json:"listNames"`
Emails []GiftEmail `json:"emails"`
// The emails' sender, category and route, as Member emails shows them.
FromName string `json:"fromName"`
FromEmail string `json:"fromEmail"`
CategoryName string `json:"categoryName"`
CategoryKind string `json:"categoryKind"`
RoutePrimary string `json:"routePrimary"`
// Ending is set while gift-ending isn't published and a reminder is
// due: when the first one is, and for whose gift.
Ending *GiftEndingWarning `json:"ending,omitempty"`
// NeedsLook: delivered a week ago and not redeemed, or refunded lately.
NeedsLook []GiftRow `json:"needsLook"`
CanEdit bool `json:"canEdit"`
CanManage bool `json:"canManage"`
Helpers []string `json:"helpers"`
}
GiftsView is Earn › Gifts: the numbers, the gift options and the gift page, the gift emails, and the gifts that need a look.
type Join ¶
type Join struct {
Email, FirstName, LastName string
Lists []uuid.UUID
// ConsentText is the redeem page's text they agreed to; Note names
// the gift ("Gift from Priya Natarajan").
ConsentText, Note string
IP *netip.Addr
UserAgent string
At time.Time
}
Join is a recipient redeeming a gift.
type PageOption ¶
type PageOption struct {
ID string
Title string
Price string
Sub string
// Tier names the tier when the page gives more than one.
Tier string
}
PageOption is a gift on the page.
type PageView ¶
type PageView struct {
// State: form, or off ("Gifts aren't available right now").
State string
Heading string
Intro string
Options []PageOption
In BuyInput
// Errors are per field (option, recipientEmail, date, message,
// buyerName, buyerEmail); Alert is the page's.
Errors map[string]string
Alert string
// Canceled: back from a checkout that wasn't finished.
Canceled bool
// Test: the provider's test mode takes the payment.
Test bool
// Zone is the time zone a date is read in (the browser's, filled in
// by the page's script; the workspace's until then).
Zone string
ZoneNote string
MinDate string
// MessageLeft counts down the message's characters ("300 characters
// left"); the page's script keeps it current with Words leftOne and
// leftOther.
MessageLeft string
Text string
Support string
Words map[string]string
}
PageView is the gift page.
type RedeemInput ¶
RedeemInput is the redeem page's form.
type RedeemView ¶
type RedeemView struct {
State string
Heading string
Text string
// The giver's message and its caption ("Priya Natarajan · 11 Oct").
Message string
From string
// What the tier includes.
Included string
Benefits []string
Email string
Error string
Button string
Fine string
PassOn string
// Link is the gift link to pass on (the have state), its words.
Link string
LinkURL string
Copy string
Copied string
// Support is the publisher's address for the used, expired and
// refunded states.
Support string
Words map[string]string
}
RedeemView is the redeem page in one of its states: redeem (the page), redeemed (done), have (they already have paid access), used, expired, refunded.
type Service ¶
type Service struct {
Pool *pgxpool.Pool
Q *store.Queries
Audit *audit.Logger
Earn *earn.Service
Log *slog.Logger
Now func() time.Time
// Signup joins recipients to the tier's lists (nil: they join no list).
Signup Signup
// Confirm sends the double opt-in email when joining needs it (a
// recipient who had unsubscribed).
Confirm func(ctx context.Context, ws *store.Workspace, contact uuid.UUID) error
}
Service is the gifts domain.
func (*Service) Buy ¶
func (s *Service) Buy(ctx context.Context, ws *store.Workspace, in BuyInput) (string, *PageView, error)
Buy checks the gift page's form and opens the provider's checkout for one payment. It returns the checkout's address, or the page again with what to correct.
func (*Service) ChangeDelivery ¶
func (s *Service) ChangeDelivery(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in GiftDeliveryInput) (GiftRow, error)
ChangeDelivery moves a scheduled gift's delivery.
func (*Service) CheckoutCompleted ¶
func (s *Service) CheckoutCompleted(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, cs payments.CheckoutSession, at time.Time) (bool, map[string]any, error)
CheckoutCompleted marks a gift paid when its checkout's payment went through; its receipt and delivery follow from the gifts job.
func (*Service) CheckoutFailed ¶
func (s *Service) CheckoutFailed(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, cs payments.CheckoutSession, at time.Time) (bool, map[string]any, error)
CheckoutFailed implements earn.OneTimeHook: a gift's delayed payment (a bank debit) didn't clear, so the gift is never sent. Its checkout counts as abandoned, and its timeline says why.
func (*Service) CopyLink ¶
func (s *Service) CopyLink(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (GiftLink, error)
CopyLink returns a gift's redeem link, recorded in the audit log: anyone with it can redeem the gift until it's used.
func (*Service) CreateOption ¶
func (s *Service) CreateOption(ctx context.Context, ws *store.Workspace, p *authz.Principal, in GiftOptionInput) (GiftOption, error)
CreateOption adds a gift option (earn:edit).
func (*Service) DeleteOption ¶
func (s *Service) DeleteOption(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) error
DeleteOption removes a gift option from the gift page (earn:edit). Gifts already bought keep working.
func (*Service) Export ¶
func (s *Service) Export(ctx context.Context, ws *store.Workspace, filter, search string) ([]byte, int, error)
Export writes the gifts a filter shows as CSV (review 2026-11 EA-2). They hold buyers' and recipients' addresses, so the export is audited.
func (*Service) List ¶
func (s *Service) List(ctx context.Context, ws *store.Workspace, filter, search string, pageNo int) (GiftList, error)
List is a page of the Gifts table: a filter (all, scheduled, not_redeemed, redeemed, expired, refunded) and a search.
func (*Service) Page ¶
func (s *Service) Page(ctx context.Context, ws *store.Workspace, in BuyInput, canceled bool) (PageView, error)
Page builds the gift page; in carries what was typed (a correction).
func (*Service) Redeem ¶
func (s *Service) Redeem(ctx context.Context, ws *store.Workspace, code string, in RedeemInput) (RedeemView, error)
Redeem redeems a gift for the address given.
func (*Service) RedeemHost ¶
RedeemHost is the redeem link without its scheme.
func (*Service) RedeemPage ¶
func (s *Service) RedeemPage(ctx context.Context, ws *store.Workspace, code string) (RedeemView, error)
RedeemPage builds the redeem page of a code.
func (*Service) Refunded ¶
func (s *Service) Refunded(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, ch payments.Charge, at time.Time) (bool, map[string]any, error)
Refunded marks a gift refunded when its payment is refunded in full: its link stops working and a scheduled gift isn't sent. A partial refund is noted on the gift only.
func (*Service) Resend ¶
func (s *Service) Resend(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID) (GiftRow, error)
Resend sends "Your gift" again to a delivered gift's recipient (or the buyer, in person).
func (*Service) SetPage ¶
func (s *Service) SetPage(ctx context.Context, ws *store.Workspace, p *authz.Principal, in GiftPageInput) (GiftPage, error)
SetPage changes the gift page (earn:edit). Gifts already bought keep working when it's off: their emails go out and their links can be redeemed.
func (*Service) Thanks ¶
func (s *Service) Thanks(ctx context.Context, ws *store.Workspace, session string) (ThanksView, error)
Thanks is the page a buyer comes back to from checkout. A payment whose webhook isn't in yet is read from the provider.
func (*Service) UpdateOption ¶
func (s *Service) UpdateOption(ctx context.Context, ws *store.Workspace, p *authz.Principal, id uuid.UUID, in GiftOptionInput) (GiftOption, error)
UpdateOption changes a gift option (earn:edit). Gifts already bought keep what they were sold as.
type Signup ¶
type Signup interface {
Join(ctx context.Context, tx pgx.Tx, ws *store.Workspace, j Join) (contact uuid.UUID, pending bool, err error)
}
Signup joins a gift's recipient to the tier's lists, with the redeem page's text as the consent evidence.
type ThanksView ¶
type ThanksView struct {
// State: scheduled, sent (on its way now), person (the link goes to
// the buyer), pending (the payment isn't confirmed yet).
State string
Heading string
Text string
// The gift: "Weekly Digest Insider · 1 year", "$80.00, paid once",
// and to whom.
Gift string
Paid string
To string
Note string
}
ThanksView is the page after paying (gift/thanks?session=…).
type TickArgs ¶
type TickArgs struct{}
TickArgs is the gifts job: receipts, deliveries on their date, reminders, expired links, gift ending emails and message purges.
func (TickArgs) InsertOpts ¶
func (TickArgs) InsertOpts() river.InsertOpts
InsertOpts runs on the maintenance queue, once at a time.
type TickWorker ¶
type TickWorker struct {
river.WorkerDefaults[TickArgs]
S *Service
}
TickWorker runs TickArgs.