tally

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 14 Imported by: ? modules, 0 packages

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

README

Tally

github.com/fletchhq/tally is a Go billing toolkit for Fletch apps and standalone Go services. It targets Go 1.27 with CGO_ENABLED=0 and ships as eight independent Go modules.

Modules

Module Dependencies Role
github.com/fletchhq/tally Go stdlib Money, polymorphic billables, catalog DSL, subscription state machine, entitlements, credits ledger, HTTP middleware, and tally/tallytest contract suites
github.com/fletchhq/tally/stripe stdlib + tally Pure-Go Stripe provider (2025-11-17.clover, flexible billing, meters, Checkout, Billing Portal, webhooks); zero stripe-go
github.com/fletchhq/tally/paddle stdlib + tally Pure-Go Paddle Billing v2 Merchant-of-Record provider (tax-inclusive invoices, hosted checkout, pause/unpause, webhooks)
github.com/fletchhq/tally/nock tally + nock SQLite and Postgres tally.Store and tally.CreditStore with atomic credit debits
github.com/fletchhq/tally/quiver tally + quiver Transactional webhook dispatch (EnqueueTx + Unique), worker registration, and scheduled reconcile / usage drain
github.com/fletchhq/tally/portal tally + Fletch UI Customer billing portal with PCI SAQ A guard, nonce CSP, @alpinejs/csp, and progressive <form> fallback
github.com/fletchhq/tally/sight tally + sight Local-only admin billing dashboard, resources, and capability-gated RBAC actions (PluginID() == "tally")
github.com/fletchhq/tally/examples/saas all modules Runnable SaaS app plus swap_test.go proving a Stripe to Paddle config swap with portal and Sight unchanged

Quick start

Wire a catalog, billable kinds, a store, and a provider into tally.New, then attach quiver, portal, sight, and HTTP middleware:

catalog := tally.NewCatalog(
	tally.Plan("pro", "Pro",
		tally.Description("Team workspaces and metered usage."),
		tally.Popular(),
		tally.TrialDays(14),
		tally.Features("sso", "audit_log"),
		tally.Limit("seats", 25),
		tally.Monthly(tally.USD(2900), tally.PerSeat(), tally.MinSeats(1), tally.MaxSeats(25), tally.Version(1)),
		tally.Yearly(tally.USD(29000), tally.PerSeat(), tally.MinSeats(1), tally.MaxSeats(25), tally.Version(1)),
	),
)

store := tallynock.NewStore(db)
client := stripe.New(os.Getenv("STRIPE_SECRET_KEY"))
provider := stripe.NewProvider(client, os.Getenv("STRIPE_WEBHOOK_SECRET"))

svc := tally.New(provider, store,
	tally.WithCatalog(catalog),
	tally.WithKinds(
		tally.Kind("org", resolveOrg,
			tally.Authorize(canManageOrgBilling),
			tally.Eligible(orgEligibleForBilling),
		),
	),
	tally.WithDispatcher(tallyquiver.Dispatcher(queue)),
	tally.WithPastDuePolicy(tally.PastDueAllowFor(7*24*time.Hour)),
)

tallyquiver.Register(queue, svc)

Protect HTTP routes with plain func(http.Handler) http.Handler middleware:

mux.Handle("/app/", tally.RequireSubscription(svc, refFromReq, onDeny)(appHandler))
mux.Handle("/app/audit", tally.RequireFeature(svc, refFromReq, "audit_log", onDeny)(auditHandler))
mux.Handle("/webhooks/billing", svc.WebhookHandler())

Core guarantees

  • Integer minor units only. tally.Money stores Amount int64 and Currency string (USD(2900) is $29.00). No floating-point math exists anywhere in the toolkit.
  • Frozen core API. github.com/fletchhq/tally stays stdlib-only and is guarded against accidental breaking changes by testdata/api_freeze.txt and TestAPIFreeze.
  • PCI SAQ A by construction. tally/portal renders zero inline card, expiry, or CVV inputs and loads zero Stripe.js or Paddle.js scripts. Card entry always happens on the provider's hosted page.
  • Provider swap without UI rewrites. Switching between Stripe and Paddle is a provider configuration change. examples/saas/swap_test.go verifies that the portal and Sight admin plugin run unchanged across both providers.
  • Local-only admin reads. The Sight dashboard and resource tables read from the local Nock projection and make zero provider API calls on page load.

Testing

github.com/fletchhq/tally/tallytest is stdlib-only and provides FakeProvider, Clock, MemoryStore, SignedRequest, RunProviderContract, and RunStoreContract. Use FakeProvider and MemoryStore for fast unit tests, and run the contract suites against custom providers or stores.

Documentation

Development

for m in . stripe paddle nock quiver portal sight examples/saas; do
  (cd "$m" && GOWORK=off CGO_ENABLED=0 go test -race ./...)
done
scripts/lint.sh   # golangci-lint v2.15.0

Set FLETCH_TEST_POSTGRES_URL (an admin URL) to run the nock store contract on Postgres as well as SQLite.

Docs & agent skills

When github.com/fletchhq/tally is in a Fletch app's go.mod, fletch ax sync and fletch docs automatically discover and sync its docs/ and skills/.

License

MIT or Apache-2.0, at your option. See LICENSE-MIT and LICENSE-APACHE.

Documentation

Overview

Package tally is Fletch's unified billing toolkit: Cashier (subscriptions, invoices, meters, and entitlements), Spark (self-serve customer billing portal), and the Sight plugin (operator billing dashboard: KPIs, customers, subscriptions, audited actions). The root module is the home of those layers and, like every Fletch leaf, is pure Go and stdlib-only. Today it holds no exported API; the provider clients live in submodules and the higher layers land in later phases.

The stripe submodule, github.com/fletchhq/tally/stripe, is the Stripe client: Checkout, the Billing Portal, and signed webhooks.

Index

Constants

View Source
const (
	MetaBillable = "tally_billable"
	MetaPlan     = "tally_plan"
	MetaName     = "tally_name"
)

Metadata keys tally sets on provider subscriptions, so a subscription can be tied to its billable even before the customer is known locally.

View Source
const (
	EventTrialWillEnd          = "customer.subscription.trial_will_end"
	EventInvoicePaymentFailed  = "invoice.payment_failed"
	EventInvoiceActionRequired = "invoice.payment_action_required"
)

Well-known event types the pipeline turns into domain events. Providers map theirs to these in DecodedEvent.Type when they differ.

View Source
const DefaultSubscriptionName = "default"

DefaultSubscriptionName is the name of a billable's main subscription.

View Source
const MaxWebhookBody = 1 << 20

MaxWebhookBody caps the webhook body WebhookHandler reads.

View Source
const Unlimited int64 = math.MaxInt64

Unlimited is the Limit of exempt billables, and a value plans can set.

Variables

View Source
var (
	// ErrInsufficientCredits means a debit is larger than the available
	// credit balance. Nothing is recorded.
	ErrInsufficientCredits = errors.New("tally: insufficient credits")
	// ErrCreditAmount means a grant or debit amount is not positive.
	ErrCreditAmount = errors.New("tally: credit amount must be positive")
)
View Source
var (
	// ErrNotFound means the record does not exist.
	ErrNotFound = errors.New("tally: not found")
	// ErrUnsupported means the provider lacks the capability.
	ErrUnsupported = errors.New("tally: not supported by the provider")
	// ErrNoSubscription means the billable has no live subscription.
	ErrNoSubscription = errors.New("tally: no subscription")
	// ErrUnknownPlan means the plan or price is not in the catalog.
	ErrUnknownPlan = errors.New("tally: unknown plan")
	// ErrPriceNotSynced means a catalog price has no provider price yet;
	// run SyncCatalog.
	ErrPriceNotSynced = errors.New("tally: price not synced to the provider")
	// ErrUnknownKind means the billable type was not registered.
	ErrUnknownKind = errors.New("tally: unknown billable kind")
	// ErrForbidden means the caller may not manage the billable.
	ErrForbidden = errors.New("tally: forbidden")
	// ErrIneligible wraps an EligibilityFunc refusal.
	ErrIneligible = errors.New("tally: not eligible for plan")
	// ErrQuantity means a quantity is outside the plan's seat bounds.
	ErrQuantity = errors.New("tally: quantity outside plan bounds")
	// ErrNotOnGracePeriod means only a subscription on grace can resume.
	ErrNotOnGracePeriod = errors.New("tally: subscription is not on its grace period")
	// ErrTrialUsed means the billable already had a trial.
	ErrTrialUsed = errors.New("tally: trial already used")
	// ErrRefundTooLarge means the refund exceeds what was paid or the
	// configured limit.
	ErrRefundTooLarge = errors.New("tally: refund exceeds the allowed amount")
	// ErrBadSignature means a webhook failed verification.
	ErrBadSignature = errors.New("tally: webhook signature invalid")
	// ErrCardDeclined means the provider declined the payment.
	ErrCardDeclined = errors.New("tally: payment declined")
)

Errors returned by the Service, stores, and providers.

View Source
var (
	PastDueAllow = PastDuePolicy{/* contains filtered or unexported fields */}
	PastDueBlock = PastDuePolicy{}
)

The past-due policies. PastDueAllow is the default: the provider's retries decide when the subscription ends.

View Source
var ErrAlreadySubscribed = errors.New("tally: already subscribed")

ErrAlreadySubscribed means the billable already has a live subscription with that name.

Functions

func AvailableCredits

func AvailableCredits(entries []CreditEntry, asOf time.Time) int64

AvailableCredits replays a billable's ledger, oldest entry first, and returns the balance available at asOf. Each debit draws on the grants still unexpired at its time, the soonest to expire first and grants that never expire last; what is left of a grant stops counting when it expires. Entries created after asOf are ignored. Stores share it so they agree on expiry.

func PerSeat

func PerSeat() interface {
	PlanOption
	PriceOption
}

PerSeat bills a licensed price per seat. On a plan it applies to all of the plan's licensed prices.

func RequireFeature

func RequireFeature(svc *Service, refFromReq RefFunc, feature string, onDeny http.Handler) func(http.Handler) http.Handler

RequireFeature lets a request through when a plan its billable holds grants feature.

func RequirePlan

func RequirePlan(svc *Service, refFromReq RefFunc, planKey string, onDeny http.Handler) func(http.Handler) http.Handler

RequirePlan lets a request through when its billable holds planKey.

func RequireSubscription

func RequireSubscription(svc *Service, refFromReq RefFunc, onDeny http.Handler) func(http.Handler) http.Handler

RequireSubscription lets a request through when its billable is subscribed (see Service.Subscribed). Otherwise onDeny serves it; nil answers 402 Payment Required.

func Version

func Version(v int) interface {
	PlanOption
	PriceOption
}

Version sets the version of a price, or on a plan the default version of its prices. Raising it mints new lookup keys; list the old prices with their old version to keep them for grandfathered subscribers:

Plan("seller", "Seller", Version(2),
	Monthly(USD(5900)),
	Monthly(USD(4900), Version(1)))

Types

type ActionRequired

type ActionRequired struct {
	URL            string
	ClientSecret   string
	SubscriptionID string
}

ActionRequired is returned, as an error, when a payment needs customer authentication (SCA/3-D Secure). Send the customer to URL; ClientSecret is for apps that confirm with the provider's own script.

func (*ActionRequired) Error

func (a *ActionRequired) Error() string

type ActionRequiredEvent

type ActionRequiredEvent struct {
	InvoiceEvent
	URL string
}

ActionRequiredEvent is sent when a payment waits for customer authentication (SCA). URL is where the customer confirms it.

func (ActionRequiredEvent) EventName

func (ActionRequiredEvent) EventName() string

EventName implements DomainEvent.

type Address

type Address struct {
	Line1      string
	Line2      string
	City       string
	State      string
	PostalCode string
	// Country is an ISO 3166-1 alpha-2 code.
	Country string
}

Address is a postal address for tax.

type Authorizer

type Authorizer func(ctx context.Context, ref BillableRef) error

Authorizer decides whether the caller in ctx (the signed-in user, put there by the app's auth) may manage ref's billing. A nil error allows.

type Banner struct {
	Tone        BannerTone
	Title       string
	Message     string
	ActionLabel string
	ActionURL   string
	EndsAt      time.Time
}

Banner is the one billing notice to show a billable. ActionURL is a provider page when there is one (an invoice to pay or confirm); otherwise it is empty and the app links its own billing page.

type BannerTone

type BannerTone string

BannerTone is the kind of billing banner to show.

const (
	BannerActionRequired BannerTone = "action_required"
	BannerPastDue        BannerTone = "past_due"
	BannerGracePeriod    BannerTone = "grace_period"
	BannerTrialing       BannerTone = "trialing"
)

The banner tones, in priority order.

type Billable

type Billable interface {
	BillableRef() BillableRef
	BillingEmail() string
	BillingName() string
}

Billable is an entity that pays: a user, a team, an organization.

type BillableRef

type BillableRef struct {
	Type string
	ID   string
}

BillableRef names the paying entity. (Type, ID) is its storage key: {"user", "u_1"}, {"team", "t_9"}, {"bakery", "b_3"}.

func ParseBillableRef

func ParseBillableRef(s string) (BillableRef, error)

ParseBillableRef reads "type:id".

func Ref

func Ref(typ, id string) BillableRef

Ref returns a BillableRef.

func (BillableRef) IsZero

func (r BillableRef) IsZero() bool

IsZero reports whether r is empty.

func (BillableRef) String

func (r BillableRef) String() string

String renders the ref as "type:id".

type BillingAddresser

type BillingAddresser interface {
	BillingAddress() Address
}

BillingAddresser is an optional Billable capability for tax.

type BillingLocaler

type BillingLocaler interface {
	BillingLocale() string
	BillingTimeZone() *time.Location
}

BillingLocaler is an optional Billable capability. Its time zone sets where a trial ends: at the end of the last trial day, local time.

type CallOption

type CallOption func(*callConfig)

CallOption adjusts one Service operation.

func Billed

func Billed(i Interval) CallOption

Billed picks the billing interval; the default is monthly.

func IdempotencyKey

func IdempotencyKey(k string) CallOption

IdempotencyKey makes a retried call safe at the provider, and dedupes usage reports.

func Named

func Named(name string) CallOption

Named picks the subscription by name; the default is "default".

func NoProrate

func NoProrate() CallOption

NoProrate changes the subscription without proration.

func ProrateNow

func ProrateNow() CallOption

ProrateNow invoices the proration at once.

func ResetBillingCycle

func ResetBillingCycle() CallOption

ResetBillingCycle starts a new billing period with a swap.

func Seats

func Seats(n int64) CallOption

Seats sets the quantity.

func SkipTrial

func SkipTrial() CallOption

SkipTrial starts the subscription without the plan's trial.

func TrialUntil

func TrialUntil(t time.Time) CallOption

TrialUntil sets the trial end in place of the plan's trial length.

func WithDiscount

func WithDiscount(d Discount) CallOption

WithDiscount applies a coupon or promotion code.

func WithMetadata

func WithMetadata(m map[string]string) CallOption

WithMetadata adds provider metadata.

func WithPaymentMethod

func WithPaymentMethod(token string) CallOption

WithPaymentMethod charges a stored provider payment method token.

type Canceled

type Canceled struct {
	SubscriptionEvent
	AtPeriodEnd bool
	EndsAt      time.Time
}

Canceled is sent when a subscription is canceled, at period end or now.

func (Canceled) EventName

func (Canceled) EventName() string

EventName implements DomainEvent.

type Catalog

type Catalog struct {
	// contains filtered or unexported fields
}

Catalog is the set of plans, defined in code. Provider price IDs are not part of it: SyncCatalog maps lookup keys to them in the Store.

func BuildCatalog

func BuildCatalog(plans ...*PlanDef) (*Catalog, error)

BuildCatalog builds a catalog and reports an invalid definition.

func NewCatalog

func NewCatalog(plans ...*PlanDef) *Catalog

NewCatalog builds a catalog. It panics on an invalid definition, since a catalog is a package-level value fixed at compile time; use BuildCatalog for one built at run time.

func (*Catalog) Plan

func (c *Catalog) Plan(key string) (*PlanDef, bool)

Plan returns the plan called key.

func (*Catalog) Plans

func (c *Catalog) Plans() []*PlanDef

Plans returns every plan and add-on, in declaration order.

func (*Catalog) Price

func (c *Catalog) Price(lookupKey string) (*PriceDef, bool)

Price returns the price with a lookup key, legacy versions included.

func (*Catalog) Prices

func (c *Catalog) Prices() []*PriceDef

Prices returns every price, legacy versions included, ordered by plan declaration and then by declaration within the plan.

type CatalogSyncer

type CatalogSyncer interface {
	SyncCatalog(ctx context.Context, c *Catalog, opts SyncOptions) (SyncPlan, error)
}

CatalogSyncer creates and archives provider products and prices so the provider matches the catalog.

type CheckoutItem

type CheckoutItem struct {
	PriceID  string
	Quantity int64
	// Name and Amount describe an ad-hoc price when PriceID is empty.
	Name   string
	Amount Money
	// Interval makes an ad-hoc price recurring.
	Interval     Interval
	CustomAmount *CustomAmount
}

CheckoutItem is one line of a provider checkout: a provider price, or an ad-hoc price.

type CheckoutMode

type CheckoutMode string

CheckoutMode is what a checkout collects.

const (
	CheckoutSubscription CheckoutMode = "subscription"
	CheckoutPayment      CheckoutMode = "payment"
	CheckoutSetup        CheckoutMode = "setup"
)

The checkout modes.

type CheckoutRequest

type CheckoutRequest struct {
	Plan     string
	Interval Interval
	Quantity int64
	// Name is the subscription's name; empty means "default".
	Name                string
	Mode                CheckoutMode
	Items               []CheckoutItem
	SuccessURL          string
	CancelURL           string
	SkipTrial           bool
	AllowPromotionCodes bool
	Discounts           []Discount
	AutomaticTax        bool
	TaxIDCollection     bool
	Locale              string
	Metadata            map[string]string
	IdempotencyKey      string
}

CheckoutRequest starts a hosted checkout. Set Plan for a subscription; set Mode CheckoutPayment and Items for a one-off payment, such as pay what you want with CheckoutItem.CustomAmount.

type CheckoutResult

type CheckoutResult struct {
	ID                string
	Status            string
	PaymentStatus     string
	Customer          string
	SubscriptionID    string
	ClientReferenceID string
	Metadata          map[string]string
}

CheckoutResult is a provider checkout session's outcome.

type Comped

type Comped struct {
	SubscriptionEvent
	Until time.Time
}

Comped is sent when an operator grants a comp.

func (Comped) EventName

func (Comped) EventName() string

EventName implements DomainEvent.

type CreateSubscription

type CreateSubscription struct {
	Customer string
	Prices   []SubscriptionPrice
	TrialEnd time.Time
	// PaymentMethod is a provider payment method token; empty uses the
	// customer's default.
	PaymentMethod  string
	Discounts      []Discount
	AutomaticTax   bool
	Metadata       map[string]string
	IdempotencyKey string
}

CreateSubscription creates a subscription directly, with a stored payment method, without a checkout page.

type CreditDebitParams

type CreditDebitParams struct {
	Amount         int64
	Reason         string
	Ref            string
	IdempotencyKey string
}

CreditDebitParams spends a billable's credits.

type CreditEntry

type CreditEntry struct {
	ID       string
	Billable BillableRef
	Delta    int64
	// BalanceAfter is the available balance right after the entry, at
	// CreatedAt.
	BalanceAfter int64
	Reason       string
	// Ref ties the entry to something in the app, such as an order or a
	// request ID.
	Ref string
	// IdempotencyKey, when set, is unique across the ledger: recording it
	// again returns the first entry.
	IdempotencyKey string
	// ExpiresAt ends a grant: from then on what is left of it is not
	// available. Debits never expire.
	ExpiresAt *time.Time
	CreatedAt time.Time
}

CreditEntry is one line of a billable's prepaid credit ledger: a grant (positive Delta) or a debit (negative Delta). Entries are never changed or deleted; an expired grant simply stops counting.

type CreditEvent

type CreditEvent struct {
	Entry CreditEntry
	At    time.Time
}

CreditEvent is the common part of credit events.

func (CreditEvent) BillableRef

func (e CreditEvent) BillableRef() BillableRef

BillableRef implements DomainEvent.

type CreditGrantParams

type CreditGrantParams struct {
	Amount         int64
	Reason         string
	Ref            string
	IdempotencyKey string
	ExpiresAt      *time.Time
}

CreditGrantParams adds credits to a billable.

type CreditStore

type CreditStore interface {
	// RecordCreditGrant appends a grant and fills in ID and BalanceAfter.
	// When e.IdempotencyKey is already recorded it sets *e to the stored
	// entry and reports false.
	RecordCreditGrant(ctx context.Context, e *CreditEntry) (bool, error)
	// RecordCreditDebit appends a debit (e.Delta < 0) when the balance
	// available at e.CreatedAt covers it, and ErrInsufficientCredits
	// otherwise. A repeated IdempotencyKey behaves as in
	// RecordCreditGrant, whatever the balance is now.
	RecordCreditDebit(ctx context.Context, e *CreditEntry) (bool, error)
	// CreditBalance is the balance available at asOf.
	CreditBalance(ctx context.Context, ref BillableRef, asOf time.Time) (int64, error)
	// ListCreditEntries returns the billable's entries, newest first.
	// Page.After is the ID of the last entry of the previous page; Limit
	// 0 means 50.
	ListCreditEntries(ctx context.Context, ref BillableRef, p Page) ([]CreditEntry, error)
}

CreditStore is the optional Store capability that keeps the prepaid credit ledger. Recording methods lock the billable's ledger (or join the InTx transaction holding it), so concurrent debits can never overdraw. They raise an entry's CreatedAt to the billable's newest entry's when it is earlier, so ledger order is time order.

type CreditsDebited

type CreditsDebited struct{ CreditEvent }

CreditsDebited is sent when credits are spent.

func (CreditsDebited) EventName

func (CreditsDebited) EventName() string

EventName implements DomainEvent.

type CreditsGranted

type CreditsGranted struct{ CreditEvent }

CreditsGranted is sent when credits are granted.

func (CreditsGranted) EventName

func (CreditsGranted) EventName() string

EventName implements DomainEvent.

type CreditsLowBalance

type CreditsLowBalance struct {
	CreditEvent
	Threshold int64
	Balance   int64
}

CreditsLowBalance is sent with the debit that takes the balance from at least Threshold to below it (see WithLowBalanceThreshold).

func (CreditsLowBalance) EventName

func (CreditsLowBalance) EventName() string

EventName implements DomainEvent.

type CustomAmount

type CustomAmount struct {
	Min       Money
	Max       Money
	Suggested Money
}

CustomAmount lets the customer choose the amount (pay what you want).

type Customer

type Customer struct {
	ID         string
	Billable   BillableRef
	Provider   ProviderName
	ProviderID string
	Email      string
	Name       string
	TaxExempt  bool
	Metadata   map[string]string
	CreatedAt  time.Time
	UpdatedAt  time.Time
}

Customer links a billable to a provider customer.

type CustomerQuery

type CustomerQuery struct {
	Search   string
	Provider ProviderName
	Limit    int
	Offset   int
}

CustomerQuery filters ListCustomers. Search matches email, name, and billable ID, case-insensitively. Limit 0 means 50.

type DecodedEvent

type DecodedEvent struct {
	ID         string
	Type       string
	ObjectType ObjectType
	ObjectID   string
	Created    time.Time
}

DecodedEvent is a verified webhook event. The pipeline re-fetches the object from the provider before applying it, so the payload itself is kept only for the log.

type Discount

type Discount struct {
	Coupon        string
	PromotionCode string
}

Discount applies a coupon or a promotion code.

func CouponCode

func CouponCode(id string) Discount

CouponCode returns a Discount for a provider coupon ID.

func PromotionCode

func PromotionCode(id string) Discount

PromotionCode returns a Discount for a provider promotion code ID.

type Dispatcher

type Dispatcher func(ctx context.Context, tx any, ref EventRef) error

Dispatcher hands a stored webhook event to background processing, inside the transaction that stored it, so the job exists exactly when the event does. tally/quiver provides one. With no Dispatcher events are processed inline in the webhook request.

type DomainEvent

type DomainEvent interface {
	// EventName is a stable name, such as "subscription.started".
	EventName() string
	// BillableRef is the billable the event is about.
	BillableRef() BillableRef
}

DomainEvent is a billing change an app reacts to: mail, entitlement caches, analytics. Listeners get them inside the transaction that records the change.

func Apply

func Apply(prev *Subscription, next Subscription) []DomainEvent

Apply returns the domain events of moving a subscription from prev (nil when new) to next. It compares states only, so applying the same state twice yields nothing: duplicate and out-of-order provider events are harmless once next is re-fetched from the provider.

func ApplyInvoice

func ApplyInvoice(prev *Invoice, next Invoice, at time.Time) []DomainEvent

ApplyInvoice returns the domain events of moving an invoice from prev (nil when new) to next.

type EligibilityFunc

type EligibilityFunc func(ctx context.Context, b Billable, plan *PlanDef) error

EligibilityFunc decides whether b may move to plan, such as "you have 45 listings; Seller allows 40". A non-nil error refuses, and is returned to the caller wrapped in ErrIneligible.

type Ended

type Ended struct{ SubscriptionEvent }

Ended is sent when a subscription stops granting its plan for good.

func (Ended) EventName

func (Ended) EventName() string

EventName implements DomainEvent.

type EventRef

type EventRef struct {
	// ID is the local webhook event ID to pass to ProcessWebhookEvent.
	ID       string
	Provider ProviderName
	EventID  string
	Type     string
}

EventRef identifies a stored webhook event for a Dispatcher.

type GenericTrial

type GenericTrial struct {
	Billable    BillableRef
	Plan        string
	TrialEndsAt time.Time
	CreatedAt   time.Time
}

GenericTrial is a cardless trial, on the billable rather than on a subscription.

func (GenericTrial) Active

func (g GenericTrial) Active(now time.Time) bool

Active reports whether the trial runs at now.

type Interval

type Interval string

Interval is how often a recurring price bills.

const (
	IntervalMonth Interval = "month"
	IntervalYear  Interval = "year"
)

The billing intervals.

type Invoice

type Invoice struct {
	ID                     string
	CustomerID             string
	Billable               BillableRef
	SubscriptionID         string
	Provider               ProviderName
	ProviderID             string
	ProviderCustomerID     string
	ProviderSubscriptionID string
	Number                 string
	Status                 InvoiceStatus
	Total                  Money
	AmountPaid             Money
	AmountDue              Money
	AmountRefunded         Money
	HostedURL              string
	PDFURL                 string
	PeriodStart            time.Time
	PeriodEnd              time.Time
	PaidAt                 time.Time
	// ActionRequired is set while the payment waits for customer
	// authentication.
	ActionRequired bool
	CreatedAt      time.Time
}

Invoice is the local mirror of a provider invoice.

type InvoiceEvent

type InvoiceEvent struct {
	Invoice Invoice
	At      time.Time
}

InvoiceEvent is the common part of invoice events.

func (InvoiceEvent) BillableRef

func (e InvoiceEvent) BillableRef() BillableRef

BillableRef implements DomainEvent.

type InvoiceLine

type InvoiceLine struct {
	Description    string
	Amount         Money
	Quantity       int64
	PriceLookupKey string
	Proration      bool
}

InvoiceLine is one line of an invoice or a preview.

type InvoicePaid

type InvoicePaid struct{ InvoiceEvent }

InvoicePaid is sent when an invoice is paid.

func (InvoicePaid) EventName

func (InvoicePaid) EventName() string

EventName implements DomainEvent.

type InvoicePaymentFailed

type InvoicePaymentFailed struct{ InvoiceEvent }

InvoicePaymentFailed is sent when an invoice payment attempt fails.

func (InvoicePaymentFailed) EventName

func (InvoicePaymentFailed) EventName() string

EventName implements DomainEvent.

type InvoicePreview

type InvoicePreview struct {
	Subtotal  Money
	Total     Money
	AmountDue Money
	Lines     []InvoiceLine
	PeriodEnd time.Time
}

InvoicePreview is a computed invoice, such as the proration of a swap.

type InvoiceQuery

type InvoiceQuery struct {
	CustomerID     string
	Billable       BillableRef
	SubscriptionID string
	Status         InvoiceStatus
	Limit          int
	Offset         int
}

InvoiceQuery filters ListInvoices. Results are newest first.

type InvoiceStatus

type InvoiceStatus string

InvoiceStatus is an invoice's provider status.

const (
	InvoiceDraft         InvoiceStatus = "draft"
	InvoiceOpen          InvoiceStatus = "open"
	InvoicePaidStatus    InvoiceStatus = "paid"
	InvoiceVoid          InvoiceStatus = "void"
	InvoiceUncollectible InvoiceStatus = "uncollectible"
)

The invoice statuses.

type Invoicer

type Invoicer interface {
	Invoices(ctx context.Context, customer string, p Page) ([]Invoice, error)
	Invoice(ctx context.Context, id string) (Invoice, error)
	UpcomingInvoice(ctx context.Context, customer, subscriptionID string) (InvoicePreview, error)
}

Invoicer lists and fetches invoices.

type KindDef

type KindDef struct {
	Name     string
	Resolver Resolver
	// contains filtered or unexported fields
}

KindDef registers one billable type with a Service.

func Kind

func Kind(name string, resolver Resolver, opts ...KindOption) KindDef

Kind declares a billable type, such as Kind("team", resolveTeam, Authorize(isTeamOwner)).

type KindOption

type KindOption func(*KindDef)

KindOption configures a KindDef.

func Authorize

func Authorize(fn Authorizer) KindOption

Authorize sets who may manage billables of the kind.

func Eligible

func Eligible(fn EligibilityFunc) KindOption

Eligible sets the plan eligibility check of the kind.

type Lens

type Lens string

Lens is a saved filter over subscriptions.

const (
	LensAll      Lens = ""
	LensTrialing Lens = "trialing"
	LensActive   Lens = "active"
	LensPastDue  Lens = "past_due"
	LensGrace    Lens = "grace"
	LensComped   Lens = "comped"
	LensEnded    Lens = "ended"
)

The subscription lenses.

type Listener

type Listener func(ctx context.Context, tx any, e DomainEvent) error

Listener receives domain events inside the store transaction tx. An error rolls the transaction back; a webhook event is then retried.

type MeterEvent

type MeterEvent struct {
	Customer string
	// EventName is the provider meter's event name.
	EventName string
	Quantity  int64
	// Identifier deduplicates the report at the provider.
	Identifier string
	Timestamp  time.Time
}

MeterEvent is one usage report.

type Meterer

type Meterer interface {
	ReportUsage(ctx context.Context, e MeterEvent) error
	UsageSummary(ctx context.Context, q UsageQuery) (UsageSummary, error)
}

Meterer reports metered usage.

type Metrics

type Metrics struct {
	MRR      Money
	ARR      Money
	Active   int
	Trialing int
	PastDue  int
	OnGrace  int
	Comped   int
	// Churned counts subscriptions that ended within the churn window.
	Churned int
	// PlanMix counts live subscriptions per plan, largest first.
	PlanMix []PlanCount
}

Metrics are the billing KPIs, computed locally. MRR counts active and past-due subscriptions' licensed items (yearly divided by 12); trials, comps, and metered usage are left out.

func (Metrics) ChurnRateBP

func (m Metrics) ChurnRateBP() int

ChurnRateBP is churn over the window in basis points: churned divided by churned plus those still paying.

type MetricsQuery

type MetricsQuery struct {
	Now time.Time
	// Currency is the currency of MRR; other currencies are left out.
	// Empty means USD.
	Currency string
	// ChurnWindow is how far back churn counts. Zero means 30 days.
	ChurnWindow time.Duration
	// CreatedBy, when set, leaves out subscriptions created after it, for
	// figures as of a past time.
	CreatedBy time.Time
}

MetricsQuery anchors Metrics.

type Money

type Money struct {
	Amount   int64
	Currency string
}

Money is an amount in a currency's minor unit (cents for USD) with an ISO 4217 code in upper case. There are no floats anywhere in tally.

func EUR

func EUR(cents int64) Money

EUR returns cents euros.

func GBP

func GBP(pence int64) Money

GBP returns pence pounds sterling.

func NewMoney

func NewMoney(amount int64, currency string) Money

NewMoney returns amount minor units of currency.

func USD

func USD(cents int64) Money

USD returns cents US dollars.

func (Money) Add

func (m Money) Add(o Money) (Money, error)

Add returns m + o. Both must share a currency, or one must be the zero Money.

func (Money) Format

func (m Money) Format() string

Format renders m for people: "$49.00", "€12.50", "¥500", "12.00 CHF". Negative amounts get a leading minus.

func (Money) IsZero

func (m Money) IsZero() bool

IsZero reports whether the amount is zero.

func (Money) Mul

func (m Money) Mul(n int64) Money

Mul returns m times n.

func (Money) String

func (m Money) String() string

String is Format.

type ObjectType

type ObjectType string

ObjectType is the kind of provider object a webhook event is about.

const (
	ObjectSubscription    ObjectType = "subscription"
	ObjectInvoice         ObjectType = "invoice"
	ObjectCheckoutSession ObjectType = "checkout_session"
	ObjectCustomer        ObjectType = "customer"
	ObjectOther           ObjectType = "other"
)

The object types the webhook pipeline acts on.

type Option

type Option func(*Service)

Option configures a Service.

func WithCatalog

func WithCatalog(c *Catalog) Option

WithCatalog sets the plan catalog.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock, for tests.

func WithDispatcher

func WithDispatcher(d Dispatcher) Option

WithDispatcher processes webhook events in the background.

func WithExemptCheck

func WithExemptCheck(fn func(ctx context.Context, ref BillableRef) bool) Option

WithExemptCheck marks billables (staff, demo accounts) that pass every entitlement check without a subscription.

func WithKinds

func WithKinds(kinds ...KindDef) Option

WithKinds registers billable kinds.

func WithListener

func WithListener(ls ...Listener) Option

WithListener adds domain event listeners.

func WithLowBalanceThreshold

func WithLowBalanceThreshold(n int64) Option

WithLowBalanceThreshold sends CreditsLowBalance when a debit takes a billable's credit balance below n. Zero, the default, never sends it.

func WithMaxRefundAmount

func WithMaxRefundAmount(m Money) Option

WithMaxRefundAmount caps a single refund. Larger refunds return ErrRefundTooLarge. The zero Money means no cap beyond the amount paid.

func WithPastDuePolicy

func WithPastDuePolicy(p PastDuePolicy) Option

WithPastDuePolicy sets whether past-due subscriptions stay valid. The default is PastDueAllow.

type Page

type Page struct {
	Limit int
	// After is the cursor: the last ID of the previous page.
	After string
}

Page asks for one page of a list.

type PastDuePolicy

type PastDuePolicy struct {
	// contains filtered or unexported fields
}

PastDuePolicy decides whether a past-due subscription stays valid.

func PastDueAllowFor

func PastDueAllowFor(d time.Duration) PastDuePolicy

PastDueAllowFor keeps a past-due subscription valid for d after it became past due.

func (PastDuePolicy) Grace

func (p PastDuePolicy) Grace() time.Duration

Grace returns the policy's grace period; zero means unbounded when the policy allows.

type Pauser

type Pauser interface {
	PauseSubscription(ctx context.Context, subscriptionID string, resumesAt time.Time) (Subscription, error)
	UnpauseSubscription(ctx context.Context, subscriptionID string) (Subscription, error)
}

Pauser pauses and resumes collection.

type PaymentFailed

type PaymentFailed struct{ SubscriptionEvent }

PaymentFailed is sent when a subscription becomes past due or unpaid.

func (PaymentFailed) EventName

func (PaymentFailed) EventName() string

EventName implements DomainEvent.

type PaymentMethod

type PaymentMethod struct {
	Type     string
	Brand    string
	Last4    string
	ExpMonth int
	ExpYear  int
}

PaymentMethod is a customer's default payment method, for display.

type PaymentMethods

type PaymentMethods interface {
	// DefaultPaymentMethod returns nil when the customer has none.
	DefaultPaymentMethod(ctx context.Context, customer string) (*PaymentMethod, error)
}

PaymentMethods reads payment methods.

type PlanCount

type PlanCount struct {
	Plan  string
	Count int
}

PlanCount is one slice of the plan mix.

type PlanDef

type PlanDef struct {
	Key         string
	Name        string
	Description string
	Addon       bool
	Prices      []*PriceDef
	TrialDays   int
	Features    []string
	Limits      map[string]int64
	MinSeats    int64
	MaxSeats    int64
	Popular     bool
	Hidden      bool
	// Version is the default version of the plan's prices.
	Version int
	// contains filtered or unexported fields
}

PlanDef is a plan or an add-on in the catalog.

func Addon

func Addon(key, name string, opts ...PlanOption) *PlanDef

Addon declares an add-on: a plan sold on top of another.

func Plan

func Plan(key, name string, opts ...PlanOption) *PlanDef

Plan declares a plan.

func (*PlanDef) HasFeature

func (d *PlanDef) HasFeature(feature string) bool

HasFeature reports whether the plan grants feature.

func (*PlanDef) LimitValue

func (d *PlanDef) LimitValue(key string) (int64, bool)

LimitValue returns the plan's limit for key.

func (*PlanDef) MeteredPrices

func (d *PlanDef) MeteredPrices() []*PriceDef

MeteredPrices returns the current metered prices.

func (*PlanDef) Price

func (d *PlanDef) Price(interval Interval) (*PriceDef, bool)

Price returns the current (newest, non-legacy) licensed price for an interval.

func (*PlanDef) SubscribePrices

func (d *PlanDef) SubscribePrices(interval Interval) []*PriceDef

SubscribePrices returns what a new subscription to the plan gets: the current licensed price for interval, if any, and every current metered price.

type PlanOption

type PlanOption interface {
	// contains filtered or unexported methods
}

PlanOption configures a plan.

func Description

func Description(s string) PlanOption

Description sets the plan's description.

func Features

func Features(names ...string) PlanOption

Features grants named features.

func Hidden

func Hidden() PlanOption

Hidden keeps the plan out of plan pickers; existing subscribers keep it.

func Limit

func Limit(key string, v int64) PlanOption

Limit sets a numeric entitlement, such as Limit("active_listings", 40).

func MaxSeats

func MaxSeats(n int64) PlanOption

MaxSeats sets the largest quantity.

func MinSeats

func MinSeats(n int64) PlanOption

MinSeats sets the smallest quantity.

func Popular() PlanOption

Popular marks the plan as the one to highlight.

func TrialDays

func TrialDays(n int) PlanOption

TrialDays sets the length of the plan's trial.

type PriceDef

type PriceDef struct {
	Plan     string
	Interval Interval
	// Amount is the price per period, per seat when PerSeat. Zero for
	// metered prices.
	Amount  Money
	PerSeat bool
	Metered bool
	// MeterKey names a metered price's usage, as passed to ReportUsage.
	MeterKey string
	// MeterEvent is the provider's meter event name; it defaults to MeterKey.
	MeterEvent string
	// UnitAmount is the price of one unit of metered usage.
	UnitAmount Money
	Version    int
	// Legacy is true when a newer version of the same price exists: the
	// price stays active for existing subscribers and is not offered.
	Legacy bool
}

PriceDef is one price of a plan in the catalog. Prices are immutable: a new amount is a new Version with a new lookup key, and subscribers on the old version keep it.

func Metered

func Metered(meterKey string, opts ...PriceOption) *PriceDef

Metered adds a monthly usage price for meterKey. Give it PerUnit.

func Monthly

func Monthly(m Money, opts ...PriceOption) *PriceDef

Monthly adds a monthly price.

func Yearly

func Yearly(m Money, opts ...PriceOption) *PriceDef

Yearly adds a yearly price.

func (*PriceDef) Currency

func (p *PriceDef) Currency() string

Currency is the price's currency.

func (*PriceDef) LookupKey

func (p *PriceDef) LookupKey() string

LookupKey is the price's stable key: "seller.monthly.v1" for a licensed price, "api.api_calls.v1" for a metered one. Providers store it on the price so the catalog in code stays the source of truth.

type PriceMapping

type PriceMapping struct {
	LookupKey         string
	Provider          ProviderName
	ProviderPriceID   string
	ProviderProductID string
	Active            bool
}

PriceMapping maps a catalog lookup key to a provider price.

type PriceOption

type PriceOption interface {
	// contains filtered or unexported methods
}

PriceOption configures a price.

func Meter

func Meter(name string) PriceOption

Meter sets a metered price's provider event name.

func PerUnit

func PerUnit(m Money) PriceOption

PerUnit sets a metered price's amount per unit of usage.

type Proration

type Proration string

Proration says how a change is prorated.

const (
	// ProrationDefault leaves it to the provider (Stripe: create prorations
	// on the next invoice).
	ProrationDefault Proration = ""
	ProrationNone    Proration = "none"
	// ProrationNow invoices the proration at once.
	ProrationNow Proration = "always_invoice"
)

The proration behaviors.

type Provider

type Provider interface {
	Name() ProviderName
	// EnsureCustomer returns the provider customer for b: existing when it
	// is set (updating email and name), otherwise a new one.
	EnsureCustomer(ctx context.Context, b Billable, existing string) (string, error)
	// Checkout starts a hosted checkout. A provider without hosted
	// checkout returns ErrUnsupported.
	Checkout(ctx context.Context, req ProviderCheckout) (Redirect, error)
	// Portal returns the provider's customer portal, or ErrUnsupported.
	Portal(ctx context.Context, customer, returnURL string) (Redirect, error)
	// Subscription fetches the current state of a subscription.
	Subscription(ctx context.Context, id string) (Subscription, error)
	// CheckoutSession fetches a checkout's outcome.
	CheckoutSession(ctx context.Context, id string) (CheckoutResult, error)
	Webhook() WebhookDecoder
}

Provider is the contract every billing provider driver implements. Optional capabilities are separate interfaces, detected with type assertions.

type ProviderCheckout

type ProviderCheckout struct {
	Mode                 CheckoutMode
	Customer             string
	Email                string
	Items                []CheckoutItem
	SuccessURL           string
	CancelURL            string
	TrialEnd             time.Time
	AllowPromotionCodes  bool
	Discounts            []Discount
	AutomaticTax         bool
	TaxIDCollection      bool
	Locale               string
	ClientReferenceID    string
	Metadata             map[string]string
	SubscriptionMetadata map[string]string
	IdempotencyKey       string
}

ProviderCheckout is what a provider needs to start a checkout.

type ProviderName

type ProviderName string

ProviderName names a billing provider.

const (
	ProviderStripe ProviderName = "stripe"
	ProviderPaddle ProviderName = "paddle"
	ProviderPolar  ProviderName = "polar"
	ProviderFake   ProviderName = "fake"
)

The known providers. ProviderFake is tallytest's in-memory provider.

type QuantityChanged

type QuantityChanged struct {
	SubscriptionEvent
	From, To int64
}

QuantityChanged is sent when the seat count changes.

func (QuantityChanged) EventName

func (QuantityChanged) EventName() string

EventName implements DomainEvent.

type ReconcileReport

type ReconcileReport struct {
	// Checked counts local subscriptions re-fetched from the provider.
	Checked int
	// Created counts provider subscriptions that were missing locally.
	Created int
	// Events counts the domain events the repairs fired.
	Events int
}

ReconcileReport is what Reconcile did.

type Redirect

type Redirect struct {
	ID  string
	URL string
}

Redirect is a provider-hosted page to send the customer to.

type RefFunc

type RefFunc func(r *http.Request) (ref BillableRef, ok bool)

RefFunc finds the billable of a request, such as the signed-in user's team. ok is false when there is none.

type Refund

type Refund struct {
	ID      string
	Invoice string
	Amount  Money
	Status  string
}

Refund is an issued refund.

type RefundRequest

type RefundRequest struct {
	Invoice        string
	Amount         Money
	Reason         string
	IdempotencyKey string
}

RefundRequest refunds part or all of a paid invoice.

type Refunded

type Refunded struct {
	InvoiceEvent
	Amount Money
	Reason string
	// Actor names who issued it.
	Actor string
}

Refunded is sent when a refund is issued.

func (Refunded) EventName

func (Refunded) EventName() string

EventName implements DomainEvent.

type Refunder

type Refunder interface {
	Refund(ctx context.Context, req RefundRequest) (Refund, error)
}

Refunder issues refunds.

type Resolver

type Resolver func(ctx context.Context, ref BillableRef) (Billable, error)

Resolver loads the Billable for a ref. It returns ErrNotFound when there is none.

type Resumed

type Resumed struct{ SubscriptionEvent }

Resumed is sent when a cancellation at period end is undone, or a paused subscription resumes.

func (Resumed) EventName

func (Resumed) EventName() string

EventName implements DomainEvent.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the billing API an app calls.

func New

func New(provider Provider, store Store, opts ...Option) *Service

New returns a Service over a provider and a store.

func (*Service) ActiveSubscriptions

func (s *Service) ActiveSubscriptions(ctx context.Context, ref BillableRef) ([]Subscription, error)

ActiveSubscriptions returns the billable's valid subscriptions.

func (*Service) Authorize

func (s *Service) Authorize(ctx context.Context, ref BillableRef) error

Authorize checks that the caller in ctx may manage ref's billing. A kind without an Authorizer refuses.

func (*Service) Banner

func (s *Service) Banner(ctx context.Context, ref BillableRef) (*Banner, error)

Banner returns the billing notice for the billable's default subscription, or nil when there is nothing to say.

func (*Service) Can

func (s *Service) Can(ctx context.Context, ref BillableRef, feature string) (bool, error)

Can reports whether any plan the billable holds grants feature. Exempt billables can do everything.

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)

Cancel cancels the subscription at the end of its period; it stays valid on its grace period until then.

func (*Service) CancelNow

func (s *Service) CancelNow(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)

CancelNow cancels the subscription at once.

func (*Service) Catalog

func (s *Service) Catalog() *Catalog

Catalog returns the catalog.

func (*Service) CheckEligible

func (s *Service) CheckEligible(ctx context.Context, b Billable, plan *PlanDef) error

CheckEligible runs the kind's eligibility check for plan.

func (*Service) Checkout

func (s *Service) Checkout(ctx context.Context, ref BillableRef, req CheckoutRequest) (Redirect, error)

Checkout starts a provider-hosted checkout for the billable and returns where to send the customer.

func (*Service) CreditBalance

func (s *Service) CreditBalance(ctx context.Context, ref BillableRef) (int64, error)

CreditBalance is the billable's available credit balance now.

func (*Service) CreditLedger

func (s *Service) CreditLedger(ctx context.Context, ref BillableRef, p Page) ([]CreditEntry, error)

CreditLedger returns a page of the billable's credit entries, newest first.

func (*Service) Current

func (s *Service) Current(ctx context.Context, ref BillableRef, name string) (Subscription, error)

Current returns the billable's newest subscription called name that has not ended, or ErrNoSubscription.

func (*Service) DebitCredits

func (s *Service) DebitCredits(ctx context.Context, ref BillableRef, p CreditDebitParams) (CreditEntry, error)

DebitCredits spends the billable's credits. It fails with ErrInsufficientCredits, recording nothing, when the available balance (unexpired grants less earlier debits) is smaller than Amount. A repeated IdempotencyKey returns the first entry and sends no event.

func (*Service) DecrementQuantity

func (s *Service) DecrementQuantity(ctx context.Context, ref BillableRef, n int64, opts ...CallOption) (Subscription, error)

DecrementQuantity removes n seats.

func (*Service) DefaultPaymentMethod

func (s *Service) DefaultPaymentMethod(ctx context.Context, ref BillableRef) (*PaymentMethod, error)

DefaultPaymentMethod returns the billable's default payment method, or nil.

func (*Service) DrainUsage

func (s *Service) DrainUsage(ctx context.Context, limit int) (int, error)

DrainUsage sends up to limit pending usage records to the provider and returns how many it sent. Failed records stay pending with their error.

func (*Service) ExtendTrial

func (s *Service) ExtendTrial(ctx context.Context, ref BillableRef, until time.Time, opts ...CallOption) (Subscription, error)

ExtendTrial moves the trial end of the billable's trialing subscription, or of its generic trial.

func (*Service) GrantComp

func (s *Service) GrantComp(ctx context.Context, ref BillableRef, plan string, until time.Time, actor string) (Subscription, error)

GrantComp gives the billable plan for free until a time: on its current subscription when it has one, otherwise as a local subscription with no provider side. actor is recorded in the metadata.

func (*Service) GrantCredits

func (s *Service) GrantCredits(ctx context.Context, ref BillableRef, p CreditGrantParams) (CreditEntry, error)

GrantCredits adds prepaid credits to the billable. A repeated IdempotencyKey returns the first grant and sends no event.

func (*Service) IncrementQuantity

func (s *Service) IncrementQuantity(ctx context.Context, ref BillableRef, n int64, opts ...CallOption) (Subscription, error)

IncrementQuantity adds n seats.

func (*Service) Invoices

func (s *Service) Invoices(ctx context.Context, ref BillableRef, limit, offset int) ([]Invoice, int, error)

Invoices returns the billable's invoices from the local mirror, newest first.

func (*Service) Kinds

func (s *Service) Kinds() []KindDef

Kinds returns the registered billable kinds in registration order.

func (*Service) Limit

func (s *Service) Limit(ctx context.Context, ref BillableRef, key string) (int64, error)

Limit returns the largest value of a limit across the plans the billable holds: 0 when none sets it, Unlimited for exempt billables.

func (*Service) Now

func (s *Service) Now() time.Time

Now returns the service clock's time.

func (*Service) OnPlan

func (s *Service) OnPlan(ctx context.Context, ref BillableRef, plan string) (bool, error)

OnPlan reports whether the billable holds plan, or is exempt.

func (*Service) PastDuePolicy

func (s *Service) PastDuePolicy() PastDuePolicy

PastDuePolicy returns the past-due policy.

func (*Service) Pause

func (s *Service) Pause(ctx context.Context, ref BillableRef, resumesAt time.Time, opts ...CallOption) (Subscription, error)

Pause stops collection on the billable's subscription until resumesAt, or until Unpause when resumesAt is zero.

func (*Service) Portal

func (s *Service) Portal(ctx context.Context, ref BillableRef, returnURL string) (Redirect, error)

Portal returns the provider's customer portal for the billable.

func (*Service) PreviewSwap

func (s *Service) PreviewSwap(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (InvoicePreview, error)

PreviewSwap returns the invoice a Swap with the same arguments would produce, such as its proration.

func (*Service) ProcessWebhookEvent

func (s *Service) ProcessWebhookEvent(ctx context.Context, id string) error

ProcessWebhookEvent applies a stored event: it re-fetches the event's object from the provider, so stale and out-of-order payloads are harmless, mirrors it, fires the domain events, and marks the event processed, all in one transaction. A failure increments Attempts and records LastError. An event already processed is a no-op.

func (*Service) Provider

func (s *Service) Provider() Provider

Provider returns the provider.

func (*Service) Reconcile

func (s *Service) Reconcile(ctx context.Context, since time.Time) (ReconcileReport, error)

Reconcile repairs drift between the local mirror and the provider: it re-fetches every local subscription that has not ended and, when the provider can list, mirrors provider subscriptions created since that are missing locally. Errors on single subscriptions are joined and the walk goes on.

func (*Service) Refund

func (s *Service) Refund(ctx context.Context, invoiceID string, amount Money, reason, actor string, opts ...CallOption) (Refund, error)

Refund refunds amount of a paid invoice (by local ID), up to what was paid and not yet refunded, and up to WithMaxRefundAmount. actor is recorded on the Refunded event.

func (*Service) ReplayWebhookEvent

func (s *Service) ReplayWebhookEvent(ctx context.Context, id, actor string) error

ReplayWebhookEvent marks a stored event unprocessed, records who replayed it, and processes it again: through the Dispatcher when there is one, otherwise at once.

func (*Service) ReportUsage

func (s *Service) ReportUsage(ctx context.Context, ref BillableRef, meter string, quantity int64, opts ...CallOption) error

ReportUsage records quantity units of meter in the usage outbox. DrainUsage sends them to the provider. A repeated IdempotencyKey is recorded once.

func (*Service) Resolve

func (s *Service) Resolve(ctx context.Context, ref BillableRef) (Billable, error)

Resolve loads the Billable for ref through its kind's Resolver.

func (*Service) Resume

func (s *Service) Resume(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)

Resume undoes a cancellation at period end while on the grace period.

func (*Service) StartGenericTrial

func (s *Service) StartGenericTrial(ctx context.Context, ref BillableRef, plan string, days int) (GenericTrial, error)

StartGenericTrial starts a cardless trial of plan for days. A billable gets one trial.

func (*Service) Store

func (s *Service) Store() Store

Store returns the store.

func (*Service) Subscribe

func (s *Service) Subscribe(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (Subscription, error)

Subscribe creates a subscription with a stored payment method. When the payment needs authentication it returns the incomplete subscription and an *ActionRequired error.

func (*Service) Subscribed

func (s *Service) Subscribed(ctx context.Context, ref BillableRef) (bool, error)

Subscribed reports whether the billable is exempt, has a valid subscription, or is on an active generic trial.

func (*Service) Subscriptions

func (s *Service) Subscriptions(ctx context.Context, ref BillableRef) ([]Subscription, error)

Subscriptions returns the billable's subscriptions, newest first.

func (*Service) Swap

func (s *Service) Swap(ctx context.Context, ref BillableRef, plan string, opts ...CallOption) (Subscription, error)

Swap moves the billable's subscription to another plan, keeping the interval unless Billed says otherwise.

func (*Service) SyncCatalog

func (s *Service) SyncCatalog(ctx context.Context, dryRun bool) (SyncPlan, error)

SyncCatalog makes the provider's products and prices match the catalog and stores the price mappings. With dryRun it only plans.

func (*Service) SyncCheckout

func (s *Service) SyncCheckout(ctx context.Context, sessionID string) (Subscription, error)

SyncCheckout mirrors the outcome of a finished checkout at once, for the success URL, so the app is correct before the webhook arrives. It returns the zero Subscription for a checkout that made none.

func (*Service) SyncSubscription

func (s *Service) SyncSubscription(ctx context.Context, id string) (Subscription, error)

SyncSubscription re-fetches one subscription, by local ID, from the provider and mirrors it: Reconcile for a single record.

func (*Service) Unpause

func (s *Service) Unpause(ctx context.Context, ref BillableRef, opts ...CallOption) (Subscription, error)

Unpause resumes collection on a paused subscription.

func (*Service) UpdateQuantity

func (s *Service) UpdateQuantity(ctx context.Context, ref BillableRef, qty int64, opts ...CallOption) (Subscription, error)

UpdateQuantity sets the seat count within the plan's bounds.

func (*Service) UsageSummary

func (s *Service) UsageSummary(ctx context.Context, ref BillableRef, meter string, start, end time.Time) (UsageSummary, error)

UsageSummary returns the provider's aggregated usage of meter in [start, end).

func (*Service) WebhookHandler

func (s *Service) WebhookHandler() http.Handler

WebhookHandler returns the provider webhook endpoint. It reads the raw body (413 over MaxWebhookBody), verifies it (400 on failure), stores the event once per (provider, event ID) and hands it to the Dispatcher in the same transaction, then answers 200. A duplicate delivery is a no-op 200. With no Dispatcher the event is processed before answering, and a failure is a 500 so the provider retries.

type Status

type Status string

Status is a subscription's provider status.

const (
	StatusIncomplete        Status = "incomplete"
	StatusIncompleteExpired Status = "incomplete_expired"
	StatusTrialing          Status = "trialing"
	StatusActive            Status = "active"
	StatusPastDue           Status = "past_due"
	StatusUnpaid            Status = "unpaid"
	StatusCanceled          Status = "canceled"
	StatusPaused            Status = "paused"
)

The subscription statuses.

func (Status) Ended

func (s Status) Ended() bool

Ended reports whether s is final.

type Store

type Store interface {
	// InTx runs fn in one transaction. tx is the store's transaction value
	// (a *nock.Transaction for tally/nock), handed to Dispatcher and
	// Listener so they can enqueue jobs atomically. A nested call joins the
	// outer transaction.
	InTx(ctx context.Context, fn func(ctx context.Context, tx any) error) error

	SaveCustomer(ctx context.Context, c *Customer) error
	Customer(ctx context.Context, id string) (Customer, error)
	CustomerByBillable(ctx context.Context, ref BillableRef, provider ProviderName) (Customer, error)
	CustomerByProviderID(ctx context.Context, provider ProviderName, providerID string) (Customer, error)
	ListCustomers(ctx context.Context, q CustomerQuery) ([]Customer, int, error)

	// SaveSubscription stores the subscription and replaces its items.
	SaveSubscription(ctx context.Context, s *Subscription) error
	Subscription(ctx context.Context, id string) (Subscription, error)
	// SubscriptionByProviderID locks the row for update inside a
	// transaction where the database supports it.
	SubscriptionByProviderID(ctx context.Context, provider ProviderName, providerID string) (Subscription, error)
	// SubscriptionsFor returns the billable's subscriptions, newest first.
	SubscriptionsFor(ctx context.Context, ref BillableRef) ([]Subscription, error)
	ListSubscriptions(ctx context.Context, q SubscriptionQuery) ([]Subscription, int, error)

	SaveInvoice(ctx context.Context, inv *Invoice) error
	Invoice(ctx context.Context, id string) (Invoice, error)
	InvoiceByProviderID(ctx context.Context, provider ProviderName, providerID string) (Invoice, error)
	ListInvoices(ctx context.Context, q InvoiceQuery) ([]Invoice, int, error)

	SavePriceMapping(ctx context.Context, m PriceMapping) error
	PriceMappings(ctx context.Context, provider ProviderName) ([]PriceMapping, error)

	// InsertWebhookEvent stores e unless (Provider, EventID) exists, and
	// reports whether it did. Either way e.ID is the stored event's ID.
	InsertWebhookEvent(ctx context.Context, e *WebhookEvent) (bool, error)
	WebhookEvent(ctx context.Context, id string) (WebhookEvent, error)
	// UpdateWebhookEvent stores ProcessedAt, Attempts, LastError and
	// ReplayedBy.
	UpdateWebhookEvent(ctx context.Context, e WebhookEvent) error
	ListWebhookEvents(ctx context.Context, q WebhookEventQuery) ([]WebhookEvent, int, error)

	// InsertUsage stores u unless its IdempotencyKey exists, and reports
	// whether it did.
	InsertUsage(ctx context.Context, u *UsageRecord) (bool, error)
	// PendingUsage returns unreported usage, oldest first.
	PendingUsage(ctx context.Context, limit int) ([]UsageRecord, error)
	// UpdateUsage stores ReportedAt, Attempts and LastError.
	UpdateUsage(ctx context.Context, u UsageRecord) error

	SaveGenericTrial(ctx context.Context, g GenericTrial) error
	GenericTrial(ctx context.Context, ref BillableRef) (GenericTrial, error)

	// Metrics computes the dashboard KPIs from local tables only.
	Metrics(ctx context.Context, q MetricsQuery) (Metrics, error)
}

Store persists the local billing mirror. Methods called with the ctx that InTx passes to its function run inside that transaction. Lookups return ErrNotFound when there is no record. Save methods insert or update and fill in an empty ID.

type Subscription

type Subscription struct {
	ID       string
	Billable BillableRef
	// CustomerID is the local Customer ID.
	CustomerID string
	// Name tells apart several subscriptions of one billable; usually
	// DefaultSubscriptionName.
	Name               string
	Plan               string
	Provider           ProviderName
	ProviderID         string
	ProviderCustomerID string
	Status             Status
	Quantity           int64
	Items              []SubscriptionItem
	TrialEndsAt        time.Time
	// EndsAt is when a subscription canceled at period end stops, or when
	// a canceled subscription stopped.
	EndsAt             time.Time
	CurrentPeriodStart time.Time
	CurrentPeriodEnd   time.Time
	CancelAtPeriodEnd  bool
	CanceledAt         time.Time
	// PastDueSince is when the subscription last became past due.
	PastDueSince time.Time
	// CompedUntil grants the plan for free until then.
	CompedUntil time.Time
	// BillingMode is the provider's billing mode, such as Stripe's
	// "flexible".
	BillingMode string
	Metadata    map[string]string
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Subscription is the local mirror of a provider subscription. It changes only from provider state (webhooks, SyncCheckout, Reconcile) and from local comps.

func (Subscription) Clone

func (s Subscription) Clone() Subscription

Clone returns a deep copy.

func (*Subscription) Comped

func (s *Subscription) Comped(now time.Time) bool

Comped reports whether a comp covers now.

func (*Subscription) Ended

func (s *Subscription) Ended(now time.Time) bool

Ended reports whether the subscription no longer grants anything at now.

func (*Subscription) Incomplete

func (s *Subscription) Incomplete() bool

Incomplete reports whether the first payment has not succeeded.

func (*Subscription) OnGracePeriod

func (s *Subscription) OnGracePeriod(now time.Time) bool

OnGracePeriod reports whether the subscription was canceled at period end and the period has not ended at now.

func (*Subscription) OnTrial

func (s *Subscription) OnTrial(now time.Time) bool

OnTrial reports whether the trial is running at now.

func (*Subscription) PastDue

func (s *Subscription) PastDue() bool

PastDue reports whether a renewal payment failed: past due, or unpaid after the provider stopped retrying.

func (*Subscription) Recurring

func (s *Subscription) Recurring(now time.Time) bool

Recurring reports whether the subscription will renew: active or on trial, and not canceled at period end.

func (*Subscription) Valid

func (s *Subscription) Valid(now time.Time, policy PastDuePolicy) bool

Valid reports whether the subscription grants its plan at now: comped, on trial, active, on grace, or past due within policy.

type SubscriptionEvent

type SubscriptionEvent struct {
	Subscription Subscription
	At           time.Time
}

SubscriptionEvent is the common part of subscription events.

func (SubscriptionEvent) BillableRef

func (e SubscriptionEvent) BillableRef() BillableRef

BillableRef implements DomainEvent.

type SubscriptionItem

type SubscriptionItem struct {
	ID              string
	ProviderItemID  string
	PriceLookupKey  string
	ProviderPriceID string
	Quantity        int64
	Metered         bool
	// UnitAmount and Interval are the price's, for local revenue metrics.
	UnitAmount Money
	Interval   Interval
}

SubscriptionItem is one price on a subscription.

type SubscriptionLister

type SubscriptionLister interface {
	// ListSubscriptionsSince calls fn for every subscription created at or
	// after since (all when since is zero), in no particular order.
	ListSubscriptionsSince(ctx context.Context, since time.Time, fn func(Subscription) error) error
}

SubscriptionLister walks the provider's subscriptions, for Reconcile.

type SubscriptionManager

type SubscriptionManager interface {
	// CreateSubscription returns the created subscription. When the first
	// payment needs authentication it returns the incomplete subscription
	// and an *ActionRequired error.
	CreateSubscription(ctx context.Context, req CreateSubscription) (Subscription, error)
	SwapSubscription(ctx context.Context, req SwapRequest) (Subscription, error)
	PreviewSwap(ctx context.Context, req SwapRequest) (InvoicePreview, error)
	UpdateQuantity(ctx context.Context, subscriptionID string, quantity int64, p Proration, idempotencyKey string) (Subscription, error)
	CancelSubscription(ctx context.Context, subscriptionID string, atPeriodEnd bool) (Subscription, error)
	ResumeSubscription(ctx context.Context, subscriptionID string) (Subscription, error)
	ExtendTrial(ctx context.Context, subscriptionID string, until time.Time) (Subscription, error)
}

SubscriptionManager changes subscriptions without a hosted page.

type SubscriptionPrice

type SubscriptionPrice struct {
	PriceID  string
	Quantity int64
	Metered  bool
}

SubscriptionPrice is one price a subscription should carry.

type SubscriptionQuery

type SubscriptionQuery struct {
	Status   []Status
	Lens     Lens
	Plan     string
	Billable BillableRef
	Search   string
	Now      time.Time
	Limit    int
	Offset   int
}

SubscriptionQuery filters ListSubscriptions. Now anchors the time-based lenses. Search matches the customer's email, name, and billable ID, and the plan. Results are newest first.

type SubscriptionStarted

type SubscriptionStarted struct{ SubscriptionEvent }

SubscriptionStarted is sent when a subscription first becomes trialing, active, or past due.

func (SubscriptionStarted) EventName

func (SubscriptionStarted) EventName() string

EventName implements DomainEvent.

type SwapRequest

type SwapRequest struct {
	SubscriptionID string
	Prices         []SubscriptionPrice
	Proration      Proration
	// ResetBillingCycle starts a new period now.
	ResetBillingCycle bool
	Metadata          map[string]string
	IdempotencyKey    string
}

SwapRequest sets a subscription's prices. Providers keep items whose price is unchanged, update licensed items in place, and replace metered items by adding the new one and removing the old one.

type Swapped

type Swapped struct {
	SubscriptionEvent
	From, To string
}

Swapped is sent when the plan changes.

func (Swapped) EventName

func (Swapped) EventName() string

EventName implements DomainEvent.

type SyncAction

type SyncAction struct {
	Kind            SyncActionKind
	LookupKey       string
	ProviderPriceID string
}

SyncAction is one step of a catalog sync.

type SyncActionKind

type SyncActionKind string

SyncActionKind is what SyncCatalog does to one price.

const (
	SyncCreate  SyncActionKind = "create"
	SyncKeep    SyncActionKind = "keep"
	SyncArchive SyncActionKind = "archive"
)

The sync actions.

type SyncOptions

type SyncOptions struct {
	// DryRun plans without changing the provider.
	DryRun bool
	// Existing are the stored mappings; prices mapped there but missing
	// from the catalog are archived.
	Existing []PriceMapping
}

SyncOptions configure SyncCatalog.

type SyncPlan

type SyncPlan struct {
	Actions  []SyncAction
	Mappings []PriceMapping
}

SyncPlan is a catalog sync's steps and the resulting price mappings.

type TrialWillEnd

type TrialWillEnd struct {
	SubscriptionEvent
	TrialEndsAt time.Time
}

TrialWillEnd is sent ahead of a trial's end (Stripe: three days before).

func (TrialWillEnd) EventName

func (TrialWillEnd) EventName() string

EventName implements DomainEvent.

type UsageQuery

type UsageQuery struct {
	Customer  string
	EventName string
	Start     time.Time
	End       time.Time
}

UsageQuery asks for a customer's usage of a meter in [Start, End).

type UsageRecord

type UsageRecord struct {
	ID         string
	CustomerID string
	Billable   BillableRef
	// Meter is the catalog meter key.
	Meter          string
	Quantity       int64
	IdempotencyKey string
	OccurredAt     time.Time
	// ReportedAt is zero until the provider accepted the record.
	ReportedAt time.Time
	Attempts   int
	LastError  string
}

UsageRecord is one metered usage report in the outbox.

type UsageSummary

type UsageSummary struct {
	Meter    string
	Quantity int64
	Start    time.Time
	End      time.Time
}

UsageSummary is aggregated usage.

type WebhookDecoder

type WebhookDecoder interface {
	// Decode verifies the signature over the raw body and decodes the
	// event. A verification failure wraps ErrBadSignature.
	Decode(header http.Header, body []byte) (DecodedEvent, error)
}

WebhookDecoder verifies and decodes a provider webhook request.

type WebhookEvent

type WebhookEvent struct {
	ID         string
	Provider   ProviderName
	EventID    string
	Type       string
	ObjectType ObjectType
	ObjectID   string
	Payload    []byte
	ReceivedAt time.Time
	// ProcessedAt is zero until the event is applied.
	ProcessedAt time.Time
	Attempts    int
	LastError   string
	// ReplayedBy names who last replayed the event by hand.
	ReplayedBy string
}

WebhookEvent is one received provider event in the webhook log.

type WebhookEventQuery

type WebhookEventQuery struct {
	Provider ProviderName
	Type     string
	// Unprocessed keeps events with no ProcessedAt.
	Unprocessed bool
	// Failed keeps unprocessed events with a LastError.
	Failed bool
	Limit  int
	Offset int
}

WebhookEventQuery filters ListWebhookEvents. Results are newest first.

Directories

Path Synopsis
nock module
paddle module
portal module
quiver module
sight module
stripe module
Package tallytest is tally's test kit: a settable clock, an in-memory Store, a FakeProvider that implements every capability, signed webhook requests, and the contract suites every provider and store runs.
Package tallytest is tally's test kit: a settable clock, an in-memory Store, a FakeProvider that implements every capability, signed webhook requests, and the contract suites every provider and store runs.

Jump to

Keyboard shortcuts

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