Files
zeekay fa4fc53b14 Pay a recorded plan from the prepaid balance
RecordSubscription takes processor "balance": it draws the period from
the subject's prepaid money now, raises and settles that period's
invoice, and opens a regular subscription the engine renews from the
same money. The period must be the one running now and one of the
plan's; a subject holding a plan, or one gone past due, is refused. A
balance that cannot cover the period is refused with nothing written.
The ledger entry and the invoice are the reference.

Prepaid money is read and spent one way. The creditledger seam gains
Debit, all or nothing at the address Credit and Balance already name,
so with a host ledger injected the draw lands where a grant credits and
the AI gate reads, and the tier reads its balance, beside the credit
grants, from there too. Standalone, the draw is an "iam-user"
withdrawal, the kind every deposit writes. The self-serve balance
purchase, the record and every renewal draw through it, credit grants
first, exactly once per ref. The split is recorded under the ref
before the ledger is asked, so a debit whose answer was lost is posted
again as it was and the ledger answers with the posting it holds.

The collector reads the allocation first and charges the card before
any prepaid money moves, so an invoice that cannot be paid in full
takes nothing from credits or balance. What an attempt does collect
accumulates on AmountPaid, and the draw is keyed on the subscription's
period, so two invoices raised for one period draw once between them.

Periods are billed in advance. A subscription holds the period it paid
for; when that period ends the next one is invoiced, fee in advance and
metered usage in arrears, and the row moves onto it only once it is
paid. An unpaid one leaves the row past due on the period it owes;
once that period has gone by unserved it is owed no longer, its
invoice is void, and the row owes the period running now. A row that
was served nothing until it paid, past due or late, is served a whole
period from the payment. An invoice is voided only under the guard its
payment takes, so a payment landing at once is never voided over. A
row whose renewal was missed for whole periods is billed the period
running now, never every period since. A row canceled at the end of
its period ends with the last period it paid for, and an ended row's
unpaid invoices are void.

Invoices are read by their filters rather than under the synckey
ancestor an invoice loses once it is saved again, so a paid one stays
listed and found by its renewal, and a new one is numbered one past
the highest issued. The billing cycle reads
subscriptions the same way, renews only rows of the org's own mode,
and RenewDue is the sweep as a value core a schedule can call.

Claude-Session: https://claude.ai/code/session_016hTDbBTaq6r3xTQ5RAVVtF
2026-09-23 22:09:15 -07:00

150 lines
4.5 KiB
Go

package billing
import (
"github.com/zap-proto/zip"
"github.com/hanzoai/commerce/billing/engine"
"github.com/hanzoai/commerce/datastore"
"github.com/hanzoai/commerce/log"
"github.com/hanzoai/commerce/middleware"
"github.com/hanzoai/commerce/models/billinginvoice"
"github.com/hanzoai/commerce/models/paymentmethod"
"github.com/hanzoai/commerce/models/subscription"
"github.com/hanzoai/commerce/thirdparty/kms"
"github.com/hanzoai/commerce/util/json/http"
)
// PortalOverview returns a billing summary for the authenticated customer.
//
// GET /v1/billing/portal/overview?customerId=...
func PortalOverview(c *zip.Ctx) error {
org := middleware.GetOrganization(c)
db := datastore.New(org.Namespaced(c.Context()))
customerId := c.Query("customerId")
if customerId == "" {
return http.Fail(c, 400, "customerId is required", nil)
}
// Get balance
cb, _ := engine.GetOrCreateCustomerBalance(db, customerId, "usd")
balance := int64(0)
if cb != nil {
balance = cb.Balance
}
// Count active subscriptions
rootKey := db.NewKey("synckey", "", 1, nil)
subs := make([]*subscription.Subscription, 0)
sq := subscription.Query(db).Ancestor(rootKey).
Filter("UserId=", customerId).
Filter("Status=", string(subscription.Active))
_, _ = sq.GetAll(&subs)
// Count payment methods
pms := make([]*paymentmethod.PaymentMethod, 0)
pmq := paymentmethod.Query(db).Ancestor(rootKey).
Filter("CustomerId=", customerId)
_, _ = pmq.GetAll(&pms)
return c.JSON(200, map[string]any{
"customerId": customerId,
"balance": balance,
"currency": "usd",
"activeSubscriptions": len(subs),
"paymentMethods": len(pms),
})
}
// PortalInvoices returns the customer's invoice list.
//
// GET /v1/billing/portal/invoices?customerId=...
func PortalInvoices(c *zip.Ctx) error {
org := middleware.GetOrganization(c)
db := datastore.New(org.Namespaced(c.Context()))
customerId := c.Query("customerId")
if customerId == "" {
return http.Fail(c, 400, "customerId is required", nil)
}
invoices := make([]*billinginvoice.BillingInvoice, 0)
q := billinginvoice.Query(db).
Filter("UserId=", customerId).
Order("-Created")
_, _ = q.GetAll(&invoices)
results := make([]map[string]any, len(invoices))
for i, inv := range invoices {
results[i] = map[string]any{
"id": inv.Id(),
"number": inv.NumberStr,
"status": inv.Status,
"amountDue": inv.AmountDue,
"currency": inv.Currency,
"created": inv.Created,
}
}
return c.JSON(200, results)
}
// PortalSubscriptions returns the customer's subscriptions.
//
// GET /v1/billing/portal/subscriptions?customerId=...
func PortalSubscriptions(c *zip.Ctx) error {
org := middleware.GetOrganization(c)
db := datastore.New(org.Namespaced(c.Context()))
customerId := c.Query("customerId")
if customerId == "" {
return http.Fail(c, 400, "customerId is required", nil)
}
rootKey := db.NewKey("synckey", "", 1, nil)
subs := make([]*subscription.Subscription, 0)
q := subscription.Query(db).Ancestor(rootKey).
Filter("UserId=", customerId).
Order("-Created")
_, _ = q.GetAll(&subs)
results := make([]map[string]any, len(subs))
for i, s := range subs {
results[i] = map[string]any{
"id": s.Id(),
"planId": s.PlanId,
"status": s.Status,
"periodStart": s.PeriodStart,
"periodEnd": s.PeriodEnd,
"created": s.Created,
}
}
return c.JSON(200, results)
}
// PortalPaymentMethods returns the customer's payment methods.
//
// The customer named here is a value the CALLER supplies, so the org namespace is
// what keeps one host's customerId from selecting another org's cards; asking for
// a foreign subject selects nothing inside your own namespace. It answers with
// the same ListMethods every other saved-card surface reads, because a portal
// that derived its own list would be a second answer to one question.
//
// GET /v1/billing/portal/methods?customerId=...
func PortalPaymentMethods(c *zip.Ctx) error {
org := middleware.GetOrganization(c)
customerId := c.Query("customerId")
if customerId == "" {
return http.Fail(c, 400, "customerId is required", nil)
}
creds, _ := c.Locals("kms").(*kms.CachedClient)
methods, err := ListMethods(c.Context(), org, customerId, "", creds)
if err != nil {
// A store that cannot be read has always answered an honest empty list
// here rather than a 500 — the portal renders no cards, not an error page.
log.Error("Failed to list portal payment methods: %v", err, c)
}
return c.JSON(200, methods)
}