engine

package
v1.34.0 Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Overview

Package engine provides core billing business logic: usage aggregation, payment collection, and subscription lifecycle management.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AdjustCustomerBalance

func AdjustCustomerBalance(db *datastore.Datastore, customerId string, amount int64, cur currency.Type, txnType, description string) (*balancetransaction.BalanceTransaction, error)

AdjustCustomerBalance adjusts a customer's balance and creates a ledger entry.

func AggregateItemUsage

func AggregateItemUsage(db *datastore.Datastore, item *subscriptionitem.SubscriptionItem, periodStart, periodEnd time.Time) ([]billinginvoice.LineItem, int64, error)

AggregateItemUsage aggregates usage for a single subscription item, respecting watermarks to prevent double-invoicing. Only events after the last watermark's timestamp are included.

func AggregateUsage

func AggregateUsage(db *datastore.Datastore, userId string, periodStart, periodEnd time.Time) ([]billinginvoice.LineItem, int64, error)

AggregateUsage queries all meters, collects events for the given user and period, applies pricing rules, and returns structured line items. This is the generalized version of the InvoicePreview handler logic.

func ApplyBalanceToInvoice

func ApplyBalanceToInvoice(db *datastore.Datastore, customerId, invoiceId string, amountDue int64, cur currency.Type) (int64, *balancetransaction.BalanceTransaction, error)

ApplyBalanceToInvoice deducts from customer balance to pay an invoice. Returns the amount applied and the ledger entry.

func CancelPaymentIntent

func CancelPaymentIntent(ctx context.Context, pi *paymentintent.PaymentIntent, reason string) error

CancelPaymentIntent cancels a payment intent with the given reason.

func CancelSetupIntent

func CancelSetupIntent(si *setupintent.SetupIntent, reason string) error

CancelSetupIntent cancels a setup intent.

func CancelSubscription

func CancelSubscription(sub *subscription.Subscription, atPeriodEnd bool) error

CancelSubscription cancels a subscription, either immediately or at period end.

func CapturePaymentIntent

func CapturePaymentIntent(ctx context.Context, db *datastore.Datastore, pi *paymentintent.PaymentIntent, amount int64, proc processor.PaymentProcessor) error

CapturePaymentIntent captures a previously authorized payment intent.

func ChangePlan

func ChangePlan(sub *subscription.Subscription, newPlan *plan.Plan, prorate bool) (*billinginvoice.LineItem, error)

ChangePlan updates a subscription to a new plan. If prorate is true, a proration line item will be added to the current period's invoice.

func CheckThreshold

func CheckThreshold(db *datastore.Datastore, item *subscriptionitem.SubscriptionItem, threshold int64) (exceeded bool, currentValue int64, err error)

CheckThreshold checks whether usage for a subscription item has exceeded a given threshold. Returns whether the threshold is exceeded and the current usage value.

func ConfirmPaymentIntent

func ConfirmPaymentIntent(ctx context.Context, db *datastore.Datastore, pi *paymentintent.PaymentIntent, pmId string, proc processor.PaymentProcessor) error

ConfirmPaymentIntent confirms a payment intent, optionally attaching a payment method, and processes the payment via the configured processor.

func ConfirmSetupIntent

func ConfirmSetupIntent(ctx context.Context, db *datastore.Datastore, si *setupintent.SetupIntent, pmId string, proc processor.PaymentProcessor) error

ConfirmSetupIntent confirms a setup intent, verifying the payment method can be used for future payments.

func CreateCreditNote

func CreateCreditNote(db *datastore.Datastore, params CreateCreditNoteParams) (*creditnote.CreditNote, error)

CreateCreditNote creates a credit note against an invoice.

func CreatePaymentIntent

CreatePaymentIntent creates a new payment intent in the initial state.

func CreateRefund

CreateRefund creates a full or partial refund for a payment intent or invoice. If Amount is 0, the full amount is refunded.

func CreateSetupIntent

func CreateSetupIntent(db *datastore.Datastore, params CreateSetupIntentParams) (*setupintent.SetupIntent, error)

CreateSetupIntent creates a new setup intent for saving a payment method.

func CreateWatermark

func CreateWatermark(db *datastore.Datastore, subscriptionItemId, meterId, invoiceId string, periodStart, periodEnd time.Time, aggregatedValue, eventCount int64, lastEventTimestamp time.Time) (*usagewatermark.UsageWatermark, error)

CreateWatermark records a watermark after usage has been invoiced, preventing those events from being counted again.

func DispatchWebhooks

func DispatchWebhooks(db *datastore.Datastore, evt *billingevent.BillingEvent) error

DispatchWebhooks sends the event to all matching webhook endpoints.

func EmitBillingEvent

func EmitBillingEvent(db *datastore.Datastore, eventType, objectType, objectId, customerId string, data, previousData Map) (*billingevent.BillingEvent, error)

EmitBillingEvent creates an append-only billing event record and dispatches it to all matching webhook endpoints.

func GetOrCreateCustomerBalance

func GetOrCreateCustomerBalance(db *datastore.Datastore, customerId string, cur currency.Type) (*customerbalance.CustomerBalance, error)

GetOrCreateCustomerBalance retrieves the customer balance for a given customer+currency, creating it if it doesn't exist.

func IngestUsageEvent

func IngestUsageEvent(db *datastore.Datastore, meterId, userId string, value int64, idempotencyKey string, ts time.Time, dimensions map[string]interface{}) (*meter.MeterEvent, bool, error)

IngestUsageEvent records a single usage event with idempotency handling. If the event has an idempotency key that already exists, it is silently skipped.

func IngestUsageEventBatch

func IngestUsageEventBatch(db *datastore.Datastore, events []struct {
	MeterId     string
	UserId      string
	Value       int64
	Idempotency string
	Timestamp   time.Time
	Dimensions  map[string]interface{}
}) (created int, duplicates int, err error)

IngestUsageEventBatch records multiple usage events, skipping duplicates. Returns the number of new events created and the total processed.

func ReactivateSubscription

func ReactivateSubscription(sub *subscription.Subscription) error

ReactivateSubscription reverses a pending cancellation.

func StartSubscription

func StartSubscription(sub *subscription.Subscription, p *plan.Plan)

StartSubscription initializes a new subscription: sets the initial state, computes period dates, and handles trial logic.

func TransitionTrialToActive

func TransitionTrialToActive(sub *subscription.Subscription) error

TransitionTrialToActive moves a trialing subscription to active.

func VerifyWebhookSignature

func VerifyWebhookSignature(payload []byte, signatureHeader, secret string) error

VerifyWebhookSignature verifies a webhook payload signature.

Types

type CollectionResult

type CollectionResult struct {
	Success       bool   `json:"success"`
	CreditUsed    int64  `json:"creditUsed"`
	BalanceUsed   int64  `json:"balanceUsed"`
	ProviderUsed  int64  `json:"providerUsed"`
	ProviderRef   string `json:"providerRef,omitempty"`
	AmountCharged int64  `json:"amountCharged"`
	Error         string `json:"error,omitempty"`
}

CollectionResult describes the outcome of a payment collection attempt.

func CollectInvoice

func CollectInvoice(ctx context.Context, db *datastore.Datastore, inv *billinginvoice.BillingInvoice, burnCredits CreditBurner) (*CollectionResult, error)

CollectInvoice attempts to collect payment for an invoice using the provider-agnostic waterfall: credits -> balance -> external provider. The burnCredits parameter is injected to avoid circular imports.

func RenewSubscription

RenewSubscription generates an invoice for the current billing period and attempts to collect payment. Returns the invoice and collection result.

type CreateCreditNoteParams

type CreateCreditNoteParams struct {
	InvoiceId       string
	CustomerId      string
	Amount          int64
	Reason          string
	LineItems       []creditnote.CreditNoteLineItem
	OutOfBandAmount int64
	Memo            string
}

CreateCreditNoteParams holds the parameters for creating a credit note.

type CreatePaymentIntentParams

type CreatePaymentIntentParams struct {
	CustomerId         string        `json:"customerId"`
	Amount             int64         `json:"amount"`
	Currency           currency.Type `json:"currency"`
	PaymentMethodId    string        `json:"paymentMethodId,omitempty"`
	CaptureMethod      string        `json:"captureMethod,omitempty"`      // "automatic" | "manual"
	ConfirmationMethod string        `json:"confirmationMethod,omitempty"` // "automatic" | "manual"
	SetupFutureUsage   string        `json:"setupFutureUsage,omitempty"`
	Description        string        `json:"description,omitempty"`
	ReceiptEmail       string        `json:"receiptEmail,omitempty"`
	InvoiceId          string        `json:"invoiceId,omitempty"`
}

CreatePaymentIntentParams contains parameters for creating a payment intent.

type CreateRefundParams

type CreateRefundParams struct {
	PaymentIntentId string
	InvoiceId       string
	Amount          int64  // 0 = full refund
	Reason          string // "duplicate" | "fraudulent" | "requested_by_customer"
}

CreateRefundParams holds the parameters for creating a refund.

type CreateSetupIntentParams

type CreateSetupIntentParams struct {
	CustomerId      string `json:"customerId"`
	PaymentMethodId string `json:"paymentMethodId,omitempty"`
	Usage           string `json:"usage,omitempty"` // "on_session" | "off_session"
}

CreateSetupIntentParams contains parameters for creating a setup intent.

type CreditBurner

type CreditBurner func(db *datastore.Datastore, userId string, amount int64, meterId string) (int64, error)

CreditBurner is the function signature for burning credits. This matches the existing BurnCredits function in api/billing/credit_grants.go.

type TaxLine

type TaxLine struct {
	TaxRateId    string  `json:"taxRateId"`
	Description  string  `json:"description"`
	Amount       int64   `json:"amount"` // tax amount in cents
	Rate         float64 `json:"rate"`   // e.g., 0.0875 for 8.75%
	Inclusive    bool    `json:"inclusive"`
	Jurisdiction string  `json:"jurisdiction"`
}

TaxLine represents a single tax computation on an invoice.

func CalculateInvoiceTax

func CalculateInvoiceTax(db *datastore.Datastore, inv *billinginvoice.BillingInvoice, customerAddress *types.Address) ([]TaxLine, int64, error)

CalculateInvoiceTax computes tax for an invoice based on the customer address using the existing TaxRate and TaxRegion models. Returns tax lines and total.

type UsageSummary

type UsageSummary struct {
	MeterId         string    `json:"meterId"`
	MeterName       string    `json:"meterName"`
	AggregationType string    `json:"aggregationType"`
	Value           int64     `json:"value"`
	EventCount      int64     `json:"eventCount"`
	PeriodStart     time.Time `json:"periodStart"`
	PeriodEnd       time.Time `json:"periodEnd"`
}

UsageSummary describes aggregated usage for a meter+user over a period.

func GetUsageSummary

func GetUsageSummary(db *datastore.Datastore, meterId, userId string, periodStart, periodEnd time.Time) (*UsageSummary, error)

GetUsageSummary returns aggregated usage for a meter+user over a period.

Jump to

Keyboard shortcuts

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