mirror of
https://github.com/hanzoai/commerce.git
synced 2026-10-30 15:08:42 +00:00
Square keeps an event's created_at across every retry, and the receiver refused anything older than five minutes, so every retry of an event first sent while cloud was down (Recreate, ten rollouts a day) was refused until Square gave up. The verifier now lives in payment/providers/square and needs only the key and the URL; thirdparty/square is the API client and no longer registers itself or verifies anything, so every registry holds one Square type. Replay is stopped by the event id instead: each verified event is recorded once for the whole deployment, keyed on the verifying processor and the event id with an insert-if-absent swap, so a repeat is a duplicate under any path or org. The path names the one processor that verifies, and only one that holds its webhook secret may: an unknown name, or a verifier that needs no secret, is refused rather than tried. The books an event lands in are the verifying account's, else the deployment's brand — never a header or session, which on a replay are the replayer's. An effect that did not land (a store or the ledger did not answer) leaves the delivery open with a 503, so the provider redelivers; it used to be acknowledged and never retried. A settlement reads the payment index before the org's books, because an in-session charge's receipt is in the payer's org. POST /v1/commerce/webhooks/:provider is declared once, in setupRoutes, so standalone and embedded commerce serve the same address; the /v1/billing/webhooks spelling is gone. thirdparty/kms read /v1/kms/orgs/<org>/secrets/..., which cloud no longer serves, and was off in production anyway, so per-org payment credentials never loaded. It is deleted. secrets.Org reads orgs/<org>/<name> through the host's reader, the caller re-pointed at that org with zip.ActingAs so the KMS tenancy check admits it, and payment.Hydrate loads an org's credentials where the org receives the money: storefront checkout, storefront subscriptions and wire, and the brand's bank for the billing wire rail. Hanzo's own billing no longer reads the paying org's credentials; it charges the deployment's account, as it did. The standalone binary reads through hanzoai/kms/sdk/go.
207 lines
7.0 KiB
Go
207 lines
7.0 KiB
Go
package billing
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"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/organization"
|
|
"github.com/hanzoai/commerce/models/subscription"
|
|
"github.com/hanzoai/commerce/util/json/http"
|
|
)
|
|
|
|
type cycleUserRequest struct {
|
|
UserId string `json:"userId"`
|
|
}
|
|
|
|
// RunBillingCycle processes all subscriptions whose current period has ended
|
|
// for the request's organization. It generates invoices and attempts collection
|
|
// for each due subscription.
|
|
//
|
|
// POST /v1/billing/cycle/run
|
|
func RunBillingCycle(c *zip.Ctx) error {
|
|
org := middleware.GetOrganization(c)
|
|
db := datastore.New(org.Namespaced(c.Context()))
|
|
|
|
results := renewDue(c.Context(), org, "")
|
|
|
|
// Top up each active subscriber's included monthly allotment for the
|
|
// current period (idempotent per user+month).
|
|
allotGranted, allotSkipped, _ := grantOrgAllotments(c, db, time.Now(), !org.TestMode())
|
|
|
|
return c.JSON(200, map[string]any{
|
|
"processed": len(results),
|
|
"results": results,
|
|
"allotments": map[string]any{
|
|
"granted": allotGranted,
|
|
"skipped": allotSkipped,
|
|
},
|
|
})
|
|
}
|
|
|
|
// RunBillingCycleUser processes due subscriptions for a single user within the
|
|
// request's organization.
|
|
//
|
|
// POST /v1/billing/cycle/run-user
|
|
func RunBillingCycleUser(c *zip.Ctx) error {
|
|
org := middleware.GetOrganization(c)
|
|
|
|
var req cycleUserRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
return http.Fail(c, 400, "invalid request body", err)
|
|
}
|
|
|
|
if req.UserId == "" {
|
|
return http.Fail(c, 400, "userId is required", nil)
|
|
}
|
|
|
|
results := renewDue(c.Context(), org, req.UserId)
|
|
|
|
return c.JSON(200, map[string]any{
|
|
"user": req.UserId,
|
|
"processed": len(results),
|
|
"results": results,
|
|
})
|
|
}
|
|
|
|
// RunBillingCycleAllOrgs iterates every organization and processes due
|
|
// subscriptions across all of them, then grants each org's included allotments.
|
|
//
|
|
// POST /v1/billing/cycle/run-all
|
|
func RunBillingCycleAllOrgs(c *zip.Ctx) error {
|
|
run, err := RenewDue(c.Context())
|
|
if err != nil {
|
|
log.Error("Failed to list organizations for billing cycle: %v", err, c)
|
|
return http.Fail(c, 500, "failed to list organizations", err)
|
|
}
|
|
|
|
rootDb := datastore.New(c.Context())
|
|
orgs := make([]*organization.Organization, 0)
|
|
if _, err := organization.Query(rootDb).GetAll(&orgs); err == nil {
|
|
now := time.Now()
|
|
for _, org := range orgs {
|
|
grantOrgAllotments(c, datastore.New(org.Namespaced(c.Context())), now, !org.TestMode())
|
|
}
|
|
}
|
|
|
|
return c.JSON(200, run)
|
|
}
|
|
|
|
// Renewal is what renewing one due subscription did. AmountCents is what the
|
|
// card was charged for it, in minor units of Currency: the part of the invoice
|
|
// that is new money. A period paid from credits or from a balance a top-up
|
|
// already bought is zero here, so a caller stating renewals as sales never
|
|
// counts money twice or counts a grant as a sale. Test is the row's mode: a
|
|
// sandbox renewal is no sale.
|
|
type Renewal struct {
|
|
OrgName string `json:"orgName"`
|
|
UserId string `json:"userId"`
|
|
SubscriptionId string `json:"subscriptionId"`
|
|
InvoiceId string `json:"invoiceId,omitempty"`
|
|
AmountCents int64 `json:"amountCents,omitempty"`
|
|
Currency string `json:"currency,omitempty"`
|
|
Test bool `json:"test,omitempty"`
|
|
Success bool `json:"success"`
|
|
Error string `json:"error,omitempty"`
|
|
}
|
|
|
|
// RenewalRun is one sweep: how many organizations were considered, how many
|
|
// subscriptions were due, and what renewing each one did.
|
|
type RenewalRun struct {
|
|
Orgs int `json:"orgs"`
|
|
Due int `json:"due"`
|
|
Renewed int `json:"renewed"`
|
|
Results []Renewal `json:"results"`
|
|
}
|
|
|
|
// RenewDue renews every due subscription in every organization: it invoices the
|
|
// period that ended and collects it through the one waterfall — prepaid money
|
|
// first, the card on file for the rest — moving the row on when it is paid and
|
|
// leaving it past due when it is not.
|
|
//
|
|
// It takes values because the caller is a SCHEDULE, not a person. A failure to
|
|
// collect one subscription is that subscription's result, not the sweep's: the
|
|
// loop continues. Only the population read failing ends the run.
|
|
func RenewDue(ctx context.Context) (*RenewalRun, error) {
|
|
orgs := make([]*organization.Organization, 0)
|
|
if _, err := organization.Query(datastore.New(ctx)).GetAll(&orgs); err != nil {
|
|
return nil, err
|
|
}
|
|
run := &RenewalRun{Orgs: len(orgs), Results: make([]Renewal, 0)}
|
|
for _, org := range orgs {
|
|
for _, r := range renewDue(ctx, org, "") {
|
|
run.Due++
|
|
if r.Success {
|
|
run.Renewed++
|
|
}
|
|
run.Results = append(run.Results, r)
|
|
}
|
|
}
|
|
return run, nil
|
|
}
|
|
|
|
// renewDue renews org's due subscriptions — one subject's when user is set. A row
|
|
// the sweep missed for whole periods is billed the period running now, never every
|
|
// period since (engine.RenewSubscription).
|
|
func renewDue(ctx context.Context, org *organization.Organization, user string) []Renewal {
|
|
// Subscriptions are stored ancestor-less, so they are read the way every
|
|
// other reader reads them. An Ancestor(synckey) filter matches none of them,
|
|
// which left this sweep renewing nothing.
|
|
subs, err := ListSubscriptions(ctx, org, user, "")
|
|
if err != nil {
|
|
log.Error("Failed to query subscriptions for renewal in org %q: %v", org.Name, err)
|
|
return nil
|
|
}
|
|
db := datastore.New(org.Namespaced(ctx))
|
|
|
|
now := time.Now()
|
|
pre, charge := prepaidFor(ctx, org), chargeProviderForOrg(org)
|
|
out := make([]Renewal, 0)
|
|
for _, sub := range subs {
|
|
// A row renews from the books of its own mode, and the org's prepaid money
|
|
// is the org's mode: a sandbox row is never paid from live money, nor a
|
|
// live row from sandbox money.
|
|
if sub.Test != org.TestMode() || !engine.IsDue(sub, now) {
|
|
continue
|
|
}
|
|
out = append(out, renewOne(ctx, db, org.Name, sub, pre, charge))
|
|
}
|
|
return out
|
|
}
|
|
|
|
// renewOne invoices and collects one subscription's due period, then persists
|
|
// the row as the collection left it.
|
|
func renewOne(ctx context.Context, db *datastore.Datastore, orgName string, sub *subscription.Subscription, pre engine.Prepaid, charge engine.ProviderCharger) Renewal {
|
|
// A row read by query is not bound to the store, so the write goes through a
|
|
// fresh read of the same id.
|
|
row := subscription.New(db)
|
|
if err := row.GetById(sub.Id()); err != nil {
|
|
return Renewal{OrgName: orgName, UserId: sub.UserId, SubscriptionId: sub.Id(), Error: err.Error()}
|
|
}
|
|
r := Renewal{OrgName: orgName, UserId: row.UserId, SubscriptionId: row.Id(), Test: row.Test}
|
|
inv, result, err := engine.RenewSubscription(ctx, db, row, pre, charge)
|
|
if inv != nil {
|
|
r.InvoiceId, r.Currency = inv.Id(), string(inv.Currency)
|
|
}
|
|
if result != nil {
|
|
r.AmountCents = result.ProviderUsed
|
|
}
|
|
if err != nil {
|
|
log.Error("Billing cycle: failed to renew subscription %s: %v", row.Id(), err)
|
|
r.Error = err.Error()
|
|
return r
|
|
}
|
|
if err := row.Update(); err != nil {
|
|
log.Error("Billing cycle: failed to update subscription %s after renewal: %v", row.Id(), err)
|
|
r.Error = err.Error()
|
|
return r
|
|
}
|
|
r.Success, r.Error = result.Success, result.Error
|
|
return r
|
|
}
|