app

package
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeChannelNotConfigured = "E_CHANNEL_NOT_CONFIGURED"

	CodeChannelTestUnsupported = "E_CHANNEL_TEST_UNSUPPORTED"

	CodeChannelCancelUnsupported = "E_CHANNEL_CANCEL_UNSUPPORTED"

	CodeChannelProductUnsupported = "E_CHANNEL_PRODUCT_UNSUPPORTED"
)
View Source
const (
	FieldTypeText   = "text"
	FieldTypeSecret = "secret"
	FieldTypeSelect = "select"
)

Field type literals for FieldSpec.Type.

View Source
const (
	KindPaymentFailed = "billing.payment_failed"

	KindOrderMarkedPaid = "billing.order_marked_paid"
)
View Source
const (
	CancelOutcomeCancelled       = "cancelled"
	CancelOutcomePeriodEnd       = "period_end"
	CancelOutcomeOperatorPending = "operator_pending"
)

User-cancel outcome values (LC-4). The HTTP layer answers 200 with {ok:true, outcome} for every one of them — a cancel request is always ACCEPTED; which shape it takes is channel knowledge:

  • cancelled: the channel revoked access immediately; the local plan is downgraded right away (same local path as admin cancel).
  • period_end: the channel honors the paid period; only the cancel_requested_at mark is set and the plan/subscription rows stay untouched until the period runs out (expiry sweeper collects).
  • operator_pending: the channel has no canceller API (none of the three built-in channels — 2026-10-26 correction: stripe implements it too, so this branch is reachable only for third-party channels) or the plan has no channel subscription at all; the framework CANNOT stop the next charge (audit L2) — the request lands in the admin cancel-requests queue and an operator finishes it in the channel console. This is never surfaced as a 4xx: the user's action is accepted.
View Source
const ChannelManual = "manual"
View Source
const ChannelSettingsPrefix = "billing_channel."

ChannelSettingsPrefix materializes channel field keys: billing_channel.<channel>.<field> (keep in sync with settings.BillingChannelKeyPrefix).

View Source
const DefaultChannelDisplayOrder = 500

DefaultChannelDisplayOrder is the DisplayOrder assumed for channels that do not implement ChannelCapabilityViewer — unsorted channels sink below the framework defaults (stripe 200) but stay above manual (900).

Variables

View Source
var ErrDuplicate = errors.New("duplicate")
View Source
var ErrMeterImmutable = errors.New("meter definition immutable")

Functions

func ChannelSettingsKey added in v0.13.0

func ChannelSettingsKey(channel, field string) string

ChannelSettingsKey builds one settings key for a channel field.

func PlanPriceCents added in v0.13.0

func PlanPriceCents(plan domain.Plan, interval domain.BillingInterval) int

PlanPriceCents is the exported planPriceCents lookup (BC-7): checkout, the admin catalog view and channel ProductRegistrar implementations all price a plan+interval from the same DB limits keys.

func ProcessorDisplayName added in v0.17.0

func ProcessorDisplayName(channel string) string

ProcessorDisplayName maps a payment-channel name to the legal disclosure name for "payments are processed by …" copy (LC-1/LC-7): the merchant of record is disclosed under its legal brand, direct channels under their brand. The manual channel is deliberately "" — there is no external processor to disclose. Unknown future channels fall back to the raw name so a new adapter can never silently blank the placeholder.

Types

type AdminOrderFilter

type AdminOrderFilter struct {
	WorkspaceID string
	Status      string
}

type AdminOrderView

type AdminOrderView struct {
	domain.Order
	WorkspaceName string `json:"workspace_name"`
}

type AdminRepo

type AdminRepo interface {
	ListAllOrders(ctx context.Context, f AdminOrderFilter, limit, offset int) ([]AdminOrderView, int, error)

	ListPaymentEvents(ctx context.Context, f PaymentEventFilter, limit, offset int) ([]PaymentEventView, int, error)

	ListPlanCodes(ctx context.Context) ([]string, error)

	UpdatePlan(ctx context.Context, code, name, limitsJSON string, sortNo int, currency string) (found bool, err error)
}

type AdminUsageFunc

type AdminUsageFunc func(ctx context.Context, workspaceID, key, period string) (used, granted int64, err error)

type AtomicRegistry added in v0.13.0

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

AtomicRegistry is the BC-5 hot-reload ChannelSet: channels are rebuilt from a settings source (billing_channel.<name>.* rows) on a poll and the active set is swapped behind a single pointer — readers (BillingService, /config, admin cards) never see a half-built registry and no restart is needed after an admin saves credentials.

Build rules:

  • source error → keep the previous set + log.Warn (a flaky DB read must not take checkout down; the next tick retries); at BOOT the previous set does not exist yet, so the factories run once over an EMPTY fields map — env-only channels still register, only DB-configured ones wait for the poll to heal them (fix #5),
  • factory returning (nil, nil) → the channel is simply not registered this round (credentials incomplete = unconfigured),
  • factory error → that channel is skipped this round + log.Warn (a bad pasted key disables the channel, not the whole registry).

Get/OrderedNames semantics match ChannelRegistry (capability-declared DisplayOrder, DefaultChannelDisplayOrder fallback).

func NewAtomicRegistry added in v0.13.0

func NewAtomicRegistry(ctx context.Context, log *slog.Logger,
	source func(ctx context.Context) (map[string]map[string]string, error),
	factories map[string]func(fields map[string]string) (PaymentChannel, error),
	pollEvery time.Duration) *AtomicRegistry

NewAtomicRegistry builds the first channel set synchronously and keeps rebuilding every pollEvery until ctx is done. pollEvery <= 0 defaults to 30s. A failing initial source no longer starts the process with ZERO channels (billing fix #5): the factories are run once with an empty fields map — env-only channels (manual, env-configured stripe) register as usual, only DB-configured channels wait for the poll to heal them.

func (*AtomicRegistry) Get added in v0.13.0

func (r *AtomicRegistry) Get(name string) (PaymentChannel, bool)

func (*AtomicRegistry) OrderedChannels added in v0.14.0

func (r *AtomicRegistry) OrderedChannels() []PaymentChannel

OrderedChannels returns every registered channel (disabled stubs included) in (DisplayOrder asc, name asc) order — the admin channel-cards page enumerates this so unconfigured channels stay visible and editable.

func (*AtomicRegistry) OrderedNames added in v0.13.0

func (r *AtomicRegistry) OrderedNames() []string

func (*AtomicRegistry) RefreshNow added in v0.13.0

func (r *AtomicRegistry) RefreshNow(ctx context.Context) error

RefreshNow rebuilds the channel set from the source and swaps the pointer synchronously; the admin PUT path calls it right after saving credentials so the response card reflects the new effective state (config flips from env to db within the same request). Returns the source error, if any — the previous set is kept on failure.

type Auditor

type Auditor interface {
	Record(ctx context.Context, workspaceID *string, p *webx.Principal, action, resourceType, resourceID string, meta map[string]any)
}

type BillingAdminService

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

func NewBillingAdminService

func NewBillingAdminService(core *BillingService, adminRepo AdminRepo, now Clock, log *slog.Logger) *BillingAdminService

func (*BillingAdminService) AdminCancelPendingOrder

func (s *BillingAdminService) AdminCancelPendingOrder(ctx context.Context, actor *webx.Principal, orderID string) error

func (*BillingAdminService) AdminCancelSubscription

func (s *BillingAdminService) AdminCancelSubscription(ctx context.Context, actor *webx.Principal, workspaceID string) error

func (*BillingAdminService) AdminUpdatePlan added in v0.8.0

func (s *BillingAdminService) AdminUpdatePlan(ctx context.Context, actor *webx.Principal, code string, in PlanUpdateInput) (PlanView, error)

AdminUpdatePlan full-replaces a plan's editable fields and writes a platform-level audit record (`admin.plan_change`, workspaceID nil) with from/to snapshots. Full-replace semantics: the UI submits the whole card, keys absent from Limits disappear. -1 keeps its seed meaning of "unlimited"; limit values are JSON integers by construction (map[string]int). Readers (checkout, plan listings) hit the DB per request, so the change is effective immediately — no cache, no restart; existing orders keep their snapshotted amount.

func (*BillingAdminService) BillingConfig

func (s *BillingAdminService) BillingConfig(ctx context.Context) (BillingConfigView, error)

func (*BillingAdminService) ChannelCards added in v0.13.0

func (s *BillingAdminService) ChannelCards(ctx context.Context) ([]ChannelCard, error)

ChannelCards assembles the admin billing-channels page: one card per REGISTERED channel in priority order (OrderedChannels — F16: never registered = no card). Disabled stubs (unconfigured paypal/waffo/stripe factories return app.DisabledChannel) are registered and therefore DO get a card — configured:false, schema rendered — so credentials can be pasted without env bootstrapping (the BC-5 chicken-and-egg fix); values come from the DB namespace with secrets masked to __SET__.

func (*BillingAdminService) ChannelCatalog added in v0.13.0

func (s *BillingAdminService) ChannelCatalog(ctx context.Context) (ChannelCatalog, error)

ChannelCatalog lists every registered channel product joined with the plan's current DB price, plus the plan list for the UI to render unregistered slots (BC-7 admin page).

func (*BillingAdminService) ListAllOrders

func (s *BillingAdminService) ListAllOrders(ctx context.Context, f AdminOrderFilter, limit, offset int) ([]AdminOrderView, int, error)

func (*BillingAdminService) ListPaymentEvents

func (s *BillingAdminService) ListPaymentEvents(ctx context.Context, f PaymentEventFilter, limit, offset int) ([]PaymentEventView, int, error)

func (*BillingAdminService) ListPlanCodes

func (s *BillingAdminService) ListPlanCodes(ctx context.Context) ([]string, error)

func (*BillingAdminService) ListPlanViews

func (s *BillingAdminService) ListPlanViews(ctx context.Context) ([]PlanView, error)

func (*BillingAdminService) MarkOrderPaid

func (s *BillingAdminService) MarkOrderPaid(ctx context.Context, actor *webx.Principal, orderID string) error

func (*BillingAdminService) RegisterChannelProduct added in v0.13.0

func (s *BillingAdminService) RegisterChannelProduct(ctx context.Context, actor *webx.Principal, channel, planCode, interval string) (string, error)

RegisterChannelProduct creates (or returns the existing) channel-side product for plan+interval on a catalog-based channel (BC-7, F4): the one-off create-products script becomes this admin button. Idempotent on the (channel, plan_code, interval) mapping.

func (*BillingAdminService) RunExpiryNow

func (s *BillingAdminService) RunExpiryNow(ctx context.Context) (int, error)

func (*BillingAdminService) RunOverageNow

func (s *BillingAdminService) RunOverageNow(ctx context.Context) (int, error)

func (*BillingAdminService) SyncChannelPrice added in v0.13.0

func (s *BillingAdminService) SyncChannelPrice(ctx context.Context, actor *webx.Principal, channel, planCode, interval string) (int, error)

SyncChannelPrice pushes the plan's current DB price to a registered channel product (BC-7 改价联动) and stamps synced_price_cents/synced_at so the catalog view can detect drift.

func (*BillingAdminService) TestChannelConnection

func (s *BillingAdminService) TestChannelConnection(ctx context.Context, name string) error

func (*BillingAdminService) UpdateChannelFields added in v0.13.0

func (s *BillingAdminService) UpdateChannelFields(ctx context.Context, actor *webx.Principal, channel string, fields map[string]string) (ChannelCard, error)

UpdateChannelFields persists one channel's edited fields as billing_channel.<name>.<field> rows (BC-5): unknown field names 400; a secret submitted as the empty string OR the __SET__ masked read-back keeps the stored value (billing fix #4 — a GET→PUT round-trip must never store the marker as a literal key); text/select fields overwrite (empty = clear, except a required field cleared while env does not provide it — 400, fix #6). ALL fields are validated before the first write and the writes land in one transaction via SetMany (fix #11 — a mid-loop failure used to leave a half-saved channel). After the write the channel set is rebuilt synchronously when a refresher is wired, and the response card is rebuilt from the freshly-Get-ed channel instance + a fresh DB read (fix #9 — the old card echoed the pre-save instance's mask/status).

func (*BillingAdminService) WithChannelRefresher added in v0.13.0

func (s *BillingAdminService) WithChannelRefresher(r ChannelRefresher) *BillingAdminService

WithChannelRefresher wires the hot-reload trigger called right after a successful PUT, so the response card reflects the freshly built channel.

func (*BillingAdminService) WithChannelSettings added in v0.13.0

func (s *BillingAdminService) WithChannelSettings(store ChannelSettingsStore) *BillingAdminService

WithChannelSettings wires the settings store backing billing_channel.* keys (BC-5). Without it the channel cards render env-only (no values, no PUT).

func (*BillingAdminService) WithUsage

type BillingConfigView

type BillingConfigView struct {
	Channels []ChannelConfigView `json:"channels"`
}

type BillingHooks

type BillingHooks struct {
	BeforeCheckout func(ctx context.Context, workspaceID, userID, planCode string) error

	OnPlanChanged func(ctx context.Context, workspaceID, from, to string) error

	OnPlanChangedTx func(ctx context.Context, tx pgx.Tx, workspaceID, from, to string) error

	OnPaymentFailed func(ctx context.Context, workspaceID, orderID, reason string) error

	OnSubscriptionRenewed func(ctx context.Context, workspaceID string, expiresAt time.Time) error

	OnMeteredOverage func(ctx context.Context, workspaceID, orderID, period string, items int, amountCents int64) error
}

type BillingService

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

func NewBillingService

func NewBillingService(repo Repo, channels ChannelSet, cfg Config, hooks BillingHooks, auditor Auditor, now Clock, log *slog.Logger) *BillingService

func (*BillingService) AdminCancelSubscription

func (s *BillingService) AdminCancelSubscription(ctx context.Context, actor *webx.Principal, workspaceID string) error

func (*BillingService) BillingConfig

func (s *BillingService) BillingConfig(_ context.Context) BillingConfigView

func (*BillingService) CancelPendingOrder

func (s *BillingService) CancelPendingOrder(ctx context.Context, p *webx.Principal, orderID string) error

func (*BillingService) CreateCheckout

func (s *BillingService) CreateCheckout(ctx context.Context, p *webx.Principal, workspaceID, planCode string, interval domain.BillingInterval, channelName string) (*domain.CheckoutSession, error)

func (*BillingService) CreateOverageOrder

func (s *BillingService) CreateOverageOrder(ctx context.Context, workspaceID, period string, items []OverageItem, now time.Time) (domain.Order, bool, error)

func (*BillingService) ExpireDueWorkspaces

func (s *BillingService) ExpireDueWorkspaces(ctx context.Context, now time.Time, limit int) ([]ExpiredWorkspace, error)

func (*BillingService) ExpireStaleOrders added in v0.13.0

func (s *BillingService) ExpireStaleOrders(ctx context.Context, now time.Time, limit int) ([]string, error)

ExpireStaleOrders sweeps pending orders whose checkout session expired (F15: waffo drops abandoned sessions with zero callbacks). No hooks fire — a pending order never granted rights, so canceling it changes nothing but the order row.

func (*BillingService) GetCancelSnapshot added in v0.17.0

func (s *BillingService) GetCancelSnapshot(ctx context.Context, workspaceID string) (CancelSnapshot, error)

GetCancelSnapshot assembles the cancel-state triple for the subscription view. Channel-location conditions (no paid recurring order, unregistered channel) surface as a null timing, not an error — the subscription GET must answer for every workspace shape; only real storage failures fail it.

func (*BillingService) GetMeter

func (s *BillingService) GetMeter(ctx context.Context, slug string) (Meter, bool, error)

func (*BillingService) GetSubscription

func (s *BillingService) GetSubscription(ctx context.Context, workspaceID string) (currentPlan string, orders []domain.Order, err error)

func (*BillingService) HandleWebhook

func (s *BillingService) HandleWebhook(ctx context.Context, channelName string, req WebhookRequest) error

func (*BillingService) ListCancelRequests added in v0.17.0

func (s *BillingService) ListCancelRequests(ctx context.Context, limit int) ([]CancelRequestView, error)

ListCancelRequests feeds the admin operator queue (LC-4): every workspace with a recorded cancel request that has not resolved yet.

func (*BillingService) ListMeters

func (s *BillingService) ListMeters(ctx context.Context) ([]Meter, error)

func (*BillingService) ListPlanViews

func (s *BillingService) ListPlanViews(ctx context.Context) ([]PlanView, error)

func (*BillingService) ListPlans

func (s *BillingService) ListPlans(ctx context.Context) ([]domain.Plan, error)

func (*BillingService) MarkOrderPaid

func (s *BillingService) MarkOrderPaid(ctx context.Context, actor *webx.Principal, orderID string) error

func (*BillingService) MeterDueOverages

func (s *BillingService) MeterDueOverages(ctx context.Context, now time.Time, usage func(ctx context.Context, workspaceID, key, period string) (used, granted int64, err error), limit int) ([]domain.Order, error)

func (*BillingService) RegisterMeter

func (s *BillingService) RegisterMeter(ctx context.Context, m Meter) error

func (*BillingService) TestChannelConnection

func (s *BillingService) TestChannelConnection(ctx context.Context, name string) error

func (*BillingService) UsagePreview

func (s *BillingService) UsagePreview(ctx context.Context, workspaceID string, usage func(ctx context.Context, workspaceID, key, period string) (used, granted int64, err error)) (UsagePreview, error)

func (*BillingService) UserCancelSubscription added in v0.17.0

func (s *BillingService) UserCancelSubscription(ctx context.Context, p *webx.Principal, workspaceID string) (string, error)

UserCancelSubscription cancels the workspace's subscription on the user's own behalf (LC-4: cancel must be same-medium as signup — an in-product endpoint, not a channel email portal). It must NOT be used to re-expose the admin semantics: admin cancel is an immediate local downgrade, which would contradict the "access continues until the end of the paid period" promise for period-end channels (audit L2). The local behavior follows the channel's declared CancelTiming.

func (*BillingService) WithBuyerEmailResolver added in v0.13.0

func (s *BillingService) WithBuyerEmailResolver(fn BuyerEmailResolver) *BillingService

WithBuyerEmailResolver injects the identity-side email lookup used to prefill checkout (F2). nil = checkout without email prefill.

func (*BillingService) WithEventEmitter

func (s *BillingService) WithEventEmitter(emit EventEmit) *BillingService

func (*BillingService) WithMeterRegistry

func (s *BillingService) WithMeterRegistry(r MeterRegistry) *BillingService

type BuyerEmailResolver added in v0.13.0

type BuyerEmailResolver func(ctx context.Context, userID string) (string, error)

BuyerEmailResolver resolves a checkout buyer's email from the identity side (user table). Injected by the product's main.go — billing must not import identity. Returning an error degrades to no email prefill, never fails checkout.

type CancelRequestView added in v0.17.0

type CancelRequestView struct {
	WorkspaceID     string    `json:"workspace_id"`
	RequestedAt     time.Time `json:"requested_at"`
	PlanCode        string    `json:"plan"`
	SubscriptionRef string    `json:"subscription_ref"`
}

CancelRequestView is one row of the admin operator queue (LC-4): a workspace whose user requested a cancel that still needs operator attention or is waiting out the paid period.

type CancelSnapshot added in v0.17.0

type CancelSnapshot struct {
	// CancelRequestedAt is when the user's cancel request was recorded
	// (migration 053 mark); null = no pending request.
	CancelRequestedAt *time.Time `json:"cancel_requested_at"`
	// RenewsAt is workspace.plan_expires_at — the end of the currently paid
	// period (what a period-end cancel keeps access until); null = perpetual
	// or manual plan.
	RenewsAt *time.Time `json:"renews_at"`
	// CancelTiming is the subscription channel's DECLARED cancel timing
	// (undeclared canceller channels surface the period_end default the
	// cancel flow applies); null = no channel subscription, channel not
	// registered, or channel without a canceller (operator-queue shape).
	CancelTiming *CancelTiming `json:"cancel_timing"`
}

CancelSnapshot is the cancel-state triple GET /api/billing/subscription exposes alongside plan/orders (R5): the framework-level data source for account-settings UIs (ui LegalAndPrivacySection) to render "取消请求已于 X 受理 / 当前周期至 Y / 取消立即生效" without product-side assembly.

All three fields are nullable; a free workspace with no subscription (the 409-free GET shape) answers nulls, never an error.

type CancelTiming added in v0.17.0

type CancelTiming string

CancelTiming declares when a channel-side subscription cancel takes effect (LC-4). It is channel knowledge, so it lives here — next to the rest of the capability declaration — instead of being hardcoded in the cancel flows:

  • CancelTimingImmediate: the channel revokes access right away, so the local plan flips to free at once (same local path as admin cancel).
  • CancelTimingPeriodEnd: the channel honors the already-paid period, so the local plan stays untouched and only cancel_requested_at is set; the existing plan-expiry machinery collects the workspace when the period runs out without a renewal.
  • "" (empty): timing unknown. A channel that implements SubscriptionCanceller but declares no timing is treated as period-end (the promise-preserving default: never cut a paying user short).

A channel without SubscriptionCanceller never reads this field.

const (
	CancelTimingImmediate CancelTiming = "immediate"
	CancelTimingPeriodEnd CancelTiming = "period_end"
)

type ChannelCapabilityViewer added in v0.13.0

type ChannelCapabilityViewer interface {
	Capabilities() ChannelCaps
}

ChannelCapabilityViewer is the optional capability interface channels implement to declare their caps. Channels that don't implement it get DefaultChannelDisplayOrder in OrderedNames.

type ChannelCaps added in v0.13.0

type ChannelCaps struct {
	CatalogBased      bool         `json:"catalog_based"` // 目录型(waffo/paypal 需预注册商品)vs 临时定价型(stripe price_data)
	SupportsCancelURL bool         `json:"supports_cancel_url"`
	DisplayOrder      int          `json:"display_order"` // /config billing_channels 排序;stripe 建议 200、manual 900、waffo 将来 100
	Currencies        []string     `json:"currencies"`    // 空=不声明限制;非空时 RegisterProduct / AutoRegister 在调渠道 REST 前校验 plan 币种 ∈ 清单(不符 400,修复「CNY 计划注册成功但结账必 400」)
	CancelTiming      CancelTiming `json:"cancel_timing"` // 取消时序(LC-4);空=未声明(有 canceller 时按 period_end 对待)
}

ChannelCaps is a channel's declared shape of difference. The registry and product frontends key ordering off DisplayOrder; CatalogBased/SupportsCancelURL document behavior the adapter absorbs (F1/F3): a channel that ignores CancelURL must say so here instead of silently dropping the parameter.

type ChannelCard added in v0.13.0

type ChannelCard struct {
	Name              string            `json:"name"`
	Configured        bool              `json:"configured"`
	KeyMasked         string            `json:"key_masked"`
	WebhookConfigured bool              `json:"webhook_configured"`
	Capabilities      ChannelCaps       `json:"capabilities"`
	Schema            []FieldSpec       `json:"schema"`
	Values            map[string]string `json:"values"`
	ConfigSource      string            `json:"config_source"` // "db" | "env" | ""
	// EnvProvided lists the schema keys currently supplied by process env
	// (ChannelEnvViewer, billing fix #6): the frontend exempts them from
	// required-field highlighting — clearing the DB row falls back to env.
	EnvProvided []string `json:"env_provided,omitempty"`
}

ChannelCard is one channel's admin billing-page card (BC-6 API contract — field names are shared with the frontend, do not rename).

type ChannelCatalog added in v0.13.0

type ChannelCatalog struct {
	Rows  []ChannelCatalogRow  `json:"rows"`
	Plans []ChannelCatalogPlan `json:"plans"`
}

type ChannelCatalogPlan added in v0.13.0

type ChannelCatalogPlan struct {
	Code         string `json:"code"`
	Name         string `json:"name"`
	Currency     string `json:"currency"`
	MonthlyCents int    `json:"monthly_cents"`
	YearlyCents  int    `json:"yearly_cents"`
}

ChannelCatalogPlan is the plans list the UI cross-joins client-side to render unregistered slots.

type ChannelCatalogRow added in v0.13.0

type ChannelCatalogRow struct {
	Channel          string     `json:"channel"`
	PlanCode         string     `json:"plan_code"`
	Interval         string     `json:"interval"`
	ChannelProductID string     `json:"channel_product_id"`
	SyncedPriceCents int        `json:"synced_price_cents"`
	PlanPriceCents   int        `json:"plan_price_cents"`
	SyncedAt         *time.Time `json:"synced_at"`
}

ChannelCatalogRow is one registered channel product (BC-7) joined with the plan's current DB price so the UI can flag drift.

type ChannelConfigInfo

type ChannelConfigInfo struct {
	Configured bool

	KeyMasked string

	WebhookConfigured bool
}

type ChannelConfigView

type ChannelConfigView struct {
	Name string `json:"name"`

	Configured bool `json:"configured"`

	KeyMasked string `json:"key_masked"`

	WebhookConfigured bool `json:"webhook_configured"`
}

type ChannelConfigViewer

type ChannelConfigViewer interface {
	ChannelConfig() ChannelConfigInfo
}

type ChannelEnvViewer added in v0.13.0

type ChannelEnvViewer interface {
	EnvProvidedKeys() []string
}

ChannelEnvViewer is the optional interface channels implement to expose which of their ConfigSchema keys are currently provided by process env (billing fix #6). Two consumers:

  • UpdateChannelFields: clearing a required text/select field is a 400 unless the key is env-provided (empty DB row = fall back to env, a legitimate "unconfigure the override" move, not a misconfiguration);
  • the admin card (ChannelCard.EnvProvided): the frontend can exempt those fields from required-field highlighting.

The returned keys are ConfigSchema field keys, not env var names.

type ChannelRefresher added in v0.13.0

type ChannelRefresher interface {
	RefreshNow(ctx context.Context) error
}

ChannelRefresher forces a channel-set rebuild out of band; *AtomicRegistry implements it. The admin PUT path calls it after saving so the response card reflects the new effective state without waiting for the poll.

type ChannelRegistry

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

func NewChannelRegistry

func NewChannelRegistry() *ChannelRegistry

func (*ChannelRegistry) Get

func (r *ChannelRegistry) Get(name string) (PaymentChannel, bool)

func (*ChannelRegistry) OrderedChannels added in v0.14.0

func (r *ChannelRegistry) OrderedChannels() []PaymentChannel

OrderedChannels returns every registered channel (disabled stubs included) in the same (DisplayOrder asc, name asc) order — the admin channel-cards page enumerates this.

func (*ChannelRegistry) OrderedNames added in v0.13.0

func (r *ChannelRegistry) OrderedNames() []string

OrderedNames returns ACTIVE channel names sorted by (DisplayOrder asc, name asc) so /config billing_channels is a priority list the frontend can take as-is (F18): first entry = recommended channel, no product-side re-sorting. Channels whose ChannelConfigViewer reports !Configured (disabled stubs) are excluded — see orderedNamesOf.

func (*ChannelRegistry) Register

func (r *ChannelRegistry) Register(ch PaymentChannel)

type ChannelSchemaViewer added in v0.13.0

type ChannelSchemaViewer interface {
	ConfigSchema() []FieldSpec
}

ChannelSchemaViewer is the optional interface channels implement to describe their configuration surface. Channels without it cannot be edited from the admin billing page (env-only wiring).

type ChannelSet added in v0.13.0

type ChannelSet interface {
	Get(name string) (PaymentChannel, bool)
	OrderedNames() []string
	OrderedChannels() []PaymentChannel
}

ChannelSet is the read-side channel registry BillingService depends on. Two implementations: *ChannelRegistry (products wire channels once at boot, zero-change for existing main.go wiring) and *AtomicRegistry (BC-5 hot reload — DB credentials rebuilt on a poll, pointer swapped atomically).

OrderedNames lists only ACTIVE channels (a channel whose ChannelConfig reports !Configured — e.g. a *DisabledChannel stub — is filtered out): it feeds /config billing_channels, checkout and the BillingConfig view, where an unconfigured channel must not appear. OrderedChannels returns the full registered set INCLUDING disabled placeholders — the admin billing-channels page enumerates it so unconfigured channels still get a card to paste credentials into.

type ChannelSettingsStore added in v0.13.0

type ChannelSettingsStore interface {
	Set(ctx context.Context, key, value, actor string) error
	// SetMany writes multiple keys in ONE transaction (billing fix #11): a
	// channel save is all-or-nothing — a mid-save failure used to leave the
	// hot-reload registry reading a half-saved channel. An empty map is a no-op.
	SetMany(ctx context.Context, kv map[string]string, actor string) error
	// BillingChannelFields returns all billing_channel.* rows unsealed,
	// grouped by channel name (absent = no DB config for that channel). A row
	// that fails to unseal is skipped (that channel stays unconfigured) — it
	// must not error the whole read (fix #5: one poisoned row used to take
	// every channel down).
	BillingChannelFields(ctx context.Context) (map[string]map[string]string, error)
}

ChannelSettingsStore is the settings-I/O port for channel credentials (BC-5); *settings.Store satisfies it structurally (billing must not import settings). Keys materialize as billing_channel.<name>.<field>, sealed at rest per settings.IsSensitive.

type CheckoutCanceller

type CheckoutCanceller interface {
	CancelCheckout(ctx context.Context, sessionRef string) error
}

type CheckoutRequest added in v0.13.0

type CheckoutRequest struct {
	Order      domain.Order
	SuccessURL string
	CancelURL  string // 目录型渠道可忽略,但须在 Capabilities().SupportsCancelURL=false 声明,不许静默
	BuyerEmail string // 渠道预填买家邮箱;空=不预填
	Locale     string // 站点语言透传收银台(如 "en"/"zh");空=渠道默认

	// ChannelProductID is the catalog product the service resolved for this
	// order from the billing_channel_products mapping (BC-7). Catalog-based
	// channels must prefer it; empty = the channel falls back to whatever
	// static product ids it was configured with (env-only legacy wiring).
	ChannelProductID string
}

type Clock

type Clock func() time.Time

type Config

type Config struct {
	SuccessURL string
	CancelURL  string

	Currency string

	// Locale is passed through to channel checkout pages ("en"/"zh"…);
	// empty = channel default (F19).
	Locale string

	// AutoRegisterCatalog lets CreateCheckout register a missing catalog
	// product on the fly for catalog-based channels that implement
	// ProductRegistrar (BC-7). Default false: an unmapped plan+interval fails
	// checkout with a "register it in the admin billing page" validation so
	// products never get silently created on the channel side.
	AutoRegisterCatalog bool
}

type ConnectionTester

type ConnectionTester interface {
	TestConnection(ctx context.Context) error
}

type DisabledChannel added in v0.14.0

type DisabledChannel struct {
	ChName string
	Schema []FieldSpec
	Caps   ChannelCaps
}

DisabledChannel is the placeholder a channel factory returns when the channel is "unconfigured" (credentials entirely absent): it makes the channel VISIBLE on the admin billing-channels page (its schema renders the form an operator pastes credentials into, UpdateChannelFields accepts the save) while the ACTIVE channel set (OrderedNames → /config billing_channels, checkout, BillingConfig) does not include it.

This breaks the chicken-and-egg loop of BC-5: a channel used to register only when its credentials were complete, but credentials could only be saved through a registered channel's card — env was the only way to bootstrap paypal/waffo/stripe. Factories now return NewDisabledChannel(name, Schema(), Caps()) instead of (nil, nil); once the saved fields make the real factory succeed, RefreshNow rebuilds the set and the stub is replaced by the live channel.

Returning the stub (not nil) from a factory whose signature is (app.PaymentChannel, error) also kills the typed-nil trap at the root: a concrete `return nil, nil` from (*Channel, error) used to produce a non-nil interface holding a nil pointer — a ghost channel registered into /config.

func NewDisabledChannel added in v0.14.0

func NewDisabledChannel(name string, schema []FieldSpec, caps ChannelCaps) *DisabledChannel

NewDisabledChannel builds the stub. schema/caps should come from the adapter's static Schema()/Caps() (the same single source the live channel's instance methods delegate to), so the admin form and priority ordering match the real channel exactly.

func (*DisabledChannel) CancelCheckout added in v0.14.0

func (d *DisabledChannel) CancelCheckout(_ context.Context, _ string) error

func (*DisabledChannel) CancelSubscription added in v0.14.0

func (d *DisabledChannel) CancelSubscription(_ context.Context, _ string) error

func (*DisabledChannel) Capabilities added in v0.14.0

func (d *DisabledChannel) Capabilities() ChannelCaps

Capabilities mirrors the real channel's declaration (ordering on the admin page, currency whitelist visibility) — the stub is the channel's card, not a different channel.

func (*DisabledChannel) ChannelConfig added in v0.14.0

func (d *DisabledChannel) ChannelConfig() ChannelConfigInfo

ChannelConfig reports the honest state: nothing configured, nothing masked, no webhook. OrderedNames/BillingConfig filter on this.

func (*DisabledChannel) ConfigSchema added in v0.14.0

func (d *DisabledChannel) ConfigSchema() []FieldSpec

ConfigSchema renders the admin form so credentials can be pasted — that is the stub's whole reason to exist.

func (*DisabledChannel) CreateCheckout added in v0.14.0

CreateCheckout never succeeds on a stub — the channel is not in the active set, but if a stale client reaches here anyway (e.g. ordered /config list cached from before the swap), the error names the fix instead of a generic failure.

func (*DisabledChannel) Name added in v0.14.0

func (d *DisabledChannel) Name() string

func (*DisabledChannel) ParseWebhook added in v0.14.0

ParseWebhook rejects before any signature work: a stub has no signing secret, so no signature could ever verify.

func (*DisabledChannel) TestConnection added in v0.14.0

func (d *DisabledChannel) TestConnection(context.Context) error

type EventEmit

type EventEmit func(ctx context.Context, tx pgx.Tx, ev events.Event) error

type ExpiredOrder added in v0.13.0

type ExpiredOrder struct {
	ID          string
	WorkspaceID string
}

ExpiredOrder is one pending order swept to canceled because its checkout session expiry (order.expires_at) has passed (F15: channels like waffo expire sessions with zero callbacks).

type ExpiredWorkspace

type ExpiredWorkspace struct {
	WorkspaceID string
	FromPlan    string
}

type FieldOption added in v0.13.0

type FieldOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

FieldOption is one candidate of a select-typed FieldSpec.

type FieldSpec added in v0.13.0

type FieldSpec struct {
	Key      string        `json:"key"`
	Label    string        `json:"label"`
	Type     string        `json:"type"` // "text" | "secret" | "select"
	Required bool          `json:"required"`
	Help     string        `json:"help"`
	Options  []FieldOption `json:"options"` // select 字段的候选;nil 序列化为 null
}

FieldSpec is one credential/config field of a channel's ConfigSchema (BC-6): the admin form renders from this descriptor, so a fourth channel ships with zero UI changes. JSON tags are the API contract with the billing-channels frontend — do not rename.

type ManualChannel

type ManualChannel struct {
	InfoURL string
}

func (*ManualChannel) Capabilities added in v0.13.0

func (m *ManualChannel) Capabilities() ChannelCaps

Capabilities declares manual's shape: no hosted cashier, so there is no cancel URL to return to (SupportsCancelURL=false — SuccessURL/CancelURL are ignored by design, declared here rather than silently dropped).

func (*ManualChannel) ConfigSchema added in v0.13.0

func (m *ManualChannel) ConfigSchema() []FieldSpec

ConfigSchema implements ChannelSchemaViewer (BC-6): the admin channel card renders its form from this descriptor; info_url is the payment-instruction page buyers land on instead of a hosted cashier.

func (*ManualChannel) CreateCheckout

CreateCheckout returns a zero ExpiresAt (billing fix #2): manual is an offline-transfer channel with no hosted session to expire — the old 7-day window let the abandoned-checkout sweeper flip a still-reconcilable transfer order to canceled while the buyer's bank transfer was in flight. A zero ExpiresAt persists as NULL (SetOrderChannelRefAndExpiry) and the order never participates in the sweep; offline verification stays manual (MarkOrderPaid) with no deadline.

func (*ManualChannel) Name

func (m *ManualChannel) Name() string

func (*ManualChannel) ParseWebhook

type Meter

type Meter struct {
	Slug        string `json:"slug"`
	DisplayName string `json:"display_name"`

	AggType string `json:"agg_type"`

	Unit      string    `json:"unit,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

type MeterRegistry

type MeterRegistry interface {
	RegisterMeter(ctx context.Context, m Meter) error
	ListMeters(ctx context.Context) ([]Meter, error)
	GetMeter(ctx context.Context, slug string) (Meter, bool, error)
}

type MeteredWorkspace

type MeteredWorkspace struct {
	WorkspaceID   string
	PlanCode      string
	Limits        map[string]int
	PlanExpiresAt *time.Time
}

type OverageItem

type OverageItem struct {
	Dim         string
	Used        int64
	Included    int64
	UnitCents   int64
	DisplayName string
	AggType     string
	Unit        string
}

type PaymentChannel

type PaymentChannel interface {
	Name() string

	CreateCheckout(ctx context.Context, req CheckoutRequest) (domain.CheckoutSession, error)

	ParseWebhook(ctx context.Context, req WebhookRequest) (domain.PaymentEvent, error)
}

type PaymentEventFilter

type PaymentEventFilter struct {
	WorkspaceID string
}

type PaymentEventView

type PaymentEventView struct {
	ID             string     `json:"id"`
	Channel        string     `json:"channel"`
	ChannelEventID string     `json:"channel_event_id"`
	Type           string     `json:"event_type"`
	OrderID        string     `json:"order_id,omitempty"`
	ProcessStatus  string     `json:"process_status"`
	ProcessError   string     `json:"process_error,omitempty"`
	ProcessedAt    *time.Time `json:"processed_at,omitempty"`

	Processed bool      `json:"processed"`
	CreatedAt time.Time `json:"created_at"`
}

type PlanUpdateInput added in v0.8.0

type PlanUpdateInput struct {
	Name     string
	Currency string
	SortNo   int
	Limits   map[string]int
}

PlanUpdateInput is the full-replace payload for AdminUpdatePlan; the plan code is carried outside (path identity) and can never be edited.

type PlanView

type PlanView struct {
	Code      string         `json:"code"`
	Name      string         `json:"name"`
	Currency  string         `json:"currency"`
	TrialDays int            `json:"trial_days"`
	SortNo    int            `json:"sort_no"`
	Limits    map[string]int `json:"limits"`
}

type ProductRegistrar added in v0.13.0

type ProductRegistrar interface {
	RegisterProduct(ctx context.Context, plan domain.Plan, interval domain.BillingInterval) (channelProductID string, err error)
	SyncPrice(ctx context.Context, channelProductID string, plan domain.Plan, interval domain.BillingInterval) error
}

ProductRegistrar is the optional interface catalog-based channels (waffo, paypal) implement so the framework can create/sync their product catalog instead of per-product one-off scripts (BC-7, F4). RegisterProduct creates the channel-side product for the plan+interval and returns its channel product id; SyncPrice pushes a price change to an existing product.

type Repo

type Repo interface {
	CreateOrder(ctx context.Context, o domain.Order) (domain.Order, error)
	GetOrder(ctx context.Context, id string) (domain.Order, bool, error)
	ListOrdersByWorkspace(ctx context.Context, workspaceID string, limit int) ([]domain.Order, error)

	UpdateOrderStatus(ctx context.Context, id string, from, to domain.OrderStatus, now time.Time) error

	// CancelOrder is the cancel transition that also stamps canceled_by
	// ('user' / 'admin' / 'expiry' — migration 051). Only 'expiry' rows are
	// revivable by ReviveOrderAfterExpiry; 'user'/'admin'/NULL are terminal.
	CancelOrder(ctx context.Context, id string, from domain.OrderStatus, canceledBy string, now time.Time) error

	// ReviveOrderAfterExpiry attempts the single sanctioned exit from canceled
	// (canceled → paid) when canceled_by = 'expiry' — a payment that actually
	// arrived beats the sweeper's guess. false = not revivable (user/admin
	// canceled, or a pre-051 NULL row), the caller keeps ignoring the event.
	ReviveOrderAfterExpiry(ctx context.Context, id string, now time.Time) (bool, error)

	FailOrder(ctx context.Context, o domain.Order, e domain.PaymentEvent, emit func(tx pgx.Tx) error, now time.Time) error

	PayOrder(ctx context.Context, id string, emit func(tx pgx.Tx) error, now time.Time) error
	SetOrderChannelRefAndExpiry(ctx context.Context, id, channelRef string, expiresAt time.Time) error
	FindOrderByChannelRef(ctx context.Context, channel, channelRef string) (domain.Order, bool, error)

	SetOrderPaymentIntentRef(ctx context.Context, orderID, paymentIntentRef string) error

	FindOrderByPaymentIntent(ctx context.Context, paymentIntentRef string) (domain.Order, bool, error)

	InsertPaymentEvent(ctx context.Context, e domain.PaymentEvent) (isNew bool, err error)
	MarkEventProcessed(ctx context.Context, channel, channelEventID string) error

	MarkEventError(ctx context.Context, channel, channelEventID, processErr string) error

	ListPlans(ctx context.Context) ([]domain.Plan, error)
	GetPlan(ctx context.Context, code string) (domain.Plan, bool, error)

	ChangeWorkspacePlan(ctx context.Context, workspaceID, toPlan, actor, reason string, now time.Time, inTx func(tx pgx.Tx, from string) error) error
	GetWorkspacePlan(ctx context.Context, workspaceID string) (string, error)

	SetWorkspaceSubscription(ctx context.Context, workspaceID, subscriptionRef string, expiresAt, now time.Time) error

	GetWorkspaceSubscription(ctx context.Context, workspaceID string) (ref string, ok bool, err error)

	FindWorkspaceBySubscription(ctx context.Context, subscriptionRef string) (workspaceID, planCode string, ok bool, err error)

	// LC-4 self-serve cancel bookkeeping (migration 053):
	// workspace.cancel_requested_at marks a user-requested cancel that has not
	// resolved locally yet — either the channel stops at period end (plan
	// collected by the expiry sweeper once the period runs out) or the channel
	// has no canceller API and an operator must finish it in the channel
	// console (the admin cancel-requests queue lists these rows). Set on a
	// workspace that re-subscribes is cleared by the checkout-completed path.
	SetWorkspaceCancelRequested(ctx context.Context, workspaceID string, now time.Time) error

	GetWorkspaceCancelRequested(ctx context.Context, workspaceID string) (requestedAt time.Time, ok bool, err error)

	// GetWorkspacePlanExpiry reads workspace.plan_expires_at — the end of the
	// currently paid period. It feeds the renews_at field of the subscription
	// view (R5): a period-end cancel keeps access until this timestamp; a
	// NULL (perpetual/manual plan) surfaces as no renews_at.
	GetWorkspacePlanExpiry(ctx context.Context, workspaceID string) (expiresAt time.Time, ok bool, err error)

	ClearWorkspaceCancelRequested(ctx context.Context, workspaceID string) error

	ListCancelRequestedWorkspaces(ctx context.Context, limit int) ([]CancelRequestView, error)

	LatestPaidOrderInterval(ctx context.Context, workspaceID string) (interval string, ok bool, err error)

	ExpireDueWorkspaces(ctx context.Context, now time.Time, limit int) ([]ExpiredWorkspace, error)

	ExpireStaleOrders(ctx context.Context, now time.Time, limit int) ([]ExpiredOrder, error)

	InsertOverageOrder(ctx context.Context, o domain.Order) (order domain.Order, created bool, err error)

	ListMeteredWorkspaces(ctx context.Context, limit int) ([]MeteredWorkspace, error)

	// BC-7 catalog mapping: resolve/register/list billing_channel_products.
	GetChannelProduct(ctx context.Context, channel, planCode string, interval domain.BillingInterval) (domain.ChannelProduct, bool, error)
	UpsertChannelProduct(ctx context.Context, p domain.ChannelProduct) error
	ListChannelProducts(ctx context.Context) ([]domain.ChannelProduct, error)

	// RegisterChannelProductAtomic wraps mapping check + register callback +
	// upsert under a per-(channel, plan, interval) advisory lock (billing fix
	// #12): concurrent double-clicks serialize, the loser gets existed=true.
	// The callback performs the channel REST inside the lock — see the pgrepo
	// implementation note for the accepted trade-off.
	RegisterChannelProductAtomic(ctx context.Context, channel, planCode string, interval domain.BillingInterval,
		register func(ctx context.Context) (channelProductID string, err error),
		syncedPriceCents int, syncedAt time.Time) (channelProductID string, existed bool, err error)
}

type StaticProductResolver added in v0.18.1

type StaticProductResolver interface {
	// StaticProductID returns the statically configured channel product for
	// the plan+interval, "" when this interval has no static product.
	StaticProductID(planCode string, interval domain.BillingInterval) string
}

StaticProductResolver is the adapter-side static product fallback for catalog-based channels: when the billing_channel_products table has no row for (channel, plan, interval) and AutoRegisterCatalog is off, the service uses the adapter's statically configured product id (env / channel fields) BEFORE failing. Without this seam the adapter's own fallback promise (waffo channel.go: "env-only 老接法不断") is dead code — the service 400s first, which is exactly what happened live (shuijing prod 2026-10-26: env products present, checkout still refused with "product not registered").

type SubscriptionCanceller

type SubscriptionCanceller interface {
	CancelSubscription(ctx context.Context, providerSubID string) error
}

type UsagePreview

type UsagePreview struct {
	Period              string             `json:"period"`
	Items               []UsagePreviewItem `json:"items"`
	ProjectedTotalCents int64              `json:"projected_total_cents"`
}

type UsagePreviewItem

type UsagePreviewItem struct {
	Dim                   string `json:"dim"`
	Used                  int64  `json:"used"`
	Included              int64  `json:"included"`
	UnitCents             int64  `json:"unit_cents"`
	ProjectedOverageCents int64  `json:"projected_overage_cents"`
}

type WebhookRequest

type WebhookRequest struct {
	Header map[string][]string
	Body   []byte
}

Jump to

Keyboard shortcuts

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