carlos / platform Public

console: pack changes and upgrades as prepared operations; no restore within 25 provider-time hours of renewal; stop and resume renewal (plans 6b)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 873462c663ad7b267c23a21ac4fbdf0d16aa23a6 parent cdff6f2
7 files changed, +1,564 −0
  • internal/console/billingchange.go +578 −0
  • internal/console/billingchange_test.go +916 −0
  • internal/console/billingpage_copy.go +12 −0
  • internal/console/claim_invariant_fixtures_test.go +6 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +46 −0
  • internal/console/server.go +4 −0
  • internal/console/testdata/claim-routes.txt +2 −0

CI failed — run details

diff --git a/internal/console/billingchange.go b/internal/console/billingchange.go
new file mode 100644
index 000000000..56cb7d3f1
--- /dev/null
+++ b/internal/console/billingchange.go
@@ -0,0 +1,578 @@
+package console
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/subtle"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "slices"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// Pack changes, plan upgrades and renewal (plans 6b, Task 10).
+//
+// Every change is one or two prepared operations sent by sendOpLocked under
+// the account's billing hold, computed from a fresh allowance read:
+//
+// - a reduction is one ProrateNone pack operation (it takes effect for the
+// next renewal's invoice; the period's paid count stays);
+// - a raise is split by quantityPlan into a free restore up to the
+// period's paid count (ProrateNone) and a charged step beyond it
+// (ProrateNow). A restore keeps away from the renewal (Invariant 4): the
+// whole request is refused unless the period end is more than
+// restoreMargin ahead in provider time. The charge is computed only after
+// a definite restore applied in the same period, from the item the
+// restore's answer names;
+// - an upgrade (Call 4) is one ProrateNow swap of the plan item's price, to
+// a plan whose lowest yearly total in the configured book is higher and
+// that offers every pack held, priced from the subscription's own book.
+//
+// A charge needs confirmation (the confirm page, with a local estimate) and a
+// fresh sign-in proof. Renewal is one renewal operation and needs neither.
+// While an operation is outstanding on the subscription, nothing new is
+// started: it is finished first, and still outstanding refuses.
+
+// The change refusals, each a billingCopy key.
+var (
+ errChangeOutstanding = billingRefusal{Key: "change.outstanding"}
+ errChangeNone = billingRefusal{Key: "change.none"}
+ errChangeFailed = billingRefusal{Key: "change.failed"}
+ errChangeBook = billingRefusal{Key: "change.book"}
+)
+
+// changeAsk is what a change form asks for: a pack at a quantity, or a plan.
+type changeAsk struct {
+ Pack string
+ Quantity int64
+ Plan string
+ Confirmed bool
+}
+
+// changeQuote is what the confirm page shows for a charge: the estimate in
+// minor units of currency, or none (Known false) when the console does not
+// hold the subscription's book.
+type changeQuote struct {
+ Currency string
+ Estimate int64
+ Known bool
+}
+
+// changeReply is a change's answer: a flash (kind and text), or a quote for
+// the confirm page.
+type changeReply struct {
+ Kind, Text string
+ Quote *changeQuote
+}
+
+func changeFlash(kind, key string) changeReply {
+ return changeReply{Kind: kind, Text: billingCopy[key]}
+}
+
+// newOpID is a fresh operation id; its idempotency key is op:<id>.
+func newOpID() string {
+ var b [8]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ panic(err)
+ }
+ return "op_" + hex.EncodeToString(b[:])
+}
+
+// prorateEstimate is Call 5's local quote: the yearly price of qty units
+// times the days left until periodEnd (part of a day counts as a day, at
+// most a year) over 365, rounded up. It is what the page says, never what is
+// charged: the provider computes the charge.
+func prorateEstimate(annualMinor, qty int64, now, periodEnd time.Time) int64 {
+ left := periodEnd.Sub(now)
+ if annualMinor <= 0 || qty <= 0 || left <= 0 {
+ return 0
+ }
+ days := min(int64((left+24*time.Hour-1)/(24*time.Hour)), 365)
+ total := annualMinor * qty * days
+ return (total + 364) / 365
+}
+
+// changeText is the flash text for an error a change door returns: a
+// refusal's copy, an outstanding operation, else change.failed (logged).
+func changeText(sqid string, err error) string {
+ var ref billingRefusal
+ if errors.As(err, &ref) {
+ if text, ok := billingCopy[ref.Key]; ok {
+ return text
+ }
+ }
+ if errors.Is(err, ErrOpOutstanding) {
+ return billingCopy["change.outstanding"]
+ }
+ log.Printf("console: billing change %s: %v", sqid, err)
+ return billingCopy["change.failed"]
+}
+
+// parseChangeForm reads a change form: pack and quantity (0 to the pack's
+// maximum), or a paid catalog plan, never both.
+func (s *Server) parseChangeForm(r *http.Request) (changeAsk, bool) {
+ ask := changeAsk{Pack: r.PostFormValue("pack"), Plan: r.PostFormValue("plan"), Confirmed: confirmed(r)}
+ cat := s.cfg.PlanCatalog
+ switch {
+ case ask.Pack != "" && ask.Plan == "":
+ pk, ok := cat.Packs[ask.Pack]
+ q, err := strconv.ParseInt(r.PostFormValue("quantity"), 10, 64)
+ if !ok || err != nil || q < 0 || q > int64(pk.MaxQuantity) {
+ return ask, false
+ }
+ ask.Quantity = q
+ return ask, true
+ case ask.Plan != "" && ask.Pack == "":
+ p, ok := cat.Plans[ask.Plan]
+ return ask, ok && p.Paid
+ }
+ return ask, false
+}
+
+// handleBillingChange is POST /a/{sqid}/billing/change: an owner's pack
+// change or plan upgrade. Billing off answers 404, a member the owner gate's
+// 404, no CSRF 403; a confirmed request then needs a fresh sign-in proof
+// (Call 6), before the hold. An unconfirmed charge answers the confirm page;
+// everything else goes back to the billing page with a flash.
+func (s *Server) handleBillingChange(w http.ResponseWriter, r *http.Request) {
+ if s.billing == nil {
+ http.NotFound(w, r)
+ return
+ }
+ addr, 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)
+ ask, valid := s.parseChangeForm(r)
+ if !s.billing.ready.Load() || !valid {
+ s.setFlash(w, "err", billingCopy["change.failed"])
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ if ask.Confirmed && !s.requireFreshAuth(w, r, addr, raw) {
+ return
+ }
+ ctx := s.billingClock(r.Context())
+ now := time.Now()
+ h, release := s.holdBilling(acct.Sqid)
+ reply, err := s.changeLocked(h, ctx, acct, ask, now)
+ release()
+ if err != nil {
+ reply = changeReply{Kind: "err", Text: changeText(acct.Sqid, err)}
+ }
+ if reply.Quote != nil {
+ s.renderChangeConfirm(w, r, addr, raw, acct, ask, *reply.Quote)
+ return
+ }
+ s.setFlash(w, reply.Kind, reply.Text)
+ http.Redirect(w, r, back, http.StatusSeeOther)
+}
+
+// renderChangeConfirm is the confirm page for a charge: the estimate, and a
+// form posting the same change with confirmed=1.
+func (s *Server) renderChangeConfirm(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, ask changeAsk, q changeQuote) {
+ line := billingCopy["change.no_estimate"]
+ if q.Known {
+ line = fmt.Sprintf(billingCopy["confirm.line"], plans.FormatMinor(q.Currency, q.Estimate))
+ }
+ fields := [][2]string{{"csrf", raw}}
+ if ask.Plan != "" {
+ fields = append(fields, [2]string{"plan", ask.Plan})
+ } else {
+ fields = append(fields, [2]string{"pack", ask.Pack}, [2]string{"quantity", strconv.FormatInt(ask.Quantity, 10)})
+ }
+ p := s.accountPage(w, r, addr, raw, acct, RoleOwner)
+ p.Title = billingCopy["confirm.title"]
+ p.AppName = acct.Name
+ p.ActiveNav = "billing"
+ p.Confirm = &ConfirmView{
+ Title: billingCopy["confirm.title"],
+ Lines: []string{line},
+ Action: billingPagePath(acct.Sqid) + "/change",
+ Fields: fields,
+ Button: billingCopy["confirm.button"],
+ CancelURL: billingPagePath(acct.Sqid),
+ }
+ s.render(w, http.StatusOK, "confirm_action", p)
+}
+
+// changeRefusalsLocked are the refusals a change needs no provider request
+// for: a retiring account, an open billing problem, a plan billing does not
+// own.
+func (s *Server) changeRefusalsLocked(h billingHold, acct *Account, now time.Time) error {
+ _ = h
+ if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil {
+ return err
+ } else if retiring {
+ return errBillingRetiring
+ }
+ if problems, err := s.store.OpenBillingProblemReasons(acct.ID); err != nil {
+ return err
+ } else if len(problems) > 0 {
+ return errCheckoutProblem
+ }
+ row, err := s.store.AccountPlan(acct.ID)
+ if err != nil {
+ return err
+ }
+ if row != nil && (row.Source == PlanSourceOperator || row.Source == PlanSourceSponsored) {
+ return errCheckoutOperator
+ }
+ return nil
+}
+
+// finishOutstandingLocked finishes the operation outstanding on the
+// account's recorded subscription, if any: one left sending or unresolved
+// gets finishOpLocked (a read, and at most one resend of its stored bytes); a
+// pending one gets a refresh, which settles it if the provider has paid or
+// dropped it. Still outstanding refuses (change.outstanding).
+func (s *Server) finishOutstandingLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) error {
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil || b == nil || b.Subscription == "" {
+ return err
+ }
+ op, err := s.store.OutstandingOp(b.Subscription)
+ if err != nil || op == nil {
+ return err
+ }
+ if op.State == opPending {
+ _, _, err = s.refreshLocked(h, ctx, acct, now)
+ } else {
+ _, err = s.finishOpLocked(h, ctx, acct, op, now)
+ }
+ if err != nil {
+ return err
+ }
+ if op, err = s.store.OutstandingOp(b.Subscription); err != nil {
+ return err
+ } else if op != nil {
+ return errChangeOutstanding
+ }
+ return nil
+}
+
+// changeLocked is a change under the account's billing hold.
+func (s *Server) changeLocked(h billingHold, ctx context.Context, acct *Account, ask changeAsk, now time.Time) (changeReply, error) {
+ if err := s.changeRefusalsLocked(h, acct, now); err != nil {
+ return changeReply{}, err
+ }
+ if err := s.finishOutstandingLocked(h, ctx, acct, now); err != nil {
+ return changeReply{}, err
+ }
+ b, sub, purchase, err := s.allowanceLocked(h, ctx, acct, now)
+ if err != nil {
+ return changeReply{}, err
+ }
+ if ask.Plan != "" {
+ return s.upgradeLocked(h, ctx, acct, sub, purchase, ask, now)
+ }
+ return s.packChangeLocked(h, ctx, acct, b, sub, purchase, ask, now)
+}
+
+// packChangeLocked is a pack change on the fresh allowance read.
+func (s *Server) packChangeLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, sub *billing.Subscription, purchase billing.Purchase, ask changeAsk, now time.Time) (changeReply, error) {
+ cat, prices := s.cfg.PlanCatalog, s.billing.cfg.Prices
+ if !slices.Contains(cat.Plans[purchase.Plan].Packs, ask.Pack) {
+ return changeReply{}, errChangeFailed
+ }
+ item, has := billing.FindItem(sub, prices, billing.KindPack, ask.Pack)
+ current, target, paid := int64(0), ask.Quantity, int64(b.PaidPacks[ask.Pack])
+ if has {
+ current = item.Quantity
+ }
+ if target == current {
+ return changeReply{}, errChangeNone
+ }
+ price := item.PriceID
+ if !has {
+ id, ok := prices.ID(billing.PriceRef{Book: purchase.Book, Kind: billing.KindPack, Name: ask.Pack, Currency: sub.Currency})
+ if !ok {
+ return changeReply{}, errChangeBook
+ }
+ price = id
+ }
+ // lineTo is the item change that sets the pack to q: the existing line,
+ // or a new one of the pack's price.
+ lineTo := func(it billing.Item, has bool, q int64) billing.ItemChange {
+ switch {
+ case has && q == 0:
+ return billing.ItemChange{ItemID: it.ItemID, Delete: true}
+ case has:
+ return billing.ItemChange{ItemID: it.ItemID, Quantity: q}
+ }
+ return billing.ItemChange{PriceID: price, Quantity: q}
+ }
+
+ if target < current {
+ out, _, err := s.sendChangeLocked(h, ctx, acct, sub, opPack, []billing.ItemChange{lineTo(item, has, target)},
+ map[string]int64{price: target}, current, billing.ProrateNone, now)
+ if err != nil {
+ return changeReply{}, err
+ }
+ return s.settleChangeLocked(h, ctx, acct, out, now), nil
+ }
+
+ restoreTo, chargeTo := quantityPlan(current, target, paid)
+ if restoreTo > 0 {
+ // Invariant 4, on the provider time of the allowance read: the whole
+ // request is refused inside the margin, before anything is written.
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return changeReply{}, errNoProviderTimeRefusal
+ }
+ if sub.PeriodEnd.Sub(pnow) <= restoreMargin {
+ return changeReply{}, errRestoreNearRenewal
+ }
+ }
+ if chargeTo > 0 && !ask.Confirmed {
+ q := changeQuote{Currency: sub.Currency}
+ if annual, ok := s.configuredPrice(purchase.Book, billing.KindPack, ask.Pack, sub.Currency); ok {
+ if pnow, err := s.providerNow(ctx); err == nil {
+ q.Estimate, q.Known = prorateEstimate(annual, chargeTo-max(current, paid), pnow, sub.PeriodEnd), true
+ }
+ }
+ return changeReply{Quote: &q}, nil
+ }
+
+ start := current
+ if restoreTo > 0 {
+ out, rsub, err := s.sendChangeLocked(h, ctx, acct, sub, opRestore, []billing.ItemChange{lineTo(item, has, restoreTo)},
+ map[string]int64{price: restoreTo}, current, billing.ProrateNone, now)
+ if err != nil {
+ return changeReply{}, err
+ }
+ if chargeTo == 0 {
+ return s.settleChangeLocked(h, ctx, acct, out, now), nil
+ }
+ // The charge is computed only from a definite restore applied in the
+ // same period, on the item its answer names.
+ if out.State != opApplied || rsub == nil {
+ return s.settleChangeLocked(h, ctx, acct, out, now), nil
+ }
+ if !rsub.PeriodEnd.Equal(sub.PeriodEnd) {
+ s.settleChangeLocked(h, ctx, acct, out, now)
+ return changeFlash("err", "change.retry"), nil
+ }
+ it, ok := itemOfPrice(rsub, price)
+ if !ok {
+ s.settleChangeLocked(h, ctx, acct, out, now)
+ return changeFlash("err", "change.uncertain"), nil
+ }
+ item, has, start, sub = it, true, it.Quantity, rsub
+ }
+ out, _, err := s.sendChangeLocked(h, ctx, acct, sub, opPack, []billing.ItemChange{lineTo(item, has, chargeTo)},
+ map[string]int64{price: chargeTo}, start, billing.ProrateNow, now)
+ if err != nil {
+ return changeReply{}, err
+ }
+ return s.settleChangeLocked(h, ctx, acct, out, now), nil
+}
+
+// upgradeLocked is a plan upgrade (Call 4) on the fresh allowance read: one
+// ProrateNow swap of the plan item's price, at the team's billed members or 1.
+func (s *Server) upgradeLocked(h billingHold, ctx context.Context, acct *Account, sub *billing.Subscription, purchase billing.Purchase, ask changeAsk, now time.Time) (changeReply, error) {
+ cat, prices, book := s.cfg.PlanCatalog, s.billing.cfg.Prices, s.billing.cfg.Book
+ if ask.Plan == purchase.Plan {
+ return changeReply{}, errChangeNone
+ }
+ // Higher in the configured book, and offering every pack held.
+ floor, okFrom := lowestTotal(cat, book, purchase.Plan, sub.Currency)
+ total, okTo := lowestTotal(cat, book, ask.Plan, sub.Currency)
+ if !okFrom || !okTo || total <= floor || !offersAll(cat.Plans[ask.Plan], heldPacks(purchase.Packs)) {
+ return changeReply{}, errChangeBook
+ }
+ // Priced from the subscription's own book.
+ price, ok := prices.ID(billing.PriceRef{Book: purchase.Book, Kind: billing.KindPlan, Name: ask.Plan, Currency: sub.Currency})
+ if !ok {
+ return changeReply{}, errChangeBook
+ }
+ item, ok := billing.FindItem(sub, prices, billing.KindPlan, purchase.Plan)
+ if !ok {
+ return changeReply{}, errAllowanceMismatch
+ }
+ qty := int64(1)
+ if t := cat.Plans[ask.Plan].Team; t != nil {
+ members, err := s.store.MemberCount(acct.ID)
+ if err != nil {
+ return changeReply{}, err
+ }
+ qty = int64(t.Billed(members))
+ }
+ if !ask.Confirmed {
+ q := changeQuote{Currency: sub.Currency}
+ newAnnual, okNew := s.configuredPrice(purchase.Book, billing.KindPlan, ask.Plan, sub.Currency)
+ oldAnnual, okOld := s.configuredPrice(purchase.Book, billing.KindPlan, purchase.Plan, sub.Currency)
+ if diff := newAnnual*qty - oldAnnual*item.Quantity; okNew && okOld && diff > 0 {
+ if pnow, err := s.providerNow(ctx); err == nil {
+ q.Estimate, q.Known = prorateEstimate(diff, 1, pnow, sub.PeriodEnd), true
+ }
+ }
+ return changeReply{Quote: &q}, nil
+ }
+ out, _, err := s.sendChangeLocked(h, ctx, acct, sub, opPlan,
+ []billing.ItemChange{{ItemID: item.ItemID, PriceID: price, Quantity: qty}},
+ map[string]int64{price: qty, item.PriceID: 0}, item.Quantity, billing.ProrateNow, now)
+ if err != nil {
+ return changeReply{}, err
+ }
+ return s.settleChangeLocked(h, ctx, acct, out, now), nil
+}
+
+// configuredPrice is a yearly price from the configured book, known only when
+// the subscription is on that book: the console holds no earlier book's
+// amounts, so a quote for one has no estimate.
+func (s *Server) configuredPrice(subscriptionBook, kind, name, currency string) (int64, bool) {
+ book := s.billing.cfg.Book
+ if subscriptionBook != book.Version {
+ return 0, false
+ }
+ if kind == billing.KindPlan {
+ return book.PlanPrice(name, currency)
+ }
+ return book.PackPrice(name, currency)
+}
+
+// itemOfPrice is the subscription's line of price.
+func itemOfPrice(sub *billing.Subscription, price string) (billing.Item, bool) {
+ for _, it := range sub.Items {
+ if it.PriceID == price {
+ return it, true
+ }
+ }
+ return billing.Item{}, false
+}
+
+// sendChangeLocked prepares one subscription change, its proration
+// timestamp the request's provider time captured once into the Prepared, and
+// sends it through sendOpLocked. target is what a read must show (price to
+// quantity, 0 for gone); start is the changed item's quantity in the read the
+// change was computed from.
+func (s *Server) sendChangeLocked(h billingHold, ctx context.Context, acct *Account, sub *billing.Subscription, kind string,
+ items []billing.ItemChange, target map[string]int64, start int64, proration billing.Proration, now time.Time) (opOutcome, *billing.Subscription, error) {
+ pnow, err := s.providerNow(ctx)
+ if err != nil {
+ return opOutcome{}, nil, errNoProviderTimeRefusal
+ }
+ id := newOpID()
+ p, err := s.billing.cfg.Provider.PrepareChange(billing.ChangeRequest{Subscription: sub.ID, Items: items,
+ Proration: proration, ProrationDate: pnow, IdempotencyKey: "op:" + id})
+ if err != nil {
+ return opOutcome{}, nil, err
+ }
+ op := billingOp{ID: id, AccountID: acct.ID, Subscription: sub.ID, Kind: kind, PeriodEnd: sub.PeriodEnd,
+ Target: opTarget{Quantities: target}, Prepared: p, StartQuantity: knownStart(start)}
+ return s.sendOpLocked(h, ctx, op, now)
+}
+
+// settleChangeLocked refreshes the subscription after the last send, so
+// the page shows what the provider holds, and answers the outcome's flash. A
+// failed refresh only defers that to the next read: the outcome is recorded.
+func (s *Server) settleChangeLocked(h billingHold, ctx context.Context, acct *Account, out opOutcome, now time.Time) changeReply {
+ if _, _, err := s.refreshLocked(h, ctx, acct, now); err != nil {
+ log.Printf("console: billing change %s: refresh after the change: %v", acct.Sqid, err)
+ }
+ kind, key := outcomeCopy(out)
+ return changeFlash(kind, key)
+}
+
+// ---- renewal --------------------------------------------------------------
+
+// handleBillingRenewal is POST /a/{sqid}/billing/renewal with
+// renewal=stop|resume: an owner stops or resumes renewal. No sign-in proof:
+// it charges nothing (Call 6). Billing off answers 404, a member 404, no CSRF
+// 403.
+func (s *Server) handleBillingRenewal(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)
+ v := r.PostFormValue("renewal")
+ if !s.billing.ready.Load() || (v != "stop" && v != "resume") {
+ s.setFlash(w, "err", billingCopy["change.failed"])
+ http.Redirect(w, r, back, http.StatusSeeOther)
+ return
+ }
+ ctx := s.billingClock(r.Context())
+ now := time.Now()
+ h, release := s.holdBilling(acct.Sqid)
+ reply, err := s.renewalLocked(h, ctx, acct, v == "resume", now)
+ release()
+ if err != nil {
+ reply = changeReply{Kind: "err", Text: changeText(acct.Sqid, err)}
+ }
+ s.setFlash(w, reply.Kind, reply.Text)
+ http.Redirect(w, r, back, http.StatusSeeOther)
+}
+
+// renewalText is the flash for renewal set as asked.
+func renewalText(renew bool, periodEnd time.Time) changeReply {
+ if renew {
+ return changeFlash("ok", "renewal.resumed")
+ }
+ return changeReply{Kind: "ok", Text: fmt.Sprintf(billingCopy["renewal.stopped"], billingDate(periodEnd))}
+}
+
+// renewalLocked is stopping (renew false) or resuming renewal under the
+// hold: refused while retiring; an outstanding operation is finished first;
+// then a refresh, and one renewal operation unless the subscription is
+// already as asked; then the subscription is refreshed again.
+func (s *Server) renewalLocked(h billingHold, ctx context.Context, acct *Account, renew bool, now time.Time) (changeReply, error) {
+ if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil {
+ return changeReply{}, err
+ } else if retiring {
+ return changeReply{}, errBillingRetiring
+ }
+ if err := s.finishOutstandingLocked(h, ctx, acct, now); err != nil {
+ return changeReply{}, err
+ }
+ _, sub, err := s.refreshLocked(h, ctx, acct, now)
+ if err != nil {
+ return changeReply{}, err
+ }
+ if sub == nil || !sub.Live {
+ return changeReply{}, errChangeFailed
+ }
+ if sub.CancelAtPeriodEnd == !renew {
+ return renewalText(renew, sub.PeriodEnd), nil
+ }
+ id := newOpID()
+ p, err := s.billing.cfg.Provider.PrepareRenewal(sub.ID, renew, "op:"+id)
+ if err != nil {
+ return changeReply{}, err
+ }
+ op := billingOp{ID: id, AccountID: acct.ID, Subscription: sub.ID, Kind: opRenewal, PeriodEnd: sub.PeriodEnd,
+ Target: opTarget{Renewal: true, CancelAtPeriodEnd: !renew}, Prepared: p}
+ out, _, err := s.sendOpLocked(h, ctx, op, now)
+ if err != nil {
+ return changeReply{}, err
+ }
+ reply := s.settleChangeLocked(h, ctx, acct, out, now)
+ switch out.State {
+ case opApplied:
+ return renewalText(renew, sub.PeriodEnd), nil
+ case opFailed:
+ return changeFlash("err", "change.failed"), nil
+ }
+ return reply, nil
+}
diff --git a/internal/console/billingchange_test.go b/internal/console/billingchange_test.go
new file mode 100644
index 000000000..c8c063a49
--- /dev/null
+++ b/internal/console/billingchange_test.go
@@ -0,0 +1,916 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "html"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/billing/billingtest"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// ---- fixture -----------------------------------------------------------------
+
+// newChangeFixture is an ops fixture (a synced Personal subscription with
+// packs) whose owner is signed in with no fresh step-up proof, counters
+// reset.
+func newChangeFixture(t *testing.T, packs map[string]int64) *opsFixture {
+ t.Helper()
+ o := newOpsFixture(t, packs)
+ o.signInOwner(t)
+ if err := o.st.ClearStepUp(o.csrf); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ return o
+}
+
+// stepUp records a fresh sign-in proof for the owner's session.
+func (o *opsFixture) stepUp(t *testing.T) {
+ t.Helper()
+ if err := o.st.RecordStepUp(o.csrf, "owner"+o.acct.Sqid+"@example.com", time.Now(), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func (o *opsFixture) change(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()+"/change", form)
+}
+
+func (o *opsFixture) renewal(t *testing.T, v string) billingReply {
+ t.Helper()
+ return o.request(t, http.MethodPost, o.billingBase()+"/renewal", url.Values{"renewal": {v}})
+}
+
+// wantFlash is a redirect back to the billing page with the copy text.
+func (o *opsFixture) wantFlash(t *testing.T, r billingReply, kind, text string) {
+ t.Helper()
+ if r.Status != http.StatusSeeOther || r.Loc != o.billingBase() || r.Flash != kind || r.FlashMsg != text {
+ t.Fatalf("reply = %d %q flash %s:%q, want %s:%q", r.Status, r.Loc, r.Flash, r.FlashMsg, kind, text)
+ }
+}
+
+// wantQuote is the confirm page for a charge, showing line.
+func wantQuote(t *testing.T, r billingReply, line string) {
+ t.Helper()
+ if r.Status != http.StatusOK || !strings.Contains(r.Body, html.EscapeString(billingCopy["confirm.title"])) ||
+ !strings.Contains(r.Body, html.EscapeString(line)) || !strings.Contains(r.Body, html.EscapeString(billingCopy["confirm.button"])) {
+ t.Fatalf("reply = %d %q flash %s:%q, want the confirm page with %q\n%s", r.Status, r.Loc, r.Flash, r.FlashMsg, line, r.Body)
+ }
+ if !strings.Contains(r.Body, `name="confirmed" value="1"`) {
+ t.Fatal("the confirm page does not post confirmed=1")
+ }
+}
+
+func quoteLine(currency string, minor int64) string {
+ return fmt.Sprintf(billingCopy["confirm.line"], plans.FormatMinor(currency, minor))
+}
+
+// ops is every operation the account has, oldest first.
+func (o *opsFixture) ops(t *testing.T) []billingOp {
+ t.Helper()
+ rows, err := o.st.db.Query(`SELECT id FROM billing_operations WHERE account_id = ? ORDER BY created_at, rowid`, o.acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ids []string
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ t.Fatal(err)
+ }
+ ids = append(ids, id)
+ }
+ rows.Close()
+ var out []billingOp
+ for _, id := range ids {
+ out = append(out, *o.op(t, id))
+ }
+ return out
+}
+
+func (o *opsFixture) lastOp(t *testing.T) billingOp {
+ t.Helper()
+ all := o.ops(t)
+ if len(all) == 0 {
+ t.Fatal("no operation")
+ }
+ return all[len(all)-1]
+}
+
+// fakeChangeBody is the Fake's encoding of a subscription change.
+type fakeChangeBody struct {
+ Subscription string `json:"subscription"`
+ Items []billing.ItemChange `json:"items"`
+ Proration billing.Proration `json:"proration"`
+ ProrationDate int64 `json:"proration_date"`
+}
+
+func changeBodyOf(t *testing.T, p billing.Prepared) fakeChangeBody {
+ t.Helper()
+ var b fakeChangeBody
+ if err := json.Unmarshal(p.Body, &b); err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+func appsPrice() string { return testPriceID("example-v1/pack/apps/usd") }
+
+func (o *opsFixture) planRow(t *testing.T) *AccountPlanRow {
+ t.Helper()
+ row, err := o.st.AccountPlan(o.acct.ID)
+ if err != nil || row == nil {
+ t.Fatalf("plan row: %+v %v", row, err)
+ }
+ return row
+}
+
+func (o *opsFixture) invoices(reason string) int {
+ o.fake.Lock()
+ defer o.fake.Unlock()
+ n := 0
+ for _, inv := range o.fake.Invoices {
+ if inv.Reason == reason {
+ n++
+ }
+ }
+ return n
+}
+
+// ---- the estimate --------------------------------------------------------------
+
+func TestPackEstimateRoundsUp(t *testing.T) {
+ end := time.Date(2027, 10, 25, 0, 0, 0, 0, time.UTC)
+ for _, c := range []struct {
+ annual, qty int64
+ now time.Time
+ want int64
+ }{
+ {1200, 1, end.AddDate(-1, 0, 0), 1200}, // a whole year left
+ {1200, 2, end.Add(-365 * 24 * time.Hour / 2), 1204}, // half a year (182.5 days: 183) of two
+ {1200, 1, end.Add(-24 * time.Hour), 4}, // one day: 3.28, rounded up
+ {1200, 1, end.Add(-time.Minute), 4}, // part of a day counts as a day
+ {1200, 1, end, 0},
+ {1200, 1, end.Add(time.Hour), 0},
+ {1200, 1, end.AddDate(-2, 0, 0), 1200}, // never more than a year
+ {0, 3, end.AddDate(0, -1, 0), 0},
+ } {
+ if got := prorateEstimate(c.annual, c.qty, c.now, end); got != c.want {
+ t.Errorf("prorateEstimate(%d, %d, %v) = %d, want %d", c.annual, c.qty, end.Sub(c.now), got, c.want)
+ }
+ }
+}
+
+// ---- pack changes ---------------------------------------------------------------
+
+func TestPackRaiseCharges(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ item := o.packItem(t, "sub_1", "apps")
+
+ // Unconfirmed: the confirm page with the local estimate for two packs,
+ // one read and nothing written.
+ r := o.change(t, "pack", "apps", "quantity", "3")
+ wantQuote(t, r, quoteLine("usd", prorateEstimate(1200, 2, o.providerClock(), periodEnd)))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if len(o.ops(t)) != 0 {
+ t.Fatal("the confirm page wrote an operation")
+ }
+
+ // Confirmed without a fresh sign-in proof: the step-up gate, nothing read
+ // or sent.
+ o.reset()
+ r = o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1")
+ if r.Status != http.StatusSeeOther || strings.HasPrefix(r.Loc, o.billingBase()) {
+ t.Fatalf("confirmed without step-up = %d %q, want the step-up redirect", r.Status, r.Loc)
+ }
+ wantCounts(t, o.counts(), map[string]int{})
+
+ // Confirmed with one: S + (1) + S.
+ o.stepUp(t)
+ o.reset()
+ r = o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1")
+ o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ if op.Kind != opPack || op.State != opApplied || op.StartQuantity == nil || *op.StartQuantity != 1 ||
+ op.Target.Quantities[appsPrice()] != 3 || !op.PeriodEnd.Equal(periodEnd) || op.Prepared.Key != "op:"+op.ID {
+ t.Fatalf("op = %+v", op)
+ }
+ body := changeBodyOf(t, op.Prepared)
+ if body.Proration != billing.ProrateNow || body.ProrationDate != o.providerClock().Unix() ||
+ len(body.Items) != 1 || body.Items[0].ItemID != item.ItemID || body.Items[0].Quantity != 3 || body.Items[0].PriceID != "" {
+ t.Fatalf("prepared change = %+v", body)
+ }
+ if row := o.planRow(t); row.Packs["apps"] != 3 || row.Source != PlanSourceBilling {
+ t.Fatalf("plan row = %+v", row)
+ }
+ if o.invoices(billingtest.ReasonUpdate) != 1 {
+ t.Fatalf("proration invoices = %d, want 1", o.invoices(billingtest.ReasonUpdate))
+ }
+}
+
+func TestPackReduceAndBuyBack(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 3})
+
+ // A reduction needs no confirmation and no step-up: it charges nothing,
+ // and the paid limits stay until renewal.
+ r := o.change(t, "pack", "apps", "quantity", "1")
+ o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ if body := changeBodyOf(t, op.Prepared); op.Kind != opPack || body.Proration != billing.ProrateNone || body.Items[0].Quantity != 1 ||
+ op.StartQuantity == nil || *op.StartQuantity != 3 {
+ t.Fatalf("reduction op = %+v body %+v", op, body)
+ }
+ if o.packItem(t, "sub_1", "apps").Quantity != 1 || o.planRow(t).Packs["apps"] != 3 {
+ t.Fatalf("after the reduction: item %d, plan row %+v", o.packItem(t, "sub_1", "apps").Quantity, o.planRow(t))
+ }
+
+ // Buying back up to the paid count is a free restore: no confirm page, no
+ // step-up, one write.
+ o.reset()
+ r = o.change(t, "pack", "apps", "quantity", "3")
+ o.wantFlash(t, r, "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op = o.lastOp(t)
+ if body := changeBodyOf(t, op.Prepared); op.Kind != opRestore || op.State != opApplied || body.Proration != billing.ProrateNone ||
+ body.Items[0].Quantity != 3 || *op.StartQuantity != 1 {
+ t.Fatalf("restore op = %+v body %+v", op, body)
+ }
+ if c, err := o.st.RestoreCheck(op.ID); err != nil || c == nil || c.State != restoreClear {
+ t.Fatalf("restore obligation = %+v %v, want clear", c, err)
+ }
+ if o.invoices(billingtest.ReasonUpdate) != 0 {
+ t.Fatal("a reduction or restore was charged")
+ }
+
+ // The same quantity again is no step at all.
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3"), "err", billingCopy["change.none"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+}
+
+func TestDeletedPackRestoreThenCharge(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 3})
+ old := o.packItem(t, "sub_1", "apps")
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "0"), "ok", billingCopy["change.done"])
+ if body := changeBodyOf(t, o.lastOp(t).Prepared); len(body.Items) != 1 || !body.Items[0].Delete || body.Items[0].ItemID != old.ItemID {
+ t.Fatalf("a reduction to 0 = %+v, want the item deleted", body)
+ }
+ for _, it := range o.sub("sub_1").Items {
+ if it.PriceID == appsPrice() {
+ t.Fatal("the apps item is still on the subscription")
+ }
+ }
+
+ // Unconfirmed: the estimate covers the one charged pack.
+ o.reset()
+ wantQuote(t, o.change(t, "pack", "apps", "quantity", "4"), quoteLine("usd", prorateEstimate(1200, 1, o.providerClock(), periodEnd)))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+
+ // Confirmed: restore 3 as a new item, then charge the item the restore's
+ // answer names up to 4. S + (1) + (1) + S.
+ o.stepUp(t)
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "4", "confirmed", "1"), "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 2})
+ all := o.ops(t)
+ if len(all) != 3 {
+ t.Fatalf("ops = %d, want the reduction, the restore and the charge", len(all))
+ }
+ restore, charge := all[1], all[2]
+ now := o.packItem(t, "sub_1", "apps")
+ rb, cb := changeBodyOf(t, restore.Prepared), changeBodyOf(t, charge.Prepared)
+ if restore.Kind != opRestore || restore.State != opApplied || rb.Proration != billing.ProrateNone ||
+ rb.Items[0].ItemID != "" || rb.Items[0].PriceID != appsPrice() || rb.Items[0].Quantity != 3 || *restore.StartQuantity != 0 {
+ t.Fatalf("restore = %+v body %+v", restore, rb)
+ }
+ if charge.Kind != opPack || charge.State != opApplied || cb.Proration != billing.ProrateNow ||
+ cb.Items[0].ItemID != now.ItemID || now.ItemID == old.ItemID || cb.Items[0].Quantity != 4 || *charge.StartQuantity != 3 {
+ t.Fatalf("charge = %+v body %+v (item now %s)", charge, cb, now.ItemID)
+ }
+ if now.Quantity != 4 || o.planRow(t).Packs["apps"] != 4 {
+ t.Fatalf("item %+v, plan row %+v", now, o.planRow(t))
+ }
+
+ // A restore with no definite outcome is never followed by a charge.
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "0"), "ok", billingCopy["change.done"])
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = 100
+ o.fake.Unlock()
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "5", "confirmed", "1"), "err", billingCopy["change.uncertain"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 5, "Send": 4})
+ if op := o.lastOp(t); op.Kind != opRestore || op.State != opUnresolved {
+ t.Fatalf("last op = %+v, want the unresolved restore and no charge", op)
+ }
+}
+
+func TestRestoreRefusedNearRenewal(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 3})
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "1"), "ok", billingCopy["change.done"])
+ before := len(o.ops(t))
+ o.stepUp(t)
+
+ for _, left := range []time.Duration{24 * time.Hour, restoreMargin} {
+ o.fake.SetProviderClock(periodEnd.Add(-left))
+ // A restore alone, and a restore with a charge: the whole request is
+ // refused before any write.
+ for _, q := range []string{"3", "4"} {
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", q, "confirmed", "1"), "err", billingCopy["change.near_renewal"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ }
+ // Unconfirmed, the handler refuses rather than quoting a charge it
+ // could not make.
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "4"), "err", billingCopy["change.near_renewal"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ }
+ // A charge that needs no restore is not refused: inside the margin it is
+ // an ordinary charged add.
+ o.reset()
+ wantQuote(t, o.change(t, "pack", "email", "quantity", "1"), quoteLine("usd", prorateEstimate(2400, 1, o.providerClock(), periodEnd)))
+
+ // No provider time at all: change.clock, nothing written.
+ o.fake.SetProviderClock(periodEnd.AddDate(0, -6, 0))
+ o.headerlessReads(false)
+ o.fake.Lock()
+ o.fake.ProbeErr = errors.New("probe down")
+ o.fake.Unlock()
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3"), "err", billingCopy["change.clock"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1, "ClockProbe": 1})
+ if len(o.ops(t)) != before {
+ t.Fatal("a refused restore wrote an operation")
+ }
+}
+
+func TestRestoreIgnoresConsoleClock(t *testing.T) {
+ // The renewal is three days ahead of the console's own clock, but the
+ // provider's clock is two days ahead of the console's: provider time
+ // says one day is left, so the restore is refused.
+ o := newChangeFixture(t, nil)
+ pe := time.Now().UTC().Truncate(time.Second).Add(72 * time.Hour)
+ s := o.personalSub("sub_1", "active", map[string]int64{"apps": 3})
+ s.PeriodEnd = pe
+ o.put(s)
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "1"), "ok", billingCopy["change.done"])
+ o.fake.SetProviderClock(pe.Add(-24 * time.Hour))
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3"), "err", billingCopy["change.near_renewal"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+
+ // And the other way: the console's clock a day before the renewal, the
+ // provider's three days before it: allowed.
+ pe2 := time.Now().UTC().Truncate(time.Second).Add(24 * time.Hour)
+ s = o.sub("sub_1")
+ s.PeriodEnd = pe2
+ o.put(s)
+ o.fake.SetProviderClock(pe2.Add(-72 * time.Hour))
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "0"), "ok", billingCopy["change.done"])
+ b, _ := o.st.BillingAccount(o.acct.ID)
+ b.PaidPacks = map[string]int{"apps": 3} // the new period's paid count, as if bought this period
+ if err := o.st.PutBillingState(*b); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2"), "ok", billingCopy["change.done"])
+ if op := o.lastOp(t); op.Kind != opRestore || op.State != opApplied {
+ t.Fatalf("restore = %+v", op)
+ }
+}
+
+func TestRestoreResendWindowEndsBeforeRenewal(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 3})
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "1"), "ok", billingCopy["change.done"])
+ // One second outside the margin: the first send is allowed. Its delivery
+ // is lost, and the handler's backoff is real time passing, so by the
+ // retry's read the restore is inside the margin and is not resent.
+ o.fake.SetProviderClock(periodEnd.Add(-restoreMargin - time.Second))
+ o.srv.billing.wait = func(_ context.Context, d time.Duration) { o.fake.Elapse(d) }
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = 1
+ o.fake.Unlock()
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3"), "err", billingCopy["change.uncertain"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 1})
+ op := o.lastOp(t)
+ if op.Kind != opRestore || op.State != opUnresolved {
+ t.Fatalf("restore = %+v", op)
+ }
+ // Confirm now does not resend it either.
+ o.reset()
+ if status, _ := o.confirm(t); status != http.StatusSeeOther {
+ t.Fatalf("confirm = %d", status)
+ }
+ if n := o.counts()["Send"]; n != 0 {
+ t.Fatalf("Confirm now resent the restore inside the margin: %d sends", n)
+ }
+}
+
+func TestOneOutstandingOperation(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ // A charge answered with a cached 500: indeterminate, never resent.
+ o.fake.Lock()
+ o.fake.Cached500Before = true
+ o.fake.Unlock()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "err", billingCopy["change.uncertain"])
+ if op := o.lastOp(t); op.State != opUnresolved || !op.Indeterminate {
+ t.Fatalf("op = %+v", op)
+ }
+
+ // Every later change on the subscription is refused after F (one read,
+ // no resend), and nothing new is written.
+ for _, form := range [][]string{
+ {"pack", "apps", "quantity", "0"},
+ {"pack", "email", "quantity", "1", "confirmed", "1"},
+ {"plan", "community", "confirmed", "1"},
+ } {
+ o.reset()
+ o.wantFlash(t, o.change(t, form...), "err", billingCopy["change.outstanding"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ }
+ o.reset()
+ o.wantFlash(t, o.renewal(t, "stop"), "err", billingCopy["change.outstanding"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if n := len(o.ops(t)); n != 1 {
+ t.Fatalf("ops = %d, want 1", n)
+ }
+}
+
+func TestRetryAfterDeclineIsRefusedUntilSettled(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+
+ // A soft decline leaves a pending update: the change waits for payment.
+ o.fake.Lock()
+ o.fake.FailPayment = 1
+ o.fake.Unlock()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "err", billingCopy["change.pending"])
+ first := o.lastOp(t)
+ if first.State != opPending {
+ t.Fatalf("op = %+v", first)
+ }
+ // Retrying while it waits is refused after one read.
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "err", billingCopy["change.outstanding"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+
+ // Once the provider drops the pending update, the next request settles it
+ // (abandoned) and charges afresh.
+ if err := o.fake.ExpirePending("sub_1"); err != nil {
+ t.Fatal(err)
+ }
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 1})
+ if got := o.op(t, first.ID); got.State != opAbandoned {
+ t.Fatalf("first op = %+v, want abandoned", got)
+ }
+
+ // A hard decline is terminal: the retry is a new operation at once.
+ o.fake.Lock()
+ o.fake.DeclineHard = 1
+ o.fake.Unlock()
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "err", billingCopy["change.declined"])
+ if op := o.lastOp(t); op.State != opFailed {
+ t.Fatalf("declined op = %+v", op)
+ }
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+}
+
+func TestChangeTwiceChargesOnce(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ // The double submit: the fresh read shows 3, so there is no step.
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "err", billingCopy["change.none"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+
+ // A first submit whose answer was lost after the provider applied it: the
+ // second finds it applied and charges nothing more.
+ op := o.packOp(t, "op_lost", "sub_1", "apps", 5, billing.ProrateNow, opPack)
+ o.unresolved(t, op)
+ o.setQuantity("sub_1", appsPrice(), 5)
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "5", "confirmed", "1"), "err", billingCopy["change.none"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2})
+ if got := o.op(t, "op_lost"); got.State != opApplied {
+ t.Fatalf("lost op = %+v, want applied", got)
+ }
+ if n := o.invoices(billingtest.ReasonUpdate); n != 1 {
+ t.Fatalf("proration invoices = %d, want 1", n)
+ }
+}
+
+func TestChangeComputesFromTheFreshRead(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ // The provider moved the quantity since the console last read it.
+ o.setQuantity("sub_1", appsPrice(), 3)
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "4", "confirmed", "1"), "ok", billingCopy["change.done"])
+ op := o.lastOp(t)
+ if body := changeBodyOf(t, op.Prepared); op.Kind != opPack || *op.StartQuantity != 3 || body.Proration != billing.ProrateNow || body.Items[0].Quantity != 4 {
+ t.Fatalf("charge = %+v body %+v", op, body)
+ }
+ // The estimate is from the fresh read too: one pack, not three.
+ o.setQuantity("sub_1", appsPrice(), 6)
+ o.reset()
+ wantQuote(t, o.change(t, "pack", "apps", "quantity", "7"), quoteLine("usd", prorateEstimate(1200, 1, o.providerClock(), periodEnd)))
+ // A reduction from the fresh read.
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "5"), "ok", billingCopy["change.done"])
+ if op := o.lastOp(t); op.Kind != opPack || *op.StartQuantity != 6 || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNone {
+ t.Fatalf("reduction = %+v", op)
+ }
+}
+
+func TestChangeAfterDelayedRenewal(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 3})
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "1"), "ok", billingCopy["change.done"])
+ // The subscription renews at 1; the console has not seen it.
+ if err := o.fake.Renew("sub_1"); err != nil {
+ t.Fatal(err)
+ }
+ o.stepUp(t)
+ o.reset()
+ // Last period's paid 3 is gone: back to 3 is a charge, not a restore.
+ wantQuote(t, o.change(t, "pack", "apps", "quantity", "3"), quoteLine("usd", prorateEstimate(1200, 2, o.providerClock(), periodEnd.AddDate(1, 0, 0))))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ if op.Kind != opPack || *op.StartQuantity != 1 || !op.PeriodEnd.Equal(periodEnd.AddDate(1, 0, 0)) || changeBodyOf(t, op.Prepared).Proration != billing.ProrateNow {
+ t.Fatalf("charge = %+v", op)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); !b.PaidPeriodEnd.Equal(periodEnd.AddDate(1, 0, 0)) || b.PaidPacks["apps"] != 3 {
+ t.Fatalf("billing row = %+v", b)
+ }
+}
+
+func TestChangeAfterReplacementSubscription(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 3})
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "1"), "ok", billingCopy["change.done"])
+ // sub_1 ends; a new subscription replaces it.
+ o.put(o.personalSub("sub_1", "canceled", map[string]int64{"apps": 1}))
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.put(o.personalSub("sub_2", "active", map[string]int64{"apps": 1}))
+ if err := o.srv.syncSubscription(context.Background(), "sub_2", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Subscription != "sub_2" {
+ t.Fatalf("billing row = %+v", b)
+ }
+ o.stepUp(t)
+ o.reset()
+ // The old subscription's paid 3 does not carry: a charge on sub_2.
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ if op.Subscription != "sub_2" || op.Kind != opPack || *op.StartQuantity != 1 || changeBodyOf(t, op.Prepared).Subscription != "sub_2" {
+ t.Fatalf("charge = %+v", op)
+ }
+}
+
+func TestChangeUnresolvedFinishedOnNextRequest(t *testing.T) {
+ t.Run("applied while unanswered", func(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ op := o.packOp(t, "op_prior", "sub_1", "apps", 2, billing.ProrateNow, opPack)
+ o.unresolved(t, op)
+ o.setQuantity("sub_1", appsPrice(), 2)
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ // F (one read, no resend), then S + (1) + S.
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 1})
+ if got := o.op(t, "op_prior"); got.State != opApplied {
+ t.Fatalf("prior = %+v", got)
+ }
+ if next := o.lastOp(t); next.ID == "op_prior" || *next.StartQuantity != 2 || next.Target.Quantities[appsPrice()] != 3 {
+ t.Fatalf("next = %+v", next)
+ }
+ })
+ t.Run("resent from its stored bytes", func(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ op := o.packOp(t, "op_prior", "sub_1", "apps", 2, billing.ProrateNow, opPack)
+ o.unresolved(t, op)
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1"), "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 3, "Send": 2})
+ sent := o.sent()
+ if sent[0].Key != op.Prepared.Key || string(sent[0].Body) != string(op.Prepared.Body) {
+ t.Fatalf("first send = %+v, want the stored bytes", sent[0])
+ }
+ if got := o.op(t, "op_prior"); got.State != opApplied {
+ t.Fatalf("prior = %+v", got)
+ }
+ if o.packItem(t, "sub_1", "apps").Quantity != 3 {
+ t.Fatal("the new change did not apply")
+ }
+ })
+}
+
+// ---- plan upgrades -----------------------------------------------------------------
+
+func TestPlanUpgrade(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ members, err := o.st.MemberCount(o.acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ seats := int64(o.srv.cfg.PlanCatalog.Plans["community"].Team.Billed(members))
+ planItem, ok := billing.FindItem(o.sub("sub_1"), o.srv.billing.cfg.Prices, billing.KindPlan, "")
+ if !ok || planItem.ItemID == "" {
+ t.Fatalf("plan item = %+v", planItem)
+ }
+
+ wantQuote(t, o.change(t, "plan", "community"), quoteLine("usd", prorateEstimate(600*seats-2800, 1, o.providerClock(), periodEnd)))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+
+ o.stepUp(t)
+ o.reset()
+ o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "ok", billingCopy["change.done"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ body := changeBodyOf(t, op.Prepared)
+ community, personal := testPriceID("example-v1/community/usd"), testPriceID("example-v1/personal/usd")
+ if op.Kind != opPlan || op.State != opApplied || body.Proration != billing.ProrateNow || len(body.Items) != 1 ||
+ body.Items[0].ItemID != planItem.ItemID || body.Items[0].PriceID != community || body.Items[0].Quantity != seats ||
+ *op.StartQuantity != 1 || op.Target.Quantities[community] != seats || op.Target.Quantities[personal] != 0 || len(op.Target.Quantities) != 2 {
+ t.Fatalf("upgrade = %+v body %+v", op, body)
+ }
+ if row := o.planRow(t); row.Plan != "community" || row.Packs["apps"] != 1 {
+ t.Fatalf("plan row = %+v", row)
+ }
+
+ // The same plan is no step; a lower one is not self-serve.
+ o.reset()
+ o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "err", billingCopy["change.none"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ o.reset()
+ o.wantFlash(t, o.change(t, "plan", "personal", "confirmed", "1"), "err", billingCopy["change.book"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+}
+
+func TestUpgradeRefusedWhenPackNotOffered(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"email": 1})
+ cat := o.srv.cfg.PlanCatalog
+ business := cat.Plans["business"]
+ business.Packs = []string{"apps", "disk", "storage", "bandwidth"}
+ cat.Plans["business"] = business
+ o.stepUp(t)
+ o.reset()
+ o.wantFlash(t, o.change(t, "plan", "business", "confirmed", "1"), "err", billingCopy["change.book"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ if o.fake.Writes() != 0 {
+ t.Fatal("a refused upgrade wrote")
+ }
+ // A plan that offers it is fine.
+ o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "ok", billingCopy["change.done"])
+}
+
+// subscriptionsBookPrices is the example price map plus an earlier book,
+// example-v0, that priced Personal, Community and the apps pack in usd only.
+func subscriptionsBookPrices(t *testing.T, book *plans.PriceBook) billing.PriceMap {
+ t.Helper()
+ raw := map[string]string{}
+ for name := range book.Plans {
+ for _, c := range book.Currencies {
+ k := billing.PriceRef{Book: book.Version, Kind: billing.KindPlan, Name: name, Currency: c}.Key()
+ raw[k] = testPriceID(k)
+ }
+ }
+ for name := range book.Packs {
+ for _, c := range book.Currencies {
+ k := billing.PriceRef{Book: book.Version, Kind: billing.KindPack, Name: name, Currency: c}.Key()
+ raw[k] = testPriceID(k)
+ }
+ }
+ for _, k := range []string{"example-v0/personal/usd", "example-v0/community/usd", "example-v0/pack/apps/usd"} {
+ raw[k] = testPriceID(k)
+ }
+ b, _ := json.Marshal(raw)
+ m, err := billing.ParsePriceMap(string(b), book)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return m
+}
+
+func TestChangeUsesTheSubscriptionsBook(t *testing.T) {
+ o := newChangeFixture(t, nil)
+ o.srv.billing.cfg.Prices = subscriptionsBookPrices(t, o.srv.billing.cfg.Book)
+ s := o.personalSub("sub_1", "active", nil)
+ s.Items = []billing.Item{
+ {PriceID: testPriceID("example-v0/personal/usd"), Quantity: 1, Currency: "usd"},
+ {PriceID: testPriceID("example-v0/pack/apps/usd"), Quantity: 1, Currency: "usd"},
+ }
+ o.put(s)
+ if err := o.srv.syncSubscription(context.Background(), "sub_1", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); b.Book != "example-v0" {
+ t.Fatalf("billing row = %+v", b)
+ }
+ o.stepUp(t)
+ o.reset()
+
+ // The earlier book's amounts are not known here: no estimate.
+ wantQuote(t, o.change(t, "pack", "apps", "quantity", "2"), billingCopy["change.no_estimate"])
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "2", "confirmed", "1"), "ok", billingCopy["change.done"])
+ if op := o.lastOp(t); op.Target.Quantities[testPriceID("example-v0/pack/apps/usd")] != 2 {
+ t.Fatalf("pack change = %+v", op)
+ }
+ // A pack the earlier book never priced is not available.
+ o.reset()
+ o.wantFlash(t, o.change(t, "pack", "email", "quantity", "1", "confirmed", "1"), "err", billingCopy["change.book"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+ // An upgrade is priced from the subscription's book.
+ o.wantFlash(t, o.change(t, "plan", "community", "confirmed", "1"), "ok", billingCopy["change.done"])
+ if body := changeBodyOf(t, o.lastOp(t).Prepared); body.Items[0].PriceID != testPriceID("example-v0/community/usd") {
+ t.Fatalf("upgrade = %+v", body)
+ }
+ // One the earlier book never priced is not.
+ o.reset()
+ o.wantFlash(t, o.change(t, "plan", "business", "confirmed", "1"), "err", billingCopy["change.book"])
+ if o.counts()["Send"] != 0 {
+ t.Fatal("an unpriced upgrade was sent")
+ }
+}
+
+// ---- renewal --------------------------------------------------------------------------
+
+func TestRenewalStopAndResume(t *testing.T) {
+ o := newChangeFixture(t, nil)
+ // No step-up is needed, and stopping makes one write.
+ r := o.renewal(t, "stop")
+ o.wantFlash(t, r, "ok", fmt.Sprintf(billingCopy["renewal.stopped"], billingDate(periodEnd)))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ op := o.lastOp(t)
+ if op.Kind != opRenewal || op.State != opApplied || !op.Target.Renewal || !op.Target.CancelAtPeriodEnd {
+ t.Fatalf("op = %+v", op)
+ }
+ if !o.sub("sub_1").CancelAtPeriodEnd {
+ t.Fatal("the provider still renews")
+ }
+ if b, _ := o.st.BillingAccount(o.acct.ID); !b.CancelAtPeriodEnd {
+ t.Fatalf("billing row = %+v", b)
+ }
+ // Stopping again writes nothing.
+ o.reset()
+ o.wantFlash(t, o.renewal(t, "stop"), "ok", fmt.Sprintf(billingCopy["renewal.stopped"], billingDate(periodEnd)))
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 1})
+
+ o.reset()
+ o.wantFlash(t, o.renewal(t, "resume"), "ok", billingCopy["renewal.resumed"])
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 2, "Send": 1})
+ if o.sub("sub_1").CancelAtPeriodEnd {
+ t.Fatal("the provider still ends it")
+ }
+
+ o.reset()
+ o.wantFlash(t, o.renewal(t, "maybe"), "err", billingCopy["change.failed"])
+ wantCounts(t, o.counts(), map[string]int{})
+}
+
+func TestRenewalDoors(t *testing.T) {
+ o := newChangeFixture(t, nil)
+ // No CSRF: 403, nothing read.
+ for _, path := range []string{"/renewal", "/change"} {
+ rr := httpPostNoCSRF(t, o, o.billingBase()+path, url.Values{"renewal": {"stop"}, "pack": {"apps"}, "quantity": {"1"}})
+ if rr != http.StatusForbidden {
+ t.Fatalf("%s without CSRF = %d", path, rr)
+ }
+ }
+ wantCounts(t, o.counts(), map[string]int{})
+ // Retiring: refused before any read.
+ if err := o.st.BeginBillingRetirement(o.acct.ID, "owner", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ o.wantFlash(t, o.renewal(t, "stop"), "err", billingCopy["billing.retiring"])
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "1"), "err", billingCopy["billing.retiring"])
+ wantCounts(t, o.counts(), map[string]int{})
+ // Billing off: 404.
+ o.srv.billing = nil
+ for _, path := range []string{"/renewal", "/change"} {
+ if r := o.request(t, http.MethodPost, o.billingBase()+path, url.Values{"renewal": {"stop"}}); r.Status != http.StatusNotFound {
+ t.Fatalf("%s with billing off = %d", path, r.Status)
+ }
+ }
+}
+
+func TestPackChangeRefusesOperatorPlanAndProblems(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ if _, err := o.st.OpenBillingProblem(o.acct.ID, "sub_1", problemUnrecognised, "test", billingNow); err != nil {
+ t.Fatal(err)
+ }
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "0"), "err", billingCopy["notice.problem"])
+ wantCounts(t, o.counts(), map[string]int{})
+
+ // An operator's plan: billing leaves it alone.
+ o = newChangeFixture(t, map[string]int64{"apps": 1})
+ if _, err := o.st.db.Exec(`UPDATE account_plans SET source = ? WHERE account_id = ?`, PlanSourceOperator, o.acct.ID); err != nil {
+ t.Fatal(err)
+ }
+ o.wantFlash(t, o.change(t, "pack", "apps", "quantity", "0"), "err", billingCopy["notice.operator_plan"])
+ wantCounts(t, o.counts(), map[string]int{})
+
+ // Bad input: change.failed, nothing read.
+ o = newChangeFixture(t, map[string]int64{"apps": 1})
+ for _, form := range [][]string{
+ {"pack", "nope", "quantity", "1"},
+ {"pack", "apps", "quantity", "-1"},
+ {"pack", "apps", "quantity", "21"},
+ {"pack", "apps"},
+ {"plan", "free"},
+ {},
+ } {
+ o.wantFlash(t, o.change(t, form...), "err", billingCopy["change.failed"])
+ }
+ wantCounts(t, o.counts(), map[string]int{})
+}
+
+// httpPostNoCSRF posts form as the owner without the CSRF field.
+func httpPostNoCSRF(t *testing.T, o *opsFixture, path string, form url.Values) int {
+ t.Helper()
+ req, _ := http.NewRequest(http.MethodPost, o.ts.URL+path, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ resp, err := o.owner.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ return resp.StatusCode
+}
+
+// ---- the timeout --------------------------------------------------------------------------
+
+func TestChangeAndRenewalReturnUnderTimeout(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ do func(t *testing.T, o *opsFixture) billingReply
+ }{
+ {"change", func(t *testing.T, o *opsFixture) billingReply {
+ return o.change(t, "pack", "apps", "quantity", "3", "confirmed", "1")
+ }},
+ {"renewal", func(t *testing.T, o *opsFixture) billingReply { return o.renewal(t, "stop") }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ o := newChangeFixture(t, map[string]int64{"apps": 1})
+ o.stepUp(t)
+ var waited time.Duration
+ o.srv.billing.wait = func(_ context.Context, d time.Duration) {
+ waited += d
+ o.fake.AdvanceMonotonic(d)
+ time.Sleep(d / 50)
+ }
+ o.fake.Lock()
+ o.fake.FailBeforeDelivery = 100
+ o.fake.Unlock()
+ o.reset()
+ done := make(chan billingReply, 1)
+ go func() { done <- c.do(t, o) }()
+ select {
+ case r := <-done:
+ o.wantFlash(t, r, "err", billingCopy["change.uncertain"])
+ case <-time.After(15 * time.Second):
+ t.Fatal("the handler did not return within 15 s")
+ }
+ // One send and three retries, each after a read; about 7 s of
+ // backoff in all.
+ wantCounts(t, o.counts(), map[string]int{"Subscription": 5, "Send": 4})
+ if waited != 7*time.Second {
+ t.Fatalf("backoff = %v, want 7s", waited)
+ }
+ })
+ }
+}
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go
index c71003288..59bcb66fe 100644
--- a/internal/console/billingpage_copy.go
+++ b/internal/console/billingpage_copy.go
@@ -17,6 +17,18 @@ 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.",
+ // Pack changes, upgrades and renewal (Task 10).
+ "confirm.title": "Pay for this change?",
+ "confirm.line": "You'll pay about %s now for the rest of the year, plus any tax.",
+ "change.no_estimate": "Stripe charges the difference for the rest of the year.",
+ "confirm.button": "Pay now",
+ "change.outstanding": "Another change is still being confirmed or paid for. Finish or wait for it first.",
+ "change.none": "That's already your plan.",
+ "change.book": "This change isn't available on your current prices. An operator can make it at renewal.",
+ "change.near_renewal": "Your plan renews within a day. Try again after it renews; the pack will then be a normal purchase.",
+ "renewal.stopped": "Renewal stopped. Your plan ends on %s.",
+ "renewal.resumed": "Renewal is back on.",
+
// 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.",
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index dc152402b..a8d78d96f 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1313,6 +1313,12 @@ var claimFixtures = map[string]claimFixture{
"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"),
+ // Plans 6b changes: the owner's pack change, plan upgrade and renewal
+ // stop or resume prepare and send subscription operations under the
+ // billing hold, finishing an outstanding one first, and refresh the
+ // subscription.
+ "route POST /a/{sqid}/billing/change": claimNonApp("finishes the account's outstanding billing operation, then prepares and sends a pack change or plan upgrade as billing operations under the billing hold, writing the operations, restore obligations, billing state, the plan row and billing problems; names no app"),
+ "route POST /a/{sqid}/billing/renewal": claimNonApp("finishes the account's outstanding billing operation, then prepares and sends a renewal stop or resume as a billing operation under the billing hold, writing the operation, billing state, the plan row and billing problems; 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 2dd63b824..4d58321a7 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -738,6 +738,41 @@ var claimNonAppProbes = map[string]claimProbe{
return claimBillingPlanIs(t, cx, "personal")
},
},
+ "route POST /a/{sqid}/billing/change": {
+ setup: claimChangeWorld,
+ do: claimFormReply("/a/bab/billing/change", "pack", "apps", "quantity", "1"),
+ status: http.StatusSeeOther, loc: "/a/bab/billing",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake)
+ fake.Lock()
+ var q int64
+ for _, it := range fake.Subs["sub_claim"].Items {
+ if it.PriceID == testPriceID("example-v1/pack/apps/usd") {
+ q = it.Quantity
+ }
+ }
+ fake.Unlock()
+ if q != 1 {
+ return fmt.Sprintf("bab's apps pack is at %d at the provider, want 1", q)
+ }
+ return claimBillingPlanIs(t, cx, "personal")
+ },
+ },
+ "route POST /a/{sqid}/billing/renewal": {
+ setup: claimBillingWorld,
+ do: claimFormReply("/a/bab/billing/renewal", "renewal", "stop"),
+ status: http.StatusSeeOther, loc: "/a/bab/billing",
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake)
+ fake.Lock()
+ stopped := fake.Subs["sub_claim"].CancelAtPeriodEnd
+ fake.Unlock()
+ if !stopped {
+ return "bab's subscription still renews at the provider"
+ }
+ return claimBillingPlanIs(t, cx, "personal")
+ },
+ },
"route POST /api/cli/billing/problems/{id}/close": {
setup: claimBillingProblemWorld,
do: func(t *testing.T, cx *claimCase) claimReply {
@@ -1040,6 +1075,17 @@ func claimBillingWorld(t *testing.T, cx *claimCase) {
cx.srv.billing.ready.Store(true)
}
+// claimChangeWorld is claimBillingWorld with two apps packs on sub_claim, so
+// a reduction to one is a change with no charge and no step-up.
+func claimChangeWorld(t *testing.T, cx *claimCase) {
+ t.Helper()
+ claimBillingWorld(t, cx)
+ fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake)
+ fake.Lock()
+ fake.Subs["sub_claim"] = testPersonalSub("sub_claim", "cus_claim", "bab", "active", map[string]int64{"apps": 2})
+ fake.Unlock()
+}
+
// 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) {
diff --git a/internal/console/server.go b/internal/console/server.go
index bbcbb9780..99cafb73a 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1573,6 +1573,10 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
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)
+ // Plans 6b: an owner's pack change or plan upgrade, and stopping or
+ // resuming renewal (billingchange.go). 404 with billing off.
+ s.registerRoute("POST /a/{sqid}/billing/change", s.handleBillingChange)
+ s.registerRoute("POST /a/{sqid}/billing/renewal", s.handleBillingRenewal)
// 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 5677a3177..78d64fb50 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -154,8 +154,10 @@ 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/change
route POST /a/{sqid}/billing/checkout
route POST /a/{sqid}/billing/confirm
+route POST /a/{sqid}/billing/renewal
route POST /a/{sqid}/delete
route POST /a/{sqid}/errors/level
route POST /a/{sqid}/fleets/{fleet}/detach