Repository navigation
feat(shopping): normalize prompt_result_shopping_cards + parser worker - #143
Merged
Merged
Conversation
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).
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #103. Unblocks #104, #105, #106, #107.
What
The raw
prompt_results.shopping_cardsjsonb 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), denormalizedplatform/region/brand_idso org-scoped queries don't have to join the parent row, and the original card preserved inrawjsonb for future re-parsing.Brand-match result on each row:
matched_brand_role∈('own', 'competitor', 'other')matched_brand_idis polymorphic —brands.idwhen role=own,competitors.idwhen 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 mirrorsprompt_results. Migration is already applied to the cloud DB.server/src/lib/shopping-cards.jsThree 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:
{ amount, currency }or{ value, currencyCode }$29.99,USD 29.99,29.99 USD,€19,90(EU decimals),₺499,90matchCardBrandmirrors the citations matcher inresponse-parser.js— substring match on brand name acrossproduct_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.jsAfter the
prompt_resultsinsert, callspersistShoppingCardswhich normalizes + matches + upserts in one batched call.onConflict: 'prompt_result_id,position'withignoreDuplicates: trueso a worker retry on the same result is a no-op.Failures inside
persistShoppingCardsare logged and swallowed — they can't kill the parent result write. The raw cards live onprompt_results.shopping_cardsregardless; the backfill script can re-derive any rows that were missed.server/src/scripts/backfill-shopping-cards.jsWalks the last N days of
prompt_resultswith non-emptyshopping_cardsin batches, caches brand context perbrand_id, calls the samepersistShoppingCardspath 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.jsTest plan
Live capture — trigger a tracking run on a prompt that returns shopping cards on Perplexity / AI Mode / Copilot. After the run, query:
Idempotency — run the backfill twice in a row. Second run should report 0 new rows inserted.
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
inlineProducts(ChatGPT / AI Mode) — different shape, separate normalization pass