Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(shopping): a US / Europe market switch for ChatGPT Shopping, with its source per market (#1459)

Gökhan Geyikca7ad1ec58d6
diff --git a/supabase/migrations/00267_shopping_overview_chatgpt_market.sql b/supabase/migrations/00267_shopping_overview_chatgpt_market.sql
new file mode 100644
index 000000000..6face2525
--- /dev/null
+++ b/supabase/migrations/00267_shopping_overview_chatgpt_market.sql
@@ -0,0 +1,126 @@
+-- Shopping: keep ChatGPT Shopping to one market in the Overview (#1278).
+--
+-- ChatGPT Shopping picks products differently by market (the US from OpenAI's
+-- product index, Europe from Google Shopping), so the Shopping page has a
+-- US / Europe switch that keeps ChatGPT Shopping's cards to the market's
+-- regions. The card reads apply it as a PostgREST filter; the Overview's KPIs
+-- and charts come from this function, whose `p_regions` narrows every
+-- platform. `p_chatgpt_regions` narrows ChatGPT Shopping's results and cards
+-- only and lets every other platform through. Null, the default, changes
+-- nothing: a call without it reads exactly what it did before.
+--
+-- APPLY BEFORE DEPLOYING THE WEB. The new web passes `p_chatgpt_regions`, which
+-- the old function doesn't have; the old web's calls match the new function,
+-- since the parameter has a default.
+--
+-- A new parameter makes a new overload under create or replace, and PostgREST
+-- would then have two candidates for one call. So the 6-argument version is
+-- dropped first, and the new one gets the grants it had. The body is 00115's,
+-- with one condition added to the results, cards and trend.
+
+drop function if exists public.shopping_overview(
+ uuid, timestamptz, timestamptz, text[], text[], timestamptz
+);
+
+create or replace function public.shopping_overview(
+ p_brand_id uuid,
+ p_from timestamptz default null,
+ p_to timestamptz default null,
+ p_platforms text[] default null,
+ p_regions text[] default null,
+ p_trend_from timestamptz default null,
+ p_chatgpt_regions text[] default null
+) returns jsonb
+language plpgsql
+stable
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+begin
+ return (
+ with results as materialized (
+ select r.id, r.platform
+ from public.prompt_results r
+ where r.brand_id = p_brand_id
+ and (p_from is null or r.created_at >= p_from)
+ and (p_to is null or r.created_at <= p_to)
+ and (p_platforms is null or r.platform = any (p_platforms))
+ and (p_regions is null or r.region = any (p_regions))
+ and (p_chatgpt_regions is null or r.platform <> 'chatgpt-shopping'
+ or r.region = any (p_chatgpt_regions))
+ ),
+ by_platform as (
+ select res.platform,
+ count(*) as total_results,
+ count(*) filter (where exists (
+ select 1 from public.prompt_result_shopping_cards c
+ where c.prompt_result_id = res.id
+ )) as results_with_cards
+ from results res
+ group by res.platform
+ ),
+ cards as materialized (
+ select c.matched_brand_role, c.merchant_domain
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and (p_from is null or c.created_at >= p_from)
+ and (p_to is null or c.created_at <= p_to)
+ and (p_platforms is null or c.platform = any (p_platforms))
+ and (p_regions is null or c.region = any (p_regions))
+ and (p_chatgpt_regions is null or c.platform <> 'chatgpt-shopping'
+ or c.region = any (p_chatgpt_regions))
+ ),
+ top_merchant as (
+ select merchant_domain, count(*) as card_count
+ from cards
+ where matched_brand_role = 'own' and merchant_domain is not null
+ group by merchant_domain
+ order by count(*) desc, merchant_domain
+ limit 1
+ ),
+ trend as (
+ select (c.created_at at time zone 'UTC')::date as day,
+ count(*) filter (where c.matched_brand_role = 'own') as own_cards,
+ count(*) as total_cards
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and p_trend_from is not null
+ and c.created_at >= p_trend_from
+ and (p_platforms is null or c.platform = any (p_platforms))
+ and (p_regions is null or c.region = any (p_regions))
+ and (p_chatgpt_regions is null or c.platform <> 'chatgpt-shopping'
+ or c.region = any (p_chatgpt_regions))
+ group by 1
+ )
+ select jsonb_build_object(
+ 'total_results', coalesce((select sum(total_results) from by_platform), 0),
+ 'results_with_cards', coalesce((select sum(results_with_cards) from by_platform), 0),
+ 'total_cards', (select count(*) from cards),
+ 'own_cards', (select count(*) from cards where matched_brand_role = 'own'),
+ 'top_merchant', (select jsonb_build_object('domain', merchant_domain,
+ 'card_count', card_count)
+ from top_merchant),
+ 'by_platform', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'platform', platform,
+ 'total_results', total_results,
+ 'results_with_cards', results_with_cards)
+ order by platform)
+ from by_platform),
+ '[]'::jsonb),
+ 'trend', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'day', day,
+ 'own_cards', own_cards,
+ 'total_cards', total_cards)
+ order by day)
+ from trend),
+ '[]'::jsonb)
+ )
+ );
+end;
+$$;
+
+grant execute on function public.shopping_overview(
+ uuid, timestamptz, timestamptz, text[], text[], timestamptz, text[]
+) to public, anon, authenticated, service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 3a98ba4e9..ad5685fe5 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -38430,3 +38430,133 @@ comment on table public.content_draft_inputs is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00267_shopping_overview_chatgpt_market.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Shopping: keep ChatGPT Shopping to one market in the Overview (#1278).
+--
+-- ChatGPT Shopping picks products differently by market (the US from OpenAI's
+-- product index, Europe from Google Shopping), so the Shopping page has a
+-- US / Europe switch that keeps ChatGPT Shopping's cards to the market's
+-- regions. The card reads apply it as a PostgREST filter; the Overview's KPIs
+-- and charts come from this function, whose `p_regions` narrows every
+-- platform. `p_chatgpt_regions` narrows ChatGPT Shopping's results and cards
+-- only and lets every other platform through. Null, the default, changes
+-- nothing: a call without it reads exactly what it did before.
+--
+-- APPLY BEFORE DEPLOYING THE WEB. The new web passes `p_chatgpt_regions`, which
+-- the old function doesn't have; the old web's calls match the new function,
+-- since the parameter has a default.
+--
+-- A new parameter makes a new overload under create or replace, and PostgREST
+-- would then have two candidates for one call. So the 6-argument version is
+-- dropped first, and the new one gets the grants it had. The body is 00115's,
+-- with one condition added to the results, cards and trend.
+
+drop function if exists public.shopping_overview(
+ uuid, timestamptz, timestamptz, text[], text[], timestamptz
+);
+
+create or replace function public.shopping_overview(
+ p_brand_id uuid,
+ p_from timestamptz default null,
+ p_to timestamptz default null,
+ p_platforms text[] default null,
+ p_regions text[] default null,
+ p_trend_from timestamptz default null,
+ p_chatgpt_regions text[] default null
+) returns jsonb
+language plpgsql
+stable
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+begin
+ return (
+ with results as materialized (
+ select r.id, r.platform
+ from public.prompt_results r
+ where r.brand_id = p_brand_id
+ and (p_from is null or r.created_at >= p_from)
+ and (p_to is null or r.created_at <= p_to)
+ and (p_platforms is null or r.platform = any (p_platforms))
+ and (p_regions is null or r.region = any (p_regions))
+ and (p_chatgpt_regions is null or r.platform <> 'chatgpt-shopping'
+ or r.region = any (p_chatgpt_regions))
+ ),
+ by_platform as (
+ select res.platform,
+ count(*) as total_results,
+ count(*) filter (where exists (
+ select 1 from public.prompt_result_shopping_cards c
+ where c.prompt_result_id = res.id
+ )) as results_with_cards
+ from results res
+ group by res.platform
+ ),
+ cards as materialized (
+ select c.matched_brand_role, c.merchant_domain
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and (p_from is null or c.created_at >= p_from)
+ and (p_to is null or c.created_at <= p_to)
+ and (p_platforms is null or c.platform = any (p_platforms))
+ and (p_regions is null or c.region = any (p_regions))
+ and (p_chatgpt_regions is null or c.platform <> 'chatgpt-shopping'
+ or c.region = any (p_chatgpt_regions))
+ ),
+ top_merchant as (
+ select merchant_domain, count(*) as card_count
+ from cards
+ where matched_brand_role = 'own' and merchant_domain is not null
+ group by merchant_domain
+ order by count(*) desc, merchant_domain
+ limit 1
+ ),
+ trend as (
+ select (c.created_at at time zone 'UTC')::date as day,
+ count(*) filter (where c.matched_brand_role = 'own') as own_cards,
+ count(*) as total_cards
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and p_trend_from is not null
+ and c.created_at >= p_trend_from
+ and (p_platforms is null or c.platform = any (p_platforms))
+ and (p_regions is null or c.region = any (p_regions))
+ and (p_chatgpt_regions is null or c.platform <> 'chatgpt-shopping'
+ or c.region = any (p_chatgpt_regions))
+ group by 1
+ )
+ select jsonb_build_object(
+ 'total_results', coalesce((select sum(total_results) from by_platform), 0),
+ 'results_with_cards', coalesce((select sum(results_with_cards) from by_platform), 0),
+ 'total_cards', (select count(*) from cards),
+ 'own_cards', (select count(*) from cards where matched_brand_role = 'own'),
+ 'top_merchant', (select jsonb_build_object('domain', merchant_domain,
+ 'card_count', card_count)
+ from top_merchant),
+ 'by_platform', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'platform', platform,
+ 'total_results', total_results,
+ 'results_with_cards', results_with_cards)
+ order by platform)
+ from by_platform),
+ '[]'::jsonb),
+ 'trend', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'day', day,
+ 'own_cards', own_cards,
+ 'total_cards', total_cards)
+ order by day)
+ from trend),
+ '[]'::jsonb)
+ )
+ );
+end;
+$$;
+
+grant execute on function public.shopping_overview(
+ uuid, timestamptz, timestamptz, text[], text[], timestamptz, text[]
+) to public, anon, authenticated, service_role;
+
diff --git a/web/messages/en.json b/web/messages/en.json
index a4852df17..bb647f073 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -6681,6 +6681,14 @@
"filterRegion": "Region",
"filterPlatform": "Platform",
"filterDateRange": "Date range",
+ "market": {
+ "label": "ChatGPT Shopping market",
+ "us": "US",
+ "europe": "Europe",
+ "sourceLabel": "ChatGPT's product source:",
+ "sourceUs": "OpenAI product index · via Shopify",
+ "sourceEurope": "Google Shopping · via Merchant Center"
+ },
"noBrandTitle": "No brand selected",
"noBrandDescription": "Select or create a brand to see shopping card analytics for it.",
"emptyTitle": "No shopping cards yet",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_market-switch.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_market-switch.test.tsx
new file mode 100644
index 000000000..d1a404bfc
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_market-switch.test.tsx
@@ -0,0 +1,192 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import { ShoppingMarketSwitch, useShoppingMarket } from './_market-switch';
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const countriesByBrand = new Map<string, string[]>();
+vi.mock('@/lib/actions/shopping-market', () => ({
+ getBrandMarketCountries: vi.fn(async (brandId: string) => countriesByBrand.get(brandId) ?? []),
+}));
+
+let container: HTMLDivElement;
+let root: Root;
+const onRegionReset = vi.fn();
+
+function Harness({ brandId, region }: { brandId: string; region: string }) {
+ const state = useShoppingMarket(brandId, region);
+ return (
+ <>
+ <output
+ data-testid="state"
+ data-ready={String(state.ready)}
+ data-market={state.market ?? ''}
+ data-filter={state.filter ?? ''}
+ />
+ <ShoppingMarketSwitch
+ state={state}
+ onSelect={(market) => {
+ state.select(market);
+ onRegionReset();
+ }}
+ />
+ </>
+ );
+}
+
+async function render(brandId: string, region = 'all') {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <Harness brandId={brandId} region={region} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const state = () => container.querySelector<HTMLOutputElement>('[data-testid="state"]')!.dataset;
+const group = () => container.querySelector<HTMLElement>('[role="group"]');
+const button = (name: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === name)!;
+const pressed = () =>
+ [...container.querySelectorAll('button[aria-pressed="true"]')].map((b) => b.textContent);
+
+async function click(name: string) {
+ await act(async () => {
+ button(name).click();
+ });
+}
+
+// An in-memory localStorage: the test environment has none.
+const store = new Map<string, string>();
+const memoryStorage = {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+ clear: () => store.clear(),
+};
+
+beforeEach(() => {
+ store.clear();
+ countriesByBrand.clear();
+ onRegionReset.mockClear();
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: memoryStorage });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('ShoppingMarketSwitch', () => {
+ it('opens on the US for a brand with US countries, with OpenAI as the source', async () => {
+ countriesByBrand.set('b1', ['DE', 'US-CA']);
+ await render('b1');
+
+ expect(state()).toMatchObject({ ready: 'true', market: 'us', filter: 'us' });
+ expect(pressed()).toEqual(['US']);
+ expect(container.textContent).toContain('OpenAI product index · via Shopify');
+ });
+
+ it('opens on Europe for a brand whose countries are all European', async () => {
+ countriesByBrand.set('b1', ['de', 'GB', 'CH']);
+ await render('b1');
+
+ expect(state()).toMatchObject({ market: 'europe', filter: 'europe' });
+ expect(pressed()).toEqual(['Europe']);
+ expect(container.textContent).toContain('Google Shopping · via Merchant Center');
+ });
+
+ it('shows no switch and makes no claim for a brand with no market', async () => {
+ countriesByBrand.set('b1', ['TR', 'IN']);
+ await render('b1');
+
+ expect(state()).toMatchObject({ ready: 'true', market: '', filter: '' });
+ expect(group()).toBeNull();
+ expect(container.textContent).not.toContain('product source');
+ });
+
+ it('switches the market and its source line, and remembers it per brand', async () => {
+ countriesByBrand.set('b1', ['US']);
+ countriesByBrand.set('b2', ['US']);
+ await render('b1');
+
+ await click('Europe');
+ expect(state()).toMatchObject({ market: 'europe', filter: 'europe' });
+ expect(pressed()).toEqual(['Europe']);
+ expect(container.textContent).toContain('Google Shopping · via Merchant Center');
+ expect(store.get('aeo:shopping-market:b1')).toBe('europe');
+ expect(onRegionReset).toHaveBeenCalledTimes(1);
+
+ // Another brand keeps its own default.
+ await render('b2');
+ expect(state()).toMatchObject({ market: 'us' });
+
+ // Back on the first brand, the choice is remembered.
+ await render('b1');
+ expect(state()).toMatchObject({ market: 'europe' });
+ });
+
+ it('ignores a remembered market for a brand that has no market', async () => {
+ store.set('aeo:shopping-market:b1', 'us');
+ countriesByBrand.set('b1', ['TR']);
+ await render('b1');
+
+ expect(state()).toMatchObject({ market: '', filter: '' });
+ expect(group()).toBeNull();
+ });
+
+ it('works without browser storage', async () => {
+ const broken = {
+ getItem: () => {
+ throw new Error('blocked');
+ },
+ setItem: () => {
+ throw new Error('blocked');
+ },
+ };
+ Object.defineProperty(window, 'localStorage', { configurable: true, value: broken });
+ countriesByBrand.set('b1', ['FR']);
+ await render('b1');
+
+ expect(state()).toMatchObject({ market: 'europe' });
+ await click('US');
+ expect(state()).toMatchObject({ market: 'us', filter: 'us' });
+ });
+
+ it('follows a picked region, which narrows the cards on its own', async () => {
+ countriesByBrand.set('b1', ['US', 'DE', 'TR']);
+
+ await render('b1', 'DE');
+ expect(state()).toMatchObject({ market: 'us', filter: '' });
+ expect(pressed()).toEqual(['Europe']);
+ expect(container.textContent).toContain('Google Shopping · via Merchant Center');
+
+ // A region outside both markets: nothing pressed, no source claim.
+ await render('b1', 'TR');
+ expect(pressed()).toEqual([]);
+ expect(container.textContent).not.toContain('product source');
+ });
+
+ it('is a labelled group of native buttons, so the keyboard reaches each market', async () => {
+ countriesByBrand.set('b1', ['US']);
+ await render('b1');
+
+ const labelId = group()!.getAttribute('aria-labelledby')!;
+ expect(document.getElementById(labelId)?.textContent).toBe('ChatGPT Shopping market');
+ for (const name of ['US', 'Europe']) {
+ expect(button(name).getAttribute('type')).toBe('button');
+ expect(button(name).hasAttribute('aria-pressed')).toBe(true);
+ }
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_market-switch.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_market-switch.tsx
new file mode 100644
index 000000000..03e0a106a
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_market-switch.tsx
@@ -0,0 +1,174 @@
+'use client';
+
+import { useCallback, useEffect, useId, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { AIProviderAvatar } from '@/components/ai-provider-avatar';
+import { getBrandMarketCountries } from '@/lib/actions/shopping-market';
+import {
+ defaultMarket,
+ isShoppingMarket,
+ marketForCountry,
+ SHOPPING_MARKETS,
+ type ShoppingMarket,
+} from '@/lib/shopping/markets';
+import { cn } from '@/lib/utils';
+
+const storageKey = (brandId: string) => `aeo:shopping-market:${brandId}`;
+
+function readStoredMarket(brandId: string): ShoppingMarket | null {
+ try {
+ const stored = window.localStorage.getItem(storageKey(brandId));
+ return isShoppingMarket(stored) ? stored : null;
+ } catch {
+ return null;
+ }
+}
+
+function storeMarket(brandId: string, market: ShoppingMarket) {
+ try {
+ window.localStorage.setItem(storageKey(brandId), market);
+ } catch {
+ // Private mode: the choice holds until the page is opened again.
+ }
+}
+
+const SOURCE_KEYS = {
+ us: 'sourceUs',
+ europe: 'sourceEurope',
+} as const satisfies Record<ShoppingMarket, string>;
+
+export interface ShoppingMarketState {
+ /** False until the brand's countries are read: the page waits, so it loads once. */
+ ready: boolean;
+ /** The brand's market: the remembered choice, else its default. Null when it has none. */
+ market: ShoppingMarket | null;
+ /**
+ * What the switch and the source line show: the market, or while the region
+ * filter has one picked, that region's market (null outside both).
+ */
+ shown: ShoppingMarket | null;
+ /**
+ * The market ChatGPT Shopping cards are kept to. Unset while a region is
+ * picked: the region already narrows every platform's cards.
+ */
+ filter: ShoppingMarket | undefined;
+ select: (market: ShoppingMarket) => void;
+}
+
+/**
+ * The Shopping page's market (#1278), from the brand's countries (its
+ * domains' and its prompts' locations) and the choice remembered for the
+ * brand in this browser.
+ *
+ * It composes with the filter bar's region rather than stacking on it: with
+ * All regions the market keeps ChatGPT Shopping's cards to its regions; a
+ * picked region narrows every platform on its own, and the switch shows that
+ * region's market. Choosing a market clears the region (the page does that),
+ * so the two never contradict each other.
+ */
+export function useShoppingMarket(brandId: string | null, region: string): ShoppingMarketState {
+ // Keyed by brand, so another brand never shows this one's market.
+ const [resolved, setResolved] = useState<{
+ brandId: string;
+ market: ShoppingMarket | null;
+ } | null>(null);
+
+ useEffect(() => {
+ if (!brandId) return;
+ let cancelled = false;
+ getBrandMarketCountries(brandId)
+ // A failed read makes no claim: no market, no switch.
+ .then(defaultMarket, () => null)
+ .then((fallback) => {
+ if (cancelled) return;
+ setResolved({ brandId, market: fallback && (readStoredMarket(brandId) ?? fallback) });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId]);
+
+ const select = useCallback(
+ (next: ShoppingMarket) => {
+ if (!brandId) return;
+ storeMarket(brandId, next);
+ setResolved({ brandId, market: next });
+ },
+ [brandId],
+ );
+
+ const ready = brandId !== null && resolved?.brandId === brandId;
+ const market = ready ? (resolved?.market ?? null) : null;
+ const regionPicked = region !== 'all';
+
+ return {
+ ready,
+ market,
+ shown: market && (regionPicked ? marketForCountry(region) : market),
+ filter: market && !regionPicked ? market : undefined,
+ select,
+ };
+}
+
+/**
+ * The US / Europe switch, with where ChatGPT's products come from in the
+ * market shown. Nothing renders for a brand with no market: its countries
+ * get no source claim. The Readiness checklist and the Content Editor's
+ * Shopping tab are to share this switch and its state once they exist.
+ */
+export function ShoppingMarketSwitch({
+ state,
+ onSelect,
+}: {
+ state: ShoppingMarketState;
+ onSelect: (market: ShoppingMarket) => void;
+}) {
+ const t = useTranslations('shopping.market');
+ const labelId = useId();
+
+ if (!state.market) return null;
+ const { shown } = state;
+
+ return (
+ <div className="flex flex-wrap items-center gap-3 rounded-lg border bg-card px-3 py-2 text-sm">
+ <span className="flex items-center gap-2">
+ <span aria-hidden="true">
+ <AIProviderAvatar provider="openai" />
+ </span>
+ <span id={labelId} className="text-xs font-medium text-muted-foreground">
+ {t('label')}
+ </span>
+ </span>
+ <div
+ role="group"
+ aria-labelledby={labelId}
+ className="flex overflow-hidden rounded-md border"
+ >
+ {SHOPPING_MARKETS.map((market) => (
+ <button
+ key={market}
+ type="button"
+ aria-pressed={shown === market}
+ onClick={() => onSelect(market)}
+ className={cn(
+ 'px-3 py-1 text-xs font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',
+ shown === market
+ ? 'bg-primary text-primary-foreground'
+ : 'bg-card text-foreground hover:bg-muted',
+ )}
+ >
+ {t(market)}
+ </button>
+ ))}
+ </div>
+ <p className="text-xs text-muted-foreground" aria-live="polite">
+ {shown && (
+ <>
+ {t('sourceLabel')}{' '}
+ <span className="font-medium text-foreground">{t(SOURCE_KEYS[shown])}</span>
+ </>
+ )}
+ </p>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
index 109da1cf2..b494827ab 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
@@ -92,6 +92,7 @@ import { PLATFORM_LABELS } from '@/config/platform-labels';
import { formatRegionDisplay } from '@/lib/region';
import type { AmazonShareDropAlert } from '@/lib/shopping-amazon-share-alert';
import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';
+import { ShoppingMarketSwitch, useShoppingMarket } from './_market-switch';
const DATE_PRESETS: ShoppingDatePreset[] = ['7d', '30d', '90d', 'all'];
@@ -116,6 +117,7 @@ export default function ShoppingPage() {
const [datePreset, setDatePreset] = useState<ShoppingDatePreset>('30d');
const [platform, setPlatform] = useState<string>('all');
const [region, setRegion] = useState<string>('all');
+ const shoppingMarket = useShoppingMarket(activeBrandId, region);
const [filterOpts, setFilterOpts] = useState<{ platforms: string[]; regions: string[] }>({
platforms: [],
@@ -123,7 +125,9 @@ export default function ShoppingPage() {
});
const [kpis, setKpis] = useState<ShoppingKpis | null>(null);
const [charts, setCharts] = useState<ShoppingChartData | null>(null);
- const [loading, setLoading] = useState(false);
+ // True from the start: the first load waits for the market, and an idle
+ // page with no KPIs yet would read as empty.
+ const [loading, setLoading] = useState(true);
const [amazonShareDropAlert, setAmazonShareDropAlert] = useState<AmazonShareDropAlert | null>(
null,
);
@@ -141,8 +145,9 @@ export default function ShoppingPage() {
datePreset,
platforms: platform === 'all' ? undefined : [platform],
regions: region === 'all' ? undefined : [region],
+ chatgptMarket: shoppingMarket.filter,
}),
- [datePreset, platform, region],
+ [datePreset, platform, region, shoppingMarket.filter],
);
// Load filter options once per brand so the dropdowns only show
@@ -209,8 +214,9 @@ export default function ShoppingPage() {
}, [activeBrandId, filters, hasFullAccess]);
useEffect(() => {
+ if (!shoppingMarket.ready) return;
void loadData();
- }, [loadData]);
+ }, [loadData, shoppingMarket.ready]);
// This alert always evaluates five consecutive rolling seven-day windows
// ending at query time, independently of display/platform/region filters.
@@ -283,6 +289,14 @@ export default function ShoppingPage() {
regionOpts={filterOpts.regions}
/>
+ <ShoppingMarketSwitch
+ state={shoppingMarket}
+ onSelect={(market) => {
+ shoppingMarket.select(market);
+ setRegion('all');
+ }}
+ />
+
{isEmpty ? (
<EmptyState title={t('emptyTitle')} description={t('emptyDescription')} />
) : (
diff --git a/web/src/lib/actions/shopping-market.test.ts b/web/src/lib/actions/shopping-market.test.ts
new file mode 100644
index 000000000..1986f8d77
--- /dev/null
+++ b/web/src/lib/actions/shopping-market.test.ts
@@ -0,0 +1,74 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * #1278 — the brand's countries come from its domains and from every prompt's
+ * location codes, read past PostgREST's 1,000-row cap.
+ */
+
+const PAGE_CAP = 1000;
+
+let domains: Array<{ country: string | null }> = [];
+let prompts: Array<{ id: string; regions: string[] | null }> = [];
+let promptRanges: Array<[number, number]> = [];
+
+function fakeQueryBuilder(table: string) {
+ let range: [number, number] = [0, PAGE_CAP - 1];
+ const builder = {
+ select: () => builder,
+ eq: () => builder,
+ order: () => builder,
+ range: (from: number, to: number) => {
+ range = [from, to];
+ if (table === 'prompts') promptRanges.push(range);
+ return builder;
+ },
+ then: (onFulfilled: (v: unknown) => unknown) => {
+ const data =
+ table === 'brand_domains'
+ ? domains
+ : prompts.slice(range[0], Math.min(range[1] + 1, range[0] + PAGE_CAP));
+ return Promise.resolve({ data, error: null }).then(onFulfilled);
+ },
+ };
+ return builder;
+}
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: async () => ({ from: (table: string) => fakeQueryBuilder(table) }),
+}));
+
+import { getBrandMarketCountries } from './shopping-market';
+
+beforeEach(() => {
+ domains = [];
+ prompts = [];
+ promptRanges = [];
+});
+
+describe('getBrandMarketCountries', () => {
+ it("joins the domains' countries and the prompts' locations, deduped", async () => {
+ domains = [{ country: 'US' }, { country: null }, { country: ' de ' }, { country: '' }];
+ prompts = [
+ { id: 'p1', regions: ['US', 'US-CA'] },
+ { id: 'p2', regions: ['GB'] },
+ { id: 'p3', regions: null },
+ { id: 'p4', regions: [] },
+ ];
+
+ expect(await getBrandMarketCountries('brand-1')).toEqual(['GB', 'US', 'US-CA', 'de']);
+ });
+
+ it('reads every prompt past the 1,000-row cap', async () => {
+ prompts = Array.from({ length: 2100 }, (_, i) => ({
+ id: `p${i}`,
+ regions: i === 2099 ? ['FR'] : ['US'],
+ }));
+
+ expect(await getBrandMarketCountries('brand-1')).toEqual(['FR', 'US']);
+ expect(promptRanges).toEqual([
+ [0, 999],
+ [1000, 1999],
+ [2000, 2999],
+ ]);
+ });
+});
diff --git a/web/src/lib/actions/shopping-market.ts b/web/src/lib/actions/shopping-market.ts
new file mode 100644
index 000000000..fb07d5209
--- /dev/null
+++ b/web/src/lib/actions/shopping-market.ts
@@ -0,0 +1,50 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+
+const PROMPT_PAGE_SIZE = 1000;
+const PROMPT_MAX_ROWS = 20_000;
+
+/**
+ * The brand's countries, for its AI shopping market (#1278): its domains'
+ * `country` and every location code its prompts track (`prompts.regions`,
+ * states included), deduped and sorted. Codes come back as stored;
+ * `marketForCountry` normalizes them. RLS scopes both reads to the caller's
+ * organization.
+ */
+export async function getBrandMarketCountries(brandId: string): Promise<string[]> {
+ const supabase = await createClient();
+ const countries = new Set<string>();
+ const add = (code: string | null | undefined) => {
+ const trimmed = code?.trim();
+ if (trimmed) countries.add(trimmed);
+ };
+
+ const readDomains = async () => {
+ const { data, error } = await supabase
+ .from('brand_domains')
+ .select('country')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(error.message);
+ for (const row of data ?? []) add(row.country);
+ };
+
+ // Paged: an unpaged select stops at PostgREST's 1,000-row cap (#922).
+ const readPrompts = async () => {
+ for (let start = 0; start < PROMPT_MAX_ROWS; start += PROMPT_PAGE_SIZE) {
+ const { data, error } = await supabase
+ .from('prompts')
+ .select('id, regions, prompt_sets!inner(brand_id)')
+ .eq('prompt_sets.brand_id', brandId)
+ .order('id')
+ .range(start, start + PROMPT_PAGE_SIZE - 1);
+ if (error) throw new Error(error.message);
+ const rows = data ?? [];
+ for (const row of rows) for (const code of row.regions ?? []) add(code);
+ if (rows.length < PROMPT_PAGE_SIZE) break;
+ }
+ };
+
+ await Promise.all([readDomains(), readPrompts()]);
+ return [...countries].sort();
+}
diff --git a/web/src/lib/actions/shopping.test.ts b/web/src/lib/actions/shopping.test.ts
index b2d494ed6..4336954a3 100644
--- a/web/src/lib/actions/shopping.test.ts
+++ b/web/src/lib/actions/shopping.test.ts
@@ -11,10 +11,19 @@ interface QueryState {
eq: Record<string, unknown>;
range?: [number, number];
head?: boolean;
+ or?: string;
}
const PAGE_CAP = 1000;
+/** Applies the one `or` filter the actions build: `platform.neq.X,region.in.(A,B)`. */
+function keptByOr(filter: string | undefined, row: Record<string, unknown>): boolean {
+ if (!filter) return true;
+ const match = /^platform\.neq\.([^,]+),region\.in\.\((.*)\)$/.exec(filter);
+ if (!match) throw new Error(`unexpected or filter: ${filter}`);
+ return row.platform !== match[1] || match[2].split(',').includes(String(row.region));
+}
+
let cards: Array<Record<string, unknown>> = [];
let overviewRow: Record<string, unknown> = {};
let rpcCalls: Array<{ fn: string; args: Record<string, unknown> }> = [];
@@ -33,8 +42,9 @@ function resolveQuery(state: QueryState) {
if (state.table === 'prompt_result_shopping_cards') {
const rows = cards.filter(
(c) =>
- state.eq.matched_brand_role === undefined ||
- c.matched_brand_role === state.eq.matched_brand_role,
+ (state.eq.matched_brand_role === undefined ||
+ c.matched_brand_role === state.eq.matched_brand_role) &&
+ keptByOr(state.or, c),
);
if (state.head) return { data: null, count: rows.length, error: null };
// Like PostgREST: an unpaged select still stops at the cap.
@@ -58,6 +68,10 @@ function fakeQueryBuilder(table: string) {
gte: () => builder,
lte: () => builder,
in: () => builder,
+ or: (filter: string) => {
+ state.or = filter;
+ return builder;
+ },
order: () => builder,
range: (from: number, to: number) => {
state.range = [from, to];
@@ -169,6 +183,84 @@ describe('getCompetitorSummary', () => {
});
});
+describe('ChatGPT Shopping market (#1278)', () => {
+ const placed = (
+ i: number,
+ role: 'own' | 'competitor' | 'other',
+ platform: string,
+ region: string,
+ matched?: string,
+ ) => ({ ...card(i, role, matched), product_title: `Product ${i}`, platform, region });
+
+ it("keeps ChatGPT Shopping's cards to the market and leaves other platforms alone", async () => {
+ cards = [
+ placed(1, 'own', 'chatgpt-shopping', 'DE'),
+ placed(2, 'own', 'chatgpt-shopping', 'GB'),
+ placed(3, 'own', 'chatgpt-shopping', 'US'),
+ placed(4, 'own', 'chatgpt-shopping', 'TR'),
+ placed(5, 'own', 'copilot-web', 'TR'),
+ placed(6, 'own', 'google-aimode', 'US'),
+ ];
+ const products = await getOwnProducts('brand-1', {
+ datePreset: '30d',
+ chatgptMarket: 'europe',
+ });
+
+ expect(products.map((p) => p.product_title).sort()).toEqual([
+ 'Product 1',
+ 'Product 2',
+ 'Product 5',
+ 'Product 6',
+ ]);
+ });
+
+ it('counts US states as the US market', async () => {
+ cards = [
+ placed(1, 'own', 'chatgpt-shopping', 'US-CA'),
+ placed(2, 'own', 'chatgpt-shopping', 'DE'),
+ ];
+ const products = await getOwnProducts('brand-1', { datePreset: '30d', chatgptMarket: 'us' });
+
+ expect(products.map((p) => p.product_title)).toEqual(['Product 1']);
+ });
+
+ it('applies to the share-of-voice total as well as the competitor cards', async () => {
+ cards = [
+ placed(1, 'competitor', 'chatgpt-shopping', 'US', 'c-1'),
+ placed(2, 'competitor', 'chatgpt-shopping', 'FR', 'c-1'),
+ placed(3, 'other', 'chatgpt-shopping', 'FR'),
+ placed(4, 'other', 'copilot-web', 'FR'),
+ ];
+ const summary = await getCompetitorSummary('brand-1', {
+ datePreset: '30d',
+ chatgptMarket: 'us',
+ });
+
+ expect(summary[0]).toMatchObject({ competitor_id: 'c-1', card_count: 1 });
+ expect(summary[0].sov).toBeCloseTo(1 / 2);
+ });
+
+ it("passes the market's regions to the Overview RPC only when a market applies", async () => {
+ await getShoppingOverview('brand-1', { datePreset: '30d', chatgptMarket: 'europe' });
+ await getShoppingOverview('brand-1', { datePreset: '30d' });
+
+ expect(rpcCalls.map((c) => c.fn)).toEqual(['shopping_overview', 'shopping_overview']);
+ expect(rpcCalls[0].args.p_chatgpt_regions).toEqual(
+ expect.arrayContaining(['DE', 'FR', 'GB', 'CH']),
+ );
+ expect(rpcCalls[0].args.p_chatgpt_regions).not.toContain('US');
+ expect(rpcCalls[0].args.p_regions).toBeUndefined();
+ expect(rpcCalls[1].args.p_chatgpt_regions).toBeUndefined();
+ });
+
+ it('adds no filter without a market', async () => {
+ cards = [placed(1, 'own', 'chatgpt-shopping', 'TR')];
+ await getOwnProducts('brand-1', { datePreset: '30d' });
+
+ expect(cardCalls.every((c) => c.or === undefined)).toBe(true);
+ });
+});
+
describe('getShoppingOverview', () => {
it('builds KPIs and charts from one RPC call', async () => {
const { kpis, charts } = await getShoppingOverview('brand-1', {
diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.ts
index 2f18a63c3..dea7d030b 100644
--- a/web/src/lib/actions/shopping.ts
+++ b/web/src/lib/actions/shopping.ts
@@ -6,6 +6,7 @@ import {
detectAmazonShareDrop,
type AmazonShareDropAlert,
} from '@/lib/shopping-amazon-share-alert';
+import { marketRegionCodes, type ShoppingMarket } from '@/lib/shopping/markets';
/**
* Server actions for the Shopping dashboard page. Reads from the
@@ -29,6 +30,12 @@ export interface ShoppingFilters {
platforms?: string[];
/** Region codes. */
regions?: string[];
+ /**
+ * ChatGPT Shopping's market (#1278): its results and cards are kept to the
+ * market's regions, other platforms' are unaffected. Applies to the card
+ * reads and to the Overview (`p_chatgpt_regions`, 00267).
+ */
+ chatgptMarket?: ShoppingMarket;
}
export interface ShoppingKpis {
@@ -106,6 +113,7 @@ async function loadShoppingOverview(
p_platforms: filters.platforms?.length ? filters.platforms : undefined,
p_regions: filters.regions?.length ? filters.regions : undefined,
p_trend_from: trendFrom,
+ p_chatgpt_regions: filters.chatgptMarket ? marketRegionCodes(filters.chatgptMarket) : undefined,
});
if (error) throw new Error(error.message);
return data as unknown as ShoppingOverviewRow;
@@ -253,6 +261,14 @@ async function fetchAllCards<T>(
return rows;
}
+/**
+ * A PostgREST `or` filter keeping ChatGPT Shopping's cards to one market's
+ * regions (#1278) and letting every other platform's cards through.
+ */
+function chatgptMarketFilter(market: ShoppingMarket): string {
+ return `platform.neq.chatgpt-shopping,region.in.(${marketRegionCodes(market).join(',')})`;
+}
+
/** A card query over the filter window: brand, dates, platforms and regions. */
function cardsInWindow(
supabase: Awaited<ReturnType<typeof createClient>>,
@@ -267,6 +283,7 @@ function cardsInWindow(
if (expandedTo) query = query.lte('created_at', expandedTo);
if (filters.platforms?.length) query = query.in('platform', filters.platforms);
if (filters.regions?.length) query = query.in('region', filters.regions);
+ if (filters.chatgptMarket) query = query.or(chatgptMarketFilter(filters.chatgptMarket));
return query;
}
@@ -522,6 +539,9 @@ export async function getCompetitorSummary(
if (filters.platforms?.length)
totalCardsQuery = totalCardsQuery.in('platform', filters.platforms);
if (filters.regions?.length) totalCardsQuery = totalCardsQuery.in('region', filters.regions);
+ if (filters.chatgptMarket) {
+ totalCardsQuery = totalCardsQuery.or(chatgptMarketFilter(filters.chatgptMarket));
+ }
const competitorCardsQuery = fetchAllCards<{
matched_brand_id: string | null;
diff --git a/web/src/lib/shopping/markets.test.ts b/web/src/lib/shopping/markets.test.ts
new file mode 100644
index 000000000..9ec283bc2
--- /dev/null
+++ b/web/src/lib/shopping/markets.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ defaultMarket,
+ isShoppingMarket,
+ marketForCountry,
+ marketRegionCodes,
+ SHOPPING_MARKETS,
+} from './markets';
+
+describe('marketForCountry', () => {
+ it('maps the US to the US market', () => {
+ expect(marketForCountry('US')).toBe('us');
+ });
+
+ it('maps a US state code to the US market', () => {
+ expect(marketForCountry('US-CA')).toBe('us');
+ expect(marketForCountry('US-DE')).toBe('us');
+ expect(marketForCountry('US-DC')).toBe('us');
+ });
+
+ it('maps EU countries to Europe', () => {
+ for (const code of ['DE', 'FR', 'IT', 'ES', 'NL', 'SE', 'PL', 'IE', 'AT']) {
+ expect(marketForCountry(code)).toBe('europe');
+ }
+ });
+
+ it('maps the rest of the EEA to Europe', () => {
+ for (const code of ['NO', 'IS', 'LI']) {
+ expect(marketForCountry(code)).toBe('europe');
+ }
+ });
+
+ it('maps the UK to Europe, written as GB or UK', () => {
+ expect(marketForCountry('GB')).toBe('europe');
+ expect(marketForCountry('UK')).toBe('europe');
+ });
+
+ it('maps Switzerland to Europe', () => {
+ expect(marketForCountry('CH')).toBe('europe');
+ });
+
+ it('maps any other country to no market', () => {
+ for (const code of ['TR', 'IN', 'AE', 'CA', 'JP', 'BR', 'AU', 'SG']) {
+ expect(marketForCountry(code)).toBeNull();
+ }
+ });
+
+ it('reads free-text domain countries: lower case and padded', () => {
+ expect(marketForCountry(' us ')).toBe('us');
+ expect(marketForCountry('de')).toBe('europe');
+ expect(marketForCountry('us-ny')).toBe('us');
+ });
+
+ it('maps blanks and codes that are not locations to no market', () => {
+ expect(marketForCountry(null)).toBeNull();
+ expect(marketForCountry(undefined)).toBeNull();
+ expect(marketForCountry('')).toBeNull();
+ expect(marketForCountry('United States')).toBeNull();
+ expect(marketForCountry('USA')).toBeNull();
+ // Sub-country codes exist for US states only.
+ expect(marketForCountry('US-ZZ')).toBeNull();
+ expect(marketForCountry('US-')).toBeNull();
+ expect(marketForCountry('DE-BY')).toBeNull();
+ expect(marketForCountry('US-CA-LA')).toBeNull();
+ });
+});
+
+describe('defaultMarket', () => {
+ it('opens on the US when any country is in the US', () => {
+ expect(defaultMarket(['US'])).toBe('us');
+ expect(defaultMarket(['DE', 'FR', 'US-CA'])).toBe('us');
+ expect(defaultMarket(['TR', 'US'])).toBe('us');
+ });
+
+ it('opens on Europe when every country is European', () => {
+ expect(defaultMarket(['DE'])).toBe('europe');
+ expect(defaultMarket(['GB', 'CH', 'FR'])).toBe('europe');
+ });
+
+ it('has no market when a country outside both markets sits beside European ones', () => {
+ expect(defaultMarket(['DE', 'TR'])).toBeNull();
+ });
+
+ it('has no market for unmapped countries or none at all', () => {
+ expect(defaultMarket(['TR', 'IN'])).toBeNull();
+ expect(defaultMarket([])).toBeNull();
+ });
+
+ it('ignores blank domain countries', () => {
+ expect(defaultMarket([null, '', ' ', 'DE'])).toBe('europe');
+ expect(defaultMarket([null, undefined])).toBeNull();
+ });
+});
+
+describe('marketRegionCodes', () => {
+ it('lists the US and every US state', () => {
+ const codes = marketRegionCodes('us');
+ expect(codes).toContain('US');
+ expect(codes).toContain('US-CA');
+ expect(codes).toContain('US-DC');
+ expect(codes.every((code) => marketForCountry(code) === 'us')).toBe(true);
+ });
+
+ it('lists the European countries', () => {
+ const codes = marketRegionCodes('europe');
+ expect(codes).toEqual(expect.arrayContaining(['DE', 'FR', 'GB', 'CH', 'NO']));
+ expect(codes).not.toContain('TR');
+ expect(codes.every((code) => marketForCountry(code) === 'europe')).toBe(true);
+ });
+});
+
+describe('isShoppingMarket', () => {
+ it('accepts the markets and nothing else', () => {
+ for (const market of SHOPPING_MARKETS) expect(isShoppingMarket(market)).toBe(true);
+ expect(isShoppingMarket('eu')).toBe(false);
+ expect(isShoppingMarket(null)).toBe(false);
+ });
+});
diff --git a/web/src/lib/shopping/markets.ts b/web/src/lib/shopping/markets.ts
new file mode 100644
index 000000000..55756b2a4
--- /dev/null
+++ b/web/src/lib/shopping/markets.ts
@@ -0,0 +1,115 @@
+import { US_STATES } from '@/config/prompt-options';
+
+/**
+ * AI shopping markets (#1278).
+ *
+ * ChatGPT Shopping picks products differently by market: in the US from
+ * OpenAI's own product index, built from product feeds; in Europe still from
+ * Google Shopping. What a brand should fix for ChatGPT depends on the market,
+ * so every e-commerce surface reads it from here: the Shopping page now, the
+ * Readiness checklist and the Content Editor's Shopping tab once they exist.
+ *
+ * Countries arrive as location codes (`prompts.regions` and
+ * `prompt_result_shopping_cards.region`: `DE`, `US-CA`) or as the free-text
+ * `brand_domains.country` (`US`, `tr`, `UK`). A country outside both markets
+ * maps to none, and gets no claim about where ChatGPT's products come from.
+ */
+
+export type ShoppingMarket = 'us' | 'europe';
+
+/** The switch's order. */
+export const SHOPPING_MARKETS: readonly ShoppingMarket[] = ['us', 'europe'];
+
+/** The EU, the rest of the EEA (Iceland, Liechtenstein, Norway), the UK and Switzerland. */
+const EUROPE_COUNTRIES: readonly string[] = [
+ 'AT',
+ 'BE',
+ 'BG',
+ 'CH',
+ 'CY',
+ 'CZ',
+ 'DE',
+ 'DK',
+ 'EE',
+ 'ES',
+ 'FI',
+ 'FR',
+ 'GB',
+ 'GR',
+ 'HR',
+ 'HU',
+ 'IE',
+ 'IS',
+ 'IT',
+ 'LI',
+ 'LT',
+ 'LU',
+ 'LV',
+ 'MT',
+ 'NL',
+ 'NO',
+ 'PL',
+ 'PT',
+ 'RO',
+ 'SE',
+ 'SI',
+ 'SK',
+];
+
+const EUROPE = new Set(EUROPE_COUNTRIES);
+
+const US_STATE_CODES = new Set<string>(US_STATES.map((state) => state.code));
+
+/** How people write a country in a free-text field, against its ISO code. */
+const COUNTRY_ALIASES: ReadonlyMap<string, string> = new Map([['UK', 'GB']]);
+
+export function isShoppingMarket(value: unknown): value is ShoppingMarket {
+ return value === 'us' || value === 'europe';
+}
+
+/**
+ * The market a country or location code belongs to: the US for `US` and its
+ * states (`US-CA`), Europe for an EU / EEA country, the UK or Switzerland,
+ * null for anything else. Sub-country codes exist for US states only, so any
+ * other one (`DE-BY`, `US-ZZ`) is not a location and maps to none.
+ */
+export function marketForCountry(code: string | null | undefined): ShoppingMarket | null {
+ if (typeof code !== 'string') return null;
+ const [rawCountry, state, ...rest] = code.trim().toUpperCase().split('-');
+ if (rest.length > 0) return null;
+ const country = COUNTRY_ALIASES.get(rawCountry) ?? rawCountry;
+ if (country === 'US') return state === undefined || US_STATE_CODES.has(state) ? 'us' : null;
+ if (state !== undefined) return null;
+ return EUROPE.has(country) ? 'europe' : null;
+}
+
+/**
+ * The market a brand opens on, from its countries: the US when any of them is
+ * in the US, Europe when every one of them is European, none otherwise. With
+ * none there is no switch and no source claim. Blank entries (a domain with
+ * no country) say nothing either way.
+ */
+export function defaultMarket(
+ countries: Iterable<string | null | undefined>,
+): ShoppingMarket | null {
+ let european = false;
+ let other = false;
+ for (const code of countries) {
+ if (!code?.trim()) continue;
+ const market = marketForCountry(code);
+ if (market === 'us') return 'us';
+ if (market === 'europe') european = true;
+ else other = true;
+ }
+ return european && !other ? 'europe' : null;
+}
+
+/**
+ * Every location code in a market: the values a tracked result's region, and
+ * so a shopping card's, can hold there. The US includes its states, which
+ * prompts can target.
+ */
+export function marketRegionCodes(market: ShoppingMarket): string[] {
+ if (market === 'us') return ['US', ...US_STATES.map((state) => `US-${state.code}`)];
+ return [...EUROPE_COUNTRIES];
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 895b54d50..53c63f0f0 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -4979,6 +4979,7 @@ export type Database = {
shopping_overview: {
Args: {
p_brand_id: string
+ p_chatgpt_regions?: string[]
p_from?: string
p_platforms?: string[]
p_regions?: string[]