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.
This commit is contained in:
1 parent
2bd7da0839
commit
14e2f73db9
4 files changed
+93
-61
No files matched your search
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import type { SnapshotProduct } from '@/lib/types';
|
||||
import SuggestionCarousel from './SuggestionCarousel';
|
||||
@@ -13,14 +13,14 @@ export default function AiConsultant({
|
||||
ordersEnabled,
|
||||
onAdd,
|
||||
resolveDish,
|
||||
suggestions,
|
||||
buildSuggestions,
|
||||
}: {
|
||||
slug: string;
|
||||
onClose: () => void;
|
||||
ordersEnabled: boolean;
|
||||
onAdd: (p: SnapshotProduct) => void;
|
||||
resolveDish: (name: string) => SnapshotProduct | undefined;
|
||||
suggestions: SnapshotProduct[];
|
||||
buildSuggestions: (seed: number, excludeIds?: string[]) => SnapshotProduct[];
|
||||
}) {
|
||||
const t = useTranslations('ai');
|
||||
const tm = useTranslations('menu');
|
||||
@@ -31,6 +31,15 @@ export default function AiConsultant({
|
||||
null,
|
||||
);
|
||||
const [error, setError] = useState(false);
|
||||
// New random sample per consultant open; excludes the dishes already shown above
|
||||
// (the answer's own recommendations) so the carousel never duplicates them.
|
||||
const [seed] = useState(() => Date.now());
|
||||
const suggestions = useMemo(() => {
|
||||
const shown = (answer?.recommendations ?? [])
|
||||
.map((r) => resolveDish(r.dish)?.id)
|
||||
.filter((id): id is string => !!id);
|
||||
return buildSuggestions(seed, shown);
|
||||
}, [buildSuggestions, seed, answer, resolveDish]);
|
||||
|
||||
async function ask() {
|
||||
if (!question.trim() || loading) return;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { MediaItem } from '@/lib/types';
|
||||
|
||||
// Renders the first media item as a thumbnail (image or muted video poster).
|
||||
@@ -12,7 +13,10 @@ export default function MediaThumb({
|
||||
alt: string;
|
||||
className?: string;
|
||||
}) {
|
||||
if (!media) {
|
||||
const [broken, setBroken] = useState(false);
|
||||
|
||||
// Fallback icon when there's no media OR the file 404s / fails to load.
|
||||
if (!media || broken) {
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center justify-center bg-gradient-to-br from-white/40 to-white/10 text-3xl ${className}`}
|
||||
@@ -32,9 +36,18 @@ export default function MediaThumb({
|
||||
loop
|
||||
playsInline
|
||||
preload="metadata"
|
||||
onError={() => setBroken(true)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
return <img src={media.path} alt={alt} className={`object-cover ${className}`} loading="lazy" />;
|
||||
return (
|
||||
<img
|
||||
src={media.path}
|
||||
alt={alt}
|
||||
className={`object-cover ${className}`}
|
||||
loading="lazy"
|
||||
onError={() => setBroken(true)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { MenuSnapshot, SnapshotProduct } from '@/lib/types';
|
||||
@@ -103,11 +103,12 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
|
||||
const cartCount = cart.reduce((n, l) => n + l.qty, 0);
|
||||
|
||||
// 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 }),
|
||||
// Suggestions are computed locally (no API/tokens) from the menu + cart, as a
|
||||
// RANDOM sample re-seeded per carousel open. Consumers pass their own seed (so
|
||||
// reopening reshuffles) and extra excludeIds (e.g. the consultant's own picks).
|
||||
const buildSuggestions = useCallback(
|
||||
(seed: number, excludeIds: string[] = []) =>
|
||||
getRecommendations(menu, cart.map((l) => l.product.id), { limit: 6, seed, excludeIds }),
|
||||
[menu, cart],
|
||||
);
|
||||
|
||||
@@ -378,7 +379,7 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
addToCart(p);
|
||||
}}
|
||||
resolveDish={resolveDish}
|
||||
suggestions={cartSuggestions}
|
||||
buildSuggestions={buildSuggestions}
|
||||
/>
|
||||
)}
|
||||
{orderOpen && (
|
||||
@@ -386,7 +387,7 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
slug={slug}
|
||||
cart={cart}
|
||||
setCart={setCart}
|
||||
suggestions={cartSuggestions}
|
||||
buildSuggestions={buildSuggestions}
|
||||
onAdd={addToCart}
|
||||
splitEnabled={splitEnabled}
|
||||
onPickSubaccount={joinExistingSubaccount}
|
||||
@@ -450,7 +451,7 @@ function OrderPanel({
|
||||
slug,
|
||||
cart,
|
||||
setCart,
|
||||
suggestions,
|
||||
buildSuggestions,
|
||||
onAdd,
|
||||
splitEnabled,
|
||||
onPickSubaccount,
|
||||
@@ -461,7 +462,7 @@ function OrderPanel({
|
||||
slug: string;
|
||||
cart: CartLine[];
|
||||
setCart: React.Dispatch<React.SetStateAction<CartLine[]>>;
|
||||
suggestions: SnapshotProduct[];
|
||||
buildSuggestions: (seed: number, excludeIds?: string[]) => SnapshotProduct[];
|
||||
onAdd: (p: SnapshotProduct) => void;
|
||||
splitEnabled: boolean;
|
||||
onPickSubaccount: (id: string, name: string | null, table: number) => void;
|
||||
@@ -475,6 +476,9 @@ function OrderPanel({
|
||||
const [generalNote, setGeneralNote] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
const [tableInSplit, setTableInSplit] = useState(false);
|
||||
// New random sample each time the cart sheet opens (this component remounts).
|
||||
const [seed] = useState(() => Date.now());
|
||||
const suggestions = useMemo(() => buildSuggestions(seed), [buildSuggestions, seed]);
|
||||
const [subaccounts, setSubaccounts] = useState<{ id: string; name: string | null }[]>([]);
|
||||
const [pickNew, setPickNew] = useState(false);
|
||||
const [newName, setNewName] = useState('');
|
||||
|
||||
+52
-46
@@ -1,13 +1,27 @@
|
||||
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).
|
||||
// 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 —
|
||||
@@ -60,8 +74,13 @@ export type CoOccurrenceSignal = (cartProductIds: string[]) => Map<string, numbe
|
||||
|
||||
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.
|
||||
// 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;
|
||||
};
|
||||
|
||||
@@ -71,53 +90,40 @@ export function getRecommendations(
|
||||
opts: RecoOptions = {},
|
||||
): SnapshotProduct[] {
|
||||
const limit = opts.limit ?? 6;
|
||||
const indexed = indexMenu(menu);
|
||||
const indexed = indexMenu(menu); // active products only
|
||||
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 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');
|
||||
|
||||
// 1) Complement rules → ordered list of categories we want to surface.
|
||||
const wanted: Category[] = [];
|
||||
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.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);
|
||||
if (hasFood && !cartCats.has('drink')) wanted.add('drink');
|
||||
if (hasFood && !cartCats.has('dessert')) wanted.add('dessert');
|
||||
if (onlyDrink) {
|
||||
wanted.add('starter');
|
||||
wanted.add('main');
|
||||
}
|
||||
};
|
||||
|
||||
// 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);
|
||||
}
|
||||
// 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);
|
||||
|
||||
let result = [...picked.values()];
|
||||
|
||||
// 3) Phase-2 blend (no-op today): float products with a co-occurrence signal.
|
||||
// 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));
|
||||
|
||||
Reference in new issue
Block a user