Skip to content

feat(content): pick a draft's shopping path from the brand's catalog (shopping path, part 2) - #1588

Merged
gkhngyk merged 16 commits into
ansvisor:mainfrom
cihan-gyk:feature/shopping-path-engine
Oct 27, 2026
Merged

gkhngyk merged 16 commits into
ansvisor:mainfrom
cihan-gyk:feature/shopping-path-engine

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

E-commerce Shopping path, part 2 of 7: the engine. On an online shop, a buying guide, a best-of list or a comparison should send its readers, and the AI answers that quote it, to the right category page and to products that are in stock and that Merchant Center accepts. The API picks them from the brand's catalog for the draft's topic and keeps them on the draft. Part 3 shows them in the editor's Brief tab; part 4 has the Content Agent write with them.

Stacked on #1587 (part 1, category pages), which is stacked on #1583 and #1582. This PR's own change is its commits after #1587's: 9fb02de (the engine) and 9ba0e1f (the pre-push review's fixes).

Migration 00351_content_draft_shopping_path: content_drafts.shopping_path jsonb, 64 KB at most. Members change it like the brief, so it isn't a server column. supabase/schema.sql is rebuilt.

lib/shopping-path.js builds the path:

  • Topic. The title's words count 3, the brief's keywords 2, its goal and headings 1. Stop words, years and "top 10" are dropped; Turkish and German letters are folded as category pages do (lib/letters.js).
  • Categories. Only ones with a page on the site (part 1) and stock. The best comes first; a second is added only when it scores half the first's, two at most.
  • Products. The picked categories' first, then the brand's: 2,000 scored, the best 40 read in full.
    • A product is offered when it has a link, a variant in stock, and Merchant Center doesn't refuse that variant.
    • It carries the cheapest such variant's price and its other issues (e.g. a missing GTIN).
    • A refusal counts only for free listings or an empty context. An ad-only refusal (SHOPPING_ADS) stays an issue, since the page isn't an ad.
  • How many, by page type: best-of 8, buying guide 5, comparison and alternatives 4, guide 4, blog post 3. The best left out are kept with why: sold out, refused, no link, or gone (removed from the catalog).
  • The person's choices survive a rebuild. Locked and added products are read by id from the brand's own catalog and always kept. A product id from another brand reads as gone. Removed ones never come back.
  • Stock is one list, in lib/catalog/stock.js: in_stock, instock, available and limited_availability, whatever the case, spaces or hyphens. A test reads web/src/lib/content/feed-match.ts and 00350 to keep the three the same.
  • Every read goes past PostgREST's 1,000-row cap: chunked by id (chunked-in.js) and paged (readAllRpcRows).
  • The saved path is read through Zod (readShoppingPath, exported for part 4). A bad one is taken as none and logged, never a 502.
  • The write is capped to 64 KB: first fewer issues per product, then products from the end. It goes only over the path that was read (builtAt, and savedAt once the person saved a change), so a change made meanwhile isn't overwritten.

API: POST /api/content-drafts/:draftId/shopping-path { brandId }

  • Answers { path }, or { path: null, reason }: not_a_shop, page_type, no_catalog or no_match.
  • 409 changed when the path changed while it was built.
  • Its own bucket (shoppingPathLimiter, 30 per 15 minutes), so a 429 says so.

Written by a side session working on the user's behalf. It was handed over for the final checks, the review and this PR.

Related issue

Part of the e-commerce Shopping path plan (Drive › E-commerce › ECOM-shopping-journey-plan.md §6), part 2 of 7. Builds on #1270 (#1582, #1583) and #1587.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. cd server && npx vitest run src/lib/shopping-path.test.js src/lib/catalog/stock.test.js src/routes/content-drafts.test.js src/middleware/rate-limiter.test.js
  2. With 00351 applied, take a draft of an e-commerce brand that has a catalog and category pages (part 1). Its page type should be a buying guide, a best-of list or a comparison.
    • POST /api/content-drafts/<draft>/shopping-path { brandId } answers a path, and content_drafts.shopping_path holds it.
    • Run it again after locking a product in the saved path: the product stays.

No UI in this part; the Brief tab is part 3.

The conditional write was tried against the dev DB (00351 applied there) with a temporary path on one demo draft, set back to null afterwards:

  • the wrong builtAt updates 0 rows;
  • the right builtAt with no savedAt updates 1;
  • a stale empty savedAt updates 0;
  • the right savedAt updates 1.

The shopping_path->>builtAt and ->>savedAt filters work there as in the tests.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run on this head (with #1587's fixes merged in):

  • server/: npm run format, npm run lint, npm test (3,087 tests);
  • web/: yarn format, yarn lint (0 errors), yarn typecheck, yarn test (4,207 tests) and yarn build;
  • bash supabase/build-schema.sh.

The pre-push review's six findings are folded into 9ba0e1f, each with tests:

  • kept products read by id;
  • the 1,000-row cap;
  • the bucket;
  • stop words and no_match;
  • the refusal rule;
  • one stock list, the Zod read and the conditional write.

The fixer broke 29 behaviours one at a time to check that the tests catch them.

Known limits, for later:

  • In a category of more than 2,000 products, the 2,000 scored are taken in id order.
  • Descriptions are cut to 400 characters after they're read, not in the query. A cut in SQL needs a generated column.

🤖 Generated with Claude Code

cihan-gyk and others added 15 commits October 27, 2026 12:56
…m issues (00296, ansvisor#1270 part 1)

A Merchant Center account becomes a catalog source, read with the
workspace's own Google sign-in through Composio (like Search Console and
Analytics), so the token never reaches us. Calls go to the Merchant API v1
through Composio's proxy.

- Connector merchant_center: lists the accounts the sign-in opens (plus an
  advanced account's sub-accounts), checks the picked one, reads every
  product page (1,000 a page) into the feed parsers' item shape (price from
  micros, first GTIN, availability and condition enums), keeps an offer
  listed again under another language or feed label once, and returns each
  product's item-level issues. syncOrders is a no-op.
- 00296 catalog_item_issues: code, severity, attribute, reporting context,
  description per item; replaced each sync, removed with the source;
  members read, the server writes.
- Plumbing: sign-in connectors (signIn instead of fields/connect),
  lib/catalog/sign-in.js (proxy request with 429/5xx waits, 'auth' when
  the sign-in is gone or refused), issue counts on last_counts, plain
  "Reconnect it in Settings › Integrations" words.
- API: GET /api/catalog/accounts, POST /sources with input.account,
  signIns in GET /connectors, googleMerchantCenter in /integrations/config.
- Tests with fixtures: paged list, items with and without issues, expired
  and refused sign-in, 429 wait, account picker, not set up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…account in Settings › Integrations (ansvisor#1270 part 2)

- Settings › Integrations gets a "Stores and marketplaces" group: a Google
  Merchant Center card that connects the workspace's Google sign-in like
  Search Console and Analytics, then lets the active brand pick one of the
  accounts it opens (GET /api/catalog/accounts) and add it as a catalog
  source.
- Product catalog names the account "Google Merchant Center · Name (id)"
  and its row reads "N products · M with issues · synced …"; no sign-in
  button for it (the sign-in is the workspace's). The card reads its
  sources again when an account is added above.
- The Shopping page's My Products tab links to Settings › Integrations to
  bring in the catalog.
- catalog-client: signIns in listStoreConnectors, listSignInAccounts,
  connectSignInAccount, not_connected; CatalogCounts.issues;
  IntegrationProvider 'google-merchant-center'. Words in en.json.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and keep repeated offers' issues (ansvisor#1270 review)

- sign-in.js: Composio's own 401/403 and Google's 403 are not_set_up, not
  auth; each refusal is logged by name, status and Google's reason; only
  the connector's hosts (merchantapi.googleapis.com) are reached.
- An offer listed again under another language or feed label is counted
  on its own (last_counts.repeated), its issues gathered from every listing,
  and the kept one chosen by a fixed rule (no DISAPPROVED issue, then feed
  label, then content language).
- Account listing and connecting share a 30 s deadline; the sub-account
  walk stops on a rate limit; a catalog cut at the page limit says so.
- entityIdFor moves to composio.js. Tests for paging, deadlines, limits,
  the proxy helper and the refusal codes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… integrations by kind, and say what the catalog is for (ansvisor#1270 review)

- The picked account belongs to the brand it was picked for: switching
  brands clears it, an add goes to the brand clicked for, one add at once.
  Accounts already added are marked and can't be picked; a failed list read
  offers Try again; members get their own line.
- Integrations' group headings are h3 headings; Webflow moves to a
  "Content management systems" group (IntegrationGroup).
- Shopping › My Products' catalog note says what the catalog does (the
  editor's product-page checks), only while the brand has no source.
- "1 with an issue"; a fixed platform name before /connectors is read;
  stores.errors.not_connected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eated offers, and note advanced accounts (ansvisor#1270 review)

- settings.merchantCenter.errors.not_configured says who fixes it (the
  server's set-up, or the Google account's access), with Try again.
- A source's line shows "N listed again, kept once" (last_counts.repeated).
- With several accounts, a note says an advanced account holds no products:
  pick the store's own sub-account.
- Every StoreError has a message (checked at typecheck); the Shopping note
  is _catalog-note.tsx.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… site (00350, shopping path part 1)

The shopping path links a buying guide or a comparison to the category's own
page, so each catalog category is matched, on every read, to one of the
brand's site pages whose address reads as a category page (the editor's
page-type rule: /collections/, /category/, /c/, /shop/, WooCommerce's
/product-category/; never a product page or a themed collection). Best
match: the last path segment is the category's name, then the title or h1
holds it, then most of its words; ties go to the more cited, then visited
page.

- 00350: catalog_category_pages keeps a person's decision (a page, or none)
  by category name; catalog_category_counts(brand) gives live products and
  how many are in stock (service role only).
- lib/catalog/category-pages.js: categorySlug, matchCategoryPages,
  categoryPages(brandId), setCategoryPage (page must be on the brand's
  domains).
- API: GET /api/catalog/categories (members), PUT and DELETE (admins and
  managers).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rations and let admins change it (shopping path part 1)

- Category pages, under the product catalog in Stores and marketplaces:
  each category of the active brand with its products and how many are
  in stock, its page on the site, and how it was found (its address or
  title names the category, most of its words, set by hand). Shown once
  the catalog has categories.
- Admins and managers change a page (it must be on the brand's site), set
  none, or put a hand-set one back to the automatic match; members see
  the table.
- catalog-client: listCategoryPages, setCategoryPage, resetCategoryPage;
  words in settings.catalog.categories.
- The API calls a person's decision 'manual' whether it's a page or none.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…(00351, shopping path part 2)

On an online shop, a buying guide, a best-of list or a comparison links the
right category page and products in stock that Merchant Center accepts. The
API picks them for the draft's topic and keeps them on the draft:

- Topic: the title's words count 3, the brief's keywords 2, its goal and
  headings 1.
- Categories: with a page on the site (00350) and stock, the best first,
  a second only when it scores half the first's (2 at most).
- Products: the picked categories' first, then the brand's (2,000 scored,
  the best 40 read in full); offered when they have a link, a variant in
  stock and Merchant Center doesn't refuse that variant; the cheapest such
  variant's price, and its non-refusing issues (e.g. missing GTIN). How
  many by page type: best-of 8, buying guide 5, comparison and
  alternatives 4, guide 4, blog post 3. The best left out are kept with
  why (sold out, refused, no link).
- The person's choices survive a rebuild: locked and added products stay
  (counted in the page's number), removed ones never come back.
- 00351 content_drafts.shopping_path jsonb (64 KB at most); members edit
  it like the brief.
- POST /api/content-drafts/:draftId/shopping-path { brandId }: { path },
  or { path: null, reason } ('not_a_shop', 'page_type', 'no_catalog').

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s own rule (shopping path part 1 review)

- A malformed % in a page address no longer breaks the read.
- Pages and categories are prepared once, with a word index; site_pages
  isn't read when nothing can match.
- GET uses the general limiter; PUT/DELETE get their own bucket.
- The category-page rule is the editor's (page-types.ts), checked on both
  sides by one fixture list; /blog/category/ and pages marked first
  (best-of, size guides, -vs-, policies) aren't category pages.
- Parent words count; a one-word category matches by address only.
- Turkish and German letters fold (lib/letters.js, shared with Webflow).
- The table is read again when sources change; editing resets per brand.
- catalog_category_counts counts the web's four in-stock values.
- PUT refuses a category the catalog doesn't have; messages fit the routes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…talog row, with one stock rule (shopping path part 2 review)

- Locked and added products are read by id from the brand's own catalog,
  always kept; a removed or unknown one is left out as 'gone'.
- Every read is chunked and paged past PostgREST's 1,000-row cap.
- The route has its own bucket (shoppingPathLimiter); descriptions are cut
  to 400 characters once read.
- More stop words and years, letters folded as category pages do, and
  'no_match' when nothing fits.
- A refusal counts only for free listings or an empty context.
- One stock list (catalog/stock.js), the same as feed-match.ts and 00350.
- The saved path is read through Zod; a bad one is taken as none and
  logged. Writes are capped to 64 KB and conditional on builtAt/savedAt
  (409 'changed').

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The table was 640 px wide in a 417 px card at 1024 px. The Change buttons
sat out of sight, and the header's screen-reader label, outside the
scroll box, scrolled the whole page sideways.

- How a page was found is now a line under it, so four columns fit.
- While a category is being changed, its form takes the button's cell
  as well.
- The scroll box contains its label (`relative`).
- Addresses wrap only where they must ([overflow-wrap:anywhere]).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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, with follow-ups. The build runs #1587's matching, so it needs #1587's fix before merge too: it goes through categoryPages and leafName on each build.

What I checked:

  • Own change. origin/pr/1587..origin/pr/1588: 9fb02de and 9ba0e1f. The merges 3f414e4 and 70ee502 only bring #1587's 100cbff and c3f63dc in: re-merging their parents gives the same trees.
  • 00351.
    • It adds content_drafts.shopping_path jsonb, nullable, with no default. The check takes an object of at most 65,536 bytes of jsonb text, or null.
    • It's safe to run again: add column if not exists skips the whole clause, check included.
    • Adding it locks content_drafts while the check reads the table once. Every value is null, so the read is short.
    • The guard (guard_content_draft_server_columns, latest in 00289) refuses changes to the columns it names, and this one isn't named. So members change it through RLS, as they change the brief, and part 3 (#1591) saves the person's choices that way. That fits:
      • the server reads a stored path only through readShoppingPath (Zod), and an unreadable one counts as none;
      • the ids a member can put in locked and added are read back against the brand (next bullet);
      • the server writes only with the service role.
    • schema.sql is the build script's output: I rebuilt it in a copy, and it came out identical.
  • The server never takes the client's word for an id.
    • The route takes a draftId and a brandId (both z.guid()), checks the person's access to the brand (assertBrandAccess), and answers 404 unless the draft is that brand's (shopping-path.js:525-528).
    • Categories come from categoryPages(brandId).
    • Candidate products come from the brand's category ids and from catalog_products filtered on brand_id.
    • Locked and added ids from the stored path are read with .eq('brand_id', brandId), so another brand's id reads as gone. Removing that filter makes "says why a locked product is left out" fail, and removing the draft's brand check makes another test fail.
    • Variants and images are read by those product ids, and issues by brand_id and external id, through 00296's (brand_id, external_id) index.
    • The write is filtered on id and brand_id. It goes only over the path that was read (builtAt, savedAt), or, at the first build, only where the column is still null. Otherwise the route answers 409 changed.
  • Rules.
    • One in-stock list, the same as feed-match.ts and 00350's (stock.test.js reads both files).
    • A disapproval counts only for free listings or no context.
    • The cheapest usable variant gives the price and the issues.
    • Kept products are counted in the page type's number, and removed ones never come back.
    • fitted measures jsonb's text the way the check does. It brought a 40-product path with every field at its cap under 64,000 bytes.
  • Speed.
    • topicWords, TOP_N and the stop words are linear on 100 KB titles and briefs.
    • Scoring 2,000 products reads each title (up to 1,000 characters), each type (up to 750) and each description's first 400 characters. That's fine at ordinary sizes, and slow only with every field at its cap (follow-up 2).
    • pickCategories calls leafName, which is #1587's item 1.
  • Tests. With #1587's content-drafts.js and rate-limiter.js (tests kept), 5 tests fail. On the head, shopping-path, stock, the catalog tests, content-drafts, catalog and the limiter pass (219 tests). CI passes.
  • Merge.
    • It merges cleanly on main.
    • After #1587 is squashed, this branch needs the stacked step. Squashed on its old base, it gives 4 conflicting hunks, in rate-limiter.js, its test and schema.sql.
  • Before and after the API deploy.
    • This PR is server only, so nothing changes on Vercel at merge, and nothing calls the route until part 3 (#1591).
    • If the API goes out before 00351, the route answers 502, since it selects the column.
    • Apply 00351 before #1591 merges, since its web reads and writes the column.
    • Each build writes the draft, so updated_at moves:
      • the Library lists the draft first;
      • an open editor's next autosave sees another write. Its page hasn't changed, so the save goes through after one more read.

Follow-ups:

  1. A stored path's product ids can be any string (server/src/lib/shopping-path.js:388).
    • A member's write can put an id that isn't a uuid in locked or added. .in('id', …) on the uuid column then fails, and every build of that draft answers 502. The Brief tab can't clear it, since the id never shows there. The fake db doesn't check types, which is why the tests' ids (p3, x1) read.
    • Fix: use z.guid() for these ids here and in part 3's schema, so such a path reads as unreadable and is built over, as a broken one is. Add a test with locked: ['abc'].
  2. Descriptions and long fields are read whole to score (shopping-path.js:277, :280-282, :285-337).
    • Up to 2,000 products are read with descriptions of up to 20,000 characters each (00278), in two 1,000-row responses, to keep 400 characters of each. On a catalog with long descriptions, that's tens of megabytes a build. The description names this as a known limit, saying a cut in SQL needs a generated column.
    • Fix: a cut doesn't need one. Read the products to score through a service-role-only SQL function, or a view, that returns left(description, 400), and left() of the title and the type too. The function can take the category ids and do the 2,000-row limit itself, which also saves the 100-id chunks.
  3. Categories past the first 1,000 (#1587's follow-up 3) can't be picked either. The description's "every read goes past PostgREST's 1,000-row cap" holds once categoryPages pages its read.

@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. 00351 is applied to production. Merged with main after #1587's squash. The follow-ups from the round 38 review stay open.

@gkhngyk
gkhngyk merged commit 0e9c1fa into ansvisor:main Oct 27, 2026
4 of 5 checks passed
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.

2 participants