diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 9d3a7e024..2bd817723 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -149,7 +149,7 @@ A key or token without `manage_billing` behind it answers `403` on the routes th Money is integer micro-USD (`1000000` is $1.00) in fields ending `_micros`. - `GET /store/status` returns `enabled`, `configured` (whether the instance has a GraphKit API key at all), `reason` when `enabled` is `false` (`not_configured` or `partner_managed`), `locked` (with `not_configured`: `true` only on a self-hosted instance, which shows buying as a feature to set up; `false` on a hosted instance, which hides the store until a key is added), `can_configure` (with `locked`: `true` for a session whose user is an instance admin holding `manage_settings`, never for an API key or OAuth token), `configure_url` with `can_configure` when the admin panel's address is known (the page that takes the key), and `disconnected` with `not_configured` when this workspace still has live purchases, as `{"mailboxes", "domains"}` counts, because their renewals, billing and Google mailbox connections are paused. It also returns `plan_active` (whether the workspace has the paid plan buying needs; always `true` on an instance that does not bill), `metered` (false on an instance that does not bill, where workspaces are charged nothing), `currency`, `mailbox_monthly_micros`, `domain_markup` (`at_cost` when the instance adds nothing to domain prices, otherwise `markup`), `limits` (`mailboxes_per_domain_max` and `mailboxes_per_domain_recommended`), `providers` (`google`, `microsoft`), `balance` (`balance_micros` and the saved `card` brand and last four, or `null`) and the saved `registrant`, or `null`. While `registrant` is `null` it also returns `registrant_prefill`, a draft from the workspace's billing details and its owner for the buyer to confirm. It also returns `default_forwarding_url` (where new domains forward unless the buyer changes it: the workspace's brand website, else the caller's email domain when it is not a free provider, else `""`), `photos` (whether mailbox photos can be uploaded on this instance), `min_card_charge_micros` (the least a store charge puts on the card), `billing_day` (the day of the month, 1 to 28, every mailbox is billed together; `null` before the first mailbox) and `next_bundle`, the next monthly mailbox charge as `{"charge_on", "mailboxes", "amount_micros"}`, or `null` when nothing is due. It never carries domain prices; those come from search and quotes. -- `GET /store/domains/search?q=acme&tlds=com,io` returns `query` and `data`: each result's `domain`, `display_name`, `tld`, `available`, `exact`, `years` (the extension's minimum registration term, such as `2` for `.ai`), `price_micros` (the price for those `years`), `renew_micros` (per year) and, for an unavailable one, `reason` (`registered`, `premium`, `reserved` or `tld_unsupported`). A `q` that is not a word or a domain name answers `400` `invalid_query`. +- `GET /store/domains/search?q=acme&tlds=com,io` returns `query` and `data`: each result's `domain`, `display_name`, `tld`, `available`, `exact`, `years` (the extension's minimum registration term, such as `2` for `.ai`), `price_micros` (the price for those `years`), `renew_micros` (per year) and, for an unavailable one, `reason` (`registered`, `premium`, `reserved` or `tld_unsupported`). Add `suggestions=false` to get only the exact matches, which answers much sooner; the dashboard shows those first and then the full search. A `q` that is not a word or a domain name answers `400` `invalid_query`. - `PUT /store/registrant` saves the registrant a domain is registered to: `first_name`, `last_name`, `organization`, `email`, `phone` (`+CC.NUMBER`), `address1`, `address2`, `city`, `state`, `postal_code` and `country` (ISO 3166-1 alpha-2). A refused field answers `400` `contact_invalid` with `details.fields`. - `POST /store/quotes` answers `201`. It takes `items`: `{"type": "domain", "domain", "years"}` lines, where `years` is the search result's `years`, and `{"type": "mailboxes", "domain", "provider", "mailboxes": [{"local_part", "first_name", "last_name", "admin"}]}` lines. Each mailbox needs both a `first_name` and a `last_name` (1 to 64 characters each; an empty one is `400` `invalid_name`). `admin: true` marks at most one mailbox per line as the domain's Google Workspace or Microsoft 365 admin; without one, the first mailbox is. Leave `admin` out for a domain that already has an admin, or the quote answers `400` `store_items_invalid`. A `mailboxes` line may carry `photo_id`, an uploaded photo for every mailbox on that domain, and each mailbox its own `photo_id`, which wins over the line's. One photo can be named on any number of mailboxes, on one domain or several. A photo the workspace does not have answers `400` `photo_not_found`. Each mailbox may also carry `signature`, `{"html", "plain"}`, the finished signature set on it when it connects, as `PATCH /emails/:id` takes `signature_html` and `signature_plain`. Nothing is filled in on the server, so fill any sender placeholders first; both empty buys the mailbox without a signature. A signature longer than a mailbox keeps (20,000 characters of HTML, 10,000 of plain text), or one for an address the quote does not buy, answers `400` `store_items_invalid`. Google mailboxes also get it as their Gmail signature; Microsoft 365 ones in Warmbly only. A `mailboxes` line with no `domain` line adds mailboxes to a domain the workspace already has in the store: one it bought, or one it connected whose `connection.status` is `active`. Nothing is charged for that domain, and the quote has no domain line for it. A connected domain that is not connected yet answers `409` `domain_not_ready`, and one with records in the way of mail `409` `dns_record_conflict`. A quote with a domain in it needs a saved registrant first (`422` `registrant_required`). The quote holds its prices for 15 minutes (`expires_at`) and returns `id`, `lines` (a mailboxes line adds `admin_email`, the admin mailbox's address, and `nameservers_change`, `true` when the domain is a connected one whose nameservers have to change after the order, to the set shown on the domain), `due_now_micros`, `recurring_monthly_micros`, `yearly_domain_renewal_micros` and `payment`: `balance_micros`, `from_balance_micros`, `card_charge_micros` (at least the minimum card charge, or the automatic reload amount when larger, whenever the balance falls short; `0` when it covers the order), `balance_after_micros` (the balance once the card was charged and the order paid), `card`, `needs_payment_method` and `auto_reload`, the workspace's automatic reload as it will be after the order: `{"enabled", "threshold_micros", "amount_micros", "store_managed"}`, where `store_managed` is a reload the store turns on and keeps sized to the mailboxes until it is changed by hand. - `POST /store/orders` `{"quote_id", "expected_due_now_micros", "forwarding_url", "enable_auto_reload"}` pays the quote from the balance, charging the saved card when it falls short (at least the minimum card charge, the rest staying on the balance), and answers `201` with the order. `enable_auto_reload` (default `true` when the workspace never set automatic reload up) turns the balance's automatic reload on with the first purchase, sized to the mailboxes; `false` leaves it off. `expected_due_now_micros` is the total the buyer was shown. A quote that has expired is priced again; when the total then differs from `expected_due_now_micros`, the answer is `409` `price_changed` with `details.quote`, a fresh quote to show and confirm, and nothing is charged. To go ahead, order again with that quote's `id`, and its `due_now_micros` as `expected_due_now_micros`, once the buyer has confirmed the new total. With no saved card to cover a shortfall it answers `402` `payment_method_required` with `setup_url`, a card-setup page that returns to the dashboard's buy page (an empty string when one could not be made); nothing is charged. A retry with the same `Idempotency-Key` never charges twice. An item the store cannot fulfil is refunded to the balance, exactly that item's line. diff --git a/docs/content/docs/guides/buy-mailboxes.mdx b/docs/content/docs/guides/buy-mailboxes.mdx index 5b7d8e1bb..c207a90d4 100644 --- a/docs/content/docs/guides/buy-mailboxes.mdx +++ b/docs/content/docs/guides/buy-mailboxes.mdx @@ -47,7 +47,7 @@ The summary turns into the setup as it happens. The new mailboxes appear on **Ma - Buying needs a Warmbly plan. Without one, the buy page offers the plans instead of the checkout. See [billing](/guides/billing/). - Domains are sold at cost. Mailboxes are $3 per mailbox per month, Google or Microsoft alike. -- The checkout offers only the providers available right now. When Microsoft 365 is not offered, it is left out of the provider choice and the order uses Google Workspace. +- If a provider cannot take new mailboxes when you order, the order fails before anything is charged, or is refunded in full if it was already charged, and you can order those mailboxes from the other provider. - Some domain endings register for at least two years, such as `.ai`. The price shown covers that whole first term. - A domain you already own can take mailboxes too, with nothing charged for the domain. - Domain prices can change over time. You always see the price, and what the domain renews at, before you pay. diff --git a/internal/api/handler/store.go b/internal/api/handler/store.go index 87497ef7a..04af7f7fc 100644 --- a/internal/api/handler/store.go +++ b/internal/api/handler/store.go @@ -140,12 +140,12 @@ func (h *Handler) canConfigureStore(c *gin.Context, userID uuid.UUID) bool { return err == nil && models.AdminPermission(perms).HasPermission(models.AdminPermManageSettings) } -// SearchStoreDomains is GET /v1/store/domains/search?q=&tlds=. +// SearchStoreDomains is GET /v1/store/domains/search?q=&tlds=&suggestions=; suggestions=false answers with the exact matches only. func (h *Handler) SearchStoreDomains(c *gin.Context) { if _, _, ok := h.storeCaller(c); !ok { return } - res, err := h.StoreService.Search(c.Request.Context(), c.Query("q"), c.QueryArray("tlds")) + res, err := h.StoreService.Search(c.Request.Context(), c.Query("q"), c.QueryArray("tlds"), c.Query("suggestions") == "false") if err != nil { storeError(c, err) return diff --git a/internal/app/aitools/tools_store.go b/internal/app/aitools/tools_store.go index 85c120144..f0020acce 100644 --- a/internal/app/aitools/tools_store.go +++ b/internal/app/aitools/tools_store.go @@ -19,7 +19,7 @@ import ( // StoreTools is the slice of the store the tools call, exactly as the REST handlers do. type StoreTools interface { Status(ctx context.Context, orgID uuid.UUID) (*store.Status, error) - Search(ctx context.Context, query string, tlds []string) (*store.SearchResult, error) + Search(ctx context.Context, query string, tlds []string, exactOnly bool) (*store.SearchResult, error) ListOrders(ctx context.Context, orgID uuid.UUID, cursor string, limit int) (*store.Page[store.Order], error) GetOrder(ctx context.Context, orgID, id uuid.UUID) (*store.Order, error) ListDomains(ctx context.Context, orgID uuid.UUID, cursor string, limit int) (*store.Page[store.Domain], error) @@ -84,7 +84,7 @@ func RegisterStoreTools(r *Registry, s StoreTools, auditSvc audit.AuditService) if err != nil { return "", err } - return storeResult(s.Search(ctx, in.Query, in.TLDs)) + return storeResult(s.Search(ctx, in.Query, in.TLDs, false)) }) read("list_store_orders", "List the workspace's domain and mailbox orders, newest first, with status, totals, refunds and setup steps.", page, func(ctx context.Context, inv Invocation, args json.RawMessage) (string, error) { diff --git a/internal/app/aitools/tools_store_test.go b/internal/app/aitools/tools_store_test.go index b7a55bac3..913d3e992 100644 --- a/internal/app/aitools/tools_store_test.go +++ b/internal/app/aitools/tools_store_test.go @@ -17,7 +17,7 @@ type moneyStore struct{ moved []string } func (m *moneyStore) Status(context.Context, uuid.UUID) (*store.Status, error) { return &store.Status{}, nil } -func (m *moneyStore) Search(context.Context, string, []string) (*store.SearchResult, error) { +func (m *moneyStore) Search(context.Context, string, []string, bool) (*store.SearchResult, error) { return &store.SearchResult{}, nil } func (m *moneyStore) ListOrders(context.Context, uuid.UUID, string, int) (*store.Page[store.Order], error) { diff --git a/internal/app/store/checkout.go b/internal/app/store/checkout.go index 9a9cc69a6..9fd697bdd 100644 --- a/internal/app/store/checkout.go +++ b/internal/app/store/checkout.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "regexp" - "slices" "strconv" "strings" "time" @@ -40,21 +39,6 @@ func itemsErr(msg string) *errx.Error { return errx.NewWithIdentifier(errx.BadRequest, CodeInvalidItems, msg) } -// checkProviders refuses mailboxes from a provider the price list does not list; an unreadable list is left to GraphKit. -func (s *Service) checkProviders(ctx context.Context, items []graphkit.QuoteItem) error { - p, err := s.livePricing(ctx) - if err != nil { - return nil - } - offered := offeredProviders(p) - for _, it := range items { - if it.Type == graphkit.ItemMailboxes && !slices.Contains(offered, it.Provider) { - return providerUnavailable(it.Provider) - } - } - return nil -} - // cleanItems validates and normalizes what the buyer asked for. func cleanItems(in []graphkit.QuoteItem) ([]graphkit.QuoteItem, bool, error) { if len(in) == 0 || len(in) > 20 { @@ -194,9 +178,6 @@ func (s *Service) CreateQuote(ctx context.Context, orgID uuid.UUID, in QuoteRequ if err != nil { return nil, err } - if err := s.checkProviders(ctx, items); err != nil { - return nil, err - } photos, err := s.checkPhotos(ctx, orgID, in.Photos, items) if err != nil { return nil, err diff --git a/internal/app/store/connection_test.go b/internal/app/store/connection_test.go index c34322677..620855340 100644 --- a/internal/app/store/connection_test.go +++ b/internal/app/store/connection_test.go @@ -168,7 +168,7 @@ func TestSavingAKeyTurnsTheStoreOnAndClearingItTurnsItOffWithoutARestart(t *test if !s.Enabled() || s.Source() != SourceSettings || !view.Configured || view.Source != SourceSettings || !view.APIKeySet || !view.WebhookSecretSet { t.Fatalf("after save: enabled %v, view %+v", s.Enabled(), view) } - if _, err := s.Search(ctx, "acme", nil); code(err) == CodeDisabled { + if _, err := s.Search(ctx, "acme", nil, false); code(err) == CodeDisabled { t.Fatal("the store still answers store_disabled after the key was saved") } diff --git a/internal/app/store/offered_providers_test.go b/internal/app/store/offered_providers_test.go deleted file mode 100644 index 6f49ca510..000000000 --- a/internal/app/store/offered_providers_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package store - -import ( - "slices" - "testing" - - "github.com/warmbly/warmbly/internal/pkg/graphkit" -) - -func TestOfferedProvidersFollowThePriceList(t *testing.T) { - google := &graphkit.Pricing{Mailboxes: []graphkit.MailboxPrice{{Provider: graphkit.ProviderGoogle, MonthlyMicros: 2_000_000}}} - if got := offeredProviders(google); !slices.Equal(got, []string{graphkit.ProviderGoogle}) { - t.Fatalf("google only: %v", got) - } - both := &graphkit.Pricing{Mailboxes: []graphkit.MailboxPrice{{Provider: graphkit.ProviderMicrosoft}, {Provider: graphkit.ProviderGoogle}}} - if got := offeredProviders(both); !slices.Equal(got, []string{graphkit.ProviderGoogle, graphkit.ProviderMicrosoft}) { - t.Fatalf("both: %v", got) - } - if err := providerUnavailable(graphkit.ProviderMicrosoft); err == nil || err.Identifier != CodeProviderUnavailable { - t.Fatalf("refusal: %+v", err) - } -} diff --git a/internal/app/store/rev2_test.go b/internal/app/store/rev2_test.go index 418f0fd7b..819e821f6 100644 --- a/internal/app/store/rev2_test.go +++ b/internal/app/store/rev2_test.go @@ -297,7 +297,7 @@ func TestSuspendedPartnerAlertsTheOperatorOnce(t *testing.T) { h.fake.Suspend(true) ctx := context.Background() for range 3 { - if _, err := h.s.Search(ctx, "acme", nil); code(err) != CodeUnavailable { + if _, err := h.s.Search(ctx, "acme", nil, false); code(err) != CodeUnavailable { t.Fatalf("search while suspended: %v", err) } } @@ -305,7 +305,7 @@ func TestSuspendedPartnerAlertsTheOperatorOnce(t *testing.T) { t.Fatalf("operator alerts = %q", ops.keys) } h.clock.advance(2 * time.Hour) - _, _ = h.s.Search(ctx, "acme", nil) + _, _ = h.s.Search(ctx, "acme", nil, false) if len(ops.keys) != 2 { t.Fatalf("an hour later the alert repeats once: %q", ops.keys) } @@ -350,7 +350,7 @@ func TestPurchasedDomainGetsItsTrackingHostAndAdminSignIn(t *testing.T) { func TestSearchPricesTheMinimumTerm(t *testing.T) { h := newHarness(t) - res, err := h.s.Search(context.Background(), "acmerobots", []string{"ai", "com"}) + res, err := h.s.Search(context.Background(), "acmerobots", []string{"ai", "com"}, false) if err != nil { t.Fatal(err) } diff --git a/internal/app/store/service.go b/internal/app/store/service.go index 7e8d387c3..2ca2bda7c 100644 --- a/internal/app/store/service.go +++ b/internal/app/store/service.go @@ -321,20 +321,6 @@ func (s *Service) livePricing(ctx context.Context) (*graphkit.Pricing, error) { // externalID is the workspace's id at GraphKit. func externalID(orgID uuid.UUID) string { return orgID.String() } -// offeredProviders are the mailbox providers the price list lists, Google first; only listed ones can be ordered. -func offeredProviders(p *graphkit.Pricing) []string { - out := []string{} - for _, want := range []string{graphkit.ProviderGoogle, graphkit.ProviderMicrosoft} { - for _, m := range p.Mailboxes { - if m.Provider == want { - out = append(out, want) - break - } - } - } - return out -} - // defaultLimits are GraphKit's caps when the price list cannot be read. var defaultLimits = graphkit.Limits{MailboxesPerDomainMax: 5, MailboxesPerDomainRecommended: 3} @@ -365,7 +351,6 @@ func (s *Service) Status(ctx context.Context, orgID uuid.UUID) (*Status, error) if p.Limits.MailboxesPerDomainMax > 0 { out.Limits = p.Limits } - out.Providers = offeredProviders(p) } active, err := s.planActive(ctx, orgID) if err != nil { @@ -594,7 +579,7 @@ func (s *Service) reopenAccount(ctx context.Context, orgID uuid.UUID) error { } // Search finds domains for a keyword or a name, at retail. -func (s *Service) Search(ctx context.Context, query string, tlds []string) (*SearchResult, error) { +func (s *Service) Search(ctx context.Context, query string, tlds []string, exactOnly bool) (*SearchResult, error) { if !s.Enabled() { return nil, errDisabled } @@ -602,7 +587,7 @@ func (s *Service) Search(ctx context.Context, query string, tlds []string) (*Sea if err != nil { return nil, err } - res, gerr := s.api().Search(ctx, q, cleanTLDs(tlds), 30) + res, gerr := s.api().Search(ctx, q, cleanTLDs(tlds), 30, exactOnly) if gerr != nil { return nil, s.upstream(ctx, "search", gerr) } diff --git a/internal/pkg/graphkit/client.go b/internal/pkg/graphkit/client.go index a36afb4bb..320f268e9 100644 --- a/internal/pkg/graphkit/client.go +++ b/internal/pkg/graphkit/client.go @@ -31,7 +31,7 @@ type API interface { ListAccounts(ctx context.Context, cursor string, limit int) (*Page[Account], error) Pricing(ctx context.Context) (*Pricing, error) - Search(ctx context.Context, query string, tlds []string, limit int) (*SearchResult, error) + Search(ctx context.Context, query string, tlds []string, limit int, exactOnly bool) (*SearchResult, error) Check(ctx context.Context, domains []string, key string) ([]DomainOffer, error) CreateQuote(ctx context.Context, externalID string, items []QuoteItem, key string) (*Quote, error) @@ -399,8 +399,12 @@ func (c *Client) Pricing(ctx context.Context) (*Pricing, error) { return ret(&out, c.get(ctx, "/pricing", nil, &out)) } -func (c *Client) Search(ctx context.Context, query string, tlds []string, limit int) (*SearchResult, error) { +// Search looks up domains for query; exactOnly skips suggestions, which answers much sooner. +func (c *Client) Search(ctx context.Context, query string, tlds []string, limit int, exactOnly bool) (*SearchResult, error) { q := url.Values{"q": {query}} + if exactOnly { + q.Set("suggestions", "false") + } if len(tlds) > 0 { q.Set("tlds", strings.Join(tlds, ",")) } diff --git a/internal/pkg/graphkit/fake.go b/internal/pkg/graphkit/fake.go index 621313e55..3b05b18bb 100644 --- a/internal/pkg/graphkit/fake.go +++ b/internal/pkg/graphkit/fake.go @@ -495,7 +495,7 @@ func (f *Fake) liveDomainLocked(name string) *fakeDomain { var fakeKeep = regexp.MustCompile(`[^a-z0-9-]+`) -func (f *Fake) Search(_ context.Context, query string, tlds []string, limit int) (*SearchResult, error) { +func (f *Fake) Search(_ context.Context, query string, tlds []string, limit int, exactOnly bool) (*SearchResult, error) { q := strings.ToLower(strings.TrimSpace(query)) if q == "" { return nil, fakeErr(http.StatusBadRequest, CodeInvalidRequest, "q is required") @@ -539,7 +539,7 @@ func (f *Fake) Search(_ context.Context, query string, tlds []string, limit int) } } keyword = fakeKeep.ReplaceAllString(keyword, "") - if keyword == "" { + if keyword == "" || exactOnly { return out, nil } suggestions := 0 diff --git a/internal/pkg/graphkit/fake_test.go b/internal/pkg/graphkit/fake_test.go index aa3cf1cb2..66690ac9f 100644 --- a/internal/pkg/graphkit/fake_test.go +++ b/internal/pkg/graphkit/fake_test.go @@ -342,7 +342,7 @@ func TestFakeSuspendedPartner(t *testing.T) { f, _ := fakeAt(time.Date(2026, 11, 16, 0, 0, 0, 0, time.UTC)) ctx := context.Background() f.Suspend(true) - if _, err := f.Search(ctx, "acme", nil, 5); CodeOf(err) != CodePartnerSuspended { + if _, err := f.Search(ctx, "acme", nil, 5, false); CodeOf(err) != CodePartnerSuspended { t.Fatalf("search while suspended: %v", err) } if _, err := f.UpsertAccount(ctx, "org", AccountInput{Name: "x"}, "k"); err == nil { diff --git a/internal/pkg/graphkit/search_exact_test.go b/internal/pkg/graphkit/search_exact_test.go new file mode 100644 index 000000000..41c1abc10 --- /dev/null +++ b/internal/pkg/graphkit/search_exact_test.go @@ -0,0 +1,38 @@ +package graphkit + +import ( + "context" + "net/http" + "testing" +) + +func TestSearchAsksForSuggestionsOnlyWhenWanted(t *testing.T) { + var got []string + c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) { + got = append(got, r.URL.Query().Get("suggestions")) + _, _ = w.Write([]byte(`{"query":"acme","data":[]}`)) + }) + for _, exact := range []bool{true, false} { + if _, err := c.Search(context.Background(), "acme", nil, 30, exact); err != nil { + t.Fatal(err) + } + } + if len(got) != 2 || got[0] != "false" || got[1] != "" { + t.Fatalf("suggestions params = %q, want [false, unset]", got) + } +} + +func TestFakeExactOnlySearchReturnsOnlyExactMatches(t *testing.T) { + res, err := NewFake().Search(context.Background(), "acme", nil, 30, true) + if err != nil { + t.Fatal(err) + } + if len(res.Data) == 0 { + t.Fatal("no exact matches") + } + for _, o := range res.Data { + if !o.Exact { + t.Fatalf("%s is a suggestion in an exact-only search", o.Domain) + } + } +} diff --git a/web/src/lib/api/client/app/store/store.ts b/web/src/lib/api/client/app/store/store.ts index 498707737..0f25fefa7 100644 --- a/web/src/lib/api/client/app/store/store.ts +++ b/web/src/lib/api/client/app/store/store.ts @@ -28,8 +28,10 @@ export async function getStoreStatus(signal?: AbortSignal): Promise return await Request({ method: "GET", url: "/store/status", authorization: true, signal }); } -export async function searchStoreDomains(q: string, signal?: AbortSignal): Promise { - return await Request({ method: "GET", url: "/store/domains/search", params: { q }, authorization: true, signal }); +/** `exactOnly` skips suggestions, which answers much sooner. */ +export async function searchStoreDomains(q: string, exactOnly: boolean, signal?: AbortSignal): Promise { + const params = exactOnly ? { q, suggestions: "false" } : { q }; + return await Request({ method: "GET", url: "/store/domains/search", params, authorization: true, signal }); } export async function putRegistrant(r: Registrant): Promise { diff --git a/web/src/lib/api/hooks/app/store/useStore.ts b/web/src/lib/api/hooks/app/store/useStore.ts index c76991a60..8ed7c9f35 100644 --- a/web/src/lib/api/hooks/app/store/useStore.ts +++ b/web/src/lib/api/hooks/app/store/useStore.ts @@ -100,16 +100,32 @@ export function storeDisconnected(s: StoreState): StoreDisconnected | null { /** Whether the workspace's purchases can be listed: the store is on, or it is locked with live purchases. */ export const storeListable = (s: StoreState) => s.kind === "on" || storeDisconnected(s) !== null; -export const domainSearchQuery = (q: string) => +export const domainSearchQuery = (q: string, exactOnly = false) => queryOptions({ - queryKey: [...STORE_KEY, "search", q], - queryFn: ({ signal }) => searchStoreDomains(q, signal), + queryKey: [...STORE_KEY, "search", q, exactOnly ? "exact" : "all"], + queryFn: ({ signal }) => searchStoreDomains(q, exactOnly, signal), staleTime: 60_000, retry: false, }); +/** + * The exact matches come back in a second or two and show first; the full search, with suggestions, + * replaces them when it lands. Loading and errors follow the full search unless the exact one is all there is. + */ export function useDomainSearch(q: string) { - return useQuery({ ...domainSearchQuery(q), enabled: q.length >= 2, placeholderData: keepPreviousData }); + const enabled = q.length >= 2; + const exact = useQuery({ ...domainSearchQuery(q, true), enabled, placeholderData: keepPreviousData }); + const full = useQuery({ ...domainSearchQuery(q), enabled, placeholderData: keepPreviousData }); + const current = (r: typeof full) => r.data !== undefined && !r.isPlaceholderData; + const data = current(full) ? full.data : current(exact) ? exact.data : (full.data ?? exact.data); + return { + data, + isFetching: full.isFetching, + isPending: full.isPending && exact.isPending, + isError: full.isError && !current(exact), + error: full.error ?? exact.error, + refetch: () => Promise.all([exact.refetch(), full.refetch()]), + }; } // A quote holds its prices for 15 minutes. It is re-asked for a little before it lapses, and on