Initial build: Menú inteligente platform
Multi-tenant digital menu platform (Collina Systems): public QR menu with glassmorphism + 3D macro flip cards, mobile-first editor with draft/publish versioning (5-version history + restore), AI consultant & translation (Claude Haiku), realtime orders via SSE, configurable palette, QR generation, superadmin panel, and Docker/Coolify infra.
This commit is contained in:
commit
5fb9c7a145
85 files changed
+7812
No files matched your search
@@ -0,0 +1,94 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { getAnthropic, HAIKU_MODEL } from '@/lib/anthropic';
|
||||
import { pickText } from '@/lib/text';
|
||||
import type { Locale } from '@/i18n/config';
|
||||
import type { MenuSnapshot } from '@/lib/types';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// Build a compact text context of the published menu for the model.
|
||||
function buildMenuContext(menu: MenuSnapshot, locale: Locale): string {
|
||||
const lines: string[] = [];
|
||||
for (const section of menu.sections) {
|
||||
lines.push(`## ${pickText(section.name, locale)}`);
|
||||
for (const p of section.products) {
|
||||
if (!p.isActive) continue;
|
||||
const macros = Object.entries(p.macros)
|
||||
.filter(([, v]) => v != null)
|
||||
.map(([k, v]) => `${k}:${v}`)
|
||||
.join(', ');
|
||||
lines.push(
|
||||
`- ${pickText(p.name, locale)} ($${p.price.toFixed(2)}): ${pickText(p.description, locale)}` +
|
||||
(p.dietTags.length ? ` | dieta: ${p.dietTags.join(', ')}` : '') +
|
||||
(p.allergens.length ? ` | alérgenos: ${p.allergens.join(', ')}` : '') +
|
||||
(macros ? ` | macros: ${macros}` : ''),
|
||||
);
|
||||
}
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export async function POST(req: Request, { params }: { params: { slug: string } }) {
|
||||
const body = await req.json().catch(() => null);
|
||||
const question = String(body?.question ?? '').trim();
|
||||
const locale: Locale = body?.locale === 'en' ? 'en' : 'es';
|
||||
if (!question) return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
|
||||
const restaurant = await prisma.restaurant.findUnique({
|
||||
where: { slug: params.slug },
|
||||
include: { publishedVersion: true },
|
||||
});
|
||||
if (!restaurant?.publishedVersion) {
|
||||
return NextResponse.json({ error: 'not_published' }, { status: 404 });
|
||||
}
|
||||
|
||||
const menu = restaurant.publishedVersion.snapshot as unknown as MenuSnapshot;
|
||||
const context = buildMenuContext(menu, locale);
|
||||
|
||||
const system =
|
||||
locale === 'en'
|
||||
? `You are a friendly menu consultant for the restaurant "${menu.restaurant.name}". ` +
|
||||
`Recommend ONLY dishes that appear in the menu below. Always answer in English. ` +
|
||||
`Give exactly 3 recommendations, each citing the real dish name and a short reason it fits. ` +
|
||||
`Reply ONLY with JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string}]}.`
|
||||
: `Eres un consultor amable del menú del restaurante "${menu.restaurant.name}". ` +
|
||||
`Recomienda SOLO platillos que aparezcan en el menú de abajo. Responde siempre en español. ` +
|
||||
`Da exactamente 3 recomendaciones, cada una citando el nombre real del platillo y una razón breve. ` +
|
||||
`Responde SOLO con JSON: {"intro": string, "recommendations": [{"dish": string, "reason": string}]}.`;
|
||||
|
||||
try {
|
||||
const client = getAnthropic();
|
||||
const msg = await client.messages.create({
|
||||
model: HAIKU_MODEL,
|
||||
max_tokens: 700,
|
||||
system,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: `MENÚ:\n${context}\n\nPREGUNTA: ${question}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const text = msg.content.find((c) => c.type === 'text')?.text ?? '{}';
|
||||
const json = JSON.parse(extractJson(text));
|
||||
return NextResponse.json({
|
||||
intro: typeof json.intro === 'string' ? json.intro : undefined,
|
||||
recommendations: Array.isArray(json.recommendations) ? json.recommendations.slice(0, 3) : [],
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('ai-consult error', err);
|
||||
return NextResponse.json({ error: 'ai_failed' }, { status: 502 });
|
||||
}
|
||||
}
|
||||
|
||||
// Tolerate models that wrap JSON in prose or code fences.
|
||||
function extractJson(text: string): string {
|
||||
const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/);
|
||||
if (fenced) return fenced[1];
|
||||
const start = text.indexOf('{');
|
||||
const end = text.lastIndexOf('}');
|
||||
if (start !== -1 && end !== -1) return text.slice(start, end + 1);
|
||||
return text;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { editorCookieName, signEditorToken, verifyPassword } from '@/lib/auth';
|
||||
|
||||
export async function POST(req: Request, { params }: { params: { slug: string } }) {
|
||||
const body = await req.json().catch(() => null);
|
||||
const username = String(body?.username ?? '');
|
||||
const password = String(body?.password ?? '');
|
||||
const secret = String(body?.secret ?? '');
|
||||
|
||||
const restaurant = await prisma.restaurant.findUnique({ where: { slug: params.slug } });
|
||||
if (!restaurant || !restaurant.active) {
|
||||
return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Both layers: secret link AND credentials.
|
||||
if (secret !== restaurant.editorSecret) {
|
||||
return NextResponse.json({ error: 'invalid_link' }, { status: 403 });
|
||||
}
|
||||
const ok =
|
||||
username === restaurant.username && (await verifyPassword(password, restaurant.hashedPassword));
|
||||
if (!ok) {
|
||||
return NextResponse.json({ error: 'invalid' }, { status: 401 });
|
||||
}
|
||||
|
||||
const token = await signEditorToken({ slug: restaurant.slug, restaurantId: restaurant.id });
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(editorCookieName(restaurant.slug), token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { editorCookieName } from '@/lib/auth';
|
||||
|
||||
export async function POST(_req: Request, { params }: { params: { slug: string } }) {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(editorCookieName(params.slug), '', { path: '/', maxAge: 0 });
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { publish } from '@/lib/orders-bus';
|
||||
|
||||
export async function POST(req: Request, { params }: { params: { slug: string } }) {
|
||||
const restaurant = await prisma.restaurant.findUnique({ where: { slug: params.slug } });
|
||||
if (!restaurant || !restaurant.active) {
|
||||
return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const tableNumber = Number(body?.tableNumber);
|
||||
if (!tableNumber) return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
|
||||
// Broadcast to the editor's orders stream as an ephemeral waiter call.
|
||||
publish(params.slug, { type: 'waiter', data: { tableNumber, at: new Date().toISOString() } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import type { MenuSnapshot } from '@/lib/types';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// Public menu: serves the PUBLISHED version snapshot, never the draft.
|
||||
export async function GET(_req: Request, { params }: { params: { slug: string } }) {
|
||||
const restaurant = await prisma.restaurant.findUnique({
|
||||
where: { slug: params.slug },
|
||||
include: { publishedVersion: true },
|
||||
});
|
||||
if (!restaurant || !restaurant.active) {
|
||||
return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
}
|
||||
if (!restaurant.publishedVersion) {
|
||||
return NextResponse.json({ error: 'not_published' }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json(restaurant.publishedVersion.snapshot as unknown as MenuSnapshot);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { publish } from '@/lib/orders-bus';
|
||||
import type { OrderItem } from '@/lib/types';
|
||||
|
||||
export async function POST(req: Request, { params }: { params: { slug: string } }) {
|
||||
const restaurant = await prisma.restaurant.findUnique({ where: { slug: params.slug } });
|
||||
if (!restaurant || !restaurant.active) {
|
||||
return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
}
|
||||
if (!restaurant.ordersEnabled) {
|
||||
return NextResponse.json({ error: 'orders_disabled' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const tableNumber = Number(body?.tableNumber);
|
||||
const items: OrderItem[] = Array.isArray(body?.items) ? body.items : [];
|
||||
if (!tableNumber || items.length === 0) {
|
||||
return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
}
|
||||
|
||||
const order = await prisma.order.create({
|
||||
data: {
|
||||
restaurantId: restaurant.id,
|
||||
tableNumber,
|
||||
items: items as unknown as object,
|
||||
status: 'active',
|
||||
},
|
||||
});
|
||||
|
||||
publish(params.slug, { type: 'order', data: order });
|
||||
return NextResponse.json({ ok: true, id: order.id });
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
import { publish } from '@/lib/orders-bus';
|
||||
|
||||
// Complete (or otherwise update) an order.
|
||||
export async function PATCH(
|
||||
req: Request,
|
||||
{ params }: { params: { slug: string; id: string } },
|
||||
) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const status = body?.status === 'completed' ? 'completed' : 'active';
|
||||
|
||||
const result = await prisma.order.updateMany({
|
||||
where: { id: params.id, restaurantId: guard.restaurant.id },
|
||||
data: { status, completedAt: status === 'completed' ? new Date() : null },
|
||||
});
|
||||
if (result.count === 0) return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
|
||||
publish(params.slug, { type: 'order-update', data: { id: params.id, status } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_req: Request,
|
||||
{ params }: { params: { slug: string; id: string } },
|
||||
) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
await prisma.order.deleteMany({
|
||||
where: { id: params.id, restaurantId: guard.restaurant.id },
|
||||
});
|
||||
publish(params.slug, { type: 'order-update', data: { id: params.id, status: 'deleted' } });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { subscribe } from '@/lib/orders-bus';
|
||||
import { getEditorSession } from '@/lib/auth';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// SSE stream of orders + waiter calls for the editor dashboard.
|
||||
export async function GET(_req: Request, { params }: { params: { slug: string } }) {
|
||||
const session = await getEditorSession(params.slug);
|
||||
if (!session) return new Response('unauthorized', { status: 401 });
|
||||
|
||||
const restaurant = await prisma.restaurant.findUnique({ where: { slug: params.slug } });
|
||||
if (!restaurant) return new Response('not_found', { status: 404 });
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
let heartbeat: ReturnType<typeof setInterval>;
|
||||
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
const send = (event: { type: string; data: unknown }) => {
|
||||
controller.enqueue(
|
||||
encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event.data)}\n\n`),
|
||||
);
|
||||
};
|
||||
|
||||
// Replay current active orders on connect.
|
||||
const active = await prisma.order.findMany({
|
||||
where: { restaurantId: restaurant.id, status: 'active' },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
send({ type: 'snapshot', data: active });
|
||||
|
||||
const unsubscribe = subscribe(params.slug, send);
|
||||
|
||||
heartbeat = setInterval(() => {
|
||||
controller.enqueue(encoder.encode(`: ping\n\n`));
|
||||
}, 25000);
|
||||
|
||||
// Clean up when the client disconnects.
|
||||
_req.signal.addEventListener('abort', () => {
|
||||
clearInterval(heartbeat);
|
||||
unsubscribe();
|
||||
try {
|
||||
controller.close();
|
||||
} catch {
|
||||
/* already closed */
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
Connection: 'keep-alive',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
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 palette = body?.palette;
|
||||
if (!palette || typeof palette !== 'object') {
|
||||
return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
}
|
||||
await prisma.restaurant.update({
|
||||
where: { id: guard.restaurant.id },
|
||||
data: { palette: palette as object },
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
const FIELDS = [
|
||||
'name',
|
||||
'description',
|
||||
'price',
|
||||
'isActive',
|
||||
'allergens',
|
||||
'dietTags',
|
||||
'macros',
|
||||
'media',
|
||||
'translationStatus',
|
||||
'sectionId',
|
||||
] as const;
|
||||
|
||||
export async function PATCH(
|
||||
req: Request,
|
||||
{ params }: { params: { slug: string; id: string } },
|
||||
) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
|
||||
const data: Record<string, unknown> = {};
|
||||
for (const f of FIELDS) {
|
||||
if (body[f] !== undefined) {
|
||||
data[f] = body[f];
|
||||
}
|
||||
}
|
||||
|
||||
const result = await prisma.product.updateMany({
|
||||
where: { id: params.id, restaurantId: guard.restaurant.id },
|
||||
data: data as Parameters<typeof prisma.product.updateMany>[0]['data'],
|
||||
});
|
||||
if (result.count === 0) return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_req: Request,
|
||||
{ params }: { params: { slug: string; id: string } },
|
||||
) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
await prisma.product.deleteMany({
|
||||
where: { id: params.id, restaurantId: guard.restaurant.id },
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
// Create a product in a section, or batch-reorder products.
|
||||
export async function POST(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 sectionId = String(body?.sectionId ?? '');
|
||||
if (!sectionId) return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
|
||||
const section = await prisma.section.findFirst({
|
||||
where: { id: sectionId, restaurantId: guard.restaurant.id },
|
||||
});
|
||||
if (!section) return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
|
||||
const count = await prisma.product.count({ where: { sectionId } });
|
||||
const product = await prisma.product.create({
|
||||
data: {
|
||||
sectionId,
|
||||
restaurantId: guard.restaurant.id,
|
||||
name: (body?.name as object) ?? { es: '', en: '' },
|
||||
description: (body?.description as object) ?? {},
|
||||
price: body?.price ?? 0,
|
||||
order: count,
|
||||
allergens: body?.allergens ?? [],
|
||||
dietTags: body?.dietTags ?? [],
|
||||
macros: (body?.macros as object) ?? {},
|
||||
media: (body?.media as object) ?? [],
|
||||
translationStatus: (body?.translationStatus as object) ?? {},
|
||||
},
|
||||
});
|
||||
return NextResponse.json(product);
|
||||
}
|
||||
|
||||
// Reorder: body { sectionId, ids: string[] }.
|
||||
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 ids: string[] = Array.isArray(body?.ids) ? body.ids : [];
|
||||
const sectionId: string | undefined = body?.sectionId;
|
||||
|
||||
await prisma.$transaction(
|
||||
ids.map((id, order) =>
|
||||
prisma.product.updateMany({
|
||||
where: { id, restaurantId: guard.restaurant.id },
|
||||
data: { order, ...(sectionId ? { sectionId } : {}) },
|
||||
}),
|
||||
),
|
||||
);
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
import { publishVersion } from '@/lib/menu';
|
||||
|
||||
export async function POST(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 versionName = String(body?.versionName ?? '').trim();
|
||||
if (!versionName) return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
|
||||
const version = await publishVersion(
|
||||
guard.restaurant.id,
|
||||
versionName,
|
||||
guard.restaurant.username,
|
||||
);
|
||||
return NextResponse.json(version);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import QRCode from 'qrcode';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
// Generates the public-menu QR as PNG or SVG.
|
||||
export async function GET(req: Request, { params }: { params: { slug: string } }) {
|
||||
const restaurant = await prisma.restaurant.findUnique({
|
||||
where: { slug: params.slug },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!restaurant) return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
|
||||
const format = new URL(req.url).searchParams.get('format') === 'svg' ? 'svg' : 'png';
|
||||
const base = process.env.APP_BASE_URL || new URL(req.url).origin;
|
||||
const url = `${base}/${params.slug}`;
|
||||
|
||||
if (format === 'svg') {
|
||||
const svg = await QRCode.toString(url, {
|
||||
type: 'svg',
|
||||
margin: 2,
|
||||
width: 1024,
|
||||
color: { dark: '#2a2520', light: '#ffffff' },
|
||||
});
|
||||
return new NextResponse(svg, {
|
||||
headers: {
|
||||
'Content-Type': 'image/svg+xml',
|
||||
'Content-Disposition': `attachment; filename="menu-${params.slug}.svg"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const buffer = await QRCode.toBuffer(url, {
|
||||
type: 'png',
|
||||
margin: 2,
|
||||
width: 1024,
|
||||
color: { dark: '#2a2520', light: '#ffffff' },
|
||||
});
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Content-Disposition': `attachment; filename="menu-${params.slug}.png"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
export async function PATCH(
|
||||
req: Request,
|
||||
{ params }: { params: { slug: string; id: string } },
|
||||
) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const data: { name?: object } = {};
|
||||
if (body?.name) data.name = body.name as object;
|
||||
|
||||
const result = await prisma.section.updateMany({
|
||||
where: { id: params.id, restaurantId: guard.restaurant.id },
|
||||
data,
|
||||
});
|
||||
if (result.count === 0) return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
_req: Request,
|
||||
{ params }: { params: { slug: string; id: string } },
|
||||
) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
await prisma.section.deleteMany({
|
||||
where: { id: params.id, restaurantId: guard.restaurant.id },
|
||||
});
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
// Create a new section, or reorder sections (operate on the DRAFT).
|
||||
export async function POST(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 count = await prisma.section.count({ where: { restaurantId: guard.restaurant.id } });
|
||||
const section = await prisma.section.create({
|
||||
data: {
|
||||
restaurantId: guard.restaurant.id,
|
||||
name: (body?.name as object) ?? { es: 'Nueva sección', en: 'New section' },
|
||||
order: count,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(section);
|
||||
}
|
||||
|
||||
// Batch reorder: body { ids: string[] } in the new order.
|
||||
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 ids: string[] = Array.isArray(body?.ids) ? body.ids : [];
|
||||
await prisma.$transaction(
|
||||
ids.map((id, order) =>
|
||||
prisma.section.updateMany({
|
||||
where: { id, restaurantId: guard.restaurant.id },
|
||||
data: { order },
|
||||
}),
|
||||
),
|
||||
);
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
|
||||
// Toggle ordersEnabled, defaultLocale, etc.
|
||||
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 } = {};
|
||||
if (typeof body?.ordersEnabled === 'boolean') data.ordersEnabled = body.ordersEnabled;
|
||||
if (body?.defaultLocale === 'es' || body?.defaultLocale === 'en') {
|
||||
data.defaultLocale = body.defaultLocale;
|
||||
}
|
||||
|
||||
await prisma.restaurant.update({ where: { id: guard.restaurant.id }, data });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
import { getAnthropic, HAIKU_MODEL } from '@/lib/anthropic';
|
||||
|
||||
// Translate a single field with Claude Haiku to fill the missing locale.
|
||||
export async function POST(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 text = String(body?.text ?? '').trim();
|
||||
const from: 'es' | 'en' = body?.from === 'en' ? 'en' : 'es';
|
||||
const to: 'es' | 'en' = from === 'es' ? 'en' : 'es';
|
||||
if (!text) return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
|
||||
const langName = { es: 'Spanish', en: 'English' };
|
||||
try {
|
||||
const client = getAnthropic();
|
||||
const msg = await client.messages.create({
|
||||
model: HAIKU_MODEL,
|
||||
max_tokens: 400,
|
||||
system: `You translate restaurant menu text from ${langName[from]} to ${langName[to]}. ` +
|
||||
`Keep it natural and appetizing. Reply with ONLY the translation, no quotes, no notes.`,
|
||||
messages: [{ role: 'user', content: text }],
|
||||
});
|
||||
const translated = msg.content.find((c) => c.type === 'text')?.text?.trim() ?? '';
|
||||
return NextResponse.json({ translation: translated, to });
|
||||
} catch (err) {
|
||||
console.error('translate error', err);
|
||||
return NextResponse.json({ error: 'ai_failed' }, { status: 502 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
import { saveUpload } from '@/lib/upload';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function POST(req: Request, { params }: { params: { slug: string } }) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const form = await req.formData().catch(() => null);
|
||||
const file = form?.get('file');
|
||||
if (!(file instanceof File)) {
|
||||
return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const saved = await saveUpload(guard.restaurant.slug, file);
|
||||
return NextResponse.json(saved);
|
||||
} catch (err) {
|
||||
console.error('upload error', err);
|
||||
return NextResponse.json({ error: 'upload_failed' }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
import { restoreSnapshotToDraft } from '@/lib/menu';
|
||||
import type { MenuSnapshot } from '@/lib/types';
|
||||
|
||||
// Load a stored version's snapshot back into the working draft.
|
||||
export async function POST(
|
||||
_req: Request,
|
||||
{ params }: { params: { slug: string; id: string } },
|
||||
) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const version = await prisma.menuVersion.findFirst({
|
||||
where: { id: params.id, restaurantId: guard.restaurant.id },
|
||||
});
|
||||
if (!version) return NextResponse.json({ error: 'not_found' }, { status: 404 });
|
||||
|
||||
await restoreSnapshotToDraft(
|
||||
guard.restaurant.id,
|
||||
version.snapshot as unknown as MenuSnapshot,
|
||||
);
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { requireEditor } from '@/lib/guard';
|
||||
import { MAX_VERSIONS } from '@/lib/menu';
|
||||
|
||||
// List the last 5 versions for the editor's history panel.
|
||||
export async function GET(_req: Request, { params }: { params: { slug: string } }) {
|
||||
const guard = await requireEditor(params.slug);
|
||||
if ('error' in guard) return guard.error;
|
||||
|
||||
const versions = await prisma.menuVersion.findMany({
|
||||
where: { restaurantId: guard.restaurant.id },
|
||||
orderBy: { publishedAt: 'desc' },
|
||||
take: MAX_VERSIONS,
|
||||
select: { id: true, versionName: true, publishedAt: true, createdBy: true },
|
||||
});
|
||||
return NextResponse.json({
|
||||
versions,
|
||||
publishedVersionId: guard.restaurant.publishedVersionId,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { ADMIN_COOKIE, checkAdminCredentials, signAdminToken } from '@/lib/auth';
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const body = await req.json().catch(() => null);
|
||||
const user = String(body?.user ?? '');
|
||||
const password = String(body?.password ?? '');
|
||||
|
||||
if (!checkAdminCredentials(user, password)) {
|
||||
return NextResponse.json({ error: 'invalid' }, { status: 401 });
|
||||
}
|
||||
|
||||
const token = await signAdminToken();
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(ADMIN_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { isAdminAuthed } from '@/lib/auth';
|
||||
|
||||
// Activate/deactivate a restaurant.
|
||||
export async function PATCH(req: Request, { params }: { params: { id: string } }) {
|
||||
if (!(await isAdminAuthed())) {
|
||||
return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
|
||||
}
|
||||
const body = await req.json().catch(() => null);
|
||||
const data: { active?: boolean } = {};
|
||||
if (typeof body?.active === 'boolean') data.active = body.active;
|
||||
|
||||
await prisma.restaurant.update({ where: { id: params.id }, data });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import {
|
||||
generatePassword,
|
||||
generateSecret,
|
||||
hashPassword,
|
||||
isAdminAuthed,
|
||||
} from '@/lib/auth';
|
||||
|
||||
function slugify(input: string): string {
|
||||
return input
|
||||
.toLowerCase()
|
||||
.normalize('NFD')
|
||||
.replace(/\p{Diacritic}/gu, '')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 48);
|
||||
}
|
||||
|
||||
const SUGGESTED_SECTIONS = [
|
||||
{ es: 'Entradas', en: 'Starters' },
|
||||
{ es: 'Platos fuertes', en: 'Main dishes' },
|
||||
{ es: 'Bebidas', en: 'Drinks' },
|
||||
{ es: 'Postres', en: 'Desserts' },
|
||||
];
|
||||
|
||||
export async function GET() {
|
||||
if (!(await isAdminAuthed())) {
|
||||
return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
|
||||
}
|
||||
const restaurants = await prisma.restaurant.findMany({
|
||||
orderBy: { createdAt: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
slug: true,
|
||||
name: true,
|
||||
editorSecret: true,
|
||||
username: true,
|
||||
active: true,
|
||||
ordersEnabled: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
return NextResponse.json({ restaurants });
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
if (!(await isAdminAuthed())) {
|
||||
return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null);
|
||||
const name = String(body?.name ?? '').trim();
|
||||
const defaultLocale = body?.defaultLocale === 'en' ? 'en' : 'es';
|
||||
if (!name) return NextResponse.json({ error: 'invalid' }, { status: 400 });
|
||||
|
||||
let slug = slugify(body?.slug || name);
|
||||
if (!slug) return NextResponse.json({ error: 'invalid_slug' }, { status: 400 });
|
||||
// Ensure unique slug.
|
||||
let suffix = 1;
|
||||
const base = slug;
|
||||
while (await prisma.restaurant.findUnique({ where: { slug } })) {
|
||||
slug = `${base}-${suffix++}`;
|
||||
}
|
||||
|
||||
const editorSecret = generateSecret();
|
||||
const username = body?.username?.trim() || 'admin';
|
||||
const plainPassword = body?.password?.trim() || generatePassword();
|
||||
const hashedPassword = await hashPassword(plainPassword);
|
||||
|
||||
const restaurant = await prisma.restaurant.create({
|
||||
data: {
|
||||
slug,
|
||||
name,
|
||||
editorSecret,
|
||||
username,
|
||||
hashedPassword,
|
||||
defaultLocale,
|
||||
sections: {
|
||||
create: SUGGESTED_SECTIONS.map((s, i) => ({ name: s, order: i })),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
id: restaurant.id,
|
||||
slug: restaurant.slug,
|
||||
name: restaurant.name,
|
||||
editorSecret,
|
||||
username,
|
||||
password: plainPassword, // shown once
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { UPLOAD_DIR } from '@/lib/upload';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const MIME: Record<string, string> = {
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
avif: 'image/avif',
|
||||
gif: 'image/gif',
|
||||
mp4: 'video/mp4',
|
||||
webm: 'video/webm',
|
||||
mov: 'video/quicktime',
|
||||
};
|
||||
|
||||
// Serves files stored in the upload volume. Resolves and validates the path
|
||||
// stays inside UPLOAD_DIR to prevent traversal.
|
||||
export async function GET(_req: Request, { params }: { params: { path: string[] } }) {
|
||||
const rel = params.path.join('/');
|
||||
const full = path.resolve(UPLOAD_DIR, rel);
|
||||
if (!full.startsWith(path.resolve(UPLOAD_DIR) + path.sep)) {
|
||||
return new NextResponse('forbidden', { status: 403 });
|
||||
}
|
||||
try {
|
||||
const data = await fs.readFile(full);
|
||||
const ext = full.split('.').pop()?.toLowerCase() ?? '';
|
||||
return new NextResponse(new Uint8Array(data), {
|
||||
headers: {
|
||||
'Content-Type': MIME[ext] ?? 'application/octet-stream',
|
||||
'Cache-Control': 'public, max-age=31536000, immutable',
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new NextResponse('not found', { status: 404 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user