Documentation
¶
Overview ¶
Package earn is ReputeCast's payments and paid subscriptions (design expansion phase 6, M26): a workspace connects its own payment account (Stripe, with a restricted key), defines tiers with monthly and yearly prices, sells them on a hosted upgrade page through the provider's checkout, and keeps every contact's paid status in step with the provider's events. Readers pay the publisher; ReputeCast takes no fee and gates nothing.
The provider holds the money and ReputeCast mirrors it: webhook events are verified, stored raw and applied by a River job (the payments event log), an hourly check reads any event the webhook missed, and nothing about cards is ever stored. Paid members can be imported from Substack, Ghost, beehiiv and Kit exports, given complimentary access, and emailed through eight member emails, which are transactional templates in an Essential "Memberships" category.
Every change a person makes is audited; payment events and readers' own changes stay in the payments event log and the paid members' timelines, as the ROADMAP's defaults say.
Index ¶
- Constants
- Variables
- func CurrencyNameIn(l i18n.Lang, code string) string
- func Dashboard(provider string, mode payments.Mode, kind, id string) string
- func DateIn(l i18n.Lang, t time.Time) string
- func DayMonthIn(l i18n.Lang, t time.Time) string
- func EnglishText(l i18n.Lang, key string) bool
- func Erasure() erasure.Source
- func FailureShort(l i18n.Lang, reason string) string
- func Money(cents int64, currency string) string
- func MoneyCents(cents int64, currency string) string
- func PublicPriceIn(l i18n.Lang, cents int64, currency, period string) string
- func Register(h huma.API, s *Service)
- func RegisterJobs(reg *jobs.Registry, s *Service)
- func RegisterPaymentConsumer(s *Service, c PaymentConsumer)
- func ShortTierName(name string, lists []string) string
- func StarterKey(email string) string
- func TeamPageStatus(state string) int
- func Text(key string, args i18n.Args) string
- func TextIn(l i18n.Lang, key string, args i18n.Args) string
- func TimeIn(l i18n.Lang, t time.Time) string
- func WorkspaceLang(ctx context.Context, q *store.Queries, wsID uuid.UUID) i18n.Lang
- type ApplyArgs
- type ApplyWorker
- type Brand
- type CancelTarget
- type CheckoutRequest
- type ComposerOfferHook
- type Confirmations
- type Consumed
- type DailyArgs
- type DailyWorker
- type EarnAccessInput
- type EarnAccessRules
- type EarnAccount
- type EarnAudience
- type EarnAudienceLeftOut
- type EarnAudienceTier
- type EarnCancelInput
- type EarnChecklist
- type EarnChecklistStep
- type EarnCheckoutInput
- type EarnCheckoutSettings
- type EarnComplimentaryInput
- type EarnComposer
- type EarnComposerOffer
- type EarnComposerTier
- type EarnConnectInput
- type EarnConnection
- type EarnDisconnectInput
- type EarnEvent
- type EarnEventCount
- type EarnEventFilter
- type EarnEventLog
- type EarnEventsFile
- type EarnFinishInput
- type EarnFinished
- type EarnFreeCard
- type EarnGapRun
- type EarnGrantInput
- type EarnGroupPriceInput
- type EarnGroupPrices
- type EarnImport
- type EarnImportCandidate
- type EarnImportColumn
- type EarnImportColumnsInput
- type EarnImportConflict
- type EarnImportDecisions
- type EarnImportGroup
- type EarnImportMatch
- type EarnImportPrice
- type EarnImportPriceChoice
- type EarnImportStats
- type EarnListRef
- type EarnMapPriceInput
- type EarnMember
- type EarnMemberCounts
- type EarnMemberDiscount
- type EarnMemberEmail
- type EarnMemberEmails
- type EarnMemberFilter
- type EarnMemberList
- type EarnMemberRow
- type EarnMemberSource
- type EarnMemberTeam
- type EarnPageTier
- type EarnPagesInput
- type EarnPagesSettings
- type EarnPauseInput
- type EarnPausing
- type EarnPausingInput
- type EarnPayments
- type EarnPermissionCheck
- type EarnPlans
- type EarnPortal
- type EarnPreview
- type EarnPreviewInput
- type EarnPrice
- type EarnPriceOffer
- type EarnProviderCard
- type EarnReach
- type EarnReplaceKeyInput
- type EarnResendInput
- type EarnResent
- type EarnStatus
- type EarnStepInput
- type EarnSyncStep
- type EarnSyncWarning
- type EarnTeamSeat
- type EarnTestDataCleared
- type EarnTier
- type EarnTierInput
- type EarnTierSaved
- type EarnTimelineItem
- type EarnUnmappedPrice
- type EarnUpgradeCard
- type EarnUpgradeEditor
- type EarnWebhook
- type EarnWebhookSecretInput
- type FreeCardView
- type HourlyArgs
- type HourlyWorker
- type ImportArgs
- type ImportWorker
- type Join
- type JoinInput
- type KnownReader
- type Mailer
- type MemberCategory
- type MemberEmailResult
- type MemberMessage
- type OfferBanner
- type OfferCodeRedeemer
- type OfferHook
- type OneTimeHook
- type PageNotice
- type PageSettings
- type PaidMemberEvent
- type PaidMemberSummary
- type PaidTierCount
- type PaidView
- type PaymentConsumer
- type PaymentEvent
- type PreferencesPaid
- type Reach
- type ReaderLink
- type ResumeView
- type Route
- type SellingConnection
- type Sent
- type Service
- func (s *Service) AcceptTeamInvite(ctx context.Context, ws *store.Workspace, token string, in JoinInput, ...) (TeamJoinView, error)
- func (s *Service) AccessRules(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnAccessRules, error)
- func (s *Service) ActiveMode(ctx context.Context, wsID uuid.UUID) string
- func (s *Service) Apply(ctx context.Context, id uuid.UUID) error
- func (s *Service) ApplyPending(ctx context.Context, before time.Time) (int, error)
- func (s *Service) Audience(ctx context.Context, ws *store.Workspace, list, tier string) (EarnAudience, error)
- func (s *Service) BillingURL(ctx context.Context, ws *store.Workspace, contact uuid.UUID, ...) string
- func (s *Service) CancelImport(ctx context.Context, ws *store.Workspace, id string) error
- func (s *Service) CancelPauseChoices(ctx context.Context, ws *store.Workspace, sub store.PaidSubscription) []int
- func (s *Service) CancelPortal(ctx context.Context, ws *store.Workspace, sub store.PaidSubscription, ...) (string, error)
- func (s *Service) CancelSubscription(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnMember, error)
- func (s *Service) CancelTargetOf(ctx context.Context, ws *store.Workspace, token string) (*CancelTarget, error)
- func (s *Service) CancelURL(ctx context.Context, ws *store.Workspace, contact uuid.UUID, ...) string
- func (s *Service) ChangeComplimentary(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnMember, error)
- func (s *Service) Checklist(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnChecklist, error)
- func (s *Service) ClearTestData(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnTestDataCleared, error)
- func (s *Service) ClientFor(ctx context.Context, wsID uuid.UUID, mode string) (payments.Client, store.PaymentConnection, error)
- func (s *Service) Composer(ctx context.Context, ws *store.Workspace) (EarnComposer, error)
- func (s *Service) Connect(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnConnection, error)
- func (s *Service) Connection(ctx context.Context, ws *store.Workspace, id string) (EarnConnection, error)
- func (s *Service) ContactPaid(ctx context.Context, ws *store.Workspace, p *authz.Principal, contact string) (*EarnMember, error)
- func (s *Service) CreateTier(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnTierInput) (EarnTierSaved, error)
- func (s *Service) DailyFailed(ctx context.Context) error
- func (s *Service) DateText(ws *store.Workspace, t time.Time) string
- func (s *Service) DateTextIn(l i18n.Lang, ws *store.Workspace, t time.Time) string
- func (s *Service) DeleteTier(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) error
- func (s *Service) Disconnect(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) error
- func (s *Service) EndRunOut(ctx context.Context) error
- func (s *Service) EnsureMemberEmailDrafts(ctx context.Context, ws *store.Workspace) (int, error)
- func (s *Service) EventLog(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnEventLog, error)
- func (s *Service) Export(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) ([]byte, int, error)
- func (s *Service) ExportEvents(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) ([]byte, int, error)
- func (s *Service) Finish(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnFinished, error)
- func (s *Service) GiveComplimentary(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnMember, error)
- func (s *Service) Hourly(ctx context.Context) error
- func (s *Service) Import(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnImport, error)
- func (s *Service) ManageTeamURL(ctx context.Context, ws *store.Workspace, g store.EarnGroup) string
- func (s *Service) MapPrice(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) error
- func (s *Service) MatchImport(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnImport, error)
- func (s *Service) Member(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnMember, error)
- func (s *Service) MemberEmails(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnMemberEmails, error)
- func (s *Service) Members(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnMemberList, error)
- func (s *Service) PageHost(ctx context.Context, ws *store.Workspace, path string) string
- func (s *Service) PageSettingsOf(ctx context.Context, wsID uuid.UUID) PageSettings
- func (s *Service) PageURL(ctx context.Context, ws *store.Workspace, path string) string
- func (s *Service) Pages(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnPagesSettings, error)
- func (s *Service) PaidAccessOf(ctx context.Context, ws *store.Workspace, contact uuid.UUID, mode string) (*store.PaidSubscription, string, error)
- func (s *Service) PaidMemberCounts(ctx context.Context, ws *store.Workspace) (PaidMemberSummary, error)
- func (s *Service) PaidVars(ctx context.Context, wsID uuid.UUID, contacts []uuid.UUID) (map[uuid.UUID]map[string]any, error)
- func (s *Service) PauseFromCancel(ctx context.Context, ws *store.Workspace, sub store.PaidSubscription, ...) (time.Time, error)
- func (s *Service) PauseMember(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnMember, error)
- func (s *Service) Payments(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnPayments, error)
- func (s *Service) Plans(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnPlans, error)
- func (s *Service) Portal(ctx context.Context, ws *store.Workspace, token string, kind linktoken.Kind) (string, error)
- func (s *Service) PreferencesPaid(ctx context.Context, ws *store.Workspace, contact uuid.UUID, l i18n.Lang, ...) (*PreferencesPaid, error)
- func (s *Service) PreviewUpgrade(ctx context.Context, ws *store.Workspace, in EarnPreviewInput) (EarnPreview, error)
- func (s *Service) ReaderLinks(ctx context.Context, wsID uuid.UUID) ([]ReaderLink, error)
- func (s *Service) Recheck(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnConnection, error)
- func (s *Service) RegisterAgain(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnConnection, error)
- func (s *Service) RegisterWebhook(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnConnection, error)
- func (s *Service) RemoveComplimentary(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) error
- func (s *Service) RemoveSeat(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnMember, error)
- func (s *Service) ReplaceKey(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnConnection, error)
- func (s *Service) Resend(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnResent, error)
- func (s *Service) ResumeFromLink(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang) (ResumeView, error)
- func (s *Service) ResumeMember(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnMember, error)
- func (s *Service) ResumePage(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang) (ResumeView, error)
- func (s *Service) ResumeURL(ctx context.Context, ws *store.Workspace, contact uuid.UUID) string
- func (s *Service) Routes(r chi.Router)
- func (s *Service) RunImport(ctx context.Context, id uuid.UUID) error
- func (s *Service) SaveAccessRules(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnAccessRules, error)
- func (s *Service) SaveCheckout(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnCheckoutSettings, error)
- func (s *Service) SavePages(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnPagesSettings, error)
- func (s *Service) SavePausing(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnPausing, error)
- func (s *Service) SaveUpgradePage(ctx context.Context, ws *store.Workspace, p *authz.Principal, in UpgradePage) (EarnUpgradeEditor, error)
- func (s *Service) Selling(ctx context.Context, ws *store.Workspace) (SellingConnection, bool, error)
- func (s *Service) SellingClient(ctx context.Context, ws *store.Workspace, id uuid.UUID) (payments.Client, error)
- func (s *Service) SellingIn(ctx context.Context, ws *store.Workspace, mode payments.Mode) (SellingConnection, bool, error)
- func (s *Service) SendBillingLink(ctx context.Context, ws *store.Workspace, contact uuid.UUID, l i18n.Lang) error
- func (s *Service) SendMemberEmailIn(ctx context.Context, ws *store.Workspace, email, to, toName string, ...) MemberEmailResult
- func (s *Service) SendMemberEmailTo(ctx context.Context, ws *store.Workspace, email, to, toName string, ...) MemberEmailResult
- func (s *Service) SendTeamLink(ctx context.Context, ws *store.Workspace, g store.EarnGroup, l i18n.Lang) error
- func (s *Service) SetImportColumns(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnImport, error)
- func (s *Service) SetImportDecisions(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnImport, error)
- func (s *Service) SetStep(ctx context.Context, ws *store.Workspace, id string, in EarnStepInput) (EarnConnection, error)
- func (s *Service) StartCheckout(ctx context.Context, ws *store.Workspace, r CheckoutRequest) (string, error)
- func (s *Service) StartImport(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnImport, error)
- func (s *Service) StartTeamCheckout(ctx context.Context, ws *store.Workspace, r TeamCheckoutRequest) (string, error)
- func (s *Service) Status(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnStatus, error)
- func (s *Service) Sweep(ctx context.Context) error
- func (s *Service) SyncTier(ctx context.Context, ws *store.Workspace, id string) (EarnTierSaved, error)
- func (s *Service) TeamBilling(ctx context.Context, ws *store.Workspace, token string, returnURL string, ...) (TeamResult, error)
- func (s *Service) TeamInvite(ctx context.Context, ws *store.Workspace, token, emails string, l i18n.Lang) (TeamResult, error)
- func (s *Service) TeamJoin(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang) (TeamJoinView, error)
- func (s *Service) TeamManage(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang, ...) (TeamManageView, error)
- func (s *Service) TeamPage(ctx context.Context, ws *store.Workspace, r TeamRequest) (TeamView, error)
- func (s *Service) TeamRemove(ctx context.Context, ws *store.Workspace, token, seatID string, l i18n.Lang) (TeamResult, error)
- func (s *Service) TeamResend(ctx context.Context, ws *store.Workspace, token, seatID string, l i18n.Lang) (TeamResult, error)
- func (s *Service) TeamSetSeats(ctx context.Context, ws *store.Workspace, token, seats string, l i18n.Lang) (TeamResult, error)
- func (s *Service) TestCheckoutURL(ctx context.Context, ws *store.Workspace) string
- func (s *Service) TestMode(ws *store.Workspace, token string) bool
- func (s *Service) TierDetail(ctx context.Context, ws *store.Workspace, id string) (EarnTier, error)
- func (s *Service) TierShortName(ctx context.Context, wsID uuid.UUID, tier uuid.UUID) string
- func (s *Service) Timeline(ctx context.Context, q *store.Queries, wsID, contact uuid.UUID, sub *uuid.UUID, ...) error
- func (s *Service) UnsubscribePaid(ctx context.Context, ws *store.Workspace, contact uuid.UUID, l i18n.Lang) (*UnsubscribePaid, error)
- func (s *Service) UpdateTier(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnTierSaved, error)
- func (s *Service) Upgrade(ctx context.Context, ws *store.Workspace, r UpgradeRequest) (UpgradeView, error)
- func (s *Service) UpgradeClicked(ctx context.Context, ws *store.Workspace, token string)
- func (s *Service) UpgradeEditor(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnUpgradeEditor, error)
- func (s *Service) UpgradeURL(ctx context.Context, ws *store.Workspace, contact, message uuid.UUID) string
- func (s *Service) UploadImport(ctx context.Context, ws *store.Workspace, p *authz.Principal, ...) (EarnImport, error)
- func (s *Service) Visit(ctx context.Context, ws *store.Workspace, page string)
- func (s *Service) WebhookSecret(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, ...) (EarnConnection, error)
- func (s *Service) WebhookURL(c store.PaymentConnection) string
- func (s *Service) Welcome(ctx context.Context, ws *store.Workspace, session string, l i18n.Lang) (WelcomeView, error)
- func (s *Service) WelcomeLine(ctx context.Context, ws *store.Workspace, tier *uuid.UUID, first string, ...) string
- type Signup
- type Starter
- type SweepArgs
- type SweepWorker
- type TeamCheckoutRequest
- type TeamConfirm
- type TeamFormError
- type TeamJoinView
- type TeamManageView
- type TeamMemberView
- type TeamRequest
- type TeamResult
- type TeamView
- type TemplateDraft
- type TemplateState
- type TemplateVariable
- type TierCardView
- type Token
- type UnsubscribePaid
- type UpgradeFAQ
- type UpgradePage
- type UpgradeRequest
- type UpgradeView
- type WelcomeView
Constants ¶
const ( StatusIncomplete = "incomplete" StatusTrialing = "trialing" StatusActive = "active" StatusPastDue = "past_due" StatusCanceled = "canceled" StatusComplimentary = "complimentary" StatusGift = "gift" // StatusGroup is a team seat's access (M65): it lasts while the // buyer's subscription gives access. StatusGroup = "group" )
Paid statuses (brief §2).
const ( // AutomationPaidStarted: a subscription is active or past due for // the first time ("Becomes a paid member"); from_trial when a trial // came first. AutomationPaidStarted = "paid_started" // AutomationPaidTierChanged: the subscription moved to another tier // ("Changes tier"), with the direction from the tiers' access ranks. // A monthly↔yearly switch inside one tier is no change. AutomationPaidTierChanged = "paid_tier_changed" // AutomationPaidEnded: paid access ended ("Stops paying"), with the // reason. AutomationPaidEnded = "paid_ended" // AutomationPaidTrialEnding: Stripe's notice three days before a // trial ends ("Trial ends soon"). AutomationPaidTrialEnding = "paid_trial_ending" // AutomationPaidPaused and AutomationPaidResumed: the subscription's // payments paused, and started again (M65, "Pauses payments", // "Resumes payments"), with the resume date. AutomationPaidPaused = "paid_paused" AutomationPaidResumed = "paid_resumed" )
Automation triggers for paid members (M57, G-11): Earn queues their events, internal/automations matches them to flows (the same kind strings; neither package imports the other). Only Stripe subscriptions in live mode start flows: complimentary access, gifts and test mode never do.
Each event's ref is the subscription ("sub:<id>"), its payload names the tier (tier_id, tier) and carries "liquid", the flow's email data: {{ subscription.tier }}, {{ subscription.previous_tier }} and {{ subscription.trial_ends_at }}.
const ( // LinkValidAsked is how long a link asked for works: one emailed at // once, or shown on a page opened with a signed-in session or a link // that expires itself. LinkValidAsked = time.Hour // LinkValidInEmail is how long a link in a member email or a campaign // works. LinkValidInEmail = 30 * 24 * time.Hour )
A paid member's billing link opens their Stripe portal, and their cancel link their cancel page and then the portal: whoever holds one can change the card, read the invoices and the address on them, or cancel. So the links stop working, and only an unexpired one opens the portal: one in a member email or a campaign after 30 days, one asked for after an hour. Pages reached through links that never expire (the preference center, which every "view online" page links to, the unsubscribe page, the upgrade page from an email) don't show them: the member asks there for a link, and it goes by email to the address on file (SendBillingLink).
const ( CodeSecretKey = "secret_key" CodeKeyFormat = "key_format" CodeKeyRejected = "key_rejected" CodeModeConnected = "mode_connected" CodeOtherAccount = "other_account" CodeNotConnected = "not_connected" CodeConfirm = "confirmation_mismatch" )
Problem codes of the connect flow.
const ( StepCheck = "check" StepWebhook = "webhook" StepSettings = "settings" StepDone = "done" )
Wizard steps.
const ( HealthSetup = "setup" HealthKeyRejected = "key_rejected" HealthWebhookMissing = "webhook_missing" HealthMissingPermissions = "missing_permissions" HealthWebhookSilent = "webhook_silent" HealthConnected = "connected" )
Health of a connection, worst first.
const ( SilentAfter = 24 * time.Hour SilentMinimum = 50 )
SilentAfter is how long without an event makes a webhook silent, while at least SilentMinimum subscriptions are active.
const ( TokenUpgrade linktoken.Kind = 160 TokenBilling linktoken.Kind = 161 TokenCancel linktoken.Kind = 162 // A team buyer's manage page (M65): MessageID is the team, ContactID // the buyer, Link the day it was issued; it works for a week. TokenGroupManage linktoken.Kind = 164 // A team invite (M65): MessageID is the seat, Link the day it was // issued; only a seat's newest invite works, for two weeks. TokenGroupJoin linktoken.Kind = 165 )
Link token kinds of the Earn pages (numbered after the workstream so parallel kinds never collide): a reader's personal upgrade link, the link that opens their billing portal, and their cancel page. Billing and cancel links expire (billinglinks.go).
const ( MaxImportFile = 25 << 20 MaxImportRows = 100000 )
Import limits.
const ( KindPaymentsAttention = notify.KindPaymentsAttention KindUnmappedPrice = notify.KindUnmappedPrice KindPaidImportDone = notify.KindPaidImportDone KindFailedPayments = notify.KindFailedPayments )
Notification kinds of Earn (registered in internal/notify).
const ( EmailWelcome = "welcome" EmailTrialEnding = "trial_ending" EmailPaymentFailed = "payment_failed" EmailRenewalReminder = "renewal_reminder" EmailCanceled = "canceled" EmailGiftPurchased = "gift_purchased" EmailGiftReceived = "gift_received" EmailGiftEnding = "gift_ending" // EmailGiftPaymentFailed tells a gift's buyer their bank payment // didn't go through (review 2026-11 EN-9). EmailGiftPaymentFailed = "gift_payment_failed" // The team emails (M65, G-38): the buyer's welcome with the manage // link, an invite, and the end of a seat's access. EmailGroupWelcome = "group_welcome" EmailGroupInvite = "group_invite" EmailGroupAccessEnded = "group_access_ended" // The pause emails (M65, G-39): paused until a date, and a week before // payments resume. EmailPaused = "paused" EmailResumingSoon = "resuming_soon" )
The member emails (brief 3.8, and review 2026-11 EN-9's gift payment failure), in the settings table's order.
const ( FilterWithAccess = "with_access" FilterPaying = "paying" FilterTrialing = "trialing" FilterPastDue = "past_due" FilterCancelsSoon = "cancels_soon" FilterComplimentary = "complimentary" FilterGift = "gift" FilterEnded = "ended" // FilterPaused: payments paused (M65). FilterPaused = "paused" )
Member filters (the status chips).
const ( VarUpgradeURL = paidaccess.UpgradeURL VarManageURL = paidaccess.ManageURL )
The paid link tokens.
const ( MetaGroup = "reputecast_group" MetaTeam = "reputecast_team" )
Metadata of a team checkout and its subscription.
const ( GroupLinkValid = 7 * 24 * time.Hour InviteValid = 14 * 24 * time.Hour )
How long the team links work: the buyer's manage page a week, an invite two weeks.
const ( AudienceIndividual = "individual" AudienceGroup = "group" )
Audiences of a price.
const ( VisibilityPublic = "public" VisibilityHidden = "hidden" VisibilityArchived = "archived" )
Visibilities of a tier.
const ( KindPaid = "paid" GroupPaid = "paid" // OpPaidAny shows the block to any paid tier. OpPaidAny = "any" // OpPaidTier shows it to the tier in the condition's value and above. OpPaidTier = "at_least" // OpPaidFree shows it to free subscribers only (no paid access). OpPaidFree = "free" // FieldUpgradeBlock marks the Upgrade block's own condition: free // subscribers only, and only while a live payment provider is connected // (the block is hidden until then). FieldUpgradeBlock = "upgrade" )
The paid access condition: its kind, group and operators.
const DefaultProvider = "stripe"
DefaultProvider is the payment provider connections use when none is named: the only one available so far. Earn reaches every provider through internal/payments and never imports an adapter.
const EndedWindow = 30 * 24 * time.Hour
EndedWindow is how far back the Ended chip looks.
const KindGroup = "group"
KindGroup is a team seat's paid_subscriptions row (M65).
const MaxInvites = 50
MaxInvites is how many addresses one invite may carry.
const MaxPause = 6
MaxPause is the longest pause the team may set.
const MaxWebhookBody = 1 << 20
MaxWebhookBody is the largest payment event accepted.
const PauseEvery = 365 * 24 * time.Hour
PauseEvery is how often a member may pause from the cancel page.
const RetentionDays = 90
RetentionDays is how long raw payment events are kept.
const RootPaid = "paid"
RootPaid is the Liquid variable the paid values live under.
const SourceGroupPrefix = "group:"
SourceGroupPrefix is the consent source of a team seat ("group:<team id>").
const SourcePaid = "paid_subscription"
SourcePaid is the consent source of a paid subscription.
const TokenTestCheckout linktoken.Kind = 163
TokenTestCheckout signs a team member's test checkout link (the editor's "Preview with test checkout"): the upgrade page in test mode, valid for a day. Its Link field holds the hour it expires.
Variables ¶
var ErrBadLink = errors.New("earn: the link isn't valid")
ErrBadLink means a personal link isn't valid: altered, or for another workspace.
var ErrCantPause = errors.New("earn: the subscription can't be paused")
ErrCantPause means the subscription can't be paused now.
var ErrLinkExpired = errors.New("earn: the personal link expired")
ErrLinkExpired means a personal link no longer works: it's past its time (billinglinks.go), its signature doesn't match (an earlier instance key) or its reader is gone.
var ErrLinkInvalid = errors.New("earn: not a personal link")
ErrLinkInvalid means a personal link isn't one: malformed, another kind of link, or another workspace's.
var ErrNoRoute = errors.New("earn: no Transactional route")
ErrNoRoute means transactional mail has no route: member emails can't be sent until one is chosen in Sending providers › Routing.
var ErrNoSubscription = errors.New("earn: no paid subscription")
ErrNoSubscription means the link's reader has no paid subscription to manage.
var ErrNotPublished = errors.New("earn: the template has no published version")
ErrNotPublished means a member email's template has no published version.
var ErrSuppressed = errors.New("earn: the recipient is suppressed")
ErrSuppressed means the address is suppressed for all mail.
var ErrTeamLink = errors.New("earn: the team link isn't valid")
ErrTeamLink means a team link isn't valid (altered, another workspace's).
ErrUnavailable means checkout can't open: the provider is down or not connected.
var MemberEmailOrder = []string{EmailWelcome, EmailTrialEnding, EmailPaymentFailed, EmailRenewalReminder, EmailCanceled, EmailGiftPurchased, EmailGiftPaymentFailed, EmailGiftReceived, EmailGiftEnding, EmailGroupWelcome, EmailGroupInvite, EmailGroupAccessEnded, EmailPaused, EmailResumingSoon}
MemberEmailOrder lists them in order.
var PageLang = defaultLang
PageLang is the Earn pages' language when nothing picks one: English, in ReputeCast's own formats.
var PauseMonths = []int{1, 3, 6}
PauseMonths are the lengths a workspace may allow on the cancel page.
Functions ¶
func CurrencyNameIn ¶
CurrencyNameIn names a currency in a sentence in a language: "US dollars" (the sponsor pages).
func Dashboard ¶
Dashboard links to an object in a provider's dashboard ("payments" and a payment intent's id for an order).
func DayMonthIn ¶
DayMonthIn is a day without its year in a language: "24 Dec", "24 thg 12".
func EnglishText ¶
EnglishText reports whether one of the Earn catalog's messages is written in English for a language (it isn't translated yet).
func Erasure ¶
Erasure is a contact's paid membership. A contact who still pays through Stripe can't be erased: Stripe would go on charging someone ReputeCast no longer knows, so the subscription is canceled first (Earn › Members). Complimentary and gift access ends. Subscriptions stay, without the billing address, Stripe ids or anything a person wrote, so MRR, churn and revenue history still add up; the paid timeline goes, as the Earn brief says (§3.16).
func FailureShort ¶
FailureShort is a payment failure in a few words in a language.
func MoneyCents ¶
MoneyCents is an amount with its cents: "$4.00".
func PublicPriceIn ¶
PublicPriceIn is a price as public pages write it, in a language: "$8 a month" (the cancel page's pause step).
func Register ¶
Register adds Earn's operations: the payment connection and its event log, tiers and the upgrade page, paid members, imports and the Earn settings. Changing anything that touches money or keys needs a person (API keys and agents can read).
func RegisterJobs ¶
RegisterJobs adds Earn's workers and periodic jobs.
func RegisterPaymentConsumer ¶
func RegisterPaymentConsumer(s *Service, c PaymentConsumer)
RegisterPaymentConsumer adds a consumer of the one-time payment events s applies.
func ShortTierName ¶
ShortTierName shortens a tier's name with its lists' names in hand.
func StarterKey ¶
StarterKey is a member email's template ID ("member-welcome").
func TeamPageStatus ¶
TeamPageStatus is a team page's HTTP status for a result's state.
func TextIn ¶
TextIn is one of the Earn pages' built-in words in a page's language (internal/publicpages).
Types ¶
type ApplyArgs ¶
type ApplyArgs struct {
EventID string `json:"event_id"`
}
ApplyArgs applies one stored payment event.
func (ApplyArgs) InsertOpts ¶
func (ApplyArgs) InsertOpts() river.InsertOpts
InsertOpts runs on the events queue.
type ApplyWorker ¶
type ApplyWorker struct {
river.WorkerDefaults[ApplyArgs]
S *Service
}
ApplyWorker applies stored payment events.
type Brand ¶
type Brand struct {
Publisher string `json:"publisher"`
// Accent fills buttons and the highlighted card's border; Ground is the
// page's background, Soft tints chips, Text is the accent as text and
// OnAccent the text on accent buttons.
Accent string `json:"accent"`
Ground string `json:"ground"`
Soft string `json:"soft"`
Text string `json:"text"`
OnAccent string `json:"onAccent"`
}
Brand is how the public pages look: who readers pay and the colours.
type CancelTarget ¶
type CancelTarget struct {
Contact store.EarnContactBriefRow
Sub store.PaidSubscription
Tier string
Short string
Lists []string
}
CancelTarget is whom a cancel link is for: the reader and the paid subscription the cancel page is about, with its tier's names and the tier's lists (what they keep getting for free).
type CheckoutRequest ¶
type CheckoutRequest struct {
Tier string
Period string
Token string
// Test is a test checkout from the editor, by a team member; TestToken
// is a test checkout link's token.
Test bool
TestToken string
StartedBy *authz.Principal
// ReturnTo is the page Checkout comes back to (the hidden tier's).
ReturnTo string
// Offer is the offer link's code the page was opened with (X17).
Offer string
}
CheckoutRequest is a reader's click on a card's button.
type ComposerOfferHook ¶
type ComposerOfferHook interface {
ComposerOffers(ctx context.Context, ws *store.Workspace, tier uuid.UUID) []EarnComposerOffer
}
ComposerOfferHook gives the composer the offers an Upgrade block can carry (internal/offers); the composer has none without it.
type Confirmations ¶
type Confirmations interface {
Send(ctx context.Context, ws *store.Workspace, contactID uuid.UUID) error
}
Confirmations sends the double opt-in email of a contact whose lists are pending (complimentary access for a new address), through forms.
type Consumed ¶
type Consumed struct {
// Outcome is the event log's key ("order_paid"); Ignored files it as
// ignored rather than applied.
Outcome string
Ignored bool
Detail map[string]any
ContactID *uuid.UUID
// AmountCents is signed: a refund is negative.
AmountCents *int64
Currency string
}
Consumed is what a consumer did with an event, for the event log.
type DailyArgs ¶
type DailyArgs struct{}
DailyArgs sends the daily summary of failed payments to the people who turned it on.
func (DailyArgs) InsertOpts ¶
func (DailyArgs) InsertOpts() river.InsertOpts
InsertOpts runs on the system queue, once a day.
type DailyWorker ¶
type DailyWorker struct {
river.WorkerDefaults[DailyArgs]
S *Service
}
DailyWorker runs DailyArgs.
type EarnAccessInput ¶
type EarnAccessInput struct {
OnPaymentFailure string `json:"onPaymentFailure" enum:"keep,end"`
}
EarnAccessInput changes the access rules.
type EarnAccessRules ¶
type EarnAccessRules struct {
OnPaymentFailure string `json:"onPaymentFailure" enum:"keep,end"`
CanManage bool `json:"canManage"`
Helpers []string `json:"helpers"`
}
EarnAccessRules are the access rules (Earn › Settings › Access).
type EarnAccount ¶
type EarnAccount struct {
ID string `json:"id"`
Name string `json:"name"`
Country string `json:"country"`
Currency string `json:"currency"`
TaxEnabled bool `json:"taxEnabled"`
}
EarnAccount is the connected account.
type EarnAudience ¶
type EarnAudience struct {
// Who on the list: everyone, paid members at the tier and above, free
// subscribers (no paid access). Paid and free add up to everyone with
// any paid tier.
Everyone int64 `json:"everyone"`
Paid int64 `json:"paid"`
Free int64 `json:"free"`
// WithAccess counts every paid member at the tier and above (test paid
// members never count); LeftOut says why some aren't recipients.
WithAccess int64 `json:"withAccess"`
LeftOut EarnAudienceLeftOut `json:"leftOut"`
// PastDue counts the recipients whose payment failed while Stripe
// retries (they keep access); Trialing, Complimentary and Gift the
// others included.
PastDue int64 `json:"pastDue"`
Trialing int64 `json:"trialing"`
Complimentary int64 `json:"complimentary"`
Gift int64 `json:"gift"`
Tiers []EarnAudienceTier `json:"tiers"`
// Connected is false until a payment provider is connected.
Connected bool `json:"connected"`
}
EarnAudience is the popover's numbers for a list.
type EarnAudienceLeftOut ¶
type EarnAudienceLeftOut struct {
// NotOnList: paid members who never joined the list.
NotOnList int64 `json:"notOnList"`
// Unsubscribed from the list's emails (they keep their access).
Unsubscribed int64 `json:"unsubscribed"`
Suppressed int64 `json:"suppressed"`
// Inactive contacts (bounced, complained, paused by the team).
Inactive int64 `json:"inactive"`
}
EarnAudienceLeftOut says why paid members aren't recipients.
type EarnAudienceTier ¶
type EarnAudienceTier struct {
ID string `json:"id"`
Name string `json:"name"`
// Short is how readers name it ("Insider"); Top is the highest tier
// ("Founding member" rather than "Founding member and above").
Short string `json:"short"`
Top bool `json:"top"`
}
EarnAudienceTier is a tier the popover offers, lowest first.
type EarnCancelInput ¶
type EarnCancelInput struct {
When string `json:"when" enum:"period_end,now"`
Email bool `json:"email" doc:"Send the Membership canceled email"`
Note string `json:"note,omitempty" maxLength:"500"`
}
EarnCancelInput cancels a subscription for a reader who asked by email.
type EarnChecklist ¶
type EarnChecklist struct {
Steps []EarnChecklistStep `json:"steps"`
Done int `json:"done"`
// Launched: every step is done, or readers pay through the live key
// (the Overview shows revenue instead).
Launched bool `json:"launched"`
// TestCheckouts are the test paid members, left out of every number.
TestCheckouts []EarnMemberRow `json:"testCheckouts"`
TestCheckout string `json:"testCheckoutUrl,omitempty"`
UpgradeHost string `json:"upgradeHost"`
CanManage bool `json:"canManage"`
CanEdit bool `json:"canEdit"`
}
EarnChecklist is the launch checklist on Earn's Overview while a workspace sets up paid subscriptions (EarnStates).
type EarnChecklistStep ¶
type EarnChecklistStep struct {
Key string `json:"key" enum:"connect,tier,emails,page,test,live"`
Done bool `json:"done"`
// Detail says what was done ("Test key · Acme Media · 17 Sep").
Detail string `json:"detail,omitempty"`
// Blocked says why the step can't be done yet (no Transactional route).
Blocked string `json:"blocked,omitempty" enum:"no_route,"`
// Facts for the detail line.
Mode string `json:"mode,omitempty"`
Account string `json:"account,omitempty"`
At *time.Time `json:"at,omitempty"`
Count int64 `json:"count,omitempty"`
Total int64 `json:"total,omitempty"`
Name string `json:"name,omitempty"`
PriceLine string `json:"priceLine,omitempty"`
}
EarnChecklistStep is one step of the launch checklist.
type EarnCheckoutInput ¶
type EarnCheckoutInput struct {
TaxAtCheckout bool `json:"taxAtCheckout"`
PricesIncludeTax bool `json:"pricesIncludeTax"`
Portal EarnPortal `json:"portal"`
}
EarnCheckoutInput changes checkout's settings (Earn › Settings › Payments).
type EarnCheckoutSettings ¶
type EarnCheckoutSettings struct {
Currency string `json:"currency"`
// CurrencyFixed is true once a tier has prices.
CurrencyFixed bool `json:"currencyFixed"`
TaxAvailable bool `json:"taxAvailable"`
TaxAtCheckout bool `json:"taxAtCheckout"`
PricesIncludeTax bool `json:"pricesIncludeTax"`
Portal EarnPortal `json:"portal"`
}
EarnCheckoutSettings are checkout's settings: currency, Stripe Tax and what the customer portal lets readers do.
type EarnComplimentaryInput ¶
type EarnComplimentaryInput struct {
ContactID string `json:"contactId,omitempty" doc:"An existing contact"`
Email string `json:"email,omitempty" maxLength:"320" doc:"A new address: it joins the tier's lists through the usual double opt-in"`
TierID string `json:"tierId"`
// Until is the day access ends; empty for no end date.
Until string `json:"until,omitempty" maxLength:"10" doc:"YYYY-MM-DD; empty for no end date"`
Reason string `json:"reason" enum:"team,contributor,press,partner,giveaway,other"`
Note string `json:"note,omitempty" maxLength:"500"`
SendWelcome bool `json:"sendWelcome"`
}
EarnComplimentaryInput gives a contact, or a new address, a tier.
type EarnComposer ¶
type EarnComposer struct {
// Connected is true once a live payment provider is connected: until
// then, the Upgrade block is hidden.
Connected bool `json:"connected"`
Tiers []EarnComposerTier `json:"tiers"`
UpgradeURL string `json:"upgradeUrl"`
}
EarnComposer is what the composer's paid content needs: the tiers, the connection and the upgrade page.
type EarnComposerOffer ¶
type EarnComposerOffer struct {
Code string `json:"code"`
Name string `json:"name"`
Period string `json:"period" enum:"month,year"`
// Option is the settings' choice: "FALL26 · $64 for the first year".
Option string `json:"option"`
// Line is the card's price line: "$64 for your first year with FALL26,
// then $80 a year".
Line string `json:"line"`
// Button is "Get Insider for $64".
Button string `json:"button"`
// EndsAt is when the offer ends, when it does.
EndsAt *time.Time `json:"endsAt,omitempty"`
}
EarnComposerOffer is a signup offer an Upgrade block can carry (ComposerEarnBlocks): the settings' choice and what the card says.
type EarnComposerTier ¶
type EarnComposerTier struct {
ID string `json:"id"`
Name string `json:"name"`
Short string `json:"short"`
Top bool `json:"top"`
// PriceLine is "$8/month or $80/year · 14 days free"; empty without a
// price.
PriceLine string `json:"priceLine"`
TrialDays int32 `json:"trialDays"`
// Includes names the lower tiers whose paid content it includes.
Includes []string `json:"includes"`
// Offers are the live signup offers on the tier an Upgrade block can
// carry (X17).
Offers []EarnComposerOffer `json:"offers"`
}
EarnComposerTier is a tier as the composer shows it: its name, how readers name it, and the price line the Upgrade block reads.
type EarnConnectInput ¶
type EarnConnectInput struct {
Provider string `json:"provider" enum:"stripe" default:"stripe"`
Key string `` /* 137-byte string literal not displayed */
}
EarnConnectInput starts a connection with a restricted key (the wizard's "Check key").
type EarnConnection ¶
type EarnConnection struct {
ID string `json:"id"`
Provider string `json:"provider" enum:"stripe"`
ProviderName string `json:"providerName"`
Mode string `json:"mode" enum:"live,test"`
Status string `json:"status" enum:"setup,connected"`
Step string `json:"step" enum:"check,webhook,settings,done"`
Health string `json:"health" enum:"setup,key_rejected,webhook_missing,missing_permissions,webhook_silent,connected"`
KeyHint string `json:"keyHint"`
Account EarnAccount `json:"account"`
Permissions []EarnPermissionCheck `json:"permissions"`
Granted int `json:"granted"`
CheckedAt *time.Time `json:"checkedAt,omitempty"`
KeyRejectedAt *time.Time `json:"keyRejectedAt,omitempty"`
Webhook EarnWebhook `json:"webhook"`
ConnectedAt *time.Time `json:"connectedAt,omitempty"`
ConnectedBy string `json:"connectedBy,omitempty"`
PortalSet bool `json:"portalSet"`
Demo bool `json:"demo"`
// Links into the provider's dashboard.
DashboardURL string `json:"dashboardUrl"`
KeysURL string `json:"keysUrl"`
CreateKeyURL string `json:"createKeyUrl"`
WebhooksURL string `json:"webhooksUrl"`
EmailsURL string `json:"emailsUrl"`
}
EarnConnection is a payment connection: the connect wizard's state and the Payments tab's card.
type EarnDisconnectInput ¶
type EarnDisconnectInput struct {
Confirm string `json:"confirm" maxLength:"200" doc:"The account's name, as the dialog asks (Acme Media)"`
}
EarnDisconnectInput confirms a disconnection by typing the account's name.
type EarnEvent ¶
type EarnEvent struct {
ID string `json:"id"`
Mode string `json:"mode" enum:"live,test"`
EventID string `json:"eventId"`
Type string `json:"type"`
Source string `json:"source" enum:"webhook,gap_check,history,manual"`
OccurredAt time.Time `json:"occurredAt"`
ReceivedAt time.Time `json:"receivedAt"`
// Status: applied, ignored (nothing to do), failed (retried), rejected
// (a bad signature, never applied), pending.
Status string `json:"status" enum:"pending,applied,ignored,failed,rejected"`
// Outcome names what was done ("renewed", "past_due"); Detail has its
// facts (tier, dates, the member email sent).
Outcome string `json:"outcome"`
Detail map[string]any `json:"detail"`
AmountCents *int64 `json:"amountCents,omitempty"`
Currency string `json:"currency,omitempty"`
MemberID string `json:"memberId,omitempty"`
ContactID string `json:"contactId,omitempty"`
MemberName string `json:"memberName,omitempty"`
MemberEmail string `json:"memberEmail,omitempty"`
// EventURL opens the event in the provider's dashboard.
EventURL string `json:"eventUrl,omitempty"`
}
EarnEvent is one line of the payments event log: the provider's event next to what ReputeCast did with it.
type EarnEventCount ¶
EarnEventCount is the events of one type in the last 24 hours.
type EarnEventFilter ¶
type EarnEventFilter struct {
Group string `query:"group" enum:"all,payments,failures,refunds,changes,trials" default:"all" doc:"A group of event types"`
Range string `query:"range" enum:"24h,7d,30d,90d" default:"7d" doc:"How far back (raw events are kept 90 days)"`
Q string `query:"q" maxLength:"200" doc:"Search the event type, the event id, the paid member or the raw event"`
Test bool `query:"test" doc:"Include test-mode events"`
Page int `query:"page" minimum:"1" default:"1"`
PageSize int `query:"pageSize" minimum:"1" maximum:"100" default:"8"`
}
EarnEventFilter narrows the payments event log.
type EarnEventLog ¶
type EarnEventLog struct {
Items []EarnEvent `json:"items"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
Range string `json:"range"`
// Types are the event types the log holds, for the search's hints.
Types []string `json:"types"`
}
EarnEventLog is a page of the payments event log.
type EarnEventsFile ¶
type EarnEventsFile struct {
ContentType string `header:"Content-Type"`
ContentDisposition string `header:"Content-Disposition"`
CacheControl string `header:"Cache-Control"`
Body []byte
}
EarnEventsFile is a CSV download.
type EarnFinishInput ¶
type EarnFinishInput struct {
TaxAtCheckout bool `json:"taxAtCheckout"`
PricesIncludeTax bool `json:"pricesIncludeTax"`
Portal EarnPortal `json:"portal"`
}
EarnFinishInput is the wizard's last settings: Stripe Tax at checkout, prices with or without tax, and what the portal lets readers do.
type EarnFinished ¶
type EarnFinished struct {
Connection EarnConnection `json:"connection"`
// Drafts is how many member emails were created as drafts.
Drafts int `json:"drafts"`
// Tiers is how many tiers got their product in the provider.
Tiers int `json:"tiers"`
}
EarnFinished is a finished connection and what came with it.
type EarnFreeCard ¶
type EarnFreeCard struct {
List *EarnListRef `json:"list,omitempty"`
Line string `json:"line"`
Text string `json:"text"`
Readers int64 `json:"readers"`
}
EarnFreeCard is the free list's card.
type EarnGapRun ¶
type EarnGapRun struct {
At time.Time `json:"at"`
Applied int `json:"applied"`
Types map[string]int `json:"types"`
}
EarnGapRun is one run of the hourly check for missed events.
type EarnGrantInput ¶
type EarnGrantInput struct {
TierID string `json:"tierId"`
Until string `json:"until,omitempty" maxLength:"10" doc:"YYYY-MM-DD; empty for no end date"`
Reason string `json:"reason" enum:"team,contributor,press,partner,giveaway,other"`
Note string `json:"note,omitempty" maxLength:"500"`
}
EarnGrantInput changes complimentary access: its tier or end date.
type EarnGroupPriceInput ¶
type EarnGroupPriceInput struct {
// Off removes the tier's group prices (teams that pay them keep them).
Off bool `json:"off,omitempty"`
Monthly int64 `json:"monthly,omitempty" minimum:"0" maximum:"10000000" doc:"Per seat per month, in minor units"`
Yearly int64 `json:"yearly,omitempty" minimum:"0" maximum:"100000000" doc:"Per seat per year, in minor units"`
SeatsMin int `json:"seatsMin,omitempty" minimum:"0" maximum:"1000"`
SeatsMax int `json:"seatsMax,omitempty" minimum:"0" maximum:"1000"`
}
EarnGroupPriceInput is a tier's group prices: per seat, for seatsMin to seatsMax seats (2–1000). An amount of 0 turns that period off.
type EarnGroupPrices ¶
type EarnGroupPrices struct {
Monthly *EarnPrice `json:"monthly,omitempty"`
Yearly *EarnPrice `json:"yearly,omitempty"`
SeatsMin int `json:"seatsMin"`
SeatsMax int `json:"seatsMax"`
// Teams is how many teams buy the tier now, and Seats their seats.
Teams int64 `json:"teams"`
Seats int64 `json:"seats"`
}
EarnGroupPrices is a tier's group prices.
type EarnImport ¶
type EarnImport struct {
ID string `json:"id"`
Mode string `json:"mode" enum:"live,test"`
Source string `json:"source" enum:"substack,ghost,beehiiv,kit,csv"`
Platform string `json:"platform"`
Status string `json:"status" enum:"uploaded,matched,importing,done,failed,canceled"`
FileName string `json:"fileName"`
FileSize int64 `json:"fileSize"`
Rows int `json:"rows"`
Columns []EarnImportColumn `json:"columns"`
// Problem: no_email (pick the email column) or empty.
Problem string `json:"problem,omitempty" enum:"no_email,"`
WithCustomer int64 `json:"withCustomer"`
// Account names the account the rows are matched with.
Account string `json:"account"`
// The match step's groups.
Active *EarnImportGroup `json:"active,omitempty"`
Ended *EarnImportGroup `json:"ended,omitempty"`
None *EarnImportGroup `json:"none,omitempty"`
Conflicts []EarnImportConflict `json:"conflicts"`
PaidFirst *time.Time `json:"paidFirst,omitempty"`
PaidLast *time.Time `json:"paidLast,omitempty"`
Prices []EarnImportPrice `json:"prices"`
Lists []EarnListRef `json:"lists"`
Decisions EarnImportDecisions `json:"decisions"`
Done int `json:"done"`
Stats *EarnImportStats `json:"stats,omitempty"`
Error string `json:"error,omitempty"`
CreatedBy string `json:"createdBy,omitempty"`
CreatedAt time.Time `json:"createdAt"`
StartedAt *time.Time `json:"startedAt,omitempty"`
FinishedAt *time.Time `json:"finishedAt,omitempty"`
Tiers []EarnListRef `json:"tiers"`
}
EarnImport is the import dialog's state.
type EarnImportCandidate ¶
type EarnImportCandidate struct {
Customer string `json:"customer"`
Created time.Time `json:"created"`
Status string `json:"status,omitempty"`
Since *time.Time `json:"since,omitempty"`
AmountCents int64 `json:"amountCents,omitempty"`
Currency string `json:"currency,omitempty"`
Period string `json:"period,omitempty"`
Tier string `json:"tier,omitempty"`
}
EarnImportCandidate is one of a conflict's customers.
type EarnImportColumn ¶
type EarnImportColumn struct {
Name string `json:"name"`
UsedAs string `json:"usedAs" enum:"email,customer,plan,paid_through,name,"`
Example string `json:"example"`
}
EarnImportColumn is a column of the export and what it's used as.
type EarnImportColumnsInput ¶
type EarnImportColumnsInput struct {
Email string `json:"email" maxLength:"200"`
Customer string `json:"customer,omitempty" maxLength:"200"`
Plan string `json:"plan,omitempty" maxLength:"200"`
PaidThrough string `json:"paidThrough,omitempty" maxLength:"200"`
Name string `json:"name,omitempty" maxLength:"200"`
}
EarnImportColumnsInput picks the columns by hand.
type EarnImportConflict ¶
type EarnImportConflict struct {
Row int `json:"row"`
Email string `json:"email"`
Candidates []EarnImportCandidate `json:"candidates"`
Chosen string `json:"chosen,omitempty"`
}
EarnImportConflict is one email with several customers.
type EarnImportDecisions ¶
type EarnImportDecisions struct {
// NoSubscription is what rows without a subscription become.
NoSubscription string `json:"noSubscription" enum:"complimentary,free,skip" default:"complimentary"`
// Conflicts picks a customer per conflicting row ("" skips it).
Conflicts map[string]string `json:"conflicts,omitempty"`
// Prices maps each provider price to a tier.
Prices map[string]EarnImportPriceChoice `json:"prices,omitempty"`
// Lists overrides the tiers' lists (empty: the tiers' own).
SendWelcome bool `json:"sendWelcome"`
}
EarnImportDecisions are the choices of steps 3 and 4.
type EarnImportGroup ¶
type EarnImportGroup struct {
Count int64 `json:"count"`
ByCustomer int64 `json:"byCustomer"`
ByEmail int64 `json:"byEmail"`
Examples []EarnImportMatch `json:"examples"`
}
EarnImportGroup is one group of the match step.
type EarnImportMatch ¶
type EarnImportMatch struct {
Row int `json:"row"`
Email string `json:"email"`
Name string `json:"name,omitempty"`
Customer string `json:"customer,omitempty"`
Tier string `json:"tier,omitempty"`
AmountCents int64 `json:"amountCents,omitempty"`
Currency string `json:"currency,omitempty"`
Period string `json:"period,omitempty"`
EndedAt *time.Time `json:"endedAt,omitempty"`
PaidThrough *time.Time `json:"paidThrough,omitempty"`
}
EarnImportMatch is a row of the export as matched.
type EarnImportPrice ¶
type EarnImportPrice struct {
PriceID string `json:"priceId"`
AmountCents int64 `json:"amountCents"`
Currency string `json:"currency"`
Period string `json:"period" enum:"month,year,"`
Subscriptions int64 `json:"subscriptions"`
// TierID is the tier it maps to; Legacy keeps it as a legacy price.
TierID string `json:"tierId,omitempty"`
Legacy bool `json:"legacy"`
// Known: a tier's price already (nothing to choose).
Known bool `json:"known"`
}
EarnImportPrice is a provider price the export's paid members pay.
type EarnImportPriceChoice ¶
EarnImportPriceChoice maps a provider price.
type EarnImportStats ¶
type EarnImportStats struct {
Paid int64 `json:"paid"`
Free int64 `json:"free"`
Complimentary int64 `json:"complimentary"`
Skipped int64 `json:"skipped"`
Merged int64 `json:"merged"`
New int64 `json:"new"`
PricesMapped int64 `json:"pricesMapped"`
EmailsSent int64 `json:"emailsSent"`
CompFirst *time.Time `json:"compFirst,omitempty"`
CompLast *time.Time `json:"compLast,omitempty"`
}
EarnImportStats is the import's summary.
type EarnListRef ¶
EarnListRef names a list.
type EarnMapPriceInput ¶
type EarnMapPriceInput struct {
TierID string `json:"tierId"`
// Legacy keeps it as a legacy price of the tier (its paid members keep
// paying it); otherwise it becomes the tier's current price of its period.
Legacy bool `json:"legacy"`
}
EarnMapPriceInput maps a price no tier knows.
type EarnMember ¶
type EarnMember struct {
EarnMemberRow
// Stripe holds the provider's ids and dashboard links.
CustomerID string `json:"customerId,omitempty"`
SubscriptionID string `json:"subscriptionId,omitempty"`
CustomerURL string `json:"customerUrl,omitempty"`
SubscriptionURL string `json:"subscriptionUrl,omitempty"`
BillingEmail string `json:"billingEmail,omitempty"`
BillingDiffers bool `json:"billingDiffers"`
FailureReason string `json:"failureReason,omitempty"`
// FailureText is the failure in a few words in the reader's language
// ("insufficient funds"); Stripe's own words when it isn't a usual one.
FailureText string `json:"failureText,omitempty"`
FailedAt *time.Time `json:"failedAt,omitempty"`
RenewalReminder *time.Time `json:"renewalReminder,omitempty"`
PaidCents int64 `json:"paidCents"`
ClickedAt *time.Time `json:"clickedAt,omitempty"`
ImportedAt *time.Time `json:"importedAt,omitempty"`
MatchedBy string `json:"matchedBy,omitempty"`
GrantUntil *time.Time `json:"grantUntil,omitempty"`
GrantNote string `json:"grantNote,omitempty"`
CanceledBy string `json:"canceledBy,omitempty"`
CanceledAt *time.Time `json:"canceledAt,omitempty"`
Warning *EarnSyncWarning `json:"warning,omitempty"`
Timeline []EarnTimelineItem `json:"timeline"`
// What the viewer may do, and who can help when they can't.
CanManage bool `json:"canManage"`
Helpers []string `json:"helpers"`
// Emails lists the member emails that can be resent to this paid member.
Emails []string `json:"emails"`
Link string `json:"link"`
// Lists are the tier's lists ("already on Weekly Digest"); TaxAdded says
// amounts are before tax, which checkout adds.
Lists []string `json:"lists"`
TaxAdded bool `json:"taxAdded"`
// Seats are a team buyer's people, the buyer first (M65).
Seats []EarnTeamSeat `json:"seats"`
// CanPause: payments can pause (active, Stripe, not ending); CanResume:
// they're paused.
CanPause bool `json:"canPause"`
CanResume bool `json:"canResume"`
}
EarnMember is the member panel.
type EarnMemberCounts ¶
type EarnMemberCounts struct {
WithAccess int64 `json:"withAccess"`
Paying int64 `json:"paying"`
Trialing int64 `json:"trialing"`
PastDue int64 `json:"pastDue"`
CancelsSoon int64 `json:"cancelsSoon"`
Complimentary int64 `json:"complimentary"`
Gift int64 `json:"gift"`
Ended int64 `json:"ended"`
Paused int64 `json:"paused"`
}
EarnMemberCounts are the status chips' numbers (live only).
type EarnMemberDiscount ¶
type EarnMemberDiscount struct {
Label string `json:"label"`
AmountCents int64 `json:"amountCents"`
Percent float64 `json:"percent,omitempty"`
Duration string `json:"duration,omitempty"`
EndsAt *time.Time `json:"endsAt,omitempty"`
}
EarnMemberDiscount is a paid member's discount.
type EarnMemberEmail ¶
type EarnMemberEmail struct {
Email string `` /* 142-byte string literal not displayed */
TemplateID string `json:"templateId,omitempty"`
Template string `json:"template"`
Name string `json:"name"`
// Status: live (LiveVersion is live), draft (never published), missing.
Status string `json:"status" enum:"live,draft,missing"`
LiveVersion int `json:"liveVersion"`
DraftVersion int `json:"draftVersion"`
}
EarnMemberEmail is one member email on Earn › Settings › Member emails.
type EarnMemberEmails ¶
type EarnMemberEmails struct {
Emails []EarnMemberEmail `json:"emails"`
// The sender, reply-to, category and route they go out with.
FromName string `json:"fromName"`
FromEmail string `json:"fromEmail"`
ReplyTo string `json:"replyTo"`
CategoryName string `json:"categoryName"`
CategoryKind string `json:"categoryKind"`
RoutePrimary string `json:"routePrimary"`
RouteFallback string `json:"routeFallback"`
// FirstGiftEnding is when the first Gift ending reminder is due (the
// unpublished warning).
FirstGiftEnding *time.Time `json:"firstGiftEnding,omitempty"`
// TierShort names the first tier ("Insider"), for the email names.
TierShort string `json:"tierShort"`
CanPublish bool `json:"canPublish"`
Helpers []string `json:"helpers"`
EmailsURL string `json:"emailsUrl"`
}
EarnMemberEmails is the Member emails tab.
type EarnMemberFilter ¶
type EarnMemberFilter struct {
Status string `query:"status" enum:"with_access,paying,trialing,past_due,cancels_soon,complimentary,gift,ended,paused" default:"with_access"`
Q string `query:"q" maxLength:"200" doc:"Name, email, billing email or Stripe customer ID"`
Tier string `query:"tier" doc:"Tier id"`
Period string `query:"period" enum:"month,year,"`
Source string `query:"source" enum:"campaign,automation,page,offer,website,import,gift,grant,direct,group,"`
Offer string `query:"offer" maxLength:"60" doc:"An offer's label (FALL26)"`
Since string `query:"since" enum:"7d,30d,90d,1y,"`
// Campaign is the email a paid member came from (Weekly Digest #141).
Campaign string `query:"campaign" doc:"Campaign id: paid members credited to it"`
// Before is "Before the move": paid members since before a date.
Before string `query:"before" format:"date" doc:"Paid members since before this date"`
// Test shows test paid members too (Show test data).
Test bool `query:"test"`
// AllStatuses searches Ended too ("Search Ended too").
AllStatuses bool `query:"all"`
Page int `query:"page" minimum:"1" default:"1"`
PageSize int `query:"pageSize" minimum:"1" maximum:"100" default:"8"`
}
EarnMemberFilter narrows the paid members list.
type EarnMemberList ¶
type EarnMemberList struct {
Items []EarnMemberRow `json:"items"`
Total int64 `json:"total"`
Counts EarnMemberCounts `json:"counts"`
// The summary line: paying, MRR, past due.
MRRCents int64 `json:"mrrCents"`
Currency string `json:"currency"`
// TestMembers counts the test paid members (Show test data).
TestMembers int64 `json:"testMembers"`
TestShown int64 `json:"testShown"`
Tiers []EarnListRef `json:"tiers"`
Offers []string `json:"offers"`
UpgradeURL string `json:"upgradeUrl"`
UpgradeHost string `json:"upgradeHost"`
CanManage bool `json:"canManage"`
CanExport bool `json:"canExport"`
CanImport bool `json:"canImport"`
CanSeeNames bool `json:"canSeeNames"`
Helpers []string `json:"helpers"`
ExportHelpers []string `json:"exportHelpers"`
AccessRule string `json:"accessRule" enum:"keep,end"`
Connected bool `json:"connected"`
// Campaigns are the emails paid members are credited to, newest first
// (the Source filter's choices); Platforms the imports' old platforms.
Campaigns []EarnListRef `json:"campaigns"`
Platforms []string `json:"platforms"`
// MovedAt is the first import's day ("Before the move (18 Sep)").
MovedAt *time.Time `json:"movedAt,omitempty"`
}
EarnMemberList is Earn › Paid members.
type EarnMemberRow ¶
type EarnMemberRow struct {
ID string `json:"id"`
ContactID string `json:"contactId"`
Name string `json:"name"`
Email string `json:"email"`
// Hidden: the viewer lacks subscribers:view, so names and addresses aren't shown.
Hidden bool `json:"hidden"`
// Erased: the contact was erased; the row is kept for revenue history
// with no name or address ("Erased contact").
Erased bool `json:"erased"`
Test bool `json:"test"`
Kind string `json:"kind" enum:"stripe,complimentary,gift,group"`
Tier string `json:"tier"`
TierName string `json:"tierName"`
Period string `json:"period" enum:"month,year,"`
AmountCents int64 `json:"amountCents"`
Currency string `json:"currency"`
Discount *EarnMemberDiscount `json:"discount,omitempty"`
Legacy bool `json:"legacy"`
Status string `json:"status" enum:"trialing,active,past_due,canceled,complimentary,gift,group"`
CancelAt *time.Time `json:"cancelAt,omitempty"`
Since time.Time `json:"since"`
// Next is what comes next: renews, ends, retries (past due),
// trial_ends, no_end (complimentary without an end), resumes (paused),
// ended.
Next string `json:"next" enum:"renews,ends,retries,trial_ends,no_end,resumes,ended"`
NextAt *time.Time `json:"nextAt,omitempty"`
// Quantity is a team's seats (1 otherwise); AmountCents is per seat.
Quantity int `json:"quantity"`
// PausedAt and PausedUntil: payments paused ("Paused until 15 Jan").
PausedAt *time.Time `json:"pausedAt,omitempty"`
PausedUntil *time.Time `json:"pausedUntil,omitempty"`
// Team is the buyer's team or a seat holder's.
Team *EarnMemberTeam `json:"team,omitempty"`
LTVCents int64 `json:"ltvCents"`
Refunded int64 `json:"refundedCents"`
Source EarnMemberSource `json:"source"`
// EndReason and CancelReason explain an ended row.
EndReason string `json:"endReason,omitempty"`
CancelReason string `json:"cancelReason,omitempty"`
AccessPaused bool `json:"accessPaused"`
// GiftFrom names a gift's giver; GiftPeriod its length (a year).
GiftFrom string `json:"giftFrom,omitempty"`
GiftMonths int `json:"giftMonths,omitempty"`
// PeriodShown: the tier sells monthly and yearly, so the period goes
// with its name ("Insider yearly", but "Founding member").
PeriodShown bool `json:"periodShown"`
TierID string `json:"tierId,omitempty"`
// contains filtered or unexported fields
}
EarnMemberRow is one paid member in the list.
type EarnMemberSource ¶
type EarnMemberSource struct {
Kind string `json:"kind" enum:"campaign,automation,page,offer,website,import,gift,grant,direct,group,"`
Label string `json:"label"`
CampaignID string `json:"campaignId,omitempty"`
// GrantedBy and Reason name complimentary access.
GrantedBy string `json:"grantedBy,omitempty"`
Reason string `json:"reason,omitempty"`
// Platform is the old platform of an import (substack), ImportID the
// import that brought the paid member in.
Platform string `json:"platform,omitempty"`
ImportID string `json:"importId,omitempty"`
}
EarnMemberSource is how a paid member got here.
type EarnMemberTeam ¶
type EarnMemberTeam struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role" enum:"buyer,seat"`
Seats int `json:"seats"`
// Used counts the buyer and every invited or active seat.
Used int `json:"used"`
Ended *time.Time `json:"endedAt,omitempty"`
// BuyerID opens the buyer's panel from a seat holder's; BuyerName
// names them. Invites counts the invites still open.
BuyerID string `json:"buyerId,omitempty"`
BuyerName string `json:"buyerName,omitempty"`
Invites int `json:"invites"`
// RenewsAt is when the team's subscription renews (its seats last
// with it).
RenewsAt *time.Time `json:"renewsAt,omitempty"`
// SeatID is a seat holder's seat (Remove seat from their panel).
SeatID string `json:"seatId,omitempty"`
}
EarnMemberTeam is a paid member's team: the buyer's ("Team · 8 of 10") or the one a seat holder belongs to ("Seat in Acme Inc").
type EarnPageTier ¶
type EarnPageTier struct {
ID string `json:"id"`
Name string `json:"name"`
Visibility string `json:"visibility" enum:"public,hidden,archived"`
Shown bool `json:"shown"`
TrialDays int `json:"trialDays"`
}
EarnPageTier is a tier as the page editor lists it.
type EarnPagesInput ¶
type EarnPagesInput struct {
TermsURL string `json:"termsUrl" maxLength:"500"`
SupportEmail string `json:"supportEmail" maxLength:"320"`
}
EarnPagesInput changes the pages' footer.
type EarnPagesSettings ¶
type EarnPagesSettings struct {
TermsURL string `json:"termsUrl"`
SupportEmail string `json:"supportEmail"`
UpgradeURL string `json:"upgradeUrl"`
UpgradeHost string `json:"upgradeHost"`
UpgradeLive bool `json:"upgradeLive"`
Visits int64 `json:"visits"`
CancelHost string `json:"cancelHost"`
GiftHost string `json:"giftHost"`
CanEdit bool `json:"canEdit"`
Helpers []string `json:"helpers"`
}
EarnPagesSettings are the Pages tab: what the upgrade, cancel and gift pages show in their footer, and the pages themselves.
type EarnPauseInput ¶
type EarnPauseInput struct {
Months int `json:"months,omitempty" enum:"0,1,3,6"`
Until string `json:"until,omitempty" format:"date" doc:"YYYY-MM-DD, in the workspace's time zone; at most 6 months away"`
// Note goes on the member's timeline ("Asked by email: travelling").
Note string `json:"note,omitempty" maxLength:"300"`
// SkipEmail doesn't send the "Membership paused" email.
SkipEmail bool `json:"skipEmail,omitempty"`
}
EarnPauseInput pauses a paid member's payments: for 1, 3 or 6 months, or until a date at most 6 months away.
type EarnPausing ¶
type EarnPausing struct {
Months []int `json:"months"`
}
EarnPausing is Earn › Settings › Pausing.
type EarnPausingInput ¶
type EarnPausingInput struct {
Months []int `json:"months" maxItems:"3" doc:"Any of 1, 3 and 6; none turns pausing off."`
}
EarnPausingInput sets the pause lengths members may choose on the cancel page.
type EarnPayments ¶
type EarnPayments struct {
Providers []EarnProviderCard `json:"providers"`
Live *EarnConnection `json:"live,omitempty"`
Test *EarnConnection `json:"test,omitempty"`
Checkout EarnCheckoutSettings `json:"checkout"`
Permissions []EarnPermissionCheck `json:"permissions"`
WebhookEvents []string `json:"webhookEvents"`
Unmapped []EarnUnmappedPrice `json:"unmapped"`
// Active is the mode public pages use: live once connected, else test.
Active string `json:"active" enum:"live,test,"`
// ActiveSubscriptions counts the live paying subscriptions (the silent
// webhook's sentence).
ActiveSubscriptions int64 `json:"activeSubscriptions"`
TestMembers int64 `json:"testMembers"`
CanManage bool `json:"canManage"`
// CanEditPrices maps unmapped prices (earn:edit).
CanEditPrices bool `json:"canEditPrices"`
Helpers []string `json:"helpers"`
// PauseMonths are the pause lengths members may choose on the cancel
// page (M65; none: they can't pause).
PauseMonths []int `json:"pauseMonths"`
}
EarnPayments is Earn › Settings › Payments.
type EarnPermissionCheck ¶
type EarnPermissionCheck struct {
Resource string `json:"resource"`
Access string `json:"access" enum:"read,write"`
OK *bool `json:"ok,omitempty"`
}
EarnPermissionCheck is one permission the restricted key needs and, once checked, whether it has it.
type EarnPlans ¶
type EarnPlans struct {
UpgradePage EarnUpgradeCard `json:"upgradePage"`
Free EarnFreeCard `json:"free"`
Tiers []EarnTier `json:"tiers"`
Currency string `json:"currency"`
Connected bool `json:"connected"`
CanEdit bool `json:"canEdit"`
Helpers []string `json:"helpers"`
Lists []EarnListRef `json:"lists"`
// Brand colours the tier editor's preview as readers see the card.
Brand Brand `json:"brand"`
}
EarnPlans is Earn › Plans & offers: the upgrade page, the free card and the tiers (offers and gift options come from X17's section).
type EarnPortal ¶
type EarnPortal struct {
UpdateCard bool `json:"updateCard"`
Invoices bool `json:"invoices"`
BillingEmail bool `json:"billingEmail"`
SwitchPeriod bool `json:"switchPeriod"`
Cancel bool `json:"cancel"`
}
EarnPortal is what the customer portal lets readers do.
type EarnPreview ¶
type EarnPreview struct {
HTML string `json:"html"`
}
EarnPreview is the rendered page.
type EarnPreviewInput ¶
type EarnPreviewInput struct {
Page UpgradePage `json:"page"`
// As is who the preview is for: an anonymous visitor, a free reader
// from an email, or a paid member.
As string `json:"as" enum:"visitor,free,paid,offer" default:"visitor"`
}
EarnPreviewInput renders the upgrade page with unsaved settings.
type EarnPrice ¶
type EarnPrice struct {
ID string `json:"id"`
Period string `json:"period" enum:"month,year"`
AmountCents int64 `json:"amountCents"`
Currency string `json:"currency"`
// Status: current takes new paid members; legacy keeps the ones who pay it.
Status string `json:"status" enum:"current,legacy"`
StripeLiveID string `json:"stripeLiveId,omitempty"`
StripeTestID string `json:"stripeTestId,omitempty"`
// StripeID is the id in the mode public pages use, and URL its page.
StripeID string `json:"stripeId,omitempty"`
StripeURL string `json:"stripeUrl,omitempty"`
Origin string `json:"origin" enum:"tier,mapped"`
// Members pay this price (paying and trialing), Discounted of them with an offer.
Members int64 `json:"members"`
Paying int64 `json:"paying"`
Discounted int64 `json:"discounted"`
// Offers are the paying members with an offer, by the offer's label
// ("45 with FALL26"), most first.
Offers []EarnPriceOffer `json:"offers"`
}
EarnPrice is one of a tier's prices.
type EarnPriceOffer ¶
EarnPriceOffer is how many paying members of a price have an offer.
type EarnProviderCard ¶
type EarnProviderCard struct {
Key string `json:"key" enum:"stripe,paddle,lemonsqueezy"`
Name string `json:"name"`
Available bool `json:"available"`
MerchantOfRecord bool `json:"merchantOfRecord"`
Capabilities []string `json:"capabilities"`
}
EarnProviderCard is a payment provider in the catalog (3.1).
type EarnReach ¶
type EarnReach struct {
OK bool `json:"ok"`
Checked bool `json:"checked"`
At *time.Time `json:"at,omitempty"`
Code string `json:"code,omitempty"`
Reason string `json:"reason,omitempty"`
// Host is the public URL's host ("reputecast.acme.io").
Host string `json:"host"`
}
EarnReach is the last check of whether the provider can reach the webhook address.
type EarnReplaceKeyInput ¶
type EarnReplaceKeyInput struct {
Key string `json:"key" minLength:"1" maxLength:"300" doc:"A restricted key of the same account and mode. Write-only."`
}
EarnReplaceKeyInput is a new restricted key for a connection.
type EarnResendInput ¶
type EarnResendInput struct {
Email string `json:"email" enum:"welcome,trial_ending,payment_failed,renewal_reminder,canceled,group_welcome,paused,resuming_soon"`
}
EarnResendInput resends a member email.
type EarnResent ¶
type EarnResent struct {
Status string `json:"status" enum:"sent,not_sent"`
Reason string `json:"reason,omitempty"`
}
EarnResent says how resending went.
type EarnStatus ¶
type EarnStatus struct {
Provider string `json:"provider,omitempty"`
ProviderName string `json:"providerName,omitempty"`
Account string `json:"account,omitempty"`
// Mode is the mode public pages use; "" without a payment provider.
Mode string `json:"mode" enum:"live,test,"`
Health string `json:"health,omitempty"`
// TestOnly: only a test key is connected (the Test mode banner).
TestOnly bool `json:"testOnly"`
CanManage bool `json:"canManage"`
// Setup is a connect wizard in progress, to resume.
Setup string `json:"setup,omitempty"`
// UpgradeURL is the upgrade page ("Open upgrade page").
UpgradeURL string `json:"upgradeUrl"`
}
EarnStatus is the connection chip on every Earn screen.
type EarnStepInput ¶
type EarnStepInput struct {
Step string `json:"step" enum:"webhook,settings"`
}
EarnStepInput moves the wizard on (Continue to settings).
type EarnSyncStep ¶
type EarnSyncStep struct {
Step string `json:"step" enum:"product,month,year"`
Status string `json:"status" enum:"done,failed,pending"`
At *time.Time `json:"at,omitempty"`
ID string `json:"id,omitempty"`
// Amount is the price's amount (month and year steps).
AmountCents int64 `json:"amountCents,omitempty"`
Error string `json:"error,omitempty"`
Tries int `json:"tries,omitempty"`
}
EarnSyncStep is one step of saving a tier in the provider.
type EarnSyncWarning ¶
type EarnSyncWarning struct {
Subscriptions []EarnMemberRow `json:"subscriptions"`
}
EarnSyncWarning is a second active subscription for one person.
type EarnTeamSeat ¶
type EarnTeamSeat struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
// Status is invited or active; the buyer is the team's first row.
Status string `json:"status" enum:"buyer,invited,active"`
InvitedAt time.Time `json:"invitedAt"`
AcceptedAt *time.Time `json:"acceptedAt,omitempty"`
// InviteExpiresAt is when an invite stops working.
InviteExpiresAt *time.Time `json:"inviteExpiresAt,omitempty"`
// MemberID opens an active seat holder's own panel.
MemberID string `json:"memberId,omitempty"`
}
EarnTeamSeat is one person of a team in the member panel.
type EarnTestDataCleared ¶
type EarnTestDataCleared struct {
Members int64 `json:"members"`
}
EarnTestDataCleared says what clearing test data removed.
type EarnTier ¶
type EarnTier struct {
ID string `json:"id"`
// Name is the full name; ShortName how readers say it ("Insider").
Name string `json:"name"`
ShortName string `json:"shortName"`
Slug string `json:"slug"`
Description string `json:"description"`
Benefits []string `json:"benefits"`
TrialDays int `json:"trialDays" enum:"0,7,14,30"`
Lists []EarnListRef `json:"lists"`
AccessRank int `json:"accessRank"`
Visibility string `json:"visibility" enum:"public,hidden,archived"`
// Highlight is the label above the card on the upgrade page ("Most
// popular"), when this tier is the highlighted one.
Highlight string `json:"highlight,omitempty"`
// Monthly and Yearly are the current prices.
Monthly *EarnPrice `json:"monthly,omitempty"`
Yearly *EarnPrice `json:"yearly,omitempty"`
Prices []EarnPrice `json:"prices"`
// Paying are the paying members (active and past due), by period.
Paying int64 `json:"paying"`
PayingMonthly int64 `json:"payingMonthly"`
PayingYearly int64 `json:"payingYearly"`
Trialing int64 `json:"trialing"`
// MRRCents is the tier's monthly recurring revenue (paying members
// only, after discounts, a yearly price as a twelfth).
MRRCents int64 `json:"mrrCents"`
// IncludesBelow names the tiers of lower rank whose paid content it includes.
Includes []string `json:"includes"`
// The product in the provider (in the mode public pages use).
ProductID string `json:"productId,omitempty"`
ProductURL string `json:"productUrl,omitempty"`
SyncStatus string `json:"syncStatus" enum:"draft,synced,failed"`
SyncSteps []EarnSyncStep `json:"syncSteps"`
SyncedAt *time.Time `json:"syncedAt,omitempty"`
// Origin is "import" for a tier whose product was mapped when paid
// members were imported: from ImportedFrom ("substack") on ImportedAt.
Origin string `json:"origin,omitempty"`
ImportedFrom string `json:"importedFrom,omitempty"`
ImportedAt *time.Time `json:"importedAt,omitempty"`
HiddenLink string `json:"hiddenLink"`
CreatedAt time.Time `json:"createdAt"`
ArchivedAt *time.Time `json:"archivedAt,omitempty"`
CanDelete bool `json:"canDelete"`
DiscountedYearly int64 `json:"discountedYearly"`
// Group is the tier's group prices for teams (M65), when it has any.
Group *EarnGroupPrices `json:"group,omitempty"`
}
EarnTier is a tier: what readers pay for.
type EarnTierInput ¶
type EarnTierInput struct {
Name string `json:"name" minLength:"1" maxLength:"80"`
Slug string `json:"slug,omitempty" maxLength:"60" doc:"The hidden tier's link: /upgrade/{slug}. Made from the name when empty."`
Description string `json:"description,omitempty" maxLength:"500"`
Benefits []string `json:"benefits" maxItems:"12"`
// Monthly and Yearly are amounts in minor units ($8 = 800); 0 or
// omitted turns the period off.
Monthly int64 `json:"monthly,omitempty" minimum:"0" maximum:"10000000"`
Yearly int64 `json:"yearly,omitempty" minimum:"0" maximum:"100000000"`
TrialDays int `json:"trialDays" enum:"0,7,14,30"`
Lists []string `json:"lists" maxItems:"20"`
AccessRank int `json:"accessRank" minimum:"1" maximum:"20"`
Visibility string `json:"visibility" enum:"public,hidden,archived"`
// Highlight puts the tier forward on the upgrade page with this label
// ("Most popular"); empty takes the highlight off it.
Highlight string `json:"highlight,omitempty" maxLength:"30"`
// Group sets the tier's group prices (teams, M65); omitted keeps them
// as they are.
Group *EarnGroupPriceInput `json:"group,omitempty"`
}
EarnTierInput creates or changes a tier.
type EarnTierSaved ¶
type EarnTierSaved struct {
Tier EarnTier `json:"tier"`
// SyncError says what the provider answered when a step failed; the
// tier is saved either way and Retry creates only what's missing.
SyncError string `json:"syncError,omitempty"`
}
EarnTierSaved is a saved tier and, when a provider is connected, how saving it there went.
type EarnTimelineItem ¶
type EarnTimelineItem struct {
ID string `json:"id"`
Kind string `json:"kind"`
At time.Time `json:"at"`
AmountCents *int64 `json:"amountCents,omitempty"`
Currency string `json:"currency,omitempty"`
StripeEvent string `json:"stripeEvent,omitempty"`
Actor string `json:"actor,omitempty"`
Test bool `json:"test"`
Data map[string]any `json:"data"`
// MessageStatus is the member email's delivery (delivered, bounced…) and
// Provider who carried it.
MessageStatus string `json:"messageStatus,omitempty"`
Provider string `json:"provider,omitempty"`
MessageID string `json:"messageId,omitempty"`
}
EarnTimelineItem is one entry of a paid member's timeline.
type EarnUnmappedPrice ¶
type EarnUnmappedPrice struct {
ID string `json:"id"`
Mode string `json:"mode" enum:"live,test"`
PriceID string `json:"priceId"`
Period string `json:"period" enum:"month,year,"`
AmountCents int64 `json:"amountCents"`
Currency string `json:"currency"`
FoundAt time.Time `json:"foundAt"`
Subscriptions int64 `json:"subscriptions"`
// Members are the paid members on it (up to 5).
Members []EarnMemberRow `json:"members"`
}
EarnUnmappedPrice is a price found in the provider that no tier knows.
type EarnUpgradeCard ¶
type EarnUpgradeCard struct {
URL string `json:"url"`
Host string `json:"host"`
// Live: a public tier can be bought (a payment provider is connected).
Live bool `json:"live"`
TestMode bool `json:"testMode"`
Visits int64 `json:"visits"`
CheckoutsStarted int64 `json:"checkoutsStarted"`
Completed int64 `json:"completed"`
Trials int64 `json:"trials"`
PaidAtOnce int64 `json:"paidAtOnce"`
// TestCheckoutURL opens the page in test mode for a day (team members).
TestCheckoutURL string `json:"testCheckoutUrl,omitempty"`
}
EarnUpgradeCard is the upgrade page's card on Plans & offers.
type EarnUpgradeEditor ¶
type EarnUpgradeEditor struct {
Page UpgradePage `json:"page"`
Tiers []EarnPageTier `json:"tiers"`
Lists []EarnListRef `json:"lists"`
URL string `json:"url"`
Host string `json:"host"`
Live bool `json:"live"`
PublishedAt *string `json:"publishedAt,omitempty"`
PublishedBy string `json:"publishedBy,omitempty"`
// TestCheckout: a test key is connected, so "Preview with test
// checkout" works.
TestCheckout bool `json:"testCheckout"`
TestCheckoutURL string `json:"testCheckoutUrl,omitempty"`
CanEdit bool `json:"canEdit"`
Helpers []string `json:"helpers"`
}
EarnUpgradeEditor is the upgrade page editor's data.
type EarnWebhook ¶
type EarnWebhook struct {
URL string `json:"url"`
ID string `json:"id,omitempty"`
Registered bool `json:"registered"`
RegisteredAt *time.Time `json:"registeredAt,omitempty"`
Manual bool `json:"manual"`
Events []string `json:"events"`
SecretStored bool `json:"secretStored"`
MissingAt *time.Time `json:"missingAt,omitempty"`
Reach EarnReach `json:"reach"`
// Status: unregistered, waiting (no event yet), receiving, silent, missing.
Status string `json:"status" enum:"unregistered,waiting,receiving,silent,missing"`
FirstEventAt *time.Time `json:"firstEventAt,omitempty"`
FirstEventType string `json:"firstEventType,omitempty"`
LastEventAt *time.Time `json:"lastEventAt,omitempty"`
LastEventType string `json:"lastEventType,omitempty"`
Events24h int64 `json:"events24h"`
Rejected24h int64 `json:"rejected24h"`
ByType []EarnEventCount `json:"byType"`
GapCheckedAt *time.Time `json:"gapCheckedAt,omitempty"`
GapRuns []EarnGapRun `json:"gapRuns"`
NextGapAt *time.Time `json:"nextGapAt,omitempty"`
// SilentHours is how long no event came, when silent.
SilentHours int `json:"silentHours,omitempty"`
}
EarnWebhook is the connection's webhook and its freshness.
type EarnWebhookSecretInput ¶
type EarnWebhookSecretInput struct {
Secret string `json:"secret" minLength:"10" maxLength:"300" doc:"The endpoint's signing secret (whsec_…). Write-only."`
}
EarnWebhookSecretInput is a signing secret pasted by hand (the manual path, when the public URL can't be reached).
type FreeCardView ¶
type FreeCardView struct {
Name string
Price string
Line string
Text string
Reading bool
Subscribe string
Button string
ReadingIt string
}
FreeCardView is the free list's card.
type HourlyArgs ¶
type HourlyArgs struct{}
HourlyArgs is the hourly check: every connected account's missed events, its webhook and its key.
func (HourlyArgs) InsertOpts ¶
func (HourlyArgs) InsertOpts() river.InsertOpts
InsertOpts runs on the events queue, once at a time.
type HourlyWorker ¶
type HourlyWorker struct {
river.WorkerDefaults[HourlyArgs]
S *Service
}
HourlyWorker runs HourlyArgs.
func (*HourlyWorker) Timeout ¶
func (w *HourlyWorker) Timeout(*river.Job[HourlyArgs]) time.Duration
Timeout bounds one run.
func (*HourlyWorker) Work ¶
func (w *HourlyWorker) Work(ctx context.Context, _ *river.Job[HourlyArgs]) error
Work implements river.Worker.
type ImportArgs ¶
type ImportArgs struct {
ImportID string `json:"import_id"`
}
ImportArgs runs a paid-members import.
func (ImportArgs) InsertOpts ¶
func (ImportArgs) InsertOpts() river.InsertOpts
InsertOpts runs on the default queue.
type ImportWorker ¶
type ImportWorker struct {
river.WorkerDefaults[ImportArgs]
S *Service
}
ImportWorker runs ImportArgs.
func (*ImportWorker) Timeout ¶
func (w *ImportWorker) Timeout(*river.Job[ImportArgs]) time.Duration
Timeout bounds one run.
func (*ImportWorker) Work ¶
func (w *ImportWorker) Work(ctx context.Context, job *river.Job[ImportArgs]) error
Work implements river.Worker.
type Join ¶
type Join struct {
Email, FirstName, LastName string
Lists []uuid.UUID
Double bool
// Source and Note are the consent evidence ("paid_subscription").
Source, Note string
// ConsentText, IP, UserAgent and Language are a page's evidence (a
// team invite accepted: M65).
ConsentText, IP, UserAgent, Language string
At time.Time
}
Join is a subscription request from a paid flow.
type KnownReader ¶
KnownReader is the reader of a personal link.
type Mailer ¶
type Mailer interface {
// Category returns the Essential category member emails go in: one of
// c.Known when the workspace has it, else a new one named c.Name.
Category(ctx context.Context, ws *store.Workspace, c MemberCategory) (uuid.UUID, error)
// CreateDraft creates a template draft from a member email's starter.
CreateDraft(ctx context.Context, ws *store.Workspace, p *authz.Principal, d TemplateDraft) (uuid.UUID, error)
// Templates reads the templates' keys and versions.
Templates(ctx context.Context, ws *store.Workspace, ids []uuid.UUID) (map[uuid.UUID]TemplateState, error)
// Send sends a template's live version; ErrNotPublished when it has none.
Send(ctx context.Context, ws *store.Workspace, m MemberMessage) (Sent, error)
// Route names the Transactional route ("" when there is none).
Route(ctx context.Context, ws *store.Workspace) (Route, error)
}
Mailer sends the member emails through transactional email and keeps their templates (internal/transactional, wired in internal/app).
type MemberCategory ¶
type MemberCategory struct {
Name, Description string
// Known are the names that find the category ReputeCast made before:
// Name, and the English one.
Known []string
}
MemberCategory is the member emails' category in the workspace's language ("Memberships" in English).
type MemberEmailResult ¶
type MemberEmailResult struct {
Status string
Reason string
MessageID *uuid.UUID
Template string
Version int
}
MemberEmailResult is what sending a member email did: sent, or not_sent and why (not_published, no_route, suppressed, failed, no_mailer, no_template).
func (MemberEmailResult) Sent ¶
func (r MemberEmailResult) Sent() bool
Sent reports whether the email went out.
type MemberMessage ¶
type MemberMessage struct {
Template string
To string
ToName string
Data map[string]any
// Key makes a retry send nothing twice.
Key string
// Localize writes the values that are sentences, dates or prices in the
// language of the version the send picks (a content language code, ""
// for the workspace's default); Data has them in English.
Localize func(language string) map[string]any
}
MemberMessage is one member email to send.
type OfferBanner ¶
type OfferBanner struct {
// Label is the offer's name in bold ("FALL26:").
Label string
Text string
}
OfferBanner is an offer link's line on the upgrade page.
type OfferCodeRedeemer ¶
type OfferCodeRedeemer interface {
CodeRedeemed(ctx context.Context, tx pgx.Tx, ws *store.Workspace, code string, at time.Time) error
}
OfferCodeRedeemer, when the Offers hook has it, marks a single-use offer code (a referral reward's) used once a subscription takes it.
type OfferHook ¶
type OfferHook interface {
// UpgradeOffer shows an offer link's offer (?offer=FALL26) on the
// upgrade page: its line and the price of the tier and period it
// applies to, or that it has ended and the normal prices.
UpgradeOffer(ctx context.Context, ws *store.Workspace, mode, code string, reader uuid.UUID, v *UpgradeView) error
// CheckoutCode is the provider's promotion code to apply for an offer
// link, when the offer is live and applies to the tier and period; ""
// otherwise.
CheckoutCode(ctx context.Context, ws *store.Workspace, mode, code string, reader, tier uuid.UUID, period string) string
// PeriodFor is the period an offer link opens the page on (the one
// the offer applies to); "" for the page's default.
PeriodFor(ctx context.Context, ws *store.Workspace, code string, reader uuid.UUID) string
}
OfferHook applies offers on the upgrade page and at checkout. reader is the contact of the page's personal link (?r=), uuid.Nil without one: a single-use code (a referral reward's) works only for the reader it was issued to.
type OneTimeHook ¶
type OneTimeHook interface {
// CheckoutCompleted handles a paid one-time checkout; handled is false
// when it isn't one of the hook's.
CheckoutCompleted(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, cs payments.CheckoutSession, at time.Time) (handled bool, detail map[string]any, err error)
// Refunded handles the refund of a one-time payment.
Refunded(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, ch payments.Charge, at time.Time) (handled bool, detail map[string]any, err error)
// CheckoutFailed handles a one-time checkout whose delayed payment (a
// bank debit) didn't clear.
CheckoutFailed(ctx context.Context, tx pgx.Tx, ws *store.Workspace, mode string, cs payments.CheckoutSession, at time.Time) (handled bool, detail map[string]any, err error)
}
OneTimeHook takes the payment events of one-time payments: gifts.
type PageNotice ¶
PageNotice is a notice at the top of the page.
type PageSettings ¶
PageSettings is what every Earn page shows: the terms of sale's address, the support email, the currency, and whether tax is added at checkout.
type PaidMemberEvent ¶
type PaidMemberEvent struct {
ContactID string `json:"contact_id"`
Email string `json:"email"`
SubscriptionID string `json:"subscription_id,omitempty"`
Mode string `json:"mode"`
Kind string `json:"kind"`
Status string `json:"status,omitempty"`
Tier string `json:"tier,omitempty"`
Period string `json:"period,omitempty"`
AmountCents *int64 `json:"amount_cents,omitempty"`
Currency string `json:"currency,omitempty"`
OccurredAt time.Time `json:"occurred_at"`
Detail map[string]any `json:"detail,omitempty"`
}
PaidMemberEvent is the data of a "Paid members" webhook event.
type PaidMemberSummary ¶
type PaidMemberSummary struct {
Counts EarnMemberCounts `json:"counts"`
MRRCents int64 `json:"mrr_cents"`
Currency string `json:"currency"`
Tiers []PaidTierCount `json:"tiers"`
// Mode is the mode the upgrade page sells in ("" without a connection).
Mode string `json:"mode"`
}
PaidMemberSummary is what agents read about paid members: counts by status and by tier, and the MRR, live only and without names.
type PaidTierCount ¶
type PaidTierCount struct {
Tier string `json:"tier"`
Paying int64 `json:"paying"`
Trialing int64 `json:"trialing"`
Complimentary int64 `json:"complimentary"`
Gift int64 `json:"gift"`
}
PaidTierCount is one tier's paid members.
type PaidView ¶
type PaidView struct {
Heading string
Email string
NotYou string
Tier string
Price string
Renews string
Manage bool
Button string
Note string
Emailed string
}
PaidView is the "already a paid member" card. Its personal link never expires and travels in forwarded emails, so Manage doesn't open the portal: its button emails the member a link (SendBillingLink), as Emailed says.
type PaymentConsumer ¶
PaymentConsumer handles an event about its own objects; ok false leaves the event to the next consumer, then to Earn.
type PaymentEvent ¶
type PaymentEvent struct {
Workspace *store.Workspace
ConnectionID uuid.UUID
Provider string
Mode payments.Mode
// EventID is the payments event log's row; Type the provider's event
// type ("checkout.session.completed").
EventID uuid.UUID
Type string
Payment payments.Payment
// Client opens the connection's client (to read more from the provider).
Client func() (payments.Client, error)
}
PaymentEvent is a one-time payment event offered to consumers.
type PreferencesPaid ¶
type PreferencesPaid struct {
// Kind: stripe, complimentary, gift or free.
Kind string
Title string
Heading string
Price string
Line string
// Manage opens the billing portal, Cancel the cancel step, Upgrade the
// upgrade page (free readers, and gifts to keep going). Billing says
// the member pays through Stripe: Manage and Cancel are set only when
// asked for direct links; otherwise the page has the member ask for
// them by email, under their labels.
Billing bool
Manage string
ManageLabel string
Cancel string
CancelLabel string
Upgrade string
UpgradeLabel string
Test bool
}
PreferencesPaid is the "Your paid subscription" section of the preference center: a paid member's tier and billing, complimentary access or a gift, or, for a free reader while the upgrade page is public, what they could get.
type ReaderLink ¶
ReaderLink is a link a campaign fills in per reader.
type ResumeView ¶
type ResumeView struct {
// State is ask (the page), resumed or none (nothing paused).
State string
Heading string
Text string
Email string
Button string
// Later says when it resumes on its own.
Later string
}
ResumeView is the page of a "Resume now" link (PublicEarnStates).
type SellingConnection ¶
type SellingConnection struct {
ID uuid.UUID
Provider string
Mode payments.Mode
// Account is the account's name ("Acme Media").
Account string
// Currency is the workspace currency (lowercase), else the account's.
Currency string
// Tax: the provider calculates tax (Stripe Tax), the workspace adds it
// at checkout, and whether prices include it.
TaxEnabled bool
TaxAtCheckout bool
PricesIncludeTax bool
// Live is also connected, when Mode is test: false means "test mode".
HasLive bool
}
SellingConnection is a connected payment account, as sellers see it.
type Service ¶
type Service struct {
Pool *pgxpool.Pool
Q *store.Queries
Audit *audit.Logger
Box *secrets.Box
Links *linktoken.Signer
URLs publicurl.Builder
Log *slog.Logger
Jobs func() *jobs.Client
Now func() time.Time
// Mailer sends member emails (nil: none are sent; they are logged as
// not sent).
Mailer Mailer
// Mail sends System mail: the billing link a member asks for
// (SendBillingLink; nil: none is sent).
Mail func() mailer.Sender
// Signup joins lists with consent; Confirmations sends double opt-in.
Signup Signup
Confirmations Confirmations
// PublicPages names the upgrade page's address on the workspace's own
// domain (news.acme.io/upgrade), when it has one.
PageBase func(ctx context.Context, ws *store.Workspace) string
// Brand is the public pages' branding: the publisher's name ("Acme")
// and the page colours, for the in-app previews of reader pages.
Brand func(ctx context.Context, ws *store.Workspace) Brand
// StripeBase and StripeHTTP point Stripe at a fake (tests).
StripeBase string
StripeHTTP *http.Client
// Demo is the in-process Stripe the demo's sample connections use.
Demo func() *http.Client
// AllowPrivate lets webhooks use a private public URL (development,
// tests): providers.allow_private_networks.
AllowPrivate bool
// Reach overrides the public URL's reachability check (tests).
Reach func(ctx context.Context, url, token string) Reach
// Render renders a public Earn page with the workspace's branding
// (internal/publicpages): the upgrade page editor's preview.
Render func(ctx context.Context, ws *store.Workspace, page string, view any) (string, error)
// Offers applies offer links on the upgrade page and at checkout, and
// OneTime takes one-time payments' events (gifts); X17, x17.go.
Offers OfferHook
OneTime OneTimeHook
// contains filtered or unexported fields
}
Service is the Earn domain.
func (*Service) AcceptTeamInvite ¶
func (s *Service) AcceptTeamInvite(ctx context.Context, ws *store.Workspace, token string, in JoinInput, l i18n.Lang) (TeamJoinView, error)
AcceptTeamInvite accepts an invite: the address joins the tier's lists with this acceptance as its consent (single opt-in), and gets a seat's access row that follows the buyer's.
func (*Service) AccessRules ¶
func (s *Service) AccessRules(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnAccessRules, error)
AccessRules reads the access rules.
func (*Service) ActiveMode ¶
ActiveMode is the mode the workspace sells in: live once the live key is connected, else test; "" without a connection.
func (*Service) Apply ¶
Apply applies one stored event: the paid member's status, timeline and member emails, then the event log's line. An event applied before is skipped, so a retried job changes nothing twice.
func (*Service) ApplyPending ¶
ApplyPending applies the events stored but not applied yet (tests, and the sweep after a job that never ran).
func (*Service) Audience ¶
func (s *Service) Audience(ctx context.Context, ws *store.Workspace, list, tier string) (EarnAudience, error)
Audience counts who on a list a paid-only campaign reaches.
func (*Service) BillingURL ¶
func (s *Service) BillingURL(ctx context.Context, ws *store.Workspace, contact uuid.UUID, valid time.Duration) string
BillingURL is a paid member's personal link to their billing portal, working for valid.
func (*Service) CancelImport ¶
CancelImport drops an import that hasn't started, with its file.
func (*Service) CancelPauseChoices ¶
func (s *Service) CancelPauseChoices(ctx context.Context, ws *store.Workspace, sub store.PaidSubscription) []int
CancelPauseChoices are the pause lengths a member's cancel page offers: the workspace's allowed lengths, for a subscription that can pause and hasn't paused in the last 12 months (none otherwise).
func (*Service) CancelPortal ¶
func (s *Service) CancelPortal(ctx context.Context, ws *store.Workspace, sub store.PaidSubscription, returnURL string) (string, error)
CancelPortal opens the provider portal on the subscription's cancel step; the reader comes back to returnURL.
func (*Service) CancelSubscription ¶
func (s *Service) CancelSubscription(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnCancelInput) (EarnMember, error)
CancelSubscription cancels a paid subscription in the provider, at the end of the period or now. Refunds are made in the provider.
func (*Service) CancelTargetOf ¶
func (s *Service) CancelTargetOf(ctx context.Context, ws *store.Workspace, token string) (*CancelTarget, error)
CancelTargetOf reads a cancel link (TokenCancel): ErrLinkInvalid when it isn't one, ErrLinkExpired when it's past its time or no longer verifies, ErrNoSubscription when the reader has no subscription to cancel (complimentary and gift access end on their own).
func (*Service) CancelURL ¶
func (s *Service) CancelURL(ctx context.Context, ws *store.Workspace, contact uuid.UUID, valid time.Duration) string
CancelURL is a paid member's link to cancel (the cancel page, X17; until then the portal's cancel step), working for valid.
func (*Service) ChangeComplimentary ¶
func (s *Service) ChangeComplimentary(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnGrantInput) (EarnMember, error)
ChangeComplimentary changes complimentary access.
func (*Service) Checklist ¶
func (s *Service) Checklist(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnChecklist, error)
Checklist is the launch checklist's state.
func (*Service) ClearTestData ¶
func (s *Service) ClearTestData(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnTestDataCleared, error)
ClearTestData deletes test paid members, their timelines and test checkouts. Contacts stay; live data is never touched.
func (*Service) ClientFor ¶
func (s *Service) ClientFor(ctx context.Context, wsID uuid.UUID, mode string) (payments.Client, store.PaymentConnection, error)
ClientFor opens the provider client of the workspace's connection in mode (live or test).
func (*Service) Connect ¶
func (s *Service) Connect(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnConnectInput) (EarnConnection, error)
Connect checks a restricted key and keeps the connection in progress: the account, its mode (from the key's prefix) and each permission. A key that lacks permissions is kept, so "Check again" works once the key is edited in Stripe; a refused key is never stored.
func (*Service) Connection ¶
func (s *Service) Connection(ctx context.Context, ws *store.Workspace, id string) (EarnConnection, error)
Connection is one connection's state (the wizard resumes from it).
func (*Service) ContactPaid ¶
func (s *Service) ContactPaid(ctx context.Context, ws *store.Workspace, p *authz.Principal, contact string) (*EarnMember, error)
ContactPaid is a contact's paid subscription for the contact profile's card (the one with access, else the latest).
func (*Service) CreateTier ¶
func (s *Service) CreateTier(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnTierInput) (EarnTierSaved, error)
CreateTier creates a tier and its product and prices in the provider.
func (*Service) DailyFailed ¶
DailyFailed tells the people who turned on the daily summary how many payments failed in the last day (earn:view; off by default).
func (*Service) DateText ¶
DateText is a date as the member emails write it ("24 Dec", with the year when it isn't this year's), in the workspace's time zone.
func (*Service) DateTextIn ¶
DateTextIn is DateText in a language ("24 thg 12").
func (*Service) DeleteTier ¶
func (s *Service) DeleteTier(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) error
DeleteTier deletes a tier that never had paid members.
func (*Service) Disconnect ¶
func (s *Service) Disconnect(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnDisconnectInput) error
Disconnect stops checkout, the portal links and status updates from the provider. Subscriptions keep billing there: disconnecting never cancels anyone, and paid members keep access until the end of what they paid. The key and the signing secret are deleted from ReputeCast.
func (*Service) EnsureMemberEmailDrafts ¶
ensureMemberEmails creates the Memberships category and the member emails' drafts the workspace doesn't have yet. It returns how many it created. EnsureMemberEmailDrafts makes, as ReputeCast, the member emails' drafts a workspace that already has some lacks: an email added after the workspace connected Stripe (review 2026-11 EN-9's gift payment failure). Publishing them stays the workspace's.
func (*Service) EventLog ¶
func (s *Service) EventLog(ctx context.Context, ws *store.Workspace, p *authz.Principal, f EarnEventFilter) (EarnEventLog, error)
EventLog is a page of the payments event log, newest first. Readers' own changes in checkout or the portal show here, never in the audit log.
func (*Service) Export ¶
func (s *Service) Export(ctx context.Context, ws *store.Workspace, p *authz.Principal, f EarnMemberFilter) ([]byte, int, error)
Export writes the paid members of a filter as CSV (subscribers:export, audited). Amounts are in the currency's major unit, before tax.
func (*Service) ExportEvents ¶
func (s *Service) ExportEvents(ctx context.Context, ws *store.Workspace, p *authz.Principal, f EarnEventFilter) ([]byte, int, error)
ExportEvents writes the payments event log a filter shows as CSV (review 2026-11 EA-2): what the log's table shows, not the raw payloads. It holds members' addresses, so it is audited.
func (*Service) Finish ¶
func (s *Service) Finish(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnFinishInput) (EarnFinished, error)
Finish saves the checkout settings, sets up the customer portal and finishes the connection; the first connection also creates the eight member emails as drafts, and drafted tiers get their products.
func (*Service) GiveComplimentary ¶
func (s *Service) GiveComplimentary(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnComplimentaryInput) (EarnMember, error)
GiveComplimentary gives complimentary access: it lives in ReputeCast only (nothing is created in the provider, nothing is charged, it never counts as revenue). A new address joins the tier's lists through the usual double opt-in.
func (*Service) Hourly ¶
Hourly checks every connected account: it reads the events the webhook missed and applies them, notices a webhook deleted in the provider or a rejected key, and tells the people with payments:manage once per problem.
func (*Service) Import ¶
func (s *Service) Import(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnImport, error)
Import is the import dialog's state.
func (*Service) ManageTeamURL ¶
ManageTeamURL is a team's manage link, for the buyer's account page.
func (*Service) MapPrice ¶
func (s *Service) MapPrice(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnMapPriceInput) error
MapPrice maps a price no tier knows to a tier: as a legacy price, or as the tier's current price of its period. Nothing changes in the provider; MRR and paid status update at once.
func (*Service) MatchImport ¶
func (s *Service) MatchImport(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnImport, error)
MatchImport matches every row with the connected account, read-only: by customer ID first, then by email. One email with several customers is a conflict to settle by hand.
func (*Service) Member ¶
func (s *Service) Member(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnMember, error)
Member is the member panel of a paid subscription.
func (*Service) MemberEmails ¶
func (s *Service) MemberEmails(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnMemberEmails, error)
MemberEmails is the Member emails tab.
func (*Service) Members ¶
func (s *Service) Members(ctx context.Context, ws *store.Workspace, p *authz.Principal, f EarnMemberFilter) (EarnMemberList, error)
Members is Earn › Paid members.
func (*Service) PageSettingsOf ¶
PageSettingsOf reads the Earn pages' settings.
func (*Service) PageURL ¶
PageURL is an Earn page's address: on the workspace's own domain when it has one ("https://news.acme.io/gift").
func (*Service) Pages ¶
func (s *Service) Pages(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnPagesSettings, error)
Pages reads the Pages tab.
func (*Service) PaidAccessOf ¶
func (s *Service) PaidAccessOf(ctx context.Context, ws *store.Workspace, contact uuid.UUID, mode string) (*store.PaidSubscription, string, error)
PaidAccessOf is the paid access a contact has now, in mode ("" for either): the subscription and its tier's name, or nil without any.
func (*Service) PaidMemberCounts ¶
func (s *Service) PaidMemberCounts(ctx context.Context, ws *store.Workspace) (PaidMemberSummary, error)
PaidMemberCounts summarizes the paid members (the MCP tool get_paid_member_counts).
func (*Service) PaidVars ¶
func (s *Service) PaidVars(ctx context.Context, wsID uuid.UUID, contacts []uuid.UUID) (map[uuid.UUID]map[string]any, error)
PaidVars are some readers' paid values, by contact: {"paid": {"tier": "Weekly Digest Insider", "status": "Active", "price": "$80/year", "renews_at": "7 Oct 2027", "ends_at": ""}}; every value is empty for a free subscriber. Test paid members never count.
func (*Service) PauseFromCancel ¶
func (s *Service) PauseFromCancel(ctx context.Context, ws *store.Workspace, sub store.PaidSubscription, months int, visit uuid.UUID) (time.Time, error)
PauseFromCancel pauses a member's subscription from their cancel page for one of the allowed lengths.
func (*Service) PauseMember ¶
func (s *Service) PauseMember(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnPauseInput) (EarnMember, error)
PauseMember pauses a paid member's payments from the member panel.
func (*Service) Payments ¶
func (s *Service) Payments(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnPayments, error)
Payments is Earn › Settings › Payments.
func (*Service) Plans ¶
func (s *Service) Plans(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnPlans, error)
Plans is Plans & offers.
func (*Service) Portal ¶
func (s *Service) Portal(ctx context.Context, ws *store.Workspace, token string, kind linktoken.Kind) (string, error)
Portal returns the billing portal of a personal link's paid member; cancel opens it on the cancel step of their subscription. Only a link still within its time does: ErrLinkExpired otherwise, and for a link signed with an earlier instance key.
func (*Service) PreferencesPaid ¶
func (s *Service) PreferencesPaid(ctx context.Context, ws *store.Workspace, contact uuid.UUID, l i18n.Lang, direct bool) (*PreferencesPaid, error)
PreferencesPaid builds the section for a contact (nil: none to show). direct mints Manage and Cancel, links that open the portal and the cancel page for an hour: for the account page of a member signed in on the website. The preference center's own link never expires and travels in forwarded emails (every "view online" page links to it), so it doesn't open the portal: it asks for the links by email.
func (*Service) PreviewUpgrade ¶
func (s *Service) PreviewUpgrade(ctx context.Context, ws *store.Workspace, in EarnPreviewInput) (EarnPreview, error)
PreviewUpgrade renders the upgrade page as readers would see it with the editor's settings, without saving them. Its links and buttons work in no way (the page is inert).
func (*Service) ReaderLinks ¶
ReaderLinks are the per-reader Earn links of a workspace's campaigns.
func (*Service) Recheck ¶
func (s *Service) Recheck(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnConnection, error)
Recheck checks the stored key's permissions again ("Check again").
func (*Service) RegisterAgain ¶
func (s *Service) RegisterAgain(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnConnection, error)
RegisterAgain registers a new webhook endpoint (the old one is deleted in the provider) and reads what was missed since the last event.
func (*Service) RegisterWebhook ¶
func (s *Service) RegisterWebhook(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnConnection, error)
RegisterWebhook registers the webhook in the provider: the endpoint, its events, and the sealed signing secret. When the public URL can't be reached from the internet nothing is registered and the state says so (the manual path).
func (*Service) RemoveComplimentary ¶
func (s *Service) RemoveComplimentary(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) error
RemoveComplimentary ends complimentary access now.
func (*Service) RemoveSeat ¶
func (s *Service) RemoveSeat(ctx context.Context, ws *store.Workspace, p *authz.Principal, memberID, seatID string, email bool) (EarnMember, error)
RemoveSeat removes a person from a team from Earn › Members (the buyer's panel): an invite stops working, an active seat's access ends now.
func (*Service) ReplaceKey ¶
func (s *Service) ReplaceKey(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnReplaceKeyInput) (EarnConnection, error)
ReplaceKey swaps a connection's key for a new one of the same account and mode, once its permissions are checked. The webhook stays as it is.
func (*Service) Resend ¶
func (s *Service) Resend(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnResendInput) (EarnResent, error)
Resend sends a member email again ("Resend Payment failed").
func (*Service) ResumeFromLink ¶
func (s *Service) ResumeFromLink(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang) (ResumeView, error)
ResumeFromLink resumes a member's paused subscription from their link.
func (*Service) ResumeMember ¶
func (s *Service) ResumeMember(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnMember, error)
ResumeMember resumes a paused member's payments now.
func (*Service) ResumePage ¶
func (s *Service) ResumePage(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang) (ResumeView, error)
ResumePage is the page of a resume link, in a language.
func (*Service) ResumeURL ¶
ResumeURL is a paused member's "Resume now" link (the paused email's): a billing link, working for LinkValidInEmail.
func (*Service) Routes ¶
Routes mounts the payment webhooks: POST /hooks/{provider}/{token}. Static paths win over the sending providers' /hooks/{adapter}/{token}.
func (*Service) RunImport ¶
RunImport imports the rows in pages: paid members with their subscription, ended ones as free subscribers, rows without a subscription as the choice says. Contacts are merged; everyone joins the tiers' lists with consent "Imported from Substack (paid member)". Nothing changes in the provider.
func (*Service) SaveAccessRules ¶
func (s *Service) SaveAccessRules(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnAccessInput) (EarnAccessRules, error)
SaveAccessRules changes the access rules; they apply from the next event.
func (*Service) SaveCheckout ¶
func (s *Service) SaveCheckout(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnCheckoutInput) (EarnCheckoutSettings, error)
SaveCheckout saves checkout's settings and updates the portal.
func (*Service) SavePages ¶
func (s *Service) SavePages(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnPagesInput) (EarnPagesSettings, error)
SavePages changes the pages' footer.
func (*Service) SavePausing ¶
func (s *Service) SavePausing(ctx context.Context, ws *store.Workspace, p *authz.Principal, in EarnPausingInput) (EarnPausing, error)
SavePausing saves the pause lengths members may choose.
func (*Service) SaveUpgradePage ¶
func (s *Service) SaveUpgradePage(ctx context.Context, ws *store.Workspace, p *authz.Principal, in UpgradePage) (EarnUpgradeEditor, error)
SaveUpgradePage publishes the page: readers see it at once.
func (*Service) Selling ¶
func (s *Service) Selling(ctx context.Context, ws *store.Workspace) (SellingConnection, bool, error)
Selling returns the connection sales use; ok is false when no payment provider is connected.
func (*Service) SellingClient ¶
func (s *Service) SellingClient(ctx context.Context, ws *store.Workspace, id uuid.UUID) (payments.Client, error)
SellingClient opens a client on a selling connection.
func (*Service) SellingIn ¶
func (s *Service) SellingIn(ctx context.Context, ws *store.Workspace, mode payments.Mode) (SellingConnection, bool, error)
SellingIn returns the connected account of one mode (a test order's return from checkout).
func (*Service) SendBillingLink ¶
func (s *Service) SendBillingLink(ctx context.Context, ws *store.Workspace, contact uuid.UUID, l i18n.Lang) error
SendBillingLink emails a paid member fresh links to their billing portal and their cancel page, working for LinkValidAsked, to the address on file, in a language. A contact without a subscription billed through Stripe gets nothing: complimentary access and gifts have nothing to pay.
func (*Service) SendMemberEmailIn ¶
func (s *Service) SendMemberEmailIn(ctx context.Context, ws *store.Workspace, email, to, toName string, data map[string]any, key string, texts func(l i18n.Lang) map[string]any) MemberEmailResult
SendMemberEmailIn is SendMemberEmailTo with values written in the email's language: texts gives them in the language of the version the send picks (data has them in English).
func (*Service) SendMemberEmailTo ¶
func (s *Service) SendMemberEmailTo(ctx context.Context, ws *store.Workspace, email, to, toName string, data map[string]any, key string) MemberEmailResult
SendMemberEmailTo sends one of the member emails (EmailGiftPurchased…) to an address that needn't be a contact: a gift's buyer, or its recipient before redeeming. key makes a retry send nothing twice.
func (*Service) SendTeamLink ¶
func (s *Service) SendTeamLink(ctx context.Context, ws *store.Workspace, g store.EarnGroup, l i18n.Lang) error
SendTeamLink emails a team's buyer a fresh manage link (System mail), at most one every ten minutes.
func (*Service) SetImportColumns ¶
func (s *Service) SetImportColumns(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnImportColumnsInput) (EarnImport, error)
SetImportColumns picks the columns of an export by hand (another CSV, or a file without an email column).
func (*Service) SetImportDecisions ¶
func (s *Service) SetImportDecisions(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnImportDecisions) (EarnImport, error)
SetImportDecisions saves the choices of steps 3 and 4.
func (*Service) SetStep ¶
func (s *Service) SetStep(ctx context.Context, ws *store.Workspace, id string, in EarnStepInput) (EarnConnection, error)
SetStep moves a connection in progress to a step.
func (*Service) StartCheckout ¶
func (s *Service) StartCheckout(ctx context.Context, ws *store.Workspace, r CheckoutRequest) (string, error)
StartCheckout opens the provider's checkout for a tier and returns its address. The reader's email is filled in when known; the trial is offered to readers who haven't had one; tax is added when Stripe Tax is on; offers apply as promotion codes and a reader can type one.
func (*Service) StartImport ¶
func (s *Service) StartImport(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string) (EarnImport, error)
StartImport checks the choices and starts the import in the background.
func (*Service) StartTeamCheckout ¶
func (s *Service) StartTeamCheckout(ctx context.Context, ws *store.Workspace, r TeamCheckoutRequest) (string, error)
StartTeamCheckout opens Stripe Checkout for a team: the group price per seat with the seats as its quantity, the buyer's tax ID and billing address collected, no trial. The team is made when the subscription arrives (its metadata names it).
func (*Service) Status ¶
func (s *Service) Status(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnStatus, error)
Status is the connection chip of the Earn screens.
func (*Service) Sweep ¶
Sweep applies events stored more than two minutes ago whose job never ran, ends access that has run out (complimentary access past its date, gifts past their end, and paid access a disconnected account can no longer renew) and purges raw events past 90 days.
func (*Service) SyncTier ¶
func (s *Service) SyncTier(ctx context.Context, ws *store.Workspace, id string) (EarnTierSaved, error)
SyncTier retries saving a tier in the provider.
func (*Service) TeamBilling ¶
func (s *Service) TeamBilling(ctx context.Context, ws *store.Workspace, token string, returnURL string, l i18n.Lang) (TeamResult, error)
TeamBilling opens the buyer's Stripe portal (invoices, card, billing details).
func (*Service) TeamInvite ¶
func (s *Service) TeamInvite(ctx context.Context, ws *store.Workspace, token, emails string, l i18n.Lang) (TeamResult, error)
TeamInvite invites people to a team: each address once, at most the free seats, while the team pays. Each gets the invite email.
func (*Service) TeamJoin ¶
func (s *Service) TeamJoin(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang) (TeamJoinView, error)
TeamJoin builds an invite's join page.
func (*Service) TeamManage ¶
func (s *Service) TeamManage(ctx context.Context, ws *store.Workspace, token string, l i18n.Lang, confirm string) (TeamManageView, error)
TeamManage builds the manage page of a link. An expired link mails a fresh one to the buyer (at most one every ten minutes) and says so. confirm names the seat whose Remove asks first.
func (*Service) TeamPage ¶
func (s *Service) TeamPage(ctx context.Context, ws *store.Workspace, r TeamRequest) (TeamView, error)
TeamPage builds a tier's team page.
func (*Service) TeamRemove ¶
func (s *Service) TeamRemove(ctx context.Context, ws *store.Workspace, token, seatID string, l i18n.Lang) (TeamResult, error)
TeamRemove removes a person from the team: an invite stops working, an active seat's access ends now.
func (*Service) TeamResend ¶
func (s *Service) TeamResend(ctx context.Context, ws *store.Workspace, token, seatID string, l i18n.Lang) (TeamResult, error)
TeamResend sends an invite again with a new link (the older one stops working), at most once a minute per seat.
func (*Service) TeamSetSeats ¶
func (s *Service) TeamSetSeats(ctx context.Context, ws *store.Workspace, token, seats string, l i18n.Lang) (TeamResult, error)
TeamSetSeats changes a team's seats at the provider (prorated): not below the people in the team, within the price's range.
func (*Service) TestCheckoutURL ¶
TestCheckoutURL is a test checkout link of the upgrade page, when a test key is connected ("" otherwise).
func (*Service) TestMode ¶
TestMode reports whether a test checkout link is valid for the workspace.
func (*Service) TierDetail ¶
TierDetail is the tier editor's data.
func (*Service) TierShortName ¶
TierShortName is a tier's name without its list's ("Insider" for Weekly Digest Insider on Weekly Digest).
func (*Service) Timeline ¶
func (s *Service) Timeline(ctx context.Context, q *store.Queries, wsID, contact uuid.UUID, sub *uuid.UUID, mode, kind string, at time.Time, actor *uuid.UUID, data map[string]any) error
Timeline adds an entry to a paid member's timeline in the caller's transaction (with its webhook event, when the kind has one).
func (*Service) UnsubscribePaid ¶
func (s *Service) UnsubscribePaid(ctx context.Context, ws *store.Workspace, contact uuid.UUID, l i18n.Lang) (*UnsubscribePaid, error)
UnsubscribePaid builds the note for a contact with paid access (nil otherwise).
func (*Service) UpdateTier ¶
func (s *Service) UpdateTier(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnTierInput) (EarnTierSaved, error)
UpdateTier changes a tier. A new amount is a new price: the old one becomes a legacy price its paid members keep paying.
func (*Service) Upgrade ¶
func (s *Service) Upgrade(ctx context.Context, ws *store.Workspace, r UpgradeRequest) (UpgradeView, error)
Upgrade builds the upgrade page.
func (*Service) UpgradeClicked ¶
UpgradeClicked records, on the reader's timeline, that the upgrade page was opened from an email's personal link ("Clicked the upgrade link · Weekly Digest #141 · credited to this email"), once per email.
func (*Service) UpgradeEditor ¶
func (s *Service) UpgradeEditor(ctx context.Context, ws *store.Workspace, p *authz.Principal) (EarnUpgradeEditor, error)
UpgradeEditor is the page editor's data.
func (*Service) UpgradeURL ¶
func (s *Service) UpgradeURL(ctx context.Context, ws *store.Workspace, contact, message uuid.UUID) string
UpgradeURL is a reader's personal upgrade link: the page knows them and credits the email it came from.
func (*Service) UploadImport ¶
func (s *Service) UploadImport(ctx context.Context, ws *store.Workspace, p *authz.Principal, source, name string, data []byte) (EarnImport, error)
UploadImport reads an export and finds its columns. Nothing is written to contacts until the import is started.
func (*Service) WebhookSecret ¶
func (s *Service) WebhookSecret(ctx context.Context, ws *store.Workspace, p *authz.Principal, id string, in EarnWebhookSecretInput) (EarnConnection, error)
WebhookSecret stores a signing secret for a webhook added by hand.
func (*Service) WebhookURL ¶
func (s *Service) WebhookURL(c store.PaymentConnection) string
WebhookURL is the connection's webhook address on the public URL.
func (*Service) Welcome ¶
func (s *Service) Welcome(ctx context.Context, ws *store.Workspace, session string, l i18n.Lang) (WelcomeView, error)
Welcome is the welcome page of a completed checkout. When the webhook hasn't arrived yet, the checkout is read from the provider and applied now, so the page never waits on it.
func (*Service) WelcomeLine ¶
func (s *Service) WelcomeLine(ctx context.Context, ws *store.Workspace, tier *uuid.UUID, first string, l i18n.Lang) string
WelcomeLine is the upgrade page's welcome text after its first sentence ("Your first members-only deep dive arrives Tue 21 Oct."), for a new paid member of the tier: the gift's redeem page says it too, in the page's language.
type Signup ¶
type Signup interface {
// Join subscribes email to lists with the evidence; double keeps them
// pending until the contact confirms. It returns the contact.
Join(ctx context.Context, tx pgx.Tx, ws *store.Workspace, j Join) (uuid.UUID, bool, error)
}
Signup adds a contact to lists with consent (internal/audience).
type Starter ¶
type Starter struct {
Email, Key, Name, Description string
Subject, Preheader, MJML string
Variables []TemplateVariable
Sample map[string]any
}
Starter is a member email's starter, as the drafts begin (the demo publishes them as they are).
type SweepArgs ¶
type SweepArgs struct{}
SweepArgs applies events whose job never ran, ends access that has run out and purges raw events past retention.
func (SweepArgs) InsertOpts ¶
func (SweepArgs) InsertOpts() river.InsertOpts
InsertOpts runs on the maintenance queue.
type SweepWorker ¶
type SweepWorker struct {
river.WorkerDefaults[SweepArgs]
S *Service
}
SweepWorker runs SweepArgs.
type TeamCheckoutRequest ¶
type TeamCheckoutRequest struct {
Tier string // the tier's slug
Period string
// Seats is the number typed (the stepper's).
Seats string
Team string
Email string
Token string
TestToken string
// Lang is the page's: the form's errors are written in it.
Lang i18n.Lang
}
TeamCheckoutRequest is a team's checkout from the team page.
type TeamConfirm ¶
type TeamConfirm struct {
Title, Text, Remove, Keep string
}
TeamConfirm asks before removing someone.
type TeamFormError ¶
TeamFormError is what the team page's form got wrong: a sentence per field, in the page's language.
func (*TeamFormError) Error ¶
func (e *TeamFormError) Error() string
type TeamJoinView ¶
type TeamJoinView struct {
// State is ask, accepted, full, expired, ended or bad.
State string
Lang i18n.Lang
Heading string
Text string
Email string
Consent string
Button string
// Ignore says until when the invite works; Note follows an accepted
// seat's benefits.
Ignore string
Note string
// Included titles the tier's benefits.
Included string
Benefits []string
}
TeamJoinView is an invite's join page (PublicTeamJoin).
type TeamManageView ¶
type TeamManageView struct {
// State is manage, expired (a fresh link was emailed), ended or bad.
State string
Lang i18n.Lang
Heading string
// Sub is "Yearly · $600 a year · renews 3 Sep 2027 · managed by …";
// Line says why something can't be done (paused).
Sub string
Line string
Team string
Tier string
// Seats are paid for; People are in the team (the buyer and active
// seats), Invites wait; Used = People + Invites; Over is how many to
// remove when Stripe lowered the seats below them.
Seats int
People int
Invites int
Used int
Free int
Over int
// OverTitle and OverText explain Over.
OverTitle string
OverText string
Members []TeamMemberView
// PeopleTitle is "People · 9".
PeopleTitle string
// CanInvite: a free seat and payments running; InviteHint says how
// many; FullTitle and FullText when every seat is taken.
CanInvite bool
InviteHint string
FullTitle string
FullText string
// SeatsMin and SeatsMax bound Change seats; CanChange when the
// provider can change the quantity. SeatsNote explains the seats;
// SeatsError is the change refused (too few for the people).
SeatsMin int
SeatsMax int
SeatsValue int
CanChange bool
SeatsNote string
SeatsError *PageNotice
LinkNote string
Flash *PageNotice
Words map[string]string
}
TeamManageView is a team buyer's manage page (PublicTeamManage).
type TeamMemberView ¶
type TeamMemberView struct {
ID string
Email string
Name string
Status string // buyer, invited, active
Label string
// Line is "your seat" or "sent 13 Oct · works until 27 Oct".
Line string
You string
CanResend bool
RemoveLabel string
ResendLabel string
// Confirm is Remove's question, shown under the row it asks about.
Confirm *TeamConfirm
}
TeamMemberView is one person on the manage page.
type TeamRequest ¶
type TeamRequest struct {
Tier string
Period string
Seats int
Canceled bool
TestToken string
Token string
Lang i18n.Lang
// The form as sent, when it comes back with errors.
SeatsText string
Team string
Email string
Errors map[string]string
}
TeamRequest is a visit of a tier's team page, or its form sent back with errors (Errors, in the page's language, by field).
type TeamResult ¶
type TeamResult struct {
View TeamManageView
// Redirect is the provider's page to go to (billing).
Redirect string
}
TeamResult is what a manage-page action did: the page again, with a notice.
type TeamView ¶
type TeamView struct {
Lang i18n.Lang
TestMode bool
TierSlug string
TierName string
Heading string
Intro string
Toggle bool
Period string
Monthly string
Yearly string
// Saving is the yearly price's saving ("2 months free").
Saving string
SeatsMin int
SeatsMax int
// Seats is the stepper's number; SeatsText what was typed when it
// came back out of range.
Seats int
SeatsText string
SeatsHint string
// UnitText is "$60 per seat a year"; Times "× 3 seats", Total "$180"
// and Per "a year"; Renews the tax and renewal line. TotalHint
// replaces the total while the seats are out of range.
UnitCents int64
Currency string
UnitText string
Times string
Total string
Per string
Renews string
TotalHint string
// Money is how the page's script writes the total as the seats change:
// the currency's symbol, whether it has cents, and "× # seats" by
// plural category.
MoneySymbol string
MoneyWhole bool
TimesForms map[string]string
Team string
Email string
Errors map[string]string
ErrorsTitle string
Notice *PageNotice
Words map[string]string
}
TeamView is a tier's team page (PublicUpgradeTeam).
type TemplateDraft ¶
type TemplateDraft struct {
Key, Name, Description string
Category uuid.UUID
Subject, Preheader string
MJML string
Variables []TemplateVariable
TestData map[string]any
}
TemplateDraft is a member email's starter.
type TemplateState ¶
type TemplateState struct {
Key string
Name string
// LiveVersion is 0 when nothing was ever published.
LiveVersion int
// DraftVersion is the version publishing the draft would make, when
// the draft has unpublished changes.
DraftVersion int
Deleted bool
FromName string
FromEmail string
ReplyTo string
CategoryName string
CategoryKind string
}
TemplateState is a template's key and versions.
type TemplateVariable ¶
TemplateVariable is a member email's variable.
type TierCardView ¶
type TierCardView struct {
ID string
Name string
Highlight string
Amount string
Unit string
Sub string
Trial string
Benefits []string
Button string
Primary bool
Note string
Period string
// Team links to the tier's team page ("Buying for a team? From $60 a
// year per seat") when it has a group price.
Team string
TeamHref string
}
TierCardView is a tier's card.
type UnsubscribePaid ¶
UnsubscribePaid is the paid member's note on the unsubscribe page: unsubscribing doesn't cancel the subscription. CancelLabel is the button that emails the member a cancel link (the page's own link never expires, as the preference center's).
type UpgradeFAQ ¶
UpgradeFAQ is one question on the upgrade page.
type UpgradePage ¶
type UpgradePage struct {
Headline string `json:"headline" maxLength:"120"`
Intro string `json:"intro" maxLength:"600"`
// Order lists the tiers in the page's order; Off are public tiers left
// off the page. Hidden and archived tiers never show.
Order []string `json:"order" maxItems:"20"`
Off []string `json:"off" maxItems:"20"`
DefaultPeriod string `json:"defaultPeriod" enum:"month,year"`
// Highlight is the tier put forward, with its label ("Most popular").
Highlight string `json:"highlight" maxLength:"40"`
HighlightLabel string `json:"highlightLabel" maxLength:"30"`
// The free card: its list, its line ("the Weekly Digest, every
// Tuesday") and its text.
FreeList string `json:"freeList" maxLength:"40"`
FreeLine string `json:"freeLine" maxLength:"120"`
FreeText string `json:"freeText" maxLength:"300"`
FAQ []UpgradeFAQ `json:"faq" maxItems:"8"`
Welcome string `json:"welcome" maxLength:"400" doc:"The welcome page after checkout; {{ first_name }} and {{ next_issue }} are filled in."`
Buttons map[string]string `json:"buttons,omitempty" doc:"A tier's button when it has no trial (\"Become a founding member\"), by tier id."`
}
UpgradePage is the upgrade page as readers see it (Earn › Plans & offers › Edit page): the publisher's copy and the page's choices.
type UpgradeRequest ¶
type UpgradeRequest struct {
// Token is a personal upgrade link's token (?r=).
Token string
// Tier is a hidden tier's slug (/upgrade/{slug}).
Tier string
Period string
// Canceled is set when Checkout sent the reader back (?canceled=1).
Canceled bool
// TestToken is a team member's test checkout link (?test=): the page
// sells with the test key.
TestToken string
// Preview renders for the editor: As is anonymous, free, paid.
Preview bool
As string
Page *UpgradePage
Lang i18n.Lang
// Offer is an offer link's code (?offer=FALL26), X17.
Offer string
}
UpgradeRequest is a visit of the upgrade page.
type UpgradeView ¶
type UpgradeView struct {
// Lang is the language the page is written in.
Lang i18n.Lang
Headline string
Intro string
TestMode bool
// Known is the reader of a personal link.
Known *KnownReader
Notice *PageNotice
Period string
Toggle bool
Monthly string
Yearly string
Saving string
Free *FreeCardView
Cards []TierCardView
TaxNote string
Trust string
FAQ []UpgradeFAQ
FAQTitle string
// Paid replaces the cards for a reader with paid access.
Paid *PaidView
// Unavailable: no payment provider is connected, or nothing to buy.
TermsURL string
Support string
Action string
Token string
Words map[string]string
// Offer is an offer link's line, and OfferCode goes to checkout with
// the form (X17).
Offer *OfferBanner
OfferCode string
}
UpgradeView is the upgrade page.
Source Files
¶
- access.go
- api.go
- apply.go
- audience.go
- automation.go
- billinglinks.go
- connections.go
- consumers.go
- counts.go
- earn.go
- erasure.go
- eventexport.go
- eventlog.go
- format.go
- hooks.go
- imports.go
- jobs.go
- lang.go
- memberemails.go
- members.go
- pages.go
- pause.go
- provider.go
- public.go
- readerlinks.go
- selling.go
- teams.go
- teamspages.go
- tiers.go
- tokens.go
- upgradepage.go
- visibility.go
- webhook.go
- x17.go