Replace AI pairings with a deterministic local recommendation engine

The cart/consultant suggestion carousel no longer depends on Claude-generated
pairings. It now computes suggestions locally and instantly from the menu
structure + cart — always available, zero API calls, zero cost, no failure point.

- New lib/recommendations.ts: getRecommendations(menu, cartItemIds, opts) — a pure
  function. Section-complement rules (main+no drink -> drinks; food+no dessert ->
  desserts; drink-only -> food/snacks) classified by flexible keywords (es/en,
  whole-word match so 'te'/tea doesn't match 'fuertes'), then featured fill
  (unrepresented sections first, then price desc). Excludes cart items + inactive;
  empty cart -> featured so the carousel is never empty.
- Phase-2 seam: opts.coOccurrence?(cartIds) => Map<productId, score> lets a future
  market-basket signal blend in WITHOUT changing the carousel — it still only calls
  getRecommendations(menu, cart). Documented where it plugs in.
- PublicMenu computes cartSuggestions via getRecommendations (was the pairings map);
  carousel shows whenever there's >=1 suggestion and orders are enabled, in both the
  cart sheet and the consultant. SuggestionCarousel reused unchanged.
- Removed the Claude generation: publish no longer calls generatePairings and the
  'Generar sugerencias' checkbox is gone; deleted lib/pairings.ts. Restaurant.pairings
  column kept (unused, no migration churn).

i18n parity kept. Glassmorphism/mobile-first/safe-areas untouched. Cart, consultant,
SSE, split all intact.

Verified (build passes, no Anthropic import in the carousel/publish path):
1 fresh publish (nothing generated) -> carousel shows; 2 main+no drink -> drinks
surface first; 3 cart items never suggested; 4 empty cart -> featured; 5 zero
Anthropic calls in the carousel flow; 6 carousel in both cart and consultant.
This commit is contained in:
Jorem Juárez committed 2026-06-15 20:47:20 -06:00
1 parent b30430a1ea
commit 0d924e36ef
5 files changed
+140 -122

No files matched your search

+4 -19
View File
@@ -1,9 +1,6 @@
import { NextResponse } from 'next/server';
import { requireEditor } from '@/lib/guard';
import { publishVersion, buildSnapshot } from '@/lib/menu';
import { generatePairings } from '@/lib/pairings';
export const maxDuration = 60;
import { publishVersion } from '@/lib/menu';
export async function POST(req: Request, { params }: { params: { slug: string } }) {
const guard = await requireEditor(params.slug);
@@ -11,7 +8,6 @@ export async function POST(req: Request, { params }: { params: { slug: string }
const body = await req.json().catch(() => null);
const versionName = String(body?.versionName ?? '').trim();
const generateSuggestions = body?.generateSuggestions === true;
if (!versionName) return NextResponse.json({ error: 'invalid' }, { status: 400 });
const version = await publishVersion(
@@ -20,18 +16,7 @@ export async function POST(req: Request, { params }: { params: { slug: string }
guard.restaurant.username,
);
// Optional: regenerate cart pairings from the just-published menu. Never let an
// AI failure break publishing.
let suggestions = false;
if (generateSuggestions) {
try {
const snapshot = await buildSnapshot(guard.restaurant.id);
const result = await generatePairings(guard.restaurant.id, snapshot);
suggestions = result !== null;
} catch (err) {
console.error('publish pairings error', err);
}
}
return NextResponse.json({ ...version, suggestions });
// Cart suggestions are now computed locally and deterministically at runtime
// (lib/recommendations.ts) — no AI generation at publish time.
return NextResponse.json(version);
}
+1 -16
View File
@@ -16,7 +16,6 @@ export default function PublishModal({
const t = useTranslations('editor');
const tc = useTranslations('common');
const [name, setName] = useState('');
const [suggestions, setSuggestions] = useState(false);
const [publishing, setPublishing] = useState(false);
const [success, setSuccess] = useState<string | null>(null);
@@ -26,7 +25,7 @@ export default function PublishModal({
try {
const res = await api<{ versionName: string }>(slug, '/publish', {
method: 'POST',
json: { versionName: name.trim(), generateSuggestions: suggestions },
json: { versionName: name.trim() },
});
setSuccess(res.versionName);
onPublished(res.versionName);
@@ -62,20 +61,6 @@ export default function PublishModal({
className="glass-soft rounded-2xl px-4 py-3 outline-none"
/>
</label>
<label className="glass-soft flex items-start gap-2 rounded-2xl px-3 py-2.5 text-sm">
<input
type="checkbox"
checked={suggestions}
onChange={(e) => setSuggestions(e.target.checked)}
className="mt-0.5"
/>
<span>
<span className="font-medium">✨ {t('generateSuggestions')}</span>
<span className="block text-xs text-[var(--text)]/55">
{t('generateSuggestionsHint')}
</span>
</span>
</label>
<div className="flex gap-2">
<button onClick={onClose} className="glass-pill flex-1 rounded-2xl py-3 text-sm">
{tc('cancel')}
+8 -15
View File
@@ -13,6 +13,7 @@ import Gallery from './Gallery';
import AiConsultant from './AiConsultant';
import SuggestionCarousel from './SuggestionCarousel';
import SplitPanel, { type SplitSession } from './SplitPanel';
import { getRecommendations } from '@/lib/recommendations';
type ViewMode = 'cards' | 'list';
@@ -75,7 +76,6 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
}
return map;
}, [sections]);
const pairings = menu.restaurant.pairings ?? {};
const ordersEnabled = menu.restaurant.ordersEnabled;
const splitEnabled = ordersEnabled && !!menu.restaurant.splitEnabled;
@@ -106,20 +106,13 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
const cartCount = cart.reduce((n, l) => n + l.qty, 0);
// Contextual pairings for what's in the cart (excluding items already added).
// Shared by the cart sheet and the consultant carousel — computed once here.
const cartSuggestions = useMemo(() => {
const inCart = new Set(cart.map((l) => l.product.id));
const ids = new Set<string>();
for (const line of cart) {
for (const id of pairings[line.product.id] ?? []) {
if (!inCart.has(id)) ids.add(id);
}
}
return Array.from(ids)
.map((id) => productIndex.get(id))
.filter((p): p is SnapshotProduct => !!p && p.isActive);
}, [cart, pairings, productIndex]);
// Suggestions are computed locally and deterministically (no API/tokens) from
// the menu structure + cart, so the carousel is always available and instant.
// Shared by the cart sheet and the consultant carousel.
const cartSuggestions = useMemo(
() => getRecommendations(menu, cart.map((l) => l.product.id), { limit: 6 }),
[menu, cart],
);
const resolveDish = (dishName: string) => nameIndex.get(normName(dishName));
-72
View File
@@ -1,72 +0,0 @@
import { prisma } from './prisma';
import { getAnthropic, HAIKU_MODEL } from './anthropic';
import { parseLenientJson } from './json';
import { pickText } from './text';
import type { MenuSnapshot } from './types';
export type Pairings = Record<string, string[]>;
// Generate cart pairings (complements) for a published snapshot with one cheap
// Haiku call, then store them on the restaurant. Runtime reads these — zero
// tokens per diner. Best-effort: returns null on failure so publish never breaks.
export async function generatePairings(
restaurantId: string,
snapshot: MenuSnapshot,
): Promise<Pairings | null> {
const locale = snapshot.restaurant.defaultLocale;
// Compact catalog: id, name, section, diet tags. (Macros omitted — irrelevant.)
const lines: string[] = [];
const ids = new Set<string>();
for (const section of snapshot.sections) {
const sname = pickText(section.name, locale);
for (const p of section.products) {
if (!p.isActive) continue;
ids.add(p.id);
lines.push(
`${p.id} | ${pickText(p.name, locale)} | ${sname}` +
(p.dietTags.length ? ` | ${p.dietTags.join(', ')}` : ''),
);
}
}
if (ids.size < 2) return {};
const system =
`You suggest food/drink COMPLEMENTS for a restaurant menu (pairings that go well ` +
`together — a drink with a main, a dessert, a side). Focus on complements, NOT upsell. ` +
`Each line below is "id | name | section | dietTags". For each dish, list the ids of OTHER ` +
`dishes that complement it (0 to 5; only genuine pairings, omit if none). Use ONLY the ids ` +
`provided; never invent ids; never pair a dish with itself. ` +
`Reply ONLY with JSON: {"pairings": { "<id>": ["<id>", ...] }}.\n\nMENU:\n` +
lines.join('\n');
try {
const client = getAnthropic();
const msg = await client.messages.create({
model: HAIKU_MODEL,
max_tokens: 2000,
system: [{ type: 'text', text: system }],
messages: [{ role: 'user', content: 'Generate the pairings JSON.' }],
});
const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}';
const parsed = parseLenientJson<{ pairings?: Record<string, unknown> }>(text);
const rawMap = parsed?.pairings;
if (!rawMap || typeof rawMap !== 'object') return null;
// Validate: keys/values must be real ids; drop self-references; cap at 5.
const clean: Pairings = {};
for (const [key, val] of Object.entries(rawMap)) {
if (!ids.has(key) || !Array.isArray(val)) continue;
const list = val
.filter((v): v is string => typeof v === 'string' && ids.has(v) && v !== key)
.slice(0, 5);
if (list.length) clean[key] = Array.from(new Set(list));
}
await prisma.restaurant.update({ where: { id: restaurantId }, data: { pairings: clean } });
return clean;
} catch (err) {
console.error('generatePairings error', err);
return null;
}
}
+127
View File
@@ -0,0 +1,127 @@
import type { MenuSnapshot, SnapshotProduct } from './types';
// ─────────────────────────────────────────────────────────────────────────────
// Deterministic, local recommendation engine (no API, no tokens, no latency).
// The carousel only ever calls getRecommendations(menu, cartIds). Today it uses
// section-based complement rules + featured fill. Phase 2 can blend a real
// market-basket CO-OCCURRENCE signal ("who ordered X also ordered Y") WITHOUT
// touching the carousel — just pass `opts.coOccurrence` (see the seam below).
// ─────────────────────────────────────────────────────────────────────────────
type Category = 'drink' | 'dessert' | 'starter' | 'main';
// Keyword sets (es + en + common variants) to classify a section flexibly —
// never hardcode one restaurant's exact section names.
const KEYWORDS: Record<Exclude<Category, 'main'>, string[]> = {
drink: [
'bebida', 'bebidas', 'drink', 'drinks', 'beverage', 'smoothie', 'jugo', 'juice',
'cafe', 'café', 'coffee', 'agua', 'water', 'coctel', 'cóctel', 'cocktail', 'cerveza',
'beer', 'vino', 'wine', 'refresco', 'soda', 'te', 'té', 'tea', 'latte', 'malteada', 'shake',
],
dessert: ['postre', 'postres', 'dessert', 'desserts', 'dulce', 'sweet', 'helado', 'ice cream'],
starter: [
'entrada', 'entradas', 'starter', 'starters', 'appetizer', 'appetizers', 'snack', 'snacks',
'botana', 'botanas', 'aperitivo', 'side', 'guarnicion', 'guarnición',
],
};
function classifySection(name: string): Category {
const n = name.toLowerCase();
// Whole-word match so short keywords (e.g. "te"/tea) don't match inside other
// words (e.g. "fuertes"); multi-word keywords ("ice cream") use substring.
const tokens = n.split(/[^a-záéíóúñ]+/i).filter(Boolean);
const matches = (k: string) => (k.includes(' ') ? n.includes(k) : tokens.includes(k));
for (const cat of ['drink', 'dessert', 'starter'] as const) {
if (KEYWORDS[cat].some(matches)) return cat;
}
return 'main'; // anything else is treated as a main/food section
}
type Indexed = { product: SnapshotProduct; category: Category; order: number };
// Flatten active products with their section category + a stable global order.
function indexMenu(menu: MenuSnapshot): Indexed[] {
const out: Indexed[] = [];
let order = 0;
const sections = [...menu.sections].sort((a, b) => a.order - b.order);
for (const s of sections) {
const category = classifySection(`${s.name.es ?? ''} ${s.name.en ?? ''}`);
for (const p of s.products) {
if (!p.isActive) continue;
out.push({ product: p, category, order: order++ });
}
}
return out;
}
// Phase-2 seam: a function that, given the cart, returns a score per productId
// (e.g. derived from historical co-occurrence). Higher = more recommended.
export type CoOccurrenceSignal = (cartProductIds: string[]) => Map<string, number>;
export type RecoOptions = {
limit?: number;
// When provided, co-occurrence scores are blended on top of the rule order
// (products with a signal float to the front). Today: undefined → pure rules.
coOccurrence?: CoOccurrenceSignal;
};
export function getRecommendations(
menu: MenuSnapshot,
cartProductIds: string[],
opts: RecoOptions = {},
): SnapshotProduct[] {
const limit = opts.limit ?? 6;
const indexed = indexMenu(menu);
if (indexed.length === 0) return [];
const inCart = new Set(cartProductIds);
const cartCats = new Set(indexed.filter((i) => inCart.has(i.product.id)).map((i) => i.category));
const hasFood = cartCats.has('main') || cartCats.has('starter');
const onlyDrink = cartProductIds.length > 0 && cartCats.size > 0 && [...cartCats].every((c) => c === 'drink');
// 1) Complement rules → ordered list of categories we want to surface.
const wanted: Category[] = [];
if (cartProductIds.length > 0) {
if (hasFood && !cartCats.has('drink')) wanted.push('drink');
if (hasFood && !cartCats.has('dessert')) wanted.push('dessert');
if (onlyDrink) wanted.push('starter', 'main');
}
const eligible = indexed.filter((i) => !inCart.has(i.product.id));
const picked = new Map<string, SnapshotProduct>();
const addFrom = (pool: Indexed[]) => {
for (const i of pool) {
if (picked.size >= limit) break;
if (!picked.has(i.product.id)) picked.set(i.product.id, i.product);
}
};
// Complements first, in rule order (by menu order within each category).
for (const cat of wanted) {
addFrom(eligible.filter((i) => i.category === cat).sort((a, b) => a.order - b.order));
}
// 2) Featured fill: prefer sections not represented in the cart, then price desc
// (a stable, data-free proxy for "popular" until Phase 2 supplies real data).
if (picked.size < limit) {
const featured = [...eligible].sort((a, b) => {
const aNew = cartCats.has(a.category) ? 1 : 0;
const bNew = cartCats.has(b.category) ? 1 : 0;
if (aNew !== bNew) return aNew - bNew;
if (b.product.price !== a.product.price) return b.product.price - a.product.price;
return a.order - b.order;
});
addFrom(featured);
}
let result = [...picked.values()];
// 3) Phase-2 blend (no-op today): float products with a co-occurrence signal.
if (opts.coOccurrence) {
const scores = opts.coOccurrence(cartProductIds);
result = result.sort((a, b) => (scores.get(b.id) ?? 0) - (scores.get(a.id) ?? 0));
}
return result.slice(0, limit);
}