Skip to content

feat(shopping): normalize prompt_result_shopping_cards + parser worker - #143

Merged
gkhngyk merged 1 commit into
mainfrom
feat/shopping-cards-normalization
Jun 1, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
feat/shopping-cards-normalization

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Closes #103. Unblocks #104, #105, #106, #107.

What

The raw prompt_results.shopping_cards jsonb column captures cards from three providers in three different shapes — Perplexity (snake_case), Google AI Mode (camelCase), Microsoft Copilot (camelCase). Useful for archival, useless for analytics. This PR adds the normalized analytical surface the upcoming Shopping dashboard (#104, #105, #106) and the MCP shopping tools (#107) plug into.

Pieces

Migration 00011_prompt_result_shopping_cards.sql

One row per card per prompt_result. Hoisted analytical columns (product_title, product_brand, price_amount / price_currency, image_url, merchant_url / merchant_domain, rating, review_count), denormalized platform / region / brand_id so org-scoped queries don't have to join the parent row, and the original card preserved in raw jsonb for future re-parsing.

Brand-match result on each row:

  • matched_brand_role ∈ ('own', 'competitor', 'other')
  • matched_brand_id is polymorphic — brands.id when role=own, competitors.id when role=competitor, null otherwise. No FK so a brand or competitor delete doesn't cascade into historical analytics.

Indexes target the dashboard's three top queries: (brand_id, matched_brand_role), (product_brand), (merchant_domain). RLS mirrors prompt_results. Migration is already applied to the cloud DB.

server/src/lib/shopping-cards.js

Three normalizers — parsePerplexityCard, parseAiModeCard, parseCopilotCard — each mapped to its provider's known field names. Lenient on naming because both providers we've inspected have silently renamed keys before (#49 retro on AI Mode camelCase shape).

Robust price parser handles:

  • Object form: { amount, currency } or { value, currencyCode }
  • Numeric form
  • Strings: $29.99, USD 29.99, 29.99 USD, €19,90 (EU decimals), ₺499,90

matchCardBrand mirrors the citations matcher in response-parser.js — substring match on brand name across product_brand + product_title + merchant_domain, exact match on tracked domains. Same heuristic the citations surface uses; keeps the two surfaces aligned without an extra dependency.

cloro-result-handler.js

After the prompt_results insert, calls persistShoppingCards which normalizes + matches + upserts in one batched call. onConflict: 'prompt_result_id,position' with ignoreDuplicates: true so a worker retry on the same result is a no-op.

Failures inside persistShoppingCards are logged and swallowed — they can't kill the parent result write. The raw cards live on prompt_results.shopping_cards regardless; the backfill script can re-derive any rows that were missed.

server/src/scripts/backfill-shopping-cards.js

Walks the last N days of prompt_results with non-empty shopping_cards in batches, caches brand context per brand_id, calls the same persistShoppingCards path the worker uses. Idempotent via the unique constraint.

Env knobs: SHOPPING_BACKFILL_DAYS (default 90), SHOPPING_BACKFILL_BATCH (default 200). Run with:

cd server
node src/scripts/backfill-shopping-cards.js

Test plan

  1. Live capture — trigger a tracking run on a prompt that returns shopping cards on Perplexity / AI Mode / Copilot. After the run, query:

    select platform, count(*), count(*) filter (where matched_brand_role = 'own') as own,
           count(*) filter (where matched_brand_role = 'competitor') as comp
    from prompt_result_shopping_cards
    where created_at > now() - interval '5 minutes'
    group by 1;
  2. Idempotency — run the backfill twice in a row. Second run should report 0 new rows inserted.

  3. Org isolation — sign in as a member of org A, query the table as that user (anon key), confirm only org A's brand cards are visible.

Out of scope

Closes #103.

The raw `prompt_results.shopping_cards` jsonb column captures cards from
Perplexity (snake_case), Google AI Mode (camelCase), and Microsoft
Copilot (camelCase). Useful for archival, useless for analytics —
querying 'which competitor's products are in my shopping cards?' today
means scanning every prompt_result and JSON-parsing in app code.

This drops in the analytical surface that the upcoming Shopping
dashboard (#104, #105, #106) and the MCP shopping tools (#107) plug
into.

What this adds:

- Migration 00011_prompt_result_shopping_cards.sql — one row per card
  per prompt_result, hoisted analytical columns (product_title,
  product_brand, price_amount/currency, image_url, merchant_url/domain,
  rating, review_count), denormalized platform/region/brand_id for fast
  org-scoped queries, original card preserved in raw jsonb, brand match
  result (matched_brand_id polymorphic + role enum). RLS mirrors
  prompt_results.

- server/src/lib/shopping-cards.js — one normalizer per provider
  (parsePerplexityCard, parseAiModeCard, parseCopilotCard). Lenient on
  field names because both providers we've inspected have silently
  renamed keys before (#49 retro on AI Mode). Robust price parser
  handles object form, '.99', 'USD 29.99', '€19,90', '₺499' etc.
  matchCardBrand mirrors the citations matcher: substring match on
  brand name OR exact merchant_domain match for 'own'; same checks
  against tracked competitors for 'competitor'; else 'other'.

- cloro-result-handler.js — after the prompt_results insert, calls
  persistShoppingCards which normalizes + matches + upserts in one
  batched call. ON CONFLICT (prompt_result_id, position) ignore so a
  retry on the same result is a no-op. Failures here are logged and
  swallowed so they can't kill the parent result write — the raw cards
  are already on prompt_results and the backfill can re-derive them.

- server/src/scripts/backfill-shopping-cards.js — walks the last 90d
  of prompt_results with non-empty shopping_cards in batches of 200,
  caches brand context per brand_id, calls the same
  persistShoppingCards path. Idempotent via the unique constraint.
  Env knobs: SHOPPING_BACKFILL_DAYS, SHOPPING_BACKFILL_BATCH.

Migration applied to cloud DB ahead of the merge.

Out of scope (separate issues already filed): the Shopping dashboard UI
(#104, #105, #106), the MCP shopping tools (#107), ChatGPT capture
(#95), and the inlineProducts variant of AI Mode + ChatGPT (separate
shape, not in this normalization pass).
@gkhngyk
gkhngyk merged commit 048e5d0 into main Jun 1, 2026
3 checks passed

This branch was successfully deployed

1 active deployment
Preview — b254d654 Deployed Jun 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(shopping): normalize prompt_result_shopping_cards + parser worker

1 participant