Orders persistence/expiration, cart pairings, and brand header
BLOCK 1 — Orders persistence + expiration:
- New GET /api/[slug]/orders loads active orders from PostgreSQL on mount, so the
dashboard survives reloads (SSE only carries live events); it also prunes
completed orders older than the retention window on read (no cron)
- Restaurant.orderRetentionHours (default 24, migration 0007) + editor control in
the Orders tab; settings PATCH accepts it
BLOCK 2 — Smart cart pairings (precomputed, zero tokens at runtime):
- Restaurant.pairings JSON (migration 0008) stores { productId: [productId] }
- Optional 'Generate smart suggestions' checkbox in the publish modal; on publish,
one cheap Haiku call analyzes the snapshot and stores validated complements
(lib/pairings.ts, reuses parseLenientJson). AI failure never breaks publishing
- pairings read live and exposed via the public menu; cart shows an auto-rotating,
swipeable SuggestionCarousel of complements for what's in the cart (excluding
items already added), each with Add — only when orders are on and pairings exist
BLOCK 3 — Brand header:
- Restaurant.bannerImage, profileImage, socialLinks (migration 0009)
- New editor Brand tab: upload banner + circular logo (reuses /upload), social
links with common-platform suggestions and basic URL validation; saved via settings
- Public BrandHeader: full-bleed banner (edge-to-edge behind the island, safe-area
aware), circular logo avatar, name, and clickable social icons (lucide-react).
Graceful fallbacks (palette gradient banner, initial avatar) — no broken images.
Images are language-independent
All read live (no republish needed). i18n es/en at parity; glassmorphism,
mobile-first and safe areas preserved. Adds lucide-react.
Verified: build passes; 9 migrations apply; orders persist + prune on read;
publish survives missing API key; pairings + brand exposed via /menu.
This commit is contained in:
1 parent
57a9b191bd
commit
244adaee30
25 files changed
+749
-17
No files matched your search
@@ -28,6 +28,7 @@
|
||||
"generalNotePlaceholder": "General order note (optional)",
|
||||
"total": "Total",
|
||||
"confirmOrder": "Confirm order",
|
||||
"suggestions": "You might also like",
|
||||
"yourOrder": "Your order",
|
||||
"empty": "No dishes in this section yet.",
|
||||
"waiterCalled": "The waiter is on the way",
|
||||
@@ -58,6 +59,7 @@
|
||||
"delete": "Delete",
|
||||
"catalog": "Catalog",
|
||||
"palette": "Palette",
|
||||
"brand": "Brand",
|
||||
"orders": "Orders",
|
||||
"qr": "QR",
|
||||
"publishedVersion": "Published version",
|
||||
@@ -88,6 +90,11 @@
|
||||
"uploadMedia": "Upload photo or video",
|
||||
"ordersDisabled": "Order taking is disabled",
|
||||
"enableOrders": "Enable order taking",
|
||||
"orderRetention": "Keep completed orders for",
|
||||
"orderRetentionHint": "Older completed orders are removed automatically.",
|
||||
"hours": "hours",
|
||||
"generateSuggestions": "Generate smart cart suggestions",
|
||||
"generateSuggestionsHint": "AI analyzes the menu on publish and precomputes pairings (just once).",
|
||||
"completeOrder": "Complete order",
|
||||
"itemNote": "Dish note",
|
||||
"generalNote": "General note",
|
||||
@@ -104,6 +111,16 @@
|
||||
"showMacrosDisclaimer": "Macros will stop showing to the public, but they are not deleted.",
|
||||
"sectionMacros": "Macros in this section"
|
||||
},
|
||||
"brand": {
|
||||
"banner": "Banner image",
|
||||
"bannerEmpty": "No banner",
|
||||
"uploadBanner": "Upload banner",
|
||||
"logo": "Logo / profile photo",
|
||||
"uploadLogo": "Upload logo",
|
||||
"social": "Social links",
|
||||
"platform": "Platform",
|
||||
"addLink": "Add link"
|
||||
},
|
||||
"qr": {
|
||||
"templates": "Templates",
|
||||
"customize": "Customize",
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"generalNotePlaceholder": "Nota general de la orden (opcional)",
|
||||
"total": "Total",
|
||||
"confirmOrder": "Confirmar orden",
|
||||
"suggestions": "También te puede gustar",
|
||||
"yourOrder": "Tu pedido",
|
||||
"empty": "Aún no hay platillos en esta sección.",
|
||||
"waiterCalled": "El mesero va en camino",
|
||||
@@ -58,6 +59,7 @@
|
||||
"delete": "Eliminar",
|
||||
"catalog": "Catálogo",
|
||||
"palette": "Paleta",
|
||||
"brand": "Marca",
|
||||
"orders": "Órdenes",
|
||||
"qr": "QR",
|
||||
"publishedVersion": "Versión publicada",
|
||||
@@ -88,6 +90,11 @@
|
||||
"uploadMedia": "Subir foto o video",
|
||||
"ordersDisabled": "La toma de órdenes está desactivada",
|
||||
"enableOrders": "Habilitar toma de órdenes",
|
||||
"orderRetention": "Conservar órdenes completadas",
|
||||
"orderRetentionHint": "Las órdenes completadas más viejas se eliminan automáticamente.",
|
||||
"hours": "horas",
|
||||
"generateSuggestions": "Generar sugerencias inteligentes para el carrito",
|
||||
"generateSuggestionsHint": "La IA analiza el menú al publicar y precalcula maridajes (una sola vez).",
|
||||
"completeOrder": "Completar orden",
|
||||
"itemNote": "Nota del platillo",
|
||||
"generalNote": "Nota general",
|
||||
@@ -104,6 +111,16 @@
|
||||
"showMacrosDisclaimer": "Las macros dejarán de mostrarse al público, pero no se borran.",
|
||||
"sectionMacros": "Macros en esta sección"
|
||||
},
|
||||
"brand": {
|
||||
"banner": "Imagen de banner",
|
||||
"bannerEmpty": "Sin banner",
|
||||
"uploadBanner": "Subir banner",
|
||||
"logo": "Logo / foto de perfil",
|
||||
"uploadLogo": "Subir logo",
|
||||
"social": "Redes sociales",
|
||||
"platform": "Plataforma",
|
||||
"addLink": "Agregar enlace"
|
||||
},
|
||||
"qr": {
|
||||
"templates": "Plantillas",
|
||||
"customize": "Personalizar",
|
||||
|
||||
Generated
+10
@@ -13,6 +13,7 @@
|
||||
"bcryptjs": "^2.4.3",
|
||||
"clsx": "^2.1.1",
|
||||
"jose": "^5.9.6",
|
||||
"lucide-react": "^0.469.0",
|
||||
"next": "14.2.21",
|
||||
"next-intl": "^3.26.3",
|
||||
"qr-code-styling": "^1.9.2",
|
||||
@@ -1748,6 +1749,15 @@
|
||||
"loose-envify": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/lucide-react": {
|
||||
"version": "0.469.0",
|
||||
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.469.0.tgz",
|
||||
"integrity": "sha512-28vvUnnKQ/dBwiCQtwJw7QauYnE7yd2Cyp4tTTJpvglX4EMpbflcdBgrgToX2j71B3YvugK/NH3BGUk+E/p/Fw==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/merge2": {
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"bcryptjs": "^2.4.3",
|
||||
"clsx": "^2.1.1",
|
||||
"jose": "^5.9.6",
|
||||
"lucide-react": "^0.469.0",
|
||||
"next": "14.2.21",
|
||||
"next-intl": "^3.26.3",
|
||||
"qr-code-styling": "^1.9.2",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Restaurant" ADD COLUMN "orderRetentionHours" INTEGER NOT NULL DEFAULT 24;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Restaurant" ADD COLUMN "pairings" JSONB NOT NULL DEFAULT '{}';
|
||||
@@ -0,0 +1,4 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "Restaurant" ADD COLUMN "bannerImage" TEXT;
|
||||
ALTER TABLE "Restaurant" ADD COLUMN "profileImage" TEXT;
|
||||
ALTER TABLE "Restaurant" ADD COLUMN "socialLinks" JSONB NOT NULL DEFAULT '[]';
|
||||
@@ -20,7 +20,12 @@ model Restaurant {
|
||||
palette Json @default("{}")
|
||||
qrConfig Json @default("{}") // artistic QR styling (qr-code-styling config)
|
||||
ordersEnabled Boolean @default(false)
|
||||
orderRetentionHours Int @default(24) // completed orders older than this are pruned on read
|
||||
showMacros Boolean @default(false) // when false, the public menu hides all macro layers
|
||||
pairings Json @default("{}") // precomputed cart suggestions { productId: [productId] }
|
||||
bannerImage String? // wide brand banner (uploaded)
|
||||
profileImage String? // circular logo/avatar (uploaded)
|
||||
socialLinks Json @default("[]") // [{ platform, url }]
|
||||
|
||||
defaultLocale String @default("es")
|
||||
active Boolean @default(true)
|
||||
|
||||
@@ -41,6 +41,9 @@ export default async function EditorPage({
|
||||
defaultLocale: restaurant.defaultLocale as 'es' | 'en',
|
||||
palette: (restaurant.palette as Palette) ?? {},
|
||||
qrConfig: (restaurant.qrConfig as QrConfig) ?? {},
|
||||
bannerImage: restaurant.bannerImage,
|
||||
profileImage: restaurant.profileImage,
|
||||
socialLinks: (restaurant.socialLinks as { platform: string; url: string }[]) ?? [],
|
||||
publishedVersionName: restaurant.publishedVersion?.versionName ?? null,
|
||||
sections: restaurant.sections.map((s) => ({
|
||||
id: s.id,
|
||||
|
||||
+16
-3
@@ -16,6 +16,15 @@ async function getPublishedMenu(slug: string): Promise<MenuSnapshot | null> {
|
||||
},
|
||||
});
|
||||
if (!restaurant || !restaurant.active) return null;
|
||||
// Brand + pairings come from the live restaurant (not the snapshot) so they
|
||||
// update without republishing.
|
||||
const brand = {
|
||||
pairings: (restaurant.pairings as Record<string, string[]>) ?? {},
|
||||
bannerImage: restaurant.bannerImage,
|
||||
profileImage: restaurant.profileImage,
|
||||
socialLinks: (restaurant.socialLinks as { platform: string; url: string }[]) ?? [],
|
||||
};
|
||||
|
||||
if (!restaurant.publishedVersion) {
|
||||
// No version published yet — show an empty shell using live restaurant data.
|
||||
return {
|
||||
@@ -26,15 +35,19 @@ async function getPublishedMenu(slug: string): Promise<MenuSnapshot | null> {
|
||||
ordersEnabled: restaurant.ordersEnabled,
|
||||
defaultLocale: restaurant.defaultLocale as 'es' | 'en',
|
||||
showMacros: restaurant.showMacros,
|
||||
...brand,
|
||||
},
|
||||
sections: [],
|
||||
};
|
||||
}
|
||||
const snapshot = restaurant.publishedVersion.snapshot as unknown as MenuSnapshot;
|
||||
// showMacros (global + per-section) is read live (not from the snapshot) so
|
||||
// toggling takes effect immediately without republishing — old snapshots without
|
||||
// the flags default to off (global) / on (section).
|
||||
// showMacros (global + per-section) and brand/pairings are read live (not from the
|
||||
// snapshot) so toggling/editing takes effect immediately without republishing.
|
||||
snapshot.restaurant.showMacros = restaurant.showMacros;
|
||||
snapshot.restaurant.pairings = brand.pairings;
|
||||
snapshot.restaurant.bannerImage = brand.bannerImage;
|
||||
snapshot.restaurant.profileImage = brand.profileImage;
|
||||
snapshot.restaurant.socialLinks = brand.socialLinks;
|
||||
applyLiveSectionMacros(snapshot, restaurant.sections);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
@@ -21,8 +21,14 @@ export async function GET(_req: Request, { params }: { params: { slug: string }
|
||||
return NextResponse.json({ error: 'not_published' }, { status: 404 });
|
||||
}
|
||||
const snapshot = restaurant.publishedVersion.snapshot as unknown as MenuSnapshot;
|
||||
// Read showMacros (global + per-section) live so toggles apply without republishing.
|
||||
// Read showMacros (global + per-section), pairings and brand live so changes
|
||||
// apply without republishing.
|
||||
snapshot.restaurant.showMacros = restaurant.showMacros;
|
||||
snapshot.restaurant.pairings = (restaurant.pairings as Record<string, string[]>) ?? {};
|
||||
snapshot.restaurant.bannerImage = restaurant.bannerImage;
|
||||
snapshot.restaurant.profileImage = restaurant.profileImage;
|
||||
snapshot.restaurant.socialLinks =
|
||||
(restaurant.socialLinks as { platform: string; url: string }[]) ?? [];
|
||||
applyLiveSectionMacros(snapshot, restaurant.sections);
|
||||
return NextResponse.json(snapshot);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// Loads active orders for the dashboard on mount (so a reload doesn't lose them).
|
||||
// Also prunes completed orders older than the restaurant's retention window —
|
||||
// done on read instead of via cron (simpler and robust).
|
||||
export async function GET(_req: Request, { params }: { params: { slug: string } }) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const hours = guard.restaurant.orderRetentionHours ?? 24;
|
||||
const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000);
|
||||
await prisma.order.deleteMany({
|
||||
where: {
|
||||
restaurantId: guard.restaurant.id,
|
||||
status: 'completed',
|
||||
completedAt: { lt: cutoff },
|
||||
},
|
||||
});
|
||||
|
||||
const orders = await prisma.order.findMany({
|
||||
where: { restaurantId: guard.restaurant.id, status: 'active' },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return NextResponse.json({ orders, orderRetentionHours: hours });
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
import { publishVersion } from '@/lib/menu';
|
||||
import { publishVersion, buildSnapshot } from '@/lib/menu';
|
||||
import { generatePairings } from '@/lib/pairings';
|
||||
|
||||
export const maxDuration = 60;
|
||||
|
||||
export async function POST(req: Request, { params }: { params: { slug: string } }) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
@@ -8,6 +11,7 @@ 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(
|
||||
@@ -15,5 +19,19 @@ export async function POST(req: Request, { params }: { params: { slug: string }
|
||||
versionName,
|
||||
guard.restaurant.username,
|
||||
);
|
||||
return NextResponse.json(version);
|
||||
|
||||
// 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 });
|
||||
}
|
||||
@@ -2,18 +2,54 @@ import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
// Toggle ordersEnabled, defaultLocale, etc.
|
||||
type SocialLink = { platform: string; url: string };
|
||||
|
||||
function sanitizeSocialLinks(value: unknown): SocialLink[] | undefined {
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
return value
|
||||
.map((v) => v as Record<string, unknown>)
|
||||
.filter((v) => typeof v.platform === 'string' && typeof v.url === 'string')
|
||||
.map((v) => ({
|
||||
platform: (v.platform as string).slice(0, 40),
|
||||
url: (v.url as string).trim().slice(0, 300),
|
||||
}))
|
||||
.filter((v) => v.platform && v.url)
|
||||
.slice(0, 20);
|
||||
}
|
||||
|
||||
// Update restaurant settings: orders toggle, retention, locale, macros, and brand.
|
||||
export async function PATCH(req: Request, { params }: { params: { slug: string } }) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const data: { ordersEnabled?: boolean; defaultLocale?: string; showMacros?: boolean } = {};
|
||||
const data: {
|
||||
ordersEnabled?: boolean;
|
||||
defaultLocale?: string;
|
||||
showMacros?: boolean;
|
||||
orderRetentionHours?: number;
|
||||
bannerImage?: string | null;
|
||||
profileImage?: string | null;
|
||||
socialLinks?: object;
|
||||
} = {};
|
||||
|
||||
if (typeof body?.ordersEnabled === 'boolean') data.ordersEnabled = body.ordersEnabled;
|
||||
if (typeof body?.showMacros === 'boolean') data.showMacros = body.showMacros;
|
||||
if (body?.defaultLocale === 'es' || body?.defaultLocale === 'en') {
|
||||
data.defaultLocale = body.defaultLocale;
|
||||
}
|
||||
if (Number.isFinite(Number(body?.orderRetentionHours))) {
|
||||
// Clamp to a sane range: 1 hour .. 30 days.
|
||||
data.orderRetentionHours = Math.max(1, Math.min(720, Math.round(Number(body.orderRetentionHours))));
|
||||
}
|
||||
if (body?.bannerImage === null || typeof body?.bannerImage === 'string') {
|
||||
data.bannerImage = body.bannerImage || null;
|
||||
}
|
||||
if (body?.profileImage === null || typeof body?.profileImage === 'string') {
|
||||
data.profileImage = body.profileImage || null;
|
||||
}
|
||||
const social = sanitizeSocialLinks(body?.socialLinks);
|
||||
if (social) data.socialLinks = social;
|
||||
|
||||
await prisma.restaurant.update({ where: { id: guard.restaurant.id }, data });
|
||||
return NextResponse.json({ ok: true });
|
||||
|
||||
@@ -118,4 +118,8 @@ body {
|
||||
.safe-pb-tabbar {
|
||||
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 0.5rem);
|
||||
}
|
||||
/* absolute overlay on the brand banner, kept clear of the island */
|
||||
.safe-abs-top {
|
||||
top: calc(env(safe-area-inset-top, 0px) + 0.5rem);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import type { SocialLink } from './types';
|
||||
import { api } from './api';
|
||||
|
||||
const PLATFORM_SUGGESTIONS = [
|
||||
'Instagram',
|
||||
'Facebook',
|
||||
'TikTok',
|
||||
'WhatsApp',
|
||||
'Sitio web',
|
||||
'X',
|
||||
'YouTube',
|
||||
];
|
||||
|
||||
function isValidUrl(url: string): boolean {
|
||||
if (!url.trim()) return false;
|
||||
try {
|
||||
const u = new URL(url.startsWith('http') ? url : `https://${url}`);
|
||||
return !!u.hostname.includes('.');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export default function BrandTab({
|
||||
slug,
|
||||
initialBanner,
|
||||
initialProfile,
|
||||
initialSocial,
|
||||
}: {
|
||||
slug: string;
|
||||
initialBanner: string | null;
|
||||
initialProfile: string | null;
|
||||
initialSocial: SocialLink[];
|
||||
}) {
|
||||
const t = useTranslations('brand');
|
||||
const tc = useTranslations('common');
|
||||
const [banner, setBanner] = useState<string | null>(initialBanner);
|
||||
const [profile, setProfile] = useState<string | null>(initialProfile);
|
||||
const [links, setLinks] = useState<SocialLink[]>(initialSocial);
|
||||
const [uploading, setUploading] = useState<'banner' | 'profile' | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
async function upload(kind: 'banner' | 'profile', file: File | null) {
|
||||
if (!file) return;
|
||||
setUploading(kind);
|
||||
setSaved(false);
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const res = await api<{ path: string }>(slug, '/upload', { method: 'POST', body: form });
|
||||
if (kind === 'banner') setBanner(res.path);
|
||||
else setProfile(res.path);
|
||||
} finally {
|
||||
setUploading(null);
|
||||
}
|
||||
}
|
||||
|
||||
function addLink(platform = '') {
|
||||
setLinks((prev) => [...prev, { platform, url: '' }]);
|
||||
setSaved(false);
|
||||
}
|
||||
function updateLink(i: number, patch: Partial<SocialLink>) {
|
||||
setLinks((prev) => prev.map((l, idx) => (idx === i ? { ...l, ...patch } : l)));
|
||||
setSaved(false);
|
||||
}
|
||||
function removeLink(i: number) {
|
||||
setLinks((prev) => prev.filter((_, idx) => idx !== i));
|
||||
setSaved(false);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setSaving(true);
|
||||
try {
|
||||
const cleanLinks = links.filter((l) => l.platform.trim() && isValidUrl(l.url));
|
||||
await api(slug, '/settings', {
|
||||
method: 'PATCH',
|
||||
json: { bannerImage: banner, profileImage: profile, socialLinks: cleanLinks },
|
||||
});
|
||||
setSaved(true);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Banner */}
|
||||
<section className="glass rounded-3xl p-4">
|
||||
<h3 className="display mb-2 text-sm font-semibold">{t('banner')}</h3>
|
||||
<div className="relative h-28 w-full overflow-hidden rounded-2xl bg-white/30">
|
||||
{banner ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={banner} alt="" className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-sm text-[var(--text)]/50">
|
||||
{t('bannerEmpty')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-2 flex gap-2">
|
||||
<label className="glass-pill cursor-pointer rounded-full px-4 py-2 text-sm font-medium">
|
||||
{uploading === 'banner' ? '…' : t('uploadBanner')}
|
||||
<input type="file" accept="image/*" hidden onChange={(e) => upload('banner', e.target.files?.[0] ?? null)} />
|
||||
</label>
|
||||
{banner && (
|
||||
<button onClick={() => setBanner(null)} className="rounded-full px-3 py-2 text-sm text-red-500/80">
|
||||
{tc('delete')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Profile / logo */}
|
||||
<section className="glass rounded-3xl p-4">
|
||||
<h3 className="display mb-2 text-sm font-semibold">{t('logo')}</h3>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-20 w-20 shrink-0 overflow-hidden rounded-full bg-white/30">
|
||||
{profile ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={profile} alt="" className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-2xl">🍽️</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<label className="glass-pill cursor-pointer rounded-full px-4 py-2 text-sm font-medium">
|
||||
{uploading === 'profile' ? '…' : t('uploadLogo')}
|
||||
<input type="file" accept="image/*" hidden onChange={(e) => upload('profile', e.target.files?.[0] ?? null)} />
|
||||
</label>
|
||||
{profile && (
|
||||
<button onClick={() => setProfile(null)} className="text-left text-sm text-red-500/80">
|
||||
{tc('delete')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Social links */}
|
||||
<section className="glass rounded-3xl p-4">
|
||||
<h3 className="display mb-2 text-sm font-semibold">{t('social')}</h3>
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{PLATFORM_SUGGESTIONS.map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => addLink(p)}
|
||||
className="glass-soft rounded-full px-3 py-1 text-xs"
|
||||
>
|
||||
+ {p}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
{links.map((l, i) => {
|
||||
const invalid = l.url.length > 0 && !isValidUrl(l.url);
|
||||
return (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<input
|
||||
value={l.platform}
|
||||
onChange={(e) => updateLink(i, { platform: e.target.value })}
|
||||
placeholder={t('platform')}
|
||||
className="glass-soft w-28 rounded-xl px-3 py-2 text-sm outline-none"
|
||||
/>
|
||||
<input
|
||||
value={l.url}
|
||||
onChange={(e) => updateLink(i, { url: e.target.value })}
|
||||
placeholder="https://…"
|
||||
className={`glass-soft min-w-0 flex-1 rounded-xl px-3 py-2 text-sm outline-none ${
|
||||
invalid ? 'ring-1 ring-red-400' : ''
|
||||
}`}
|
||||
/>
|
||||
<button onClick={() => removeLink(i)} className="px-1 text-red-500/70" aria-label={tc('delete')}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<button onClick={() => addLink()} className="glass-pill rounded-2xl py-2 text-sm font-medium">
|
||||
+ {t('addLink')}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<button
|
||||
onClick={save}
|
||||
disabled={saving}
|
||||
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white disabled:opacity-50"
|
||||
>
|
||||
{saved ? '✓ ' : ''}
|
||||
{tc('save')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,11 +6,12 @@ import type { EditorData, EditorSection } from './types';
|
||||
import LanguageSwitch from '@/components/LanguageSwitch';
|
||||
import CatalogTab from './CatalogTab';
|
||||
import PaletteTab from './PaletteTab';
|
||||
import BrandTab from './BrandTab';
|
||||
import OrdersTab from './OrdersTab';
|
||||
import QrTab from './QrTab';
|
||||
import PublishModal from './PublishModal';
|
||||
|
||||
type Tab = 'catalog' | 'palette' | 'orders' | 'qr';
|
||||
type Tab = 'catalog' | 'palette' | 'brand' | 'orders' | 'qr';
|
||||
|
||||
export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: string }) {
|
||||
const t = useTranslations('editor');
|
||||
@@ -24,6 +25,7 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s
|
||||
const tabs: { id: Tab; label: string; icon: string }[] = [
|
||||
{ id: 'catalog', label: t('catalog'), icon: '📋' },
|
||||
{ id: 'palette', label: t('palette'), icon: '🎨' },
|
||||
{ id: 'brand', label: t('brand'), icon: '🏷️' },
|
||||
{ id: 'orders', label: t('orders'), icon: '🔔' },
|
||||
{ id: 'qr', label: t('qr'), icon: '🔳' },
|
||||
];
|
||||
@@ -53,6 +55,14 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s
|
||||
/>
|
||||
)}
|
||||
{tab === 'palette' && <PaletteTab slug={data.slug} initialPalette={data.palette} />}
|
||||
{tab === 'brand' && (
|
||||
<BrandTab
|
||||
slug={data.slug}
|
||||
initialBanner={data.bannerImage}
|
||||
initialProfile={data.profileImage}
|
||||
initialSocial={data.socialLinks}
|
||||
/>
|
||||
)}
|
||||
{tab === 'orders' && (
|
||||
<OrdersTab
|
||||
slug={data.slug}
|
||||
|
||||
@@ -35,9 +35,32 @@ export default function OrdersTab({
|
||||
const locale = useLocale() as Locale;
|
||||
const [orders, setOrders] = useState<Order[]>([]);
|
||||
const [waiterCalls, setWaiterCalls] = useState<WaiterCall[]>([]);
|
||||
const [retention, setRetention] = useState(24);
|
||||
const [now, setNow] = useState(() => 0);
|
||||
const esRef = useRef<EventSource | null>(null);
|
||||
|
||||
// Load active orders from the DB on mount so a reload doesn't lose them
|
||||
// (the SSE stream only carries live events). Also pulls the retention setting.
|
||||
useEffect(() => {
|
||||
if (!ordersEnabled) return;
|
||||
let cancelled = false;
|
||||
api<{ orders: Order[]; orderRetentionHours: number }>(slug, '/orders')
|
||||
.then((res) => {
|
||||
if (cancelled) return;
|
||||
setOrders(res.orders);
|
||||
setRetention(res.orderRetentionHours);
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [slug, ordersEnabled]);
|
||||
|
||||
async function saveRetention(hours: number) {
|
||||
setRetention(hours);
|
||||
await api(slug, '/settings', { method: 'PATCH', json: { orderRetentionHours: hours } });
|
||||
}
|
||||
|
||||
// Flat list of dishes for the "add dish" search.
|
||||
const menuOptions = useMemo<MenuOption[]>(
|
||||
() =>
|
||||
@@ -114,6 +137,27 @@ export default function OrdersTab({
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{ordersEnabled && (
|
||||
<div className="glass flex items-center justify-between gap-3 rounded-3xl p-4">
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium">{t('orderRetention')}</div>
|
||||
<div className="text-xs text-[var(--text)]/55">{t('orderRetentionHint')}</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
max={720}
|
||||
value={retention}
|
||||
onChange={(e) => setRetention(Math.max(1, Math.min(720, Number(e.target.value) || 1)))}
|
||||
onBlur={() => saveRetention(retention)}
|
||||
className="glass-soft w-16 rounded-xl px-2 py-1.5 text-center text-sm outline-none"
|
||||
/>
|
||||
<span className="text-xs text-[var(--text)]/55">{t('hours')}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!ordersEnabled && (
|
||||
<p className="text-center text-sm text-[var(--text)]/55">{t('ordersDisabled')}</p>
|
||||
)}
|
||||
|
||||
@@ -16,6 +16,7 @@ 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);
|
||||
|
||||
@@ -25,7 +26,7 @@ export default function PublishModal({
|
||||
try {
|
||||
const res = await api<{ versionName: string }>(slug, '/publish', {
|
||||
method: 'POST',
|
||||
json: { versionName: name.trim() },
|
||||
json: { versionName: name.trim(), generateSuggestions: suggestions },
|
||||
});
|
||||
setSuccess(res.versionName);
|
||||
onPublished(res.versionName);
|
||||
@@ -61,6 +62,20 @@ 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')}
|
||||
|
||||
@@ -37,6 +37,8 @@ export type QrConfig = {
|
||||
errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H';
|
||||
};
|
||||
|
||||
export type SocialLink = { platform: string; url: string };
|
||||
|
||||
export type EditorData = {
|
||||
slug: string;
|
||||
name: string;
|
||||
@@ -45,6 +47,9 @@ export type EditorData = {
|
||||
defaultLocale: Locale;
|
||||
palette: Palette;
|
||||
qrConfig: QrConfig;
|
||||
bannerImage: string | null;
|
||||
profileImage: string | null;
|
||||
socialLinks: SocialLink[];
|
||||
publishedVersionName: string | null;
|
||||
sections: EditorSection[];
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
Instagram,
|
||||
Facebook,
|
||||
Youtube,
|
||||
Twitter,
|
||||
Globe,
|
||||
MessageCircle,
|
||||
Music2,
|
||||
Link2,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import LanguageSwitch from '@/components/LanguageSwitch';
|
||||
|
||||
type SocialLink = { platform: string; url: string };
|
||||
|
||||
// Map a platform name to a lucide icon (brand-less icons; closest match + fallback).
|
||||
function iconFor(platform: string): LucideIcon {
|
||||
const p = platform.toLowerCase();
|
||||
if (p.includes('instagram')) return Instagram;
|
||||
if (p.includes('facebook')) return Facebook;
|
||||
if (p.includes('youtube')) return Youtube;
|
||||
if (p.includes('twitter') || p === 'x') return Twitter;
|
||||
if (p.includes('whatsapp') || p.includes('whats')) return MessageCircle;
|
||||
if (p.includes('tiktok')) return Music2;
|
||||
if (p.includes('web') || p.includes('sitio') || p.includes('site')) return Globe;
|
||||
return Link2;
|
||||
}
|
||||
|
||||
function normalizeUrl(url: string): string {
|
||||
return url.startsWith('http') ? url : `https://${url}`;
|
||||
}
|
||||
|
||||
export default function BrandHeader({
|
||||
name,
|
||||
banner,
|
||||
logo,
|
||||
socialLinks,
|
||||
}: {
|
||||
name: string;
|
||||
banner?: string | null;
|
||||
logo?: string | null;
|
||||
socialLinks?: SocialLink[];
|
||||
}) {
|
||||
const links = (socialLinks ?? []).filter((l) => l.url);
|
||||
|
||||
return (
|
||||
<header className="mb-4">
|
||||
{/* Banner — full-bleed, extends edge-to-edge behind the island. Falls back
|
||||
to a palette gradient when no image is set. */}
|
||||
<div className="relative -mx-4 h-44 overflow-hidden">
|
||||
{banner ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={banner} alt="" className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<div
|
||||
className="h-full w-full"
|
||||
style={{ background: 'linear-gradient(160deg, var(--accent), var(--bg-2))' }}
|
||||
/>
|
||||
)}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/25 to-transparent" />
|
||||
<div className="safe-abs-top absolute right-3">
|
||||
<LanguageSwitch />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Logo + name + socials, pulled up over the banner. */}
|
||||
<div className="-mt-12 flex flex-col items-center gap-2 px-2 text-center">
|
||||
<div className="h-24 w-24 overflow-hidden rounded-full border-4 border-white/70 bg-white/40 shadow-lg">
|
||||
{logo ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={logo} alt={name} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-3xl font-semibold text-[var(--accent)]">
|
||||
{name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<h1 className="display text-2xl font-semibold leading-tight">{name}</h1>
|
||||
{links.length > 0 && (
|
||||
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||
{links.map((l, i) => {
|
||||
const Icon = iconFor(l.platform);
|
||||
return (
|
||||
<a
|
||||
key={i}
|
||||
href={normalizeUrl(l.url)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
aria-label={l.platform}
|
||||
className="glass-pill flex h-9 w-9 items-center justify-center rounded-full"
|
||||
>
|
||||
<Icon className="h-4 w-4 text-[var(--text)]" />
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -5,12 +5,13 @@ import { useLocale, useTranslations } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { MenuSnapshot, SnapshotProduct } from '@/lib/types';
|
||||
import { pickText } from '@/lib/text';
|
||||
import LanguageSwitch from '@/components/LanguageSwitch';
|
||||
import BrandHeader from './BrandHeader';
|
||||
import DishCard from './DishCard';
|
||||
import ListRow from './ListRow';
|
||||
import MacroLegend from './MacroLegend';
|
||||
import Gallery from './Gallery';
|
||||
import AiConsultant from './AiConsultant';
|
||||
import SuggestionCarousel from './SuggestionCarousel';
|
||||
|
||||
type ViewMode = 'cards' | 'list';
|
||||
|
||||
@@ -44,6 +45,14 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
const [view, setView] = useState<ViewMode>('cards');
|
||||
const sectionRefs = useRef<Record<string, HTMLElement | null>>({});
|
||||
|
||||
// Flat index of active products for pairing lookups.
|
||||
const productIndex = useMemo(() => {
|
||||
const map = new Map<string, SnapshotProduct>();
|
||||
for (const s of sections) for (const p of s.products) map.set(p.id, p);
|
||||
return map;
|
||||
}, [sections]);
|
||||
const pairings = menu.restaurant.pairings ?? {};
|
||||
|
||||
const ordersEnabled = menu.restaurant.ordersEnabled;
|
||||
// Macros hierarchy: global flag AND the section's own flag. The legend appears
|
||||
// only if at least one visible section actually shows macros.
|
||||
@@ -73,12 +82,14 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
const cartCount = cart.reduce((n, l) => n + l.qty, 0);
|
||||
|
||||
return (
|
||||
<div className="safe-pt-header mx-auto min-h-screen max-w-2xl px-4 pb-32">
|
||||
{/* Header */}
|
||||
<header className="mb-4 flex items-center justify-between gap-3">
|
||||
<h1 className="display text-2xl font-semibold leading-tight">{menu.restaurant.name}</h1>
|
||||
<LanguageSwitch />
|
||||
</header>
|
||||
<div className="mx-auto min-h-screen max-w-2xl px-4 pb-32">
|
||||
{/* Brand header (banner + logo + name + social icons) */}
|
||||
<BrandHeader
|
||||
name={menu.restaurant.name}
|
||||
banner={menu.restaurant.bannerImage}
|
||||
logo={menu.restaurant.profileImage}
|
||||
socialLinks={menu.restaurant.socialLinks}
|
||||
/>
|
||||
|
||||
{/* Section tabs */}
|
||||
{sections.length > 0 && (
|
||||
@@ -233,6 +244,9 @@ export default function PublicMenu({ menu, slug }: { menu: MenuSnapshot; slug: s
|
||||
slug={slug}
|
||||
cart={cart}
|
||||
setCart={setCart}
|
||||
productIndex={productIndex}
|
||||
pairings={pairings}
|
||||
onAdd={addToCart}
|
||||
onClose={() => setOrderOpen(false)}
|
||||
onSent={() => {
|
||||
setCart([]);
|
||||
@@ -280,12 +294,18 @@ function OrderPanel({
|
||||
slug,
|
||||
cart,
|
||||
setCart,
|
||||
productIndex,
|
||||
pairings,
|
||||
onAdd,
|
||||
onClose,
|
||||
onSent,
|
||||
}: {
|
||||
slug: string;
|
||||
cart: CartLine[];
|
||||
setCart: React.Dispatch<React.SetStateAction<CartLine[]>>;
|
||||
productIndex: Map<string, SnapshotProduct>;
|
||||
pairings: Record<string, string[]>;
|
||||
onAdd: (p: SnapshotProduct) => void;
|
||||
onClose: () => void;
|
||||
onSent: () => void;
|
||||
}) {
|
||||
@@ -295,6 +315,19 @@ function OrderPanel({
|
||||
const [generalNote, setGeneralNote] = useState('');
|
||||
const [sending, setSending] = useState(false);
|
||||
|
||||
// Contextual pairings: complements of what's in the cart, excluding items
|
||||
// already added. Read from precomputed associations — no AI call.
|
||||
const inCart = new Set(cart.map((l) => l.product.id));
|
||||
const suggestionIds = new Set<string>();
|
||||
for (const line of cart) {
|
||||
for (const id of pairings[line.product.id] ?? []) {
|
||||
if (!inCart.has(id)) suggestionIds.add(id);
|
||||
}
|
||||
}
|
||||
const suggestions = Array.from(suggestionIds)
|
||||
.map((id) => productIndex.get(id))
|
||||
.filter((p): p is SnapshotProduct => !!p && p.isActive);
|
||||
|
||||
function setQty(id: string, delta: number) {
|
||||
setCart((prev) =>
|
||||
prev
|
||||
@@ -365,6 +398,8 @@ function OrderPanel({
|
||||
))}
|
||||
</div>
|
||||
|
||||
{suggestions.length > 0 && <SuggestionCarousel products={suggestions} onAdd={onAdd} />}
|
||||
|
||||
{cart.length > 0 && (
|
||||
<div className="flex items-center justify-between px-1 text-sm font-semibold">
|
||||
<span>{t('total')}</span>
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useLocale, useTranslations } from 'next-intl';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { SnapshotProduct } from '@/lib/types';
|
||||
import { pickText } from '@/lib/text';
|
||||
import MediaThumb from './MediaThumb';
|
||||
|
||||
// Auto-rotating, manually-swipeable carousel of precomputed cart pairings.
|
||||
// Reads associations from the DB (passed in) — no AI call at runtime.
|
||||
export default function SuggestionCarousel({
|
||||
products,
|
||||
onAdd,
|
||||
}: {
|
||||
products: SnapshotProduct[];
|
||||
onAdd: (p: SnapshotProduct) => void;
|
||||
}) {
|
||||
const locale = useLocale() as Locale;
|
||||
const t = useTranslations('menu');
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Auto-advance one card every few seconds; wraps to the start at the end.
|
||||
useEffect(() => {
|
||||
if (products.length <= 1) return;
|
||||
const id = setInterval(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const card = el.firstElementChild as HTMLElement | null;
|
||||
const step = card ? card.offsetWidth + 12 : 160;
|
||||
if (el.scrollLeft + el.clientWidth >= el.scrollWidth - 8) {
|
||||
el.scrollTo({ left: 0, behavior: 'smooth' });
|
||||
} else {
|
||||
el.scrollBy({ left: step, behavior: 'smooth' });
|
||||
}
|
||||
}, 3500);
|
||||
return () => clearInterval(id);
|
||||
}, [products.length]);
|
||||
|
||||
if (products.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-[var(--text)]/55">
|
||||
{t('suggestions')}
|
||||
</p>
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="flex snap-x gap-3 overflow-x-auto pb-1 no-scrollbar"
|
||||
>
|
||||
{products.map((p) => (
|
||||
<div
|
||||
key={p.id}
|
||||
className="glass-soft flex w-36 shrink-0 snap-start flex-col overflow-hidden rounded-2xl"
|
||||
>
|
||||
<MediaThumb
|
||||
media={[...p.media].sort((a, b) => a.order - b.order)[0]}
|
||||
alt={pickText(p.name, locale)}
|
||||
className="h-20 w-full"
|
||||
/>
|
||||
<div className="flex flex-1 flex-col gap-1 p-2">
|
||||
<span className="line-clamp-2 text-xs font-medium leading-tight">
|
||||
{pickText(p.name, locale)}
|
||||
</span>
|
||||
<span className="text-xs text-[var(--accent)]">${p.price.toFixed(2)}</span>
|
||||
<button
|
||||
onClick={() => onAdd(p)}
|
||||
className="mt-auto rounded-full bg-[var(--accent)] py-1 text-xs font-medium text-white"
|
||||
>
|
||||
{t('addToOrder')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,10 @@ export type MenuSnapshot = {
|
||||
ordersEnabled: boolean;
|
||||
defaultLocale: Locale;
|
||||
showMacros: boolean;
|
||||
pairings?: Record<string, string[]>;
|
||||
bannerImage?: string | null;
|
||||
profileImage?: string | null;
|
||||
socialLinks?: { platform: string; url: string }[];
|
||||
};
|
||||
sections: SnapshotSection[];
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user