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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(shopping): list the catalog's products with their AI shelf, visits, orders and readiness (Product Visibility, part 4) (#1639)
Cihance92aabe6022
diff --git a/supabase/migrations/00361_catalog_product_ai_stats.sql b/supabase/migrations/00361_catalog_product_ai_stats.sqlnew file mode 100644index 000000000..2b58f8f9b--- /dev/null+++ b/supabase/migrations/00361_catalog_product_ai_stats.sql@@ -0,0 +1,125 @@+-- ============================================================================+-- 00361: AI visits and orders per catalog product (product visibility, part 4)+-- ============================================================================+-- Product Visibility's Products table (ECOM-007) shows, for each product in+-- the brand's catalog (00278), the AI-referred visits its page got and the+-- orders those visits led to, beside where it stands on the AI shelf. No+-- source carries an order's line items yet (Shopify order sync, #1267), so an+-- order is credited to the product whose page the AI visitor landed on first:+-- ai_traffic_events.first_url (CE-017, 00286).+--+-- * ai_visits: AI-referred page views on the product's page (the tracking+-- snippet, ai_traffic_logs: a visit's first view, from an AI source);+-- * orders, revenue: order conversions whose AI visit started on it, the+-- revenue in its main currency;+-- * a product's page is its link, else its first variant's, matched as+-- page paths are everywhere (normalize_page_path, lowercased);+-- * only the products with an AI visit or an order: a big catalog's other+-- products would only add zero rows, past PostgREST's 1000-row page;+-- * p_product_id: that one product's row (its page), none for all.+--+-- Members of the brand's organization only, as the Shopping reads.++create or replace function public.catalog_product_ai_stats(+ p_brand_id uuid,+ p_from timestamptz,+ p_to timestamptz default null,+ p_product_id uuid default null+)+returns table (+ product_id uuid,+ ai_visits bigint,+ orders bigint,+ revenue numeric,+ currency text+)+language plpgsql+stable+security definer+set search_path to 'public'+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+ with pages as (+ select+ p.id as product_id,+ lower(public.normalize_page_path(coalesce(p.url, (+ select v.url+ from public.catalog_variants v+ where v.product_id = p.id and v.removed_at is null and v.url is not null+ order by v.external_id+ limit 1+ )))) as page+ from public.catalog_products p+ where p.brand_id = p_brand_id+ and p.removed_at is null+ and (p_product_id is null or p.id = p_product_id)+ ),+ keyed as (+ select pages.product_id, pages.page+ from pages+ where pages.page is not null and pages.page <> '/'+ ),+ visits as (+ select lower(public.normalize_page_path(l.url)) as page, count(*) as n+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.created_at >= p_from+ and (p_to is null or l.created_at < p_to)+ and l.visit_of is null+ and l.source_platform is not null+ group by 1+ ),+ sales as (+ select e.first_key as page, e.currency, count(*) as n, coalesce(sum(e.value), 0) as value+ from public.ai_traffic_events e+ where e.brand_id = p_brand_id+ and e.kind = 'conversion'+ and e.goal = 'order'+ and e.occurred_at >= p_from+ and (p_to is null or e.occurred_at < p_to)+ group by 1, 2+ ),+ -- A page's orders in its main currency: the one most of them are in.+ main_sales as (+ select distinct on (s.page) s.page, s.currency, s.value+ from sales s+ order by s.page, s.n desc, s.currency+ ),+ all_sales as (+ select s.page, sum(s.n) as n+ from sales s+ group by 1+ )+ select+ k.product_id,+ coalesce(v.n, 0)::bigint,+ coalesce(a.n, 0)::bigint,+ m.value,+ m.currency+ from keyed k+ left join visits v on v.page = k.page+ left join all_sales a on a.page = k.page+ left join main_sales m on m.page = k.page+ where v.n is not null or a.n is not null;+end;+$$;++revoke all on function public.catalog_product_ai_stats(uuid, timestamptz, timestamptz, uuid) from public, anon;+grant execute on function public.catalog_product_ai_stats(uuid, timestamptz, timestamptz, uuid)+ to authenticated, service_role;++comment on function public.catalog_product_ai_stats(uuid, timestamptz, timestamptz, uuid) is+ 'Product visibility, part 4 (00361): per live catalog product of a brand with an AI visit or an order (or the one p_product_id names), the AI-referred visits to its page and the orders whose AI visit started there (first_url), with their revenue in the main currency. A product''s page is its link, else its first variant''s. Security definer with an organization check.';++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex df098bd88..a1b7d829e 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -41944,6 +41944,135 @@ grant execute on function public.set_shopping_card_matches(uuid, jsonb) to servinotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00361_catalog_product_ai_stats.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00361: AI visits and orders per catalog product (product visibility, part 4)+-- ============================================================================+-- Product Visibility's Products table (ECOM-007) shows, for each product in+-- the brand's catalog (00278), the AI-referred visits its page got and the+-- orders those visits led to, beside where it stands on the AI shelf. No+-- source carries an order's line items yet (Shopify order sync, #1267), so an+-- order is credited to the product whose page the AI visitor landed on first:+-- ai_traffic_events.first_url (CE-017, 00286).+--+-- * ai_visits: AI-referred page views on the product's page (the tracking+-- snippet, ai_traffic_logs: a visit's first view, from an AI source);+-- * orders, revenue: order conversions whose AI visit started on it, the+-- revenue in its main currency;+-- * a product's page is its link, else its first variant's, matched as+-- page paths are everywhere (normalize_page_path, lowercased);+-- * only the products with an AI visit or an order: a big catalog's other+-- products would only add zero rows, past PostgREST's 1000-row page;+-- * p_product_id: that one product's row (its page), none for all.+--+-- Members of the brand's organization only, as the Shopping reads.++create or replace function public.catalog_product_ai_stats(+ p_brand_id uuid,+ p_from timestamptz,+ p_to timestamptz default null,+ p_product_id uuid default null+)+returns table (+ product_id uuid,+ ai_visits bigint,+ orders bigint,+ revenue numeric,+ currency text+)+language plpgsql+stable+security definer+set search_path to 'public'+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+ with pages as (+ select+ p.id as product_id,+ lower(public.normalize_page_path(coalesce(p.url, (+ select v.url+ from public.catalog_variants v+ where v.product_id = p.id and v.removed_at is null and v.url is not null+ order by v.external_id+ limit 1+ )))) as page+ from public.catalog_products p+ where p.brand_id = p_brand_id+ and p.removed_at is null+ and (p_product_id is null or p.id = p_product_id)+ ),+ keyed as (+ select pages.product_id, pages.page+ from pages+ where pages.page is not null and pages.page <> '/'+ ),+ visits as (+ select lower(public.normalize_page_path(l.url)) as page, count(*) as n+ from public.ai_traffic_logs l+ where l.brand_id = p_brand_id+ and l.created_at >= p_from+ and (p_to is null or l.created_at < p_to)+ and l.visit_of is null+ and l.source_platform is not null+ group by 1+ ),+ sales as (+ select e.first_key as page, e.currency, count(*) as n, coalesce(sum(e.value), 0) as value+ from public.ai_traffic_events e+ where e.brand_id = p_brand_id+ and e.kind = 'conversion'+ and e.goal = 'order'+ and e.occurred_at >= p_from+ and (p_to is null or e.occurred_at < p_to)+ group by 1, 2+ ),+ -- A page's orders in its main currency: the one most of them are in.+ main_sales as (+ select distinct on (s.page) s.page, s.currency, s.value+ from sales s+ order by s.page, s.n desc, s.currency+ ),+ all_sales as (+ select s.page, sum(s.n) as n+ from sales s+ group by 1+ )+ select+ k.product_id,+ coalesce(v.n, 0)::bigint,+ coalesce(a.n, 0)::bigint,+ m.value,+ m.currency+ from keyed k+ left join visits v on v.page = k.page+ left join all_sales a on a.page = k.page+ left join main_sales m on m.page = k.page+ where v.n is not null or a.n is not null;+end;+$$;++revoke all on function public.catalog_product_ai_stats(uuid, timestamptz, timestamptz, uuid) from public, anon;+grant execute on function public.catalog_product_ai_stats(uuid, timestamptz, timestamptz, uuid)+ to authenticated, service_role;++comment on function public.catalog_product_ai_stats(uuid, timestamptz, timestamptz, uuid) is+ 'Product visibility, part 4 (00361): per live catalog product of a brand with an AI visit or an order (or the one p_product_id names), the AI-referred visits to its page and the orders whose AI visit started there (first_url), with their revenue in the main currency. A product''s page is its link, else its first variant''s. Security definer with an organization check.';++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00365_action_outcome_mixed.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 073d934c5..7df416f79 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -7986,6 +7986,52 @@"trends": "Trends","failed": "Couldn't read the shelves right now. The other tabs still work; try again in a moment."},+ "products": {+ "label": "Your products",+ "viewsLabel": "Product views",+ "views": {+ "all": "All",+ "never": "Never shown",+ "notClicked": "Shown, not clicked",+ "notBought": "Clicked, not bought",+ "topSellers": "Top sellers from AI"+ },+ "columns": {+ "product": "Product",+ "shelves": "On shelf",+ "winRate": "Win rate",+ "avgRank": "Avg pos.",+ "aiVisits": "AI clicks",+ "orders": "AI orders",+ "revenue": "AI revenue",+ "readiness": "Readiness"+ },+ "readiness": {+ "label": "Readiness {score} of 100",+ "missing": "Missing: {check} (−{points})",+ "complete": "Everything the catalog can tell is in place.",+ "checks": {+ "gtin": "a GTIN",+ "image": "a photo",+ "inStock": "in stock",+ "price": "a price",+ "description": "a description of 25 words or more",+ "typeFirst": "what the product is, in the description's first 40 words",+ "category": "a category",+ "brand": "a brand"+ }+ },+ "empty": {+ "all": "No products in the catalog.",+ "never": "Every product was on an AI shelf in this period.",+ "notClicked": "No product was shown without an AI visit to its page.",+ "notBought": "No product had AI visits without an order.",+ "topSellers": "No orders from AI visits started on a product page in this period."+ },+ "capped": "Showing {shown} of {total} products: every one AI showed or sent visits to, then the rest.",+ "more": "Show {count} more",+ "failed": "Couldn't read your catalog's products right now. These are the products AI showed, by title."+ },"sources": {"label": "Data sources","catalog": "Product catalog",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.test.tsxnew file mode 100644index 000000000..3f9d375be--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.test.tsx@@ -0,0 +1,114 @@+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 { productRows, type CatalogProductRow } from '@/lib/shopping/products';+import { ProductsTable } from './_products-table';++/** The Products table (ECOM-007). */++(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 ?? '';+}++const product = (+ id: string,+ title: string,+ over: Partial<CatalogProductRow> = {},+): CatalogProductRow => ({+ id,+ title,+ url: null,+ productType: 'Backpacks',+ brand: 'Northwind',+ description: null,+ image: null,+ category: 'Bags > Backpacks',+ price: 119,+ currency: 'USD',+ inStock: true,+ hasGtin: false,+ ...over,+});++const rows = productRows(+ [product('p1', 'Ridge 30L Backpack'), product('p2', 'StormShell Jacket', { price: 189 })],+ [{ productId: 'p2', shelf: 'q1:copilot-web', rank: 1 }],+ [{ productId: 'p2', aiVisits: 402, orders: 38, revenue: 7200, currency: 'USD' }],+);++const views = () =>+ [...container.querySelectorAll('button[aria-pressed]')].map((b) => b.textContent);+const bodyRows = () =>+ [...container.querySelectorAll('tbody tr')].map((tr) =>+ [...tr.querySelectorAll('td')].map((td) => td.textContent),+ );++describe('ProductsTable', () => {+ it("lists the catalog with each product's shelf, visits, orders and readiness", () => {+ render(<ProductsTable products={{ rows, total: 2 }} loading={false} />);+ expect(views()).toEqual([+ 'All2',+ 'Never shown1',+ 'Shown, not clicked0',+ 'Clicked, not bought0',+ 'Top sellers from AI1',+ ]);+ expect(bodyRows()).toEqual([+ ['StormShell JacketBackpacks · $189', '1', '100%', '1.0', '402', '38', '$7,200', '40'],+ ['Ridge 30L BackpackBackpacks · $119', '0', '—', '—', '0', '0', '—', '40'],+ ]);+ });++ it('shows a view, and says when it has nothing', () => {+ render(<ProductsTable products={{ rows, total: 2 }} loading={false} />);+ const notBought = [...container.querySelectorAll('button[aria-pressed]')].find((b) =>+ b.textContent?.startsWith('Clicked, not bought'),+ ) as HTMLButtonElement;+ act(() => notBought.click());+ expect(container.textContent).toContain('No product had AI visits without an order.');+ const never = [...container.querySelectorAll('button[aria-pressed]')].find((b) =>+ b.textContent?.startsWith('Never shown'),+ ) as HTMLButtonElement;+ act(() => never.click());+ expect(bodyRows().map((row) => row[0])).toEqual(['Ridge 30L BackpackBackpacks · $119']);+ });++ it('says when the catalog is larger than the table reads, and counts All and Never shown out of it', () => {+ expect(render(<ProductsTable products={{ rows, total: 2400 }} loading={false} />)).toContain(+ 'Showing 2 of 2,400 products: every one AI showed or sent visits to, then the rest.',+ );+ expect(views()).toEqual([+ 'All2,400',+ 'Never shown2,399',+ 'Shown, not clicked0',+ 'Clicked, not bought0',+ 'Top sellers from AI1',+ ]);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsxnew file mode 100644index 000000000..93c0ead06--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_products-table.tsx@@ -0,0 +1,235 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { ShoppingBag } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Card } from '@/components/ui/card';+import { Skeleton } from '@/components/ui/skeleton';+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/table';+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';+import { formatNumber } from '@/lib/format';+import { cn } from '@/lib/utils';+import type { ShoppingProducts } from '@/lib/actions/shopping';+import {+ PRODUCT_VIEWS,+ READINESS_CHECKS,+ viewCounts,+ viewRows,+ type ProductRow,+ type ProductView,+} from '@/lib/shopping/products';+import { priceText } from '@/lib/shopping/price';++/** Rows shown before "Show more". */+const ROWS_SHOWN = 50;++function readinessTone(score: number): string {+ if (score >= 80)+ return 'border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400';+ if (score >= 50) return 'border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400';+ return 'border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-400';+}++function Readiness({ row }: { row: ProductRow }) {+ const t = useTranslations('shopping.products.readiness');+ return (+ <Tooltip>+ <TooltipTrigger+ delay={200}+ closeDelay={0}+ render={+ <button+ type="button"+ className={cn(+ 'inline-flex h-6 min-w-9 items-center justify-center rounded-md border px-1.5 text-xs font-semibold tabular-nums focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ readinessTone(row.readiness),+ )}+ aria-label={t('label', { score: row.readiness })}+ />+ }+ >+ {row.readiness}+ </TooltipTrigger>+ <TooltipContent className="max-w-72 space-y-1">+ <p className="font-medium">{t('label', { score: row.readiness })}</p>+ {row.missing.length ? (+ row.missing.map((check) => (+ <p key={check} className="opacity-90">+ {t('missing', { check: t(`checks.${check}`), points: READINESS_CHECKS[check] })}+ </p>+ ))+ ) : (+ <p className="opacity-90">{t('complete')}</p>+ )}+ </TooltipContent>+ </Tooltip>+ );+}++function ProductCell({ row }: { row: ProductRow }) {+ const { product } = row;+ return (+ <div className="flex min-w-0 items-center gap-2.5">+ <div className="grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-md border bg-muted/50">+ {product.image ? (+ // eslint-disable-next-line @next/next/no-img-element -- catalog images from the brand's store+ <img+ src={product.image}+ alt=""+ loading="lazy"+ referrerPolicy="no-referrer"+ className="h-full w-full object-cover"+ />+ ) : (+ <ShoppingBag className="h-4 w-4 text-muted-foreground/40" aria-hidden />+ )}+ </div>+ <div className="min-w-0">+ <p className="truncate text-sm font-medium" title={product.title}>+ {product.title}+ </p>+ <p className="truncate text-xs text-muted-foreground">+ {[+ product.category?.split('>').at(-1)?.trim(),+ product.price !== null ? priceText(product.price, product.currency) : null,+ ]+ .filter(Boolean)+ .join(' · ')}+ </p>+ </div>+ </div>+ );+}++/**+ * The Products table (ECOM-007): the brand's catalog, each product with the+ * shelves it was on, its win rate (#1 or #2) and average place, the AI+ * visits its page got, the orders they led to and their revenue, and its+ * readiness. Views: never shown, shown but not clicked, clicked but not+ * bought, and the top sellers from AI.+ */+export function ProductsTable({+ products,+ loading,+}: {+ products: ShoppingProducts | null;+ loading: boolean;+}) {+ const t = useTranslations('shopping.products');+ const [view, setView] = useState<ProductView>('all');+ const [shown, setShown] = useState(ROWS_SHOWN);++ if (loading || !products) {+ return <Skeleton className="h-[320px] w-full" />;+ }+ const rows = viewRows(products.rows, view);+ const counts = viewCounts(products.rows, products.total);++ return (+ <section className="space-y-3" aria-label={t('label')}>+ <div+ className="flex flex-wrap items-center gap-1.5"+ role="group"+ aria-label={t('viewsLabel')}+ >+ {PRODUCT_VIEWS.map((id) => (+ <button+ key={id}+ type="button"+ aria-pressed={view === id}+ onClick={() => {+ setView(id);+ setShown(ROWS_SHOWN);+ }}+ className={cn(+ 'inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50',+ view === id+ ? 'border-primary bg-primary text-primary-foreground'+ : 'bg-card text-muted-foreground hover:bg-muted hover:text-foreground',+ )}+ >+ {t(`views.${id}`)}+ <span className="tabular-nums opacity-70">{formatNumber(counts[id])}</span>+ </button>+ ))}+ </div>+ {products.total > products.rows.length && (+ <p className="text-xs text-muted-foreground">+ {t('capped', {+ shown: formatNumber(products.rows.length),+ total: formatNumber(products.total),+ })}+ </p>+ )}+ <Card className="py-0">+ {rows.length === 0 ? (+ <p className="px-6 py-10 text-center text-sm text-muted-foreground">+ {t(`empty.${view}`)}+ </p>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="pl-4">{t('columns.product')}</TableHead>+ <TableHead className="text-right">{t('columns.shelves')}</TableHead>+ <TableHead className="text-right">{t('columns.winRate')}</TableHead>+ <TableHead className="text-right">{t('columns.avgRank')}</TableHead>+ <TableHead className="text-right">{t('columns.aiVisits')}</TableHead>+ <TableHead className="text-right">{t('columns.orders')}</TableHead>+ <TableHead className="text-right">{t('columns.revenue')}</TableHead>+ <TableHead className="pr-4 text-right">{t('columns.readiness')}</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {rows.slice(0, shown).map((row) => (+ <TableRow key={row.product.id}>+ <TableCell className="max-w-[180px] pl-4 xl:max-w-[360px]">+ <ProductCell row={row} />+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {formatNumber(row.shelves)}+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {row.winRate === null ? '—' : `${Math.round(row.winRate * 100)}%`}+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {row.avgRank === null ? '—' : row.avgRank.toFixed(1)}+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {formatNumber(row.aiVisits)}+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {formatNumber(row.orders)}+ </TableCell>+ <TableCell className="text-right tabular-nums">+ {row.orders && row.revenue !== null+ ? priceText(Math.round(row.revenue), row.currency)+ : '—'}+ </TableCell>+ <TableCell className="pr-4 text-right">+ <Readiness row={row} />+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}+ </Card>+ {rows.length > shown && (+ <div className="flex justify-center">+ <Button variant="outline" size="sm" onClick={() => setShown((n) => n + ROWS_SHOWN)}>+ {t('more', { count: rows.length - shown })}+ </Button>+ </div>+ )}+ </section>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsxindex e1b6f7eb6..f01e2b024 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.test.tsx@@ -14,7 +14,8 @@ vi.mock('@/i18n/navigation', () => ({),}));-const { ShelfKpis, ShelfRows, priceText } = await import('./_shelf');+const { ShelfKpis, ShelfRows } = await import('./_shelf');+const { priceText } = await import('@/lib/shopping/price');(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =true;diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsxindex 9859dc22d..077ce9341 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_shelf.tsx@@ -21,6 +21,7 @@ import { getFaviconUrl } from '@/lib/favicon';import { formatCompactNumber, formatNumber } from '@/lib/format';import { getPlatformName } from '@/lib/traffic-platforms';import { cn } from '@/lib/utils';+import { priceText } from '@/lib/shopping/price';import type { ShoppingAiOrders, ShoppingShelf } from '@/lib/actions/shopping';import {PRICE_BANDS,@@ -44,21 +45,6 @@ const MARKETPLACE_NAMES: Record<string, string> = {const marketplaceName = (id: string) =>MARKETPLACE_NAMES[id] ?? id.charAt(0).toUpperCase() + id.slice(1);-/** A price as the card shows it: "$139", "$24.50", "€89", or the amount and its code. */-export function priceText(value: number, currency: string | null): string {- const digits = Number.isInteger(value) ? 0 : 2;- try {- return new Intl.NumberFormat('en-US', {- style: 'currency',- currency: currency || 'USD',- minimumFractionDigits: digits,- maximumFractionDigits: digits,- }).format(value);- } catch {- return `${value.toFixed(digits)} ${currency ?? ''}`.trim();- }-}-/** A month's revenue, short: "$24.9k". */function revenueText(value: number, currency: string | null): string {if (value < 1000) return priceText(Math.round(value), currency);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxindex 67173bc64..1acda7f4f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx@@ -38,6 +38,7 @@ import {getCompetitorProducts,getCompetitorSummary,getShoppingAiOrders,+ getShoppingProducts,getShoppingShelf,type ShoppingChartData,type ShoppingDatePreset,@@ -46,6 +47,7 @@ import {type ShoppingProduct,type CompetitorShoppingSummary,type ShoppingAiOrders,+ type ShoppingProducts,type ShoppingShelf,} from '@/lib/actions/shopping';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';@@ -92,6 +94,7 @@ import { googleSourceStatus } from '@/lib/traffic-sources';import { readUrlChoice, writeUrlParams } from '@/lib/url-state';import { CatalogNote } from './_catalog-note';import { ProductDataStrip, useProductSources } from './_data-strip';+import { ProductsTable } from './_products-table';import { ShelfKpis, ShelfRows } from './_shelf';import { ShoppingMarketSwitch, useShoppingMarket } from './_market-switch';import { WhyDialog } from './_why-dialog';@@ -99,6 +102,7 @@ import { MerchantSplitCard } from './merchant_split_card';import { OpenAiIndexCard } from './openai_index_card';import { ProductMatchScores } from './product_match_scores';import { ResellerPriceAlerts } from './reseller_price_alerts';+import { useKeyedRead } from './use_keyed_read';import { useMerchantDestinations } from './use_merchant_destinations';import { useOpenAiIndex } from './use_openai_index';@@ -142,7 +146,6 @@ export default function ShoppingPage() {const [ownProducts, setOwnProducts] = useState<ShoppingProduct[]>([]);const [competitorProducts, setCompetitorProducts] = useState<ShoppingProduct[]>([]);const [competitorSummary, setCompetitorSummary] = useState<CompetitorShoppingSummary[]>([]);- const [shelf, setShelf] = useState<ShoppingShelf | 'failed' | null>(null);const [orders, setOrders] = useState<ShoppingAiOrders | null>(null);const [tableLoading, setTableLoading] = useState(false);const [selectedProduct, setSelectedProduct] = useState<ShoppingProduct | null>(null);@@ -225,11 +228,6 @@ export default function ShoppingPage() {getOwnProducts(activeBrandId, filters),getCompetitorProducts(activeBrandId, filters),getCompetitorSummary(activeBrandId, filters),- // The Shelf reads on its own: a failure there leaves the rest.- getShoppingShelf(activeBrandId, filters).catch((err) => {- console.error('Failed to read the shelves:', err);- return 'failed' as const;- }),);}@@ -239,11 +237,10 @@ export default function ShoppingPage() {const overview = results[0] as { kpis: ShoppingKpis; charts: ShoppingChartData };setKpis(overview.kpis);setCharts(overview.charts);- if (hasFullAccess && results.length >= 5) {+ if (hasFullAccess && results.length >= 4) {setOwnProducts(results[1] as ShoppingProduct[]);setCompetitorProducts(results[2] as ShoppingProduct[]);setCompetitorSummary(results[3] as CompetitorShoppingSummary[]);- setShelf(results[4] as ShoppingShelf | 'failed');}}} finally {@@ -259,6 +256,29 @@ export default function ShoppingPage() {void loadData();}, [loadData, shoppingMarket.ready]);+ // The Shelf (ECOM-006) and the Products table (ECOM-007) read once per+ // brand and filters, apart from the rest: neither waits for the other, nor+ // for the older tables. The Products table reads when its tab is open.+ const readKey = `${activeBrandId}:${JSON.stringify(filters)}`;+ const canRead = !!activeBrandId && hasFullAccess && shoppingMarket.ready;+ // Null while it reads.+ const shelf: ShoppingShelf | 'failed' | null =+ useKeyedRead(+ canRead,+ readKey,+ () => getShoppingShelf(activeBrandId!, filters),+ 'the shelves',+ ) ?? null;+ const productsRead = useKeyedRead(+ canRead && activeTab === 'products',+ readKey,+ () => getShoppingProducts(activeBrandId!, filters),+ 'the products',+ );+ const productsLoading = productsRead === undefined;+ // Null for a brand without a catalog, and while it reads.+ const catalogTable: ShoppingProducts | null | 'failed' = productsRead ?? null;+// Orders from AI visits, the last 30 days whatever the filters (ECOM-006).useEffect(() => {if (!activeBrandId || !hasFullAccess) return;@@ -405,7 +425,7 @@ export default function ShoppingPage() {/></div><ShelfRows- shelf={tableLoading || shelf === 'failed' ? null : shelf}+ shelf={shelf === 'failed' ? null : shelf}platforms={filterOpts.platforms}platform={platform}onPlatform={setPlatform}@@ -438,8 +458,21 @@ export default function ShoppingPage() {</TabsContent><TabsContent value="products" className="space-y-6">- {hasFullAccess ? (+ {hasFullAccess && (productsLoading || (catalogTable && catalogTable !== 'failed')) ? (+ <ProductsTable+ products={catalogTable === 'failed' ? null : catalogTable}+ loading={productsLoading}+ />+ ) : hasFullAccess ? (<>+ {/* No catalog yet: the products AI showed, by title, until one is connected. */}+ {catalogTable === 'failed' ? (+ <p className="rounded-lg border bg-muted/40 px-4 py-3 text-sm text-muted-foreground">+ {t('products.failed')}+ </p>+ ) : (+ <CatalogNote brandId={activeBrandId} />+ )}<div className="flex items-center justify-between"><h2 className="text-lg font-semibold">{t('tabMyProducts')}</h2><Button@@ -484,7 +517,6 @@ export default function ShoppingPage() {{tCommon('exportCsv')}</Button></div>- <CatalogNote brandId={activeBrandId} /><ProductTablet={t}products={ownProducts}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_keyed_read.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_keyed_read.test.tsxnew file mode 100644index 000000000..330d6d1cd--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_keyed_read.test.tsx@@ -0,0 +1,92 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { useKeyedRead } from './use_keyed_read';++/** The Shelf's and the Products table's reads (product visibility): once per key, when wanted. */++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let root: Root;+let seen: (string | undefined)[];++function Probe({+ wanted,+ readKey,+ read,+}: {+ wanted: boolean;+ readKey: string;+ read: () => Promise<string>;+}) {+ seen.push(useKeyedRead(wanted, readKey, read, 'the probe'));+ return null;+}++/** A read that answers when told to. */+function deferred() {+ const calls: { resolve: (value: string) => void; reject: (err: Error) => void }[] = [];+ const read = vi.fn(+ () =>+ new Promise<string>((resolve, reject) => {+ calls.push({ resolve, reject });+ }),+ );+ return { read, calls };+}++const render = (props: Parameters<typeof Probe>[0]) => act(() => root.render(<Probe {...props} />));+const last = () => seen.at(-1);++beforeEach(() => {+ seen = [];+ root = createRoot(document.createElement('div'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+});++afterEach(() => {+ act(() => root.unmount());+ vi.restoreAllMocks();+});++describe('useKeyedRead', () => {+ it('reads nothing until wanted, then once for its key, however often the page renders', async () => {+ const { read, calls } = deferred();+ render({ wanted: false, readKey: 'b1:30d', read });+ expect(read).not.toHaveBeenCalled();+ expect(last()).toBeUndefined();++ render({ wanted: true, readKey: 'b1:30d', read });+ render({ wanted: true, readKey: 'b1:30d', read });+ expect(read).toHaveBeenCalledTimes(1);+ expect(last()).toBeUndefined();+ await act(async () => calls[0].resolve('shelf'));+ expect(last()).toBe('shelf');++ // Not wanted any more (another tab), then wanted again: kept, not read again.+ render({ wanted: false, readKey: 'b1:30d', read });+ render({ wanted: true, readKey: 'b1:30d', read });+ expect(read).toHaveBeenCalledTimes(1);+ expect(last()).toBe('shelf');+ });++ it('reads again for a new key, and drops the answer for the old one', async () => {+ const { read, calls } = deferred();+ render({ wanted: true, readKey: 'b1:30d', read });+ render({ wanted: true, readKey: 'b1:7d', read });+ expect(read).toHaveBeenCalledTimes(2);+ await act(async () => calls[0].resolve('30 days'));+ expect(last()).toBeUndefined();+ await act(async () => calls[1].resolve('7 days'));+ expect(last()).toBe('7 days');+ });++ it("gives 'failed' for a read that threw", async () => {+ const { read, calls } = deferred();+ render({ wanted: true, readKey: 'b1:30d', read });+ await act(async () => calls[0].reject(new Error('down')));+ expect(last()).toBe('failed');+ expect(console.error).toHaveBeenCalledWith('Failed to read the probe:', expect.any(Error));+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_keyed_read.ts b/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_keyed_read.tsnew file mode 100644index 000000000..7a566c16e--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/use_keyed_read.ts@@ -0,0 +1,44 @@+'use client';++import { useEffect, useRef, useState } from 'react';++/**+ * A read made once per `key` while it's `wanted`, and kept for that key:+ * undefined while it reads (or until it's wanted), 'failed' when it threw.+ * `key` names what `read` reads (the brand and the filters): a new key reads+ * again, and an answer for an older one is dropped. Product Visibility's+ * Shelf and Products table read this way, each apart from the page's other+ * reads, so none waits for another.+ */+export function useKeyedRead<T>(+ wanted: boolean,+ key: string,+ read: () => Promise<T>,+ /** What it reads, for the console when it fails. */+ what: string,+): T | 'failed' | undefined {+ const [kept, setKept] = useState<{ key: string; value: T | 'failed' } | null>(null);+ // The latest read: a new function each render, called for the key it was made with.+ const readRef = useRef(read);+ useEffect(() => {+ readRef.current = read;+ });+ const keptKey = kept?.key;+ useEffect(() => {+ if (!wanted || keptKey === key) return;+ let cancelled = false;+ readRef.current().then(+ (value) => {+ if (!cancelled) setKept({ key, value });+ },+ (err) => {+ console.error(`Failed to read ${what}:`, err);+ if (!cancelled) setKept({ key, value: 'failed' });+ },+ );+ return () => {+ cancelled = true;+ };+ }, [wanted, key, keptKey, what]);+ return kept?.key === key ? kept.value : undefined;+}diff --git a/web/src/lib/actions/shopping-products.test.ts b/web/src/lib/actions/shopping-products.test.tsnew file mode 100644index 000000000..63da4e234--- /dev/null+++ b/web/src/lib/actions/shopping-products.test.ts@@ -0,0 +1,294 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** The Products table's read (ECOM-007): the catalog, its cards on the shelves and its AI visits and orders. */++const BRAND = '33333333-3333-3333-3333-333333333333';++let tables: Record<string, Record<string, unknown>[]>;+let catalogCount: number;+let stats: Record<string, unknown>[];+const rpcCalls: { name: string; args: Record<string, unknown>; range?: [number, number] }[] = [];+const cardFilters: Record<string, unknown>[] = [];+// The id lists each read filtered by, as [table, column, how many].+let filtered: [string, string, number][];++/** A table read, or an RPC's rows (`rows`), with the PostgREST calls it gets; pages of 1000 at most. */+function query(+ table: string,+ rows?: () => Record<string, unknown>[],+ onRange?: (r: [number, number]) => void,+) {+ const state: {+ eq: Record<string, unknown>;+ in: [string, unknown[]][];+ not: string[];+ head?: boolean;+ range?: [number, number];+ } = {+ eq: {},+ in: [],+ not: [],+ };+ const q = {+ select: (_columns: string, opts?: { head?: boolean }) => ((state.head = opts?.head), q),+ eq: (column: string, value: unknown) => ((state.eq[column] = value), q),+ not: (column: string) => (state.not.push(column), q),+ is: () => q,+ in: (column: string, values: unknown[]) => (+ state.in.push([column, values]),+ filtered.push([table, column, values.length]),+ q+ ),+ gte: () => q,+ lte: () => q,+ or: () => q,+ order: () => q,+ range: (from: number, to: number) => ((state.range = [from, to]), onRange?.([from, to]), q),+ then: (resolve: (value: unknown) => void) => {+ if (state.head) return resolve({ data: null, count: catalogCount, error: null });+ if (table === 'prompt_result_shopping_cards')+ cardFilters.push({ ...state.eq, not: state.not });+ const [from, to] = state.range ?? [0, 999];+ const found = (rows ? rows() : (tables[table] ?? [])).filter((row) =>+ state.in.every(([column, values]) => values.includes(row[column])),+ );+ resolve({ data: found.slice(from, Math.min(to, from + 999) + 1), error: null });+ },+ };+ return q;+}++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: (table: string) => query(table),+ rpc: (name: string, args: Record<string, unknown>) => {+ const call: (typeof rpcCalls)[number] = { name, args };+ rpcCalls.push(call);+ return query(+ name,+ () => stats,+ (range) => (call.range = range),+ );+ },+ })),+}));++const { getShoppingProducts } = await import('./shopping');++beforeEach(() => {+ tables = {};+ stats = [];+ catalogCount = 0;+ rpcCalls.length = 0;+ cardFilters.length = 0;+ filtered = [];+ vi.useFakeTimers({ now: new Date('2026-10-27T12:00:00Z'), toFake: ['Date'] });+});++describe('getShoppingProducts', () => {+ it('reads no catalog as none', async () => {+ expect(await getShoppingProducts(BRAND, { datePreset: '30d' })).toBeNull();+ });++ it("joins each product's variants, first photo, category, shelves and AI visits and orders", async () => {+ catalogCount = 2;+ tables.catalog_products = [+ {+ id: 'p1',+ title: 'Trail Runner X',+ url: null,+ product_type: 'Shoes',+ product_brand: 'Northwind',+ description: null,+ },+ {+ id: 'p2',+ title: 'Ridge 30L',+ url: null,+ product_type: null,+ product_brand: null,+ description: null,+ },+ ];+ tables.catalog_variants = [+ {+ product_id: 'p1',+ gtin: null,+ price: 149,+ sale_price: 129,+ currency: 'USD',+ availability: 'In Stock',+ },+ {+ product_id: 'p1',+ gtin: '0012345678905',+ price: 99,+ sale_price: null,+ currency: 'USD',+ availability: 'out of stock',+ },+ {+ product_id: 'p2',+ gtin: null,+ price: 119,+ sale_price: null,+ currency: 'USD',+ availability: 'out_of_stock',+ },+ ];+ tables.catalog_images = [+ { product_id: 'p1', url: 'https://cdn.example/b.jpg', position: 2 },+ { product_id: 'p1', url: 'https://cdn.example/a.jpg', position: 0 },+ ];+ tables.catalog_product_categories = [+ { product_id: 'p1', category: { name: 'Shoes > Trail running' } },+ { product_id: 'p1', category: { name: 'Sale' } },+ ];+ tables.prompt_result_shopping_cards = [+ {+ catalog_product_id: 'p1',+ position: 0,+ platform: 'chatgpt-shopping',+ prompt_results: { prompt_id: 'q1' },+ },+ {+ catalog_product_id: 'p1',+ position: 2,+ platform: 'copilot-web',+ prompt_results: { prompt_id: 'q1' },+ },+ ];+ stats = [{ product_id: 'p1', ai_visits: 318, orders: 41, revenue: '5300.00', currency: 'USD' }];++ const read = await getShoppingProducts(BRAND, { datePreset: '30d' });+ expect(read?.total).toBe(2);+ const [p1, p2] = read!.rows;+ // In stock: the in-stock variant's sale price, not the cheaper sold-out one.+ expect(p1.product).toMatchObject({+ image: 'https://cdn.example/a.jpg',+ category: 'Shoes > Trail running',+ price: 129,+ inStock: true,+ hasGtin: true,+ });+ expect(p1).toMatchObject({+ shelves: 2,+ winRate: 0.5,+ avgRank: 2,+ aiVisits: 318,+ orders: 41,+ revenue: 5300,+ });+ expect(p2.product).toMatchObject({ price: 119, inStock: false, image: null, category: null });+ expect(cardFilters[0]).toEqual({+ brand_id: BRAND,+ matched_brand_role: 'own',+ not: ['catalog_product_id'],+ });+ expect(rpcCalls).toEqual([+ {+ name: 'catalog_product_ai_stats',+ args: { p_brand_id: BRAND, p_from: '2026-09-27T12:00:00.000Z' },+ range: [0, 999],+ },+ ]);+ // A catalog the table holds whole is read by the brand, not by ids.+ expect(filtered).toEqual([]);+ });++ it('reads the last 90 days of visits and orders for All time', async () => {+ catalogCount = 1;+ tables.catalog_products = [+ {+ id: 'p1',+ title: 'X',+ url: null,+ product_type: null,+ product_brand: null,+ description: null,+ },+ ];+ await getShoppingProducts(BRAND, { datePreset: 'all' });+ expect(rpcCalls[0].args.p_from).toBe('2026-07-29T12:00:00.000Z');+ });++ it("reads every page of the products' AI visits and orders, past PostgREST's 1000 rows", async () => {+ catalogCount = 1500;+ tables.catalog_products = Array.from({ length: 1500 }, (_, i) => ({+ id: `p${String(i).padStart(4, '0')}`,+ title: `Product ${i}`,+ }));+ stats = tables.catalog_products.map(({ id }) => ({+ product_id: id,+ ai_visits: 1,+ orders: 0,+ revenue: null,+ currency: null,+ }));+ const read = await getShoppingProducts(BRAND, { datePreset: '30d' });+ expect(rpcCalls.map((call) => call.range)).toEqual([+ [0, 999],+ [1000, 1999],+ ]);+ expect(read!.rows.every((row) => row.aiVisits === 1)).toBe(true);+ });++ describe('a catalog bigger than the table', () => {+ const id = (i: number) => `p${String(i).padStart(5, '0')}`;+ beforeEach(() => {+ catalogCount = 3000;+ tables.catalog_products = Array.from({ length: 3000 }, (_, i) => ({+ id: id(i),+ title: `Product ${i}`,+ }));+ tables.catalog_variants = tables.catalog_products.map((p) => ({+ product_id: p.id,+ gtin: null,+ price: 10,+ sale_price: null,+ currency: 'USD',+ availability: 'in stock',+ }));+ });++ it('lists the products on a shelf or visited from AI first, then the rest by id', async () => {+ // Past the first 2,000 by id: one on a shelf, one visited, one sold.+ tables.prompt_result_shopping_cards = [+ {+ catalog_product_id: id(2900),+ position: 0,+ platform: 'chatgpt-shopping',+ prompt_results: { prompt_id: 'q1' },+ },+ ];+ stats = [+ { product_id: id(2950), ai_visits: 12, orders: 0, revenue: null, currency: null },+ { product_id: id(2990), ai_visits: 3, orders: 2, revenue: '80.00', currency: 'USD' },+ ];+ const read = await getShoppingProducts(BRAND, { datePreset: '30d' });+ expect(read!.total).toBe(3000);+ const ids = read!.rows.map((row) => row.product.id);+ expect(ids).toHaveLength(2000);+ expect(ids).toEqual(expect.arrayContaining([id(2900), id(2950), id(2990), id(0), id(1996)]));+ expect(ids).not.toContain(id(1997));+ expect(read!.rows.find((row) => row.product.id === id(2990))).toMatchObject({+ orders: 2,+ product: { price: 10, inStock: true },+ });+ });++ it("reads the listed products' rows, variants among them, a hundred ids at a time", async () => {+ await getShoppingProducts(BRAND, { datePreset: '30d' });+ for (const table of [+ 'catalog_products',+ 'catalog_variants',+ 'catalog_images',+ 'catalog_product_categories',+ ]) {+ const reads = filtered.filter(([name]) => name === table).map(([, , count]) => count);+ expect(reads, table).toHaveLength(20);+ expect(reads.every((count) => count === 100)).toBe(true);+ }+ });+ });+});diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex 7bb77af40..0c3df0e96 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -1,6 +1,7 @@'use server';import { createClient } from '@/lib/supabase/server';+import { readAllRpcRows } from '@/lib/supabase/rpc-pages';import { expandDateToEndOfDay } from '@/lib/dates';import {detectAmazonShareDrop,@@ -16,6 +17,13 @@ import {type ShelfRow,type ShelfStats,} from '@/lib/shopping/shelf';+import {+ productRows,+ type CatalogProductRow,+ type ProductAiStats,+ type ProductCardRow,+ type ProductRow,+} from '@/lib/shopping/products';import {toMerchantSplit,type MerchantSplitRow,@@ -1221,3 +1229,302 @@ export async function getShoppingAiOrders(brandId: string): Promise<ShoppingAiOr.sort((a, b) => b.orders - a.orders || a.source.localeCompare(b.source)),};}++// ── Products (Product Visibility, ECOM-007) ───────────────────────────────────++/** Catalog products the table reads at most. */+const PRODUCTS_TABLE_MAX = 2000;+const CATALOG_PAGE = 1000;+/** Product ids one catalog read filters by: each request's address stays short. */+const IDS_PER_READ = 100;+/** Such reads in flight at once. */+const ID_READS_AT_ONCE = 6;+const IN_STOCK = new Set(['in_stock', 'instock', 'available', 'limited_availability']);++type ServerClient = Awaited<ReturnType<typeof createClient>>;++export interface ShoppingProducts {+ rows: ProductRow[];+ /** The brand's live catalog products; more than `rows` when past PRODUCTS_TABLE_MAX. */+ total: number;+}++/** Every row of a brand's catalog table, in `.range()` pages, up to `max`. */+async function readCatalogRows<T>(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder generics+ build: () => any,+ max: number,+): Promise<T[]> {+ const rows: T[] = [];+ for (let start = 0; start < max; start += CATALOG_PAGE) {+ const { data, error } = await build().range(start, Math.min(start + CATALOG_PAGE, max) - 1);+ if (error) throw new Error(error.message);+ rows.push(...((data ?? []) as T[]));+ if ((data ?? []).length < CATALOG_PAGE) break;+ }+ return rows;+}++/** A catalog table's rows for these ids: IDS_PER_READ ids a read, ID_READS_AT_ONCE reads at a time. */+async function readForIds<T>(ids: readonly string[], read: (some: string[]) => Promise<T[]>) {+ const slices: string[][] = [];+ for (let i = 0; i < ids.length; i += IDS_PER_READ) slices.push(ids.slice(i, i + IDS_PER_READ));+ const out: T[][] = [];+ let next = 0;+ await Promise.all(+ Array.from({ length: Math.min(ID_READS_AT_ONCE, slices.length) }, async () => {+ while (next < slices.length) {+ const at = next++;+ out[at] = await read(slices[at]);+ }+ }),+ );+ return out.flat();+}++/**+ * Per product, its AI visits and orders over the window (00361): only the+ * products with either, every page of them.+ */+async function readProductAiStats(supabase: ServerClient, brandId: string, from: string) {+ return readAllRpcRows((start, end) =>+ supabase+ .rpc('catalog_product_ai_stats', { p_brand_id: brandId, p_from: from })+ .order('product_id')+ .range(start, end),+ );+}++/**+ * The Products table: the brand's catalog, each product with its shelves,+ * win rate and average place over the filter window (its cards, 00360),+ * the AI visits its page got and the orders they led to (00361), and its+ * readiness. Null when the brand has no catalog.+ *+ * Past PRODUCTS_TABLE_MAX products, the table holds the products on a+ * shelf or visited from AI first (those with orders, then the most shelves,+ * then the most visits), then the rest by id; `total` counts them all.+ */+export async function getShoppingProducts(+ brandId: string,+ filters: ShoppingFilters,+): Promise<ShoppingProducts | null> {+ const supabase = await createClient();+ const { count: total, error: countErr } = await supabase+ .from('catalog_products')+ .select('id', { count: 'exact', head: true })+ .eq('brand_id', brandId)+ .is('removed_at', null);+ if (countErr) throw new Error(countErr.message);+ if (!total) return null;++ const { from } = resolveDateRange(filters);+ const [cards, stats] = await Promise.all([+ fetchAllCards<{+ catalog_product_id: string;+ position: number;+ platform: string;+ prompt_results: { prompt_id: string } | null;+ }>(() =>+ cardsInWindow(+ supabase,+ brandId,+ filters,+ 'catalog_product_id, position, platform, prompt_results:prompt_result_id ( prompt_id )',+ )+ .eq('matched_brand_role', 'own')+ .not('catalog_product_id', 'is', null),+ ),+ // All time reads the last 90 days of visits and orders.+ readProductAiStats(supabase, brandId, from ?? daysAgoIso(90)),+ ]);++ const shelfCards: ProductCardRow[] = cards.map((card) => ({+ productId: card.catalog_product_id,+ shelf: `${card.prompt_results?.prompt_id ?? '?'}:${card.platform}`,+ rank: card.position + 1,+ }));+ const aiStats: ProductAiStats[] = stats.map((row) => ({+ productId: row.product_id,+ aiVisits: Number(row.ai_visits),+ orders: Number(row.orders),+ revenue: row.revenue === null ? null : Number(row.revenue),+ currency: row.currency,+ }));+ const ids =+ total > PRODUCTS_TABLE_MAX+ ? await tableProductIds(supabase, brandId, shelfCards, aiStats)+ : null;+ const catalog = await readCatalogProducts(supabase, brandId, ids);+ return { rows: productRows(catalog, shelfCards, aiStats), total };+}++/**+ * The PRODUCTS_TABLE_MAX products a catalog bigger than that lists: those on+ * a shelf or visited from AI, the ones with orders first, then the most+ * shelves, then the most visits; then the rest of the catalog by id.+ */+async function tableProductIds(+ supabase: ServerClient,+ brandId: string,+ cards: readonly ProductCardRow[],+ stats: readonly ProductAiStats[],+): Promise<string[]> {+ const shelvesOf = new Map<string, Set<string>>();+ for (const card of cards) {+ if (!shelvesOf.has(card.productId)) shelvesOf.set(card.productId, new Set());+ shelvesOf.get(card.productId)!.add(card.shelf);+ }+ const statsOf = new Map(stats.map((row) => [row.productId, row]));+ const active = [...new Set([...shelvesOf.keys(), ...statsOf.keys()])].sort(+ (a, b) =>+ (statsOf.get(b)?.orders ?? 0) - (statsOf.get(a)?.orders ?? 0) ||+ (shelvesOf.get(b)?.size ?? 0) - (shelvesOf.get(a)?.size ?? 0) ||+ (statsOf.get(b)?.aiVisits ?? 0) - (statsOf.get(a)?.aiVisits ?? 0) ||+ (a < b ? -1 : 1),+ );+ const ids = new Set(active.slice(0, PRODUCTS_TABLE_MAX));+ if (ids.size < PRODUCTS_TABLE_MAX) {+ // The rest, by id: as many as could be needed past those already in.+ const rest = await readCatalogRows<{ id: string }>(+ () =>+ supabase+ .from('catalog_products')+ .select('id')+ .eq('brand_id', brandId)+ .is('removed_at', null)+ .order('id'),+ PRODUCTS_TABLE_MAX,+ );+ for (const { id } of rest) {+ if (ids.size >= PRODUCTS_TABLE_MAX) break;+ ids.add(id);+ }+ }+ return [...ids];+}++/**+ * The brand's live catalog products as Product Visibility reads them, with+ * their variants' stock, price and GTIN, first photo and category: the+ * whole catalog (up to PRODUCTS_TABLE_MAX) for `ids` null, else the products+ * `ids` names, their rows read IDS_PER_READ ids at a time.+ */+async function readCatalogProducts(+ supabase: ServerClient,+ brandId: string,+ ids: readonly string[] | null,+): Promise<CatalogProductRow[]> {+ // Each table read for the whole catalog, or for the ids, a slice at a time.+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder generics+ const each = <T>(column: string, build: () => any, max: number): Promise<T[]> =>+ ids === null+ ? readCatalogRows<T>(build, max)+ : readForIds(ids, (some) =>+ readCatalogRows<T>(() => build().in(column, some), CARD_MAX_ROWS),+ );+ const [products, variants, images, categories] = await Promise.all([+ each<{+ id: string;+ title: string;+ url: string | null;+ product_type: string | null;+ product_brand: string | null;+ description: string | null;+ }>(+ 'id',+ () =>+ supabase+ .from('catalog_products')+ .select('id, title, url, product_type, product_brand, description')+ .eq('brand_id', brandId)+ .is('removed_at', null)+ .order('id'),+ PRODUCTS_TABLE_MAX,+ ),+ each<{+ product_id: string;+ gtin: string | null;+ price: number | null;+ sale_price: number | null;+ currency: string | null;+ availability: string | null;+ }>(+ 'product_id',+ () =>+ supabase+ .from('catalog_variants')+ .select('product_id, gtin, price, sale_price, currency, availability')+ .eq('brand_id', brandId)+ .is('removed_at', null)+ .order('id'),+ CARD_MAX_ROWS,+ ),+ each<{ product_id: string; url: string; position: number }>(+ 'product_id',+ () =>+ supabase+ .from('catalog_images')+ .select('product_id, url, position')+ .eq('brand_id', brandId)+ .order('id'),+ CARD_MAX_ROWS,+ ),+ each<{ product_id: string; category: { name: string } | null }>(+ 'product_id',+ () =>+ supabase+ .from('catalog_product_categories')+ .select('product_id, category:category_id ( name )')+ .eq('brand_id', brandId)+ .order('product_id')+ .order('category_id'),+ CARD_MAX_ROWS,+ ),+ ]);++ const variantsOf = new Map<string, typeof variants>();+ for (const v of variants) {+ if (!variantsOf.has(v.product_id)) variantsOf.set(v.product_id, []);+ variantsOf.get(v.product_id)!.push(v);+ }+ const imageOf = new Map<string, { url: string; position: number }>();+ for (const image of images) {+ const kept = imageOf.get(image.product_id);+ if (!kept || image.position < kept.position) imageOf.set(image.product_id, image);+ }+ const categoryOf = new Map<string, string>();+ for (const row of categories) {+ if (row.category?.name && !categoryOf.has(row.product_id)) {+ categoryOf.set(row.product_id, row.category.name);+ }+ }+ return products.map((p) => {+ const own = variantsOf.get(p.id) ?? [];+ const stocked = own.filter((v) =>+ IN_STOCK.has(+ String(v.availability ?? '')+ .toLowerCase()+ .replace(/[\s-]+/g, '_'),+ ),+ );+ const priced = (stocked.length ? stocked : own)+ .map((v) => ({ price: v.sale_price ?? v.price, currency: v.currency }))+ .filter((v): v is { price: number; currency: string | null } => v.price !== null)+ .sort((a, b) => a.price - b.price);+ return {+ id: p.id,+ title: p.title,+ url: p.url,+ productType: p.product_type,+ brand: p.product_brand,+ description: p.description,+ image: imageOf.get(p.id)?.url ?? null,+ category: categoryOf.get(p.id) ?? null,+ price: priced[0] ? Number(priced[0].price) : null,+ currency: priced[0]?.currency ?? null,+ inStock: stocked.length > 0,+ hasGtin: own.some((v) => !!v.gtin),+ };+ });+}diff --git a/web/src/lib/shopping/price.ts b/web/src/lib/shopping/price.tsnew file mode 100644index 000000000..5c51073d8--- /dev/null+++ b/web/src/lib/shopping/price.ts@@ -0,0 +1,18 @@+/**+ * Prices as Product Visibility shows them, in en-US like the rest of the UI.+ */++/** A price as the card shows it: "$139", "$24.50", "€89", or the amount and its code. */+export function priceText(value: number, currency: string | null): string {+ const digits = Number.isInteger(value) ? 0 : 2;+ try {+ return new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: currency || 'USD',+ minimumFractionDigits: digits,+ maximumFractionDigits: digits,+ }).format(value);+ } catch {+ return `${value.toFixed(digits)} ${currency ?? ''}`.trim();+ }+}diff --git a/web/src/lib/shopping/products.test.ts b/web/src/lib/shopping/products.test.tsnew file mode 100644index 000000000..dc39cb845--- /dev/null+++ b/web/src/lib/shopping/products.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from 'vitest';+import {+ inView,+ productRows,+ readiness,+ viewCounts,+ viewRows,+ type CatalogProductRow,+} from './products';++/** Product Visibility's Products table (ECOM-007). */++const product = (over: Partial<CatalogProductRow>): CatalogProductRow => ({+ id: 'p1',+ title: 'Trail Runner X',+ url: 'https://northwind.example/products/trail-runner-x',+ productType: 'Trail running shoes',+ brand: 'Northwind',+ description:+ "Men's trail running shoe, 268 g, 6 mm drop, with a waterproof membrane and a grippy outsole for wet rock and mud. Built for long days on technical trails.",+ image: 'https://cdn.example/x.jpg',+ category: 'Shoes > Trail running',+ price: 129,+ currency: 'USD',+ inStock: true,+ hasGtin: true,+ ...over,+});++describe('readiness', () => {+ it('scores a complete product 100', () => {+ expect(readiness(product({}))).toEqual({ score: 100, missing: [] });+ });++ it('says what a product misses, and what each costs', () => {+ expect(+ readiness(+ product({+ hasGtin: false,+ image: null,+ inStock: false,+ price: null,+ description: 'Our story began in 1998 in the mountains.',+ category: null,+ brand: null,+ }),+ ),+ ).toEqual({+ score: 0,+ missing: [+ 'gtin',+ 'image',+ 'inStock',+ 'price',+ 'description',+ 'typeFirst',+ 'category',+ 'brand',+ ],+ });+ });++ it('reads the type from the category when the product has none, singular or plural', () => {+ const backpack = product({+ productType: null,+ category: 'Bags > Hiking backpacks',+ description:+ 'A 30 litre hiking backpack for women, 1.1 kg, with a ventilated back panel, hip belt pockets and a rain cover, sized for day hikes and short overnights in the hills.',+ });+ expect(readiness(backpack).missing).toEqual([]);+ expect(+ readiness({+ ...backpack,+ description: `${'Born in the hills, made by people who love long walks and good company. '.repeat(4)} This backpack carries it all.`,+ }).missing,+ ).toEqual(['typeFirst']);+ });+});++describe('productRows and the views', () => {+ const products = [+ product({ id: 'never', title: 'Ridge 30L' }),+ product({ id: 'shown', title: 'Basecamp 2P' }),+ product({ id: 'clicked', title: 'Carbon Trek Poles' }),+ product({ id: 'seller', title: 'StormShell Jacket' }),+ ];+ const rows = productRows(+ products,+ [+ { productId: 'shown', shelf: 'q1:chatgpt-shopping', rank: 3 },+ { productId: 'shown', shelf: 'q1:chatgpt-shopping', rank: 4 },+ { productId: 'clicked', shelf: 'q2:copilot-web', rank: 1 },+ { productId: 'clicked', shelf: 'q3:copilot-web', rank: 3 },+ { productId: 'seller', shelf: 'q4:chatgpt-shopping', rank: 1 },+ ],+ [+ { productId: 'clicked', aiVisits: 210, orders: 0, revenue: null, currency: null },+ { productId: 'seller', aiVisits: 402, orders: 38, revenue: 7200, currency: 'USD' },+ ],+ );++ it('counts each product its shelves, win rate (#1 or #2), average place, visits and orders', () => {+ const byId = Object.fromEntries(rows.map((row) => [row.product.id, row]));+ expect(byId.never).toMatchObject({ shelves: 0, winRate: null, avgRank: null, aiVisits: 0 });+ expect(byId.shown).toMatchObject({ shelves: 1, winRate: 0, avgRank: 3.5 });+ expect(byId.clicked).toMatchObject({+ shelves: 2,+ winRate: 0.5,+ avgRank: 2,+ aiVisits: 210,+ orders: 0,+ });+ expect(byId.seller).toMatchObject({+ orders: 38,+ revenue: 7200,+ currency: 'USD',+ readiness: 100,+ });+ });++ it('puts each product in its view, top sellers by revenue', () => {+ const ids = (view: Parameters<typeof viewRows>[1]) =>+ viewRows(rows, view).map((row) => row.product.id);+ expect(ids('never')).toEqual(['never']);+ expect(ids('notClicked')).toEqual(['shown']);+ expect(ids('notBought')).toEqual(['clicked']);+ expect(ids('topSellers')).toEqual(['seller']);+ expect(ids('all')).toEqual(['clicked', 'seller', 'shown', 'never']);+ expect(rows.every((row) => inView(row, 'all'))).toBe(true);+ });++ it('counts each view, All and Never shown out of the whole catalog when the rows are part of it', () => {+ const counts = { all: 4, never: 1, notClicked: 1, notBought: 1, topSellers: 1 };+ expect(viewCounts(rows, 4)).toEqual(counts);+ // The rows of a 5,000-product catalog: the 3 shown are among them, the other 4,997 never were.+ expect(viewCounts(rows, 5000)).toEqual({ ...counts, all: 5000, never: 4997 });+ });+});diff --git a/web/src/lib/shopping/products.ts b/web/src/lib/shopping/products.tsnew file mode 100644index 000000000..a60410188--- /dev/null+++ b/web/src/lib/shopping/products.ts@@ -0,0 +1,202 @@+/**+ * Product Visibility's Products table (ECOM-007): every product of the+ * brand's catalog with where it stands on the AI shelf (its cards, 00360),+ * the AI visits its page got and the orders they led to (00361), and how+ * ready it is for AI shopping from what the catalog holds.+ */++/** A catalog product as the table reads it. */+export interface CatalogProductRow {+ id: string;+ title: string;+ url: string | null;+ productType: string | null;+ brand: string | null;+ description: string | null;+ image: string | null;+ category: string | null;+ price: number | null;+ currency: string | null;+ inStock: boolean;+ hasGtin: boolean;+}++/** One of the brand's cards on a shelf, matched to a catalog product. */+export interface ProductCardRow {+ productId: string;+ /** The question and channel: one shelf. */+ shelf: string;+ /** Its place on the shelf, from 1. */+ rank: number;+}++/** AI visits and orders per product (00361). */+export interface ProductAiStats {+ productId: string;+ aiVisits: number;+ orders: number;+ revenue: number | null;+ currency: string | null;+}++/** The checks behind a product's readiness, and what each is worth. */+export const READINESS_CHECKS = {+ gtin: 20,+ image: 15,+ inStock: 15,+ price: 10,+ description: 15,+ typeFirst: 10,+ category: 10,+ brand: 5,+} as const;+export type ReadinessCheck = keyof typeof READINESS_CHECKS;++/** Words a description needs to say enough. */+const DESCRIPTION_WORDS = 25;+/** ChatGPT reads about this many words of a description (ECOM-024). */+export const FIRST_WORDS = 40;++const wordsOf = (text: string | null) =>+ String(text ?? '')+ .toLowerCase()+ .split(/[^\p{L}\p{N}]+/u)+ .filter(Boolean);++/**+ * A product's readiness, 0–100, and the checks it misses: a GTIN, a photo,+ * in stock, a price, a description that says enough and names what the+ * product is in its first 40 words, a category and a brand.+ */+export function readiness(product: CatalogProductRow): {+ score: number;+ missing: ReadinessCheck[];+} {+ const description = wordsOf(product.description);+ const type = wordsOf(product.productType ?? product.category?.split('>').at(-1) ?? null);+ const firstWords = new Set(description.slice(0, FIRST_WORDS));+ const passed: Record<ReadinessCheck, boolean> = {+ gtin: product.hasGtin,+ image: !!product.image,+ inStock: product.inStock,+ price: product.price !== null,+ description: description.length >= DESCRIPTION_WORDS,+ // The type's last word, as a description says it: "Trail running shoe" → "shoe".+ typeFirst:+ type.length > 0 &&+ [type.at(-1)!, type.at(-1)!.replace(/s$/, '')].some((word) =>+ [...firstWords].some((w) => w === word || w.replace(/s$/, '') === word),+ ),+ category: !!product.category,+ brand: !!product.brand,+ };+ const missing = (Object.keys(READINESS_CHECKS) as ReadinessCheck[]).filter(+ (check) => !passed[check],+ );+ const score = (Object.keys(READINESS_CHECKS) as ReadinessCheck[])+ .filter((check) => passed[check])+ .reduce((sum, check) => sum + READINESS_CHECKS[check], 0);+ return { score, missing };+}++/** A product's row in the table. */+export interface ProductRow {+ product: CatalogProductRow;+ /** The shelves (question × channel) it was on. */+ shelves: number;+ /** Its share of appearances at #1 or #2, null when never shown. */+ winRate: number | null;+ avgRank: number | null;+ aiVisits: number;+ orders: number;+ revenue: number | null;+ currency: string | null;+ readiness: number;+ missing: ReadinessCheck[];+}++/** The table's ready-made views (ECOM-007), the AI Traffic "Cited, not clicked" pattern. */+export const PRODUCT_VIEWS = ['all', 'never', 'notClicked', 'notBought', 'topSellers'] as const;+export type ProductView = (typeof PRODUCT_VIEWS)[number];++export function productRows(+ products: readonly CatalogProductRow[],+ cards: readonly ProductCardRow[],+ stats: readonly ProductAiStats[],+): ProductRow[] {+ const byProduct = new Map<string, { shelves: Set<string>; ranks: number[] }>();+ for (const card of cards) {+ let entry = byProduct.get(card.productId);+ if (!entry) {+ entry = { shelves: new Set(), ranks: [] };+ byProduct.set(card.productId, entry);+ }+ entry.shelves.add(card.shelf);+ entry.ranks.push(card.rank);+ }+ const statsOf = new Map(stats.map((s) => [s.productId, s]));+ return products.map((product) => {+ const shown = byProduct.get(product.id);+ const ai = statsOf.get(product.id);+ const ranks = shown?.ranks ?? [];+ const ready = readiness(product);+ return {+ product,+ shelves: shown?.shelves.size ?? 0,+ winRate: ranks.length ? ranks.filter((rank) => rank <= 2).length / ranks.length : null,+ avgRank: ranks.length ? ranks.reduce((a, b) => a + b, 0) / ranks.length : null,+ aiVisits: ai?.aiVisits ?? 0,+ orders: ai?.orders ?? 0,+ revenue: ai?.revenue ?? null,+ currency: ai?.currency ?? null,+ readiness: ready.score,+ missing: ready.missing,+ };+ });+}++export function inView(row: ProductRow, view: ProductView): boolean {+ switch (view) {+ case 'never':+ return row.shelves === 0;+ case 'notClicked':+ return row.shelves > 0 && row.aiVisits === 0;+ case 'notBought':+ return row.aiVisits > 0 && row.orders === 0;+ case 'topSellers':+ return row.orders > 0;+ default:+ return true;+ }+}++/**+ * How many products each view holds. The rows may be part of the catalog+ * (the table's first PRODUCTS_TABLE_MAX, those on a shelf or visited first):+ * All is then the catalog's `total`, and Never shown the products beyond+ * those shown.+ */+export function viewCounts(+ rows: readonly ProductRow[],+ total: number,+): Record<ProductView, number> {+ const counts = Object.fromEntries(+ PRODUCT_VIEWS.map((id) => [id, rows.filter((row) => inView(row, id)).length]),+ ) as Record<ProductView, number>;+ const shown = rows.length - counts.never;+ counts.all = Math.max(total, rows.length);+ counts.never = counts.all - shown;+ return counts;+}++/** A view's rows, in its order: top sellers by revenue, the rest by shelves, then visits. */+export function viewRows(rows: readonly ProductRow[], view: ProductView): ProductRow[] {+ const listed = rows.filter((row) => inView(row, view));+ return listed.sort((a, b) =>+ view === 'topSellers'+ ? (b.revenue ?? 0) - (a.revenue ?? 0) || b.orders - a.orders+ : b.shelves - a.shelves ||+ b.aiVisits - a.aiVisits ||+ a.product.title.localeCompare(b.product.title),+ );+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 41b41ae54..44b8c8695 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1208,6 +1208,75 @@ export type Database = {},]}+ catalog_categories: {+ Row: {+ brand_id: string+ created_at: string+ id: string+ name: string+ }+ Insert: {+ brand_id: string+ created_at?: string+ id?: string+ name: string+ }+ Update: {+ brand_id?: string+ created_at?: string+ id?: string+ name?: string+ }+ Relationships: [+ {+ foreignKeyName: "catalog_categories_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ ]+ }+ catalog_product_categories: {+ Row: {+ brand_id: string+ category_id: string+ product_id: string+ }+ Insert: {+ brand_id: string+ category_id: string+ product_id: string+ }+ Update: {+ brand_id?: string+ category_id?: string+ product_id?: string+ }+ Relationships: [+ {+ foreignKeyName: "catalog_product_categories_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "catalog_product_categories_category_id_fkey"+ columns: ["category_id"]+ isOneToOne: false+ referencedRelation: "catalog_categories"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "catalog_product_categories_product_id_fkey"+ columns: ["product_id"]+ isOneToOne: false+ referencedRelation: "catalog_products"+ referencedColumns: ["id"]+ },+ ]+ }catalog_variants: {Row: {attributes: Json@@ -5726,6 +5795,21 @@ export type Database = {regions: string[]}[]}+ catalog_product_ai_stats: {+ Args: {+ p_brand_id: string+ p_from: string+ p_product_id?: string+ p_to?: string+ }+ Returns: {+ ai_visits: number+ currency: string | null+ orders: number+ product_id: string+ revenue: number | null+ }[]+ }shopping_merchant_split: {Args: {p_brand_id: string