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): show where AI sends shoppers, and flag resellers cheaper than the brand (#1460)

Gökhan Geyik703ef0098bea
diff --git a/supabase/migrations/00268_shopping_merchant_split.sql b/supabase/migrations/00268_shopping_merchant_split.sql
new file mode 100644
index 000000000..33e7155c9
--- /dev/null
+++ b/supabase/migrations/00268_shopping_merchant_split.sql
@@ -0,0 +1,176 @@
+-- Shopping: where AI sends shoppers, and resellers cheaper than the brand (#1277).
+--
+-- 00225 stores each card's destination (merchant_kind, marketplace,
+-- listing_id). Two reads over the brand's own products (cards with
+-- matched_brand_role = 'own') build on it, in the Overview tab's window and
+-- filters (p_from, p_to, p_platforms, p_regions and ChatGPT Shopping's market,
+-- p_chatgpt_regions, as in shopping_overview since 00267):
+--
+-- 1. shopping_merchant_split: the cards per destination (your store,
+-- Amazon, Walmart, eBay, other marketplaces, other resellers). Cards
+-- with no merchant URL (merchant_kind null) are counted apart, never
+-- spread over the segments, so the segments add up to the classified
+-- cards.
+-- 2. shopping_own_product_offers: the lowest price per merchant, listing,
+-- title and currency, with the link of the card that showed it. The web
+-- app matches these offers to the brand's store and flags the cheaper
+-- resellers (web/src/lib/shopping-reseller-price-alert.ts).
+--
+-- Both are aggregated here, not read as rows: PostgREST caps rows at 1,000,
+-- and the offers come back as one jsonb value for the same reason. On the
+-- largest brands the own products are a few hundred cards a quarter, read
+-- through the (brand_id, matched_brand_role) indexes.
+--
+-- Security definer behind the same membership check as
+-- shopping_amazon_share_weekly (00225), its sibling over these columns: the
+-- check runs once, a non-member gets no rows (or an empty list), and the
+-- reads below use the indexes without the per-row RLS filter.
+--
+-- Apply after 00267 and before deploying the web: the web passes
+-- p_chatgpt_regions to both, as it does to shopping_overview.
+
+create or replace function public.shopping_merchant_split(
+ 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_chatgpt_regions text[] default null
+)
+returns table (
+ own_store_cards bigint,
+ amazon_cards bigint,
+ walmart_cards bigint,
+ ebay_cards bigint,
+ other_marketplace_cards bigint,
+ reseller_cards bigint,
+ unclassified_cards bigint
+)
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1
+ from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id
+ and pf.id = auth.uid()
+ ) then
+ return;
+ end if;
+
+ return query
+ select
+ count(*) filter (where c.merchant_kind = 'own'),
+ count(*) filter (where c.merchant_kind = 'marketplace' and c.marketplace = 'amazon'),
+ count(*) filter (where c.merchant_kind = 'marketplace' and c.marketplace = 'walmart'),
+ count(*) filter (where c.merchant_kind = 'marketplace' and c.marketplace = 'ebay'),
+ count(*) filter (where c.merchant_kind = 'marketplace'
+ and coalesce(c.marketplace, '') not in ('amazon', 'walmart', 'ebay')),
+ count(*) filter (where c.merchant_kind = 'reseller'),
+ count(*) filter (where c.merchant_kind is null)
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and c.matched_brand_role = 'own'
+ 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));
+end;
+$$;
+
+revoke all on function public.shopping_merchant_split(uuid, timestamptz, timestamptz, text[], text[], text[]) from public, anon;
+grant execute on function public.shopping_merchant_split(uuid, timestamptz, timestamptz, text[], text[], text[]) to authenticated, service_role;
+
+-- One entry per merchant offer of the brand's own products: the classified
+-- cards with a price, grouped by destination, listing, title (case and outer
+-- spaces aside) and currency. Repeat sightings of the same offer collapse to
+-- its lowest price, all the price rule needs, so the list stays short.
+create or replace function public.shopping_own_product_offers(
+ 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_chatgpt_regions text[] default null
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1
+ from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id
+ and pf.id = auth.uid()
+ ) then
+ return '[]'::jsonb;
+ end if;
+
+ return (
+ with offers as (
+ select
+ c.merchant_kind,
+ c.marketplace,
+ c.merchant_domain,
+ c.listing_id,
+ min(c.product_title) as product_title,
+ upper(btrim(c.price_currency)) as price_currency,
+ min(c.price_amount) as price_amount,
+ (array_agg(c.merchant_url order by c.price_amount, c.created_at desc))[1] as merchant_url
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and c.matched_brand_role = 'own'
+ and c.merchant_kind is not null
+ and c.merchant_url is not null
+ and c.price_amount > 0
+ and nullif(btrim(c.price_currency), '') is not null
+ 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))
+ group by
+ c.merchant_kind,
+ c.marketplace,
+ c.merchant_domain,
+ c.listing_id,
+ lower(btrim(c.product_title)),
+ upper(btrim(c.price_currency))
+ )
+ -- Without both a store offer and another merchant's there is nothing to
+ -- compare: return an empty list rather than every store offer.
+ select coalesce(
+ jsonb_agg(jsonb_build_object(
+ 'merchant_kind', o.merchant_kind,
+ 'marketplace', o.marketplace,
+ 'merchant_domain', o.merchant_domain,
+ 'merchant_url', o.merchant_url,
+ 'listing_id', o.listing_id,
+ 'product_title', o.product_title,
+ 'price_amount', o.price_amount,
+ 'price_currency', o.price_currency)),
+ '[]'::jsonb)
+ from offers o
+ where exists (select 1 from offers x where x.merchant_kind = 'own')
+ and exists (select 1 from offers x where x.merchant_kind <> 'own')
+ );
+end;
+$$;
+
+revoke all on function public.shopping_own_product_offers(uuid, timestamptz, timestamptz, text[], text[], text[]) from public, anon;
+grant execute on function public.shopping_own_product_offers(uuid, timestamptz, timestamptz, text[], text[], text[]) to authenticated, service_role;
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index ad5685fe5..ab3bc2c46 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -38560,3 +38560,183 @@ grant execute on function public.shopping_overview(
uuid, timestamptz, timestamptz, text[], text[], timestamptz, text[]
) to public, anon, authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00268_shopping_merchant_split.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Shopping: where AI sends shoppers, and resellers cheaper than the brand (#1277).
+--
+-- 00225 stores each card's destination (merchant_kind, marketplace,
+-- listing_id). Two reads over the brand's own products (cards with
+-- matched_brand_role = 'own') build on it, in the Overview tab's window and
+-- filters (p_from, p_to, p_platforms, p_regions and ChatGPT Shopping's market,
+-- p_chatgpt_regions, as in shopping_overview since 00267):
+--
+-- 1. shopping_merchant_split: the cards per destination (your store,
+-- Amazon, Walmart, eBay, other marketplaces, other resellers). Cards
+-- with no merchant URL (merchant_kind null) are counted apart, never
+-- spread over the segments, so the segments add up to the classified
+-- cards.
+-- 2. shopping_own_product_offers: the lowest price per merchant, listing,
+-- title and currency, with the link of the card that showed it. The web
+-- app matches these offers to the brand's store and flags the cheaper
+-- resellers (web/src/lib/shopping-reseller-price-alert.ts).
+--
+-- Both are aggregated here, not read as rows: PostgREST caps rows at 1,000,
+-- and the offers come back as one jsonb value for the same reason. On the
+-- largest brands the own products are a few hundred cards a quarter, read
+-- through the (brand_id, matched_brand_role) indexes.
+--
+-- Security definer behind the same membership check as
+-- shopping_amazon_share_weekly (00225), its sibling over these columns: the
+-- check runs once, a non-member gets no rows (or an empty list), and the
+-- reads below use the indexes without the per-row RLS filter.
+--
+-- Apply after 00267 and before deploying the web: the web passes
+-- p_chatgpt_regions to both, as it does to shopping_overview.
+
+create or replace function public.shopping_merchant_split(
+ 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_chatgpt_regions text[] default null
+)
+returns table (
+ own_store_cards bigint,
+ amazon_cards bigint,
+ walmart_cards bigint,
+ ebay_cards bigint,
+ other_marketplace_cards bigint,
+ reseller_cards bigint,
+ unclassified_cards bigint
+)
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1
+ from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id
+ and pf.id = auth.uid()
+ ) then
+ return;
+ end if;
+
+ return query
+ select
+ count(*) filter (where c.merchant_kind = 'own'),
+ count(*) filter (where c.merchant_kind = 'marketplace' and c.marketplace = 'amazon'),
+ count(*) filter (where c.merchant_kind = 'marketplace' and c.marketplace = 'walmart'),
+ count(*) filter (where c.merchant_kind = 'marketplace' and c.marketplace = 'ebay'),
+ count(*) filter (where c.merchant_kind = 'marketplace'
+ and coalesce(c.marketplace, '') not in ('amazon', 'walmart', 'ebay')),
+ count(*) filter (where c.merchant_kind = 'reseller'),
+ count(*) filter (where c.merchant_kind is null)
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and c.matched_brand_role = 'own'
+ 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));
+end;
+$$;
+
+revoke all on function public.shopping_merchant_split(uuid, timestamptz, timestamptz, text[], text[], text[]) from public, anon;
+grant execute on function public.shopping_merchant_split(uuid, timestamptz, timestamptz, text[], text[], text[]) to authenticated, service_role;
+
+-- One entry per merchant offer of the brand's own products: the classified
+-- cards with a price, grouped by destination, listing, title (case and outer
+-- spaces aside) and currency. Repeat sightings of the same offer collapse to
+-- its lowest price, all the price rule needs, so the list stays short.
+create or replace function public.shopping_own_product_offers(
+ 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_chatgpt_regions text[] default null
+)
+returns jsonb
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+set plan_cache_mode to 'force_custom_plan'
+as $$
+begin
+ if auth.role() is distinct from 'service_role' and not exists (
+ select 1
+ from public.brands b
+ join public.profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id
+ and pf.id = auth.uid()
+ ) then
+ return '[]'::jsonb;
+ end if;
+
+ return (
+ with offers as (
+ select
+ c.merchant_kind,
+ c.marketplace,
+ c.merchant_domain,
+ c.listing_id,
+ min(c.product_title) as product_title,
+ upper(btrim(c.price_currency)) as price_currency,
+ min(c.price_amount) as price_amount,
+ (array_agg(c.merchant_url order by c.price_amount, c.created_at desc))[1] as merchant_url
+ from public.prompt_result_shopping_cards c
+ where c.brand_id = p_brand_id
+ and c.matched_brand_role = 'own'
+ and c.merchant_kind is not null
+ and c.merchant_url is not null
+ and c.price_amount > 0
+ and nullif(btrim(c.price_currency), '') is not null
+ 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))
+ group by
+ c.merchant_kind,
+ c.marketplace,
+ c.merchant_domain,
+ c.listing_id,
+ lower(btrim(c.product_title)),
+ upper(btrim(c.price_currency))
+ )
+ -- Without both a store offer and another merchant's there is nothing to
+ -- compare: return an empty list rather than every store offer.
+ select coalesce(
+ jsonb_agg(jsonb_build_object(
+ 'merchant_kind', o.merchant_kind,
+ 'marketplace', o.marketplace,
+ 'merchant_domain', o.merchant_domain,
+ 'merchant_url', o.merchant_url,
+ 'listing_id', o.listing_id,
+ 'product_title', o.product_title,
+ 'price_amount', o.price_amount,
+ 'price_currency', o.price_currency)),
+ '[]'::jsonb)
+ from offers o
+ where exists (select 1 from offers x where x.merchant_kind = 'own')
+ and exists (select 1 from offers x where x.merchant_kind <> 'own')
+ );
+end;
+$$;
+
+revoke all on function public.shopping_own_product_offers(uuid, timestamptz, timestamptz, text[], text[], text[]) from public, anon;
+grant execute on function public.shopping_own_product_offers(uuid, timestamptz, timestamptz, text[], text[], text[]) to authenticated, service_role;
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index bb647f073..c10f6d84e 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -6734,7 +6734,33 @@
"drawerTimestamp": "Timestamp",
"drawerPlatform": "Platform",
"drawerRegion": "Region",
- "drawerCardsTitle": "Cards returned"
+ "drawerCardsTitle": "Cards returned",
+ "merchantSplit": {
+ "title": "Where AI sends shoppers",
+ "description": "Where the cards for your products link, in the selected window.",
+ "own_store": "Your store",
+ "amazon": "Amazon",
+ "walmart": "Walmart",
+ "ebay": "eBay",
+ "other_marketplace": "Other marketplaces",
+ "reseller": "Other resellers",
+ "cards": "{count, plural, one {# card} other {# cards}}",
+ "underOnePercent": "<1%",
+ "partLabel": "{destination}: {cards}, {percent}",
+ "unclassified": "{count, plural, one {# card has no merchant link and is} other {# cards have no merchant link and are}} not in the split.",
+ "empty": "No cards for your products link to a merchant in this window."
+ },
+ "resellerPrices": {
+ "title": "Resellers cheaper than you",
+ "description": "Your products sold elsewhere for at least {percent} less than the lowest price on your store, in the same currency, in the selected window.",
+ "empty": "No reseller undercuts your store in this window.",
+ "yourStore": "Your store",
+ "reseller": "Reseller",
+ "lowerBy": "{percent} lower",
+ "untitled": "Untitled product",
+ "unknownMerchant": "Unknown merchant",
+ "openLink": "Open {merchant} in a new tab"
+ }
},
"reports": {
"title": "Reports",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/merchant_destinations.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/merchant_destinations.test.tsx
new file mode 100644
index 000000000..379fdd0d5
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/merchant_destinations.test.tsx
@@ -0,0 +1,120 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+import { toMerchantSplit } from '@/lib/shopping-merchant-split';
+import { detectResellerPriceAlerts } from '@/lib/shopping-reseller-price-alert';
+import { MerchantSplitCard } from './merchant_split_card';
+import { ResellerPriceAlerts } from './reseller_price_alerts';
+
+/**
+ * #1277: the Overview tab's "Where AI sends shoppers" split and the
+ * "Resellers cheaper than you" list.
+ */
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+function render(node: React.ReactNode) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ {node}
+ </NextIntlClientProvider>,
+ );
+ });
+ return container.textContent ?? '';
+}
+
+describe('MerchantSplitCard', () => {
+ it('lists each destination with its cards and share, and the unclassified apart', () => {
+ const split = toMerchantSplit({
+ own_store_cards: 1,
+ amazon_cards: 300,
+ walmart_cards: 0,
+ ebay_cards: 0,
+ other_marketplace_cards: 99,
+ reseller_cards: 600,
+ unclassified_cards: 12,
+ });
+ const text = render(<MerchantSplitCard split={split} loading={false} />);
+
+ expect(text).toContain('Where AI sends shoppers');
+ expect(text).toContain('Your store1 card<1%');
+ expect(text).toContain('Amazon300 cards30%');
+ expect(text).toContain('Walmart0 cards0%');
+ expect(text).toContain('Other resellers600 cards60%');
+ expect(text).toContain('12 cards have no merchant link and are not in the split.');
+ // Only destinations with cards are drawn in the bar.
+ expect(container.querySelectorAll('[role="img"] > span')).toHaveLength(4);
+ });
+
+ it('says so when no card links to a merchant', () => {
+ const text = render(<MerchantSplitCard split={toMerchantSplit(null)} loading={false} />);
+ expect(text).toContain('No cards for your products link to a merchant in this window.');
+ expect(container.querySelector('[role="img"]')).toBeNull();
+ });
+});
+
+describe('ResellerPriceAlerts', () => {
+ it('shows both prices and opens both links in a new tab', () => {
+ const alerts = detectResellerPriceAlerts([
+ {
+ merchantKind: 'own',
+ marketplace: null,
+ merchantDomain: 'acme.example',
+ merchantUrl: 'https://acme.example/runner',
+ listingId: null,
+ productTitle: 'Acme Runner',
+ priceAmount: 120,
+ priceCurrency: 'USD',
+ },
+ {
+ merchantKind: 'marketplace',
+ marketplace: 'amazon',
+ merchantDomain: 'amazon.com',
+ merchantUrl: 'https://www.amazon.com/dp/B000000001',
+ listingId: 'B000000001',
+ productTitle: 'Acme Runner',
+ priceAmount: 99,
+ priceCurrency: 'USD',
+ },
+ ]);
+ const text = render(<ResellerPriceAlerts alerts={alerts} loading={false} />);
+
+ expect(text).toContain('Acme Runner');
+ expect(text).toContain('18% lower');
+ expect(text).toContain('$120.00');
+ expect(text).toContain('$99.00');
+ const links = [...container.querySelectorAll('a')];
+ expect(links.map((a) => a.getAttribute('href'))).toEqual([
+ 'https://acme.example/runner',
+ 'https://www.amazon.com/dp/B000000001',
+ ]);
+ for (const link of links) {
+ expect(link.getAttribute('target')).toBe('_blank');
+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');
+ }
+ });
+
+ it('says so when no reseller undercuts the store', () => {
+ expect(render(<ResellerPriceAlerts alerts={[]} loading={false} />)).toContain(
+ 'No reseller undercuts your store in this window.',
+ );
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/merchant_split_card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/merchant_split_card.tsx
new file mode 100644
index 000000000..e45fcfe32
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/merchant_split_card.tsx
@@ -0,0 +1,109 @@
+'use client';
+
+import { useLocale, useTranslations } from 'next-intl';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Skeleton } from '@/components/ui/skeleton';
+import { numberFormat } from '@/lib/number-format';
+import { cn } from '@/lib/utils';
+import type {
+ MerchantSplitPart,
+ MerchantSplitSegment,
+ ShoppingMerchantSplit,
+} from '@/lib/shopping-merchant-split';
+
+/**
+ * Each destination's colour. The same steps hold in both themes: checked for
+ * lightness, colour-blind separation between neighbours and 3:1 contrast on
+ * the light and the dark card. Other resellers, the remainder, stay grey.
+ */
+const SEGMENT_FILL: Record<MerchantSplitSegment, string> = {
+ own_store: 'bg-emerald-600',
+ amazon: 'bg-violet-600',
+ walmart: 'bg-amber-600',
+ ebay: 'bg-sky-600',
+ other_marketplace: 'bg-rose-600',
+ reseller: 'bg-muted-foreground/40',
+};
+
+/** "Where AI sends shoppers" (#1277): the destinations of your products' cards. */
+export function MerchantSplitCard({
+ split,
+ loading,
+}: {
+ split: ShoppingMerchantSplit | null;
+ loading: boolean;
+}) {
+ const t = useTranslations('shopping.merchantSplit');
+ const f = numberFormat(useLocale());
+ // A segment with cards never reads 0%.
+ const percent = (part: MerchantSplitPart) =>
+ part.cards > 0 && part.percent === 0 ? t('underOnePercent') : f.percent(part.percent, 0);
+ const describe = (part: MerchantSplitPart) =>
+ t('partLabel', {
+ destination: t(part.segment),
+ cards: t('cards', { count: part.cards }),
+ percent: percent(part),
+ });
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>
+ <p className="text-xs text-muted-foreground">{t('description')}</p>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ {loading ? (
+ <Skeleton className="h-[132px] w-full" />
+ ) : !split || split.classifiedCards === 0 ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">{t('empty')}</p>
+ ) : (
+ <>
+ <div
+ role="img"
+ aria-label={split.parts
+ .filter((part) => part.cards > 0)
+ .map(describe)
+ .join('; ')}
+ className="flex h-2.5 gap-0.5 overflow-hidden rounded-full"
+ >
+ {split.parts
+ .filter((part) => part.cards > 0)
+ .map((part) => (
+ <span
+ key={part.segment}
+ title={describe(part)}
+ className={cn('h-full min-w-1 basis-0', SEGMENT_FILL[part.segment])}
+ style={{ flexGrow: part.cards }}
+ />
+ ))}
+ </div>
+ <ul className="grid gap-x-6 gap-y-1.5 text-xs sm:grid-cols-2">
+ {split.parts.map((part) => (
+ <li key={part.segment} className="flex items-center justify-between gap-3">
+ <span className="flex min-w-0 items-center gap-2">
+ <span
+ aria-hidden
+ className={cn('h-2 w-2 shrink-0 rounded-[2px]', SEGMENT_FILL[part.segment])}
+ />
+ <span className="truncate text-foreground">{t(part.segment)}</span>
+ </span>
+ <span className="shrink-0 tabular-nums text-muted-foreground">
+ {t('cards', { count: part.cards })}
+ <span className="ml-2 inline-block w-9 text-right font-medium text-foreground">
+ {percent(part)}
+ </span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ {!loading && split && split.unclassifiedCards > 0 && (
+ <p className="border-t pt-3 text-xs text-muted-foreground">
+ {t('unclassified', { count: split.unclassifiedCards })}
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
index b494827ab..ef1c77d61 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
@@ -93,6 +93,9 @@ 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';
+import { MerchantSplitCard } from './merchant_split_card';
+import { ResellerPriceAlerts } from './reseller_price_alerts';
+import { useMerchantDestinations } from './use_merchant_destinations';
const DATE_PRESETS: ShoppingDatePreset[] = ['7d', '30d', '90d', 'all'];
@@ -149,6 +152,13 @@ export default function ShoppingPage() {
}),
[datePreset, platform, region, shoppingMarket.filter],
);
+ // Like the Overview's own load, these wait for the market.
+ const destinations = useMerchantDestinations(
+ activeBrandId,
+ filters,
+ hasFullAccess && shoppingMarket.ready,
+ );
+ const destinationsLoading = destinations.loading || !shoppingMarket.ready;
// Load filter options once per brand so the dropdowns only show
// platform / region values that actually appear in this brand's data.
@@ -318,18 +328,27 @@ export default function ShoppingPage() {
<TabsContent value="overview" className="space-y-6">
{hasFullAccess ? (
- <div className="grid gap-4 lg:grid-cols-2">
- <PlatformCardRateChart
- t={t}
- data={charts?.platformCardRate ?? []}
- loading={loading}
- />
- <OwnPresenceTrendChart
- t={t}
- data={charts?.ownPresenceTrend ?? []}
- loading={loading}
- />
- </div>
+ <>
+ <div className="grid gap-4 lg:grid-cols-2">
+ <PlatformCardRateChart
+ t={t}
+ data={charts?.platformCardRate ?? []}
+ loading={loading}
+ />
+ <OwnPresenceTrendChart
+ t={t}
+ data={charts?.ownPresenceTrend ?? []}
+ loading={loading}
+ />
+ </div>
+ <div className="grid gap-4 lg:grid-cols-2">
+ <MerchantSplitCard split={destinations.split} loading={destinationsLoading} />
+ <ResellerPriceAlerts
+ alerts={destinations.priceAlerts}
+ loading={destinationsLoading}
+ />
+ </div>
+ </>
) : (
<UpgradeCard t={t} requiredPlan={requiredPlanFor('shopping_analytics')} />
)}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/reseller_price_alerts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/reseller_price_alerts.tsx
new file mode 100644
index 000000000..18663d3b9
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/reseller_price_alerts.tsx
@@ -0,0 +1,145 @@
+'use client';
+
+import { useLocale, useTranslations } from 'next-intl';
+import { ExternalLink, TrendingDown } from 'lucide-react';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Skeleton } from '@/components/ui/skeleton';
+import { numberFormat } from '@/lib/number-format';
+import {
+ RESELLER_PRICE_MIN_DISCOUNT,
+ type ResellerPriceAlert,
+} from '@/lib/shopping-reseller-price-alert';
+
+function formatPrice(locale: string, amount: number, currency: string): string {
+ try {
+ return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount);
+ } catch {
+ // Not an ISO 4217 code: show the amount with the code as stored.
+ return `${new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(amount)} ${currency}`;
+ }
+}
+
+/** A merchant's price and its link, opened in a new tab. */
+function MerchantPrice({
+ label,
+ price,
+ url,
+ domain,
+ emphasis = false,
+}: {
+ label: string;
+ price: string;
+ url: string | null;
+ domain: string | null;
+ emphasis?: boolean;
+}) {
+ const t = useTranslations('shopping.resellerPrices');
+ const name = domain ?? t('unknownMerchant');
+ return (
+ <div className="min-w-0">
+ <span className="block text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
+ {label}
+ </span>
+ <span
+ className={
+ emphasis
+ ? 'block font-semibold tabular-nums text-foreground'
+ : 'block font-medium tabular-nums text-foreground'
+ }
+ >
+ {price}
+ </span>
+ {url ? (
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={t('openLink', { merchant: name })}
+ className="inline-flex max-w-full items-center gap-0.5 text-xs text-muted-foreground transition-colors hover:text-primary"
+ >
+ <span className="truncate">{name}</span>
+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden />
+ </a>
+ ) : (
+ <span className="block truncate text-xs text-muted-foreground">{name}</span>
+ )}
+ </div>
+ );
+}
+
+/**
+ * "Reseller cheaper than you" (#1277): the brand's products another merchant
+ * sells for at least 5% less than the lowest price on its own store.
+ */
+export function ResellerPriceAlerts({
+ alerts,
+ loading,
+}: {
+ alerts: ResellerPriceAlert[];
+ loading: boolean;
+}) {
+ const t = useTranslations('shopping.resellerPrices');
+ const locale = useLocale();
+ const f = numberFormat(locale);
+
+ return (
+ <Card>
+ <CardHeader className="pb-2">
+ <CardTitle className="flex items-center gap-1.5 text-sm font-medium">
+ <TrendingDown className="h-4 w-4 text-muted-foreground" aria-hidden />
+ {t('title')}
+ </CardTitle>
+ <p className="text-xs text-muted-foreground">
+ {t('description', { percent: f.percent(RESELLER_PRICE_MIN_DISCOUNT * 100, 0) })}
+ </p>
+ </CardHeader>
+ <CardContent>
+ {loading ? (
+ <div className="space-y-2">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} className="h-16 w-full" />
+ ))}
+ </div>
+ ) : alerts.length === 0 ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">{t('empty')}</p>
+ ) : (
+ <ul className="max-h-[360px] divide-y overflow-y-auto rounded-md border">
+ {alerts.map((alert, i) => (
+ <li
+ key={`${i}|${alert.currency}|${alert.productTitle ?? ''}`}
+ className="space-y-2 p-3"
+ >
+ <div className="flex items-start justify-between gap-3">
+ <span
+ className="line-clamp-2 text-sm font-medium text-foreground"
+ title={alert.productTitle ?? undefined}
+ >
+ {alert.productTitle ?? t('untitled')}
+ </span>
+ <span className="shrink-0 rounded-md bg-amber-50 px-1.5 py-0.5 text-xs font-medium tabular-nums text-amber-900 dark:bg-amber-950/30 dark:text-amber-200">
+ {t('lowerBy', { percent: f.percent(alert.discount * 100, 0) })}
+ </span>
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <MerchantPrice
+ label={t('yourStore')}
+ price={formatPrice(locale, alert.ownPrice, alert.currency)}
+ url={alert.ownUrl}
+ domain={alert.ownDomain}
+ />
+ <MerchantPrice
+ label={t('reseller')}
+ price={formatPrice(locale, alert.resellerPrice, alert.currency)}
+ url={alert.resellerUrl}
+ domain={alert.resellerDomain}
+ emphasis
+ />
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_merchant_destinations.ts b/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_merchant_destinations.ts
new file mode 100644
index 000000000..c8990cddc
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_merchant_destinations.ts
@@ -0,0 +1,53 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import {
+ getResellerPriceAlerts,
+ getShoppingMerchantSplit,
+ type ShoppingFilters,
+} from '@/lib/actions/shopping';
+import type { ShoppingMerchantSplit } from '@/lib/shopping-merchant-split';
+import type { ResellerPriceAlert } from '@/lib/shopping-reseller-price-alert';
+
+interface Loaded {
+ key: string;
+ split: ShoppingMerchantSplit | null;
+ priceAlerts: ResellerPriceAlert[];
+}
+
+/**
+ * The Overview tab's destination reads (#1277): where AI sends shoppers, and
+ * the resellers cheaper than the brand's store, for the same window and
+ * filters as the KPIs. Read here, in the page, rather than in the cards, so
+ * switching tabs doesn't read them again. Both are supplemental: a failed
+ * read leaves its card empty instead of breaking Shopping.
+ */
+export function useMerchantDestinations(
+ brandId: string | null,
+ filters: ShoppingFilters,
+ enabled: boolean,
+): { split: ShoppingMerchantSplit | null; priceAlerts: ResellerPriceAlert[]; loading: boolean } {
+ const key = enabled && brandId ? `${brandId}|${JSON.stringify(filters)}` : null;
+ const [loaded, setLoaded] = useState<Loaded | null>(null);
+
+ useEffect(() => {
+ if (!key || !brandId) return;
+ let cancelled = false;
+ Promise.all([
+ getShoppingMerchantSplit(brandId, filters).catch(() => null),
+ getResellerPriceAlerts(brandId, filters).catch(() => [] as ResellerPriceAlert[]),
+ ]).then(([split, priceAlerts]) => {
+ if (!cancelled) setLoaded({ key, split, priceAlerts });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [key, brandId, filters]);
+
+ const current = key !== null && loaded?.key === key ? loaded : null;
+ return {
+ split: current?.split ?? null,
+ priceAlerts: current?.priceAlerts ?? [],
+ loading: key !== null && current === null,
+ };
+}
diff --git a/web/src/lib/actions/shopping.test.ts b/web/src/lib/actions/shopping.test.ts
index 4336954a3..de930640a 100644
--- a/web/src/lib/actions/shopping.test.ts
+++ b/web/src/lib/actions/shopping.test.ts
@@ -26,6 +26,7 @@ function keptByOr(filter: string | undefined, row: Record<string, unknown>): boo
let cards: Array<Record<string, unknown>> = [];
let overviewRow: Record<string, unknown> = {};
+let rpcData: Record<string, unknown> = {};
let rpcCalls: Array<{ fn: string; args: Record<string, unknown> }> = [];
let cardCalls: QueryState[] = [];
@@ -90,7 +91,7 @@ vi.mock('@/lib/supabase/server', () => ({
from: (table: string) => fakeQueryBuilder(table),
rpc: async (fn: string, args: Record<string, unknown>) => {
rpcCalls.push({ fn, args });
- return { data: overviewRow, error: null };
+ return { data: fn in rpcData ? rpcData[fn] : overviewRow, error: null };
},
}),
}));
@@ -99,7 +100,9 @@ import {
getCompetitorProducts,
getCompetitorSummary,
getOwnProducts,
+ getResellerPriceAlerts,
getShoppingKpis,
+ getShoppingMerchantSplit,
getShoppingOverview,
} from './shopping';
@@ -125,6 +128,7 @@ function card(i: number, role: 'own' | 'competitor' | 'other', matched?: string)
beforeEach(() => {
cards = [];
+ rpcData = {};
rpcCalls = [];
cardCalls = [];
overviewRow = {
@@ -253,6 +257,30 @@ describe('ChatGPT Shopping market (#1278)', () => {
expect(rpcCalls[1].args.p_chatgpt_regions).toBeUndefined();
});
+ it("passes the market's regions to the merchant split and offers RPCs only with a market", async () => {
+ rpcData.shopping_merchant_split = [];
+ rpcData.shopping_own_product_offers = [];
+ await getShoppingMerchantSplit('brand-1', { datePreset: '30d', chatgptMarket: 'us' });
+ await getResellerPriceAlerts('brand-1', { datePreset: '30d', chatgptMarket: 'us' });
+ await getShoppingMerchantSplit('brand-1', { datePreset: '30d' });
+ await getResellerPriceAlerts('brand-1', { datePreset: '30d' });
+
+ expect(rpcCalls.map((c) => c.fn)).toEqual([
+ 'shopping_merchant_split',
+ 'shopping_own_product_offers',
+ 'shopping_merchant_split',
+ 'shopping_own_product_offers',
+ ]);
+ for (const call of rpcCalls.slice(0, 2)) {
+ expect(call.args.p_chatgpt_regions).toEqual(expect.arrayContaining(['US', 'US-CA']));
+ expect(call.args.p_chatgpt_regions).not.toContain('DE');
+ expect(call.args.p_regions).toBeUndefined();
+ }
+ for (const call of rpcCalls.slice(2)) {
+ expect(call.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' });
@@ -303,3 +331,81 @@ describe('getShoppingKpis', () => {
expect(rpcCalls[0].args.p_trend_from).toBeUndefined();
});
});
+
+describe('getShoppingMerchantSplit', () => {
+ it("reads the split for the Overview's window and filters", async () => {
+ rpcData.shopping_merchant_split = [
+ {
+ own_store_cards: 286,
+ amazon_cards: 1200,
+ walmart_cards: 400,
+ ebay_cards: 90,
+ other_marketplace_cards: 500,
+ reseller_cards: 11752,
+ unclassified_cards: '1404',
+ },
+ ];
+ const split = await getShoppingMerchantSplit('brand-1', {
+ datePreset: '30d',
+ platforms: ['copilot-web'],
+ regions: ['US'],
+ });
+
+ expect(rpcCalls).toHaveLength(1);
+ expect(rpcCalls[0].fn).toBe('shopping_merchant_split');
+ expect(rpcCalls[0].args).toMatchObject({
+ p_brand_id: 'brand-1',
+ p_from: expect.any(String),
+ p_platforms: ['copilot-web'],
+ p_regions: ['US'],
+ });
+ expect(split.classifiedCards).toBe(14228);
+ expect(split.unclassifiedCards).toBe(1404);
+ expect(split.parts.reduce((sum, p) => sum + p.cards, 0)).toBe(14228);
+ expect(split.parts.reduce((sum, p) => sum + p.percent, 0)).toBe(100);
+ });
+
+ it('is all zeros when the RPC returns no row', async () => {
+ rpcData.shopping_merchant_split = [];
+ const split = await getShoppingMerchantSplit('brand-1', { datePreset: '7d' });
+ expect(split.classifiedCards).toBe(0);
+ expect(split.unclassifiedCards).toBe(0);
+ });
+});
+
+describe('getResellerPriceAlerts', () => {
+ it('flags a marketplace offer at least 5% under the store', async () => {
+ rpcData.shopping_own_product_offers = [
+ {
+ merchant_kind: 'own',
+ marketplace: null,
+ merchant_domain: 'acme.example',
+ merchant_url: 'https://acme.example/runner',
+ listing_id: null,
+ product_title: 'Acme Runner',
+ price_amount: '120.00',
+ price_currency: 'USD',
+ },
+ {
+ merchant_kind: 'marketplace',
+ marketplace: 'amazon',
+ merchant_domain: 'amazon.com',
+ merchant_url: 'https://www.amazon.com/dp/B000000001',
+ listing_id: 'B000000001',
+ product_title: 'Acme Runner',
+ price_amount: 99,
+ price_currency: 'USD',
+ },
+ ];
+ const alerts = await getResellerPriceAlerts('brand-1', { datePreset: '90d' });
+
+ expect(rpcCalls[0].fn).toBe('shopping_own_product_offers');
+ expect(alerts).toHaveLength(1);
+ expect(alerts[0]).toMatchObject({ ownPrice: 120, resellerPrice: 99, currency: 'USD' });
+ });
+
+ it('is empty when the RPC returns no offers', async () => {
+ rpcData.shopping_own_product_offers = [];
+ expect(await getResellerPriceAlerts('brand-1', { datePreset: '30d' })).toEqual([]);
+ });
+});
diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.ts
index dea7d030b..63d550c82 100644
--- a/web/src/lib/actions/shopping.ts
+++ b/web/src/lib/actions/shopping.ts
@@ -7,6 +7,16 @@ import {
type AmazonShareDropAlert,
} from '@/lib/shopping-amazon-share-alert';
import { marketRegionCodes, type ShoppingMarket } from '@/lib/shopping/markets';
+import {
+ toMerchantSplit,
+ type MerchantSplitRow,
+ type ShoppingMerchantSplit,
+} from '@/lib/shopping-merchant-split';
+import {
+ detectResellerPriceAlerts,
+ type MerchantKind,
+ type ResellerPriceAlert,
+} from '@/lib/shopping-reseller-price-alert';
/**
* Server actions for the Shopping dashboard page. Reads from the
@@ -33,7 +43,8 @@ export interface ShoppingFilters {
/**
* 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).
+ * reads and to the Overview (`p_chatgpt_regions`, 00267), including where
+ * AI sends shoppers and the reseller prices (00268).
*/
chatgptMarket?: ShoppingMarket;
}
@@ -82,6 +93,22 @@ function daysAgoIso(days: number): string {
return new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
}
+/**
+ * The Overview window's RPC arguments: brand, dates, platforms, regions and
+ * ChatGPT Shopping's market (#1278), whose regions go only with a market.
+ */
+function windowArgs(brandId: string, filters: ShoppingFilters) {
+ const { from, to } = resolveDateRange(filters);
+ return {
+ p_brand_id: brandId,
+ p_from: from,
+ p_to: expandDateToEndOfDay(to),
+ p_platforms: filters.platforms?.length ? filters.platforms : undefined,
+ p_regions: filters.regions?.length ? filters.regions : undefined,
+ p_chatgpt_regions: filters.chatgptMarket ? marketRegionCodes(filters.chatgptMarket) : undefined,
+ };
+}
+
// ── Overview (KPIs + charts) ──────────────────────────────────────────────────
interface ShoppingOverviewRow {
@@ -105,15 +132,9 @@ async function loadShoppingOverview(
trendFrom?: string,
): Promise<ShoppingOverviewRow> {
const supabase = await createClient();
- const { from, to } = resolveDateRange(filters);
const { data, error } = await supabase.rpc('shopping_overview', {
- p_brand_id: brandId,
- p_from: from,
- p_to: expandDateToEndOfDay(to),
- p_platforms: filters.platforms?.length ? filters.platforms : undefined,
- p_regions: filters.regions?.length ? filters.regions : undefined,
+ ...windowArgs(brandId, filters),
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;
@@ -216,6 +237,66 @@ export async function getShoppingAmazonShareDropAlert(
);
}
+/**
+ * "Where AI sends shoppers" (#1277): the brand's own-product cards per
+ * destination over the Overview window and filters, counted in Postgres by
+ * `shopping_merchant_split` so the split holds past PostgREST's 1,000-row cap.
+ */
+export async function getShoppingMerchantSplit(
+ brandId: string,
+ filters: ShoppingFilters,
+): Promise<ShoppingMerchantSplit> {
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc(
+ 'shopping_merchant_split',
+ windowArgs(brandId, filters),
+ );
+ if (error) throw new Error(error.message);
+ return toMerchantSplit((data as MerchantSplitRow[] | null)?.[0]);
+}
+
+interface OwnProductOfferRow {
+ merchant_kind: MerchantKind;
+ marketplace: string | null;
+ merchant_domain: string | null;
+ merchant_url: string | null;
+ listing_id: string | null;
+ product_title: string | null;
+ price_amount: number | string;
+ price_currency: string | null;
+}
+
+/**
+ * Resellers selling the brand's products for at least 5% less than its own
+ * store (#1277), over the Overview window and filters. The RPC returns each
+ * merchant's lowest price per product as one jsonb list (no row cap); the
+ * matching and the 5% rule live in `detectResellerPriceAlerts`.
+ */
+export async function getResellerPriceAlerts(
+ brandId: string,
+ filters: ShoppingFilters,
+): Promise<ResellerPriceAlert[]> {
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc(
+ 'shopping_own_product_offers',
+ windowArgs(brandId, filters),
+ );
+ if (error) throw new Error(error.message);
+ const rows = (Array.isArray(data) ? data : []) as unknown as OwnProductOfferRow[];
+ return detectResellerPriceAlerts(
+ rows.map((row) => ({
+ merchantKind: row.merchant_kind,
+ marketplace: row.marketplace,
+ merchantDomain: row.merchant_domain,
+ merchantUrl: row.merchant_url,
+ listingId: row.listing_id,
+ productTitle: row.product_title,
+ priceAmount: Number(row.price_amount),
+ priceCurrency: row.price_currency,
+ })),
+ );
+}
+
/**
* Collected once at page load so the filter bar shows only platform / region
* values that actually appear in this brand's data — all of it, not the first
diff --git a/web/src/lib/shopping-merchant-split.test.ts b/web/src/lib/shopping-merchant-split.test.ts
new file mode 100644
index 000000000..028328f1f
--- /dev/null
+++ b/web/src/lib/shopping-merchant-split.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+import { toMerchantSplit, wholePercents } from './shopping-merchant-split';
+
+describe('toMerchantSplit', () => {
+ it('splits the classified own cards and keeps the unclassified apart', () => {
+ const split = toMerchantSplit({
+ own_store_cards: 50,
+ amazon_cards: '30',
+ walmart_cards: 10,
+ ebay_cards: 5,
+ other_marketplace_cards: 3,
+ reseller_cards: 2,
+ unclassified_cards: '40',
+ });
+
+ expect(split.classifiedCards).toBe(100);
+ expect(split.unclassifiedCards).toBe(40);
+ expect(split.parts).toEqual([
+ { segment: 'own_store', cards: 50, percent: 50 },
+ { segment: 'amazon', cards: 30, percent: 30 },
+ { segment: 'walmart', cards: 10, percent: 10 },
+ { segment: 'ebay', cards: 5, percent: 5 },
+ { segment: 'other_marketplace', cards: 3, percent: 3 },
+ { segment: 'reseller', cards: 2, percent: 2 },
+ ]);
+ });
+
+ it('is all zeros without a row (no access or no cards)', () => {
+ const split = toMerchantSplit(undefined);
+ expect(split.classifiedCards).toBe(0);
+ expect(split.unclassifiedCards).toBe(0);
+ expect(split.parts.every((p) => p.cards === 0 && p.percent === 0)).toBe(true);
+ });
+
+ it('leaves unclassified cards out of the percentages', () => {
+ const split = toMerchantSplit({
+ own_store_cards: 1,
+ amazon_cards: 1,
+ walmart_cards: 0,
+ ebay_cards: 0,
+ other_marketplace_cards: 0,
+ reseller_cards: 0,
+ unclassified_cards: 98,
+ });
+ expect(split.parts.slice(0, 2).map((p) => p.percent)).toEqual([50, 50]);
+ });
+});
+
+describe('wholePercents', () => {
+ it('adds up to 100 where rounding each share would not', () => {
+ // 33.3 / 33.3 / 33.3 rounds to 99; 16.7 × 6 rounds to 102.
+ expect(wholePercents([1, 1, 1])).toEqual([34, 33, 33]);
+ expect(wholePercents([1, 1, 1, 1, 1, 1]).reduce((a, b) => a + b, 0)).toBe(100);
+ expect(wholePercents([286, 2190, 11752, 0, 0, 0]).reduce((a, b) => a + b, 0)).toBe(100);
+ });
+
+ it('is all zeros when there is nothing to split', () => {
+ expect(wholePercents([0, 0, 0])).toEqual([0, 0, 0]);
+ });
+});
diff --git a/web/src/lib/shopping-merchant-split.ts b/web/src/lib/shopping-merchant-split.ts
new file mode 100644
index 000000000..d4e07ad87
--- /dev/null
+++ b/web/src/lib/shopping-merchant-split.ts
@@ -0,0 +1,94 @@
+/**
+ * "Where AI sends shoppers" (#1277): where the cards for the brand's own
+ * products link, as shopping_merchant_split (00268) counts them for the
+ * Overview tab's window and filters. Only classified cards enter the split;
+ * a card with no merchant URL is counted apart, never spread over the
+ * segments, so the segments always add up to the classified cards.
+ */
+
+export const MERCHANT_SPLIT_SEGMENTS = [
+ 'own_store',
+ 'amazon',
+ 'walmart',
+ 'ebay',
+ 'other_marketplace',
+ 'reseller',
+] as const;
+
+export type MerchantSplitSegment = (typeof MERCHANT_SPLIT_SEGMENTS)[number];
+
+/** One row of shopping_merchant_split; bigint counts may arrive as strings. */
+export interface MerchantSplitRow {
+ own_store_cards: number | string;
+ amazon_cards: number | string;
+ walmart_cards: number | string;
+ ebay_cards: number | string;
+ other_marketplace_cards: number | string;
+ reseller_cards: number | string;
+ unclassified_cards: number | string;
+}
+
+export interface MerchantSplitPart {
+ segment: MerchantSplitSegment;
+ cards: number;
+ /** Whole percent of the classified cards; the parts add up to 100. */
+ percent: number;
+}
+
+export interface ShoppingMerchantSplit {
+ parts: MerchantSplitPart[];
+ classifiedCards: number;
+ /** Own-product cards with no merchant URL, left out of the parts. */
+ unclassifiedCards: number;
+}
+
+const ROW_COLUMN: Record<MerchantSplitSegment, keyof MerchantSplitRow> = {
+ own_store: 'own_store_cards',
+ amazon: 'amazon_cards',
+ walmart: 'walmart_cards',
+ ebay: 'ebay_cards',
+ other_marketplace: 'other_marketplace_cards',
+ reseller: 'reseller_cards',
+};
+
+function count(value: number | string | null | undefined): number {
+ const n = Number(value ?? 0);
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
+}
+
+/**
+ * Whole percentages that add up to exactly 100 (largest remainder): rounding
+ * each share on its own can show 99% or 101%. All zeros when the total is 0.
+ */
+export function wholePercents(counts: readonly number[]): number[] {
+ const total = counts.reduce((sum, n) => sum + n, 0);
+ if (total <= 0) return counts.map(() => 0);
+ // Multiplied first, so whole shares stay whole (7/50 → 14, not 14.000…2).
+ const exact = counts.map((n) => (n * 100) / total);
+ const floors = exact.map(Math.floor);
+ let left = 100 - floors.reduce((sum, n) => sum + n, 0);
+ const byRemainder = exact
+ .map((value, index) => ({ index, remainder: value - floors[index] }))
+ .sort((a, b) => b.remainder - a.remainder || a.index - b.index);
+ for (const { index } of byRemainder) {
+ if (left <= 0) break;
+ floors[index] += 1;
+ left -= 1;
+ }
+ return floors;
+}
+
+/** The RPC's row as the card's parts; no row (no access, no data) is all zeros. */
+export function toMerchantSplit(row: MerchantSplitRow | null | undefined): ShoppingMerchantSplit {
+ const cards = MERCHANT_SPLIT_SEGMENTS.map((segment) => count(row?.[ROW_COLUMN[segment]]));
+ const percents = wholePercents(cards);
+ return {
+ parts: MERCHANT_SPLIT_SEGMENTS.map((segment, i) => ({
+ segment,
+ cards: cards[i],
+ percent: percents[i],
+ })),
+ classifiedCards: cards.reduce((sum, n) => sum + n, 0),
+ unclassifiedCards: count(row?.unclassified_cards),
+ };
+}
diff --git a/web/src/lib/shopping-reseller-price-alert.test.ts b/web/src/lib/shopping-reseller-price-alert.test.ts
new file mode 100644
index 000000000..bf4aa66e1
--- /dev/null
+++ b/web/src/lib/shopping-reseller-price-alert.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it } from 'vitest';
+import {
+ detectResellerPriceAlerts,
+ normalizeProductTitle,
+ type ShoppingPriceOffer,
+} from './shopping-reseller-price-alert';
+
+function ownStore(price: number, overrides: Partial<ShoppingPriceOffer> = {}): ShoppingPriceOffer {
+ return {
+ merchantKind: 'own',
+ marketplace: null,
+ merchantDomain: 'acme.example',
+ merchantUrl: 'https://acme.example/products/runner-2',
+ listingId: null,
+ productTitle: 'Acme Runner 2',
+ priceAmount: price,
+ priceCurrency: 'USD',
+ ...overrides,
+ };
+}
+
+function amazon(price: number, overrides: Partial<ShoppingPriceOffer> = {}): ShoppingPriceOffer {
+ return {
+ merchantKind: 'marketplace',
+ marketplace: 'amazon',
+ merchantDomain: 'amazon.com',
+ merchantUrl: 'https://www.amazon.com/dp/B000000001',
+ listingId: 'B000000001',
+ productTitle: 'Acme Runner 2',
+ priceAmount: price,
+ priceCurrency: 'USD',
+ ...overrides,
+ };
+}
+
+describe('detectResellerPriceAlerts', () => {
+ it('flags an Amazon card at 99 USD against the store at 120 USD', () => {
+ expect(detectResellerPriceAlerts([ownStore(120), amazon(99)])).toEqual([
+ {
+ productTitle: 'Acme Runner 2',
+ currency: 'USD',
+ ownPrice: 120,
+ ownUrl: 'https://acme.example/products/runner-2',
+ ownDomain: 'acme.example',
+ resellerPrice: 99,
+ resellerUrl: 'https://www.amazon.com/dp/B000000001',
+ resellerDomain: 'amazon.com',
+ resellerKind: 'marketplace',
+ marketplace: 'amazon',
+ discount: 21 / 120,
+ },
+ ]);
+ });
+
+ it('does not flag equal prices', () => {
+ expect(detectResellerPriceAlerts([ownStore(120), amazon(120)])).toEqual([]);
+ });
+
+ it('does not compare prices in different currencies', () => {
+ expect(
+ detectResellerPriceAlerts([ownStore(120), amazon(99, { priceCurrency: 'EUR' })]),
+ ).toEqual([]);
+ });
+
+ it('flags a gap of exactly 5% despite floating-point error', () => {
+ // (19.99 − 18.9905) / 19.99 is 0.049999999999999885 in floating point.
+ expect(detectResellerPriceAlerts([ownStore(120), amazon(114)])).toHaveLength(1);
+ expect(detectResellerPriceAlerts([ownStore(100), amazon(95)])).toHaveLength(1);
+ expect(detectResellerPriceAlerts([ownStore(19.99), amazon(18.9905)])).toHaveLength(1);
+ });
+
+ it('does not flag a gap just under 5%', () => {
+ expect(detectResellerPriceAlerts([ownStore(120), amazon(114.01)])).toEqual([]);
+ expect(detectResellerPriceAlerts([ownStore(100), amazon(95.01)])).toEqual([]);
+ });
+
+ it("compares against the store's lowest price", () => {
+ const alerts = detectResellerPriceAlerts([ownStore(130), ownStore(104), amazon(99)]);
+ // 99 is under 5% below 104, the lowest store price: no alert.
+ expect(alerts).toEqual([]);
+ });
+
+ it('matches by normalized title when there is no listing id', () => {
+ const reseller: ShoppingPriceOffer = {
+ merchantKind: 'reseller',
+ marketplace: null,
+ merchantDomain: 'shoes.example',
+ merchantUrl: 'https://shoes.example/acme-runner-2',
+ listingId: null,
+ productTitle: ' ACME Runner-2 ',
+ priceAmount: 80,
+ priceCurrency: 'usd',
+ };
+ const [alert] = detectResellerPriceAlerts([ownStore(100), reseller]);
+ expect(alert).toMatchObject({
+ currency: 'USD',
+ ownPrice: 100,
+ resellerPrice: 80,
+ resellerKind: 'reseller',
+ resellerDomain: 'shoes.example',
+ discount: 0.2,
+ });
+ });
+
+ it('links a marketplace listing to the store through another card with the same listing id', () => {
+ const alerts = detectResellerPriceAlerts([
+ ownStore(120),
+ amazon(118),
+ // Same ASIN, different title: the same product as the card above.
+ amazon(90, { productTitle: 'Acme Runner 2 Mens Road Running Shoe' }),
+ ]);
+ expect(alerts).toHaveLength(1);
+ expect(alerts[0]).toMatchObject({ resellerPrice: 90, productTitle: 'Acme Runner 2' });
+ });
+
+ it('keeps different products apart', () => {
+ expect(
+ detectResellerPriceAlerts([
+ ownStore(120),
+ amazon(60, { productTitle: 'Acme Trail 5', listingId: 'B000000002' }),
+ ]),
+ ).toEqual([]);
+ });
+
+ it('raises one alert per product, for its cheapest reseller, biggest gap first', () => {
+ const alerts = detectResellerPriceAlerts([
+ ownStore(120),
+ amazon(99),
+ amazon(105, { marketplace: 'walmart', merchantDomain: 'walmart.com', listingId: '123' }),
+ ownStore(50, { productTitle: 'Acme Sock', merchantUrl: 'https://acme.example/sock' }),
+ amazon(30, { productTitle: 'Acme Sock', listingId: 'B000000003' }),
+ ]);
+ expect(alerts.map((a) => [a.productTitle, a.resellerPrice])).toEqual([
+ ['Acme Sock', 30],
+ ['Acme Runner 2', 99],
+ ]);
+ });
+
+ it('never flags without a store price', () => {
+ expect(
+ detectResellerPriceAlerts([amazon(99), amazon(50, { listingId: 'B000000009' })]),
+ ).toEqual([]);
+ });
+
+ it('ignores prices that are missing, zero or have no currency', () => {
+ expect(detectResellerPriceAlerts([ownStore(120), amazon(0)])).toEqual([]);
+ expect(detectResellerPriceAlerts([ownStore(120), amazon(Number.NaN)])).toEqual([]);
+ expect(detectResellerPriceAlerts([ownStore(120), amazon(99, { priceCurrency: ' ' })])).toEqual(
+ [],
+ );
+ });
+
+ it('drops links that are not http(s)', () => {
+ const [alert] = detectResellerPriceAlerts([
+ ownStore(120),
+ amazon(99, { merchantUrl: 'javascript:alert(1)', merchantDomain: null }),
+ ]);
+ expect(alert.resellerUrl).toBeNull();
+ expect(alert.resellerDomain).toBeNull();
+ });
+});
+
+describe('normalizeProductTitle', () => {
+ it('drops case, accents, punctuation and extra spaces', () => {
+ expect(normalizeProductTitle(' Café Crème – 2-Pack! ')).toBe('cafe creme 2 pack');
+ expect(normalizeProductTitle(null)).toBe('');
+ });
+});
diff --git a/web/src/lib/shopping-reseller-price-alert.ts b/web/src/lib/shopping-reseller-price-alert.ts
new file mode 100644
index 000000000..e34daf6ba
--- /dev/null
+++ b/web/src/lib/shopping-reseller-price-alert.ts
@@ -0,0 +1,186 @@
+/** A reseller is flagged when it is at least this much below the brand's store. */
+export const RESELLER_PRICE_MIN_DISCOUNT = 0.05;
+
+export type MerchantKind = 'own' | 'marketplace' | 'reseller';
+
+/**
+ * The lowest price one merchant showed for one of the brand's own products in
+ * the window, as shopping_own_product_offers (00268) returns it.
+ */
+export interface ShoppingPriceOffer {
+ merchantKind: MerchantKind;
+ /** Marketplace id (amazon, ebay, …) for marketplace offers, else null. */
+ marketplace: string | null;
+ merchantDomain: string | null;
+ merchantUrl: string | null;
+ /** Marketplace-native listing id, such as an Amazon ASIN. */
+ listingId: string | null;
+ productTitle: string | null;
+ priceAmount: number;
+ priceCurrency: string | null;
+}
+
+export interface ResellerPriceAlert {
+ /** The title on the brand's store, else the reseller's. */
+ productTitle: string | null;
+ currency: string;
+ ownPrice: number;
+ /** Null when the stored link isn't an http(s) URL. */
+ ownUrl: string | null;
+ ownDomain: string | null;
+ resellerPrice: number;
+ resellerUrl: string | null;
+ resellerDomain: string | null;
+ resellerKind: Exclude<MerchantKind, 'own'>;
+ marketplace: string | null;
+ /** How far below the store's price the reseller is: 0.175 is 17.5% lower. */
+ discount: number;
+}
+
+/**
+ * Lowercased, accents and punctuation dropped, spaces collapsed: "Acme Runner
+ * 2 – Black" and "acme runner 2 black" are the same product.
+ */
+export function normalizeProductTitle(title: string | null | undefined): string {
+ return (title ?? '')
+ .normalize('NFKD')
+ .replace(/\p{M}+/gu, '')
+ .toLowerCase()
+ .replace(/[^\p{L}\p{N}]+/gu, ' ')
+ .trim();
+}
+
+function normalizeCurrency(currency: string | null | undefined): string {
+ return (currency ?? '').trim().toUpperCase();
+}
+
+/** Only http(s) links are shown; a scheme-less merchant link gets https. */
+function safeLink(url: string | null | undefined): string | null {
+ const raw = url?.trim();
+ if (!raw) return null;
+ try {
+ const parsed = new URL(/^[a-z][a-z\d+.-]*:/i.test(raw) ? raw : `https://${raw}`);
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : null;
+ } catch {
+ return null;
+ }
+}
+
+function domainOf(offer: ShoppingPriceOffer, link: string | null): string | null {
+ if (offer.merchantDomain) return offer.merchantDomain;
+ if (!link) return null;
+ try {
+ return new URL(link).hostname.replace(/^www\./, '');
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The keys that make two offers the same product: the marketplace listing id,
+ * else the normalized title. Every offer here is already one of the brand's
+ * own products (matched_brand_role = 'own'), which stands for the brand half
+ * of "title plus brand": the cards' product_brand often carries the seller
+ * instead ("Marketplace + others"), so it would keep a store and a reseller
+ * apart even when they sell the same product.
+ */
+function matchKeys(offer: ShoppingPriceOffer): string[] {
+ const keys: string[] = [];
+ const listingId = offer.listingId?.trim();
+ if (listingId) keys.push(`listing:${offer.marketplace ?? ''}:${listingId.toUpperCase()}`);
+ const title = normalizeProductTitle(offer.productTitle);
+ if (title) keys.push(`title:${title}`);
+ return keys;
+}
+
+/** Group offers that share any key, so a listing id links titles that differ. */
+function productGroups(offers: readonly ShoppingPriceOffer[]): ShoppingPriceOffer[][] {
+ const parent = offers.map((_, i) => i);
+ const find = (i: number): number => {
+ while (parent[i] !== i) {
+ parent[i] = parent[parent[i]];
+ i = parent[i];
+ }
+ return i;
+ };
+ const firstWithKey = new Map<string, number>();
+ offers.forEach((offer, i) => {
+ for (const key of matchKeys(offer)) {
+ const first = firstWithKey.get(key);
+ if (first === undefined) firstWithKey.set(key, i);
+ else parent[find(i)] = find(first);
+ }
+ });
+
+ const groups = new Map<number, ShoppingPriceOffer[]>();
+ offers.forEach((offer, i) => {
+ if (matchKeys(offer).length === 0) return;
+ const root = find(i);
+ const group = groups.get(root);
+ if (group) group.push(offer);
+ else groups.set(root, [offer]);
+ });
+ return [...groups.values()];
+}
+
+function cheapest(offers: readonly ShoppingPriceOffer[]): ShoppingPriceOffer | null {
+ let best: ShoppingPriceOffer | null = null;
+ for (const offer of offers) {
+ if (!best || offer.priceAmount < best.priceAmount) best = offer;
+ }
+ return best;
+}
+
+/**
+ * Flag the brand's products a reseller or marketplace sells for at least 5%
+ * less than the lowest price seen on the brand's own store, in the same
+ * currency. Prices in different currencies are never compared. One alert per
+ * product and currency, for its cheapest reseller; biggest gaps first.
+ */
+export function detectResellerPriceAlerts(
+ input: readonly ShoppingPriceOffer[],
+): ResellerPriceAlert[] {
+ const offers = input.filter(
+ (offer) =>
+ Number.isFinite(offer.priceAmount) &&
+ offer.priceAmount > 0 &&
+ normalizeCurrency(offer.priceCurrency) !== '',
+ );
+
+ const alerts: ResellerPriceAlert[] = [];
+ for (const group of productGroups(offers)) {
+ const currencies = new Set(group.map((offer) => normalizeCurrency(offer.priceCurrency)));
+ for (const currency of currencies) {
+ const inCurrency = group.filter(
+ (offer) => normalizeCurrency(offer.priceCurrency) === currency,
+ );
+ const own = cheapest(inCurrency.filter((offer) => offer.merchantKind === 'own'));
+ const other = cheapest(inCurrency.filter((offer) => offer.merchantKind !== 'own'));
+ if (!own || !other || other.merchantKind === 'own') continue;
+
+ const discount = (own.priceAmount - other.priceAmount) / own.priceAmount;
+ // The tolerance keeps an exact 5% gap (19.99 → 18.9905) from missing on float error.
+ if (discount < RESELLER_PRICE_MIN_DISCOUNT - 1e-9) continue;
+
+ const ownUrl = safeLink(own.merchantUrl);
+ const resellerUrl = safeLink(other.merchantUrl);
+ alerts.push({
+ productTitle: own.productTitle?.trim() || other.productTitle?.trim() || null,
+ currency,
+ ownPrice: own.priceAmount,
+ ownUrl,
+ ownDomain: domainOf(own, ownUrl),
+ resellerPrice: other.priceAmount,
+ resellerUrl,
+ resellerDomain: domainOf(other, resellerUrl),
+ resellerKind: other.merchantKind,
+ marketplace: other.marketplace,
+ discount,
+ });
+ }
+ }
+
+ return alerts.sort(
+ (a, b) => b.discount - a.discount || (a.productTitle ?? '').localeCompare(b.productTitle ?? ''),
+ );
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 53c63f0f0..887960bfa 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -4976,6 +4976,25 @@ export type Database = {
regions: string[]
}[]
}
+ shopping_merchant_split: {
+ Args: {
+ p_brand_id: string
+ p_chatgpt_regions?: string[]
+ p_from?: string
+ p_platforms?: string[]
+ p_regions?: string[]
+ p_to?: string
+ }
+ Returns: {
+ amazon_cards: number
+ ebay_cards: number
+ other_marketplace_cards: number
+ own_store_cards: number
+ reseller_cards: number
+ unclassified_cards: number
+ walmart_cards: number
+ }[]
+ }
shopping_overview: {
Args: {
p_brand_id: string
@@ -4988,6 +5007,17 @@ export type Database = {
}
Returns: Json
}
+ shopping_own_product_offers: {
+ Args: {
+ p_brand_id: string
+ p_chatgpt_regions?: string[]
+ p_from?: string
+ p_platforms?: string[]
+ p_regions?: string[]
+ p_to?: string
+ }
+ Returns: Json
+ }
signals_summary: {
Args: { p_brand_id: string; p_from: string; p_to: string }
Returns: Json