carlos / platform Public

console: transfer purchases and registration expiry alerts in the store

domain_purchases gains kind (buy or transfer, fixed at create) and three
live transfer states, so the one-live-purchase index, DomainObligations
and account deletion cover transfers. purchaseDetails gains the transfer
fields and the frozen transferFacts; outcome enums are stored as stable
strings and an unknown string fails the read. AuthCode is redacted under
every fmt verb on both purchaseDetails and DomainPurchase.
domain_registrations gains expiry_alerted_at, with
RegistrationsExpiringBefore and MarkExpiryAlerted; PendingTransfers lists
live transfers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c3dd9cb6bb61f29b9e41909ec9e5989787abf3a5 parent 7771bb8
3 files changed, +605 −7
  • internal/console/domainstore.go +169 −7
  • internal/console/domainstore_test.go +289 −0
  • internal/console/domaintransfer_facts.go +147 −0
diff --git a/internal/console/domainstore.go b/internal/console/domainstore.go
index 651fb2a98..586c24c04 100644
--- a/internal/console/domainstore.go
+++ b/internal/console/domainstore.go
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
"log"
"strings"
"time"
@@ -15,6 +16,15 @@ import (
"github.com/carlosframework/platform/internal/registrar"
)
+// PurchaseKind says whether a purchase registers a new domain or transfers
+// one in. It is fixed when the purchase is created.
+type PurchaseKind string
+
+const (
+ PurchaseKindBuy PurchaseKind = "buy"
+ PurchaseKindTransfer PurchaseKind = "transfer"
+)
+
type PurchaseState string
const (
@@ -28,6 +38,12 @@ const (
PurchaseFailed PurchaseState = "failed"
PurchaseExpired PurchaseState = "expired"
PurchaseUnpaid PurchaseState = "unpaid"
+
+ // Transfer states. All three are live: a transfer in any of them holds
+ // its domain and blocks account deletion.
+ PurchaseTransferSubmitting PurchaseState = "transfer_submitting" // sent; outcome may be unknown
+ PurchaseTransferPending PurchaseState = "transfer_pending" // accepted by the registrar
+ PurchaseTransferRefunding PurchaseState = "transfer_refunding" // failed after capture; refund in flight
)
var (
@@ -58,10 +74,56 @@ type purchaseDetails struct {
// cleanup (release the original App's hosts, unpoint the zone, done
// with no app), even if the app comes back.
Unpointing bool `json:",omitempty"`
+
+ // Transfer-in fields (Kind transfer only).
+ //
+ // AuthCode is a secret: cleared in the move that enters
+ // transfer_submitting and on every pre-submit terminal path, and never
+ // logged. String, GoString and Format redact it.
+ AuthCode string `json:",omitempty"`
+ Nameservers []string `json:",omitempty"` // read at check, sent at submit
+ SubmittedAt time.Time `json:",omitzero"`
+ // Facts are the recorded registrar, payment and refund outcomes.
+ Facts transferFacts `json:",omitzero"`
+ // CaptureBefore is the provider's authorisation deadline, or CreatedAt
+ // + 6 days when unknown.
+ CaptureBefore time.Time `json:",omitzero"`
+ // Alerts maps an alert kind (24h-unknown, lapse, weekly-unknown,
+ // capture-refused, refund-failed) to when it was last sent.
+ Alerts map[string]time.Time `json:",omitempty"`
+ // NextStatusAt is the next registrar status read: 30 minutes for the
+ // first 7 days after submit, then daily.
+ NextStatusAt time.Time `json:",omitzero"`
+ // Resolution is the operator-recorded outcome of an unknown transfer:
+ // "failed" or "completed".
+ Resolution string `json:",omitempty"`
+ ResolvedBy string `json:",omitempty"`
+}
+
+// purchaseDetailsFields is purchaseDetails without its formatting methods,
+// so they can print it without calling themselves.
+type purchaseDetailsFields purchaseDetails
+
+const redactedAuthCode = "[redacted]"
+
+func (d purchaseDetails) redacted() purchaseDetailsFields {
+ if d.AuthCode != "" {
+ d.AuthCode = redactedAuthCode
+ }
+ return purchaseDetailsFields(d)
+}
+
+func (d purchaseDetails) String() string { return fmt.Sprintf("%+v", d.redacted()) }
+func (d purchaseDetails) GoString() string { return fmt.Sprintf("%#v", d.redacted()) }
+
+// Format redacts AuthCode under every verb, not only those that call String.
+func (d purchaseDetails) Format(f fmt.State, verb rune) {
+ fmt.Fprintf(f, fmt.FormatString(f, verb), d.redacted())
}
type DomainPurchase struct {
purchaseDetails
+ Kind PurchaseKind // "" on create means buy
Revision int64
ID string
AccountID int64
@@ -74,6 +136,43 @@ type DomainPurchase struct {
CheckoutExpires, CreatedAt, UpdatedAt time.Time
}
+// domainPurchaseFields is a DomainPurchase for printing: its details are a
+// named field, so their redacting Format applies. A field added to
+// DomainPurchase must be added here (TestPurchaseDetailsRedactAuthCode
+// checks).
+type domainPurchaseFields struct {
+ Details purchaseDetails
+ Kind PurchaseKind
+ Revision int64
+ 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
+}
+
+func (p DomainPurchase) printable() domainPurchaseFields {
+ return domainPurchaseFields{
+ Details: p.purchaseDetails, Kind: p.Kind, Revision: p.Revision, ID: p.ID, AccountID: p.AccountID,
+ Domain: p.Domain, App: p.App, Currency: p.Currency, Amount: p.Amount, State: p.State, Reason: p.Reason,
+ CheckoutSession: p.CheckoutSession, PaymentIntent: p.PaymentIntent, ZoneID: p.ZoneID, RegistrarID: p.RegistrarID,
+ Attempts: p.Attempts, CheckoutExpires: p.CheckoutExpires, CreatedAt: p.CreatedAt, UpdatedAt: p.UpdatedAt,
+ }
+}
+
+// String, GoString and Format print a purchase with its AuthCode redacted.
+// They are declared here, not only promoted from purchaseDetails, so the
+// purchase's own fields print too.
+func (p DomainPurchase) String() string { return fmt.Sprintf("%+v", p.printable()) }
+func (p DomainPurchase) GoString() string { return fmt.Sprintf("%#v", p.printable()) }
+func (p DomainPurchase) Format(f fmt.State, verb rune) {
+ fmt.Fprintf(f, fmt.FormatString(f, verb), p.printable())
+}
+
type DomainRegistration struct {
Domain string
AccountID int64
@@ -84,6 +183,9 @@ type DomainRegistration struct {
// Registrant is the purchase's frozen contact; a saved-contact edit
// never changes it.
Registrant registrar.Contact
+ // ExpiryAlertedAt is when the expiry alert was sent; zero until then.
+ // Only MarkExpiryAlerted sets it.
+ ExpiryAlertedAt time.Time
}
// SavedContact is one of an account's registrant contacts. Every edit bumps
@@ -158,6 +260,8 @@ CREATE TABLE IF NOT EXISTS domain_meta (
`ALTER TABLE domain_purchases ADD COLUMN details TEXT NOT NULL DEFAULT '{}'`,
`ALTER TABLE domain_purchases ADD COLUMN revision INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE domain_registrations ADD COLUMN registrant TEXT NOT NULL DEFAULT '{}'`,
+ `ALTER TABLE domain_purchases ADD COLUMN kind TEXT NOT NULL DEFAULT 'buy'`,
+ `ALTER TABLE domain_registrations ADD COLUMN expiry_alerted_at INTEGER NOT NULL DEFAULT 0`,
} {
if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
@@ -276,7 +380,7 @@ func newDomainPurchaseID() string {
}
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, details, revision`
+ checkout_session, payment_intent, zone_id, registrar_id, attempts, checkout_expires, created_at, updated_at, details, revision, kind`
func (s *Store) CreateDomainPurchase(p DomainPurchase) error {
if p.ID == "" {
@@ -285,6 +389,13 @@ func (s *Store) CreateDomainPurchase(p DomainPurchase) error {
if p.State == "" {
p.State = PurchaseAwaitingPayment
}
+ switch p.Kind {
+ case "":
+ p.Kind = PurchaseKindBuy
+ case PurchaseKindBuy, PurchaseKindTransfer:
+ default:
+ return fmt.Errorf("console: unknown domain purchase kind %q", p.Kind)
+ }
now := time.Now().UTC()
if p.CreatedAt.IsZero() {
p.CreatedAt = now
@@ -297,11 +408,11 @@ func (s *Store) CreateDomainPurchase(p DomainPurchase) error {
return err
}
res, err := s.db.Exec(`INSERT INTO domain_purchases (`+domainPurchaseColumns+`)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ 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(), string(details), p.Revision)
+ domainUnix(p.CheckoutExpires), p.CreatedAt.Unix(), p.UpdatedAt.Unix(), string(details), p.Revision, p.Kind)
if err != nil {
return err
}
@@ -321,7 +432,7 @@ func scanDomainPurchase(sc interface{ Scan(...any) error }) (*DomainPurchase, er
var details string
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, &details, &p.Revision); err != nil {
+ &expires, &created, &updated, &details, &p.Revision, &p.Kind); err != nil {
return nil, err
}
if err := json.Unmarshal([]byte(details), &p.purchaseDetails); err != nil {
@@ -353,6 +464,8 @@ func (s *Store) AdvanceDomainPurchase(id string, from, to PurchaseState, set fun
return s.compareDomainPurchase(*p, to, set)
}
+// compareDomainPurchase writes every column but kind, which is fixed at
+// create.
func (s *Store) compareDomainPurchase(before DomainPurchase, to PurchaseState, set func(*DomainPurchase)) error {
p := before
if set != nil {
@@ -400,6 +513,24 @@ func (s *Store) LiveDomainPurchases() ([]DomainPurchase, error) {
return out, rows.Err()
}
+// PendingTransfers lists live transfer purchases, oldest first.
+func (s *Store) PendingTransfers(ctx context.Context) ([]DomainPurchase, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT `+domainPurchaseColumns+` FROM domain_purchases WHERE kind = 'transfer' AND `+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)
@@ -459,13 +590,13 @@ func registrantJSON(c registrar.Contact) (string, error) {
return string(b), err
}
-const domainRegistrationColumns = `domain, account_id, registrar_id, zone_id, expires_at, auto_renew, created_at, registrant`
+const domainRegistrationColumns = `domain, account_id, registrar_id, zone_id, expires_at, auto_renew, created_at, registrant, expiry_alerted_at`
func scanDomainRegistration(sc interface{ Scan(...any) error }) (*DomainRegistration, error) {
var r DomainRegistration
- var expires, created int64
+ var expires, created, alerted int64
var registrant string
- if err := sc.Scan(&r.Domain, &r.AccountID, &r.RegistrarID, &r.ZoneID, &expires, &r.AutoRenew, &created, &registrant); err != nil {
+ if err := sc.Scan(&r.Domain, &r.AccountID, &r.RegistrarID, &r.ZoneID, &expires, &r.AutoRenew, &created, &registrant, &alerted); err != nil {
return nil, err
}
if err := json.Unmarshal([]byte(registrant), &r.Registrant); err != nil {
@@ -474,10 +605,41 @@ func scanDomainRegistration(sc interface{ Scan(...any) error }) (*DomainRegistra
if expires != 0 {
r.Expires = time.Unix(expires, 0).UTC()
}
+ if alerted != 0 {
+ r.ExpiryAlertedAt = time.Unix(alerted, 0).UTC()
+ }
r.CreatedAt = time.Unix(created, 0).UTC()
return &r, nil
}
+// RegistrationsExpiringBefore lists, soonest first, the registrations that
+// expire before t and have had no expiry alert. A registration with no
+// recorded expiry is not listed.
+func (s *Store) RegistrationsExpiringBefore(ctx context.Context, t time.Time) ([]DomainRegistration, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT `+domainRegistrationColumns+` FROM domain_registrations
+ WHERE expires_at > 0 AND expires_at < ? AND expiry_alerted_at = 0 ORDER BY expires_at, domain`, t.Unix())
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []DomainRegistration
+ for rows.Next() {
+ r, err := scanDomainRegistration(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, *r)
+ }
+ return out, rows.Err()
+}
+
+// MarkExpiryAlerted records that domain's expiry alert went out at at. A
+// registration removed meanwhile is not an error.
+func (s *Store) MarkExpiryAlerted(ctx context.Context, domain string, at time.Time) error {
+ _, err := s.db.ExecContext(ctx, `UPDATE domain_registrations SET expiry_alerted_at = ? WHERE domain = ?`, at.Unix(), domain)
+ return err
+}
+
// DomainRegistrations lists an account's registrations by domain.
func (s *Store) DomainRegistrations(ctx context.Context, accountID int64) ([]DomainRegistration, error) {
rows, err := s.db.QueryContext(ctx, `SELECT `+domainRegistrationColumns+` FROM domain_registrations WHERE account_id = ? ORDER BY domain`, accountID)
diff --git a/internal/console/domainstore_test.go b/internal/console/domainstore_test.go
index bb503a36e..54e3f68ca 100644
--- a/internal/console/domainstore_test.go
+++ b/internal/console/domainstore_test.go
@@ -643,3 +643,292 @@ func TestAppLessPurchaseRowAllowedByGate(t *testing.T) {
t.Fatalf("app-less row: %+v, %v", row, err)
}
}
+
+func testTransferPurchase(id, domain string, state PurchaseState) DomainPurchase {
+ t0 := time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC)
+ return DomainPurchase{ID: id, AccountID: 1, Domain: domain, Kind: PurchaseKindTransfer, State: state, Currency: "eur", Amount: 1200, CreatedAt: t0}
+}
+
+func TestTransferPurchaseRoundTripKindAndDetails(t *testing.T) {
+ ctx := t.Context()
+ s := openTestStore(t)
+ t0 := time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC)
+ p := testTransferPurchase("dp_0000000000000001", "moving.example", PurchaseTransferSubmitting)
+ p.purchaseDetails = purchaseDetails{
+ AuthCode: "auth-code-not-yet-cleared",
+ Nameservers: []string{"ns1.example.net", "ns2.example.net"},
+ SubmittedAt: t0.Add(time.Hour),
+ CaptureBefore: t0.Add(6 * 24 * time.Hour),
+ Alerts: map[string]time.Time{"24h-unknown": t0.Add(25 * time.Hour)},
+ NextStatusAt: t0.Add(90 * time.Minute),
+ Resolution: "completed",
+ ResolvedBy: "operator@example.com",
+ Facts: transferFacts{
+ Registrar: rUnknown, RegistrarReason: "timeout",
+ Completed: &registrar.Registered{Domain: "moving.example", RegistrarID: "r-1", Expires: t0.AddDate(1, 0, 0), Nameservers: []string{"ns1.example.net"}},
+ Payment: pAuthorised,
+ Refund: fPending, RefundAttempt: 2, RefundID: "re_1",
+ Resolution: "completed",
+ CaptureAttempted: true,
+ CheckoutExpires: t0.Add(time.Hour),
+ Alerts: map[string]time.Time{"lapse": t0.Add(2 * time.Hour)},
+ SubmittedAt: t0.Add(time.Hour),
+ CaptureBefore: t0.Add(6 * 24 * time.Hour),
+ Now: t0.Add(3 * time.Hour), // not persisted
+ },
+ }
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ got, err := s.DomainPurchase(p.ID)
+ if err != nil || got == nil {
+ t.Fatalf("read: %v %v", got, err)
+ }
+ want := p
+ want.Facts.Now = time.Time{}
+ want.Revision, want.UpdatedAt = got.Revision, got.UpdatedAt
+ if !reflect.DeepEqual(*got, want) {
+ t.Fatalf("round trip:\n got %+v\nwant %+v", *got, want)
+ }
+ var raw string
+ if err := s.db.QueryRow(`SELECT details FROM domain_purchases WHERE id = ?`, p.ID).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ for _, frag := range []string{`"Registrar":"unknown"`, `"Payment":"authorised"`, `"Refund":"pending"`} {
+ if !regexp.MustCompile(regexp.QuoteMeta(frag)).MatchString(raw) {
+ t.Fatalf("details %s: outcomes are not stable strings (want %s)", raw, frag)
+ }
+ }
+ if regexp.MustCompile(`"Now"`).MatchString(raw) {
+ t.Fatalf("details persist Now: %s", raw)
+ }
+ // An unknown outcome string is an error, never a silent zero (rNotSent
+ // would invite a second send).
+ if _, err := s.db.Exec(`UPDATE domain_purchases SET details = json_set(details, '$.Facts.Registrar', 'renamed') WHERE id = ?`, p.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.DomainPurchase(p.ID); err == nil {
+ t.Fatal("an unknown registrar outcome decoded")
+ }
+ if _, err := s.db.Exec(`UPDATE domain_purchases SET details = ? WHERE id = ?`, raw, p.ID); err != nil {
+ t.Fatal(err)
+ }
+
+ // Kind is fixed at create; an advance keeps it.
+ if err := s.AdvanceDomainPurchase(p.ID, PurchaseTransferSubmitting, PurchaseTransferPending, func(row *DomainPurchase) {
+ row.Kind = PurchaseKindBuy
+ row.AuthCode = ""
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := s.DomainPurchase(p.ID); err != nil || got.Kind != PurchaseKindTransfer || got.State != PurchaseTransferPending || got.AuthCode != "" {
+ t.Fatalf("after advance: %+v %v", got, err)
+ }
+
+ // A buy with no kind is a buy; a kind that is neither is refused.
+ buy := DomainPurchase{ID: "dp_0000000000000002", AccountID: 1, Domain: "bought.example", State: PurchaseAwaitingPayment, CreatedAt: t0}
+ if err := s.CreateDomainPurchase(buy); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := s.DomainPurchase(buy.ID); err != nil || got.Kind != PurchaseKindBuy || got.Nameservers != nil || got.Alerts != nil || !reflect.DeepEqual(got.Facts, transferFacts{}) {
+ t.Fatalf("buy: %+v %v", got, err)
+ }
+ if err := s.CreateDomainPurchase(DomainPurchase{ID: "dp_0000000000000003", Domain: "odd.example", Kind: "lease"}); err == nil {
+ t.Fatal("unknown kind accepted")
+ }
+
+ // PendingTransfers: live transfers only, oldest first.
+ for i, q := range []DomainPurchase{
+ testTransferPurchase("dp_0000000000000004", "refunding.example", PurchaseTransferRefunding),
+ testTransferPurchase("dp_0000000000000005", "paying.example", PurchaseAwaitingPayment),
+ testTransferPurchase("dp_0000000000000006", "ended.example", PurchaseFailed),
+ } {
+ q.CreatedAt = t0.Add(time.Duration(i+1) * time.Minute)
+ if err := s.CreateDomainPurchase(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ pending, err := s.PendingTransfers(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var ids []string
+ for _, q := range pending {
+ ids = append(ids, q.ID)
+ }
+ if want := []string{"dp_0000000000000001", "dp_0000000000000004", "dp_0000000000000005"}; !reflect.DeepEqual(ids, want) {
+ t.Fatalf("pending transfers = %v, want %v", ids, want)
+ }
+}
+
+func TestOneLivePurchasePerDomainAcrossKinds(t *testing.T) {
+ for _, live := range []PurchaseState{PurchaseAwaitingPayment, PurchaseTransferSubmitting, PurchaseTransferPending, PurchaseTransferRefunding} {
+ t.Run(string(live), func(t *testing.T) {
+ s := openTestStore(t)
+ transfer := testTransferPurchase("dp_0000000000000001", "shop.example", live)
+ if err := s.CreateDomainPurchase(transfer); err != nil {
+ t.Fatal(err)
+ }
+ buy := DomainPurchase{ID: "dp_0000000000000002", AccountID: 2, Domain: "shop.example", State: PurchaseAwaitingPayment}
+ if err := s.CreateDomainPurchase(buy); !errors.Is(err, ErrDomainPurchaseLive) {
+ t.Fatalf("buy over a live transfer: %v", err)
+ }
+ if err := s.AdvanceDomainPurchase(transfer.ID, live, PurchaseFailed, nil); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.CreateDomainPurchase(buy); err != nil {
+ t.Fatalf("buy after the transfer ended: %v", err)
+ }
+ again := testTransferPurchase("dp_0000000000000003", "shop.example", live)
+ if err := s.CreateDomainPurchase(again); !errors.Is(err, ErrDomainPurchaseLive) {
+ t.Fatalf("transfer over a live buy: %v", err)
+ }
+ })
+ }
+}
+
+func TestDomainObligationsCountsPendingTransfer(t *testing.T) {
+ ctx := t.Context()
+ s := openTestStore(t)
+ const acct = 7 // not the ops account, which is never deletable
+ for i, st := range []PurchaseState{PurchaseTransferSubmitting, PurchaseTransferPending, PurchaseTransferRefunding, PurchaseFailed, PurchaseDone} {
+ p := testTransferPurchase(fmt.Sprintf("dp_%016x", i+1), fmt.Sprintf("t%d.example", i), st)
+ p.AccountID = acct
+ if err := s.CreateDomainPurchase(p); err != nil {
+ t.Fatal(err)
+ }
+ }
+ got, err := s.DomainObligations(ctx, acct)
+ if want := []string{"t0.example", "t1.example", "t2.example"}; err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("obligations = %v, %v; want %v", got, err, want)
+ }
+ if err := s.DeleteAccount(acct, time.Now()); !errors.Is(err, errAccountHoldsDomains) {
+ t.Fatalf("deleting an account with a live transfer: %v", err)
+ }
+}
+
+func TestPurchaseDetailsRedactAuthCode(t *testing.T) {
+ const secret = "Zq7-auth-code-secret"
+ p := testTransferPurchase("dp_0000000000000001", "moving.example", PurchaseAwaitingPayment)
+ p.AuthCode = secret
+ p.Nameservers = []string{"ns1.example.net"}
+ d := p.purchaseDetails
+ outputs := map[string]string{}
+ for _, verb := range []string{"%v", "%+v", "%#v", "%s", "%q", "%d", "%x"} {
+ outputs[verb+" details"] = fmt.Sprintf(verb, d)
+ outputs[verb+" *details"] = fmt.Sprintf(verb, &d)
+ outputs[verb+" purchase"] = fmt.Sprintf(verb, p)
+ outputs[verb+" *purchase"] = fmt.Sprintf(verb, &p)
+ outputs[verb+" []purchase"] = fmt.Sprintf(verb, []DomainPurchase{p})
+ }
+ outputs["String details"], outputs["GoString details"] = d.String(), d.GoString()
+ outputs["String purchase"], outputs["GoString purchase"] = p.String(), p.GoString()
+ hexSecret := fmt.Sprintf("%x", secret)
+ for name, out := range outputs {
+ if regexp.MustCompile(regexp.QuoteMeta(secret)).MatchString(out) || regexp.MustCompile(hexSecret).MatchString(out) {
+ t.Errorf("%s leaks the auth code: %s", name, out)
+ }
+ }
+ // Redaction keeps everything else readable.
+ plus := fmt.Sprintf("%+v", p)
+ for _, f := range reflect.VisibleFields(reflect.TypeOf(p)) {
+ if f.Anonymous || !f.IsExported() {
+ continue
+ }
+ if !regexp.MustCompile(`\b` + f.Name + `:`).MatchString(plus) {
+ t.Errorf("%%+v of a purchase lost field %s: %s", f.Name, plus)
+ }
+ }
+ for _, want := range []string{"moving.example", "ns1.example.net", "AuthCode:[redacted]"} {
+ if !regexp.MustCompile(regexp.QuoteMeta(want)).MatchString(plus) {
+ t.Errorf("%%+v of a purchase lost %q: %s", want, plus)
+ }
+ }
+ if p.AuthCode != secret {
+ t.Fatal("formatting changed the purchase")
+ }
+ var none DomainPurchase
+ if out := fmt.Sprintf("%+v", none); regexp.MustCompile(`redacted`).MatchString(out) {
+ t.Errorf("an empty auth code reads as redacted: %s", out)
+ }
+}
+
+func TestRegistrationsExpiringBeforeAndMarkAlerted(t *testing.T) {
+ ctx := t.Context()
+ s := openTestStore(t)
+ t0 := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
+ for _, r := range []DomainRegistration{
+ {Domain: "later.example", AccountID: 1, Expires: t0.Add(48 * time.Hour)},
+ {Domain: "soon.example", AccountID: 1, Expires: t0.Add(-time.Hour)},
+ {Domain: "sooner.example", AccountID: 2, Expires: t0.Add(-48 * time.Hour), ZoneID: ""}, // a transfer: no zone
+ {Domain: "unknown.example", AccountID: 1}, // no expiry recorded
+ {Domain: "edge.example", AccountID: 1, Expires: t0},
+ } {
+ if err := s.AddDomainRegistration(r); err != nil {
+ t.Fatal(err)
+ }
+ }
+ domains := func() []string {
+ t.Helper()
+ regs, err := s.RegistrationsExpiringBefore(ctx, t0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, r := range regs {
+ if !r.ExpiryAlertedAt.IsZero() {
+ t.Fatalf("an alerted registration listed: %+v", r)
+ }
+ out = append(out, r.Domain)
+ }
+ return out
+ }
+ if got, want := domains(), []string{"sooner.example", "soon.example"}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("expiring = %v, want %v", got, want)
+ }
+ at := t0.Add(-30 * time.Minute)
+ if err := s.MarkExpiryAlerted(ctx, "soon.example", at); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := domains(), []string{"sooner.example"}; !reflect.DeepEqual(got, want) {
+ t.Fatalf("after alert = %v, want %v", got, want)
+ }
+ if r, err := s.DomainRegistrationFor(ctx, 1, "soon.example"); err != nil || r == nil || !r.ExpiryAlertedAt.Equal(at) {
+ t.Fatalf("alerted registration: %+v %v", r, err)
+ }
+ if err := s.MarkExpiryAlerted(ctx, "missing.example", at); err != nil {
+ t.Fatalf("marking a missing registration: %v", err)
+ }
+}
+
+func TestMigrateAddsKindAndExpiryAlertedIdempotent(t *testing.T) {
+ ctx := t.Context()
+ s := openTestStore(t)
+ // Roll the schema back to before transfers.
+ for _, stmt := range []string{
+ `ALTER TABLE domain_purchases DROP COLUMN kind`,
+ `ALTER TABLE domain_registrations DROP COLUMN expiry_alerted_at`,
+ `INSERT INTO domain_purchases (id, account_id, domain, app, currency, amount, state, created_at, updated_at)
+ VALUES ('dp_0000000000000001', 1, 'old.example', '', 'eur', 1500, 'registering', 1, 1)`,
+ `INSERT INTO domain_registrations (domain, account_id, registrar_id, zone_id, expires_at, created_at)
+ VALUES ('old.example', 1, 'r-1', 'zone-1', 1000, 1)`,
+ } {
+ if _, err := s.db.Exec(stmt); err != nil {
+ t.Fatalf("%s: %v", stmt, err)
+ }
+ }
+ for i := 0; i < 2; i++ {
+ if err := s.migrateDomains(); err != nil {
+ t.Fatalf("migrate %d: %v", i, err)
+ }
+ }
+ if p, err := s.DomainPurchase("dp_0000000000000001"); err != nil || p == nil || p.Kind != PurchaseKindBuy {
+ t.Fatalf("old purchase: %+v %v", p, err)
+ }
+ if regs, err := s.RegistrationsExpiringBefore(ctx, time.Unix(2000, 0)); err != nil || len(regs) != 1 || regs[0].Domain != "old.example" {
+ t.Fatalf("old registration: %+v %v", regs, err)
+ }
+ if pending, err := s.PendingTransfers(ctx); err != nil || len(pending) != 0 {
+ t.Fatalf("an old buy reads as a transfer: %+v %v", pending, err)
+ }
+}
diff --git a/internal/console/domaintransfer_facts.go b/internal/console/domaintransfer_facts.go
new file mode 100644
index 000000000..433a770d9
--- /dev/null
+++ b/internal/console/domaintransfer_facts.go
@@ -0,0 +1,147 @@
+package console
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+// The outcomes a transfer has recorded, and the facts decideTransfer reads.
+// Each outcome is stored in purchase details as a stable string, never its
+// number, so reordering the constants never changes a stored record. A
+// stored string this build does not know fails the read rather than decoding
+// as the zero outcome: a zero registrar outcome is "not sent", and reading an
+// unknown one as that would invite a second send.
+
+// registrarOutcome is what the registrar has said about the transfer request.
+type registrarOutcome int
+
+const (
+ rNotSent registrarOutcome = iota // never sent
+ rUnknown // sent, no definite answer
+ rPending // accepted
+ rCompleted // the domain arrived
+ rFailed // refused or failed; the reason is kept beside it
+)
+
+var registrarOutcomeNames = []string{
+ rNotSent: "not_sent",
+ rUnknown: "unknown",
+ rPending: "pending",
+ rCompleted: "completed",
+ rFailed: "failed",
+}
+
+// paymentOutcome is the transfer's payment as last read from the provider.
+type paymentOutcome int
+
+const (
+ pUnknown paymentOutcome = iota // not read yet
+ pAwaiting // Checkout open, no authorisation yet: includes a declined card the customer may retry
+ pAuthorised // requires_capture
+ pCaptured // succeeded
+ pCancelled // Checkout expired, authorisation cancelled or lapsed: nothing taken
+ pFailed // requires_payment_method or another definite failure AFTER a capture attempt, nothing taken
+)
+
+var paymentOutcomeNames = []string{
+ pUnknown: "unknown",
+ pAwaiting: "awaiting",
+ pAuthorised: "authorised",
+ pCaptured: "captured",
+ pCancelled: "cancelled",
+ pFailed: "failed",
+}
+
+// refundOutcome is the current refund attempt's outcome.
+type refundOutcome int
+
+const (
+ fNone refundOutcome = iota // no refund attempt
+ fPending // current attempt pending or requires_action
+ fSucceeded // current attempt succeeded AND amount and currency equal the capture
+ fFailed // current attempt failed or canceled
+)
+
+var refundOutcomeNames = []string{
+ fNone: "none",
+ fPending: "pending",
+ fSucceeded: "succeeded",
+ fFailed: "failed",
+}
+
+// transferFacts is everything decideTransfer reads. All but Now is stored
+// in the purchase's details.
+type transferFacts struct {
+ Registrar registrarOutcome `json:",omitempty"`
+ RegistrarReason string `json:",omitempty"`
+ Completed *registrar.Registered `json:",omitempty"`
+ Payment paymentOutcome `json:",omitempty"`
+ Refund refundOutcome `json:",omitempty"`
+ // RefundAttempt numbers refund attempts from 1; 0 is untagged.
+ RefundAttempt int `json:",omitempty"`
+ RefundID string `json:",omitempty"`
+ Resolution string `json:",omitempty"` // operator: "", "failed", "completed"
+ CaptureAttempted bool `json:",omitempty"`
+ CheckoutExpires time.Time `json:",omitzero"`
+ Alerts map[string]time.Time `json:",omitempty"` // alert kind -> last delivered
+ Now time.Time `json:"-"`
+ SubmittedAt time.Time `json:",omitzero"`
+ CaptureBefore time.Time `json:",omitzero"`
+}
+
+func (o registrarOutcome) String() string { return outcomeName(registrarOutcomeNames, int(o)) }
+func (o paymentOutcome) String() string { return outcomeName(paymentOutcomeNames, int(o)) }
+func (o refundOutcome) String() string { return outcomeName(refundOutcomeNames, int(o)) }
+
+func (o registrarOutcome) MarshalText() ([]byte, error) {
+ return marshalOutcome("registrar", registrarOutcomeNames, int(o))
+}
+func (o paymentOutcome) MarshalText() ([]byte, error) {
+ return marshalOutcome("payment", paymentOutcomeNames, int(o))
+}
+func (o refundOutcome) MarshalText() ([]byte, error) {
+ return marshalOutcome("refund", refundOutcomeNames, int(o))
+}
+
+func (o *registrarOutcome) UnmarshalText(b []byte) error {
+ n, err := unmarshalOutcome("registrar", registrarOutcomeNames, b)
+ *o = registrarOutcome(n)
+ return err
+}
+
+func (o *paymentOutcome) UnmarshalText(b []byte) error {
+ n, err := unmarshalOutcome("payment", paymentOutcomeNames, b)
+ *o = paymentOutcome(n)
+ return err
+}
+
+func (o *refundOutcome) UnmarshalText(b []byte) error {
+ n, err := unmarshalOutcome("refund", refundOutcomeNames, b)
+ *o = refundOutcome(n)
+ return err
+}
+
+func outcomeName(names []string, n int) string {
+ if n < 0 || n >= len(names) {
+ return fmt.Sprintf("outcome(%d)", n)
+ }
+ return names[n]
+}
+
+func marshalOutcome(kind string, names []string, n int) ([]byte, error) {
+ if n < 0 || n >= len(names) {
+ return nil, fmt.Errorf("console: %s outcome %d has no name", kind, n)
+ }
+ return []byte(names[n]), nil
+}
+
+func unmarshalOutcome(kind string, names []string, b []byte) (int, error) {
+ for n, name := range names {
+ if string(b) == name {
+ return n, nil
+ }
+ }
+ return 0, fmt.Errorf("console: unknown %s outcome %q", kind, b)
+}