app

package
v0.10.3 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeChannelNotConfigured = "E_CHANNEL_NOT_CONFIGURED"

	CodeChannelTestUnsupported = "E_CHANNEL_TEST_UNSUPPORTED"

	CodeChannelCancelUnsupported = "E_CHANNEL_CANCEL_UNSUPPORTED"
)
View Source
const (
	KindPaymentFailed = "billing.payment_failed"

	KindOrderMarkedPaid = "billing.order_marked_paid"
)
View Source
const ChannelManual = "manual"

Variables

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

Functions

This section is empty.

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 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) 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) RunExpiryNow

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

func (*BillingAdminService) RunOverageNow

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

func (*BillingAdminService) TestChannelConnection

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

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 *ChannelRegistry, 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) 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) 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) WithEventEmitter

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

func (*BillingService) WithMeterRegistry

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

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 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) Names

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

func (*ChannelRegistry) Register

func (r *ChannelRegistry) Register(ch PaymentChannel)

type CheckoutCanceller

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

type Clock

type Clock func() time.Time

type Config

type Config struct {
	SuccessURL string
	CancelURL  string

	Currency string
}

type ConnectionTester

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

type EventEmit

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

type ExpiredWorkspace

type ExpiredWorkspace struct {
	WorkspaceID string
	FromPlan    string
}

type ManualChannel

type ManualChannel struct {
	InfoURL string
}

func (*ManualChannel) CreateCheckout

func (m *ManualChannel) CreateCheckout(_ context.Context, order domain.Order, _, _ string) (domain.CheckoutSession, error)

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, order domain.Order, successURL, cancelURL string) (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 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

	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
	SetOrderChannelRef(ctx context.Context, id, channelRef string) 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)

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

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

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

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

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