Files
smartmenu-collina/src/lib/recommendations.ts
T
Jorem Juárez 14e2f73db9 Carousel: random sample (reshuffles per open), dedup vs consultant, broken-image fallback
1) getRecommendations is now a RANDOM sample of the whole active menu, lightly
   refined by complement rules (a +0.25 nudge toward wanted categories that can't
   beat a strong random draw — variety dominates, all sections surface). New
   opts.seed re-randomizes per open; opts.excludeIds filters extra ids. Signature
   and the CoOccurrence Phase-2 seam are unchanged. Never returns empty unless the
   whole menu is excluded.
2) PublicMenu passes a buildSuggestions(seed, excludeIds) callback instead of a
   memoized list. OrderPanel and AiConsultant each seed on mount (Date.now()), so
   reopening reshuffles. The consultant excludes the dishes it already showed above
   (answer.recommendations resolved to ids) → no more carousel/answer duplicates
   (fixes the Combo Aguacate dup).
3) MediaThumb adds onError on <img>/<video> → a 404/broken file falls back to the
   🍽️ icon, same as missing media.

Verified: build passes; reopening yields a different sample (same seed stable);
sample spans all sections; consultant picks + cart items excluded; never empty.
2026-06-15 21:36:37 -06:00

134 lines
5.9 KiB
TypeScript

import type { MenuSnapshot, SnapshotProduct } from './types';
// ─────────────────────────────────────────────────────────────────────────────
// Local recommendation engine (no API, no tokens, no latency). The carousel only
// ever calls getRecommendations(menu, cartIds, opts). Today: a RANDOM sample of
// the whole menu, lightly refined by complement rules (variety dominates). Pass
// opts.seed to re-randomize per carousel open. Phase 2 can blend a real
// market-basket CO-OCCURRENCE signal WITHOUT touching the carousel — just pass
// `opts.coOccurrence` (see the seam below).
// ─────────────────────────────────────────────────────────────────────────────
// Small seeded PRNG (mulberry32) so a given seed yields a stable shuffle within a
// render but a fresh one each time the seed changes (i.e. each carousel open).
function rng(seed: number): () => number {
let a = (seed >>> 0) || 1;
return () => {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
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;
// Re-randomize per carousel open. Same seed → same sample within a render.
seed?: number;
// Extra product ids to exclude (e.g. dishes the AI consultant already showed
// above the carousel) — on top of the cart items, which are always excluded.
excludeIds?: string[];
// When provided, co-occurrence scores are blended on top (products with a
// signal float to the front). Today: undefined → random + light rules.
coOccurrence?: CoOccurrenceSignal;
};
export function getRecommendations(
menu: MenuSnapshot,
cartProductIds: string[],
opts: RecoOptions = {},
): SnapshotProduct[] {
const limit = opts.limit ?? 6;
const indexed = indexMenu(menu); // active products only
if (indexed.length === 0) return [];
const exclude = new Set<string>([...cartProductIds, ...(opts.excludeIds ?? [])]);
const eligible = indexed.filter((i) => !exclude.has(i.product.id));
if (eligible.length === 0) return [];
// Complement rules → categories to gently favor (variety still dominates).
const cartCats = new Set(
indexed.filter((i) => cartProductIds.includes(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');
const wanted = new Set<Category>();
if (cartProductIds.length > 0) {
if (hasFood && !cartCats.has('drink')) wanted.add('drink');
if (hasFood && !cartCats.has('dessert')) wanted.add('dessert');
if (onlyDrink) {
wanted.add('starter');
wanted.add('main');
}
}
// Random sample of the WHOLE menu (high variety), with a small nudge toward
// complement categories — the nudge (+0.25) can't beat a strong random draw, so
// it only refines/orders lightly without collapsing variety.
const rand = rng(opts.seed ?? 1);
let result = eligible
.map((i) => ({ p: i.product, s: rand() + (wanted.has(i.category) ? 0.25 : 0) }))
.sort((a, b) => b.s - a.s)
.map((x) => x.p);
// 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);
}