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:
Jorem Juárez committed 2026-06-15 17:25:35 -06:00
1 parent 57a9b191bd
commit 244adaee30
25 files changed
+749 -17

No files matched your search

+7 -1
View File
@@ -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);
}
+29
View File
@@ -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 });
}
+20 -2
View File
@@ -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 });
}
+38 -2
View File
@@ -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 });