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): alert on sharp drops in Amazon product share (#1313)

Sanjeev Kumar087e9b42c207
diff --git a/server/src/lib/cloro-result-handler.js b/server/src/lib/cloro-result-handler.js
index c7a5b10e6..ee4a282ad 100644
--- a/server/src/lib/cloro-result-handler.js
+++ b/server/src/lib/cloro-result-handler.js
@@ -25,6 +25,7 @@ import {
import { updateTargetUrlStats } from './target-url-stats.js';
import { persistCitationRows } from './citation-rows.js';
import { logger } from './logger.js';
+import { classifyMerchant } from './merchant-detection.js';
/**
* @param {object} args
@@ -154,6 +155,9 @@ export async function persistShoppingCards({
const rows = normalized.map((card) => {
const match = matchCardBrand(card, brandInfo, competitors);
+ const destination = card.merchant_url
+ ? classifyMerchant(card.merchant_url, { brandDomains: brandInfo.domains })
+ : null;
return {
prompt_result_id: promptResultId,
brand_id: brandId,
@@ -165,6 +169,9 @@ export async function persistShoppingCards({
image_url: card.image_url,
merchant_url: card.merchant_url,
merchant_domain: card.merchant_domain,
+ merchant_kind: destination?.kind ?? null,
+ marketplace: destination?.marketplace ?? null,
+ listing_id: destination?.listingId ?? null,
rating: card.rating,
review_count: card.review_count,
raw: card.raw,
diff --git a/server/src/lib/cloro-result-handler.test.js b/server/src/lib/cloro-result-handler.test.js
index 479aaee63..91819f8cc 100644
--- a/server/src/lib/cloro-result-handler.test.js
+++ b/server/src/lib/cloro-result-handler.test.js
@@ -64,6 +64,43 @@ describe('persistShoppingCards – ChatGPT inline products (#1183)', () => {
expect(upsert.mock.calls[0][0][0].position).toBe(1);
});
+ it('persists the merchant classification and keeps cards without a URL unclassified', async () => {
+ const inserted = await persistShoppingCards({
+ ...base,
+ rawCards: [
+ {
+ products: [
+ {
+ title: 'Acme Trail Runner on Amazon',
+ url: 'https://www.amazon.com/dp/B0C123ABCD?tag=tracking',
+ price: '$75.00',
+ },
+ {
+ title: 'Acme Trail Runner Store',
+ url: 'https://shop.acme.com/products/trail-runner',
+ price: '$75.00',
+ },
+ {
+ title: 'Acme Trail Runner Reseller',
+ url: 'https://shop.example/products/trail-runner',
+ price: '$70.00',
+ },
+ { title: 'Acme Trail Runner without merchant URL', price: '$75.00' },
+ ],
+ },
+ ],
+ });
+
+ expect(inserted).toBe(4);
+ const rows = upsert.mock.calls[0][0];
+ expect(rows.map((row) => [row.merchant_kind, row.marketplace, row.listing_id])).toEqual([
+ ['marketplace', 'amazon', 'B0C123ABCD'],
+ ['own', null, null],
+ ['reseller', null, null],
+ [null, null, null],
+ ]);
+ });
+
it('writes nothing when there are neither cards nor inline products', async () => {
const inserted = await persistShoppingCards({ ...base, rawCards: [] });
expect(inserted).toBe(0);
diff --git a/server/src/scripts/backfill-shopping-card-merchants.js b/server/src/scripts/backfill-shopping-card-merchants.js
new file mode 100644
index 000000000..5f06a009d
--- /dev/null
+++ b/server/src/scripts/backfill-shopping-card-merchants.js
@@ -0,0 +1,128 @@
+/**
+ * Classify destinations on existing normalized shopping-card rows.
+ *
+ * Run after migration 00225:
+ * node src/scripts/backfill-shopping-card-merchants.js
+ *
+ * Add --all to reclassify every row with a merchant URL after brand-domain changes:
+ * node src/scripts/backfill-shopping-card-merchants.js --all
+ *
+ * By default, only unclassified rows are selected, so an interrupted run can be
+ * safely resumed by running the command again. Pages across the normalized
+ * card table and uses the same pure classifier as
+ * the live result handler. Cards without a merchant URL remain unclassified.
+ */
+import 'dotenv/config';
+import supabaseAdmin from '../config/supabase.js';
+import { classifyMerchant } from '../lib/merchant-detection.js';
+
+const BATCH_SIZE = Number.parseInt(process.env.SHOPPING_MERCHANT_BACKFILL_BATCH ?? '500', 10);
+const UPDATE_CONCURRENCY = 20;
+
+async function loadBrandDomains(brandId) {
+ const { data, error } = await supabaseAdmin
+ .from('brand_domains')
+ .select('domain')
+ .eq('brand_id', brandId);
+ if (error) throw new Error(`Failed to load domains for ${brandId}: ${error.message}`);
+ return (data ?? []).map((row) => row.domain).filter(Boolean);
+}
+
+async function updateBatch(rows, domainCache) {
+ let updated = 0;
+ let skipped = 0;
+ let failed = 0;
+
+ const withUrls = rows.filter(
+ (row) => typeof row.merchant_url === 'string' && row.merchant_url.trim(),
+ );
+ skipped += rows.length - withUrls.length;
+
+ for (let start = 0; start < withUrls.length; start += UPDATE_CONCURRENCY) {
+ const slice = withUrls.slice(start, start + UPDATE_CONCURRENCY);
+ const results = await Promise.all(
+ slice.map(async (row) => {
+ let domainsPromise = domainCache.get(row.brand_id);
+ if (!domainsPromise) {
+ domainsPromise = loadBrandDomains(row.brand_id);
+ domainCache.set(row.brand_id, domainsPromise);
+ }
+ const domains = await domainsPromise;
+ const destination = classifyMerchant(row.merchant_url, { brandDomains: domains });
+ const { error } = await supabaseAdmin
+ .from('prompt_result_shopping_cards')
+ .update({
+ merchant_kind: destination.kind,
+ marketplace: destination.marketplace,
+ listing_id: destination.listingId,
+ })
+ .eq('id', row.id);
+ if (error) return { failed: true, error, id: row.id };
+ return { updated: true };
+ }),
+ );
+
+ for (const result of results) {
+ if (result.failed) {
+ failed += 1;
+ console.error(`[backfill] Failed to classify ${result.id}: ${result.error.message}`);
+ } else {
+ updated += 1;
+ }
+ }
+ }
+
+ return { updated, skipped, failed };
+}
+
+async function main() {
+ const domainCache = new Map();
+ const reclassifyAll = process.argv.includes('--all');
+ let lastId = null;
+ let scanned = 0;
+ let updated = 0;
+ let skipped = 0;
+ let failed = 0;
+
+ while (true) {
+ let query = supabaseAdmin
+ .from('prompt_result_shopping_cards')
+ .select('id, brand_id, merchant_url')
+ .not('merchant_url', 'is', null)
+ .order('id', { ascending: true })
+ .limit(BATCH_SIZE);
+
+ if (!reclassifyAll) query = query.is('merchant_kind', null);
+ if (lastId) query = query.gt('id', lastId);
+
+ const { data: rows, error } = await query;
+
+ if (error) throw new Error(`Failed to read shopping cards: ${error.message}`);
+ if (!rows?.length) break;
+
+ const result = await updateBatch(rows, domainCache);
+ scanned += rows.length;
+ updated += result.updated;
+ skipped += result.skipped;
+ failed += result.failed;
+ console.log(
+ `[backfill] scanned=${scanned} updated=${updated} skipped(no URL)=${skipped} failed=${failed}`,
+ );
+
+ // The keyset cursor is stable while merchant_kind updates rows that this
+ // default run has already classified. It also avoids OFFSET skipping rows
+ // if older cards are concurrently deleted.
+ lastId = rows[rows.length - 1].id;
+ if (rows.length < BATCH_SIZE) break;
+ }
+
+ console.log(
+ `[backfill] complete: scanned=${scanned}, updated=${updated}, skipped=${skipped}, failed=${failed}`,
+ );
+ if (failed > 0) process.exitCode = 1;
+}
+
+main().catch((error) => {
+ console.error('[backfill] Fatal:', error);
+ process.exitCode = 1;
+});
diff --git a/supabase/migrations/00225_shopping_merchant_classification.sql b/supabase/migrations/00225_shopping_merchant_classification.sql
new file mode 100644
index 000000000..b4d9d7ca7
--- /dev/null
+++ b/supabase/migrations/00225_shopping_merchant_classification.sql
@@ -0,0 +1,85 @@
+-- Shopping merchant classification needed for "Where AI sends shoppers"
+-- and weekly Amazon share alerts (#1277, #1284).
+
+alter table public.prompt_result_shopping_cards
+ add column if not exists merchant_kind text,
+ add column if not exists marketplace text,
+ add column if not exists listing_id text;
+
+alter table public.prompt_result_shopping_cards
+ drop constraint if exists prompt_result_shopping_cards_merchant_kind_check;
+
+alter table public.prompt_result_shopping_cards
+ add constraint prompt_result_shopping_cards_merchant_kind_check
+ check (merchant_kind is null or merchant_kind in ('own', 'marketplace', 'reseller'));
+
+create index if not exists prompt_result_shopping_cards_amazon_share_idx
+ on public.prompt_result_shopping_cards (brand_id, matched_brand_role, created_at)
+ include (marketplace)
+ where merchant_kind is not null;
+
+comment on column public.prompt_result_shopping_cards.merchant_kind is
+ 'Destination kind from classifyMerchant: own, marketplace, or reseller. Null means the card has no merchant URL and cannot be classified.';
+comment on column public.prompt_result_shopping_cards.marketplace is
+ 'Normalized marketplace id (for example amazon, ebay, walmart); null for own stores, resellers, and unclassified cards.';
+comment on column public.prompt_result_shopping_cards.listing_id is
+ 'Marketplace-native listing identifier when it can be extracted safely (for example an Amazon ASIN).';
+
+-- Return five complete rolling seven-day windows ending at p_as_of. Every
+-- bucket covers exactly seven days, including when p_as_of falls mid-week.
+-- Only brand-matched own products with a classified merchant destination
+-- enter the denominator; cards without a merchant URL stay unclassified.
+create or replace function public.shopping_amazon_share_weekly(
+ p_brand_id uuid,
+ p_as_of timestamptz default now()
+)
+returns table (
+ week_start date,
+ amazon_cards bigint,
+ classified_cards bigint
+)
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+as $$
+#variable_conflict use_column
+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
+ with weeks as (
+ select
+ g.i,
+ p_as_of - (g.i + 1) * interval '7 days' as from_ts,
+ p_as_of - g.i * interval '7 days' as to_ts
+ from generate_series(0, 4) as g(i)
+ )
+ select
+ (w.from_ts at time zone 'UTC')::date as week_start,
+ count(c.id) filter (where c.marketplace = 'amazon') as amazon_cards,
+ count(c.id) as classified_cards
+ from weeks w
+ left join public.prompt_result_shopping_cards c
+ on c.brand_id = p_brand_id
+ and c.matched_brand_role = 'own'
+ and c.merchant_kind is not null
+ and c.created_at >= w.from_ts
+ and c.created_at < w.to_ts
+ group by w.i, w.from_ts
+ order by w.from_ts;
+end;
+$$;
+
+revoke all on function public.shopping_amazon_share_weekly(uuid, timestamptz) from public, anon;
+grant execute on function public.shopping_amazon_share_weekly(uuid, timestamptz) to authenticated, service_role;
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 1537d66f1..b17992bca 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -31697,6 +31697,95 @@ alter table public.prompt_result_citations set (
autovacuum_analyze_scale_factor = 0.02
);
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00225_shopping_merchant_classification.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Shopping merchant classification needed for "Where AI sends shoppers"
+-- and weekly Amazon share alerts (#1277, #1284).
+
+alter table public.prompt_result_shopping_cards
+ add column if not exists merchant_kind text,
+ add column if not exists marketplace text,
+ add column if not exists listing_id text;
+
+alter table public.prompt_result_shopping_cards
+ drop constraint if exists prompt_result_shopping_cards_merchant_kind_check;
+
+alter table public.prompt_result_shopping_cards
+ add constraint prompt_result_shopping_cards_merchant_kind_check
+ check (merchant_kind is null or merchant_kind in ('own', 'marketplace', 'reseller'));
+
+create index if not exists prompt_result_shopping_cards_amazon_share_idx
+ on public.prompt_result_shopping_cards (brand_id, matched_brand_role, created_at)
+ include (marketplace)
+ where merchant_kind is not null;
+
+comment on column public.prompt_result_shopping_cards.merchant_kind is
+ 'Destination kind from classifyMerchant: own, marketplace, or reseller. Null means the card has no merchant URL and cannot be classified.';
+comment on column public.prompt_result_shopping_cards.marketplace is
+ 'Normalized marketplace id (for example amazon, ebay, walmart); null for own stores, resellers, and unclassified cards.';
+comment on column public.prompt_result_shopping_cards.listing_id is
+ 'Marketplace-native listing identifier when it can be extracted safely (for example an Amazon ASIN).';
+
+-- Return five complete rolling seven-day windows ending at p_as_of. Every
+-- bucket covers exactly seven days, including when p_as_of falls mid-week.
+-- Only brand-matched own products with a classified merchant destination
+-- enter the denominator; cards without a merchant URL stay unclassified.
+create or replace function public.shopping_amazon_share_weekly(
+ p_brand_id uuid,
+ p_as_of timestamptz default now()
+)
+returns table (
+ week_start date,
+ amazon_cards bigint,
+ classified_cards bigint
+)
+language plpgsql
+stable
+security definer
+set search_path to 'public'
+as $$
+#variable_conflict use_column
+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
+ with weeks as (
+ select
+ g.i,
+ p_as_of - (g.i + 1) * interval '7 days' as from_ts,
+ p_as_of - g.i * interval '7 days' as to_ts
+ from generate_series(0, 4) as g(i)
+ )
+ select
+ (w.from_ts at time zone 'UTC')::date as week_start,
+ count(c.id) filter (where c.marketplace = 'amazon') as amazon_cards,
+ count(c.id) as classified_cards
+ from weeks w
+ left join public.prompt_result_shopping_cards c
+ on c.brand_id = p_brand_id
+ and c.matched_brand_role = 'own'
+ and c.merchant_kind is not null
+ and c.created_at >= w.from_ts
+ and c.created_at < w.to_ts
+ group by w.i, w.from_ts
+ order by w.from_ts;
+end;
+$$;
+
+revoke all on function public.shopping_amazon_share_weekly(uuid, timestamptz) from public, anon;
+grant execute on function public.shopping_amazon_share_weekly(uuid, timestamptz) to authenticated, service_role;
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00226_content_reads_bounded.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index 1657db859..26c151e2e 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -5575,6 +5575,7 @@
"kpiTopMerchantSub": "Most frequent merchant domain",
"platformBreakdownTitle": "Card rate by platform",
"trendTitle": "Your shopping presence — last 30 days",
+ "amazonShareDropAlert": "Amazon's share fell from {from}% to {to}% over the last seven days. AI may be leaving Amazon out; your own store link matters more.",
"filterRegion": "Region",
"filterPlatform": "Platform",
"filterDateRange": "Date range",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
index 44b882e78..2ac7b1e1d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx
@@ -31,12 +31,14 @@ import {
Search,
Calendar,
Globe,
+ AlertTriangle,
} from 'lucide-react';
import { useBrandStore } from '@/stores/use-brand-store';
import { useFeatureGate } from '@/hooks/use-feature-gate';
import {
getShoppingFilterOptions,
getShoppingOverview,
+ getShoppingAmazonShareDropAlert,
getOwnProducts,
getCompetitorProducts,
getCompetitorSummary,
@@ -88,6 +90,7 @@ import {
import { toCsv } from '@/lib/csv';
import { PLATFORM_LABELS } from '@/config/platform-labels';
import { formatRegionDisplay } from '@/lib/region';
+import type { AmazonShareDropAlert } from '@/lib/shopping-amazon-share-alert';
const DATE_PRESETS: ShoppingDatePreset[] = ['7d', '30d', '90d', 'all'];
@@ -120,6 +123,9 @@ export default function ShoppingPage() {
const [kpis, setKpis] = useState<ShoppingKpis | null>(null);
const [charts, setCharts] = useState<ShoppingChartData | null>(null);
const [loading, setLoading] = useState(false);
+ const [amazonShareDropAlert, setAmazonShareDropAlert] = useState<AmazonShareDropAlert | null>(
+ null,
+ );
const [ownProducts, setOwnProducts] = useState<ShoppingProduct[]>([]);
const [competitorProducts, setCompetitorProducts] = useState<ShoppingProduct[]>([]);
@@ -205,6 +211,27 @@ export default function ShoppingPage() {
void loadData();
}, [loadData]);
+ // This alert always evaluates five consecutive rolling seven-day windows
+ // ending at query time, independently of display/platform/region filters.
+ useEffect(() => {
+ if (!activeBrandId) {
+ setAmazonShareDropAlert(null);
+ return;
+ }
+ let cancelled = false;
+ getShoppingAmazonShareDropAlert(activeBrandId)
+ .then((alert) => {
+ if (!cancelled) setAmazonShareDropAlert(alert);
+ })
+ .catch(() => {
+ // The alert is supplemental; a query failure must not break Shopping.
+ if (!cancelled) setAmazonShareDropAlert(null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeBrandId]);
+
if (!activeBrandId) {
return (
<div className="space-y-6">
@@ -225,6 +252,24 @@ export default function ShoppingPage() {
<div className="space-y-6">
<PageHeader t={t} />
+ {amazonShareDropAlert && (
+ <div
+ role="alert"
+ className="flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-900/50 dark:bg-amber-950/30"
+ >
+ <AlertTriangle
+ className="mt-0.5 h-5 w-5 shrink-0 text-amber-600 dark:text-amber-500"
+ aria-hidden="true"
+ />
+ <p className="text-sm text-amber-900 dark:text-amber-200">
+ {t('amazonShareDropAlert', {
+ from: Math.round(amazonShareDropAlert.fromShare * 100),
+ to: Math.round(amazonShareDropAlert.toShare * 100),
+ })}
+ </p>
+ </div>
+ )}
+
<FilterBar
t={t}
datePreset={datePreset}
diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.ts
index 93d469c4b..2f18a63c3 100644
--- a/web/src/lib/actions/shopping.ts
+++ b/web/src/lib/actions/shopping.ts
@@ -2,6 +2,10 @@
import { createClient } from '@/lib/supabase/server';
import { expandDateToEndOfDay } from '@/lib/dates';
+import {
+ detectAmazonShareDrop,
+ type AmazonShareDropAlert,
+} from '@/lib/shopping-amazon-share-alert';
/**
* Server actions for the Shopping dashboard page. Reads from the
@@ -176,6 +180,34 @@ export async function getShoppingOverview(
return { kpis: toKpis(row), charts: toChartData(row) };
}
+/**
+ * Returns an Amazon share-drop alert for own-product cards across five rolling
+ * seven-day windows. The RPC aggregates in Postgres so this stays accurate
+ * beyond PostgREST's 1,000-row cap; only classified cards enter the counts.
+ */
+export async function getShoppingAmazonShareDropAlert(
+ brandId: string,
+): Promise<AmazonShareDropAlert | null> {
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('shopping_amazon_share_weekly', {
+ p_brand_id: brandId,
+ });
+ if (error) throw new Error(error.message);
+
+ const rows = (data ?? []) as Array<{
+ week_start: string;
+ amazon_cards: number | string;
+ classified_cards: number | string;
+ }>;
+ return detectAmazonShareDrop(
+ rows.map((row) => ({
+ weekStart: row.week_start,
+ amazonCards: Number(row.amazon_cards),
+ classifiedCards: Number(row.classified_cards),
+ })),
+ );
+}
+
/**
* 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-amazon-share-alert.test.ts b/web/src/lib/shopping-amazon-share-alert.test.ts
new file mode 100644
index 000000000..ca95d3c5e
--- /dev/null
+++ b/web/src/lib/shopping-amazon-share-alert.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+import { detectAmazonShareDrop, type WeeklyAmazonShare } from './shopping-amazon-share-alert';
+
+function fixture(shares: number[], classifiedCards: number[] = [100, 100, 100, 100, 100]) {
+ const firstWeek = Date.parse('2026-09-21T00:00:00.000Z');
+ return shares.map((share, index): WeeklyAmazonShare => {
+ const weekStart = new Date(firstWeek + index * 7 * 24 * 60 * 60 * 1000)
+ .toISOString()
+ .slice(0, 10);
+ const total = classifiedCards[index];
+ return {
+ weekStart,
+ amazonCards: Math.round((share / 100) * total),
+ classifiedCards: total,
+ };
+ });
+}
+
+describe('detectAmazonShareDrop', () => {
+ it('alerts on a fall from 31% to 4% when every week has enough classified cards', () => {
+ expect(detectAmazonShareDrop(fixture([31, 31, 31, 31, 4]))).toEqual({
+ fromShare: 0.31,
+ toShare: 0.04,
+ baselineCards: 400,
+ currentCards: 100,
+ });
+ });
+
+ it('does not alert on ordinary weekly noise', () => {
+ expect(detectAmazonShareDrop(fixture([31, 28, 33, 30, 26]))).toBeNull();
+ });
+
+ it('does not alert when the current week has fewer than 30 classified cards', () => {
+ expect(
+ detectAmazonShareDrop(fixture([31, 31, 31, 31, 4], [100, 100, 100, 100, 29])),
+ ).toBeNull();
+ });
+
+ it('does not alert if any week in the four-week baseline has fewer than 30 cards', () => {
+ expect(
+ detectAmazonShareDrop(fixture([31, 31, 31, 31, 4], [100, 29, 100, 100, 100])),
+ ).toBeNull();
+ });
+
+ it('does not alert unless the current share is below half of the baseline', () => {
+ expect(detectAmazonShareDrop(fixture([31, 31, 31, 31, 16]))).toBeNull();
+ });
+
+ it('does not alert when the drop is below ten percentage points', () => {
+ expect(detectAmazonShareDrop(fixture([20, 20, 20, 20, 11]))).toBeNull();
+ });
+
+ it('alerts at exactly ten percentage points despite floating-point representation', () => {
+ expect(detectAmazonShareDrop(fixture([18, 18, 18, 18, 8]))).toEqual({
+ fromShare: 0.18,
+ toShare: 0.08,
+ baselineCards: 400,
+ currentCards: 100,
+ });
+ });
+
+ it('requires five consecutive weeks', () => {
+ const weeks = fixture([31, 31, 31, 31, 4]);
+ weeks[2] = { ...weeks[2], weekStart: '2026-10-06' };
+ expect(detectAmazonShareDrop(weeks)).toBeNull();
+ });
+
+ it('does not alert on malformed counts', () => {
+ const weeks = fixture([31, 31, 31, 31, 4]);
+ weeks[4] = { ...weeks[4], amazonCards: 101 };
+ expect(detectAmazonShareDrop(weeks)).toBeNull();
+ });
+});
diff --git a/web/src/lib/shopping-amazon-share-alert.ts b/web/src/lib/shopping-amazon-share-alert.ts
new file mode 100644
index 000000000..711e60def
--- /dev/null
+++ b/web/src/lib/shopping-amazon-share-alert.ts
@@ -0,0 +1,79 @@
+export const AMAZON_SHARE_REQUIRED_WEEKS = 5;
+export const AMAZON_SHARE_MIN_CLASSIFIED_CARDS = 30;
+export const AMAZON_SHARE_MAX_CURRENT_RATIO = 0.5;
+export const AMAZON_SHARE_MIN_ABSOLUTE_DROP = 0.1;
+
+export interface WeeklyAmazonShare {
+ weekStart: string;
+ amazonCards: number;
+ classifiedCards: number;
+}
+
+export interface AmazonShareDropAlert {
+ /** Median Amazon share across the previous four complete rolling seven-day windows. */
+ fromShare: number;
+ /** Amazon share in the latest complete seven-day window ending at query time. */
+ toShare: number;
+ baselineCards: number;
+ currentCards: number;
+}
+
+function median(values: number[]): number {
+ const sorted = [...values].sort((a, b) => a - b);
+ const middle = Math.floor(sorted.length / 2);
+ return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle];
+}
+
+function isConsecutiveWeeks(weeks: WeeklyAmazonShare[]): boolean {
+ const weekStarts = weeks.map((week) => Date.parse(`${week.weekStart}T00:00:00.000Z`));
+ if (weekStarts.some((date) => !Number.isFinite(date))) return false;
+ const sevenDays = 7 * 24 * 60 * 60 * 1000;
+ return weekStarts.every(
+ (date, index) => index === 0 || date - weekStarts[index - 1] === sevenDays,
+ );
+}
+
+/**
+ * Detect a meaningful drop in Amazon's share of classified cards for a brand's
+ * own products. Requires five consecutive rolling seven-day windows with at
+ * least 30 classified cards each, so low-volume windows never trigger the alert.
+ */
+export function detectAmazonShareDrop(
+ input: readonly WeeklyAmazonShare[],
+): AmazonShareDropAlert | null {
+ const weeks = [...input]
+ .sort((a, b) => a.weekStart.localeCompare(b.weekStart))
+ .slice(-AMAZON_SHARE_REQUIRED_WEEKS);
+ if (weeks.length !== AMAZON_SHARE_REQUIRED_WEEKS || !isConsecutiveWeeks(weeks)) return null;
+
+ for (const week of weeks) {
+ if (
+ !Number.isFinite(week.amazonCards) ||
+ !Number.isFinite(week.classifiedCards) ||
+ week.classifiedCards < AMAZON_SHARE_MIN_CLASSIFIED_CARDS ||
+ week.amazonCards < 0 ||
+ week.amazonCards > week.classifiedCards
+ ) {
+ return null;
+ }
+ }
+
+ const shares = weeks.map((week) => week.amazonCards / week.classifiedCards);
+ const baselineShare = median(shares.slice(0, -1));
+ const currentShare = shares[shares.length - 1];
+ const absoluteDrop = baselineShare - currentShare;
+
+ if (
+ currentShare >= baselineShare * AMAZON_SHARE_MAX_CURRENT_RATIO ||
+ absoluteDrop < AMAZON_SHARE_MIN_ABSOLUTE_DROP - 1e-9
+ ) {
+ return null;
+ }
+
+ return {
+ fromShare: baselineShare,
+ toShare: currentShare,
+ baselineCards: weeks.slice(0, -1).reduce((total, week) => total + week.classifiedCards, 0),
+ currentCards: weeks[weeks.length - 1].classifiedCards,
+ };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index cfe59c10e..31752933c 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -2268,9 +2268,12 @@ export type Database = {
created_at: string
id: string
image_url: string | null
+ listing_id: string | null
+ marketplace: string | null
matched_brand_id: string | null
matched_brand_role: string
merchant_domain: string | null
+ merchant_kind: string | null
merchant_url: string | null
platform: string
position: number
@@ -2289,9 +2292,12 @@ export type Database = {
created_at?: string
id?: string
image_url?: string | null
+ listing_id?: string | null
+ marketplace?: string | null
matched_brand_id?: string | null
matched_brand_role?: string
merchant_domain?: string | null
+ merchant_kind?: string | null
merchant_url?: string | null
platform: string
position: number
@@ -2310,9 +2316,12 @@ export type Database = {
created_at?: string
id?: string
image_url?: string | null
+ listing_id?: string | null
+ marketplace?: string | null
matched_brand_id?: string | null
matched_brand_role?: string
merchant_domain?: string | null
+ merchant_kind?: string | null
merchant_url?: string | null
platform?: string
position?: number
@@ -4291,6 +4300,14 @@ export type Database = {
}
Returns: Json
}
+ shopping_amazon_share_weekly: {
+ Args: { p_as_of?: string; p_brand_id: string }
+ Returns: {
+ amazon_cards: number
+ classified_cards: number
+ week_start: string
+ }[]
+ }
shopping_filter_options: {
Args: { p_brand_id: string }
Returns: {