mirror of
https://github.com/hanzoai/commerce.git
synced 2026-11-23 10:57:12 +00:00
- A plan can be paid by stablecoin: the first period opens its subscription when the deposit succeeds; each renewal raises its invoice, opens a deposit for the exact amount, leaves the subscription past due and announces renewal.action_required with the addresses, amount and expiry. The period starts only when the deposit succeeds, once; a deposit reported again changes nothing, and an unpaid deposit follows the dunning a card does. - A recurring token's remaining room is on the order and the subscription read. Three days before a renewal its token cannot cover (less room than the renewal, or expiring first), the agent is told once, with the path to supply a fresh token (POST /v1/billing/subscriptions/:id/agent-token). - The catalog resolves its payment types from the host's brand for an anonymous caller. Testing: go test ./api/billing; stablecoin plan and renewal (paid, unpaid, replayed) with a Stripe double; live Stripe test mode for the warning, the room, and a fresh token. Risk: new payment type for plans; the renewal sweep also announces token shortfalls. How to revert: git revert this commit.
278 lines
9.7 KiB
Go
278 lines
9.7 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/idempotencykey"
|
|
"github.com/hanzoai/commerce/models/organization"
|
|
"github.com/hanzoai/commerce/models/paymentorg"
|
|
"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, or that a plan which does not
|
|
// renew ended (Lapsed). AmountCents is what the card was charged for it, in minor
|
|
// units of Currency. A plan's period is paid by its card alone, so this is the
|
|
// whole of what the invoice collected. 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"`
|
|
// Lapsed says this row was not renewed but ended: a plan collected outside
|
|
// commerce whose period ran out with no later payment recorded.
|
|
Lapsed bool `json:"lapsed,omitempty"`
|
|
}
|
|
|
|
// RenewalRun is one sweep: how many organizations were considered, how many
|
|
// subscriptions were due, how many of those renewed, how many plans collected
|
|
// outside commerce lapsed, and what each one did.
|
|
type RenewalRun struct {
|
|
Orgs int `json:"orgs"`
|
|
Due int `json:"due"`
|
|
Renewed int `json:"renewed"`
|
|
Lapsed int `json:"lapsed"`
|
|
Results []Renewal `json:"results"`
|
|
}
|
|
|
|
// RenewDue renews every due subscription in every organization: it invoices the
|
|
// period that ended and charges it to the card on file — never to prepaid money,
|
|
// which pays for usage — moving the row on when it is paid and leaving it past
|
|
// due when it is not. A plan collected outside commerce whose period ran out with
|
|
// no later payment recorded is ended.
|
|
//
|
|
// 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 {
|
|
warnTokenRenewals(ctx, org)
|
|
for _, r := range renewDue(ctx, org, "") {
|
|
switch {
|
|
case r.Lapsed:
|
|
run.Lapsed++
|
|
case r.Success:
|
|
run.Due++
|
|
run.Renewed++
|
|
default:
|
|
run.Due++
|
|
}
|
|
run.Results = append(run.Results, r)
|
|
}
|
|
}
|
|
stranded(ctx)
|
|
reconcileIntents(ctx)
|
|
return run, nil
|
|
}
|
|
|
|
// stranded raises the alarm (uncredited) for every order whose starting balance has
|
|
// not reached its wallet since its sale stopped: charged, and not credited after
|
|
// the sale's guard would have let a retry finish it. Sending the same order again
|
|
// finishes it; until then each sweep says so.
|
|
func stranded(ctx context.Context) {
|
|
rows, ids, err := paymentorg.Owing()
|
|
if err != nil {
|
|
log.Error("RECONCILE: the orders owing a starting balance could not be read: %v", err)
|
|
return
|
|
}
|
|
for i, r := range rows {
|
|
if time.Since(r.CreatedAt) < idempotencykey.StartedTTL {
|
|
continue // a sale in flight
|
|
}
|
|
uncredited(ctx, nil, r.Org, r.Subject, ids[i],
|
|
"an order's starting balance is not credited: its sale stopped after the charge, and the same order sent again finishes it",
|
|
r.Left(), false)
|
|
}
|
|
}
|
|
|
|
// 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() {
|
|
continue
|
|
}
|
|
if !engine.IsDue(sub, now) {
|
|
if r, ok := lapse(db, org, sub, now); ok {
|
|
out = append(out, r)
|
|
}
|
|
continue
|
|
}
|
|
out = append(out, renewOne(ctx, db, org, sub, pre, charge))
|
|
}
|
|
return out
|
|
}
|
|
|
|
// lapse ends, once it is over (engine.Over), a plan collected outside commerce
|
|
// whose period ran out with no later payment recorded, and a trial, which
|
|
// converts to nothing. Readers already serve it nothing from that end; this is the
|
|
// mark, so its row says it ended. Any other row is left alone.
|
|
func lapse(db *datastore.Datastore, org *organization.Organization, sub *subscription.Subscription, now time.Time) (Renewal, bool) {
|
|
external := sub.Type == subscription.External && sub.Status == subscription.Active
|
|
if !(external || sub.Status == subscription.Trialing) || !engine.Over(sub, now) {
|
|
return Renewal{}, false
|
|
}
|
|
r := Renewal{OrgName: org.Name, UserId: sub.UserId, SubscriptionId: sub.Id(), Test: sub.Test, Lapsed: true}
|
|
row := subscription.New(db)
|
|
if err := row.GetById(sub.Id()); err != nil {
|
|
r.Error = err.Error()
|
|
return r, true
|
|
}
|
|
ended, err := engine.Lapse(db, row, now)
|
|
if err != nil {
|
|
log.Error("Billing cycle: subscription %s lapsed and its open invoices were not voided: %v", row.Id(), err)
|
|
}
|
|
if !ended {
|
|
return Renewal{}, false
|
|
}
|
|
if err := row.Update(); err != nil {
|
|
log.Error("Billing cycle: failed to end lapsed subscription %s: %v", row.Id(), err)
|
|
r.Error = err.Error()
|
|
}
|
|
return r, true
|
|
}
|
|
|
|
// 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, org *organization.Organization, sub *subscription.Subscription, pre engine.Prepaid, charge engine.ProviderCharger) Renewal {
|
|
orgName := org.Name
|
|
// 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
|
|
}
|