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.

fix(content): show a catalog product at one price everywhere: its best stock, then its lowest price there (#1663)

Cihan3904cce6066e
diff --git a/docs/guides/content-editor.mdx b/docs/guides/content-editor.mdx
index 4c1e93b4d..dfcc4a45c 100644
--- a/docs/guides/content-editor.mdx
+++ b/docs/guides/content-editor.mdx
@@ -155,7 +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.
+- **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 (in stock before low stock, then its cheapest variant there; a sale price when it's lower), 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/offer.js b/server/src/lib/catalog/offer.js
new file mode 100644
index 000000000..e97307855
--- /dev/null
+++ b/server/src/lib/catalog/offer.js
@@ -0,0 +1,46 @@
+import { isInStock, stockKey } from './stock.js';
+
+/**
+ * The price a catalog product is shown and linked with, read one way
+ * everywhere (#1607 follow-up): the path's offer (shopping-path.js
+ * offerOf), the agent's grid and what it's told (shopping-blocks.js,
+ * shopping-links.js), and the editor's card (web/src/lib/content/
+ * shopping-path.ts, the same rule): keep them alike.
+ */
+
+/** An amount above 0, or null: a price of 0 is none given. */
+const positive = (value) =>
+ value != null && Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : null;
+
+/**
+ * A price as a card reads it: the sale price when it's under the price, or
+ * when there's no price; else the price; null without either.
+ */
+export function priceAmount({ price, salePrice }) {
+ const regular = positive(price);
+ const sale = positive(salePrice);
+ if (regular == null) return sale;
+ return sale != null && sale < regular ? sale : regular;
+}
+
+/** In stock before low stock (limited availability): the better stock, the lower. */
+function inStockRank(availability) {
+ return stockKey(availability) === 'limited_availability' ? 1 : 0;
+}
+
+/**
+ * The variant in stock a product is shown with: the best stock, then the
+ * lowest price at it, one with no price last; null with none in stock.
+ * Variants as catalog_variants rows: `availability`, `price`, `sale_price`.
+ */
+export function bestInStock(variants) {
+ const amount = (v) => priceAmount({ price: v.price, salePrice: v.sale_price }) ?? Infinity;
+ return (
+ variants
+ .filter((v) => isInStock(v.availability))
+ .sort(
+ (a, b) =>
+ inStockRank(a.availability) - inStockRank(b.availability) || amount(a) - amount(b),
+ )[0] ?? null
+ );
+}
diff --git a/server/src/lib/catalog/offer.test.js b/server/src/lib/catalog/offer.test.js
new file mode 100644
index 000000000..f5cdf1466
--- /dev/null
+++ b/server/src/lib/catalog/offer.test.js
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import { bestInStock, priceAmount } from './offer.js';
+
+/** The price a catalog product is shown with, one rule everywhere (#1607 follow-up). */
+
+describe('priceAmount', () => {
+ it('takes the sale price under the price, else the price', () => {
+ expect(priceAmount({ price: 199, salePrice: 149 })).toBe(149);
+ expect(priceAmount({ price: 199, salePrice: 249 })).toBe(199);
+ expect(priceAmount({ price: '199.00', salePrice: null })).toBe(199);
+ });
+
+ it('keeps a sale price when there is no price, and reads 0 as none', () => {
+ expect(priceAmount({ price: null, salePrice: 149 })).toBe(149);
+ expect(priceAmount({ price: 0, salePrice: 149 })).toBe(149);
+ expect(priceAmount({ price: 199, salePrice: 0 })).toBe(199);
+ expect(priceAmount({ price: 0, salePrice: null })).toBeNull();
+ });
+});
+
+const variant = (price, availability, sale_price = null) => ({ price, sale_price, availability });
+
+describe('bestInStock', () => {
+ it('prefers in stock to low stock, whatever the price', () => {
+ const inStock = variant(199, 'in stock');
+ expect(bestInStock([variant(149, 'limited_availability'), inStock])).toBe(inStock);
+ });
+
+ it('takes the lowest price at the best stock, a sale counted, one with no price last', () => {
+ const onSale = variant(220, 'in_stock', 150);
+ expect(bestInStock([variant(null, 'in stock'), variant(180, 'In Stock'), onSale])).toBe(onSale);
+ const priced = variant(90, 'limited availability');
+ expect(bestInStock([variant(null, 'limited_availability'), priced])).toBe(priced);
+ });
+
+ it('is null with none in stock: pre-order, back-order and none given are not', () => {
+ expect(
+ bestInStock([variant(10, 'preorder'), variant(12, 'backorder'), variant(14, null)]),
+ ).toBeNull();
+ });
+});
diff --git a/server/src/lib/shopping-blocks.js b/server/src/lib/shopping-blocks.js
index 093af1072..9a1bb80f3 100644
--- a/server/src/lib/shopping-blocks.js
+++ b/server/src/lib/shopping-blocks.js
@@ -1,4 +1,5 @@
import * as cheerio from 'cheerio';
+import { priceAmount } from './catalog/offer.js';
import { isInStock } from './catalog/stock.js';
import { linkHref } from './content-links.js';
@@ -19,17 +20,12 @@ export const GRID_PAGE_TYPES = new Set(['best_of', 'buying_guide', 'comparison',
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.
+ * A product's price as the editor's card reads it ("$189.00"), by
+ * catalog/offer.js's priceAmount; 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;
+ const amount = priceAmount({ price, salePrice });
if (amount == null) return null;
try {
return currency
diff --git a/server/src/lib/shopping-blocks.test.js b/server/src/lib/shopping-blocks.test.js
index 377f403cc..fa4c9ff5e 100644
--- a/server/src/lib/shopping-blocks.test.js
+++ b/server/src/lib/shopping-blocks.test.js
@@ -41,12 +41,13 @@ describe('priceText', () => {
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', () => {
+ it('reads a price of 0 as none, a sale price not under the price as no sale, and a sale price alone as 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();
+ expect(priceText({ price: null, salePrice: 129, currency: 'USD' })).toBe('$129.00');
+ expect(priceText({ price: null, salePrice: null, currency: 'USD' })).toBeNull();
});
});
diff --git a/server/src/lib/shopping-links.js b/server/src/lib/shopping-links.js
index 66a4ba41d..ac8116354 100644
--- a/server/src/lib/shopping-links.js
+++ b/server/src/lib/shopping-links.js
@@ -2,6 +2,7 @@ import * as cheerio from 'cheerio';
import supabaseAdmin from '../config/supabase.js';
import { onBrandDomain } from './audit/host.js';
import { brandSite, leafName, singular } from './catalog/category-pages.js';
+import { priceAmount } from './catalog/offer.js';
import { isInStock, stockKey } from './catalog/stock.js';
import { linkHref, linkKey } from './content-links.js';
import { foldLetters } from './letters.js';
@@ -69,20 +70,9 @@ const CURRENCY_SIGNS = {
TRY: '₺',
};
-/** A product's price, the sale price first; null with none. */
-function amountOf(product) {
- // 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". */
function offerLine(product) {
- const amount = amountOf(product);
+ const amount = priceAmount(product);
const price =
amount == null ? null : `${amount.toFixed(2)}${product.currency ? ` ${product.currency}` : ''}`;
return [price, stockWords(product.availability)].filter(Boolean).join(', ');
@@ -90,7 +80,7 @@ function offerLine(product) {
/** The ways a product's price may be written: 189, 189.00, $189, $189.00 ("$1,299" reads as 1299). */
function priceSpellings(product) {
- const amount = amountOf(product);
+ const amount = priceAmount(product);
if (amount == null) return [];
const values = [...new Set([amount.toFixed(2), String(amount)])];
const signs = [
@@ -221,7 +211,7 @@ async function withOffer(db, brandId, products, draftId) {
const rank = STOCK_ORDER.indexOf(stockWords(v.availability));
return rank === -1 ? STOCK_ORDER.length : rank;
};
- const amount = (v) => amountOf({ price: v.price, salePrice: v.sale_price }) ?? Infinity;
+ const amount = (v) => priceAmount({ price: v.price, salePrice: v.sale_price }) ?? Infinity;
const best = new Map();
for (const variant of data) {
const held = best.get(variant.product_id);
diff --git a/server/src/lib/shopping-path.js b/server/src/lib/shopping-path.js
index b114458f6..ecbcb3241 100644
--- a/server/src/lib/shopping-path.js
+++ b/server/src/lib/shopping-path.js
@@ -1,6 +1,7 @@
import { z } from 'zod';
import supabaseAdmin from '../config/supabase.js';
import { categoryPages, leafName, wordsOf } from './catalog/category-pages.js';
+import { bestInStock } from './catalog/offer.js';
import { isInStock, stockKey } from './catalog/stock.js';
import { selectInChunks } from './chunked-in.js';
import { siteTypeOf } from './content-page-types.js';
@@ -159,8 +160,9 @@ export function refuses(issue) {
/**
* A product as the path offers it, or why it can't be: a variant in stock
- * that Merchant Center doesn't refuse, its lowest price, and the issues
- * Merchant Center reports for it that don't refuse it.
+ * that Merchant Center doesn't refuse, the best stock then the lowest price
+ * (catalog/offer.js bestInStock), and the issues Merchant Center reports
+ * for it that don't refuse it.
*/
export function offerOf(product) {
const url = product.url ?? product.variants.find((v) => v.url)?.url ?? null;
@@ -174,10 +176,7 @@ export function offerOf(product) {
? 'refused'
: null;
if (reason) return { reason };
- const cheapest = usable
- .filter((v) => v.price != null)
- .sort((a, b) => (a.sale_price ?? a.price) - (b.sale_price ?? b.price))[0];
- const variant = cheapest ?? usable[0];
+ const variant = bestInStock(usable);
const issues = [
...new Map(
variant.issues.map((i) => [
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 dfc1f1cae..e15c2a607 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
@@ -128,12 +128,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.
+ // A price of 0 is none; a sale price is one only under the price, or alone.
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();
+ expect(priceText({ price: null, salePrice: 129, currency: 'USD' })).toBe('$129.00');
});
});
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 53f5892d2..2c6ec27b3 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
@@ -18,6 +18,7 @@ import {
choicesOf,
leftOutReason,
placementOf,
+ priceAmount,
withAdded,
withLocked,
withRemoved,
@@ -27,17 +28,9 @@ import {
} from '@/lib/content/shopping-path';
import { pagePath } from '@/lib/content/overlap';
-/** 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.
- */
+/** A product's price as the catalog has it, in its currency (priceAmount); null without one. */
export function priceText(product: Pick<ShoppingProduct, 'price' | 'salePrice' | 'currency'>) {
- const price = positive(product.price);
- const sale = positive(product.salePrice);
- const amount = sale != null && price != null && sale < price ? sale : price;
+ const amount = priceAmount(product);
if (amount == null) return null;
try {
return product.currency
diff --git a/web/src/lib/actions/shopping-path.test.ts b/web/src/lib/actions/shopping-path.test.ts
index 42c5e8c5b..67850e7fd 100644
--- a/web/src/lib/actions/shopping-path.test.ts
+++ b/web/src/lib/actions/shopping-path.test.ts
@@ -291,16 +291,18 @@ describe('getProductsForBlock', () => {
};
};
- it("shows each one's cheapest variant in stock, however the feed spells it, its sale price first", async () => {
+ it("shows each one's best stock, then its cheapest variant there, however the feed spells it, a sale price counted", 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.
+ // In stock before low stock, though the low-stock one sells for less
+ // (as the agent's grid picks it, #1607); on sale, the cheapest it sells at.
[P4]: [
- variant(120, 'in_stock'),
variant(130, 'LIMITED AVAILABILITY', { sale_price: 110, currency: 'EUR' }),
+ variant(125, 'in_stock'),
+ variant(140, 'in_stock', { sale_price: 115, currency: 'EUR' }),
],
// All sold out: no price, not in stock.
[P2]: [variant(50, 'sold out'), variant(40, 'preorder')],
@@ -316,7 +318,7 @@ describe('getProductsForBlock', () => {
currency: 'USD',
inStock: true,
},
- { ...row(4), image: null, price: 130, salePrice: 110, currency: 'EUR', inStock: true },
+ { ...row(4), image: null, price: 140, salePrice: 115, currency: 'EUR', inStock: true },
{ ...row(2), image: null, price: null, salePrice: null, currency: null, inStock: false },
]);
});
diff --git a/web/src/lib/actions/shopping-path.ts b/web/src/lib/actions/shopping-path.ts
index fe56799c7..ad015bdd9 100644
--- a/web/src/lib/actions/shopping-path.ts
+++ b/web/src/lib/actions/shopping-path.ts
@@ -15,6 +15,7 @@ import type {
import { readAllRpcRows } from '@/lib/supabase/rpc-pages';
import {
NO_PATH_REASONS,
+ bestInStock,
shoppingChoicesSchema,
shoppingPathSchema,
type NoPathReason,
@@ -218,28 +219,6 @@ export interface BlockProductRead {
}
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
@@ -273,7 +252,8 @@ function blockProduct(
product: { id: string; title: string; url: string | null },
details: Awaited<ReturnType<typeof readBlockDetails>>,
): BlockProductRead {
- const variant = blockVariant(details.variants);
+ // As the API's path and the agent's grid pick it: the best stock, then the lowest price.
+ const variant = bestInStock(details.variants);
return {
id: product.id,
title: product.title,
diff --git a/web/src/lib/content/shopping-path.test.ts b/web/src/lib/content/shopping-path.test.ts
index 4664c5b6b..bd6884a6b 100644
--- a/web/src/lib/content/shopping-path.test.ts
+++ b/web/src/lib/content/shopping-path.test.ts
@@ -9,6 +9,8 @@ import {
withLocked,
withRemoved,
type ShoppingPath,
+ bestInStock,
+ priceAmount,
} from './shopping-path';
/** A draft's shopping path as the Brief tab holds it (shopping path, 00351). */
@@ -140,3 +142,31 @@ describe('shoppingPathSchema', () => {
]);
});
});
+
+describe('priceAmount', () => {
+ it('takes the sale price under the price, the sale price alone, and reads 0 as none', () => {
+ expect(priceAmount({ price: 199, salePrice: 149 })).toBe(149);
+ expect(priceAmount({ price: 199, salePrice: 249 })).toBe(199);
+ expect(priceAmount({ price: null, salePrice: 149 })).toBe(149);
+ expect(priceAmount({ price: 0, salePrice: 0 })).toBeNull();
+ });
+});
+
+describe('bestInStock', () => {
+ const variant = (price: number | null, availability: string | null, sale_price = null) => ({
+ price,
+ sale_price,
+ availability,
+ });
+
+ it('prefers in stock to low stock, as the agent’s grid does (#1607)', () => {
+ const inStock = variant(199, 'in stock');
+ expect(bestInStock([variant(149, 'limited availability'), inStock])).toBe(inStock);
+ });
+
+ it('takes the lowest price at the best stock, one with no price last, none when none is in stock', () => {
+ const cheap = variant(120, 'In Stock');
+ expect(bestInStock([variant(null, 'in_stock'), variant(180, 'in stock'), cheap])).toBe(cheap);
+ expect(bestInStock([variant(10, 'preorder'), variant(12, null)])).toBeNull();
+ });
+});
diff --git a/web/src/lib/content/shopping-path.ts b/web/src/lib/content/shopping-path.ts
index 185f59e4a..b8c4cc469 100644
--- a/web/src/lib/content/shopping-path.ts
+++ b/web/src/lib/content/shopping-path.ts
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { variantStock } from '@/lib/content/feed-match';
import type { SiteType } from '@/lib/content/page-types';
/**
@@ -40,6 +41,55 @@ export function shoppingPathFits(siteType: SiteType, pageType: string | null): b
return siteType === 'ecommerce' && pageType != null && Object.hasOwn(PRODUCTS_FOR, pageType);
}
+/** An amount above 0, or null: a price of 0 is none given. */
+const positive = (value: number | null | undefined) =>
+ value != null && Number.isFinite(value) && value > 0 ? value : null;
+
+/**
+ * A price as a card reads it: the sale price when it's under the price, or
+ * when there's no price; else the price; null without either. The API's
+ * rule (server/src/lib/catalog/offer.js priceAmount): change both together.
+ */
+export function priceAmount({
+ price,
+ salePrice,
+}: {
+ price: number | null | undefined;
+ salePrice: number | null | undefined;
+}): number | null {
+ const regular = positive(price);
+ const sale = positive(salePrice);
+ if (regular == null) return sale;
+ return sale != null && sale < regular ? sale : regular;
+}
+
+/** In stock before low stock (limited availability): the better stock, the lower. */
+function inStockRank(availability: string | null): number {
+ return (availability ?? '').toLowerCase().replace(/[\s-]+/g, '_') === 'limited_availability'
+ ? 1
+ : 0;
+}
+
+/**
+ * The variant in stock a product is shown with: the best stock, then the
+ * lowest price at it, one with no price last; null with none in stock. The
+ * API's rule (server/src/lib/catalog/offer.js bestInStock), so a card put in
+ * by hand shows the price the agent's grid would.
+ */
+export function bestInStock<
+ V extends { availability: string | null; price: number | null; sale_price: number | null },
+>(variants: readonly V[]): V | null {
+ const amount = (v: V) => priceAmount({ price: v.price, salePrice: v.sale_price }) ?? Infinity;
+ return (
+ variants
+ .filter((v) => variantStock(v.availability) === 'in')
+ .sort(
+ (a, b) =>
+ inStockRank(a.availability) - inStockRank(b.availability) || amount(a) - amount(b),
+ )[0] ?? null
+ );
+}
+
/** Why a product is left out, as the API says it: sold out, refused, no link, gone from the catalog. */
export const LEFT_OUT_REASONS = ['sold_out', 'refused', 'no_link', 'gone'] as const;
export type LeftOutReason = (typeof LEFT_OUT_REASONS)[number];