flatfee

package
v1.0.0-beta.231 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func UsageBookedAt

func UsageBookedAt(paymentTerm productcatalog.PaymentTermType, servicePeriod timeutil.ClosedPeriod) time.Time

UsageBookedAt returns the ledger booking time for a flat-fee service period.

Types

type AdvanceChargeInput

type AdvanceChargeInput struct {
	ChargeID meta.ChargeID
}

func (AdvanceChargeInput) Validate

func (i AdvanceChargeInput) Validate() error

type Charge

type Charge struct {
	ChargeBase

	Realizations Realizations `json:"realizations"`
}

func (Charge) GetBase

func (c Charge) GetBase() ChargeBase

func (Charge) GetStatus

func (c Charge) GetStatus() Status

func (Charge) Validate

func (c Charge) Validate() error

func (Charge) WithBase

func (c Charge) WithBase(base ChargeBase) Charge

func (Charge) WithStatus

func (c Charge) WithStatus(status Status) Charge

type ChargeAdapter

type ChargeAdapter interface {
	CreateCharges(ctx context.Context, charges CreateChargesInput) ([]Charge, error)

	UpdateCharge(ctx context.Context, charge ChargeBase) (ChargeBase, error)
	CreateChargeOverride(ctx context.Context, charge ChargeBase, override IntentMutableFields) (ChargeBase, error)
	DeleteChargeOverride(ctx context.Context, charge ChargeBase) (ChargeBase, error)
	UpdateSubscriptionItemID(ctx context.Context, charge Charge, newSubscriptionItemID string) (Charge, error)
	DeleteCharge(ctx context.Context, charge Charge) error
	GetByIDs(ctx context.Context, ids GetByIDsInput) ([]Charge, error)
	GetByID(ctx context.Context, id GetByIDInput) (Charge, error)
}

type ChargeBase

type ChargeBase struct {
	meta.ManagedResource

	Intent OverridableIntent `json:"intent"`
	Status Status            `json:"status"`

	State State `json:"state"`
}

func (ChargeBase) ErrorAttributes

func (c ChargeBase) ErrorAttributes() models.Attributes

func (ChargeBase) GetChargeID

func (c ChargeBase) GetChargeID() meta.ChargeID

func (ChargeBase) GetCurrency

func (c ChargeBase) GetCurrency() currencyx.Code

func (ChargeBase) GetCustomerID

func (c ChargeBase) GetCustomerID() customer.CustomerID

func (ChargeBase) Validate

func (c ChargeBase) Validate() error

type ChargeCreditAllocationAdapter

type ChargeCreditAllocationAdapter interface {
	CreateCreditAllocations(ctx context.Context, runID RealizationRunID, creditAllocations creditrealization.CreateInputs) (creditrealization.Realizations, error)
}

type ChargeDetailedLineAdapter

type ChargeDetailedLineAdapter interface {
	UpsertDetailedLines(ctx context.Context, runID RealizationRunID, lines DetailedLines) error
	FetchCurrentRunDetailedLines(ctx context.Context, charge Charge) (Charge, error)
}

type ChargeInvoicedUsageAdapter

type ChargeInvoicedUsageAdapter interface {
	CreateInvoicedUsage(ctx context.Context, input CreateInvoicedUsageInput) (invoicedusage.AccruedUsage, error)
}

type ChargePaymentAdapter

type ChargePaymentAdapter interface {
	CreatePayment(ctx context.Context, runID RealizationRunID, paymentSettlement payment.InvoicedCreate) (payment.Invoiced, error)
	UpdatePayment(ctx context.Context, paymentSettlement payment.Invoiced) (payment.Invoiced, error)
}

type ChargeRunAdapter

type ChargeRunAdapter interface {
	CreateCurrentRun(ctx context.Context, input CreateCurrentRunInput) (RealizationRunBase, error)
	UpdateRealizationRun(ctx context.Context, input UpdateRealizationRunInput) (RealizationRunBase, error)
	DetachCurrentRun(ctx context.Context, chargeID meta.ChargeID) error
}

type ChargeWithGatheringLine

type ChargeWithGatheringLine struct {
	Charge                Charge
	GatheringLineToCreate *billing.GatheringLine
}

type CorrectCreditAllocationsInput

type CorrectCreditAllocationsInput struct {
	Charge   Charge    `json:"charge"`
	BookedAt time.Time `json:"bookedAt"`

	Corrections                  creditrealization.CorrectionRequest   `json:"corrections"`
	LineageSegmentsByRealization lineage.ActiveSegmentsByRealizationID `json:"-"`
}

func (CorrectCreditAllocationsInput) Validate

func (i CorrectCreditAllocationsInput) Validate() error

func (CorrectCreditAllocationsInput) ValidateWith

func (i CorrectCreditAllocationsInput) ValidateWith(currencyCalculator currencyx.Calculator) error

type CreateChargesInput

type CreateChargesInput struct {
	Namespace string
	Intents   []IntentWithInitialStatus
}

func (CreateChargesInput) Validate

func (i CreateChargesInput) Validate() error

type CreateCurrentRunInput

type CreateCurrentRunInput struct {
	Charge                    ChargeBase
	ServicePeriod             timeutil.ClosedPeriod
	AmountAfterProration      alpacadecimal.Decimal
	NoFiatTransactionRequired bool
	Immutable                 bool
	LineID                    *string
	InvoiceID                 *string
}

func (CreateCurrentRunInput) Validate

func (i CreateCurrentRunInput) Validate() error

type CreateInput

type CreateInput struct {
	Namespace     string
	Intents       []Intent
	FeatureMeters feature.FeatureMeters
}

func (CreateInput) Validate

func (i CreateInput) Validate() error

type CreateInvoicedUsageInput

type CreateInvoicedUsageInput struct {
	RunID         RealizationRunID
	LineID        string
	InvoiceID     string
	InvoicedUsage invoicedusage.AccruedUsage
}

func (CreateInvoicedUsageInput) Validate

func (i CreateInvoicedUsageInput) Validate() error

type DetailedLine

type DetailedLine = stddetailedline.Base

type DetailedLines

type DetailedLines []DetailedLine

func (DetailedLines) Clone

func (l DetailedLines) Clone() DetailedLines

func (DetailedLines) Validate

func (l DetailedLines) Validate() error

type FlatFeeService

type FlatFeeService interface {
	// Create returns one result for each input intent, preserving input order.
	// Invoice-line create flows rely on this to merge charge target state back
	// onto the matching billing-preallocated line identity.
	Create(ctx context.Context, input CreateInput) ([]ChargeWithGatheringLine, error)
	// GetByIDs loads flat-fee charges. Request realization expansions when the
	// caller needs invoice-line, credit-allocation, or payment lifecycle state.
	GetByIDs(ctx context.Context, input GetByIDsInput) ([]Charge, error)
	// GetByID loads one flat-fee charge. Effective behavior may come from an
	// override layer, while subscription sync should compare the base intent.
	GetByID(ctx context.Context, input GetByIDInput) (Charge, error)
	// UpdateSubscriptionItemID repairs subscription ownership metadata on the
	// base intent; it must not rewrite an active customer-facing override layer.
	UpdateSubscriptionItemID(ctx context.Context, charge Charge, newSubscriptionItemID string) (Charge, error)
	// AdvanceCharge drives one charge through its lifecycle. Invoice-backed
	// changes are emitted as invoice patches for the billing boundary to consume.
	AdvanceCharge(ctx context.Context, input AdvanceChargeInput) (*Charge, error)
	// TriggerPatch applies an explicit base/override target patch and then
	// reconciles invoice artifacts from the effective flat-fee intent.
	TriggerPatch(ctx context.Context, charge meta.ChargeID, patch meta.Patch) (meta.TriggerPatchResult[Charge], error)
}

type GetByIDInput

type GetByIDInput struct {
	ChargeID meta.ChargeID
	Expands  meta.Expands
}

func (GetByIDInput) Validate

func (i GetByIDInput) Validate() error

type GetByIDsInput

type GetByIDsInput struct {
	Namespace string
	IDs       []string

	Expands meta.Expands
}

func (GetByIDsInput) Validate

func (i GetByIDsInput) Validate() error

type GetByMetasInput

type GetByMetasInput struct {
	Namespace string
	Expands   meta.Expands
	Charges   meta.Charges
}

func (GetByMetasInput) Validate

func (i GetByMetasInput) Validate() error

type Handler

type Handler interface {
	// OnAllocateCredits is called when a flat fee allocates credits.
	OnAllocateCredits(ctx context.Context, input OnAllocateCreditsInput) (creditrealization.CreateAllocationInputs, error)

	// OnFlatFeeStandardInvoiceUsageAccrued is called when the remaining usage is sent to the customer on a standard invoice.
	OnInvoiceUsageAccrued(ctx context.Context, input OnInvoiceUsageAccruedInput) (ledgertransaction.GroupReference, error)

	// OnCorrectCreditAllocations is called when a credit allocation needs to be corrected.
	OnCorrectCreditAllocations(ctx context.Context, input CorrectCreditAllocationsInput) (creditrealization.CreateCorrectionInputs, error)

	// OnFlatFeePaymentAuthorized is called when a flat fee payment is authorized.
	OnPaymentAuthorized(ctx context.Context, input OnPaymentAuthorizedInput) (ledgertransaction.GroupReference, error)

	// OnFlatFeePaymentSettled is called when a flat fee payment is settled.
	OnPaymentSettled(ctx context.Context, input OnPaymentSettledInput) (ledgertransaction.GroupReference, error)

	// OnFlatFeePaymentUncollectible is called when a flat fee payment is uncollectible
	OnPaymentUncollectible(ctx context.Context, charge Charge) (ledgertransaction.GroupReference, error)
}

type Intent

type Intent struct {
	meta.Intent
	IntentMutableFields `json:"intentMutableFields"`
	SettlementMode      productcatalog.SettlementMode `json:"settlementMode"`
	FeatureKey          *string                       `json:"featureKey,omitempty"`
}

func (Intent) AsOverridableIntent

func (i Intent) AsOverridableIntent() OverridableIntent

AsOverridableIntent maps the intent's mutable fields as the base layer.

func (Intent) CalculateAmountAfterProration

func (i Intent) CalculateAmountAfterProration() (alpacadecimal.Decimal, error)

CalculateAmountAfterProration computes the prorated amount from AmountBeforeProration, ServicePeriod, and FullServicePeriod. Returns AmountBeforeProration when proration is not applicable (disabled, unsupported mode, or zero-length periods).

func (Intent) Normalized

func (i Intent) Normalized() Intent

func (Intent) Validate

func (i Intent) Validate() error

type IntentMutableFields

type IntentMutableFields struct {
	meta.IntentMutableFields

	// IntentDeletedAt marks the flat-fee base/original intent as deleted.
	// Adapters derive the effective charge DeletedAt from this value when no intent override is present.
	IntentDeletedAt *time.Time `json:"intentDeletedAt,omitempty"`

	InvoiceAt           time.Time                      `json:"invoiceAt"`
	PaymentTerm         productcatalog.PaymentTermType `json:"paymentTerm"`
	PercentageDiscounts *billing.PercentageDiscount    `json:"percentageDiscounts"`

	ProRating             productcatalog.ProRatingConfig `json:"proRating"`
	AmountBeforeProration alpacadecimal.Decimal          `json:"amountBeforeProration"`
}

func (IntentMutableFields) Clone

func (IntentMutableFields) Normalized

func (f IntentMutableFields) Normalized(currency currencyx.Code) IntentMutableFields

func (IntentMutableFields) Validate

func (f IntentMutableFields) Validate() error

type IntentWithInitialStatus

type IntentWithInitialStatus struct {
	Intent Intent

	FeatureID                 *string
	InitialStatus             Status
	InitialAdvanceAfter       *time.Time
	AmountAfterProration      alpacadecimal.Decimal
	NoFiatTransactionRequired bool
}

func (IntentWithInitialStatus) Validate

func (i IntentWithInitialStatus) Validate() error

type OnAllocateCreditsInput

type OnAllocateCreditsInput struct {
	Charge        Charge                `json:"charge"`
	ServicePeriod timeutil.ClosedPeriod `json:"servicePeriod"`
	BookedAt      time.Time             `json:"bookedAt"`
	// PreTaxAmountToAllocate is the pre-tax amount to allocate from credits.
	// The input charge's settlement mode governs whether this may create a negative balance.
	PreTaxAmountToAllocate alpacadecimal.Decimal `json:"preTaxAmountToAllocate"`
}

func (OnAllocateCreditsInput) Validate

func (i OnAllocateCreditsInput) Validate() error

type OnInvoiceUsageAccruedInput

type OnInvoiceUsageAccruedInput struct {
	Charge        Charge                `json:"charge"`
	ServicePeriod timeutil.ClosedPeriod `json:"servicePeriod"`
	BookedAt      time.Time             `json:"bookedAt"`
	Totals        totals.Totals         `json:"totals"`
}

func (OnInvoiceUsageAccruedInput) Validate

func (i OnInvoiceUsageAccruedInput) Validate() error

type OnPaymentAuthorizedInput

type OnPaymentAuthorizedInput = PaymentEventInput

type OnPaymentSettledInput

type OnPaymentSettledInput = PaymentEventInput

type OverridableIntent

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

OverridableIntent stores the immutable intent plus the base and optional override mutable layers. Direct layer access is error-prone because callers must manually decide which layer is active; this API centralizes that choice so reads and mutations use the correct override layer when present.

func NewOverridableIntent

func NewOverridableIntent(baseIntent Intent, overrideLayer *IntentMutableFields) OverridableIntent

func (OverridableIntent) CalculateAmountAfterProration

func (i OverridableIntent) CalculateAmountAfterProration() (alpacadecimal.Decimal, error)

func (OverridableIntent) GetBaseIntent

func (i OverridableIntent) GetBaseIntent() Intent

func (OverridableIntent) GetBaseManagedBy

func (i OverridableIntent) GetBaseManagedBy() billing.InvoiceLineManagedBy

func (OverridableIntent) GetCurrency

func (i OverridableIntent) GetCurrency() currencyx.Code

func (OverridableIntent) GetCustomerID

func (i OverridableIntent) GetCustomerID() string

func (OverridableIntent) GetDeletedAt

func (i OverridableIntent) GetDeletedAt() *time.Time

func (OverridableIntent) GetEffectiveIntent

func (i OverridableIntent) GetEffectiveIntent() Intent

GetEffectiveIntent returns the customer-facing intent by combining the immutable intent with the active mutable layer.

WARNING: this clones and normalizes the intent and mutable fields. Prefer the narrower effective getters when only a few fields are required.

func (OverridableIntent) GetEffectiveInvoiceAt

func (i OverridableIntent) GetEffectiveInvoiceAt() time.Time

GetEffectiveInvoiceAt returns the invoice-at timestamp from the active mutable layer, preferring the override layer when it is present.

func (OverridableIntent) GetEffectiveMetaIntentMutableFields

func (i OverridableIntent) GetEffectiveMetaIntentMutableFields() meta.IntentMutableFields

GetEffectiveMetaIntentMutableFields returns the shared meta mutable fields from the active mutable layer, preferring the override layer when it is present.

func (OverridableIntent) GetEffectivePaymentTerm

func (i OverridableIntent) GetEffectivePaymentTerm() productcatalog.PaymentTermType

GetEffectivePaymentTerm returns the payment term from the active mutable layer, preferring the override layer when it is present.

func (OverridableIntent) GetEffectiveServicePeriod

func (i OverridableIntent) GetEffectiveServicePeriod() timeutil.ClosedPeriod

GetEffectiveServicePeriod returns the service period from the active mutable layer, preferring the override layer when it is present.

func (OverridableIntent) GetFeatureKey

func (i OverridableIntent) GetFeatureKey() string

GetFeatureKey returns the immutable flat-fee feature key from the base intent. Override layers cannot change feature attribution.

func (OverridableIntent) GetIntentForTarget

func (i OverridableIntent) GetIntentForTarget(target meta.ChangeTarget) (Intent, error)

func (OverridableIntent) GetOverrideLayerMutableFields

func (i OverridableIntent) GetOverrideLayerMutableFields() *IntentMutableFields

func (OverridableIntent) GetSettlementMode

func (i OverridableIntent) GetSettlementMode() productcatalog.SettlementMode

func (OverridableIntent) GetSubscription

func (i OverridableIntent) GetSubscription() *meta.SubscriptionReference

func (OverridableIntent) GetTaxConfig

GetTaxConfig returns the immutable tax config from the base intent. Override layers cannot change tax attribution.

func (OverridableIntent) GetUniqueReferenceID

func (i OverridableIntent) GetUniqueReferenceID() *string

func (OverridableIntent) HasOverrideLayer

func (i OverridableIntent) HasOverrideLayer() bool

func (*OverridableIntent) Mutate

func (i *OverridableIntent) Mutate(target meta.ChangeTarget, editFn func(*IntentMutableFields)) error

Mutate edits the requested intent mutable field layer.

The callback always receives a non-nil pointer to a cloned mutable-field value. The clone is written back only after it normalizes and validates, so validation errors do not partially mutate the intent.

func (*OverridableIntent) MutateEffective

func (i *OverridableIntent) MutateEffective(editFn func(*IntentMutableFields)) error

func (OverridableIntent) Normalized

func (i OverridableIntent) Normalized() OverridableIntent

func (OverridableIntent) Validate

func (i OverridableIntent) Validate() error

type PaymentEventInput

type PaymentEventInput struct {
	Charge  Charge                `json:"charge"`
	EventAt time.Time             `json:"eventAt"`
	Amount  alpacadecimal.Decimal `json:"amount"`
}

func (PaymentEventInput) Validate

func (i PaymentEventInput) Validate() error

type ProRatingModeAdapterEnum

type ProRatingModeAdapterEnum string
const (
	ProratePricesProratingAdapterMode ProRatingModeAdapterEnum = ProRatingModeAdapterEnum(productcatalog.ProRatingModeProratePrices)
	NoProratingAdapterMode            ProRatingModeAdapterEnum = "no_prorate"
)

func (ProRatingModeAdapterEnum) Values

func (e ProRatingModeAdapterEnum) Values() []string

type RealizationRun

type RealizationRun struct {
	RealizationRunBase

	CreditRealizations creditrealization.Realizations `json:"creditRealizations"`
	AccruedUsage       *invoicedusage.AccruedUsage    `json:"accruedUsage"`
	Payment            *payment.Invoiced              `json:"payment"`
	DetailedLines      mo.Option[DetailedLines]       `json:"detailedLines,omitzero"`
}

func (RealizationRun) IsVoidedBillingHistory

func (r RealizationRun) IsVoidedBillingHistory() bool

IsVoidedBillingHistory reports whether this run must be ignored as billing history. Deleted runs were already cleaned up through billing; unsupported credit-note runs are retained for audit even though the invoice line should have been removed once prorating/credit-note support exists.

func (RealizationRun) Validate

func (r RealizationRun) Validate() error

type RealizationRunBase

type RealizationRunBase struct {
	ID RealizationRunID `json:"id"`
	models.ManagedModel

	LineID    *string `json:"lineId,omitempty"`
	InvoiceID *string `json:"invoiceId,omitempty"`

	Type        RealizationRunType `json:"type"`
	InitialType RealizationRunType `json:"initialType"`

	ServicePeriod             timeutil.ClosedPeriod `json:"servicePeriod"`
	AmountAfterProration      alpacadecimal.Decimal `json:"amountAfterProration"`
	Totals                    totals.Totals         `json:"totals"`
	NoFiatTransactionRequired bool                  `json:"noFiatTransactionRequired"`
	// Immutable means the backing invoice line can no longer be updated in place.
	// When true, deleting this run requires issuing a credit note instead of mutating the invoice line.
	Immutable bool `json:"immutable"`
}

func (RealizationRunBase) Normalized

func (r RealizationRunBase) Normalized() RealizationRunBase

func (RealizationRunBase) Validate

func (r RealizationRunBase) Validate() error

type RealizationRunID

type RealizationRunID models.NamespacedID

func (RealizationRunID) Validate

func (i RealizationRunID) Validate() error

type RealizationRunType

type RealizationRunType string
const (
	RealizationRunTypeFinalRealization                  RealizationRunType = "final_realization"
	RealizationRunTypeInvalidDueToUnsupportedCreditNote RealizationRunType = "invalid_due_to_unsupported_credit_note"
)

func (RealizationRunType) IsVoidedBillingHistory

func (t RealizationRunType) IsVoidedBillingHistory() bool

func (RealizationRunType) Validate

func (t RealizationRunType) Validate() error

func (RealizationRunType) Values

func (t RealizationRunType) Values() []string

type RealizationRuns

type RealizationRuns []RealizationRun

func (RealizationRuns) Validate

func (r RealizationRuns) Validate() error

type Realizations

type Realizations struct {
	CurrentRun *RealizationRun `json:"currentRun,omitempty"`
	PriorRuns  RealizationRuns `json:"priorRuns,omitempty"`
}

func (Realizations) GetByLineID

func (r Realizations) GetByLineID(lineID string) (RealizationRun, error)

func (Realizations) Validate

func (r Realizations) Validate() error

type Service

type Service interface {
	FlatFeeService
	GetLineEngine() billing.LineEngine
}

type State

type State struct {
	AdvanceAfter         *time.Time            `json:"advanceAfter,omitempty"`
	FeatureID            *string               `json:"featureId,omitempty"`
	AmountAfterProration alpacadecimal.Decimal `json:"amountAfterProration"`
}

func (State) Normalized

func (s State) Normalized() State

func (State) Validate

func (s State) Validate() error

type Status

type Status string
const (
	StatusCreated Status = Status(meta.ChargeStatusCreated)
	StatusActive  Status = Status(meta.ChargeStatusActive)

	StatusActiveRealizationStarted              Status = "active.realization.started"
	StatusActiveRealizationWaitingForCollection Status = "active.realization.waiting_for_collection"
	StatusActiveRealizationProcessing           Status = "active.realization.processing"
	StatusActiveRealizationIssuing              Status = "active.realization.issuing"
	StatusActiveRealizationCompleted            Status = "active.realization.completed"
	StatusActiveAwaitingPaymentSettlement       Status = "active.awaiting_payment_settlement"

	StatusFinal   Status = Status(meta.ChargeStatusFinal)
	StatusDeleted Status = Status(meta.ChargeStatusDeleted)
)

func (Status) ToMetaChargeStatus

func (s Status) ToMetaChargeStatus() (meta.ChargeStatus, error)

func (Status) Validate

func (s Status) Validate() error

func (Status) Values

func (Status) Values() []string

type UpdateRealizationRunInput

type UpdateRealizationRunInput struct {
	ID RealizationRunID

	Type                      mo.Option[RealizationRunType]    `json:"type"`
	DeletedAt                 mo.Option[*time.Time]            `json:"deletedAt,omitempty"`
	LineID                    mo.Option[*string]               `json:"lineId,omitempty"`
	InvoiceID                 mo.Option[*string]               `json:"invoiceId,omitempty"`
	ServicePeriod             mo.Option[timeutil.ClosedPeriod] `json:"servicePeriod"`
	AmountAfterProration      mo.Option[alpacadecimal.Decimal] `json:"amountAfterProration"`
	Totals                    mo.Option[totals.Totals]         `json:"totals"`
	NoFiatTransactionRequired mo.Option[bool]                  `json:"noFiatTransactionRequired"`
	Immutable                 mo.Option[bool]                  `json:"immutable"`
}

func (UpdateRealizationRunInput) Normalized

func (UpdateRealizationRunInput) Validate

func (r UpdateRealizationRunInput) Validate() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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