billing

package
v0.0.0-...-1064994 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: AGPL-3.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Account

type Account struct {
	BillingAccountID  string          `json:"billing_account_id"`
	OrgID             string          `json:"org_id"`
	Name              string          `json:"name"`
	Status            string          `json:"status"`
	Metadata          json.RawMessage `json:"metadata"`
	CreatedAt         time.Time       `json:"created_at"`
	UpdatedAt         time.Time       `json:"updated_at"`
	NextInvoiceNumber int32           `json:"next_invoice_number"`
}

type ConvergeInvoiceParams

type ConvergeInvoiceParams struct {
	IssuedAt       sql.NullTime  `json:"issued_at"`
	PaidAt         sql.NullTime  `json:"paid_at"`
	VoidedAt       sql.NullTime  `json:"voided_at"`
	SubscriptionID uuid.NullUUID `json:"subscription_id"`
	Status         string        `json:"status"`
	InvoiceID      string        `json:"invoice_id"`
	AmountDue      int32         `json:"amount_due"`
	AmountPaid     int32         `json:"amount_paid"`
	DueDate        sql.NullTime  `json:"due_date"`
}

type CoreProductShape

type CoreProductShape struct {
	ProductID        string      `json:"product_id"`
	LifecycleStatus  string      `json:"lifecycle_status"`
	IsPublic         bool        `json:"is_public"`
	SetPresent       interface{} `json:"set_present"`
	LadderCount      int64       `json:"ladder_count"`
	BillingShape     string      `json:"billing_shape"`
	ConsumptionShape string      `json:"consumption_shape"`
	ActiveRuleCount  int64       `json:"active_rule_count"`
	PerUnitRuleCount int64       `json:"per_unit_rule_count"`
}

type CountBillingAccountsPageParams

type CountBillingAccountsPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	ExcludeIds []string       `json:"exclude_ids"`
}

type CountInvoicesPageParams

type CountInvoicesPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	InvoiceIds []string       `json:"invoice_ids"`
	Status     sql.NullString `json:"status"`
	ExcludeIds []string       `json:"exclude_ids"`
}

type CountLiveSubscriptionsByStatusRow

type CountLiveSubscriptionsByStatusRow struct {
	ActiveCount   int64 `json:"active_count"`
	TrialingCount int64 `json:"trialing_count"`
}

type CountPaymentsPageParams

type CountPaymentsPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	ExcludeIds []string       `json:"exclude_ids"`
}

type CountSubscriptionsPageParams

type CountSubscriptionsPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	Status     sql.NullString `json:"status"`
	ExcludeIds []string       `json:"exclude_ids"`
}

type CreateBillingAccountParams

type CreateBillingAccountParams struct {
	OrgID    string          `json:"org_id"`
	Name     string          `json:"name"`
	Status   string          `json:"status"`
	Metadata json.RawMessage `json:"metadata"`
}

type CreateInvoiceLineItemParams

type CreateInvoiceLineItemParams struct {
	InvoiceID          string         `json:"invoice_id"`
	SubscriptionItemID uuid.NullUUID  `json:"subscription_item_id"`
	PriceID            string         `json:"price_id"`
	Amount             int32          `json:"amount"`
	Currency           string         `json:"currency"`
	Description        sql.NullString `json:"description"`
	Quantity           int32          `json:"quantity"`
	PeriodStart        sql.NullTime   `json:"period_start"`
	PeriodEnd          sql.NullTime   `json:"period_end"`
}

type CreateInvoiceParams

type CreateInvoiceParams struct {
	BillingAccountID string         `json:"billing_account_id"`
	SubscriptionID   uuid.NullUUID  `json:"subscription_id"`
	Status           string         `json:"status"`
	AmountDue        int32          `json:"amount_due"`
	AmountPaid       int32          `json:"amount_paid"`
	Currency         string         `json:"currency"`
	PeriodStart      sql.NullTime   `json:"period_start"`
	PeriodEnd        sql.NullTime   `json:"period_end"`
	DueDate          sql.NullTime   `json:"due_date"`
	InvoiceNumber    sql.NullString `json:"invoice_number"`
	IssuedAt         sql.NullTime   `json:"issued_at"`
	PaidAt           sql.NullTime   `json:"paid_at"`
	VoidedAt         sql.NullTime   `json:"voided_at"`
}

type CreatePaymentMethodParams

type CreatePaymentMethodParams struct {
	BillingAccountID string         `json:"billing_account_id"`
	PmType           string         `json:"pm_type"`
	CardBrand        sql.NullString `json:"card_brand"`
	CardLast4        sql.NullString `json:"card_last4"`
	CardExpMonth     sql.NullInt32  `json:"card_exp_month"`
	CardExpYear      sql.NullInt32  `json:"card_exp_year"`
	Funding          sql.NullString `json:"funding"`
	IsDefault        bool           `json:"is_default"`
}

type CreatePaymentParams

type CreatePaymentParams struct {
	InvoiceID        string        `json:"invoice_id"`
	BillingAccountID string        `json:"billing_account_id"`
	PaymentMethodID  uuid.NullUUID `json:"payment_method_id"`
	Amount           int32         `json:"amount"`
	Currency         string        `json:"currency"`
	Status           string        `json:"status"`
	PaidAt           sql.NullTime  `json:"paid_at"`
	FailedAt         sql.NullTime  `json:"failed_at"`
}

type CreatePlanLadderParams

type CreatePlanLadderParams struct {
	Name        string         `json:"name"`
	Description sql.NullString `json:"description"`
	IsActive    bool           `json:"is_active"`
	Key         sql.NullString `json:"key"`
}

type CreatePlanLadderTierParams

type CreatePlanLadderTierParams struct {
	PlanLadderID string `json:"plan_ladder_id"`
	ProductID    string `json:"product_id"`
}

type CreatePriceParams

type CreatePriceParams struct {
	ProductID         string         `json:"product_id"`
	Currency          string         `json:"currency"`
	UnitAmount        int32          `json:"unit_amount"`
	RecurringInterval sql.NullString `json:"recurring_interval"`
	TrialPeriodDays   sql.NullInt32  `json:"trial_period_days"`
	Key               sql.NullString `json:"key"`
}

type CreateProductParams

type CreateProductParams struct {
	Name             string         `json:"name"`
	Description      sql.NullString `json:"description"`
	DisplayCategory  sql.NullString `json:"display_category"`
	IsActive         bool           `json:"is_active"`
	IsPublic         bool           `json:"is_public"`
	EntitlementSetID uuid.NullUUID  `json:"entitlement_set_id"`
	LifecycleStatus  string         `json:"lifecycle_status"`
	Key              sql.NullString `json:"key"`
}

type CreateScheduledChangeParams

type CreateScheduledChangeParams struct {
	SubscriptionID    string         `json:"subscription_id"`
	ChangeType        string         `json:"change_type"`
	TargetPriceID     uuid.NullUUID  `json:"target_price_id"`
	TargetQuantity    sql.NullInt32  `json:"target_quantity"`
	EffectiveAt       time.Time      `json:"effective_at"`
	EffectiveTrigger  string         `json:"effective_trigger"`
	CreditDisposition sql.NullString `json:"credit_disposition"`
}

type CreateSubscriptionChangeParams

type CreateSubscriptionChangeParams struct {
	SubscriptionID string         `json:"subscription_id"`
	PreviousStatus sql.NullString `json:"previous_status"`
	NewStatus      string         `json:"new_status"`
	StripeEventID  string         `json:"stripe_event_id"`
}

type CreateSubscriptionItemParams

type CreateSubscriptionItemParams struct {
	SubscriptionID string `json:"subscription_id"`
	ProductID      string `json:"product_id"`
	PriceID        string `json:"price_id"`
	Quantity       int32  `json:"quantity"`
}

type CreateSubscriptionParams

type CreateSubscriptionParams struct {
	BillingAccountID   string       `json:"billing_account_id"`
	Status             string       `json:"status"`
	CurrentPeriodStart sql.NullTime `json:"current_period_start"`
	CurrentPeriodEnd   sql.NullTime `json:"current_period_end"`
}

type DBTX

type DBTX interface {
	ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
	PrepareContext(context.Context, string) (*sql.Stmt, error)
	QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
	QueryRowContext(context.Context, string, ...interface{}) *sql.Row
}

type DeleteTierParams

type DeleteTierParams struct {
	PlanLadderID string `json:"plan_ladder_id"`
	ProductID    string `json:"product_id"`
}

type EnsurePlanLadderTierParams

type EnsurePlanLadderTierParams struct {
	PlanLadderID string `json:"plan_ladder_id"`
	ProductID    string `json:"product_id"`
}

type GetInvoicesByNumberRow

type GetInvoicesByNumberRow struct {
	InvoiceID        string         `json:"invoice_id"`
	BillingAccountID string         `json:"billing_account_id"`
	OrgID            string         `json:"org_id"`
	InvoiceNumber    sql.NullString `json:"invoice_number"`
	IssuedAt         sql.NullTime   `json:"issued_at"`
}

type GetPriceByProductAndKeyParams

type GetPriceByProductAndKeyParams struct {
	ProductID string         `json:"product_id"`
	Key       sql.NullString `json:"key"`
}

type GetTierByLadderRankParams

type GetTierByLadderRankParams struct {
	PlanLadderID string `json:"plan_ladder_id"`
	Rank         int32  `json:"rank"`
}

type Invoice

type Invoice struct {
	InvoiceID        string         `json:"invoice_id"`
	BillingAccountID string         `json:"billing_account_id"`
	SubscriptionID   uuid.NullUUID  `json:"subscription_id"`
	Status           string         `json:"status"`
	AmountDue        int32          `json:"amount_due"`
	AmountPaid       int32          `json:"amount_paid"`
	Currency         string         `json:"currency"`
	PeriodStart      sql.NullTime   `json:"period_start"`
	PeriodEnd        sql.NullTime   `json:"period_end"`
	DueDate          sql.NullTime   `json:"due_date"`
	PaidAt           sql.NullTime   `json:"paid_at"`
	VoidedAt         sql.NullTime   `json:"voided_at"`
	CreatedAt        time.Time      `json:"created_at"`
	UpdatedAt        time.Time      `json:"updated_at"`
	InvoiceNumber    sql.NullString `json:"invoice_number"`
	IssuedAt         sql.NullTime   `json:"issued_at"`
}

type InvoiceLineItem

type InvoiceLineItem struct {
	LineItemID         string         `json:"line_item_id"`
	InvoiceID          string         `json:"invoice_id"`
	SubscriptionItemID uuid.NullUUID  `json:"subscription_item_id"`
	PriceID            string         `json:"price_id"`
	Amount             int32          `json:"amount"`
	Currency           string         `json:"currency"`
	Description        sql.NullString `json:"description"`
	Quantity           int32          `json:"quantity"`
	PeriodStart        sql.NullTime   `json:"period_start"`
	PeriodEnd          sql.NullTime   `json:"period_end"`
	CreatedAt          time.Time      `json:"created_at"`
	UpdatedAt          time.Time      `json:"updated_at"`
}

type ListBillingAccountsPageParams

type ListBillingAccountsPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	ExcludeIds []string       `json:"exclude_ids"`
	PageOffset int32          `json:"page_offset"`
	PageLimit  int32          `json:"page_limit"`
}

type ListBillingAccountsPageRow

type ListBillingAccountsPageRow struct {
	BillingAccountID string          `json:"billing_account_id"`
	OrgID            string          `json:"org_id"`
	Name             string          `json:"name"`
	Status           string          `json:"status"`
	Metadata         json.RawMessage `json:"metadata"`
	CreatedAt        time.Time       `json:"created_at"`
	UpdatedAt        time.Time       `json:"updated_at"`
	TotalCount       int64           `json:"total_count"`
}

type ListCurrentConferringProductsBySubscriptionIDsRow

type ListCurrentConferringProductsBySubscriptionIDsRow struct {
	SubscriptionID string `json:"subscription_id"`
	ProductID      string `json:"product_id"`
}

type ListCurrentSubscriptionItemsByBillingAccountIDRow

type ListCurrentSubscriptionItemsByBillingAccountIDRow struct {
	SubscriptionID string `json:"subscription_id"`
	ProductID      string `json:"product_id"`
}

type ListCurrentSubscriptionItemsBySubscriptionIDsRow

type ListCurrentSubscriptionItemsBySubscriptionIDsRow struct {
	SubscriptionID string `json:"subscription_id"`
	ProductID      string `json:"product_id"`
}

type ListInvoicesPageParams

type ListInvoicesPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	InvoiceIds []string       `json:"invoice_ids"`
	Status     sql.NullString `json:"status"`
	ExcludeIds []string       `json:"exclude_ids"`
	PageOffset int32          `json:"page_offset"`
	PageLimit  int32          `json:"page_limit"`
}

type ListInvoicesPageRow

type ListInvoicesPageRow struct {
	InvoiceID          string         `json:"invoice_id"`
	BillingAccountID   string         `json:"billing_account_id"`
	OrgID              string         `json:"org_id"`
	SubscriptionID     uuid.NullUUID  `json:"subscription_id"`
	Status             string         `json:"status"`
	AmountDue          int32          `json:"amount_due"`
	AmountPaid         int32          `json:"amount_paid"`
	Currency           string         `json:"currency"`
	PeriodStart        sql.NullTime   `json:"period_start"`
	PeriodEnd          sql.NullTime   `json:"period_end"`
	DueDate            sql.NullTime   `json:"due_date"`
	IssuedAt           sql.NullTime   `json:"issued_at"`
	PaidAt             sql.NullTime   `json:"paid_at"`
	VoidedAt           sql.NullTime   `json:"voided_at"`
	InvoiceNumber      sql.NullString `json:"invoice_number"`
	UpdatedAt          time.Time      `json:"updated_at"`
	BillingAccountName string         `json:"billing_account_name"`
	TotalCount         int64          `json:"total_count"`
}

type ListLaddersByProductRow

type ListLaddersByProductRow struct {
	PlanLadderID string    `json:"plan_ladder_id"`
	ProductID    string    `json:"product_id"`
	Rank         int32     `json:"rank"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	LadderName   string    `json:"ladder_name"`
}

type ListPaymentsPageParams

type ListPaymentsPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	ExcludeIds []string       `json:"exclude_ids"`
	PageOffset int32          `json:"page_offset"`
	PageLimit  int32          `json:"page_limit"`
}

type ListPaymentsPageRow

type ListPaymentsPageRow struct {
	PaymentID          string         `json:"payment_id"`
	InvoiceID          string         `json:"invoice_id"`
	BillingAccountID   string         `json:"billing_account_id"`
	OrgID              string         `json:"org_id"`
	PaymentMethodID    uuid.NullUUID  `json:"payment_method_id"`
	Amount             int32          `json:"amount"`
	Currency           string         `json:"currency"`
	Status             string         `json:"status"`
	PaidAt             sql.NullTime   `json:"paid_at"`
	FailedAt           sql.NullTime   `json:"failed_at"`
	UpdatedAt          time.Time      `json:"updated_at"`
	BillingAccountName string         `json:"billing_account_name"`
	PaymentMethodType  sql.NullString `json:"payment_method_type"`
	CardBrand          sql.NullString `json:"card_brand"`
	CardLast4          sql.NullString `json:"card_last4"`
	InvoiceNumber      sql.NullString `json:"invoice_number"`
	TotalCount         int64          `json:"total_count"`
}

type ListPlanLadderNamesByIDsRow

type ListPlanLadderNamesByIDsRow struct {
	PlanLadderID string `json:"plan_ladder_id"`
	Name         string `json:"name"`
}

type ListPlanLaddersWithRankZeroProductRow

type ListPlanLaddersWithRankZeroProductRow struct {
	PlanLadderID        string         `json:"plan_ladder_id"`
	LadderName          string         `json:"ladder_name"`
	IsActive            bool           `json:"is_active"`
	ProductID           uuid.NullUUID  `json:"product_id"`
	RankZeroProductName sql.NullString `json:"rank_zero_product_name"`
}

type ListProductNamesByIDsRow

type ListProductNamesByIDsRow struct {
	ProductID string `json:"product_id"`
	Name      string `json:"name"`
}

type ListProductsByNameCIParams

type ListProductsByNameCIParams struct {
	Name             string        `json:"name"`
	ExcludeProductID uuid.NullUUID `json:"exclude_product_id"`
}

type ListProductsByNameCIRow

type ListProductsByNameCIRow struct {
	ProductID  string         `json:"product_id"`
	Name       string         `json:"name"`
	IsActive   bool           `json:"is_active"`
	LadderID   uuid.NullUUID  `json:"ladder_id"`
	LadderName sql.NullString `json:"ladder_name"`
}

type ListProductsPageParams

type ListProductsPageParams struct {
	Q               sql.NullString `json:"q"`
	LifecycleStatus sql.NullString `json:"lifecycle_status"`
	PageOffset      int32          `json:"page_offset"`
	PageLimit       int32          `json:"page_limit"`
}

type ListProductsPageRow

type ListProductsPageRow struct {
	ProductID        string                `json:"product_id"`
	Name             string                `json:"name"`
	Description      sql.NullString        `json:"description"`
	DisplayCategory  sql.NullString        `json:"display_category"`
	Metadata         pqtype.NullRawMessage `json:"metadata"`
	IsActive         bool                  `json:"is_active"`
	IsPublic         bool                  `json:"is_public"`
	CreatedAt        time.Time             `json:"created_at"`
	UpdatedAt        time.Time             `json:"updated_at"`
	EntitlementSetID uuid.NullUUID         `json:"entitlement_set_id"`
	LifecycleStatus  string                `json:"lifecycle_status"`
	Key              sql.NullString        `json:"key"`
	TotalCount       int64                 `json:"total_count"`
}

type ListRecentInvoicesRow

type ListRecentInvoicesRow struct {
	InvoiceID        string       `json:"invoice_id"`
	BillingAccountID string       `json:"billing_account_id"`
	OrgID            string       `json:"org_id"`
	AmountDue        int32        `json:"amount_due"`
	AmountPaid       int32        `json:"amount_paid"`
	Currency         string       `json:"currency"`
	Status           string       `json:"status"`
	IssuedAt         sql.NullTime `json:"issued_at"`
	TotalCount       int64        `json:"total_count"`
}

type ListRecentPaymentsRow

type ListRecentPaymentsRow struct {
	PaymentID        string       `json:"payment_id"`
	InvoiceID        string       `json:"invoice_id"`
	BillingAccountID string       `json:"billing_account_id"`
	OrgID            string       `json:"org_id"`
	Amount           int32        `json:"amount"`
	Currency         string       `json:"currency"`
	Status           string       `json:"status"`
	PaidAt           sql.NullTime `json:"paid_at"`
	FailedAt         sql.NullTime `json:"failed_at"`
	TotalCount       int64        `json:"total_count"`
}

type ListSharedTierProductsRow

type ListSharedTierProductsRow struct {
	ProductID    string `json:"product_id"`
	ProductName  string `json:"product_name"`
	PlanLadderID string `json:"plan_ladder_id"`
	LadderName   string `json:"ladder_name"`
	Rank         int32  `json:"rank"`
}

type ListSubscriptionRungsByOrgRow

type ListSubscriptionRungsByOrgRow struct {
	SubscriptionID          string         `json:"subscription_id"`
	Status                  string         `json:"status"`
	CurrentPeriodEnd        sql.NullTime   `json:"current_period_end"`
	CancelAtPeriodEnd       bool           `json:"cancel_at_period_end"`
	PauseCollectionBehavior sql.NullString `json:"pause_collection_behavior"`
	PauseCollectionMarked   bool           `json:"pause_collection_marked"`
	CancellationAt          sql.NullTime   `json:"cancellation_at"`
	DowngradeAt             sql.NullTime   `json:"downgrade_at"`
	DowngradeProductID      uuid.NullUUID  `json:"downgrade_product_id"`
	DowngradeProductName    sql.NullString `json:"downgrade_product_name"`
	ProductID               string         `json:"product_id"`
	PriceID                 string         `json:"price_id"`
	UnitAmount              int32          `json:"unit_amount"`
	Currency                string         `json:"currency"`
	RecurringInterval       sql.NullString `json:"recurring_interval"`
	PlanLadderID            string         `json:"plan_ladder_id"`
	Rank                    int32          `json:"rank"`
}

type ListSubscriptionsPageParams

type ListSubscriptionsPageParams struct {
	Q          sql.NullString `json:"q"`
	OrgIds     []string       `json:"org_ids"`
	Status     sql.NullString `json:"status"`
	ExcludeIds []string       `json:"exclude_ids"`
	PageOffset int32          `json:"page_offset"`
	PageLimit  int32          `json:"page_limit"`
}

type ListSubscriptionsPageRow

type ListSubscriptionsPageRow struct {
	SubscriptionID          string         `json:"subscription_id"`
	BillingAccountID        string         `json:"billing_account_id"`
	OrgID                   string         `json:"org_id"`
	Status                  string         `json:"status"`
	CurrentPeriodStart      sql.NullTime   `json:"current_period_start"`
	CurrentPeriodEnd        sql.NullTime   `json:"current_period_end"`
	CancelAtPeriodEnd       bool           `json:"cancel_at_period_end"`
	PauseCollectionBehavior sql.NullString `json:"pause_collection_behavior"`
	CanceledAt              sql.NullTime   `json:"canceled_at"`
	EndedAt                 sql.NullTime   `json:"ended_at"`
	CreatedAt               time.Time      `json:"created_at"`
	UpdatedAt               time.Time      `json:"updated_at"`
	BillingAccountName      string         `json:"billing_account_name"`
	TotalCount              int64          `json:"total_count"`
}

type ListTiersByLadderWithProductsRow

type ListTiersByLadderWithProductsRow struct {
	PlanLadderID    string         `json:"plan_ladder_id"`
	ProductID       string         `json:"product_id"`
	Rank            int32          `json:"rank"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	ProductName     string         `json:"product_name"`
	DisplayCategory sql.NullString `json:"display_category"`
	LifecycleStatus string         `json:"lifecycle_status"`
}

type ListTiersWithProductsByLadderIDsRow

type ListTiersWithProductsByLadderIDsRow struct {
	PlanLadderID    string         `json:"plan_ladder_id"`
	ProductID       string         `json:"product_id"`
	Rank            int32          `json:"rank"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	ProductName     string         `json:"product_name"`
	DisplayCategory sql.NullString `json:"display_category"`
	LifecycleStatus string         `json:"lifecycle_status"`
}

type LockPlanLadderOrderRow

type LockPlanLadderOrderRow struct {
	PlanLadderID string `json:"plan_ladder_id"`
	SortOrder    int32  `json:"sort_order"`
}

type MarkDefaultPriceParams

type MarkDefaultPriceParams struct {
	PriceID   string `json:"price_id"`
	ProductID string `json:"product_id"`
}

type MarkPaymentSucceededParams

type MarkPaymentSucceededParams struct {
	PaidAt    sql.NullTime `json:"paid_at"`
	PaymentID string       `json:"payment_id"`
}

type Payment

type Payment struct {
	PaymentID        string        `json:"payment_id"`
	InvoiceID        string        `json:"invoice_id"`
	BillingAccountID string        `json:"billing_account_id"`
	PaymentMethodID  uuid.NullUUID `json:"payment_method_id"`
	Amount           int32         `json:"amount"`
	Currency         string        `json:"currency"`
	Status           string        `json:"status"`
	FailedAt         sql.NullTime  `json:"failed_at"`
	CreatedAt        time.Time     `json:"created_at"`
	UpdatedAt        time.Time     `json:"updated_at"`
	PaidAt           sql.NullTime  `json:"paid_at"`
}

type PaymentMethod

type PaymentMethod struct {
	PaymentMethodID  string         `json:"payment_method_id"`
	BillingAccountID string         `json:"billing_account_id"`
	PmType           string         `json:"pm_type"`
	CardBrand        sql.NullString `json:"card_brand"`
	CardLast4        sql.NullString `json:"card_last4"`
	CardExpMonth     sql.NullInt32  `json:"card_exp_month"`
	CardExpYear      sql.NullInt32  `json:"card_exp_year"`
	Funding          sql.NullString `json:"funding"`
	IsDefault        bool           `json:"is_default"`
	DetachedAt       sql.NullTime   `json:"detached_at"`
	CreatedAt        time.Time      `json:"created_at"`
	UpdatedAt        time.Time      `json:"updated_at"`
}

type PlanLadder

type PlanLadder struct {
	PlanLadderID string         `json:"plan_ladder_id"`
	Key          sql.NullString `json:"key"`
	Name         string         `json:"name"`
	Description  sql.NullString `json:"description"`
	IsActive     bool           `json:"is_active"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	SortOrder    int32          `json:"sort_order"`
}

type PlanLadderTier

type PlanLadderTier struct {
	PlanLadderID string    `json:"plan_ladder_id"`
	ProductID    string    `json:"product_id"`
	Rank         int32     `json:"rank"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
}

type Price

type Price struct {
	PriceID           string         `json:"price_id"`
	ProductID         string         `json:"product_id"`
	Currency          string         `json:"currency"`
	UnitAmount        int32          `json:"unit_amount"`
	RecurringInterval sql.NullString `json:"recurring_interval"`
	TrialPeriodDays   sql.NullInt32  `json:"trial_period_days"`
	IsActive          bool           `json:"is_active"`
	CreatedAt         time.Time      `json:"created_at"`
	UpdatedAt         time.Time      `json:"updated_at"`
	IsDefault         bool           `json:"is_default"`
	UsageType         sql.NullString `json:"usage_type"`
	Key               sql.NullString `json:"key"`
}

type Product

type Product struct {
	ProductID   string         `json:"product_id"`
	Name        string         `json:"name"`
	Description sql.NullString `json:"description"`
	// Presentation-layer grouping only (Doc 41 Decision 136): storefront sections and operator filters. No code may branch on this value for behavior — structural facts live in plan_ladder_tiers and per-price columns.
	DisplayCategory  sql.NullString        `json:"display_category"`
	Metadata         pqtype.NullRawMessage `json:"metadata"`
	IsActive         bool                  `json:"is_active"`
	IsPublic         bool                  `json:"is_public"`
	CreatedAt        time.Time             `json:"created_at"`
	UpdatedAt        time.Time             `json:"updated_at"`
	EntitlementSetID uuid.NullUUID         `json:"entitlement_set_id"`
	LifecycleStatus  string                `json:"lifecycle_status"`
	Key              sql.NullString        `json:"key"`
}

type Querier

type Querier interface {
	// Setup-checklist existence probe.
	AnyActivePrice(ctx context.Context) (bool, error)
	// Setup-checklist existence probe.
	AnyPublishedProduct(ctx context.Context) (bool, error)
	// Setup-checklist existence probe: a ladder delivers only through its rank-0
	// tier, so "ladder exists" alone is not the step.
	AnyRankZeroTier(ctx context.Context) (bool, error)
	// Webhook-primary closeout: when a subscription actually ends (Stripe fires
	// customer.subscription.deleted at period end), mark its still-pending scheduled
	// changes applied so the intent ledger reflects what happened.
	ApplyScheduledChangesForSubscription(ctx context.Context, subscriptionID string) error
	// The transactional, gapless counter invoice-numbers D1 specifies: the
	// account's next_invoice_number is incremented and the prior value
	// returned in the same statement, so the caller runs this inside the same
	// transaction that inserts the invoice row (invoice.finalized projection).
	// Never a Postgres sequence — a sequence burns values on rollback, and this
	// counter must not: a projection that fails after this call rolls back
	// with the transaction, leaving the counter exactly where it was. Row
	// locking is implicit in the UPDATE and serializes only within one
	// account.
	AssignNextInvoiceNumber(ctx context.Context, billingAccountID string) (int32, error)
	// First half of the make-default handshake; run in the same transaction as
	// MarkDefaultPrice (clear before set, so the partial unique index never sees
	// two defaults for one product).
	ClearDefaultPrice(ctx context.Context, productID string) error
	// The invoice reconcile's write to an invoice that exists
	// (stripe-invoice-reconcile D3). Two snapshots of one invoice can commit
	// out of order, so the merge only moves forward:
	//   - status by rank: draft, then open, then uncollectible, then paid or
	//     void. A snapshot at a lower rank never moves the status back, and
	//     paid and void never replace each other. Any other stored status
	//     (refunded) outranks them all and is never replaced.
	//   - amount_due and due_date from a snapshot at the same rank or higher.
	//     Two snapshots at the same rank applied out of order can leave the
	//     older values; the sweep's daily read of open invoices corrects them.
	//   - amount_paid the larger of the two.
	//   - issued_at from Stripe's date of issue, and paid_at and voided_at from
	//     its status transitions, when Stripe has one, never cleared (D17).
	//   - subscription_id filled only while NULL.
	// The three times and subscription_id are merged with the row as this
	// statement locks it, not as the CTE read it: the sweep fills
	// subscription_id outside the invoice lock (FillInvoiceSubscriptionLinks),
	// and a fill that commits while this statement waits for the row must not
	// be written back to NULL.
	// The final guard skips the write when nothing would change, so a replay
	// does not touch updated_at (its trigger fires on every UPDATE).
	ConvergeInvoice(ctx context.Context, arg ConvergeInvoiceParams) (int64, error)
	// The same predicates as ListBillingAccountsPage, without paging: the caller runs it twice,
	// once with sqlc.narg(exclude_ids) and once without, and the difference is
	// how many rows the environment filter holds back from the view the
	// operator is looking at. The billing views' absence line reports that
	// number under the search and the facet in force
	// (stripe-environment-stamp D7), which the page query's count(*) OVER()
	// cannot give, because it counts the rows that were shown.
	CountBillingAccountsPage(ctx context.Context, arg CountBillingAccountsPageParams) (int64, error)
	// The invoice reconcile inserts lines only into an invoice with none
	// (stripe-invoice-reconcile D5), and asks this under its lock.
	CountInvoiceLineItemsByInvoiceID(ctx context.Context, invoiceID string) (int64, error)
	// The same predicates as ListInvoicesPage, without paging: the caller runs it twice,
	// once with sqlc.narg(exclude_ids) and once without, and the difference is
	// how many rows the environment filter holds back from the view the
	// operator is looking at. The billing views' absence line reports that
	// number under the search and the facet in force
	// (stripe-environment-stamp D7), which the page query's count(*) OVER()
	// cannot give, because it counts the rows that were shown.
	CountInvoicesPage(ctx context.Context, arg CountInvoicesPageParams) (int64, error)
	// Both halves of the operator overview's Monthly recurring caption in one
	// read: 'active' and 'trialing' are the two statuses that mean the
	// subscription is presently owed service (the pair operator_billing.go
	// treats as live), but only active ones contribute money, so the caption
	// needs them separately.
	CountLiveSubscriptionsByStatus(ctx context.Context) (CountLiveSubscriptionsByStatusRow, error)
	// The same predicates as ListPaymentsPage, without paging: the caller runs it twice,
	// once with sqlc.narg(exclude_ids) and once without, and the difference is
	// how many rows the environment filter holds back from the view the
	// operator is looking at. The billing views' absence line reports that
	// number under the search and the facet in force
	// (stripe-environment-stamp D7), which the page query's count(*) OVER()
	// cannot give, because it counts the rows that were shown.
	CountPaymentsPage(ctx context.Context, arg CountPaymentsPageParams) (int64, error)
	// Operator catalog overview (ux-ia-naming 2.1): how many published products
	// are a tier on some plan ladder, vs. off-ladder. A product counts once even
	// when it is shared across more than one ladder (DISTINCT).
	CountPublishedTierProducts(ctx context.Context) (int64, error)
	// The same predicates as ListSubscriptionsPage, without paging: the caller runs it twice,
	// once with sqlc.narg(exclude_ids) and once without, and the difference is
	// how many rows the environment filter holds back from the view the
	// operator is looking at. The billing views' absence line reports that
	// number under the search and the facet in force
	// (stripe-environment-stamp D7), which the page query's count(*) OVER()
	// cannot give, because it counts the rows that were shown.
	CountSubscriptionsPage(ctx context.Context, arg CountSubscriptionsPageParams) (int64, error)
	CreateBillingAccount(ctx context.Context, arg CreateBillingAccountParams) (Account, error)
	// invoice_number is the platform-assigned reference number (invoice-numbers
	// D1-D3): the caller assigns it via AssignNextInvoiceNumber (billing_accounts.sql)
	// in the same transaction, inside the invoice reconcile's creating branch,
	// and passes the formatted result here. Drafts pass NULL/invalid
	// (chk_invoices_issued_have_number allows a NULL number only when status is
	// 'draft').
	// issued_at, paid_at and voided_at are Stripe's times when the caller has
	// them (stripe-invoice-reconcile D17): an invoice projected late sits at its
	// issue time in every list, which sorts by issued_at. created_at is left to
	// its default, the time the row is written, and nothing passes it.
	CreateInvoice(ctx context.Context, arg CreateInvoiceParams) (Invoice, error)
	CreateInvoiceLineItem(ctx context.Context, arg CreateInvoiceLineItemParams) (InvoiceLineItem, error)
	// paid_at or failed_at is when the attempt succeeded or failed, as Stripe
	// reports it (stripe-invoice-reconcile D17), so a payment recorded late is
	// still dated when it happened. created_at is left to its default, the time
	// the row is written, and nothing passes it.
	CreatePayment(ctx context.Context, arg CreatePaymentParams) (Payment, error)
	CreatePaymentMethod(ctx context.Context, arg CreatePaymentMethodParams) (PaymentMethod, error)
	// `key` is the optional declarative address (entity-keys §3), root-scoped.
	// The operator create form asks for a name only, so a UI-created ladder
	// leaves it NULL; a seed or a configuration loader supplies it.
	CreatePlanLadder(ctx context.Context, arg CreatePlanLadderParams) (PlanLadder, error)
	// Appends the tier at the end of the ladder: rank self-assigns to MAX+1 in the
	// INSERT itself (no read-then-write race). Reorder keeps ranks contiguous
	// 0..N-1, so MAX+1 == COUNT; operators position tiers by drag-and-drop.
	CreatePlanLadderTier(ctx context.Context, arg CreatePlanLadderTierParams) (PlanLadderTier, error)
	// The first price a product gets becomes its default automatically (there is
	// nothing else to offer members); subsequent prices are created non-default
	// and promoted explicitly via Clear/MarkDefaultPrice. The NOT EXISTS probe
	// also self-heals a product that somehow lost its default: the next price
	// created becomes it. The partial unique index
	// (idx_prices_one_default_per_product) backstops concurrent creation races.
	//
	// `key` is the optional declarative address (entity-keys §3), unique within
	// the product because a price is a child of one. Stripe's `lookup_key` is
	// the same idea on the same entity. The operator create form does not
	// collect one, so a UI-created price leaves it NULL.
	CreatePrice(ctx context.Context, arg CreatePriceParams) (Price, error)
	// `key` is the optional declarative address (entity-keys §3), root-scoped.
	// Product names deliberately carry no uniqueness constraint (two ladders may
	// each have a "Pro"), which is exactly why a caller outside the database
	// needs a key to name one row. The operator create form does not collect
	// one, so a UI-created product leaves it NULL.
	CreateProduct(ctx context.Context, arg CreateProductParams) (Product, error)
	CreateScheduledChange(ctx context.Context, arg CreateScheduledChangeParams) (SubscriptionScheduledChange, error)
	CreateSubscription(ctx context.Context, arg CreateSubscriptionParams) (Subscription, error)
	CreateSubscriptionChange(ctx context.Context, arg CreateSubscriptionChangeParams) (SubscriptionChange, error)
	CreateSubscriptionItem(ctx context.Context, arg CreateSubscriptionItemParams) (SubscriptionItem, error)
	// Handlers must refuse to deactivate the default price (members would lose
	// the purchase path); the is_default guard here backstops that rule.
	DeactivatePrice(ctx context.Context, priceID string) (Price, error)
	DeletePlanLadder(ctx context.Context, planLadderID string) error
	DeleteTier(ctx context.Context, arg DeleteTierParams) error
	// Mark an item as no longer on its subscription (reconcile, when its Stripe
	// item is gone from the subscription). A row already ended is left as it is.
	EndSubscriptionItem(ctx context.Context, subscriptionItemID string) (int64, error)
	// Idempotent tier membership for a seed (entity-keys §6 as amended by §9 A1:
	// a seed ensures a row exists and never overwrites one). A tier has no key of
	// its own: it is a relationship, and its identity is the pair (§2 class E),
	// which is also its primary key. Rank self-assigns to MAX+1 exactly as
	// CreatePlanLadderTier does, so a caller inserting tiers in ascending order
	// gets 0..N-1; a second run conflicts on the pair and does nothing, leaving
	// an operator's own reordering alone.
	EnsurePlanLadderTier(ctx context.Context, arg EnsurePlanLadderTierParams) error
	GetBillingAccountByID(ctx context.Context, billingAccountID string) (Account, error)
	GetInvoiceByID(ctx context.Context, invoiceID string) (Invoice, error)
	// Insert order, which is Stripe's line order. One transaction inserts every
	// line of an invoice at one NOW(), so the id breaks the tie.
	GetInvoiceLineItemsByInvoiceID(ctx context.Context, invoiceID string) ([]InvoiceLineItem, error)
	// The lines of several invoices in one read, for the member's invoice
	// list, which shows each invoice's period from its lines. Each invoice's
	// lines come in insert order, as GetInvoiceLineItemsByInvoiceID returns
	// them.
	GetInvoiceLineItemsByInvoiceIDs(ctx context.Context, invoiceIds []string) ([]InvoiceLineItem, error)
	// Newest issue first, a draft (no issue time) ahead of them all, the id
	// breaking ties (stripe-invoice-reconcile D17): every invoice list orders
	// this way, never by created_at, the time the console wrote the row.
	GetInvoicesByBillingAccountID(ctx context.Context, billingAccountID string) ([]Invoice, error)
	// The operator landing-surface lookup's invoice-number resolver
	// (operator-panel-navigation design D4: exact key -> exact invoice number ->
	// persons -> organizations). invoice_number is unique per billing account
	// only (uq_invoices_account_invoice_number), never globally, so an exact
	// number can legitimately match several invoices across different
	// organizations' accounts; the caller renders a disambiguation row per
	// match (number, organization resolved Go-side via OrgQ, issued date).
	// Most recently issued first, as every invoice list orders
	// (stripe-invoice-reconcile D17).
	GetInvoicesByNumber(ctx context.Context, invoiceNumber sql.NullString) ([]GetInvoicesByNumberRow, error)
	// The invoice a billing account issued last (any status), in the order
	// every invoice list uses (stripe-invoice-reconcile D17). A draft has not
	// been issued, so it is never the latest. Used by the per-org composite's
	// billing-summary section.
	GetLatestInvoiceByBillingAccountID(ctx context.Context, billingAccountID string) (Invoice, error)
	// Most recent subscription for a billing account (any status). Used by the
	// per-org composite's billing-summary section.
	GetLatestSubscriptionByBillingAccountID(ctx context.Context, billingAccountID string) (Subscription, error)
	// Sum of (amount_due - amount_paid) across invoices with status='open' — the
	// only actionable non-terminal invoice status per design/billing/model.md.
	// Returns 0 if no open invoices exist.
	GetOutstandingBalanceByBillingAccountID(ctx context.Context, billingAccountID string) (int64, error)
	// Newest outcome first, a payment with neither time (pending or canceled,
	// which nothing records today) ahead of them all, the id breaking ties
	// (stripe-invoice-reconcile D17): every payment list orders this way, never
	// by created_at, the time the console wrote the row.
	GetPaymentsByInvoiceID(ctx context.Context, invoiceID string) ([]Payment, error)
	GetPlanLadderByID(ctx context.Context, planLadderID string) (PlanLadder, error)
	// Root key resolver (entity-keys §5). uq_plan_ladders_key guarantees at most
	// one row matches.
	GetPlanLadderByKey(ctx context.Context, key sql.NullString) (PlanLadder, error)
	GetPrice(ctx context.Context, priceID string) (Price, error)
	// Child key resolver (entity-keys §5): the declarative address of a price is
	// its product's key plus its own. uq_prices_product_id_key guarantees at
	// most one row matches.
	GetPriceByProductAndKey(ctx context.Context, arg GetPriceByProductAndKeyParams) (Price, error)
	GetProductByID(ctx context.Context, productID string) (Product, error)
	// Root key resolver (entity-keys §5). uq_products_key guarantees at most one
	// row matches -- unlike GetProductByName, whose column has no unique
	// constraint at all.
	GetProductByKey(ctx context.Context, key sql.NullString) (Product, error)
	// Diagnostics view (migrations 00006, 00018): independent structural
	// dimensions per product. Readiness reads set_present, billing_shape and
	// active_rule_count, which is the sole source of the answer to whether a
	// product's set provides anything (product-catalog). The two counts are
	// cast because the view's COALESCE over a grouped count gives sqlc no type
	// to infer.
	GetProductShape(ctx context.Context, productID string) (CoreProductShape, error)
	GetScheduledChangeByID(ctx context.Context, scheduledChangeID string) (SubscriptionScheduledChange, error)
	GetSubscriptionByID(ctx context.Context, subscriptionID string) (Subscription, error)
	GetSubscriptionItemByID(ctx context.Context, subscriptionItemID string) (SubscriptionItem, error)
	// The subscription's current items: an item Stripe replaced (a schedule's
	// phase change does) keeps its row for the invoice lines that reference it,
	// with ended_at set, and is not returned.
	GetSubscriptionItemsBySubscriptionID(ctx context.Context, subscriptionID string) ([]SubscriptionItem, error)
	GetSubscriptionsByBillingAccountID(ctx context.Context, billingAccountID string) ([]Subscription, error)
	GetTierByLadderRank(ctx context.Context, arg GetTierByLadderRankParams) (PlanLadderTier, error)
	ListActiveProducts(ctx context.Context) ([]Product, error)
	ListActiveScheduledChangesBySubscription(ctx context.Context, subscriptionID string) ([]SubscriptionScheduledChange, error)
	ListAllProducts(ctx context.Context) ([]Product, error)
	ListBillingAccountsByOrgID(ctx context.Context, orgID string) ([]Account, error)
	// Operator billing-accounts view, paged and searched (operator-list-scale
	// UX-4; operator-billing-views D8). No status facet: core.accounts.status
	// carries no CHECK-enforced vocabulary and operator-list-scale's "Status
	// filters exist where a status vocabulary exists" requirement does not
	// name accounts, so this query offers search + pagination only.
	//
	// sqlc.narg(q): NULL matches every row; set, a case-insensitive substring
	// match against the account's own name, or its organization via
	// sqlc.narg(org_ids) (design D3: "billing: organization name plus the
	// view's leading identifier"). Organization-name search resolves through
	// a pre-resolved ID array rather than a join to core.organizations: no
	// existing internal/billing query crosses that module boundary
	// (grep 'core\.' internal/billing/queries/ turns up none), so
	// operator_billing.go's matchingOrgIDs resolves matching org IDs in Go and
	// passes them here, mirroring the grants lane's product-name pattern.
	// sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is
	// in the array are left out of the page AND out of count(*) OVER(), so the
	// pager's total counts only what renders. The operator billing views hand
	// it the ids whose stripe mapping records the environment the API key is
	// not in (stripe-environment-stamp D7), resolved in the stripe store the
	// same way org_ids and invoice_ids are resolved in Go, because no query
	// here crosses that module boundary.
	// count(*) OVER() carries the true total for the filtered set (design D2).
	// Accounts written in one transaction share created_at, so ties fall to the
	// account id: it is time-ordered, which lists the later-written account first,
	// so each lists on exactly one page.
	ListBillingAccountsPage(ctx context.Context, arg ListBillingAccountsPageParams) ([]ListBillingAccountsPageRow, error)
	// The products of the listed subscriptions' current items whose product has
	// an entitlement set, one row per subscription and product: the products
	// the collection pause rule counts (grant-pauses-subscription-billing D2),
	// in one statement for a page of the drift sweep (D5). A product with no
	// set rides the pause and is left out.
	ListCurrentConferringProductsBySubscriptionIDs(ctx context.Context, subscriptionIds []string) ([]ListCurrentConferringProductsBySubscriptionIDsRow, error)
	// The current items of every subscription of the billing account, the rows
	// mirrorItems writes, in one statement for the organization page's Billing
	// card (displaced-subscription-waits D4).
	ListCurrentSubscriptionItemsByBillingAccountID(ctx context.Context, billingAccountID string) ([]ListCurrentSubscriptionItemsByBillingAccountIDRow, error)
	// The current items of one page of the operator's subscriptions list, the
	// rows mirrorItems writes, in one statement for the page
	// (displaced-subscription-waits D4).
	ListCurrentSubscriptionItemsBySubscriptionIDs(ctx context.Context, subscriptionIds []string) ([]ListCurrentSubscriptionItemsBySubscriptionIDsRow, error)
	// Sweeper backstop: due, not-yet-fired rows. Concurrency safety comes from the
	// per-row claim (MarkScheduledChangeApplied), not row locking, so a plain read
	// is sufficient.
	ListDueScheduledChanges(ctx context.Context) ([]SubscriptionScheduledChange, error)
	// Operator invoices view, paged/searched/filtered (operator-list-scale
	// UX-4; operator-billing-views D5/D8). Carries ba.org_id so the handler can
	// resolve and link the organization without a cross-module join (see
	// billing_accounts.sql's ListBillingAccountsPage comment for why).
	//
	// sqlc.narg(q): NULL matches every row; set, a case-insensitive substring
	// match against the billing account's name (the view's leading identifier
	// pre-reorder), the invoice's own invoice_number (invoice-numbers D3/D4 --
	// matches both the platform form and a grandfathered Stripe-format string,
	// since both live in this column), or its organization via
	// sqlc.narg(org_ids), pre-resolved in Go (operator_billing.go:
	// matchingOrgIDs). sqlc.narg(invoice_ids): a search also matches an
	// invoice whose stripe.invoice_mappings row carries a matching
	// stripe_invoice_number (design D6) -- internal/billing has no query that
	// joins the stripe schema (mirrors the org-name pattern above: no existing
	// query crosses that module boundary either), so operator_billing.go
	// resolves the matching invoice ids there
	// (matchingInvoiceIDsByStripeNumber) and passes them in pre-resolved, the
	// same shape as org_ids.
	// sqlc.narg(status): NULL matches every status. The stored status
	// vocabulary (design/data-model.md: draft, open, paid, void,
	// uncollectible, refunded -- core.invoices carries no CHECK constraint,
	// this is the documented closed set) matches exactly; the sentinel value
	// 'overdue' instead selects the derived predicate design D5 defines --
	// status = 'open' AND due_date IS NOT NULL AND due_date < now() -- so the
	// Overdue filter's total is computed in SQL, never after LIMIT (the same
	// predicate operator_billing.go's invoiceIsOverdue applies in Go for
	// per-row presentation; a test pins their agreement).
	// sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is
	// in the array are left out of the page AND out of count(*) OVER(), so the
	// pager's total counts only what renders. The operator billing views hand
	// it the ids whose stripe mapping records the environment the API key is
	// not in (stripe-environment-stamp D7), resolved in the stripe store the
	// same way org_ids and invoice_ids are resolved in Go, because no query
	// here crosses that module boundary.
	// count(*) OVER() carries the true total for the filtered set (design D2).
	// Ordered by issue time, the id ending the order so a page holds the same
	// rows on every load (stripe-invoice-reconcile D17).
	ListInvoicesPage(ctx context.Context, arg ListInvoicesPageParams) ([]ListInvoicesPageRow, error)
	ListLaddersByProduct(ctx context.Context, productID string) ([]ListLaddersByProductRow, error)
	// Operator payments view, paged and searched (operator-list-scale UX-4;
	// operator-billing-views D8). No status facet: the operator-list-scale
	// spec's "Status filters exist where a status vocabulary exists"
	// requirement enumerates grants/invoices/subscriptions/organizations, not
	// payments, so this query offers search + pagination only. Carries
	// ba.org_id so the handler can resolve and link the organization without a
	// cross-module join (see billing_accounts.sql's ListBillingAccountsPage
	// comment for why).
	//
	// sqlc.narg(q): NULL matches every row; set, a case-insensitive substring
	// match against the billing account's name (the view's leading identifier
	// pre-reorder) or its organization via sqlc.narg(org_ids), pre-resolved in
	// Go (operator_billing.go: matchingOrgIDs).
	// Joins to core.invoices (not left -- invoice_id is NOT NULL on
	// core.payments) to carry invoice_number: invoice-numbers D3 puts the
	// number in the title of this view's "View invoice" cross-reference.
	// sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is
	// in the array are left out of the page AND out of count(*) OVER(), so the
	// pager's total counts only what renders. The operator billing views hand
	// it the ids whose stripe mapping records the environment the API key is
	// not in (stripe-environment-stamp D7), resolved in the stripe store the
	// same way org_ids and invoice_ids are resolved in Go, because no query
	// here crosses that module boundary.
	// count(*) OVER() carries the true total for the filtered set (design D2).
	// Ordered by when each attempt succeeded or failed, the id ending the order
	// so a page holds the same rows on every load (stripe-invoice-reconcile
	// D17).
	ListPaymentsPage(ctx context.Context, arg ListPaymentsPageParams) ([]ListPaymentsPageRow, error)
	// The names of the plan ladders one operator page names, in one read (#10).
	// An id with no row is absent from the result.
	ListPlanLadderNamesByIDs(ctx context.Context, planLadderIds []string) ([]ListPlanLadderNamesByIDsRow, error)
	ListPlanLadders(ctx context.Context) ([]PlanLadder, error)
	// LEFT JOINs on purpose: a ladder whose rank-0 tier was deleted must still
	// appear (product columns NULL) so surfaces that reference it — notably an
	// org type's configured default — can show it as broken instead of silently
	// dropping it from a dropdown and NULLing the stored value on save.
	ListPlanLaddersWithRankZeroProduct(ctx context.Context) ([]ListPlanLaddersWithRankZeroProductRow, error)
	ListPricesByProduct(ctx context.Context, productID string) ([]Price, error)
	// Batch reader for the products list's per-page verdict (product-management
	// "The verdict per page, from batches, never cached", design D4): every
	// active price for the page's products, one query instead of one per
	// product (mirrors ListPricesByProduct's is_active filter and order, so
	// priceReadinessFromBatches can pick the same tracked price per product
	// from the grouped rows).
	ListPricesByProductIDs(ctx context.Context, productIds []string) ([]Price, error)
	// The names of the products one operator page names, in one read (#10). An
	// id with no row is absent from the result.
	ListProductNamesByIDs(ctx context.Context, productIds []string) ([]ListProductNamesByIDsRow, error)
	// Batch reader for the products list's per-page verdict (product-management
	// "The verdict per page, from batches, never cached", design D4): the
	// product_shape view for every product on the page, one query instead of
	// one per row.
	ListProductShapesByIDs(ctx context.Context, productIds []string) ([]CoreProductShape, error)
	// Product duplicate-name warning (entity-keys): products may
	// legitimately share a name (a "Pro" tier on two ladders), so
	// core.products.name carries no uniqueness constraint -- this powers a live,
	// non-blocking warning on the create/edit forms instead of a 422. Matches
	// case-insensitively; when exclude_product_id is set (the edit form's own
	// product), that product is excluded from its own duplicate check. LEFT
	// JOINs the ladder tables so a matching product that is on no ladder still
	// returns one row (ladder columns NULL); the caller groups rows by
	// product_id in Go and collects each product's ladder names.
	ListProductsByNameCI(ctx context.Context, arg ListProductsByNameCIParams) ([]ListProductsByNameCIRow, error)
	// Products list operator surface (operator-list-scale; product-management
	// "The list takes the scaffold"): the paged, searched, lifecycle-filtered
	// successor to ListAllProducts, in the Organizations list's shape.
	//
	// sqlc.narg(q): NULL matches every row; set, a case-insensitive substring
	// match against the product's name.
	// sqlc.narg(lifecycle_status): NULL matches every lifecycle state; set, an
	// exact facet match (the Draft/Published/Retired pills).
	// count(*) OVER() carries the true total for the filtered set (design D2),
	// so the stated total never reflects only the page.
	// Product names are not unique, and products written in one transaction share
	// created_at, so ties on the name fall to the product id: it is time-ordered,
	// which lists the later-written product first, so each lists on exactly one
	// page.
	ListProductsPage(ctx context.Context, arg ListProductsPageParams) ([]ListProductsPageRow, error)
	// Plan products are those attached to a ladder via plan_ladder_tiers
	// (Doc 31 Amendment #3); membership is the structural signal —
	// display_category is presentation-only and never branched on.
	ListPublicPlanProducts(ctx context.Context) ([]Product, error)
	ListPublicProducts(ctx context.Context) ([]Product, error)
	// Recent invoices for the operator landing activity timeline, newest first,
	// to the depth the page asks for, with total_count, the number of invoice
	// events the timeline holds. Joins to core.accounts to resolve the org_id
	// (same schema, safe for sqlc). The timeline places an invoice at its issue
	// time (stripe-invoice-reconcile D17), so an invoice without one (a draft)
	// is not an event. Invoices issued at one instant list the later-written
	// first, the order the feed merges its sources in.
	ListRecentInvoices(ctx context.Context, limit int32) ([]ListRecentInvoicesRow, error)
	// Recent payments for the operator landing activity timeline, newest first,
	// to the depth the page asks for, with total_count, the number of payment
	// events the timeline holds. Joins to core.accounts to resolve the org_id
	// (same schema, safe for sqlc). The timeline places a payment when it
	// succeeded or failed (stripe-invoice-reconcile D17), so a payment with
	// neither time is not an event. Payments placed at one instant list the
	// later-written first, the order the feed merges its sources in.
	ListRecentPayments(ctx context.Context, limit int32) ([]ListRecentPaymentsRow, error)
	// Products that are a tier in more than one ladder (the many-to-many made
	// legible for the operator topology overview). Returns one row per
	// (shared product, ladder) membership, ordered for stable grouping in Go.
	ListSharedTierProducts(ctx context.Context) ([]ListSharedTierProductsRow, error)
	// The organization's live subscriptions (active, trialing, past_due, unpaid,
	// paused), one row per current item and tier row of the item's product, for
	// the offer decision's fact "a subscription pays for a tier of this ladder"
	// (grant-pauses-subscription-billing D9): the subscription's status, period
	// end, cancel_at_period_end, the mirror's collection pause and marker, the
	// first scheduled cancellation and the first scheduled plan switch (joined as
	// ListLadderPositionsByPool joins them), and the item's price facts. A product
	// that is a tier of no ladder has no row. Read once per request, never per
	// ladder.
	ListSubscriptionRungsByOrg(ctx context.Context, orgID string) ([]ListSubscriptionRungsByOrgRow, error)
	// Operator subscriptions view, paged/searched/filtered (operator-list-scale
	// UX-4; operator-billing-views D8). Carries ba.org_id so the handler can
	// resolve and link the organization without a cross-module join (see
	// billing_accounts.sql's ListBillingAccountsPage comment for why).
	//
	// sqlc.narg(q): NULL matches every row; set, a case-insensitive substring
	// match against the billing account's name (the view's leading identifier
	// pre-reorder) or its organization via sqlc.narg(org_ids), pre-resolved in
	// Go (operator_billing.go: matchingOrgIDs).
	// sqlc.narg(status): NULL matches every status; set, an exact match
	// against the subscription's CHECK-constrained status vocabulary
	// (00010_schema_hardening.sql: chk_subscriptions_status_valid --
	// incomplete, incomplete_expired, trialing, active, past_due, canceled,
	// unpaid, paused).
	// sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is
	// in the array are left out of the page AND out of count(*) OVER(), so the
	// pager's total counts only what renders. The operator billing views hand
	// it the ids whose stripe mapping records the environment the API key is
	// not in (stripe-environment-stamp D7), resolved in the stripe store the
	// same way org_ids and invoice_ids are resolved in Go, because no query
	// here crosses that module boundary.
	// count(*) OVER() carries the true total for the filtered set (design D2).
	// Subscriptions written in one transaction share created_at, so ties fall to
	// the subscription id: it is time-ordered, which lists the later-written
	// subscription first, so each lists on exactly one page.
	ListSubscriptionsPage(ctx context.Context, arg ListSubscriptionsPageParams) ([]ListSubscriptionsPageRow, error)
	ListTiersByLadder(ctx context.Context, planLadderID string) ([]PlanLadderTier, error)
	ListTiersByLadderWithProducts(ctx context.Context, planLadderID string) ([]ListTiersByLadderWithProductsRow, error)
	// ListTiersByLadderWithProducts for several ladders in one read (#10): the
	// tiers of each ladder as it is now, by rank, with each tier's product.
	ListTiersWithProductsByLadderIDs(ctx context.Context, planLadderIds []string) ([]ListTiersWithProductsByLadderIDsRow, error)
	// Every ladder's display order, each row locked in ascending id order: the
	// topology reorder takes them first in its transaction, so two reorders wait
	// for each other instead of deadlocking, and the later one compares against
	// the order the earlier committed. FOR NO KEY UPDATE is the lock the
	// reorder's update of sort_order takes anyway; it does not conflict with the
	// FOR KEY SHARE a tier, a position or an org type's default takes on the
	// ladder through its foreign key, so no conferral waits on a reorder.
	LockPlanLadderOrder(ctx context.Context) ([]LockPlanLadderOrderRow, error)
	// Second half of the make-default handshake. Scoped to (price_id, product_id)
	// so a stale/forged price ID from another product cannot be promoted; the
	// is_active guard keeps a deactivated price from becoming the default.
	MarkDefaultPrice(ctx context.Context, arg MarkDefaultPriceParams) (Price, error)
	MarkPaymentMethodDetached(ctx context.Context, paymentMethodID string) error
	// The one move a recorded attempt makes (stripe-invoice-reconcile D3):
	// from failed to succeeded, when Stripe reports that outcome for its
	// charge. failed_at is cleared and paid_at set with it, because the row now
	// records a success. Guarded on failed, so a replay changes nothing.
	MarkPaymentSucceeded(ctx context.Context, arg MarkPaymentSucceededParams) (int64, error)
	// Idempotency guard / claim: the status transition scheduled->applied is the
	// claim. A second firer (webhook vs sweeper) gets sql.ErrNoRows and no-ops.
	MarkScheduledChangeApplied(ctx context.Context, scheduledChangeID string) (SubscriptionScheduledChange, error)
	// Links a payment method to payments recorded before it was mapped
	// (stripe-invoice-reconcile D7). Never replaces a method already set.
	SetPaymentMethodIfNull(ctx context.Context, arg SetPaymentMethodIfNullParams) (int64, error)
	// Dates a recorded attempt from Stripe (stripe-invoice-reconcile D17). The
	// time is written only into a payment whose status is the charge's
	// outcome, as paid_at for a success and failed_at for a failure, so a
	// snapshot that still reports a succeeded payment's charge failed writes
	// nothing into it. With overwrite the time replaces what the row holds: a
	// failed charge's creation, the invoice's paid time on the payment of the
	// charge that paid it, and the charge's time on a payment the reconcile
	// adopts, which until then held the console's clock or the migration's
	// backfill. Without it the time is written only while the column is NULL,
	// so a snapshot read before the invoice was paid, applied after a later
	// one, never moves a payment off the invoice's paid time.
	// The final guard skips a write that changes nothing, so a replay does not
	// touch updated_at.
	SetPaymentTime(ctx context.Context, arg SetPaymentTimeParams) (int64, error)
	// Sets a single ladder's display order. Used by the topology reorder flow,
	// which renumbers ladders to a contiguous sequence; sort_order is deliberately
	// NOT writable via UpdatePlanLadder so editing a ladder never reorders it.
	SetPlanLadderSortOrder(ctx context.Context, arg SetPlanLadderSortOrderParams) error
	// The Monthly recurring headline, per currency — the caller displays the
	// largest bucket and acknowledges the rest (cross-currency conversion is
	// explicitly out of scope: forge issue #79). Monthly-normalized: month prices at
	// face value, year at one-twelfth, each times item quantity. Active only —
	// trialing subscriptions pay nothing today and counting their money would
	// overstate. A subscription whose collection is paused (any pause, the console's
	// or the Dashboard's) is left out: Stripe collects nothing on it. Current items
	// only: an item Stripe replaced is no longer billed.
	SumMonthlyRecurringByCurrency(ctx context.Context) ([]SumMonthlyRecurringByCurrencyRow, error)
	// A new scheduled change (or an immediate action) supersedes any still-pending
	// intent on the same subscription.
	SupersedeActiveScheduledChanges(ctx context.Context, subscriptionID string) error
	// Reconcile's convergence for a move Stripe fires (plan-switch-timing D4):
	// a period-end row Stripe no longer holds (a released schedule, a cleared
	// cancel_at_period_end) is superseded, one row at a time.
	SupersedeScheduledChange(ctx context.Context, scheduledChangeID string) (SubscriptionScheduledChange, error)
	UpdateInvoicePaid(ctx context.Context, arg UpdateInvoicePaidParams) (Invoice, error)
	UpdatePaymentMethodSafeFields(ctx context.Context, arg UpdatePaymentMethodSafeFieldsParams) (PaymentMethod, error)
	UpdatePlanLadder(ctx context.Context, arg UpdatePlanLadderParams) (PlanLadder, error)
	UpdateProduct(ctx context.Context, arg UpdateProductParams) (Product, error)
	// Records the collection pause Stripe reports for the subscription; every
	// reconcile writes it from the subscription it fetched.
	UpdateSubscriptionCollection(ctx context.Context, arg UpdateSubscriptionCollectionParams) error
	// Converge a core item row after an in-place Stripe price modification (paid->paid
	// switch): the Stripe item id is unchanged but it now carries a new price/product.
	UpdateSubscriptionItemPriceProduct(ctx context.Context, arg UpdateSubscriptionItemPriceProductParams) (SubscriptionItem, error)
	UpdateSubscriptionStatus(ctx context.Context, arg UpdateSubscriptionStatusParams) (Subscription, error)
	UpdateTierRank(ctx context.Context, arg UpdateTierRankParams) (PlanLadderTier, error)
}

type Queries

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

func New

func New(db DBTX) *Queries

func (*Queries) AnyActivePrice

func (q *Queries) AnyActivePrice(ctx context.Context) (bool, error)

Setup-checklist existence probe.

func (*Queries) AnyPublishedProduct

func (q *Queries) AnyPublishedProduct(ctx context.Context) (bool, error)

Setup-checklist existence probe.

func (*Queries) AnyRankZeroTier

func (q *Queries) AnyRankZeroTier(ctx context.Context) (bool, error)

Setup-checklist existence probe: a ladder delivers only through its rank-0 tier, so "ladder exists" alone is not the step.

func (*Queries) ApplyScheduledChangesForSubscription

func (q *Queries) ApplyScheduledChangesForSubscription(ctx context.Context, subscriptionID string) error

Webhook-primary closeout: when a subscription actually ends (Stripe fires customer.subscription.deleted at period end), mark its still-pending scheduled changes applied so the intent ledger reflects what happened.

func (*Queries) AssignNextInvoiceNumber

func (q *Queries) AssignNextInvoiceNumber(ctx context.Context, billingAccountID string) (int32, error)

The transactional, gapless counter invoice-numbers D1 specifies: the account's next_invoice_number is incremented and the prior value returned in the same statement, so the caller runs this inside the same transaction that inserts the invoice row (invoice.finalized projection). Never a Postgres sequence — a sequence burns values on rollback, and this counter must not: a projection that fails after this call rolls back with the transaction, leaving the counter exactly where it was. Row locking is implicit in the UPDATE and serializes only within one account.

func (*Queries) ClearDefaultPrice

func (q *Queries) ClearDefaultPrice(ctx context.Context, productID string) error

First half of the make-default handshake; run in the same transaction as MarkDefaultPrice (clear before set, so the partial unique index never sees two defaults for one product).

func (*Queries) ConvergeInvoice

func (q *Queries) ConvergeInvoice(ctx context.Context, arg ConvergeInvoiceParams) (int64, error)

The invoice reconcile's write to an invoice that exists (stripe-invoice-reconcile D3). Two snapshots of one invoice can commit out of order, so the merge only moves forward:

  • status by rank: draft, then open, then uncollectible, then paid or void. A snapshot at a lower rank never moves the status back, and paid and void never replace each other. Any other stored status (refunded) outranks them all and is never replaced.
  • amount_due and due_date from a snapshot at the same rank or higher. Two snapshots at the same rank applied out of order can leave the older values; the sweep's daily read of open invoices corrects them.
  • amount_paid the larger of the two.
  • issued_at from Stripe's date of issue, and paid_at and voided_at from its status transitions, when Stripe has one, never cleared (D17).
  • subscription_id filled only while NULL.

The three times and subscription_id are merged with the row as this statement locks it, not as the CTE read it: the sweep fills subscription_id outside the invoice lock (FillInvoiceSubscriptionLinks), and a fill that commits while this statement waits for the row must not be written back to NULL. The final guard skips the write when nothing would change, so a replay does not touch updated_at (its trigger fires on every UPDATE).

func (*Queries) CountBillingAccountsPage

func (q *Queries) CountBillingAccountsPage(ctx context.Context, arg CountBillingAccountsPageParams) (int64, error)

The same predicates as ListBillingAccountsPage, without paging: the caller runs it twice, once with sqlc.narg(exclude_ids) and once without, and the difference is how many rows the environment filter holds back from the view the operator is looking at. The billing views' absence line reports that number under the search and the facet in force (stripe-environment-stamp D7), which the page query's count(*) OVER() cannot give, because it counts the rows that were shown.

func (*Queries) CountInvoiceLineItemsByInvoiceID

func (q *Queries) CountInvoiceLineItemsByInvoiceID(ctx context.Context, invoiceID string) (int64, error)

The invoice reconcile inserts lines only into an invoice with none (stripe-invoice-reconcile D5), and asks this under its lock.

func (*Queries) CountInvoicesPage

func (q *Queries) CountInvoicesPage(ctx context.Context, arg CountInvoicesPageParams) (int64, error)

The same predicates as ListInvoicesPage, without paging: the caller runs it twice, once with sqlc.narg(exclude_ids) and once without, and the difference is how many rows the environment filter holds back from the view the operator is looking at. The billing views' absence line reports that number under the search and the facet in force (stripe-environment-stamp D7), which the page query's count(*) OVER() cannot give, because it counts the rows that were shown.

func (*Queries) CountLiveSubscriptionsByStatus

func (q *Queries) CountLiveSubscriptionsByStatus(ctx context.Context) (CountLiveSubscriptionsByStatusRow, error)

Both halves of the operator overview's Monthly recurring caption in one read: 'active' and 'trialing' are the two statuses that mean the subscription is presently owed service (the pair operator_billing.go treats as live), but only active ones contribute money, so the caption needs them separately.

func (*Queries) CountPaymentsPage

func (q *Queries) CountPaymentsPage(ctx context.Context, arg CountPaymentsPageParams) (int64, error)

The same predicates as ListPaymentsPage, without paging: the caller runs it twice, once with sqlc.narg(exclude_ids) and once without, and the difference is how many rows the environment filter holds back from the view the operator is looking at. The billing views' absence line reports that number under the search and the facet in force (stripe-environment-stamp D7), which the page query's count(*) OVER() cannot give, because it counts the rows that were shown.

func (*Queries) CountPublishedTierProducts

func (q *Queries) CountPublishedTierProducts(ctx context.Context) (int64, error)

Operator catalog overview (ux-ia-naming 2.1): how many published products are a tier on some plan ladder, vs. off-ladder. A product counts once even when it is shared across more than one ladder (DISTINCT).

func (*Queries) CountSubscriptionsPage

func (q *Queries) CountSubscriptionsPage(ctx context.Context, arg CountSubscriptionsPageParams) (int64, error)

The same predicates as ListSubscriptionsPage, without paging: the caller runs it twice, once with sqlc.narg(exclude_ids) and once without, and the difference is how many rows the environment filter holds back from the view the operator is looking at. The billing views' absence line reports that number under the search and the facet in force (stripe-environment-stamp D7), which the page query's count(*) OVER() cannot give, because it counts the rows that were shown.

func (*Queries) CreateBillingAccount

func (q *Queries) CreateBillingAccount(ctx context.Context, arg CreateBillingAccountParams) (Account, error)

func (*Queries) CreateInvoice

func (q *Queries) CreateInvoice(ctx context.Context, arg CreateInvoiceParams) (Invoice, error)

invoice_number is the platform-assigned reference number (invoice-numbers D1-D3): the caller assigns it via AssignNextInvoiceNumber (billing_accounts.sql) in the same transaction, inside the invoice reconcile's creating branch, and passes the formatted result here. Drafts pass NULL/invalid (chk_invoices_issued_have_number allows a NULL number only when status is 'draft'). issued_at, paid_at and voided_at are Stripe's times when the caller has them (stripe-invoice-reconcile D17): an invoice projected late sits at its issue time in every list, which sorts by issued_at. created_at is left to its default, the time the row is written, and nothing passes it.

func (*Queries) CreateInvoiceLineItem

func (q *Queries) CreateInvoiceLineItem(ctx context.Context, arg CreateInvoiceLineItemParams) (InvoiceLineItem, error)

func (*Queries) CreatePayment

func (q *Queries) CreatePayment(ctx context.Context, arg CreatePaymentParams) (Payment, error)

paid_at or failed_at is when the attempt succeeded or failed, as Stripe reports it (stripe-invoice-reconcile D17), so a payment recorded late is still dated when it happened. created_at is left to its default, the time the row is written, and nothing passes it.

func (*Queries) CreatePaymentMethod

func (q *Queries) CreatePaymentMethod(ctx context.Context, arg CreatePaymentMethodParams) (PaymentMethod, error)

func (*Queries) CreatePlanLadder

func (q *Queries) CreatePlanLadder(ctx context.Context, arg CreatePlanLadderParams) (PlanLadder, error)

`key` is the optional declarative address (entity-keys §3), root-scoped. The operator create form asks for a name only, so a UI-created ladder leaves it NULL; a seed or a configuration loader supplies it.

func (*Queries) CreatePlanLadderTier

func (q *Queries) CreatePlanLadderTier(ctx context.Context, arg CreatePlanLadderTierParams) (PlanLadderTier, error)

Appends the tier at the end of the ladder: rank self-assigns to MAX+1 in the INSERT itself (no read-then-write race). Reorder keeps ranks contiguous 0..N-1, so MAX+1 == COUNT; operators position tiers by drag-and-drop.

func (*Queries) CreatePrice

func (q *Queries) CreatePrice(ctx context.Context, arg CreatePriceParams) (Price, error)

The first price a product gets becomes its default automatically (there is nothing else to offer members); subsequent prices are created non-default and promoted explicitly via Clear/MarkDefaultPrice. The NOT EXISTS probe also self-heals a product that somehow lost its default: the next price created becomes it. The partial unique index (idx_prices_one_default_per_product) backstops concurrent creation races.

`key` is the optional declarative address (entity-keys §3), unique within the product because a price is a child of one. Stripe's `lookup_key` is the same idea on the same entity. The operator create form does not collect one, so a UI-created price leaves it NULL.

func (*Queries) CreateProduct

func (q *Queries) CreateProduct(ctx context.Context, arg CreateProductParams) (Product, error)

`key` is the optional declarative address (entity-keys §3), root-scoped. Product names deliberately carry no uniqueness constraint (two ladders may each have a "Pro"), which is exactly why a caller outside the database needs a key to name one row. The operator create form does not collect one, so a UI-created product leaves it NULL.

func (*Queries) CreateScheduledChange

func (*Queries) CreateSubscription

func (q *Queries) CreateSubscription(ctx context.Context, arg CreateSubscriptionParams) (Subscription, error)

func (*Queries) CreateSubscriptionChange

func (q *Queries) CreateSubscriptionChange(ctx context.Context, arg CreateSubscriptionChangeParams) (SubscriptionChange, error)

func (*Queries) CreateSubscriptionItem

func (q *Queries) CreateSubscriptionItem(ctx context.Context, arg CreateSubscriptionItemParams) (SubscriptionItem, error)

func (*Queries) DeactivatePrice

func (q *Queries) DeactivatePrice(ctx context.Context, priceID string) (Price, error)

Handlers must refuse to deactivate the default price (members would lose the purchase path); the is_default guard here backstops that rule.

func (*Queries) DeletePlanLadder

func (q *Queries) DeletePlanLadder(ctx context.Context, planLadderID string) error

func (*Queries) DeleteTier

func (q *Queries) DeleteTier(ctx context.Context, arg DeleteTierParams) error

func (*Queries) EndSubscriptionItem

func (q *Queries) EndSubscriptionItem(ctx context.Context, subscriptionItemID string) (int64, error)

Mark an item as no longer on its subscription (reconcile, when its Stripe item is gone from the subscription). A row already ended is left as it is.

func (*Queries) EnsurePlanLadderTier

func (q *Queries) EnsurePlanLadderTier(ctx context.Context, arg EnsurePlanLadderTierParams) error

Idempotent tier membership for a seed (entity-keys §6 as amended by §9 A1: a seed ensures a row exists and never overwrites one). A tier has no key of its own: it is a relationship, and its identity is the pair (§2 class E), which is also its primary key. Rank self-assigns to MAX+1 exactly as CreatePlanLadderTier does, so a caller inserting tiers in ascending order gets 0..N-1; a second run conflicts on the pair and does nothing, leaving an operator's own reordering alone.

func (*Queries) GetBillingAccountByID

func (q *Queries) GetBillingAccountByID(ctx context.Context, billingAccountID string) (Account, error)

func (*Queries) GetInvoiceByID

func (q *Queries) GetInvoiceByID(ctx context.Context, invoiceID string) (Invoice, error)

func (*Queries) GetInvoiceLineItemsByInvoiceID

func (q *Queries) GetInvoiceLineItemsByInvoiceID(ctx context.Context, invoiceID string) ([]InvoiceLineItem, error)

Insert order, which is Stripe's line order. One transaction inserts every line of an invoice at one NOW(), so the id breaks the tie.

func (*Queries) GetInvoiceLineItemsByInvoiceIDs

func (q *Queries) GetInvoiceLineItemsByInvoiceIDs(ctx context.Context, invoiceIds []string) ([]InvoiceLineItem, error)

The lines of several invoices in one read, for the member's invoice list, which shows each invoice's period from its lines. Each invoice's lines come in insert order, as GetInvoiceLineItemsByInvoiceID returns them.

func (*Queries) GetInvoicesByBillingAccountID

func (q *Queries) GetInvoicesByBillingAccountID(ctx context.Context, billingAccountID string) ([]Invoice, error)

Newest issue first, a draft (no issue time) ahead of them all, the id breaking ties (stripe-invoice-reconcile D17): every invoice list orders this way, never by created_at, the time the console wrote the row.

func (*Queries) GetInvoicesByNumber

func (q *Queries) GetInvoicesByNumber(ctx context.Context, invoiceNumber sql.NullString) ([]GetInvoicesByNumberRow, error)

The operator landing-surface lookup's invoice-number resolver (operator-panel-navigation design D4: exact key -> exact invoice number -> persons -> organizations). invoice_number is unique per billing account only (uq_invoices_account_invoice_number), never globally, so an exact number can legitimately match several invoices across different organizations' accounts; the caller renders a disambiguation row per match (number, organization resolved Go-side via OrgQ, issued date). Most recently issued first, as every invoice list orders (stripe-invoice-reconcile D17).

func (*Queries) GetLatestInvoiceByBillingAccountID

func (q *Queries) GetLatestInvoiceByBillingAccountID(ctx context.Context, billingAccountID string) (Invoice, error)

The invoice a billing account issued last (any status), in the order every invoice list uses (stripe-invoice-reconcile D17). A draft has not been issued, so it is never the latest. Used by the per-org composite's billing-summary section.

func (*Queries) GetLatestSubscriptionByBillingAccountID

func (q *Queries) GetLatestSubscriptionByBillingAccountID(ctx context.Context, billingAccountID string) (Subscription, error)

Most recent subscription for a billing account (any status). Used by the per-org composite's billing-summary section.

func (*Queries) GetOutstandingBalanceByBillingAccountID

func (q *Queries) GetOutstandingBalanceByBillingAccountID(ctx context.Context, billingAccountID string) (int64, error)

Sum of (amount_due - amount_paid) across invoices with status='open' — the only actionable non-terminal invoice status per design/billing/model.md. Returns 0 if no open invoices exist.

func (*Queries) GetPaymentsByInvoiceID

func (q *Queries) GetPaymentsByInvoiceID(ctx context.Context, invoiceID string) ([]Payment, error)

Newest outcome first, a payment with neither time (pending or canceled, which nothing records today) ahead of them all, the id breaking ties (stripe-invoice-reconcile D17): every payment list orders this way, never by created_at, the time the console wrote the row.

func (*Queries) GetPlanLadderByID

func (q *Queries) GetPlanLadderByID(ctx context.Context, planLadderID string) (PlanLadder, error)

func (*Queries) GetPlanLadderByKey

func (q *Queries) GetPlanLadderByKey(ctx context.Context, key sql.NullString) (PlanLadder, error)

Root key resolver (entity-keys §5). uq_plan_ladders_key guarantees at most one row matches.

func (*Queries) GetPrice

func (q *Queries) GetPrice(ctx context.Context, priceID string) (Price, error)

func (*Queries) GetPriceByProductAndKey

func (q *Queries) GetPriceByProductAndKey(ctx context.Context, arg GetPriceByProductAndKeyParams) (Price, error)

Child key resolver (entity-keys §5): the declarative address of a price is its product's key plus its own. uq_prices_product_id_key guarantees at most one row matches.

func (*Queries) GetProductByID

func (q *Queries) GetProductByID(ctx context.Context, productID string) (Product, error)

func (*Queries) GetProductByKey

func (q *Queries) GetProductByKey(ctx context.Context, key sql.NullString) (Product, error)

Root key resolver (entity-keys §5). uq_products_key guarantees at most one row matches -- unlike GetProductByName, whose column has no unique constraint at all.

func (*Queries) GetProductShape

func (q *Queries) GetProductShape(ctx context.Context, productID string) (CoreProductShape, error)

Diagnostics view (migrations 00006, 00018): independent structural dimensions per product. Readiness reads set_present, billing_shape and active_rule_count, which is the sole source of the answer to whether a product's set provides anything (product-catalog). The two counts are cast because the view's COALESCE over a grouped count gives sqlc no type to infer.

func (*Queries) GetScheduledChangeByID

func (q *Queries) GetScheduledChangeByID(ctx context.Context, scheduledChangeID string) (SubscriptionScheduledChange, error)

func (*Queries) GetSubscriptionByID

func (q *Queries) GetSubscriptionByID(ctx context.Context, subscriptionID string) (Subscription, error)

func (*Queries) GetSubscriptionItemByID

func (q *Queries) GetSubscriptionItemByID(ctx context.Context, subscriptionItemID string) (SubscriptionItem, error)

func (*Queries) GetSubscriptionItemsBySubscriptionID

func (q *Queries) GetSubscriptionItemsBySubscriptionID(ctx context.Context, subscriptionID string) ([]SubscriptionItem, error)

The subscription's current items: an item Stripe replaced (a schedule's phase change does) keeps its row for the invoice lines that reference it, with ended_at set, and is not returned.

func (*Queries) GetSubscriptionsByBillingAccountID

func (q *Queries) GetSubscriptionsByBillingAccountID(ctx context.Context, billingAccountID string) ([]Subscription, error)

func (*Queries) GetTierByLadderRank

func (q *Queries) GetTierByLadderRank(ctx context.Context, arg GetTierByLadderRankParams) (PlanLadderTier, error)

func (*Queries) ListActiveProducts

func (q *Queries) ListActiveProducts(ctx context.Context) ([]Product, error)

func (*Queries) ListActiveScheduledChangesBySubscription

func (q *Queries) ListActiveScheduledChangesBySubscription(ctx context.Context, subscriptionID string) ([]SubscriptionScheduledChange, error)

func (*Queries) ListAllProducts

func (q *Queries) ListAllProducts(ctx context.Context) ([]Product, error)

func (*Queries) ListBillingAccountsByOrgID

func (q *Queries) ListBillingAccountsByOrgID(ctx context.Context, orgID string) ([]Account, error)

func (*Queries) ListBillingAccountsPage

func (q *Queries) ListBillingAccountsPage(ctx context.Context, arg ListBillingAccountsPageParams) ([]ListBillingAccountsPageRow, error)

Operator billing-accounts view, paged and searched (operator-list-scale UX-4; operator-billing-views D8). No status facet: core.accounts.status carries no CHECK-enforced vocabulary and operator-list-scale's "Status filters exist where a status vocabulary exists" requirement does not name accounts, so this query offers search + pagination only.

sqlc.narg(q): NULL matches every row; set, a case-insensitive substring match against the account's own name, or its organization via sqlc.narg(org_ids) (design D3: "billing: organization name plus the view's leading identifier"). Organization-name search resolves through a pre-resolved ID array rather than a join to core.organizations: no existing internal/billing query crosses that module boundary (grep 'core\.' internal/billing/queries/ turns up none), so operator_billing.go's matchingOrgIDs resolves matching org IDs in Go and passes them here, mirroring the grants lane's product-name pattern. sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is in the array are left out of the page AND out of count(*) OVER(), so the pager's total counts only what renders. The operator billing views hand it the ids whose stripe mapping records the environment the API key is not in (stripe-environment-stamp D7), resolved in the stripe store the same way org_ids and invoice_ids are resolved in Go, because no query here crosses that module boundary. count(*) OVER() carries the true total for the filtered set (design D2). Accounts written in one transaction share created_at, so ties fall to the account id: it is time-ordered, which lists the later-written account first, so each lists on exactly one page.

func (*Queries) ListCurrentConferringProductsBySubscriptionIDs

func (q *Queries) ListCurrentConferringProductsBySubscriptionIDs(ctx context.Context, subscriptionIds []string) ([]ListCurrentConferringProductsBySubscriptionIDsRow, error)

The products of the listed subscriptions' current items whose product has an entitlement set, one row per subscription and product: the products the collection pause rule counts (grant-pauses-subscription-billing D2), in one statement for a page of the drift sweep (D5). A product with no set rides the pause and is left out.

func (*Queries) ListCurrentSubscriptionItemsByBillingAccountID

func (q *Queries) ListCurrentSubscriptionItemsByBillingAccountID(ctx context.Context, billingAccountID string) ([]ListCurrentSubscriptionItemsByBillingAccountIDRow, error)

The current items of every subscription of the billing account, the rows mirrorItems writes, in one statement for the organization page's Billing card (displaced-subscription-waits D4).

func (*Queries) ListCurrentSubscriptionItemsBySubscriptionIDs

func (q *Queries) ListCurrentSubscriptionItemsBySubscriptionIDs(ctx context.Context, subscriptionIds []string) ([]ListCurrentSubscriptionItemsBySubscriptionIDsRow, error)

The current items of one page of the operator's subscriptions list, the rows mirrorItems writes, in one statement for the page (displaced-subscription-waits D4).

func (*Queries) ListDueScheduledChanges

func (q *Queries) ListDueScheduledChanges(ctx context.Context) ([]SubscriptionScheduledChange, error)

Sweeper backstop: due, not-yet-fired rows. Concurrency safety comes from the per-row claim (MarkScheduledChangeApplied), not row locking, so a plain read is sufficient.

func (*Queries) ListInvoicesPage

func (q *Queries) ListInvoicesPage(ctx context.Context, arg ListInvoicesPageParams) ([]ListInvoicesPageRow, error)

Operator invoices view, paged/searched/filtered (operator-list-scale UX-4; operator-billing-views D5/D8). Carries ba.org_id so the handler can resolve and link the organization without a cross-module join (see billing_accounts.sql's ListBillingAccountsPage comment for why).

sqlc.narg(q): NULL matches every row; set, a case-insensitive substring match against the billing account's name (the view's leading identifier pre-reorder), the invoice's own invoice_number (invoice-numbers D3/D4 -- matches both the platform form and a grandfathered Stripe-format string, since both live in this column), or its organization via sqlc.narg(org_ids), pre-resolved in Go (operator_billing.go: matchingOrgIDs). sqlc.narg(invoice_ids): a search also matches an invoice whose stripe.invoice_mappings row carries a matching stripe_invoice_number (design D6) -- internal/billing has no query that joins the stripe schema (mirrors the org-name pattern above: no existing query crosses that module boundary either), so operator_billing.go resolves the matching invoice ids there (matchingInvoiceIDsByStripeNumber) and passes them in pre-resolved, the same shape as org_ids. sqlc.narg(status): NULL matches every status. The stored status vocabulary (design/data-model.md: draft, open, paid, void, uncollectible, refunded -- core.invoices carries no CHECK constraint, this is the documented closed set) matches exactly; the sentinel value 'overdue' instead selects the derived predicate design D5 defines -- status = 'open' AND due_date IS NOT NULL AND due_date < now() -- so the Overdue filter's total is computed in SQL, never after LIMIT (the same predicate operator_billing.go's invoiceIsOverdue applies in Go for per-row presentation; a test pins their agreement). sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is in the array are left out of the page AND out of count(*) OVER(), so the pager's total counts only what renders. The operator billing views hand it the ids whose stripe mapping records the environment the API key is not in (stripe-environment-stamp D7), resolved in the stripe store the same way org_ids and invoice_ids are resolved in Go, because no query here crosses that module boundary. count(*) OVER() carries the true total for the filtered set (design D2). Ordered by issue time, the id ending the order so a page holds the same rows on every load (stripe-invoice-reconcile D17).

func (*Queries) ListLaddersByProduct

func (q *Queries) ListLaddersByProduct(ctx context.Context, productID string) ([]ListLaddersByProductRow, error)

func (*Queries) ListPaymentsPage

func (q *Queries) ListPaymentsPage(ctx context.Context, arg ListPaymentsPageParams) ([]ListPaymentsPageRow, error)

Operator payments view, paged and searched (operator-list-scale UX-4; operator-billing-views D8). No status facet: the operator-list-scale spec's "Status filters exist where a status vocabulary exists" requirement enumerates grants/invoices/subscriptions/organizations, not payments, so this query offers search + pagination only. Carries ba.org_id so the handler can resolve and link the organization without a cross-module join (see billing_accounts.sql's ListBillingAccountsPage comment for why).

sqlc.narg(q): NULL matches every row; set, a case-insensitive substring match against the billing account's name (the view's leading identifier pre-reorder) or its organization via sqlc.narg(org_ids), pre-resolved in Go (operator_billing.go: matchingOrgIDs). Joins to core.invoices (not left -- invoice_id is NOT NULL on core.payments) to carry invoice_number: invoice-numbers D3 puts the number in the title of this view's "View invoice" cross-reference. sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is in the array are left out of the page AND out of count(*) OVER(), so the pager's total counts only what renders. The operator billing views hand it the ids whose stripe mapping records the environment the API key is not in (stripe-environment-stamp D7), resolved in the stripe store the same way org_ids and invoice_ids are resolved in Go, because no query here crosses that module boundary. count(*) OVER() carries the true total for the filtered set (design D2). Ordered by when each attempt succeeded or failed, the id ending the order so a page holds the same rows on every load (stripe-invoice-reconcile D17).

func (*Queries) ListPlanLadderNamesByIDs

func (q *Queries) ListPlanLadderNamesByIDs(ctx context.Context, planLadderIds []string) ([]ListPlanLadderNamesByIDsRow, error)

The names of the plan ladders one operator page names, in one read (#10). An id with no row is absent from the result.

func (*Queries) ListPlanLadders

func (q *Queries) ListPlanLadders(ctx context.Context) ([]PlanLadder, error)

func (*Queries) ListPlanLaddersWithRankZeroProduct

func (q *Queries) ListPlanLaddersWithRankZeroProduct(ctx context.Context) ([]ListPlanLaddersWithRankZeroProductRow, error)

LEFT JOINs on purpose: a ladder whose rank-0 tier was deleted must still appear (product columns NULL) so surfaces that reference it — notably an org type's configured default — can show it as broken instead of silently dropping it from a dropdown and NULLing the stored value on save.

func (*Queries) ListPricesByProduct

func (q *Queries) ListPricesByProduct(ctx context.Context, productID string) ([]Price, error)

func (*Queries) ListPricesByProductIDs

func (q *Queries) ListPricesByProductIDs(ctx context.Context, productIds []string) ([]Price, error)

Batch reader for the products list's per-page verdict (product-management "The verdict per page, from batches, never cached", design D4): every active price for the page's products, one query instead of one per product (mirrors ListPricesByProduct's is_active filter and order, so priceReadinessFromBatches can pick the same tracked price per product from the grouped rows).

func (*Queries) ListProductNamesByIDs

func (q *Queries) ListProductNamesByIDs(ctx context.Context, productIds []string) ([]ListProductNamesByIDsRow, error)

The names of the products one operator page names, in one read (#10). An id with no row is absent from the result.

func (*Queries) ListProductShapesByIDs

func (q *Queries) ListProductShapesByIDs(ctx context.Context, productIds []string) ([]CoreProductShape, error)

Batch reader for the products list's per-page verdict (product-management "The verdict per page, from batches, never cached", design D4): the product_shape view for every product on the page, one query instead of one per row.

func (*Queries) ListProductsByNameCI

func (q *Queries) ListProductsByNameCI(ctx context.Context, arg ListProductsByNameCIParams) ([]ListProductsByNameCIRow, error)

Product duplicate-name warning (entity-keys): products may legitimately share a name (a "Pro" tier on two ladders), so core.products.name carries no uniqueness constraint -- this powers a live, non-blocking warning on the create/edit forms instead of a 422. Matches case-insensitively; when exclude_product_id is set (the edit form's own product), that product is excluded from its own duplicate check. LEFT JOINs the ladder tables so a matching product that is on no ladder still returns one row (ladder columns NULL); the caller groups rows by product_id in Go and collects each product's ladder names.

func (*Queries) ListProductsPage

func (q *Queries) ListProductsPage(ctx context.Context, arg ListProductsPageParams) ([]ListProductsPageRow, error)

Products list operator surface (operator-list-scale; product-management "The list takes the scaffold"): the paged, searched, lifecycle-filtered successor to ListAllProducts, in the Organizations list's shape.

sqlc.narg(q): NULL matches every row; set, a case-insensitive substring match against the product's name. sqlc.narg(lifecycle_status): NULL matches every lifecycle state; set, an exact facet match (the Draft/Published/Retired pills). count(*) OVER() carries the true total for the filtered set (design D2), so the stated total never reflects only the page. Product names are not unique, and products written in one transaction share created_at, so ties on the name fall to the product id: it is time-ordered, which lists the later-written product first, so each lists on exactly one page.

func (*Queries) ListPublicPlanProducts

func (q *Queries) ListPublicPlanProducts(ctx context.Context) ([]Product, error)

Plan products are those attached to a ladder via plan_ladder_tiers (Doc 31 Amendment #3); membership is the structural signal — display_category is presentation-only and never branched on.

func (*Queries) ListPublicProducts

func (q *Queries) ListPublicProducts(ctx context.Context) ([]Product, error)

func (*Queries) ListRecentInvoices

func (q *Queries) ListRecentInvoices(ctx context.Context, limit int32) ([]ListRecentInvoicesRow, error)

Recent invoices for the operator landing activity timeline, newest first, to the depth the page asks for, with total_count, the number of invoice events the timeline holds. Joins to core.accounts to resolve the org_id (same schema, safe for sqlc). The timeline places an invoice at its issue time (stripe-invoice-reconcile D17), so an invoice without one (a draft) is not an event. Invoices issued at one instant list the later-written first, the order the feed merges its sources in.

func (*Queries) ListRecentPayments

func (q *Queries) ListRecentPayments(ctx context.Context, limit int32) ([]ListRecentPaymentsRow, error)

Recent payments for the operator landing activity timeline, newest first, to the depth the page asks for, with total_count, the number of payment events the timeline holds. Joins to core.accounts to resolve the org_id (same schema, safe for sqlc). The timeline places a payment when it succeeded or failed (stripe-invoice-reconcile D17), so a payment with neither time is not an event. Payments placed at one instant list the later-written first, the order the feed merges its sources in.

func (*Queries) ListSharedTierProducts

func (q *Queries) ListSharedTierProducts(ctx context.Context) ([]ListSharedTierProductsRow, error)

Products that are a tier in more than one ladder (the many-to-many made legible for the operator topology overview). Returns one row per (shared product, ladder) membership, ordered for stable grouping in Go.

func (*Queries) ListSubscriptionRungsByOrg

func (q *Queries) ListSubscriptionRungsByOrg(ctx context.Context, orgID string) ([]ListSubscriptionRungsByOrgRow, error)

The organization's live subscriptions (active, trialing, past_due, unpaid, paused), one row per current item and tier row of the item's product, for the offer decision's fact "a subscription pays for a tier of this ladder" (grant-pauses-subscription-billing D9): the subscription's status, period end, cancel_at_period_end, the mirror's collection pause and marker, the first scheduled cancellation and the first scheduled plan switch (joined as ListLadderPositionsByPool joins them), and the item's price facts. A product that is a tier of no ladder has no row. Read once per request, never per ladder.

func (*Queries) ListSubscriptionsPage

func (q *Queries) ListSubscriptionsPage(ctx context.Context, arg ListSubscriptionsPageParams) ([]ListSubscriptionsPageRow, error)

Operator subscriptions view, paged/searched/filtered (operator-list-scale UX-4; operator-billing-views D8). Carries ba.org_id so the handler can resolve and link the organization without a cross-module join (see billing_accounts.sql's ListBillingAccountsPage comment for why).

sqlc.narg(q): NULL matches every row; set, a case-insensitive substring match against the billing account's name (the view's leading identifier pre-reorder) or its organization via sqlc.narg(org_ids), pre-resolved in Go (operator_billing.go: matchingOrgIDs). sqlc.narg(status): NULL matches every status; set, an exact match against the subscription's CHECK-constrained status vocabulary (00010_schema_hardening.sql: chk_subscriptions_status_valid -- incomplete, incomplete_expired, trialing, active, past_due, canceled, unpaid, paused). sqlc.narg(exclude_ids): NULL excludes nothing; set, the rows whose id is in the array are left out of the page AND out of count(*) OVER(), so the pager's total counts only what renders. The operator billing views hand it the ids whose stripe mapping records the environment the API key is not in (stripe-environment-stamp D7), resolved in the stripe store the same way org_ids and invoice_ids are resolved in Go, because no query here crosses that module boundary. count(*) OVER() carries the true total for the filtered set (design D2). Subscriptions written in one transaction share created_at, so ties fall to the subscription id: it is time-ordered, which lists the later-written subscription first, so each lists on exactly one page.

func (*Queries) ListTiersByLadder

func (q *Queries) ListTiersByLadder(ctx context.Context, planLadderID string) ([]PlanLadderTier, error)

func (*Queries) ListTiersByLadderWithProducts

func (q *Queries) ListTiersByLadderWithProducts(ctx context.Context, planLadderID string) ([]ListTiersByLadderWithProductsRow, error)

func (*Queries) ListTiersWithProductsByLadderIDs

func (q *Queries) ListTiersWithProductsByLadderIDs(ctx context.Context, planLadderIds []string) ([]ListTiersWithProductsByLadderIDsRow, error)

ListTiersByLadderWithProducts for several ladders in one read (#10): the tiers of each ladder as it is now, by rank, with each tier's product.

func (*Queries) LockPlanLadderOrder

func (q *Queries) LockPlanLadderOrder(ctx context.Context) ([]LockPlanLadderOrderRow, error)

Every ladder's display order, each row locked in ascending id order: the topology reorder takes them first in its transaction, so two reorders wait for each other instead of deadlocking, and the later one compares against the order the earlier committed. FOR NO KEY UPDATE is the lock the reorder's update of sort_order takes anyway; it does not conflict with the FOR KEY SHARE a tier, a position or an org type's default takes on the ladder through its foreign key, so no conferral waits on a reorder.

func (*Queries) MarkDefaultPrice

func (q *Queries) MarkDefaultPrice(ctx context.Context, arg MarkDefaultPriceParams) (Price, error)

Second half of the make-default handshake. Scoped to (price_id, product_id) so a stale/forged price ID from another product cannot be promoted; the is_active guard keeps a deactivated price from becoming the default.

func (*Queries) MarkPaymentMethodDetached

func (q *Queries) MarkPaymentMethodDetached(ctx context.Context, paymentMethodID string) error

func (*Queries) MarkPaymentSucceeded

func (q *Queries) MarkPaymentSucceeded(ctx context.Context, arg MarkPaymentSucceededParams) (int64, error)

The one move a recorded attempt makes (stripe-invoice-reconcile D3): from failed to succeeded, when Stripe reports that outcome for its charge. failed_at is cleared and paid_at set with it, because the row now records a success. Guarded on failed, so a replay changes nothing.

func (*Queries) MarkScheduledChangeApplied

func (q *Queries) MarkScheduledChangeApplied(ctx context.Context, scheduledChangeID string) (SubscriptionScheduledChange, error)

Idempotency guard / claim: the status transition scheduled->applied is the claim. A second firer (webhook vs sweeper) gets sql.ErrNoRows and no-ops.

func (*Queries) SetPaymentMethodIfNull

func (q *Queries) SetPaymentMethodIfNull(ctx context.Context, arg SetPaymentMethodIfNullParams) (int64, error)

Links a payment method to payments recorded before it was mapped (stripe-invoice-reconcile D7). Never replaces a method already set.

func (*Queries) SetPaymentTime

func (q *Queries) SetPaymentTime(ctx context.Context, arg SetPaymentTimeParams) (int64, error)

Dates a recorded attempt from Stripe (stripe-invoice-reconcile D17). The time is written only into a payment whose status is the charge's outcome, as paid_at for a success and failed_at for a failure, so a snapshot that still reports a succeeded payment's charge failed writes nothing into it. With overwrite the time replaces what the row holds: a failed charge's creation, the invoice's paid time on the payment of the charge that paid it, and the charge's time on a payment the reconcile adopts, which until then held the console's clock or the migration's backfill. Without it the time is written only while the column is NULL, so a snapshot read before the invoice was paid, applied after a later one, never moves a payment off the invoice's paid time. The final guard skips a write that changes nothing, so a replay does not touch updated_at.

func (*Queries) SetPlanLadderSortOrder

func (q *Queries) SetPlanLadderSortOrder(ctx context.Context, arg SetPlanLadderSortOrderParams) error

Sets a single ladder's display order. Used by the topology reorder flow, which renumbers ladders to a contiguous sequence; sort_order is deliberately NOT writable via UpdatePlanLadder so editing a ladder never reorders it.

func (*Queries) SumMonthlyRecurringByCurrency

func (q *Queries) SumMonthlyRecurringByCurrency(ctx context.Context) ([]SumMonthlyRecurringByCurrencyRow, error)

The Monthly recurring headline, per currency — the caller displays the largest bucket and acknowledges the rest (cross-currency conversion is explicitly out of scope: forge issue #79). Monthly-normalized: month prices at face value, year at one-twelfth, each times item quantity. Active only — trialing subscriptions pay nothing today and counting their money would overstate. A subscription whose collection is paused (any pause, the console's or the Dashboard's) is left out: Stripe collects nothing on it. Current items only: an item Stripe replaced is no longer billed.

func (*Queries) SupersedeActiveScheduledChanges

func (q *Queries) SupersedeActiveScheduledChanges(ctx context.Context, subscriptionID string) error

A new scheduled change (or an immediate action) supersedes any still-pending intent on the same subscription.

func (*Queries) SupersedeScheduledChange

func (q *Queries) SupersedeScheduledChange(ctx context.Context, scheduledChangeID string) (SubscriptionScheduledChange, error)

Reconcile's convergence for a move Stripe fires (plan-switch-timing D4): a period-end row Stripe no longer holds (a released schedule, a cleared cancel_at_period_end) is superseded, one row at a time.

func (*Queries) UpdateInvoicePaid

func (q *Queries) UpdateInvoicePaid(ctx context.Context, arg UpdateInvoicePaidParams) (Invoice, error)

func (*Queries) UpdatePaymentMethodSafeFields

func (q *Queries) UpdatePaymentMethodSafeFields(ctx context.Context, arg UpdatePaymentMethodSafeFieldsParams) (PaymentMethod, error)

func (*Queries) UpdatePlanLadder

func (q *Queries) UpdatePlanLadder(ctx context.Context, arg UpdatePlanLadderParams) (PlanLadder, error)

func (*Queries) UpdateProduct

func (q *Queries) UpdateProduct(ctx context.Context, arg UpdateProductParams) (Product, error)

func (*Queries) UpdateSubscriptionCollection

func (q *Queries) UpdateSubscriptionCollection(ctx context.Context, arg UpdateSubscriptionCollectionParams) error

Records the collection pause Stripe reports for the subscription; every reconcile writes it from the subscription it fetched.

func (*Queries) UpdateSubscriptionItemPriceProduct

func (q *Queries) UpdateSubscriptionItemPriceProduct(ctx context.Context, arg UpdateSubscriptionItemPriceProductParams) (SubscriptionItem, error)

Converge a core item row after an in-place Stripe price modification (paid->paid switch): the Stripe item id is unchanged but it now carries a new price/product.

func (*Queries) UpdateSubscriptionStatus

func (q *Queries) UpdateSubscriptionStatus(ctx context.Context, arg UpdateSubscriptionStatusParams) (Subscription, error)

func (*Queries) UpdateTierRank

func (q *Queries) UpdateTierRank(ctx context.Context, arg UpdateTierRankParams) (PlanLadderTier, error)

func (*Queries) WithTx

func (q *Queries) WithTx(tx *sql.Tx) *Queries

type SetPaymentMethodIfNullParams

type SetPaymentMethodIfNullParams struct {
	PaymentMethodID string   `json:"payment_method_id"`
	PaymentIds      []string `json:"payment_ids"`
}

type SetPaymentTimeParams

type SetPaymentTimeParams struct {
	Overwrite bool      `json:"overwrite"`
	OutcomeAt time.Time `json:"outcome_at"`
	PaymentID string    `json:"payment_id"`
	Outcome   string    `json:"outcome"`
}

type SetPlanLadderSortOrderParams

type SetPlanLadderSortOrderParams struct {
	PlanLadderID string `json:"plan_ladder_id"`
	SortOrder    int32  `json:"sort_order"`
}

type Subscription

type Subscription struct {
	SubscriptionID           string         `json:"subscription_id"`
	BillingAccountID         string         `json:"billing_account_id"`
	Status                   string         `json:"status"`
	CurrentPeriodStart       sql.NullTime   `json:"current_period_start"`
	CurrentPeriodEnd         sql.NullTime   `json:"current_period_end"`
	CancelAtPeriodEnd        bool           `json:"cancel_at_period_end"`
	CanceledAt               sql.NullTime   `json:"canceled_at"`
	EndedAt                  sql.NullTime   `json:"ended_at"`
	CreatedAt                time.Time      `json:"created_at"`
	UpdatedAt                time.Time      `json:"updated_at"`
	CommitmentEnd            sql.NullTime   `json:"commitment_end"`
	CommitmentRenewal        sql.NullString `json:"commitment_renewal"`
	EarlyTerminationPolicy   sql.NullString `json:"early_termination_policy"`
	PauseCollectionBehavior  sql.NullString `json:"pause_collection_behavior"`
	PauseCollectionResumesAt sql.NullTime   `json:"pause_collection_resumes_at"`
	PauseCollectionMarked    bool           `json:"pause_collection_marked"`
}

type SubscriptionChange

type SubscriptionChange struct {
	ChangeID       string         `json:"change_id"`
	SubscriptionID string         `json:"subscription_id"`
	PreviousStatus sql.NullString `json:"previous_status"`
	NewStatus      string         `json:"new_status"`
	StripeEventID  string         `json:"stripe_event_id"`
	ChangedAt      time.Time      `json:"changed_at"`
}

type SubscriptionItem

type SubscriptionItem struct {
	SubscriptionItemID string       `json:"subscription_item_id"`
	SubscriptionID     string       `json:"subscription_id"`
	ProductID          string       `json:"product_id"`
	PriceID            string       `json:"price_id"`
	Quantity           int32        `json:"quantity"`
	CreatedAt          time.Time    `json:"created_at"`
	UpdatedAt          time.Time    `json:"updated_at"`
	EndedAt            sql.NullTime `json:"ended_at"`
}

type SubscriptionScheduledChange

type SubscriptionScheduledChange struct {
	ScheduledChangeID string         `json:"scheduled_change_id"`
	SubscriptionID    string         `json:"subscription_id"`
	ChangeType        string         `json:"change_type"`
	TargetPriceID     uuid.NullUUID  `json:"target_price_id"`
	TargetQuantity    sql.NullInt32  `json:"target_quantity"`
	EffectiveAt       time.Time      `json:"effective_at"`
	EffectiveTrigger  string         `json:"effective_trigger"`
	CreditDisposition sql.NullString `json:"credit_disposition"`
	Status            string         `json:"status"`
	CreatedAt         time.Time      `json:"created_at"`
	UpdatedAt         time.Time      `json:"updated_at"`
}

type SumMonthlyRecurringByCurrencyRow

type SumMonthlyRecurringByCurrencyRow struct {
	Currency     string `json:"currency"`
	MonthlyCents int64  `json:"monthly_cents"`
}

type UpdateInvoicePaidParams

type UpdateInvoicePaidParams struct {
	InvoiceID  string       `json:"invoice_id"`
	AmountPaid int32        `json:"amount_paid"`
	PaidAt     sql.NullTime `json:"paid_at"`
}

type UpdatePaymentMethodSafeFieldsParams

type UpdatePaymentMethodSafeFieldsParams struct {
	PaymentMethodID string         `json:"payment_method_id"`
	CardBrand       sql.NullString `json:"card_brand"`
	CardLast4       sql.NullString `json:"card_last4"`
	CardExpMonth    sql.NullInt32  `json:"card_exp_month"`
	CardExpYear     sql.NullInt32  `json:"card_exp_year"`
	Funding         sql.NullString `json:"funding"`
}

type UpdatePlanLadderParams

type UpdatePlanLadderParams struct {
	PlanLadderID string         `json:"plan_ladder_id"`
	Name         string         `json:"name"`
	Description  sql.NullString `json:"description"`
	IsActive     bool           `json:"is_active"`
}

type UpdateProductParams

type UpdateProductParams struct {
	ProductID        string                `json:"product_id"`
	Name             string                `json:"name"`
	Description      sql.NullString        `json:"description"`
	DisplayCategory  sql.NullString        `json:"display_category"`
	IsActive         bool                  `json:"is_active"`
	IsPublic         bool                  `json:"is_public"`
	EntitlementSetID uuid.NullUUID         `json:"entitlement_set_id"`
	Metadata         pqtype.NullRawMessage `json:"metadata"`
}

type UpdateSubscriptionCollectionParams

type UpdateSubscriptionCollectionParams struct {
	SubscriptionID           string         `json:"subscription_id"`
	PauseCollectionBehavior  sql.NullString `json:"pause_collection_behavior"`
	PauseCollectionResumesAt sql.NullTime   `json:"pause_collection_resumes_at"`
	PauseCollectionMarked    bool           `json:"pause_collection_marked"`
}

type UpdateSubscriptionItemPriceProductParams

type UpdateSubscriptionItemPriceProductParams struct {
	SubscriptionItemID string `json:"subscription_item_id"`
	ProductID          string `json:"product_id"`
	PriceID            string `json:"price_id"`
	Quantity           int32  `json:"quantity"`
}

type UpdateSubscriptionStatusParams

type UpdateSubscriptionStatusParams struct {
	SubscriptionID     string       `json:"subscription_id"`
	Status             string       `json:"status"`
	CurrentPeriodStart sql.NullTime `json:"current_period_start"`
	CurrentPeriodEnd   sql.NullTime `json:"current_period_end"`
	CancelAtPeriodEnd  bool         `json:"cancel_at_period_end"`
	CanceledAt         sql.NullTime `json:"canceled_at"`
	EndedAt            sql.NullTime `json:"ended_at"`
}

type UpdateTierRankParams

type UpdateTierRankParams struct {
	PlanLadderID string `json:"plan_ladder_id"`
	ProductID    string `json:"product_id"`
	Rank         int32  `json:"rank"`
}

Jump to

Keyboard shortcuts

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