From 244adaee3020c2e367d616de7c8434cb3043c604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorem=20Ju=C3=A1rez?= Date: Mon, 15 Jun 2026 17:25:35 -0600 Subject: [PATCH] Orders persistence/expiration, cart pairings, and brand header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- messages/en.json | 17 ++ messages/es.json | 17 ++ package-lock.json | 10 + package.json | 1 + .../0007_order_retention/migration.sql | 2 + .../0008_restaurant_pairings/migration.sql | 2 + .../0009_restaurant_brand/migration.sql | 4 + prisma/schema.prisma | 5 + src/app/[slug]/editor/page.tsx | 3 + src/app/[slug]/page.tsx | 19 +- src/app/api/[slug]/menu/route.ts | 8 +- src/app/api/[slug]/orders/route.ts | 29 +++ src/app/api/[slug]/publish/route.ts | 22 +- src/app/api/[slug]/settings/route.ts | 40 +++- src/app/globals.css | 4 + src/components/editor/BrandTab.tsx | 199 ++++++++++++++++++ src/components/editor/Editor.tsx | 12 +- src/components/editor/OrdersTab.tsx | 44 ++++ src/components/editor/PublishModal.tsx | 17 +- src/components/editor/types.ts | 5 + src/components/public/BrandHeader.tsx | 103 +++++++++ src/components/public/PublicMenu.tsx | 49 ++++- src/components/public/SuggestionCarousel.tsx | 78 +++++++ src/lib/pairings.ts | 72 +++++++ src/lib/types.ts | 4 + 25 files changed, 749 insertions(+), 17 deletions(-) create mode 100644 prisma/migrations/0007_order_retention/migration.sql create mode 100644 prisma/migrations/0008_restaurant_pairings/migration.sql create mode 100644 prisma/migrations/0009_restaurant_brand/migration.sql create mode 100644 src/app/api/[slug]/orders/route.ts create mode 100644 src/components/editor/BrandTab.tsx create mode 100644 src/components/public/BrandHeader.tsx create mode 100644 src/components/public/SuggestionCarousel.tsx create mode 100644 src/lib/pairings.ts diff --git a/messages/en.json b/messages/en.json index 08fceff..7e85d27 100644 --- a/messages/en.json +++ b/messages/en.json @@ -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", diff --git a/messages/es.json b/messages/es.json index ad2025b..ddd5488 100644 --- a/messages/es.json +++ b/messages/es.json @@ -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", diff --git a/package-lock.json b/package-lock.json index 11c1dc7..b30cb97 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 94c2e82..b0e3960 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/prisma/migrations/0007_order_retention/migration.sql b/prisma/migrations/0007_order_retention/migration.sql new file mode 100644 index 0000000..d70ddf1 --- /dev/null +++ b/prisma/migrations/0007_order_retention/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Restaurant" ADD COLUMN "orderRetentionHours" INTEGER NOT NULL DEFAULT 24; diff --git a/prisma/migrations/0008_restaurant_pairings/migration.sql b/prisma/migrations/0008_restaurant_pairings/migration.sql new file mode 100644 index 0000000..153e5b4 --- /dev/null +++ b/prisma/migrations/0008_restaurant_pairings/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Restaurant" ADD COLUMN "pairings" JSONB NOT NULL DEFAULT '{}'; diff --git a/prisma/migrations/0009_restaurant_brand/migration.sql b/prisma/migrations/0009_restaurant_brand/migration.sql new file mode 100644 index 0000000..ad38c47 --- /dev/null +++ b/prisma/migrations/0009_restaurant_brand/migration.sql @@ -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 '[]'; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index d496647..1ba3c51 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -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) diff --git a/src/app/[slug]/editor/page.tsx b/src/app/[slug]/editor/page.tsx index 3106724..7b43570 100644 --- a/src/app/[slug]/editor/page.tsx +++ b/src/app/[slug]/editor/page.tsx @@ -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, diff --git a/src/app/[slug]/page.tsx b/src/app/[slug]/page.tsx index a22bcea..6863512 100644 --- a/src/app/[slug]/page.tsx +++ b/src/app/[slug]/page.tsx @@ -16,6 +16,15 @@ async function getPublishedMenu(slug: string): Promise { }, }); 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) ?? {}, + 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 { 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; } diff --git a/src/app/api/[slug]/menu/route.ts b/src/app/api/[slug]/menu/route.ts index d5912c7..9e5ec7d 100644 --- a/src/app/api/[slug]/menu/route.ts +++ b/src/app/api/[slug]/menu/route.ts @@ -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) ?? {}; + 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); } diff --git a/src/app/api/[slug]/orders/route.ts b/src/app/api/[slug]/orders/route.ts new file mode 100644 index 0000000..bf957c2 --- /dev/null +++ b/src/app/api/[slug]/orders/route.ts @@ -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 }); +} diff --git a/src/app/api/[slug]/publish/route.ts b/src/app/api/[slug]/publish/route.ts index bfeb2ce..d5d5a96 100644 --- a/src/app/api/[slug]/publish/route.ts +++ b/src/app/api/[slug]/publish/route.ts @@ -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 }); } diff --git a/src/app/api/[slug]/settings/route.ts b/src/app/api/[slug]/settings/route.ts index 12d93c9..a507536 100644 --- a/src/app/api/[slug]/settings/route.ts +++ b/src/app/api/[slug]/settings/route.ts @@ -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) + .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 }); diff --git a/src/app/globals.css b/src/app/globals.css index 9f63d24..1317d4e 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -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); + } } diff --git a/src/components/editor/BrandTab.tsx b/src/components/editor/BrandTab.tsx new file mode 100644 index 0000000..40d97fb --- /dev/null +++ b/src/components/editor/BrandTab.tsx @@ -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(initialBanner); + const [profile, setProfile] = useState(initialProfile); + const [links, setLinks] = useState(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) { + 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 ( +
+ {/* Banner */} +
+

{t('banner')}

+
+ {banner ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( +
+ {t('bannerEmpty')} +
+ )} +
+
+ + {banner && ( + + )} +
+
+ + {/* Profile / logo */} +
+

{t('logo')}

+
+
+ {profile ? ( + // eslint-disable-next-line @next/next/no-img-element + + ) : ( +
🍽️
+ )} +
+
+ + {profile && ( + + )} +
+
+
+ + {/* Social links */} +
+

{t('social')}

+
+ {PLATFORM_SUGGESTIONS.map((p) => ( + + ))} +
+
+ {links.map((l, i) => { + const invalid = l.url.length > 0 && !isValidUrl(l.url); + return ( +
+ updateLink(i, { platform: e.target.value })} + placeholder={t('platform')} + className="glass-soft w-28 rounded-xl px-3 py-2 text-sm outline-none" + /> + 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' : '' + }`} + /> + +
+ ); + })} + +
+
+ + +
+ ); +} diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsx index 3f691e5..a90a07d 100644 --- a/src/components/editor/Editor.tsx +++ b/src/components/editor/Editor.tsx @@ -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' && } + {tab === 'brand' && ( + + )} {tab === 'orders' && ( ([]); const [waiterCalls, setWaiterCalls] = useState([]); + const [retention, setRetention] = useState(24); const [now, setNow] = useState(() => 0); const esRef = useRef(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( () => @@ -114,6 +137,27 @@ export default function OrdersTab({ + {ordersEnabled && ( +
+
+
{t('orderRetention')}
+
{t('orderRetentionHint')}
+
+
+ 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" + /> + {t('hours')} +
+
+ )} + {!ordersEnabled && (

{t('ordersDisabled')}

)} diff --git a/src/components/editor/PublishModal.tsx b/src/components/editor/PublishModal.tsx index 125ce5c..be3528a 100644 --- a/src/components/editor/PublishModal.tsx +++ b/src/components/editor/PublishModal.tsx @@ -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(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" /> +
+
+ + ))} + + + ); +} diff --git a/src/lib/pairings.ts b/src/lib/pairings.ts new file mode 100644 index 0000000..f15b4da --- /dev/null +++ b/src/lib/pairings.ts @@ -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; + +// 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 { + const locale = snapshot.restaurant.defaultLocale; + + // Compact catalog: id, name, section, diet tags. (Macros omitted — irrelevant.) + const lines: string[] = []; + const ids = new Set(); + 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": { "": ["", ...] }}.\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 }>(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; + } +} diff --git a/src/lib/types.ts b/src/lib/types.ts index 5266817..22d82e3 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -36,6 +36,10 @@ export type MenuSnapshot = { ordersEnabled: boolean; defaultLocale: Locale; showMacros: boolean; + pairings?: Record; + bannerImage?: string | null; + profileImage?: string | null; + socialLinks?: { platform: string; url: string }[]; }; sections: SnapshotSection[]; };