Documentation
¶
Overview ¶
Package finance is the SaaS business/finance dashboard (/v1/admin/finance) — the profitability panel: what we pay every vendor (COGS), what we earn, the gross margin, how fast we're burning the DigitalOcean promo credit, and the runway that credit + burn imply. SUPERADMIN ONLY (core.Guard).
It FABRICATES NOTHING and OWNS NO cost logic. COGS is the SINGLE source of truth in commerce (GET /v1/costs) — cloud CONSUMES it. Revenue + MRR come from commerce billing. The one direct vendor read that remains is the DigitalOcean promo-CREDIT balance + burn-down history — an ORTHOGONAL treasury view. The derived margin/runway math is a pure function (ComputeFinance) with a unit test proving the numbers.
Per-provider UPSTREAM credit ledger + usage funding split for admin.hanzo.ai.
TWO-LEDGER MODEL (do not conflate):
- UPSTREAM (this file): what WE spend at each provider — provider promo credit (grant) burning down to paid. DigitalOcean's $26k GenAI credit is the first real row; DO's live remaining/burn/runway come from the DO billing API (reused from finance.go), every provider's burn from the ONE cloud_usage ledger. Grants are fixed contractual numbers seeded here (not a live vendor read); move to KMS/config when there is more than one.
- DOWNSTREAM (clients/commerce): what we bill OUR customers (credit/prepaid/card). Orthogonal — never mixed with the upstream provider credits above.
Two SuperAdmin endpoints (the console renders them; this is the authoritative contract). Both reuse the admin auth guard + the cloud_usage warehouse — no new datastore, no duplicate reads.
Index ¶
- func AvgDailyBurnCents(monthToDateSpendCents int64, now time.Time) int64
- func Backfill(s *cloud.Service[core.State], c *zip.Ctx) error
- func Deposit(s *cloud.Service[core.State], c *zip.Ctx) error
- func Finance(s *cloud.Service[core.State], c *zip.Ctx) error
- func ProvidersCredit(s *cloud.Service[core.State], c *zip.Ctx) error
- func Routes(app *zip.App, s *cloud.Service[core.State])
- func UsageFunding(s *cloud.Service[core.State], c *zip.Ctx) error
- type DoCost
- type DoHistoryPoint
- type FinanceCost
- type FinanceData
- type FinanceDerived
- type FinanceInput
- type FinanceRevenue
- type ProviderCredit
- type UsageFundingRow
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AvgDailyBurnCents ¶
AvgDailyBurnCents derives the average daily DO burn from month-to-date usage: month-to-date spend divided by the number of elapsed days in the current month (at least 1, so day 1 doesn't divide by zero).
func Backfill ¶ added in v1.799.2
Backfill answers POST /v1/admin/finance/backfill?org=<org> — the ONE-TIME cutover that carries an org's CURRENT commerce prepaid balance into the native finance wallet. It reads the pre-migration source of truth (the org's commerce balance for the org-pool subject == the org slug) and deposits it into finance under the FIXED ref "backfill:<org>", so re-running the cutover credits the wallet AT MOST ONCE. SuperAdmin only (core.Guard). Returns { org, migratedCents, entryId }; entryId is "" when the balance was non-positive (nothing to carry).
func Deposit ¶ added in v1.799.2
Deposit answers POST /v1/admin/finance/deposit — a SuperAdmin credit into an ARBITRARY subject's native prepaid wallet. Where the credit-grant + the backfill fund the org POOL (subject == the org slug), this funds a SPECIFIC wallet: an org pool ("hanzo") or a human ("hanzo/z" → wallet:z in orgs/hanzo/finance.db). It posts a balanced double-entry credit on the ONE finance ledger and is additive (no idempotency ref, so distinct grants stack). SuperAdmin only (core.Guard).
Params arrive as a JSON body OR query: org, subject, cents (>0), notes?, currency? (usd). 503 when no finance ledger is co-resident on this deployment; 400 on a missing/invalid arg or non-positive cents.
func Finance ¶
Finance answers GET /v1/admin/finance. It reads the multi-vendor COGS from commerce /v1/costs, the DO promo-credit/burn-down treasury view, and the fleet commerce revenue, then hands them to ComputeFinance. SuperAdmin only.
func ProvidersCredit ¶
ProvidersCredit serves GET /v1/admin/providers/credit — the per-provider upstream credit ledger. SuperAdmin-guarded (see Routes).
Types ¶
type DoCost ¶
type DoCost struct {
Configured bool `json:"configured"`
Error string `json:"error,omitempty"`
CreditRemainingCents int64 `json:"creditRemainingCents"`
MonthToDateSpendCents int64 `json:"monthToDateSpendCents"`
AvgDailyBurnCents int64 `json:"avgDailyBurnCents"`
AccountBalanceCents int64 `json:"accountBalanceCents"`
GeneratedAt string `json:"generatedAt,omitempty"`
History []DoHistoryPoint `json:"history"`
}
DoCost is the DigitalOcean credit + spend view. When Configured is false every number is zero and the console renders the honest "connect DO_API_TOKEN" state.
type DoHistoryPoint ¶
type DoHistoryPoint struct {
Date string `json:"date"`
AmountCents int64 `json:"amountCents"`
Type string `json:"type"`
Description string `json:"description"`
}
DoHistoryPoint is one credit burn-down series point (usage charge over time).
type FinanceCost ¶
type FinanceCost struct {
Configured bool `json:"configured"`
Error string `json:"error,omitempty"`
Period string `json:"period"`
TotalCents int64 `json:"totalCents"`
Vendors []commerce.Vendor `json:"vendors"`
DigitalOcean DoCost `json:"digitalocean"`
}
FinanceCost is the platform COGS view — what WE pay our vendors. Its authority is commerce GET /v1/costs: TotalCents is the whole-platform COGS the margin math folds, and Vendors is the per-vendor breakdown. Configured is false (and every number 0) when commerce /v1/costs is unreachable.
DigitalOcean here is an ORTHOGONAL treasury view (promo-credit remaining + burn-down), NOT part of COGS: it feeds only the runway projection.
type FinanceData ¶
type FinanceData struct {
Cost FinanceCost `json:"cost"`
Revenue FinanceRevenue `json:"revenue"`
Derived FinanceDerived `json:"derived"`
GeneratedAt string `json:"generatedAt"`
Sources []core.SourceStatus `json:"sources"`
}
FinanceData is the full /v1/admin/finance aggregate.
func ComputeFinance ¶
func ComputeFinance(in FinanceInput) FinanceData
ComputeFinance is the PURE derivation: given the multi-vendor COGS view and the commerce revenue view, it computes gross margin, margin %, runway, and profitability. No I/O.
grossMarginCents = revenue - COGS(total, all vendors) grossMarginPct = grossMargin / revenue * 100 (0 when revenue is 0) runwayDays = DO creditRemaining / DO avgDailyBurn (nil when burn 0 or DO off) profitable = revenue > COGS
type FinanceDerived ¶
type FinanceDerived struct {
GrossMarginCents int64 `json:"grossMarginCents"`
GrossMarginPct float64 `json:"grossMarginPct"`
RunwayDays *float64 `json:"runwayDays"`
Profitable bool `json:"profitable"`
}
FinanceDerived is the pure profitability math. Runway is a pointer so it can be null (no honest runway when burn is zero or DO is unconfigured).
type FinanceInput ¶
type FinanceInput struct {
Cost FinanceCost
Revenue FinanceRevenue
GeneratedAt string
Sources []core.SourceStatus
}
FinanceInput is the raw material ComputeFinance folds into FinanceData. The handler fills Cost from the commerce COGS read (+ the DO-credit treasury view) and Revenue from commerce billing; the pure function does the math so the derivation is unit-testable in isolation.
type FinanceRevenue ¶
type FinanceRevenue struct {
Configured bool `json:"configured"`
TotalRevenueCents int64 `json:"totalRevenueCents"`
MRRCents int64 `json:"mrrCents"`
CreditsConsumedCents int64 `json:"creditsConsumedCents"`
}
FinanceRevenue is the commerce revenue view (all money in USD cents).
type ProviderCredit ¶
type ProviderCredit struct {
Provider string `json:"provider"`
GrantCents int64 `json:"grant_cents"`
BurnCents int64 `json:"burn_cents"`
RemainingCents int64 `json:"remaining_cents"`
RunwayDays *float64 `json:"runway_days"` // nil when burn is 0 / unknown (never a fabricated infinity)
HasCredit bool `json:"has_credit"`
IsPaidOnly bool `json:"is_paid_only"`
}
ProviderCredit is one provider's upstream credit ledger row.
type UsageFundingRow ¶
type UsageFundingRow struct {
Provider string `json:"provider"`
Model string `json:"model"`
Funding string `json:"funding"` // credit | paid | paid_only | byo
Tokens int64 `json:"tokens"`
CostCents int64 `json:"cost_cents"`
Requests int64 `json:"requests"`
}
UsageFundingRow is one (provider, model) usage roll-up tagged by funding class.