Documentation
¶
Overview ¶
Package billing implements plan management, usage credits, Stripe integration, and feature gating for the Bowrain platform.
Index ¶
- Constants
- Variables
- func AdminGuard(idTokenVerifier, accessTokenVerifier *oidc.IDTokenVerifier) echo.MiddlewareFunc
- func ContainerTimeCredits(d time.Duration) int64
- func CreditsForPlan(plan Plan) int64
- func EnsureTrialGrant(ctx context.Context, store BillingStore, workspaceID string)
- func GetLimit(plan Plan, limitName string) int
- func GuardSyncCredits(c *echo.Context, store BillingStore, byo bool, onBlock ...GuardEventFunc) error
- func HasFeature(plan Plan, feature Feature, overrides ...map[Feature]bool) bool
- func IsPlaceholder(v string) bool
- func IsStripePriceID(v string) bool
- func IsStripeSecretKey(v string) bool
- func IsStripeWebhookSecret(v string) bool
- func MarshalLandingPlanCatalog() ([]byte, error)
- func MonthEnd(t time.Time) time.Time
- func MonthStart(t time.Time) time.Time
- func OverridesFromContext(c *echo.Context) map[Feature]bool
- func PlanGuard(feature Feature, onBlock ...GuardEventFunc) echo.MiddlewareFunc
- func ProjectAbuseCap(plan Plan) int
- func QuotaGuard(store BillingStore, onBlock ...GuardEventFunc) echo.MiddlewareFunc
- func RequireFeature(c *echo.Context, feature Feature, onBlock ...GuardEventFunc) error
- func SetupTrial(ctx context.Context, store BillingStore, workspaceID string, ...)
- func SetupTrialWith(ctx context.Context, store BillingStore, workspaceID string, plan Plan, ...)
- func TokensToCredits(tokens int) int64
- type BillingEvent
- type BillingNotifier
- func (n *BillingNotifier) NotifyCreditsExhausted(ctx context.Context, email, workspaceID string)
- func (n *BillingNotifier) NotifyCreditsWarning(ctx context.Context, email, workspaceID string, used, total int64)
- func (n *BillingNotifier) NotifyPaymentFailed(ctx context.Context, email, workspaceID string)
- func (n *BillingNotifier) NotifySubscriptionChanged(ctx context.Context, email, workspaceID string, plan Plan, status string)
- type BillingStore
- type CheckoutOptions
- type CreditAllocation
- type EmailSender
- type EventTracker
- type ExpiredTrial
- type Feature
- type FeatureOverride
- type GuardEventFunc
- type LandingPlan
- type LandingPlanCatalog
- type LedgerEntry
- type LedgerPage
- type LedgerQuery
- type PgBillingStore
- func (s *PgBillingStore) AddNote(ctx context.Context, note *WorkspaceNote) error
- func (s *PgBillingStore) CheckCredits(ctx context.Context, workspaceID string) (int64, error)
- func (s *PgBillingStore) DeductCredits(ctx context.Context, workspaceID string, amount int64, op string, refID string) error
- func (s *PgBillingStore) DeleteFeatureOverride(ctx context.Context, workspaceID string, feature Feature) error
- func (s *PgBillingStore) ExpireTrials(ctx context.Context, now time.Time, limit int) ([]ExpiredTrial, error)
- func (s *PgBillingStore) GetCurrentAllocation(ctx context.Context, workspaceID string) (*CreditAllocation, error)
- func (s *PgBillingStore) GetFeatureOverrides(ctx context.Context, workspaceID string) ([]FeatureOverride, error)
- func (s *PgBillingStore) GetLedger(ctx context.Context, workspaceID string, from, to time.Time) ([]LedgerEntry, error)
- func (s *PgBillingStore) GetLedgerPage(ctx context.Context, workspaceID string, q LedgerQuery) (*LedgerPage, error)
- func (s *PgBillingStore) GetNetByOperation(ctx context.Context, workspaceID string, from, to time.Time) (map[string]int64, error)
- func (s *PgBillingStore) GetPlatformMetrics(ctx context.Context) (*PlatformMetrics, error)
- func (s *PgBillingStore) GetSubscription(ctx context.Context, workspaceID string) (*Subscription, error)
- func (s *PgBillingStore) GetUpsellOpportunities(ctx context.Context) ([]UpsellOpportunity, error)
- func (s *PgBillingStore) GetUsageByOperation(ctx context.Context, workspaceID string, from, to time.Time) (map[string]int64, error)
- func (s *PgBillingStore) GrantCredits(ctx context.Context, workspaceID string, amount int64, source string) error
- func (s *PgBillingStore) GrantPurchasedCredits(ctx context.Context, workspaceID string, amount int64, referenceID string) (bool, error)
- func (s *PgBillingStore) GrantTrialCredits(ctx context.Context, workspaceID string, amount int64) (bool, error)
- func (s *PgBillingStore) ListAllFeatureOverrides(ctx context.Context) ([]FeatureOverride, error)
- func (s *PgBillingStore) ListBillingEvents(ctx context.Context, limit, offset int, eventType string) ([]BillingEvent, error)
- func (s *PgBillingStore) ListNotes(ctx context.Context, workspaceID string) ([]WorkspaceNote, error)
- func (s *PgBillingStore) ListSubscriptions(ctx context.Context, limit, offset int) ([]*Subscription, error)
- func (s *PgBillingStore) MarkStripeEventProcessed(ctx context.Context, eventID, eventType string) (bool, error)
- func (s *PgBillingStore) RecordBillingEvent(ctx context.Context, event *BillingEvent) error
- func (s *PgBillingStore) SetFeatureOverride(ctx context.Context, override *FeatureOverride) error
- func (s *PgBillingStore) UnmarkStripeEvent(ctx context.Context, eventID string) error
- func (s *PgBillingStore) UpsertSubscription(ctx context.Context, sub *Subscription) error
- type Plan
- type PlanInfo
- type PlatformMetrics
- type StripeClient
- func (c *StripeClient) CreateCheckoutSession(_ context.Context, customerID, priceID, successURL, cancelURL string, ...) (string, error)
- func (c *StripeClient) CreateCheckoutSessionWithOptions(customerID, priceID, successURL, cancelURL string, opts CheckoutOptions) (string, error)
- func (c *StripeClient) CreateCustomer(_ context.Context, workspaceID, email, name string) (string, error)
- func (c *StripeClient) CreatePaymentCheckout(_ context.Context, customerID, priceID, successURL, cancelURL string, ...) (string, error)
- func (c *StripeClient) CreatePortalSession(_ context.Context, customerID, returnURL string) (string, error)
- func (c *StripeClient) GetInvoices(_ context.Context, customerID string, limit int) ([]StripeInvoice, error)
- func (c *StripeClient) ReportMeterEvent(ctx context.Context, customerID, eventName string, value int64, ...)
- type StripeInvoice
- type Subscription
- type TrialSweepStore
- type TrialSweeper
- type UpsellOpportunity
- type UsageHooks
- type WebhookHandler
- type WorkspaceNote
- type WorkspacePlanSyncer
Constants ¶
const ( SourcePlan = "plan" SourceTrial = "trial" SourcePurchased = "purchased" )
Credit allocation sources. Credits are the single user-facing ledger (Epic 004). A workspace draws from three buckets:
- SourcePlan: the monthly plan allowance for PAID plans (see MonthlyCredits). Scoped to the current calendar month; unspent plan credits expire at month rollover. Free has no recurring allowance.
- SourceTrial: the one-time trial grant every workspace receives at creation (FreeTrialGrantCredits). Non-expiring, granted exactly once per workspace, ever — it is what bounds free-tier cost exposure now that the Free plan has no recurring allowance.
- SourcePurchased: one-time top-up packs bought with Stripe. Non-expiring — they persist across monthly rollovers until spent (see the non-expiring sentinel below).
Spend cascades plan → trial → purchased (PgBillingStore.DeductCredits): the expiring bucket is drained first (it evaporates at month end anyway), then the promotional trial grant, and paid-for pack credits last — a customer's paid balance is preserved the longest. The spendable balance sums all three (PgBillingStore.CheckCredits).
const ( LimitMaxCustodians = "max-custodians" LimitMaxMarkets = "max-markets" LimitMaxBrands = "max-brands" )
PlanLimits defines numeric plan limits; -1 means unlimited.
Custodians have grants to manage voice or terms within a region. Free includes no custodians; SetupTrial grants Pro access for DefaultTrialDays. Markets and brands limit the scope available to a workspace.
Members, checks and coordinates are not metered. Viewer and contributor accounts and machine tokens are uncapped. Markets and brands are plan limits, not per-coordinate charges.
Configure limits here; dollar prices are stored in Stripe (DECISIONS L4). Named limits below let the compiler catch misspelled keys.
const ( // ProMonthlyCredits is Pro's monthly plan allowance (4× the former 500K // weekly allowance). ProMonthlyCredits = 2_000_000 // TeamMonthlyCredits is Team's monthly plan allowance (4× the former 2M // weekly allowance). TeamMonthlyCredits = 8_000_000 // FreeTrialGrantCredits is the one-time, non-expiring credit grant every // new workspace receives at creation (source='trial'). It replaces the // Free tier's recurring allowance — Free's MonthlyCredits is 0 — so the // platform's free-tier cost exposure is bounded to exactly one grant per // workspace instead of an open-ended weekly drip. FreeTrialGrantCredits = 200_000 )
Credit allowance tuning knobs. These are the ONLY places the numbers live — every surface (allocation grants, /billing/plans payload, pricing copy) derives from them. The current values are provisional: Pro/Team are the former weekly allowances ×4, and the final numbers come from the cold-start estimator data. Tune here, nowhere else.
const ContextKeyFeatureOverrides = "feature_overrides"
ContextKeyFeatureOverrides is the echo context key under which the resolved per-workspace feature overrides (map[Feature]bool) are stored. It is populated by the server's feature-overrides middleware after workspace access resolves, and read by PlanGuard and by handlers that surface entitlements to clients. Exported so the server package sets the same key PlanGuard reads.
const CreditPackCredits = 200_000
CreditPackCredits is the credit grant for one purchased top-up pack. The pack is $5 (the dollar amount lives in Stripe, DECISIONS L4); this is the credit side of that same SKU, so it must stay in step with the price the provisioning tool creates and with what the pricing page advertises. Packs do not expire — they are drawn from only after the monthly plan allowance and the trial grant (Epic 004; cascade order in credits.go).
const DefaultTrialDays = 14
DefaultTrialDays is the default Pro trial period for new workspaces.
const FreeProjectAbuseCap = 3
FreeProjectAbuseCap bounds how many projects a free workspace may hold.
This is an abuse guard, not a meter, and the difference is the reason it lives here rather than in PlanLimits. A meter is something a customer buys more of; nothing about a paid plan says "more projects", and no pricing surface mentions a project count. What this stops is scripted workspace creation burning storage behind an account with no payment instrument — which is also why it applies only to Free. A card is its own abuse control.
Keep it out of PlanLimits, PlanInfo and LandingPlan. The moment a project count appears beside markets and brands, customers start contorting their project structure to fit the bill, which is exactly what dropping the old max-projects meter was for.
const MaxLedgerPageSize = 500
MaxLedgerPageSize bounds one page of ledger entries. GetLedgerPage clamps to it; handlers reuse it so a client sees the same ceiling it will get.
Variables ¶
var Migrations = []storage.Migration{
{
Version: 8,
Description: "billing baseline (folds 1-7) + idempotent referenced deductions",
SQL: `
CREATE TABLE IF NOT EXISTS subscriptions (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL UNIQUE,
-- Nullable with an empty default, and deliberately NOT UNIQUE
-- here: a subscription that never went through Stripe (a local
-- trial, an admin override) has no customer id, and many of them
-- would collide on ''. Uniqueness is enforced by the partial
-- index below, over real customer ids only.
stripe_customer_id TEXT DEFAULT '',
stripe_subscription_id TEXT,
plan TEXT NOT NULL DEFAULT 'free',
status TEXT NOT NULL DEFAULT 'active',
seat_count INTEGER NOT NULL DEFAULT 1,
current_period_start TIMESTAMPTZ,
current_period_end TIMESTAMPTZ,
cancel_at TIMESTAMPTZ,
trial_ends_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE UNIQUE INDEX IF NOT EXISTS subscriptions_stripe_customer_id_key
ON subscriptions (stripe_customer_id)
WHERE stripe_customer_id IS NOT NULL AND stripe_customer_id != '';
CREATE INDEX IF NOT EXISTS idx_subscriptions_trialing
ON subscriptions (trial_ends_at)
WHERE status = 'trialing';
CREATE TABLE IF NOT EXISTS credit_allocations (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
credits_total BIGINT NOT NULL,
credits_used BIGINT NOT NULL DEFAULT 0,
week_start TIMESTAMPTZ NOT NULL,
week_end TIMESTAMPTZ NOT NULL,
source TEXT NOT NULL DEFAULT 'plan',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE(workspace_id, week_start, source)
);
CREATE TABLE IF NOT EXISTS credit_ledger (
id BIGSERIAL PRIMARY KEY,
workspace_id TEXT NOT NULL,
allocation_id TEXT,
amount BIGINT NOT NULL,
balance_after BIGINT NOT NULL,
operation TEXT NOT NULL,
reference_id TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_credit_ledger_workspace ON credit_ledger(workspace_id, created_at);
-- A purchased credit-pack grant must happen exactly once per Stripe
-- checkout, even though the webhook can be delivered more than once
-- and rolls its event marker back on a partial failure. The Stripe
-- session id lands in reference_id; this makes a second grant for the
-- same session collide rather than double-credit the workspace.
CREATE UNIQUE INDEX IF NOT EXISTS credit_ledger_purchase_ref
ON credit_ledger (workspace_id, reference_id)
WHERE operation = 'purchase' AND reference_id <> '';
-- Metered work is charged against a reference the caller can
-- reproduce (a job id and its chunk offset, a message id), so a
-- redelivered job must not pay twice for a chunk it already paid
-- for. Surplus rows are the charges a retry already made: everything
-- past the first entry for one (workspace, operation, reference,
-- allocation). Deleting them and giving the credits back is both the
-- repair and what lets the index below be created on a database that
-- already double-charged. Only debits qualify: a positive amount is
-- a grant, and grants carry no reference.
WITH surplus AS (
SELECT id, allocation_id, amount FROM (
SELECT id, allocation_id, amount,
row_number() OVER (
PARTITION BY workspace_id, operation, reference_id, allocation_id
ORDER BY id
) AS seq
FROM credit_ledger
WHERE COALESCE(reference_id, '') <> '' AND amount < 0
) ranked WHERE seq > 1
), refund AS (
SELECT allocation_id, SUM(amount) AS delta FROM surplus
WHERE allocation_id IS NOT NULL GROUP BY allocation_id
), restored AS (
UPDATE credit_allocations a
SET credits_used = GREATEST(a.credits_used + r.delta, 0)
FROM refund r WHERE a.id = r.allocation_id
RETURNING a.id
)
DELETE FROM credit_ledger WHERE id IN (SELECT id FROM surplus);
CREATE UNIQUE INDEX IF NOT EXISTS credit_ledger_usage_ref
ON credit_ledger (workspace_id, operation, reference_id, allocation_id)
WHERE reference_id <> '';
CREATE TABLE IF NOT EXISTS feature_overrides (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL,
feature TEXT NOT NULL,
enabled BOOLEAN NOT NULL,
reason TEXT,
created_by TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ,
UNIQUE(workspace_id, feature)
);
CREATE TABLE IF NOT EXISTS workspace_notes (
id BIGSERIAL PRIMARY KEY,
workspace_id TEXT NOT NULL,
author_email TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS billing_events (
id BIGSERIAL PRIMARY KEY,
workspace_id TEXT NOT NULL,
event_type TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_billing_events_type ON billing_events(event_type, created_at);
CREATE TABLE IF NOT EXISTS processed_stripe_events (
event_id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Monthly credits: plan allocations are keyed on the CALENDAR MONTH
-- (UTC) rather than the calendar week, the Free plan has no recurring
-- allowance (replaced by a one-time source='trial' grant in the
-- non-expiring sentinel period, like purchased packs), and spend
-- cascades plan -> trial -> purchased. The week_* column names are
-- historical; renaming them is not a zero-downtime change and buys
-- nothing, so the meaning is documented on the columns instead.
COMMENT ON COLUMN credit_allocations.week_start IS
'Allocation period start (UTC). plan: calendar-month start (calendar-week Monday before the monthly-credits change); trial/purchased: non-expiring sentinel 1970-01-01. Column name is historical.';
COMMENT ON COLUMN credit_allocations.week_end IS
'Allocation period end, exclusive (UTC). plan: next month start; trial/purchased: non-expiring sentinel 9999-01-01. Column name is historical.';
`,
},
}
Migrations is the billing schema as a single consolidated baseline.
LEDGER — every version this subsystem has ever issued, now folded in:
1 create billing tables 2 allow empty stripe_customer_id for non-Stripe subscriptions (trials, admin overrides) 3 track processed Stripe webhook events for idempotent delivery 4 give local trials an end date so they can expire 5 idempotency guard for one-time credit-pack grants 6 document the monthly-credits period model on the allocation columns 7 billing baseline (folded 1-6)
The subsystem carries exactly one baseline (migrations/schema_test.go enforces it), so a schema change is made by editing the baseline in place and bumping its version. Version 8 makes a referenced deduction idempotent: it repairs the ledger rows a retry duplicated, refunds them, and adds the unique index that stops the next one.
NEVER reuse a version number, even for a migration later found unnecessary: deployed databases record applied versions and silently skip a reused number (see the repo-wide migration-squash postmortem).
Two things v2 did are folded rather than replayed. It dropped the inline UNIQUE on subscriptions.stripe_customer_id and replaced it with a PARTIAL unique index of the same name, so the baseline declares the column without a constraint and creates that index directly. The v4 backfill (dating existing trials from created_at) is not carried: it repaired rows written before trial_ends_at existed, and a database built from this baseline has none.
Baseline is version 8 — above every number issued, so an existing database applies it once and any drift between its schema and its bookkeeping is repaired. Retired numbers are never reused; the next migration is version 9.
var MonthlyCredits = map[Plan]int64{ PlanFree: 0, PlanPro: ProMonthlyCredits, PlanTeam: TeamMonthlyCredits, PlanEnterprise: -1, }
MonthlyCredits defines the monthly AI credit allocation per plan. A value of -1 means unlimited (Enterprise); 0 means no recurring allowance (Free — its credits are the one-time FreeTrialGrantCredits grant).
var PerSeatPlans = map[Plan]bool{ PlanTeam: true, }
PerSeatPlans are the plans priced per seat: the Stripe subscription quantity is the seat count, so checkout must send it and seat changes re-price.
var PlanDisplayNames = map[Plan]string{ PlanFree: "Free", PlanPro: "Pro", PlanTeam: "Team", PlanEnterprise: "Enterprise", }
PlanDisplayNames are the human-readable plan names shown in the UI.
var PlanFeatures = map[Plan]map[Feature]bool{ PlanFree: { FeatureBravo: false, FeatureBravoCodeExec: false, FeatureConnectorsGit: false, FeatureAPIAccess: true, FeatureConnectorsCustom: false, FeatureSSOSAML: false, }, PlanPro: { FeatureBravo: false, FeatureBravoCodeExec: false, FeatureConnectorsGit: true, FeatureConnectorsCustom: false, FeatureAPIAccess: true, FeatureSSOSAML: false, }, PlanTeam: { FeatureBravo: false, FeatureBravoCodeExec: true, FeatureConnectorsGit: true, FeatureConnectorsCustom: true, FeatureAPIAccess: true, FeatureSSOSAML: false, }, PlanEnterprise: { FeatureBravo: false, FeatureBravoCodeExec: true, FeatureConnectorsGit: true, FeatureConnectorsCustom: true, FeatureAPIAccess: true, FeatureSSOSAML: true, }, }
PlanFeatures defines which features are available on each plan. This is the source of truth for feature gating.
var PlanLimits = map[Plan]map[string]int{ PlanFree: {"max-custodians": 0, "max-markets": 2, "max-brands": 1}, PlanPro: {"max-custodians": 1, "max-markets": 5, "max-brands": 1}, PlanTeam: {"max-custodians": 5, "max-markets": 25, "max-brands": 3}, PlanEnterprise: {"max-custodians": -1, "max-markets": -1, "max-brands": -1}, }
var SelfServePlans = []Plan{PlanPro, PlanTeam}
SelfServePlans are the plans a workspace owner can subscribe to from the app. Free is the downgrade target rather than a purchase, and Enterprise is sold by hand, so neither is self-serve.
var ValidPlans = map[Plan]bool{ PlanFree: true, PlanPro: true, PlanTeam: true, PlanEnterprise: true, }
ValidPlans is the set of valid Plan values.
Functions ¶
func AdminGuard ¶
func AdminGuard(idTokenVerifier, accessTokenVerifier *oidc.IDTokenVerifier) echo.MiddlewareFunc
AdminGuard returns Echo middleware that verifies the JWT was issued by the admin Keycloak realm. It accepts both access tokens and ID tokens. Two verifiers are needed because Keycloak access tokens use aud="account" while ID tokens use aud=<client_id>. It sets "admin_email" and "admin_name" on the context.
func ContainerTimeCredits ¶
ContainerTimeCredits converts container time duration to credits. Container time costs 10 credits per second.
func CreditsForPlan ¶
CreditsForPlan returns the monthly credit allocation for a plan. Returns -1 for unlimited (Enterprise) and 0 for no recurring allowance (Free and any unknown plan — the safe default is to grant nothing).
func EnsureTrialGrant ¶
func EnsureTrialGrant(ctx context.Context, store BillingStore, workspaceID string)
EnsureTrialGrant grants the workspace its one-time trial credits if it has never received them. It is called at workspace creation (onboarding and explicit workspace creation) and — as a lazy backfill for workspaces created before the trial-grant model existed — from the allocation middleware for plans with no recurring allowance. Idempotent: at most one trial grant per workspace, ever (enforced by the store's unique key). Nil-store safe; errors are logged, not returned, because a missed grant self-heals on the next touch and must never fail workspace creation.
func GetLimit ¶
GetLimit returns a numeric limit for a plan. Returns -1 if the limit is not defined (treated as unlimited).
func GuardSyncCredits ¶
func GuardSyncCredits(c *echo.Context, store BillingStore, byo bool, onBlock ...GuardEventFunc) error
GuardSyncCredits enforces the credit gate from inside a handler, where BYO is known from the parsed request body. It returns a non-nil echo 429 error when the workspace is out of platform credits and the request is NOT BYO; nil (allow) otherwise. It is the body-aware counterpart to the QuotaGuard middleware: a synchronous AI route that accepts a bring-your-own key (provider_config_id / api_key) cannot be wrapped by QuotaGuard, because the middleware cannot see the body to know the request burns no credits.
Like QuotaGuard, it degrades to allow when billing is not configured, the plan is empty or enterprise, there is no workspace context, or the balance is unreadable — so a self-hosted or misconfigured deployment is never blocked.
func HasFeature ¶
HasFeature checks whether a plan grants access to a feature, considering optional per-workspace overrides. Overrides take precedence over the plan matrix.
func IsPlaceholder ¶
IsPlaceholder reports whether v is the placeholder value Terraform seeds the Stripe SSM parameters with. Callers use it to distinguish "an operator has not provisioned Stripe yet" (expected before epic 005's provisioning step, worth a single informational log) from "an operator set something wrong" (worth a warning).
func IsStripePriceID ¶
IsStripePriceID checks the shape of a Stripe price ID. Missing or placeholder IDs make the plan unavailable for purchase in GET /billing/plans.
func IsStripeSecretKey ¶
IsStripeSecretKey reports whether v looks like a Stripe secret (or restricted) key.
"Non-empty" is not the same as "configured". Terraform creates the Stripe SSM parameters as literal "CHANGEME" placeholders (epic 002, modules/secrets), and STRIPE_SECRET_KEY being set is what the platform reads as *this is a billed deployment*: it enables the checkout surface, constructs the Stripe client, turns on worker credit metering, and makes a missing BOWRAIN_SECRETS_KEY a hard startup failure. A placeholder passing that test gives the worst of both worlds — the product advertises billing while every Stripe call 401s. Callers treat a value that fails this check as absent.
func IsStripeWebhookSecret ¶
IsStripeWebhookSecret reports whether v looks like a Stripe webhook signing secret. A placeholder here would fail every signature verification with a 400, which Stripe retries — better to report the endpoint as unconfigured.
func MarshalLandingPlanCatalog ¶
MarshalLandingPlanCatalog renders the catalog as the exact bytes committed to plans.json: 2-space-indented JSON with a trailing newline, HTML escaping off, so the file is diff-clean and byte-identical between the generator and the drift test.
func MonthEnd ¶
MonthEnd returns the first instant of the next calendar month (the exclusive end of the month containing t) — which is also when a paid plan's allowance refreshes.
func MonthStart ¶
MonthStart returns the first instant (day 1, 00:00 UTC) of the calendar month containing t.
func OverridesFromContext ¶
OverridesFromContext returns the per-workspace feature overrides stored on the echo context by the feature-overrides middleware, or nil if none are set.
func PlanGuard ¶
func PlanGuard(feature Feature, onBlock ...GuardEventFunc) echo.MiddlewareFunc
PlanGuard returns Echo middleware that rejects requests when the workspace plan does not include the required feature. It reads the plan from the echo context (set by workspace access middleware) and checks overrides. When billing is not configured (plan is empty), all features are allowed.
func ProjectAbuseCap ¶
ProjectAbuseCap returns the project ceiling for a plan, or -1 for no ceiling. Only Free is bounded; see FreeProjectAbuseCap for why.
func QuotaGuard ¶
func QuotaGuard(store BillingStore, onBlock ...GuardEventFunc) echo.MiddlewareFunc
QuotaGuard returns Echo middleware that rejects requests when the workspace's spendable credits (monthly plan allowance + trial grant + purchased packs) are exhausted. Returns 429 with Retry-After set to the next month start (00:00 UTC on the 1st) — when a paid plan's allowance refreshes. When billing is not configured (store is nil or plan is empty), all requests pass.
func RequireFeature ¶
func RequireFeature(c *echo.Context, feature Feature, onBlock ...GuardEventFunc) error
RequireFeature is PlanGuard for a decision a handler can only make after reading the request body — a connector's type, say, which decides whether the request needs a paid feature at all. It returns nil when the workspace is entitled, and otherwise writes the same 403 `upgrade_required` payload the middleware writes, so the client's upgrade prompt does not have to know which of the two blocked it.
Like PlanGuard, it allows everything when no plan is on the context (billing not configured — a self-hosted deployment gates nothing).
func SetupTrial ¶
func SetupTrial(ctx context.Context, store BillingStore, workspaceID string, syncer ...WorkspacePlanSyncer)
SetupTrial sets up a 14-day Pro trial for a new workspace, using the product defaults (PlanPro, DefaultTrialDays). See SetupTrialWith for the config-driven variant (ctrl-managed new-workspace plan/trial defaults).
func SetupTrialWith ¶
func SetupTrialWith(ctx context.Context, store BillingStore, workspaceID string, plan Plan, trialDays int, syncer ...WorkspacePlanSyncer)
SetupTrialWith sets up a trial for a new workspace on the given plan and duration. This is the config-driven entry point: callers pass the instance's ctrl-managed new-workspace defaults (platformconfig DefaultPlan / TrialDays) so an admin can change the plan and trial length without a redeploy. An invalid plan falls back to PlanPro and a non-positive trialDays to DefaultTrialDays, so a misconfigured value never breaks signup.
The trial is local and card-free: no Stripe subscription exists for it, so nothing in Stripe ends it. Its whole lifecycle is the trial_ends_at deadline written here and the TrialSweeper that enforces it. (A Stripe-side trial via CheckoutOptions.TrialDays would mean collecting a card at signup, which is the wrong trade for a self-serve launch — see AD-018.)
The trial grants the plan's FEATURES, not its monthly credit allowance: the `trialing` status makes EnsureMonthlyAllocation skip the paid plan grant, and the workspace's AI credits during (and after) the trial are its one-time trial grant (EnsureTrialGrant, made at workspace creation). This is what bounds per-signup cost exposure to FreeTrialGrantCredits.
If a WorkspacePlanSyncer is provided, the workspace's cached plan field is updated to match the trial plan.
func TokensToCredits ¶
TokensToCredits converts AI token count to credits. 1 token = 1 credit.
Types ¶
type BillingEvent ¶
type BillingEvent struct {
ID int64 `json:"id"`
WorkspaceID string `json:"workspace_id"`
EventType string `json:"event_type"` // subscription_created, subscription_updated, payment_failed, credits_purchased, plan_changed, feature_override
Detail string `json:"detail"`
CreatedAt time.Time `json:"created_at"`
}
BillingEvent represents a billing-related event for the admin event feed.
type BillingNotifier ¶
type BillingNotifier struct {
Sender EmailSender
Store BillingStore
}
BillingNotifier sends billing-related email notifications. All methods are safe to call on a nil receiver (no-op).
func (*BillingNotifier) NotifyCreditsExhausted ¶
func (n *BillingNotifier) NotifyCreditsExhausted(ctx context.Context, email, workspaceID string)
NotifyCreditsExhausted sends a notice when credits reach zero.
func (*BillingNotifier) NotifyCreditsWarning ¶
func (n *BillingNotifier) NotifyCreditsWarning(ctx context.Context, email, workspaceID string, used, total int64)
NotifyCreditsWarning sends a warning when credits reach 80% usage.
func (*BillingNotifier) NotifyPaymentFailed ¶
func (n *BillingNotifier) NotifyPaymentFailed(ctx context.Context, email, workspaceID string)
NotifyPaymentFailed sends a grace period notice when payment fails.
func (*BillingNotifier) NotifySubscriptionChanged ¶
func (n *BillingNotifier) NotifySubscriptionChanged(ctx context.Context, email, workspaceID string, plan Plan, status string)
NotifySubscriptionChanged sends a confirmation when the subscription changes.
type BillingStore ¶
type BillingStore interface {
// Subscriptions
GetSubscription(ctx context.Context, workspaceID string) (*Subscription, error)
UpsertSubscription(ctx context.Context, sub *Subscription) error
ListSubscriptions(ctx context.Context, limit, offset int) ([]*Subscription, error)
// Credits
GetCurrentAllocation(ctx context.Context, workspaceID string) (*CreditAllocation, error)
DeductCredits(ctx context.Context, workspaceID string, amount int64, op string, refID string) error
CheckCredits(ctx context.Context, workspaceID string) (remaining int64, err error)
GrantCredits(ctx context.Context, workspaceID string, amount int64, source string) error
// GrantPurchasedCredits grants a one-time credit pack idempotently, keyed on
// referenceID (the Stripe checkout session id). It returns granted=false when
// the reference was already granted — a duplicate webhook delivery — so the
// caller can treat it as success without re-crediting. See the PgBillingStore
// implementation for why the webhook's marker-rollback makes this necessary.
GrantPurchasedCredits(ctx context.Context, workspaceID string, amount int64, referenceID string) (granted bool, err error)
// GrantTrialCredits grants the workspace's one-time trial credits
// (source='trial', non-expiring). At most one grant per workspace, EVER —
// keyed on the allocation table's unique constraint — so it is safe to call
// on every touch (the allocation middleware uses it as a lazy backfill).
// Returns granted=false when the workspace already has its grant.
GrantTrialCredits(ctx context.Context, workspaceID string, amount int64) (granted bool, err error)
// Ledger
GetLedger(ctx context.Context, workspaceID string, from, to time.Time) ([]LedgerEntry, error)
// GetLedgerPage returns one page of the ledger, filtered and counted in
// SQL. It is what a client-facing history view reads: GetLedger returns
// the whole window and is for callers that need every row.
GetLedgerPage(ctx context.Context, workspaceID string, q LedgerQuery) (*LedgerPage, error)
// GetUsageByOperation sums the debits in the window per operation, so the
// usage breakdown does not depend on how many entries a page carries.
GetUsageByOperation(ctx context.Context, workspaceID string, from, to time.Time) (map[string]int64, error)
// GetNetByOperation sums EVERY movement in the window per operation, signed:
// a debit stays negative, a purchase or grant positive.
//
// It exists because GetUsageByOperation answers a narrower question than its
// key set suggests. Summing `amount < 0` only, it never mentions purchase,
// grant, expire or plan_reset — so a client deriving the ledger's operation
// filter from it could not offer the operations the ledger table right below
// was displaying. This one names every operation the window contains.
GetNetByOperation(ctx context.Context, workspaceID string, from, to time.Time) (map[string]int64, error)
// Feature overrides
GetFeatureOverrides(ctx context.Context, workspaceID string) ([]FeatureOverride, error)
ListAllFeatureOverrides(ctx context.Context) ([]FeatureOverride, error)
SetFeatureOverride(ctx context.Context, override *FeatureOverride) error
DeleteFeatureOverride(ctx context.Context, workspaceID string, feature Feature) error
// Notes
ListNotes(ctx context.Context, workspaceID string) ([]WorkspaceNote, error)
AddNote(ctx context.Context, note *WorkspaceNote) error
// Upsells
GetUpsellOpportunities(ctx context.Context) ([]UpsellOpportunity, error)
// Metrics
GetPlatformMetrics(ctx context.Context) (*PlatformMetrics, error)
// Events
ListBillingEvents(ctx context.Context, limit, offset int, eventType string) ([]BillingEvent, error)
RecordBillingEvent(ctx context.Context, event *BillingEvent) error
// Webhook idempotency
//
// MarkStripeEventProcessed records that a Stripe webhook event has been
// processed. It returns alreadyProcessed=true when the event ID was already
// present (i.e. this is a duplicate delivery), allowing callers to
// short-circuit before re-applying side effects such as granting credits.
// The insert uses ON CONFLICT DO NOTHING so concurrent duplicate deliveries
// race to a single winner.
MarkStripeEventProcessed(ctx context.Context, eventID, eventType string) (alreadyProcessed bool, err error)
// UnmarkStripeEvent removes the processed marker for an event ID. It is used
// to roll back the idempotency claim when downstream processing fails, so a
// retried delivery is reprocessed instead of being silently skipped.
UnmarkStripeEvent(ctx context.Context, eventID string) error
}
BillingStore persists subscription, credit, and billing-related data.
type CheckoutOptions ¶
type CheckoutOptions struct {
Metadata map[string]string
// Quantity is the subscription quantity, for a per-seat plan (Team) this is
// the seat count Stripe multiplies the per-seat price by. Zero means 1.
Quantity int64
// TrialDays puts the Stripe subscription into a trial. Unused at launch: the
// 14-day Pro trial is local and card-free (billing.SetupTrial), because a
// Stripe trial requires collecting a card at signup. See AD-018.
TrialDays int64
}
CheckoutOptions configures optional checkout behavior.
type CreditAllocation ¶
type CreditAllocation struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
CreditsTotal int64 `json:"credits_total"`
CreditsUsed int64 `json:"credits_used"`
PeriodStart time.Time `json:"period_start"`
PeriodEnd time.Time `json:"period_end"`
Source string `json:"source"` // "plan", "trial", or "purchased"
CreatedAt time.Time `json:"created_at"`
}
CreditAllocation tracks credit usage for a workspace within one allocation period: the current calendar month for plan allowances, the non-expiring sentinel period for trial grants and purchased packs. (The backing DB columns are still named week_start/week_end — historical, see billing migration 6.)
func EnsureMonthlyAllocation ¶
func EnsureMonthlyAllocation(ctx context.Context, store BillingStore, workspaceID string, plan Plan) (*CreditAllocation, error)
EnsureMonthlyAllocation lazily creates the current month's plan allocation for a PAID plan if one does not already exist, and returns it. It is invoked on every workspace-scoped request (MonthlyAllocationMiddleware), so the fast path is a single read.
Two deliberate skips (both return (nil, nil)):
- Plans with no recurring allowance (Free, MonthlyCredits == 0). The Free tier's credits are the one-time trial grant (EnsureTrialGrant), not a recurring allocation.
- Workspaces whose subscription is still `trialing`. The local card-free trial grants Pro *features*, not the Pro monthly credit allowance — otherwise every signup would mint a paid-size allocation and the founder's cost exposure would not be bounded to trial grants. The paid allowance starts with the first non-trialing month touch after conversion.
Transition note (weekly → monthly): rows from the weekly era are keyed on their old week bounds, so they simply age out — a paid workspace mid-week at deploy time gets its month allocation on next touch, and the month-keyed UNIQUE constraint (plus grant-once-per-period semantics in GrantCredits) prevents double-granting within the transition month.
type EmailSender ¶
EmailSender sends a rendered email to a recipient.
type EventTracker ¶
EventTracker captures product analytics events (e.g. PostHog).
type ExpiredTrial ¶
ExpiredTrial identifies a workspace whose local trial the sweeper just ended.
type Feature ¶
type Feature string
Feature represents a gated platform capability.
const ( // FeatureBravo gates the entire @bravo agent surface (chat panel, settings, // routes). It is dark by default — false on every plan — because @bravo's // self-hostable runtime is not launch-safe (see epic 015 / AD-016). The only // way to enable it is a per-workspace FeatureOverride via the control plane, // which lets the founder dogfood it without shipping it to customers. Flip a // plan's entry to true once the runtime + billing guardrails are hardened. FeatureBravo Feature = "bravo" FeatureBravoCodeExec Feature = "bravo-code-exec" FeatureConnectorsGit Feature = "connectors-git" FeatureConnectorsCustom Feature = "connectors-custom" FeatureAPIAccess Feature = "api-access" FeatureSSOSAML Feature = "sso-saml" )
type FeatureOverride ¶
type FeatureOverride struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
Feature Feature `json:"feature"`
Enabled bool `json:"enabled"`
Reason string `json:"reason,omitempty"`
CreatedBy string `json:"created_by"` // admin email
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
FeatureOverride allows per-workspace feature grants or revocations that override the plan matrix. Managed via the control plane.
type GuardEventFunc ¶
GuardEventFunc is an optional callback fired when PlanGuard or QuotaGuard blocks a request. Used for analytics (e.g. PostHog).
type LandingPlan ¶
type LandingPlan struct {
ID Plan `json:"id"`
Name string `json:"name"`
MonthlyCredits int64 `json:"monthlyCredits"` // -1 = unlimited, 0 = no recurring allowance
MaxMarkets int `json:"maxMarkets"` // -1 = unlimited
MaxBrands int `json:"maxBrands"` // -1 = unlimited
MaxCustodians int `json:"maxCustodians"` // 0 on Free, -1 = unlimited
PerSeat bool `json:"perSeat"`
SelfServe bool `json:"selfServe"`
}
LandingPlan is one plan's Go-sourced FACTS, serialized into the committed landing-page catalog (bowrain/web/landing/src/generated/plans.json). It deliberately carries no dollar price — that lives in Stripe (DECISIONS L4) and is hand-authored marketing copy on the landing page. The landing pairs these facts with the copy (price, description, feature phrasing, icons) keyed by ID.
type LandingPlanCatalog ¶
type LandingPlanCatalog struct {
Note string `json:"_note"`
TrialGrantCredits int64 `json:"trialGrantCredits"`
Plans []LandingPlan `json:"plans"`
}
LandingPlanCatalog is the whole committed catalog: the per-plan facts plus the one-time trial-grant credit figure the pricing copy quotes.
func BuildLandingPlanCatalog ¶
func BuildLandingPlanCatalog() LandingPlanCatalog
BuildLandingPlanCatalog assembles the landing catalog from the plan tables in plans.go, in tier order. It is the single source the generator writes and the drift test regenerates, so the committed file can never silently disagree with plans.go.
type LedgerEntry ¶
type LedgerEntry struct {
ID int64 `json:"id"`
WorkspaceID string `json:"workspace_id"`
AllocationID string `json:"allocation_id,omitempty"`
Amount int64 `json:"amount"` // negative = debit, positive = credit
BalanceAfter int64 `json:"balance_after"`
Operation string `json:"operation"` // ai_translation, bravo_message, bravo_container, purchase, grant, trial_grant, expire
ReferenceID string `json:"reference_id,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
LedgerEntry is an immutable record of a credit transaction.
type LedgerPage ¶
type LedgerPage struct {
Entries []LedgerEntry `json:"entries"`
Total int `json:"total"`
Limit int `json:"limit"`
Offset int `json:"offset"`
}
LedgerPage is one page of ledger entries, newest first, plus the total number of entries the same filter matches.
type LedgerQuery ¶
type LedgerQuery struct {
From time.Time
To time.Time
Operation string // empty = every operation
Limit int
Offset int
}
LedgerQuery selects one page of a workspace's credit ledger.
type PgBillingStore ¶
type PgBillingStore struct {
// contains filtered or unexported fields
}
PgBillingStore implements BillingStore using PostgreSQL.
func NewPgBillingStore ¶
func NewPgBillingStore(db *storage.PgDB) (*PgBillingStore, error)
NewPgBillingStore creates a PostgreSQL-backed BillingStore and runs migrations.
func (*PgBillingStore) AddNote ¶
func (s *PgBillingStore) AddNote(ctx context.Context, note *WorkspaceNote) error
func (*PgBillingStore) CheckCredits ¶
CheckCredits returns the workspace's total spendable balance: this month's remaining plan allowance plus all non-expiring credits (the one-time trial grant and purchased packs, Epic 004).
Only a workspace with NO credit rows at all yields the "no allocation" error (callers — the enqueue pre-check, QuotaGuard — degrade to allowing the request). A workspace whose buckets exist but are spent returns the real, possibly zero-or-negative balance and IS blocked: with the Free plan's recurring allowance gone, "trial grant fully spent" is the steady state of a free workspace and must read as out-of-credits, not as unmetered.
func (*PgBillingStore) DeductCredits ¶
func (s *PgBillingStore) DeductCredits(ctx context.Context, workspaceID string, amount int64, op string, refID string) error
DeductCredits charges amount against a workspace's credits, cascading across sources: draw from the monthly plan allowance first, then the one-time trial grant, then non-expiring purchased packs (Epic 004). The order is deliberate: the expiring bucket goes first (unspent plan credits evaporate at month rollover anyway), the promotional trial grant next, and credits the customer paid real money for are preserved the longest. Any overage once every bucket is exhausted is recorded against the plan bucket (or the first non-expiring bucket that exists) so the debt is never lost. One immutable ledger entry is written per bucket touched.
A non-empty refID makes the charge idempotent: the same (workspace, operation, reference) is applied once, however many times it arrives. Every metered path is at-least-once — a job requeued after a provider error restarts from its first chunk, a redelivered queue message re-runs the whole worker — so without this a late failure bills the customer again for work already paid for, and the balance it drives negative blocks the workspace's next job.
func (*PgBillingStore) DeleteFeatureOverride ¶
func (*PgBillingStore) ExpireTrials ¶
func (s *PgBillingStore) ExpireTrials(ctx context.Context, now time.Time, limit int) ([]ExpiredTrial, error)
ExpireTrials atomically downgrades expired trial subscriptions and their cached workspaces.plan values, returning the affected workspaces. Authorization and credit grants read that cache, so both writes must succeed or roll back together.
This operation writes the auth-owned workspace table directly to preserve that transaction boundary. FOR UPDATE SKIP LOCKED prevents concurrent sweepers from claiming the same row. Rechecking status = 'trialing' under the lock prevents a concurrent paid conversion from being downgraded.
The one-time trial credit grant is retained regardless of plan.
func (*PgBillingStore) GetCurrentAllocation ¶
func (s *PgBillingStore) GetCurrentAllocation(ctx context.Context, workspaceID string) (*CreditAllocation, error)
GetCurrentAllocation returns the current month's PLAN allocation only. It is the monthly-allowance bucket that drives EnsureMonthlyAllocation (has this month been granted yet?) and the low-credit threshold notifications. It deliberately excludes the non-expiring buckets — spendable balance (plan + trial + purchased) is CheckCredits, and spending cascades across all three in DeductCredits (Epic 004).
func (*PgBillingStore) GetFeatureOverrides ¶
func (s *PgBillingStore) GetFeatureOverrides(ctx context.Context, workspaceID string) ([]FeatureOverride, error)
func (*PgBillingStore) GetLedger ¶
func (s *PgBillingStore) GetLedger(ctx context.Context, workspaceID string, from, to time.Time) ([]LedgerEntry, error)
func (*PgBillingStore) GetLedgerPage ¶
func (s *PgBillingStore) GetLedgerPage(ctx context.Context, workspaceID string, q LedgerQuery) (*LedgerPage, error)
GetLedgerPage returns the [offset, offset+limit) window of the workspace's ledger for the query's window and operation, plus the total the filter matches.
func (*PgBillingStore) GetNetByOperation ¶
func (s *PgBillingStore) GetNetByOperation(ctx context.Context, workspaceID string, from, to time.Time) (map[string]int64, error)
GetNetByOperation sums every movement in the window per operation, signed.
func (*PgBillingStore) GetPlatformMetrics ¶
func (s *PgBillingStore) GetPlatformMetrics(ctx context.Context) (*PlatformMetrics, error)
func (*PgBillingStore) GetSubscription ¶
func (s *PgBillingStore) GetSubscription(ctx context.Context, workspaceID string) (*Subscription, error)
func (*PgBillingStore) GetUpsellOpportunities ¶
func (s *PgBillingStore) GetUpsellOpportunities(ctx context.Context) ([]UpsellOpportunity, error)
func (*PgBillingStore) GetUsageByOperation ¶
func (s *PgBillingStore) GetUsageByOperation(ctx context.Context, workspaceID string, from, to time.Time) (map[string]int64, error)
GetUsageByOperation sums the debits (negative amounts, returned positive) in the window per operation.
func (*PgBillingStore) GrantCredits ¶
func (*PgBillingStore) GrantPurchasedCredits ¶
func (s *PgBillingStore) GrantPurchasedCredits(ctx context.Context, workspaceID string, amount int64, referenceID string) (bool, error)
GrantPurchasedCredits grants one purchased credit pack, exactly once per Stripe checkout, and records its billing event — all in a single transaction keyed on referenceID (the Stripe session id).
This exists because the webhook handler rolls its idempotency marker back on ANY dispatch error, so a grant that commits while a later, separate write fails would be re-applied by Stripe's retry — a $5 pack crediting 400K. Folding the grant and its event into one transaction means a retry re-runs an all-or-nothing unit, and the unique index on (workspace_id, reference_id) for purchase rows makes even a concurrent double-delivery collide instead of double-crediting. Returns false (no error) when this session was already granted, so the caller treats the duplicate as success.
func (*PgBillingStore) GrantTrialCredits ¶
func (s *PgBillingStore) GrantTrialCredits(ctx context.Context, workspaceID string, amount int64) (bool, error)
GrantTrialCredits grants the workspace's one-time trial credits: a non-expiring source='trial' allocation created at most once per workspace, EVER, keyed on the UNIQUE(workspace_id, week_start, source) constraint with the sentinel period. The grant, its ledger row, and its billing event are one transaction, so the audit trail cannot drift from the money.
The duplicate fast path is a single read (no transaction): the allocation middleware calls this on every touch of a workspace with no recurring allowance, so the already-granted case must stay hot-path cheap. Two concurrent first grants race to the insert; DO NOTHING makes the loser a no-op (granted=false) rather than a double grant.
func (*PgBillingStore) ListAllFeatureOverrides ¶
func (s *PgBillingStore) ListAllFeatureOverrides(ctx context.Context) ([]FeatureOverride, error)
func (*PgBillingStore) ListBillingEvents ¶
func (s *PgBillingStore) ListBillingEvents(ctx context.Context, limit, offset int, eventType string) ([]BillingEvent, error)
func (*PgBillingStore) ListNotes ¶
func (s *PgBillingStore) ListNotes(ctx context.Context, workspaceID string) ([]WorkspaceNote, error)
func (*PgBillingStore) ListSubscriptions ¶
func (s *PgBillingStore) ListSubscriptions(ctx context.Context, limit, offset int) ([]*Subscription, error)
func (*PgBillingStore) MarkStripeEventProcessed ¶
func (*PgBillingStore) RecordBillingEvent ¶
func (s *PgBillingStore) RecordBillingEvent(ctx context.Context, event *BillingEvent) error
func (*PgBillingStore) SetFeatureOverride ¶
func (s *PgBillingStore) SetFeatureOverride(ctx context.Context, override *FeatureOverride) error
func (*PgBillingStore) UnmarkStripeEvent ¶
func (s *PgBillingStore) UnmarkStripeEvent(ctx context.Context, eventID string) error
func (*PgBillingStore) UpsertSubscription ¶
func (s *PgBillingStore) UpsertSubscription(ctx context.Context, sub *Subscription) error
type Plan ¶
type Plan string
Plan represents a subscription tier.
func MinimumPlanFor ¶
MinimumPlanFor returns the lowest plan that includes the given feature. Returns an empty string if no plan includes it.
type PlanInfo ¶
type PlanInfo struct {
ID Plan `json:"id"`
Name string `json:"name"`
MonthlyCredits int64 `json:"monthly_credits"` // -1 = unlimited, 0 = no recurring allowance
// MaxMarkets is the headline number: how much of the world this plan's
// custody covers. -1 = unlimited.
MaxMarkets int `json:"max_markets"`
// MaxBrands is the coarser boundary. -1 = unlimited.
MaxBrands int `json:"max_brands"`
// MaxCustodians is how many people may author what governs content over a
// bounded region. 0 on Free; -1 = unlimited. Every other member is free.
MaxCustodians int `json:"max_custodians"`
PerSeat bool `json:"per_seat"` // the Stripe quantity is the custodian count
Purchasable bool `json:"purchasable"`
Current bool `json:"current"`
}
PlanInfo describes a plan to the client. It deliberately carries no dollar amounts: prices live in Stripe (DECISIONS L4), and the client's only job is to know which plans it may ask to check out.
func DescribePlan ¶
DescribePlan builds the client-facing description of a plan. purchasable is decided by the caller, which knows whether the plan's Stripe price is configured in this deployment.
type PlatformMetrics ¶
type PlatformMetrics struct {
MRR float64 `json:"mrr"`
ActiveWorkspaces int `json:"active_workspaces"`
NewSignups7d int `json:"new_signups_7d"`
NewSignups30d int `json:"new_signups_30d"`
CreditUtilizationPct float64 `json:"credit_utilization_pct"`
ChurnRate float64 `json:"churn_rate"`
}
PlatformMetrics holds platform-wide KPIs for the admin dashboard.
type StripeClient ¶
type StripeClient struct {
// contains filtered or unexported fields
}
StripeClient wraps the Stripe SDK for billing operations.
func NewStripeClient ¶
func NewStripeClient(secretKey string) *StripeClient
NewStripeClient creates a StripeClient with the given secret key.
func (*StripeClient) CreateCheckoutSession ¶
func (c *StripeClient) CreateCheckoutSession(_ context.Context, customerID, priceID, successURL, cancelURL string, metadata ...map[string]string) (string, error)
CreateCheckoutSession creates a Stripe Checkout session for subscribing to a plan. metadata is attached to the session (e.g. workspace_id for webhook routing).
func (*StripeClient) CreateCheckoutSessionWithOptions ¶
func (c *StripeClient) CreateCheckoutSessionWithOptions(customerID, priceID, successURL, cancelURL string, opts CheckoutOptions) (string, error)
CreateCheckoutSessionWithOptions creates a Stripe Checkout session with full options.
func (*StripeClient) CreateCustomer ¶
func (c *StripeClient) CreateCustomer(_ context.Context, workspaceID, email, name string) (string, error)
CreateCustomer creates a Stripe customer for a workspace.
func (*StripeClient) CreatePaymentCheckout ¶
func (c *StripeClient) CreatePaymentCheckout(_ context.Context, customerID, priceID, successURL, cancelURL string, metadata map[string]string) (string, error)
CreatePaymentCheckout creates a one-time payment checkout session (e.g. credit packs).
func (*StripeClient) CreatePortalSession ¶
func (c *StripeClient) CreatePortalSession(_ context.Context, customerID, returnURL string) (string, error)
CreatePortalSession creates a Stripe Customer Portal session for managing subscriptions.
func (*StripeClient) GetInvoices ¶
func (c *StripeClient) GetInvoices(_ context.Context, customerID string, limit int) ([]StripeInvoice, error)
GetInvoices returns recent invoices for a customer.
func (*StripeClient) ReportMeterEvent ¶
func (c *StripeClient) ReportMeterEvent(ctx context.Context, customerID, eventName string, value int64, dimensions map[string]string)
ReportMeterEvent sends a meter event to Stripe for usage-based billing. This is called asynchronously and errors are logged, not returned. An idempotency key is derived from the dimensions to prevent duplicate billing.
type StripeInvoice ¶
type StripeInvoice struct {
ID string `json:"id"`
Number string `json:"number"`
Status string `json:"status"`
AmountDue int64 `json:"amount_due"`
AmountPaid int64 `json:"amount_paid"`
Currency string `json:"currency"`
Created int64 `json:"created"`
InvoicePDF string `json:"invoice_pdf"`
HostedURL string `json:"hosted_url"`
}
StripeInvoice represents a simplified invoice for API responses.
type Subscription ¶
type Subscription struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
StripeCustomerID string `json:"stripe_customer_id"`
StripeSubscriptionID string `json:"stripe_subscription_id,omitempty"`
Plan Plan `json:"plan"`
Status string `json:"status"` // active, past_due, canceled, trialing
SeatCount int `json:"seat_count"`
CurrentPeriodStart time.Time `json:"current_period_start,omitzero"`
CurrentPeriodEnd time.Time `json:"current_period_end,omitzero"`
CancelAt *time.Time `json:"cancel_at,omitempty"`
// TrialEndsAt is set only for the local, card-free Pro trial (SetupTrial):
// it is the deadline the TrialSweeper downgrades on. Any Stripe-driven
// subscription write clears it — once a real subscription exists, the trial
// is over regardless of how much of it was left.
TrialEndsAt *time.Time `json:"trial_ends_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Subscription represents a workspace's billing subscription. The source of truth is Stripe; this is a local cache for fast access.
type TrialSweepStore ¶
type TrialSweepStore interface {
ExpireTrials(ctx context.Context, now time.Time, limit int) ([]ExpiredTrial, error)
RecordBillingEvent(ctx context.Context, event *BillingEvent) error
}
TrialSweepStore is the store surface the trial sweeper drives. PgBillingStore satisfies it. It is deliberately narrower than BillingStore: the sweeper needs exactly two operations, and keeping it separate means an in-memory BillingStore (self-hosted, tests) does not have to grow a trial-expiry implementation.
type TrialSweeper ¶
type TrialSweeper struct {
// contains filtered or unexported fields
}
TrialSweeper ends local Pro trials that have run out.
Nothing else can end them: the trial is card-free, so there is no Stripe subscription whose lifecycle events would downgrade the workspace. Without this loop every signup keeps Pro limits forever, which is precisely the state the platform was in before epic 005.
A trial that converts needs no sweeping — the checkout webhook overwrites plan and status, and clears trial_ends_at, so the row no longer matches.
The sweeper does not carry a plan-cache syncer: ExpireTrials updates the workspace plan cache atomically with the downgrade (a separate sync step could drift, see its doc), so the sweeper only has to record the audit event.
func NewTrialSweeper ¶
func NewTrialSweeper(store TrialSweepStore, interval time.Duration) *TrialSweeper
NewTrialSweeper builds a trial sweeper. A zero interval uses the default (hourly): the trial boundary is a day-scale deadline, so hourly precision is far finer than the product promises and costs one indexed query per hour.
func (*TrialSweeper) Run ¶
func (s *TrialSweeper) Run(ctx context.Context) error
Run drives the sweep loop until ctx is cancelled, fitting the worker's errgroup. It returns ctx.Err() on cancellation, which the worker treats as a clean shutdown. A sweep that fails is logged and retried on the next tick — an expired trial staying up one more hour is not worth crashing the worker.
type UpsellOpportunity ¶
type UpsellOpportunity struct {
WorkspaceID string `json:"workspace_id"`
WorkspaceName string `json:"workspace_name"`
CurrentPlan Plan `json:"current_plan"`
Signal string `json:"signal"` // credit_exhaustion, seat_pressure, feature_gate_hits, high_usage, dormant_paid
Score int `json:"score"` // priority score (higher = more urgent)
Detail string `json:"detail"` // human-readable detail
SuggestedPlan Plan `json:"suggested_plan"`
DetectedAt time.Time `json:"detected_at"`
}
UpsellOpportunity represents a workspace that may be a candidate for upgrade.
type UsageHooks ¶
type UsageHooks struct {
Store BillingStore
Stripe *StripeClient
Notifier *BillingNotifier
// getOwnerEmail resolves workspace owner email for notifications.
// Set by the server when wiring up hooks.
GetOwnerEmail func(ctx context.Context, workspaceID string) string
}
UsageHooks provides billing integration points for AI operations. All methods are safe to call on a nil receiver (no-op).
func (*UsageHooks) DeductContainerTime ¶
func (h *UsageHooks) DeductContainerTime(ctx context.Context, workspaceID string, duration time.Duration, refID string)
DeductContainerTime deducts container-time credits and reports to Stripe.
func (*UsageHooks) DeductTokens ¶
func (h *UsageHooks) DeductTokens(ctx context.Context, workspaceID string, tokens int, op, refID string)
DeductTokens deducts token credits and reports to Stripe Meters. workspaceID is the billing workspace, tokens is the raw token count, op describes the operation (e.g. "ai_translation", "bravo_message"), and refID is a correlation ID (job ID, message ID, etc.).
type WebhookHandler ¶
type WebhookHandler struct {
// contains filtered or unexported fields
}
WebhookHandler processes Stripe webhook events.
func NewWebhookHandler ¶
func NewWebhookHandler(store BillingStore, webhookSecret string) *WebhookHandler
NewWebhookHandler creates a WebhookHandler.
func (*WebhookHandler) HandleWebhook ¶
func (h *WebhookHandler) HandleWebhook(payload []byte, signature string) error
HandleWebhook verifies the Stripe signature and processes the event.
Stripe delivers webhooks at-least-once and retries on any non-2xx response, so the handler must be idempotent: a duplicate delivery of the same event.ID must not re-apply side effects (e.g. double-granting credits). Before dispatching, the event ID is recorded in a processed-events table; a duplicate ID short-circuits and returns nil (HTTP 200) so Stripe stops retrying. If dispatch fails, the marker is rolled back so a subsequent retry reprocesses the event.
A nil return maps to HTTP 200 at the server. We return nil for handled events, duplicate deliveries, and intentionally-ignored event types; we return a non-nil error only for genuine processing failures that should be retried.
func (*WebhookHandler) SetEventTracker ¶
func (h *WebhookHandler) SetEventTracker(tracker EventTracker)
SetEventTracker configures the event tracker for conversion tracking.
func (*WebhookHandler) SetNotifier ¶
func (h *WebhookHandler) SetNotifier(notifier *BillingNotifier)
SetNotifier configures the billing email notifier.
func (*WebhookHandler) SetPlanSyncer ¶
func (h *WebhookHandler) SetPlanSyncer(syncer WorkspacePlanSyncer)
SetPlanSyncer configures the workspace plan syncer. When set, webhook handlers will update the workspace plan cache after subscription changes.