Skip to content

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.

feat(content): put catalog products in a page as a card or a grid, by hand or with the agent (shopping path, part 5) (#1607)

Cihan13b3ff78c40a
diff --git a/docs/guides/content-editor.mdx b/docs/guides/content-editor.mdx
index b888f4deb..4c1e93b4d 100644
--- a/docs/guides/content-editor.mdx
+++ b/docs/guides/content-editor.mdx
@@ -155,6 +155,7 @@ The Content Agent never changes these passages. If you edit one, the editor asks
- **Copy HTML** copies the whole page as HTML, HTML blocks and schema included, to paste into your CMS.
- **Export** downloads the page as **Word**, **HTML** or **Markdown**. Only the HTML file carries the schema (JSON-LD).
- **Add HTML** in the toolbar adds an HTML block: an embed, a widget or a form, kept exactly as written. Ansvisor never runs it. **Edit as HTML** shows the page's source; scripts, iframes and inline styles are removed when you switch back.
+- **Products** (the bag in the toolbar, or **Add › Products** on an empty line), on an online shop's draft, adds products from your catalog: search by name, pick 1 to 4 that are in stock, and **Insert**. One shows as a card, more as a grid, each with its picture, name and price (its cheapest variant in stock), linked to its page. It goes in as an HTML block; Webflow's rich text has no grid, so there it's a list, a product a line. A product sold out by the time you insert is left out, and the editor says so. When the Content Agent writes a new buying guide, best-of list, comparison or alternatives page with a shopping path, it adds the same grid of the path's products in stock (two or more), at the end of the section that links them most.
- **Send to CMS** (admins and managers) sends the page to the brand's Webflow collection as a draft item, or to your workflow tool through the brand's webhook, for it to create the post in your CMS. See [Send to CMS](/guides/send-to-cms).
- **Mark ready** saves the page, sets it to **Ready** and keeps a version in History. If the draft was sent to the Action Center, it also completes its task there. Ansvisor doesn't publish the page: copy or export it to your site, or send it to your CMS.
- **Mark published** (the Library's **Status** menu, or the header's **Next step** once the page is ready, when Quality is on): once the page is live, tell Ansvisor where. It asks for the live address, starting from the page it optimizes or your site with the page's slug, and the **Live page** tab measures that address from then. If the draft came from the Action Center, its Publish task is completed once all the action's work is live. On a published page, the header's **Published** button changes the address. A page your CMS reports live, or one published in Webflow, gets its address on its own. An archived page is restored first.
diff --git a/server/src/lib/catalog/stock.js b/server/src/lib/catalog/stock.js
index afdcdca06..2f6484a25 100644
--- a/server/src/lib/catalog/stock.js
+++ b/server/src/lib/catalog/stock.js
@@ -1,6 +1,6 @@
/**
* A catalog variant's stock, read one way everywhere: as the editor's feed
- * match reads it (web/src/lib/content/feed-match.ts, feedStock) and as
+ * match reads it (web/src/lib/content/feed-match.ts, variantStock) and as
* catalog_category_counts (00350) counts it. Feeds and stores spell it many
* ways ("in stock", "IN_STOCK", "limited-availability"), so it is read
* lowercased, with spaces and hyphens as "_". stock.test.js checks the three
diff --git a/server/src/lib/cms/webflow-items.js b/server/src/lib/cms/webflow-items.js
index 4f160e4cf..58e914d7d 100644
--- a/server/src/lib/cms/webflow-items.js
+++ b/server/src/lib/cms/webflow-items.js
@@ -84,6 +84,7 @@ const ownRows = ($, table) =>
* A page's publishable HTML as Webflow's rich text keeps it:
* - a table becomes a list, a row an item ("Header: cell · …"), a table in
* a cell first: rich text has no tables (#1331);
+ * - a product card or grid becomes a list, a product an item ("Name $189.00");
* - images and media are left out until workspace files (CHAT-06, #1331),
* a figure of one with its caption; scripts (the JSON-LD has its own
* field), embeds, forms and rules go too;
@@ -139,6 +140,23 @@ export function toWebflowRichText(html) {
);
}
+ // A product card or grid (the editor's product-block.ts, shopping-blocks.js)
+ // as a list: a product an item, its name linked, its price after it.
+ $('.ansvisor-products').each((_, grid) => {
+ const items = $(grid)
+ .find('a.ansvisor-product')
+ .toArray()
+ .flatMap((card) => {
+ const name = squash($(card).find('strong').text());
+ if (!name) return [];
+ const price = squash($(card).find('span').text());
+ const $item = $('<li></li>').append($(card).text(name));
+ if (price) $item.append(` ${escape(price)}`);
+ return [$item];
+ });
+ $(grid).replaceWith(items.length ? $('<ul></ul>').append(items) : '');
+ });
+
// A figure of media goes with its caption; a figure of words (a table's) keeps them.
$('figure').each((_, figure) => {
if ($(figure).find(MEDIA).length) $(figure).remove();
diff --git a/server/src/lib/cms/webflow-items.test.js b/server/src/lib/cms/webflow-items.test.js
index 47759b6fb..bf109e374 100644
--- a/server/src/lib/cms/webflow-items.test.js
+++ b/server/src/lib/cms/webflow-items.test.js
@@ -1,3 +1,4 @@
+import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { fieldDataFor, toWebflowRichText, webflowSlug } from './webflow-items.js';
@@ -76,6 +77,29 @@ describe('toWebflowRichText, on what pages hold', () => {
expect(html).toBe('<p>Loose <strong>words</strong></p><h2>Next</h2><p>Orphan</p>');
expect(changed.images).toBe(1);
});
+
+ it('reads a product grid as a list, a product a line: its name linked, its price after it', () => {
+ // The editor's and the agent's grid (web/src/lib/content/product-block.ts, shopping-blocks.js).
+ const grid = JSON.parse(
+ readFileSync(
+ new URL('../../../../web/src/lib/content/__fixtures__/product-block.json', import.meta.url),
+ 'utf8',
+ ),
+ ).html;
+ const { html, changed } = toWebflowRichText(
+ `<p>Our picks:</p><!-- html-block -->\n${grid}\n<!-- /html-block --><p>More below.</p>`,
+ );
+ expect(html).toBe(
+ '<p>Our picks:</p><ul><li><a href="https://shop.example/products/p1?variant=2">Summit "GTX" Boot</a> $189.00</li><li><a href="https://shop.example/products/p2">Trail Mid</a></li></ul><p>More below.</p>',
+ );
+ expect(changed.images).toBe(1);
+ // A card whose name is gone isn't an item, and a grid of none is nothing.
+ expect(
+ toWebflowRichText(
+ '<div class="ansvisor-products"><a class="ansvisor-product" href="https://s.example/p"><strong> </strong></a></div><p>x</p>',
+ ).html,
+ ).toBe('<p>x</p>');
+ });
});
describe('webflowSlug', () => {
diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.js
index ee4f4e64f..6cd9570c2 100644
--- a/server/src/lib/content-writer.js
+++ b/server/src/lib/content-writer.js
@@ -32,6 +32,7 @@ import {
import { inputSources, readDraftInputs } from './content-inputs.js';
import { draftLanguage } from './content-language.js';
import { linkAllowList, linkTargetsPrompt, readLinkTargets } from './content-links.js';
+import { insertProductGrid } from './shopping-blocks.js';
import {
linkShoppingPath,
shoppingGiven,
@@ -990,8 +991,12 @@ async function writeWithRun({ draft, brand, model, input, budget, rewrite, run }
draft,
{
title,
- // The shopping path's names it wrote, linked (shopping-links.js).
- body_html: linkShoppingPath(renderPage({ ...written, title }), shoppingPath).html,
+ // The shopping path's names it wrote, linked (shopping-links.js), and
+ // its products as a grid where the page names them most (shopping-blocks.js).
+ body_html: insertProductGrid(
+ linkShoppingPath(renderPage({ ...written, title }), shoppingPath).html,
+ shoppingPath && { ...shoppingPath, pageType: draft.page_type },
+ ),
status: 'in_review',
author: 'agent',
agent_state: null,
diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.js
index 7c672b9e9..97332c6e1 100644
--- a/server/src/lib/content-writer.test.js
+++ b/server/src/lib/content-writer.test.js
@@ -628,6 +628,65 @@ describe('runDraftWriting on a new page', () => {
}
});
+ it("puts the checked path's products in stock as a grid, not the ones the draft keeps (shopping path, part 5)", async () => {
+ generateObject.mockResolvedValue({
+ object: {
+ ...page,
+ sections: [
+ { heading: 'How to choose', paragraphs: ['Fit first.'], bullets: [] },
+ {
+ heading: 'Our picks',
+ paragraphs: ['The Summit GTX Boot, then the Trail 450 Boot.'],
+ bullets: [],
+ },
+ ],
+ },
+ usage: { inputTokens: 10, outputTokens: 20 },
+ });
+ rows.brand_domains = [{ domain: 'shop.example' }];
+ const variant = (id, productId, price) => ({
+ id,
+ product_id: productId,
+ availability: 'in stock',
+ price,
+ sale_price: null,
+ currency: 'USD',
+ });
+ // All in stock now, the first cheaper than when the path was built.
+ rows.catalog_variants = [
+ variant('v1', 'p1', 179),
+ variant('v2', 'p2', 129),
+ variant('v3', 'p3', 99),
+ variant('v4', 'p4', 99),
+ ];
+ const kept = shoppingPath({ pageType: 'buying_guide' });
+ // Kept as a member saved it: one page off the brand's site (Evil Boot), one over http.
+ kept.products.push({
+ ...kept.products[1],
+ id: 'p4',
+ title: 'Plain Boot',
+ url: 'http://shop.example/products/p4',
+ });
+ await expect(
+ run(draftRow({ page_type: 'buying_guide', shopping_path: kept })),
+ ).resolves.toEqual({ written: true });
+ const written = draftUpdates().find((u) => u.body_html)?.body_html;
+ const encoded = /<div data-html-block="([^"]+)"><\/div>/.exec(written);
+ const grid = Buffer.from(encoded[1], 'base64').toString('utf8');
+ expect(grid.match(/class="ansvisor-product"/g)).toHaveLength(2);
+ expect(grid).toContain('href="https://shop.example/products/p1"');
+ expect(grid).toContain('href="https://shop.example/products/p2"');
+ expect(grid).not.toContain('Evil Boot');
+ expect(grid).not.toContain('Plain Boot');
+ // The catalog's price now, not the one the path was built with.
+ expect(grid).toContain('$179.00');
+ expect(grid).not.toContain('$189.00');
+ // At the end of the section that links them.
+ expect(written).toMatch(
+ /Trail 450 Boot<\/a>\.<\/p><div data-html-block="[^"]+"><\/div><h2>FAQ<\/h2>/,
+ );
+ });
+
it('leaves a draft marked ready during the run as it is', async () => {
finished = null;
await expect(run(draftRow())).resolves.toEqual({ skipped: true });
diff --git a/server/src/lib/shopping-blocks.js b/server/src/lib/shopping-blocks.js
new file mode 100644
index 000000000..093af1072
--- /dev/null
+++ b/server/src/lib/shopping-blocks.js
@@ -0,0 +1,130 @@
+import * as cheerio from 'cheerio';
+import { isInStock } from './catalog/stock.js';
+import { linkHref } from './content-links.js';
+
+/**
+ * The product grid a new page gets from its shopping path (shopping path,
+ * part 5): the path's products in stock as an HTML block, each its picture,
+ * name and price, linked to its page, put at the end of the section that
+ * names them most. The markup is the editor's product card and grid
+ * (web/src/lib/content/product-block.ts): keep the two alike. Stored as the
+ * editor stores an HTML block: UTF-8 in base64, in a data attribute.
+ */
+
+/** Products a grid shows at most, as the editor's block. */
+export const MAX_BLOCK_PRODUCTS = 4;
+/** The page types that show their products as a grid. */
+export const GRID_PAGE_TYPES = new Set(['best_of', 'buying_guide', 'comparison', 'alternatives']);
+
+const ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
+const escape = (text) => String(text).replace(/[&<>"']/g, (c) => ENTITIES[c]);
+
+/** An amount above 0, or null: a price of 0 is none given. */
+const positive = (value) => (value != null && Number(value) > 0 ? Number(value) : null);
+
+/**
+ * A product's price as the editor's card reads it ("$189.00"): the sale
+ * price when it's under the price, else the price; null without one.
+ */
+export function priceText({ price, salePrice, currency }) {
+ const regular = positive(price);
+ const sale = positive(salePrice);
+ const amount = sale != null && regular != null && sale < regular ? sale : regular;
+ if (amount == null) return null;
+ try {
+ return currency
+ ? new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount)
+ : new Intl.NumberFormat('en-US', { minimumFractionDigits: 2 }).format(amount);
+ } catch {
+ return `${amount} ${currency}`;
+ }
+}
+
+/** The page a card links to, as the editor's productHref: https only, without tracking or a hash; else null. */
+export function productHref(url) {
+ const href = linkHref(url);
+ return href && href.startsWith('https:') ? href : null;
+}
+
+/** An https picture the card shows, or null. */
+function imageSrc(value) {
+ try {
+ const url = new URL(String(value ?? ''));
+ return url.protocol === 'https:' ? url.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The block's HTML, as the editor's productBlockHtml writes it; '' with none to show. */
+export function productBlockHtml(products) {
+ const items = products
+ .map((p) => ({ ...p, url: productHref(p.url), image: imageSrc(p.image) }))
+ .filter((p) => p.url && String(p.title ?? '').trim())
+ .slice(0, MAX_BLOCK_PRODUCTS);
+ if (!items.length) return '';
+ // A space before the price and a line between cards: where the styles
+ // are dropped (a text export, a CMS's rich text), each product reads
+ // "Name $189.00" on its own.
+ const cards = items.map((p) => {
+ // The name as alt too: a text export reads an image by its alt (draft-export.ts), and
+ // an empty one would print "[Image]" there.
+ const image = p.image
+ ? `<img src="${escape(p.image)}" alt="${escape(String(p.title).trim())}" loading="lazy" style="display:block;width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:8px">`
+ : '';
+ const price = p.price
+ ? ` <span style="display:block;margin-top:4px">${escape(p.price)}</span>`
+ : '';
+ return `<a class="ansvisor-product" href="${escape(p.url)}" style="display:block;border:1px solid #e5e5e5;border-radius:12px;padding:12px;text-decoration:none;color:inherit">${image}<strong style="display:block;margin-top:8px">${escape(String(p.title).trim())}</strong>${price}</a>`;
+ });
+ return `<div class="ansvisor-products" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px;margin:16px 0">${cards.join('\n')}</div>`;
+}
+
+/** An HTML block as a draft stores it (html-allowlist.ts htmlBlockElement). */
+export function htmlBlockElement(code) {
+ return `<div data-html-block="${Buffer.from(code, 'utf8').toString('base64')}"></div>`;
+}
+
+/**
+ * A new page with its shopping path's products in stock as a grid: at the
+ * end of the H2 section that links them most, else before the last H2 (a
+ * FAQ, most often), else, with no H2, at the end. Only for a list, a buying
+ * guide or a comparison with two such products or more; any other page is
+ * returned as it is. The path is shoppingPathFor's (shopping-links.js): its
+ * pages on the brand's site, its stock and prices as the catalog has them now.
+ */
+export function insertProductGrid(html, path) {
+ if (!html || !GRID_PAGE_TYPES.has(path?.pageType)) return html;
+ const products = (path?.products ?? []).filter(
+ (p) => isInStock(p.availability) && productHref(p.url),
+ );
+ if (products.length < 2) return html;
+ const code = productBlockHtml(
+ products.map((p) => ({ title: p.title, url: p.url, image: p.image, price: priceText(p) })),
+ );
+ if (!code) return html;
+ const block = htmlBlockElement(code);
+ const keys = new Set(products.map((p) => productHref(p.url)));
+
+ const $ = cheerio.load(html, null, false);
+ const top = $.root().children().toArray();
+ const headings = top.filter((el) => el.tagName === 'h2');
+ if (!headings.length) {
+ $.root().append(block);
+ return $.html();
+ }
+ // Each H2's section: the elements up to the next H2.
+ let best = null;
+ headings.forEach((heading, i) => {
+ const from = top.indexOf(heading);
+ const to = i + 1 < headings.length ? top.indexOf(headings[i + 1]) : top.length;
+ const links = top
+ .slice(from + 1, to)
+ .flatMap((el) => $(el).find('a[href]').addBack('a[href]').toArray())
+ .filter((a) => keys.has(productHref($(a).attr('href')))).length;
+ if (links > 0 && (!best || links > best.links)) best = { links, last: top[to - 1] };
+ });
+ if (best) $(best.last).after(block);
+ else $(headings.at(-1)).before(block);
+ return $.html();
+}
diff --git a/server/src/lib/shopping-blocks.test.js b/server/src/lib/shopping-blocks.test.js
new file mode 100644
index 000000000..3d1a86218
--- /dev/null
+++ b/server/src/lib/shopping-blocks.test.js
@@ -0,0 +1,173 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../config/supabase.js', () => ({ default: {} }));
+
+import {
+ htmlBlockElement,
+ insertProductGrid,
+ priceText,
+ productBlockHtml,
+} from './shopping-blocks.js';
+
+/** The product grid a new page gets from its shopping path (shopping path, part 5). */
+
+// The editor's product-block.test.ts reads the same products and expects the same markup.
+const SAME_AS_THE_EDITOR = JSON.parse(
+ readFileSync(
+ new URL('../../../web/src/lib/content/__fixtures__/product-block.json', import.meta.url),
+ 'utf8',
+ ),
+);
+
+const product = (id, title, extra = {}) => ({
+ id,
+ title,
+ url: `https://shop.example/products/${id}`,
+ price: 189,
+ salePrice: null,
+ currency: 'USD',
+ availability: 'in_stock',
+ image: null,
+ issues: [],
+ score: 9,
+ ...extra,
+});
+
+describe('priceText', () => {
+ it('writes a price in its currency, the sale price when it is under the price', () => {
+ expect(priceText({ price: 189, salePrice: null, currency: 'USD' })).toBe('$189.00');
+ expect(priceText({ price: 149, salePrice: 129, currency: 'EUR' })).toBe('€129.00');
+ expect(priceText({ price: null, salePrice: null, currency: 'USD' })).toBeNull();
+ });
+
+ it('reads a price of 0 as none, and a sale price not under the price as no sale', () => {
+ expect(priceText({ price: 0, salePrice: null, currency: 'USD' })).toBeNull();
+ expect(priceText({ price: 149, salePrice: 0, currency: 'USD' })).toBe('$149.00');
+ expect(priceText({ price: 149, salePrice: 149, currency: 'USD' })).toBe('$149.00');
+ expect(priceText({ price: 149, salePrice: 159, currency: 'USD' })).toBe('$149.00');
+ expect(priceText({ price: null, salePrice: 129, currency: 'USD' })).toBeNull();
+ });
+});
+
+describe('productBlockHtml', () => {
+ it("writes the editor's markup: picture, name and price, linked over https without tracking, escaped", () => {
+ expect(productBlockHtml(SAME_AS_THE_EDITOR.products)).toBe(SAME_AS_THE_EDITOR.html);
+ expect(productBlockHtml([])).toBe('');
+ });
+
+ it('shows four at most, the first that have a page', () => {
+ const many = [
+ { title: 'No page', url: 'http://s.example/p0', image: null, price: null },
+ ...Array.from({ length: 5 }, (_, i) => ({
+ title: `P${i + 1}`,
+ url: `https://s.example/p${i + 1}`,
+ image: null,
+ price: null,
+ })),
+ ];
+ const code = productBlockHtml(many);
+ expect(code.match(/class="ansvisor-product"/g)).toHaveLength(4);
+ expect(code).toContain('>P4</strong>');
+ expect(code).not.toContain('>P5</strong>');
+ });
+});
+
+describe('htmlBlockElement', () => {
+ it('stores the code as the editor does: UTF-8 in base64', () => {
+ const element = htmlBlockElement('<p>Bot – ü</p>');
+ const encoded = /data-html-block="([^"]+)"/.exec(element)[1];
+ expect(Buffer.from(encoded, 'base64').toString('utf8')).toBe('<p>Bot – ü</p>');
+ });
+});
+
+describe('insertProductGrid', () => {
+ const path = {
+ pageType: 'buying_guide',
+ products: [product('p1', 'Summit GTX Boot'), product('p2', 'Trail Mid')],
+ };
+ const link = (id) => `<a href="https://shop.example/products/${id}">x</a>`;
+ const decoded = (html) =>
+ [...html.matchAll(/data-html-block="([^"]+)"/g)].map((m) =>
+ Buffer.from(m[1], 'base64').toString('utf8'),
+ );
+
+ it('puts the grid at the end of the section that links the products most', () => {
+ const html =
+ '<h1>T</h1><p>Intro</p><h2>Choose</h2><p>How.</p>' +
+ `<h2>Picks</h2><p>${link('p1')}</p><ul><li><p>${link('p2')}</p></li></ul>` +
+ `<h2>FAQ</h2><h3>Q?</h3><p>${link('p1')}</p>`;
+ const out = insertProductGrid(html, path);
+ expect(out.indexOf('data-html-block')).toBeGreaterThan(out.indexOf('</ul>'));
+ expect(out.indexOf('data-html-block')).toBeLessThan(out.indexOf('<h2>FAQ</h2>'));
+ expect(decoded(out)[0]).toContain('https://shop.example/products/p2');
+ });
+
+ it("counts only links to the grid's products, not to other pages", () => {
+ const html =
+ '<h1>T</h1><h2>Brands</h2>' +
+ '<p><a href="https://other.example/a">a</a> <a href="https://shop.example/about">b</a></p>' +
+ `<h2>Picks</h2><p>${link('p1')}</p><h2>FAQ</h2><p>q</p>`;
+ const out = insertProductGrid(html, path);
+ expect(out).toMatch(
+ /<a href="https:\/\/shop\.example\/products\/p1">x<\/a><\/p><div data-html-block=/,
+ );
+ });
+
+ it('puts it before the last H2 when no section links them, a lone one too, or at the end with none', () => {
+ const out = insertProductGrid('<h1>T</h1><h2>A</h2><p>a</p><h2>FAQ</h2><p>q</p>', path);
+ expect(out).toMatch(/<p>a<\/p><div data-html-block="[^"]+"><\/div><h2>FAQ<\/h2>/);
+ // One H2, linking none of them: before it, not after its section.
+ expect(insertProductGrid('<h1>T</h1><p>a</p><h2>FAQ</h2><p>q</p>', path)).toMatch(
+ /<p>a<\/p><div data-html-block="[^"]+"><\/div><h2>FAQ<\/h2><p>q<\/p>$/,
+ );
+ expect(insertProductGrid('<h1>T</h1><p>a</p>', path)).toMatch(/<p>a<\/p><div data-html-block=/);
+ });
+
+ it('shows only the products in stock, as the catalog has them now', () => {
+ const withOut = (availability) => ({
+ ...path,
+ products: [...path.products, product('p3', 'Ridge Low', { availability })],
+ });
+ for (const availability of ['out_of_stock', '']) {
+ const code = decoded(insertProductGrid('<h1>T</h1><p>a</p>', withOut(availability)))[0];
+ expect(code).toContain('Summit GTX Boot');
+ expect(code).not.toContain('Ridge Low');
+ }
+ expect(
+ decoded(insertProductGrid('<h1>T</h1><p>a</p>', withOut('limited_availability')))[0],
+ ).toContain('Ridge Low');
+ // One left in stock: no grid.
+ const html = '<h1>T</h1><p>a</p>';
+ expect(
+ insertProductGrid(html, {
+ ...path,
+ products: [path.products[0], { ...path.products[1], availability: 'out_of_stock' }],
+ }),
+ ).toBe(html);
+ });
+
+ it("writes each one's price as the path has it, and links only https pages", () => {
+ const code = decoded(
+ insertProductGrid('<h1>T</h1><p>a</p>', {
+ ...path,
+ products: [
+ product('p1', 'Summit GTX Boot', { price: 149, salePrice: 129 }),
+ product('p2', 'Trail Mid', { price: 0 }),
+ product('p3', 'Ridge Low', { url: 'http://shop.example/products/p3' }),
+ ],
+ }),
+ )[0];
+ expect(code).toContain('$129.00');
+ expect(code).not.toContain('$149.00');
+ expect(code).not.toContain('$0.00');
+ expect(code).not.toContain('Ridge Low');
+ });
+
+ it('leaves a page type without a grid, or a path with one product, as it is', () => {
+ const html = '<h1>T</h1><h2>A</h2><p>a</p>';
+ expect(insertProductGrid(html, { ...path, pageType: 'blog_post' })).toBe(html);
+ expect(insertProductGrid(html, { ...path, products: [product('p1', 'One')] })).toBe(html);
+ expect(insertProductGrid(html, null)).toBe(html);
+ });
+});
diff --git a/server/src/lib/shopping-links.js b/server/src/lib/shopping-links.js
index 87c8f4b27..66a4ba41d 100644
--- a/server/src/lib/shopping-links.js
+++ b/server/src/lib/shopping-links.js
@@ -71,8 +71,13 @@ const CURRENCY_SIGNS = {
/** A product's price, the sale price first; null with none. */
function amountOf(product) {
- const amount = product.salePrice ?? product.price;
- return amount != null && Number.isFinite(Number(amount)) ? Number(amount) : null;
+ // As the card reads it (shopping-blocks.js priceText): an amount of 0 is
+ // none, and the sale price counts only under the price.
+ const positive = (value) =>
+ value != null && Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : null;
+ const regular = positive(product.price);
+ const sale = positive(product.salePrice);
+ return sale != null && regular != null && sale < regular ? sale : regular;
}
/** A product's price and stock as the agent is told them: "189.00 USD, in stock". */
@@ -243,8 +248,8 @@ async function withOffer(db, brandId, products, draftId) {
* The draft's shopping path as the agent writes with it, or null: read as
* shopping-path.js reads it (none when it isn't a path), its pages only
* https ones on the brand's own site (a stored path is a member's to
- * change), its products' stock as the catalog has it now. The site not
- * read, it has none: nothing it can't check is linked.
+ * change), its products' stock and prices as the catalog has them now.
+ * The site not read, it has none: nothing it can't check is linked.
*/
export async function shoppingPathFor(draft, { db = supabaseAdmin } = {}) {
const path = readShoppingPath(draft.shopping_path, { draftId: draft.id });
diff --git a/server/src/lib/shopping-links.test.js b/server/src/lib/shopping-links.test.js
index bae7dbbf3..83632606c 100644
--- a/server/src/lib/shopping-links.test.js
+++ b/server/src/lib/shopping-links.test.js
@@ -142,6 +142,22 @@ describe('shoppingPrompt', () => {
expect(shoppingPrompt({ categories: [], products: [] })).toBe('');
});
+ it('tells the price as the card shows it: a sale price only under the price, never 0', () => {
+ const prompt = shoppingPrompt({
+ ...PATH,
+ products: [
+ product('p1', 'Summit GTX Boot', { salePrice: 149 }),
+ product('p2', 'Trail Mid', { salePrice: 0 }),
+ product('p3', 'Ridge Low', { salePrice: 249 }),
+ product('p4', 'Canyon Sandal', { price: 0, salePrice: null }),
+ ],
+ });
+ expect(prompt).toContain('- Summit GTX Boot: 149.00 USD');
+ expect(prompt).toContain('- Trail Mid: 189.00 USD');
+ expect(prompt).toContain('- Ridge Low: 189.00 USD');
+ expect(prompt).not.toContain('0.00 USD');
+ });
+
it('never says a product out of stock or on pre-order is in stock, nor any stock it cannot read', () => {
const prompt = shoppingPrompt({
...PATH,
@@ -531,6 +547,10 @@ describe('shoppingPathFor', () => {
});
const read = await shoppingPathFor(draft(PATH), { db });
expect(read.products.map((p) => p.availability)).toEqual(['in_stock', 'limited_availability']);
+ expect(read.products.map((p) => [p.price, p.salePrice])).toEqual([
+ [189, null],
+ [149, 129],
+ ]);
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ draftId: 'd1' }),
expect.stringContaining('reading stock failed'),
diff --git a/web/messages/en.json b/web/messages/en.json
index c397d8650..6a56904ae 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -4199,9 +4199,12 @@
"table": "Table",
"tableHint": "Insert a table on this line",
"image": "Image",
- "imageHint": "Insert an image on this line"
+ "imageHint": "Insert an image on this line",
+ "products": "Products",
+ "productsHint": "Insert products from your catalog on this line"
},
"attach": "Attach a file: Excel, CSV, Word, Markdown, HTML or text",
+ "products": "Insert products from your catalog",
"html": "Edit as HTML",
"htmlBack": "Back to visual",
"openLink": "Open the link in a new tab (or ⌘/Ctrl + click it in the page)",
@@ -4512,6 +4515,24 @@
},
"untitled": "Untitled product"
},
+ "productBlock": {
+ "title": "Add products",
+ "description": "Pick 1 to {max} products in stock from your catalog. One shows as a card, more as a grid, each with its picture, name and price, linked to its page.",
+ "searchLabel": "Search the catalog",
+ "placeholder": "Product name…",
+ "empty": "No product with that name.",
+ "searchFailed": "Couldn't search the catalog. Try again.",
+ "soldOut": "Sold out",
+ "noPage": "No page to link",
+ "picked": "{count} of {max} picked",
+ "unpick": "Remove {title}",
+ "insert": "Insert",
+ "inserting": "Inserting…",
+ "cancel": "Cancel",
+ "leftOut": "Left out, not in stock now: {titles}",
+ "noLink": "These products have no page to link.",
+ "failed": "Couldn't read the products. Try again."
+ },
"brief": {
"loadError": "Couldn't load the brief.",
"retry": "Retry",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
index 36a461a74..512699e62 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
@@ -4098,6 +4098,8 @@ export function DraftEditor({
onToggleHtml={htmlSource === null ? openHtmlView : applyHtmlView}
onAttach={attachments.open}
linkRequest={linkRequest}
+ // + Insert › Products, from an online shop's catalog (shopping path, part 5).
+ productsBrandId={siteType === 'ecommerce' ? draft.brandId : null}
/>
)}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_product-block-dialog.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_product-block-dialog.test.tsx
new file mode 100644
index 000000000..b77b7f417
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_product-block-dialog.test.tsx
@@ -0,0 +1,228 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import type { BlockProductRead } from '@/lib/actions/shopping-path';
+
+const searchProductsForBlock = vi.fn();
+const getProductsForBlock = vi.fn();
+vi.mock('@/lib/actions/shopping-path', () => ({
+ searchProductsForBlock: (...args: unknown[]) => searchProductsForBlock(...args),
+ getProductsForBlock: (...args: unknown[]) => getProductsForBlock(...args),
+ searchCatalogProducts: vi.fn(),
+ getDraftShoppingPath: vi.fn(),
+ buildDraftShoppingPath: vi.fn(),
+ saveDraftShoppingPath: vi.fn(),
+}));
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { ProductBlockDialog } = await import('./_product-block-dialog');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** + Insert › Products (shopping path, part 5). */
+
+const boot = (n: number, over: Partial<BlockProductRead> = {}): BlockProductRead => ({
+ id: `p${n}`,
+ title: `Boot ${n}`,
+ url: `https://shop.example/products/p${n}`,
+ image: null,
+ price: 100 + n,
+ salePrice: null,
+ currency: 'USD',
+ inStock: true,
+ ...over,
+});
+const HITS = [1, 2, 3, 4, 5].map((n) => boot(n));
+
+let container: HTMLElement;
+let root: Root;
+const onInsert = vi.fn();
+const onClose = vi.fn();
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <ProductBlockDialog brandId="b1" onInsert={onInsert} onClose={onClose} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+// The dialog portals to the body. A hit's button reads its name, then its price or why it can't go in.
+const buttons = () => [...document.body.querySelectorAll('button')];
+const button = (label: string) =>
+ buttons().find((b) => b.textContent === label || b.getAttribute('aria-label') === label);
+const hit = (title: string) =>
+ buttons().find(
+ (b) => b.getAttribute('aria-pressed') !== null && b.textContent?.startsWith(title),
+ );
+async function search(text: string) {
+ const input = document.body.querySelector<HTMLInputElement>('input[type="search"]')!;
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setter.call(input, text);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300);
+ });
+}
+const counter = () => document.body.querySelector('[aria-live="polite"]')!.textContent;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ searchProductsForBlock.mockReset().mockResolvedValue(HITS);
+ getProductsForBlock
+ .mockReset()
+ .mockResolvedValue([boot(1, { image: 'https://cdn.example/p1.jpg', price: 189 }), boot(2)]);
+ onInsert.mockReset();
+ onClose.mockReset();
+ toast.error.mockReset();
+ toast.warning.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe('ProductBlockDialog', () => {
+ it('finds products by name, picks up to four, and inserts them as a block', async () => {
+ await render();
+ await search('boot');
+ expect(searchProductsForBlock).toHaveBeenCalledWith('b1', 'boot');
+ // Each hit with its price.
+ expect(hit('Boot 1')!.textContent).toBe('Boot 1$101.00');
+ for (const n of [1, 2, 3, 4]) await act(async () => hit(`Boot ${n}`)!.click());
+ // A fifth can't be picked.
+ expect(hit('Boot 5')!.disabled).toBe(true);
+ expect(counter()).toBe('4 of 4 picked');
+ await act(async () => hit('Boot 4')!.click());
+ await act(async () => hit('Boot 3')!.click());
+ expect(counter()).toBe('2 of 4 picked');
+
+ await act(async () => button('Insert')!.click());
+ expect(getProductsForBlock).toHaveBeenCalledWith('b1', ['p1', 'p2']);
+ const code = onInsert.mock.calls[0][0] as string;
+ expect(code).toContain('href="https://shop.example/products/p1"');
+ expect(code).toContain('$189.00');
+ expect(code).toContain('Boot 2');
+ expect(toast.warning).not.toHaveBeenCalled();
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('marks a sold-out product, and one with no page, and lets neither be picked', async () => {
+ searchProductsForBlock.mockResolvedValue([
+ boot(1, { inStock: false, price: null }),
+ boot(2, { url: null }),
+ boot(3, { url: 'http://shop.example/products/p3' }),
+ boot(4),
+ ]);
+ await render();
+ await search('boot');
+ expect(hit('Boot 1')!.textContent).toBe('Boot 1Sold out');
+ expect(hit('Boot 1')!.disabled).toBe(true);
+ expect(hit('Boot 2')!.textContent).toBe('Boot 2No page to link');
+ expect(hit('Boot 2')!.disabled).toBe(true);
+ expect(hit('Boot 3')!.disabled).toBe(true);
+ expect(hit('Boot 4')!.disabled).toBe(false);
+ });
+
+ it('keeps the picked ones listed through a new search, each to unpick', async () => {
+ await render();
+ await search('boot');
+ await act(async () => hit('Boot 1')!.click());
+ searchProductsForBlock.mockResolvedValue([boot(7)]);
+ await search('trail');
+ expect(hit('Boot 1')).toBeUndefined();
+ expect(counter()).toBe('1 of 4 picked');
+ await act(async () => button('Remove Boot 1')!.click());
+ expect(counter()).toBe('0 of 4 picked');
+ expect(button('Insert')!.disabled).toBe(true);
+ });
+
+ it('leaves out one sold out since it was picked, and says so', async () => {
+ getProductsForBlock.mockResolvedValue([boot(1), boot(2, { inStock: false, price: null })]);
+ await render();
+ await search('boot');
+ for (const n of [1, 2, 3]) await act(async () => hit(`Boot ${n}`)!.click());
+ await act(async () => button('Insert')!.click());
+ // Boot 3 is gone from the catalog.
+ expect(toast.warning).toHaveBeenCalledWith('Left out, not in stock now: Boot 2, Boot 3');
+ const code = onInsert.mock.calls[0][0] as string;
+ expect(code).toContain('Boot 1');
+ expect(code).not.toContain('Boot 2');
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('inserts nothing when all are sold out now, and unpicks them', async () => {
+ getProductsForBlock.mockResolvedValue([boot(1, { inStock: false, price: null })]);
+ await render();
+ await search('boot');
+ await act(async () => hit('Boot 1')!.click());
+ await act(async () => button('Insert')!.click());
+ expect(onInsert).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(toast.warning).toHaveBeenCalledWith('Left out, not in stock now: Boot 1');
+ expect(toast.error).not.toHaveBeenCalled();
+ expect(counter()).toBe('0 of 4 picked');
+ });
+
+ it("says so when no product picked has a page, or the products can't be read", async () => {
+ getProductsForBlock.mockResolvedValueOnce([boot(1, { url: null })]);
+ await render();
+ await search('boot');
+ await act(async () => hit('Boot 1')!.click());
+ await act(async () => button('Insert')!.click());
+ expect(onInsert).not.toHaveBeenCalled();
+ expect(toast.error).toHaveBeenCalledWith('These products have no page to link.');
+
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ getProductsForBlock.mockRejectedValueOnce(new Error('down'));
+ await act(async () => button('Insert')!.click());
+ expect(toast.error).toHaveBeenLastCalledWith("Couldn't read the products. Try again.");
+ } finally {
+ error.mockRestore();
+ }
+ });
+
+ it('shows Inserting… while the products are read, and inserts nothing once cancelled', async () => {
+ let answer!: (read: BlockProductRead[]) => void;
+ getProductsForBlock.mockReturnValue(new Promise((resolve) => (answer = resolve)));
+ await render();
+ await search('boot');
+ await act(async () => hit('Boot 1')!.click());
+ await act(async () => button('Insert')!.click());
+ const insert = button('Inserting…')!;
+ expect(insert.disabled).toBe(true);
+ expect(insert.getAttribute('aria-busy')).toBe('true');
+ await act(async () => button('Cancel')!.click());
+ expect(onClose).toHaveBeenCalledTimes(1);
+ await act(async () => answer([boot(1)]));
+ expect(onInsert).not.toHaveBeenCalled();
+ expect(toast.warning).not.toHaveBeenCalled();
+ });
+
+ it('says a failed search as such, not as no product found', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ searchProductsForBlock.mockRejectedValue(new Error('down'));
+ await render();
+ await search('boot');
+ expect(document.body.querySelector('[role="alert"]')!.textContent).toBe(
+ "Couldn't search the catalog. Try again.",
+ );
+ expect(document.body.textContent).not.toContain('No product with that name.');
+ } finally {
+ error.mockRestore();
+ }
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_product-block-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_product-block-dialog.tsx
new file mode 100644
index 000000000..65c61fb2e
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_product-block-dialog.tsx
@@ -0,0 +1,232 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Check, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Input } from '@/components/ui/input';
+import {
+ getProductsForBlock,
+ searchProductsForBlock,
+ type BlockProductRead,
+} from '@/lib/actions/shopping-path';
+import { MAX_BLOCK_PRODUCTS, productBlockHtml, productHref } from '@/lib/content/product-block';
+import { priceText } from './_shopping-path';
+
+/**
+ * + Insert › Products (shopping path, part 5): the person searches the
+ * brand's catalog by name and picks one to four products in stock with a
+ * page; Insert puts them on the line as an HTML block, a card for one, a
+ * grid for more, each with its picture, name and price, linked to its page.
+ * Read again on Insert: one sold out since is left out, and said so.
+ */
+export function ProductBlockDialog({
+ brandId,
+ onInsert,
+ onClose,
+}: {
+ brandId: string;
+ onInsert: (code: string) => void;
+ onClose: () => void;
+}) {
+ const t = useTranslations('contentEditor.editor.productBlock');
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [query, setQuery] = useState('');
+ const [hits, setHits] = useState<BlockProductRead[] | 'failed' | null>(null);
+ const [picked, setPicked] = useState<BlockProductRead[]>([]);
+ const [busy, setBusy] = useState(false);
+
+ // Closed (Cancel, Esc) while the products are read: nothing goes in the page.
+ const closed = useRef(false);
+ useEffect(() => {
+ closed.current = false;
+ return () => {
+ closed.current = true;
+ };
+ }, []);
+ const close = () => {
+ closed.current = true;
+ onClose();
+ };
+
+ useEffect(() => {
+ if (query.trim().length < 2) {
+ setHits(null);
+ return;
+ }
+ let cancelled = false;
+ const timer = setTimeout(() => {
+ searchProductsForBlock(brandId, query).then(
+ (found) => {
+ if (!cancelled) setHits(found);
+ },
+ (err) => {
+ console.error('Failed to search the catalog:', err);
+ if (!cancelled) setHits('failed');
+ },
+ );
+ }, 250);
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [query, brandId]);
+
+ const isPicked = (id: string) => picked.some((p) => p.id === id);
+ /** Why a product can't go in a block, or null: sold out, or no page to link. */
+ const blocked = (p: BlockProductRead) =>
+ !p.inStock ? t('soldOut') : !productHref(p.url) ? t('noPage') : null;
+ const toggle = (hit: BlockProductRead) =>
+ setPicked((now) =>
+ now.some((p) => p.id === hit.id)
+ ? now.filter((p) => p.id !== hit.id)
+ : now.length < MAX_BLOCK_PRODUCTS
+ ? [...now, hit]
+ : now,
+ );
+
+ const insert = async () => {
+ setBusy(true);
+ try {
+ const read = await getProductsForBlock(
+ brandId,
+ picked.map((p) => p.id),
+ );
+ if (closed.current) return;
+ const now = new Map(read.map((p) => [p.id, p]));
+ // Sold out since it was picked, or gone from the catalog: left out, and said so.
+ const left = picked.filter((p) => !now.get(p.id)?.inStock);
+ if (left.length) {
+ toast.warning(t('leftOut', { titles: left.map((p) => p.title).join(', ') }));
+ }
+ const code = productBlockHtml(
+ picked.flatMap((p) => {
+ const product = now.get(p.id);
+ return product?.inStock
+ ? [
+ {
+ title: product.title,
+ url: product.url,
+ image: product.image,
+ price: priceText(product),
+ },
+ ]
+ : [];
+ }),
+ );
+ if (!code) {
+ if (!left.length) toast.error(t('noLink'));
+ // Nothing to put in: the ones left out are unpicked, for others to be picked.
+ setPicked((was) => was.filter((p) => now.get(p.id)?.inStock));
+ return;
+ }
+ onInsert(code);
+ close();
+ } catch (err) {
+ if (closed.current) return;
+ console.error('Failed to read the products:', err);
+ toast.error(t('failed'));
+ } finally {
+ if (!closed.current) setBusy(false);
+ }
+ };
+
+ return (
+ <Dialog open onOpenChange={(next) => !next && close()}>
+ <DialogContent className="sm:max-w-lg" initialFocus={inputRef}>
+ <DialogHeader>
+ <DialogTitle>{t('title')}</DialogTitle>
+ <DialogDescription>{t('description', { max: MAX_BLOCK_PRODUCTS })}</DialogDescription>
+ </DialogHeader>
+ <Input
+ ref={inputRef}
+ type="search"
+ value={query}
+ maxLength={100}
+ placeholder={t('placeholder')}
+ aria-label={t('searchLabel')}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ {hits === 'failed' && (
+ <p className="text-xs text-muted-foreground" role="alert">
+ {t('searchFailed')}
+ </p>
+ )}
+ {Array.isArray(hits) && hits.length === 0 && (
+ <p className="text-xs text-muted-foreground">{t('empty')}</p>
+ )}
+ {Array.isArray(hits) && hits.length > 0 && (
+ <ul className="max-h-64 divide-y overflow-y-auto rounded-md border">
+ {hits.map((hit) => {
+ const on = isPicked(hit.id);
+ const why = blocked(hit);
+ return (
+ <li key={hit.id}>
+ <button
+ type="button"
+ aria-pressed={on}
+ disabled={!on && (!!why || picked.length >= MAX_BLOCK_PRODUCTS)}
+ className="flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-muted disabled:opacity-50"
+ onClick={() => toggle(hit)}
+ >
+ <span
+ aria-hidden="true"
+ className="flex h-4 w-4 shrink-0 items-center justify-center rounded border"
+ >
+ {on && <Check className="h-3 w-3" />}
+ </span>
+ <span className="min-w-0 flex-1 truncate">{hit.title}</span>
+ <span className="shrink-0 text-xs text-muted-foreground">
+ {why ?? priceText(hit)}
+ </span>
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ <div className="space-y-1.5">
+ <p className="text-xs text-muted-foreground" aria-live="polite">
+ {t('picked', { count: picked.length, max: MAX_BLOCK_PRODUCTS })}
+ </p>
+ {picked.length > 0 && (
+ <ul className="flex flex-wrap gap-1.5">
+ {picked.map((p) => (
+ <li
+ key={p.id}
+ className="flex max-w-full items-center gap-1 rounded-full border py-0.5 pl-2.5 pr-1 text-xs"
+ >
+ <span className="truncate">{p.title}</span>
+ <button
+ type="button"
+ aria-label={t('unpick', { title: p.title })}
+ className="rounded-full p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"
+ onClick={() => toggle(p)}
+ >
+ <X className="h-3 w-3" aria-hidden="true" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>
+ <Button disabled={!picked.length || busy} aria-busy={busy} onClick={() => void insert()}>
+ {busy ? t('inserting') : t('insert')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.test.tsx
index 89eac007b..323f795a0 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.test.tsx
@@ -123,6 +123,12 @@ describe('priceText', () => {
expect(priceText({ price: 149, salePrice: 129, currency: 'EUR' })).toBe('€129.00');
expect(priceText({ price: null, salePrice: null, currency: 'USD' })).toBeNull();
expect(priceText({ price: 10, salePrice: null, currency: 'XX1' })).toBe('10 XX1');
+ // A price of 0 is none; a sale price is one only under the price.
+ expect(priceText({ price: 0, salePrice: null, currency: 'USD' })).toBeNull();
+ expect(priceText({ price: 149, salePrice: 0, currency: 'USD' })).toBe('$149.00');
+ expect(priceText({ price: 149, salePrice: 149, currency: 'USD' })).toBe('$149.00');
+ expect(priceText({ price: 149, salePrice: 159, currency: 'USD' })).toBe('$149.00');
+ expect(priceText({ price: null, salePrice: 129, currency: 'USD' })).toBeNull();
});
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.tsx
index 2933558af..f0bd24624 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_shopping-path.tsx
@@ -27,9 +27,17 @@ import {
} from '@/lib/content/shopping-path';
import { pagePath } from '@/lib/content/overlap';
-/** A product's price as the catalog has it, in its currency; null without one. */
+/** An amount above 0, or null: a price of 0 is none given. */
+const positive = (value: number | null) => (value != null && value > 0 ? value : null);
+
+/**
+ * A product's price as the catalog has it, in its currency: the sale price
+ * when it's under the price, else the price; null without one.
+ */
export function priceText(product: Pick<ShoppingProduct, 'price' | 'salePrice' | 'currency'>) {
- const amount = product.salePrice ?? product.price;
+ const price = positive(product.price);
+ const sale = positive(product.salePrice);
+ const amount = sale != null && price != null && sale < price ? sale : price;
if (amount == null) return null;
try {
return product.currency
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.test.ts
deleted file mode 100644
index 9838093c9..000000000
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.test.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { Editor } from '@tiptap/core';
-import StarterKit from '@tiptap/starter-kit';
-import { afterEach, describe, expect, it } from 'vitest';
-import { onEmptyLine } from './_toolbar';
-
-let editor: Editor | null = null;
-afterEach(() => {
- editor?.destroy();
- editor = null;
-});
-
-/** An editor on the page, with the cursor at `pos`. */
-function at(content: string, pos: number) {
- editor = new Editor({ extensions: [StarterKit], content });
- editor.commands.setTextSelection(pos);
- return onEmptyLine(editor, editor.state);
-}
-
-describe('onEmptyLine', () => {
- // "<h1>Title</h1>" takes positions 0–7: the empty paragraph after it opens at 7.
- it('offers the insert menu on an empty line between blocks', () => {
- expect(at('<h1>Title</h1><p></p><p>Text</p>', 8)).toBe(true);
- });
-
- it('not on a line with text, a heading or a list item', () => {
- expect(at('<h1>Title</h1><p></p><p>Text</p>', 11)).toBe(false);
- expect(at('<h1>Title</h1><p></p>', 3)).toBe(false);
- expect(at('<h1>Title</h1><ul><li><p></p></li></ul>', 10)).toBe(false);
- });
-
- it('not on an empty page, where the placeholder shows', () => {
- expect(at('<p></p>', 1)).toBe(false);
- });
-});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.test.tsx
new file mode 100644
index 000000000..ba7c02a56
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.test.tsx
@@ -0,0 +1,100 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { Editor } from '@tiptap/core';
+import StarterKit from '@tiptap/starter-kit';
+import { CharacterCount } from '@tiptap/extensions';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+
+vi.mock('@/lib/actions/shopping-path', () => ({
+ searchProductsForBlock: vi.fn(),
+ getProductsForBlock: vi.fn(),
+}));
+
+const { EditorToolbar, onEmptyLine } = await import('./_toolbar');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let editor: Editor | null = null;
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+});
+
+/** An editor on the page, with the cursor at `pos`. */
+function at(content: string, pos: number) {
+ editor = new Editor({ extensions: [StarterKit], content });
+ editor.commands.setTextSelection(pos);
+ return onEmptyLine(editor, editor.state);
+}
+
+describe('onEmptyLine', () => {
+ // "<h1>Title</h1>" takes positions 0–7: the empty paragraph after it opens at 7.
+ it('offers the insert menu on an empty line between blocks', () => {
+ expect(at('<h1>Title</h1><p></p><p>Text</p>', 8)).toBe(true);
+ });
+
+ it('not on a line with text, a heading or a list item', () => {
+ expect(at('<h1>Title</h1><p></p><p>Text</p>', 11)).toBe(false);
+ expect(at('<h1>Title</h1><p></p>', 3)).toBe(false);
+ expect(at('<h1>Title</h1><ul><li><p></p></li></ul>', 10)).toBe(false);
+ });
+
+ it('not on an empty page, where the placeholder shows', () => {
+ expect(at('<p></p>', 1)).toBe(false);
+ });
+});
+
+describe('EditorToolbar', () => {
+ let container: HTMLElement;
+ let root: Root;
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.body.replaceChildren();
+ });
+
+ async function render(productsBrandId: string | null) {
+ editor = new Editor({
+ extensions: [StarterKit, CharacterCount],
+ content: '<h1>Title</h1><p>Text</p>',
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <EditorToolbar
+ editor={editor!}
+ target={3000}
+ lengthWarning={false}
+ htmlView={false}
+ onToggleHtml={() => {}}
+ onAttach={() => {}}
+ productsBrandId={productsBrandId}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+ }
+ const products = () =>
+ document.body.querySelector<HTMLButtonElement>(
+ 'button[aria-label="Insert products from your catalog"]',
+ );
+
+ it("leaves + Insert › Products out of a draft that isn't an online shop's", async () => {
+ await render(null);
+ expect(products()).toBeNull();
+ // The other tools are there.
+ expect(document.body.querySelector('button[aria-label="Add an HTML block"]')).not.toBeNull();
+ });
+
+ it("offers it on an online shop's draft, from its brand's catalog", async () => {
+ await render('b1');
+ await act(async () => products()!.click());
+ expect(document.body.textContent).toContain('Add products');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
index 4ed05c5dd..4e8939484 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_toolbar.tsx
@@ -21,6 +21,7 @@ import {
Paperclip,
Quote,
Rows3,
+ ShoppingBag,
Table2,
Trash2,
type LucideIcon,
@@ -41,6 +42,7 @@ import { formatNumber } from '@/lib/format';
import { safeImageSrc, safeLinkHref } from '@/lib/content/editor';
import { cn } from '@/lib/utils';
import { HtmlBlockDialog } from './_html-block';
+import { ProductBlockDialog } from './_product-block-dialog';
import { h1Positions } from './_one-h1';
/**
@@ -64,7 +66,9 @@ export function onEmptyLine(editor: Editor, state: EditorState): boolean {
* quote · table, image, Add HTML, attach a file · </> HTML, and the length counter against the page
* type's target. Inside a table it adds a row, a column, or removes the
* table. While the HTML view is open, only its own button works. On an empty
- * line, a small menu offers an HTML block, a table or an image there.
+ * line, a small menu offers an HTML block, a table or an image there. With
+ * `productsBrandId` (an online shop's draft), both offer products from its
+ * catalog too (shopping path, part 5).
*/
export function EditorToolbar({
editor,
@@ -74,6 +78,7 @@ export function EditorToolbar({
onToggleHtml,
onAttach,
linkRequest = 0,
+ productsBrandId = null,
}: {
editor: Editor;
target: number;
@@ -87,9 +92,11 @@ export function EditorToolbar({
* source, its claim selected (CE-045).
*/
linkRequest?: number;
+ /** The brand whose catalog + Insert › Products picks from; null hides it. */
+ productsBrandId?: string | null;
}) {
const t = useTranslations('contentEditor.editor.toolbar');
- const [dialog, setDialog] = useState<'link' | 'image' | 'htmlBlock' | null>(null);
+ const [dialog, setDialog] = useState<'link' | 'image' | 'htmlBlock' | 'products' | null>(null);
// Only a new request opens it: not the toolbar showing again.
const [linkAsked, setLinkAsked] = useState(linkRequest);
if (linkRequest !== linkAsked) {
@@ -190,6 +197,16 @@ export function EditorToolbar({
run: () => setDialog('htmlBlock'),
text: t('addHtml'),
},
+ ...(productsBrandId
+ ? [
+ {
+ key: 'products',
+ icon: ShoppingBag,
+ on: false,
+ run: () => setDialog('products'),
+ },
+ ]
+ : []),
{ key: 'attach', icon: Paperclip, on: false, run: onAttach },
],
];
@@ -270,6 +287,9 @@ export function EditorToolbar({
{ key: 'html', icon: Code2, run: () => setDialog('htmlBlock') },
{ key: 'table', icon: Table2, run: insertTable },
{ key: 'image', icon: ImagePlus, run: () => setDialog('image') },
+ ...(productsBrandId
+ ? [{ key: 'products', icon: ShoppingBag, run: () => setDialog('products') }]
+ : []),
] as const
).map((item) => (
<ToolButton key={item.key} label={t(`insert.${item.key}Hint`)} onClick={item.run}>
@@ -282,6 +302,15 @@ export function EditorToolbar({
{/* Mounted while open, so each opening starts from the selection. */}
{dialog === 'link' && <LinkDialog editor={editor} onClose={() => setDialog(null)} />}
{dialog === 'image' && <ImageDialog editor={editor} onClose={() => setDialog(null)} />}
+ {dialog === 'products' && productsBrandId && (
+ <ProductBlockDialog
+ brandId={productsBrandId}
+ onInsert={(code) =>
+ editor.chain().focus().insertContent({ type: 'htmlBlock', attrs: { code } }).run()
+ }
+ onClose={() => setDialog(null)}
+ />
+ )}
{dialog === 'htmlBlock' && (
<HtmlBlockDialog
initial=""
diff --git a/web/src/lib/actions/shopping-path.test.ts b/web/src/lib/actions/shopping-path.test.ts
index 39f93c8f3..99e7f0e68 100644
--- a/web/src/lib/actions/shopping-path.test.ts
+++ b/web/src/lib/actions/shopping-path.test.ts
@@ -10,9 +10,14 @@ interface Call {
op: string;
value?: unknown;
filters: [string, string, unknown][];
+ orders: [string, unknown][];
+ limit?: number;
}
+type Answer = { data: unknown; error: { message: string } | null };
let calls: Call[];
-let read: { data: unknown; error: { message: string } | null };
+let read: Answer;
+/** A read's answer by what it asks, where one table's reads differ; `read` otherwise. */
+let answer: ((call: Call) => Answer | undefined) | null;
let written: { data: unknown; error: { message: string } | null };
let session: { access_token: string } | null;
@@ -20,9 +25,9 @@ vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({
auth: { getSession: async () => ({ data: { session } }) },
from: (table: string) => {
- const call: Call = { table, op: 'select', filters: [] };
+ const call: Call = { table, op: 'select', filters: [], orders: [] };
calls.push(call);
- const result = () => (call.op === 'update' ? written : read);
+ const result = () => (call.op === 'update' ? written : (answer?.(call) ?? read));
const filter = (kind: string) => (col: string, v: unknown) => (
call.filters.push([kind, col, v]),
chain
@@ -32,8 +37,9 @@ vi.mock('@/lib/supabase/server', () => ({
eq: filter('eq'),
is: filter('is'),
ilike: filter('ilike'),
- order: () => chain,
- limit: () => chain,
+ in: filter('in'),
+ order: (col: string, opts: unknown) => (call.orders.push([col, opts]), chain),
+ limit: (n: number) => ((call.limit = n), chain),
update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),
maybeSingle: async () => result(),
then: (resolve: (r: unknown) => void) => resolve(result()),
@@ -46,8 +52,10 @@ vi.mock('@/lib/supabase/server', () => ({
const {
buildDraftShoppingPath,
getDraftShoppingPath,
+ getProductsForBlock,
saveDraftShoppingPath,
searchCatalogProducts,
+ searchProductsForBlock,
} = await import('./shopping-path');
const product = (id: string) => ({
@@ -83,6 +91,7 @@ const respond = (status: number, body: unknown) =>
beforeEach(() => {
calls = [];
read = { data: null, error: null };
+ answer = null;
written = { data: [{ id: DRAFT }], error: null };
session = { access_token: 'jwt' };
fetchMock.mockReset();
@@ -246,3 +255,198 @@ describe('searchCatalogProducts', () => {
await expect(searchCatalogProducts(BRAND, 'boots')).rejects.toThrow('boom');
});
});
+
+describe('getProductsForBlock', () => {
+ const id = (n: number) => `aaaaaaaa-0000-4000-8000-00000000000${n}`;
+ const [P1, P2, P3, P4, P5, P6] = [1, 2, 3, 4, 5, 6].map(id);
+ const row = (n: number): { id: string; title: string; url: string | null } => ({
+ id: id(n),
+ title: `Boot ${n}`,
+ url: `https://s.example/p/${n}`,
+ });
+ const variant = (price: number | null, availability: string | null, extra = {}) => ({
+ url: null,
+ price,
+ sale_price: null,
+ currency: 'USD',
+ availability,
+ ...extra,
+ });
+ const of = (call: Call) => call.filters.find(([, col]) => col === 'product_id')?.[2] as string;
+ /** The catalog: its live products, and each one's variants and pictures, read by its id. */
+ const catalog = ({
+ products = [] as ReturnType<typeof row>[],
+ variants = {} as Record<string, ReturnType<typeof variant>[]>,
+ images = {} as Record<string, { url: string }[]>,
+ errors = {} as Record<string, string>,
+ }) => {
+ answer = (call) => {
+ if (errors[call.table]) return { data: null, error: { message: errors[call.table] } };
+ if (call.table === 'catalog_products') return { data: products, error: null };
+ if (call.table === 'catalog_variants') return { data: variants[of(call)] ?? [], error: null };
+ if (call.table === 'catalog_images') return { data: images[of(call)] ?? [], error: null };
+ };
+ };
+
+ it("shows each one's cheapest variant in stock, however the feed spells it, its sale price first", async () => {
+ catalog({
+ products: [row(1), row(2), row(4)],
+ variants: {
+ // The cheapest sold out; "In Stock" is in stock.
+ [P1]: [variant(99, 'Out of Stock'), variant(189, 'in_stock'), variant(149, 'In Stock')],
+ // On sale, the cheapest it sells at.
+ [P4]: [
+ variant(120, 'in_stock'),
+ variant(130, 'LIMITED AVAILABILITY', { sale_price: 110, currency: 'EUR' }),
+ ],
+ // All sold out: no price, not in stock.
+ [P2]: [variant(50, 'sold out'), variant(40, 'preorder')],
+ },
+ images: { [P1]: [{ url: 'https://cdn.example/p1.jpg' }] },
+ });
+ expect(await getProductsForBlock(BRAND, [P1, P4, P2])).toEqual([
+ {
+ ...row(1),
+ image: 'https://cdn.example/p1.jpg',
+ price: 149,
+ salePrice: null,
+ currency: 'USD',
+ inStock: true,
+ },
+ { ...row(4), image: null, price: 130, salePrice: 110, currency: 'EUR', inStock: true },
+ { ...row(2), image: null, price: null, salePrice: null, currency: null, inStock: false },
+ ]);
+ });
+
+ it('reads each product on its own: its live variants, its own picture first', async () => {
+ catalog({ products: [row(1), row(2)] });
+ await getProductsForBlock(BRAND, [P1, P2]);
+ const variants = calls.filter((c) => c.table === 'catalog_variants');
+ expect(variants.map((c) => c.filters)).toEqual([
+ [
+ ['eq', 'product_id', P1],
+ ['is', 'removed_at', null],
+ ],
+ [
+ ['eq', 'product_id', P2],
+ ['is', 'removed_at', null],
+ ],
+ ]);
+ expect(variants.every((c) => c.limit === undefined)).toBe(true);
+ const images = calls.filter((c) => c.table === 'catalog_images');
+ expect(images.map((c) => c.filters)).toEqual([
+ [['eq', 'product_id', P1]],
+ [['eq', 'product_id', P2]],
+ ]);
+ expect(images[0].orders).toEqual([
+ ['variant_id', { ascending: true, nullsFirst: true }],
+ ['position', { ascending: true }],
+ ]);
+ expect(images[0].limit).toBe(1);
+ expect(calls.find((c) => c.table === 'catalog_products')!.filters).toEqual([
+ ['eq', 'brand_id', BRAND],
+ ['is', 'removed_at', null],
+ ['in', 'id', [P1, P2]],
+ ]);
+ });
+
+ it('keeps the order asked, leaves out one gone from the catalog, and reads four at most', async () => {
+ catalog({
+ // Read in another order; P3 is gone.
+ products: [row(5), row(1), row(2), row(4), row(6)],
+ variants: { [P1]: [variant(10, 'in_stock', { url: 'https://s.example/v/1' })] },
+ });
+ const read = await getProductsForBlock(BRAND, [P4, P3, P1, P1, 'nope', P2, P5, P6]);
+ expect(read.map((p) => p.id)).toEqual([P4, P1, P2]);
+ expect(calls.filter((c) => c.table === 'catalog_variants')).toHaveLength(4);
+ // A product without a page of its own links its variant's.
+ catalog({
+ products: [{ ...row(1), url: null }],
+ variants: { [P1]: [variant(10, 'in_stock', { url: 'https://s.example/v/1' })] },
+ });
+ expect((await getProductsForBlock(BRAND, [P1]))[0].url).toBe('https://s.example/v/1');
+ });
+
+ it('reads nothing for a brand or ids it cannot read, and fails on a failed read', async () => {
+ expect(await getProductsForBlock('nope', [P1])).toEqual([]);
+ expect(await getProductsForBlock(BRAND, ['nope'])).toEqual([]);
+ expect(calls).toHaveLength(0);
+ for (const table of ['catalog_products', 'catalog_variants', 'catalog_images']) {
+ catalog({ products: [row(1)], errors: { [table]: `${table} down` } });
+ await expect(getProductsForBlock(BRAND, [P1])).rejects.toThrow(`${table} down`);
+ }
+ });
+});
+
+describe('searchProductsForBlock', () => {
+ it('finds products by name, each with its price and stock, without reading pictures', async () => {
+ const P1 = 'aaaaaaaa-0000-4000-8000-000000000001';
+ const P2 = 'aaaaaaaa-0000-4000-8000-000000000002';
+ answer = (call) => {
+ if (call.table === 'catalog_products') {
+ return {
+ data: [
+ { id: P1, title: 'Boot 1', url: 'https://s.example/p/1' },
+ { id: P2, title: 'Boot 2', url: null },
+ ],
+ error: null,
+ };
+ }
+ const id = call.filters.find(([, col]) => col === 'product_id')?.[2];
+ return {
+ data:
+ id === P1
+ ? [
+ {
+ url: null,
+ price: 89,
+ sale_price: null,
+ currency: 'USD',
+ availability: 'In Stock',
+ },
+ ]
+ : [
+ {
+ url: null,
+ price: 59,
+ sale_price: null,
+ currency: 'USD',
+ availability: 'sold_out',
+ },
+ ],
+ error: null,
+ };
+ };
+ expect(await searchProductsForBlock(BRAND, 'boot')).toEqual([
+ {
+ id: P1,
+ title: 'Boot 1',
+ url: 'https://s.example/p/1',
+ image: null,
+ price: 89,
+ salePrice: null,
+ currency: 'USD',
+ inStock: true,
+ },
+ {
+ id: P2,
+ title: 'Boot 2',
+ url: null,
+ image: null,
+ price: null,
+ salePrice: null,
+ currency: null,
+ inStock: false,
+ },
+ ]);
+ expect(calls.some((c) => c.table === 'catalog_images')).toBe(false);
+ expect(calls[0].filters).toContainEqual(['ilike', 'title', '%boot%']);
+ });
+
+ it('waits for two letters, and fails on a failed read', async () => {
+ expect(await searchProductsForBlock(BRAND, 'b')).toEqual([]);
+ expect(calls).toHaveLength(0);
+ read = { data: null, error: { message: 'boom' } };
+ await expect(searchProductsForBlock(BRAND, 'boots')).rejects.toThrow('boom');
+ });
+});
diff --git a/web/src/lib/actions/shopping-path.ts b/web/src/lib/actions/shopping-path.ts
index c7ae5abf9..8f464cce4 100644
--- a/web/src/lib/actions/shopping-path.ts
+++ b/web/src/lib/actions/shopping-path.ts
@@ -4,6 +4,8 @@ import { z } from 'zod';
import { API_BASE_URL } from '@/config/api';
import { createClient } from '@/lib/supabase/server';
import { jsonbBytes } from '@/lib/content/draft-inputs';
+import { variantStock } from '@/lib/content/feed-match';
+import { MAX_BLOCK_PRODUCTS } from '@/lib/content/product-block';
import {
NO_PATH_REASONS,
shoppingChoicesSchema,
@@ -189,3 +191,133 @@ export async function searchCatalogProducts(
if (error) throw new Error(error.message);
return (data ?? []).map((p) => ({ id: p.id, title: p.title, url: p.url ?? null }));
}
+
+/** A catalog product as a product card shows it (product-block.ts). */
+export interface BlockProductRead {
+ id: string;
+ title: string;
+ url: string | null;
+ image: string | null;
+ price: number | null;
+ salePrice: number | null;
+ currency: string | null;
+ /** A live variant is in stock (feed-match.ts variantStock): only then does it go in a block. */
+ inStock: boolean;
+}
+
+type Client = Awaited<ReturnType<typeof createClient>>;
+interface VariantRead {
+ url: string | null;
+ price: number | null;
+ sale_price: number | null;
+ currency: string | null;
+ availability: string | null;
+}
+
+/**
+ * The variant a card shows, as the API's path picks it (shopping-path.js
+ * offerOf): the cheapest in stock, its sale price first; null with none in
+ * stock.
+ */
+function blockVariant(variants: VariantRead[]): VariantRead | null {
+ const inStock = variants.filter((v) => variantStock(v.availability) === 'in');
+ const sellsAt = (v: VariantRead) => v.sale_price ?? v.price ?? 0;
+ return (
+ inStock.filter((v) => v.price != null).sort((a, b) => sellsAt(a) - sellsAt(b))[0] ??
+ inStock[0] ??
+ null
+ );
+}
+
+/**
+ * A product's live variants and, with `image`, its picture, read for it
+ * alone, so no product's are cut off by another's: the product's own
+ * first picture, else a variant's first.
+ */
+async function readBlockDetails(supabase: Client, id: string, image: boolean) {
+ const [variants, images] = await Promise.all([
+ supabase
+ .from('catalog_variants')
+ .select('url, price, sale_price, currency, availability')
+ .eq('product_id', id)
+ .is('removed_at', null),
+ image
+ ? supabase
+ .from('catalog_images')
+ .select('url')
+ .eq('product_id', id)
+ .order('variant_id', { ascending: true, nullsFirst: true })
+ .order('position', { ascending: true })
+ .limit(1)
+ : null,
+ ]);
+ if (variants.error) throw new Error(variants.error.message);
+ if (images?.error) throw new Error(images.error.message);
+ return { variants: variants.data ?? [], image: images?.data?.[0]?.url ?? null };
+}
+
+/** A product as a card shows it, from its row and its details. */
+function blockProduct(
+ product: { id: string; title: string; url: string | null },
+ details: Awaited<ReturnType<typeof readBlockDetails>>,
+): BlockProductRead {
+ const variant = blockVariant(details.variants);
+ return {
+ id: product.id,
+ title: product.title,
+ url: product.url ?? details.variants.find((v) => v.url)?.url ?? null,
+ image: details.image,
+ price: variant?.price ?? null,
+ salePrice: variant?.sale_price ?? null,
+ currency: variant?.currency ?? null,
+ inStock: variant !== null,
+ };
+}
+
+/**
+ * The brand's catalog products by id, as a product card shows them: the
+ * product's page, its picture, and the price of its cheapest variant in
+ * stock (none, and `inStock` false, when none is). In the order asked,
+ * MAX_BLOCK_PRODUCTS at most; a product gone from the catalog is left out.
+ */
+export async function getProductsForBlock(
+ brandId: string,
+ ids: string[],
+): Promise<BlockProductRead[]> {
+ const wanted = [...new Set(ids)]
+ .filter((id) => guid.safeParse(id).success)
+ .slice(0, MAX_BLOCK_PRODUCTS);
+ if (!guid.safeParse(brandId).success || !wanted.length) return [];
+ const supabase = await createClient();
+ const [products, details] = await Promise.all([
+ supabase
+ .from('catalog_products')
+ .select('id, title, url')
+ .eq('brand_id', brandId)
+ .is('removed_at', null)
+ .in('id', wanted),
+ Promise.all(wanted.map((id) => readBlockDetails(supabase, id, true))),
+ ]);
+ if (products.error) throw new Error(products.error.message);
+ const byId = new Map((products.data ?? []).map((p) => [p.id, p]));
+ return wanted.flatMap((id, i) => {
+ const product = byId.get(id);
+ return product ? [blockProduct(product, details[i])] : [];
+ });
+}
+
+/**
+ * + Insert › Products' search: the brand's live catalog products whose
+ * title holds `query` (searchCatalogProducts), each with its price and
+ * stock as a card shows them; no picture.
+ */
+export async function searchProductsForBlock(
+ brandId: string,
+ query: string,
+): Promise<BlockProductRead[]> {
+ const hits = await searchCatalogProducts(brandId, query);
+ if (!hits.length) return [];
+ const supabase = await createClient();
+ const details = await Promise.all(hits.map((hit) => readBlockDetails(supabase, hit.id, false)));
+ return hits.map((hit, i) => blockProduct(hit, details[i]));
+}
diff --git a/web/src/lib/content/__fixtures__/product-block.json b/web/src/lib/content/__fixtures__/product-block.json
new file mode 100644
index 000000000..f232ce168
--- /dev/null
+++ b/web/src/lib/content/__fixtures__/product-block.json
@@ -0,0 +1,29 @@
+{
+ "products": [
+ {
+ "title": "Summit \"GTX\" Boot",
+ "url": "https://shop.example/products/p1?utm_source=feed&variant=2#reviews",
+ "image": "https://cdn.example/p1.jpg",
+ "price": "$189.00"
+ },
+ {
+ "title": "Trail Mid",
+ "url": "https://shop.example/products/p2",
+ "image": "http://cdn.example/p2.jpg",
+ "price": null
+ },
+ {
+ "title": "Ridge Low",
+ "url": "http://shop.example/products/p3",
+ "image": null,
+ "price": "$99.00"
+ },
+ {
+ "title": "No page",
+ "url": "javascript:alert(1)",
+ "image": null,
+ "price": null
+ }
+ ],
+ "html": "<div class=\"ansvisor-products\" style=\"display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px;margin:16px 0\"><a class=\"ansvisor-product\" href=\"https://shop.example/products/p1?variant=2\" style=\"display:block;border:1px solid #e5e5e5;border-radius:12px;padding:12px;text-decoration:none;color:inherit\"><img src=\"https://cdn.example/p1.jpg\" alt=\"Summit &quot;GTX&quot; Boot\" loading=\"lazy\" style=\"display:block;width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:8px\"><strong style=\"display:block;margin-top:8px\">Summit &quot;GTX&quot; Boot</strong> <span style=\"display:block;margin-top:4px\">$189.00</span></a>\n<a class=\"ansvisor-product\" href=\"https://shop.example/products/p2\" style=\"display:block;border:1px solid #e5e5e5;border-radius:12px;padding:12px;text-decoration:none;color:inherit\"><strong style=\"display:block;margin-top:8px\">Trail Mid</strong></a></div>"
+}
diff --git a/web/src/lib/content/feed-match.test.ts b/web/src/lib/content/feed-match.test.ts
index 60459b6f1..96f852bb4 100644
--- a/web/src/lib/content/feed-match.test.ts
+++ b/web/src/lib/content/feed-match.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { feedCheck, feedStock, pageKey, stockOnPage, type FeedVariant } from './feed-match';
+import {
+ feedCheck,
+ feedStock,
+ pageKey,
+ stockOnPage,
+ variantStock,
+ type FeedVariant,
+} from './feed-match';
/** A product page against its product feed (Quality spec §11, CE-053). */
@@ -73,6 +80,17 @@ describe('feedStock', () => {
});
});
+describe('variantStock', () => {
+ it("reads a variant's stock as the API does, whatever its case, spaces or hyphens", () => {
+ expect(variantStock('In Stock')).toBe('in');
+ expect(variantStock('Limited-Availability')).toBe('in');
+ expect(variantStock('SOLD OUT')).toBe('out');
+ expect(variantStock('preorder')).toBeNull();
+ expect(variantStock('')).toBeNull();
+ expect(variantStock(null)).toBeNull();
+ });
+});
+
describe('feedCheck', () => {
const texts = ['The Ridge 28 costs $129.', 'In stock.'];
diff --git a/web/src/lib/content/feed-match.ts b/web/src/lib/content/feed-match.ts
index 9026ea96b..be7c259e8 100644
--- a/web/src/lib/content/feed-match.ts
+++ b/web/src/lib/content/feed-match.ts
@@ -103,16 +103,22 @@ export function stockOnPage(
return found;
}
+/**
+ * A variant's stock, as the API's stock.js reads it ("In Stock" is
+ * "in_stock"): in, out, or none for pre-orders or none given.
+ */
+export function variantStock(availability: string | null | undefined): 'in' | 'out' | null {
+ const a = (availability ?? '').toLowerCase().replace(/[\s-]+/g, '_');
+ return ['in_stock', 'instock', 'available', 'limited_availability'].includes(a)
+ ? 'in'
+ : ['out_of_stock', 'outofstock', 'sold_out', 'discontinued'].includes(a)
+ ? 'out'
+ : null;
+}
+
/** The feed's stock: in when a variant is, out when every one is; none for pre-orders or none given. */
export function feedStock(variants: readonly FeedVariant[]): 'in' | 'out' | null {
- const read = variants.map((v) => {
- const a = (v.availability ?? '').toLowerCase().replace(/[\s-]+/g, '_');
- return ['in_stock', 'instock', 'available', 'limited_availability'].includes(a)
- ? 'in'
- : ['out_of_stock', 'outofstock', 'sold_out', 'discontinued'].includes(a)
- ? 'out'
- : null;
- });
+ const read = variants.map((v) => variantStock(v.availability));
if (read.includes('in')) return 'in';
return read.length && read.every((s) => s === 'out') ? 'out' : null;
}
diff --git a/web/src/lib/content/product-block.test.ts b/web/src/lib/content/product-block.test.ts
new file mode 100644
index 000000000..0b3899a61
--- /dev/null
+++ b/web/src/lib/content/product-block.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+import SAME_AS_THE_SERVER from './__fixtures__/product-block.json';
+import { MAX_BLOCK_PRODUCTS, productBlockHtml, productHref } from './product-block';
+
+/** Product card and product grid (shopping path, part 5). */
+
+describe('productBlockHtml', () => {
+ // server/src/lib/shopping-blocks.test.js reads the same products and expects the same markup.
+ it('writes picture, name and price, linked over https without tracking, escaped, and leaves out what has no page', () => {
+ expect(productBlockHtml(SAME_AS_THE_SERVER.products)).toBe(SAME_AS_THE_SERVER.html);
+ });
+
+ it('shows four at most, the first that have a page, and nothing with none', () => {
+ const many = [
+ { title: 'No page', url: 'http://s.example/p0', image: null, price: null },
+ ...Array.from({ length: 6 }, (_, i) => ({
+ title: `P${i + 1}`,
+ url: `https://s.example/p${i + 1}`,
+ image: null,
+ price: null,
+ })),
+ ];
+ const code = productBlockHtml(many);
+ expect(code.match(/class="ansvisor-product"/g)).toHaveLength(MAX_BLOCK_PRODUCTS);
+ expect(code).toContain('>P4</strong>');
+ expect(productBlockHtml([])).toBe('');
+ });
+});
+
+describe('productHref', () => {
+ it('links an https page without tracking or a hash, and nothing else', () => {
+ expect(productHref('https://shop.example/p?utm_medium=x&gclid=1&size=9#top')).toBe(
+ 'https://shop.example/p?size=9',
+ );
+ expect(productHref('http://shop.example/p')).toBeNull();
+ expect(productHref('javascript:alert(1)')).toBeNull();
+ expect(productHref('/p')).toBeNull();
+ expect(productHref(null)).toBeNull();
+ });
+});
diff --git a/web/src/lib/content/product-block.ts b/web/src/lib/content/product-block.ts
new file mode 100644
index 000000000..7fa0f801f
--- /dev/null
+++ b/web/src/lib/content/product-block.ts
@@ -0,0 +1,77 @@
+import { linkHref } from './link-targets';
+
+/**
+ * Product card and product grid (shopping path, part 5): one to four of the
+ * brand's catalog products as an HTML block in the page, each its picture,
+ * name and price, linked to its page. Plain HTML with inline styles; no
+ * words of its own, so it reads in any language. The server writes the same
+ * markup when the agent puts a grid in (server/src/lib/shopping-blocks.js):
+ * keep the two alike.
+ */
+
+/** Products a block shows at most. */
+export const MAX_BLOCK_PRODUCTS = 4;
+
+/** A product as a block shows it: `price` as it reads ("$189.00"), null without one. */
+export interface BlockProduct {
+ title: string;
+ url: string | null;
+ image: string | null;
+ price: string | null;
+}
+
+const ENTITIES: Record<string, string> = {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+};
+const escape = (text: string) => text.replace(/[&<>"']/g, (c) => ENTITIES[c]);
+
+/**
+ * The page a card links to: https only, without tracking parameters or a
+ * hash (link-targets.ts linkHref, as the server's); null for any other.
+ * On any site: a block put in by hand holds products the person picked
+ * from their own catalog, where the agent's grid holds only its shopping
+ * path's, checked on the brand's site (server/src/lib/shopping-links.js).
+ */
+export function productHref(url: string | null): string | null {
+ const href = url ? linkHref(url) : null;
+ return href?.startsWith('https:') ? href : null;
+}
+
+/** An https picture the card shows, or null. */
+function imageSrc(value: string | null): string | null {
+ if (!value) return null;
+ try {
+ const url = new URL(value);
+ return url.protocol === 'https:' ? url.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The block's HTML: a card for one product, a grid for more; '' with none to show. */
+export function productBlockHtml(products: BlockProduct[]): string {
+ const items = products
+ .map((p) => ({ ...p, url: productHref(p.url), image: imageSrc(p.image) }))
+ .filter((p) => p.url && p.title.trim())
+ .slice(0, MAX_BLOCK_PRODUCTS);
+ if (!items.length) return '';
+ // A space before the price and a line between cards: where the styles
+ // are dropped (a text export, a CMS's rich text), each product reads
+ // "Name $189.00" on its own.
+ const cards = items.map((p) => {
+ // The name as alt too: a text export reads an image by its alt (draft-export.ts), and
+ // an empty one would print "[Image]" there.
+ const image = p.image
+ ? `<img src="${escape(p.image)}" alt="${escape(p.title.trim())}" loading="lazy" style="display:block;width:100%;aspect-ratio:1/1;object-fit:cover;border-radius:8px">`
+ : '';
+ const price = p.price
+ ? ` <span style="display:block;margin-top:4px">${escape(p.price)}</span>`
+ : '';
+ return `<a class="ansvisor-product" href="${escape(p.url!)}" style="display:block;border:1px solid #e5e5e5;border-radius:12px;padding:12px;text-decoration:none;color:inherit">${image}<strong style="display:block;margin-top:8px">${escape(p.title.trim())}</strong>${price}</a>`;
+ });
+ return `<div class="ansvisor-products" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px;margin:16px 0">${cards.join('\n')}</div>`;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 39136b1f1..3d541f82f 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -868,6 +868,55 @@ export type Database = {
},
]
}
+ catalog_images: {
+ Row: {
+ brand_id: string
+ id: string
+ position: number
+ product_id: string
+ url: string
+ variant_id: string | null
+ }
+ Insert: {
+ brand_id: string
+ id?: string
+ position?: number
+ product_id: string
+ url: string
+ variant_id?: string | null
+ }
+ Update: {
+ brand_id?: string
+ id?: string
+ position?: number
+ product_id?: string
+ url?: string
+ variant_id?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "catalog_images_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "catalog_images_product_id_fkey"
+ columns: ["product_id"]
+ isOneToOne: false
+ referencedRelation: "catalog_products"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "catalog_images_variant_id_fkey"
+ columns: ["variant_id"]
+ isOneToOne: false
+ referencedRelation: "catalog_variants"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
catalog_products: {
Row: {
brand_id: string