carlos / platform Public

console: Checkout with prepared customer, create and expiry requests resent verbatim; continue and start over from the page; passes only observe (plans 6b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev de7e00bb6781c30d03d7e0f100eaf567706ef844 parent d93bc33
12 files changed, +2,489 −35
  • internal/console/billingcheckout.go +1,115 −0
  • internal/console/billingcheckout_test.go +1,037 −0
  • internal/console/billingops.go +13 −6
  • internal/console/billingops_test.go +90 −20
  • internal/console/billingpage_copy.go +8 −0
  • internal/console/billingpass.go +55 −0
  • internal/console/billingstore.go +49 −9
  • internal/console/billingwebhook.go +12 −0
  • internal/console/claim_invariant_fixtures_test.go +8 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +93 −0
  • internal/console/server.go +6 −0
  • internal/console/testdata/claim-routes.txt +3 −0

CI failed — run details

diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go
new file mode 100644
index 000000000..8b427f049
--- /dev/null
+++ b/internal/console/billingcheckout.go
@@ -0,0 +1,1115 @@
+package console
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "log"
+ "maps"
+ "net/http"
+ "net/url"
+ "slices"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+)
+
+// Checkout (plans 6b, Task 9): start, continue, start over and return.
+//
+// Every write to the provider here is a prepared request persisted before
+// its first send and resent only verbatim under its key, as operations are
+// (Invariant 1): the customer create on the billing row (customer:<sqid>:<n>),
+// the Checkout create on the intent (checkout:<intent id>) and its expiry
+// (expire:<intent id>). Each has one sender, gated by recoveryEligible, and
+// the stamps and windows are provider time (Invariant 9).
+//
+// - The customer create has no id to read, so its same-key resend is its
+// own check. A cached 5xx or a closed window retires the attempt, and the
+// next attempt has a new key (Risks R3: an orphan customer is harmless).
+// - The Checkout create is checked by the customer's exhaustive session
+// list since the intent's stamp, looking for the intent id. A create that
+// ends indeterminate, or whose window closes, is abandoned when that list
+// does not hold it (Invariant 1's stated exception; Risks R2).
+// - The expiry is checked by a read of the session, which decides: expired,
+// or complete (then the subscription is synced and the intent completed).
+//
+// Observation (observeIntentLocked, the pass, the webhook, the return) only
+// reads the provider and records what the reads show.
+
+const (
+ // checkoutLifetime is how long a Checkout session stays payable:
+ // expires_at is provider time plus this.
+ checkoutLifetime = time.Hour
+ // continueMargin: Continue sends the buyer to a session only while it has
+ // more than this left, in provider time.
+ continueMargin = 5 * time.Minute
+ // customerAttemptsPerRequest bounds the fresh customer attempts one
+ // request starts: a retired attempt gets one more, then the request is
+ // refused.
+ customerAttemptsPerRequest = 2
+)
+
+// The Checkout refusals, each a billingCopy key.
+var (
+ errCheckoutAlready = billingRefusal{Key: "checkout.already"}
+ errCheckoutFailed = billingRefusal{Key: "checkout.failed"}
+ errCheckoutUncertain = billingRefusal{Key: "checkout.uncertain"}
+ errBillingRetiring = billingRefusal{Key: "billing.retiring"}
+ errCheckoutOperator = billingRefusal{Key: "notice.operator_plan"}
+ errCheckoutProblem = billingRefusal{Key: "notice.problem"}
+ errCurrencyUnshown = billingRefusal{Key: "currency.refused_unshown"}
+)
+
+// currencyFixedRefusal refuses a currency other than the account's own
+// (Call 3), naming it.
+type currencyFixedRefusal struct{ Currency string }
+
+func (r currencyFixedRefusal) Error() string {
+ return "billing: refused: currency is fixed at " + r.Currency
+}
+
+// checkoutAsk is what the buy form (or Start over) asks for.
+type checkoutAsk struct {
+ Plan, Currency string
+ Packs map[string]int
+ StartOver bool
+}
+
+func billingPagePath(sqid string) string { return "/a/" + url.PathEscape(sqid) + "/billing" }
+
+// newIntentID is a fresh Checkout intent id.
+func newIntentID() string {
+ var b [8]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ panic(err)
+ }
+ return "ci_" + hex.EncodeToString(b[:])
+}
+
+// checkoutRefusalText is the flash text for an error a Checkout door
+// returns: a refusal's copy, else checkout.failed (logged by the caller).
+func checkoutRefusalText(err error) string {
+ var fixed currencyFixedRefusal
+ if errors.As(err, &fixed) {
+ return fmt.Sprintf(billingCopy["currency.fixed"], fixed.Currency)
+ }
+ var ref billingRefusal
+ if errors.As(err, &ref) && ref != errNoProviderTimeRefusal {
+ if text, ok := billingCopy[ref.Key]; ok {
+ return text
+ }
+ }
+ return billingCopy["checkout.failed"]
+}
+
+// parseCheckoutForm reads the buy form: a paid catalog plan, an explicit
+// currency the book sells exactly as written (empty is none), and pack
+// quantities the plan offers within their bounds. A refusal is its flash
+// text.
+func (s *Server) parseCheckoutForm(r *http.Request) (checkoutAsk, string) {
+ cat, book := s.cfg.PlanCatalog, s.billing.cfg.Book
+ ask := checkoutAsk{Plan: r.PostFormValue("plan"), Packs: map[string]int{}, StartOver: r.PostFormValue("start_over") == "1"}
+ plan, ok := cat.Plans[ask.Plan]
+ if !ok || !plan.Paid {
+ return ask, billingCopy["checkout.failed"]
+ }
+ if raw := r.PostFormValue("currency"); raw != "" {
+ code, refused, shown := currencyQuery(raw, book)
+ switch {
+ case refused && shown != "":
+ return ask, fmt.Sprintf(billingCopy["currency.refused"], shown)
+ case refused:
+ return ask, billingCopy["currency.refused_unshown"]
+ }
+ ask.Currency = code
+ }
+ for name, pk := range cat.Packs {
+ raw := r.PostFormValue("pack_" + name)
+ if raw == "" {
+ continue
+ }
+ q, err := strconv.Atoi(raw)
+ if err != nil || q < 0 || q > pk.MaxQuantity || (q > 0 && !slices.Contains(plan.Packs, name)) {
+ return ask, billingCopy["checkout.failed"]
+ }
+ if q > 0 {
+ ask.Packs[name] = q
+ }
+ }
+ return ask, ""
+}
+
+// handleBillingCheckout is POST /a/{sqid}/billing/checkout: an owner buys a
+// plan through a Checkout session, or Starts over. Billing off answers 404,
+// a member the owner gate's 404, no CSRF 403. Success is a redirect to the
+// payment page; anything else goes back to the billing page with a flash.
+func (s *Server) handleBillingCheckout(w http.ResponseWriter, r *http.Request) {
+ if s.billing == nil {
+ http.NotFound(w, r)
+ return
+ }
+ _, raw, acct, ok := s.owner(w, r)
+ if !ok {
+ return
+ }
+ if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 {
+ s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
+ return
+ }
+ back := billingPagePath(acct.Sqid)
+ if !s.billing.ready.Load() {
+ s.setFlash(w, "err", billingCopy["checkout.failed"])
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ ask, refused := s.parseCheckoutForm(r)
+ if refused != "" {
+ s.setFlash(w, "err", refused)
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ ctx := s.billingClock(r.Context())
+ now := time.Now()
+ h, release := s.holdBilling(acct.Sqid)
+ to, err := s.checkoutLocked(h, ctx, acct, ask, now)
+ release()
+ if err != nil {
+ var ref billingRefusal
+ var fixed currencyFixedRefusal
+ if !errors.As(err, &ref) && !errors.As(err, &fixed) {
+ log.Printf("console: billing checkout %s: %v", acct.Sqid, err)
+ }
+ s.setFlash(w, "err", checkoutRefusalText(err))
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ http.Redirect(w, r, to, http.StatusSeeOther)
+}
+
+// checkoutLocked is the Checkout POST under the account's billing hold. It
+// answers the payment page to send the buyer to, or a refusal.
+func (s *Server) checkoutLocked(h billingHold, ctx context.Context, acct *Account, ask checkoutAsk, now time.Time) (string, error) {
+ cfg := s.billing.cfg
+ // Refusals that need no provider request.
+ if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil {
+ return "", err
+ } else if retiring {
+ return "", errBillingRetiring
+ }
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil {
+ return "", err
+ }
+ if row != nil && (row.Source == PlanSourceOperator || row.Source == PlanSourceSponsored) {
+ return "", errCheckoutOperator
+ }
+ if problems, err := s.store.OpenBillingProblemReasons(acct.ID); err != nil {
+ return "", err
+ } else if len(problems) > 0 {
+ return "", errCheckoutProblem
+ }
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ return "", err
+ }
+ if b != nil && b.Currency != "" {
+ // Call 3: an account's currency is fixed after its first purchase.
+ if ask.Currency == "" {
+ ask.Currency = b.Currency
+ }
+ if ask.Currency != b.Currency {
+ return "", currencyFixedRefusal{Currency: b.Currency}
+ }
+ }
+ if ask.Currency == "" {
+ return "", errCurrencyUnshown
+ }
+ if _, err := s.houseCoupon(acct); err != nil {
+ return "", err
+ }
+ want := checkoutIntent{AccountID: acct.ID, Book: cfg.Book.Version, Plan: ask.Plan, Currency: ask.Currency, Packs: ask.Packs}
+ if want.Seats, err = s.checkoutSeats(acct, ask.Plan); err != nil {
+ return "", err
+ }
+ if _, err := s.checkoutItems(&want); err != nil {
+ return "", err
+ }
+
+ // The recorded subscription, then every subscription of the customer
+ // (Invariant 6: judged from an exhaustive list, never from an intent).
+ b, sub, err := s.refreshLocked(h, ctx, acct, now)
+ if err != nil {
+ return "", err
+ }
+ if sub != nil && sub.Live {
+ return "", errCheckoutAlready
+ }
+ if b != nil && b.Subscription != "" && sub == nil {
+ return "", errCheckoutFailed // the provider has no such subscription: a problem is open
+ }
+ if b != nil && b.Customer != "" {
+ ids, err := cfg.Provider.LiveSubscriptions(ctx, b.Customer)
+ if err != nil {
+ log.Printf("console: billing checkout %s: listing subscriptions: %v", acct.Sqid, err)
+ return "", errCheckoutFailed
+ }
+ for _, id := range ids {
+ if err := s.syncSubscriptionLocked(h, ctx, acct, id, now); err != nil {
+ log.Printf("console: billing checkout %s: syncing %s: %v", acct.Sqid, id, err)
+ }
+ }
+ if len(ids) > 0 {
+ return "", errCheckoutAlready
+ }
+ }
+
+ // A prior intent that is not history yet.
+ prior, err := s.store.CheckoutIntent(acct.ID)
+ if err != nil {
+ return "", err
+ }
+ if prior != nil && !intentTerminal(prior) {
+ if prior.State == intentCreating {
+ err = s.finishCreateLocked(h, ctx, acct, prior, now)
+ } else {
+ err = s.observeIntentLocked(h, ctx, acct, prior, now)
+ }
+ if err != nil {
+ return "", err
+ }
+ switch prior.State {
+ case intentCompleted:
+ return "", errCheckoutAlready
+ case intentCreating:
+ return "", errCheckoutUncertain
+ case intentOpen:
+ if !ask.StartOver && sameCheckout(prior, &want) {
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return "", errCheckoutFailed
+ }
+ if prior.URL != "" && prior.ExpiresAt.After(pnow.Add(continueMargin)) {
+ return prior.URL, nil
+ }
+ }
+ if err := s.replaceIntentLocked(h, ctx, acct, prior, now); err != nil {
+ return "", err
+ }
+ switch {
+ case prior.State == intentCompleted:
+ return "", errCheckoutAlready
+ case !intentTerminal(prior):
+ return "", errCheckoutUncertain
+ }
+ }
+ }
+
+ // The customer, then the new intent and its create.
+ if _, err := s.ensureCustomerLocked(h, ctx, acct, now); err != nil {
+ return "", err
+ }
+ want.ID = newIntentID()
+ if err := s.createSessionLocked(h, ctx, acct, &want, now); err != nil {
+ return "", err
+ }
+ switch want.State {
+ case intentOpen:
+ if want.URL != "" {
+ return want.URL, nil
+ }
+ return "", errCheckoutFailed
+ case intentCompleted:
+ return "", errCheckoutAlready
+ case intentCreating:
+ return "", errCheckoutUncertain
+ }
+ return "", errCheckoutFailed
+}
+
+// sameCheckout is two intents asking for the same purchase.
+func sameCheckout(a, b *checkoutIntent) bool {
+ held := func(p map[string]int) map[string]int {
+ out := map[string]int{}
+ for k, v := range p {
+ if v > 0 {
+ out[k] = v
+ }
+ }
+ return out
+ }
+ return a.Book == b.Book && a.Plan == b.Plan && a.Currency == b.Currency && a.Seats == b.Seats && maps.Equal(held(a.Packs), held(b.Packs))
+}
+
+// houseCoupon is the coupon id a house account's Checkout carries, read
+// from the configuration now, "" for an account that is not a house one.
+// A house account with no coupon configured is refused before anything is
+// prepared or sent.
+func (s *Server) houseCoupon(acct *Account) (string, error) {
+ house, err := s.store.BillingHouse(acct.ID)
+ if err != nil || !house {
+ return "", err
+ }
+ coupon := s.billing.cfg.HouseCoupon
+ if coupon == "" {
+ log.Printf("console: billing checkout %s: %v", acct.Sqid, billing.ErrNoHouseCoupon)
+ return "", errCheckoutFailed
+ }
+ return coupon, nil
+}
+
+// checkoutSeats is a team plan's billed seats for the account's members now
+// (at least the plan's minimum), 0 off team plans.
+func (s *Server) checkoutSeats(acct *Account, plan string) (int, error) {
+ p := s.cfg.PlanCatalog.Plans[plan]
+ if p.Team == nil {
+ return 0, nil
+ }
+ members, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ return 0, err
+ }
+ return p.Team.Billed(members), nil
+}
+
+// checkoutItems resolves an intent's purchase into provider prices: the
+// plan at 1, or at its seats on a team plan, then each held pack by name.
+// Anything the book or the price map does not price is refused.
+func (s *Server) checkoutItems(ci *checkoutIntent) ([]billing.CheckoutItem, error) {
+ cfg, cat := s.billing.cfg, s.cfg.PlanCatalog
+ plan, ok := cat.Plans[ci.Plan]
+ if !ok || !plan.Paid {
+ return nil, errCheckoutFailed
+ }
+ if _, ok := cfg.Book.PlanPrice(ci.Plan, ci.Currency); !ok {
+ return nil, errCheckoutFailed
+ }
+ id, ok := cfg.Prices.ID(billing.PriceRef{Book: ci.Book, Kind: billing.KindPlan, Name: ci.Plan, Currency: ci.Currency})
+ if !ok {
+ return nil, errCheckoutFailed
+ }
+ qty := int64(1)
+ if plan.Team != nil {
+ if ci.Seats < plan.Team.MinMembers {
+ return nil, errCheckoutFailed
+ }
+ qty = int64(ci.Seats)
+ }
+ items := []billing.CheckoutItem{{PriceID: id, Quantity: qty}}
+ for _, name := range heldPacks(ci.Packs) {
+ if _, ok := cfg.Book.PackPrice(name, ci.Currency); !ok || !slices.Contains(plan.Packs, name) {
+ return nil, errCheckoutFailed
+ }
+ id, ok := cfg.Prices.ID(billing.PriceRef{Book: ci.Book, Kind: billing.KindPack, Name: name, Currency: ci.Currency})
+ if !ok {
+ return nil, errCheckoutFailed
+ }
+ items = append(items, billing.CheckoutItem{PriceID: id, Quantity: int64(ci.Packs[name])})
+ }
+ return items, nil
+}
+
+// ---- the customer -------------------------------------------------------------
+
+// customerOutcome is what one customer-create attempt came to.
+type customerOutcome int
+
+const (
+ customerUnknown customerOutcome = iota // no definite answer yet: the attempt stays, to be resent inside its window
+ customerBound // a definite answer, bound to the account
+ customerRetired // a cached 5xx or a closed window: the attempt is over, a new one may start
+ customerRefused // a definite refusal: the attempt is over and the request refused
+)
+
+func customerKey(sqid string, attempt int) string {
+ return fmt.Sprintf("customer:%s:%d", sqid, attempt)
+}
+
+// ensureCustomerLocked is the account's provider customer, created if
+// needed. An attempt already stored and not bound is finished first, by
+// resending its bytes while recoveryEligible; one that is over is replaced by
+// a new attempt with a new key. A new attempt is prepared and stored, with
+// its provider-time stamp, before its first send; with no provider time
+// nothing is stored or sent. Only a definite answer is bound.
+func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (string, error) {
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ return "", err
+ }
+ if b == nil {
+ b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}}
+ }
+ if b.Customer != "" {
+ return b.Customer, nil
+ }
+ started := 0
+ for {
+ recovering := b.CustomerPrepared != nil
+ if !recovering {
+ if started == customerAttemptsPerRequest {
+ return "", errCheckoutFailed
+ }
+ started++
+ if err := s.startCustomerLocked(h, ctx, acct, b); err != nil {
+ return "", err
+ }
+ }
+ out, err := s.sendCustomerLocked(h, ctx, acct, b, recovering, handlerRetries, now)
+ if err != nil {
+ return "", err
+ }
+ switch out {
+ case customerBound:
+ return b.Customer, nil
+ case customerUnknown:
+ return "", errCheckoutUncertain
+ case customerRefused:
+ return "", errCheckoutFailed
+ }
+ }
+}
+
+// startCustomerLocked prepares the next customer attempt and stores it on
+// the billing row with its provider-time stamp, before anything is sent.
+func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount) error {
+ _ = h
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return errNoProviderTimeRefusal
+ }
+ attempt := b.CustomerAttempt + 1
+ p, err := s.billing.cfg.Provider.PrepareCustomer(acct.Sqid, customerKey(acct.Sqid, attempt))
+ if err != nil {
+ return err
+ }
+ next := *b
+ next.CustomerAttempt, next.CustomerPrepared, next.CustomerFirstSentAt = attempt, &p, pnow.Truncate(time.Second)
+ if err := s.store.PutBillingState(next); err != nil {
+ return err
+ }
+ *b = next
+ return nil
+}
+
+// customerResendState is the stored attempt's resend state: delivery
+// unknown, its window the key lifetime from its first send.
+func customerResendState(b *billingAccount) resendState {
+ return resendState{State: opUnresolved, FirstSent: b.CustomerFirstSentAt, ContextCurrent: true}
+}
+
+// sendCustomerLocked sends the stored customer create: first, when this
+// request just stored it; otherwise as a recovery, gated first. An unknown
+// delivery (no response, 409, 429) is resent up to retries times, each after
+// the backoff and only while recoveryEligible; there is no read to make, so
+// the resend is the check, and provider time comes from the request's
+// recorder or one probe.
+func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, recovering bool, retries int, now time.Time) (customerOutcome, error) {
+ cfg := s.billing.cfg
+ for attempt := 0; ; attempt++ {
+ if recovering || attempt > 0 {
+ if attempt > 0 {
+ s.waitBackoff(ctx, handlerBackoff(attempt))
+ }
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ log.Printf("console: billing: account %s: customer create: no provider time; not resent", acct.Sqid)
+ return customerUnknown, nil
+ }
+ if ok, reason := recoveryEligible(customerResendState(b), pnow); !ok {
+ log.Printf("console: billing: account %s: customer create %s not resent (%s)", acct.Sqid, b.CustomerPrepared.Key, reason)
+ if permanentlyIneligible(reason) {
+ return s.retireCustomerLocked(h, b, customerRetired)
+ }
+ return customerUnknown, nil
+ }
+ }
+ res, err := cfg.Provider.Send(ctx, *b.CustomerPrepared)
+ if !retryableSend(err) || attempt == retries {
+ return s.recordCustomerLocked(h, acct, b, res, err, now)
+ }
+ }
+}
+
+// recordCustomerLocked records a customer create's answer: a definite one is
+// bound; a refusal or a cached 5xx retires the attempt; an unknown delivery or
+// a reused key leaves it to be resent. An error outside every class (a crash)
+// is returned at once with nothing recorded.
+func (s *Server) recordCustomerLocked(h billingHold, acct *Account, b *billingAccount, res billing.Result, err error, now time.Time) (customerOutcome, error) {
+ switch {
+ case err == nil && res.Customer != "":
+ if err := s.store.SetBillingCustomer(acct.ID, res.Customer, now); err != nil {
+ return customerUnknown, err
+ }
+ b.Customer = res.Customer
+ return customerBound, nil
+ case err == nil:
+ log.Printf("console: billing: account %s: customer create answered with no customer; left unresolved", acct.Sqid)
+ return customerUnknown, nil
+ case errors.Is(err, billing.ErrRefused), errors.Is(err, billing.ErrPaymentFailed):
+ log.Printf("console: billing: account %s: customer create refused: %v", acct.Sqid, err)
+ return s.retireCustomerLocked(h, b, customerRefused)
+ case errors.Is(err, billing.ErrIndeterminate):
+ log.Printf("console: billing: account %s: customer create %s indeterminate; a new attempt replaces it", acct.Sqid, b.CustomerPrepared.Key)
+ return s.retireCustomerLocked(h, b, customerRetired)
+ case errors.Is(err, billing.ErrIdempotencyMismatch):
+ log.Printf("console: billing: account %s: customer create: %v (a programming error; left unresolved)", acct.Sqid, err)
+ return customerUnknown, nil
+ case retryableSend(err):
+ return customerUnknown, nil
+ }
+ return customerUnknown, err
+}
+
+// retireCustomerLocked ends the stored attempt without a customer: the next
+// attempt prepares a new key. The provider may hold an orphan customer from
+// it, which is never bound (Risks R3).
+func (s *Server) retireCustomerLocked(h billingHold, b *billingAccount, out customerOutcome) (customerOutcome, error) {
+ _ = h
+ next := *b
+ next.CustomerPrepared, next.CustomerFirstSentAt = nil, time.Time{}
+ if err := s.store.PutBillingState(next); err != nil {
+ return customerUnknown, err
+ }
+ *b = next
+ return out, nil
+}
+
+// ---- the Checkout create ------------------------------------------------------
+
+// intentResendState is a create's resend state: delivery unknown, its window
+// the key lifetime from its first send, cut off at the session's expiry.
+func intentResendState(ci *checkoutIntent) resendState {
+ return resendState{State: opUnresolved, FirstSent: ci.FirstSentAt, ResendUntil: ci.ExpiresAt, ContextCurrent: true}
+}
+
+// createSessionLocked prepares the intent's Checkout create with every
+// parameter resolved (the price ids, the house coupon as configured now,
+// the URLs, and expires_at at provider time plus checkoutLifetime), puts the
+// intent creating with that request and its first-send stamp, and sends it
+// with the handler's retries. ci carries what it buys (ID, Book, Plan,
+// Currency, Seats, Packs); on return its State says how it ended: open,
+// abandoned, or still creating. With no provider time nothing is written
+// or sent.
+func (s *Server) createSessionLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error {
+ cfg := s.billing.cfg
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ return err
+ }
+ if b == nil || b.Customer == "" {
+ return fmt.Errorf("billing: account %s has no customer for a Checkout", acct.Sqid)
+ }
+ coupon, err := s.houseCoupon(acct)
+ if err != nil {
+ return err
+ }
+ items, err := s.checkoutItems(ci)
+ if err != nil {
+ return err
+ }
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return errNoProviderTimeRefusal
+ }
+ stamp := pnow.Truncate(time.Second)
+ base := s.cfg.Origin + billingPagePath(acct.Sqid)
+ p, err := cfg.Provider.PrepareCheckout(billing.CheckoutRequest{
+ Customer: b.Customer, AccountSqid: acct.Sqid, IntentID: ci.ID, Book: ci.Book, Currency: ci.Currency, Items: items,
+ SuccessURL: base + "/done?session={CHECKOUT_SESSION_ID}", CancelURL: base, Coupon: coupon,
+ ExpiresAt: stamp.Add(checkoutLifetime), IdempotencyKey: "checkout:" + ci.ID,
+ })
+ if err != nil {
+ return err
+ }
+ ci.AccountID, ci.Prepared, ci.State, ci.CreatedAt = acct.ID, p, intentCreating, now
+ ci.FirstSentAt, ci.ExpiresAt = stamp, stamp.Add(checkoutLifetime)
+ if err := s.store.PutCheckoutIntent(*ci); err != nil {
+ return err
+ }
+ return s.sendCreateLocked(h, ctx, acct, ci, false, now)
+}
+
+// finishCreateLocked is a later request finishing a create left creating
+// (no answer, or a crash after the send): the customer's session list is
+// read for the intent id, and otherwise the same bytes are sent once more
+// while recoveryEligible. A create whose window has closed and that the list
+// does not hold is abandoned.
+func (s *Server) finishCreateLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error {
+ if ci.State != intentCreating {
+ return nil
+ }
+ return s.sendCreateLocked(h, ctx, acct, ci, true, now)
+}
+
+// sendCreateLocked is the one sender of a Checkout create. A first send goes
+// at once; a recovery (and every in-handler retry, after the backoff) first
+// reads the customer's sessions since the intent's stamp, which settles it
+// when the intent id is there, then resends the same bytes only while
+// recoveryEligible. A recovery sends at most once.
+func (s *Server) sendCreateLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, recovering bool, now time.Time) error {
+ cfg := s.billing.cfg
+ retries := handlerRetries
+ if recovering {
+ retries = 0
+ }
+ for attempt := 0; ; attempt++ {
+ if recovering || attempt > 0 {
+ if attempt > 0 {
+ s.waitBackoff(ctx, handlerBackoff(attempt))
+ }
+ found, err := s.findIntentSessionLocked(h, ctx, acct, ci, now)
+ if err != nil || found != sessionMissing {
+ return err // recorded, or the list could not be read: settled later
+ }
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ log.Printf("console: billing: intent %s: no provider time; not resent", ci.ID)
+ return nil
+ }
+ if ok, reason := recoveryEligible(intentResendState(ci), pnow); !ok {
+ log.Printf("console: billing: intent %s: create not resent (%s)", ci.ID, reason)
+ if permanentlyIneligible(reason) {
+ // Not in the exhaustive list and past its window: a late
+ // session would be unusable (Risks R2).
+ return s.endIntentLocked(h, ci, intentAbandoned, now)
+ }
+ return nil
+ }
+ }
+ res, err := cfg.Provider.Send(ctx, ci.Prepared)
+ if !retryableSend(err) || attempt == retries {
+ return s.recordCreateLocked(h, ctx, acct, ci, res, err, now)
+ }
+ }
+}
+
+// recordCreateLocked records a create's answer: the session it made; a
+// refusal abandons; a cached 5xx is decided by the customer's session list
+// (found, recorded; not found, abandoned); an unknown delivery or a reused
+// key stays creating. An error outside every class (a crash) is returned at
+// once with the intent left creating.
+func (s *Server) recordCreateLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, res billing.Result, err error, now time.Time) error {
+ switch {
+ case err == nil && res.Checkout != nil:
+ return s.recordSessionLocked(h, ctx, acct, ci, *res.Checkout, now)
+ case err == nil:
+ log.Printf("console: billing: intent %s: the create answered with no session; left creating", ci.ID)
+ return nil
+ case errors.Is(err, billing.ErrRefused), errors.Is(err, billing.ErrPaymentFailed):
+ log.Printf("console: billing: intent %s: create refused: %v", ci.ID, err)
+ return s.endIntentLocked(h, ci, intentAbandoned, now)
+ case errors.Is(err, billing.ErrIndeterminate):
+ found, err := s.findIntentSessionLocked(h, ctx, acct, ci, now)
+ if err != nil || found != sessionMissing {
+ return err
+ }
+ return s.endIntentLocked(h, ci, intentAbandoned, now)
+ case errors.Is(err, billing.ErrIdempotencyMismatch):
+ log.Printf("console: billing: intent %s: %v (a programming error; left creating)", ci.ID, err)
+ return nil
+ case retryableSend(err):
+ return nil
+ }
+ return err
+}
+
+// sessionSearch is what a look for an intent's session found.
+type sessionSearch int
+
+const (
+ sessionUnread sessionSearch = iota // the list could not be read
+ sessionFound // the intent's session, now recorded
+ sessionMissing // the exhaustive list does not hold it
+)
+
+// findIntentSessionLocked reads every session of the account's customer
+// created at or after the intent's whole-second stamp (exhaustive) and
+// records the one carrying the intent's id.
+func (s *Server) findIntentSessionLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) (sessionSearch, error) {
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ return sessionUnread, err
+ }
+ if b == nil || b.Customer == "" {
+ log.Printf("console: billing: intent %s: the account has no customer to list", ci.ID)
+ return sessionUnread, nil
+ }
+ list, err := s.billing.cfg.Provider.CustomerCheckouts(ctx, b.Customer, ci.FirstSentAt.Truncate(time.Second))
+ if err != nil {
+ log.Printf("console: billing: intent %s: listing sessions: %v", ci.ID, err)
+ return sessionUnread, nil
+ }
+ for _, info := range list {
+ if info.IntentID == ci.ID {
+ return sessionFound, s.recordSessionLocked(h, ctx, acct, ci, info, now)
+ }
+ }
+ return sessionMissing, nil
+}
+
+// recordSessionLocked records what a read (or an answer) shows of the
+// intent's session: open, expired, or complete, which also syncs the
+// subscription the session made.
+func (s *Server) recordSessionLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, info billing.CheckoutInfo, now time.Time) error {
+ if info.ID != "" {
+ ci.Session = info.ID
+ }
+ if info.URL != "" {
+ ci.URL = info.URL
+ }
+ switch info.State {
+ case billing.CheckoutOpen:
+ ci.State = intentOpen
+ case billing.CheckoutComplete:
+ ci.State, ci.ResolvedAt = intentCompleted, now
+ case billing.CheckoutExpired:
+ ci.State, ci.ResolvedAt = intentExpired, now
+ default:
+ log.Printf("console: billing: intent %s: session %s in an unknown state; nothing recorded", ci.ID, info.ID)
+ return nil
+ }
+ if err := s.store.PutCheckoutIntent(*ci); err != nil {
+ return err
+ }
+ if ci.State == intentCompleted && info.Subscription != "" {
+ return s.syncSubscriptionLocked(h, ctx, acct, info.Subscription, now)
+ }
+ return nil
+}
+
+// endIntentLocked makes the intent terminal.
+func (s *Server) endIntentLocked(h billingHold, ci *checkoutIntent, state string, now time.Time) error {
+ _ = h
+ ci.State, ci.ResolvedAt = state, now
+ return s.store.PutCheckoutIntent(*ci)
+}
+
+// observeIntentLocked reads what the provider has for a non-terminal intent
+// and records it: an open intent's session is read; a creating one is looked
+// for in the customer's session list, and abandoned when it is not there and
+// its window has closed by the read's provider time. It reads only: nothing
+// is sent.
+func (s *Server) observeIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error {
+ switch ci.State {
+ case intentOpen:
+ info, err := s.billing.cfg.Provider.Checkout(ctx, ci.Session)
+ if err != nil {
+ return fmt.Errorf("billing: reading session %s of intent %s: %w", ci.Session, ci.ID, err)
+ }
+ return s.recordSessionLocked(h, ctx, acct, ci, info, now)
+ case intentCreating:
+ found, err := s.findIntentSessionLocked(h, ctx, acct, ci, now)
+ if err != nil || found != sessionMissing {
+ return err
+ }
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return nil
+ }
+ if ok, reason := recoveryEligible(intentResendState(ci), pnow); !ok && permanentlyIneligible(reason) {
+ return s.endIntentLocked(h, ci, intentAbandoned, now)
+ }
+ }
+ return nil
+}
+
+// ---- expiry: Start over and retirement ------------------------------------------
+
+// replaceIntentLocked clears the way for another purchase (Start over, a
+// different request, or retirement): a creating intent's create is finished
+// first; an open one's session is expired. On return ci's State is
+// terminal, or still non-terminal when nothing definite could be learned;
+// completed means the buyer paid first.
+func (s *Server) replaceIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error {
+ if ci.State == intentCreating {
+ if err := s.finishCreateLocked(h, ctx, acct, ci, now); err != nil {
+ return err
+ }
+ }
+ if ci.State != intentOpen {
+ return nil
+ }
+ return s.expireIntentLocked(h, ctx, acct, ci, now)
+}
+
+// expireResendState is an expiry's resend state: delivery unknown, its
+// window the key lifetime from its own first send, cut off at the session's
+// expiry (after which the provider has expired it anyway).
+func expireResendState(ci *checkoutIntent) resendState {
+ return resendState{State: opUnresolved, FirstSent: ci.ExpireFirstSentAt, ResendUntil: ci.ExpiresAt, ContextCurrent: true}
+}
+
+// expireIntentLocked is the one sender of an intent's expiry. The first
+// time, the expiry is prepared and stored on the intent with its
+// provider-time stamp before it is sent. A stored one is a recovery, read
+// first. An unknown delivery is retried after the backoff with a read of the
+// session, which decides when it is no longer open, then the same bytes only
+// while recoveryEligible.
+func (s *Server) expireIntentLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, now time.Time) error {
+ cfg := s.billing.cfg
+ recovering := ci.ExpirePrepared != nil
+ if !recovering {
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return errNoProviderTimeRefusal
+ }
+ p, err := cfg.Provider.PrepareExpire(ci.Session, "expire:"+ci.ID)
+ if err != nil {
+ return err
+ }
+ next := *ci
+ next.ExpirePrepared, next.ExpireFirstSentAt = &p, pnow.Truncate(time.Second)
+ if err := s.store.PutCheckoutIntent(next); err != nil {
+ return err
+ }
+ *ci = next
+ }
+ for attempt := 0; ; attempt++ {
+ if recovering || attempt > 0 {
+ if attempt > 0 {
+ s.waitBackoff(ctx, handlerBackoff(attempt))
+ }
+ info, err := cfg.Provider.Checkout(ctx, ci.Session)
+ if err != nil {
+ log.Printf("console: billing: intent %s: reading session %s before resending its expiry: %v", ci.ID, ci.Session, err)
+ return nil
+ }
+ if info.State != billing.CheckoutOpen {
+ return s.recordSessionLocked(h, ctx, acct, ci, info, now)
+ }
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return nil
+ }
+ if ok, reason := recoveryEligible(expireResendState(ci), pnow); !ok {
+ log.Printf("console: billing: intent %s: expiry not resent (%s)", ci.ID, reason)
+ return nil
+ }
+ }
+ res, err := cfg.Provider.Send(ctx, *ci.ExpirePrepared)
+ if !retryableSend(err) || attempt == handlerRetries {
+ return s.recordExpireLocked(h, ctx, acct, ci, res, err, now)
+ }
+ }
+}
+
+// recordExpireLocked records an expiry's answer: the expired session; a
+// refusal (the session was no longer open) or a cached 5xx is decided by a
+// read of the session; an unknown delivery or a reused key leaves the intent
+// open. An error outside every class is returned at once.
+func (s *Server) recordExpireLocked(h billingHold, ctx context.Context, acct *Account, ci *checkoutIntent, res billing.Result, err error, now time.Time) error {
+ switch {
+ case err == nil && res.Checkout != nil:
+ return s.recordSessionLocked(h, ctx, acct, ci, *res.Checkout, now)
+ case err == nil:
+ log.Printf("console: billing: intent %s: the expiry answered with no session", ci.ID)
+ return nil
+ case errors.Is(err, billing.ErrRefused), errors.Is(err, billing.ErrPaymentFailed), errors.Is(err, billing.ErrIndeterminate):
+ info, rerr := s.billing.cfg.Provider.Checkout(ctx, ci.Session)
+ if rerr != nil {
+ log.Printf("console: billing: intent %s: reading session %s after its expiry (%v): %v", ci.ID, ci.Session, err, rerr)
+ return nil
+ }
+ return s.recordSessionLocked(h, ctx, acct, ci, info, now)
+ case errors.Is(err, billing.ErrIdempotencyMismatch):
+ log.Printf("console: billing: intent %s: %v (a programming error; left open)", ci.ID, err)
+ return nil
+ case retryableSend(err):
+ return nil
+ }
+ return err
+}
+
+// ---- Confirm now ----------------------------------------------------------------
+
+// confirmCheckoutLocked is Confirm now's Checkout work: a customer create
+// left without an answer is resent once while recoveryEligible; a create
+// left creating is finished. It answers the flash's kind and copy key, ""
+// for none.
+func (s *Server) confirmCheckoutLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, now time.Time) (kind, key string, err error) {
+ if b != nil && b.Customer == "" && b.CustomerPrepared != nil {
+ out, err := s.sendCustomerLocked(h, ctx, acct, b, true, 0, now)
+ if err != nil {
+ return "", "", err
+ }
+ if out == customerUnknown {
+ return "err", "checkout.uncertain", nil
+ }
+ }
+ ci, err := s.store.CheckoutIntent(acct.ID)
+ if err != nil || ci == nil || ci.State != intentCreating {
+ return "", "", err
+ }
+ if err := s.finishCreateLocked(h, ctx, acct, ci, now); err != nil {
+ return "", "", err
+ }
+ switch ci.State {
+ case intentCreating:
+ return "err", "checkout.uncertain", nil
+ case intentAbandoned, intentExpired:
+ return "err", "checkout.failed", nil
+ }
+ return "", "", nil
+}
+
+// ---- Continue and the return ------------------------------------------------------
+
+// handleBillingContinue is GET /a/{sqid}/billing/continue: the owner goes
+// back to the open payment page. The session is read first; it is offered
+// only while open with more than continueMargin left in the read's provider
+// time. Otherwise a flash and back to the billing page.
+func (s *Server) handleBillingContinue(w http.ResponseWriter, r *http.Request) {
+ if s.billing == nil {
+ http.NotFound(w, r)
+ return
+ }
+ _, _, acct, ok := s.owner(w, r)
+ if !ok {
+ return
+ }
+ back := billingPagePath(acct.Sqid)
+ if !s.billing.ready.Load() {
+ s.setFlash(w, "err", billingCopy["checkout.failed"])
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ ctx := s.billingClock(r.Context())
+ now := time.Now()
+ h, release := s.holdBilling(acct.Sqid)
+ to, key, err := s.continueLocked(h, ctx, acct, now)
+ release()
+ if err != nil {
+ log.Printf("console: billing continue %s: %v", acct.Sqid, err)
+ key = "checkout.failed"
+ }
+ if to != "" {
+ http.Redirect(w, r, to, http.StatusSeeOther)
+ return
+ }
+ s.setFlash(w, "err", billingCopy[key])
+ http.Redirect(w, r, back, http.StatusSeeOther)
+}
+
+func (s *Server) continueLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (to, key string, err error) {
+ ci, err := s.store.CheckoutIntent(acct.ID)
+ if err != nil {
+ return "", "", err
+ }
+ if ci == nil {
+ return "", "checkout.expired", nil
+ }
+ switch ci.State {
+ case intentCreating:
+ return "", "checkout.uncertain", nil
+ case intentOpen:
+ if err := s.observeIntentLocked(h, ctx, acct, ci, now); err != nil {
+ return "", "", err
+ }
+ }
+ switch ci.State {
+ case intentOpen:
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return "", "checkout.failed", nil
+ }
+ if ci.URL != "" && ci.ExpiresAt.After(pnow.Add(continueMargin)) {
+ return ci.URL, "", nil
+ }
+ return "", "checkout.expired", nil
+ case intentCompleted:
+ return "", "checkout.already", nil
+ }
+ return "", "checkout.expired", nil
+}
+
+// handleBillingDone is GET /a/{sqid}/billing/done?session=: the owner back
+// from the payment page. The intent the session names is marked returned and
+// observed (a completed session syncs its subscription), then the billing
+// page, saying which plan the account is on when it is paid.
+func (s *Server) handleBillingDone(w http.ResponseWriter, r *http.Request) {
+ if s.billing == nil {
+ http.NotFound(w, r)
+ return
+ }
+ _, _, acct, ok := s.owner(w, r)
+ if !ok {
+ return
+ }
+ back := billingPagePath(acct.Sqid)
+ if !s.billing.ready.Load() {
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ ctx := s.billingClock(r.Context())
+ now := time.Now()
+ h, release := s.holdBilling(acct.Sqid)
+ kind, text, err := s.doneLocked(h, ctx, acct, r.URL.Query().Get("session"), now)
+ release()
+ if err != nil {
+ log.Printf("console: billing return %s: %v", acct.Sqid, err)
+ }
+ if text != "" {
+ s.setFlash(w, kind, text)
+ }
+ http.Redirect(w, r, back, http.StatusSeeOther)
+}
+
+func (s *Server) doneLocked(h billingHold, ctx context.Context, acct *Account, session string, now time.Time) (kind, text string, err error) {
+ if session == "" {
+ return "", "", nil
+ }
+ ci, err := s.store.CheckoutIntentBySession(session)
+ if err != nil || ci == nil || ci.AccountID != acct.ID {
+ return "", "", err
+ }
+ if ci.ReturnedAt.IsZero() {
+ ci.ReturnedAt = now
+ if err := s.store.PutCheckoutIntent(*ci); err != nil {
+ return "", "", err
+ }
+ }
+ if !intentTerminal(ci) {
+ if err := s.observeIntentLocked(h, ctx, acct, ci, now); err != nil {
+ return "", "", err
+ }
+ }
+ if ci.State != intentCompleted {
+ return "", "", nil
+ }
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil || b == nil || b.State != billing.StatePaid {
+ return "", "", err
+ }
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil || row == nil || row.Source != PlanSourceBilling {
+ return "", "", err
+ }
+ return "ok", fmt.Sprintf(billingCopy["checkout.done"], planLabel(row.Plan)), nil
+}
+
+// ---- the webhook -------------------------------------------------------------------
+
+// observeCheckoutEvent is a Checkout event for a session an intent records:
+// the intent is observed under its account's hold (a completed session
+// syncs its subscription). It reports false when no non-terminal intent
+// records the session, for the webhook's own path.
+func (s *Server) observeCheckoutEvent(ctx context.Context, session string, now time.Time) (bool, error) {
+ ci, err := s.store.CheckoutIntentBySession(session)
+ if err != nil || ci == nil || intentTerminal(ci) {
+ return false, err
+ }
+ acct, err := s.store.AccountByID(ci.AccountID)
+ if err != nil || acct == nil {
+ return false, err
+ }
+ h, release := s.holdBilling(acct.Sqid)
+ defer release()
+ cur, err := s.store.CheckoutIntent(acct.ID)
+ if err != nil || cur == nil || cur.ID != ci.ID || intentTerminal(cur) {
+ return false, err
+ }
+ return true, s.observeIntentLocked(h, ctx, acct, cur, now)
+}
diff --git a/internal/console/billingcheckout_test.go b/internal/console/billingcheckout_test.go
new file mode 100644
index 000000000..31e24d10c
--- /dev/null
+++ b/internal/console/billingcheckout_test.go
@@ -0,0 +1,1037 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "reflect"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/billing/billingtest"
+ "github.com/carlosframework/platform/internal/billingstripe"
+)
+
+// newCheckoutFixture is an ops fixture with no subscription: billing ready,
+// the Fake's clocks wired, the owner signed in and the counters reset. With
+// bound the account has customer cus_1; without, it has no billing row at
+// all (a first purchase).
+func newCheckoutFixture(t *testing.T, bound bool) *opsFixture {
+ t.Helper()
+ bf := newBillingFixture(t)
+ bf.srv.billing.ready.Store(true)
+ if !bound {
+ bf.acct = planAccount(t, bf.consoleFixture, 502)
+ }
+ o := &opsFixture{billingFixture: bf}
+ o.wire()
+ o.signInOwner(t)
+ o.reset()
+ return o
+}
+
+// billingReply is what one browser request to the server answered, with
+// the flash it set.
+type billingReply struct {
+ Status int
+ Loc, Body string
+ Flash, FlashMsg string
+}
+
+// request sends one request as the owner straight to the current server
+// (which may be a restarted one). A POST form gets the session's CSRF token.
+func (o *opsFixture) request(t *testing.T, method, path string, form url.Values) billingReply {
+ t.Helper()
+ if o.owner == nil {
+ o.signInOwner(t)
+ }
+ var body io.Reader
+ if method == http.MethodPost {
+ if form == nil {
+ form = url.Values{}
+ }
+ form.Set("csrf", o.csrf)
+ body = strings.NewReader(form.Encode())
+ }
+ req := httptest.NewRequest(method, o.ts.URL+path, body)
+ if body != nil {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ u, _ := url.Parse(o.ts.URL)
+ for _, ck := range o.owner.Jar.Cookies(u) {
+ if ck.Name != flashCookie {
+ req.AddCookie(ck)
+ }
+ }
+ rr := httptest.NewRecorder()
+ o.srv.ServeHTTP(rr, req)
+ out := billingReply{Status: rr.Code, Loc: rr.Header().Get("Location"), Body: rr.Body.String()}
+ for _, ck := range rr.Result().Cookies() {
+ if ck.Name == flashCookie && ck.Value != "" {
+ v, _ := url.QueryUnescape(ck.Value)
+ out.Flash, out.FlashMsg, _ = strings.Cut(v, "|")
+ }
+ }
+ return out
+}
+
+func (o *opsFixture) billingBase() string { return "/a/" + o.acct.Sqid + "/billing" }
+
+// checkout posts the buy form (or Start over) with kv as its fields.
+func (o *opsFixture) checkout(t *testing.T, kv ...string) billingReply {
+ t.Helper()
+ form := url.Values{}
+ for i := 0; i+1 < len(kv); i += 2 {
+ form.Set(kv[i], kv[i+1])
+ }
+ return o.request(t, http.MethodPost, o.billingBase()+"/checkout", form)
+}
+
+func (o *opsFixture) intent(t *testing.T) *checkoutIntent {
+ t.Helper()
+ ci, err := o.st.CheckoutIntent(o.acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return ci
+}
+
+func (o *opsFixture) sessions() int {
+ o.fake.Lock()
+ defer o.fake.Unlock()
+ return len(o.fake.Sessions)
+}
+
+func (o *opsFixture) session(id string) billingtest.Session {
+ o.fake.Lock()
+ defer o.fake.Unlock()
+ return *o.fake.Sessions[id]
+}
+
+// wantRefused is a redirect back to the billing page with an error flash.
+func (o *opsFixture) wantRefused(t *testing.T, r billingReply, msg string) {
+ t.Helper()
+ if r.Status != http.StatusSeeOther || r.Loc != o.billingBase() || r.Flash != "err" || r.FlashMsg != msg {
+ t.Fatalf("reply = %d %q flash %s:%q, want a refusal %q", r.Status, r.Loc, r.Flash, r.FlashMsg, msg)
+ }
+}
+
+// wantSession is a redirect to the Fake's payment page.
+func wantSession(t *testing.T, r billingReply) {
+ t.Helper()
+ if r.Status != http.StatusSeeOther || !strings.HasPrefix(r.Loc, "https://checkout.example.test/c/") {
+ t.Fatalf("reply = %d %q flash %s:%q, want a redirect to the payment page", r.Status, r.Loc, r.Flash, r.FlashMsg)
+ }
+}
+
+// armOnce runs arm the first time a Send of kind reaches the Fake.
+func (o *opsFixture) armOnce(kind string, arm func(f *billingtest.Fake)) {
+ done := false
+ o.fake.Lock()
+ o.fake.BeforeSend = func(p billing.Prepared) error {
+ if p.Kind == kind && !done {
+ done = true
+ o.fake.Lock()
+ arm(o.fake)
+ o.fake.Unlock()
+ }
+ return nil
+ }
+ o.fake.Unlock()
+}
+
+func (o *opsFixture) disarm() {
+ o.fake.Lock()
+ o.fake.BeforeSend = nil
+ o.fake.Unlock()
+}
+
+// fakeCheckoutBody is the Fake's encoding of a Checkout create.
+type fakeCheckoutBody struct {
+ Customer string `json:"customer"`
+ AccountSqid string `json:"account_sqid"`
+ IntentID string `json:"intent_id"`
+ Book string `json:"book"`
+ Currency string `json:"currency"`
+ Items []billing.CheckoutItem `json:"items"`
+ SuccessURL string `json:"success_url"`
+ CancelURL string `json:"cancel_url"`
+ Coupon string `json:"coupon"`
+ ExpiresAt int64 `json:"expires_at"`
+}
+
+func checkoutBodyOf(t *testing.T, p billing.Prepared) fakeCheckoutBody {
+ t.Helper()
+ var b fakeCheckoutBody
+ if err := json.Unmarshal(p.Body, &b); err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// ---- starting a Checkout ----------------------------------------------------
+
+func TestCheckoutStartsSession(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ r := o.checkout(t, "plan", "personal", "currency", "usd", "pack_apps", "2")
+ wantSession(t, r)
+ // L(all subs) for the bound customer, then the create; the list's Date is
+ // the provider time for the stamp and expires_at, so no probe.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Send": 1})
+ ci := o.intent(t)
+ pnow := o.providerClock()
+ if ci == nil || ci.State != intentOpen || ci.URL != r.Loc || ci.Plan != "personal" || ci.Currency != "usd" || ci.Seats != 0 ||
+ ci.Book != o.srv.billing.cfg.Book.Version || !reflect.DeepEqual(ci.Packs, map[string]int{"apps": 2}) {
+ t.Fatalf("intent = %+v", ci)
+ }
+ if !ci.FirstSentAt.Equal(pnow) || !ci.ExpiresAt.Equal(pnow.Add(checkoutLifetime)) || ci.Prepared.Key != "checkout:"+ci.ID {
+ t.Fatalf("stamps %v %v key %q, want provider %v", ci.FirstSentAt, ci.ExpiresAt, ci.Prepared.Key, pnow)
+ }
+ if sent := o.sent(); len(sent) != 1 || !reflect.DeepEqual(sent[0], ci.Prepared) {
+ t.Fatalf("sent %+v, want the stored create", sent)
+ }
+ body := checkoutBodyOf(t, ci.Prepared)
+ base := o.srv.cfg.Origin + o.billingBase()
+ want := fakeCheckoutBody{Customer: "cus_1", AccountSqid: o.acct.Sqid, IntentID: ci.ID, Book: ci.Book, Currency: "usd",
+ Items: []billing.CheckoutItem{{PriceID: testPriceID("example-v1/personal/usd"), Quantity: 1},
+ {PriceID: testPriceID("example-v1/pack/apps/usd"), Quantity: 2}},
+ SuccessURL: base + "/done?session={CHECKOUT_SESSION_ID}", CancelURL: base, ExpiresAt: pnow.Add(checkoutLifetime).Unix()}
+ if !reflect.DeepEqual(body, want) {
+ t.Fatalf("create body\n got %+v\nwant %+v", body, want)
+ }
+ // The page now offers Continue and Start over.
+ page := o.request(t, http.MethodGet, o.billingBase(), nil)
+ if !strings.Contains(page.Body, o.billingBase()+"/continue") || !strings.Contains(page.Body, `name="start_over" value="1"`) {
+ t.Fatalf("page after checkout:\n%s", page.Body)
+ }
+}
+
+func TestCheckoutTeamSeats(t *testing.T) {
+ for _, tc := range []struct {
+ members int
+ qty int64
+ }{{4, 10}, {13, 13}} {
+ t.Run(fmt.Sprint(tc.members), func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ for i := 1; i < tc.members; i++ {
+ if err := o.st.AddMember(o.acct.ID, fmt.Sprintf("m%d@example.com", i), RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ wantSession(t, o.checkout(t, "plan", "community", "currency", "usd"))
+ ci := o.intent(t)
+ body := checkoutBodyOf(t, ci.Prepared)
+ if ci.Seats != int(tc.qty) || len(body.Items) != 1 || body.Items[0] != (billing.CheckoutItem{PriceID: testPriceID("example-v1/community/usd"), Quantity: tc.qty}) {
+ t.Fatalf("%d members: seats %d items %+v, want %d", tc.members, ci.Seats, body.Items, tc.qty)
+ }
+ })
+ }
+}
+
+func TestCheckoutContinueSameRequest(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ first := o.checkout(t, "plan", "personal", "currency", "usd")
+ wantSession(t, first)
+ o.reset()
+ again := o.checkout(t, "plan", "personal", "currency", "usd")
+ if again.Status != http.StatusSeeOther || again.Loc != first.Loc {
+ t.Fatalf("same request = %d %q, want the open session %q", again.Status, again.Loc, first.Loc)
+ }
+ // S (none recorded) + L + 1 session read, whose Date serves the continue check.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Checkout": 1})
+ if o.sessions() != 1 {
+ t.Fatalf("sessions = %d", o.sessions())
+ }
+ o.reset()
+ r := o.request(t, http.MethodGet, o.billingBase()+"/continue", nil)
+ if r.Status != http.StatusSeeOther || r.Loc != first.Loc {
+ t.Fatalf("continue = %d %q", r.Status, r.Loc)
+ }
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1})
+ // Inside the last five minutes, Continue sends the buyer back instead.
+ o.fake.AdvanceProvider(checkoutLifetime - 4*time.Minute)
+ o.wantRefused(t, o.request(t, http.MethodGet, o.billingBase()+"/continue", nil), billingCopy["checkout.expired"])
+}
+
+func TestCheckoutStartOverReplaces(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ kv []string
+ }{
+ {"start over", []string{"plan", "personal", "currency", "usd", "start_over", "1"}},
+ {"a different request", []string{"plan", "personal", "currency", "usd", "pack_apps", "3"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ first := o.checkout(t, "plan", "personal", "currency", "usd")
+ wantSession(t, first)
+ old := o.intent(t)
+ o.reset()
+ r := o.checkout(t, tc.kv...)
+ wantSession(t, r)
+ if r.Loc == first.Loc {
+ t.Fatal("the old session was reused")
+ }
+ // S + L + 1 session read + the expiry + the new create.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Checkout": 1, "Send": 2})
+ sent := o.sent()
+ if sent[0].Kind != billing.PreparedExpire || sent[0].Key != "expire:"+old.ID {
+ t.Fatalf("first send %+v, want the old intent's expiry", sent[0])
+ }
+ if o.session(old.Session).State != billing.CheckoutExpired {
+ t.Fatal("the old session is still open")
+ }
+ ci := o.intent(t)
+ if ci.ID == old.ID || ci.State != intentOpen || ci.URL != r.Loc {
+ t.Fatalf("intent = %+v", ci)
+ }
+ })
+ }
+}
+
+func TestCheckoutExpiryLosesToCompletion(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ old := o.intent(t)
+ o.reset()
+ // The buyer pays just before the expiry arrives.
+ o.fake.Lock()
+ o.fake.BeforeSend = func(p billing.Prepared) error {
+ if p.Kind == billing.PreparedExpire {
+ if _, err := o.fake.CompleteCheckout(old.Session); err != nil {
+ t.Error(err)
+ }
+ }
+ return nil
+ }
+ o.fake.Unlock()
+ r := o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1")
+ o.wantRefused(t, r, billingCopy["checkout.already"])
+ // The read, the refused expiry, the read that decides, then the sync.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Checkout": 2, "Send": 1, "Subscription": 1})
+ if ci := o.intent(t); ci.ID != old.ID || ci.State != intentCompleted {
+ t.Fatalf("intent = %+v", ci)
+ }
+ if o.plan(t) != "personal" || o.sessions() != 1 {
+ t.Fatalf("plan %q sessions %d", o.plan(t), o.sessions())
+ }
+}
+
+func TestCheckoutAfterCancellationWithOldRecorded(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.put(o.personalSub("sub_1", "canceled", nil))
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1, "LiveSubscriptions": 1, "Send": 1})
+}
+
+func TestCheckoutRefusesScheduledCancellation(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ sub := o.personalSub("sub_1", "active", nil)
+ sub.CancelAtPeriodEnd = true
+ o.put(sub)
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.already"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if ci := o.intent(t); ci != nil {
+ t.Fatalf("an intent was written: %+v", ci)
+ }
+}
+
+func TestCheckoutSeesLiveSubscriptionOnPageTwo(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ for i := 0; i < 150; i++ {
+ o.put(o.personalSub(fmt.Sprintf("sub_a%03d", i), "canceled", nil))
+ }
+ o.put(o.personalSub("sub_z", "active", nil))
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.already"])
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 2, "Subscription": 1})
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Subscription != "sub_z" || o.plan(t) != "personal" {
+ t.Fatalf("the live subscription was not synced: %+v", b)
+ }
+ if o.fake.Writes() != 0 {
+ t.Fatalf("writes = %d", o.fake.Writes())
+ }
+}
+
+func TestCheckoutRefusesIncompleteList(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.fake.PageSize = 1
+ for i := 0; i < 11; i++ {
+ o.put(o.personalSub(fmt.Sprintf("sub_a%03d", i), "canceled", nil))
+ }
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.failed"])
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": billing.MaxListPages})
+ if ci := o.intent(t); ci != nil {
+ t.Fatalf("an intent was written: %+v", ci)
+ }
+}
+
+// ---- an unclear create --------------------------------------------------------
+
+func TestLostCreateResentInHandler(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.fake.FailBeforeDelivery = 1
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ // 1 + N x (L(c) + 1): one retry, its session list, then the same bytes.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Send": 2, "CustomerCheckouts": 1})
+ sent := o.sent()
+ if !reflect.DeepEqual(sent[0], sent[1]) || !reflect.DeepEqual(sent[0], o.intent(t).Prepared) {
+ t.Fatalf("resent other bytes: %+v", sent)
+ }
+ if o.sessions() != 1 || o.intent(t).State != intentOpen {
+ t.Fatalf("sessions %d intent %+v", o.sessions(), o.intent(t))
+ }
+}
+
+// unresolvedCreate leaves the create and the handler's read after it with
+// no answer: the intent stays creating and the provider made nothing.
+func (o *opsFixture) unresolvedCreate(t *testing.T) *checkoutIntent {
+ t.Helper()
+ o.armOnce(billing.PreparedCheckout, func(f *billingtest.Fake) { f.HeaderlessTimeout = 2 })
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ o.disarm()
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Send": 1, "CustomerCheckouts": 1})
+ ci := o.intent(t)
+ if ci == nil || ci.State != intentCreating || ci.FirstSentAt.IsZero() || o.sessions() != 0 {
+ t.Fatalf("intent %+v sessions %d", ci, o.sessions())
+ }
+ o.reset()
+ return ci
+}
+
+func TestLostCreateContinuedFromThePage(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ ci := o.unresolvedCreate(t)
+ page := o.request(t, http.MethodGet, o.billingBase(), nil)
+ if !strings.Contains(page.Body, o.billingBase()+"/confirm") {
+ t.Fatalf("the page offers no Confirm now:\n%s", page.Body)
+ }
+ if status, loc := o.confirm(t); status != http.StatusSeeOther || loc != o.billingBase() {
+ t.Fatalf("confirm = %d %q", status, loc)
+ }
+ // F on the create: L(c), whose Date serves the gate, then the same bytes.
+ wantCounts(t, o.counts(), map[string]int{"CustomerCheckouts": 1, "Send": 1})
+ if sent := o.sent(); !reflect.DeepEqual(sent[0], ci.Prepared) {
+ t.Fatalf("resent %+v, want the stored create", sent[0])
+ }
+ got := o.intent(t)
+ if got.State != intentOpen || got.ID != ci.ID {
+ t.Fatalf("intent = %+v", got)
+ }
+ page = o.request(t, http.MethodGet, o.billingBase(), nil)
+ if !strings.Contains(page.Body, o.billingBase()+"/continue") {
+ t.Fatalf("the page offers no Continue:\n%s", page.Body)
+ }
+ o.reset()
+ r := o.request(t, http.MethodGet, o.billingBase()+"/continue", nil)
+ if r.Status != http.StatusSeeOther || r.Loc != got.URL {
+ t.Fatalf("continue = %d %q, want %q", r.Status, r.Loc, got.URL)
+ }
+ if o.sessions() != 1 {
+ t.Fatalf("sessions = %d", o.sessions())
+ }
+}
+
+// stubStripe is just enough of the provider's HTTP API for a house Checkout
+// through the real adapter: the subscription and session lists, session
+// creates, and the price the clock probe reads. While down it reads each
+// request and drops the connection with no answer.
+type stubStripe struct {
+ mu sync.Mutex
+ down bool
+ downOnCreate bool
+ creates [][]byte
+ sessions []map[string]any
+}
+
+func (st *stubStripe) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ st.mu.Lock()
+ create := r.Method == http.MethodPost && r.URL.Path == "/v1/checkout/sessions"
+ if create {
+ st.creates = append(st.creates, body)
+ if st.downOnCreate {
+ st.down, st.downOnCreate = true, false
+ }
+ }
+ if st.down {
+ st.mu.Unlock()
+ if conn, _, err := w.(http.Hijacker).Hijack(); err == nil {
+ conn.Close()
+ }
+ return
+ }
+ defer st.mu.Unlock()
+ list := func(data []map[string]any) {
+ if data == nil {
+ data = []map[string]any{}
+ }
+ json.NewEncoder(w).Encode(map[string]any{"object": "list", "data": data, "has_more": false})
+ }
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/v1/subscriptions":
+ list(nil)
+ case r.Method == http.MethodGet && r.URL.Path == "/v1/checkout/sessions":
+ list(st.sessions)
+ case create:
+ form, _ := url.ParseQuery(string(body))
+ id := fmt.Sprintf("cs_test_%d", len(st.sessions)+1)
+ exp, _ := strconv.ParseInt(form.Get("expires_at"), 10, 64)
+ s := map[string]any{"id": id, "object": "checkout.session", "url": "https://checkout.stripe.com/c/pay/" + id, "status": "open",
+ "customer": form.Get("customer"), "livemode": false, "currency": form.Get("currency"), "expires_at": exp,
+ "metadata": map[string]string{"checkout_intent": form.Get("metadata[checkout_intent]")}}
+ st.sessions = append(st.sessions, s)
+ json.NewEncoder(w).Encode(s)
+ case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/v1/prices/"):
+ json.NewEncoder(w).Encode(map[string]any{"id": strings.TrimPrefix(r.URL.Path, "/v1/prices/"), "object": "price"})
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{"type": "invalid_request_error", "code": "resource_missing"}})
+ }
+}
+
+func TestCheckoutResendBytesSurviveConfigChange(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ stub := &stubStripe{downOnCreate: true}
+ srv := httptest.NewServer(stub)
+ defer srv.Close()
+ adapter, err := billingstripe.NewProvider(billingstripe.ProviderConfig{
+ SecretKey: "rk_test_census", Account: "acct_1", WebhookSecrets: []string{"whsec_test"}, PortalConfiguration: "bpc_1",
+ PriceIDs: []string{testPriceID("example-v1/personal/usd")}, BaseURL: srv.URL,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ o.srv.billing.cfg.Provider = adapter
+ o.srv.billing.cfg.HouseCoupon = "co_house_a"
+ if err := o.st.SetBillingHouse(o.acct.ID, true, "op@example.com", "house", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ // The create reaches the provider and its answer is lost; the handler's
+ // session list gets no answer either, so the create stays unresolved.
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ if ci := o.intent(t); ci == nil || ci.State != intentCreating {
+ t.Fatalf("intent = %+v", ci)
+ }
+ // The house coupon is reconfigured; then Confirm now.
+ stub.mu.Lock()
+ stub.down = false
+ stub.mu.Unlock()
+ o.srv.billing.cfg.HouseCoupon = "co_house_b"
+ if status, _ := o.confirm(t); status != http.StatusSeeOther {
+ t.Fatalf("confirm = %d", status)
+ }
+ stub.mu.Lock()
+ defer stub.mu.Unlock()
+ if len(stub.creates) != 2 || !bytes.Equal(stub.creates[0], stub.creates[1]) {
+ t.Fatalf("creates on the wire:\n%q", stub.creates)
+ }
+ if !bytes.Contains(stub.creates[1], []byte("co_house_a")) || bytes.Contains(stub.creates[1], []byte("co_house_b")) {
+ t.Fatalf("the resend is not the original house create: %s", stub.creates[1])
+ }
+ if ci := o.intent(t); ci.State != intentOpen || len(stub.sessions) != 1 {
+ t.Fatalf("intent %+v sessions %d", ci, len(stub.sessions))
+ }
+}
+
+func TestCreateCached500ObservedByIntentID(t *testing.T) {
+ t.Run("before applying: abandoned", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.fake.Cached500Before = true
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.failed"])
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Send": 1, "CustomerCheckouts": 1})
+ if ci := o.intent(t); ci.State != intentAbandoned || o.sessions() != 0 {
+ t.Fatalf("intent %+v sessions %d", ci, o.sessions())
+ }
+ })
+ t.Run("after applying: found by intent id", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.fake.Cached500After = true
+ r := o.checkout(t, "plan", "personal", "currency", "usd")
+ wantSession(t, r)
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Send": 1, "CustomerCheckouts": 1})
+ if ci := o.intent(t); ci.State != intentOpen || ci.URL != r.Loc || o.sessions() != 1 {
+ t.Fatalf("intent %+v sessions %d", ci, o.sessions())
+ }
+ })
+}
+
+func TestCreateWindowClosedNotFoundAbandoned(t *testing.T) {
+ t.Run("confirm now", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.unresolvedCreate(t)
+ o.fake.Elapse(checkoutLifetime + time.Minute)
+ if status, _ := o.confirm(t); status != http.StatusSeeOther {
+ t.Fatalf("confirm = %d", status)
+ }
+ wantCounts(t, o.counts(), map[string]int{"CustomerCheckouts": 1})
+ if ci := o.intent(t); ci.State != intentAbandoned {
+ t.Fatalf("intent = %+v", ci)
+ }
+ })
+ t.Run("the pass", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.unresolvedCreate(t)
+ o.fake.Elapse(checkoutLifetime + time.Minute)
+ o.pass(billingNow)
+ // The intent pass: a probe (the round has no observation yet), then
+ // L(c); then discovery's list for the recently bound customer.
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "CustomerCheckouts": 1, "LiveSubscriptions": 1})
+ if ci := o.intent(t); ci.State != intentAbandoned {
+ t.Fatalf("intent = %+v", ci)
+ }
+ })
+}
+
+func TestCreateCrashRecovered(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.fake.CrashAfterSend = true
+ r := o.checkout(t, "plan", "personal", "currency", "usd")
+ if r.Status != http.StatusSeeOther || r.Loc != o.billingBase() {
+ t.Fatalf("crash = %d %q", r.Status, r.Loc)
+ }
+ if ci := o.intent(t); ci.State != intentCreating || ci.FirstSentAt.IsZero() {
+ t.Fatalf("intent after the crash = %+v", ci)
+ }
+ o.restart(t)
+ o.reset()
+ if status, _ := o.confirm(t); status != http.StatusSeeOther {
+ t.Fatalf("confirm = %d", status)
+ }
+ wantCounts(t, o.counts(), map[string]int{"CustomerCheckouts": 1})
+ if ci := o.intent(t); ci.State != intentOpen || o.sessions() != 1 {
+ t.Fatalf("intent %+v sessions %d", ci, o.sessions())
+ }
+}
+
+func TestCreateRetryCountsSessionPages(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ for i := 0; i < 250; i++ {
+ o.fake.AddSession(&billingtest.Session{CheckoutInfo: billing.CheckoutInfo{Customer: "cus_1", IntentID: fmt.Sprintf("ci_other%d", i),
+ State: billing.CheckoutExpired}})
+ }
+ o.reset()
+ o.fresh()
+ o.observe()
+ o.fake.FailBeforeDelivery = 2
+ ci := &checkoutIntent{AccountID: o.acct.ID, ID: "ci_counted", Book: o.srv.billing.cfg.Book.Version, Plan: "personal", Currency: "usd"}
+ h, release := o.hold()
+ err := o.srv.createSessionLocked(h, o.ctx, o.acct, ci, billingNow)
+ release()
+ if err != nil || ci.State != intentOpen {
+ t.Fatalf("create: %v, intent %+v", err, ci)
+ }
+ // 250 sessions since the intent, 2 retries: 1 + 2 x (3 + 1) == 9.
+ wantCounts(t, o.counts(), map[string]int{"Send": 3, "CustomerCheckouts": 6})
+}
+
+// ---- the customer --------------------------------------------------------------
+
+func TestCustomerCreateNoResponseResent(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.fake.FailBeforeDelivery = 1
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ // No customer: no list read; one probe stamps the customer create, whose
+ // answer then serves the create's stamp.
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "Send": 3})
+ sent := o.sent()
+ key := "customer:" + o.acct.Sqid + ":1"
+ if sent[0].Key != key || !reflect.DeepEqual(sent[0], sent[1]) || sent[2].Kind != billing.PreparedCheckout {
+ t.Fatalf("sent %+v", sent)
+ }
+ b, _ := o.st.BillingAccount(o.acct.ID)
+ if b == nil || b.Customer == "" || b.CustomerAttempt != 1 || b.CustomerPrepared == nil || !reflect.DeepEqual(*b.CustomerPrepared, sent[0]) ||
+ !b.CustomerFirstSentAt.Equal(o.providerClock()) {
+ t.Fatalf("billing row = %+v", b)
+ }
+ if body := checkoutBodyOf(t, sent[2]); body.Customer != b.Customer {
+ t.Fatalf("the create names customer %q, want %q", body.Customer, b.Customer)
+ }
+}
+
+func TestCustomerCreateCached500NewAttempt(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.fake.Cached500Before = true
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "Send": 3})
+ sent := o.sent()
+ if sent[0].Key != "customer:"+o.acct.Sqid+":1" || sent[1].Key != "customer:"+o.acct.Sqid+":2" {
+ t.Fatalf("keys %q %q, want attempts 1 and 2", sent[0].Key, sent[1].Key)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Customer == "" || b.CustomerAttempt != 2 {
+ t.Fatalf("billing row = %+v", b)
+ }
+}
+
+func TestCustomerCreateWindowClosedNewAttempt(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.fake.FailBeforeDelivery = 1 + handlerRetries
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ // Past the key lifetime from the first send: never resent; a new key.
+ o.fake.Elapse(resendLifetime + time.Minute)
+ o.reset()
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "Send": 2})
+ if sent := o.sent(); sent[0].Key != "customer:"+o.acct.Sqid+":2" {
+ t.Fatalf("sent %q first, want attempt 2", sent[0].Key)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Customer == "" || b.CustomerAttempt != 2 {
+ t.Fatalf("billing row = %+v", b)
+ }
+}
+
+func TestCustomerRetryCountsNoRead(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.fresh()
+ o.observe()
+ o.fake.FailBeforeDelivery = 3
+ h, release := o.hold()
+ customer, err := o.srv.ensureCustomerLocked(h, o.ctx, o.acct, billingNow)
+ release()
+ if err != nil || customer == "" {
+ t.Fatalf("customer %q, %v", customer, err)
+ }
+ // 3 retries, no read: 1 + N == 4 requests.
+ wantCounts(t, o.counts(), map[string]int{"Send": 4})
+}
+
+// ---- expiry and Start over ---------------------------------------------------
+
+func TestExpiryNoResponseResent(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ old := o.intent(t)
+ o.reset()
+ o.fake.FailBeforeDelivery = 1
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1"))
+ // The read; the expiry (1 + 2N, N = 1); the new create.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Checkout": 2, "Send": 3})
+ sent := o.sent()
+ if sent[0].Kind != billing.PreparedExpire || !reflect.DeepEqual(sent[0], sent[1]) {
+ t.Fatalf("the expiry was not resent verbatim: %+v", sent)
+ }
+ if o.session(old.Session).State != billing.CheckoutExpired || o.intent(t).ID == old.ID {
+ t.Fatal("the old session was not replaced")
+ }
+}
+
+// TestCheckoutExpiryNotResentPastItsWindow: the provider still shows the
+// session open after the intent's provider-time ExpiresAt (its own expiry
+// lags); an expiry whose first send got no answer is not resent outside its
+// window, and Start over is refused rather than creating a second session.
+func TestCheckoutExpiryNotResentPastItsWindow(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ old := o.intent(t)
+ o.fake.Lock()
+ o.fake.Sessions[old.Session].ExpiresAt = old.ExpiresAt.Add(2 * time.Hour)
+ o.fake.Unlock()
+ o.fake.AdvanceProvider(checkoutLifetime + time.Minute)
+ o.reset()
+ o.fake.FailBeforeDelivery = 1
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd", "start_over", "1"), billingCopy["checkout.uncertain"])
+ // The read; the expiry, lost; the retry's read; no resend.
+ wantCounts(t, o.counts(), map[string]int{"LiveSubscriptions": 1, "Checkout": 2, "Send": 1})
+ if ci := o.intent(t); ci.ID != old.ID || ci.State != intentOpen || ci.ExpirePrepared == nil || ci.ExpireFirstSentAt.IsZero() {
+ t.Fatalf("intent = %+v", ci)
+ }
+ if o.sessions() != 1 {
+ t.Fatalf("sessions = %d", o.sessions())
+ }
+}
+
+// ---- passes, return and the webhook --------------------------------------------
+
+func TestPassRightAfterCheckoutKeepsSession(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ first := o.checkout(t, "plan", "personal", "currency", "usd")
+ wantSession(t, first)
+ o.reset()
+ o.pass(billingNow)
+ // One session read for the open intent; discovery's list for the
+ // recently bound customer. 0 writes.
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "LiveSubscriptions": 1})
+ if ci := o.intent(t); ci.State != intentOpen || ci.URL != first.Loc {
+ t.Fatalf("intent = %+v", ci)
+ }
+ if r := o.request(t, http.MethodGet, o.billingBase()+"/continue", nil); r.Loc != first.Loc {
+ t.Fatalf("continue after the pass = %d %q", r.Status, r.Loc)
+ }
+
+ // A create still inside its window is the owner's to finish: the pass
+ // learns provider time (one probe) and reads no sessions.
+ t.Run("creating inside its window", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ ci := o.unresolvedCreate(t)
+ o.fake.Elapse(10 * time.Minute)
+ o.pass(billingNow)
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "LiveSubscriptions": 1})
+ if got := o.intent(t); got.State != intentCreating || got.ID != ci.ID {
+ t.Fatalf("intent = %+v", got)
+ }
+ })
+}
+
+func TestPassObservesCompletedIntent(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ if _, err := o.fake.CompleteCheckout(ci.Session); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ o.pass(billingNow)
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
+ if got := o.intent(t); got.State != intentCompleted || o.plan(t) != "personal" {
+ t.Fatalf("intent %+v plan %q", got, o.plan(t))
+ }
+}
+
+func TestCompletedIntentDoesNotBlockNextPurchase(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ old := o.intent(t)
+ subID, err := o.fake.CompleteCheckout(old.Session)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+old.Session, nil); r.Status != http.StatusSeeOther {
+ t.Fatalf("done = %d", r.Status)
+ }
+ o.fake.Lock()
+ s := o.fake.Subs[subID]
+ s.Live, s.State, s.ProviderStatus = false, billing.StateEnded, "canceled"
+ o.fake.Unlock()
+ if err := o.srv.syncSubscription(context.Background(), subID, billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1, "LiveSubscriptions": 1, "Send": 1})
+ if ci := o.intent(t); ci.ID == old.ID || ci.State != intentOpen {
+ t.Fatalf("intent = %+v", ci)
+ }
+}
+
+func TestCheckoutDoneSyncs(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ if _, err := o.fake.CompleteCheckout(ci.Session); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ // Another account's session changes nothing here.
+ if r := o.request(t, http.MethodGet, o.billingBase()+"/done?session=cs_someone_else", nil); r.Status != http.StatusSeeOther || r.Loc != o.billingBase() || r.Flash != "" {
+ t.Fatalf("foreign session = %+v", r)
+ }
+ wantCounts(t, o.counts(), map[string]int{})
+ r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil)
+ if r.Status != http.StatusSeeOther || r.Loc != o.billingBase() || r.Flash != "ok" || r.FlashMsg != fmt.Sprintf(billingCopy["checkout.done"], "Personal") {
+ t.Fatalf("done = %+v", r)
+ }
+ // 1 session read + S.
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
+ if got := o.intent(t); got.State != intentCompleted || got.ReturnedAt.IsZero() || o.plan(t) != "personal" {
+ t.Fatalf("intent %+v plan %q", got, o.plan(t))
+ }
+}
+
+func TestCheckoutDoneSettling(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ subID, err := o.fake.CompleteCheckout(ci.Session)
+ if err != nil {
+ t.Fatal(err)
+ }
+ o.fake.Lock()
+ s := o.fake.Subs[subID]
+ s.State, s.ProviderStatus = billing.StatePending, "incomplete"
+ o.fake.Unlock()
+ r := o.request(t, http.MethodGet, o.billingBase()+"/done?session="+ci.Session, nil)
+ if r.Status != http.StatusSeeOther || r.Loc != o.billingBase() || r.Flash != "" {
+ t.Fatalf("done = %+v, want back to the page with no flash", r)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Subscription != subID || b.State != billing.StatePending {
+ t.Fatalf("billing row = %+v", b)
+ }
+ page := o.request(t, http.MethodGet, o.billingBase(), nil)
+ if !strings.Contains(page.Body, esc(billingCopy["notice.settling"])) {
+ t.Fatalf("the page does not say it is settling:\n%s", page.Body)
+ }
+}
+
+func TestCheckoutWebhookObservesIntent(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ if _, err := o.fake.CompleteCheckout(ci.Session); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ if status := billingDeliver(t, o.consoleFixture, "checkout", ci.Session, false); status != http.StatusNoContent {
+ t.Fatalf("webhook = %d", status)
+ }
+ wantCounts(t, o.counts(), map[string]int{"Checkout": 1, "Subscription": 1})
+ if got := o.intent(t); got.State != intentCompleted || o.plan(t) != "personal" {
+ t.Fatalf("intent %+v plan %q", got, o.plan(t))
+ }
+}
+
+// ---- refusals ---------------------------------------------------------------------
+
+func TestCheckoutRefusesOperatorRows(t *testing.T) {
+ for _, source := range []string{PlanSourceOperator, PlanSourceSponsored} {
+ t.Run(source, func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ if _, err := o.st.SetAccountPlan(o.acct.ID, "personal", nil, 0, source, nil, "set by hand", "op@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["notice.operator_plan"])
+ wantCounts(t, o.counts(), map[string]int{})
+ })
+ }
+ t.Run("retiring", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ if err := o.st.BeginBillingRetirement(o.acct.ID, "owner", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["billing.retiring"])
+ wantCounts(t, o.counts(), map[string]int{})
+ })
+ t.Run("a problem", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ if _, err := o.st.OpenBillingProblem(o.acct.ID, "sub_x", problemUnrecognised, "census", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["notice.problem"])
+ wantCounts(t, o.counts(), map[string]int{})
+ })
+}
+
+func TestCheckoutNotReadyStartsNothing(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.srv.billing.ready.Store(false)
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.failed"])
+ wantCounts(t, o.counts(), map[string]int{})
+ if b, _ := o.st.BillingAccount(o.acct.ID); b != nil {
+ t.Fatalf("a billing row was written: %+v", b)
+ }
+ if ci := o.intent(t); ci != nil {
+ t.Fatalf("an intent was written: %+v", ci)
+ }
+}
+
+func TestCheckoutHouseWithoutCoupon(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ if err := o.st.SetBillingHouse(o.acct.ID, true, "op@example.com", "house", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.failed"])
+ wantCounts(t, o.counts(), map[string]int{})
+ if b, _ := o.st.BillingAccount(o.acct.ID); b != nil {
+ t.Fatalf("a customer create was prepared: %+v", b)
+ }
+ if ci := o.intent(t); ci != nil {
+ t.Fatalf("an intent was written: %+v", ci)
+ }
+ // With a coupon configured, the create carries it.
+ o.srv.billing.cfg.HouseCoupon = "co_house"
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ if body := checkoutBodyOf(t, o.intent(t).Prepared); body.Coupon != "co_house" {
+ t.Fatalf("coupon = %q", body.Coupon)
+ }
+}
+
+func TestCheckoutCurrencyRules(t *testing.T) {
+ for _, tc := range []struct{ name, currency, msg string }{
+ {"unsold", "chf", fmt.Sprintf(billingCopy["currency.refused"], "chf")},
+ {"not as written", "USD", fmt.Sprintf(billingCopy["currency.refused"], "usd")},
+ {"unshowable", "<b>", billingCopy["currency.refused_unshown"]},
+ {"none chosen", "", billingCopy["currency.refused_unshown"]},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", tc.currency), tc.msg)
+ wantCounts(t, o.counts(), map[string]int{})
+ })
+ }
+ t.Run("fixed after the first purchase", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ b, _ := o.st.BillingAccount(o.acct.ID)
+ b.Currency = "eur"
+ if err := o.st.PutBillingState(*b); err != nil {
+ t.Fatal(err)
+ }
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), fmt.Sprintf(billingCopy["currency.fixed"], "eur"))
+ wantCounts(t, o.counts(), map[string]int{})
+ wantSession(t, o.checkout(t, "plan", "personal"))
+ if body := checkoutBodyOf(t, o.intent(t).Prepared); body.Currency != "eur" || body.Items[0].PriceID != testPriceID("example-v1/personal/eur") {
+ t.Fatalf("body = %+v", body)
+ }
+ })
+}
+
+func TestPutCheckoutIntentGuards(t *testing.T) {
+ st, ids := planStore(t, "bab")
+ ci := testIntent(ids["bab"], "ci_1")
+ if err := st.PutCheckoutIntent(ci); err != nil {
+ t.Fatal(err)
+ }
+ for name, edit := range map[string]func(c *checkoutIntent){
+ "plan": func(c *checkoutIntent) { c.Plan = "business" },
+ "currency": func(c *checkoutIntent) { c.Currency = "eur" },
+ "seats": func(c *checkoutIntent) { c.Seats = 13 },
+ "packs": func(c *checkoutIntent) { c.Packs = map[string]int{"apps": 3} },
+ "book": func(c *checkoutIntent) { c.Book = "example-v2" },
+ "first sent": func(c *checkoutIntent) { c.FirstSentAt = c.FirstSentAt.Add(time.Minute) },
+ "first sent gone": func(c *checkoutIntent) { c.FirstSentAt = time.Time{} },
+ } {
+ c := ci
+ c.Packs = map[string]int{"apps": 2, "email": 1}
+ edit(&c)
+ if err := st.PutCheckoutIntent(c); err == nil {
+ t.Errorf("%s: changed on the same intent", name)
+ }
+ }
+ // The expiry's stamp is written once too.
+ ci.State, ci.Session = intentOpen, "cs_1"
+ ci.ExpireFirstSentAt = billingNow.Add(time.Minute)
+ if err := st.PutCheckoutIntent(ci); err != nil {
+ t.Fatal(err)
+ }
+ moved := ci
+ moved.ExpireFirstSentAt = billingNow.Add(2 * time.Minute)
+ if err := st.PutCheckoutIntent(moved); err == nil {
+ t.Error("the expiry's first-send stamp moved")
+ }
+ // Terminal is final.
+ ci.State = intentExpired
+ if err := st.PutCheckoutIntent(ci); err != nil {
+ t.Fatal(err)
+ }
+ ci.State = intentOpen
+ if err := st.PutCheckoutIntent(ci); err == nil {
+ t.Error("an expired intent was opened again")
+ }
+ if got, _ := st.CheckoutIntent(ids["bab"]); got.State != intentExpired || !got.ExpireFirstSentAt.Equal(billingNow.Add(time.Minute)) {
+ t.Fatalf("stored = %+v", got)
+ }
+}
diff --git a/internal/console/billingops.go b/internal/console/billingops.go
index 194b434ee..b3f54fd70 100644
--- a/internal/console/billingops.go
+++ b/internal/console/billingops.go
@@ -696,16 +696,23 @@ func outcomeCopy(out opOutcome) (kind, key string) {
return "err", "change.uncertain"
}
-// confirmBillingLocked is Confirm now under the hold: an operation left
-// sending or unresolved on the account's subscription is finished
-// (finishOpLocked), then the subscription is refreshed. It answers the
-// flash's kind and copy key, "" for none. The Checkout work (an unresolved
-// customer create or session create) is added here by the Checkout task.
+// confirmBillingLocked is Confirm now under the hold: the Checkout work
+// first (a customer create or a session create left without an answer,
+// confirmCheckoutLocked), then an operation left sending or unresolved on the
+// account's subscription is finished (finishOpLocked), then the subscription
+// is refreshed. It answers the flash's kind and copy key, "" for none.
func (s *Server) confirmBillingLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (kind, key string, err error) {
b, err := s.store.BillingAccount(acct.ID)
- if err != nil || b == nil || b.Subscription == "" {
+ if err != nil {
return "", "", err
}
+ if kind, key, err = s.confirmCheckoutLocked(h, ctx, acct, b, now); err != nil {
+ return kind, key, err
+ }
+ // The Checkout work may have bound a customer or synced a subscription.
+ if b, err = s.store.BillingAccount(acct.ID); err != nil || b == nil || b.Subscription == "" {
+ return kind, key, err
+ }
op, err := s.store.OutstandingOp(b.Subscription)
if err != nil {
return "", "", err
diff --git a/internal/console/billingops_test.go b/internal/console/billingops_test.go
index 9e6366ba1..bc88e251c 100644
--- a/internal/console/billingops_test.go
+++ b/internal/console/billingops_test.go
@@ -1082,25 +1082,49 @@ func TestRestoreNeedsProviderTime(t *testing.T) {
}
}
-// The proration_date half; the expires_at half is Task 9's (Checkout), under
-// this same name's scenario there (Ruling R2).
+// The console's wall clock is 3 h off provider time: a change's
+// proration_date and a Checkout's expires_at both follow provider time (the
+// expires_at half is Task 9's, Ruling R2).
func TestExpiresAtAndProrationDateUseProviderTime(t *testing.T) {
- o := newOpsFixture(t, map[string]int64{"apps": 1})
- o.fake.SetConsoleClock(o.providerClock().Add(3 * time.Hour))
- o.observe()
- op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack)
- var body struct {
- ProrationDate int64 `json:"proration_date"`
- }
- if err := json.Unmarshal(op.Prepared.Body, &body); err != nil {
- t.Fatal(err)
- }
- if body.ProrationDate != o.providerClock().Unix() {
- t.Fatalf("proration_date = %d, want provider time %d", body.ProrationDate, o.providerClock().Unix())
- }
- if body.ProrationDate == o.fake.ConsoleNow().Unix() {
- t.Fatal("proration_date followed the console's wall clock")
- }
+ t.Run("proration_date", func(t *testing.T) {
+ o := newOpsFixture(t, map[string]int64{"apps": 1})
+ o.fake.SetConsoleClock(o.providerClock().Add(3 * time.Hour))
+ o.observe()
+ op := o.packOp(t, "op_1", "sub_1", "apps", 3, billing.ProrateNow, opPack)
+ var body struct {
+ ProrationDate int64 `json:"proration_date"`
+ }
+ if err := json.Unmarshal(op.Prepared.Body, &body); err != nil {
+ t.Fatal(err)
+ }
+ if body.ProrationDate != o.providerClock().Unix() {
+ t.Fatalf("proration_date = %d, want provider time %d", body.ProrationDate, o.providerClock().Unix())
+ }
+ if body.ProrationDate == o.fake.ConsoleNow().Unix() {
+ t.Fatal("proration_date followed the console's wall clock")
+ }
+ })
+ t.Run("expires_at", func(t *testing.T) {
+ o := newCheckoutFixture(t, true)
+ // The handler's wall clock is the process's; provider time runs 3 h
+ // behind it.
+ o.fake.SetProviderClock(time.Now().UTC().Add(-3 * time.Hour).Truncate(time.Second))
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ ci := o.intent(t)
+ var body struct {
+ ExpiresAt int64 `json:"expires_at"`
+ }
+ if err := json.Unmarshal(ci.Prepared.Body, &body); err != nil {
+ t.Fatal(err)
+ }
+ want := o.providerClock().Add(checkoutLifetime)
+ if body.ExpiresAt != want.Unix() || !ci.ExpiresAt.Equal(want) || !ci.FirstSentAt.Equal(o.providerClock()) {
+ t.Fatalf("expires_at = %d (intent %v, first sent %v), want provider time + 1 h = %v", body.ExpiresAt, ci.ExpiresAt, ci.FirstSentAt, want)
+ }
+ if d := time.Until(time.Unix(body.ExpiresAt, 0)); d > 30*time.Minute {
+ t.Fatalf("expires_at followed the console's wall clock: %v from now", d)
+ }
+ })
}
func TestFirstSendUnderSkewThenLateRecoveryRefused(t *testing.T) {
@@ -1167,8 +1191,54 @@ func TestFirstSendUnderSkewRecoveryInsideWindow(t *testing.T) {
}
}
-// TestQuietCustomerRecoveryUsesProbe is written in Task 9 (customer create).
-// TestHeaderlessTimeoutRecoveredThroughProbe is written in Task 9 (customer create).
+// TestQuietCustomerRecoveryUsesProbe: a first purchase's customer create
+// gets no answer; eleven quiet minutes later the next Checkout has no customer
+// to list and an empty recorder, so one probe gives the gate its provider time,
+// and the stored bytes go once (Ruling R2: written with the customer create).
+func TestQuietCustomerRecoveryUsesProbe(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.fake.FailBeforeDelivery = 1 + handlerRetries
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "Send": 1 + handlerRetries})
+ b, _ := o.st.BillingAccount(o.acct.ID)
+ if b == nil || b.Customer != "" || b.CustomerPrepared == nil || b.CustomerFirstSentAt.IsZero() {
+ t.Fatalf("billing row = %+v", b)
+ }
+ stored := *b.CustomerPrepared
+ o.fake.Elapse(11 * time.Minute)
+ o.reset()
+ wantSession(t, o.checkout(t, "plan", "personal", "currency", "usd"))
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "Send": 2})
+ if sent := o.sent(); !reflect.DeepEqual(sent[0], stored) || sent[1].Kind != billing.PreparedCheckout {
+ t.Fatalf("sent %+v, want the stored customer create then the Checkout", sent)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Customer == "" || b.CustomerAttempt != 1 {
+ t.Fatalf("billing row = %+v", b)
+ }
+}
+
+// TestHeaderlessTimeoutRecoveredThroughProbe: the customer create times out
+// before any header arrives; Confirm now two minutes later (no observation
+// at most 60 s old) probes, resends and binds (Ruling R2).
+func TestHeaderlessTimeoutRecoveredThroughProbe(t *testing.T) {
+ o := newCheckoutFixture(t, false)
+ o.armOnce(billing.PreparedCustomer, func(f *billingtest.Fake) { f.HeaderlessTimeout = 1 + handlerRetries })
+ o.wantRefused(t, o.checkout(t, "plan", "personal", "currency", "usd"), billingCopy["checkout.uncertain"])
+ o.disarm()
+ o.fake.Elapse(2 * time.Minute)
+ o.reset()
+ if status, loc := o.confirm(t); status != http.StatusSeeOther || loc != o.billingBase() {
+ t.Fatalf("confirm = %d %q", status, loc)
+ }
+ wantCounts(t, o.counts(), map[string]int{"ClockProbe": 1, "Send": 1})
+ b, _ := o.st.BillingAccount(o.acct.ID)
+ if b == nil || b.Customer == "" || b.CustomerAttempt != 1 {
+ t.Fatalf("billing row = %+v", b)
+ }
+ if sent := o.sent(); !reflect.DeepEqual(sent[0], *b.CustomerPrepared) {
+ t.Fatalf("sent %+v, want the stored bytes", sent)
+ }
+}
// ---- passes ------------------------------------------------------------------
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index fcc2912d8..c71003288 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -17,6 +17,14 @@ var billingCopy = map[string]string{
"change.retry": "Your plan just renewed. Try again in a minute.",
"change.clock": "We can't make that change right now. Try again in a few minutes.",
+ // Checkout (Task 9).
+ "checkout.already": "This account already has a paid plan, or a payment is finishing. Check back in a minute.",
+ "checkout.failed": "We couldn't start the payment. Try again in a minute.",
+ "checkout.uncertain": "We couldn't confirm the payment page was created. Use Confirm now, or try again in a few minutes.",
+ "checkout.done": "You're on %s.",
+ "checkout.expired": "That payment page has expired. Start again.",
+ "billing.retiring": "This account is being deleted.",
+
// The page (Task 8).
"page.title": "Billing",
"notice.not_ready": "Billing isn't available right now. Try again in a few minutes.",
diff --git a/internal/console/billingpass.go b/internal/console/billingpass.go
index efe53abda..6c388b661 100644
--- a/internal/console/billingpass.go
+++ b/internal/console/billingpass.go
@@ -133,9 +133,64 @@ func (s *Server) billingSyncPass(ctx context.Context, now time.Time) {
}
s.billingOpsPass(ctx, now, synced)
s.billingRestorePass(ctx, now, synced)
+ s.billingIntentPass(ctx, now)
s.billingDiscoveryPass(ctx, now)
}
+// billingIntentPass observes every non-terminal Checkout intent (plans 6b):
+// an open one gets a session read, which records a completed session (and
+// syncs its subscription) or an expired one; a creating one is looked for in
+// its customer's session list only once provider time is past its
+// ExpiresAt, and abandoned when the list does not hold it (Invariant 1's
+// exception). A creating intent inside its window is left to the owner's
+// next request, which may resend it. Reads and store writes only: 0 writes
+// to the provider.
+func (s *Server) billingIntentPass(ctx context.Context, now time.Time) {
+ var afterCreated time.Time
+ var afterAccount int64
+ for ctx.Err() == nil {
+ page, err := s.store.NonTerminalCheckoutIntentsAfter(afterCreated, afterAccount, billingSyncBatch)
+ if err != nil {
+ log.Printf("console: billing intent pass: %v", err)
+ return
+ }
+ for _, ci := range page {
+ afterCreated, afterAccount = ci.CreatedAt, ci.AccountID
+ s.observeIntent(ctx, ci, now)
+ }
+ if len(page) < billingSyncBatch {
+ return
+ }
+ }
+}
+
+func (s *Server) observeIntent(ctx context.Context, ci checkoutIntent, now time.Time) {
+ acct, err := s.store.AccountByID(ci.AccountID)
+ if err != nil || acct == nil {
+ log.Printf("console: billing intent pass: intent %s: account %d: %v", ci.ID, ci.AccountID, err)
+ return
+ }
+ if ci.State == intentCreating {
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ log.Printf("console: billing intent pass: intent %s: no provider time; not observed this round", ci.ID)
+ return
+ }
+ if pnow.Before(ci.ExpiresAt) {
+ return
+ }
+ }
+ h, release := s.holdBilling(acct.Sqid)
+ defer release()
+ cur, err := s.store.CheckoutIntent(acct.ID)
+ if err != nil || cur == nil || cur.ID != ci.ID || intentTerminal(cur) {
+ return
+ }
+ if err := s.observeIntentLocked(h, ctx, acct, cur, now); err != nil {
+ log.Printf("console: billing intent pass: intent %s: %v", ci.ID, err)
+ }
+}
+
// billingOpsPass observes every outstanding operation (Call 17, Invariant
// 8): its subscription is synced under the hold, unless this round already
// did, which adopts an orphaned sending row and settles on positive
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index d47ef0aaa..4ee774fb3 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -197,6 +197,11 @@ CREATE TABLE IF NOT EXISTS billing_restore_checks (
if err != nil {
return err
}
+ // The expiry's own first-send stamp (provider time, Invariant 9), for a
+ // store created before the column existed.
+ if _, err := s.db.Exec(`ALTER TABLE billing_checkout_intents ADD COLUMN expire_first_sent_at INTEGER NOT NULL DEFAULT 0`); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
return s.migrateBillingOperations()
}
@@ -701,6 +706,10 @@ type checkoutIntent struct {
ExpirePrepared *billing.Prepared // set when an expiry is prepared
State string
CreatedAt, ExpiresAt, FirstSentAt, ReturnedAt, ResolvedAt time.Time
+ // ExpireFirstSentAt is the expiry's provider-time stamp, taken just
+ // before its first send and written once, like FirstSentAt for the
+ // create.
+ ExpireFirstSentAt time.Time
}
// intentTerminal is an intent nothing more will happen to: completed,
@@ -714,17 +723,18 @@ func intentTerminal(ci *checkoutIntent) bool {
}
const checkoutIntentColumns = `account_id, intent_id, session, url, book, plan, currency, seats, packs, prepared, expire_prepared,
- state, created_at, expires_at, first_sent_at, returned_at, resolved_at`
+ state, created_at, expires_at, first_sent_at, returned_at, resolved_at, expire_first_sent_at`
func scanCheckoutIntent(sc interface{ Scan(...any) error }) (*checkoutIntent, error) {
var ci checkoutIntent
var packs string
var prepared, expire []byte
- var created, expires, firstSent, returned, resolved int64
+ var created, expires, firstSent, returned, resolved, expireSent int64
if err := sc.Scan(&ci.AccountID, &ci.ID, &ci.Session, &ci.URL, &ci.Book, &ci.Plan, &ci.Currency, &ci.Seats, &packs,
- &prepared, &expire, &ci.State, &created, &expires, &firstSent, &returned, &resolved); err != nil {
+ &prepared, &expire, &ci.State, &created, &expires, &firstSent, &returned, &resolved, &expireSent); err != nil {
return nil, err
}
+ ci.ExpireFirstSentAt = timeOrZero(expireSent)
if err := json.Unmarshal([]byte(packs), &ci.Packs); err != nil {
return nil, err
}
@@ -746,8 +756,11 @@ func scanCheckoutIntent(sc interface{ Scan(...any) error }) (*checkoutIntent, er
// PutCheckoutIntent writes the account's intent. The same intent is
// updated in place, but its prepared requests are never edited (Invariant
// 1): a create whose bytes differ, or an expiry other than the one already
-// stored, is refused. Another intent replaces the account's only when the
-// stored one is terminal, so an outstanding create is never lost.
+// stored, is refused. So is a change to what it buys (book, plan,
+// currency, seats, packs), to a first-send stamp already written, and a
+// terminal intent made non-terminal again: a terminal intent is history.
+// Another intent replaces the account's only when the stored one is
+// terminal, so an outstanding create is never lost.
func (s *Store) PutCheckoutIntent(ci checkoutIntent) error {
if ci.ID == "" {
return errors.New("billing: checkout intent without an id")
@@ -785,22 +798,41 @@ func (s *Store) PutCheckoutIntent(ci checkoutIntent) error {
if cur.ExpirePrepared != nil && !samePrepared(cur.ExpirePrepared, ci.ExpirePrepared) {
return fmt.Errorf("billing: checkout intent %s: the prepared expiry cannot change", ci.ID)
}
+ curPacks, err := canonicalPacks(cur.Packs)
+ if err != nil {
+ return err
+ }
+ if cur.Book != ci.Book || cur.Plan != ci.Plan || cur.Currency != ci.Currency || cur.Seats != ci.Seats || curPacks != packs {
+ return fmt.Errorf("billing: checkout intent %s: what it buys cannot change", ci.ID)
+ }
+ if !writeOnce(cur.FirstSentAt, ci.FirstSentAt) || !writeOnce(cur.ExpireFirstSentAt, ci.ExpireFirstSentAt) {
+ return fmt.Errorf("billing: checkout intent %s: a first-send stamp is written once", ci.ID)
+ }
+ if intentTerminal(cur) && !intentTerminal(&ci) {
+ return fmt.Errorf("billing: checkout intent %s is %s, which is final", ci.ID, cur.State)
+ }
}
if _, err := tx.Exec(`INSERT INTO billing_checkout_intents (`+checkoutIntentColumns+`)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(account_id) DO UPDATE SET intent_id = excluded.intent_id, session = excluded.session, url = excluded.url,
book = excluded.book, plan = excluded.plan, currency = excluded.currency, seats = excluded.seats, packs = excluded.packs,
prepared = excluded.prepared, expire_prepared = excluded.expire_prepared, state = excluded.state,
created_at = excluded.created_at, expires_at = excluded.expires_at, first_sent_at = excluded.first_sent_at,
- returned_at = excluded.returned_at, resolved_at = excluded.resolved_at`,
+ returned_at = excluded.returned_at, resolved_at = excluded.resolved_at, expire_first_sent_at = excluded.expire_first_sent_at`,
ci.AccountID, ci.ID, ci.Session, ci.URL, ci.Book, ci.Plan, ci.Currency, ci.Seats, packs, prepared, expire,
ci.State, unixOrZero(ci.CreatedAt), unixOrZero(ci.ExpiresAt), unixOrZero(ci.FirstSentAt),
- unixOrZero(ci.ReturnedAt), unixOrZero(ci.ResolvedAt)); err != nil {
+ unixOrZero(ci.ReturnedAt), unixOrZero(ci.ResolvedAt), unixOrZero(ci.ExpireFirstSentAt)); err != nil {
return err
}
return tx.Commit()
}
+// writeOnce is a stamp stored to the second that next leaves as it is: none
+// yet, or the same second.
+func writeOnce(cur, next time.Time) bool {
+ return cur.IsZero() || (!next.IsZero() && cur.Unix() == next.Unix())
+}
+
// samePrepared is two prepared requests that send the same bytes.
func samePrepared(a, b *billing.Prepared) bool {
if a == nil || b == nil {
@@ -834,8 +866,16 @@ func (s *Store) CheckoutIntentBySession(session string) (*checkoutIntent, error)
// NonTerminalCheckoutIntents is up to limit intents still creating or
// open, oldest first: the pass's observation list.
func (s *Store) NonTerminalCheckoutIntents(limit int) ([]checkoutIntent, error) {
+ return s.NonTerminalCheckoutIntentsAfter(time.Time{}, 0, limit)
+}
+
+// NonTerminalCheckoutIntentsAfter pages NonTerminalCheckoutIntents by
+// (created_at, account_id): up to limit intents after the given position.
+func (s *Store) NonTerminalCheckoutIntentsAfter(afterCreated time.Time, afterAccount int64, limit int) ([]checkoutIntent, error) {
+ at := unixOrZero(afterCreated)
rows, err := s.db.Query(`SELECT `+checkoutIntentColumns+` FROM billing_checkout_intents
- WHERE state IN (?, ?) ORDER BY created_at, account_id LIMIT ?`, intentCreating, intentOpen, limit)
+ WHERE state IN (?, ?) AND (created_at > ? OR (created_at = ? AND account_id > ?))
+ ORDER BY created_at, account_id LIMIT ?`, intentCreating, intentOpen, at, at, afterAccount, limit)
if err != nil {
return nil, err
}
diff --git a/internal/console/billingwebhook.go b/internal/console/billingwebhook.go
index 4d1f5ce6b..38c460266 100644
--- a/internal/console/billingwebhook.go
+++ b/internal/console/billingwebhook.go
@@ -58,6 +58,18 @@ func (s *Server) handleBillingWebhook(w http.ResponseWriter, r *http.Request) {
case billing.EventSubscription:
subscription = ev.Object
case billing.EventCheckout:
+ // A session an intent records: observe the intent (plans 6b), which
+ // syncs a completed session's subscription.
+ observed, err := s.observeCheckoutEvent(s.billingClock(r.Context()), ev.Object, now)
+ if err != nil {
+ log.Printf("console: billing webhook: event %s: observing its checkout: %v", ev.ID, err)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ if observed {
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
subscription, err = cfg.Provider.CheckoutSubscription(r.Context(), ev.Object)
if errors.Is(err, billing.ErrNotFound) {
subscription, err = "", nil
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index e01d7b7df..dc152402b 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1305,6 +1305,14 @@ var claimFixtures = map[string]claimFixture{
// operation under the account's billing hold and refreshes the
// subscription.
"route POST /a/{sqid}/billing/confirm": claimNonApp("finishes the account's outstanding billing operation from a fresh provider read and refreshes its subscription, writing billing state, the plan row and billing problems; names no app"),
+ // Plans 6b Checkout: the owner's buy or Start over prepares and sends a
+ // customer create and a Checkout create (and an old session's expiry),
+ // writing the billing row and the Checkout intent; Continue and the
+ // return read the session and record what it shows on the intent, a
+ // completed one syncing its subscription.
+ "route POST /a/{sqid}/billing/checkout": claimNonApp("prepares and sends the account's customer create, Checkout create and an old session's expiry under the billing hold, writing the billing row, the Checkout intent, the plan row and billing problems; names no app"),
+ "route GET /a/{sqid}/billing/continue": claimNonApp("reads the open Checkout session and records its state on the account's intent (a completed one syncs its subscription) before redirecting to it; names no app"),
+ "route GET /a/{sqid}/billing/done": claimNonApp("marks the account's Checkout intent returned, reads its session and syncs the subscription a completed one made, writing the intent, billing state and the plan row; names no app"),
// ---- POST: CLI, account and deployment level ----
"route POST /accounts/new": claimNonApp("creates an account and its owner membership"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index 95e62dc4a..2dd63b824 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -699,6 +699,45 @@ var claimNonAppProbes = map[string]claimProbe{
return claimBillingPlanIs(t, cx, "personal")
},
},
+ "route POST /a/{sqid}/billing/checkout": {
+ setup: claimCheckoutWorld,
+ do: claimFormReply("/a/bab/billing/checkout", "plan", "personal", "currency", "usd"),
+ status: http.StatusSeeOther, loc: "https://checkout.example.test/c/",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ return claimCheckoutIntentIs(cx, intentOpen)
+ },
+ },
+ "route GET /a/{sqid}/billing/continue": {
+ setup: claimOpenIntentWorld,
+ do: claimPageReply("/a/bab/billing/continue"),
+ status: http.StatusSeeOther, loc: "https://checkout.example.test/c/cs_claim",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake)
+ fake.Lock()
+ reads := fake.CallsBy["Checkout"]
+ fake.Unlock()
+ if reads != 1 {
+ return fmt.Sprintf("continue made %d session reads, want 1", reads)
+ }
+ return claimCheckoutIntentIs(cx, intentOpen)
+ },
+ },
+ "route GET /a/{sqid}/billing/done": {
+ setup: func(t *testing.T, cx *claimCase) {
+ claimOpenIntentWorld(t, cx)
+ if _, err := cx.srv.billing.cfg.Provider.(*billingtest.Fake).CompleteCheckout("cs_claim"); err != nil {
+ t.Fatal(err)
+ }
+ },
+ do: claimPageReply("/a/bab/billing/done?session=cs_claim"),
+ status: http.StatusSeeOther, loc: "/a/bab/billing",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ if msg := claimCheckoutIntentIs(cx, intentCompleted); msg != "" {
+ return msg
+ }
+ return claimBillingPlanIs(t, cx, "personal")
+ },
+ },
"route POST /api/cli/billing/problems/{id}/close": {
setup: claimBillingProblemWorld,
do: func(t *testing.T, cx *claimCase) claimReply {
@@ -1001,6 +1040,60 @@ func claimBillingWorld(t *testing.T, cx *claimCase) {
cx.srv.billing.ready.Store(true)
}
+// claimCheckoutWorld switches billing on with a Fake provider and binds bab
+// to customer cus_claim, with no subscription: a first purchase.
+func claimCheckoutWorld(t *testing.T, cx *claimCase) {
+ t.Helper()
+ enableBilling(t, cx.srv)
+ acct, err := cx.srv.store.AccountBySqid("bab")
+ if err != nil || acct == nil {
+ t.Fatalf("bab: %v", err)
+ }
+ if err := cx.srv.store.SetBillingCustomer(acct.ID, "cus_claim", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ cx.srv.billing.ready.Store(true)
+}
+
+// claimOpenIntentWorld is claimCheckoutWorld with an open Checkout intent
+// for Personal whose session cs_claim the provider has open.
+func claimOpenIntentWorld(t *testing.T, cx *claimCase) {
+ t.Helper()
+ claimCheckoutWorld(t, cx)
+ acct, _ := cx.srv.store.AccountBySqid("bab")
+ fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake)
+ fake.Lock()
+ expires := fake.ProviderClock.Add(checkoutLifetime)
+ fake.Unlock()
+ req := billing.CheckoutRequest{Customer: "cus_claim", AccountSqid: "bab", IntentID: "ci_claim", Book: cx.srv.billing.cfg.Book.Version,
+ Currency: "usd", Items: []billing.CheckoutItem{{PriceID: testPriceID("example-v1/personal/usd"), Quantity: 1}}, ExpiresAt: expires,
+ IdempotencyKey: "checkout:ci_claim"}
+ fake.AddSession(&billingtest.Session{CheckoutInfo: billing.CheckoutInfo{ID: "cs_claim", Customer: "cus_claim", IntentID: "ci_claim",
+ State: billing.CheckoutOpen, ExpiresAt: expires}, Request: req})
+ p, err := fake.PrepareCheckout(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := cx.srv.store.PutCheckoutIntent(checkoutIntent{AccountID: acct.ID, ID: "ci_claim", Session: "cs_claim",
+ URL: "https://checkout.example.test/c/cs_claim", Book: req.Book, Plan: "personal", Currency: "usd", Prepared: p,
+ State: intentOpen, CreatedAt: time.Now(), ExpiresAt: expires, FirstSentAt: expires.Add(-checkoutLifetime)}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// claimCheckoutIntentIs reports "" when bab's Checkout intent is in state.
+func claimCheckoutIntentIs(cx *claimCase, state string) string {
+ acct, err := cx.srv.store.AccountBySqid("bab")
+ if err != nil || acct == nil {
+ return "no bab account"
+ }
+ ci, err := cx.srv.store.CheckoutIntent(acct.ID)
+ if err != nil || ci == nil || ci.State != state {
+ return fmt.Sprintf("bab's Checkout intent is not %s: %+v %v", state, ci, err)
+ }
+ return ""
+}
+
// claimBillingWebhookReply delivers a signed Fake event for sub_claim.
func claimBillingWebhookReply(t *testing.T, cx *claimCase) claimReply {
t.Helper()
diff --git a/internal/console/server.go b/internal/console/server.go
index 16e08975a..bbcbb9780 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1567,6 +1567,12 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// Plans 6b: an owner's Confirm now finishes a billing operation left
// without a definite outcome (billingops.go). 404 with billing off.
s.registerRoute("POST /a/{sqid}/billing/confirm", s.handleBillingConfirm)
+ // Plans 6b: Checkout (billingcheckout.go). The owner's buy and Start over
+ // POST, Continue back to an open payment page, and the return from it.
+ // 404 with billing off.
+ s.registerRoute("POST /a/{sqid}/billing/checkout", s.handleBillingCheckout)
+ s.registerRoute("GET /a/{sqid}/billing/continue", s.handleBillingContinue)
+ s.registerRoute("GET /a/{sqid}/billing/done", s.handleBillingDone)
// The billing page (billingpage.go): member-readable, its forms the
// owner's. 404 with billing off.
s.registerRoute("GET /a/{sqid}/billing", s.handleBilling)
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index aabff5e3f..5677a3177 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -30,6 +30,8 @@ route GET /a/{sqid}/apps/{app}/releases
route GET /a/{sqid}/apps/{app}/settings
route GET /a/{sqid}/apps/{app}/settings/{section}
route GET /a/{sqid}/billing
+route GET /a/{sqid}/billing/continue
+route GET /a/{sqid}/billing/done
route GET /a/{sqid}/fleet
route GET /a/{sqid}/fleet/byo
route GET /a/{sqid}/fleets/{fleet}
@@ -152,6 +154,7 @@ route POST /a/{sqid}/apps/{app}/restart
route POST /a/{sqid}/apps/{app}/rollback
route POST /a/{sqid}/apps/{app}/store/destroy
route POST /a/{sqid}/apps/{app}/swap
+route POST /a/{sqid}/billing/checkout
route POST /a/{sqid}/billing/confirm
route POST /a/{sqid}/delete
route POST /a/{sqid}/errors/level