Skip to content

feat(shopping): alert on sharp drops in Amazon product share - #1313

Merged
gkhngyk merged 32 commits into
ansvisor:mainfrom
knockknock10:feature/shopping-amazon-share-alert-1284
Oct 22, 2026
Merged

gkhngyk merged 32 commits into
ansvisor:mainfrom
knockknock10:feature/shopping-amazon-share-alert-1284

Conversation

@knockknock10

@knockknock10 knockknock10 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Persist merchant destination classification (own, marketplace, reseller), normalized marketplace, and listing ID for new shopping-card rows. Cards without a merchant URL remain unclassified.
  • Add an idempotent backfill script for existing normalized cards, using the same classifier as the live result handler.
  • Add a Postgres RPC that returns five complete rolling seven-day windows ending at p_as_of for classified cards on the brand's own products.
  • Trigger only when all five windows have at least 30 classified cards, the latest window's Amazon share is below half the median of the preceding four windows, and the absolute drop is at least 10 percentage points.
  • Keep the rule as a pure function with fixture tests, and show its alert row on the Shopping page.

Related issue

Closes #1284

Depends on the merchant-classification prerequisite also described in #1277; this PR implements only the storage/backfill needed for the alert, not the separate full destination breakdown and price comparison.

Type of change

  • feat — New feature
  • test — Adding or updating tests
  • docs/schema — Database migration and generated schema update

Validation

  • Server npm run lint
  • Server npm run format:check
  • Server npm test
  • Web Prettier format check
  • Web ESLint
  • Web TypeScript typecheck
  • Web Vitest suite, including the exact 18% to 8% threshold boundary
  • Next.js production build
  • Consolidated schema check on the latest main sync
  • GitHub Actions CI on the latest main sync

After migration 00225_shopping_merchant_classification.sql is applied, run node src/scripts/backfill-shopping-card-merchants.js from server/ to classify historical cards so existing rolling windows can contribute to the alert. Use --all to reclassify all rows with merchant URLs after brand-domain changes.

Copilot AI balanced review requested due to automatic review settings October 21, 2026 12:27

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 21, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. Verdict: changes requested. Reusing classifyMerchant works well, the thresholds match the issue, and CI is green. These are the changes we need before merging:

  1. Migration number. supabase/migrations/00204_shopping_merchant_classification.sql: open PRs already use 00204–00222. Please rename it to 00223_shopping_merchant_classification.sql, or the next free number when you rebase. Then update the "Run after migration 00204" note in server/src/scripts/backfill-shopping-card-merchants.js:4 and rerun bash supabase/build-schema.sh.

  2. "This week" is a partial week. 00204_…sql:46: date_trunc('week', …) makes the current bucket the calendar week so far. On a Monday the share rests on a single day of runs. A brand with 30+ own cards a day clears the 30-card floor on day one, so one run without Amazon cards fires the alert: four weeks at 31% followed by 0/30 returns an alert today. Please use rolling 7-day windows ending at p_as_of, so every bucket is a full week:

    with weeks as (
      select i,
             p_as_of - (i + 1) * interval '7 days' as from_ts,
             p_as_of - i * interval '7 days'       as to_ts
      from generate_series(0, 4) as i
    )
    -- join on c.created_at >= w.from_ts and c.created_at < w.to_ts
    -- and return (w.from_ts at time zone 'UTC')::date as week_start

    The returned dates stay 7 days apart, so isConsecutiveWeeks still passes. Please also update the comments in shopping-amazon-share-alert.ts:13-16 and above the effect in page.tsx.

  3. RPC security. 00204_…sql:42 and :72: our newer reads use security definer with an explicit organization check and no anon access, as citation_gap_domains_daily does in 00203_citation_gap_rollups.sql. As written, Supabase's default privileges also give anon and public EXECUTE on the function. Please follow that pattern (plpgsql with #variable_conflict use_column, as in 00203):

    security definer
    set search_path to 'public'
    as $$
    #variable_conflict use_column
    begin
      if auth.role() is distinct from 'service_role' and not exists (
        select 1 from public.brands b
        join public.profiles pf on pf.organization_id = b.organization_id
        where b.id = p_brand_id and pf.id = auth.uid()
      ) then
        return;
      end if;
      return query ...;
    end;
    $$;
    
    revoke all on function public.shopping_amazon_share_weekly(uuid, timestamptz) from public, anon;
    grant execute on function public.shopping_amazon_share_weekly(uuid, timestamptz) to authenticated, service_role;
    
    notify pgrst, 'reload schema';
  4. The 10-point boundary. web/src/lib/shopping-amazon-share-alert.ts:64-68: in JS, 0.18 - 0.08 is 0.09999999999999999, so a drop from 18% to 8% doesn't fire, although it is exactly 10 points and below half. Please compare with a small tolerance, e.g. absoluteDrop < AMAZON_SHARE_MIN_ABSOLUTE_DROP - 1e-9, and add that case as a fixture.

  5. Backfill paging. server/src/scripts/backfill-shopping-card-merchants.js:82-100: running it twice gives the same result. However, offset paging updates every row again on each run, and it can skip rows if older cards are deleted mid-run. Please page by id and pick up only unclassified rows, so a rerun resumes where the last one stopped:

    let query = supabaseAdmin
      .from('prompt_result_shopping_cards')
      .select('id, brand_id, merchant_url')
      .is('merchant_kind', null)
      .not('merchant_url', 'is', null)
      .order('id', { ascending: true })
      .limit(BATCH_SIZE);
    if (lastId) query = query.gt('id', lastId);

    An optional --all flag that drops the merchant_kind filter would let us reclassify after a brand's domains change. Also, at line 40 please cache the promise in domainCache rather than the result. Then 20 rows of one brand in a slice make one request instead of 20.

  6. Small ones.

    • web/src/lib/actions/shopping.ts:184-193: the new function sits between getShoppingFilterOptions's doc comment and its declaration. Please move it above that comment.
    • web/src/types/supabase.ts:1983: the Update type lacks merchant_kind, marketplace and listing_id. Please regenerate the types, or add them in alphabetical order as the generator does.
    • page.tsx:258-260: amber is right for a warning. Please match the limit note in prompts/_suggestions-card.tsx (amber background with dark: variants) so the row stays consistent in dark mode.

@gkhngyk

gkhngyk commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Update on the migration number: #1126 took 00223 and #1315 takes 00224 meanwhile, so please use 00225 (or the next free one when you rebase).

gkhngyk
gkhngyk previously approved these changes Oct 21, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. Verdict: approved once the description is updated. Every point from the last review is fixed, the branch merges cleanly with main, and CI is green on the new head.

What I checked:

  • Migration: it is now 00225_shopping_merchant_classification.sql, which is still free. schema.sql matches what build-schema.sh produces from the merged tree.
  • The RPC:
    • It uses rolling seven-day windows ending at p_as_of, so a partial week can't trigger the alert any more.
    • It is security definer with the organization check, and anon/public no longer have access.
    • It responds in 8–42 ms on our largest brands.
  • The rule: it uses the tolerance at the 10-point boundary, and the 18% to 8% fixture fires as expected.
  • Backfill: it pages by id over unclassified rows, has the --all flag and caches the domain promise.
  • The rest: the doc comment is in its place, the Update type has the new columns, and the alert row matches our amber warning style in both themes. The new "last seven days" copy fits the windows.

One small thing before we merge:

  1. PR description. It still says migration 00204, "the current UTC week", and has the two validation boxes unticked. Please update it to 00225 and rolling seven-day windows, since it becomes the squash commit message. CI has confirmed the typecheck and the schema check, so both boxes can be ticked.

@knockknock10
knockknock10 requested a review from gkhngyk October 22, 2026 08:24

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. The description now says 00225 and rolling seven-day windows, and the validation boxes are ticked. Since the last review, the feature code, the migration and the RPC are unchanged. The later commits are merges of main, the schema.sql separator fix, the supabase.ts field order and a comment rewrap.

00225 is applied on the hosted database. shopping_amazon_share_weekly returns its five weeks for a member in 17 ms and no rows for an outsider. Tested on top of the current main: web and server tests, tsc, lint and Prettier pass, and schema.sql matches a rebuild.

We'll run the merchant backfill after the next server deploy. Thanks!

@gkhngyk
gkhngyk merged commit 087e9b4 into ansvisor:main Oct 22, 2026
5 checks passed
@knockknock10
knockknock10 deleted the feature/shopping-amazon-share-alert-1284 branch October 22, 2026 09:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(shopping): alert when Amazon's share of where AI sends shoppers drops sharply

3 participants