carlos / platform Public

domains: confirmed price is the charged price; sponsored gate unchanged

Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 28ced7e9ab43d4d281233b18d46b73c6178cc706 parent 2d1e2bb
24 files changed, +668 −116
  • apimode.go +18 −5
  • domains_buy_cli.go +44 −12
  • domains_buy_cli_test.go +122 −2
  • domains_buy_copy.go +2 −0
  • internal/console/apidomainbuy.go +15 −5
  • internal/console/apidomainbuy_test.go +5 −5
  • internal/console/appdomainbuy.go +17 −3
  • internal/console/billingcard_test.go +9 −2
  • internal/console/billingcheckout.go +22 −6
  • internal/console/billingcustomer.go +4 −7
  • internal/console/billingpage.go +5 −0
  • internal/console/billingpage_test.go +4 −2
  • internal/console/billingstore.go +20 −8
  • internal/console/domainbuy.go +56 −28
  • internal/console/domainbuy_copy.go +3 −1
  • internal/console/domainbuy_final_fix_test.go +5 −5
  • internal/console/domainbuy_fix_test.go +1 −1
  • internal/console/domainbuy_nosub_test.go +8 −7
  • internal/console/domainbuy_registry_test.go +1 −1
  • internal/console/domainbuy_round1_test.go +278 −0
  • internal/console/domainbuy_test.go +25 −12
  • internal/console/plancaps.go +0 −3
  • internal/console/templates/domain_buy.html +3 −0
  • internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv +1 −1
diff --git a/apimode.go b/apimode.go
index 20e3bf86a..e9dd25463 100644
--- a/apimode.go
+++ b/apimode.go
@@ -4692,6 +4692,13 @@ type domainPurchaseResp struct {
type domainContactError struct{ error }
+type domainPriceChangedError struct {
+ error
+ Quote domainQuoteResp
+}
+
+func (e *domainPriceChangedError) Unwrap() error { return e.error }
+
func (e *domainContactError) Unwrap() error { return e.error }
func domainBuyAPIPath(acct apiAcct, tail string) string {
@@ -4719,13 +4726,15 @@ func (s *apiSession) postDomainCheck(ctx context.Context, acct apiAcct, name str
return out, nil
}
-func (s *apiSession) postDomainPurchase(ctx context.Context, acct apiAcct, name, app string, contact *registrar.Contact) (domainPurchaseResp, error) {
+func (s *apiSession) postDomainPurchase(ctx context.Context, acct apiAcct, name, app string, contact *registrar.Contact, confirmed domainQuoteResp) (domainPurchaseResp, error) {
var out domainPurchaseResp
status, body, err := s.postJSON(ctx, domainBuyAPIPath(acct, "/purchases"), struct {
- Name string `json:"name"`
- App string `json:"app"`
- Contact *registrar.Contact `json:"contact,omitempty"`
- }{name, app, contact})
+ Name string `json:"name"`
+ App string `json:"app"`
+ Contact *registrar.Contact `json:"contact,omitempty"`
+ Currency string `json:"currency"`
+ Price int64 `json:"price"`
+ }{name, app, contact, confirmed.Currency, confirmed.Price})
if err != nil {
return out, err
}
@@ -4733,6 +4742,10 @@ func (s *apiSession) postDomainPurchase(ctx context.Context, acct apiAcct, name,
err := apiErrorFromBody(status, body)
var refusal struct {
Code string `json:"code"`
+ domainQuoteResp
+ }
+ if status == http.StatusConflict && json.Unmarshal(body, &refusal) == nil && refusal.Code == "price_changed" && refusal.Currency != "" && refusal.Price > 0 {
+ return out, &domainPriceChangedError{err, refusal.domainQuoteResp}
}
if status == http.StatusUnprocessableEntity && json.Unmarshal(body, &refusal) == nil && refusal.Code == "contact" {
return out, &domainContactError{err}
diff --git a/domains_buy_cli.go b/domains_buy_cli.go
index 221ee07b1..79798dd67 100644
--- a/domains_buy_cli.go
+++ b/domains_buy_cli.go
@@ -124,22 +124,54 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri
return nil
}
}
- p, err := s.postDomainPurchase(ctx, acct, name, app, contact)
- var contactErr *domainContactError
- if errors.As(err, &contactErr) {
- if !o.terminal {
- return fmt.Errorf(domainsBuyCopy["contactNonTTY"], err)
+ var p domainPurchaseResp
+ contactRetried, priceRetried := false, false
+ for {
+ p, err = s.postDomainPurchase(ctx, acct, name, app, contact, q)
+ var contactErr *domainContactError
+ var priceErr *domainPriceChangedError
+ if errors.As(err, &contactErr) && !contactRetried {
+ if !o.terminal {
+ return fmt.Errorf(domainsBuyCopy["contactNonTTY"], err)
+ }
+ contactRetried = true
+ fmt.Fprintln(o.out, err)
+ contact, err = promptDomainContact(input, o.out)
+ if err != nil {
+ return err
+ }
+ continue
+ }
+ if errors.As(err, &priceErr) {
+ printDomainQuote(o.out, priceErr.Quote)
+ if priceRetried {
+ return err
+ }
+ priceRetried = true
+ if o.yes {
+ if q.Currency != priceErr.Quote.Currency || q.Price != priceErr.Quote.Price {
+ return err
+ }
+ } else {
+ if !o.terminal {
+ return err
+ }
+ answer, askErr := domainBuyAnswer(input, o.out, domainsBuyCopy["confirmChanged"])
+ if askErr != nil {
+ return askErr
+ }
+ if !strings.EqualFold(answer, "y") && !strings.EqualFold(answer, "yes") {
+ fmt.Fprintln(o.out, domainsBuyCopy["cancelled"])
+ return nil
+ }
+ }
+ q = priceErr.Quote
+ continue
}
- // One retry, after collecting all fields. Validation remains at the door.
- fmt.Fprintln(o.out, err)
- contact, err = promptDomainContact(input, o.out)
if err != nil {
return err
}
- p, err = s.postDomainPurchase(ctx, acct, name, app, contact)
- }
- if err != nil {
- return err
+ break
}
fmt.Fprintf(o.out, domainsBuyCopy["purchaseID"], p.ID)
if p.CheckoutURL != "" {
diff --git a/domains_buy_cli_test.go b/domains_buy_cli_test.go
index a030082a8..d85e0225c 100644
--- a/domains_buy_cli_test.go
+++ b/domains_buy_cli_test.go
@@ -319,7 +319,7 @@ func TestDomainsBuyDoorErrors(t *testing.T) {
case "check":
_, err = s.postDomainCheck(context.Background(), apiAcct{Seg: "bab"}, "shop.com")
case "purchase":
- _, err = s.postDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "shop.com", "shop", nil)
+ _, err = s.postDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "shop.com", "shop", nil, domainQuoteResp{Currency: "eur", Price: 1299})
case "status":
_, err = s.getDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "p1")
}
@@ -361,7 +361,7 @@ func TestDomainsBuyAPIExactAccountAndEscapedID(t *testing.T) {
case "check":
_, err = s.postDomainCheck(context.Background(), a, "shop.com")
case "purchase":
- _, err = s.postDomainPurchase(context.Background(), a, "shop.com", "shop", nil)
+ _, err = s.postDomainPurchase(context.Background(), a, "shop.com", "shop", nil, domainQuoteResp{Currency: "eur", Price: 1299})
case "status":
_, err = s.getDomainPurchase(context.Background(), a, "p/1")
}
@@ -420,3 +420,123 @@ func TestDomainsBuyLivePollHasRemainingDeadline(t *testing.T) {
t.Fatal(err)
}
}
+
+func TestDomainsBuyConfirmedPriceRetry(t *testing.T) {
+ for _, mode := range []string{"accept", "decline", "yes", "twice", "unchanged"} {
+ t.Run(mode, func(t *testing.T) {
+ calls := 0
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ var in struct {
+ Currency string
+ Price int64
+ }
+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
+ t.Error(err)
+ }
+ expected := int64(1299)
+ if calls > 1 && mode != "unchanged" {
+ expected = 1699
+ }
+ if in.Currency != "eur" || in.Price != expected {
+ t.Errorf("confirmed price missing/wrong: %+v", in)
+ }
+ if calls == 1 || mode == "twice" {
+ price := 1699
+ if mode == "unchanged" {
+ price = 1299
+ }
+ if calls > 1 {
+ price = 1799
+ }
+ w.WriteHeader(409)
+ fmt.Fprintf(w, `{"code":"price_changed","error":"price changed","domain":"shop.com","available":true,"currency":"eur","price":%d}`, price)
+ return
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ }, nil)
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.noWait = true
+ o.terminal = true
+ o.yes = mode == "yes" || mode == "unchanged"
+ o.in = strings.NewReader("y\ny\n")
+ if mode == "decline" {
+ o.in = strings.NewReader("y\nn\n")
+ }
+ err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o)
+ wantErr := mode == "yes" || mode == "twice"
+ wantCalls := 2
+ if mode == "yes" || mode == "decline" {
+ wantCalls = 1
+ }
+ if (err != nil) != wantErr || calls != wantCalls {
+ t.Fatalf("calls=%d err=%v output=%s", calls, err, &out)
+ }
+ if mode != "unchanged" && !strings.Contains(out.String(), "16.99") {
+ t.Fatalf("new price missing: %s", &out)
+ }
+ if mode == "twice" && !strings.Contains(out.String(), "17.99") {
+ t.Fatalf("second change missing: %s", &out)
+ }
+ })
+ }
+}
+
+func TestDomainsBuyChangedPriceExitsNonZero(t *testing.T) {
+ calls := 0
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ w.WriteHeader(409)
+ fmt.Fprint(w, `{"code":"price_changed","error":"price changed","domain":"shop.com","available":true,"currency":"gbp","price":1700}`)
+ }, nil)
+ out, err := runBuyTestCommand(t, ts.URL, "--no-wait")
+ if err == nil || calls != 1 || !strings.Contains(out, "£17 GBP") {
+ t.Fatalf("calls=%d err=%v output=%s", calls, err, out)
+ }
+}
+
+func TestDomainsBuyChangedPriceAfterContact(t *testing.T) {
+ calls := 0
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ var in struct {
+ Price int64
+ Currency string
+ Contact json.RawMessage
+ }
+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
+ t.Error(err)
+ }
+ want := int64(1299)
+ if calls == 3 {
+ want = 1699
+ }
+ if in.Price != want || in.Currency != "eur" {
+ t.Errorf("request %d: %+v", calls, in)
+ }
+ if calls == 1 {
+ w.WriteHeader(422)
+ fmt.Fprint(w, `{"code":"contact","error":"contact required"}`)
+ return
+ }
+ if len(in.Contact) == 0 {
+ t.Error("lost collected contact")
+ }
+ if calls == 2 {
+ w.WriteHeader(409)
+ fmt.Fprint(w, `{"code":"price_changed","error":"price changed","domain":"shop.com","available":true,"currency":"eur","price":1699}`)
+ return
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ }, nil)
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes = false
+ o.noWait = true
+ o.terminal = true
+ o.in = strings.NewReader("y\nJane\nBuyer\n\nbuyer@example.test\n353\n871234567\nMain Street\n\nDublin\n\nD01 A123\nIE\ny\n")
+ if err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil || calls != 3 {
+ t.Fatalf("calls=%d err=%v output=%s", calls, err, &out)
+ }
+}
diff --git a/domains_buy_copy.go b/domains_buy_copy.go
index 37f0d9191..7c8a2679a 100644
--- a/domains_buy_copy.go
+++ b/domains_buy_copy.go
@@ -9,6 +9,8 @@ const domainsCheckUsage = "usage: carlos domains check <name> [--account <a>] [-
const domainsBuyUsage = "usage: carlos domains buy <name> --app <a> [--contact-file contact.json] [--yes] [--no-wait] [--account <a>] [--account-id <id>] [--console <origin>]\n"
var domainsBuyCopy = map[string]string{
+ // Draft for the Luna pass: round 1 price-change confirmation.
+ "confirmChanged": "buy this domain at the new price? [y/N] ",
// Draft for the Luna pass: domain registration Plan 2, slice 1.
"purchaseID": "purchase: %s\n",
"appFlag": "app the domain will serve",
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go
index cea2c370a..c18716230 100644
--- a/internal/console/apidomainbuy.go
+++ b/internal/console/apidomainbuy.go
@@ -36,7 +36,11 @@ func (s *Server) domainBuyAPIGate(w http.ResponseWriter, r *http.Request) (strin
}
func (s *Server) checkDomainBuy(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) {
- return s.admitDomainBuy(ctx, acct, name)
+ c, _, err := s.store.DomainContact(acct.ID)
+ if err != nil {
+ return domainreg.Quote{}, domainBuyUnavailable()
+ }
+ return s.admitDomainBuy(ctx, acct, name, c.Country)
}
func (s *Server) liveDomainPurchaseRefusal(ctx context.Context, name string) *doorRefusal {
@@ -77,9 +81,11 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request)
return
}
var in struct {
- Name string `json:"name"`
- App string `json:"app"`
- Contact *registrar.Contact `json:"contact"`
+ Name string `json:"name"`
+ App string `json:"app"`
+ Contact *registrar.Contact `json:"contact"`
+ Currency string `json:"currency"`
+ Price int64 `json:"price"`
}
if !readJSONStrictLimit(w, r, &in, 16<<10) {
return
@@ -101,7 +107,11 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request)
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
- p, checkout, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr)
+ p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr, domainreg.Quote{Currency: in.Currency, Price: in.Price})
+ if changed != nil {
+ writeJSON(w, http.StatusConflict, map[string]any{"error": ref.Msg, "code": "price_changed", "domain": changed.Domain, "currency": changed.Currency, "price": changed.Price, "available": true})
+ return
+ }
if ref != nil {
if ref.Status == 422 && ref.Msg == domainBuyCopy["contactError"] {
writeJSON(w, 422, map[string]string{"error": ref.Msg, "code": "contact"})
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go
index d510f1226..15598c346 100644
--- a/internal/console/apidomainbuy_test.go
+++ b/internal/console/apidomainbuy_test.go
@@ -45,7 +45,7 @@ func buyRequest(t *testing.T, f *purchaseFixture, method, path, token, body stri
return resp.StatusCode, string(b)
}
func buyBody() string {
- b, _ := json.Marshal(map[string]any{"name": "shop.com", "app": "kass", "contact": purchaseContact()})
+ b, _ := json.Marshal(map[string]any{"name": "shop.com", "app": "kass", "contact": purchaseContact(), "currency": "usd", "price": 1500})
return string(b)
}
func TestBuyDoorAbsentWhenNotConfigured(t *testing.T) {
@@ -188,7 +188,7 @@ func TestBrowserBuyRedirectsToCheckout(t *testing.T) {
t.Errorf("missing visible copy %q", want)
}
}
- values := url.Values{"csrf": {csrf}, "name": {"shop.com"}}
+ values := url.Values{"csrf": {csrf}, "name": {"shop.com"}, "currency": {"usd"}, "price": {"1500"}}
for _, field := range buyContactFields(purchaseContact()) {
values.Set(field.Name, field.Value)
}
@@ -231,14 +231,14 @@ func TestBrowserBuyCSRF(t *testing.T) {
func TestBuyDoorStoredContact(t *testing.T) {
f := newPurchaseFixture(t)
tok := buyToken(t, f)
- status, b := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass"}`)
+ status, b := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass","currency":"usd","price":1500}`)
if status != 422 || !strings.Contains(b, `"code":"contact"`) {
t.Fatalf("missing contact %d %s", status, b)
}
if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil {
t.Fatal(err)
}
- status, b = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass"}`)
+ status, b = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass","currency":"usd","price":1500}`)
if status != 200 && status != 201 {
t.Fatalf("stored contact %d %s", status, b)
}
@@ -257,7 +257,7 @@ func setupClaimBuyDoors(t *testing.T, cx *claimCase) {
cx.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}}
}
func claimBuyForm(t *testing.T, cx *claimCase) int {
- kv := []string{"name", "shop.com"}
+ kv := []string{"name", "shop.com", "currency", "usd", "price", "1500"}
for _, field := range buyContactFields(purchaseContact()) {
kv = append(kv, field.Name, field.Value)
}
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go
index abfee982e..1e4e63ce6 100644
--- a/internal/console/appdomainbuy.go
+++ b/internal/console/appdomainbuy.go
@@ -5,6 +5,7 @@ import (
"crypto/subtle"
"net/http"
"net/url"
+ "strconv"
"time"
"github.com/carlosframework/platform/internal/domainreg"
@@ -20,6 +21,7 @@ type domainBuyView struct {
Base, Back, PollURL string
CheckoutURL string
Price string
+ PriceChanged bool
Quote *domainreg.Quote
Fields []domainBuyField
Purchase *DomainPurchase
@@ -70,7 +72,11 @@ func (s *Server) renderDomainBuy(w http.ResponseWriter, r *http.Request, addr, r
v.Price = plans.FormatMinor(v.Quote.Currency, v.Quote.Price)
}
p.DomainBuy = v
- s.render(w, 200, "domain_buy", p)
+ status := http.StatusOK
+ if v.PriceChanged {
+ status = http.StatusConflict
+ }
+ s.render(w, status, "domain_buy", p)
}
func (s *Server) handleAppDomainBuyForm(w http.ResponseWriter, r *http.Request) {
addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r)
@@ -99,7 +105,7 @@ func (s *Server) handleAppDomainBuyCheck(w http.ResponseWriter, r *http.Request)
s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Quote: &q, Fields: buyContactFields(c)})
}
func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) {
- addr, _, acct, app, ok := s.domainBuyBrowserGate(w, r)
+ addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r)
if !ok {
return
}
@@ -112,7 +118,15 @@ func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) {
City: r.FormValue("City"), State: r.FormValue("State"), PostalCode: r.FormValue("PostalCode"), Country: r.FormValue("Country")}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
- p, checkout, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr)
+ price, err := strconv.ParseInt(r.FormValue("price"), 10, 64)
+ if err != nil {
+ price = 0
+ }
+ p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr, domainreg.Quote{Currency: r.FormValue("currency"), Price: price})
+ if changed != nil {
+ s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Quote: changed, Fields: buyContactFields(c), PriceChanged: true})
+ return
+ }
if ref != nil {
s.renderDoorRefusal(w, r, ref)
return
diff --git a/internal/console/billingcard_test.go b/internal/console/billingcard_test.go
index 78614539a..cf7cf9291 100644
--- a/internal/console/billingcard_test.go
+++ b/internal/console/billingcard_test.go
@@ -9,11 +9,18 @@ import (
"time"
"github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/domainreg"
+ "github.com/carlosframework/platform/internal/registrar/registrartest"
+ "github.com/carlosframework/platform/internal/zonehost/zonehosttest"
)
func TestBillingAddCardWithoutCustomer(t *testing.T) {
o := newCheckoutFixture(t, false)
- if _, err := o.st.SetAccountPlan(o.acct.ID, "free", nil, 0, PlanSourceSponsored, nil, "test", "operator", time.Now()); err != nil {
+ o.srv.cfg.Registrar = registrartest.New()
+ o.srv.cfg.ZoneHost = zonehosttest.New("ns1.example.test")
+ o.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3}
+ sponsored := sponsorUnlimited()
+ if _, err := o.st.SetAccountPlan(o.acct.ID, "free", nil, 0, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil {
t.Fatal(err)
}
page := o.request(t, http.MethodGet, o.billingBase(), nil)
@@ -31,7 +38,7 @@ func TestBillingAddCardWithoutCustomer(t *testing.T) {
}
}
b, err := o.st.BillingAccount(o.acct.ID)
- if err != nil || b == nil || b.Customer == "" || b.Subscription != "" {
+ if err != nil || b == nil || b.Customer == "" || b.Subscription != "" || b.Currency != "" {
t.Fatalf("billing: %+v %v", b, err)
}
customers, setups := 0, 0
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go
index d4c213962..0f4b3e77b 100644
--- a/internal/console/billingcheckout.go
+++ b/internal/console/billingcheckout.go
@@ -428,13 +428,24 @@ func customerKey(sqid string, attempt int) string {
return fmt.Sprintf("customer:%s:%d", sqid, attempt)
}
+type customerSetup struct {
+ Details billing.CustomerDetails
+ Currency string
+}
+
// 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, details ...billing.CustomerDetails) (string, error) {
+func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *Account, now time.Time, setup ...customerSetup) (string, error) {
+ var currency string
+ var details []billing.CustomerDetails
+ if len(setup) > 0 {
+ currency = setup[0].Currency
+ details = []billing.CustomerDetails{setup[0].Details}
+ }
b, err := s.store.BillingAccount(acct.ID)
if err != nil {
return "", err
@@ -443,6 +454,11 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *
b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}}
}
if b.Customer != "" {
+ if currency != "" {
+ if err := s.store.SetBillingCustomer(acct.ID, b.Customer, now, currency); err != nil {
+ return "", err
+ }
+ }
return b.Customer, nil
}
started := 0
@@ -457,7 +473,7 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *
return "", err
}
}
- out, err := s.sendCustomerLocked(h, ctx, acct, b, recovering, handlerRetries, now)
+ out, err := s.sendCustomerLocked(h, ctx, acct, b, recovering, handlerRetries, now, currency)
if err != nil {
return "", err
}
@@ -510,7 +526,7 @@ func customerResendState(b *billingAccount) resendState {
// 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) {
+func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, recovering bool, retries int, now time.Time, currency ...string) (customerOutcome, error) {
if recovering {
retries = 0 // a recovery is F: at most one resend, whoever calls
}
@@ -534,7 +550,7 @@ func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Ac
}
res, err := s.sendPreparedLocked(h, ctx, *b.CustomerPrepared)
if !retryableSend(err) || attempt == retries {
- return s.recordCustomerLocked(h, acct, b, res, err, now)
+ return s.recordCustomerLocked(h, acct, b, res, err, now, currency...)
}
}
}
@@ -543,10 +559,10 @@ func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Ac
// 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) {
+func (s *Server) recordCustomerLocked(h billingHold, acct *Account, b *billingAccount, res billing.Result, err error, now time.Time, currency ...string) (customerOutcome, error) {
switch {
case err == nil && res.Customer != "":
- if err := s.store.SetBillingCustomer(acct.ID, res.Customer, now); err != nil {
+ if err := s.store.SetBillingCustomer(acct.ID, res.Customer, now, currency...); err != nil {
return customerUnknown, err
}
b.Customer = res.Customer
diff --git a/internal/console/billingcustomer.go b/internal/console/billingcustomer.go
index ac1adc833..462c01497 100644
--- a/internal/console/billingcustomer.go
+++ b/internal/console/billingcustomer.go
@@ -27,8 +27,9 @@ func (s *Server) paymentCustomerLocked(h billingHold, ctx context.Context, acct
if b == nil {
b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}}
}
- if fixCurrency && b.Currency == "" {
- currency, err := s.billing.cfg.Book.ChooseCurrency("", country)
+ currency := b.Currency
+ if fixCurrency && currency == "" {
+ currency, err = s.billing.cfg.Book.ChooseCurrency("", country)
if err != nil {
return nil, err
}
@@ -39,10 +40,6 @@ func (s *Server) paymentCustomerLocked(h billingHold, ctx context.Context, acct
if prior != nil && (!intentTerminal(prior) || prior.State == intentCompleted) && prior.Currency != currency {
return nil, errCheckoutUncertain
}
- b.Currency = currency
- if err := s.store.PutBillingState(*b); err != nil {
- return nil, err
- }
}
details := billing.CustomerDetails{Country: country, PostalCode: postal}
members, err := s.store.Members(acct.ID)
@@ -58,7 +55,7 @@ func (s *Server) paymentCustomerLocked(h billingHold, ctx context.Context, acct
if details.Email == "" {
return nil, errors.New("billing: account has no owner")
}
- if _, err := s.ensureCustomerLocked(h, ctx, acct, now, details); err != nil {
+ if _, err := s.ensureCustomerLocked(h, ctx, acct, now, customerSetup{Details: details, Currency: currency}); err != nil {
return nil, err
}
return s.store.BillingAccount(acct.ID)
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go
index ec7781840..cc41b5103 100644
--- a/internal/console/billingpage.go
+++ b/internal/console/billingpage.go
@@ -50,6 +50,7 @@ type billingPageInput struct {
Op *billingOp // the outstanding operation, nil for none
Problems []string // open problem reasons
Retiring, Ready, Owner bool
+ CanBuyDomains bool
// Exempt is the ops account, which has no plan (planExempt).
Exempt bool
Now time.Time
@@ -71,6 +72,9 @@ type billingPageState struct {
// owner's notice and, where an owner would act, notice.owners_only.
func decideBillingPage(in billingPageInput) billingPageState {
notice, offered := decideBillingOwner(in)
+ if !in.CanBuyDomains {
+ offered = slices.DeleteFunc(offered, func(key string) bool { return key == offerCard })
+ }
if in.Owner {
return billingPageState{Notice: notice, Offered: offered}
}
@@ -316,6 +320,7 @@ func (s *Server) billingPageInputFor(acct *Account, role string, now time.Time)
if in.Exempt {
return in, nil // nothing else decides its page
}
+ in.CanBuyDomains = s.domainBuyReady() && s.checkCustomDomains(acct) == nil
var err error
if in.Row, err = s.store.AccountPlan(acct.ID); err != nil {
return in, err
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go
index 6bcad8dc9..92a894a62 100644
--- a/internal/console/billingpage_test.go
+++ b/internal/console/billingpage_test.go
@@ -22,6 +22,7 @@ import (
func TestDecideBillingPage(t *testing.T) {
now := billingNow
+ sponsored := sponsorUnlimited()
paid := func(mod func(b *billingAccount)) *billingAccount {
b := &billingAccount{Customer: "cus_1", Subscription: "sub_1", State: billing.StatePaid, Live: true, Currency: "usd", PeriodEnd: periodEnd}
if mod != nil {
@@ -53,7 +54,8 @@ func TestDecideBillingPage(t *testing.T) {
{"another problem, unbound", billingPageInput{Ready: true, Problems: []string{problemUnknownCustomer}}, "notice.problem", nil},
{"operator row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "business", Source: PlanSourceOperator}, Billing: free,
Op: op(opUnresolved)}, "notice.operator_plan", []string{"portal"}},
- {"sponsored row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored}}, "notice.operator_plan", []string{"card"}},
+ {"sponsored row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored, Sponsored: &sponsored}}, "notice.operator_plan", nil},
+ {"sponsored with buying enabled", billingPageInput{Ready: true, CanBuyDomains: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored, Sponsored: &sponsored}}, "notice.operator_plan", []string{"card"}},
{"op unresolved", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opUnresolved)},
"notice.confirming", []string{"confirm", "portal"}},
{"op sending", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opSending)},
@@ -69,7 +71,7 @@ func TestDecideBillingPage(t *testing.T) {
{"intent creating", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCreating)},
"notice.settling", []string{"confirm"}},
{"not live", billingPageInput{Ready: true, Billing: free}, "", []string{"buy", "portal"}},
- {"no billing row", billingPageInput{Ready: true}, "", []string{"buy", "card"}},
+ {"no billing row", billingPageInput{Ready: true}, "", []string{"buy"}},
{"intent open but live", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Intent: intent(intentOpen)},
"", []string{"change", "stop", "portal"}},
{"pending state", billingPageInput{Ready: true, Billing: paid(func(b *billingAccount) { b.State = billing.StatePending })},
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go
index 1d14d8c65..178f88c00 100644
--- a/internal/console/billingstore.go
+++ b/internal/console/billingstore.go
@@ -380,28 +380,40 @@ func (s *Store) BillingAccountByCustomer(customer string) (*billingAccount, erro
}
// SetBillingCustomer binds the account's provider customer. Binding the
-// same customer again is a no-op; a customer bound to another account, or
-// a second customer for this one, is an error.
-func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Time) error {
+// same customer preserves its binding time. An optional currency fixes an
+// unset currency in the same write, including for an existing card customer.
+// A different customer or fixed currency is refused.
+func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Time, currency ...string) error {
+ fix := ""
+ if len(currency) > 0 {
+ fix = currency[0]
+ }
if customer == "" {
return errors.New("billing: empty customer")
}
- res, err := s.db.Exec(`INSERT INTO billing_accounts (account_id, customer, synced_at, bound_at) VALUES (?, ?, ?, ?)
- ON CONFLICT(account_id) DO UPDATE SET customer = excluded.customer, bound_at = excluded.bound_at WHERE billing_accounts.customer = ''`,
- accountID, customer, now.Unix(), now.Unix())
+ res, err := s.db.Exec(`INSERT INTO billing_accounts (account_id, customer, synced_at, bound_at, currency) VALUES (?, ?, ?, ?, ?)
+ ON CONFLICT(account_id) DO UPDATE SET customer = excluded.customer,
+ bound_at = CASE WHEN billing_accounts.customer = '' THEN excluded.bound_at ELSE billing_accounts.bound_at END,
+ currency = CASE WHEN billing_accounts.currency = '' THEN excluded.currency ELSE billing_accounts.currency END
+ WHERE (billing_accounts.customer = '' OR billing_accounts.customer = excluded.customer)
+ AND (excluded.currency = '' OR billing_accounts.currency = '' OR billing_accounts.currency = excluded.currency)`,
+ accountID, customer, now.Unix(), now.Unix(), fix)
if err != nil {
return err
}
if n, err := res.RowsAffected(); err != nil || n == 1 {
return err
}
- var bound string
- if err := s.db.QueryRow(`SELECT customer FROM billing_accounts WHERE account_id = ?`, accountID).Scan(&bound); err != nil {
+ var bound, fixed string
+ if err := s.db.QueryRow(`SELECT customer, currency FROM billing_accounts WHERE account_id = ?`, accountID).Scan(&bound, &fixed); err != nil {
return err
}
if bound != customer {
return errors.New("billing: the account already has another customer")
}
+ if fix != "" && fixed != fix {
+ return currencyFixedRefusal{Currency: fixed}
+ }
return nil
}
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go
index a3b6f446d..cc0436649 100644
--- a/internal/console/domainbuy.go
+++ b/internal/console/domainbuy.go
@@ -125,62 +125,84 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string,
return q, nil
}
-func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) {
+// A non-nil third result supplies the replacement quote for confirmation.
+func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string, confirmed domainreg.Quote) (*DomainPurchase, string, *domainreg.Quote, *doorRefusal) {
// Serialize starts so a concurrent buyer resumes the winning checkout.
defer s.planLock(acct)()
q, ref := s.admitDomainBuy(ctx, acct, name, c.Country)
if ref != nil {
- return nil, "", ref
+ return nil, "", nil, ref
}
name = q.Domain
own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name)
if err != nil {
- return nil, "", domainBuyUnavailable()
+ return nil, "", nil, domainBuyUnavailable()
}
if own != nil {
- return s.resumeDomainPurchase(ctx, own)
+ if confirmed.Currency != q.Currency || confirmed.Price != q.Price {
+ return nil, "", &q, domainBuyStateRefusal("priceChanged", http.StatusConflict)
+ }
+ p, link, ref := s.resumeDomainPurchase(ctx, own)
+ return p, link, nil, ref
}
exists, err := s.store.HasAppIn(acct.ID, app)
if err != nil {
- return nil, "", domainBuyUnavailable()
+ return nil, "", nil, domainBuyUnavailable()
}
if !exists {
- return nil, "", &doorRefusal{Status: http.StatusNotFound}
+ return nil, "", nil, &doorRefusal{Status: http.StatusNotFound}
}
if err := c.Validate(); err != nil {
- return nil, "", &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]}
+ return nil, "", nil, &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]}
+ }
+ h, release, err := s.holdBilling(acct)
+ if err != nil {
+ return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
+ }
+ // Choose and confirm under the same hold that creates the customer. A
+ // subscription may have fixed currency since admission read the account.
+ b, err := s.store.BillingAccount(acct.ID)
+ if err != nil {
+ release()
+ return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
+ }
+ if b != nil && b.Currency != "" {
+ q.Currency = b.Currency
+ }
+ q.Price = s.cfg.DomainCatalog.TLDs[q.TLD].Register[q.Currency]
+ if q.Price <= 0 {
+ release()
+ return nil, "", nil, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
+ }
+ if confirmed.Currency != q.Currency || confirmed.Price != q.Price {
+ release()
+ return nil, "", &q, domainBuyStateRefusal("priceChanged", http.StatusConflict)
}
count, err := s.store.PurchasesToday(acct.ID, time.Now())
if err != nil {
- return nil, "", domainBuyUnavailable()
+ release()
+ return nil, "", nil, domainBuyUnavailable()
}
if count >= s.cfg.DomainCatalog.DailyCap {
- return nil, "", &doorRefusal{http.StatusTooManyRequests, domainPurchaseCopy.DailyCap}
+ release()
+ return nil, "", nil, &doorRefusal{http.StatusTooManyRequests, domainPurchaseCopy.DailyCap}
}
balance, err := s.cfg.Registrar.Balance(ctx)
if err != nil {
- return nil, "", s.domainBuyRegistrarRefusal(ctx, acct, name, err)
+ release()
+ return nil, "", nil, s.domainBuyRegistrarRefusal(ctx, acct, name, err)
}
if balance.Currency != q.Cost.Currency || balance.Minor < q.Cost.Minor {
s.purchaseRefusalAlert(ctx, acct, name, "balance", "registrar balance")
- return nil, "", domainBuyUnavailable()
- }
- h, release, err := s.holdBilling(acct)
- if err != nil {
- return nil, "", domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
+ release()
+ return nil, "", nil, domainBuyUnavailable()
}
- b, err := s.paymentCustomerLocked(h, s.billingClock(ctx), acct, c.Country, c.PostalCode, true)
+ _, err = s.paymentCustomerLocked(h, s.billingClock(ctx), acct, c.Country, c.PostalCode, true)
release()
if err != nil {
log.Printf("console: domain buy billing %s: %v", acct.Sqid, err)
- return nil, "", domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
- }
- // Subscription checkout or card setup may have acquired the billing hold first.
- q.Currency = b.Currency
- q.Price = s.cfg.DomainCatalog.TLDs[q.TLD].Register[q.Currency]
- if q.Price <= 0 {
- return nil, "", domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
+ return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable)
}
now := time.Now().UTC()
p := DomainPurchase{ID: newDomainPurchaseID(), AccountID: acct.ID, Domain: q.Domain, App: app, Currency: q.Currency, Amount: q.Price,
@@ -190,17 +212,23 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na
if errors.Is(err, ErrDomainPurchaseLive) {
own, readErr := s.ownLiveDomainPurchase(ctx, acct.ID, name)
if readErr != nil {
- return nil, "", domainBuyUnavailable()
+ return nil, "", nil, domainBuyUnavailable()
}
if own != nil {
- return s.resumeDomainPurchase(ctx, own)
+ if confirmed.Currency != own.Currency || confirmed.Price != own.Amount {
+ changed := domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}
+ return nil, "", &changed, domainBuyStateRefusal("priceChanged", http.StatusConflict)
+ }
+ p, link, ref := s.resumeDomainPurchase(ctx, own)
+ return p, link, nil, ref
}
- return nil, "", claimRefusal(name, domains.ErrHostUnavailable)
+ return nil, "", nil, claimRefusal(name, domains.ErrHostUnavailable)
}
if err != nil {
- return nil, "", domainBuyUnavailable()
+ return nil, "", nil, domainBuyUnavailable()
}
- return s.resumeDomainPurchase(ctx, &p)
+ purchase, link, ref := s.resumeDomainPurchase(ctx, &p)
+ return purchase, link, nil, ref
}
func (s *Server) ownLiveDomainPurchase(ctx context.Context, account int64, name string) (*DomainPurchase, error) {
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go
index 5f64105cf..ebd2e7286 100644
--- a/internal/console/domainbuy_copy.go
+++ b/internal/console/domainbuy_copy.go
@@ -15,7 +15,9 @@ import (
// docs/superpowers/specs/LUNA-COPY-RESULT-DOMAINS-1.md, plus controller rulings
// on four flags. Apply later edits through a copy pass.
var domainBuyCopy = map[string]string{
- "plan": capMessage("cli.cap.custom_domain"), // Existing approved plan refusal.
+ // Draft for the Luna pass: round 1 confirmed-price refusal.
+ "priceChanged": "the price changed. confirm the new price to continue",
+ "plan": capMessage("cli.cap.custom_domain"), // Existing approved plan refusal.
// Approved by delegation (Luna), 2026-11-03: domain registration Plan 2, slice 1.
"billingSetup": "we could not set up billing for your account. try again later",
"currency": "we could not find a price for this domain in your account currency",
diff --git a/internal/console/domainbuy_final_fix_test.go b/internal/console/domainbuy_final_fix_test.go
index c4f43d1f0..41e17d286 100644
--- a/internal/console/domainbuy_final_fix_test.go
+++ b/internal/console/domainbuy_final_fix_test.go
@@ -66,7 +66,7 @@ func TestOwnLivePurchaseResumes(t *testing.T) {
}
f.srv.cfg.DomainCatalog.DailyCap = 1
before := len(f.fake.Sent)
- status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"SHOP.COM.","app":"kass"}`)
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"SHOP.COM.","app":"kass","currency":"usd","price":1500}`)
var got struct {
ID string
State PurchaseState
@@ -88,11 +88,11 @@ func TestOwnLivePurchaseResumes(t *testing.T) {
func TestOwnLostCheckoutResumes(t *testing.T) {
f := newPurchaseFixture(t)
f.fake.LoseNextResponse = true
- p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
+ p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
if p == nil {
t.Fatal("missing journal")
}
- status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass"}`)
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass","currency":"usd","price":1500}`)
if status != 200 || !strings.Contains(body, p.ID) || !strings.Contains(body, `"checkout_url":"https://`) {
t.Fatalf("resume: %d %s", status, body)
}
@@ -125,7 +125,7 @@ func TestCheckoutCancelPageOffersContinue(t *testing.T) {
if status != 200 || !strings.Contains(body, `href="`+info.URL+`"`) || !strings.Contains(body, ">continue to payment</a>") {
t.Fatalf("missing continue link: status=%d", status)
}
- values := url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}}
+ values := url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}, "currency": {"usd"}, "price": {"1500"}}
status, loc, _ := postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/buy", values)
if status != 303 || loc != info.URL {
t.Fatalf("browser resume: %d %s", status, loc)
@@ -291,7 +291,7 @@ func TestPurchaseRefusalAlertsRateLimited(t *testing.T) {
alerts := 0
pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil }
for _, name := range []string{"shop.com", "other.com", "shop.net", "shop.com"} {
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", name, purchaseContact(), "buyer")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", name, purchaseContact(), "buyer")
if ref == nil || ref.Status != 503 {
t.Fatalf("refusal: %+v", ref)
}
diff --git a/internal/console/domainbuy_fix_test.go b/internal/console/domainbuy_fix_test.go
index fafcfc2cb..cc5207f2f 100644
--- a/internal/console/domainbuy_fix_test.go
+++ b/internal/console/domainbuy_fix_test.go
@@ -255,7 +255,7 @@ func TestHeldElsewhereLogsNoAlert(t *testing.T) {
old := log.Writer()
log.SetOutput(&logs)
defer log.SetOutput(old)
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
if ref == nil || ref.Status != 409 {
t.Fatalf("refusal: %+v", ref)
}
diff --git a/internal/console/domainbuy_nosub_test.go b/internal/console/domainbuy_nosub_test.go
index 70443332b..df84aca35 100644
--- a/internal/console/domainbuy_nosub_test.go
+++ b/internal/console/domainbuy_nosub_test.go
@@ -17,7 +17,8 @@ import (
func firstPurchaseAccount(t *testing.T, f *purchaseFixture) {
t.Helper()
f.acct = planAccount(t, f.consoleFixture, 503)
- if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, nil, "test", "operator", time.Now()); err != nil {
+ sponsored := sponsorUnlimited()
+ if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil {
t.Fatal(err)
}
if _, err := f.st.CreateAppIn(f.acct.ID, "kass", "buyer@example.test", time.Now()); err != nil {
@@ -35,7 +36,7 @@ func TestPurchaseWithoutSubscription(t *testing.T) {
firstPurchaseAccount(t, f)
c := purchaseContact()
c.Country = country
- p, link, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test")
+ p, link, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test")
if ref != nil || p == nil || link == "" {
t.Fatalf("start: %+v %q %+v", p, link, ref)
}
@@ -79,7 +80,7 @@ func TestPurchaseConcurrentFirstCustomer(t *testing.T) {
wg.Add(1)
go func() {
defer wg.Done()
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test")
errs <- ref
}()
}
@@ -120,7 +121,7 @@ func TestPurchaseOwnStateReasons(t *testing.T) {
if reason == "daily" {
name = "second.com"
}
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test")
if ref == nil || ref.Msg == domainBuyCopy["unavailable"] || strings.TrimSpace(ref.Msg) == "" {
t.Fatalf("%s: %+v", reason, ref)
}
@@ -152,7 +153,7 @@ func TestPurchaseWithoutSubscriptionRefusalsHaveNoCustomer(t *testing.T) {
case "balance":
f.reg.BalanceMoney.Minor = 0
}
- p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test")
+ p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test")
if p != nil || ref == nil {
t.Fatalf("expected refusal: %+v %+v", p, ref)
}
@@ -173,7 +174,7 @@ func TestPurchaseKeepsFirstCurrency(t *testing.T) {
f.reg.Available["second.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}}
c := purchaseContact()
c.Country = "GB"
- p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "second.com", c, "buyer@example.test")
+ p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "second.com", c, "buyer@example.test")
if ref != nil || p == nil || p.Currency != first.Currency || p.Amount != first.Amount {
t.Fatalf("currency moved: %+v %+v %+v", first, p, ref)
}
@@ -191,7 +192,7 @@ func TestPurchaseAndCardShareCustomer(t *testing.T) {
refs := make(chan *doorRefusal, 1)
go func() {
defer wg.Done()
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
refs <- ref
}()
go func() {
diff --git a/internal/console/domainbuy_registry_test.go b/internal/console/domainbuy_registry_test.go
index 7bcf05ae3..9a70eb2f1 100644
--- a/internal/console/domainbuy_registry_test.go
+++ b/internal/console/domainbuy_registry_test.go
@@ -38,7 +38,7 @@ func TestPurchaseRegistryErrors(t *testing.T) {
alerts := 0
pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil }
for i := 0; i < 2; i++ {
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
if ref == nil || ref.Msg != domainBuyCopy["unavailable"] {
t.Fatalf("refusal: %+v", ref)
}
diff --git a/internal/console/domainbuy_round1_test.go b/internal/console/domainbuy_round1_test.go
new file mode 100644
index 000000000..6d2e4567c
--- /dev/null
+++ b/internal/console/domainbuy_round1_test.go
@@ -0,0 +1,278 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+func TestPurchaseCheckUsesSavedCountry(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil {
+ t.Fatal(err)
+ }
+ tok := buyToken(t, f)
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"shop.com"}`)
+ var q struct {
+ Currency string
+ Price int64
+ }
+ if err := json.Unmarshal([]byte(body), &q); err != nil {
+ t.Fatal(err)
+ }
+ if status != 200 || q.Currency != "eur" || q.Price != 1600 {
+ t.Fatalf("check: %d %s", status, body)
+ }
+ status, body = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass","currency":"eur","price":1600}`)
+ if status != 200 {
+ t.Fatalf("purchase: %d %s", status, body)
+ }
+ var out struct{ ID string }
+ if err := json.Unmarshal([]byte(body), &out); err != nil {
+ t.Fatal(err)
+ }
+ p := f.read(t, out.ID)
+ if p.Currency != q.Currency || p.Amount != q.Price {
+ t.Fatalf("charged %+v after quote %+v", p, q)
+ }
+ var checkout struct {
+ Request billing.PaymentCheckoutRequest
+ }
+ if err := json.Unmarshal(p.CheckoutPrepared.Body, &checkout); err != nil {
+ t.Fatal(err)
+ }
+ if checkout.Request.Currency != q.Currency || checkout.Request.Amount != q.Price {
+ t.Fatalf("checkout differs from confirmation: %+v", checkout.Request)
+ }
+ b, err := f.st.BillingAccount(f.acct.ID)
+ if err != nil || b.Currency != "eur" || f.sent(billing.PreparedCustomer) != 1 {
+ t.Fatalf("billing: %+v %v", b, err)
+ }
+}
+
+func TestPurchaseConfirmedPriceMismatch(t *testing.T) {
+ for _, fields := range []string{`"currency":"usd","price":1500`, `"currency":"eur","price":1599`, `"currency":"usd","price":1600`, `"currency":"eur"`, `"price":1600`, `"currency":"eur","price":0`} {
+ t.Run(fields, func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ f.reg.BalanceMoney.Minor = 0 // A changed price must refuse before balance alerts or billing.
+ if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil {
+ t.Fatal(err)
+ }
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass",`+fields+`}`)
+ var out struct {
+ Code, Currency string
+ Price int64
+ }
+ if err := json.Unmarshal([]byte(body), &out); err != nil {
+ t.Fatal(err)
+ }
+ if status != 409 || out.Code != "price_changed" || out.Currency != "eur" || out.Price != 1600 {
+ t.Fatalf("refusal: %d %s", status, body)
+ }
+ assertNoPurchaseEffects(t, f)
+ })
+ }
+}
+
+func assertNoPurchaseEffects(t *testing.T, f *purchaseFixture) {
+ t.Helper()
+ b, err := f.st.BillingAccount(f.acct.ID)
+ if err != nil || b != nil {
+ t.Fatalf("wrote billing: %+v %v", b, err)
+ }
+ var count int
+ if err := f.st.db.QueryRow(`SELECT count(*) FROM domain_purchases WHERE account_id=?`, f.acct.ID).Scan(&count); err != nil || count != 0 {
+ t.Fatalf("purchase count=%d err=%v", count, err)
+ }
+ if f.sent(billing.PreparedCustomer) != 0 || f.sent(billing.PreparedPaymentCheckout) != 0 || purchaseCalls(f.reg.Calls, "contact:") != 0 {
+ t.Fatal("refusal made provider writes")
+ }
+}
+
+func TestBrowserBuyConfirmedPrice(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil {
+ t.Fatal(err)
+ }
+ c := newBrowser(t)
+ f.setUser("owner" + f.acct.Sqid + "@example.com")
+ signUp(t, f.consoleFixture, c, "price-browser")
+ base := f.ts.URL + "/a/" + f.acct.Sqid + "/apps/kass/domains"
+ values := url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}}
+ status, _, body := postForm(t, c, base+"/check", values)
+ if status != 200 || !strings.Contains(body, `name="currency" value="eur"`) || !strings.Contains(body, `name="price" value="1600"`) {
+ t.Fatalf("confirm: %d %s", status, body)
+ }
+ contact := purchaseContact()
+ contact.Country = "GB"
+ for _, field := range buyContactFields(contact) {
+ values.Set(field.Name, field.Value)
+ }
+ values.Set("currency", "eur")
+ values.Set("price", "1600")
+ status, _, body = postForm(t, c, base+"/buy", values)
+ if status != 409 || !strings.Contains(body, `name="currency" value="gbp"`) || !strings.Contains(body, `name="price" value="1700"`) || !strings.Contains(body, `name="Country" value="GB"`) {
+ t.Fatalf("new confirmation: %d %s", status, body)
+ }
+ assertNoPurchaseEffects(t, f)
+ values.Set("currency", "gbp")
+ values.Set("price", "1700")
+ status, loc, _ := postForm(t, c, base+"/buy", values)
+ if status != 303 || !strings.HasPrefix(loc, "https://checkout.example.test/") {
+ t.Fatalf("confirmed: %d %s", status, loc)
+ }
+}
+
+func TestPurchaseSponsoredLimitsStillGate(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ partial := plans.Limits{RunningThings: 40}
+ if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, &partial, "test", "operator", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.srv.checkCustomDomains(f.acct); !isPlanCap(err) {
+ t.Fatalf("partial sponsorship allowed domains: %v", err)
+ }
+}
+
+func TestPaymentCustomerFailureDoesNotFixCurrency(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ f.fake.Err = billing.ErrRefused
+ h, release, err := f.srv.holdBilling(f.acct)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer release()
+ if _, err := f.srv.paymentCustomerLocked(h, f.srv.billingClock(context.Background()), f.acct, "IE", "D01 A123", true); err == nil {
+ t.Fatal("expected customer failure")
+ }
+ b, err := f.st.BillingAccount(f.acct.ID)
+ if err != nil || (b != nil && (b.Currency != "" || b.Customer != "")) {
+ t.Fatalf("failed customer fixed currency: %+v %v", b, err)
+ }
+}
+
+func TestPaymentCustomerCurrencyBoundAtomically(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ // A persisted currency with no customer is forbidden, even between writes.
+ for _, event := range []string{"INSERT", "UPDATE"} {
+ _, err := f.st.db.Exec(fmt.Sprintf(`CREATE TRIGGER test_currency_%s BEFORE %s ON billing_accounts WHEN NEW.currency != '' AND NEW.customer = '' BEGIN SELECT RAISE(ABORT, 'currency before customer'); END`, event, event))
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ h, release, err := f.srv.holdBilling(f.acct)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer release()
+ b, err := f.srv.paymentCustomerLocked(h, f.srv.billingClock(context.Background()), f.acct, "IE", "D01 A123", true)
+ if err != nil || b.Customer == "" || b.Currency != "eur" {
+ t.Fatalf("customer/currency: %+v %v", b, err)
+ }
+}
+
+func TestBillingAddCardRequiresDomainBuying(t *testing.T) {
+ for _, mode := range []string{"enabled", "disabled", "free", "partial"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ switch mode {
+ case "disabled":
+ f.srv.cfg.DomainCatalog = nil
+ case "free":
+ if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ case "partial":
+ partial := plans.Limits{RunningThings: 40}
+ if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, &partial, "test", "operator", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ c := newBrowser(t)
+ f.setUser("owner" + f.acct.Sqid + "@example.com")
+ signUp(t, f.consoleFixture, c, "card-visibility")
+ status, _, body := get(t, c, f.ts.URL+billingPagePath(f.acct.Sqid))
+ want := mode == "enabled"
+ if status != 200 || strings.Contains(body, "/billing/card") != want || strings.Contains(body, billingCopy["card.hint"]) != want {
+ t.Fatalf("mode=%s status=%d card=%t", mode, status, strings.Contains(body, "/billing/card"))
+ }
+ })
+ }
+}
+
+// Run a competing billing action between admission and the purchase's hold.
+type currencyChangeRegistrar struct {
+ registrar.Registrar
+ change func()
+}
+
+func (r currencyChangeRegistrar) Check(ctx context.Context, name string) (registrar.Availability, error) {
+ r.change()
+ return r.Registrar.Check(ctx, name)
+}
+func TestPurchaseConfirmsCurrencyUnderBillingHold(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil {
+ t.Fatal(err)
+ }
+ f.srv.cfg.Registrar = currencyChangeRegistrar{f.reg, func() {
+ h, release, err := f.srv.holdBilling(f.acct)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer release()
+ _, err = f.srv.paymentCustomerLocked(h, f.srv.billingClock(context.Background()), f.acct, "US", "10001", true)
+ if err != nil {
+ t.Error(err)
+ }
+ }}
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass","currency":"eur","price":1600}`)
+ if status != 409 || !strings.Contains(body, `"currency":"usd"`) || !strings.Contains(body, `"price":1500`) {
+ t.Fatalf("race: %d %s", status, body)
+ }
+ if f.sent(billing.PreparedCustomer) != 1 || f.sent(billing.PreparedPaymentCheckout) != 0 {
+ t.Fatal("purchase did provider writes after concurrent customer creation")
+ }
+ b, err := f.st.BillingAccount(f.acct.ID)
+ if err != nil || b.Currency != "usd" {
+ t.Fatalf("changed concurrent currency: %+v %v", b, err)
+ }
+}
+
+func TestPurchaseCheckDefaultAndFixedCurrency(t *testing.T) {
+ for _, fixed := range []bool{false, true} {
+ t.Run(fmt.Sprint(fixed), func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ firstPurchaseAccount(t, f)
+ if fixed {
+ if err := f.st.SetBillingCustomer(f.acct.ID, "cus_fixed", time.Now(), "usd"); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", buyToken(t, f), `{"name":"shop.com"}`)
+ if status != 200 || !strings.Contains(body, `"currency":"usd"`) || !strings.Contains(body, `"price":1500`) {
+ t.Fatalf("check: %d %s", status, body)
+ }
+ })
+ }
+}
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go
index 34777a145..f123319ec 100644
--- a/internal/console/domainbuy_test.go
+++ b/internal/console/domainbuy_test.go
@@ -63,7 +63,7 @@ func purchaseContact() registrar.Contact {
}
func (f *purchaseFixture) start(t *testing.T) *DomainPurchase {
t.Helper()
- p, url, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ p, url, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
if ref != nil || p == nil || url == "" {
t.Fatalf("start: %+v %q %+v", p, url, ref)
}
@@ -228,7 +228,7 @@ func TestStartRefusesClaimHeldElsewhereBeforePayment(t *testing.T) {
if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: host, Account: "foreign", App: "other", CreatedBy: "other"}); err != nil {
t.Fatal(err)
}
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
want := claimRefusal(host, domains.ErrHostUnavailable)
if ref == nil || *ref != *want || f.sent(billing.PreparedPaymentCheckout) != 0 {
t.Fatalf("refusal: %+v", ref)
@@ -241,7 +241,7 @@ func TestStartRefusesFreePlan(t *testing.T) {
if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil {
t.Fatal(err)
}
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
if ref == nil || f.sent(billing.PreparedPaymentCheckout) != 0 {
t.Fatal("free plan bought domain")
}
@@ -252,7 +252,7 @@ func TestStartRefusesOverDailyCap(t *testing.T) {
if err := f.st.CreateDomainPurchase(DomainPurchase{AccountID: f.acct.ID, Domain: "earlier.com", App: "kass", State: PurchaseExpired}); err != nil {
t.Fatal(err)
}
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
if ref == nil || f.sent(billing.PreparedPaymentCheckout) != 0 {
t.Fatal("cap bypassed")
}
@@ -262,7 +262,7 @@ func TestStartRefusesLowRegistrarBalance(t *testing.T) {
alerts := 0
pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil }
f.reg.BalanceMoney.Minor = 1
- _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
+ _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer")
if ref == nil || ref.Msg != "buying domains is unavailable right now" || f.sent(billing.PreparedPaymentCheckout) != 0 || alerts != 1 {
t.Fatalf("balance refusal: %+v", ref)
}
@@ -381,7 +381,7 @@ func setupClaimPurchase(t *testing.T, cx *claimCase) {
func TestPurchaseCheckoutLostResponseReplaysStoredRequest(t *testing.T) {
f := newPurchaseFixture(t)
f.fake.LoseNextResponse = true
- p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
if p == nil || ref == nil {
t.Fatalf("lost checkout response: %+v %+v", p, ref)
}
@@ -403,7 +403,7 @@ func TestPurchaseCheckoutLostResponseReplaysStoredRequest(t *testing.T) {
func TestPurchaseCheckoutUnknownPastExpiryStaysLive(t *testing.T) {
f := newPurchaseFixture(t)
f.fake.LoseNextResponse = true
- p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
if p == nil {
t.Fatal("missing pending purchase")
}
@@ -674,11 +674,11 @@ func TestPurchaseHappyPathWithClaimSQLGate(t *testing.T) {
cx.srv.cfg.DomainCatalog = &domainreg.Catalog{Version: "test", DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}}
cx.srv.billing.ready.Store(true)
f := &purchaseFixture{billingFixture: bf, reg: reg, zone: zone}
- p, _, ref := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test")
+ p, _, ref := startQuotedPurchase(f.srv, context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test")
if ref != nil || p == nil {
t.Fatalf("start: %+v", ref)
}
- resumed, checkout, duplicate := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test")
+ resumed, checkout, duplicate := startQuotedPurchase(f.srv, context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test")
if duplicate != nil || resumed == nil || resumed.ID != p.ID || checkout == "" || f.sent(billing.PreparedPaymentCheckout) != 1 {
t.Fatalf("resume: %+v %q %+v", resumed, checkout, duplicate)
}
@@ -817,7 +817,7 @@ func TestRegisteringAlertsOperatorAfterAnHour(t *testing.T) {
func TestCheckoutCreateRefusedFailsAtOnce(t *testing.T) {
f := newPurchaseFixture(t)
f.fake.BeforeSend = func(billing.Prepared) error { return billing.ErrRefused }
- p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
if p == nil || ref == nil {
t.Fatal("expected refused create")
}
@@ -866,7 +866,7 @@ func TestStepErrorsAreReturnedAndLogged(t *testing.T) {
func TestLostCheckoutCreateExpiresWhenNoneListed(t *testing.T) {
f := newPurchaseFixture(t)
f.fake.Err = billing.ErrIndeterminate
- p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
if p == nil {
t.Fatal("missing purchase")
}
@@ -891,7 +891,7 @@ func TestLostCheckoutCreateExpiresWhenNoneListed(t *testing.T) {
func TestLostCheckoutCreateAdoptsListedSession(t *testing.T) {
f := newPurchaseFixture(t)
f.fake.LoseNextResponse = true
- p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
+ p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test")
if p == nil || p.CheckoutSession != "" {
t.Fatal("expected lost response")
}
@@ -1000,3 +1000,16 @@ func TestPurchaseRereadsJournalInsideOperation(t *testing.T) {
t.Fatalf("purchase=%+v error=%v", fresh, err)
}
}
+
+func startQuotedPurchase(s *Server, ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) {
+ currency, _ := s.billing.cfg.Book.ChooseCurrency("", c.Country)
+ if b, _ := s.store.BillingAccount(acct.ID); b != nil && b.Currency != "" {
+ currency = b.Currency
+ }
+ q := domainreg.Quote{Currency: currency, Price: s.cfg.DomainCatalog.TLDs["com"].Register[currency]}
+ if own, _ := s.ownLiveDomainPurchase(ctx, acct.ID, name); own != nil {
+ q.Currency, q.Price = own.Currency, own.Amount
+ }
+ p, link, _, ref := s.startDomainPurchase(ctx, acct, app, name, c, principal, q)
+ return p, link, ref
+}
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go
index cb1f788fd..412745eee 100644
--- a/internal/console/plancaps.go
+++ b/internal/console/plancaps.go
@@ -211,9 +211,6 @@ func (s *Server) checkFleets(acct *Account) error {
// checkCustomDomains refuses a custom domain on a plan without them.
// Platform hostnames are not custom domains; callers check those first.
func (s *Server) checkCustomDomains(acct *Account) error {
- if sponsored, err := s.planSponsored(acct); err != nil || sponsored {
- return err
- }
l, err := s.EffectiveLimits(acct)
if err != nil || l == nil || l.CustomDomains {
return err
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html
index 323356fdc..0831c6295 100644
--- a/internal/console/templates/domain_buy.html
+++ b/internal/console/templates/domain_buy.html
@@ -29,6 +29,7 @@
})();
</script>
{{else if .Quote}}
+{{if .PriceChanged}}<p role="alert">{{$.DomainBuyCopy.priceChanged}}</p>{{end}}
<p>{{$.DomainBuyCopy.name}}: <strong>{{.Quote.Domain}}</strong></p>
<p>{{$.DomainBuyCopy.quote}}: {{.Price}}</p>
<p class="small">{{$.DomainBuyCopy.paymentDetails}}</p>
@@ -38,6 +39,8 @@
<form method="post" action="{{.Base}}/buy">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="name" value="{{.Quote.Domain}}">
+ <input type="hidden" name="currency" value="{{.Quote.Currency}}">
+ <input type="hidden" name="price" value="{{.Quote.Price}}">
{{range .Fields}}
<p><label for="buy-{{.Name}}">{{.Label}}</label>
<input id="buy-{{.Name}}" name="{{.Name}}" value="{{.Value}}" {{if .Required}}required{{end}}></p>
diff --git a/internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv b/internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv
index 2cb216230..08dea4404 100644
--- a/internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv
+++ b/internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv
@@ -1,4 +1,4 @@
# Census overlay domains-buy-nosub, written by census-propose (#369). census-ruling-domains-buy-nosub, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-domains-buy-nosub.md.
# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-@coverage . 0b97f970046b7ed1ca4044e16dfb658bc013cd5120dce1cd8572d6e6b7ab5993
+@coverage . 0b36c7aecfa58a4d48d41a08d38167f0ac8417f966432828463faeb85b4b804f
@coverage internal/registrar 438f7149d09aa6a151338c68bfe428f704a09628f56e942b8fd4de8cebadd932