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): show what a done Products action did, 7 days on, on the product and its category (Product Visibility, part 11) (#1646)
Cihan80900e483b84
diff --git a/docs/guides/action-center.mdx b/docs/guides/action-center.mdxindex 4fa64cb8e..558933816 100644--- a/docs/guides/action-center.mdx+++ b/docs/guides/action-center.mdx@@ -67,7 +67,7 @@ The cards at the top count and filter the list. Click one to narrow the table toBelow them, filter by category, **Priority**, **Status** and **Assignee**, or search. **Sort** by Priority (the default), Newest, Due date or Recently updated. Filters live in the URL, so a filtered view can be shared.-For an online shop, a **From Products** chip beside the categories lists only the actions sent from **Products** (a product to get on the AI shelf, or a category to win), whatever the category. Click it again to clear it.+For an online shop, a **From Products** chip beside the categories lists only the actions sent from **Products** (a product to get on the AI shelf, or a category to win), whatever the category. Click it again to clear it. Once one is **Completed**, Products shows what it did 7 days on, on the product's page and under the category's name: the shelves of its shopping questions in the week after it was done beside the week before.An action's status is **New**, **In Progress**, **On Hold**, **Completed** or **Dismissed**. The row menu sets In Progress, Completed or Dismiss without opening the action. Dismissing, from the row menu or the action's status, asks why: it doesn't matter to us, it's already done, the data behind it is wrong, or not now (or none). History shows the reason. **Delete** (admins and managers only) removes it for everyone, and it won't come back on its own the next day.diff --git a/web/messages/en.json b/web/messages/en.jsonindex 732389d2a..1e8186d51 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -8133,6 +8133,20 @@"open": "Open","failed": "Couldn't send to Action Center. Try again."},+ "recheck": {+ "title": "After action #{number}",+ "pending": "Done {done}. Its result shows on {ready}, 7 days on.",+ "result": "In the 7 days after it was done, on {after} of {afterShelves, plural, one {# shelf} other {# shelves}}. In the 7 days before, on {before} of {beforeShelves}.",+ "noRuns": "Done {done}. No shopping answers were read in the 7 days after it, so there's nothing to compare.",+ "trend": {+ "better": "On more of its shelves",+ "worse": "On fewer of its shelves",+ "same": "No change"+ },+ "open": "Open the action",+ "short": "#{number}: {before}/{beforeShelves} → {after}/{afterShelves} shelves",+ "shortPending": "#{number} done · result {ready}"+ },"detail": {"back": "Products","onShelves": "On {count} of {total} shelves",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-result.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-result.tsxnew file mode 100644index 000000000..9fe1f22e2--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-result.tsx@@ -0,0 +1,108 @@+'use client';++import { useTranslations } from 'next-intl';+import { ArrowRight, Minus, TrendingDown, TrendingUp } from 'lucide-react';+import { Link } from '@/i18n/navigation';+import { buttonVariants } from '@/components/ui/button-variants';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { formatDate } from '@/lib/format';+import { resultTrend, type ActionResult } from '@/lib/shopping/recheck';+import { cn } from '@/lib/utils';++/**+ * What a done Products action did, 7 days on (ECOM-018): on the product's+ * page a card, in the Categories table a line under the category's name.+ */++const actionHref = (result: ActionResult) =>+ `/dashboard/action-center/actions?action=${result.actionId}`;++const TREND = {+ better: {+ icon: TrendingUp,+ tone: 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-400',+ },+ worse: {+ icon: TrendingDown,+ tone: 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-400',+ },+ same: { icon: Minus, tone: 'bg-muted text-muted-foreground' },+} as const;++export function ActionResultCard({ result }: { result: ActionResult }) {+ const t = useTranslations('shopping.recheck');+ const trend = resultTrend(result);+ const done = formatDate(result.completedAt);+ const Trend = trend ? TREND[trend].icon : null;+ return (+ <Card>+ <CardHeader className="pb-2">+ <div className="flex flex-wrap items-center gap-2">+ <CardTitle className="text-base">{t('title', { number: result.actionNo })}</CardTitle>+ {trend && Trend && (+ <span+ className={cn(+ 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs font-medium',+ TREND[trend].tone,+ )}+ >+ <Trend className="h-3.5 w-3.5" aria-hidden />+ {t(`trend.${trend}`)}+ </span>+ )}+ </div>+ </CardHeader>+ <CardContent className="flex flex-wrap items-center justify-between gap-3">+ <p className="text-sm text-muted-foreground">+ {result.after === null+ ? t('pending', { done, ready: formatDate(result.readyAt) })+ : result.after.shelves === 0+ ? t('noRuns', { done })+ : t('result', {+ after: result.after.on,+ afterShelves: result.after.shelves,+ before: result.before.on,+ beforeShelves: result.before.shelves,+ })}+ </p>+ <Link+ href={actionHref(result)}+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'shrink-0 gap-1.5')}+ >+ {t('open')}+ <ArrowRight className="h-3.5 w-3.5" aria-hidden />+ </Link>+ </CardContent>+ </Card>+ );+}++/** None when the category has no done action. */+export function ActionResultLine({ result }: { result: ActionResult | undefined }) {+ const t = useTranslations('shopping.recheck');+ if (!result) return null;+ const trend = resultTrend(result);+ return (+ <Link+ href={actionHref(result)}+ className={cn(+ 'block truncate text-xs hover:underline',+ trend === 'better'+ ? 'text-emerald-700 dark:text-emerald-400'+ : trend === 'worse'+ ? 'text-amber-700 dark:text-amber-400'+ : 'text-muted-foreground',+ )}+ >+ {result.after === null+ ? t('shortPending', { number: result.actionNo, ready: formatDate(result.readyAt) })+ : t('short', {+ number: result.actionNo,+ before: result.before.on,+ beforeShelves: result.before.shelves,+ after: result.after.on,+ afterShelves: result.after.shelves,+ })}+ </Link>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsxindex 91cdf896d..d6b16e6b9 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx@@ -7,7 +7,14 @@ import type { CategoryRow } from '@/lib/shopping/categories';const sendShoppingActions = vi.hoisted(() => vi.fn());vi.mock('@/lib/actions/shopping', () => ({ sendShoppingActions }));-vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: React.ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+ useRouter: () => ({ push: vi.fn() }),+}));vi.mock('sonner', () => ({toast: Object.assign(vi.fn(), {loading: vi.fn(),@@ -95,6 +102,36 @@ describe('CategoriesTable', () => {]);});+ it("shows a category's last done action under its name, 7 days on", () => {+ const done = {+ actionId: 'a9',+ actionNo: 9,+ completedAt: '2026-10-12T09:00:00Z',+ readyAt: '2026-10-19T09:00:00Z',+ before: { shelves: 5, on: 1 },+ after: { shelves: 6, on: 3 },+ };+ render(+ <CategoriesTable+ categories={[row({}), row({ id: 'packs', leaf: 'Hiking backpacks' })]}+ loading={false}+ failed={false}+ results={{+ 'category:shoes': done,+ 'category:packs': { ...done, actionId: 'a10', actionNo: 10, after: null },+ }}+ />,+ );+ const links = [...container.querySelectorAll('tbody a')].map((a) => [+ a.getAttribute('href'),+ a.textContent,+ ]);+ expect(links).toEqual([+ ['/dashboard/action-center/actions?action=a9', '#9: 1/5 → 3/6 shelves'],+ ['/dashboard/action-center/actions?action=a10', '#10 done · result Oct 19, 2026'],+ ]);+ });+it("plans a category's actions in a dialog, measured on its questions", async () => {sendShoppingActions.mockResolvedValue({ actionId: 'a1', actionNo: 302, created: true });render(diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsxindex cac931322..1474aa933 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.tsx@@ -26,20 +26,24 @@ import { priceText } from '@/lib/shopping/price';import { cn } from '@/lib/utils';import { categoryPlan } from '@/lib/shopping/action-plan';import type { CategoryRow } from '@/lib/shopping/categories';+import { resultKey, type ActionResult } from '@/lib/shopping/recheck';import { ActionPlan } from './_action-plan';+import { ActionResultLine } from './_action-result';/*** The Categories table (ECOM-008): one row per catalog category, with its* shopping questions, the brand's share of their shelves, its products on* them, the rival with the most slots there and its products' AI revenue.* A category the brand barely shows in is marked "needs attention". Its- * Plan actions sends the category's work to the Action Center (ECOM-013).+ * Plan actions sends the category's work to the Action Center (ECOM-013);+ * its last done one shows under its name, 7 days on (ECOM-018).*/export function CategoriesTable({categories,loading,failed,brandId,+ results = {},}: {/** Null for a catalog without categories. */categories: CategoryRow[] | null;@@ -47,6 +51,8 @@ export function CategoriesTable({failed: boolean;/** The brand, to send a category's actions with; none, no Plan actions. */brandId?: string;+ /** Each category's last done action, 7 days on, by "category:<id>". */+ results?: Record<string, ActionResult>;}) {const t = useTranslations('shopping.categories');const [planning, setPlanning] = useState<CategoryRow | null>(null);@@ -96,6 +102,7 @@ export function CategoriesTable({</span>)}</p>+ <ActionResultLine result={results[resultKey({ type: 'category', id: row.id })]} /></TableCell><TableCell className="text-right">{row.shelfShare === null ? (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsxindex 73c769c22..1a4d03f73 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_product-detail.tsx@@ -22,6 +22,7 @@ import type { ComparisonState } from '@/lib/shopping/product-detail';import { productPlan } from '@/lib/shopping/action-plan';import { cn } from '@/lib/utils';import { ActionPlan } from './_action-plan';+import { ActionResultCard } from './_action-result';const platformName = (platform: string) => PLATFORM_LABELS[platform] ?? platform;@@ -34,8 +35,8 @@ const STATE_ICON: Record<ComparisonState, React.ReactNode> = {/*** A product's page (ECOM-011), drawn: its header with its AI visits and- * orders, "Why not your product?" beside the winner, where it shows, and- * its readiness.+ * orders, "Why not your product?" beside the winner, its last done action+ * 7 days on (ECOM-018), where it shows, and its readiness.*/export function ProductDetailView({detail,@@ -173,6 +174,8 @@ export function ProductDetailView({)}</Card>+ {detail.result && <ActionResultCard result={detail.result} />}+{brandId && (<Card><CardHeader className="pb-2">diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/page.tsxindex e6ee3f879..030b506ae 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,+ getShoppingActionResults,getShoppingCategories,getShoppingProducts,getShoppingShelf,@@ -90,6 +91,7 @@ import { PLATFORM_LABELS } from '@/config/platform-labels';import { formatRegionDisplay } from '@/lib/region';import type { AmazonShareDropAlert } from '@/lib/shopping-amazon-share-alert';import type { CategoryRow } from '@/lib/shopping/categories';+import { RECHECK_TARGETS, type ActionResult } from '@/lib/shopping/recheck';import { readinessChecklist } from '@/lib/shopping/readiness';import { formatNumber } from '@/lib/format';import { HeaderWithAiUsage } from '@/components/ai-usage/ai-usage-meter';@@ -156,6 +158,8 @@ export default function ShoppingPage() {const [categories, setCategories] = useState<{key: string;rows: CategoryRow[] | null | 'failed';+ /** Each category's last done action, 7 days on (ECOM-018). */+ results?: Record<string, ActionResult>;} | null>(null);const [tableLoading, setTableLoading] = useState(false);const [selectedProduct, setSelectedProduct] = useState<ShoppingProduct | null>(null);@@ -306,7 +310,19 @@ export default function ShoppingPage() {let cancelled = false;getShoppingCategories(activeBrandId, filters).then((rows) => {- if (!cancelled) setCategories({ key: categoriesKey, rows });+ if (cancelled) return;+ setCategories({ key: categoriesKey, rows });+ if (!rows?.length) return;+ // Then their last done actions, 7 days on: a table without them is still the table.+ // Kept by key, not `cancelled`: setting the rows re-runs this effect.+ getShoppingActionResults(+ activeBrandId,+ rows.slice(0, RECHECK_TARGETS).map((row) => ({ type: 'category' as const, id: row.id })),+ )+ .then((results) =>+ setCategories((read) => (read?.key === categoriesKey ? { ...read, results } : read)),+ )+ .catch((err) => console.error('Failed to re-check the categories’ actions:', err));}).catch((err) => {console.error('Failed to read the categories:', err);@@ -519,6 +535,7 @@ export default function ShoppingPage() {categories={categoriesRead === 'failed' ? null : (categoriesRead ?? null)}loading={categoriesRead === undefined}failed={categoriesRead === 'failed'}+ results={categories?.key === categoriesKey ? categories.results : undefined}/>) : (<UpgradeCard t={t} requiredPlan={requiredPlanFor('shopping_analytics')} />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsxindex 5704a8953..8594cfe83 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx@@ -136,6 +136,7 @@ const detail: ShoppingProductDetail = {{ key: 'gtin', you: null, winner: null, state: 'missing' },],ai: { visits: 4, orders: 0, revenue: null, currency: null },+ result: null,};describe('ShoppingProductPage', () => {@@ -182,6 +183,35 @@ describe('ShoppingProductPage', () => {);});+ const result = {+ actionId: 'a7',+ actionNo: 7,+ completedAt: '2026-10-12T09:00:00Z',+ readyAt: '2026-10-19T09:00:00Z',+ before: { shelves: 3, on: 0 },+ after: { shelves: 4, on: 2 },+ };++ it('shows what its last done action did, 7 days on', async () => {+ getShoppingProductDetail.mockResolvedValue({ ...detail, result });+ const text = await render();+ expect(text).toContain('After action #7');+ expect(text).toContain('On more of its shelves');+ expect(text).toContain(+ 'In the 7 days after it was done, on 2 of 4 shelves. In the 7 days before, on 0 of 3.',+ );+ expect(+ container.querySelector('a[href="/dashboard/action-center/actions?action=a7"]')?.textContent,+ ).toBe('Open the action');+ });++ it('says when a done action’s result shows', async () => {+ getShoppingProductDetail.mockResolvedValue({ ...detail, result: { ...result, after: null } });+ const text = await render();+ expect(text).toContain('Done Oct 12, 2026. Its result shows on Oct 19, 2026, 7 days on.');+ expect(text).not.toContain('On more of its shelves');+ });+it('says when the product is gone, or locked', async () => {getShoppingProductDetail.mockResolvedValue(null);expect(await render()).toContain("This product isn't in your catalog anymore.");diff --git a/web/src/lib/actions/shopping-product-detail.test.ts b/web/src/lib/actions/shopping-product-detail.test.tsindex 8ea53a32a..4c3dec5d4 100644--- a/web/src/lib/actions/shopping-product-detail.test.ts+++ b/web/src/lib/actions/shopping-product-detail.test.ts@@ -6,6 +6,8 @@ const BRAND = '33333333-3333-3333-3333-333333333333';const PRODUCT = '11111111-0000-0000-0000-000000000001';let tables: Record<string, Record<string, unknown>[]>;+// The id lists each read filtered by, as [table, column, how many].+let filtered: [string, string, number][];let rpcArgs: Record<string, unknown>[];// The id lists the catalog reads filtered by, as [table, column, the ids].let byIds: [string, string, unknown[]][];@@ -17,10 +19,16 @@ function query(table: string) {select: () => q,eq: () => q,is: () => q,- in: (column: string, values: unknown[]) => (byIds.push([table, column, values]), q),+ in: (column: string, values: unknown[]) => (+ filtered.push([table, column, values.length]),+ byIds.push([table, column, values]),+ q+ ),not: () => q,gte: () => q,lte: () => q,+ lt: () => q,+ limit: () => q,or: () => q,order: () => q,maybeSingle: () => ((single = true), q),@@ -52,6 +60,7 @@ const { getShoppingProductDetail } = await import('./shopping');beforeEach(() => {tables = {};+ filtered = [];rpcArgs = [];byIds = [];});@@ -138,5 +147,87 @@ describe('getShoppingProductDetail', () => {expect(rpcArgs).toEqual([{ p_brand_id: BRAND, p_from: expect.any(String), p_product_id: PRODUCT },]);+ expect(detail?.result).toBeNull();+ });++ it('sets the week after its last done action beside the week before (ECOM-018)', async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-10-30T00:00:00Z'));+ try {+ tables.catalog_products = [{ id: PRODUCT, title: 'Ridge 30L Backpack', description: null }];+ tables.actions = [+ {+ id: 'a7',+ action_no: 7,+ completed_at: '2026-10-20T00:00:00Z',+ payload: { target: { type: 'product', id: PRODUCT }, promptIds: ['q1'] },+ },+ // An older one for the same product: the latest done counts.+ {+ id: 'a3',+ action_no: 3,+ completed_at: '2026-10-01T00:00:00Z',+ payload: { target: { type: 'product', id: PRODUCT }, promptIds: ['q1'] },+ },+ ];+ const prompt = {+ prompt_id: 'q1',+ search_queries: [],+ prompt: { id: 'q1', text: 'lightweight 30L hiking backpack for women' },+ };+ tables.prompt_result_shopping_cards = [+ card({+ prompt_result_id: 'r-1',+ created_at: '2026-10-15T08:00:00Z',+ prompt_results: prompt,+ }),+ card({+ prompt_result_id: 'r0',+ created_at: '2026-10-22T08:00:00Z',+ product_title: 'Ridge 30L Backpack',+ matched_brand_role: 'own',+ catalog_product_id: PRODUCT,+ prompt_results: prompt,+ }),+ ];+ const detail = await getShoppingProductDetail(BRAND, PRODUCT, { datePreset: '30d' });+ // One read for the action's one question.+ expect(filtered.filter(([, column]) => column === 'prompt_results.prompt_id')).toEqual([+ ['prompt_result_shopping_cards', 'prompt_results.prompt_id', 1],+ ]);+ expect(detail?.result).toEqual({+ actionId: 'a7',+ actionNo: 7,+ completedAt: '2026-10-20T00:00:00Z',+ readyAt: '2026-10-27T00:00:00.000Z',+ before: { shelves: 1, on: 0 },+ after: { shelves: 1, on: 1 },+ });+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('the re-check read (ECOM-018)', () => {+ it('reads the cards of many questions a hundred ids at a time', async () => {+ tables.catalog_products = [{ id: PRODUCT, title: 'Ridge 30L Backpack', description: null }];+ tables.actions = [+ {+ id: 'a7',+ action_no: 7,+ completed_at: new Date(Date.now() - 86_400_000).toISOString(),+ payload: {+ target: { type: 'product', id: PRODUCT },+ promptIds: Array.from({ length: 250 }, (_, i) => `q${i}`),+ },+ },+ ];+ await getShoppingProductDetail(BRAND, PRODUCT, { datePreset: '30d' });+ expect(+ filtered+ .filter(([, column]) => column === 'prompt_results.prompt_id')+ .map(([, , count]) => count),+ ).toEqual([100, 100, 50]);});});diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex 5911bd5be..f097d4836 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -28,6 +28,16 @@ import {type ProductShelfLine,} from '@/lib/shopping/product-detail';import { priceText } from '@/lib/shopping/price';+import { FROM_PRODUCTS_KINDS } from '@/lib/action-center/registry';+import {+ RECHECK_DAYS,+ RECHECK_TARGETS,+ actionResult,+ resultKey,+ type ActionResult,+ type RecheckAction,+ type RecheckCard,+} from '@/lib/shopping/recheck';import {productRows,readiness,@@ -1672,6 +1682,8 @@ export interface ShoppingProductDetail {comparison: ComparisonRow[];/** AI visits to its page and the orders they led to, over the window (00361). */ai: { visits: number; orders: number; revenue: number | null; currency: string | null };+ /** Its last done action from Products, 7 days on (ECOM-018); null without one. */+ result: ActionResult | null;}/** A product of the brand's catalog, on the AI shelves of the questions it belongs on. Null when it isn't the brand's. */@@ -1687,6 +1699,13 @@ export async function getShoppingProductDetail(}const asked = focusOn && z.guid().safeParse(focusOn.promptId).success ? focusOn : null;const supabase = await createClient();+ // Read beside the rest; a re-check that can't be read leaves the page as it is.+ const resultsRead = readActionResults(supabase, brandId, [+ { type: 'product', id: productId },+ ]).catch((err) => {+ console.error('Failed to re-check the product’s last action:', err);+ return {} as Record<string, ActionResult>;+ });const { from } = resolveDateRange(filters);const [[product], cards, stats, domain] = await Promise.all([readCatalogProducts(supabase, brandId, [productId]),@@ -1760,6 +1779,7 @@ export async function getShoppingProductDetail(const shown = detailCards.filter((card) => card.productId === productId).sort((a, b) => (a.at < b.at ? 1 : -1))[0];+ const results = await resultsRead;const shelves = productShelves(product, detailCards, { include: asked?.promptId ?? null });const focus = focusShelf(shelves, asked);const ai = (stats.data ?? []).find((row) => row.product_id === productId);@@ -1781,9 +1801,136 @@ export async function getShoppingProductDetail(revenue: ai?.revenue === null || ai?.revenue === undefined ? null : Number(ai.revenue),currency: ai?.currency ?? null,},+ result: results[resultKey({ type: 'product', id: productId })] ?? null,};}+// ── Re-check after a done action (Product Visibility, ECOM-018) ───────────────++/** Done actions this recent are re-checked: older ones say little about the shelf now. */+const RECHECK_SINCE_DAYS = 60;+/** The actions read at most, the latest done first. */+const RECHECK_ACTIONS = 500;+/** The questions read at most across the actions re-checked. */+const RECHECK_PROMPTS = 400;+/** Question ids one card read filters by: each request's address stays short. */+const RECHECK_PROMPTS_PER_READ = 100;++const recheckTargets = z+ .array(z.object({ type: z.enum(['product', 'category']), id: z.guid() }))+ .max(RECHECK_TARGETS);++/**+ * Each target's last done action from Products, 7 days on: the shelves of+ * its questions in the week before it was done beside the week after+ * (recheck.ts), by "product:<id>" / "category:<id>". Through the member's+ * session (RLS): only the brand's own actions and cards.+ */+async function readActionResults(+ supabase: Awaited<ReturnType<typeof createClient>>,+ brandId: string,+ targets: { type: 'product' | 'category'; id: string }[],+ now: number = Date.now(),+): Promise<Record<string, ActionResult>> {+ const wanted = new Set(targets.map(resultKey));+ if (!wanted.size) return {};+ const { data, error } = await supabase+ .from('actions')+ .select('id, action_no, completed_at, payload')+ .eq('brand_id', brandId)+ .in('kind', [...FROM_PRODUCTS_KINDS])+ .eq('status', 'completed')+ .gte('completed_at', new Date(now - RECHECK_SINCE_DAYS * 86_400_000).toISOString())+ .order('completed_at', { ascending: false })+ .limit(RECHECK_ACTIONS);+ if (error) throw new Error(error.message);++ const actions = new Map<string, RecheckAction>();+ for (const row of data ?? []) {+ const payload = (row.payload ?? {}) as {+ target?: { type?: unknown; id?: unknown };+ promptIds?: unknown;+ };+ const type = payload.target?.type;+ const id = payload.target?.id;+ if ((type !== 'product' && type !== 'category') || typeof id !== 'string') continue;+ const target = { type, id } as RecheckAction['target'];+ const key = resultKey(target);+ // The latest done one per target: the rows come newest first.+ if (!wanted.has(key) || actions.has(key) || !row.completed_at) continue;+ actions.set(key, {+ id: row.id,+ actionNo: Number(row.action_no),+ target,+ completedAt: row.completed_at,+ promptIds: Array.isArray(payload.promptIds)+ ? payload.promptIds.filter((p): p is string => typeof p === 'string')+ : [],+ });+ }+ if (!actions.size) return {};++ const promptIds = [...new Set([...actions.values()].flatMap((a) => a.promptIds))].slice(+ 0,+ RECHECK_PROMPTS,+ );+ const dones = [...actions.values()].map((a) => Date.parse(a.completedAt));+ const week = RECHECK_DAYS * 86_400_000;+ const from = new Date(Math.min(...dones) - week).toISOString();+ const to = new Date(Math.min(now, Math.max(...dones) + week)).toISOString();+ const reads = [];+ for (let i = 0; i < promptIds.length; i += RECHECK_PROMPTS_PER_READ) {+ const some = promptIds.slice(i, i + RECHECK_PROMPTS_PER_READ);+ reads.push(+ fetchAllCards<{+ created_at: string;+ platform: string;+ matched_brand_role: string;+ catalog_product_id: string | null;+ prompt_results: { prompt_id: string } | null;+ }>(() =>+ supabase+ .from('prompt_result_shopping_cards')+ .select(+ 'created_at, platform, matched_brand_role, catalog_product_id, prompt_results!inner ( prompt_id )',+ )+ .eq('brand_id', brandId)+ .gte('created_at', from)+ .lt('created_at', to)+ .in('prompt_results.prompt_id', some),+ ),+ );+ }+ const rows = (await Promise.all(reads)).flat();+ const cards: RecheckCard[] = rows.flatMap((row) =>+ row.prompt_results+ ? [+ {+ promptId: row.prompt_results.prompt_id,+ platform: row.platform,+ at: row.created_at,+ own: row.matched_brand_role === 'own',+ productId: row.catalog_product_id,+ },+ ]+ : [],+ );+ return Object.fromEntries(+ [...actions].map(([key, action]) => [key, actionResult(action, cards, now)]),+ );+}++/** What the brand's done Products actions did, 7 days on, for the Categories table (ECOM-018). */+export async function getShoppingActionResults(+ brandId: string,+ targets: { type: 'product' | 'category'; id: string }[],+): Promise<Record<string, ActionResult>> {+ const parsed = recheckTargets.safeParse(targets);+ if (!z.guid().safeParse(brandId).success || !parsed.success) throw new Error('invalid');+ const supabase = await createClient();+ return readActionResults(supabase, brandId, parsed.data);+}+// ── Actions from Product Visibility (ECOM-013) ────────────────────────────────/** A work type sent with a product or category, for a person ("me") or the agent. */diff --git a/web/src/lib/shopping/action-plan.test.ts b/web/src/lib/shopping/action-plan.test.tsindex 123f7188d..ec62fd462 100644--- a/web/src/lib/shopping/action-plan.test.ts+++ b/web/src/lib/shopping/action-plan.test.ts@@ -42,6 +42,7 @@ const detail = (over: Partial<ShoppingProductDetail> = {}): ShoppingProductDetai},comparison: [],ai: { visits: 0, orders: 0, revenue: null, currency: null },+ result: null,...over,});diff --git a/web/src/lib/shopping/recheck.test.ts b/web/src/lib/shopping/recheck.test.tsnew file mode 100644index 000000000..5b5ff0373--- /dev/null+++ b/web/src/lib/shopping/recheck.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from 'vitest';+import {+ actionResult,+ resultKey,+ resultTrend,+ shelfPresence,+ type RecheckAction,+ type RecheckCard,+} from './recheck';++/** A done Products action, 7 days on (ECOM-018). */++const DAY = 86_400_000;+const DONE = '2026-10-20T00:00:00.000Z';++const action: RecheckAction = {+ id: 'a1',+ actionNo: 7,+ target: { type: 'product', id: 'ridge' },+ completedAt: DONE,+ promptIds: ['q1', 'q2'],+};++const card = (over: Partial<RecheckCard>): RecheckCard => ({+ promptId: 'q1',+ platform: 'chatgpt-shopping',+ at: '2026-10-15T08:00:00Z',+ own: false,+ productId: null,+ ...over,+});++const cards = [+ // The week before: two shelves, the product on neither (another of the brand's on one).+ card({}),+ card({ platform: 'gemini-web', own: true, productId: 'other' }),+ // The week after: the product on q1's ChatGPT shelf, q2's read without it.+ card({ at: '2026-10-22T08:00:00Z' }),+ card({ at: '2026-10-22T08:00:00Z', own: true, productId: 'ridge' }),+ card({ promptId: 'q2', at: '2026-10-23T08:00:00Z' }),+ // Not its questions, or outside both weeks.+ card({ promptId: 'q9', at: '2026-10-22T08:00:00Z', own: true, productId: 'ridge' }),+ card({ at: '2026-10-28T08:00:00Z', own: true, productId: 'ridge' }),+ card({ at: '2026-10-01T08:00:00Z', own: true, productId: 'ridge' }),+];++describe('shelfPresence', () => {+ it("counts the action's shelves in the window and those the product was on", () => {+ const done = Date.parse(DONE);+ expect(shelfPresence(cards, action, done - 7 * DAY, done)).toEqual({ shelves: 2, on: 0 });+ expect(shelfPresence(cards, action, done, done + 7 * DAY)).toEqual({ shelves: 2, on: 1 });+ });++ it("counts any of the brand's products for a category", () => {+ const done = Date.parse(DONE);+ const category = { ...action, target: { type: 'category' as const, id: 'c1' } };+ expect(shelfPresence(cards, category, done - 7 * DAY, done)).toEqual({ shelves: 2, on: 1 });+ });+});++describe('actionResult', () => {+ it('waits for the 7 days after, then sets them beside the 7 before', () => {+ const pending = actionResult(action, cards, Date.parse('2026-10-25T00:00:00Z'));+ expect(pending).toMatchObject({+ actionId: 'a1',+ actionNo: 7,+ readyAt: '2026-10-27T00:00:00.000Z',+ before: { shelves: 2, on: 0 },+ after: null,+ });+ expect(resultTrend(pending)).toBeNull();+ const ready = actionResult(action, cards, Date.parse('2026-10-27T00:00:00Z'));+ expect(ready.after).toEqual({ shelves: 2, on: 1 });+ expect(resultTrend(ready)).toBe('better');+ });++ it('reads no trend when no answer was read in the week after', () => {+ const quiet = actionResult(action, [card({})], Date.parse('2026-11-01T00:00:00Z'));+ expect(quiet.after).toEqual({ shelves: 0, on: 0 });+ expect(resultTrend(quiet)).toBeNull();+ });+});++describe('resultTrend', () => {+ const result = (before: [number, number], after: [number, number]) =>+ resultTrend({+ actionId: 'a1',+ actionNo: 1,+ completedAt: DONE,+ readyAt: DONE,+ before: { on: before[0], shelves: before[1] },+ after: { on: after[0], shelves: after[1] },+ });++ it('compares the share of shelves, not the counts', () => {+ expect(result([2, 4], [2, 2])).toBe('better');+ expect(result([2, 2], [2, 4])).toBe('worse');+ expect(result([1, 2], [2, 4])).toBe('same');+ expect(result([0, 0], [0, 3])).toBe('same');+ });+});++it('keys a result by its target', () => {+ expect(resultKey({ type: 'category', id: 'c1' })).toBe('category:c1');+});diff --git a/web/src/lib/shopping/recheck.ts b/web/src/lib/shopping/recheck.tsnew file mode 100644index 000000000..f6f0d3f9e--- /dev/null+++ b/web/src/lib/shopping/recheck.ts@@ -0,0 +1,102 @@+/**+ * ECOM-018: what a done Products action did, 7 days on. An action sent from+ * Product Visibility (a product to get on the AI shelf, a category to win)+ * names the shopping questions it's measured on; once someone completes it,+ * the shelves of those questions in the 7 days after are set beside the 7+ * days before: how many the brand's product (or, for a category, any of its+ * products) was on. Read from the cards already kept, when the page opens:+ * no job, nothing stored.+ */++export const RECHECK_DAYS = 7;+/** Targets re-checked in one read at most. */+export const RECHECK_TARGETS = 500;+const DAY_MS = 86_400_000;++/** A card as the re-check reads it: its shelf (question × channel), when, and whose. */+export interface RecheckCard {+ promptId: string;+ platform: string;+ at: string;+ own: boolean;+ productId: string | null;+}++/** A done action from Products, as the re-check reads it. */+export interface RecheckAction {+ id: string;+ actionNo: number;+ target: { type: 'product' | 'category'; id: string };+ completedAt: string;+ /** The shopping questions it's measured on. */+ promptIds: string[];+}++/** Shelves read in a window, and how many the brand was on. */+export interface ShelfPresence {+ shelves: number;+ on: number;+}++export interface ActionResult {+ actionId: string;+ actionNo: number;+ completedAt: string;+ /** When the 7 days after end: the result shows from then. */+ readyAt: string;+ before: ShelfPresence;+ /** Null until the 7 days after have passed. */+ after: ShelfPresence | null;+}++/** The action's shelves read in [from, to), and how many had the brand's product on them. */+export function shelfPresence(+ cards: readonly RecheckCard[],+ action: Pick<RecheckAction, 'target' | 'promptIds'>,+ from: number,+ to: number,+): ShelfPresence {+ const prompts = new Set(action.promptIds);+ const shelves = new Map<string, boolean>();+ for (const card of cards) {+ const at = Date.parse(card.at);+ if (!(at >= from && at < to) || !prompts.has(card.promptId)) continue;+ const key = `${card.promptId}:${card.platform}`;+ const ours = action.target.type === 'product' ? card.productId === action.target.id : card.own;+ shelves.set(key, (shelves.get(key) ?? false) || ours);+ }+ return { shelves: shelves.size, on: [...shelves.values()].filter(Boolean).length };+}++/** The action's result: the week before it was done beside the week after, once that has passed. */+export function actionResult(+ action: RecheckAction,+ cards: readonly RecheckCard[],+ now: number = Date.now(),+): ActionResult {+ const done = Date.parse(action.completedAt);+ const ready = done + RECHECK_DAYS * DAY_MS;+ return {+ actionId: action.id,+ actionNo: action.actionNo,+ completedAt: action.completedAt,+ readyAt: new Date(ready).toISOString(),+ before: shelfPresence(cards, action, done - RECHECK_DAYS * DAY_MS, done),+ after: now >= ready ? shelfPresence(cards, action, done, ready) : null,+ };+}++/**+ * Which way it went: the share of shelves it was on, after beside before.+ * Null while the week after runs, or when no answer was read in it.+ */+export function resultTrend(result: ActionResult): 'better' | 'worse' | 'same' | null {+ const { before, after } = result;+ if (!after?.shelves) return null;+ const share = (p: ShelfPresence) => (p.shelves ? p.on / p.shelves : 0);+ const change = share(after) - share(before);+ return change > 0 ? 'better' : change < 0 ? 'worse' : 'same';+}++/** A target's key in the results: "product:<id>" or "category:<id>". */+export const resultKey = (target: RecheckAction['target']) => `${target.type}:${target.id}`;