carlos / platform Public

console: domain purchase, registration and contact tables

Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 5426b1d5a4b42282eeb1e9d65d31fc09d2c1aba9 parent a589906
5 files changed, +551 −1
  • internal/console/claim_invariant_test.go +2 −0
  • internal/console/domainstore.go +261 −0
  • internal/console/domainstore_test.go +280 −0
  • internal/console/store.go +4 −1
  • internal/console/store_gate.go +4 −0
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index 6ebdb3d34..53756fbad 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -190,6 +190,8 @@ var claimWriterReasons = map[string]string{
"the only code that puts versioned objects, and its own versioned callers are the db door's reads and the purge sweep's DeleteVersion",
"versioned/CopyVersion": "no console door calls it: only internal/park (archive copies) and internal/hostbox call CopyVersion, " +
"and the console imports neither",
+ "sql/domain_purchases": "domain registration Plan 1 Task 6 adds the store before Tasks 7-8 add its engine and buy door; " +
+ "no route or worker writes it yet; TestDomainPurchaseClaimGate pins refusal without a permit and success under the app permit; replace this reason with door coverage when the buy door is added",
"sql/owners": "legacy per-app grants, written only by cmd/console's operator grant and revoke verbs " +
"(Store.GrantAt and Revoke); enabled operator DBs are guarded too and refuse these unbound legacy grants; no route or worker writes them",
"sql/mail_counts": "retired by the senders migration: nothing writes it, the one-shot backfill only reads it, " +
diff --git a/internal/console/domainstore.go b/internal/console/domainstore.go
new file mode 100644
index 000000000..e332e78c5
--- /dev/null
+++ b/internal/console/domainstore.go
@@ -0,0 +1,261 @@
+package console
+
+import (
+ "crypto/rand"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+type PurchaseState string
+
+const (
+ PurchaseAwaitingPayment PurchaseState = "awaiting_payment"
+ PurchaseAuthorised PurchaseState = "authorised"
+ PurchaseZoneReady PurchaseState = "zone_ready"
+ PurchaseRegistering PurchaseState = "registering"
+ PurchaseRegistered PurchaseState = "registered"
+ PurchaseCaptured PurchaseState = "captured"
+ PurchaseDone PurchaseState = "done"
+ PurchaseFailed PurchaseState = "failed"
+ PurchaseExpired PurchaseState = "expired"
+ PurchaseUnpaid PurchaseState = "unpaid"
+)
+
+var (
+ ErrDomainPurchaseLive = errors.New("console: live domain purchase exists")
+ ErrPurchaseStateMoved = errors.New("console: domain purchase state moved")
+)
+
+type DomainPurchase struct {
+ ID string
+ AccountID int64
+ Domain, App, Currency string
+ Amount int64
+ State PurchaseState
+ Reason string
+ CheckoutSession, PaymentIntent, ZoneID, RegistrarID string
+ Attempts int
+ CheckoutExpires, CreatedAt, UpdatedAt time.Time
+}
+
+type DomainRegistration struct {
+ Domain string
+ AccountID int64
+ RegistrarID, ZoneID string
+ Expires time.Time
+ AutoRenew bool
+ CreatedAt time.Time
+}
+
+const liveDomainPurchaseSQL = `state NOT IN ('done','failed','expired','unpaid')`
+
+func (s *Store) migrateDomains() error {
+ _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS domain_contacts (
+ account_id INTEGER PRIMARY KEY,
+ contact TEXT NOT NULL,
+ handle TEXT NOT NULL DEFAULT '',
+ updated_at INTEGER NOT NULL
+);
+CREATE TABLE IF NOT EXISTS domain_purchases (
+ id TEXT PRIMARY KEY,
+ account_id INTEGER NOT NULL,
+ domain TEXT NOT NULL,
+ app TEXT NOT NULL,
+ currency TEXT NOT NULL,
+ amount INTEGER NOT NULL,
+ state TEXT NOT NULL,
+ reason TEXT NOT NULL DEFAULT '',
+ checkout_session TEXT NOT NULL DEFAULT '',
+ payment_intent TEXT NOT NULL DEFAULT '',
+ zone_id TEXT NOT NULL DEFAULT '',
+ registrar_id TEXT NOT NULL DEFAULT '',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ checkout_expires INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+CREATE UNIQUE INDEX IF NOT EXISTS domain_purchases_live_domain ON domain_purchases(domain)
+ WHERE ` + liveDomainPurchaseSQL + `;
+CREATE INDEX IF NOT EXISTS domain_purchases_account_created ON domain_purchases(account_id, created_at);
+CREATE TABLE IF NOT EXISTS domain_registrations (
+ domain TEXT PRIMARY KEY,
+ account_id INTEGER NOT NULL,
+ registrar_id TEXT NOT NULL,
+ zone_id TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ auto_renew INTEGER NOT NULL DEFAULT 1,
+ created_at INTEGER NOT NULL
+);`)
+ return err
+}
+
+func newDomainPurchaseID() string {
+ var b [8]byte
+ _, _ = rand.Read(b[:])
+ return "dp_" + hex.EncodeToString(b[:])
+}
+
+const domainPurchaseColumns = `id, account_id, domain, app, currency, amount, state, reason,
+ checkout_session, payment_intent, zone_id, registrar_id, attempts, checkout_expires, created_at, updated_at`
+
+func (s *Store) CreateDomainPurchase(p DomainPurchase) error {
+ if p.ID == "" {
+ p.ID = newDomainPurchaseID()
+ }
+ if p.State == "" {
+ p.State = PurchaseAwaitingPayment
+ }
+ now := time.Now().UTC()
+ if p.CreatedAt.IsZero() {
+ p.CreatedAt = now
+ }
+ if p.UpdatedAt.IsZero() {
+ p.UpdatedAt = now
+ }
+ res, err := s.db.Exec(`INSERT INTO domain_purchases (`+domainPurchaseColumns+`)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(domain) WHERE `+liveDomainPurchaseSQL+` DO NOTHING`,
+ p.ID, p.AccountID, p.Domain, p.App, p.Currency, p.Amount, p.State, p.Reason,
+ p.CheckoutSession, p.PaymentIntent, p.ZoneID, p.RegistrarID, p.Attempts,
+ domainUnix(p.CheckoutExpires), p.CreatedAt.Unix(), p.UpdatedAt.Unix())
+ if err != nil {
+ return err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return ErrDomainPurchaseLive
+ }
+ return nil
+}
+
+func scanDomainPurchase(sc interface{ Scan(...any) error }) (*DomainPurchase, error) {
+ var p DomainPurchase
+ var expires, created, updated int64
+ if err := sc.Scan(&p.ID, &p.AccountID, &p.Domain, &p.App, &p.Currency, &p.Amount, &p.State, &p.Reason,
+ &p.CheckoutSession, &p.PaymentIntent, &p.ZoneID, &p.RegistrarID, &p.Attempts,
+ &expires, &created, &updated); err != nil {
+ return nil, err
+ }
+ if expires != 0 {
+ p.CheckoutExpires = time.Unix(expires, 0).UTC()
+ }
+ p.CreatedAt, p.UpdatedAt = time.Unix(created, 0).UTC(), time.Unix(updated, 0).UTC()
+ return &p, nil
+}
+
+func (s *Store) DomainPurchase(id string) (*DomainPurchase, error) {
+ p, err := scanDomainPurchase(s.db.QueryRow(`SELECT `+domainPurchaseColumns+` FROM domain_purchases WHERE id = ?`, id))
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return p, err
+}
+
+func (s *Store) AdvanceDomainPurchase(id string, from, to PurchaseState, set func(*DomainPurchase)) error {
+ p, err := s.DomainPurchase(id)
+ if err != nil {
+ return err
+ }
+ if p == nil || p.State != from {
+ return ErrPurchaseStateMoved
+ }
+ if set != nil {
+ set(p)
+ }
+ p.State, p.UpdatedAt = to, time.Now().UTC()
+ res, err := s.db.Exec(`UPDATE domain_purchases SET
+ account_id = ?, domain = ?, app = ?, currency = ?, amount = ?, state = ?, reason = ?,
+ checkout_session = ?, payment_intent = ?, zone_id = ?, registrar_id = ?, attempts = ?,
+ checkout_expires = ?, created_at = ?, updated_at = ? WHERE id = ? AND state = ?`,
+ p.AccountID, p.Domain, p.App, p.Currency, p.Amount, p.State, p.Reason,
+ p.CheckoutSession, p.PaymentIntent, p.ZoneID, p.RegistrarID, p.Attempts,
+ domainUnix(p.CheckoutExpires), p.CreatedAt.Unix(), p.UpdatedAt.Unix(), id, from)
+ if err != nil {
+ return err
+ }
+ n, err := res.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n == 0 {
+ return ErrPurchaseStateMoved
+ }
+ return nil
+}
+
+func (s *Store) LiveDomainPurchases() ([]DomainPurchase, error) {
+ rows, err := s.db.Query(`SELECT ` + domainPurchaseColumns + ` FROM domain_purchases WHERE ` + liveDomainPurchaseSQL + ` ORDER BY created_at, id`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []DomainPurchase
+ for rows.Next() {
+ p, err := scanDomainPurchase(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *p)
+ }
+ return out, rows.Err()
+}
+
+func (s *Store) PurchasesToday(accountID int64, now time.Time) (int, error) {
+ now = now.UTC()
+ start := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC)
+ var n int
+ err := s.db.QueryRow(`SELECT COUNT(*) FROM domain_purchases WHERE account_id = ? AND created_at >= ? AND created_at < ?`,
+ accountID, start.Unix(), start.Add(24*time.Hour).Unix()).Scan(&n)
+ return n, err
+}
+
+func (s *Store) DomainContact(accountID int64) (registrar.Contact, string, error) {
+ var c registrar.Contact
+ var contact, handle string
+ err := s.db.QueryRow(`SELECT contact, handle FROM domain_contacts WHERE account_id = ?`, accountID).Scan(&contact, &handle)
+ if errors.Is(err, sql.ErrNoRows) {
+ return c, "", nil
+ }
+ if err != nil {
+ return c, "", err
+ }
+ if err := json.Unmarshal([]byte(contact), &c); err != nil {
+ return registrar.Contact{}, "", err
+ }
+ return c, handle, nil
+}
+
+func (s *Store) SetDomainContact(accountID int64, c registrar.Contact, handle string) error {
+ contact, err := json.Marshal(c)
+ if err != nil {
+ return err
+ }
+ _, err = s.db.Exec(`INSERT INTO domain_contacts (account_id, contact, handle, updated_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT(account_id) DO UPDATE SET contact = excluded.contact, handle = excluded.handle, updated_at = excluded.updated_at`,
+ accountID, string(contact), handle, time.Now().Unix())
+ return err
+}
+
+func (s *Store) AddDomainRegistration(r DomainRegistration) error {
+ if r.CreatedAt.IsZero() {
+ r.CreatedAt = time.Now().UTC()
+ }
+ _, err := s.db.Exec(`INSERT INTO domain_registrations (domain, account_id, registrar_id, zone_id, expires_at, auto_renew, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, r.Domain, r.AccountID, r.RegistrarID, r.ZoneID, domainUnix(r.Expires), r.AutoRenew, r.CreatedAt.Unix())
+ return err
+}
+
+func domainUnix(t time.Time) int64 {
+ if t.IsZero() {
+ return 0
+ }
+ return t.Unix()
+}
diff --git a/internal/console/domainstore_test.go b/internal/console/domainstore_test.go
new file mode 100644
index 000000000..ccc3e6bf9
--- /dev/null
+++ b/internal/console/domainstore_test.go
@@ -0,0 +1,280 @@
+package console
+
+import (
+ "database/sql"
+ "errors"
+ "fmt"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+func TestOnlyOneLivePurchasePerDomain(t *testing.T) {
+ for _, terminal := range []PurchaseState{PurchaseFailed, PurchaseDone, PurchaseExpired, PurchaseUnpaid} {
+ t.Run(string(terminal), func(t *testing.T) {
+ s := openTestStore(t)
+ first := DomainPurchase{ID: "dp_0000000000000001", AccountID: 1, Domain: "shop.example", State: PurchaseAwaitingPayment}
+ if err := s.CreateDomainPurchase(first); err != nil {
+ t.Fatal(err)
+ }
+ second := first
+ second.ID, second.AccountID = "dp_0000000000000002", 2
+ if err := s.CreateDomainPurchase(second); !errors.Is(err, ErrDomainPurchaseLive) {
+ t.Fatalf("second create: %v", err)
+ }
+ if err := s.AdvanceDomainPurchase(first.ID, first.State, terminal, nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.CreateDomainPurchase(second); err != nil {
+ t.Fatal(err)
+ }
+ live, err := s.LiveDomainPurchases()
+ if err != nil || len(live) != 1 || live[0].ID != second.ID {
+ t.Fatalf("live = %+v, %v", live, err)
+ }
+ second.Domain = "other.example"
+ if err := s.CreateDomainPurchase(second); err == nil || errors.Is(err, ErrDomainPurchaseLive) {
+ t.Fatalf("duplicate ID misclassified: %v", err)
+ }
+ })
+ }
+}
+
+func TestAdvanceIsCompareAndSet(t *testing.T) {
+ s := openTestStore(t)
+ p := DomainPurchase{ID: "dp_0000000000000001", AccountID: 123, Domain: "shop.example", App: "shop", Currency: "eur", Amount: 1500,
+ State: PurchaseAwaitingPayment, CheckoutSession: "cs_1", CheckoutExpires: time.Now().UTC().Add(time.Hour).Truncate(time.Second)}
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.AdvanceDomainPurchase(p.ID, p.State, PurchaseAuthorised, func(row *DomainPurchase) {
+ row.PaymentIntent, row.ZoneID, row.RegistrarID, row.Reason = "pi_1", "zone_1", "reg_1", "authorised"
+ row.Attempts++
+ }); err != nil {
+ t.Fatal(err)
+ }
+ before, err := s.DomainPurchase(p.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if before.State != PurchaseAuthorised || before.PaymentIntent != "pi_1" || before.ZoneID != "zone_1" || before.RegistrarID != "reg_1" || before.Reason != "authorised" || before.Attempts != 1 || before.Amount != p.Amount || before.AccountID != p.AccountID || before.App != p.App || before.Currency != p.Currency || before.CheckoutSession != p.CheckoutSession || !before.CheckoutExpires.Equal(p.CheckoutExpires) || before.CreatedAt.IsZero() || before.UpdatedAt.IsZero() {
+ t.Fatalf("round trip: %+v", before)
+ }
+ called := false
+ if err := s.AdvanceDomainPurchase(p.ID, p.State, PurchaseFailed, func(row *DomainPurchase) { called = true; row.Reason = "stale" }); !errors.Is(err, ErrPurchaseStateMoved) {
+ t.Fatalf("stale advance: %v", err)
+ }
+ after, err := s.DomainPurchase(p.ID)
+ if err != nil || called || !reflect.DeepEqual(before, after) {
+ t.Fatalf("stale update changed row: before=%+v after=%+v called=%v err=%v", before, after, called, err)
+ }
+ if err := s.AdvanceDomainPurchase("missing", p.State, PurchaseFailed, nil); !errors.Is(err, ErrPurchaseStateMoved) {
+ t.Fatalf("missing advance: %v", err)
+ }
+ if row, err := s.DomainPurchase("missing"); err != nil || row != nil {
+ t.Fatalf("missing lookup: %+v, %v", row, err)
+ }
+}
+
+func TestPurchaseConcurrentAdvance(t *testing.T) {
+ s := openTestStore(t)
+ p := DomainPurchase{ID: "dp_0000000000000001", Domain: "shop.example", State: PurchaseAwaitingPayment}
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ start := make(chan struct{})
+ read := make(chan struct{}, 2)
+ write := make(chan struct{})
+ results := make(chan error, 2)
+ for i := 0; i < 2; i++ {
+ go func() {
+ <-start
+ results <- s.AdvanceDomainPurchase(p.ID, p.State, PurchaseAuthorised, func(p *DomainPurchase) {
+ read <- struct{}{}
+ <-write
+ p.Attempts++
+ })
+ }()
+ }
+ close(start)
+ for i := 0; i < 2; i++ {
+ select {
+ case <-read:
+ case <-time.After(5 * time.Second):
+ close(write)
+ t.Fatal("concurrent advances did not both read the starting state")
+ }
+ }
+ close(write)
+ wins, moved := 0, 0
+ for i := 0; i < 2; i++ {
+ err := <-results
+ if err == nil {
+ wins++
+ } else if errors.Is(err, ErrPurchaseStateMoved) {
+ moved++
+ } else {
+ t.Fatal(err)
+ }
+ }
+ row, err := s.DomainPurchase(p.ID)
+ if wins != 1 || moved != 1 || err != nil || row.Attempts != 1 {
+ t.Fatalf("wins=%d moved=%d row=%+v err=%v", wins, moved, row, err)
+ }
+}
+
+func TestPurchasesTodayCountsUTCDay(t *testing.T) {
+ s := openTestStore(t)
+ now := time.Date(2026, 11, 1, 23, 30, 0, 0, time.FixedZone("west", -7*3600))
+ start := time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)
+ for i, at := range []time.Time{start.Add(-time.Second), start, start.Add(23 * time.Hour), start.Add(24 * time.Hour)} {
+ if err := s.CreateDomainPurchase(DomainPurchase{ID: fmt.Sprintf("dp_%016x", i), AccountID: 123, Domain: fmt.Sprintf("d%d.example", i), State: PurchaseFailed, CreatedAt: at}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.CreateDomainPurchase(DomainPurchase{AccountID: 456, Domain: "other.example", CreatedAt: start}); err != nil {
+ t.Fatal(err)
+ }
+ if n, err := s.PurchasesToday(123, now); err != nil || n != 2 {
+ t.Fatalf("today = %d, %v; want 2", n, err)
+ }
+ if n, err := s.PurchasesToday(999, now); err != nil || n != 0 {
+ t.Fatalf("other account = %d, %v", n, err)
+ }
+}
+
+func TestDomainContactRoundTrip(t *testing.T) {
+ s := openTestStore(t)
+ if c, h, err := s.DomainContact(123); err != nil || c != (registrar.Contact{}) || h != "" {
+ t.Fatalf("absent: %+v, %q, %v", c, h, err)
+ }
+ want := registrar.Contact{FirstName: "Jane", LastName: "Doe", Company: "Example", Email: "jane@example.com", PhoneCountryCode: "353", Phone: "123456789", Street: "Main Street", HouseNumber: "12A", City: "Dublin", State: "Dublin", PostalCode: "D01TEST", Country: "IE"}
+ for _, handle := range []string{"contact-1", "contact-2"} {
+ if err := s.SetDomainContact(123, want, handle); err != nil {
+ t.Fatal(err)
+ }
+ got, h, err := s.DomainContact(123)
+ if err != nil || got != want || h != handle {
+ t.Fatalf("contact: %+v, %q, %v", got, h, err)
+ }
+ want.HouseNumber = "14"
+ }
+ if _, h, err := s.DomainContact(456); err != nil || h != "" {
+ t.Fatalf("account isolation: %q, %v", h, err)
+ }
+}
+
+func TestPurchaseGeneratedIDs(t *testing.T) {
+ s := openTestStore(t)
+ for _, domain := range []string{"one.example", "two.example"} {
+ if err := s.CreateDomainPurchase(DomainPurchase{Domain: domain}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ rows, err := s.LiveDomainPurchases()
+ if err != nil || len(rows) != 2 {
+ t.Fatalf("purchases: %+v, %v", rows, err)
+ }
+ valid := regexp.MustCompile(`^dp_[0-9a-f]{16}$`)
+ for _, row := range rows {
+ if !valid.MatchString(row.ID) || row.State != PurchaseAwaitingPayment || !row.CheckoutExpires.IsZero() {
+ t.Fatalf("generated purchase: %+v", row)
+ }
+ }
+ if rows[0].ID == rows[1].ID {
+ t.Fatal("duplicate generated ID")
+ }
+}
+
+func TestMigrateDomainsIdempotent(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if s != nil {
+ s.Close()
+ }
+ })
+ if err := s.SetDomainContact(123, registrar.Contact{HouseNumber: "12"}, "contact-1"); err != nil {
+ t.Fatal(err)
+ }
+ p := DomainPurchase{ID: "dp_0000000000000001", Domain: "shop.example", State: PurchaseRegistering}
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ expires := time.Date(2027, 11, 1, 0, 0, 0, 0, time.UTC)
+ for i, renew := range []bool{true, false} {
+ r := DomainRegistration{Domain: fmt.Sprintf("registered%d.example", i), AccountID: 123, RegistrarID: "reg_1", ZoneID: "zone_1", Expires: expires, AutoRenew: renew}
+ if err := s.AddDomainRegistration(r); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.AddDomainRegistration(r); err == nil {
+ t.Fatal("duplicate registration accepted")
+ }
+ }
+ if err := s.Close(); err != nil {
+ t.Fatal(err)
+ }
+ s, err = Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if c, h, err := s.DomainContact(123); err != nil || h != "contact-1" || c.HouseNumber != "12" {
+ t.Fatalf("contact after reopen: %+v %q %v", c, h, err)
+ }
+ if row, err := s.DomainPurchase(p.ID); err != nil || row == nil || row.State != PurchaseRegistering {
+ t.Fatalf("purchase after reopen: %+v, %v", row, err)
+ }
+ p.ID = "dp_0000000000000002"
+ if err := s.CreateDomainPurchase(p); !errors.Is(err, ErrDomainPurchaseLive) {
+ t.Fatalf("index after reopen: %v", err)
+ }
+ for i, wantRenew := range []bool{true, false} {
+ var account, expiry, created int64
+ var registrarID, zoneID string
+ var renew bool
+ err := s.db.QueryRow(`SELECT account_id, registrar_id, zone_id, expires_at, auto_renew, created_at FROM domain_registrations WHERE domain = ?`, fmt.Sprintf("registered%d.example", i)).Scan(&account, &registrarID, &zoneID, &expiry, &renew, &created)
+ if err != nil || account != 123 || registrarID != "reg_1" || zoneID != "zone_1" || expiry != expires.Unix() || renew != wantRenew || created == 0 {
+ t.Fatalf("registration: %d %q %q %d %v %d %v", account, registrarID, zoneID, expiry, renew, created, err)
+ }
+ }
+ if _, err := s.db.Exec(`INSERT INTO domain_registrations (domain, account_id, registrar_id, zone_id, expires_at, created_at) VALUES ('default.example', 123, '', '', 0, 0)`); err != nil {
+ t.Fatal(err)
+ }
+ var renew sql.NullBool
+ if err := s.db.QueryRow(`SELECT auto_renew FROM domain_registrations WHERE domain = 'default.example'`).Scan(&renew); err != nil || !renew.Valid || !renew.Bool {
+ t.Fatalf("default renewal: %+v %v", renew, err)
+ }
+}
+
+func TestDomainPurchaseClaimGate(t *testing.T) {
+ s := openGatedStore(t)
+ seedGateApp(t, s)
+ if err := s.SetDomainContact(gateAcct, registrar.Contact{FirstName: "Jane"}, "contact-1"); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.AddDomainRegistration(DomainRegistration{Domain: "shop.example", AccountID: gateAcct, AutoRenew: true}); err != nil {
+ t.Fatal(err)
+ }
+ p := DomainPurchase{ID: "dp_0000000000000001", AccountID: gateAcct, App: gateScope.App, Domain: "shop.example", State: PurchaseAwaitingPayment}
+ requireDenied(t, "purchase without permit", s.CreateDomainPurchase(p))
+ if err := s.withClaimSQL(gateCtx(t), []claimSQLScope{gateScope}, allowAllClaimSQL, func(v *Store) error { return v.CreateDomainPurchase(p) }); err != nil {
+ t.Fatal(err)
+ }
+ requireDenied(t, "advance without permit", s.AdvanceDomainPurchase(p.ID, p.State, PurchaseAuthorised, nil))
+ if err := s.withClaimSQL(gateCtx(t), []claimSQLScope{gateScope}, allowAllClaimSQL, func(v *Store) error {
+ return v.AdvanceDomainPurchase(p.ID, p.State, PurchaseAuthorised, func(row *DomainPurchase) { row.PaymentIntent = "pi_1" })
+ }); err != nil {
+ t.Fatal(err)
+ }
+ row, err := s.DomainPurchase(p.ID)
+ if err != nil || row == nil || row.State != PurchaseAuthorised || row.PaymentIntent != "pi_1" {
+ t.Fatalf("gated purchase: %+v, %v", row, err)
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index e9d4eb8e8..ac17a3bf6 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -675,7 +675,10 @@ func (s *Store) migrate() error {
return err
}
// The alert engine's tables (alertstore.go), for the same reason.
- return s.migrateAlerts()
+ if err := s.migrateAlerts(); err != nil {
+ return err
+ }
+ return s.migrateDomains()
}
// migratePlanSeats adds account_plans.seats (plans 6b): the paid seat count
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index afd308024..a88db6905 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -201,6 +201,7 @@ var claimSQLTables = map[string]claimSQLTable{
"app_policy_revisions": {Account: "account_id", App: "app"}, // apppolicy_store.go; the purge never writes it (revisions only rise)
"plan_lapse_items": {Account: "account_id", App: "app"},
"pending_changes": {Account: "account_id", App: "app"},
+ "domain_purchases": {Account: "account_id", App: "app"},
"pending_confirms": {Account: "account_id", App: "app", Via: &claimSQLVia{Parent: "pending_changes", ChildCol: "change_id", ParentCol: "id"}},
"mail_counts": {Sqid: "account", App: "app"},
"mail_sender_counts": {Sqid: "account", App: "app"},
@@ -241,6 +242,9 @@ var claimSQLTables = map[string]claimSQLTable{
"email_challenges": {NonApp: "emailed sign-in and step-up links and codes in flight, keyed by id hash; carries no app column"},
"pending_actions": {NonApp: "replay-by-token actions, keyed by token hash; carries no app column and re-enters the ordinary handlers"},
+ "domain_contacts": {NonApp: "registrant contact details and handle, keyed by account; names no app"},
+ "domain_registrations": {NonApp: "domain ownership and renewal records, keyed by domain and account; names no app"},
+
// Plans 6b's billing tables.
"billing_checkout_intents": {NonApp: "an account's Checkout intent and its prepared provider requests, keyed by account; names no app"},
"billing_house": {NonApp: "house accounts an operator marked, keyed by account; names no app"},